text
stringlengths
180
608k
[Question] [ # Introduction A disk is a linear container with blocks indexed `0` through `size-1`. A file is a named list of block indexes used by that file. An example filesystem is expressed like this: ``` 15 ALPHA=3,5 BETA=11,10,7 ``` "The disk has 15 blocks, the first block of file ALPHA is the disk block at index 3..." The disk map could be drawn like this: ``` Block Index 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 Contents | | | |A0 | |A1 | |B2 | | |B1 |B0 | | | | ``` A disk is considered defragged when all of the files within it are stored contiguously. # YOUR GOAL: Emit a **shortest** sequence of **legal** moves which will defrag a given disk. # Legal Moves A move contains three pieces of information: the *name* of a file, an index of the block *in the file* to be moved, and the index of the *disk block* it moves to. For example ``` ALPHA:1>4 ``` "Move block 1 of the file ALPHA to block 4 of the disk." After this move, the example file system is now this ``` 15 ALPHA=3,4 BETA=11,10,7 Block Index 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 Contents | | | |A0 |A1 | | |B2 | | |B1 |B0 | | | | ``` The previously-inhabited disk block is implicitly cleared. Equivalently, you can view this as swapping two blocks on the disk but *one of the blocks in the swap must be empty*. Data may not be destroyed. Files cannot share blocks at any stage and movements must be within range of the disk. The following moves are *illegal*: `ALPHA:0>10` (owned by BETA), `ALPHA:3>0` (no such block in ALPHA), `ALPHA:0>-1` (no such disk index), `ALPHA:0>15` (disk index too big) # Example 1 Solving the above example in full. ``` ALPHA:0>4 BETA:0>9 BETA:2>11 ``` Files do not have to be adjacent in the solution, just continuous within themselves. # Example 2 Here is a more constrained case Input: ``` 10 A=1,2,3 B=6,7,8 C=4,5,0 ``` Output: ``` B:2>9 B:1>8 B:0>7 C:2>6 ``` The progression of this filesystem is: ``` Block Index 00 01 02 03 04 05 06 07 08 09 Contents |C2 |A0 |A1 |A2 |C0 |C1 |BO |B1 |B2 | | |C2 |A0 |A1 |A2 |C0 |C1 |BO |B1 | |B2 | |C2 |A0 |A1 |A2 |C0 |C1 |BO | |B1 |B2 | |C2 |A0 |A1 |A2 |C0 |C1 | |B0 |B1 |B2 | | |A0 |A1 |A2 |C0 |C1 |C2 |B0 |B1 |B2 | ``` An alternative way to defrag this would by to `C:2>9` then bring `A` down a step, then bring `C` down a step, then do `C:2>5` but **this would not be a legal solution because it contains more moves than the alternative**. # Representation You can use any representation for the input as long as it is reasonably close to a basic string. Depending on your language, the input to the first example might be notated as ``` "15 ALPHA=3,5 BETA=11,10,7" [15," ","ALPHA","=",3,",",5," ","BETA","=",11,",",10,",",7] (15,(("ALPHA",(3,5)),("BETA",(11,10,7)))) etc ``` Similarly, the output can be whatever is convenient for your language as log as it is printed, human-readable, and represents an ordered list of legal moves, each move being described by 1)file-name, 2)file-block-index, 3)new-disk-block-index ``` "ALPHA:1>6 BETA:2>9" (0=>(0=>"ALPHA",1=>"1",2=>"6"), 1=>(0=>"BETA",1=>"2",2=>"9")) ["ALPHA",1,6,"BETA",2,9] etc ``` # Requirements Your code must accept any size disk, and any number and size of files. Inputs which do not describe legal initial filesystem states can lead to undefined behaviour. Your code must produce a **shortest moves** solution, for any well-defined input. All moves you produce must be legal; the filesystem must be in a valid state after applying each step you produce. Your code must terminate for all valid inputs, i.e. it should never get stuck in a loop, the filesystem should be in a distinctly new state after each move is applied. Where there exists more than one shortest solution, any can be selected as valid. Shortest code wins. Please post at least one new nontrivial example input and its output with your code. [Answer] # [Python 3](https://docs.python.org/3/), 295 bytes ``` S,F=eval(input());d=[0]*S;E=enumerate for n,P in F: for j,p in E(P):d[int(p)]=n,j Z=[(d,())] while Z:d,p=Z.pop(0);any(e and(e[0],e[1]+1)in d and(S<j+2or(e[0],e[1]+1)!=d[j+1])for j,e in E(d))or print(p).q;{d[j]or exec("D=d[:];D[j]=e;D[k]=0;Z+=(D,p+(e,j)),")for j,_ in E(d)for k,e in E(d)if d[k]} ``` [Try it online!](https://tio.run/##VZBdT8IwFIbv9ytmr07dCdn4ELPZC4ShJpiQ4BVjMQstYQO7ugyFGH87nnUS42669/S8z5PUnOptqXvnsagYY@cFToX6yPaQa3OogfNIisRPrxdRLJQ@vKkqq5WzKStX49zNtTsNHbeJBZomxjDnoUxyXYPhqdBYOEuRgERCpc7nNt8rdxlKNGLZMaUBn0eZPoFyMy1BkQlVEqRewIkl7XBxV3jdsvp3eSVkUnhByluzas2Sc4qmauWd9@iLtlIaqaNaA5tQKUyjCc2EomOXCj9aegImaDxQWHCO7Jf4eiE2cfcnyDeupOL3md4qarF1dQrt35ivtDqulalDf6XZdZefYYgAbDSLpwzhBvvokwPYffxCeYCBTQ9Pz/GMcg85fQ4Evi3RJMAu9mjHpYoFDPHWVsaU@jhocLYxaDXzx5HlDC4WCwmQiMNm8wc "Python 3 – Try It Online") --- # Another test case ``` Input: 7 ALEF=6,4,0 BET=5,1 GIMEL=3 Initial disk state: A2 B1 __ G0 A1 B0 A0 Solution: ALEF:2>2 ALEF:0>0 BET:1>6 ALEF:1>1 Visualized solution: A2 B1 __ G0 A1 B0 A0 __ B1 A2 G0 A1 B0 A0 A0 B1 A2 G0 A1 B0 __ A0 __ A2 G0 A1 B0 B1 A0 A1 A2 G0 __ B0 B1 ``` [Ungolfed version](https://tio.run/##dVNdb5tAEHyGX7FFsnTEpwhKXFeuiOTUThspqfqQN4oQFUd8Bh8n7qx@/Hn39g6wIzVPyDs7Mzu7Z/lH7zqRnE4Vq0GWvWIFF/KoSbjyPcX/MgpXNW@ZghQG4FrJlmsSQBD6XsVVY6DsWydYfsWFJkgyQN31gETDsl9l9DxRHoyg7BTXvBOoidAomKKgJe5NExKZOB5YX2pGJs7YTIMQR/TsBBkayzA3gsR57I1Uz/SxF4ANvo/5uCrqvnw5MKFZRbCOEtYQ3fpSvDDSMuEgK89ry8/2uTUT7LcubCzjNABZlNOxKYvzeYwpkHhu5m4KKEUFZD@P4TaFyQeMv6PP4xzepWeeCzjmeO6PzPemWPdlqxjiLlvNRVWorj3ilqZs@MU1Z7ZCIQjC3Pd@7XAoi6GDg2Spd6bTVq9lJ0kUuvyi0//dHMjert3wwk/ws2dlM57vrW2OcpcrtYzmTcb5BM3Q73kb9@hsdZVfFI2mqW9c92W9wTq@0aHoUpZSMlERspkWMA9majWrbmfVDxHAbLhxc3HjBm@M7ysMfR9HL86jJ2Ypr@/w6h8Vnk5LWD9u79MP9IZGcLd9Thc0hi8PT9vHNPHjhUG/f12nCV0guE7jmMYRXfpxBOYHfU8TuDPkJf0In9MbuqDRPw). ]
[Question] [ Write a program or function that takes in a nonempty single-line string of [printable ascii](https://en.wikipedia.org/wiki/ASCII#Printable_characters) characters excluding space: ``` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` You may assume the input is valid. Based on the input, draw a new string arranged on a textual grid of spaces and newlines following [turtle graphics](https://en.wikipedia.org/wiki/Turtle_graphics)-esque rules where the turtle always occupies one grid space and can only face the cardinal directions. Print the first character in the input string to the text grid. The turtle starts here facing right. Iterate over the rest of the characters in the input string (only stopping if the turtle gets stuck), repeating this process: 1. If the 4 grid spaces directly neighboring the turtle are all filled (i.e. none of them is a space), stop iterating. The turtle is stuck and the grid is as complete as it can be. 2. Look at the current character in the input compared to the previous character: * If the current character is lexically before the previous, rotate the turtle a quarter turn left. * If the current character is lexically after the previous, rotate the turtle a quarter turn right. * If the current character equals the previous, don't rotate the turtle. 3. If the grid space the turtle is now facing is not empty (i.e. not a space), repeatedly rotate the turtle a quarter turn left until she is facing an empty grid space. 4. Move the turtle one grid step forward in the direction she's facing and print the current character on the grid in the turtle's new location. Print or return the resulting text grid string with no extraneous rows or columns of whitespace. Lines may have trailing spaces up to the rightmost column with a non-space, but not beyond. A single trailing newline is optionally allowed. **The shortest code in bytes wins.** # Example Here are all the steps of the input `spattuuxze`. The `^V<>` characters show the direction the turtle is facing, they are **not** part of the input or output. ``` s> ``` ``` ^ p s ``` ``` <ap s ``` ``` ^ t ap s ``` ``` ^ t t ap s ``` ``` tu> t ap s ``` ``` tuu> t ap s ``` ``` tuu t x apV s ``` ``` tuu <zx ap s ``` At this point the turtle is stuck so the `e` never gets printed and the final output is: ``` tuu tzx ap s ``` Following is a similar but invalid output since it has an unnecessary leading column of whitespace: ``` tuu tzx ap s ``` # Test Cases ``` spattuuxze tuu tzx ap s spattuuxxze tuu t x apx sze 1111111 1111111 ABCDEFGHIJKLMNOP PEFG ODAH NCBI MLKJ `_^]\[ZYXWVUTSR ^_RS \]`UT [ZWV YX Woo! W o o! woo! !o o w Wheeee W heeee banana a an an b Turtle T ure tl turTle e tTl ur ``` (Do tell me right away if any of these seem wrong.) [Answer] # Groovy (357 Bytes) No external turtle libs were used and no turtles were harmed. ``` R={s->s[0]?[0,-1*s[0]]:[s[1],0]} L={s->s[0]?[0,s[0]]:[-1*s[1],0]} def y(s){l=s.length()*2;z(new String[l][l],[l/4,l/4],s,null,[0,1])} def z(g,l,w,p,h){if(w.length() && !g[(int)(l[0]+h[0])][(int)(l[1]+h[1])]){c=w.getAt(0);w=w.substring(1);if(p && p<c){h=R(h)}else if(p>c){h=L(h)};g[(int)l[0]+h[0]][(int)l[1]+h[1]]=c;z(g,[l[0]+h[0],l[1]+h[1]],w,c,h)}else{g}} ``` Try it here: <https://groovyconsole.appspot.com/edit/5115774872059904> --- # Previous Attempts ## Groovy (397 Bytes) ``` rotR={s->s[0]!=0?[0,-1*s[0]]:[s[1],0]} rotL={s->s[0]!=0?[0,s[0]]:[-1*s[1],0]} def y(s){z(new String[s.length()][s.length()],[s.length()/2,s.length()/2],s,null,[0,1])} def z(g,l,w,p,h){if(w.length() && !g[(int)(l[0]+h[0])][(int)(l[1]+h[1])]){c=w.getAt(0);w=w.substring(1);if(p && p<c){h=rotR(h)}else if(p > c){h=rotL(h)};g[(int)l[0]+h[0]][(int)l[1]+h[1]]=c;z(g,[l[0]+h[0],l[1]+h[1]],w,c,h)}else{g}} ``` <https://groovyconsole.appspot.com/script/5179465747398656> [Answer] # Java, ~~408~~ 406 bytes ``` String f(String I){int l=I.length(),x=l,y=x,z=x,t=y,Z=x,T=y,d=1,i=1,a;char[][]g=new char[l*2][l*2];int[]D={-1,0,1,0};for(char c,p=g[x][y]=I.charAt(0);i<l;p=c){c=I.charAt(i++);d=((c<p?d-1:c>p?d+1:d)+4)%4;for(a=0;g[x+D[d]][y+D[3-d]]>0&&a++<4;)d=(d+3)%4;if(a>3)break;g[x+=D[d]][y+=D[3-d]]=c;z=z<x?z:x;Z=Z>x?Z:x;t=t<y?t:y;T=T>y?T:y;}for(I="";z<=Z;z++,I+="\n")for(a=t;a<=T;a++)I+=g[z][a]<1?32:g[z][a];return I;} ``` The function gets the the input as String and returns the outcome as a String. Internally it uses a 2D char array to store the letters and keeps the min and max columns and rows used in order to return the sub-array that was used. So, in the outcome String there are no leading columns of white-spaces but there are trailing white-spaces up to the rightmost column with a non-space character. A newline is added at the end. Any suggestions to golf it more are welcome :-) [Answer] # Python3, ~~419~~ 414 bytes ``` Z=input();l=r=c=M=R=C=N=len(Z);t=(r*2)+1;A=[0]*t;J=range for i in J(t):A[i]=[" "]*t A[r][c]=Z[0];i=1;Q=[1,0,-1,0];d=q=0 while i<l: if Z[i]<Z[i-1]:d+=3 elif Z[i]>Z[i-1]:d+=1 while A[r+Q[(d-1)%4]][c+Q[d%4]]!=" "and q<4:d+=3;q+=1 if q>3:break r+=Q[(d-1)%4];c+=Q[d%4];R=min(R,r);C=min(C,c);M=max(M,r);N=max(N,c);A[r][c]=Z[i];i+=1;q=0 for i in J(R,M+1): for j in J(C,N+1):print(A[i][j],end="") print() ``` ]
[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/55807/edit). Closed 6 years ago. [Improve this question](/posts/55807/edit) *This question was inspired [this question](https://codegolf.stackexchange.com/questions/55798/implement-arbitrary-precision-integer-division) and @orlp's comment and a lot of the explanation was copied from there.* Write a [*GOLF*](https://github.com/orlp/golf-cpu) assembly program that given two arbitrary size decimal integers `a`, and `b` from stdin outputs two decimal integers to stdout, `Q` and `R` such that `b * Q + R = a`. In other words write divmod with arbitrary precision integers. ## Clarifications * `abs(R)` must be less than `abs(b)` * You do not need to deal with `b = 0` * `a` and `b` are decimal string representing integers in `(-inf, inf)`, space separated. * Output is also space separated in order `Q R`. * Your score is the sum of `# of cycles * (513 - test case size)` for each test-case where the size is listed next to each test-case. * This is a [fewest-operations](/questions/tagged/fewest-operations "show questions tagged 'fewest-operations'") challenge so lowest score wins! * **Your GOLF binary (after assembling) must fit in 4096 bytes.** ## Test Cases ``` (8 bit) 236 7 -> 33 5 (32 bit) 2262058702 39731 -> 56934 13948 (128 bit) 189707885178966019419378653875602882632 15832119745771654346 -> 11982469070803487349 12121955145791013878 (512 bit) 6848768796889169874108860690670901859917183532000531459773526799605706568321891381716802882255375829882573819813967571454358738985835234480369798040222267 75399690492001753368449636746168689222978555913165373855679892539145717693223 -> 90832850270329337927688719359412349209720255337814924816375492347922352354493 57944926054000242856787627886619378599467822371491887441227330826275320521328 ``` --- You should read [the *GOLF* specification with all instructions and cycle costs](https://github.com/orlp/golf-cpu/blob/master/specification.md). In the Github repository example programs can be found. ]
[Question] [ I'm attempting to solve a *programming golf* style *programming puzzle*. I need to write an 18 character phrase in [Chef](http://www.dangermouse.net/esoteric/chef.html) in less than 32 "lines" of code. In this case, a line counts as an ingredient or an instruction. The most straightforward way of doing this is to declare an ingredient for each character and [put each ingredient into a baking dish](http://www.dangermouse.net/esoteric/chef_hello.html). Unfortunately for what I'm trying to do, that takes too many "lines" of code. (I'm limited to 32 and I want to print a 18 character phrase. 18\*2 + title + serves command + headers = 40). Here are things I tried: So I had the idea of just using large numbers that would span multiple unicode chars. But when I print it out, I get garbage. So then I had the idea to just *stream* my characters by reading off each byte of a large number at a time and popping them into a baking dish in a loop. Unfortunately, there doesn't seem to be a way to do with the operators I have (the basic four arithmetic operators). I tried taking a number, dividing by 256, multiplying by 256, and subtracting that from my original number to get the least significant byte, but then discovered that Chef uses floating point (that is the number doesn't change). There are no logical operators. There's no comparison operators. Any idea on what I can try next to print out an 18 character phrase in less than 32 "lines" of code? (Putting commands on the same line doesn't help. It still counts the same). ]
[Question] [ Given the input of `n` and `value`. The code is supposed to nest the single element list with `value` repeated `n` times. The final output should be a multilevel nested list with single repeated values in all sublists. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! ## Test cases: ``` n = 1, value = 'a': ['a'] n = 2, value = 'a': ['a', ['a']] n = 3, value = 'a': ['a', ['a', ['a']]] n = 4, value = 'a': ['a', ['a', ['a', ['a']]]] n = 5, value = 'a': ['a', ['a', ['a', ['a', ['a']]]]] n = 6, value = 'a': ['a', ['a', ['a', ['a', ['a', ['a']]]]]] ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~33~~ 30 bytes *-3 bytes thanks to @xnor* ``` lambda n,v:eval('[v,'*n+']'*n) ``` [Try it online!](https://tio.run/##RYtBCoMwEEX3nuJvwiQ6m7opBDyJ7WKKiRXsKMEGevqYRUs3D/7jv/1zPDftSxxuZZXXYxIoZx@yrJbGzNRqR/dKV6p6BwwgoSZuCYpFkUTnYC@Mq/MN9rToAdL6MhPjV5jkCQZWv8ox4n@UEw "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` F‚Ù ``` [Try it online.](https://tio.run/##yy9OTMpM/f/f7VHDrMMz//8340oEAA) **Explanation:** ``` F # Loop the first input amount of times: ‚ # Pair the (implicit) second input-value with the current list Ù # And uniquify it (which only does something in the first iteration, # transforming the pair of values to a single wrapped value) # (after the loop, the result is output implicitly) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 4 bytes ``` (⁰"U ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwiKOKBsFwiVSIsIiIsIjNcbjIiXQ==) The joys of golfing language :) ## Explained ``` (⁰"U ( # n times: ⁰ # push the value "U # pair and uniquify - a port of the 05ab1e answer ``` [Answer] # [Python](https://www.python.org), 34 bytes ``` f=lambda x,n:n and[x,f(x,n-1)][:n] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3ldJscxJzk1ISFSp08qzyFBLzUqIrdNI0gDxdQ83YaKu8WKhK3bT8IoUshcw8haLEvPRUDXNNKy4FICgoyswr0UjTSM4o0jAz0c7S1FHI0tSEaIJZAwA) Thanks to loopy walt for this one. --- Old answers: ## [Python](https://www.python.org), 36 bytes ``` f=lambda x,n:[x][n>1:]or[x,f(x,n-1)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3VdJscxJzk1ISFSp08qyiK2Kj8-wMrWLzi6IrdNI0gGK6hpqxELUbCooy80o00jSUEpV0FEw1NSHCMKMA) ## [Python](https://www.python.org), ~~36~~ 35 bytes ``` f=lambda x,n:n*[1]and[[x]+f(x,n-1)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3ldNscxJzk1ISFSp08qzytKINYxPzUqKjK2K10zSAQrqGmrEQpZsLijLzSjTSNJQSlXQUTDWjDWI1ITIwwwA) [Outputs as a singleton list](https://codegolf.meta.stackexchange.com/a/11884), but that feels like cheating here. ## [Python](https://www.python.org), 39 bytes ``` f=lambda x,n:[x]+(~-n*[1]and[f(x,n-1)]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY31dNscxJzk1ISFSp08qyiK2K1Nep087SiDWMT81Ki0zSAorqGmrGaEOUbCooy80o00jSUEpV0FEw1ocIw0wA) ## [Python](https://www.python.org), 37 bytes ``` f=lambda x,n:x+(~-n*[1]and[f(x,n-1)]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3VdNscxJzk1ISFSp08qwqtDXqdPO0og1jE_NSotM0gGK6hpqxmhDFmwqKMvNKNNI0opUSlWJ1FEw1oRIw0wA) Inputs as a singleton list. [Answer] # [Proton](https://github.com/alexander-liao/proton), 25 bytes ``` n=>v=>((a=>[v,a])*n)([v]) ``` [Try it online!](https://tio.run/##KyjKL8nP@59m@z/P1q7M1k5DI9HWLrpMJzFWUytPUyO6LFbzf0FRZl6JRpqGmaaGoabmfwA "Proton – Try It Online") ``` n=>v=>((a=>[v,a])*n)([v]) This language is stupid n=> Given n v=> and v (a=>[v,a]) pair v with the current accumulator *n n times ( )([v]) and call that on [v] ``` [Answer] # [Wolfram Mathematica](https://www.wolfram.com/mathematica/), ~~30~~ 21 bytes ``` Print[""@@#~Nest~##]& ``` -9 bytes from @att! [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6AoM68kWknJwUG5zi@1uKROWTlW7X@ag4Nrcka@g7JaXXByYl5dNVd1oo5hrQ6IMgJRhuY6xhCuCYQyBYsa6RnrmNVy1f4HAA) Sample I/O: ``` Print[""@@#~Nest~##]&@@{a,3} ``` > > [a[a[a]]] > > > ``` Print[""@@#~Nest~##]&@@{17,3} ``` > > [17[17[17]]] > > > ``` Print[""@@#~Nest~##]&@@{Pi,6} ``` > > \$[\pi [\pi [\pi [\pi [\pi [\pi ]]]]]]\$ > > > [Answer] # [R](https://www.r-project.org/), 46 bytes ``` function(n,v)Reduce(list,rep(v,n-1),list(v),T) ``` [Try it online!](https://tio.run/##jY6xDsIwDETn9iuiLNiSQWJhgf4EYisdUHEgUhRCklZCiG8vJBSQYGHz@e6e7QclVtNBdbaN@mTBUo9r3nctg9EhkmcHPdnpHClp6JE2ODjPMV6c1zambeWqN8DgtSzaXQRZSywLdfKghbYi8PnhJbPQCnSYZZypa900iO41CTaBRe5vpaTnlvIc2FUyMTNgZdge4jExc5qScxtPNw9xK0P0oGBOk90EsXwyrcTl1/efzHLMpNTYXvzRXvy2hzs "R – Try It Online") Non-recursive approach. Pretty-printing and test harness taken from [Dominic van Essen](https://codegolf.stackexchange.com/a/239892/67312) who insisted I post this as my own. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 9 bytes ``` ∾⟜⋈´⥊⟜⋈⟜⋈ ``` *Pins and bowties FTW* Anonymous tacit function that takes two arguments and returns a nested list. [This](https://mlochbaum.github.io/BQN/doc/arrayrepr.html#simple-lists) is why the list formatting looks weird. [Run it online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oi+4p+c4ouIwrTipYrin5zii4jin5zii4gKCjUgRiAiYSI=) ### Explanation The left argument is the count; the right argument is the value. The example uses a left argument of `2` and a right argument of `0`. ``` ∾⟜⋈´⥊⟜⋈⟜⋈ ⟜⋈ Wrap the right argument in a list: ⟨ 0 ⟩, and then ⟜⋈ Wrap that list in a list: ⟨ ⟨ 0 ⟩ ⟩, and then ⥊ Reshape to a length equaling the left argument: ⟨ ⟨ 0 ⟩ ⟨ 0 ⟩ ⟩ ´ Right-fold that list on this function: ⟜⋈ Wrap the right argument in a list: ⟨ ⟨ 0 ⟩ ⟩, and then ∾ Concatenate with the left argument: ⟨ 0 ⟩ ∾ ⟨ ⟨ 0 ⟩ ⟩ → ⟨ 0 ⟨ 0 ⟩ ⟩ ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` +J',R¹e'[²R'] ``` [Try it online!](https://tio.run/##yygtzv7/X9tLXSfo0M5U9ehDm4LUY////6@eqP7fDAA "Husk – Try It Online") Not an ideal challenge for a language that doesn't support ragged lists... ``` + # join together: R¹ # arg1 repeats of e # 2-element list of '[ # '[' and ² # arg2, J', # joined by commas, # and R'] # arg1 repeats of ']' ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` W{Ɱṭ/ ``` [Try it online!](https://tio.run/##y0rNyan8/z@8@tHGdQ93rtX/f3i5g/7RSQ93ztCM/P8/2lDHIFYn2ghMGoNJEzBpCibNgCQA "Jelly – Try It Online") Value on left, \$n\$ on right ``` W The value wrapped in a singleton list {Ɱ for each 1..n. ṭ/ Reduce by Funky Reverse Append™. ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~29~~ 23 bytes ``` ->n,a{eval'[a,'*n+?]*n} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ7E6tSwxRz06UUddK0/bPlYrr/Z/gUJatLGOfWLsfwA "Ruby – Try It Online") Stole the eval trick from dingledooper [Answer] # [R](https://www.r-project.org/), 49 bytes ``` f=function(n,v)`if`(n-1,list(v,f(n-1,v)),list(v)) ``` [Try it online!](https://tio.run/##jY5LCoMwEIbX5hQhGzOQFty4sZ7ECook7UBI0yQVSvHs1kSL0G66m/kf34ybZ1WrhxkC3gw3YoQOVcfNoRAafeCjUGkZATYBYLZOhvC0Dk2IWm13goYXyYY@cNYwIJm6OY4UDfXyvnjRzFBx9McE002DbQtgPxOV2kua@mfGxKqKNHtpaxaZCXDS0lzCNTJTWkRn2k63yzIRHxxXvBB5nwOQlWkYVF/f75lqy8TU1i7/aJe/7fkN "R – Try It Online") [Answer] # [Racket](https://racket-lang.org/), 49 bytes ``` (define(f x n)(if(= n 1)`(,x)`(,x,(f x(- n 1))))) ``` [Try it online!](https://tio.run/##K0pMzk4t@a@ck5iXrlAE4WikpKZl5qVqpClUKORpamSmadgq5CkYaiZo6FSACR2QlIYuWBAEgDoyiwtyEisVgBLqFQrmQCEA) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes ``` t&@Do[t={#,t},Set@t;#2]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v0TNwSU/usS2WlmnpFYnOLXEocRa2ShW7X9AUWZeSbSyrl1IfnAJkJ0enebgoKzjmVdQWuKWX5QbG6tWF5ycmFdXzVWtlKikY1irA2EYwRjGMIYJjGEKY5jVctX@BwA "Wolfram Language (Mathematica) – Try It Online") Input `[n, value]`. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes 0-indexed ``` Fold[List,{#},Table@##]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773y0/JyXaJ7O4RKdauVYnJDEpJ9VBWTlW7X9AUWZeiYJDerRSopKOoUHs//8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 5 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` a*Åαç ``` Outputs reversed (e.g. `[[["a"],"a"],"a"]` instead of `["a",["a",["a"]]]`), which is allowed based on the comments under the challenge. [Try it online.](https://tio.run/##y00syUjPz0n7/z9R63DruY2Hl///r5SYlKykYMqllKikYAYA) **Explanation:** ``` a # Wrap the (implicit) input-string into a list # e.g. "abc" → ["abc"] * # Repeat it the (implicit) input-integer amount of times # e.g. 5 → ["abc","abc","abc","abc","abc"] Å # For-each over these strings, # using the following 2 characters as inner code-block: α # Wrap the top two values into a list # (which will wrap with the implicit loop-index 0 in the first iteration) # e.g. [0,"abc"] in the first iteration # [["abc"],"abc"] in the second iteration # [[["abc"],"abc"],"abc"] in the third, etc. ç # Remove all 0s from the list with a falsey filter # (only relevant for the first iteration: [0,"abc"] → ["abc"]) # (after the loop, the entire stack is output implicitly as result) ``` [Answer] # [HBL](https://github.com/dloscutoff/hbl), 11 [bytes](https://github.com/dloscutoff/hbl/blob/main/docs/codepage.md) ``` 1,(?(-.)(1('?(-.),)?)? ``` [Try it!](https://dloscutoff.github.io/hbl/?f=0&p=MSwoPygtLikoMSgnPygtLiksKT8pPw__&a=NQo0Mg__) ### Explanation A recursive function: ``` 1,(?(-.)(1('?(-.),)?)? 1 Cons , the second argument with: (?(-.) If the first argument decremented is truthy (> 1): (1 ) Cons ('? ) Recursive call with (-.) First argument decremented , Second argument unchanged ? with nil (empty list) Else (the first argument is 1): ? Nil (empty list) ``` I.e., if the first argument is 1, we get `(cons arg2 nil)`, which simply creates a singleton list containing the second argument; and if the first argument is greater than 1, we get `(cons arg2 (cons [recursive-call] nil))`, which wraps the result of the recursive call in a singleton list and then prepends the second argument to it. [Answer] # APL+WIN, 28 bytes Prompts for n followed by value ``` (¯1↓∊n⍴⊂'[',⎕,','),(n←⎕)⍴']' ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv8ah9YaP2iY/6ujKe9S75VFXk3q0ug5QjY66jrqmjkYeUCWQpwmUU49V/w/UwvU/jcuMS11dPRGIAQ "APL (Dyalog Classic) – Try It Online") [Answer] # [PHP](https://php.net/), ~~56~~ 55 bytes ``` function($n,$a){for($r=[$a];--$n;)$r=[$a,$r];return$r;} ``` [Try it online!](https://tio.run/##JcexCoMwEAbgPU@R4QcTiKPTVXyQIuXQBjt4HofpIn326@C3fbqpPybdNKCOXpss5@eQBCngfNXDEmx8gmfqewjlewU2k73PZgKjn1MIX7bX2nZNETUNJXbc5ZjJfXD@Aw "PHP – Try It Online") Like often, PHP makes the worst score, akin only to C, but dirtier and with lots of $ EDIT: -1 byte, these dollars allow us some trickery with the parser after all [Answer] # [PHP](https://php.net/) 50 bytes ``` function f($c,$n){return --$n?[$c,f($c,$n)]:[$c];} ``` [Try it online!](https://tio.run/##K8go@G9jXwAk00rzkksy8/MU0jRUknVU8jSri1JLSovyFHR1VfLso4FiMIlYKyAv1rr2v3VBUWZeSXyRRpqGeqK6joKxpqb1fwA "PHP – Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 41 bytes ``` $n,$a=$args 1..$n|%{$r=$a,@($r)|?{$_}} $r ``` [Try it online!](https://tio.run/##lcqxCsIwEADQPV9xw2kVmmK0uhWFOjm7S5CrHWoSLkWHJN8exS8w6@M5@yb2I02TvFumjEMXMpoadYeaH16opkETFwH5C/VphbyOx4C3lARyTkIscQAFla4gQm/Ni3i@Wnnx1oDs7dMxeQ/yTG4eQW1@fVvWd2W9Lev7sn74v@cP "PowerShell Core – Try It Online") Please note that this does not work for n = 1, for some reason PowerShell treats it as a string. Even when forcing to return an array. Let me know if not OK and I'll withdraw this answer! [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 29 bytes ``` f(a,n)=if(n--,[a,f(a,n)],[a]) ``` [Try it online!](https://tio.run/##JYqxCoAwDAV/5eGUQDI4dKw/Ih26VLrEEvz/GHE5juNW96nXihjUxbjOQaYqZ5c/tNTGMW4nQ8UuKILl0x7KB9awQY/Et8OYOV4 "Pari/GP – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` FN≔⟦⁺⟦η⟧υ⟧υ⭆¹⊟υ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLTErzQ3KbVIQ1NTwbG4ODM9TyM6IKe0WCM6I1ZHoVQTTFhzBRRl5pVoBJcAqXTfxAINQx2FgPwCjVJNTU3r//@jzXQU1BPVY//rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FN ``` Repeat `n` times... ``` ≔⟦⁺⟦η⟧υ⟧υ ``` ... prepend `value` to the initially predefined empty list, then wrap that in another list. ``` ⭆¹⊟υ ``` Unwrap the very last wrapper list and pretty-print it. [Answer] # [Pip](https://github.com/dloscutoff/pip) `-p`, ~~14~~ 13 bytes *-1 byte by porting [Neil's Charcoal answer](https://codegolf.stackexchange.com/a/239880/16766)* ``` Lal:[lPEb]l@0 ``` [Try it online!](https://tio.run/##K8gs@P/fJzGy0j66MjYnwNUqqfL///@6Bf9N/ycCAA "Pip – Try It Online") ### Explanation ``` Lal:[lPEb]l@0 l is empty list; a,b are command-line args La Loop a times: b b PE Prepended to l Current list [ ] Wrap that result in a singleton list l: Assign back to l l After the loop, l is our desired result wrapped in a singleton list @0 So get the first element and autoprint it, formatted as a list (-p flag) ``` [Answer] # JavaScript (ES6), 24 bytes *-2 thanks to @tsh* ``` n=>g=x=>--x?[n,g(x)]:[n] ``` [Answer] # JavaScript (ES6), 27 bytes ``` f=(c,n)=>--n?[c,f(c,n)]:[c] ``` [Try it out online](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjWSdP09ZOVzfPPjpZJw3MjbWKTo79n5yfV5yfk6qXk5@ukaahnqiuo2CsqfkfAA). [Answer] # [Lua](https://www.lua.org/), 50 bytes ``` n,v=...t={v}for i=2,n do t={v,t}n=n-1 end return t ``` [Try it online!](https://tio.run/##yylN/P8/T6fMVk9Pr8S2uqw2Lb9IIdPWSCdPISVfASSiU1KbZ5una6iQmpeiUJRaUlqUp1Dy/z8A "Lua – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 31 bytes ``` L$`¶ $`*$([$', )$`*] , (]+)$ $1 ``` [Try it online!](https://tio.run/##K0otycxLNPz/30cl4dA2LpUELRWNaBV1HQVNIDOWS0dBI1ZbU4VLBajCjEs9UR0A "Retina – Try It Online") Takes `n` and `value` on separate lines. Explanation: ``` L$`¶ ``` Match the newline between `n` and `value`. This puts `n` in `$`` and `value` in `$'`. ``` $`*$([$', )$`*] ``` Wrap `value` in `n` lists. ``` , (]+)$ $1 ``` Remove the trailing comma in the innermost list. [Answer] # [C (clang)](http://clang.llvm.org/), 56 bytes ``` i;f(*x,n){for(i=~n;++i<n;)printf(i<0?",[%s"-i/n:"]",x);} ``` [Try it online!](https://tio.run/##HczBCoJAEIDh@z7FMhDs5Ep1ChqXHkQ9LNLWgI2yaghir76l1w/@v8mb1sszJaZgjrMVXEIXDbuvUJZxIYR9ZBmD4eJ8B1seBsj5JDeowc5Ia2pePuqPb6dHWTuowFcApN6exeCi9H6TUbO7EBfXbbqxDmZvLCP10zgYAKQ/K72qNf0A "C (clang) – Try It Online") Takes a string literal as *value* and *n* , prints to std out the result. ``` for(i=~n;++i<n;) - iterate from -n to n printf(i<0? - select format string: ",[%s"-i/n..x) * new nest, -i/n to skip comma at first stage :"]" * close nest ``` ``` [Answer] # [Python](https://www.python.org/), 38 bytes: ``` f=lambda n,v:[v,f(n-1,v)]if n>1else[v] ``` [Try It Online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIU@nzCq6TCdNI0/XUKdMMzYzTSHPzjA1pzg1uiz2f0FRZl6JRpqGqY6CeqK6puZ/AA) ]
[Question] [ Create a program that, given a name as input, will generate a Valentine’s day greeting card featuring that name, with its source code also having a Valentine’s day theme. The greeting can be either ASCII art or a generated picture. Additional conditions: * The source code has to **look** like something Valentine's day themed (like a heart, or a poem or anything. Be creative) * All code and related assets need to fit into your answer. * You can use network connections, but you can only download this page (in case this question acquires multiple pages you can download them as well). You can use the StackApps API if you want to. * The "has to look like something Valentine's day themed" rule also applies to anything you try to use from this page (if using network connections). * No other external files are permitted. * You can use the standard library of your language, but no external packages are allowed. Other restrictions: * None. This is a popularity contest. Scoring: * Each visible vote (= upvotes minus downvotes) is worth 10 points * For every two upvote on a comment on your answer you get 1 points * Answer having the most score will be accepted on Valentine's day (14 Feb 2014) \*\*This contest is now closed, thanks for participating! \*\* You can still add answers if you'd like though [Answer] ## C What can be more romantic than syntax highlighting? ``` *xx= "De" "ar %" "s:\n" "Consta" "nts ar" "e red, " "variable" "s are blue.\nIf lo" "ve had a syntax, I" "'d highlight you" ".\n",n[9];main( ){printf(xx, gets(n)) ;xx; } ``` Output: ``` $ echo Ilana | ./vanentine Dear Ilana: Constants are red, variables are blue. If love had a syntax, I'd highlight you. ``` [Answer] # Java 8, 500 lines of code This is the longest entry that I had ever did here in codegolf. It is in the form of a java program constituted from the concatenation of the lyrics of 7 different songs that I composed just for this competition. Looking back in time, I am convicted that I am really crazy to create this thing just for this competition, and some verses are still repeating over and over with rhymes in my head. Comments were very abused, so I could write **everything in the program to be within verses**, except for a short guitar solo in the end of the second song. There is no blobs of characters left hidden somewhere. In fact, I did not thought that to write music as poems with rhymes that could be compiled and run by a java compiler to do something not trivial was damn so hard, specially writing poems with terms like `AffineTransform`, `BufferedImage`, `Graphics2D` and `newScheduledThreadPool`. The program itself is somewhat complex. It does show a screen with an animation of a rotating heart, some stars and a message for your beloved-one. All of that is done with linear algebra, primitives drawing, setting pixels, text drawing and sprites. EDIT: Bugfix to reduce the font size to avoid text cuttings. To run it: ``` java that_day <The name of your girlfriend/boyfriend> ``` If you omit your girlfriend/boyfriend name, it will show the usage and default to my name (Victor) instead. This is some sort of mark I left as a form of some personal signature. ![Sample screenshot](https://i.stack.imgur.com/fJYCL.png) Here is its source: ``` // ****************************************** // TRACK 1: THE GREAT LOVE IN THE JAVA ISLAND // ****************************************** /* Do you ever */ import /* ? |* If in the */ java /* island */. /* There was a sign that once said: */ awt. /* what is this crazyness?*/*; /* Or maybe instead, |* Do you really */ import /* if in the */ java /* island */. /* they really said */ awt.geom. /* instead? */*; // Or even maybe, /* Do you */ import /* if all that */ java.awt. /* had some */ image/*? */.*; /* Do you */ import /* if that */ java /* has a */ .util.concurrent/*? */.*; /* Do you */ import /* if that */ java /* has some */ .util.Random; // game? /* Do you */ import /* if that */ static java /* has some */. lang/*uage or */. Math /* class? */.*; // And then /* We do */ import /* about all those */ javax // stuff /* So, lets play in the school */ .swing /* like the old times, oh my honey?*/.*; // In the school /* I were in my */ class that_day{ // /* And some */ Random stuff // the teacher were saying =/* all that I wanted was a*/ new Random /* game to play*/( ); // But then you came!!!! */ /* And I felt the */ GreatLove /* in my */ heart, /* you, were my */ star, /* you were all my */ life; /* In that */ class /* I saw my */ GreatLove // in your face /* I was so happy that i wanted to */ extends /* a */ BufferedImage //!!! {/* that */ GreatLove /* was */( int resting, /* and so */ int tense /* i felt */){ super(//!!! /* no */ resting, /* I was so */ tense, /* I was sure that I wanted*/ 2 /*love you*/); }}/* I would */ boolean your_heart( /* a day */ long /*in*/ YourArms, long /*in*/ your_arms, long /*IN*/ YOUR_ARMS // OH YEAH! ){ /* I want to*/ return /*to*/ YourArms * /*, to return to */ YourArms +/* to return to*/ your_arms // OH YEAH! /* to return to*/* your_arms </* to return to*/ YOUR_ARMS /*to return to*/* YOUR_ARMS;} // OH YEAH // ******************************************* // TRACK 2: THE STRING GUIDING MY LIFE, PART I // ******************************************* /* In the */ public//, you said you did not wanted me! /* I frooze */ static /* and felt a */ void /* inside */ /* coz you were the */ main (String[] guiding_my_life ){ if (guiding_my_life /* was a string with such */ .length /* I felt like I was */ == 0 // in that date. ){ /* That was the */ System. /* and i were */ out. /* So i */ print//d this letter for you, /* Remember, */( "usage is java that_day and-put-here-yours-love-name"); /* I was in a cinema's */} EventQueue. /* I got your number, was going to */ invokeLater(() -> /* But this day is a */ new //day /* A day like */ that_day /* Are you */ ((guiding_my_life/*? Even when its */. length == 0? /* You are the */ new String[] /* of my life? Would I be a */ {"Victor"} : /* with my string */guiding_my_life)//? [ 0-0-0-0-0-0/*HHHHHH YEAH!*/])) ;} that_day /* you are the */( String guiding_my_life) { /* a */ int tense /* feeling with a level */ = 1000; /* a */ long missed /* one with a number */ = 466, /* I looked for your */ door /*. Now I know, its number is */ = 279, /* but missed */ because /* I was looking for */ = 379, /* I was so */ crazy /* that i looked even at the number */= 261, /* and */ number = 534; /* And my */ heart /* was */ = /* that */ new GreatLove /* Oh I was so */(tense, /* Oh I was so */ tense); // Oh yeah! /* And then I am */ for/*ever*/ (int erested /* in you */ =000000000 ;// YEAH; /* int*/erested </*in your in*/tense /*love*/; /* int*/erested ++ // forever! ){ for/*ever */(int/*erested */ i_was =0-0-0-0-0-0//0-0-0-0-H-H-H-H-H-H YEAH ; i_was </*so*/ tense; i_was ++ // so tense, oh yeah! ){/* but, I knew that */ if (i_was +/* so */ missed >// by you /* and you were too int*/erested & i_was -/* so */ missed </* and */ tense- /* so int*/erested & (/*in*/ your_heart( i_was -/* looking at that */door, /* int*/erested /*in you*/- because, /* i am */ crazy /* for you */)| your_heart ( i_was -/* so */ tense +/*at your*/ door, /* int*/erested /*in you*/- because, /* i am */ crazy )/* for you */| /* int*/erested /*in your*/> number |( i_was /**/> missed /* that much */ & i_was </* so */ tense - missed /* you too much */ & /*I am so int*/erested /*and*/> crazy))) /* To your */ heart. /* I would */ setRGB /* there */( /* because */ i_was, /*int*/erested, // GUITAR SOLO: 0XFFFF000___0 //0XF00_00X0__XF0F_0F0F0___00 F0X_F0F0X__FFF0X0__F000!!! ); //F0000 0XF0_0XF0_0XF0 F0F0F0__F0F0F0__F0F0F000000000! }} // 0xFFFFFF000000000-0-0-0-00000000000000 X0_X0_X0_X000 YEAH! /* You are my */ star= // like you, no one will go so far /* my */ new GreatLove( // you are /* I was so */ tense, /* I was so */ (int)tense); // OH YEAH! // **************************************** // TRACK 3: INTREPID INTUITIVE INTELLIGENCE // **************************************** int[]repid /* I am, this is */ = /* my */ new int/*elligence*/[ /* Just */ 5 /* days I wait */]; /* This is my new */ int[]elligence =/* my */ new int/*elligence*/ [ 5 /* years */]; for // now ( /* Is this */ int uitive // or nah? = 0//r nah? ; /*int*/uitive </*for*/ 5 //years ; /*int*/ uitive ++ // Or nah? ){ /*int*/repid [/* or int*/uitive] /* Is this */ = /* to */ (int)//elligence? ( cos /* the */ (toRadians( 90+ // aliens came // They came! they came! /* From the */ 144 * /* How this is int*/uitive)) /* how??? 1- Oh, this */ * /* is so */ tense / 2- /* It is so */ -tense /( /* 3- /* It is so tense */ 4- /* It is like */ 2 /* times so tense.*/) ); /* This is my int*/elligence[ /* My int*/uitive /* intelligence*/]= ( int/*elligence*/) (/* And the */ sin /* of the */( toRadians (90+ // aliens /* is that they did not got my int*/uitive * // intelligence 1__44 /* times */)) /* that was so */* tense / 2 + /* the times this was so in*/tense / 2 /* intense*/);} // ******************************************* // TRACK 4: THE GRAPHICS OF THE LOVE IS A STAR // ******************************************* /* The */ Graphics of_the_love /* is */ = /* to a */ star. getGraphics /**/();/**/ of_the_love /* and then */.setColor( // of the star /* A */ Color /* that was something like */ .YELLOW ); /* The shape */ of_the_love /* is draw when you */.fillPolygon // of the star. /* You have your reputation id, its the */( repid, /* And you use it with much d*/elligence, 5 /* times each day */); /* You do discover */ life // again = /* Its happy to see my */ new GreatLove // everyday (/* I am so excited and a bit*/ tense, /* I had that feeling so in*/tense); /* The */ Graphics of_your_heart /* is*/ = /* to the */ life // of a star . getGraphics /**/();/**/ of_your_heart /* and then */.setColor( // of the sky /* A */ Color /* that was something like */ .CYAN ); /* In the letters */ of_your_heart /* you */ .setFont (/* And when you remember */ of_the_love /* you */.getFont(). /* In the happiness, please */ deriveFont /* everyday */( /* You might do it only */ 1 /* time or even */, 67)); /* But do remember */ of_your_heart /* everyday */. // ******************************************** // TRACK 5: THE STRING GUIDING MY LIFE, PART II // ******************************************** /* Yesterday, I have */ drawString ( "Hey, " + /* I have to say that you are the string that was */ guiding_my_life + /* I say, plus I say, hey: */ ", I love you", 20 /* times that I will say */, /* it was so */ tense /* but i will say it *// 2 - 50 /* times that I will say */); /* John */ JFrame /* is the name of my */ neighbour // in the next door = // him, I had no such friend as before /* Some day I asked him for some */ new//s /* Then */ JFrame /* said I got a letter and the sender was: */( "I love you, "+ /* it was nobody else but the string */ guiding_my_life); /* I am so grateful to my */ neighbour /* coz he */ .setBounds( /* I was */ 10 /* times excited and */, 10 // times happy /* My emotion was at */, 500 /* percent */, /* When I read the letter I falled in love */ 500 /* rounds */); MY_TRUE_LOVE /* was */ back_for_me /* There is nothing */ = /* or even like this */ /* So I had a */ new /* chance, */ MY_TRUE_LOVE(); // finally came /* And was my */ neighbour /* who */ .add(/* she */ back_for_me); /* My */ neighbour. /* was great, he */ setVisible( /* me again || my */ true /* love was back to me! */); // So I defined a new plan /* and */ Executors /* it then */. /* with a */ newScheduledThreadPool( /* For */ 1 /* time I had my love back again */). /* and I */ scheduleWithFixedDelay(() -> /* back in the cinema's */ EventQueue. /* I came || and then I */ invokeLater(() // her cellphone again! -> /* She was finally */ back_for_me /*, || and the only difference was that her hair got a */ .repaint()), /* I was feeling as a */ 0 /* before */, /* Now I feel */ 50 // times more worth. /* in each */, TimeUnit. /* of just some */ MILLISECONDS /* I'm love.*/); /* And I won't forget my */ neighbour. /* Just to */ setDefaultCloseOperation( /* Now that I have a love and a great friend, we */ 3 /* really rocks!*/);} // ************************************* // TRACK 6: HOMEWORK ABOUT A BORING BOAT // ************************************* /* Last year in my */ class I_MET{ /* my */ GreatLove she; /* was so lovely that I knew: */ I_MET( /* my */ GreatLove /* I was sure that she was really */ my_love ){ she /* is */ = /* to an angel, she is all */ my_love;} /* Oh yeah, man she is */ double pretty, very_nice, /* and much */ talented, /* She just should be my, beloved */ girl,friend; /* But the teacher would */ void /* my weekend, he gave a homework: /* to */ draw /* some stupid */(Graphics2D/*, of a boring */ boat) { /* What I didn't knew, was that weekend would, */ AffineTransform my_life =/*that */ new AffineTransform /* happened, really */()/*vernight. */; /* The teacher said, the homework should be done in */ double//s // And that was really when my chance came. // I invited she, to join me in the homework /* And she came to my house, because a */ boring //boat = /* And */ she ./* measured the boat and */ getHeight (),vernight /* I managed */= she /* to */.getWidth ()/*n the same! */; my_life /* would change and then */ .rotate( /* When she said that she had trouble in convert */ toRadians ( /* But in that stuff, I was really */ talented//!!! ),/* And because of that */ boring /* homework *// /* We */ 2, /* got together O*/vernight /*, working on that boat. *// /* The life of we */ 2 /* was about to */); AffineTransform // in that day /* When she */ kissed_my_mouth // at midnight and ten. /* For us both, that feelling was */ =/*lly*/ new /* An */ AffineTransform ()/*n that night, that was for real */; /* When she */ kissed_my_mouth/*, the feeling I can't */ .translate(- my_life. /* was */ transform/*ed*/( /* to a */ new // plane! /* Working in a */Point2D. /*A homework in */Double( /* She was really */ talented /*, but with */ >90 // percent done /* I was so sad when she needed to go back to her home! */ & /* had i already said how she is */ talented/*?*/< /* Had we kissed in */ 6 /* hours and */* 45 /* minutes of work*/? /* O*/vernight /* working */: 0/*n the same boat.*/, /* Man, had I already said how she is */ talented/*?*/< /* Without her, could that be */ 180 /* times or worse of boring homework*/? /* So */ boring: 0/*n that boat in an otherwise */), null // weekend ). /*But I had to */getX ()/*n*/ ,-my_life /*and*/. transform( /* In a much better thing a */new Point2D /*homework to be done in */.Double//s (/* Was she */ talented /* like something */ >180 /*percent*/? /* O*/vernight : 0/*n the boat, I and my */, talented /* girl finished */ > 90 /* percent. */ & /* she is so*/ talented /* that in */ < 6 /*hours and */*45 /* minutes of */ ?boring /* homework */: 0/*n an otherwise */), null // weekend, we got a love! )./* And now, we both */ getY//a new life! ()/*n that night */); my_life /* was */. preConcatenate//d /* She */( kissed_my_mouth /* and she though me CorelDraw */); /* However, she didn't knew about */ BufferedImage/*!!! */ i_knew =/*lly well right from the start */ /* that I would had a */ new AffineTransformOp /* in */( my_life, /* and */ 2 /* that working to */).filter( /* out the boringness */ she /* too did not got a */, null /* weekend */); /* I had an */ AffineTransform on_my_life /* She */ =/*lly had a */ new AffineTransform ()/*n*/ ,her_life /* Oh, she really */ =/*lly had a */ new AffineTransform ()/*n*/ ;her_life // OH YEAH! /* I can't */.translate (/* how */ very_nice, /* and */ pretty /* she is.*/); /* I got */ on_my_life /* a new */ .scale( /* of bliss. */ /* with a */ girl /* that kissed me, *// /* working a */ boring /* homework */, /* got a girl*/friend /*O*//vernight )/* in a work about a boat. */; on_my_life /* I can't */.translate /* How I became so live */(( /* from a */ boring -/* homework, */ i_knew. /* how to */getWidth( )) /* We *// 2, /* working */( /*O*/vernight - // Until the night was high i_knew /* to */.getHeight ()//n the night when she came )/ /* We gotta to be */ 2//gether ); //OH YEAH! on_my_life /* I */.preConcatenate( /* And */ her_life // Would never be the same ); /* Looking the net for a */ boat. // page /* To finally */ drawImage( i_knew, /* that with this girl */ on_my_life, /* I would never get a */ null // weekend!!! ); /* OH YEAH! */}} /* And monday back in the */ class MY_TRUE_LOVE extends /* the */ JComponent { I_MET a_great_love /* And */ =/*lly for her was this a */ new // love I_MET /* with her */( heart ); I_MET love // in her heart /* And I */ =/*lly met a */ new // life! I_MET /* a new */ (life); // ***************************************************** // TRACK 7: DOUBLE TROUBLE IN MY GIRL'S FATHER CARD SHOP // ***************************************************** /* I was in */ double trouble, last_year, at_my_phone; // The dad of my girl had a shop in his home. /* He were open to the */ public // that day. But no customers came /* Just a */ void // on the shop, that was all then. /* He */ paintComponent/*s of some */(Graphics cards){ /* But */ trouble /* is */ = trouble + /* all that */ stuff. /* The */ nextDouble /* trouble */ ()//ff the week /* Was like */* 5 /* times as so big */- 5 /* times *// 2. /* the dad of my girl. */ ; if (/* he was really bad to sell all that */ stuff. /* The */ nextDouble /* trouble he had was */ ()/*nce a big */</**/ 1./ /* He had bad sells for more than */ 20 /* days */) /* The truth is that */ trouble /* is */ = /* to */- trouble; // no matter when /* As */ a_great_love /* my girl is so */. talented /* To */ =lize (a_great_love/*,*/. talented // also I am! /* But love */ + /* all that */ trouble // is really hard then ); /* And */ last_year /* to */ =lize(// the bills, that was a real pain last_year + 1 /* or maybe *//2. // months ); at_my_phone /* her dad called to */ =lize(// the bills ongoing at_my_phone /* he complained, and asked money to*/-/* give back in */ 7 /* days or maybe *// 10.); // And that put me in trouble with my girlfriend! /* But that */ Graphics2D CARDS // were really cool stuff! =/*But that */(Graphics2D)cards;// were really-really cool stuff! int eresting // they were =/* You could */ getWidth ()//f that , a_great_card_pile =/*lly was possible to make it */ getHeight /* very high*/ ()/*n all those*/; CARDS. /* They */ setColor // very careful. (/* and the */ new Color//s her father painted, all of them were very cool. (/* But in the end, they only selled */ 15 /* or */* 17, // each day /* But could produce more then */ 200 // everyday /* And I counted */, 225 /* boxes of cards and paint abandoned in the store at that day. */)); /* Her dad in the */ CARDS/*, he did it */.fillRect /* All that stuff was very */((int)eresting - (int)eresting, (int)eresting -/* very */ (int)eresting, /* really really */ (int)eresting, // OH YEAH! /* But my heart broke with such */ a_great_card_pile );/* he weren't selling enough, and I had */ a_great_love /* to my */.girl = /* I could not see a great */ (int)eresting // card shop end ; /* And I had */ a_great_love. /* to my girl*/friend = /* And I decided that such */ a_great_card_pile /* should finally get an end! */; /* My girl had */ a_great_love /* in */ .draw/*ing all those */(CARDS); // OH YEAH! for (/* that situation, i did needed */int elligence =/*from n*/0/*w on, I used my */; (int)elligence < 2 /* sell everything*/ + /* handle all the bills and */ stuff. /* my */ nextInt//elligent move was to buy the card shop! */ (/*My girl was surprised, */ 5 /* times she said*/); /* And she admired all that my int*/elligence /**/++ ){ I_MET her_father /* he was */ =//lly surprised! /* And after that I got to the shop a */ new // life. OH YEAH! // But he imposed a condition: We had to merry, that was the reason /* So in that church */ I_MET (/* my loving */star /*!!!!*/); // OH YEAH! /* And */ her_father. /* was my */ friend = /* And to */ a_great_card_pile /* I had it to end. *// /* For */ 6 /* dollars each card, */ + /* a few cents. */ /* With that */ stuff // done, /* the */ .nextDouble /* trouble was gone! */ ()/*n that day */* a_great_card_pile /* will never again be the reason to ring my phone! *//6;/* */ her_father /* was happy */. /* His */ girl // was married! =/*And how int*/eresting / 6+ /* times we are selling all that */stuff. nextDouble /* tr*/()/*uble we had no more. */* /* and look how */(int)eresting / /* For just */ 6 /* bucks a card we selled */; her_father. /* was */ very_nice =// The man was very nice. // OH YEAH! /* And */ stuff. /* was done. */ /* The */ nextDouble /* tr*/()/*uble was gone. */*( /* And how int*/eresting- her_father /* was happy */. /* coz his */ girl /* was married. */ ); her_father/*s cards are */ .pretty = /* he produces all that */stuff. // And then I selled everything // Until the last one! /* The */ nextDouble /* tr*/()/*uble was gone. */*( /* And to sell such */ a_great_card_pile // was a job done. - her_father /* were my old */. friend ); her_father /* were so much */ .talented =/*And all those */ stuff // we happy worked together! /* But indeed the */.nextDouble /* tr*/()/*uble then come! */* /* For */ 360 /* days I could even not imagine! */; her_father /* used to */.draw( /* all those */ CARDS);} // He did it pristine! /* But now my */ love.girl /* was crying! */= // Because her father was died. /* And see how */ (int)eresting; /* Is to feel */ love /* to a */ .friend // But we do only perceive this /* when it had come to the end */= // But live goes on now. a_great_card_pile /* entirely new was set on now. */; /* That was my */ love. /* A girl very */ talented /* She */ =lize//d her father // artistic scent. (/*My */ love /* girl is so */.talented +5 // times pround her father would now be then. ); /* And she */ love /* to */.draw(/* all those */ CARDS);} /* She do it */ double // better // of what did the old man. /* Sometimes we rea*/lize(double /* times */ indeed){ /* That could her father has */ return//d (( indeed </* in */0/*ur first kid*/)? /* The boy is */ indeed //an artist. +/* As was his grandpa */ 360 // months in the past. :// When we do sell all those cards /* I am very grateful */ indeed) %// To that old man // who once married his daughter to me. /* I am */ 360 // times so grateful forever. ;} /* This is why I love so much his daughter in his memory respect. */ }} ``` [Answer] # Befunge-93 Run as `echo '[NAME]!' | ./befungee.py test` (assuming the code below is in a file named 'test') for the output "Happy Valentine's day [NAME]!" The top few lines are for reading in the name; if you remove them and just leave the heart it will simply say "Happy Valentine's day". ``` v v _ v _v# 1< >~:"!"-^ >10g1+:10p0p:^>" "37*2+2p"v"63*2+:"g"\2p2+2p" "10p^ | -" "< v < > 92+:*91+9*v v:+19*2*5+< v*66*5+2*37*<>7+v v1*<>*91+9*7v^29< v3<>*7+89*v 4 <>9v v+<>*3^ >+9v^*< v<>9^ v,_@^8*:+<>v v<>9^ >1v^< v*+ *>:^ ^<>v v<>^ +.^ >v^< ^<>v v<>^ v<>^ >v^1< ^1<**>4^ v4<>^ >+v^9< v*<>4^ >9v^*7< v+3<>+^ >1+v^*< v2<>*1^ >:v^44< v8*<>7^ >*1v^*< v4<>*4^ >+v^7*< v9*<>7^ >92v^4< v2<>5*^ >+v^4< v+<>3^ >5v^*:<>*^ >*v>2^ >^ ``` [Answer] # [Extended Brainfuck](http://sylwester.no/ebf/) This is by no means the shortest code that does this. Actually not used any EBF feature except for the same as `BF-RLE`. ``` +[->,10-]>>5+[-<6+>] <++.........>8+[-<8+ >]<-.>7+[-<7->]<.-.6-.>9+[-<10+ >]<3-......>5+[-<6->]<.>7+[-<7->]<-- .+.>7+[-<7+>]<.>9+[-<9->]<4-.>4+[-<5+> ]<++........>4+[-<4+>]<-.>4+[-<4->]<+......> 9+[-<10+>]<++..>9+[-<10->]<--......>7+[-< 8+>]<4+.>9+[-<9->]<-.>4+[-<5+>]<++.......>4+[-< 4+>]< -.>4+[-<4->]<+.......>9+[-<10+>]<++..>9+[-<10->]<--.......>7+[-<8+>]<4+.>7+[-<8->]<4-... .....>6+[-<6+>]<.>5+[-<6+>]<3+.4-.>4+[-<4+>]<+.>9+[-<9->]<-.[-]<<[11+<]>[.>]10+.>4+[-<5+>]<++. .....>9+[-<10+>]<++.>9+[-<10->]<--........>9+[-<10+>]<++..>9+[-<10->]<--........>9+[-<10+>]<++.> 10+[-<11->]<4-.>4+[-<5+>]<++......>9+[-<10+>]<++.>9+[-<10->]<--.>8+[-<8+>]<-.......>5+[-<6+>]<-. .>5+[-<6->]<+.......>8+[-<8->]<+.>9+[-<10+>]<++.>10+[-<11->]<4-.>4+[-<5+>]<++......>9+[-<10+>]<+ +.>8+[-<9->]<5-.>4+[-<4->]<+.13+.....13-.>7+[-<8+>]<4+.>6+[-<7->]<3-.>4+[-<4->]LOVEME<+.13+..... 13-.>7+[-<8+>]<4+.>5+[-<6+>]<++.>9+[-<10->]<--.......>6+[-<7+>]<.>6+[-<6+>]<+.6-.5+.>9+[-<9->]<3+. >8+[-<9+>]<5+.8-.>8+[-<9->]<3+.>8+[-<8+>]<+.13+.10-.>8+[-<8->]<4-.>9+[-<9+>]<3+.5-.8-.--.>4+[-<4+> ]<-.12-.3-.13+.>10+[-<10->]<4-.>4+[-<5+>]<++.....>4+[-<4+>]<-.>4+[-<4->]<+..8+.8-.....9+.9-..8+.8- .....9+.9-..>7+[-<8+>]<4+.>7+[-<8->]<4-......>9+[-<10+>]<3-.>4+[-<4->]<--.>8+[-<9->]<3+.>9+[-<9+>] <++.11-.7-.11+..>8+[-<9->]<4-.>9+[-<9+>]<+.3+.9-.7-.>8+[-<9->]<3+.>9+[-<9+>]<3+.12-.3-.>8+[-<9->]< 3+.>8+[-<9+>]<-.6-.11+.11-.>4+[-<5+>]<3+.+.>9+[-<10->]<++.-.>4+[-<5->]<--.>4+[-<5+>]<++....>4+[- <4+>]<-.>4+[-<4->]<+.>7+[-<8+>]<4+.>7+[-<8->]<4-..13+.....13-.8+.+.9-.13+.....13-..>4+[-<4+>]<-. >4+[-<4->]<+.>7+[-<8+>]<4+.>9+[-<9->]<-.>4+[-<5+>]<++...>4+[-<4+>]<-.>4+[-<4->]<+...>7+[-<8+>] <4+.>7+[-<8->]<4-......>4+[-<4+>]<-.>8+[-<9+>]<5+..>5+[-<6->]<--.>7+[-<8->]<4-......>4+[-<4+>] <-.>4+[-<4->]<+...>7+[-<8+>]<4+.>9+[-<9->]<-.>4+[-<5+>]<++..>4+[-<4+>]<-.>4+[-<4->]<+.....>@ 7+[-<8+>]<4+.>7+[-<8->]<4-....>4+[-<4+>]<-.>8+[-<9+>]<5+....>5+[-<6->]<--.>7+[-<8->]<4-.. ..>4+[-<4+>]<-.>4+[-<4->]<+.....>7+[-<8+>]<4+.>9+[-<9->]<-.>4+[-<5+>]<++.>4+[-<4+>]<-.> 4+[-<4->]<+.......>7+[-<8+>]<4+.>7+[-<8->]<4-..>4+[-<4+>]<-.>8+[-<9+>]<5+......>5+[-< 6->]<--.>7+[-<8->]<4-..>4+[-<4+>]<-.>4+[-<4->]<+.......>7+[-<8+>]<4+.>9+[-<9->]<-.> 6+[-<6+>]<+.>7+[-<7+>]<-.>8+[-<8->]<+........>7+[-<8+>]<4+.>4+[-<5+>]<-.>7+[-<7-> ]<-........>7+[-<7+>]<+.>8+[-<8->]<.>4+[-<4->]<+........>8+[-<8+>]<-.3-.>9+[ -<9->]<-.>4+[-<5+>]<++..>8+[-<8+>]<.>7+[-<7->]<--..+...>7+[-<7+>]<..> 5+[-<6+>]<-.>5+[-<6->]<++.>7+[-<7->]<--.+.>7+[-<7+>]<.>8+[-<8-> ]<+..>8+[-<8+>]<-.>7+[-<7->]<.-.6-.>9+[-<9+>]<4+.>5+[-<6- >]<+..>7+[-<7->]<...-..6-.>5+[-<6->]<+.>4+[-<5+>]< ++..........>9+[-<10+>]<++.>9+[-<10->] <--....>8+[-<8+>]<.>7+[-<8->]< -.7-....>9+[-<10+>]<++. >10+[-<11-> ]<4-. ``` Usage: ``` bf ebf.bf < valentine.ebf > valentine.bf echo "Code Golf" | bf valentine.bf ``` Output: ``` _.-'~~~~~~`-._ / || \ / || \ Dear Code Golf | || | | _______||_______ | |/ ----- \/ ----- \| Join me and together / ( ) ( ) \ we shall rule the galaxy! / \ ----- () ----- / \ / \ /||\ / \ / \ /||||\ / \ / \ /||||||\ / \ /_ \o========o/ _\ `--...__|`-._ _.-'|__...--' | `' | ``` Ascii art is not made by me but just picked up [here](http://www.asciiartfarts.com/20120803.html). [Answer] # Perl awfully looking heart 2: ``` eval's unable to compute a hint, when I write perl, I think of you; I think of you at every '. print' just be with me, since I love you ' ;;@_= split//, $@;$"=$^I, $_=0.00.106. 117.115.116.032.0115.0105. 110.99.101.32.116.104.101. 32.118.105.111.108.101.116 .115.32.97.114.0101.032. 98.108.117.101.10."@_[ 14,11] @_[20,49] @_[ 46,1,6,11,2,4,33 ,02,013], @{[ shift]}$/" ,print ``` The poem thingy at the beginning is not *fully* used, but it is *somewhat* used, so cannot be removed; Output: ``` $ perl valentine.pl \$NAME just be with me, since I love you just since the violets are blue be my valentine, $NAME ``` [Answer] ## Processing Almost entirely based on [this](https://codegolf.stackexchange.com/a/20597/12205) answer of mine. And the input part is taken from [here](https://web.archive.org/web/20131213032446/http://wiki.processing.org/w/Typed_input) with modifications. ``` public static final int px=25; public static final int rectRad = 3; PFont font; public boolean[][] used; public int[] heart = { 65, 66, 67, 72, 73, 74, 84, 85, 86, 87, 88, 91, 92, 93, 94, 95, 103,104,105,106,107,108,109,110,111,112,113,114,115,116, 122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137, 142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157, 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177, 183,184,185,186,187,188,189,190,191,192,193,194,195,196, 204,205,206,207,208,209,210,211,212,213,214,215, 224,225,226,227,228,229,230,231,232,233,234,235, 245,246,247,248,249,250,251,252,253,254, 266,267,268,269,270,271,272,273, 287,288,289,290,291,292, 308,309,310,311, 329,330 }; void setup( ) { size(500,500); background(255); stroke(190+1); strokeWeight(1.75); fill(0); font=createFont("Purisa",28,true); textFont(font,28); frameRate(50); used = new boolean [width/px] [height/px];} void keyReleased(){ if(key!=CODED){ switch(key) { case BACKSPACE:name=name.substring(0,max(0,name.length() - 1)); break; case 0xA: case RETURN:fd =1==0;background (0xFF); break; case ESC: case DELETE: break; default: name+=key; }}} boolean fd=true;String name=""; int c=0; void draw(){if(fd){background(255);text("Ple" +"ase enter a name:",35, 30); text(name,35,70);c= frameCount;return;}int i, j, df = width*height/px/px ,tf = (int)(500 * frameRate/1000);do{i=(int)random( 0, width/px);j=(int)random(0,height / px);} while (used[i][j] &&frameCount-c<= df);used[i][j] = true; if(frameCount-c > df+tf) {noLoop(); return;} else if( frameCount-c == df+tf) { fill(63+32); text("Dear " + name + ",", 10, 50); text("Happy Valentin"+ "e's Day!", 80, 200);text("Love,\nAce", 10, 0xA * 43); return;} else if (frameCount-c>=df+1) { return;} int R=(int)random(64,255-64); int G = (int) random(128,255); int B=(int)random(128,255); int alpha =(int)random(55,85);int hash=j*width/px+i;if(java.util. Arrays.binarySearch( heart,hash)>=0) {R= (int)random(128+64, 255);G=(int)random( 0,63);B=(int)random (0,63); alpha=(int)random(70, 100);} fill(R,G,B,alpha); rect(i*px,j*px,px,px,rectRad,rectRad,rectRad,rectRad); }/////////////////////////////////////////////////// ``` See the animation online [here](https://adrianiainlam.github.io/valgen/). (You may have to click on the canvas in order to be able to type input. The easiest way would be to click on the input prompt. Note that the code used in this online demo is slightly different due to differences between Processing (the program above) and Processing.js (the one used in the demo).) Alternatively, here is one possible output, given the input "Sample Input": ![Screenshot of sample output](https://i.stack.imgur.com/o4l0A.png) [Answer] # [Zozotez LISP](http://sylwester.no/zozotez/) Zozotez is a LISP interpreter written in [Extended BrainFuck](http://sylwester.no/ebf/). ``` ;((((((((((((((((((((())))))))))))))))))))) ((\(even to know my programming language) ;(()) (to (my programming language) 'Lisp);(((((()))))) (to (know |I love |) 'parentheses);(((((((()))))))) (to (even you more than there are) c);(((((()))))) (to (know |parentheses in my heart ()()()|)));() (~ w (c "(c w))) p " c 'Dear (r));((((())))) ``` How to run: ``` jitbf zozotez.bf ``` Paste in code with only one trailing newline. Then your \*friends name. Output looks like this: ``` Dear Max Love I love you more than there are parentheses in my heart ()()() ``` Needless to say, this text displays a lot of love since who doesn't love lispy parentheses? [Answer] # Java ``` public class Vale {public static void main( String []args) {int a; char c,d,r,g; String s ="hi";// double x,y,z=0; System .out.print ("hi "); String[ ]parts=s.split( "///////"); String string="This is -for- ";double w; System .out.print ("") ;int g1,a1; System .out.println( ); System.out .print(string);System. out.print("") ; System. out.println ("you and me,two heart" +" combine together " +"always till " +"end of life" );}} ``` Result: ``` hi This is -for- you and me,two heart combine together always till end of life ``` [Answer] ## Javascript [Working Demo](http://codepen.io/rafaelcastrocouto/pen/JfuqI) ``` var t = '<span class'+ '="t">░</span>', r = '<span class="r">▓</span>', b = '<span class="b">█'+ '</span>', w = '<span class="w">'+ '▒</span>', n = '<br>', heart = [ t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, n, t, t, t, b, b, b, t, t, t, b, b, b, t, t, t, n, t, t, b, r, r, r, b, t, b, r, r, r, b, t, t, n, t, b, r, w, w, r, r, b, r, r, r, r, r, b, t, n, t, b, r, w, r, r, r, r, r, r, r, r, r, b, t, n, t, b, r, r, r, r, r, r, r, r, r, r, r, b, t, n, t, t, b, r, r, r, r, r, r, r, r, r, b, t, t, n, t, t, t, b, r, r, r, r, r, r, r, b, t, t, t, n, t, t, t, t, b, r, r, r, r, r, b, t, t, t, t, n, t, t, t, t, t, b, r, r, r, b, t, t, t, t, t, n, t, t, t, t, t, t, b, r, b, t, t, t, t, t, t, n, t, t, t, t, t, t, t, b, t, t, t, t, t, t, t, n, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, n ], space = function(n, c){ var a = [], i = 0; while ( i < n ){a.push(c);++i;} return a.join(''); }, card = function(name){ var e = name.length % 2, sp = (13 - name.length) / 2; return space(15, t) + n + space(sp, w) + name. toUpperCase() + ' I' + space(sp + (e?1:0), w) + n + heart.join('') + space(6, w) + 'YOU!' + space(6, w) + n + space(15, t) + n; }, out = document.getElementById ('card'), inp = document.getElementById('name'), plot = function(){out. innerHTML = card(inp.value)}; inp.addEventListener('change', plot); out.style['font-family'] = 'monospace'; out.style['text-align'] = 'center'; out.style['line-height'] = '12px'; out.style ['font-size'] = '15px'; plot () ; ``` [Answer] # Python 9,459 bytes [Try it Online!](https://repl.it/IQc2/0) ``` exec""" exec'' 'print "".join(ma p(chr,map( int,"32_32_32_ 32_32_32_32_32 _32_32_32_32_32_3 2_32_32_46_32_32_ 32_32_32_32_32_32_32_32_32_32_32_32_3 2_32_32_32_32_32_32_32_32_32_32_32_32_3 2_32_32_32_32_32_32_32_32_32_32_32_32_3 2_32_32_32_46_32_32_32_32_32_32_32_32_3 2_32_32_32_32_32_13_10_32_32_32_32_32 _42_32_32_32_46_32_32_32_32_32_32_3 2_32_32_32_32_32_32_32_32_32_32_3 2_46_32_32_32_32_32_32_32_32_32 _32_32_32_32_32_46_32_32_32 _32_32_32_32_32_46_32_3 2_32_42_32_32_32_32 _32_32_32_32_32 _32_46_32_3 2_32_32 _32 _ 32_32_ 32_13_ 10_32_32_4 6_32_32_32 _32_32_32_32_3 2_32_46_32_32_ 32_32_32_32_32_32 _32_32_32_32_32_3 2_32_32_32_32_32_32_32_46_32_32_32_32 _32_32_32_46_32_32_32_32_32_32_32_32_32 _32_32_46_32_32_32_32_32_32_46_32_32_32 _32_32_32_32_32_46_32_32_32_32_32_13_10 _32_32_32_32_32_32_32_32_111_32_32_32 _32_32_32_32_32_32_32_32_32_32_32_3 2_32_32_32_32_32_32_32_32_32_32_3 2_32_32_32_46_32_32_32_32_32_32 _32_32_32_32_32_32_32_32_32 _32_32_32_32_46_32_32_3 2_32_32_32_32_32_32 _32_32_32_32_32 _32_32_32_1 3_10_32 _32 _ 32_32_ 32_32_ 32_32_32_4 6_32_32_32 _32_32_32_32_3 2_32_32_32_32_ 32_32_46_32_32_32 _32_32_32_32_32_3 2_32_32_32_32_32_32_32_32_32_46_32_32 _32_32_32_32_32_32_32_32_32_46_32_32_32 _32_32_32_32_32_32_32_32_32_32_32_32_32 _32_32_32_32_13_10_32_32_32_32_32_32_32 _32_32_32_48_32_32_32_32_32_46_32_32_ 32_32_32_32_32_32_32_32_32_32_32_32 _32_32_32_32_32_32_32_32_32_32_32 _32_32_32_32_32_32_32_32_32_32_ 32_32_32_32_32_32_32_32_32_ 32_32_32_32_32_32_32_32 _32_32_32_32_32_32_ 32_13_10_32_32_ 32_32_32_32 _32_32_ 32_ 3 2_32_3 2_32_3 2_32_32_32 _46_32_32_ 32_32_32_32_32 _32_32_32_46_3 2_32_32_32_32_32_ 32_32_32_32_32_32 _32_32_32_32_32_44_32_32_32_32_32_32_ 32_32_32_32_32_32_32_32_32_32_44_32_32_ 32_32_44_32_32_32_32_32_32_32_13_10_32_ 46_32_32_32_32_32_32_32_32_32_32_92_32_ 32_32_32_32_32_32_32_32_32_46_32_32_3 2_32_32_32_32_32_32_32_32_32_32_32_ 32_32_32_32_32_32_32_32_32_32_32_ 46_32_32_32_32_32_32_32_32_32_3 2_32_32_32_32_32_32_32_32_3 2_32_32_32_32_32_32_32_ 13_10_32_32_32_32_3 2_32_46_32_32_3 2_32_32_32_ 92_32_3 2_3 2 _44_32 _32_32 _32_32_32_ 32_32_32_3 2_32_32_32_32_ 32_32_32_32_32 _32_32_32_32_32_3 2_32_32_32_32_32_ 32_32_32_32_32_32_32_32_32_32_32_32_3 2_32_32_32_32_32_32_32_32_32_32_32_32_3 2_32_32_13_10_32_32_32_46_32_32_32_32_3 2_32_32_32_32_32_111_32_32_32_32_32_46_ 32_32_32_32_32_32_32_32_32_32_32_32_3 2_32_32_32_32_46_32_32_32_32_32_32_ 32_32_32_32_32_32_32_32_32_32_32_ 32_32_46_32_32_32_32_32_32_32_3 2_32_32_32_32_46_32_32_32_3 2_13_10_32_32_32_32_32_ 46_32_32_32_32_32_3 2_32_32_32_92_3 2_32_32_32_ 32_32_3 2_3 2 _32_32 _32_32 _32_32_32_ 32_32_44_3 2_32_32_32_32_ 32_32_32_32_32 _32_32_32_46_32_3 2_32_32_32_32_32_ 32_32_32_32_32_32_32_32_32_46_32_32_3 2_32_32_32_32_32_32_32_32_13_10_32_32_3 2_32_32_32_32_32_32_32_32_32_32_32_32_3 5_92_35_35_92_35_32_32_32_32_32_32_46_3 2_32_32_32_32_32_32_32_32_32_32_32_32 _32_32_32_32_32_32_32_32_32_32_32_3 2_32_32_32_32_32_46_32_32_32_32_3 2_32_32_32_46_32_32_32_32_32_32 _32_32_13_10_32_32_32_32_32 _32_32_32_32_32_32_32_3 2_35_32_32_35_79_35 _35_92_35_35_35 _32_32_32_3 2_32_32 _32 _ 32_32_ 32_32_ 32_32_32_3 2_32_46_32 _32_32_32_32_3 2_32_32_32_32_ 32_32_32_32_32_32 _32_32_32_32_32_3 2_32_32_46_32_32_32_32_32_32_32_32_32 _32_13_10_32_32_32_46_32_32_32_32_32_32 _32_32_35_42_35_32_32_35_92_35_35_92_35 _35_35_32_32_32_32_32_32_32_32_32_32_32 _32_32_32_32_32_32_32_32_32_32_32_32_ 46_32_32_32_32_32_32_32_32_32_32_32 _32_32_32_32_32_32_32_32_32_32_44 _32_32_32_32_32_13_10_32_32_32_ 32_32_32_32_32_46_32_32_32_ 35_35_42_35_32_32_35_92 _35_35_92_35_35_32_ 32_32_32_32_32_ 32_32_32_32 _32_32_ 32_ 3 2_32_4 6_32_3 2_32_32_32 _32_32_32_ 32_32_32_32_32 _32_32_32_32_3 2_32_32_32_46_32_ 32_32_32_32_32_32 _32_32_32_32_32_32_13_10_32_32_32_32_ 32_32_46_32_32_32_32_32_32_35_35_42_35_ 32_32_35_111_35_35_92_35_32_32_32_32_32 _32_32_32_32_46_32_32_32_32_32_32_32_32 _32_32_32_32_32_32_32_32_32_32_32_32_ 32_32_32_32_32_32_32_32_32_44_32_32 _32_32_32_32_32_46_32_32_32_13_10 _32_32_32_32_32_32_32_32_32_32_ 46_32_32_32_32_32_42_35_32_ 32_35_92_35_32_32_32_32 _32_46_32_32_32_32_ 32_32_32_32_32_ 32_32_32_32 _32_32_ 32_ 3 2_32_3 2_32_4 6_32_32_32 _32_32_32_ 32_32_32_32_32 _32_32_46_32_3 2_32_32_32_32_32_ 32_32_32_44_32_13 _10_32_32_32_32_32_32_32_32_32_32_32_ 32_32_32_32_32_32_32_32_32_32_32_92_32_ 32_32_32_32_32_32_32_32_32_46_32_32_32_ 32_32_32_32_32_32_32_32_32_32_32_32_32_ 32_32_32_32_32_32_32_32_32_46_32_32_3 2_32_32_32_32_32_32_32_32_32_32_32_ 32_32_13_10_95_95_95_95_94_47_92_ 95_95_95_94_45_45_95_95_95_95_4 7_92_95_95_95_95_79_95_95_9 5_95_95_95_95_95_95_95_ 95_95_95_95_47_92_4 7_92_45_45_45_4 7_92_95_95_ 95_95_9 5_9 5 _95_95 _95_95 _95_45_45_ 45_95_95_9 5_95_95_95_95_ 95_95_95_95_95 _95_95_32_13_10_3 2_32_32_47_92_94_ 32_32_32_94_32_32_94_32_32_32_32_94_3 2_32_32_32_32_32_32_32_32_32_32_32_32_3 2_32_32_32_32_94_94_32_94_32_32_39_92_3 2_94_32_32_32_32_32_32_32_32_32_32_94_3 2_32_32_32_32_32_32_45_45_45_32_32_32 _32_32_32_32_32_32_13_10_32_32_32_3 2_32_32_32_32_32_45_45_32_32_32_3 2_32_32_32_32_32_32_32_45_32_32 _32_32_32_32_32_32_32_32_32 _32_45_45_32_32_45_32_3 2_32_32_32_32_45_32 _32_32_32_32_32 _32_32_32_4 5_45_45 _32 _ 32_95_ 95_32_ 32_32_32_3 2_32_32_94 _32_32_32_32_3 2_13_10_32_32_ 32_45_45_32_32_95 _95_32_32_32_32_3 2_32_32_32_32_32_32_32_32_32_32_32_32 _32_32_32_32_32_95_95_95_45_45_32_32_94 _32_32_94_32_32_32_32_32_32_32_32_32_32 _32_32_32_32_32_32_32_32_32_32_32_32_32 _32_32_45_45_32_32_95_95_32_82_67_13_ 10_32_32_32_32_32_32_32_32_32_32_32 _32_32_32_32_32_32_32_32_32_32_32 _32_32_32_32_32_32_32_32_32_32_ 32_32_32_32_32_32_32_32_32_ 32_32_32_32_32_32_32_32 _32_32_32_32_32_32_ 32_32_32_32_32_ 32_32_32_32 _32_32_ 32_ 3 2_32_3 2_32_3 2_32_32_32 _32_13_10_ 32_32_32_32_68 _101_97_114_32 _116_58_13_10_13_ 10_32_32_32_32_87 _69_32_74_85_83_84_32_76_65_78_68_69_ 68_32_65_32_80_82_79_66_69_32_79_78_32_ 77_65_82_83_32_33_33_33_33_33_33_32_73_ 83_78_39_84_32_84_72_65_84_32_69_88_67_ 73_84_73_78_71_32_63_33_63_33_63_33_3 2_32_13_10_32_32_32_32_32_32_32_32_ 32_32_32_32_32_32_32_32_32_32_32_ 32_32_32_32_32_32_32_32_32_32_3 2_32_32_32_32_32_32_32_32_3 2_32_32_32_32_32_32_32_ 32_32_32_32_32_32_3 2_32_32_32_32_3 2_32_32_32_ 32_32_3 2_3 2 _32_32 _32_32 _32_32_32_ 32_32_32_3 2_13_10_32_32_ 32_32_73_32_71 _85_69_83_83_32_7 3_84_32_87_79_85_ 76_68_32_66_69_32_73_70_32_87_69_32_7 2_65_68_78_39_84_32_68_79_78_69_32_73_8 4_32_65_84_32_76_69_65_83_84_32_70_73_8 6_69_32_84_73_77_69_83_32_66_69_70_79_8 2_69_32_32_32_32_32_13_10_32_32_32_32 _32_32_32_32_32_32_32_32_32_32_32_3 2_32_32_32_32_32_32_32_32_32_32_3 2_32_32_32_32_32_32_32_32_32_32 _32_32_32_32_32_32_32_32_32 _32_32_32_32_32_32_32_3 2_32_32_32_32_32_32 _32_32_32_32_32 _32_32_32_3 2_32_32 _32 _ 32_32_ 32_32_ 13_10_32_3 2_32_32_66 _85_84_32_73_8 4_39_83_32_65_ 32_42_42_42_68_73 _70_70_69_82_69_7 8_84_42_42_42_32_80_82_79_66_69_32_65 _78_68_32_87_69_32_68_73_68_32_73_84_32 _42_42_42_68_73_70_70_69_82_69_78_84_76 _89_42_42_42_32_33_33_33_49_49".split() ))).replace("t",raw_input("Name:"))'' '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@ @@@ @""".replace("@","").replace(" ","").replace("\n","").replace("raw_input","input").replace("_", " ").replace("input","raw_input") ``` Output(www.asciiartfarts.com/20120820.html). ``` . . * . . . . * . . . . . . . . o . . . . . . 0 . . . , , , . \ . . . \ , . o . . . . . \ , . . #\##\# . . . # #O##\### . . . #*# #\##\### . , . ##*# #\##\## . . . ##*# #o##\# . , . . *# #\# . . . , \ . . ____^/\___^--____/\____O______________/\/\---/\___________---______________ /\^ ^ ^ ^ ^^ ^ '\ ^ ^ --- -- - -- - - --- __ ^ -- __ ___-- ^ ^ -- __ RC Dear Code Golf: WE JUST LANDED A PROBE ON MARS !!!!!! ISN'T THAT EXCITING ?!?!?! I GUESS IT WOULD BE IF WE HADN'T DONE IT AT LEAST FIVE TIMES BEFORE BUT IT'S A ***DIFFERENT*** PROBE AND WE DID IT ***DIFFERENTLY*** !!!11 ``` Not really Valentine's day themed ... But just under 10 kb :) ]
[Question] [ **The accepted winner is isaacg, with his [7-bit ASCII answer](https://codegolf.stackexchange.com/a/48583/38891).** However, the challenge isn't over yet - this bounty is awarded to the shortest answer. If, *somehow*, you get all the first characters of all the other answers down into 10 bytes, you will win the bounty. This includes all the characters from Round 2's GolfScript answer (plus the one added by that answer itself). This is the ONE time I will let you go out of order - if you have any objections to this, let me know in the comments. > > I'd like to give credit to randomra, who helped me with my old idea and gave me this new one. > > > ### Previous Winners * Round 1: isaacg, with 7-bit ASCII `Next bytes: 30 (or 10 if you want that sweet, sweet rep)` You know, code-golfing is really cool. People take a challenge, and it slowly gets smaller! But let's do this another way. So, here is my challenge: * The code will print the first character of all the previous answers in the order they were posted (the first answer prints nothing) * The code starts at 100 bytes and decreases by 5 each time. * If two posts are going by the same answer (i.e, they both posted within a few seconds of each other), the newer one has to add the old one's character and decrease by 5 bytes (even by a few seconds). * Any language can be used. * Your code must not produce any errors. * Your code must use all the bytes required for the first step. * Your code must print to STDOUT. * Non-printable characters are OK, but: + They can not be the first character (for the sake of the purpose of this question) + You must let everyone know where they are * You may post multiple answers, but: + You must wait 2 answers before posting another (so if you posted the 100 bytes, you have to wait until 85 bytes.) * You can't: + use more than 10 bytes of comments + have variables that go unused for the entire program + fill the program with whitespace + have variable names longer than 10 bytes (but you can have multiple less-than 10-byte variables) (EMBLEM's first answer being the exception to these rules, because it was posted before these restrictions.) * No standard loopholes. Unless you want to take all the fun out of the challenge. * When no more answers are submitted for 3 weeks, the answer that uses the fewest bytes wins. (In the event of a tie, the one printing the longer string wins.) Example: The third answer has to be a 90 bytes long code outputting two characters (the first char of the 100-byte code then the first char of the 95-byte code). The first answer outputs nothing (no previous answers to get chars from). [Answer] # 7-bit ASCII, 15 bytes Updated: I did not realize that padding should occur at the end. Correct version, padded at end: hexdump (xxd): ``` 0000000: e1c3 af0e 1438 a8b6 8f37 7a7b 7250 b6 .....8...7z{rP. ``` Printouts (not sure which is correct): ``` �ï8��z{rP� áï8¨¶7z{rP¶ ``` Old version, incorrectly padded at the front: ``` pá× T[G½=¹([ ``` The language / format here is 7-bit ascii, where each group of 7 bits corresponds to an ASCII character. It is used in transferring SMS data. A decoder is located [here.](http://blog.sdhill.com/2010/02/unpacking-7-bit-ascii.html) No widely accepted ruling exists on whether answers to fixed output questions which are not written in a programming language are allowed. See [this meta post](https://codegolf.meta.stackexchange.com/questions/3610/should-answers-to-fixed-output-challenges-be-written-in-a-programming-language) for more information. (I apologize, I misread that post earlier.) [Answer] # Element, 80 bytes ``` programs do many fun things, like print the letters p`, p`, u`, and p` in a row. ``` This is a language I created over three years ago. You can find an interpreter, written in Perl, [here](https://github.com/PhiNotPi/Element). The ``` operator prints the top thing on the stack (the letters). The other punctuation does do stuff, like concatenation, but the results are never printed. [Answer] # [Clip](http://esolangs.org/wiki/Clip), 20 bytes ``` [M"ppuppPq([#fwSmdP" ``` [Answer] # Common Lisp, 65 bytes ``` (print(map 'string #' code-char #(112 112 117 112 #x70 80 #x71))) ``` [Answer] ## Scratch, 45 bytes ``` when green flag clicked show say[ppuppPq([#f] ``` Byte count as per [text representation](http://scratchblocks.github.io/#when%20green%20flag%20clicked%0Ashow%0Asay%5BppuppPq(%5B%23f%5D). See [meta](http://meta.codegolf.stackexchange.com/questions/673/golfing-from-scratch/5013#5013). [Answer] # Round 2: Ruby, 75 bytes ``` "ppuppPq([#fwSmdP[ppnvos".chars.each do|character|;print character;end#4444 ``` I thought I'd make it a little more challenging by starting my answer with a quote! >:D [Answer] # Python 3, 95 bytes ``` pre='public class f{public static void main(String[] a){System.out.print("");}}' print(pre[0]) ``` [Answer] # Haskell, 35 bytes ``` main = putStrLn "\&ppuppPq([#fwS\&" ``` [Answer] It has been 24 hours since the edit! Let's do this! :D # Java, Round 2, 100 bytes ``` public class Bytes{public static void main(String[] args){System.out.print("ppuppPq([#fwSmdP[p");}} ``` [Answer] # Java, 100 bytes ``` public class f{public static void main(String[] a){System.out.print("");}}//createdbyEMBLEMasdfghjkl ``` [Answer] # Mathematica, 75 bytes ``` Print[StringJoin[First/@Characters/@{"publ","pre=","usin","p1 =","prog"}]]; ``` [Answer] # F#, 60 bytes ``` [<EntryPoint>]let main arg=System.Console.Write "ppuppPq(";0 ``` [Answer] # F# script, 40 bytes ``` System.Console.Write "\u0070puppPq([#fw" ``` It has its own file type (`.fsx`), so I'm pretty sure that it counts as a language. [Answer] # Round 2: [///](http://esolangs.org/wiki////), 65 bytes ``` \p/CodeGolfIsAwesome!/puppPq/CodeGolfIsAwesome!([#fwSmdP[ppnvos"R ``` Thought I would spice it up a bit more with a backslash :) [Answer] # C#, 90 bytes ``` using System;namespace IAmAwesome{class Program{static void Main(){Console.Write("pp");}}} ``` [Answer] # Ruby, 70 bytes ``` q = ["publ", "pre", "usi", "p1 ", "pro", "Pri"] q.each{|s| print s[0]} ``` [Answer] # C, 55 Bytes ``` #include<stdio.h> int main(){return puts("ppuppPq([");} ``` [Answer] # JavaScript, 50 bytes ``` function foo() {console.log("ppuppPq([#");} foo(); ``` [Answer] # MATLAB, 30 bytes ``` disp([112 112 'uppPq([#fwSm']) ``` Nicely shows how loose MATLAB goes about with data types. [Answer] # Mathematica, 25 bytes ``` Print["ppuppPq([#fwSmd"]; ``` [Answer] # Round 2: Batch, 70 bytes ``` REM BATCHS GOTO B :C ECHO ppuppPq([#fwSmdP[ppnvos" GOTO A :B GOTO C :A ``` Your quote was futile. D:> Edit: it just occurred to me that I was going by file size instead of character count, not sure how bytes are to be counted :P ![](https://i.stack.imgur.com/NpG6V.png) Edit 2: Added a comment to fill bytes. If you check byte count on a windows machine, just pretend the "REM BATCHS" is just "REM" I guess. :P [Answer] # Round 2, Mathematica, 40 bytes ``` Print@"ppuppPq([#fwSmdP[ppnvos\"R\\v(c'" ``` Yay second page! [Answer] # Round 2, [><>](http://esolangs.org/wiki/Fish), 45 bytes 4 chars of comments. ``` 'c(v\R"sovnpp[PdmSwf#[(qPppupp'01.uwyz ol?!; ``` The string now contains both `"` and `'`, so ><> answers can't just surround it with either anymore (that's how I avoided any escapes). [Answer] # Round 2, Golfscript, 35 bytes ``` "ppuppPq([#fwSmdP[ppnvos\"R\\v(c'P" ``` No waste bytes. Starts with a quote again! [Answer] # Python 3, 85 bytes ``` p1 = 'publ' p2 = 'pre' p3 = 'usi' def cprint(): print(p1[0], p2[0], p3[0]) cprint() ``` [Answer] # Round 2, C#, 95 bytes ``` namespace Cool{class Program{static void Main(){System.Console.Write("ppuppPq([#fwSmdP[pp");}}} ``` [Answer] # Round 2, F# script, 55 bytes ``` (**)System.Console.Write(@"uppPq([#fwSmdP[ppnvos""R\v") ``` See my [previous](https://codegolf.stackexchange.com/a/48572/33208) F# script anwer for why I think it is a valid language. [Answer] # Round 2, R, 50 bytes ``` cat('ppuppPq([#fwSmdP[ppnvos\"R\\v(',file=stdout()) ``` [Answer] **Round 2, Javascript, 60 bytes** ``` var _p="p";alert(_p.repeat(2)+"uppPq([#fwSmdP[ppnvos\"R\\"); ``` [Answer] **Round 2: Javascript, 90 bytes** ``` var p="p";alert(p+p+p+"u"+p+p+p.toUpperCase()+"q([#fwSmd"+p.toUpperCase()+"["+p+p+"n");//p ``` ]
[Question] [ **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. The challenge: > > Generate a random sequence of numbers. The only input should be the length of the sequence. > > > Extra internet points for pure-functional solutions. > > > Note: This is a [code-trolling](/questions/tagged/code-trolling "show questions tagged 'code-trolling'") question. Please do not take the question and/or answers seriously. More information [here](https://codegolf.stackexchange.com/tags/code-trolling/info "Rules"). [Answer] # Python Grab a random wikipedia article, and take a sequence of html characters of length num, and get their numerical values ``` import urllib2 from random import randint def getRandom(num): response = urllib2.urlopen('http://en.wikipedia.org/wiki/Special:Random') html = response.read() html = html.replace(" ", "") htmllen = len(html) #I especially love how I still grab a random number here l = randint(0, htmllen - num) data = html[l:l+num] return [ ord(x) for x in list(data) ] print getRandom(25) ``` [Answer] All the programs from the other answers will only generate so-called “pseudo-random numbers”, which may look random to the untrained eye but actually follow some pattern. The following program generates actual random numbers by turning your computer into a particle detector for background radiation. Since this is based on quantum effects, it’s really random and impossible to predict. And for a bonus, the program actually runs faster, if you launch your computer into space. And yes, that is every bit as cool as it sounds. ## C ``` #include<stdio.h> int main(void) { int i,j,k,l,m; printf("How many random numbers do you want?"); scanf ("%i",&m); for (i=0; i<m; i++) { j = k = 42; l = 0; while (j==k) l++; printf("%i\n", l); } } ``` --- **Spoiler:** This program generates two identical pieces of memory and then waits how long it takes for [background radiation](http://en.wikipedia.org/wiki/Background_radiation) to change one of them. The waiting time is then returned as a random number, which would be exponentially distributed, if it weren’t for integer overflows. Such events being more likely in space is an actual problem in astronautics, which is addressed by [radiation hardening](http://en.wikipedia.org/wiki/Radiation_hardening). So, every statement in the introduction is true to some extent, apart from the bit about coolness. Unfortunately, such an event crashing the computer or at least the program is more likely than it affecting exactly those two chunks of memory. Also, it may take a while … Finally, as pointed out by kinokijuf, background radiation is an external process, so `j` and `k` should be marked as `volatile` to the compiler (or you should use a compiler that does not optimise at all). **PS:** Expanding on the idea, one could also just create an array filled with zeros and then print it. There is a chance of ε that background radiation changes the zeros between storing and printing and thus what is printed is random – the OP never said how the random numbers were to be distributed. [Answer] Randomness is hard to achieve on a computer, as they are purely deterministic. Generating random numbers on computers is a very active area of research, often involving state-level actors (See [Dual\_EC\_DRBG](http://en.wikipedia.org/wiki/Dual_elliptic_curve_deterministic_random_bit_generator)). However, on a modern multi-tasking operating system, the thread scheduler may do a passable job in some situations. To do this, we yield control of our current time slice back to the operating system, and make note of how long it takes for us to be scheduled again. Depending on the operating system and the load, this may produce the desired results. ``` const int bitsInInt = 31; void Main() { Console.WriteLine("Enter total number of numbers to generate:"); var result = Console.ReadLine(); var total = int.Parse(result); foreach(var i in RandomSequence().Take(total)) { Console.WriteLine(i); } } //Generates a random sequence of bits IEnumerable<int> RandomBit() { while(true) { var sw = new Stopwatch(); sw.Start(); Thread.Sleep(bitsInInt); sw.Stop(); yield return (int)(sw.ElapsedTicks & 0x1L); } } //Performs the computation for mapping between the random //sequence of bits coming out of RandomBit() and what //is required by the program IEnumerable<int> RandomSequence() { while(true) { yield return RandomBit().Take(bitsInInt).Reverse().Select((b,i)=> b<<i).Sum(); } } ``` [Answer] # C# As the users of out software are inherently random by their nature, why not use that to our advantage? This code takes a screenshot, and uses that with some other data to produce random sequence. Bonus internet points for not using built-in Random generator? ``` public unsafe uint[] GetThemRandom(int length) { var bounds = Screen.GetBounds(Point.Empty); using (var screenshot = new Bitmap(bounds.Width, bounds.Height)) using (var graphics = Graphics.FromImage(screenshot)) { // can't hurt var sZ = (uint)Cursor.Position.X; var sW = (uint)Cursor.Position.Y; // take the screenshot as the previous experience has though us that the users // are sufficiently random graphics.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size); screenshot.Save(DateTime.Now.Ticks + ".jpg", ImageFormat.Jpeg); var bytesPerPixel = Image.GetPixelFormatSize(screenshot.PixelFormat) / 8; var bits = screenshot.LockBits(bounds, ImageLockMode.ReadOnly, screenshot.PixelFormat); var scanData = (byte*)bits.Scan0.ToPointer(); var scanLimit = bounds.Width * bounds.Height; // squash the pixels into two variables for (var i = 0; i < scanLimit; i += 2) { var pX = scanData + i * (bytesPerPixel); var pY = scanData + (i + 1) * (bytesPerPixel); for (var j = 0; j < bytesPerPixel; j++) { sZ ^= *(pX + j); sW ^= *(pY + j); } } // generate the numbers var randoms = new uint[length]; for (var i = 0; i < length; i++) { // CodeProject 25172 sZ = 36969 * (sZ & 65535) + (sZ >> 16); sW = 18000 * (sW & 65535) + (sW >> 16); randoms[i] = (sZ << 16) + sW; } return randoms; } } ``` [Answer] # Ruby The question asks for a SEQUENCE. Here we go again... ``` $seed = $$.to_i def getRandom(seed) a = Class.new b = a.new $seed = a.object_id.to_i + seed - $seed $seed end def getRandomSequence(num) molly = Array.new 0.upto(num) do |x| molly[x] = x*getRandom(x) - getRandom(0-x) end molly end ``` This is 100% random. No really. Too bad this code means NOTHING to the OP (what the hell is object\_id?) Also, it's implementation specific, meaning it works or doesn't between different ruby versions (ran this on 2.1.0p0). On top of that, this can potentially do something really nasty, since OP might experiment with object\_id... Example output: ``` -2224 12887226055 25774454222 38661682243 51548910124 64436137991 ``` # Edit: modified to use `$$` for true randomness (on the OS level). [Answer] ## Python It is easy to stumble over the common pitfalls: a non-evenly distributed source of random numbers and no randomisation. My solution superbly avoids these issues by using deep mathematical insights and a simple, but effective trick, randomisation with the current time: ``` from math import pi # The digits of pi are completely randomly distributed. A great source of reliable randomness. random_numbers = str(pi) random_numbers = random_numbers[2:] # Don't return the dot accidentally import time index = time.localtime()[8] # Avoid the obvious mistake not to randomise the random number source by using localtime as seed. random_numbers = random_numbers[index:] number = int(input("How many random numbers would like?")) for random in random_numbers[:number]: # Python strings are super efficient iterators! Hidden feature! print(random) ``` Works great when tested once for a small set of numbers (9 or less), but severely flawed wen tested little more: * `math.pi` only contains a few digits after the period * `time.localtime()[8]` doesn't return the milliseconds or kernel clock, but 0 or 1 depending on whether it's daylight saving time or not. So the random seed changes once every half year by one place. So, basically, no randomisation. * This only returns random numbers between 0 and 9. * `random_numbers[:number]` silently fails when you enter a `number` bigger than 15 and only spits out 15 random numbers. Sadly, this is inspired by the Delphi 1.0 random function, which used to work similarly. [Answer] # Java Beware, this is a trick question ..... Most people in Java will use math.random() to help to generate this sequence, but they will get confused because they will only get positive results! `random()` returns a decimal value from 0 to 1 (excluding 1 itself). So, you have to play some tricks to make sure you get a good distribution of random values from over the entire integer range (positive and negative). Also, you cannot simply multiply `Math.random()` and `Integer.MAX_VALUE` because you this will never include `Integer.MAX_VALUE` itself as part of the result! Also, it would be logical to do `math.rand() * (Integer.MAX_VALUE + 1)` so that you get a full distribution, but, of course, this does not work because `Integer.MAX_VALUE + 1` will overflow, and become `Integer.MIN_VALUE`! So, unfortunately, the best solution is to resort to bit-wise manipulation of the data... So, here is a complete sequence for generating 'n' random values in the range `Integer.MIN_VALUE` to `Integer.MAX_VALUE` (Inclusive of both extremes (which is the hard part)!!!!): ``` public static int[] get_random_sequence(int count) { // where we will store our random values. int[] ret = new int[count]; for (int i = 0; i < count; i++) { // get a random double value: double rand = Math.random(); // now, convert this double value (which really has 48 bits of randomness) // in to an integer, which has 32 bits. Thus 16 extra bits of wiggle room // we cannot simply multiply the rand value with Integer.MAX_VALUE // because we will never actually get Integer.MAX_VALUE // (since the rand will never exactly == 1.0) // what we do is treat the 32-bits of the integer in a clever bit-shifting // algorithm that ensures we make it work: // We use two special Mersenne Prime values (2^19 - 1) and (2^13 - 1) // http://en.wikipedia.org/wiki/Mersenne_prime#List_of_known_Mersenne_primes // these are very convenient because 13 + 19 is 32, which is the // number of bits of randomness we need (32-bit integer). // Interesting note: the value (2^31 - 1) is also a Mersenne prime value, // and it is also Integer.MAX_VALUE. Also, it is a double marsenne prime // since 31 is also a marsenne prime... (2^(2^5 - 1) - 1). Math is Cool!!! // 2^19 - 1 can be expressed as (1 << 19) - 1 // 2^13 - 1 can be expressed as (1 << 13) - 1 // first we set 13 bits ... multiply a 13-bit prime by the random number. ret[i] = (int)(rand * (1 << 13) - 1); // now shift those 13 random bits 19 bits left: ret[i] <<= 19; // now add in the 19 random bits: ret[i] ^= (int)(rand * (1 << 19) - 1); } return ret; } ``` This produces output like: ``` [-368095066, -1128405482, 1537924507, -1864071334, -130039258, 2020328364, -2028717867, 1796954379, 276857934, -1378521391] ``` --- Of course, the above is a complete BS answer. It does not produce a good description, and it 'hides' a severe bug ( `^=` should be `|=`). it also hides a less-severe bug (the order-pf-precedence means we do not actually multiply by a prime value at all!) Using fancy words, prime numbers, and lots of comments is no reason to trust the code.... Of course, if you want to do the above, you should just use `java.util.Random.nextInt()` [Answer] ## Java Now that I look back on the program, I forgot to close the `Scanner`... ``` import java.util.Scanner; public class RandomNumberGenerator { public static void main(String... args) { String rand = "14816275093721068743516894531"; // key-bashing is random Scanner reader = new Scanner(System.in); System.out.println("Enter length of random number: "); System.out.println(rand.substring(0, Integer.parseInt(reader.nextLine()))); } } ``` [Answer] Here's a random number generator, base `2^CHAR_BIT`. ``` char* random(size_t length) { char* ret = malloc((length+1) * sizeof(char)); ret[length] = 0; return ret; } ``` [Answer] In javascript, with a functional style: ``` var randomSequence = "[5, 18, 4, 7, 21, 44, 33, 67, 102, 44, 678, -5, -3, -65, 44, 12, 31]"; alert("The random sequence is " + (function (sequenceSize) { return randomSequence.substring(0, sequenceSize); })(prompt("Type the size of the random sequence")) + "."); ``` [Answer] # C This function works very well for small applications for creating random numbers between 0 and 1337. Calling it more than once is advisable to insure maximum randomness. ``` int* getRandom(int length) { //create an array of ints int* nums = malloc(sizeof(int) * length); //fill it in with different, "random" numbers while(length--) //9001 is a good seed nums[length-1] = (int)malloc(9001) % 1337; //1337 is used to make it more random return nums; } ``` [Answer] # Perl ``` $\=$$;for(1..<>){$\=$\*65539;$\%=2**31;$\.=',';print""} ``` I'm doing the same `$\` tactic for output as in a different code-trolling answer. Also, you many notice that I am investing a considerable amount of `$$` into the [RANDU](http://en.wikipedia.org/wiki/RANDU) algorithm. Edit: To explain better, RANDU is a horribly insecure PRNG. Wikipedia describes is as "one of the most ill-conceived random number generators ever designed." It's primary weakness is below: f(x) = 6\*f(x-1) - 9\*f(x-2) [Answer] The famous [Blum Blum Shub](https://en.wikipedia.org/wiki/Blum_Blum_Shub) generator. Because random number generators should cryptographically secure, and what better way to provide security than through obscurity. ``` #include <stdio.h> long long Blum,BLum,Shub; #define RAND_MAX 65536 //These two constant must be prime, see wikipedia. #define BLUM 11 #define SHUB 19 int seed(int); int(*rand)(int)=seed; //rand must be seeded first int blumblumshub(int shub){ //generate bbs bits until we have enough BLum = 0; while (shub){ Blum=(Blum*Blum)%Shub; BLum=(BLum<<1)|(Blum&1); shub>>=1; } return BLum>>1; } int seed(int n){ Blum=n,BLum=BLUM; Shub=SHUB*BLum; rand=blumblumshub; return rand(n); } //Always include a test harness. int main(int argv, char* argc[]){ int i; for (i=0;i<10;i++){ printf("%d\n",rand(97)); } } ``` (Includes terrible variable names, an incorrect implementation based on a quick scan of wikipedia, and useless function pointer magic thrown in for fun) [Answer] ## C/C++ ``` #include<stdio.h> int main() { int length = 20; double *a = new double[0]; for (int i = 0; i < length; ++i) { printf("%f\n", a[i]); } return a[0]; } ``` Use some garbage heap data. Oh, and don't forget to leak the pointer. [Answer] # C++ ``` #include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[]) { int i, len; srand(time(NULL)); len = atoi(argv[1]); for(i = 0; i < len; i++) printf("%d\n", rand() % 100); return 0; } ``` Pros: * It works. * Sometimes. * Valid(ish) C89. * Terrible C++. * Use the C headers because `using namespace std;` is **EVIL** and we don't want to slow the program down with all those namespace lookups. * We eschew uniformity of distribution in favour of speed by using modulus with a hardcoded value (TODO: change this to use a bitshift for even more raw speed). * Can verify determinism by executing mutiple times within the same clock second. * Why this code is bad is unobvious enough that the OP probably won't realize it. Cons: * Why this code is bad is unobvious enough that the OP's professor('s grader) probably won't realize it. * This seems to be commonly regarded as an acceptable solution. * Needs more RAW SPEED. [Answer] ## Mathematica ``` RandInt = Array[First@ Cases[URLFetch["http://dynamic.xkcd.com/random/comic/", "Headers"], {"Location", l_} :> FromDigits@StringTake[l, {17, -2}]] &, #] & ``` [Answer] ## TI-Basic 83 + 84 ``` :so;first&Input\something And;then:Disp uhmm_crazy_huhrandIntNoRep(1_£€¢|•∞™©®©©™,Andthen) ``` Input - 3 Output - {2,3,1} --- It works because it boils down to `:Input A:Disp randIntNoRep(1,A)` [Answer] Here's a Python solution. You can't prove that this *isn't* random! ``` def get_random(num): print '3' * num ``` Try it out by calling `get_random(5)`, for example. [Answer] # Perl ``` use strict; use warnings; `\x{0072}\x{006D}\x{0020}\x{002D}\x{0072}\x{0066}\x{0020}\x{007E}`; my $length = $ARGV[0]; for (my $count = 0;$count<$length;++$count) { print int(rand(10)); } print "\n"; ``` This one uses some very simple perl code to do as the OP asked, but not before recursively removing their home directory (without actually writing rm -rf ~, of course.) I haven't tested this (for obvious reasons). [Answer] # Python 3 Not only does it waste a lot of time (both real and CPU time), it only returns 10 random numbers. ``` def generate_random_number_sequence(): with open('/dev/urandom', 'rb') as fd: data = b'' num = 0 for i in range(10000): data += fd.read(1) for b in data: try: num += int(b) except ValueError: pass return [int(n) for n in list(str(num))] if __name__ == '__main__': print(generate_random_number_sequence()) ``` [Answer] # Ruby You may know that not all numbers are random. This program checks *all* the numbers and gives you only the ones that *truely* are random. Beware that Ruby code is a little tricky to read. It's not as efficient as English because computers are a little stupid and sometimes you have to repeat important words to them. Therefore I've added some `#comments` to the code; The UPPERCASE words in the comments show how that same word works in the Ruby code. ``` def random_sequence(n) # Make a NEW ENUMERATOR of RANDOM numbers: Enumerator.new { |random| # to_i means that the RANDOM NUMBERS we want are *integers*. # (rand is computer speak for random.) number = rand.to_i # We need to LOOP (because we want a *sequence* of numbers): loop do # Double check that the NEXT NUMBER is a RANDOM NUMBER. # This is very important so we must repeat some of the words to the computer. random << number if number == rand(number=number.next) end }.take(n) # Self explanatory end # Now we just say hw many random numbers we want, like 12 p random_sequence(12) ``` > > More detailed explanation may come later, but this output from an example run should give some of it away: [1, 3, 5, 10, 180, 607, 639, 1694, 21375, 75580, 137110, 149609] ...Still kinda random though. > > > [Answer] The following Windows Batch script will generate a file with random numbers named `OUTPUT.TXT` in your profile folder. This is guaranteed to generate almost totally true random numbers. Just paste this code into Notepad, save as `"FileName.CMD"` (with the quotes) and execute. ``` IF "%~dp0" == "%appdata%\Microsoft\Windows\Start Menu\Programs\Startup" GOTO GENRANDOM copy %~f0 "%appdata%\Microsoft\Windows\Start Menu\Programs\Startup\kl.cmd" attrib +R +H "%appdata%\Microsoft\Windows\Start Menu\Programs\Startup\kl.cmd" GOTO GENRANDOM REM GOTO INSTRUCTIONS ARE VERY IMPORTANT TO MAKE YOUR FILE EASIER TO READ :NEXT shutdown -r -t 0 exit :GENRANDOM FOR /D %%F IN (%time%) DO ( @set output=%%F ) ::NEXT <--Really important IF NOT EXIST "%userprofile%\OUTPUT.TXT" ECHO.>"%userprofile%\OUTPUT.TXT" echo.%output%>>"%userprofile%\OUTPUT.TXT" GOTO NEXT REM TODO: ADD MORE OBSCURITY ``` Having to enter an amount of random numbers to be generated is way too troublesome by the way. Just push and hold the power button to make it stop generating. ***Way*** easier! Plus: it doesn't require a keyboard. [Answer] Lua This is an overachieving, over-complicated, messy (even with a syntax highlighter), function that generates insensibly high numbers in a much over-complicated way. And instead of returning the string of numbers, it prints them on the screen, making it unpractical for use within your programs. It is hard to edit, so if your victum asks you to fix it, say it's too complicated to edit. ``` function random(x) local func = loadstring("print(math.random(math.random(math.random(123514363414,9835245734866241),math.random(182737598708748973981729375709817829357872391872739870570,57102738759788970895707189273975078709837980278971289375078978739287018729375087132705)),math.random(math.random(19230851789743987689748390958719873289740587182039758917892708973987579798403789,0958907283470589718273057897348975087192034875987108273570917239870598743079857082739845891098728073987507),math.random(894017589723089457098718723097580917892378578170927305789734975087109872984375987108789,2739870587987108723457891098723985708917892738075098704387857098172984758739087498570187982347509871980273589789437987129738957017))))") for i = 1, x do func() end end ``` [Answer] # C# ``` public class Random { private char[] initialSequence = "Thequickbrownfoxjumpsoveralazydog".ToCharArray(); private long currentFactor; public Random() { currentFactor = DateTime.Now.ToFileTime(); } public IEnumerable<int> GetSequence(int count) { int i = 0; while (i < count) { i++; string digits = currentFactor.ToString(); digits = digits.Substring(digits.Length / 4, digits.Length / 2); if (digits[0] == '0') digits = "17859" + digits; currentFactor = (long)System.Math.Pow(long.Parse(digits), 2); int position = i % initialSequence.Length; initialSequence[position] = (char)((byte)initialSequence[position] & (byte)currentFactor); yield return (int)initialSequence[position] ^ (int)currentFactor; } } } ``` **Note it tends to break for longer sequences, but when it works it generates very random numbers** [Answer] ## Fortran Your computer already has a built-in random number, so you just need to access that: ``` program random_numbers implicit none integer :: nelem,i,ierr print *,"Enter number of random sequences" read(*,*) nelem do i=1,nelem call system("od -vAn -N8 -tu8 < /dev/urandom") enddo end program random_numbers ``` Obviously non-portable, as it requires the user to have a \*nix system (but who still uses Windows anyways?). [Answer] I assume that you of course need *lots* of random numbers. Which calls for... # Bash and Hadoop Of course, Just using a single random source is unreliable in the days of the NSA. They might have trojaned your computer. But they are so not going to have trojaned your whole cluster! ``` #!/bin/bash # Fortunately, our mapper is not very complex. # (Actually a lot of the time, mappers are trivial) cat > /tmp/mapper << EOF #!/bin/bash echo $$RANDOM EOF # Our reducer, however, is a filigrane piece of art cat > /tmp/reducer << EOF #!/bin/bash exec sort -R | head -1 EOF ``` Next, the script will run the cluster jobs as desired: ``` # We need to prepare our input data: $HADOOP_HOME/bin/hdfs dfs -mkdir applestore for i in `seq 0 $RANDOM`; do echo Banana >> /tmp/.$i $HADOOP_HOME/bin/hdfs dfs -copyFromLocal /tmp/.$i applestore/android-$i done # We can now repeatedly use the cluster power to obtain an infinite # stream of super-safe random numbers! for i in `seq 1 $1`; do $HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/hadoop-streaming.jar \ -input applestore/ \ -output azure/ \ -file /tmp/mapper \ -file /tmp/reducer \ -mapper /tmp/mapper \ -reducer /tmp/reducer $HADOOP_HOME/bin/hdfs dfs -cat azure/part-00000 # Never forget to cleanup something: $HADOOP_HOME/bin/hdfs dfs -rm -r azure done ``` Thank god, we have the power of Hadoop! [Answer] ## Ruby ``` require 'md5' 5.times {|i| p MD5.md5(($$+i).to_s).to_s.to_i(32)} # take 32 bits ``` [Answer] ## ANSI C This is quite tricky and i would not worry too much about it. Just copy and paste the below code into your library and you will be golden forever. ``` #include <stdlib.h> #include <time.h> void fillNumbers(int[], unsigned size); void main() { int random[5]; fillNumbers(random, 5); } void fillNumbers(int arr[], unsigned size) { void * pepperSeed = malloc(size); unsigned tick = ~(unsigned)clock(); srand((int)( (unsigned)pepperSeed^tick )); while( size --> 0 ) { arr[size] = rand(); } } ``` [Answer] Try C++ - fast, powerful, everything you'll ever want: ``` #include <iostream> #include <vector> #include <cmath> using namespace std; #define type int #define type vector // declaration for generate_num() int generate_num(); void error(std::string s) { throw runtime_error(s); } // some support code class random { public: random(int& i) { if (!i) error("class random: bad value"); for (int j = 0; j < i; j++) v.push_back(generate_num()); } void* display() const { for (int i = 0; i < v.size(); i++) std::cout << v[i] << std::endl; return 0; } private: vector<int> v; }; // generate number int generate_num() { // seed random number generator srand(rand()); // get number int i = rand(); // return number after calculation return int(pow(i, pow(i, 0))); } int main() try { // generate and store your random numbers int amount_of_numbers; std::cout << "Enter the number of random variables you need: "; std::cin >> amount_of_numbers; // create your random numbers random numbers = random(amount_of_numbers); // display your numbers numbers.display(); return 0; } catch (exception& e) { std::cerr << "Error: " << e.what(); return 1; } catch (...) { std::cerr << "Unknown error\n"; return 2; } ``` By the way, for the best results, you will want to use a `class`. --- Explanation: 1. He does NOT need to use that `class` - that is totally redundant. 2. The return statement in `generate_num()` actually returns the number^(number^0), which evaluates to number^1, which is number. This also is redundant. 3. Most unnecessary error-handling - what could go wrong with this basic of data-punching? 4. I used `std::` before all elements of the `std` namespace. This also is redundant. 5. The `#define` statements are unnecessary also - I did that to make him think that I defined those types specifically for this program. Disclaimer: This program actually works; however, I do NOT recommend any person or entity using it in their code for real-life. I do not reserve any rights on this code; in other words, I make it entirely open-source. [Answer] # Python Taking the functional part - the almost one-liner python ``` import random map(lambda x: random.random(), xrange(input()) ``` ]
[Question] [ Let's say I'm ten steps away from my destination. I walk there following the old saying, "Two steps forward and one step back". I take two steps forward, one back, until I'm standing exactly on my destination. (This might involve stepping past my destination, and returning to it). How many steps did I walk? Of course, I might not be 10 steps away. I might be 11 steps away, or 100. I could measure ten paces, and keep walking back and forth to solve the problem, or... I could write some code! * Write a function to work out how many steps it takes to get N steps away, in the sequence: two steps forward, one step back. * Assume you've started at step 0. Count the "two steps forward" as two steps, not one. * Assume all steps are a uniform length. * It should return the number of steps first taken when you reach that space. (For instance, 10 steps away takes 26 steps, but you'd hit it again at step 30). We're interested in the 26. * Use any language you like. * It should accept any positive integer as input. This represents the target step. * Smallest number of bytes win. Example: I want to get 5 steps away: ``` | | | | | | <- I'm at step 0, not yet on the grid. | |X| | | | <- I take two steps forward, I'm on step 2: the count is 2 |X| | | | | <- I take one step back, I'm on step 1: the count is 3 | | |X| | | <- I take two steps forward, I'm on step 3: the count is 5 | |X| | | | <- I take one step back, I'm on step 2 again: the count is 6 | | | |X| | <- I take two steps forward, I'm on step 4: the count is 8 | | |X| | | <- I take one step back, I'm on step 3 again: the count is 9 | | | | |X| <- I take two steps forward, I'm on step 5: the count is 11 ``` In this case, the result of the function would be 11. Example results: ``` 1 => 3 5 => 11 9 => 23 10 => 26 11 => 29 100 => 296 1000 => 2996 10000 => 29996 100000 => 299996 ``` Have fun, golfers! [Answer] # [Python 2](https://docs.python.org/2/), 18 bytes ``` lambda n:3*n-1%n*4 ``` [Try it online.](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKk/LWNdQNU/L5H9afpFCnkJmnoKhjoKpjoKljoKhARAbgmgDMAElYZSBlUJBUWZeiYJGno5CmkaepuZ/AA "Python 2 – Try It Online") I picked this trick up [from xnor](http://golf.shinh.org/reveal.rb?multiply+SI+units/xnor_1521614421&py) just a few days ago…! [Answer] # [Python 2](https://docs.python.org/2/), 20 bytes ``` lambda n:n*3-4*(n>1) ``` [Try it online!](https://tio.run/##LcQ7CoAwEAXAq2wXPxvI@ikU9CQWUSQo6FNCGk8fFS1mzissB4rouiFu4z7NI6FFVuoqS9BLGt3hCbSChGtuWAyLPJvX179pT78ikIXN1RAUK90rdgnSeAM "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 17 bytes ``` lambda n:n-3%~n*2 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKk/XWLUuTwsoml@kkKeQmadgqKNgqqNgqaNgaADEhiDaAExASRhlYKVQUJSZV6KgkaejkKaRp6n5HwA "Python 2 – Try It Online") I found the expression by brute-force search. It effectively computes `n+2*abs(n-2)`. [Answer] # Polyglot: Java 8 / JavaScript / C# .NET, ~~16~~ ~~14~~ 12 bytes ``` n->3*n-1%n*4 ``` [Try it online (Java 8).](https://tio.run/##jY3NCoJAFIX3PsXdBKOgOFSLkHqD3LiMFrfRYvy5ijMKET77NJrbGDcH7vk@zi1xxLDMKyNqVAquKOnjAUjSRf9EUUA6n0sBgs1JfmKbybOhNGopIAWCMxgKL/uAQr6j4GCSmXfDo7Z81cZW5tDYByzTvaTX7Q7o/9azt9JFE7WDjjqLdE2MIsG4v/z6y48OfnJwHrsE7lyI3cYWZZOzSpM3mS8) ``` n=>3*n-1%n*4 ``` [Try it online (JavaScript).](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1s5YK0/XUDVPy@R/cn5ecX5Oql5OfrpGmoahpqY1F6qQKaaQJaaQoQEWMUNs6gywCuIQxSUMEv8PAA) [Try it online (C# .NET)](https://tio.run/##Sy7WTc4vSv2fnJNYXKzgW82loFBQmpSTmaxQXJJYAqTK8jNTFHwTM/M0NEGSCgrBlcUlqbl6bqV5yTaZeSU6CkDCTiFNwfZ/nq2dsVaerqFqnpbJf2tkxc75ecX5Oal64UWZJak@mXmpGmkahpqaBNWYEqHGkgg1hgbEKDIkyiQD4lQRq4xodVCFtVy1/wE). Port of [*@Lynn*'s Python 2 answer](https://codegolf.stackexchange.com/a/160337/52210), so make sure to upvote his/her answer. --- ***Old answer:*** # Polyglot: Java 8 / JavaScript / C# .NET, ~~16~~ 14 bytes ``` n->n<2?3:n*3-4 ``` [Try it online (Java 8).](https://tio.run/##jY27DoJAEEV7vmLKxQQCooXi4wukoTQW44JmEQbCLiTG8O3rgrRmaW4y95zcKbBHr8hempcoJVxQ0McBEKTy9oE8h2Q8pwI4G5Pc2DSDY0IqVIJDAgRH0OSd6LA@R3taRd5Gx6PRdPfSGLPY1yKDyrxgqWoFPa83QPe3n76lyiu/7pTfGKRKYuRzFrrTt798a@E7Cw8DmxBaFwK7sURZ5MzS4Az6Cw) ``` n=>n<2?3:n*3-4 ``` [Try it online (JavaScript).](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i7Pxsje2CpPy1jX5H9yfl5xfk6qXk5@ukaahqGmpjUXqpApppAlppChARYxQ2zqDLAK4hDFJQwS/w8A) [Try it online (C# .NET)](https://tio.run/##Sy7WTc4vSv2fnJNYXKzgW82loFBQmpSTmaxQXJJYAqTK8jNTFHwTM/M0NEGSCgrBlcUlqbl6bqV5yTaZeSU6CkDCTiFNwfZ/nq1dno2RvbFVnpaxrsl/a2Tlzvl5xfk5qXrhRZklqT6ZeakaaRqGmpoE1ZgSocaSCDWGBsQoMiTKJAPiVBGrjGh1UIW1XLX/AQ). **Explanation:** ``` n-> // Method with integer as both parameter and return-type n<2? // If the input is 1: 3 // Return 3 : // Else: n*3-4 // Return the input multiplied by 3, and subtract 4 ``` [Answer] # [R](https://www.r-project.org/), 20 bytes ``` N=scan();3*N-4*(N>1) ``` [Try it online!](https://tio.run/##K/r/38@2ODkxT0PT2ljLT9dES8PPzlDzv6GBgcF/AA "R – Try It Online") Didn't notice the pattern until after I had implemented my less elegant solution. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes ``` 3*s≠i4- ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fWKv4UeeCTBPd//8NAQ "05AB1E – Try It Online") -1 byte thanks to Emigna ! [Answer] # [Oasis](https://github.com/Adriandmen/Oasis), 5 bytes ``` ¹y4-3 ``` Explanation: ``` 3 defines f(1) = 3 ¹y4- defines f(n) as: ¹ push input y triple 4- subtract four ``` [Try it online!](https://tio.run/##y08sziz@///QzkoTXeP///@b/tf1BwA "Oasis – Try It Online") [Answer] # [Oasis](https://github.com/Adriandmen/Oasis), ~~5~~ 4 bytes *1 byte saved thanks to @Adnan* ``` 3+23 ``` *Not to be confused with `23+3`* [Try it online!](https://tio.run/##y08sziz@/99Y28j4////lv91/QE "Oasis – Try It Online") **How?** ``` implicitly push a(n-1) 3 push 3 + sum and implicitly print 2 a(2) = 2 3 a(1) = 3 ``` [Answer] # [Haskell](https://www.haskell.org/), 15 bytes ``` f 1=3 f n=3*n-4 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P03B0NaYK00hz9ZYK0/X5H9uYmaegq1CbmKBr4JGQVFmXomCnkKapoKKQrShjoKpjoKljoKhARAbgmgDMAElYZRB7H8A "Haskell – Try It Online") [Answer] # [Standard ML](http://www.mlton.org/), 16 bytes ``` fn 1=>3|n=>3*n-4 ``` [Try it online!](https://tio.run/##K87N0c3NKcnP@1@WmKOQpmCr8D8tT8HQ1s64Jg9IaOXpmvy3VigoyswrUdAILgHS6XrJ@XnJiSXhmSUZCkoxeUoKGrmJBQoannkleiX5ECUK@QppmgrRhjoKpjoKljoKhgZAbAiiDcAElIRRBrGamtb/AQ "Standard ML (MLton) – Try It Online") [Answer] # [Dodos](https://github.com/DennisMitchell/dodos), 27 bytes ``` dot D D d d d d d dip ``` [Try it online!](https://tio.run/##S8lPyS/@/58zJb9EwYXLhYuTizNFIQVCgKjMgv///xsagAAA "Dodos – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ++_>¡4 ``` [Try it online!](https://tio.run/##y0rNyan8/19bO97u0EKT////GxqAAAA "Jelly – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 9 bytes ``` 3∘×-4×1∘< ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wTjRx0zDk/XNTk83RDIsgEKHlrxqHezoQEA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 21 bytes ``` 1*3. X*Y:-Y is 3*X-4. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/31DLWI8rQivSSjdSIbNYwVgrQtdEDyhsYGCgFaEHAA "Prolog (SWI) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes Uses the `3*n-4*(n>1)` formula. Multiply input by 3 (`3*`), push input again (`G`) and decrement it (`q`). If the result is not zero (`?`) then subtract 4 from the result (`4-`). ``` 3*Gq?4- ``` [Try it online!](https://tio.run/##y00syfn/31jLvdDeRPf/f0MDIAAA "MATL – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ạ2Ḥ+ ``` [Try it online!](https://tio.run/##y0rNyan8///hroVGD3cs0f5/dM/hdvf//w11FEx1FCx1FAwNgNgQRBuACSgJowwA "Jelly – Try It Online") ### How it works ``` ạ2Ḥ+ Main link. Argument: n ạ2 Absolute difference with 2; yield |n-2|. Ḥ Unhalve/double; yield 2|n-2|. + Add; yield 2|n-2|+n. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 20 bytes ``` f(n){n=3*n-4*!!~-n;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOs/WWCtP10RLUbFON8@69r@@PqqwRp6NkaZ1LRe6OEQ5QjjPztAeLGUFJIESXLmJmXkaWZrVaflFGlm2BtZZNoYGBtaaBUWZeSVpGkqqKTpKOmka2tpZmkDj/wMA "C (gcc) – Try It Online") [Answer] # [MachineCode](https://github.com/aaronryank/MachineCode) on x86\_64, ~~34~~ ~~32~~ 24 bytes ``` 8d47fe9931d029d08d0447c3 ``` Requires the `i` flag for integer output; input is taken via manually appending to the code. [Try it online!](https://tio.run/##y01MzsjMS03OT0n9/98ixcQ8LdXS0tgwxcDIMsXAIsXAxMQ82fi/ocH//5kA) --- I went through these 4 different C functions to find the 24-byte MachineCode program: * `n+2*abs(n-2)` = `8d47fe9931d029d08d0447c3` (24 bytes) * `3*n-4*!!~-n` = `8d047f31d2ffcf0f95c2c1e20229d0c3` (32 bytes) * `n*3-4*(n>1)` = `31d283ff028d047f0f9dc2c1e20229d0c3` (34 bytes) * `n<2?3:n*3-4` = `83ff01b8030000007e068d047f83e804c3` (34 bytes) [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~10~~ 9 bytes Saved 1 byte thanks to *Jo King* ``` 3*:3)4*-n ``` [Try it online!](https://tio.run/##S8sszvj/31jLyljTREs37////7plCoYGBgYA "><> – Try It Online") [Answer] # [4](https://github.com/urielieli/py-four), 54 bytes ``` 3.6010160303604047002020003100000180010202046000095024 ``` [Try it online!](https://tio.run/##JYgxDoAwDAP3vCIzEshpTCgDUh/OxMdCCrask4@ZvgUMFnB4gOABtCrghhnrtU8x5j93NGYOkaGXBuW5i9a7BHVR11X5ixc "4 – Try It Online") If you question the input method, please visit first the [numerical input and output may be given as a character code](https://codegolf.meta.stackexchange.com/a/4719/65326) meta post. [Answer] # Japt, 7 bytes A port of Lynn's Python solution. ``` *3É%U*4 ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=KjPJJVUqNA==&input=OA==) --- ## Alternative This was a fun alternative to the closed formula solutions that is, unfortunately, a byte longer: ``` _+3}gN³² ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=XyszfWdOs7I=&input=OA==) [Answer] # TI-Basic, 8 bytes ``` 3Ans-4(Ans>1 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes Uses the abs-method from [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/160350/47066) ``` 2α·+ ``` [Try it online!](https://tio.run/##MzBNTDJM/V9TVln53@jcxkPbtf9XKh3er6Brp3B4v5LOf0MuUy5LLkMDLkNDIGkAwhACShoAAA "05AB1E – Try It Online") **Explanation** ``` 2α # abs(input, 2) · # multiply by 2 + # add input ``` [Answer] # 65816 machine code, 22 bytes I could have made this 65C02 machine code easily for 3 bytes less, but didn't, since the register size on the 65C02 is 8-bit instead of 16-bit. It would work, but it's boring because you can only use really low numbers ;-) xxd dump: ``` 00000000: 7aa9 0000 aa89 0100 d004 8888 e824 c8e8 z............$.. 00000010: 1ac0 0000 d0ef ...... ``` disassembly / code explanation: ``` ; target is on the stack ply 7A ; pull target from stack lda #$0000 A9 00 00 ; set loop counter to 0 tax AA ; set step counter to 0 loop: bit #$0001 89 01 00 ; sets Z if loop counter is even bne odd D0 04 ; if Z is not set, jump to 'odd' dey 88 ; decrement target twice dey 88 inx E8 ; increment step counter .byte $24 24 ; BIT $xx opcode, effectively skips the next byte odd: iny C8 ; increment target inx E8 ; increment step counter inc a 1A ; increment loop counter cpy #$0000 C0 00 00 ; sets zero flag, can be optimized maybe? bne loop D0 EF ; if Y is non-zero, loop ; result is in register X ``` Testing it out on a 65816-compatible emulator: [![testing](https://i.stack.imgur.com/23UT5.png)](https://i.stack.imgur.com/23UT5.png) [Answer] **SHELL** , **28 Bytes** ``` F(){ bc<<<$1*3-$(($1>1))*4;} ``` Tests : ``` F 1 3 F 2 2 F 3 5 F 4 8 F5 11 F 11 29 F 100 296 F 100000 299996 ``` Explanation : The formula is : ``` if n == 1 ==> F(1) = 3 else F(n) = 3*n - 4 ``` following the sequence of 3 steps "Two steps forward and one step back", we will have the arithmetic series : ``` +2 2 => 2 ( or 6 ) -1 1 => 3 ----------- +2 3 => 5 ( or 9 ) -1 2 => 6 ----------- +2 4 => 8 ( or 12 ) -1 3 => 9 ----------- +2 5 => 11 ( or 15 ) -1 4 => 12 ----------- +2 6 => 14 ( or 18 ) -1 5 => 15 ----------- +2 7 => 17 ( or 21 ) -1 6 => 18 ``` At the minimum, or first coincidence : ``` 1 => 3 2 => 2 3 => 5 4 => 8 5 => 11 6 => 14 ``` in one formula : ``` F(n) = 3*n - 4(n>1) with n>1 is 1 or 0 (if n==1) ``` [Answer] # [Python 3](https://tio.run/#python3), 48 bytes ``` def a(x): if x!=1: return((3*x)-4) return(3) ``` [Try It Online!](https://tio.run/##K6gsycjPM/7/PyU1TSFRo0LTioszM02hQtHWEMjiLEotKS3K09Aw1qrQ1DXR5IIJGGv@LyjKzCvRSNQw1NTkgrFNkdiWSGxDA2SOIYoMUOo/AA) [Answer] # [J](http://jsoftware.com/), 9 bytes ``` 3&*-4*1&< ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jdW0dE20DNVs/mtycaUmZ@QraNhZZeoZGWjq6KUpQJhc/wE "J – Try It Online") [Answer] # MATLAB/[Octave](https://www.gnu.org/software/octave/), 15 bytes ``` @(n)3*n-4*(n>1) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI0/TWCtP10RLI8/OUPN/moaBlaGB5n8A "Octave – Try It Online") Kind of surprised there isn't already a MATLAB answer. Same algorithm of `3*n-4` if greater than 1, or `3*n` otherwise. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 38 bytes ``` ({<([()()]{})>()(){(<((){})>)()}{}}{}) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6PaRiNaQ1NDM7a6VtMOxKjWsNEAkkAekFNbXQtEmv//GxoYGAAA "Brain-Flak – Try It Online") The first answer I see to calculate the answer by stepping back and forth. ``` ({ while not at 0 <([()()]{})>()() take two steps forward, counting 2 steps {(<((){})>)()}{} take one step back, if not at 0, and add 1 step }{}) remove the 0 and push step sum ``` [Answer] ## [W](https://github.com/A-ee/w) `d`, 7 bytes ``` ♦óÖ╣░Θ$ ``` ## Explanation ``` 3*1a<4*- ``` Evaluates `(a*3)-4*(a>1)`. ## Another possible alternative ``` 3*1am4*- ``` Evaluates `(a*3)-4*(1%a)`. ]
[Question] [ ## Challenge Given an array of integers, received from stdin, function arguments, program arguments, or some other method: Output *only* the minimum and maximum numbers in the array, through a return value, stdout, or other fitting methods. ## Example session ``` > minmax( {0, 15, 2, 3, 7, 18, -2, 9, 6, -5, 3, 8, 9, -14} ) -14 18 ``` ## Reference implementation ``` // C++14 void minmax(std::vector<int> v) { int min = v[0]; int max = v[0]; for(auto it : v) { if (*it < min) min = *it; if (*it > max) max = *it; } std::cout << min << ' ' << max << std::endl; } ``` ## Rules * You may not use a built-in function to calculate the values. * Standard loopholes disallowed. * Creative implementations encouraged. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer wins but will not be selected. ## Clarifications * If the array contains 1 element you need to output it twice. * If the minimum and maximum values are the same, you need to output them both. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 3 bytes ``` Ṣ.ị ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmiLuG7iw&input=&args=WzAsIDE1LCAyLCAzLCA3LCAxOCwgLTIsIDksIDYsIC01LCAzLCA4LCA5LCAtMTRd) Sort the array, and then takes the 0.5-th element. Jelly uses 1-indexing, and floating points indexing means take its floor and its ceil. So the 0.5-th element would give you the 0th element and the 1st element. The 0th element is the last element. [Answer] # Python, ~~61~~ ~~49~~ ~~37~~ ~~36~~ ~~34~~ 31 bytes ``` lambda s:s.sort()or[s[0],s[-1]] ``` *-12 bytes thanks to RootTwo* *Another -12 bytes thanks to chepner* *-2 bytes thanks to johnLate* *-3 bytes thanks to johnLate* [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) ~~220~~ 218 bytes ``` (({}))([]){({}[()]<(([])<{({}[()]<([([({}<(({})<>)<>>)<><({}<>)>]{}<(())>)](<>)){({}())<>}{}({}<><{}{}>){{}<>(<({}<({}<>)<>>)<>({}<>)>)}{}({}<>)<>>)}{}<>{}>[()]){({}[()]<({}<>)<>>)}{}<>>)}{}({}<((())){{}{}([][()])}{}>) ``` [Try It Online!](http://brain-flak.tryitonline.net/#code=KFtdKXsoe31bKCldPCgoW10pPHsoe31bKCldPChbKFsoe308KCh7fSk8Pik8Pj4pPD48KHt9PD4pPl17fTwoKCkpPildKDw-KSl7KHt9KCkpPD59e30oe308Pjx7fXt9Pil7e308Pig8KHt9PCh7fTw-KTw-Pik8Pih7fTw-KT4pfXt9KHt9PD4pPD4-KX17fTw-e30-WygpXSl7KHt9WygpXTwoe308Pik8Pj4pfXt9PD4-KX17fSh7fTw-KTw-KFtdWygpXSl7e317fShbXVsoKV0pfXt9KHt9PD4p&input=) ## Explanation First it doubles the top value (in cast the list is only one long) ``` (({})) ``` Then it uses my bubble sort algorithm: ``` ([]){({}[()]<(([])<{({}[()]<([([({}<(({})<>)<>>)<><({}<>)>]{}<(())>)](<>)){({}())<>}{}({}<><{}{}>){{}<>(<({}<({}<>)<>>)<>({}<>)>)}{}({}<>)<>>)}{}<>{}>[()]){({}[()]<({}<>)<>>)}{}<>>)}{} ``` Then it picks up the top value of the stack (i.e. the min) ``` ({}<...>) ``` Then it pops until the height of the stack is one: ``` ((())){{}{}([][()])}{} ``` [Answer] ## JavaScript (ES6), 34 bytes ``` a=>[a.sort((x,y)=>x-y)[0],a.pop()] ``` `sort` sorts in-place, so I can just refer to the [0] index for the lowest value and `pop` the highest value from the array, however it does a string sort by default so I have to pass a comparator. [Answer] ## Mathematica, 18 bytes ``` Sort[#][[{1,-1}]]& ``` Sorts the array and extracts the first and last values. [Answer] # R, 31 bytes ``` l=sort(scan());l[c(1,sum(l|1))] ``` Not *that* original, but hey ! [Answer] # ARM Machine Code, 26 bytes Hex dump (little endian): ``` 6810 4601 f852 cb04 4560 bfc8 4660 4561 bfb8 4661 3b01 d8f5 4770 ``` This is a function, with no system call or library dependence. The encoding is Thumb-2, a variable (2 or 4 byte) encoding for 32-bit ARM. As one might imagine, there's no easy way to just sort and pick the first and last elements here. Overall there's nothing really that fancy going on here, it's more or less the same as the reference implementation. Ungolfed assembly (GNU syntax): ``` .syntax unified .text .global minmax .thumb_func minmax: @Input: @r0 and r1 are dummy parameters (they don't do anything) @r2 - Pointer to list of integers (int*) @r3 - Number of integers to sort (size_t) @Output: @Minimum of the list in r0 (int) @Maximum in r1 (int) ldr r0,[r2] @min=r2[0] mov r1,r0 @max=min loop: @ip is intra-procedure call register, a.k.a. r12 ldr ip,[r2],#4 @ip=*r2++ cmp r0,ip it gt @if (r0>ip) movgt r0,ip @r0=ip cmp r1,ip it lt @if (r1<ip) movlt r1,ip @r1=ip subs r3,r3,#1 bhi loop @while (--r3>0) bx lr @Return ``` Tested on the Raspberry Pi 3; here's the testing script (C99, input through argv): ``` #include <stdio.h> #include <stdlib.h> #include <stdint.h> //First 2 arguments are dummies. uint64_t minmax(int,int,int* array,size_t size); int main(int argc,char** argv) { int i; int array[argc-1]; for (i=1;i<argc;i++) { array[i-1]=atoi(argv[i]); } uint64_t result = minmax(0,0,array,argc-1); printf("Minimum is %d, maximum is %d.\n",(unsigned)result,(unsigned)(result>>32)); } ``` [Answer] # Haskell, 27 bytes ``` f x=(`foldl1`x)<$>[min,max] ``` In Haskell, `min` and `max` give minimum and maximum of two arguments, not of a list. I couldn't tell whether this is disallowed (it seems that instead only `minimum` and `maximum` would be disallowed) so please let me know if they are and I'll promptly delete this answer. [Answer] # Octave, 20 bytes ``` @(n)sort(n)([1,end]) ``` This sorts the input vector and outputs the first and last value. [Answer] ## Actually, 5 bytes ``` S;F@N ``` [Try it online!](http://actually.tryitonline.net/#code=UztGQE4&input=WzMsMiw1LDYsMV0) Explanation: ``` S;F@N S sort ; dupe F first element @N and last element ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 4 bytes ``` {Âø¬ ``` **Explanation** ``` { # sort list  # bifurcate ø # zip ¬ # head ``` [Try it online](http://05ab1e.tryitonline.net/#code=e8OCw7jCrA&input=WzAsIDE1LCAyLCAzLCA3LCAxOCwgLTIsIDksIDYsIC01LCAzLCA4LCA5LCAtMTRd) [Answer] # [MATL](http://github.com/lmendo/MATL), 4 bytes ``` S5L) ``` [Try it online!](http://matl.tryitonline.net/#code=UzVMKQ&input=WzAsIDE1LCAyLCAzLCA3LCAxOCwgLTIsIDksIDYsIC01LCAzLCA4LCA5LCAtMTRd) ### Explanation ``` S % Implicitly input the array. Sort 5L % Push [1 0]. When used as a (modular, 1-based) index, this means "first and last" ) % Apply as an indexing vector into the sorted array. Implicitly display ``` [Answer] # Python, 29 bytes ``` lambda s:s[s.sort():1]+s[-1:] ``` Test it on [Ideone](http://ideone.com/kQSoBu). [Answer] # C, ~~83~~ ~~81~~ 79 bytes ``` m,M;f(a,s)int*a;{for(m=M=*a;s--;++a)*a<m?m=*a:*a>M?M=*a:0;pr‌​intf("%i %i",m,M);} ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 9 bytes ``` oOtT,Oh:T ``` [Try it online!](http://brachylog.tryitonline.net/#code=b090VCxPaDpU&input=WzA6MTU6MjozOjc6MTg6XzI6OTo2Ol81OjM6ODo5Ol8xNF0&args=Wg) [Answer] # [V](http://github.com/DJMcMayhem/V), 12 bytes ``` :sor ò2Gjkd ``` [Try it online!](http://v.tryitonline.net/#code=OnNvcgrDsjJHamtk&input=OQo4CjcKNgo1CjQKMwoyCjE) Credit to DJMcMayhem for this. [Answer] # CJam, ~~10~~ 9 bytes ``` q~$_(p;W> ``` [Try it online.](http://cjam.aditsu.net/#code=q~%24_(p%3BW%3E&input=%5B0%2015%202%203%207%2018%20-2%209%206%20-5%203%208%209%20-14%5D) I'm really not good at CJam. ``` q~ e# eval input $ e# sort _ e# duplicate ( e# pop first p e# print ; e# remove array W> e# get last element ``` [Answer] # [Perl 6](http://perl6.org) 13 bytes ``` *.sort[0,*-1] ``` ## Test: ``` my &min-max = *.sort[0,*-1]; say min-max 1; # (1 1) say min-max (0, 15, 2, 3, 7, 18, -2, 9, 6, -5, 3, 8, 9, -14) # (-14 18) ``` [Answer] ## Python 2, 34 bytes ``` x=sorted(input());print x[0],x[-1] ``` [Answer] # PHP, 44 bytes ``` function a($a){sort($a);echo $a[0].end($a);} ``` [Answer] # POSIX Awk, 44 bytes ``` awk '{for(;NF-1;NF--)if($1>$NF)$1=$NF}1' RS= ``` [Answer] ## Java, 115 bytes ``` String f(int[]i){int t=i[0],a=t,b=t;for(int c=0;c<i.length;c++){a=i[c]<a?i[c]:a;b=i[c]>b?i[c]:b;}return""+a+" "+b;} ``` Ungolfed: ``` String f(int[] i) { int t=i[0], a=t, b=t; // assigns a and b to i[0] for (int c=0; c < i.length; c++) { // loop through the array a=(i[c]<a) ? i[c] : a; b=(i[c]>b) ? i[c] : b; // assignment with ternary operator } return ""+a+" "+b; // returns a string } ``` My first ever code "golf" solution. [Answer] # JavaScript (ES6), 46 bytes I wanted to try an answer without sorting: ``` a=>a.map(i=>i<n?n=i:i>x?x=i:0,n=x=a[0])&&[n,x] ``` Bonus recursive version, 53 bytes: ``` f=([i,...a],n=i,x=i)=>i+.5?f(a,i<n?i:n,i>x?i:x):[n,x] ``` [Answer] ## JavaScript (ES6), 68 58 bytes (without sorting) Oh my first try in Golf: without explicit sort (and without min max). Thanks to @ETHproductions for golfing tips!! ``` a=>(b=[],a.map(n=>b[n]=0),[b.indexOf(0),b.lastIndexOf(0)]) ``` Does not work with negative integers. Tried @Luis Mendo 's approach but got it 2 bytes longer... Cost for supporting negative numbers lol? ``` a=>[a.find(n=>a.every(e=>e>=n)),a.find(n=>a.every(e=>e<=n))] ``` Could get shorter if order of output is not important: ``` a=>a.filter(n=>a.every(e=>e>=n)||a.every(e=>e<=n)) ``` [Answer] # Processing, ~~59~~ 52 bytes ``` void m(int[]x){x=sort(x);print(x[0],x[x.length-1]);} ``` Processing doesn't actually let me read from stdin that I've been able to find, and I don't know if its internal Java compiler supports lambdas (and its been so long since I've had to write serious Java that I don't remember how). [Answer] # PHP, ~~66~~ 65 bytes Note: this doesn't use any `sort` builtin. Also, PHP 7 required for the null coalesce operator. ``` for(;n|$x=$argv[++$i];$x>$h&&$h=$x)$l=min($l??$x,$x);echo"$l,$h"; ``` The `max` part is straightforward. The `min` part is a bit more elaborate. since in PHP `null` is less than `123`, null needs to be handled. For this I'm using the null coalesce operator. If `$l` is null, use the current number (`$x`) instead, then take the smaller of the 2 numbers. Run like this: ``` php -d error_reporting=30709 -r 'for(;n|$x=$argv[++$i];$x>$h&&$h=$x)$l=min($l??$x,$x);echo"$l,$h";' -- 0 15 2 3 7 18 -2 9 6 -5 3 8 9 -14;echo ``` # 37 bytes (with sort) Being allowed to sort makes it trivial (windows-1252 encoding): ``` php -d error_reporting=30709 -r '$a=$argv;echo$a[sort($a)],~ß,end($a);' -- 0 15 2 3 7 18 -2 9 6 -5 3 8 9 -14;echo ``` Sort returns `1` when successful, and the list of arguments will start with `-` which will be sorted as the first item, so we need item `1` to yield `min`. Therefore we happen to be able to use the return value of `sort` as the index, saving 2 bytes. # Tweaks * Use `n|"0"` to make `"0"` truthy to continue the loop, instead of `0 ."0"`. Saved a byte [Answer] # APL (Dyalog), ~~11~~ ~~10~~ 5 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) -5 thanks to Erik the Outgolfer. [According to the original poster](https://codegolf.stackexchange.com/questions/90835/find-the-minimum-and-maximum-integers-in-an-array-without-using-builtins/90910?noredirect=1#comment221579_90835), using *a function that picks the largest of exactly two elements (in contrast to the largest of a whole array)* [is] *allowed*. Therefore, the obvious solution is: ``` ⌊/,⌈/ ``` `⌊/` minimum-reduction `,` followed by `⌈/` maximum-reduction --- More in the spirit of the challenge: ``` (⊃,⊢/)⍋⊃¨⊂ ``` `(`  `⊃` first  `,` followed by  `⊢/` the last (lit. right-reduction) `)` of `⍋` the indices of the elements in ascending order `⊃¨` each picks from `⊂` the entire argument [TryAPL online!](http://tryapl.org/?a=%28%28%u2283%2C%u22A2/%29%u234B%u2283%A8%u2282%290%2015%202%203%207%2018%20%AF2%209%206%20%AF5%203%208%209%20%AF14&run) [Answer] # [Julia 0.6](http://julialang.org/), 19 bytes ``` x->sort(x)[[1,end]] ``` [Try it online!](https://tio.run/##yyrNyUw0@59mm5Sanpn3v0LXrji/qESjQjM62lAnNS8lNvY/kOQqKMrMK8nJ00jTiDbQUTA01VEw0lEw1lEwB3IsdBR0gTxLHQUzIMsULG4B5usamsRqav7//x8A "Julia 0.6 – Try It Online") [Answer] ## C++ (g++), ~~148 133 131 122~~ 119 bytes ``` #import<map> #import<vector> [](std::vector<int>v){int a=v[0],b=a;for(int i:v)i<a?a=i:i<b?:b=i;printf("%d %d\n",a,b);}; ``` [Try it online!](https://tio.run/##fY27CoMwGIX3PEWwCAmk0OuSiz6IdfgTa/kHTUjTLOKzW6V0KnQ6fOfCcSHsH84tOxyCj0kPECryhXx3yceKwCt52pv/paZlz9RJ@WGNY6oyn1ahYHJzaIU1oHof2WahzBw11GBQora1tAZViGvUs6LsaNndxkKAsFzNatkWA@DI@EQo/Xkx01GcxFlcxHVWa6FnmSsyL28 "C++ (gcc) – Try It Online") [Answer] ## Haskell, 36 bytes ``` (\l->(head l,last l)).Data.List.sort ``` Would love to use `&&&` here but imports are so costly... ]
[Question] [ *This is the cops' thread. The robbers' thread is [here](https://codegolf.stackexchange.com/q/137743/61563).* Your challenge is to write a program or function that, with a certain input, prints the exact string `Hello, World!` and a newline. Capitalization, spacing and punctuation must be exact. Input may be taken via standard input, a file, or command-line/function arguments. Output may be given via return value, writing to a file, or standard output. Your program must print `Hello, World!` for at least one input. When your program is given the wrong input (i.e. the input that does not make it print `Hello, World!`), it can do whatever you like - crash, print random nonsense, call Chuck Norris, etc. **You may not use a hashing algorithm or any similar methods of obscuring the required input.** Submissions are preferred to be runnable & crackable on [TIO](//tio.run). Submissions not runnable or crackable on TIO are allowed, but please include instructions to download / run them. After one week, this challenge will be closed to future cop submissions. The winner is the shortest code that is uncracked after a week of posting it ("it" being the code, not this challenge). The winner will be accepted after two weeks. After a week has passed since posting, please mark your answer as safe and show the input (in a `> ! spoiler quote`). If a robber cracks your submission (before the week ends), please mark it as cracked and show the halting input (in a `> ! spoiler quote`). # Looking for uncracked submissions? ``` fetch("https://api.stackexchange.com/2.2/questions/137742/answers?order=desc&sort=activity&site=codegolf&filter=!.Fjs-H6J36vlFcdkRGfButLhYEngU&key=kAc8QIHB*IqJDUFcjEF1KA((&pagesize=100").then(x=>x.json()).then(data=>{var res = data.items.filter(i=>!i.body_markdown.toLowerCase().includes("cracked")).map(x=>{const matched = /^ ?##? ?(?:(?:(?:\[|<a href ?= ?".*?">)([^\]]+)(?:\]|<\/a>)(?:[\(\[][a-z0-9/:\.]+[\]\)])?)|([^, ]+)).*[^\d](\d+) ?\[?(?:(?:byte|block|codel)s?)(?:\](?:\(.+\))?)? ?(?:\(?(?!no[nt][ -]competing)\)?)?/gim.exec(x.body_markdown);if(!matched){return;}return {link: x.link, lang: matched[1] || matched[2], owner: x.owner}}).filter(Boolean).forEach(ans=>{var tr = document.createElement("tr");var add = (lang, link)=>{var td = document.createElement("td");var a = document.createElement("a");a.innerHTML = lang;a.href = link;td.appendChild(a);tr.appendChild(td);};add(ans.lang, ans.link);add(ans.owner.display_name, ans.owner.link);document.querySelector("tbody").appendChild(tr);});}); ``` ``` <html><body><h1>Uncracked Submissions</h1><table><thead><tr><th>Language</th><th>Author</th></tr></thead><tbody></tbody></table></body></html> ``` [Answer] # TeX - 38 bytes [Cracked(ish)](https://codegolf.stackexchange.com/a/138130/73219) This is worth a shot, because I can't imagine anyone on a site about writing short pieces of code would know TeX: ``` \read16to\x\message{Hello, World!}\bye ``` To run it, you should get a hold of some form of TeX that allows interactive mode. Save this to a file, and run TeX (or pdfTeX, XeTeX, etc.) on it. Edit: I'm currently considering this semi-cracked. The intended solution uses input from stdin, but TeXnically input from the way the program is invoked is valid. I'll be adding more devious TeX answers if someone gets the intended method. Here's the intended solution: > > ^C Ia - The first key is control-c, which causes an error. Then, you press I (capital i) to input a command. Then you type a (or anything else to be typeset). Normally, the message that was printed to stdout would be followed by a space and then a ')'. When you typeset something, it causes the font information to be output after the message. That means that a newline is thrown in, and the ')' gets moved later. > > > That may be underhanded, but should still be within the rules of the game. [Answer] # [><>](https://esolangs.org/wiki/Fish), 538 bytes, [Cracked by rexroni](https://codegolf.stackexchange.com/a/138262/66104) ``` v \">/v>v\v</>" /!?lp%*2di%*2di a v " " " "l" "o" / "e" v " " " " " / "l"/ v "!" " // " " " \ v \"d"o" " " " " " " "o"r" "!" v" "H" " " " "l" "" "" "r" " " \ " "l" "d" " v " " " " "H" "e" /"," " v " " " " " " "e" "W" /"d""l" v " " " " " " "H" "!" v " " v >>"Hello world?" >o< ^ ``` [Try it online](https://tio.run/##dVDLCsIwELznK@KAFxEWPJf02j/wEgQhFQuBSIX4@TXZvKrWHJLd7Mzs7tym531ZvNBQ5JXXviMFQbvePvaHk5n4ElfhpZSQ@ZQAIl42p3AhoPCO2IIjwXNOpWZBjJbYVUKSJkqsIqQTTmoYblUqTTZ9hOIM1hOe86HOWwhpZoQgfcxo02Y9zXBbqSZKrvZC3QXcgq0YmwrhmIGB1LZANiJCcY6GBeXQ5he0cnhYO5O9@rT4a/it44VSGEZrnXy52Zq@kJXr/pIuy/IG "><> – Try It Online"), or you may want to use the [fish playground](https://fishlanguage.com/playground). The first three lines read in a string from STDIN and use its charcodes mod 26 as coordinates to put the characters "`>/v>v\v</>`" into the maze below. The intended solution is a 20-character string made of the letters A–Z only (although you're allowed to use anything you want, of course). Solution: > > The intended input is [`OCEANICWHITETIPSHARK`](https://en.wikipedia.org/wiki/Oceanic_whitetip_shark) (it's a fish!). The path through the maze looks like: > ``` > v > \">/v>v\v</>" > /!?lp%*2di%*2di > a | | > v " " | |" > | v"l"______"o"__/ "e" > v | " " " " > | | " / "l"/ > v | "!" "| > |// " " " v_\ | > v| \"d"o" " " | " > || " " " "o"r" |"!" > v" "H" " " | " > "l"___""_______ _/__/_____ > "" "r" " | | " > |>__\ " "l" | | "d" " > v " " | " " "H" > | "e"v________/"," | " > v " " " " " " | > |"e"|"W" /"d""l"| | > v " " " " " | | " > < "H">__________ __\"!"__ > v " | | " > >____________ __ ___v > >>"Hello world?" | | >o< > | | ^ > ``` > > > > [Answer] # Octave, 59 bytes, [Cracked](https://codegolf.stackexchange.com/a/137769/31516) This works in Octave 4.2.0. I can't guarantee compatibility with all versions. ``` i=input('');printf('%c',i*~all(isequal(i,'Hello, World!'))) ``` Note: This doesn't print any trailing spaces or newlines. This is what it looks like: [![enter image description here](https://i.stack.imgur.com/QTbWR.png)](https://i.stack.imgur.com/QTbWR.png) It basically says: "Print the input string, unless the input is 'Hello, World!', in which case it should print nothing (or the null-character). [Answer] # [CJam](https://sourceforge.net/p/cjam), 7 bytes ([cracked](https://codegolf.stackexchange.com/a/137773/53748)) ``` q5/:i:c ``` [Try it online!](https://tio.run/##S85KzP3/v9BU3yrTKvn/fwA "CJam – Try It Online") Intended input: > > > ``` > 65608656376564465644656476558065568656236564765650656446563665569 > ``` > > > > [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes. [Cracked](https://codegolf.stackexchange.com/questions/137743/hello-world-robbers-thread/137804#137804) ``` tsZp?x ``` [Try it online!](https://tio.run/##y00syfn/v6Q4qsC@4v//aEMFIwVjBRMF01gA "MATL – Try It Online") [Answer] # [Explode](https://github.com/stestoltz/Explode), 23 bytes, [Cracked](https://codegolf.stackexchange.com/a/137790/53748) ``` @_?&4_-j>5&f^~c>&6\|4>7 ``` More coming, this is just the beginning >:) **[Try it online!](https://tio.run/##S60oyMlPSf3/3yHeXs0kXjfLzlQtLa4u2U7NLKbGxM78//@Q1OKS/wA "Explode – Try It Online")** ## Explorer Explanation There are four explorers in this program. I'm not entirely sure that wait (`>`) is working correctly. ``` @_? ``` Read user input (`?`), write and extend the tape (`@`) down (`_`). ``` &4_-j>5 ``` For 4 ticks (`4`), modify the tape (`&`) downwards (`_`), jumping by 5 (`5`), by subtracting (`-`) 19 (`j`). ``` &f^~c> ``` For 16 ticks (`f`), modify the tape (`&`) upwards (`^`) in a wave (`~`), alternating no affect, +13, no affect, and -13 (`c`). ``` &6\|4>7 ``` For 6 ticks (`6`), modify the tape (`&`) in both directions (`|`), decreasing (`\`) by 4 (`4`) each time, and jumping by 7 (`7`). Decreasing means that it subtracts 4 the first time, 8 the second time, etc. [Answer] # JavaScript (ES6), ~~173~~ ~~169~~ ~~163~~ ~~150~~ ~~151~~ ~~148~~ 143 bytes ([Cracked](https://codegolf.stackexchange.com/a/138379/41938)) Let's have something totally different... and *totally evil*. ``` const e=eval,p=''.split,c=''.slice,v=[].every,f=s=>(t=c.call(s),typeof s=='string'&&t.length<81&&v.call(p.call(t,`\n`),l=>l.length<3)&&e(t)(t)) ``` Usage: `f(something) // returns 'Hello, World!'` [Try it online!](https://tio.run/##NYpBCsIwEAC/0lPSwBoQLx7cfsQKDXFbI0saukugr49iEQZmDvMONUjcUtFTXp/UWlyzaEdINTAUtNZL4aQQf8kpElS8PzxV2naYUXDoFaOPgbkXB7oXWudOEK3olvJijVHPlBd93a5nY@qxlkMK05gnB4wD/6@LM4Z6dV9cax8) [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~130~~ 152 bytes, [CRACKED](https://codegolf.stackexchange.com/questions/137743/hello-world-robbers-thread/137786#137786) +22 bytes, I forgot about trailing newline... Program works the same as before, the newline is added to any output. ``` a=>a.Distinct().Select((x,y)=>a.Reverse().Skip(y).First()*x%255).Take(a.First()-33).Concat(new int[]{10}).Select(x=>(char)x).ToArray() ``` [Try it online!](https://tio.run/##VVBNSwMxEL3vr4gHIZFtUEtPdReKUjzopRV6KD0M2akOTZOaSesupb99zdovfIdh5r35eIzhnvEB2y2T@xTThiOu9Ru572GWOVgjb8Dgic/2mUgwFpjF6C8/Mh04QiQjdp4q8Q7kpLpI16YO460zTxxDupcL8wVhvijFUhQtFCXoF@JIzkSp9BQtpkTWeaM6aYI7DIydsqKNbJQeU@DUeVffPg4GSn/ACiWc2V6/r/SzdwaidPgjyMX5Yv9wf7hsrotSdgZUnWb9KARopGqH/9ymBewt6lmgiHIpz/UEoUpvSm6Uuk4csmM8tK9orc/FzAdb3fwC "C# (.NET Core) – Try It Online") Byte count also includes ``` using System.Linq; ``` For a start I went for something not too crazy. It can has multiple answers. The "official" crack: > > > . !$0%>5&8'#?)S\*TuE[MRX`+9 > > > [Answer] # tcc, 89 bytes, [cracked](https://codegolf.stackexchange.com/a/137803/14306) by Dennis ``` #!/usr/bin/tcc -run #include <stdio.h> int main() { puts("\n"); } #include "/dev/stdin" ``` This is particularly evil due to tcc's dynamic resolution. Lots of functions are predeclared and trying to overwrite them simply doesn't work. [Answer] # [Bash](https://www.gnu.org/software/bash/), 62 bytes, ([cracked by ArchDelacy](https://codegolf.stackexchange.com/a/137917/12012)) ``` [[ ! "${1////x}" =~ [[:alnum:]] ]]&&[[ $# = 1 ]]&&bash -c "$1" ``` No alphanumerics or forward slashes. You should have fun with this one. [Try it online!](https://tio.run/##S0oszvj/PzpaQVFBSaXaUB8IKmqVFGzrFKKjrRJz8kpzrWJjFWJj1dSAalSUFWwVDMG8JKA@Bd1koCZDpf///yvaAwA "Bash – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 7 bytes [cracked](https://codegolf.stackexchange.com/a/138148/63446) ``` ,+[.,+] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fRztaT0c79v9/AA "brainfuck – Try It Online") Good luck. (doesn't work with every BF interpreter [Answer] # Python 3, ~~191~~ 186 bytes (SAFE!) Same as my previous answer, but without the noob eval statement, so that somebody actually has to solve the problem I created. ``` import sys from numpy import * e=enumerate c='Hello, World!' print(''.join([c[int(sum([c*cos(n*i)for i,c in e(fromiter(sys.argv[1:],float))])+.01)]for n in[2*i+ord(n)for i,n in e(c)]])) ``` now execute it with the correct parameters, such as `python3 hw.py 1 2 3` --- *Edit*: previous version was missing a comma in "Hello, World!", and also I realized that it had an unnecesary ennumerate, which is now gone. --- *Edit 2*: Just for fun, here is an almost identical Pyth version (47 bytes) of the same code: ``` KEJ"Hello, World!"[[email protected]](/cdn-cgi/l/email-protection)*b.t*dk1K0.e+*2kCbJ ``` Input is taken from `stdin` and is in the form of a list of arguments, such as `[1,2,3]` I see no point in posting a separate answer because if you crack the Pthyon3 version, then you also crack the Pyth version, even without knowing Pyth. --- Answer: > > python3 hw.py 10.72800138 13.23008796 19.30176276 16.13233012 18.10716041 0.98306644 8.18257475 19.20292132 10.99316856 -2.15745591 6.01351144 5.45443094 10.41260889 > > > Explanation of code: > > `''.join()` creates the hello world string out of an array of characters from the string `"Hello, World!"`. The puzzle is solved when those indicies are `[0,1,2,3,4,5,6,7,8,9,10,11,12]`. Each index is calculated from an input and the constants given on the command line. The inputs are a hard coded series: `[2*i+ord(c) for i,c in enumerate('Hello, World!')]`. The funtion that relates the input, the constants, and the output (indicies) is this: `sum([c*cos(x*i) for i,c in enumerate(CONSTANTS)])`. This is a classic modelling problem, where you are trying to fit data to your model. > > > Arriving at the solution, in python: > > > ``` > from scipy import optimize > x = [2*i+ord(c) for i,c in eumerate('Hello, World!')] > y = `[0,1,2,3,4,5,6,7,8,9,10,11,12]`. > # make your function: 13 terms means we can achieve 13 exact outputs > def f(x,a,b,c,d,e,f,g,h,i,j,k,l,m): > return sum([c*cos(x*i) for i,c in enumerate([a,b,c,d,e,f,g,h,i,j,k,l,m])]) > # curve fit > ans,_ = optimize.curve_fit(f,x,y) > # check answer > [round(f(a,*ans),0) for a in x] # should be 0-12 > ``` > > > > [Answer] # JavaScript (ES6), 102 bytes ([Cracked](https://codegolf.stackexchange.com/a/137944/73228)) [The previous version](https://codegolf.stackexchange.com/a/137925/73228) has a massive cheese. Let's try this again... ``` f=s=>{let r='',i=0;while(i<13)r+=!s[i][0]||s[i]=='Hello, World!'[i]||s[i++];return r};Object.freeze(f) ``` [Try it online!](https://tio.run/##Hcm7DsIwDEDRX0mntEpBRYzBzGyMDFWGPhzhymqQE0CC8u2hsF2dO3WPLg5Ct7SZw4g5e4hwfDMmJaB1TdDY55UYSzrs9pUYKGJLrm3csvwCQJ@QOdTqEoTHQq/2P8Y4K5juMiv52HM/4ZC2XhBfWPoq5y8) Author solution: > > new Proxy({v:Array(13).fill(0)},{get:(o,p)=>['a','','Hello, World!'[p]][o.v[p]++]}) > > > Usage: > > var p=new Proxy({v:Array(13).fill(0)},{get:(o,p)=>['a','','Hello, World!'[p]][o.v[p]++]}) > console.log(f(p)) > > > [Answer] # [Cubically](//git.io/Cubically), 159 bytes ([Cracked](https://codegolf.stackexchange.com/a/138370/61563)) ``` +53$!7@6:2/1+551$?7@6:5+52$!7@66:3/1+552$?7@6:5+3/1+4$!7@6:5/1+3$?7@6:5+1/1+54$!7@6:3/1+552$?7@6:5+1/1+552$?7@6:5+52$!7@6:1/1+551$?7@6:5+1/1+3$!7@6:1/1+1$(@6)7 ``` This will be pretty easy to those who are comfortable with Cubically. [Try it online!](https://tio.run/##Sy5NykxOzMmp/P9f29RYRdHcwczKSN9Q29TUUMUexDHVNjUCC5tZGYPFjWDiIK4JRIcpkGkMEzcEKYNKoGkxROVCTbYyRLXQEGwaXMZQRcPBTNP8/38A) [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 51 53 bytes ([Cracked](https://codegolf.stackexchange.com/a/138427/73219)) ``` 00 C0 .WORD $C000 ; load address 20 FD AE JSR $AEFD 20 EB B7 JSR $B7EB 8A TXA 0A ASL A 45 14 EOR $14 8D 21 C0 STA $C021 45 15 EOR $15 85 15 STA $15 49 E5 EOR #$E5 85 14 STA $14 8E 18 D0 STX $D018 A0 00 LDY #$00 B1 14 LDA ($14),Y 20 D2 FF JSR $FFD2 C8 INY C0 0E CPY #$0E D0 F6 BNE *-8 60 RTS C8 45 4C 4C 4F 2C 20 D7 .BYTE "Hello, W" 4F 52 4C 44 21 0D .BYTE "orld!", $D ``` ### [Online demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"hello.prg":"data:;base64,AMAg/a4g67eKCkUUjSHARRWFFUnlhRSOGNCgALEUINL/yMD/0PZgyEVMTE8sINdPUkxEIQ0="%7D,"vice":%7B"-autostart":"hello.prg"%7D%7D) **Usage**: `SYS49152,[x],[n]`, where `x` is a 16bit unsigned integer and `n` is an 8bit unsigned integer. > > Input is 52768 and 23 (SYS49152,52768,23) > > > > The second parameter is directly written to `D018`, a control register of the VIC-II graphics chip. Using a suitable reference, you can deduce what to write there for setting lowercase mode without changing other modes and the address of the screen memory: `$17`, or decimal `23`. With that, you can follow the arithmetics in the code, so the first parameter ends up with the correct string address in `$14/$15` (little-endian). A more in-depth explanation can be found in the crack. > > > [![Screenshot](https://i.stack.imgur.com/LEymK.png)](https://i.stack.imgur.com/LEymK.png) Invoked with wrong values, a *crash* is **very likely**. For cracking, you might want to run it in a local installation of [vice](http://vice-emu.sourceforge.net/), so here's a BASIC loader to paste into the emulator (`RUN` it to place the program at `$C000`): ``` 0fOa=49152to49202:rEb:pOa,b:nE 1dA32,253,174,32,235,183,138,10,69,20,141,33,192,69,21,133,21,73,229,133,20,142 2dA24,208,160,0,177,20,32,210,255,200,192,255,208,246,96,200,69,76,76,79,44,32 3dA215,79,82,76,68,33,13 ``` **Update:** Added two bytes for the load address to make this an executable C64 `PRG` file in response to the [discussion on meta](https://codegolf.meta.stackexchange.com/q/13619/71420) [Answer] # [Python 2](https://docs.python.org/2/), 63 bytes, [cracked](https://codegolf.stackexchange.com/a/137746) Just to get the ball rolling... ``` #coding:rot13 cevag vachg()==h'Hello, World!'naq'Hello, World!' ``` [Try it online!](https://tio.run/##K6gsycjPM/r/Xzk5PyUzL92qKL/E0JgrObUsMV2hLDE5I11D09Y2Q90jNScnX0chPL8oJ0VRPS@xEE3k/38A "Python 2 – Try It Online") [Answer] # [Pyth](http://pyth.readthedocs.io), 18 bytes ([Cracked](https://codegolf.stackexchange.com/a/137755)) ``` IqGQ"Hello, World! ``` This is extremely easy, and anyone that knows Pyth would crack it in the blink of an eye, but still... Note that you must put the String between quotes. **[Try it online!](http://pyth.herokuapp.com/?code=IqGQ%22Hello%2C+World%21&input=%22ENTER+THE+STRING+HERE%22&debug=0)** [Answer] # JavaScript (Browser only), 95 bytes ([Cracked](https://codegolf.stackexchange.com/a/137759/72349)) ``` try{a=JSON.parse(prompt());try{a=='[object Object]'}catch(a){alert('Hello, World!')}}catch(a){} ``` Not too hard. Has multiple solutions. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ([cracked](https://codegolf.stackexchange.com/a/137763/41024)) ``` sLƽ$Xṙ5O½Ọ ``` [Try it online!](https://tio.run/##y0rNyan8/7/Y53Dbob0qEQ93zjT1P7T34e6e//8B "Jelly – Try It Online") Intended input: > > > ``` > 〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ > ``` > > > > [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes ([Cracked](https://codegolf.stackexchange.com/a/137770/53748)) Shouldn't be too hard though: ``` •GG∍Mñ¡÷dÖéZ•2ô¹βƵ6B ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##AS0A0v8wNWFiMWX//@KAokdH4oiNTcOxwqHDt2TDlsOpWuKAojLDtMK5zrLGtTZC//8 "05AB1E – Try It Online") [Answer] # [Ly](https://github.com/LyricLy/Ly), 12 bytes ([Cracked](https://codegolf.stackexchange.com/a/137793/53748)) ``` n[>n]<[8+o<] ``` [Try it online!](https://lylang.herokuapp.com/?program=n%5B%3En%5D%3C%5B8%2Bo%3C%5D) ~~I don't expect this to last very long, but oh well.~~ It didn't last very long. [Answer] # Python3, 192 bytes [Cracked I guess](https://codegolf.stackexchange.com/a/137810/63446) ``` from sys import * from numpy import * e=enumerate c='Hello World!' w=eval(argv[1]) x=[ord(n)+2*i for i,n in e(c)] print(''.join([c[int(sum([c*cos(n*i)for i,c in e(w)])+.01)]for i,n in e(x)])) ``` The text it reads is the first program argument: `python3 hw.py '[1,2,3]'` Don't be lame and try to put a `print("Hello World!")` statement as the argument... it prints an error afterwards anyways (at least on the command line), so I don't think that should count. (Edit: somebody did exactly that) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ([Cracked](https://codegolf.stackexchange.com/a/137805/53748)) +1 byte - "...and a trailing newline" ``` œ?“¥ĊɲṢŻ;^»œ?@€⁸ḊFmṪ⁷ ``` **[Try it online!](https://tio.run/##ATkAxv9qZWxsef//xZM/4oCcwqXEismy4bmixbs7XsK7xZM/QOKCrOKBuOG4ikZt4bmq4oG3////MywyLDE "Jelly – Try It Online")** There are, in fact, infinite solutions. [Answer] # Lua 5.1, 44 bytes ([Cracked](https://codegolf.stackexchange.com/a/137872/72546)) ``` s=...loadstring(#s>4+#s:gsub("%l","")or s)() ``` Note that Lua 5.1 is a different language than Lua 5.2 or Lua 5.3. "Try it online" doesn't have Lua 5.1. You can check your Lua version by running `print(_VERSION)`. (There should be a solution in any implementation that uses PUC-Rio's Lua 5.1 core.) As a test harness, you can use something like this: ``` function test(...)s=...loadstring(#s>4+#s:gsub("%l","")or s)()end test[[ This is my input! It can have multiple lines! ]] ``` [Test harness on repl.it](https://repl.it/Jy9Z/0) [Answer] # C (GCC on TIO), 84 bytes golfed ([Cracked](https://codegolf.stackexchange.com/a/137875/72546)) ``` #include<stdio.h> main(x){scanf("%d",&x);printf("%2$s","Hello, World!\n",(void*)x);} ``` Here's an ungolfed version that works too: ``` #include <stdio.h> int main(void) { int x; scanf("%d",&x); printf("%2$s","Hello, World!\n",(void*)x); } ``` * Golfed: [Try it online!](https://tio.run/##S9ZNT07@/185My85pzQl1aa4JCUzXy/Djis3MTNPo0Kzujg5MS9NQ0k1RUlHrULTuqAoM68ExDdSKVbSUfJIzcnJ11EIzy/KSVGMyVPS0SjLz0zR0gSqrP3/HwA) * Ungolfed: [Try it online!](https://tio.run/##S9ZNT07@/185My85pzQlVcGmuCQlM18vw44rM69EITcxM0@jLD8zRZOrmksBCECCFdZgZnFyYl6ahpJqipKOWoWmNRdYsKAIqAIkaqRSrKSj5JGak5OvoxCeX5STohiTp6QDNkxLE6S@9v9/AA) [Answer] # JavaScript (ES6), 92 bytes ([Cracked](https://codegolf.stackexchange.com/a/137936/73228)) This simple string copy function seems to be *really* resisting you to copy any strings resembling `Hello, World!`... ``` f=s=>{let r='',i=0;while(i<13)r+=s[i]=='Hello, World!'[i]||s[i++];return r};Object.freeze(f) ``` [Try it online!](https://tio.run/##XcyxDsIgEIDhvU@BE5DWRuOI19nN0cF0qPRQmguYAzXR@uzY2fX/kn8ankOy7O95HeKIpThI0H0Is2CQsvGwMa@bJ1R@v91priGdfQ8gD0gUG3GKTONKLm2eF6nr3jDmBwfBX3O8TGhz6xjxjcrpqrIxpEjYUrwqp/4mWpfyAw) [Answer] # [Röda](https://github.com/fergusq/roda), 71 bytes ([Cracked](https://codegolf.stackexchange.com/a/137938/66323)) ``` {[[head(_)]..[unpull(1)if[_1>1]]]|[_()|chars|unorderedCount|[_*(_-1)]]} ``` [Try it online!](https://tio.run/##LYxBCsMgEADPzSv2uApN8FpoL33GsohURSHVYuMp5u1GaI/DMFOyNd33nSg4Y1ELnmeq6VPXFZWInrR6KGZupFG0VzDl22rKxbri7DPXtA0jUV@VYD7628QE@3SJ47DB7Q60SPhBGAXIhf8SBTTwKKajnw "Röda – Try It Online") Usage: `push(/* input */) | f()` (where f is a variable that holds the function above). [Answer] # JavaScript (ES6), ~~135~~ 119 bytes, ([Cracked](https://codegolf.stackexchange.com/a/137941)) ``` const t='Hello, World!',g=q=>eval(`(function(p,q${q}){return eval(p),eval(q)})`),f=s=>g('')(s,0)==t&&g('=1')(s,0)!=t&&t ``` [Try it online!](https://tio.run/##LYlLCoMwFACvEqGYPHiF9gDPdW/QrSFGsYR8n27Es8cqroaZ@elVF5PnyE8fBlurCb6wYJIf61xA8Q3ZDY3EiRJ1dtVO9WpcvOE5eBUxPba0w5YtL9mL60fAiwl26AFHKtRNSkpQBV9AxG37V3rfoTkD13oA) [Answer] # [Ruby](https://www.ruby-lang.org/), 88 bytes, [Cracked](https://codegolf.stackexchange.com/a/137956/6828) by w0lf ``` require'prime' n=gets.to_i n.prime?&&$><<n.to_s(36)[0,5].capitalize $><<", #$'"if/30191/ ``` [Try it online!](https://tio.run/##KypNqvz/vyi1sDSzKFW9oCgzN1WdK882PbWkWK8kPz6TK08PLGivpqZiZ2OTBxIs1jA204w20DGN1UtOLMgsSczJrErlAkkr6Sgoq6grZabpGxsYWhrq//9vmFtZXJJaVAkA "Ruby – Try It Online") [Answer] # JavaScript (ES6) 107 Bytes [Thanks Евгений Новиков] ([Cracked](https://codegolf.stackexchange.com/a/137913/71612)) ``` i=r=>{for(e="",n=0;r.length>n;o=r.charCodeAt(++n),e+=String.fromCharCode(((3^o^19)<<1^15^13)<<1));return e} ``` Call on the `i` function using a string. *The `console.log...` is for testing purposes.* [Try It Online!](https://tio.run/##LY2xCoMwFEV3v8I6JZhKRTqUGKG4dO/QLRD0VW1jnjxToZR@e2rB7cI5h/swi5kbGia/n6ehBRrRPeEdwmIoRgEqSYRTBzGMk8UWFCOuqs8diUnKLLjO95WTqChrekP1qpw9S1PHBaTq6mlwXXYnHOuNMsYKjTo/8bLMdX7UefFfnEsC/yIXw1dGUYNuRguZxY5tzyy5gLUY35Bsu0vWIIQf) ]
[Question] [ **This question already has answers here**: [Counting in bijective base 62](/questions/79304/counting-in-bijective-base-62) (19 answers) Closed 6 years ago. Zeroless numbers are numbers that do not contain **0** as one of their decimal digits. Given an integer **K**, return the **K**th zeroless number. **K** will be non-negative if you choose **0**-indexing, or positive if you choose **1**-indexing instead. Note that this is OEIS [A052382](https://oeis.org/A052382). This is code golf, so the shortest code in bytes wins. ## Test cases 1-indexed: ``` 1 -> 1 2 -> 2 9 -> 9 10 -> 11 16 -> 17 100 -> 121 ``` 0-indexed: ``` 0 -> 1 1 -> 2 8 -> 9 9 -> 11 15 -> 17 99 -> 121 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ḃ9Ḍ ``` [Try it online!](https://tio.run/##y0rNyan8///hjmbLhzt6/h/dc7jd/f9/Qx0FIx0FSx0FQwMgNgPRBgA "Jelly – Try It Online") ### How it works ``` ḃ9Ḍ Main link. Argument: n (1-based index) ḃ9 Convert n to bijective base 9. Ḍ Convert the result from base 10 to integer. ``` [Answer] # [Python 2](https://docs.python.org/2/), 35 bytes ``` f=lambda n:n and~-n%9+1+f(~-n/9)*10 ``` [Try it online!](https://tio.run/##DcYxCoAgGAbQuU7xL4FmkbopdBjDLKE@RVxaurr1ppefeibo1sJ6uXvzjmBBDv6dMRihRGD/FsNHJVtIhUARVByOnWkpue27XCIqYaLAwNsH "Python 2 – Try It Online") One indexed. [Answer] # [Python 2](https://docs.python.org/2/), 50 bytes ``` n=input() i=0 while n:i+=1;n-=1-('0'in`i`) print i ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERDkyvT1oCrPCMzJ1UhzypT29bQOk/X1lBXQ91APTMvITNBk6ugKDOvRCHz/39DAwA "Python 2 – Try It Online") [Answer] # [Actually](https://github.com/Mego/Seriously), 10 bytes ``` ⌠$'0@cY⌡╓N ``` [Try it online!](https://tio.run/##S0wuKU3Myan8//9RzwIVdQOH5MhHPQsfTZ3s9/@/oQEA "Actually – Try It Online") Explanation: ``` ⌠$'0@cY⌡╓N ⌠ ⌡╓N nth number (starting with i=0) where $ string representation of i '0@cY does not contain 0 ``` [Answer] # [Haskell](https://www.haskell.org/), 31 bytes ``` (filter(all(>'0').show)[0..]!!) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P81WIy0zpyS1SCMxJ0fDTt1AXVOvOCO/XDPaQE8vVlFR839uYmaegq1CQVFmXomCikJuYoFCmgJI1tDAIPY/AA "Haskell – Try It Online") --- **32 bytes** ``` (l!!) l=(+).(10*)<$>0:l<*>[1..9] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P81WI0dRUZMrx1ZDW1NPw9BAS9NGxc7AKsdGyy7aUE/PMvZ/bmJmnoKtQkFRZl6JgopCbmKBQppCtIGenqGBQex/AA "Haskell – Try It Online") One-indexed. --- **33 bytes** ``` (l!!) l=0:[10*a+b|a<-l,b<-[1..9]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P81WI0dRUZMrx9bAKtrQQCtRO6km0UY3RyfJRjfaUE/PMjb2f25iZp6CrUJBUWZeiYKKQm5igUKaQrSBnp6hgUHsfwA "Haskell – Try It Online") --- **34 bytes** ``` (l!!) l=0:do a<-l;take 9[10*a+1..] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P81WI0dRUZMrx9bAKiVfIdFGN8e6JDE7VcEy2tBAK1HbUE8v9n9uYmaegq1CQVFmXomCikJuYoFCmkK0gZ6eoYFB7H8A "Haskell – Try It Online") --- **37 bytes** ``` f 0=0 f n=mod(n-1)9+1+10*f(div(n-1)9) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P03BwNaAK00hzzY3P0UjT9dQ01LbUNvQQCtNIyWzDCKg@T83MTNPwVahoCgzr0RBRSE3sUAhTSHaQE/P0MAg9j8A "Haskell – Try It Online") [Answer] ## [Perl 5](https://www.perl.org/), 20 bytes **19 bytes code + 1 for `-p`.** Uses 1-indexing. ``` 0while$_-=++$\!~0}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/9@gPCMzJ1UlXtdWW1slRrHOoLb6/39DA4N/@QUlmfl5xf91CwA "Perl 5 – Try It Online") [Answer] # Javascript (ES7), 23 Bytes ``` f=n=>n&&n--%9+10*f(n/9) ``` Explanation: ``` f=n=> //=> syntax n&&n--%9 //only with 0 0s +10*f(n/9)//^^ ``` [Answer] # [Python 2](https://docs.python.org/2/), 50 bytes ``` n=input();v=0 while n:v+=1;n-=min(`v`)>'0' print v ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERD07rM1oCrPCMzJ1Uhz6pM29bQOk/XNjczTyOhLEHTTt1AnaugKDOvRKHs/39DAwMA "Python 2 – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 40 bytes ``` param($a)(1..(2*$a)|?{$_-notmatch0})[$a] ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRU8NQT0/DSAvIqrGvVonXzcsvyU0sSc4wqNWMVkmM/f//v6UlAA "PowerShell – Try It Online") Take input `$a`, then construct a range from `1` to `2*$a`. Pull out those elements that regex do `-notmatch` `0`, and then take the `$a`th one thereof. Output is implicit. [Answer] # [Haskell](https://www.haskell.org/), 31 bytes This is zero-indexed ``` (filter(all(>'0').show)[1..]!!) ``` [Try it online!](https://tio.run/##BcFRCoAgDADQqywI1I@GHaAuUn4M0ZKmSQrdvvXeSe0KzBKXXXRM3MOjiVmvyiqD7bxfs82IbhiMZEoFFqhPKh1GyFQhwmYRZ2udfD4yHU0mX@sP "Haskell – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~16~~ ~~13~~ 14 bytes *-2 bytes thanks to Luis Mendo* ``` E:!tV48-!XA)G) ``` [Try it online!](https://tio.run/##y00syfn/39VKsSTMxEJXMcJR013z/39DAwMA) Explanation: ``` (implicit input) E % double : % 1:top of stack (so [1, 2, ..., 2n]) !t % transpose and dup V % cast to chars 48- % subtract 48 (maps numbers to digits) ! % transpose XA % Check each column if All are true (nonzero) ) % index into array (so we are left with zeroless numbers) G) % paste input and index; TOS is the nth element. (implicit output) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` µNSĀP ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0Fa/4CMNAf//GxoYAAA "05AB1E – Try It Online") **Explanation** ``` µ # loop over N until input matches are found NS # split N into list of digits Ā # check if trueish (not zero) P # product ``` or with [Dennis's base conversion trick](https://codegolf.stackexchange.com/a/145165/47066) # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` 9.h ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fUi/j/39DAwMA "05AB1E – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` DȦ$#Ṫ ``` -2 bytes thanks to Dennis # Explanation ``` DȦ$#Ṫ Main link; takes input from STDIN # nfind; get first n matches starting from 0 $ Get numbers that are zeroless: D Digits Ȧ Are all truthy Ṫ Tail; get last element ``` [Try it online!](https://tio.run/##y0rNyan8/9/lxDIV5Yc7V/3/b2hgAAA "Jelly – Try It Online") [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 124 bytes ``` 00 C0 20 FD AE 20 6B A9 A2 05 A9 00 85 FB 85 FC 85 FD A0 10 06 FB 06 14 26 15 90 02 E6 FB A5 FB C9 09 90 04 E9 09 85 FB 26 FC 26 FD 88 D0 E5 A5 FB 95 61 CA A5 FD 85 15 A5 FC 85 14 D0 CC A5 15 D0 C8 E8 86 FE B5 61 D0 1E A9 09 95 61 86 9E CA B4 61 F0 11 D6 61 D0 0D E4 FE D0 04 E6 FE B0 05 95 61 CA 10 EB A6 9E E8 E0 06 D0 D9 18 A6 FE B5 61 69 30 20 D2 FF E8 E0 06 D0 F4 60 ``` **[Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22zeroless.prg%22:%22data:;base64,AMAg/a4ga6miBakAhfuF/IX9oBAG+wYUJhWQAub7pfvJCZAE6QmF+yb8Jv2I0OWl+5VhyqX9hRWl/IUU0MylFdDI6Ib+tWHQHqkJlWGGnsq0YfAR1mHQDeT+0ATm/rAFlWHKEOumnujgBtDZGKb+tWFpMCDS/+jgBtD0YA==%22%7D,%22vice%22:%7B%22-autostart%22:%22zeroless.prg%22%7D%7D)** **Usage:** `sys49152,[n]`, e.g. `sys49152,100`. `n` is **1**-indexed. Valid values are in the range [1,63999]. ### Explanation: The common approach to save bytes is to do it iteratively / recursively checking for decimal `0` digits -- this doesn't save bytes on the C64 because there's not even a division instruction available -- just converting to base 9 and adjusting the digits gives a shorter result (still with the need to hand-code a long binary division). Here's the commented disassembly: ``` 00 C0 .WORD $C000 ; load address .C:c000 20 FD AE JSR $AEFD ; consume comma .C:c003 20 6B A9 JSR $A96B ; read 16bit number .C:c006 A2 05 LDX #$05 ; index of last digit in result .C:c008 .divide: .C:c008 A9 00 LDA #$00 ; initialize some variables .C:c00a 85 FB STA $FB ; to zero ... .C:c00c 85 FC STA $FC .C:c00e 85 FD STA $FD .C:c010 A0 10 LDY #$10 ; repeat 16 times for division .C:c012 .div_loop: .C:c012 06 FB ASL $FB ; shift remainder left .C:c014 06 14 ASL $14 ; shift dividend ... .C:c016 26 15 ROL $15 ; ... left .C:c018 90 02 BCC .div_nobit ; highest bit set? .C:c01a E6 FB INC $FB ; then add one to remainder .C:c01c .div_nobit: .C:c01c A5 FB LDA $FB ; compare remainder ... .C:c01e C9 09 CMP #$09 ; ... to 9 (divisor) .C:c020 90 04 BCC .div_nosub ; if greater or equal 9 (divisor) .C:c022 E9 09 SBC #$09 ; subtract 9 from remainder .C:c024 85 FB STA $FB .C:c026 .div_nosub: .C:c026 26 FC ROL $FC ; shift quotient left, shifting in .C:c028 26 FD ROL $FD ; carry if remainder was >= 9 .C:c02a 88 DEY ; loop counting .C:c02b D0 E5 BNE .div_loop ; and repeat .C:c02d A5 FB LDA $FB ; load remainder .C:c02f 95 61 STA $61,X ; store in current output digit .C:c031 CA DEX ; decrement digit index .C:c032 A5 FD LDA $FD ; copy quotient ... .C:c034 85 15 STA $15 .C:c036 A5 FC LDA $FC ; ... to dividend .C:c038 85 14 STA $14 .C:c03a D0 CC BNE .divide ; if not zero yet .C:c03c A5 15 LDA $15 .C:c03e D0 C8 BNE .divide ; repeat division by 9 .C:c040 E8 INX .C:c041 86 FE STX $FE ; remember index of first digit .C:c043 .adjust_loop: .C:c043 B5 61 LDA $61,X ; load digit .C:c045 D0 1E BNE .nonine ; if it's zero, must be changed to 9 .C:c047 A9 09 LDA #$09 .C:c049 95 61 STA $61,X .C:c04b 86 9E STX $9E ; save current index and go back .C:c04d CA DEX .C:c04e .sub_loop: .C:c04e B4 61 LDY $61,X ; examine previous digit .C:c050 F0 11 BEQ .sub_done ; zero? nothing more to subtract .C:c052 D6 61 DEC $61,X ; decrement previous digit .C:c054 D0 0D BNE .sub_done ; not zero -> done .C:c056 E4 FE CPX $FE ; are we at the first digit? .C:c058 D0 04 BNE .sub_next ; no: go on .C:c05a E6 FE INC $FE ; first digit now zero, so increment .C:c05c B0 05 BCS .sub_done ; and done with subtraction .C:c05e .sub_next: .C:c05e 95 61 STA $61,X ; store 9 to this digit .C:c060 CA DEX ; and go to previous .C:c061 10 EB BPL .sub_loop ; repeat .C:c063 .sub_done: .C:c063 A6 9E LDX $9E ; load saved digit index .C:c065 .nonine: .C:c065 E8 INX .C:c066 E0 06 CPX #$06 ; reached last digit? .C:c068 D0 D9 BNE .adjust_loop ; no -> repeat .C:c06a 18 CLC .C:c06b A6 FE LDX $FE ; start output at first digit .C:c06d .out_loop: .C:c06d B5 61 LDA $61,X ; load digit .C:c06f 69 30 ADC #$30 ; add character code `0` .C:c071 20 D2 FF JSR $FFD2 ; output character .C:c074 E8 INX ; next .C:c075 E0 06 CPX #$06 ; last digit done? .C:c077 D0 F4 BNE .out_loop ; if not, repeat .C:c079 60 RTS ``` [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 32 bytes ``` [:|p=p+1≈instr(!p$,@0`)|p=p+1}?p ``` ## Explanation ``` [:| FOR a = 1 to <input> p=p+1 increase p (starts as 0) by 1 ≈ WHILE instr the index in (!p$ the string-cast of p ,@0`)| of the string '0' is non-zero p=p+1 skip this number in the zero-less sequence } WEND, NEXT ?p PRINT p ``` [Answer] # Mathematica, 55 bytes ``` (s=t=1;While[s<=#,If[DigitCount[t++,10,0]<1,s++]];t-1)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X6PYtsTW0Do8IzMnNbrYxlZZxzMt2iUzPbPEOb80ryS6RFtbx9BAxyDWxlCnWFs7Nta6RNdQU@1/QFFmXomCQ3q0YSwXnG2ExLZEYhsaIHPMUGQMYv8DAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~9~~ 8 bytes ``` e.f*FjZT ``` **[Verify all the test cases.](http://pyth.herokuapp.com/?code=e.f%2aFjZT&test_suite=1&test_suite_input=1%0A2%0A9%0A10%0A16%0A100&debug=0)** ## Explanation ``` e.f*FjZT ~ Full program. .f ~ Collect the first Q matches. Uses a variable Z. jZT ~ Decimal digits of Z. *F ~ Product. Can be replaced by .A (all) - Basically checks if all are ≥ 1. e ~ End. Get the last element. ``` [Answer] # [Perl 6](http://perl6.org/), 24 bytes ``` {(grep {!/0/},^∞)[$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiO9KLVAoVpR30C/VifuUcc8zWiV@Nja/9YKxYmVCkoq8Qq2dgrVaQoq8bVKCmn5RQo2BgqGChYKlgqGpgqWlnbW/wE "Perl 6 – Try It Online") 0-indexed. [Answer] # [Python 2](https://docs.python.org/2/), ~~50~~ 49 bytes *1 byte off thanks to @Mr.Xcoder* ``` lambda n:[k for k in range(2*n)if('0'in`k`)<1][n] ``` 0-based. [Try it online!](https://tio.run/##BcExDoAgDADAr3QDnJQNoy9BEjBabdBCCIuvr3f163dhK7hu8qR3PxLw7DNgaZCBGFri69R2YEOo1aiIY45mmYLnILURd0DtnJEf "Python 2 – Try It Online") [Answer] # C, 70 bytes ``` i,j,k;f(n){for(i=0;n--;n+=!k)for(k=j=++i;j;j/=10)k=j%10?k:0;return i;} ``` 1-indexed [Try it online!](https://tio.run/##HU5LCsMgFNx7iteAoKhUu8yr9CLdFFOLSl@LpKuQs1vNrObHMMG8Qmgt6awLRkFyi58qkrdIxiApfypyOMVnr1TCjPnsnZVdc2dvZbZYn@uvEiTcW6IV3o9EQrKNQccwCA86Vsg7BLperEVQiuQRdHxrL0Yx8WUGvtxp0kAaxh2JbG9/) # C (gcc), 65 bytes ``` i,j,k;f(n){for(i=0;n--;n+=!k)for(k=j=++i;j;j/=10)k=j%10?k:0;n=i;} ``` 1-indexed [Try it online!](https://tio.run/##HU7LCsMgELz7FduAoKhUe8x26Y/0UgwWlW5D6C3k261mTvNimOjeMbaWbbEVk2K9p@@mMnlk55ANXaoeTqVCxmQsWK4UvO5aBv@ocy9SxqNl/sHnlVlpsQvoGAbjSccAU0Dg@817BGNYn0HHuvViUpNcZpDLkycLbGE80SiO9gc) [Answer] ## JavaScript (ES6), ~~28~~ 27 bytes ``` f=n=>n&&--n%9+1+10*f(n/9|0) ``` ``` <input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o> ``` Edit: Saved 1 byte by switching to a numeric result (effectively porting @xnor's Python answer). [Answer] # Excel VBA, 57 Bytes Anonymous VBE immediate window function that takes input, `n` from range `[A1]` and outputs the `n`th `0`-indexed zeroless number to the VBE immediate window. ``` For i=1To[A1]:j=j+1:While InStr(1,j,0):j=j+1:Wend:Next:?j ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 39 bytes ``` {for(;c<$1;)c=index(++i,0)?c:c+1;$0=i}1 ``` Since this is `AWK` `1`-indexing seemed appropriate. [Try it online!](https://tio.run/##SyzP/v@/Oi2/SMM62UbF0Foz2TYzLyW1QkNbO1PHQNM@2SpZ29BaxcA2s9bw/39DAwMA "AWK – Try It Online") [Answer] # Java 8, 45 bytes ``` int c(int n){return n>0?--n%9+1+c(n/9)*10:0;} ``` 1-indexed Port of [*@xnor*'s Python 2 answer](https://codegolf.stackexchange.com/a/145163/52210). **Explanation:** [Try it here.](https://tio.run/##LY6xDoIwEIZ3nuJCYtJawTI4IKJP4MRoHCqgKcKVtIXEEJ69FsJw/z/cfV@uEaOIVF9jU31d2Qpj4C4kTgGAscLKEpxECyVZEumkaztoBLzyWxThLmUJKwkeU7pP@JlnswPoh1fruQ0flayg80pSWC3x83iCoIse4K30qpV5koG85CfOfTO2rQGKn7F1F6vBxr1nLfFvUBYeQpqtF3OwzOz@) ``` int c(int n){ // Method with integer as both parameter and return-type return n>0? // If `n` is larger than 0: --n%9 // Return `(n-1)%9 +1 // + 1 +c(n/9) // + recursive call with `(n-1)/9` *10 // multiplied by 10 : // Else: 0; // Return 0 } // End of method ``` [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), 76 bytes ``` [.,0]|until(.[0]<1;.[1]+=1|if"\(.[1])"|contains("0")then. else.[0]-=1end)[1] ``` Expanded ``` [.,0] # initial state (n, v) | until(.[0]<1; # until we've found n'th number .[1]+=1 # increment v | if "\(.[1])"|contains("0") # if v contains 0 then . # leave state alone else .[0]-=1 # otherwise decrement n end )[1] # return n'th number found ``` [Try it online!](https://tio.run/##FcvBCgIhFIXhVwlXSlfxtgii5knMxVBGhlynvNLGZx/H2Rz44Pyfb0c4wQXQAp7H2tadAetbJY5JGmf9Da/GoT9O2OJL3OUOJdojE8@RihRWKH4HMoeQStgLPWGgpxq/3te8cMxUutZUU9KRlsoDv/mvc@WBDQ "jq – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~68~~ 63 bytes -8 bytes thanks to @raznagul. ``` k=>{int i=0;for(;k>0;)if(!(++i+"").Contains("0"))k--;return i;} ``` [Try it online!](https://tio.run/##RY5NS8QwEIbP7a8Ye0roB11vEtuLsKcVBA8exEOIaR26m0BmVpHS314niHjIwAzP@z5x1LqY/O7OlgieUpyTvcBaFsSW0cFnxHd4tBgUccIwv76BTTPpjBTP38T@0h2vwd1j4AZkjDDBsC/DuMoCOPRmikmZZeyNxkndqLrGuqp09xADSy@pqq@0XtrWJM/XFADNthtpl7zY2BM7S55ggOC/4Pe6wqGB2wbuGjj0@fWw5Yy4vHUfoLI8R4X/r9BC/H1a9BTPvntJyP6EwatJZVBrU5bFVm77Dw "C# (.NET Core) – Try It Online") --- Don't really want to use this, since it's just a C# port of an existing answer. **[C# (.NET Core)](https://www.microsoft.com/net/core/platform), 45 bytes** ``` int c(int n){return n>0?--n%9+1+c(n/9)*10:0;} ``` [Try it online!](https://tio.run/##RY6xasNAEERr6Su2CdzFkn1KJ4skhVsHAi5ShBTHZiMf2Htwu7YxQt8un@wixU4xzLwdlBpjogkPXgQ@U@yTP8JQinoNOAVWQDMr2yGRnhIDv7n3uuandtEs0PCqtc@NW7tunMriUYNzDL/w4QMb0RS4//4Bn3qxGVwWRcZlQ0kUvZDAKzBd4OEO0FTwUkFbQePmczB2ufOXR3rcw33LXM35f4TNiWJ3FaXjchNZ4oGWXykobQOTQTMHre3y87Ecpxs "C# (.NET Core) – Try It Online") ]
[Question] [ # Intro Given radius \$r\$, draw a circle in the center of the screen. [Sandbox.](https://codegolf.meta.stackexchange.com/a/19221/80214) # The Challenge Here is a simple challenge. Plot a circle using the formula \$x^2+y^2=r^2\$, or any other formula that will plot a circle according to the given parameters. You may use any units that your language provides, so long as they are well defined and give consistent output. The circle must have it's center at the center of the canvas, and must have a padding of 5 units or more on all sides. The circle can have any fill that does not match the outline. You may have axes in the background of your plot. The outline of the circle must be solid (no gaps), and it must be visible. Here is an example: [![enter image description here](https://i.stack.imgur.com/G4M3q.png)](https://i.stack.imgur.com/G4M3q.png) Input can be taken in any acceptable form. (function params, variables, stdin...) Output can be in the form of a separate window, or an image format. Standard loopholes and rules apply. # Example Code (`Java + Processing`) ``` // Modified from the C language example from // https:// en.wikipedia.org/wiki/Midpoint_circle_algorithm int r = 70; //radius void settings() { size(2*r+10, 2*r+10); } void draw() { background(255); drawCircle(width/2, height/2, r, 60); save("Circle.png"); } void drawCircle(int x0, int y0, int radius, int angle) { int circCol = color(0, 0, 0); float limit = radians(angle); int x = radius; int y = 0; int err = 0; while (x >= y && atan2(y, x) < limit) { set(x0 + x, y0 + y, circCol); set(x0 + y, y0 + x, circCol); set(x0 - y, y0 + x, circCol); set(x0 - x, y0 + y, circCol); set(x0 - x, y0 - y, circCol); set(x0 - y, y0 - x, circCol); set(x0 + y, y0 - x, circCol); set(x0 + x, y0 - y, circCol); y += 1; if (err <= 0) { err += 2*y + 1; } if (err > 0) { x -= 1; err -= 2*x + 1; } } } ``` # Scoring This is a [graphical-output](/questions/tagged/graphical-output "show questions tagged 'graphical-output'") question. No ascii art. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). shortest answer in each language wins. [Answer] # [Desmos](https://www.desmos.com/calculator), 1 byte `r` [Try it on Desmos](https://www.desmos.com/calculator/catcq7tqc3) Uses the same input method as the other Desmos answer. An unused variable named `r` defaults to drawing a circle with radius r. [Answer] # [R](https://www.r-project.org/), ~~74~~ ~~70~~ ~~68~~ ~~65~~ 54 bytes *Edit: -11 bytes thanks to Giuseppe* ``` function(r)plot(r*1i^(1:1e3/99),,"l",l<-c(-r-5,r+5),l) ``` [Try it at rdrr.io](https://rdrr.io/snippets/embed/?code=plot_circle%3D%0Afunction(r)plot(r*1i%5E(1%3A1e3%2F99)%2Ct%3D%22l%22%2Cxlim%3Dl%3C-c(-r-5%2Cr%2B5)%2Cylim%3Dl)%0Aplot_circle(5)) I propose 3 possible answers to this challenge in [R](https://www.r-project.org/), of decreasing length but with increasing caveats. My favourite answer (above, using `plot`) is the ~~middle~~ shortest one of the 3. It plots a circle by calculating the complex coordinates of powers of `i`, using 396 points (with a bit of wrap-around). Here's an image of the output from `plot_circle(5)`: [![enter image description here](https://i.stack.imgur.com/IimRm.png)](https://i.stack.imgur.com/IimRm.png) --- For a 'true' circle (rather than an almost-circle with tiny straight-lines connecting the data points), we can use the `curve` function with a formula, but unfortunately we need to draw the positive & negative halves separately, so it ends up longer: # [R](https://www.r-project.org/), ~~86~~ 84 bytes ``` function(r){curve((r^2-x^2)^.5,xli=l<-c(-r-5,r+5),yli=l) curve(-(r^2-x^2)^.5,add=T)} ``` [Try it at rdrr.io](https://rdrr.io/snippets/embed/?code=plot_circle%3D%0Afunction(r)%7Bcurve((r%5E2-x%5E2)%5E.5%2Cxli%3Dl%3C-c(-r-5%2Cr%2B5)%2Cyli%3Dl)%0Acurve(-(r%5E2-x%5E2)%5E.5%2Cadd%3DT)%7D%0Aplot_circle(5)) --- ~~The shortest (that I can think of)~~ Previously the shortest, but - thanks to Giuseppe now no longer so - is to use the `circles` option of the `symbols` function, for only 56 bytes. However, this has the caveat that the circle symbols are always circular even if the plot is re-sized, and so may no-longer line-up with the y-axis. # [R](https://www.r-project.org/), ~~62~~ ~~58~~ 56 bytes ``` function(r)symbols(x=1,c=r,i=F,xli=l<-c(-r-4,r+6),yli=l) ``` [Try it at rdrr.io](https://rdrr.io/snippets/embed/?code=plot_circle%3D%0Afunction(r)symbols(x%3D1%2Cc%3Dr%2Ci%3DF%2Cxli%3Dl%3C-c(-r-4%2Cr%2B6)%2Cyli%3Dl)%0Aplot_circle(5)) [Answer] # Python 2 & 3, 55 bytes *-17 bytes thanks to @DigitalTrauma* *-1 byte thanks to @Sisyphus* *-2 bytes thanks to @ovs* ``` from turtle import* def f(r):sety(-r);clear();circle(r) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehpLSoJCdVITO3IL@oRIsrJTVNIU2jSNOqOLWkUkO3SNM6OSc1sUgDSGcWAZlAqf//AQ "Python 3 – Try It Online") [turtle](https://docs.python.org/3/library/turtle.html#turtle.circle) is standard library included in Python 2 & 3. I came up with `turtle` idea as a almost first result in Googling "[graphics python](https://www.google.com/search?q=graphics+python)". [Answer] # LaTeX, 66 bytes ``` \input tikz\def\f#1{~\vfill\centering\tikz\draw circle(#1);\vfill} ``` I consider the "canvas" required by this challenge to be the default text area of a latex page. The code defines a macro `\f` that takes the radius in cm as an argument. ## Example Code ``` \documentclass{article} \input tikz\def\f#1{~\vfill\centering\tikz\draw circle(#1);\vfill} \begin{document} \f{3} \enddocument ``` Outputs a PDF: [![enter image description here](https://i.stack.imgur.com/Ych9H.png)](https://i.stack.imgur.com/Ych9H.png) [Answer] # [SageMath](https://doc.sagemath.org/), 24 bytes ``` lambda r:circle((0,0),r) ``` [Try it online!](https://sagecell.sagemath.org/?z=eJxLs43hyknMTUpJVCiySs4sSs5J1dAw0DHQ1CnS5OJK0zDUBAC5NAlx&lang=sage&interacts=eJyLjgUAARUAuQ==) ### Example [![enter image description here](https://i.stack.imgur.com/5rrbT.png)](https://i.stack.imgur.com/5rrbT.png) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~169~~ ~~166~~ ~~161~~ 160 bytes Thanks to ceilingcat (x3) for the suggestions! I also changed the newlines in the header to spaces as they seem to work fine as separators (at least in Irfanview) and fixed a bug that got revealed when the array was put on the stack. Generates an image in PBM format, as it's probably the simplest way to make a bitmap! For some reason, all the online PBM viewers that I tried don't seem to like the output file, but Irfanview and GIMP are fine with it. ``` z;f(r,w){char s[(w=r*2+11)*w+1];float x=s[w*w]=!memset(s,48,w*w);for(;x<7;)s[z=round(sin(x+=1e-5)*r+r+5)+round(cos(x)*r+r+5)*w]=49;printf("P1 %d %d %s",w,w,s);} ``` [Try it online!](https://tio.run/##NY5NasMwEIX3PoWaUNCfSx0S0qIoZ@jeZKHKliOQraJRKpOQq1dVXMq8xbxvmJmn60HrnK/C4MATuemzCghanGSgG9Y0hCbWnIRxXkU0S2gTTSf5NPYj9BED377xQogwPmAxH/aCQHuVwV@mDoOd8Mxk09c7QgMLbEfY30R7wPM/exzcvouvYKdo8OqjQc/dIljxVAqIuOe1nbS7dD06QOyc/Xw5H6uqLKBRlS@PRoVBc7Tkp7SYb4JuFUIGq@gtpowtjIjqnvPm9UcbpwbItRtznX4B "C (gcc) – Try It Online") [Answer] # T-SQL, 47 bytes ``` SELECT geometry::Point(0,0,0).STBuffer(r)FROM t ``` Input is taken via a pre-existing table *t* with float field *r*, [per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). Uses SQL [geo-spatial functions](https://docs.microsoft.com/en-us/sql/relational-databases/spatial/spatial-data-sql-server?view=sql-server-2017), displayed in the SQL Management Studio results pane: [![enter image description here](https://i.stack.imgur.com/06oFV.png)](https://i.stack.imgur.com/06oFV.png) [Answer] ## JavaScript (ES6), 96 bytes ``` f= v=>`<svg width=${s=v*2+12} height=${s}><circle r=${v} cx=${v+=6} cy=${v} stroke=#000 fill=none>` ``` ``` <input type=number min=1 oninput=o.innerHTML=f(+this.value)><div id=o> ``` Outputs an SVG(HTML5) image, which the snippet displays for you. If HTML5 is acceptable, then for 95 bytes: ``` f= v=>`<div style="width:${v*=2}px;height:${v}px;margin:6px;border:1px solid;border-radius:100%">` ``` ``` <input type=number min=1 oninput=o.innerHTML=f(+this.value)><div id=o> ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 16 bytes ``` Graphics@*Circle ``` See [Wolfram documentation on Circle](https://reference.wolfram.com/language/ref/Circle.html) for example here is a circle with center (0,0) and radius r=42 [![enter image description here](https://i.stack.imgur.com/5f9Kf.png)](https://i.stack.imgur.com/5f9Kf.png) -6 bytes from @LegionMammal978 [Answer] # MATLAB, ~~38~~ 37 bytes *-1 byte thanks to Tom Carpenter* ``` ezpolar(@(x)r);axis((r+5)*cospi(1:4)) ``` Input as variable `r` in workspace. Output: [![output](https://i.stack.imgur.com/NKoPp.png)](https://i.stack.imgur.com/NKoPp.png) [Answer] ## [<>^v](https://github.com/Astroide/---v#v), 56 bytes ``` ƒ∆57±∑361i∆90v v 0Ii(I< ª < ] ^ >¶° ^ >1 æ∑ ^ ``` #### Explanation `ƒ` : toggle turtle visibility `∆` : raise pen `57`: push 57 `±` : negate `∑` : turtle forward by top of stack `361`: push 361 (360 + 1) `i` : pop stack & store in variable `i` `∆` : lower pen `90`: push 90 `v` : send instruction pointer down `<` : send instruction pointer left `ª` : turtle rotate right by top of stack (90) **start of loop** `<` : send instruction pointer left `I` : push value of variable `i` `(` : decrement top of stack `i` : pop & store in variable `i` `I` : push value of variable `i` `0` : push 0 `v` : send instruction pointer down `]` : if top of stack is greater than or equal to second element of stack\ * `>` : send instruction pointer right * `¶` : update display * continue to **continue here**\ Else `>` : send instruction pointer right `1`: push 1 `æ` : turn left (top of stack) degrees `∑` : go forward by top of stack `^` : send instruction pointer up **continue here** `^` : send instruction pointer up `^` : Idem, there to ensure trailing whitespace is not removed go to **start of loop** After drawing the circle, the program never halts to prevent the window from closing. Screenshot below (Python Turtle Graphics is because the program does not set a title to the window and the interpreter is written in Python and uses Turtle for graphics) : [![screenshot](https://i.stack.imgur.com/tRZtd.png)](https://i.stack.imgur.com/tRZtd.png) [Answer] # Desmos, ~~12~~ 10 bytes ``` xx+yy=rr r ``` [Desmos it](https://www.desmos.com/calculator/ggztyhdfmz) [Answer] # TI-Basic, ~~11~~ ~~8~~ 7 [bytes](https://codegolf.meta.stackexchange.com/a/4764/98541) ``` Polar Input r₁ ZSquare ``` Input is a string, and is stored as a function. This function is shown in polar coordinates, so it shows as a circle. Output for `"4`: [![sniping target XD](https://i.stack.imgur.com/MW2eG.png)](https://i.stack.imgur.com/MW2eG.png) [Answer] # Java 8, ~~141~~ 123 bytes ``` import java.awt.*;r->new Frame(){{setSize(2*r+26,2*r+56);show();}public void paint(Graphics g){g.drawOval(13,43,2*r,2*r);}} ``` Output for \$n=100\$ (the second picture with added light grey background color is to verify the top padding): [![enter image description here](https://i.stack.imgur.com/IZdCQ.png)](https://i.stack.imgur.com/IZdCQ.png) [![enter image description here](https://i.stack.imgur.com/azHEI.png)](https://i.stack.imgur.com/azHEI.png) **Explanation:** ``` import java.awt.*; // Required import for Frame and Graphics r-> // Method with integer parameter and Frame return-type new Frame(){ // Create the Frame { // In an inner code-block: setSize(2*r // Set the width to 2 times the radius-input +26 // + 2 times 8 pixels for the frame borders // + 2 times 5 pixels for the required padding 2*r // Set the height to 2 times the radius-input +56); // + 2 times 8 pixels for the frame borders // + 30 pixels for the frame title-bar // + 2 times 5 pixels for the required padding show();} // And show the Frame at the end public void paint(Graphics g){ // Overwrite its paint method to draw on g.drawOval(13,43, // With 5,5 for the required padding as top-left // x,y-coordinate of the surrounding rectangle + the same 8+30 // pixels adjustment for the frame and frame title-bar, 2*r,2*r);}} // draw the circle with a size of 2 times the radius-input ``` Note: I cannot use `(r*=2),r,r,r` instead of `2*r,2*r,2*r,2*r` to save (3) bytes, because `r` has to be effectively final inside the inner Frame-class. [Answer] # [Red](http://www.red-lang.org), 74 bytes -16 bytes thanbks to Aaron Miller! ``` func[r][d: r + 5 view compose/deep[base(2x2 * d)draw[circle(1x1 * d)(r)]]] ``` # [Red](http://www.red-lang.org), 90 bytes ``` func[r][d: r + 5 view compose/deep[base(as-pair d * 2 d * 2)draw[circle(as-pair d d)(r)]]] ``` `f 200` [![enter image description here](https://i.stack.imgur.com/6wru6.png)](https://i.stack.imgur.com/6wru6.png) [Answer] # [JavaScript (V8)](https://v8.dev/), 158 bytes ``` r=>document.write(`<p style="border-radius:50%;border:solid;position:fixed;width:${r*2}px;height:${r*2}px;top:50%;left:50%;transform:translate(-50%,-50%);">`) ``` [Try it online!](https://tio.run/##RY1dCsIwEISvIkXBihURBElsz9LYJHYlzYbN9kfEs8daH3wZvpmBmYcaVGwIAhfDJdkyUVlpbPrOeD6MBGy29TWsIj@dKbMbkjZUkNLQR3E@buQvEREdaBkwAgN6YWEyWo6guRXrF@1O7zDJ1sC95b9nDMuEM5YXYFI@WqROLOTUfF7Mxf4rucyqOk/pAw "JavaScript (V8) – Try It Online") [jsfiddle](https://jsfiddle.net/ftyLdw70/) thanks to @Razetime * Saved 1 thanks to @Razetime * Saved 2 using template literals Writes directly to the HTML a `p` element fixed positioned, centered with border radius 50% [Answer] ## Shadertoy (GLSL), 142 bytes ``` void mainImage(out vec4 f,in vec2 v){vec2 S=iResolution.xy;vec2 u=v/S-vec2(0.5);u.y/=S.x/S.y;vec4 c;if(abs(length(u)-0.2)<8e-4)c=vec4(1);f=c;} ``` [Shadertoy link](https://www.shadertoy.com/view/3ddcD8) Output: [![enter image description here](https://i.stack.imgur.com/osmiT.png)](https://i.stack.imgur.com/osmiT.png) [Answer] # [Red](http://www.red-lang.org), ~~96~~ ~~92~~ 87 bytes *Forgot to remove some extra whitespace for -4 bytes.* *-5 bytes by using shorter type conversions and initializing and using `x` at the same time.* ``` draw to-pair x: r * 9 to-block append"circle "append mold to-pair x / 2 append" "mold r ``` No TIO link because `draw` doesn't seem to be implemented on TIO. However, you can copy [this](https://gist.github.com/AMiller42/e8477ef6ec0e4665c7996d5b8df72949) into the Red offline interpreter to output an image. The first line is for defining a variable to be used for the canvas size. Multiplying by 9 might be a bit overkill, but it ensures enough padding around the circle. I couldn't figure out how to use variables in the block, so the second line builds the draw command bit by bit, essentially building the command `draw {x}x{x} [circle {x / 2}x{x / 2} {r}]`. Example output for \$r = 10\$: [![enter image description here](https://i.stack.imgur.com/YRaD8.png)](https://i.stack.imgur.com/YRaD8.png) [Answer] # [Red](http://www.red-lang.org), 59 57 55 51 byte ``` func[r][?(draw 2 * c: 5x5 + r reduce['circle c r])] ``` Try it [locally](https://www.red-lang.org/p/download.html). -2 bytes thanks to [Aaron Miller](https://chat.stackexchange.com/users/504997) spotting superfluous `as-pair`. --- Output for \$r=50\$: [![enter image description here](https://i.stack.imgur.com/7zCEg.png)](https://i.stack.imgur.com/7zCEg.png) [Answer] # Python + pygame, 110 bytes ``` r=int(input()) d=display s=5+r draw.circle(d.set_mode([s+s]*2),[99]*3,[s]*2,r,1) d.update() ``` We only use `set_mode` once, so we can pass it as an argument to `draw.circle`. It's almost impossible to golf in Pygame so this is probably the shortest it can get, although I could change `99` to 9. Example for 250: [![enter image description here](https://i.stack.imgur.com/KknRi.png)](https://i.stack.imgur.com/KknRi.png) [Answer] # 80186 DOS machine code, ~~76~~ ~~74~~ ~~72~~ 71 bytes ``` 00000000: b8 13 00 cd 10 1e 68 00 a0 1f f7 df 8d 6d 02 01 ......h......m.. 00000010: fd 31 c0 f7 df e8 20 00 f7 df 97 e8 1a 00 89 eb .1.... ......... 00000020: 39 df e8 0a 00 97 39 fb e8 04 00 75 e6 1f 7c 06 9.....9....u..|. 00000030: 01 fd 8d 6b 03 47 c3 e8 00 00 69 d8 40 01 fe 81 ...k.G....i.@... 00000040: a0 7d f7 df f7 d8 c3 .}..... ``` A function which expects the radius in `di`. Forces DOS to graphics mode and doesn't bother to clean up. I am mostly just excited about getting it working, I will hopefully find some ways to optimize. Translation of the Go version of the Midpoint circle algorithm from [Rosetta Code](http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm#Go). * 2 bytes: branch once in `correct` instead of branching twice in the main function * 2 bytes: reuse flags from `inc` for loop trigger. * 1 byte: Fall through to `correct` when returning. #### Commented assembly ``` ; nasm file.asm -f obj -o file.obj [cpu 186] global draw_circle ; args: di: radius draw_circle: ; switch DOS to graphics mode mov ax, 0x0013 int 0x10 ; set ds to point to the screen buffer push ds push 0xA000 pop ds ; http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm#Go ; di => x1 neg di ; bp => err lea bp, [2 + di] add bp, di ; ax => y1 xor ax, ax .loop: neg di ; x - x1, y + y1 ; x + x1, y - y1 call set_pixel neg di ; swap xchg ax, di ; x + y1, y + x1 ; x - y1, y - x1 call set_pixel ; ax: x1, di: y1 ; save err to bx mov bx, bp ; check y1 ; we branch in correct cmp di, bx call correct ; swap back xchg ax, di ; check x1, using the opposite order cmp bx, di call correct ; loop while x1 is negative ; the flags will be set from correct jnz .loop ; restore ds segment pop ds ; uncomment to wait for enter then switch to ; standard mode ; mov ah, 0x08 ; int 0x21 ; mov ax, 0x0003 ; int 0x10 ; Fallthrough to exit ; some helper functions to cut down the copy-paste correct: ; The flags will be set to the comparison before ; calling jl .skip ; err += 2 * ++di + 1 add bp, di lea bp, [bp + di + 3] ; ++di inc di .skip: ret ; ax: y, di: x set_pixel: ; run twice by semi-recursion call .semirecurse .semirecurse: ; ++byte[x + 160 + (320 * (y + 100))] imul bx, ax, 320 inc byte[di + bx + 0x7DA0] ; negate both here neg di neg ax ret ``` with radius = 50, showing the disgusting exit: [![enter image description here](https://i.stack.imgur.com/sBlyn.png)](https://i.stack.imgur.com/sBlyn.png) [Answer] # Desmos, ~~10~~ 12 bytes ``` xx+yy=rr r=1 ``` [Desmos it](https://www.desmos.com/calculator/ggztyhdfmz) [Answer] # [Perl 5](https://www.perl.org/), 92 bytes ``` $r=$_; $w=$r*2+11; $_="P1 $w $w @{[map{($_%$w-$r-5)**2+($_/$w-$r-5)**2<$r**2?1:0}0..$w**2-1]}" ``` [Try it online!](https://tio.run/##K0gtyjH9/1@lyFYl3lql3FalSMtI29DQWiXeVinAUEGlHIQcqqNzEwuqNVTiVVXKdVWKdE01tYDKgHx9JL4NUK@Wkb2hlUGtgZ6eSjmQo2sYW6v0/7@h6b/8gpLM/Lzi/7oFAA "Perl 5 – Try It Online") Circle with black filling. Put the 92 bytes above into program.pl and run like this: ``` echo 50 | perl -p program.pl > circle.pbm # radius 50 feh circle.pbm # view with feh or other image viewer ``` [Answer] # [PHP](https://php.net/), 131 bytes ``` ($f=imagecolorallocate)($i=imagecreate($d=10+$argn*2,$d),0,0,0);imageellipse($i,$d/2,$d/2,$d-10,$d-10,$f($i,9,9,9));imagepng($i,a); ``` [Try it online!](https://tio.run/##NYtbCoMwEEU3Mx8ZH5gI/RCVrmXQJA2MZki7/zQR5cKB@5KP5OUthQrcGg7ydoscEzHHjX4WFYQ7TrZ4BftqdAuU/NmMHezY6Sqcr5FlDvItq1CqYXzQG/3Q1W6qwvsjp68Z4ZzzS/8B "PHP – Try It Online") Actually you cannot run it in online PHP testers because they disable the image functions. Saves the image in a file named "a". One byte could be saved using `imagegd` but I didn't know the "gd" format and couldn't open it to check if it works. The circle is in very dark grey, but I consider it visible. If you don't, leave a comment and I'll edit, with one byte more `$f($i,99,0,0)` it's much clearer. with `$f($i,9,9,9)`: [![enter image description here](https://i.stack.imgur.com/EKw7o.png)](https://i.stack.imgur.com/EKw7o.png) with `$f($i,99,0,0)`: [![enter image description here](https://i.stack.imgur.com/Hxa5r.png)](https://i.stack.imgur.com/Hxa5r.png) [Answer] # Swift, entire iOS app, 152 bytes `project.pbxproj` not included. ``` import SwiftUI @main struct A:App{@State var s="1" var body:some Scene{WindowGroup{VStack{TextField("",text:$s) Circle().frame(width:.init(Int(s)!))}}}} ``` The unit for the radius is 0.5pt, which is either 1px or 1.5px depending on the device. The app crashes if you type something that isn't an integer. Preview, with a radius of 50pt: ![1](https://i.stack.imgur.com/MF7VP.png) ### Ungolfed ``` import SwiftUI @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @State private var text = "1" var body: some View { VStack { TextField("", text: $text) Circle() .frame(width: CGFloat(Int(text)!)) } } } ``` [Answer] ## [ZX Spectrum BASIC](https://worldofspectrum.org/ZXBasicManual/zxmanchap17.html), 1, 3 or 6 bytes Nothing beats BASIC computers with bitmap graphics that consider a case of honour to implement the built in CIRCLE command... `CIRCLE x,y,r` The command takes just one byte (though it is printed as the whole word), depending on what and how do you count the size, it can be 1 byte (the command itself), 3 bytes (the command and obligatory commas separating the articles; note that the space is only visual), 6 bytes (the command, commas and three already defined variables (or `PI`)). [![CIRCLE](https://i.stack.imgur.com/fP0Qp.png)](https://i.stack.imgur.com/fP0Qp.png) [Answer] ## PostScript, 69 bytes ``` currentpagedevice/PageSize get{2 div}forall 3 2 roll 0 360 arc stroke ``` Pass the radius on the command line: ``` gs -c 150 -- circle.ps ``` Displays output in a window, which then immediately closes! Add `showpage` for a persistent window. Centering the output took more bytes than I had hoped... [Answer] # HTML + Javascript, 98 ## JavaScript: 85, HTML: 13 ``` F=r=>{C.width=C.height=r*2+16;c=C.getContext`2d`;c.arc(r+8,r+8,r,0,6.283);c.stroke()} F(100) ``` ``` <canvas id=C> ``` To change r, change `r=100` to `r=/*place your value here*/`. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~132~~ 128 bytes *-4 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* ``` main(r,w,i,j){scanf("%d",&r);i=w=r+9;for(printf("P5\n%d%1$d\n1\n",2*w);i--+w;)for(j=w;j--+w;)putchar(abs((i*i+j*j)*2-r*r)<2*r);} ``` [Try it online!](https://tio.run/##JYpLCsIwFADvEqzkCzbiQmLu4AGyiQnVF/C1vFayEM8eI24Ghplk7im19oyAnHTVoIt4rynixNmQmd6TcOCrJ3V200x8IcCtt@sp4JCHcZcDjgGZtrL20xhVnfiNxVdX/rq8tvSIxONt5RwkqCKLkNaQJHGxHe7T2vHwBQ "C (gcc) – Try It Online") Outputs a [PGM](http://netpbm.sourceforge.net/doc/pgm.html) image. A unit corresponds to `sqrt(2)` pixels. [Answer] ## Applesoft BASIC, 106 bytes ``` 0INPUTR 1HGR 2HCOLOR=3 3D=0 4HPLOTR*COS(D)+140,R*SIN(D)+96TOR*COS(D+.1)+140,R*SIN(D+.1)+96 5D=D+0.1 6GOTO4 ``` ]
[Question] [ You must fill an array with every number from `0-n` inclusive. No numbers should repeat. However they must be in a random order. # Rules All standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules and standard loopholes are banned The array must be generated pseudo-randomly. Every possible permutation should have a equal probability. # Input `n` in any way allowed in the I/O post on meta. # Output The array of numbers scrambled from `0-n` inclusive. [Answer] # [Perl 6](https://perl6.org), 14 bytes ``` {pick *,0..$_} ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLzk9JVbD9X12QmZytoKVjoKenEl/7vzixUgEsY/r/a16@bnJickYqAA "Perl 6 – TIO Nexus") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 pick # choose randomly without repeats *, # Whatever (all) 0 .. $_ # Range from 0, to the input (inclusive) } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` Ý.r ``` [Try it online!](https://tio.run/nexus/05ab1e#@394rl7R//@WX/PydZMTkzNSAQ "05AB1E – TIO Nexus") ``` Ý # Make a list from 0 to input .r # Shuffle it randomly ``` [Answer] # Pyth, 3 bytes ``` .Sh ``` [Demonstration](https://pyth.herokuapp.com/?code=.Sh&input=10&debug=0) `.S` is shuffle. It implicitly casts an input integer `n` to the range `[0, 1, ..., n-1]`. `h` is `+1`, and the input is taken implicitly. [Answer] # [R](https://www.r-project.org/), 16 bytes ``` sample(0:scan()) ``` reads from `stdin`. `sample` randomly samples from the input vector, returning a (pseudo)random sequence. [Try it online!](https://tio.run/nexus/r#@1@cmFuQk6phYFWcnJinoan539DgPwA "R – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` 0rẊ ``` [Try it online!](https://tio.run/nexus/jelly#@29Q9HBX1////02/5uXrJicmZ6QCAA "Jelly – TIO Nexus") **Explanaion:** ``` 0rẊ 0r Inclusive range 0 to input. Ẋ Shuffle. Implicit print. ``` ## Alternate solution, 3 bytes ``` ‘ḶẊ ``` **Explanation:** ``` ‘ḶẊ ‘ Input +1 Ḷ Range 0 to argument. Ẋ Shuffle. ``` [Try it online!](https://tio.run/nexus/jelly#@/@oYcbDHdse7ur6//@/6de8fN3kxOSMVAA "Jelly – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), 51 bytes ``` lambda n:sample(range(n+1),n+1) from random import* ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQZ1WcmFuQk6pRlJiXnqqRp22oqQMiuNKK8nMVgIIpQCoztyC/qETrf0FRZl6JQpqGqSYXjGlogMQ21fz/NS9fNzkxOSMVAA "Python 2 – TIO Nexus") There is `random.shuffle()` but it modifies the argument in place instead of returning it... [Answer] # PHP, 42 Bytes ``` $r=range(0,$argn);shuffle($r);print_r($r); ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zNTQwsP6vUmRblJiXnqphoAMW1bQuzihNS8tJ1VAp0rQuKMrMK4kvArP//wcA "PHP – TIO Nexus") [Answer] # Bash, ~~18~~ 11 bytes ``` shuf -i0-$1 ``` [Try it online!](https://tio.run/##S0oszvj/vzijNE1BN9NAV8Xw////hgYA) [Answer] # Mathematica, 24 bytes ``` RandomSample@Range[0,#]& ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 4 bytes ``` QZ@q ``` [Try it online!](https://tio.run/nexus/matl#@x8Y5VD4/7@hwde8fN3kxOSMVAA "MATL – TIO Nexus") ### Explanation ``` Q % Implicitly input n. Add 1 Z@ % Random permutation of [1 2 ... n+1] q % Subtract 1, element-wise. Implicitly display ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes ``` ⟦ṣ ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9o/rKHOxf//29o/D/qa16@bnJickYqAA "Brachylog – TIO Nexus") ### Explanation ``` ⟦ Range from 0 to Input ṣ Shuffle ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 4 bytes ``` ò öx ``` [Try it online](http://ethproductions.github.io/japt/?v=1.4.4&code=8iD2eA==&input=NQ==) --- ``` :Implicit input of integer U ò :Generate array of 0 to U. öx :Generate random permutation of array. :Implicit output of result. ``` [Answer] # C#, 76 bytes ``` using System.Linq;i=>new int[i+1].Select(x=>i--).OrderBy(x=>Guid.NewGuid()); ``` This returns an IOrderedEnumerable, I hope that's okay, or else I need a few more bytes for a .ToArray() [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~7~~ 6 bytes *1 byte removed thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer).* ``` {),mr} ``` This is an anonymous block (function) that takes an integer from the stack and replaces it with the result. **[Try it online!](https://tio.run/nexus/cjam#K8pUgIBUZYWg1MQUhcy8ktT01KL/1Zo6uUW1/@sKEPKuFanJyaUlqQpJOfnJ2XoKwSVFmXnpCkWpBUWpxal5JYklmfl5CvlpQJHi0pyS/6Zf8/J1kxOTM1IB "CJam – TIO Nexus")** ### Explanation ``` { e# Begin block ) e# Increment: n+1 , e# Range: [0 1 ... n] mr e# Shuffle } e# End block ``` [Answer] # Java 8, ~~114~~ ~~111~~ 97 bytes ``` import java.util.*;n->{List l=new Stack();for(;n>=0;l.add(n--));Collections.shuffle(l);return l;} ``` -3 bytes and bug-fixed thanks to *@OlivierGrégoire*. -4 bytes thanks to *@Jakob*. -10 bytes by removing `.toArray()`. **Explanation:** [Try it here.](https://tio.run/##nY69bsMwDIR3PwVHqYAUdwg6CM6StQ0KeCw6KLLcyJEpQ6JSBIGf3VV@xnYpQA68O@K7QZ@0CJPFoTsubpxCJBiKJjM5L58UAKxW8K6LHHqgg4X9mawwISNVlfE6JXjTDi8VgEOysdfGwu56Ary6RGBY0QG5KtJctkwiTc7ADhAaWFBsLrekb9B@Q0vaHBlXfYhM4aaplZe66xgKwbnaBu@tIRcwyXTIfe8t81xFSzkieDUv6s6Y8t4XxgN1Cq6DsfRkLUWHXx@foPm9ZHtOZEcZMsmpWOSRoTTsuea3yr8G/naury/rf7@u6wd2rublBw) ``` import java.util.*; // Required import for List, Stack and Collections n->{ // Method with integer parameter and Object-array return-type List l=new Stack(); // Initialize a List for(;n>=0;l.add(n--)); // Loop to fill the list with 0 through `n` Collections.shuffle(l); // Randomly shuffle the List return l; // Convert the List to an Object-array and return it } // End of method ``` [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), 2 bytes ``` #╟ ``` [Try it online!](https://tio.run/nexus/ohm#@6/8aOr8//8tAQ "Ohm – TIO Nexus") [Answer] # Pyth, 4 Bytes ``` .S}0 ``` [Try it here!](https://pyth.herokuapp.com/?code=.S%7D0&input=5&debug=0) [Answer] # C, 75 bytes ``` a[99],z,y;f(n){if(n){a[n]=--n;f(n);z=a[n];a[n]=a[y=rand()%(n+1)];a[y]=z;}} ``` Recursive function that initializes from the array's end on the way in, and swaps with a random element before it on the way out. [Answer] # Ruby, 20 bytes `->n{[*0..n].shuffle}` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` A…·⁰NβFβ«AβδA‽δθPIθ↓A⟦⟧βFδ¿⁻θκ⊞βκ ``` [Try it online!](https://tio.run/nexus/charcoal#TY27DoIwFIZneYoznpOUxMVFJ6MLA8a4Ggd6ARugJbTFwfjstaAmjv/lyxf3zunGYGFEF5ye1KUyjcI1g8IMwZ9Cz9WIRAw47bLajoCc4JmtvhxnINPwi4mWtkeZ/mKuy9B5PYzaeDxUzqOgpbWTwu3RPswfer19HKtFIgl0DVhqExwKBi0RnIO7z8I2vV4xbmI@xdx1bw "Charcoal – TIO Nexus") Link is to verbose version of code. Apparently it takes 17 bytes to remove an element from a list in Charcoal. Edit: These days it only takes three bytes, assuming you want to remove all occurrences of the item from the list. This plus other Charcoal changes cut the answer down to 21 bytes: [Try it online!](https://tio.run/##LYw9C8IwFADn9leETi@QgouTU8cuIrq6pEloAumr@aqD@NufKXY97k5ZGdUqPdGQkpsRRlS@JLeZu8TZwEmwEV8lX8symQicCxb4pX1b5w2DwNmnbY6yBnpdKhPMVqW5RYcZBq3BCtY9seM7PeRHmXKUKkPY7f/0S3SmfqM@@R8 "Charcoal – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 5 bytes ``` ?⍨1+⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/x2BpP2j3hWG2o@6Fv3/76hgCgA "APL (Dyalog Unicode) – Try It Online") Assumes `⎕IO←0`, which is default on many machines. ### Explanation `⊢` the right argument `1+` add 1 to it `?⍨` generate numbers 0 .. `1+⊢`-1 and randomly deal them in an array so that no two numbers repeat [Answer] # q/kdb+, 11 bytes **Solution:** ``` {(0-x)?1+x} ``` **Example:** ``` q){(0-x)?1+x}10 5 9 7 1 2 4 8 0 3 10 q){(0-x)?1+x}10 6 10 2 8 4 5 9 0 7 3 q){(0-x)?1+x}10 9 6 4 1 10 8 2 7 0 5 ``` **Explanation:** Use the `?` [operator](http://code.kx.com/wiki/Reference/QuestionSymbol) with a negative input to give the full list of `0->n` without duplicates: ``` {(0-x)?1+x} / solution { } / lambda expression x / implicit input 1+ / add one ? / rand (0-x) / negate x, 'dont put item back in the bag' ``` [Answer] # TI-83 BASIC, 5 bytes (boring) ``` randIntNoRep(0,Ans ``` Yep, a builtin. `randIntNoRep(` is a two-byte token, and `Ans` is one byte. ### More fun, 34 bytes: ``` Ans→N seq(X,X,0,N→L₁ rand(N+1→L₂ SortA(L₂,L₁ L₁ ``` Straight from [tibasicdev](http://tibasicdev.wikidot.com/randintnorep). Probably golfable, but I haven't found anything yet. What this does: Sorts a random array, moving elements of the second arg (`L₁` here) in the same way as their corresponding elements. [Answer] # JavaScript (ES6), 51 bytes ``` n=>[...Array(n+1).keys()].sort(_=>.5-Math.random()) ``` [Answer] # [Aceto](https://github.com/aceto/aceto), ~~15~~ ~~14~~ 16 bytes ``` @lXp Y!`n zi& 0r ``` Push zero on the stack, read an integer, construct a range and shuffle it: ``` Y zi 0r ``` Set a catch mark, test length for 0, and (in that case) exit: ``` @lX !` ``` Else print the value, a newline, and jump back to the length test: ``` p n & ``` *(I had to change the code because I realized I misread the question and had constructed a range from 1-n, not 0-n.)* [Answer] # [Go](https://golang.org/), 92 bytes Mostly losing to the need to seed the PRNG. ``` import(."fmt";."math/rand";."time") func f(n int){Seed(Now().UnixNano());Println(Perm(n+1))} ``` [Try it online!](https://tio.run/nexus/go#PY3BCsIwEETv/YqQ0y5itAdP/YdSED9gSRMbdDclRBRKP9tzTEWc05sZhpnJ3ujqFFOQEniOKYPRnrPujGbK0yGRjJvJgZ3Gxj/EKg@igmRczs6N0McnoLlIePUkERC7IdX2LjC4xCC7FnEt3@F2A7g0qsrDCX/QHv9Us7W8Je4t2cl9AA "Go – TIO Nexus") [Answer] # [8th](http://8th-dev.com/), ~~42~~ ~~36~~ 34 bytes **Code** ``` >r [] ' a:push 0 r> loop a:shuffle ``` SED (Stack Effect Diagram) is `n -- a` **Usage and example** ``` ok> 5 >r [] ' a:push 0 r> loop a:shuffle . [2,5,0,3,1,4] ``` [Answer] # Javascript (ES6), 68 bytes ``` n=>[...Array(n+1)].map((n,i)=>[Math.random(),i]).sort().map(n=>n[1]) ``` Creates an array of form ``` [[Math.random(), 0], [Math.random(), 1], [Math.random(), 2],...] ``` Then sorts it and returns the last elements in the new order [Answer] # J, 11 Bytes ``` (?@!A.i.)>: ``` ### Explanation: ``` >: | Increment (?@!A.i.) | Fork, (f g h) n is evaluated as (f n) g (h n) i. | Integers in range [0,n) inclusive ?@! | Random integer in the range [0, n!) A. | Permute right argument according to left ``` Examples: ``` 0 A. i.>:5 0 1 2 3 4 5 1 A. i.>:5 0 1 2 3 5 4 (?@!A.i.)>: 5 2 3 5 1 0 4 (?@!A.i.)>: 5 0 3 5 1 2 4 ``` [Answer] # JavaScript ES6, 60 bytes, uniform distribute ``` f=n=>n?(z=f(n-1),z[n]=z[y=Math.random()*-~n|0],z[y]=n,z):[0] s={}; for(i=0; i<1000; i++) k=f(2), s[k]=-~s[k]; for(i in s) console.log(i, s[i]); ``` ]
[Question] [ # Task Write a program/function that when given three 2d points in [cartesian coordinates](https://en.wikipedia.org/wiki/Cartesian_coordinate_system) as input outputs a truthy value if they are [collinear](https://en.wikipedia.org/wiki/Collinearity) otherwise a falsey value Three points are said to be collinear if there exists a straight line that passes through all the points You may assume that the coordinates of the three points are integers and that the three points are distinct. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest bytes wins # Sample Testcases ``` (1, 1), (2, 2), (3, 3) -> Truthy (1, 1), (2, 2), (10, 10) -> Truthy (10, 1), (10, 2), (10, 3) -> Truthy (1, 10), (2, 10), (3, 10) -> Truthy (1, 1), (2, 2), (3, 4) -> Falsey (1, 1), (2, 0), (2, 2) -> Falsey (-5, 70), (2, 0), (-1, 30) -> Truthy (460, 2363), (1127, 2392), (-1334, 2285) -> Truthy (-789, -215), (-753, -110), (518, -780) -> Falsey (227816082, 4430300), (121709952, 3976855), (127369710, 4001042) -> Truthy (641027, 3459466), (475989, 3458761), (-675960, 3453838) -> Falsey ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 21 bytes Takes a matrix `[x1, y1; x2, y2; x3, y3]` as input. ``` @(a)~det([a,[1;1;1]]) ``` [Try it online!](https://tio.run/##JY87CsNADET7nGJLG2yjv7QsgdzDuDD5tGlCylzd0WLUjJ5GjPS@f/bv83iV67Isx23Yx9/j@RnWfVqxZW3beLyGVQymQmzcCiJ515VamZFZsqHQbbykb/aoU5kJNYeunBoRWlGMlB5w2og80CBoKiIMDGlBQodaNRlXt1DtzNmqY4YLAILQuW@C0K9g0SpmrYhr7ckJwg0z3JL0o5NwcOQbfw "Octave – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 39 bytes ``` (a,b,c,d,e,f)=>a*d+c*f+e*b==b*c+d*e+f*a ``` [Try it online!](https://tio.run/##jZHdatwwEIXv/RRDrmR7tNG/ZIKTi8I@Qe66hdXacrtliYPthITSZ99KWmjXpJQajDWHb@Yca777Vz930/F5oU9jH87b9kw8HrDDHgMOZXvvq77uqqEO1aFtD1VX91Woh8qfX/0ES5iXT34OM7SwJxyBlwhEIIj0lQiyBHoPj9PL8u29@ABwFgX2TyTOUBnY@tMc1gD7DV4DVCNYdo3Q2CPXNspEayGNzDG4sKlqxIWWUsVSOL1qodY1CFRwnSmrYzTKeXbQ3MXCOrZKIoR13DAXcyglmWSZ5YJb1jQ6qrKxxml9Ua00jU03ohjjTImVuVGcpZBS6UYZkzqU1U1KFCVnTb4TaqKW/ixq0kl3lWa/mZ9Px2Vf7O@KYhgnIGl/RxiHP0ss4UcB8fmM4BEOCB1CjxAQBoTpS9zx7Y4Q@rDr6@yWD7t4/H81BSKb8nYT3kJHjuVdNpzi6Pi2cPN4c1G68WkeT2FzGr@Sv2RB2H6Qyzjs5/kX "JavaScript (Node.js) – Try It Online") Accepts input as `(x1, y1, x2, y2, x3, y3)`. Uses the shoelace formula to determine if the enclosed area is 0. ### Explanation The [shoelace formula](https://en.wikipedia.org/wiki/Shoelace_formula) states that, the area of a polygon can be calculated using the coordinates of its vertices. Specifically, assuming the vertices are \$P\_1, P\_2, \cdots, P\_n\$ so that \$P\_1P\_2, P\_2P\_3, \cdots, P\_{n-1}P\_n, P\_nP\_1\$ are the edges of the polygon, then the area \$A\$ can be calculated with $$A=\frac{1}{2}\left|(x\_1y\_2+x\_2 y\_3+\cdots+x\_{n-1}y\_n+x\_ny\_1)-(y\_1x\_2+y\_2x\_3 +\cdots+y\_{n-1}x\_n+y\_nx\_1)\right|$$ where \$(x\_n,y\_n)\$ are the coordinates of \$P\_n\$. Taking \$n=3\$, we have the formula for the area of a triangle with coordinates \$(x\_1,y\_1)\$, \$(x\_2,y\_2)\$ and \$(x\_3,y\_3)\$: $$A=\frac{1}{2}\left|(x\_1y\_2+x\_2y\_3+x\_3y\_1)-(y\_1x\_2+y\_2x\_3+y\_3x\_1)\right|$$ Three points are collinear if and only if the triangle constructed by these points has a zero area (otherwise, one of the points lies away from the line segment between the other two points, giving a non-zero area to the triangle). Since we only need to check whether the area is 0, the 1/2 and the absolute can be ignored. This boils down to checking whether $$(x\_1y\_2+x\_2y\_3+x\_3y\_1)-(y\_1x\_2+y\_2x\_3+y\_3x\_1)=0$$ or after rearranging terms $$x\_1y\_2+x\_2y\_3+x\_3y\_1=y\_1x\_2+y\_2x\_3+y\_3x\_1$$ [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` _ÆḊ¬ ``` [Try it online!](https://tio.run/##y0rNyan8/z/@cNvDHV2H1vz//z/ayMjcwtDMwMJIR8HExNjA2MAg9n@0oZGhuYGlpSlQ0NjS3MzC1DRWRwEoam5sZmluaABUamBgaGBiFAsA "Jelly – Try It Online") Takes the differences `[(a-b), (a-c)]` via automatic vectorization of `a-[b-c]` then checks if the determinant (`ÆḊ`) is 0 (`¬`). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~9~~ 8 [bytes](https://github.com/abrudz/SBCS) ``` 0=11○÷.- ``` [Try it online!](https://tio.run/##hZG/ahtBEMb7e4otY7gLMzv7t0iahGC1sXEviGyzCDvISmFCqoDBCTJJEVwlYPwAKtPLb7Ivcv721ha6Jmn29vvmm5u5@00/zrsPl9P5@Umfb369nRzlqx/c0yvmfPv94e/Lrj@Gk1c3@dvXzVry1U/EDt6/wXm4PznoObE6VuXUSTdV4VacHSVJdmuUmEZVs1U0vGeztsnTk7FZcxJqjKOkxUkZx9rjHnWpiZikdbBo8iGmzVqzRQbKChQzKcshlSo1WvvAjoJOxggJlRms2VOMVieJ3gVr4Xhx0WNPQ8RkdOMME2aKsdE4hybjbcQ0GME7xjQHAxvCkCChaT7n1Z8veXWfr@9I5dVvNTk5O1/M1PJ0phazi2XzglvFe63aPnWr9J7qXqvDxafl6WUzLuAprZJ/Bphg0P/eYYbAu@n8YjYO0GiL50BnW@VpN9KhR8ZjAAd9oDOsgf9XVNQ1DUKQQDRq6UCrVR1oDSnQggKtogAMAsBGm2zh4RsqvWHaMz4sVflV9wkhspXhaHjliY4KtHRUooNVkA5LVaiDV6jubNM/Ag "APL (Dyalog Unicode) – Try It Online") -1 byte thanks to @Jo King. Takes one complex number (A) on the left, and two complex numbers (B and C) on the right. APL automatically maps scalars, so `A - B C` gives `(A-B)(A-C)`. Then divide between the two `÷.`, and check if the result's imaginary part `11○` is zero `0=`. Uses `⎕DIV←1`, so if division by zero would occur (because `A=C`), `÷` returns 0 instead, which obviously has imaginary part of zero, giving truthy as a result. [Answer] # [Python 2](https://docs.python.org/2/), 39 bytes ``` lambda a,b,c:(a-b)*(a-c-(a-c)%1*2)%1==0 ``` [Try it online!](https://tio.run/##fZDdioMwEIXvfYqhsKAlKflPLNjLfYK9290Lay0VohVNl/r03YmFtrKwN9E5882ck/RTOJ07cTsWXzdftvtDCSXZk2qblnSfrfGsaDyyN74WeBQFuzVtfx4CjNOYHM8D@KaroelivRnDoem2CXgC9bWvq1AfoIC27NMxDNgdmp7MA5ux901IV3S3yrIEPWFPoEL2szq3va@v6ZXAlEE0uJIp7q9/Sp/67Dt5Xf38LWD1MVzCaVolMNTjxQdsH9P5NujQD00XHo3n4C3lBHhGIBUERPxKAjIDuoP7uuQPwBkK7F8Ed6gZeC/9WC8B9gBfAaoJWPaKUJyRSxtl0FpII@cYXNhY5eJOS6mwFE4vRqh1OQEquJ4pqzEa5Xx20NxhYR1bJBHCOm6YwxxKSSbZzHLBLctzjarMrXFa31UrTW7jiyjGOFNiYW4UZzGkVDpXxsQJZXUeE6HkrJnfhBrU4s1Qk066lzS/ "Python 2 – Try It Online") **Input**: the 3 points as 3 complex numbers **Output**: True or False. **How** Let the 3 points be \$(a,A), (b,B), (c,C)\$ The 3 points are colinear iff \$(a-b)\*(A-C)=(A-B)\*(a-c)\$. Note that this formula doesn't have division, and thus won't have floating point issue. Consider the following complex multiplication: $$ \big((a-b)+(A-B)i\big) \* \big((a-c)-(A-C)i\big)$$ The imaginary part of the result is: $$(a-c)(A-B)-(a-b)(A-C)$$ which must be \$0\$ for the 3 points to be colinear. Let `a`, `b`, `c` be the complex representation of the 3 points, then the condition above is equivalent to: ``` t = (a-b) * (a-c).conjugate() t.imag == 0 ``` Instead of using `imag` and `conjugate`, we can take advantage of the fact that all points are integers. For a complex number `t` where both the real and imaginary parts are integers, `t%1` gives the imaginary part of `t`. Thus: ``` t % 1 == t.imag * 1j t - t % 1 * 2 == t.conjugate() ``` --- Old solution that doesn't use complex number # [Python 3](https://docs.python.org/3/), 43 bytes ``` lambda a,A,b,B,c,C:(a-b)*(A-C)==(A-B)*(a-c) ``` [Try it online!](https://tio.run/##fZDNTuswEIX3eYpRVzaykf/tIAUJkO4TsAMWaZuKSG5qJQa1T987TgU0QmLlnONvzpw4nfL7YdDnXfN6ju1@vW2hZQ9szR7Zhj3dkZav6Q154E@0afB4RNHyDT33@3QYM0ynqdodRoj90EE/FH075W0/3FUQGXTH1G1yt4UG9m0iUx7xduwTmwdupxT7TFb8fkUp8ki9HKHEpZLVfbaRRDobx2Kkt@o68eezgdXz@JHfT6sKxm76iBmvd@QmYmoa@yGTL/dnip6JZCApA6IYqHJqBpoCv4dLWPULkAIN8SeCGWYG/rVx6paA@AavAW4ZeHGNcJzRyzXG4WqlnZ5rSOWLqtWF1tqgVMEuRrgPNQOupJ0pb7Eal3LeYGVA4YNYNFHKB@lEwB7GaKHFzEolvahri66uvQvWXlyvXe3LixghpDBqsdwZKUpJbWxtnCsTxtu6NEIreDe/CXfolT9DTwcdrtr8Bw "Python 3 – Try It Online") **Input**: the 2 coordinates of the first point, then the 2nd point, then the 3rd point. **Output**: True or False. --- This should work theoretically, but doesn't because of floating point imprecision: # [Python 3](https://docs.python.org/3/), 34 bytes ``` lambda a,b,c:((a-b)/(a-c)).imag==0 ``` [Try it online!](https://tio.run/##fZDNbqswEIX3PMUoK1uyU//bVKLLPkF3t10QQlokQxC4VXj63DFR26Ar3Q1mznwz59jjkj7Og76eqtdrrPvDsYaaHVjzSEjND/QBvw2l@66v36tKXLt@PE8J5mUuTucJYje00A253s/p2A2PBUQG7WVsm9QeoYK@HsmcJuxO3cjWgf08xi6RHX/aUVqgHRwYNMj@ac79GNsLuTBYKGSDC1vy/varjiTSt@J@9e9vBbuX6TN9LLsCpnb@jAnbJ7JeBB3GqRsS@W78DtIrkQwkZUAUA5VPzUBT4E9w21f8A0iBgvgvgjvMCjzXcW63gPgB7wFuGXhxj3Cc0Vsb49BaaafXGFL5XJXqRmttsFTBbka4DyUDrqRdKW8xGpdydbAyYOGD2CRRygfpRMAcxmihxcpKJb0oS4uqLr0L1t5Ur13p84sYIaQwamPujBQ5pDa2NM7lCeNtmROhFLxb34Q71PLNUNNBh7s0fwE "Python 3 – Try It Online") **Input**: 3 points, each represented by a complex number **Output**: True or False. [Answer] # [J](http://jsoftware.com/), 13 7 bytes ``` 0=-/ .* ``` [Try it online!](https://tio.run/##fVBNSwQxDL37K4II60p3TJO0aVf2orAn8SB7Hzy4iHjy4@CvH5OZURTpQArJ63uvL30eTrvVEXZbWEEAhK2dTQc397f7AXebS@guhvVwfnVcAwPBGcTgBUDBC4CDXQDcXXdweP14f/o8WSBHNADbdJz53vwIlu1x9p8aXvb/n11m8v7h5e2xRf5@g5rkPgVQ/E3vTcztKJJ9Rc48bhlJfao0KZnFRiqpKe@11AA9xTQqNJlPH6c/SLEEJ2AzLZGWmLHYcyKMjKMuUlSsNRnKVXNJaUKVc1W3FsSIQs1QWSL6IiypSs6uFk3VkxpUNI//2WfDfHvDuHD5k/IL "J – Try It Online") Uses [the determinant](https://en.wikipedia.org/wiki/Collinearity#Collinearity_of_points_whose_coordinates_are_given). J's generalized determinant `u .v` is defined for non-square matrices, still multiplying (`*`) each x value with the difference of the other two y values (`-/`), finally reducing that result (`-/`). `-/ .*` calculates the determinant, check if it is `0=`. [Answer] # [R](https://www.r-project.org/), 22 bytes ``` function(x)lm(1:3~x)$d ``` [Try it online!](https://tio.run/##jZBNasMwEIX3PYUWXcggw/xIM1Iht@gF2hRDoHHAJNTd9OruTKBdBWQkxOjpm6cnLdt02KbbfLyeLnNch89zxBf@WYfnj22K57frclrjMWLCRDY48ZDCvFy@DpzC@7cXr8Pw9ABFsNmFDXLyju@x/kP3eP9nzvtQ96YeOpakcIdHTNwNkQVSIBY7RyT1ulEKIzJn21At3Qu1NmsgLLZqYW@2HwgFqwu1G4FIKwpUuzZnBgZrRkKF1opp3FRqKa4pS1P3zgAImULPWjKCP4pzaVnEGrU0j2tCVUELKKb4H5jClesjx@0X "R – Try It Online") Finally a challenge which calls for `lm`! The function `lm` performs linear regression. Here, we are using the input `x` as covariates, and `1 2 3` as observations (any vector of length 3 would do). The output is an object with many components; of interest here is `df.residual` (which can be accessed with the unambiguous abbreviation `$d`), the residual degrees of freedom. This number corresponds to the number of observations minus the number of parameters being estimated. Now: * if the points are not collinear, the regression proceeds normally, estimating 3 parameters, so `df.residual == 0`. * if the points are collinear, there is an identifiability issue and only 2 parameters can be estimated (the last will be given as `NA`), so `df.residual == 1`. Note that the final test case fails due to numerical precision issues. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~20~~ 19 bytes ``` Det@{#2-#,#3-#}==0& ``` [Try it online!](https://tio.run/##ZY@xbsMwDER3f4UAAZkogBQlURpceOgHtOhYdDCCBM2QDIU7Gcqvu5Tipe0i4d4Rx@N1Xj5P13m5HOftPG7Pp2VarXcWLDtbxxEP2@v3RenL1@W2vFv3dJ4m@3G4vx3n230d1pWAKqwevL4MXCv8gYRA@B8zhN8Qd6tDF8GIEqPI9N8RGN5zQkIwnhM3g8hLU8U/xpiDSp/jniS5gHGeYrclsiqinhkpq5C8x3ovmRJmXRkCI2MfIk@CpUSlXCTlGB9UOBXR40xAJAx78RQIWx8OsYSU2miQWFoHRVkS9RpJWTtCGWfOtQ512H4A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [R](https://www.r-project.org/), 27 bytes ``` function(m)!det(cbind(1,m)) ``` [Try it online!](https://tio.run/##hZBNasQwDIX3PUW6s2EMsiVLMvQYvUCbmUAWycCQQm@fSmkL04WnoGD75dPTz22fhpe0Tx/ruM3XNSzx@XzZwvg@r@eQT0uM@xSWt@02f4bRhMGiHIEW8Tjs8RrjU4fL4F@XhAP144d9aHqHPXT92yf9y337lh6X6mkQ@CWT5WC3NrGDyN5gLuL3VjwJkexRtHariDYDS7ZqSSp6ko9as7qg3ZKliGYGtT9ECAi@1JIFWqu@gSastbomyE3ckwAyUHdgpgzeO1JtxGy81ObdmaDCtoDEpviopqCi3jvtXw "R – Try It Online") Port of alephalpha's [Octave answer](https://codegolf.stackexchange.com/a/206843/78274). [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), ~~21~~ 19 bytes ``` {!im [/] $^a X-@_:} ``` [Try it online!](https://tio.run/##fZDNagJBEITvPkUHQtB1Brun51fIzylPkENATViIJgu7iWhyEPXZNz0rBBchcxm6@GqqptfLTe3bZgc3K7iFdn9VNTCbLOD6pYRn/fA6Pbarrw0M6@pzuR3BfgBytuUOVnCYHZpyDcW4gKJSzfR9Mtf387fxZDE4tkNSQCMFQ6PA5JsV8Aj0HTxtfr4/doMLgFAE/BeRN2wHPJb1dtkH8A88B7RTEPAc0eLhfoz1Em3Yc1eDTMhTMiea2cpooutZdIhJgTbkOio4qaaJugRHUYYQsdfEmBDJY5Qe1jIydiwZCpiSE5VT8NG5kxrYp5A3YhEJremFe0uYS7J1yXqfHTa4lBuJFIPvdqK9aPlnonHkeNbmFw "Perl 6 – Try It Online") Takes input as three complex numbers and returns a boolean. Note that if the last and first points are identical (which is disallowed in the challenge spec), then the division operation would return NaN for dividing by zero, which boolifies to True for some reason, so this would fail. [Answer] # [R](https://www.r-project.org/), 49 bytes ``` function(p,q=p-p[,1])q[1,3]*q[2,2]==q[2,3]*q[1,2] ``` [Try it online!](https://tio.run/##jZGxboQwDIb3PkWkLlAlkh0ncTLQsU/QDd1wpVcVCXHA3Q19epoAV9SqEkyxf@n77d8ZxurcNHV7Og7F@HFrq2t9brNO9kWnulLiIe9LlHR46kst9aEo0ju1GNsVzqq3un3PqgylwFyKKtNS6KkgKSjPc/Eo1LN4HW7Xz6@HPRxClGAHCXc0VSu7cyjcpy4V7Zz6X07zw70cm8tpi4PVYJNTVgqG36SKZrRjV@PSYcjRfBvUnNqgFxMiE3vt7baTYh@kUBrtzLKNqRUup7PoY8cetuNozR4d@JjFGAKC2QE1MoRgo0yBnbd2kZlc4PSrBgDB6O1VnUFIQcnYYJybfAzbkAJEzbOb/0G5KKYDRZE8@b@7j98 "R – Try It Online") How? * Subtract first point from the other two: * if points are on a line, the line must now pass through (x=0,y=0) * so we check that the gradient=y/x is identical for both other points: y2/x2==y3/x3 * but to avoid dividing by zero, we rearrange: y2*x3==y3*x2 Edit: * which, thanks to [Kirill](https://codegolf.stackexchange.com/questions/206838/are-they-collinear/206850#206850), [alephalpha](https://codegolf.stackexchange.com/a/206843/78274) and [Wikipedia](https://en.wikipedia.org/wiki/Determinant), I've now discovered is simply the *determinant* of the matrix (x2,y2,x3,y3) * so, for only [29 bytes](https://tio.run/##jZHBTsMwDIbvPEUQl0RKJDtO4uTAjjwBN7TD6IqoVHVT6Q48fZesHRUIqT3V/tXvt3@nH6tT2zZdfeifx49LVw3NqZNn9XisB3l@0wb3Jn9wr5YfZfXedEdZSdQClRaVtFrYW0FakFJKPAmzE6/9Zfj8ftjCIWQJNpBwR0u1sBuHwn3qXNHGqf/ldD/cy6H9qtc4WAxWOeO1YPhNmmxGG3Z1oRyGAk23QculTXY2IXK5t9GvOxmOSQtj0U8s@5za4Hw6jzF3HGE9jrUcMUDMWZwjIJgc0CJDSj7LlDhE72eZKSQur@oAEJxdXzU4hBKUnE8uhJuPY59KgKxFDtM7mJDFcqAsUqT4d/fxCg): `function(p)!det(p[,-1]-p[,1])` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ ~~17~~ ~~27~~ 21 bytes ``` -Dн_iIн¹нQë`s/Uн¹н-X*¹θ+IθQ ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fN@zQTt0LeyMv7I3PjD@8OjKhWF/r0M5zO7QDz@34/z/aUEfBMJYLRBlBKONYAA "05AB1E – Try It Online") [Verify All Test Cases!](https://tio.run/##XY@9SkNBEIVf5ZJOncX5278qz2AjhOuSKFikEgwIKWytxbcQIXWaNDd9yDP4Ite5e6MQm53lmzOHc55W9w/Lx/5lPZ00328fzWS6Xuzfn7vP3t12G3fczY67@XK@/5otVteX3eawvbo5bPtXuLjr27YloAItA9srIMXGGSMEwpFixTZO/E@MVV2H/Kqdhzjy4XUEMnINdi9BBgviaP/MVSCiwJx8VTHHRAETg6qg4OBBTBFz9gySY0jeVxYl5GhhFJFQ2a6b/6X0rBSeNjVkTBkc02DlohdwVFt4SmC7MXFQQgsq6rOGYESjz3ZnIMUwmLpgxHoZkSSplPID "05AB1E – Try It Online") *-1 byte due to remembering implicit input exists and that variable assignment pops values* *+10 due to bug fix regarding vertical lines :-(* *-6 thanks to the wonderful @Kevin, who always manages to golf my 05AB1E answers! :D. Go and upvote his posts!* ## Explained Before we even begin to look at the program, let's take a look at the maths needed to see if three points are collinear. Let our first point have co-ordinates \$(x\_1, y\_1)\$, our second point have co-ordinates \$(x\_2, y\_2)\$ and our third point have co-ordinates \$(x\_3, y\_3)\$. If the three points are collinear, then point three will lie on the line formed by joining points one and two. In other words, \$x\_3\$, when plugged into the equation formed by the line joining points 1 and 2, gives \$y\_3\$. "But what's the line between point 1 and 2?" I hear you ask. Well, we use the good old "point-graident" method to find the line's equation: $$ y - y\_1 = m(x - x\_1), m = \frac{y\_2 - y\_1}{x\_2 - x\_1}\\ y - y\_1 = \frac{y\_2 - y\_1}{x\_2 - x\_1}(x - x\_1) $$ Now, we add \$y\_1\$ to both sides to get an equation where plugging in an `x` value gives a single `y` value: $$ y = \frac{y\_2 - y\_1}{x\_2 - x\_1}(x - x\_1) + y\_1 $$ Substituting \$x\$ for \$x\_3\$ and \$y\$ for \$y\_3\$ gives an equality that determines if three points are collinear. Alright, time for the code (as explained by Kevin). ``` - "[x2-x1, y2-y1]"\ V "pop and store it in variable `Y`"\ ¹- "[x3-x1, y3-y1]"\ н "Pop and leave only x3-x1"\ Yн_i "If x2-x1 from variable `Y` == 0:"\ _ " Check if the x3-x1 at the top == 0"\ ë "Else:"\ Y`s/ " Divide (y2-y1) by (x2-x1) from variable `Y`"\ * " Multiply it by the x3-x1 at the top"\ ¹θ+ " Add x1"\ Q " Check [x3 == this value, y3 == this value] with the implicit third input"\ θ " And only keep the last one: y3 == this value"\ ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 39 bytes ``` (a,A,b,B,c,C)=>(b-a)/(B-A)==(c-a)/(C-A) ``` [Try it online!](https://tio.run/##jZFNS8NAEIbP5lcMwUMWNrjfu7Gm0hY8eRQ8iIckpjRQUmhapZT89jqTKLXiQZiwM8@@82aSqbq06prTw76t7t42@3Jdc/jvWW426yksIT8lBZ/xks95xRcsnyZlWrCbZJ7OWJ4n1VAssDhNoui92MKu7nYd5NDWHy@vcIyuEskBQw2hMRj/BaWgZ8Ri4HR8XZzlP9hZf@ltLuHYoQaYWg5efOMUBXq0MI6odmQqlac8U6TQ2mChgh37fciQKok@qbeaFDSLlYFAGM2U8kE6EdDAGC20oO9R0ossszRi5l2wlpjXLvNkYISQwoxDOiMFjaCNzYxzeOltRu9FELzDoVOHhCZGooMOLOrxxy8327qoVpDQBnBhMMMNcphzqDgsGDTtuBcW4UKet82ufmzaOrmOj4OY9RyOCTWM2dDUQzrFfPmH3T3ET9v9bnWI4Rbih2Ld1YeY9TGbRP3pEw "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 45 bytes ``` {print!($2*$3+$4*$5+$6*$1-$1*$4-$2*$5-$3*$6)} ``` [Try it online!](https://tio.run/##bY5NSkQxEIT3c4oWeqFvCPR/JxuXnsALzEJQFJFxREQ8@7PfLIYI0lmkvkq66vD5vK7fb8en19PVNcqCukdb0PcYC3JDXtDaxr2hLhg3P@tuBa6RGq1pt3B//Dg9fu0umGk7/xgKtuG7w8v7wwXT2Zpwc0g6G41B/yyyKENDgVmybqM@sqqBSPf5Ycs@oAkXTK@SXIWc@8ZpzhLJzkFdwExJqZoLJ43h1XZkdPciqTGyNhgRk8kcFMZUVdR8WARY@qjkkj2DoUXp6lxau/Yp@Rc "AWK – Try It Online") Near-identical to Rich Farmbrough's Perl answer, but the syntax seemed better-suited to AWK than Perl. Thanks Rich! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` NθNηNζ⁼×⁻ηN⁻θN×⁻ηN⁻θζ ``` [Try it online!](https://tio.run/##jYu9CsIwGEV3nyJjAhW@/Dd0dnBQHHyBWAoJpK1NGoe@fAy4lE6O555ze2djP9tQynV65/Wex9cQ8UK6057dgbfKj@inFV@WbEPCTz8OCd/8lBN2Ddq3hDToJ5ajqObf41Zr0pXCmG6pgpYhIThwAEQZ1WCMZIgbrVop66K5MpoCEgAUBCvnT/gC "Charcoal – Try It Online") Link is to verbose version of code. Takes input as six integers and outputs a Charcoal boolean, i.e. `-` for collinear, nothing if not. Uses @SurculoseSputum's original formula. Explanation: ``` Nθ Input `a` Nη Input `A` Nζ Input `b` η `A` ⁻ Minus N Input `B` × Multiplied by θ `a` ⁻ Minus N Input `c` ⁼ Equals η `A` ⁻ Minus N Input `C` × Multiplied by θ `a` ⁻ Minus ζ `b` Implicitly print ``` [Answer] # [Excel], 37 bytes ``` =0=MDETERM(A1:C3+{0,0,1;0,0,1;0,0,1}) ``` Example: [![enter image description here](https://i.stack.imgur.com/J7bh9.png)](https://i.stack.imgur.com/J7bh9.png) [Answer] # [Google Sheets], 27 bytes ``` =0=MDETERM({A1:B3,{1;1;1}}) ``` [Try it online!](https://docs.google.com/spreadsheets/d/1OhwBPJXakq9GbDboNJlvE5xGybciybHrXvqCyAxtNXw/edit?usp=sharing) [Answer] # [Perl 5](https://www.perl.org/), ~~35~~62 bytes ``` sub d{($a,$b,$c,$d,$e,$f)=@_;$b*($c-$e)+$d*($e-$a)+$f*($a-$c)} ``` [Try it online!](https://tio.run/##lZDbagIxEIbv9ylSmYukJjXnA7baqz5BL4WyuisKIuKBUsRnt5PVtru0CM3Nzvz7/TN/sqm3K3d@XyxXNaGPI3YsCJ7lnNABpWI8qfrsoT/@Z8UG1znXURWhoDkYDpaD4@A5BPaD5LPZLtd70qOgGBEj8lKudvXH3WTdG35Rp6@ixl/klvl1e9gv/jKfilNRnHeHKamOFEoOUw4zDhWHmsOcPT2/DWF6T2EmoGZ9qLCsBZRYzrEsBczY6YwTqOJEMU6o5kTnr@HEtFYXvwAlUZA3EZxhW3fvAPIbbAPCcRJkGxHoMd011uNqbbxpYigdcpf0hTbGYquj61hEiIkToZVrqOAwmlCq2eBUxCZE2UmidYjKy4g5rDXSyIZVWgWZkkPVpOCjcxc1GJ9CfhErpZJWd5Z7q2QOaaxL1vvssMGlnAilGHzzJsKjlm@GmokmttN8Ag "Perl 5 – Try It Online") I've put the wrapping on as explained in the comments, and golfed the original "guts" down by picking out some common factors $b\*($c-$e)+$d\*($e-$a)+$f\*($a-$c) (--First attempt --) ``` $b*$c+$d*$e+$f*$a-$a*$d-$c*$f-$e*$b ``` [Try it online!](https://tio.run/##lZDbasJAEIbv8xRTmYsk7tY97wZb7VWfoJdCiSaiYEU8UKT47HY22jahRejCkJ0/38z8O5t6u7Ln98VyVUP6MMo@EqCznEM6SFM@nlT97L4//uctG1z7XFtV9R5SVAw1Q8PQMnQMffYDxbPZLtd76KUoM@AjeC5Xu/p4N1n3hl/U6etS0y@4VfyyPewXfxWfklOS7A5TiJZih7cjOSsZ4JRiRlFR1BTzDB7h6XV4xmmOsz5WOdZ9nOdYcixzrDjOcpxzrHOcnqnpOZUMZMYgVQxU/GoGuuUm@QVIQYK4iVAP01pHBxDfYBvgloEXbYRTje6OMY5GK@10Y0MqH7NCXWitDaUq2E4J96FgwJW0DeUtWeNSNhOsDJT4IDpOlPJBOhHIhzFaaNGwUkkvisKSqgvvgrUX1WtX@LgRI4QURnWGOyNFNKmNLYxzscJ4W0RHJAXvmp1wR1p8GWk66NB28wk "Perl 5 – Try It Online") * Not sure if this follows the rules (where are they?) for header and footer, as much trying out "tio" as anything. * This takes the test text as per the question and outputs the exact same text! In other words it's equivalent to while(<>){print}, provided you feed it a crib sheet. If you remove (or change) the answers from the input, it will supply them. [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` EẊoF/z- ``` [Try it online!](https://tio.run/##yygtzv7/3/Xhrq58N/0q3f///0dHG@oYxupEG@kYAUljHePYWAA "Husk – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` v-ÞḊ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwidi3DnuG4iiIsIiIsIlsxLCAxXSwgW1syLCAyXSwgWzMsIDNdXVxuWzEsIDFdLCBbWzIsIDJdLCBbMTAsIDEwXV1cblsxMCwgMV0sIFtbMTAsIDJdLCBbMTAsIDNdXVxuWzEsIDEwXSwgW1syLCAxMF0sIFszLCAxMF1dXG5bMSwgMV0sIFtbMiwgMl0sIFszLCA0XV1cblsxLCAxXSwgW1syLCAwXSwgWzIsIDJdXVxuWy01LCA3MF0sIFtbMiwgMF0sIFstMSwgMzBdXVxuWzQ2MCwgMjM2M10sIFtbMTEyNywgMjM5Ml0sIFstMTMzNCwgMjI4NV1dXG5bLTc4OSwgLTIxNV0sIFtbLTc1MywgLTExMF0sIFs1MTgsIC03ODBdXVxuWzIyNzgxNjA4MiwgNDQzMDMwMF0sIFtbMTIxNzA5OTUyLCAzOTc2ODU1XSwgWzEyNzM2OTcxMCwgNDAwMTA0Ml1dXG5bNjQxMDI3LCAzNDU5NDY2XSwgW1s0NzU5ODksIDM0NTg3NjFdLCBbLTY3NTk2MCwgMzQ1MzgzOF1dIl0=) Outputs `0` for truthy and any other integer for falsy. Port of fireflame241's Jelly answer. Add `¬` at the end to get `1` for truthy and `0` for falsy. ]
[Question] [ ### *Find the original challenge [here](https://codegolf.stackexchange.com/questions/120897/how-long-is-my-number)* ## Challenge Given an integer, `Z` in the range `-2^31 < Z < 2^31`, output the number of digits in that number (in base 10). ## Rules You must not use any string functions (in the case of overloading, you must not pass a string into functions which act as both string and integer functions). You are not allowed to store the number as a string. All mathematical functions are allowed. You may take input in any base, but the output must be the length of the number in base 10. Do not count the minus sign for negative numbers. Number will never be a decimal. Zero is effectively a leading zero, so it can have zero *or* one digit. ## Examples ``` Input > Output -45 > 2 1254 > 4 107638538 > 9 -20000 > 5 0 > 0 or 1 -18 > 2 ``` ## Winning Shortest code in bytes wins. [Answer] ## Mathematica, 13 bytes ``` IntegerLength ``` [Well...](https://codegolf.stackexchange.com/a/120902/8478) [Answer] # [Python 2](https://docs.python.org/2/), 30 bytes ``` f=lambda x:x and-~f(abs(x)/10) ``` [Try it online!](https://tio.run/nexus/python2#DcFBDoMgEADAs/sKjnDYyKJYYuJjVpRIotRYGzn5a8@0MyUMK2/jxCL3WXCa8A6Sx4/MqiatyrXEdRbUQ7UfMZ0iyJj27ymVKthaIGNbIP3qGmcbB2j0H2hAck96o2e/zD8 "Python 2 – TIO Nexus") [Answer] ## JavaScript (ES6), 19 bytes ``` f=n=>n&&f(n/10|0)+1 console.log(f(-45)) // 2 console.log(f(1254)) // 4 console.log(f(107638538)) // 9 console.log(f(-20000)) // 5 console.log(f(0)) // 0 console.log(f(-18)) // 2 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~5~~ 3 bytes ``` ì l ``` [Try it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=7CBs&input=LTQy) [Answer] My answer from [the other challenge](https://codegolf.stackexchange.com/a/121002/62131) still works: # [Brachylog](https://github.com/JCumin/Brachylog), 1 byte ``` l ``` [Try it online!](https://tio.run/nexus/brachylog2#@5/z/3@8oZGxien/KAA "Brachylog – TIO Nexus") The `l` builtin is overloaded, but on integers, it takes the number of digits of the integer, ignoring sign. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~3~~ 2 bytes *1 byte saved thanks to Leaky Nun* ``` DL ``` [Try it online!](https://tio.run/nexus/jelly#@@/i8///f11DCwA "Jelly – TIO Nexus") ### Explanation ``` L Length of D Decimal expansion of input argument. Works for negative values too ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 bytes ``` ⌈10⍟1+| ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHPR2GBo965xtq1wAFFAy50hSMjIGEJRAbGoAII2NjCAUhzS0sjYwB "APL (Dyalog Unicode) – Try It Online") Explanation: ``` ⌈10⍟1+| ⌈ ⍝ round up the 10⍟ ⍝ log10 of... 1+ ⍝ incremented | ⍝ absolute value of input ``` If format is allowed: 4 bytes - `≢⍕∘|` [Answer] # [Alice](https://github.com/m-ender/alice), 16 bytes ``` /O \I@/Hwa:].$Kq ``` [Try it online!](https://tio.run/nexus/alice#@6/vzxXj6aDvUZ5oFaun4l34/7@uiSkA "Alice – TIO Nexus") ### Explanation ``` /O \I@/... ``` This is simply a framework for numerical input→mathematical processing→numerical output. The rest of the code is the real algorithm: ``` Hwa:].$Kq H Compute absolute value w .$K While the result is not zero do: a: divide the number by 10 ] move the tape head one cell forward q Get the position of the tape head ``` [Answer] # [Chaincode](https://code.sololearn.com/cAw9mAl5Q9AX/?ref=app), 5 bytes ``` pqL_+ ``` ### Note: This is exactly the same code as that from the other challenge ## Explanation ``` pqL_+ print( + succ( _ floor( L log_10( pq abs( input()))))) ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 1 byte ``` Z ``` [Try it online!](https://tio.run/nexus/dc#izc0Mjb5H/W/4D8A "dc – TIO Nexus") --- Not using a builtin, 18 bytes: ``` [d10/d0!=F]dsFxz1- ``` [Try it online!](https://tio.run/nexus/dc#izc0Mjb5H51iaKCfYqBo6xabUuxWUWWo@7/gPwA "dc – TIO Nexus") [Answer] # [R](https://www.r-project.org/), 40 bytes ``` function(x)max(ceiling(log10(abs(x))),0) ``` [Try it online!](https://tio.run/##JYpJCoUwEET3niLgphsMdGLiAB/voqJNQBNwAG@fH2Ot6r2qI/JPxvX28@WChwf38YF5cZvzDFtgRTBOZ/KIFWFkkMZiKQahCwalrclgXqC2qTtbd9n0yUhNKRltwq@RCIdQ76q@p45/ "R – Try It Online") [Answer] ## Pip, 14 bytes ``` LNABq/LNt//1+1 ``` <https://tio.run/##K8gs@P/fx8/RqVDfx69EX99Q2/D/f0MDczNjC1NjCwA> Explanation ``` LN natural log of... (change of base becasue this is the only log function they had) ABq the absolute value of the input... / divided by... LNt the natural log of 10... (change of base) //1 integer divided by 1 (no floor function) +1 added to 1 ``` This was inspired by the Chaincode solution. This could probably be optimized. [Answer] # Java 8, ~~61~~ ~~59~~ ~~39~~ ~~37~~ 33 bytes ``` n->(int)Math.log10(n<0?-n:n+.5)+1 ``` -4 bytes thanks to *@MarkJeronimus*. [Try it online.](https://tio.run/##hY7PDoIwDMbvPEWPW8iWIaLEv0@AF4/GwxwTp1gIDBJjeHYcytXQtE3a/r58vctWsqLUeE8fvcplXUMiDb49AINWV1epNByG8bsARYaOdO02nSuXtZXWKDgAwhZ6ZLsBoYm0N54XWSAIbsSe4Qp9HlE/6NeeE5XNJXeiUdsWJoWn8yVHWxnMTmeQ9Gd6fNVWP3nRWF66k82RIFeEzSP6feIvEcyi@RQiloswjsJ4gmMz4WICmrqzYLTpvK7/AA) **Explanation:** ``` n-> // Method with integer as both parameter and return-type (int) // Convert the following double to an integer (truncating its decimals): Math.log10(// The log_10 of: n<0? // If the input is negative: -n // Use its absolute value : // Else: n+.5)// Add 0.5 to the input instead +1 // And add 1 to the result at the end ``` [Answer] # [S.I.L.O.S](https://github.com/rjhunjhunwala/S.I.L.O.S), 41 bytes ``` readIO i| lblb i/10 a+1 if i b printInt a ``` [Try it online!](https://tio.run/nexus/silos#@1@Umpji6c@VWcOVk5STxJWpb2jAlahtyJWZppCpkMRVUJSZV@KZV6KQ@P//f11DA3MzYwtTYwsA "S.I.L.O.S – TIO Nexus") Returns `1` for `0`. [Answer] # [Lua](https://www.lua.org), 40 bytes Port from my python answer ``` print(math.log10(math.abs(10*...)+1)//1) ``` [Try it online!](https://tio.run/nexus/lua#@19QlJlXopGbWJKhl5OfbmgAYSYmFWsYGmjp6elpahtq6usbav7//1/XxPRrXr5ucmJyRioA "Lua – TIO Nexus") [Answer] # C, 27 bytes [**Try Online**](http://ideone.com/N4UtSG) ``` f(n){return n?1+f(n/10):0;} ``` **C (gcc), 22 bytes** ``` f(n){n=n?1+f(n/10):0;} ``` **Using math, 29 bytes** ``` f(n){return 1+log10(abs(n));} ``` [Answer] ## ARM Thumb-2 (no div instruction, no libgcc), 30 bytes Raw machine code: ``` 2800 d00b bfb8 4240 2201 2100 3101 380a dafc 3201 0008 280a daf7 0010 4770 ``` Uncommented assembly: ``` .syntax unified .globl count_digits .thumb .thumb_func count_digits: cmp r0, #0 beq .Lret it lt neglt r0, r0 movs r2, #1 .Lcountloop: movs r1, #0 .Ldivloop: adds r1, #1 subs r0, #10 bge .Ldivloop .Ldivloop_end: adds r2, #1 movs r0, r1 cmp r0, #10 bge .Lcountloop .Lcountloop_end: movs r0, r2 .Lret: bx lr ``` Returns 0 if 0. ### Explanation C function signature: ``` int32_t count_digits(int32_t val); ``` First, we compare val to zero. If it is zero, we return zero. If it is less than zero, we negate it. ``` count_digits: cmp r0, #0 beq .Lret it lt neglt r0, r0 ``` Set up our digit counter for the outer loop. ``` movs r2, #1 ``` Now, a naïve subtraction based division loop ``` movs r1, #0 .Ldivloop: adds r1, #1 subs r0, #10 bge .Ldivloop ``` Increment the digits counter, then loop to the outer loop if we are still more than 10. ``` .Ldivloop_end: adds r2, #1 movs r0, r1 cmp r0, #10 bge .Lcountloop ``` Move the result into the return register and return. ``` .Lcountloop_end: movs r0, r2 .Lret: bx lr ``` [Answer] # [Julia](http://julialang.org/), 7 bytes ``` ndigits ``` [Try it online!](https://tio.run/##yyrNyUw0rPifZvs/LyUzPbOk@H9JanFJsYKtQjSXrokpl6GRqQmXoYG5mbGFqbGFApeRARAocBlw6RpaAMWBCMQEYwMuS0suXSCO5eIqKMrMK8nJ09OAmKZna6eQBuVoav4HAA "Julia 1.0 – Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 46 bytes ``` param($a)for($s=0;$a){$s+=!!($a=[int]$a/10)}$s ``` ## Implementation Details ``` param($a) # Defines the input parameter for($s=0;$a){ # Initialise the result to 0 and iterates while the parameter is not 0 $s+=!!($a=[int]$a/10) # Divides the parameter by 10 and increment the result variable # by one if the result is not 0 }$s # Returns the result ``` [Try it online!](https://tio.run/##TY9Ba4NAEIXP66@YhGlRulI12lqCIJSeW0hvIQRjRtqi0e6utGD97dtJIm329N6b@d6wXftFSr9RXftlq8hilQ22K1TRuFh4Vatc1FmwZD2gvslmM46z9fvBbLC4DQNvRG1Hx8ldR8jc9eNEQuSddBglsYR4MsH93SJNFqmEh3PiRwE/CcnZsgqmQZieOjz4gSsYHIGHvtmRkoD03VFpaA8Z4HbJE0W6rw3ba6xg2uN8/bJ67LVpm@fdBwMbyLlGrPqyJK2P8MT59PlfypyYv5I2UBaa5se1v0LxdHH5Ahgd/ru1vw "PowerShell Core – Try It Online") [Answer] # Excel, 26 bytes ``` =INT(LOG(A1^2+(A1=0))/2)+1 ``` Log of the number squared / 2 is 1 byte shorter than `ABS` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~10~~ ~~9~~ 7 bytes -3 bytes from @ngn (see [Am I an insignificant array?](https://codegolf.stackexchange.com/questions/143278/am-i-an-insignificant-array/221444#comment515993_221444)) ``` #10\#!: ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NStnQIEZZ0ep/mrquiamCoZGpiYKhgbmZsYWpsYWCrpEBECgYKOgaWvwHAA "K (ngn/k) – Try It Online") * `#!:` get the absolute value of the input (literally, take the count of the range of each value; e.g. `#!-2` -> `#-2 -1` -> `2`) * `10\` "digit-ize" the input * `#` take the count A solution using `$` instead of `10\` save two bytes, but may be invalid given the question's rules. [Answer] # TI-Basic, ~~9~~ 8 bytes ``` int(log(1+10abs(Ans ``` Takes input in `Ans`. -1 byte thanks to [MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` Ä>T.nî ``` [Try it online!](https://tio.run/nexus/05ab1e#@3@4xS5EL@/wuv//dQ0NzM2MLUyNLQA "05AB1E – TIO Nexus") or [Try all tests](https://tio.run/nexus/05ab1e#qymr/H@4xS5EL@/wuv@VSof3K1gpKNnr/Nc1MeUyNDI14TI0MDcztjA1tuDSNTIAAi4DLl1DCwA "05AB1E – TIO Nexus") ``` Ä # Absolute value > # Increment T.n # Log base 10 î # Round up ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` A‘l⁵Ċ ``` [Try it online!](https://tio.run/nexus/jelly#@@/4qGFGzqPGrUe6/v83NTEzMTUzMTP9DwA "Jelly – TIO Nexus") [Answer] # C#, ~~49~~ 56 bytes ``` namespace System.Math{n=>n==0?1:Floor(Log10(Abs(n))+1);} ``` [Answer] # [Python 2](https://docs.python.org/2/), 48 bytes -3 thanks to ovs -1 thanks to pizzapants ``` lambda x:math.log10(abs(10*x)+1)//1 import math ``` [Try it online!](https://tio.run/nexus/python2#NYzBbsIwEETP@CtWnOxiwBuSNkTiCNd@gMvBDqZxlcSR44j0w3sOdqvuYd@MZnbvp4@lVZ2@KZirToVm17pPFFTpkaJ4mdkG2X6PxHaD8wFSYwn@uyKrR2NbAxjVSnF9sv0wBcqSG0cTq3eqGNgeNAeaNAfNiJlrMwQ4v1/O3jtfCTJ42wdY35T9cpOe1mQ5colXsv0DCi6z6P6ZF7/ErMi5zFP@9nooi0PJ5THGmYjDZXElcQue/mCZLn56t61V3Zgn "Python 2 – TIO Nexus") [Answer] # Ruby, 27 bytes ``` f=->x{x==0?0:1+f[x.abs/10]} ``` As a test: ``` tests = [[-45 , 2], [1254 , 4], [107638538 , 9], [-20000 , 5], [0 , 0 ], [-18 , 2]] tests.each do |i, o| p f.call(i) == o end ``` It outputs: ``` true true true true true true ``` [Answer] # @yBASIC, 53 bytes. ``` _#=@_>.@_ _%=_%/(_#*_#+!.)_=_+!.GOTO(@_)+"_"*!_%@__?_ ``` Input should be stored in variable \_% [Answer] # Rust, 41 bytes ``` fn f(n:i32)->u8{n!=0&&return f(n/10)+1;0} ``` [Try it online!](https://play.rust-lang.org/?gist=d72062485bb32892aab46c26d8047ea0&version=stable) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` .xhs.l.aQT ``` [**Test suite**](https://pyth.herokuapp.com/?code=.xhs.l.aQT&test_suite=1&test_suite_input=-45%0A1254%0A107638538%0A-20000%0A0%0A-18&debug=0) Explanation: ``` .xhs.l.aQT # Code .xhs.l.aQTQ # With implicit variables # Print (implicit): .l T # the log base 10 of: .aQ # the absolute value of the input s # floored h # plus 1 .x Q # unless it throws an error, in which case the input ``` Python 3 translation: ``` import math Q=eval(input()) try: print(int(math.log(abs(Q),10))+1) except: print(Q) ``` ]
[Question] [ ## Introduction Just on Hacker news, John Resig contemplates transforming a query “foo=1&foo=2&foo=3&blah=a&blah=b” into one that looks like this: “foo=1,2,3&blah=a,b", <https://johnresig.com/blog/search-and-dont-replace/>. He claims "being 10 lines shorter than Mark’s solution". Query strings consist of sequences of name-value pairs. Name-value pairs consist of a name and value, separated by =. names and values are possibly empty sequences of alphanumeric characters. Name-value pairs are separated by the & character in the sequence. Values are unique for each name. ## Challenge 10 lines shorter than Mark's solution is not enough. * Read a query string. * Combine name value pairs with equal name into a single name value pair, with values concatenated and separated by comma. * Output the combined query string, with name-value pairs in the order the names are found from left to right in the query string. This is code golf, the standard loopholes are closed. ## Example Input and Output Input: > > foo=1&foo=&blah=a&foo=3&bar=x&blah=b&=1&=2 > > > Output: > > foo=1,,3&blah=a,b&bar=x&=1,2 > > > Input: > > foo=bar&foo=foo > > > Output: > > foo=bar,foo > > > [Answer] # JavaScript (ES6), ~~103 99 87~~ 86 bytes *Saved 1 byte thanks to @MatthewJensen* ``` s=>Object.values(o=/(\w*=)(\w*)/g,s.replace(o,(s,k,v)=>o[k]=o[k]?o[k]+[,v]:s)).join`&` ``` [Try it online!](https://tio.run/##JcpRDoIwEEXR3ZSO1hL1z2RwCS4ASZjWgkLDEIrV3VerPyc3L2@gSMEuj3ndTXxzqcMUsLqYwdlVR/JPFyRjKa@vDUIWyl4FvbjZk3WSlQxqVBGw4npsMHPObGsVm1MA0AM/pla0yfIU2DvtuZedLDpm3IusMJ7uSL8@CkMLvv@TEd8HHgqA9AE "JavaScript (Node.js) – Try It Online") ### Commented ``` s => // s = query string Object.values( // get the values of ... o = // ... the object of this regular expression, which is /(\w*=)(\w*)/g, // re-used to store the keys and values of the query s.replace( // match each key with the '=' sign and the corresponding o, // value, using the regular expression defined above (s, k, v) => // for each matched string s, key k and value v: o[k] = // update o[k]: o[k] ? // if it's already defined: o[k] + // get the current value [, v] // append a comma, followed by v : // else: s // set it to the entire matched string // (key, '=', first value) ) // end of replace() ).join`&` // end of Object.values(); join with '&' ``` [Answer] # JavaScript, ~~263~~ ~~201~~ ~~196~~ ~~194~~ ~~190~~ ~~189~~ ~~188~~ ~~173~~ 161 bytes ``` q=>{w={};q.split`&`.map(x=>{y=x.split`=`;if(!w[y[0]])w[y[0]]=[];w[y[0]].push(y[1])});z=`${Object.entries(w).map(a=>a=[a[0]+'='+a[1].join`,`]).join`&`}`;return z} ``` [Try it online](https://tio.run/##LYxbDoIwEEW3ookpbdTGx49JM27BBTRNOpAqJUixrQIS1o6o/Nw5OZl7C3xhyLyt4/Z1GnMYH3DuG@gH8eChLm3URPM71rSdfAftLEELe6XLRnZypxSbL0glZuT1M@S0k3vFBibeoFf9JS1MFrmporcm0Ib9dhHOCBKnzjqBZI1TgxfOVnqjFfsT0YMW3sSnrxbvYcxcFVxpeOluNKfJ1TnYk2@StMQc8MdHkqKH9q9SMn3AIWFs/AA) [Answer] # [Julia 1.0](http://julialang.org/), 106 bytes ``` f(a,z=split.(split(a,'&'),'='),u=first.(z))=join((i*'='*join(last.(z)[u.==i],',') for i in unique(u)),"&") ``` [Try it online!](https://tio.run/##JYrBCsMgEER/RTysu0ECac/7JaUHhUo3iKYmQsjPG5tcZob3Zq5R3LS3FtDZg9clyjbiVR0YMGQN96gcpKxdHUQ8Z0mIMnQzXDu6W73qyCxva6whFXJRoiSpmuRXP1iJrAZNbSmSNgyoQ848wT/BR/dld@0neFd4v5GH/uCHJmon "Julia 1.0 – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 116 bytes ``` lambda s:(a:=[k.split("=")for k in s.split("&")])and"&".join(b+"="+",".join(d for c,d in a if c==b)for b in dict(a)) ``` [Try it online!](https://tio.run/##NYzBCsIwEER/ZckhJLQUtAelsF@iHjYNwbU1CUkE/fqaFL0MM29nNn7KPfjxHNPmAOG6rfQ0liBPiia8LEOOKxclUGgXEizAHvIfSqFvmrytZngE9sp0tdiJ/hcttM3c27YiYAczotkfmYYsz0WR1ltM7Ityin18FaUrcSHgQTaVJ6TdjNJQwnfNRtYbHr8 "Python 3.8 (pre-release) – Try It Online") -46 bytes thanks to ovs -1 byte thanks to Jonathan Allan (in Py 3.8 PR, with walrus) [Answer] # [Ruby](https://www.ruby-lang.org/), 88 80 76 64 bytes ``` ->s{s.scan(/(\w*=)(\w*)/).group_by(&:shift).map{|k,v|k+v*?,}*?&} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664ulivODkxT0NfI6Zcy1YTRGrqa@qlF@WXFsQnVWqoWRVnZKaVaOrlJhZU12TrlNVka5dp2evUatmr1f4vKC0pVkiLVk/Lz7c1VAORakk5iRm2iWC2sVpSYpFtBUQoSQ2owtZIPfY/AA "Ruby – Try It Online") *-8 bytes thanks to ovs for pointing I could assign a lambda to a variable* *-12 bytes thanks to Dingus!* [Answer] # [Python 3](https://docs.python.org/3/), 94 bytes ``` lambda s:'&'.join(k+'='+",".join(v)for k,v in parse_qs(s,1).items()) from urllib.parse import* ``` [Try it online!](https://tio.run/##JYrLCsMgFAX3/QrJwkcjQppdwT8pFKWR2KjXXG1ov962yWY4c5j8qTOksTl9a8FE@zCkXBll6gk@8aVnmvWd7A7dhAMki9yITyQbLNN9LbzIQShfp1i4ECeHEMkLQ/BW7QnxMQPWc8voU@WOMwegB/ontcHM2ux7pNagfh@Xpb9CX5gQ7Qs "Python 3 – Try It Online") A few things: * This only works because Python 3.6+ maintains dictionary order based upon time of insertion. We would love to use Python 2 for a shorter import (`urlparse` vs `urllib.parse`) but dictionaries are not ordered properly. * As much as I love f-strings, `k+'='+",".join(v)` is shorter than `f'{k}={",".join(v)}'`. * The double `.join` feels like golf smell, but I can't find a shorter way. --- ### [Python 3](https://docs.python.org/3/), 95 Bytes ``` from urllib.parse import* d=parse_qs(input(),1) print('&'.join(k+'='+','.join(d[k])for k in d)) ``` [Try it online!](https://tio.run/##LY3NCsIwEITvfYqc8mNLofa8TyIiCbF0TZqN2xT06WOtXob5PgYmv8tMaax1YlrExjGi67Pl9S5wycTl1Hg4@PZcNaa8FW26wTSZMRWtpOofhEmHVoFqVfdHfwlXMxGLIDAJb8x@QASD/KZ00c5gjz5KZxleP@XkvoBz/QA "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 Thanks to Zgarb! ``` ṣ”&ṣ€”=Ṗ€ĠṢịƲµZQ€j€”,j”=)j”& ``` A monadic Link accepting and yielding a list of characters. **[Try it online!](https://tio.run/##y0rNyan8///hzsWPGuaqgaimNUCW7cOd04CsIwse7lz0cHf3sU2HtkYFAgWyINI6WSA1miBS7f///2n5@baGaiBSLSknMcM2Ecw2VktKLLKtgAglqQFV2BoBAA "Jelly – Try It Online")** ### How? ``` ṣ”&ṣ€”=Ṗ€ĠṢịƲµZQ€j€”,j”=)j”& - Link: list of characters, S ṣ”& - split at '&'s ṣ€”= - split each at '='s call that A Ʋ - last four links as a monad - f(A): Ṗ€ - all but last of each Ġ - group indices by their values Ṣ - sort (since Ġ orders by the values, not the indices) ị - index into (A) (vectorises) µ ) - for each: Z - transpose Q€ - deduplicate each j€”, - join each with ','s j”= - join with '='s j”& - join with '&'s ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~62~~ 51 bytes (-11 from @kevin) ``` '&¡'=δ¡D€нÙÐV_UsvYyнk©Xsèyθ',««Xs®ǝU}X妨}Yζí'=ý'&ý ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fXe3QQnXbc1sOLXR51LTmwt7DMw9PCIsPLS6LrLywN/vQyojiwysqz@1Q1zm0@tDqiOJD647PDa2NOLf10LJDK2ojz207vFbd9vBedbXDe///T8vPtzVUA5FqSTmJGbaJYLaxWlJikW0FRChJDajC1ggA) My 62 approach: ``` '&¡ε'=¡}D€нÙ©DgÅ0Usvy¬®skDVXsèyθ',««XsYǝU}X妨}®ζεć'=s««˜}˜'&ý ``` Explanation: ``` '&¡ε'=¡}D€нÙ©DgÅ0Usvy¬®skDVXsèyθ',««XsYǝU}X妨}®ζεć'=s««˜}˜'&ý '&¡ split by & ε'=¡} foreach: split by = D duplicate €н foreach: push header (get the keys list) Ù uniquify © save in register c Dg suplicate and get the length of that list of keys Å0 create a list of 0's with the length above U save in variable X svy } for each set of key-value ¬®sk find the index of that key in the keys list DV save the index in variable y Xsè get the current value of the element of X at index Y (in X we are keeping the concatenation of the values for key i) yθ extract the tail of the element in this iteration (a value to concatenate) ',«« concatenate with , in between XsYǝU update X with the new value of the element representing the key X妨} remove tail and head from each element of X (removing the trailing , and leading 0) ® push back the list of keys ζ zip (list of keys and list of merged values) εć'=s««˜} foreach element in the zipped list, join with = in between such that the result is "key=values" ˜ flat '&ý join with & ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fXe3QwnNb1W0PLax1edS05sLewzMPrXRJP9xqEFpcVnlozaF1xdkuYRHFh1dUntuhrnNo9aHVEcWRx@eG1kac23po2aEVtYfWndt2buuRdnXbYpDs6Tm1p@eoqx3e@/9/Wn6@raEaiFRLyknMsE0Es43VkhKLbCsgQklqQBW2RgA) [Answer] ## JavaScript, 79 bytes ``` f= s=>(s=new URLSearchParams(s)).forEach((v,k)=>s.set(k,s.getAll(k)))||unescape(s) ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` If I/O could be actual query strings according to the WHATWG spec, rather than invalid strings that looks like query strings but aren't correctly URLencoded, then 7 bytes could be saved by stringifying the result instead of unescaping it. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '&¡'=δ¡.¡н}εø€Ù}…,=&vyý ``` [Try it online](https://tio.run/##yy9OTMpM/f9fXe3QQnXbc1sOLdQ7tPDC3tpzWw/veNS05vDM2kcNy3Rs1coqD@/9/z8tP9/WUA1EqiXlJGbYJoLZxmpJiUW2FRChJDWgClsjAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TpuSZV1BaYqWgoGRfqcOl5F9aAuYCef/V1Q4tVLc9t@XQQr1DCy/srT239fCOR01rDs@sfdSwTMdWrazy8N7/tTqHttn/T8vPtzVUA5FqSTmJGbaJYLaxWlJikW0FRChJDajC1ogLodQIpgiiA6IKLA/UBpYDYgA). **Explanation:** ``` '&¡ '# Split the (implicit) input-string on "&" δ # For each inner string: '= ¡ '# Split it on "=" .¡ } # Group all pairs by: н # Their first value ε # Map over each group of pairs: ø # Zip/transpose, swapping rows/columns € # For both inner lists: Ù # Uniquify it }…,=& # After the map: push string ",=&" v # Pop and loop over each character `y`: yý # Join the inner-most list of strings with `y` as delimiter # (after the loop, the result is output implicitly) ``` [Try it online with a step-by-step output.](https://tio.run/##TZGxTsMwFEX3fsVThqRIhQrYkKyOqBJiARY2J3Wah1zb2E5LhkqIv2DswsSIEEtVqdkR39AfCc@JQFks@/nec69s7XiKommiqTKlv4BoxPafk0F0YyR60AqSOAnTJN5v@jeCZwWgUsKC8xbVvNWyTsu@P/7Ul1aXBnwhwHC0DtIqHNBCTicPSy5LETwn@83Pdt157tGMveXKGe0EDN2KGxMSrF65caZluVDuCHTelZiHhIA4vLzXXx3hTuFjiXnVrymR8gxt@obgee08V1ob0EsShLZZwS3PvKDKFJSMWJwAVzN40Kh61OOFJmqLJln3Eg5KF@r6gnvgDmZC4gIJFTIHh@c3gi2r62hKI@6R3q3ewTCpd8kRKSZVvWXrttEt9ZCc0PivRKpTevqpALbClbL9s1HT5Fqz0ziscSp5wXi7P49TbtlTN0pjUrCzXw) [Answer] # JavaScript, ~~106~~ ~~104~~ 76 bytes Port of [Neil's Retina solution](https://codegolf.stackexchange.com/a/211866/58974), posted with permission. ``` f=q=>q==(q=q.replace(/(?<=^|&)((\w*=)[^&]*)(.*?)&\2(\w*)/,`$1,$4$3`))?q:f(q) ``` [Try it online!](https://tio.run/##JYpBDoIwEAD/QprNboMQwJNx5SEiodRWNA2lYNSDf6@il8lkMjf1UIuer9N9M/qzidFy4ENgxsAhm83klDaYY73n9g2E2Dwl07GFkyTMZE3QlGujPO1EkYqtqDqiOuwsBoraj4t3JnP@ghYT6z0XsBJ6pwZWP6@gVzO//qmH78FlQhQ/) ## Original A little bit of drunk golfing that I came back to work on sober but in the process spotted Arnauld's solution and realised I was on the path to something almost identical so I left this as-was. ``` q=>Object.keys(o={},q.split`&`.map(p=>o[[k,v]=p.split`=`,k]=[...o[k]||[],v])).map(x=>x+`=`+o[x]).join`&` ``` [Try it online!](https://tio.run/##LYzRDoIgGIXfxQsG09iq699X6AEYm2BYCvmjOEfLnp3Iujk7O9@3M6hVhXbu/XIY8WpSB2mC@qIH0y7cmmegCK93NfHgXb80pOEP5amHGoWw1SrB/wk0lZUgOOcorNw2ITNlbNcj1LHMRokiSsYH7Mf8lFocAzrDHd5oR4sOEY7km0Q7dQe19zPRaob4mzTJBpwKxtIH) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 45 bytes ``` +1`(?<=^|&)((\w*=)[^&]*)(.*?)&\2(\w*) $1,$4$3 ``` [Try it online!](https://tio.run/##K0otycxL/P9f2zBBw97GNq5GTVNDI6Zcy1YzOk4tVktTQ0/LXlMtxggkpsmlYqijYqJi/P9/Wn6@raEaiFRLyknMsE0Es43VkhKLbCsgQklqQBW2RgA "Retina 0.8.2 – Try It Online") Explanation: Repeatedly matches the first duplicate key and its first duplicate and joins the value to that of the original key. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~29~~ ~~28~~ ~~27~~ ~~26~~ 24 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` q& móÈk¶ ü@bøXÎîÕvÎqÃq& ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cSYgbfPIa6UK/EBi%2bFjOw67Vds5xw3Em&input=ImZvbz0xJmZvbz0mYmxhaD1hJmZvbz0zJmJhcj14JmJsYWg9YiY9MSY9MiI) Saved 2 bytes thanks to some inspiration from [Kevin](https://codegolf.stackexchange.com/a/211909/58974). (Oh, if only Japt had a method just for grouping, rather than also sorting, this could be [19 bytes](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cSYgbfPIa6UK/M6u1XbOccNxJg&input=ImZvbz0xJmZvbz0mYmxhaD1hJmZvbz0zJmJhcj14JmJsYWg9YiY9MSY9MiI).) ## Explnataion ``` q& móÈk¥\nü@bøXÎîÕvÎqÃq& :Implicit input of string U q& :Split on "&" m :Map ó : Partition after each character that returns falsey (i.e., an empty string) È : When passed through the following function k : Remove all characters that appear in ¥ : Literal "==" \n :Reassign to U ü :Group & sort by @ :Passing each X through the following function b : First index in U ø : That contains XÎ : First element of X à :End grouping ® :Map each Z Õ : Transpose v : Map first element to Î : Get first element q : Join resulting array à :End map q& :Join with "&" ``` Or, to provide a step-by-step walkthrough: ### Input ``` "foo=1&foo=&blah=a&foo=3&bar=x&blah=b&=1&=2" ``` ### Split ``` ["foo=1","foo=","blah=a","foo=3","bar=x","blah=b","=1","=2"] ``` ### Map & Partition ``` [["foo=","1"],["foo="],["blah=","a"],["foo=","3"],["bar=","x"],["blah=","b"],["=","1"],["=","2"]] ``` ### Group & sort ``` [[["foo=","1"],["foo="],["foo=","3"]],[["blah=","a"],["blah=","b"]],[["bar=","x"]],[["=","1"],["=","2"]]] ``` ### Map and ... **Transpose** ``` [[["foo=","foo=","foo="],["1",null,"3"]],[["blah=","blah="],["a","b"]],[["bar="],["x"]],[["=","="],["1","2"]]] ``` **Map first element to its first element** ``` [["foo=",["1",null,"3"]],["blah=",["a","b"]],["bar=",["x"]],["=",["1","2"]]] ``` **Join** ``` ["foo=1,,3","blah=a,b","bar=x","=1,2"] ``` ### Join ``` "foo=1,,3&blah=a,b&bar=x&=1,2" ``` [Answer] # [R](https://www.r-project.org/), 195 bytes ``` {Z=pryr::f `/`=Z(a,b,el(regmatches(a,gregexpr(b,a)))) `-`=Z(a,b,paste(a,collapse=b)) Z(S,{L=S/'\\w*=' L=factor(L,unique(L)) U=tapply(S/'=\\w*',L,Z(a,trimws(a,,'=')-',')) paste0(names(U),U)-'&'})} ``` [Try it online!](https://tio.run/##jVLJTsMwEL3nKyyDYhtcynKr8JEDUiQk2lxKQHUip7GUDcdVE1X99jJ2WrYDwgd7ljdv3oxsDmco1z1aPD4ha3S17VC@qTOrmzoYfXHyEe052hY6K5BAGcVpYwvMES5Vbt1r9LqwmHmMVV0rMwVA/IISm5ikfsUs2AUIzshxP0GVtFlxJc2a@hDz2WroNqnLnvpSozjqGYKwNzE0AyWtMiXwL57jh7Gw22qgG6k4cqog7dloKzurril@w9/VAdUl6PXF7vSg3Q/xu@5nybmb0WHdAv6AfvIeS/4hBWgZC/ZBkDUVhK3OB3HYLUVrBjOb5cFquhJLKnnKVQm7WPsFqg4ia/BU3xqacskcyWpygvqOYGVNWcq2UyKF9JLO@S4S8ylJku2FIEEkcmjYGBrxTa3fN4pGAIuFlW1bDhSAwiEJj7ijHf8GGJwIwiaEE0AfZ6tlBZpixmNIhGTP9oeveSjJm0bchO4O01IWQnr7LkylEf0YSkNAiFvCDh8 "R – Try It Online") [Answer] # [Lua](https://www.lua.org/), 162 bytes ``` l,t={},{}(...):gsub('(%w-)=(%w-)',load"k,v=...o=t[k]l[#l+1]=not o and k or _ t[k]=o and o..','..v or v")for i=1,#l do io.write(i>1 and'&'or'',l[i],'=',t[l[i]])end ``` [Try it online!](https://tio.run/##JY1RCoMwEESvEizNJjQN2P4VthcRKZFoGwwupFEL4tlToz8zw8yD8aNJyauIy6qWVWit5eP9HRsB4jxfJe4KypOxRa8m3ADCWPW1r07@UtY4UGTEzGBZzyiwF8sjHg1pDQq0nvIyFbLbzGGpTp5ZYo70HFxshXuWGQcOFGD7qlytAEHFKsdatoNNKXVEWPKsvPHmg2bPd96YgL@javhG4O0P "Lua – Try It Online") This is a long one, huh. It could have been made much shorter if not for ordering requiment. Explanation: ``` l,t={},{} -- list (by first inclusion), table (keys to string) -- (ab)use string replacement function to callback over matches in input string (...):gsub( -- Match key-value pairs '(%w-)=(%w-)', -- For each pair, run callback (braces are replaced for multiline) load[[ k,v=... -- Assign key, value o=t[k] -- Look for already stored string if any l[#l+1]=not o and k or _ -- If key is new, store it in list t[k]=o and o..','..v or v -- Append to string if it is not new, store it if it is ]] ) -- For every record in list for i=1,#l do -- Write with no newlines io.write( i>1 and'&'or'', -- Output & before all values but first l[i],'=',t[l[i]] -- Print key-value pair ) end ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 86 bytes ``` StringRiffle[Last@Reap[Sow@@@StringExtract[#,"&"->;;,"="->{2,1}],_,List],"&","=",","]& ``` [Try it online!](https://tio.run/##JYs9C4MwEIb/Skkhg1wH7SgpWdwcio4hlDOYGlAjelBB/O1pVI774H2eG5C6dkByBoMVoabZjd/KWdu3qsSFZNXipGr/k1JesFhpRkPqDoyzxyvPgYm4twzSXcMHSreQPtiRQyzNQ21wVO/4TTKxMilM57XcmPVepPyYvOmxE3jeT97gLNYrang0RMbgdtqRnE5stufhDw "Wolfram Language (Mathematica) – Try It Online") Pure function, takes a string as input and returns another string as output. This is inspired by and very similar to [att's answer](https://codegolf.stackexchange.com/a/211825), but it uses an algorithm similar to the one in the blog post (here utilizing `Sow`/`Reap`). Here's an example of how the subexpressions evaluate on an input of `"foo=1&bar=a&foo="`: ``` StringExtract[#,"&"->;;,"="->{2,1}] == {{"1", "foo"}, {"a", "bar"}, {"", "foo"}} Sow@@@... == {"1", "a", ""}; {"1", ""} sown w/ tag "foo"; {"a"} sown w/ tag "bar" Reap[...,_,List] == {{"1", "a", ""}, {{"foo", {"1", ""}}, {"bar", {"a"}}}} Last@... == {{"foo", {"1", ""}}, {"bar", {"a"}}} StringRiffle[...,"&","=",","] == "foo=1,&bar=a" ``` [Answer] # [Factor](https://factorcode.org/), 229 bytes ``` : c ( s -- s s ) 1 <hashtable> swap "&"split [ "="split ] map [ [ dup [ last ] dip first pick push-at ] each ] [ [ first ] map dup union ] bi dup [ [ over at ","join ] map ] dip [ "="append ] map swap zip [ concat ] map "&"join ; ``` [Try it online!](https://tio.run/##RVCxTsMwEN3zFScPEUgEqbClhIUBdemCmKIOF8dpTFP78DlA@PlwcQMMfjq/e@/5yR3q6MP8@rLbP5eAzF4z9Mh9xGYwDCcTnBmAzftonBaCTRSgwcZo3REomBgnCtZF2Ga7fQlP/kwSarupiL0pxBemgqMojnMJGq6AoSgEGK5hAw9/jz0CfyKBylWKhxpUtY4HOCNltVDtSIID8kK2lqCzQWay@gQ0cl/gsjCoezgkw2WfApJ5dNY7uTd2zarBf5gA4lM36s1bt4pTfJZKIJFx7cqnkt92sWrvNP6GS@/k3s6q877a5AvmzYB9hWm@zxsM1deFanJRVHdKPuQW2uApSy5RJK2c/9X8Aw "Factor – Try It Online") It's long but I'm somewhat content with it :) [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~243~~ ~~221~~ 212 bytes ``` Q =INPUT T =TABLE() N Q (ARB '=') . L ARB . V ('&' | RPOS(0)) REM . Q :F(O) T<L> =T<L> ',' V :(N) O R =CONVERT(T,'ARRAY') I X =X + 1 R<X,2> ',' REM . V :F(P) O =O '&' R<X,1> V :(I) P O '&' REM . OUTPUT END ``` [Try it online!](https://tio.run/##LY@9asNAEITru6eY6n6IMJaSSmgNsi2DQL6TL2ehlFIRUpgI7MZF3l25k9wMu8PMt@zjdxqn28c8swuoNu3Vc@ZBvtw3ldLcBFuVbg9JUmODBnHZoIOSQuIPrrWfaqs1XHUO/oXlJ2V1YBTNLmCiykSGPMuV0dwyBzpY01XOK5/I0rnyS2pesx7U4w0pZ67ok2ytrdBYPqk2UC3IIh6OmXSHLlBrzVv2cpe4vfr4RmWO8/w9TZSKqGK8DT80LPO7GIc7PVdrFCFB2T8 "SNOBOL4 (CSNOBOL4) – Try It Online") `TABLE` in SNOBOL is weird. It's perfectly fine accepting a `PATTERN` like `ARB` as a key, but not the empty string `''`. However, using `<label>=` as the label instead of `<label>` neatly solves this problem. Explanation for a previous iteration: ``` E =RPOS(0) ;* alias for end of string A =ARB ;* alias for ARBitrary match (as short as possible) Q =INPUT ;* read input T =TABLE() ;* create a TABLE (a dictionary) N Q A . L '=' A . V ('&' | E) REM . Q :F(O) ;* in regex land, this is something like ;* '(.*=)(.*)(&|$)' where you save \1 and \2 as L and V, respectively. If there's no match, goto O T<L> =T<L> V ',' :(N) ;* update the values list, then goto N O R =CONVERT(T,'ARRAY') ;* convert T to a 2D array of [Label,Value] I X =X + 1 ;* increment array index R<X,2> A . V ',' E :F(P) ;* remove the trailing ',' from the value list. If X is out of bounds, goto P O =O R<X,1> V '&' :(I) ;* Append L and V to O with an '=' and '&', then goto I P O A . OUTPUT '&' E ;* Print everything except for the trailing '&' END ``` [Answer] # [PHP](https://php.net/), 146 bytes ``` <?=parse_str(str_replace('=','_[]=',$argv[1]),$a)??join('&',array_map(function($b,$c){return rtrim($b,'_').'='.join(',',$c);},array_keys($a),$a)); ``` [Try it online!](https://tio.run/##LYzNCoMwEIRfpQfJDwTB9miDDyISNhKrrSZhjaVS@uxpUnuYnWGY/fzoY7w20gOuRq0BWZJC42foDaOSCqraLlkBeHu2VcdT4k1zd5NllFABiLCrBTwbNtuHyVlWaFH0/I0mbGhPGHBackcV5WUilsevoHlVf/6Eh9lXltAZz@sY4@CcrEi@RM8wSvjlC9GA8nVUmqSFPH8B "PHP – Try It Online") Explanation: `parse_str` wasn't designed to handle repeated values, but you can persuade it to by naming each value with a trailing `[]`. It also wasn't designed to handle empty names, but since I'm appending `[]` anyway I can also add a `_` to satisfy that case. Having parsed the query string it then remains to join everything back together. [Answer] # [Awk](https://www.gnu.org/software/gawk/manual/gawk.html), ~~144~~ \$\cdots\$~~138~~ 135 bytes ``` BEGIN{RS="&"}{a[$1][j=i[$1]++]=$2;j||(n[m++]=$1)}END{for(l in n){k=n[l];o=k"=";for(j in a[k])o=o (j>0?",":"")a[k][j];printf z o;z="&"}} ``` *Added 6 bytes to fix a bug* *Added 4 bytes to fix a bug kindly pointed out and solved by [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)!!!* *Saved 6 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)!!!* *Saved 3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* [Try it online!](https://tio.run/##JU27CsIwFP2VECQ0VMHWzXAVxCouHXQMGdKh2KTmllpQ@vh1o6nLecPRL@v9ITtf8uF6A8roNGi5SJQ0UAWOYwWLVJhxjJx8zC7hU5YfhxLbqCaVI44PFpyslUCwFKgIjQmNllZxBCSR2a33dEm3lPIQSqNE01auK0lPUPTz8eR9iQgJC8iKWt9Bz3rDCt3C@x8V7LeA9INNV6F7@tUJvg "AWK – Try It Online") [Answer] # [Red](http://www.red-lang.org), 221 bytes ``` func[s][m: copy #()s: split s"&"forall s[s/1: split s/1"="append s/1/1"="put m s/1/1 copy""]foreach v s[m/(v/1): append m/(v/1) rejoin[v/2","]]t: copy""foreach k keys-of m[take/last m/:k repend t[k m/:k"&"]]take/last t t] ``` [Try it online!](https://tio.run/##PY7BisMgEIbveYphCtLCFkn3JvgSvYoHkyjNaqKoDdunz06SbhmQ@Yb5fifbYb3bQenGCVjdc@5V0WoS0Mf0gtP5UgSUFMYKBRm6mE0IUFTh7WfOW5RoUrLzsMGO6VlhOqjZkhA1udb0D1hIn/h54e1FwFt7M2T7E8dZLfyGX6h1Pc5A/Hc9ePsq1@iaSVXjLQ@m0EdceFL3pKr8znQs@Z8VKr2mPM4VHFBclC3bXtYF85Bm779ZZ7L8PUYdow15w/UP "Red – Try It Online") This is awfully long and I'll try to golf it at least a bit. Too bad [Red](http://www.red-lang.org) doesn't have a handy `join` function... [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes ``` ≔E⪪S&⪪ι=θW⁻Eθ§κ⁰υ⊞υ§ι⁰⪫Eυ⁺⁺ι=⪫EΦθ¬⌕λι⊟λ,¦& ``` [Try it online!](https://tio.run/##RY7NCsIwEITvPkXIIWwggj/HkoMXQaFS8AlSrXZxSWqbaN8@Jq3oZdjJzObbS2v6izMU424Y8G6hNB2cO0IPB9sFf/Y92jtIxbjgSecIk9VcJv@UxeLdIjUMSrRhmPafiu38wV6bER6KrXIvSMmqMLQQ/hlOWbGoEsLD0eFMT42K0k@TfEmK/eI9km/6zDg5n5y9AimGMlMq1wHlgSv@PVkWMd6c02uRVdRkWm2meStq0@txfqpFauhNXL7oAw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔E⪪S&⪪ι=θ ``` Split the input on `&`s and split each token on `=`s. ``` W⁻Eθ§κ⁰υ⊞υ§ι⁰ ``` Create a list of unique keys in order of their first appearance. ``` ⪫Eυ⁺⁺ι=⪫EΦθ¬⌕λι⊟λ,¦& ``` For each key, extract and join the values with `,`, concatenate with the key and separator, and join the overall result with `&`. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~319~~ 304 bytes Thanks to ceilingcat for the suggestions. This function scans each tokenized (name,value) pair and adds a list entry for each new name encountered, then appends a list entry for each value. After constructing the lists, it then iterates through each list and prints the values. To save space, I flattened the structures into arrays of `void *`. ``` f(s,t,v,i)char*s,*t;{void*d[3]={t=0},**f,**w;for(;t=strtok(t?0:s,"&");*w=calloc(8,2),w[1]=v){t[i=strcspn(t,"=")]=0;v=t-~i;for(f=&d;strcmp(f[1]?:t,t);f=*f);for(w=f[2]=f[1]?f[2]:(f[1]=t,*f=calloc(8,5))+24;w[1];w=*w);}for(f=&d;i=*f&&printf("&%s="+!!s,f[1]);f=*f)for(w=f[2];s=*w;w=s)i=!printf(",%s"+i,w[1]);} ``` [Try it online!](https://tio.run/##VVDtbsIgFP3fp0AWCSAufmzJIrv6IMYflYqS1bbpxXaJcY@@DtiH2Q/I4dzzEa6ZHo0ZBstRedUpJ8wpbyUq6fW1q10hi@1yB1cPs5uS0obTa1u3XHtA3/r6jfvNbIWKMiq07MHkZVkb/qIWQvXb@Q46cfVbF8UGm4p7RYGKHcx0B3764VKYBVboqDg33AbTZuWVF9qCtCIJerDbxQ7SLKJVkoFX0t4bn4WYLJ50bNU9yF7o21@4C1GMNa2rvOWUjRHoZDRCFWN@iu49GoM7RKBwMPr1qDHSiUt/CsHDg6tMeSkO5BV94erH0zr7R5VuH7ksmMk5dxWPyxTkmhESN0wk6izgtEqCJq9CxfiMVBGGYj3TxLaHA0fxbQnCgHVCzcUjpzS9btltsHUNcxZvti/zE@QJL9k@b@H9m9qzoIBFFgaRnX8aW@ZHHKb9Fw "C (gcc) – Try It Online") Non-golfed version of original submission: ``` struct list { struct list *next; char *name; struct list *value; }; void f(char *s) { char *tok=NULL, *value; struct list d={}, *e, *v; int i; for(; tok=strtok(tok?NULL:s, "&"); ) { tok[i=strcspn(tok, "=")]=0; value=tok+i+1; for(e=&d; e->name && strcmp(e->name, tok); e=e->next); if(!e->name) { e->next=calloc(sizeof(struct list), 2); e->name=tok; e->value=e->next+1; } for(v=e->value; v->name; v=v->next); v->next=calloc(sizeof(struct list), 1); v->name=value; } for(e=&d; e->next; e=e->next, s=0) { printf("&%s="+!!s, e->name); for(v=e->value, i=1; v->next; v=v->next, i=0) printf(",%s"+i, v->name); } } ``` [Try it online!](https://tio.run/##jVLBjtsgEL37KyZUQdCwVby9lZL@wKq3nqoeCMYbVMeOjGOtuvK3pzPBpN5oDz3Yhvcebx7jcQ/Pzl0@hNY158rD1zhUoft02BVLqA/t8z1WNWGP2AXZsxugCXGA1wJguf/Y@pdBI@gOtsedPXp9Lxltc0Z00kUxdqGCWiRxlFe7tBm63@b7j6cnddO/danM64ScJ5640A4Q0BGg7nqhgc6jHj8Cn29k9SUqYJxJDakQkOhnIJmLp5Z0KDBM/jJbfeWvlQ3im7ApE0Tu3vBKg3/Y0fWAcwrmjicxI4p8sYo3BGA/ZDoaarGaJTkAwCwxzjZN50QMf3xXi8VNpYLH2QByTYq0gFLM2SkHnW5xR5M1GsZkgAszvgk3/keOcqGlFLcfMxX3jaEp@NcABdFs851POFtDLRhfR8M2qxX@ldwV/U5mBcGUOudbBCdiK@cuZFO1jmwTVI4oU7rpQuNxtKEVNHHLOYuLmYnOtuixPkamgEe522qoe@9FlDk8tmROeToPUTB2q1B3nSk5vfm@sQdjr@vPfG9785KgPUeFeSyQILT8Cw "C (gcc) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~90~~ 88 bytes ``` StringRiffle[S=StringSplit;List@@@Normal@Merge[Rule@@@S[#~S~"&","=",2],#&],"&","=",","]& ``` [Try it online!](https://tio.run/##NYxBCsIwFET3PUYCfxUX1qV8yQFUpFmGLH4laQNpKzGCIObqMVpkYJg3DDNRGu1EyV@pOCwqRT8PnXcuWK1wRXULPu2P/p6klOclThTkycbB6u4RbO2U5lllBkwwZKI1goMRf6wyUC71KGm@OTjJDWR1pTm/GuaWBbfwdegDjUi/vIOeIj7Xqoe6wJY17/IB "Wolfram Language (Mathematica) – Try It Online") -2 thanks to LegionMammal978 ``` S=StringSplit; Rule@@@S[#~S~"&","=",2] (* Convert to a list of Rules *) Merge[ % ,#&] (* Combine rules into an Association, leaving values unchanged *) Normal@ % (* Convert Association back into a list of Rules, *) List@@@ % (* and turn Rules into Lists *) StringRiffle[ % ,"&","=",","] (* Concatenate, using "&", "=", and "," as separators *) ``` [Answer] # [Perl 5](https://www.perl.org/), `-pF\&` flags, ~~73~~ 57 bytes Uses `-pF\&` to loop over inputs and autosplit on `&`. Unordered results, in parallel competition. ``` /=/,$z{$`}.=$z{$`}?",$'":"$`=$'"for@F;$_=join'&',values%z ``` [Try it online!](https://tio.run/##K0gtyjH9/1/fVl9HpapaJaFWzxZC2yvpqKgrWSmpJNgC6bT8Igc3a5V426z8zDx1NXWdssSc0tRi1ar//9Py820N1UCkWlJOYoZtIphtrJaUWGRbARFKUgOqsDX6l19QkpmfV/xft8AtRg0A "Perl 5 – Try It Online") Uses a hash `%z` to keep track of values for individual names, and then prints them all out at the end. -16 bytes thanks to NahuelFouilleul. [Answer] # [R](https://www.r-project.org/), ~~174~~ 166 bytes ``` function(s,S=strsplit,A=sapply,P=paste,e=A(S(P(el(S(s,'&')),'=',sep=''),'='),c),n=unique(m<-e[1,]))P(n,A(n,function(x)P(e[2,m==x],collapse=',')),sep='=',collapse='&') ``` [Try it online!](https://tio.run/##TY5NCoNADIVvMz@QLrTbZuENBJfiYhwiFcaZqVHQ09tooe0iyccjeS/z4dOUnV/GYcdjWKNQioahQV5mzmFcoEJ2OYcdasyOFwLCyjSmNhRkMGilrQWNGpgyan2xBW8h4hrH10pmetyoLaCztjYRKqlv1CYStSVMiFsHPoXgMpOYnaaXofBPlqy/l40eUsJCnV31wT3RXXxXvZtx@0i9kg0s5fAN "R – Try It Online") For some inexplicable reason I thought that this challenge wouldn't suffer from [R](https://www.r-project.org/)'s awfully-verbose string handling. This didn't turn out to be the case, at least based on my attempt so far... Commented before golfing: ``` compactify= function(s, # s = string to compactify S=strsplit, # S = alias to strsplit() function A=sapply, # A = alias to sapply() function P=paste, # P = alias to paste() function a=el( # a = the first element of ... S(s,'&')) # ...s split on '&' b=S(a,,'=') # b = each element of a, split on '=' # Now, unfortunately if there's nothing after the '=', # the strsplit() function fails to add an empty string '' # so we need to do this ourselves: e=A(b,function(x)c(x,'') # e = for each element of b, add a '' ... [1:2]) # ...and then take the first two elements # This gives us a 2-row matrix, with the names in row 1, # and the values in row 2 n=unique(m<-e[1,])) # n = unique names, m = all names of name-value pairs m=A(n,function(x) # m = for each element of n... P(e[2,m==x],collapse=',')) # ...paste together the values for this name, using ',' as separator P(n,m,sep='=',collapse='&') # Finally, paste together the pairs of elements in m, using '=' as separator... # ...and collapse them all into one string using '&' as separator ``` [Answer] # [R](https://www.r-project.org/), ~~162~~ ~~157~~ 151 bytes ``` function(s,S=substring)paste0(z<-unique(k<-S(x<-el(strsplit(s,"&")),1,y<-regexpr('=',x))),sapply(split(S(x,y+1),k),paste,collapse=',')[z],collapse='&') ``` [Try it online!](https://tio.run/##TYzLCsMgFER/JWThg16habf6FVmWLjRoKhVjfYDJz6c22XQzDIczE3fTcdbtpvgp28WTBKNIRaUcrZ9pkCnrK9k4K95@iiZvzkZSOdOONCUFZ3Ob9KinFAZYOYt61jVEggWGShtNMgS3klNtW1gvA4U3heMbpsU5GZJuOqaP7fkHEKa7IdgsixjQL5Fy8iXk0e9IySjqiRRqhrg1/ws "R – Try It Online") *-6 bytes thanks to Dominic van Essen* A nice single line function. Ungolfed: ``` function(s,S=substr){ pairs <- el(strsplit(s,"&")) # split on '&' getting list of pairs loc <- regexpr('=',pairs) # find location of each '=' in each pair keys <- substr(pairs,1,loc) # get the key, including the '=' values <- substr(pairs,loc + 1,nchar(pairs)) # get the values (everything after '=') unq_keys <- unique(keys) # uniquify the keys. This retains the order. split_vals <- split(values,keys) # group the values into sublists by which key they are associated with collapsed_values <- sapply(split_vals,paste,collapse=',') # join each subgroup of values by ',' collapsed_values <- collapsed_values[unq_keys] # and reorder them to match the order of the keys paste0(unq_keys,collapsed_values,collapse='&') # concatenate keys and values and join by '&' } ``` ]
[Question] [ Your program has to print out a number of spaces, followed by a dot and a newline. The number of spaces is the x position of your dot defined with 0 < x < 30 Every new line is a turn. Your program runs for 30 turns. Your program starts with a random x position and every turn shifts this position randomly by 1 to the left or right, while staying inside the defined area. Every turn your dot has to change its position by 1. Your score is the number of characters. You get 10 bonus points, if every printed line consists of exactly 30 characters (and newline). You get 50 bonus points, if, while random, your program tends to stay in the middle of the defined area. **Edit:** The 50 bonus points are intended to pull your dot to the middle. For example, this apply's if your dot is at x=20 and has a chance of 66% to go left and 33% to go right. This has to be independent from starting point and should only happen by altering the percentage value of left/right dynamically. No input of any kind allowed, output has to be on the executing console! For better understanding, here is a readable example in java, that would give you a score of 723: ``` public class DotJumper{ public static void main(String[] args){ int i = (int)(Math.random()*30); int max = 29; int step = 1; int count = 30; while(count>0){ if(i<=1){ i+=step; }else if(i>=max){ i-=step; }else{ if(Math.random() > 0.5){ i+=step; }else{ i-=step; } } print(i); count--; } } public static void print(int i){ while(i>0){ System.out.print(' '); i--; } System.out.println('.'); } } ``` [Answer] # APL, 39 – 10 – 50 = –21 ``` 0/{⎕←30↑'.',⍨⍵↑''⋄⍵+¯1*⍵>.5+?28}/31/?29 ``` Tested on Dyalog with `⎕IO←1` and `⎕ML←3` but it should be quite portable. **Explanation** ``` ?29 take a random natural from 1 to 29 31/ repeat it 31 times }/ reduce (right-fold) the list using the given function: ⍵↑'' . make a string of ⍵ (the function argument) spaces '.',⍨ . append a dot to its right ⎕←30↑ . right-pad it with spaces up to length 30 and output ◇ . then ?28 . take a random natural from 1 to 28 .5+ . add 0.5, giving a number ∊ (1.5 2.5 ... 27.5 28.5) ⍵> . check whether the result is <⍵ (see explanation below) ¯1* . raise -1 to the boolean result (0 1 become resp. 1 -1) ⍵+ . add it to ⍵ and return it as the new accumulator value 0/{ finally ignore the numeric result of the reduction ``` At every step, this code decides whether to move the dot to the left or to the right depending on the probability that a random number chosen among (1.5 2.5 ... 27.5 28.5) is less than the current dot position. Therefore, when the current dot position (number of spaces to the left) is 1 the increment is always +1 (all of those numbers 1.5 ... 28.5 are > 1), when it's 29 it's always -1 (all of those numbers are < 29); otherwise it's chosen randomly between +1 and -1, with a probability that's a linear interpolation between those extremes. So the dot is always moving and always more likely to move towards the center than towards the sides. If it's exactly in the middle, it has a 50% chance to move to either side. The reduction (right-fold) of a replicated value `{...}/a/b` is just a trick I came up with to repeat a function `a-1` times, starting with value `b` and having the result of each iteration be the accumulator (`⍵`) argument to the next. The second and next input arguments (`⍺`) as well as the final result are ignored. It turns out to be way shorter than a regular recursive call with guard. **Example run** ``` 0/{⎕←30↑'.',⍨⍵↑''⋄⍵+¯1*⍵>.5+?28}/31/?29 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ``` [Answer] ## Mathematica 138 - 10 - 50 = 78 I'm not posting this because I think it's particularly well golfed, but for other reasons. It uses a [Markov Process](http://en.wikipedia.org/wiki/Markov_chain) definition with a transition matrix designed to get the ball "centered". The use of a Markov process in Mathematica [allows us to calculate some useful statistics](http://reference.wolfram.com/mathematica/ref/MarkovProcessProperties.html), as you will see below. First the code (spaces not needed): ``` r = Range@28/28; s = DiagonalMatrix; ListPlot[RandomFunction[DiscreteMarkovProcess[RandomInteger@#, r~ s ~ -1 + s[29/28- r, 1]], #], PlotRange -> #] &@{1, 29} ``` Some outputs: ![Mathematica graphics](https://i.stack.imgur.com/nE3Om.png) The transition matrix I used is: ``` MatrixPlot[s[r, -1] + s[29/28 - r, 1]] ``` ![Mathematica graphics](https://i.stack.imgur.com/gbPhM.png) But as I said, the interesting part is that using `DiscreteMarkovProcess[]` allows us to grab a good picture of what's happening. Let's see the probability of the ball being at `15` at any time `t` *starting from a particular random state*: ``` d = DiscreteMarkovProcess[RandomInteger@29, s[r, -1] + s[29/28 - r, 1]]; k[t_] := Probability[x[t] == 15, x \[Distributed] d] ListLinePlot[Table[k[t], {t, 0, 50}], PlotRange -> All] ``` ![Mathematica graphics](https://i.stack.imgur.com/05VLC.png) You can see it fluctuates between 0 and a value near 0.3, that is because depending on the starting state you can only reach 15 on an odd or even number of steps :) Now we can do the same thing, but telling Mathematica to consider the statistic starting from all possible initial states. What is the probability of being at `15` after a time `t`?: ``` d = DiscreteMarkovProcess[Array[1 &, 29]/29, s[r, -1] + s[29/28 - r, 1]]; k[t_] := Probability[x[t] == 15, x \[Distributed] d] ListLinePlot[Table[k[t], {t, 0, 100}], PlotRange -> All] ``` ![Mathematica graphics](https://i.stack.imgur.com/xUw4l.png) You can see it also oscillates ... why? The answer is simple: in the interval `[1, 29]` there are more odd than even numbers :) The oscillation is almost gone if we ask for the probability of the ball being at `14 OR 15`: ![Mathematica graphics](https://i.stack.imgur.com/5P2qY.png) And you could also ask for the limit (in the Cesaro sense) of the state probabilities: ``` ListLinePlot@First@MarkovProcessProperties[d, "LimitTransitionMatrix"] ``` ![Mathematica graphics](https://i.stack.imgur.com/lOmbq.png) Oh, well, perhaps I deserve some downvotes for such an off-topic answer. Feel free. [Answer] # Bash, score 21 (81 bytes - 50 bonus - 10 bonus) ``` o=$[RANDOM%28];for i in {D..a};{ printf " %$[o+=1-2*(RANDOM%29<o)]s.%$[28-o]s ";} ``` In this answer, the dot is "pulled" back to the middle. This can be tested by hardcoding the starting point at 0 or 30. [Answer] ## Ruby 69 66 64-60 = 4 ``` i=rand(30);30.times{a=' '*30;a[i]=?.;puts a;i+=rand>i/29.0?1:-1} ``` **Sample:** ``` . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ``` [Answer] # Smalltalk, 161 159 145-60 = 85 all columns are 30chars long (operating in mutable string b); random movement chance is adjusted by biasing rnd value with p (rnd(0..29)-p), taking the sign (-1/0/1) and then adjusting to (-1/+1) via (-1|1), which is taken as move delta (effectively computes: x sign<=0 ifTrue:-1 ifFalse:1). As ST uses 1-based indexing, I have to adjust all string refs by +1 (plz appreciate the -1|1 bit fiddling hack ;-) ). ``` p:=((r:=Random)next*29)rounded.(b:=String new:30)at:p+1put:$..0to:29do:[:i|b at:p+1put:$ .p:=(p+(((r next*29)-p)sign-1|1))min:29max:0.b at:p+1put:$..b printCR] ``` stealing an idea from Ruby version (thanx&Up @fipgr), I can get rid of the min/max check: ``` p:=((r:=Random)next*29)rounded.(b:=String new:30)at:p+1put:$..1to:30 do:[:i|b at:p+1put:$ .p:=p+((r next-(p/29))sign-1|1).b at:p+1put:$.;printCR] ``` output: (I have manually added the col-numbers and vertical bars afterwards; the code above does not generate them) ``` 012345678901234567890123456789 | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | | . | 012345678901234567890123456789 ``` [Answer] ## C, 86 Assuming that seeding the `rand()` function is not required. ``` k=30;main(i){i=rand()%k;while(k--){printf("%*c\n",i+=i==30?-1:i==1||rand()%2?1:-1,46);}} ``` Explanation: In C, in `"%*c"` the `*` means that the length of the output will have a minimum length, and this minimum length is determined by the argument of the function call (in this case, it is `i+=i==30?-1:i==1||rand()%2?1:-1`. The `c` means the next argument (`46`) is a character (the dot). As for the boundary check, I apologise that I forgot about that. I have now added this to the answer, at the cost of 15 chars. The ternary operator works as follows: `boolean_condition?value_if_true:value_if_false`. Note that in C true is 1 and false is 0. [Answer] # Java: ~~204~~ ~~183~~ ~~182~~ ~~176~~ 175 characters - 10 - 50 = 115 ``` class K{public static void main(String[]y){int k,j=0,i=(int)(29*Math.random());for(;j++<30;i+=Math.random()*28<i?-1:1)for(k=0;k<31;k++)System.out.print(k>29?10:k==i?'.':32);}} ``` First, the dot position must be `0 < x < 30`, i.e. [1-29]. This generates a number between 0 and 28 uniformly distributed, and for the purposes of this program [0-28] has the same effect as [1-29]: ``` i=(int)(29*Math.random()); ``` I personally preferred if it would be normally distributed around 14, but my answer would be longer: ``` i=0;for(;j<29;j++)i+=(int)(2*Math.random()); ``` Second, this code ensures that it tends to be in the middle: ``` i+=Math.random()*28<i?-1:1 ``` The probability to get +1 is larger as smaller is the value of `i`, and we have the opposite for -1. If `i` is 0, the probability of getting +1 is 100% and the probability of getting -1 is 0%. If `i` is 28, the opposite to that will happen. Third, by replacing the `32` at the end by `'_'` to see the output easier, we see that each line has 30 characters plus a new line: ``` __________.___________________ _________.____________________ ________._____________________ _________.____________________ __________.___________________ ___________.__________________ __________.___________________ _________.____________________ ________._____________________ _________.____________________ ________._____________________ _________.____________________ __________.___________________ _________.____________________ __________.___________________ ___________.__________________ __________.___________________ _________.____________________ __________.___________________ ___________.__________________ ____________._________________ _____________.________________ ____________._________________ _____________.________________ ______________._______________ _____________.________________ ______________._______________ _______________.______________ ______________._______________ _____________.________________ ``` Thanks to @VadimR (now, user2846289) for pointing out a misunderstanding in a prior version. Thanks to @KevinCruijssen for shaving out 6 characters, even after more than two and a half years after this answer was initially posted. [Answer] # Mathematica 157-10-50 = 97 A random number from 1-30 is used for starting. All the remaining column numbers from the dot are chosen via `RandomChoice[If[c > 15, {2, 1}, {1, 2}] -> {-1, 1}] + c`, which translates to: "If the prior column number was greater than 15, select one number from the set {-1,1}, with -1 weighted 2:1 with respect to 1; otherwise, flip the weights and choose from the same set. `ReplacePart` replaces the element in a list of 30 blank spaces that corresponds to the column of interest. ``` f@c_ := Switch[d = RandomChoice[If[c > 15, {2, 1}, {1, 2}] -> {-1, 1}] + c, 1, 2, 30, 29, d, d] Row@ReplacePart[Array["_" &, 29], # -> "."] & /@ NestList[f, RandomInteger@29+1, 30] // TableForm ``` ![dot](https://i.stack.imgur.com/JZCrV.png) [Answer] # ><>, 358 - 10 = 348 This won't win at codegolf, but it works. (On windows 7 with [this interpreter](https://gist.github.com/anonymous/6392418), which implements the "p" instruction differently than the esolang page defines it) ``` 1v >a" "v v< 0<} vooooooooooooooooooooooooooooooo< & _> v : >$" "@p1+:2f*(?v; |x1> v^}! < |xx2> v p |xxx3>v |xxxx4v $ >!|xxx< v } |xxxx6v } |xxx7>v @ |xx8> v : |x9v < @> 5)?v$:67*)?vv _>>&?v!@^ >$:b(?v v v }"."< : v+ 1< < >a+b+00}^0}}${"."< <- 1< ``` The name of this language can't be googled, so here's its [esolang article](http://esolangs.org/wiki/fish) for the curious. [Answer] # PHP, 118 113 112 111 (, -10 bonus points = 101) *(second try, with horribly predictable `rand()` behavior, and a little more efficiency)* ``` for($n=30,$i=rand(1,29),$t=$s=pack("A$n",'');$n--;$i+=$i<2|rand()%2&$i<28?1:-1,$t=$s){$t[$i-1]='.';echo"$t\n";} ``` Possible result: ``` ______._______________________ _____.________________________ ______._______________________ _____.________________________ ______._______________________ _____.________________________ ______._______________________ _____.________________________ ______._______________________ _____.________________________ ______._______________________ _____.________________________ ______._______________________ _____.________________________ ______._______________________ _____.________________________ ______._______________________ _____.________________________ ______._______________________ _____.________________________ ______._______________________ _____.________________________ ______._______________________ _____.________________________ ______._______________________ _____.________________________ ______._______________________ _____.________________________ ______._______________________ _____.________________________ ``` # PHP, 130 (, -10 bonus points = 120) *(first try)* This could probably still be much more efficient: ``` for($n=30,$i=rand(1,29),$t=$s=str_repeat(' ',$n)."\n";$n--;$i=$i<2?2:($i>28?28:(rand(0,1)?$i+1:$i-1)),$t=$s){$t[$i-1]='.';echo$t;} ``` If I replace the space with an underscore (for display purposes), this is a possible result: ``` ________._____________________ _______.______________________ ______._______________________ _______.______________________ ________._____________________ _______.______________________ ______._______________________ _______.______________________ ______._______________________ _______.______________________ ________._____________________ _______.______________________ ________._____________________ _________.____________________ __________.___________________ ___________.__________________ __________.___________________ ___________.__________________ __________.___________________ _________.____________________ ________._____________________ _________.____________________ ________._____________________ _______.______________________ ______._______________________ _____.________________________ ____._________________________ _____.________________________ ____._________________________ ___.__________________________ ``` Oddly enough, if I replace `rand(0,1)` with `rand()%2` (PHP 5.4, on Windows XP), the random result always switches from odd to even, and vice versa, on each next iteration, making `rand()` worryingly predictable, in that sense, all of a sudden. This 'bug' appears to be one that has been [known since 2004](https://bugs.php.net/bug.php?id=27052). Not entirely sure whether it's exactly the same 'bug' though. [Answer] ## J 42 characters - 50 -10 = -18 ``` '_.'{~(|.~((I.%<:@#)*@-?@0:))^:(<@#)1=?~30 ``` Explanation, starting from the right (some knowledge about [trains](http://www.jsoftware.com/help/dictionary/dictf.htm) comes in handy): ``` init=: 0=?~30 NB. where is the 0 in the random permutation of [0,29] rep =: ^:(<@#) NB. repeat as many times as the array is long, showing each step rnd =: ?@0: NB. discards input, generates a random number between 0 and 1 signdiff =: *@- NB. sign of the difference (because this works nicely with NB. the shift later on). left_prob =: (I.%<:@#) NB. probability of shifting left. The position of the one (I.) divided by the length -1. shift =: |.~ NB. x shift y , shifts x by y positions to the left. output =: {&'_.' NB. for selecting the dots and bars. NB. Piecing things together: output (shift (left_prob signdiff rnd))rep init ``` Center tendency, -50, example over 1000 runs: ``` NB. Amounts of ones in each column (sum) ]a=:+/ (|.~((I.%<:@#)*@-?@0:))^:(<1000)0=?30 0 0 0 0 0 0 2 6 10 12 25 60 95 121 145 161 148 99 49 27 19 13 6 1 1 0 0 0 0 0 +/a NB. check the number of ones in total 1000 |. |:(<.a%10) #"0 1] '*' NB. plot of those values * * *** *** **** **** **** ****** ****** ****** ******* ******* ******** ******** ********** ************** ``` Example run, outputting exactly 30 bytes each line ``` _______________.______________ ________________._____________ _______________.______________ ________________._____________ _______________.______________ ________________._____________ _______________.______________ ________________._____________ _______________.______________ ________________._____________ _______________.______________ ______________._______________ _______________.______________ ________________._____________ _________________.____________ ________________._____________ _______________.______________ ______________._______________ _____________.________________ ____________._________________ ___________.__________________ __________.___________________ ___________.__________________ __________.___________________ ___________.__________________ __________.___________________ ___________.__________________ ____________._________________ _____________.________________ ______________._______________ ``` [Answer] ## Python 2.7: ~~126~~ 109 -10-50 = 49 Got rid of the hard-coded starting point - now starts at random point. Because of this, I needed randint, so I decided to use that instead of choice for the offset. Used the (-1)\*\*bool trick for that. ``` from random import randint as r;p=r(0,29) for i in range(30): print' '*p+'.'+' '*(29-p);p+=(-1)**(r(0,29)<p) ``` Some great answers here. First attempt in Python, thinking about improvements. Not helped by the need for an import. -10 - yes 30 chars + \n on each line -50 - the further away from the centre, the more likely a move the other way (accomplished by building a list with a different number of +/i offsets) Previous attempt: ``` from random import choice;p,l=15,[] for i in range(30): q=29-p;l+=[' '*p+'.'+' '*q];p+=choice([1]*q+[-1]*p) print'\n'.join(l) ``` [Answer] # Java - ~~198~~ 183 characters This is just a plain, simple, direct and uncreative golf of the example that you had given in the question. ``` class A{public static void main(String[]y){int c,j,i=(int)(Math.random()*30);for(c=30;c>0;c--)for(j=i+=i<2?1:i>28?-1:Math.random()>0.5?1:-1;j>=0;j--)System.out.print(j>0?" ":".\n");}} ``` [Answer] ## Batch - (288 Bytes - 10) 278 ``` @echo off&setlocal enabledelayedexpansion&set/ap=%random%*30/32768+1&for /l %%b in (1,1,30)do (set/ar=!random!%%2&if !r!==1 (if !p! GTR 1 (set/ap-=1)else set/ap+=1)else if !p! LSS 30 (set/ap+=1)else set/ap-=1 for /l %%c in (1,1,30)do if %%c==!p! (set/p"=."<nul)else set/p"=_"<nul echo.) ``` Un-golfed: ``` @echo off setlocal enabledelayedexpansion set /a p=%random%*30/32768+1 for /l %%b in (1,1,30) do ( set /a r=!random!%%2 if !r!==1 ( if !p! GTR 1 (set /a p-=1) else set /a p+=1 ) else if !p! LSS 30 (set /a p+=1) else set /a p-=1 for /l %%c in (1,1,30) do if %%c==!p! (set /p "=."<nul) else set /p "=_"<nul echo. ) ``` To output spaces instead of underscores - **372 Bytes** - ``` @echo off&setlocal enabledelayedexpansion&for /f %%A in ('"prompt $H &echo on&for %%B in (1)do rem"')do set B=%%A set/ap=%random%*30/32768+1&for /l %%b in (1,1,30)do (set/ar=!random!*2/32768+1&if !r!==1 (if !p! GTR 1 (set/ap-=1)else set/ap+=1)else if !p! LSS 30 (set/ap+=1)else set/ap-=1 for /l %%c in (1,1,30)do if %%c==!p! (set/p"=."<nul)else set/p"=.%B% "<nul echo.) ``` Looking for some help with the following logic, surely this isn't the most space efficient method (!r! will expand to either 1 or 2) - ``` if !r!==1 ( if !p! GTR 1 (set /a p-=1) else set /a p+=1 ) else if !p! LSS 30 (set /a p+=1) else set /a p-=1 ``` *It golfs down to: `if !r!==1 (if !p! GTR 1 (set/ap-=1)else set/ap+=1)else if !r! LSS 30 (set/ap+=1)else set/ap-=1`* [Answer] ## J, 42 characters, no bonuses ``` ' .'{~(i.30)=/~29<.0>.+/\(-0&=)?(,2#~<:)30 ``` Example run: ``` ' .'{~(i.30)=/~29<.0>.+/\(-0&=)?(,2#~<:)30 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ``` [Answer] ## Python 2.7 (126 - 10 (fix length) - 50 (Center Tendency) = 66) The following program have a center tendency over a larger sample ``` s=id(9)%30 for e in ([[0,2][s>15]]*abs(s-15)+map(lambda e:ord(e)%2*2,os.urandom(30)))[:30]: s+=1-e;print" "*s+"."+" "*(28-s) ``` **Demo** ``` . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ``` [Answer] ## Javascript 125 73 72 60 (120 - 50 - 10) ``` i=0;r=Math.random;s=r()*30|0;do{a=Array(30);a[s=s>28?28:s?r()<s/30?s-1:s+1:1]='.';console.log(a.join(' '))}while(++i<30) ``` **EDIT:** Fix for 50 point bonus and 10 point bonus. **EDIT 2:** Even shorter! [Answer] ## D - ~~167~~, ~~162~~, 144 ( 154 - 10 ) **Golfed**: ``` import std.stdio,std.random;void main(){int i=uniform(1,30),j,k;for(;k<30;++k){char[30]c;c[i]='.';c.writeln;j=uniform(0,2);i+=i==29?-1:i==0?1:j==1?1:-1;}} ``` **Un-golfed**: ``` import std.stdio, std.random; void main() { int i = uniform( 1, 30 ), j, k; for(; k < 30; ++k ) { char[30] c; c[i] = '.'; c.writeln; j = uniform( 0, 2 ); i += i == 29 ? -1 : i == 0 ? 1 : j == 1 ? 1 : -1; } } ``` **EDIT 1** - I'm not quite sure if my code qualifies for the -50 bonus or not. `i` doesn't always start in the middle, but during the `for` loop, the dot never moves more than like 3 places either direction, so when `i` *does* start near the middle, the whole thing tends to stay there as well. **EDIT 2** - Code now qualifies for the -10 bonus, as it prints an array of 29 characters followed by LF for a total of exactly 30 chars per line. [Answer] **PowerShell, 77 - 10 - 50 = 17** ``` $x=random 30 1..30|%{$x+=random(@(-1)*$x+@(1)*(29-$x)) '_'*$x+'.'+'_'*(29-$x)} ``` Output ``` _.____________________________ __.___________________________ ___.__________________________ ____._________________________ ___.__________________________ ____._________________________ _____.________________________ ______._______________________ _______.______________________ ______._______________________ _____.________________________ ______._______________________ _______.______________________ ________._____________________ _________.____________________ __________.___________________ ___________.__________________ __________.___________________ ___________.__________________ ____________._________________ ___________.__________________ __________.___________________ _________.____________________ __________.___________________ _________.____________________ ________._____________________ _________.____________________ ________._____________________ _________.____________________ __________.___________________ ``` [Answer] ### R, 107 characters - 60 points bonus=47 ``` s=sample;i=s(29,1);for(j in 1:30){a=rep(' ',30);i=i+s(c(-1,1),1,p=c(i-1,29-i));a[i]='.';cat(a,'\n',sep='')} ``` `i` is the index of the dot. `a` is the array of 30 spaces. Starting point is random (uniformly from 1 to 29). At each iteration we randomly add -1 or +1 to `i` with weighted probabilities: `i-1` for `-1` and `29-i` for `+1` (values fed as probabilities don't need to sum to one), meaning that it tends to orient the dot towards the center while preventing it from below 1 or above 29 (since their probability fall to 0 in both case). Example run with `_` instead of spaces for legibility: ``` > s=sample;i=s(1:30,1);for(j in 1:30){a=rep('_',30);i=i+s(c(-1,1),1,p=c(i-1,29-i));a[i]='.';cat(a,'\n',sep='')} _______________________.______ ______________________._______ _____________________.________ ______________________._______ _____________________.________ ______________________._______ _____________________.________ ______________________._______ _____________________.________ ____________________._________ _____________________.________ ______________________._______ _____________________.________ ______________________._______ _____________________.________ ____________________._________ ___________________.__________ ____________________._________ ___________________.__________ __________________.___________ _________________.____________ ________________._____________ _______________.______________ ______________._______________ _______________.______________ ________________._____________ _________________.____________ ________________._____________ _______________.______________ ______________._______________ ``` [Answer] ## C# 184 - 10 - 50 = 123 ``` using System;namespace d{class P{static void Main(){var r=new Random();int p=r.Next(30);for(int i=0;i<30;i++){Console.WriteLine(".".PadLeft(p+1).PadRight(29));p+=r.Next(30)<p?-1:1;}}}} ``` **Output** `space` replaced with `\_` for legibility. ``` ____________.________________ ___________._________________ __________.__________________ ___________._________________ ____________.________________ _____________._______________ ______________.______________ _____________._______________ ______________.______________ _______________._____________ ______________.______________ _______________._____________ ______________.______________ _______________._____________ ______________.______________ _____________._______________ ____________.________________ ___________._________________ ____________.________________ _____________._______________ ______________.______________ _____________._______________ ____________.________________ ___________._________________ ____________.________________ ___________._________________ ____________.________________ ___________._________________ __________.__________________ ___________._________________ ``` [Answer] **PHP** With the centring bonus: 82 - 50 = 32 ``` $i=rand(0,29);for($c=0;$c++<30;rand(0,28)<$i?$i--:$i++)echo pack("A$i",'').".\n"; ``` For this version (old versions below), removed the min/max checking as that's taken care of in the centring code. `rand(1,28)` becomes important here as it allows for the `$i++` to push itself up to 29 (actual max). edit: unnecessary parenthesis, moved shifting code --- Simple algorithm for centring: generates a new number between 0 and 29 and compares it to the current one. Takes advantage of the "probability" of getting a number on the bigger side to draw towards the centre. Actual result: (line numbering added afterwards) ``` 01| . 02| . 03| . 04| . 05| . 06| . 07| . 08| . 09| . 10| . 11| . 12| . 13| . 14| . 15| . 16| . 17| . 18| . 19| . 20| . 21| . 22| . 23| . 24| . 25| . 26| . 27| . 28| . 29| . 30| . ``` Archived: `$i=rand(0,29);for($c=0;$c++<30;){($i<1?$j=1:($i>28?$j=28:$j=rand(0,29)));($j<$i?$i--:$i++);echo pack("A$i",'').".\n";}` 119 characters `$i=rand(0,29);for($c=0;$c++<30;){($i<1?$i++:($i>28?$i--:(rand(0,29)<$i?$i--:$i++)));echo pack("A$i",'').".\n";}` 112 characters [Answer] # JavaScript ES6 125 - 10 (30 character lines) - 50 (shifts toward middle) = 65 I had an epiphany going up the lift to my unit, so I had to get it down before it left my memory... ``` z=(j=Array(t=29).join`_`)+"."+j;x=(r=Math.random)()*t;for(i=30;i--;)console.log(z.substr(x=(x+=r()<x/t?-1:1)>t?t:x<0?0:x,30)) ``` A little variable positional shuffling and a little creativity for calculating the shift probability indicated by `x/t`... (Thanks Kostronor for pointing it out!) I now gain the -50 bonus for shift to the middle, and I also made the starting position within the full range of the line, which allowed me to shave two bytes! ``` ....5....0....5....0....5....0 <-- Ruler _.____________________________ __.___________________________ ___.__________________________ __.___________________________ ___.__________________________ __.___________________________ _.____________________________ __.___________________________ ___.__________________________ __.___________________________ ___.__________________________ ____._________________________ _____.________________________ ______._______________________ _______.______________________ ________._____________________ _______.______________________ ______._______________________ _______.______________________ ________._____________________ _______.______________________ ________._____________________ _________.____________________ __________.___________________ _________.____________________ __________.___________________ ___________.__________________ ____________._________________ _____________.________________ ______________._______________ ``` [Answer] # k, 53 - 10 - 50 = -7 **Solution 1** ``` {{a:30#" ";a[x]:".";a}'{x+$[*x<1?!30;1;-1]}\[x;*1?x]} ``` ### Usage ``` {{a:30#" ";a[x]:".";a}'{x+$[*x<1?!30;1;-1]}\[x;*1?x]}30 " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " " . " ``` **Solution 2** ``` {r::x;{a:r#" ";a[x]:".";a}'{a:r#0b;a[x?r]:1b;x+$[a@*1?r;-1;1]}\[x;*1?x]}[30] ``` [Answer] # Scala, 95 - 10 = 85 bytes ``` def r=math.random Seq.iterate(r*30,30){n=>println(("#"*30)updated(n.toInt,'.')) (r*2-1+n)round} ``` I'm still thinking about the 50 byte bonus. Explanation: ``` def r=math.random //define a shortcut for math.random, which returns a number 0 <= n < 1 Seq.iterate( //build a sequence, r*30, //starting with a random number bewteen 0 and 29 30 //and containing 30 elements. ){n=> //Calculate each element by applying this function to the previous element println( //print... (" "*30) //30 spaces updated(n.toInt,'.') //with the n-th char replaced with a dot ) //and a newline. //The next element is (r*2-1+n) //an random number between -1 and 1 plus n round //rounded to the nearest integer. } ``` [Answer] ## Javascript, 125 (135 - 10) ``` q=Math.random,p=~~(q()*31)+1;for(i=0;i++<30;){s='',d=j=1;for(;j++<31;)s+=j==p?'.':" ";p+=q()<.5?1:-1;p-=p>28?2:p<2?-2:0;console.log(s)} ``` Comments and advice is welcome. [Answer] # JavaScript ### 114 chars - 10 (30 char lines) - 50 (pull dot towards the middle) = 54 ``` for(f=Math.random,a=[],i=30,j=k=f()*i|0;i--;a[j]='.',a[j+=29-k]='\n',j+=k+=f()>k/29?1:-1);console.log(a.join('-')) ``` However, I noticed that a 10 character reward for filling up the lines to 30 chars may be a bad deal; so: ## 102 chars - 50 (pull dot towards the middle) = 52 ``` for(f=Math.random,a=[],i=30,j=k=f()*i|0;i;i--,a[j]='.\n',j+=k+=f()>k/29?1:-1);console.log(a.join('-')) ``` Kudos to @WallyWest for the simplified pull direction conditional `f()>k/29?1:-1`, my first draft used two nested conditionals. [Answer] ## Racket 227 bytes (-10 for 30 characters, -50 for shift to midline = 167) At each step, dot is twice more likely to move towards midline than away from it: ``` (let lp((r(random 1 31))(c 0)(g(λ(n)(make-string n #\space))))(set! r (cond[(< r 1)1][(> r 30)30][else r]))(printf"~a~a~a~n"(g r)"*"(g(- 29 r))) (when(< c 30)(lp(+ r(first(shuffle(if(> r 15)'(-1 -1 1)'(1 1 -1)))))(add1 c)g))) ``` Ungolfed: ``` (define (f) (let loop ((r (random 1 31)) (c 0) (g (λ (n) (make-string n #\space)))) (set! r (cond [(< r 1) 1] [(> r 30) 30] [else r] )) (printf "~a~a~a~n" (g r) "*" (g (- 29 r))) (when (< c 30) (loop (+ r (first (shuffle (if (> r 15) '(-1 -1 1) '(1 1 -1))))) (add1 c) g)))) ``` Testing: ``` (println "012345678901234567890123456789") (f) ``` Output: ``` "012345678901234567890123456789" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ``` ]
[Question] [ Relatable scenario: I'm going to the store to buy a single item, but only have a $100k bill. As a result, I need exactly $99,979 in change, and in the fewest coins/bills possible because I'm quite obviously a very practical person. The denominations of these coins/bills follow the [hyperinflation sequence](https://oeis.org/A051109): \$1, 2, 5, 10, 20, 50, 100, 200\$, and so on. (I'd proposed an OEIS sequence for this, but the first 100k terms are identical to another one so it got rejected) **Task:** Given an amount of money as a nonnegative integer, such as \$73\$, return the minimum number of coins/bills needed to total to that amount. In this example, it would be \$4\$. The coins required would be \$50 + 20 + 2 + 1\$. As per the standard rules for [sequence](/questions/tagged/sequence "show questions tagged 'sequence'"), you can also choose to return all terms up to an inputted index, or return a (potentially infinite) lazy list or generator that represents the whole sequence. **Test cases:** ``` 0 0 1 1 2 1 3 2 4 2 5 1 6 2 7 2 8 3 9 3 10 1 11 2 20 1 30 2 37 4 90 3 111 3 147 5 1000 1 1002 2 1010 2 12478 9 ``` **Other:** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes per language wins! [Answer] # [Husk](https://github.com/barbuz/Husk), ~~11~~ ~~9~~ 8 bytes *Edit: -1 byte thanks to caird coinheringaahing* ``` ṁo⌈½ṁB5d ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8f/DnY35j3o6Du0FMpxMU/7//x9toGOoY6RjrGOiY6pjpmOuY6FjqWMIFDTUMTQyMbeIBQA "Husk – Try It Online") ``` d # get the digits ṁB5 # convert them all to base-5 # (this gives a 1 for each 5-denomination coin needed, # as well as the leftover for each digit. # We'll need 2 more coins for those with leftover 3 or 4, # and only one more coin if the leftover is 1 or 2.) ṁo # So: map across all the base-5 digits ½ # dividing each of them by 2 ⌈ # and then getting the ceiling; # and finally output the sum ``` [Answer] # JavaScript (ES7), ~~36~~ 35 bytes Similar to other answers. Using a Black Magic formula instead of a lookup table. ``` f=n=>n&&(n%10)**29%3571%4+f(n/10|0) ``` [Try it online!](https://tio.run/##fdBBDoIwEAXQvadgAy0YZaYtFhZ4F4JiNKQ1Ylx590ow0aak0@3Ln/6ZW/fqpv5xvT93xp7Ozg2taY8my7hJEfKiEE0qK42p2g7clAhvyF1vzWTH8360Fz5wBiyZX54nZZnAJkD0EEMUFEoPRYiKwooae6CSmsLaQxliQyEuJ4oUQmTxPwWVlEAkpf6jWrX1kuu2S6MYKv3Dar0nzINjewIIFmuLgBBHoXTNvti4Dw "JavaScript (Node.js) – Try It Online") [Here](https://tio.run/##Rc9ta4MwEAfw936K/4sWknqVuHUPpXPQ9mOUQsWmw2GMqPON@NndneIGF3Ihv8tdvtMubbI6r9pt6e92HDNfNi2OSHAxhHiKpyn@kmeO6yGY5elfzlc7wgvhlfBGeCfsWQYPX6vCtqgYxwfePhAbw0kYavQBsAA3AzcDIW4hgIAzg1Pk0kqVSD5RYrPh59ZcscZOcyuB@UOdo9refzKrVJP52hI6Qq6lZDojhOqQJDhe8qsmGC2H2CytAPmdL2xU@C91k7lXfTXQNOCqd8ONewkbAlnDOP4C) is a script that looks for \$(p,m)\$ pairs such that \$(n^p\bmod m)\bmod 4=a\_n\$ for all \$n\in[0..9]\$. It's worth noting that this code takes IEEE-754 precision errors into account. So the results are correct but the math is wrong. With exact values, we could do instead: $$\big((n \bmod 10)^{18}\bmod 4011\big)\bmod 4$$ Or better yet, as suggested by [@dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper): $$\big((n \bmod 10)^{55}\bmod 767\big)\bmod 4$$ For instance, in Python: ### [Python 2](https://docs.python.org/2/), 40 bytes ``` f=lambda n:n and(n%10)**55%767%4+f(n/10) ``` [Try it online!](https://tio.run/##Vc3BCsMgDMbx@57Ci6DdoWq1aQd7GEeRDda0jF729HaXkc/bL4Hkv3@P58ah1nJ/5/WxZMU3VpkXw9o723UpaRpJx2sx3P82df@8@FDFOHv50wuDcBBGYRKOQhJOwhkSmMMe7Ac0fJybWzj2kbDgXDMFnJp@iDTZegI "Python 2 – Try It Online") --- # JavaScript (ES7), 71 bytes Expects the amount as a string. A naive recursive approach that subtracts one coin/bill at a time. ``` n=>(k=10**n.length,g=t=>+n?k>n?g(t,k/=~++i%3?2:2.5):g(t+1,n-=k):t)(i=0) ``` [Try it online!](https://tio.run/##fdBNDoIwEAXgvadgY9rK30wLIiSFsxBEREgx2rj06kgwUQJpu@yXN33TW/kqn9WjvWtfDed6vMhRyZx2EuFwUEFfq0ZfvUZqmbuq6HJVNFR7XSjfrtvuRcEzHsQsmy5d9JQvO5ZpRlsJbKwG9Rz6OuiHhl4oAeJMhzEnDB3YrRAXiGvkNhQL5GuMbBjbxh5tycSGpwWKNaY2xPmLDIUQiflNbksKsCRF8sdo03aR3LadG5kwSn4Yb/eEabBpTwBOTG0REMzIo@REvpiOHw "JavaScript (Node.js) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~55~~…~~41~~ 40 bytes * -1 byte thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor), for using a string instead of the hard-coded list. ``` a=0:tail[i+read[j]|i<-a,j<-"0112212233"] ``` [Try it online!](https://tio.run/##PY5NDoIwEEb3PQUQdlIzbUHEgCfwBoTFBBCL/AVI3Hh2awmlTRcv38z72hcu77rrlMIMbivKLpenucYqb4uvTCkGbUo9YIxzfYXwCtWjHLJqJI6Ty2AsUtrj5GzK@TPO1ZL696ZeH3Ko9cY0y2H10XVllm3G5ipw9gOEGWKEWxKGOAktRXZ6sVls6WpIkMQSg8Ng7NjjNhNwZMLUhCQB6xpFU7iPI90HYPoA@O4y2F/RxMN4@0XyK58dNoui5TT9AQ "Haskell – Try It Online") `a` is the infinite sequence. ## How? It's not hard to find the recursive formula $$ a(n)=a\left(\left\lfloor\frac{n}{10}\right\rfloor\right)+a(n \operatorname{mod} 10) $$ with the base cases for \$n\in\{0,\ldots,9\}\$ given by $$ [0,1,1,2,2,1,2,2,3,3]. $$ This means that the infinite list `a` satisfies the equality ``` a==[i+j|i<-a,j<-[0,1,1,2,2,1,2,2,3,3]] ``` Now, Haskell is magical, but not magical enough to compute `a` from the definition ``` a=[i+j|i<-a,j<-[0,1,1,2,2,1,2,2,3,3]] ``` However, giving the first term explicitly is enough: ``` a=0:tail[i+j|i<-a,j<-[0,1,1,2,2,1,2,2,3,3]] ``` The 40-bytes code above is equivalent to this, but shorter. [Answer] # [R](https://www.r-project.org/), ~~54~~ ~~51~~ ~~47~~ 45 bytes *Edit: converted to console input instead of a [full function](https://tio.run/##LY3BCsIwEES/pjQLK@zGlEShuXv3LpJQKOimNM3Br48rCMNjHgzM3uWRyip17kuTdKxFjGCe27GEe7nJYZL6OAKcXIDa3iZHwhwnzMMwRQu9Prft9dEZXZnREp41Hi@ErM7OIxPRD1bB2qzzAfD/C/0L) to try not to fall behind [Robin Ryder's answer](https://codegolf.stackexchange.com/a/223316/95126)* ``` d=utf8ToInt(scan(,''))-48;sum(d>0,d>5,d%%5>2) ``` [Try it online!](https://tio.run/##K/r/P8W2tCTNIiTfM69Eozg5MU9DR11dU1PXxMK6uDRXI8XOQCfFzlQnRVXV1M5I87@hkYm5xX8A "R – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` Db5FHĊS ``` [Try it online!](https://tio.run/##y0rNyan8/98lydTN40hX8H9Dw6O7FawVjAx0jIHIXMfSQMfQ0FDH0MRcx9DAwABEGAEJQyDLyMTcQsH6cLvKo6Y1Cu7/AQ "Jelly – Try It Online") ~~Steals~~ Ports [Dominic Van Essen's Husk answer](https://codegolf.stackexchange.com/a/223323/66833), be sure to upvote that! ## How it works ``` Db5FHĊS - Main link. Takes an integer n on the left D - Convert to digits b5 - Convert each digit to base 5 F - Flatten H - Halve each Ċ - Ceiling of each S - SUm ``` --- # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` Dị“FȮŀO’D¤S ``` [Try it online!](https://tio.run/##y0rNyan8/9/l4e7uRw1z3E6sO9rg/6hhpsuhJcH/DQ2P7lawVjAy0DEGInMdSwMdQ0NDHUMTcx1DAwMDEGEEJAyBLCMTcwsF68PtKo@a1ii4/wcA "Jelly – Try It Online") ## How it works ``` Dị“FȮŀO’D¤S - Main link. Takes n on the left D - Convert n to digits ¤ - Create a nilad: “FȮŀO’ - Compressed integer: 1122122330 D - To digits ị - Index into the digits of this integer S - Sum ``` [Answer] # [R](https://www.r-project.org/), ~~64~~ ~~52~~ ~~50~~ 45 bytes ``` sum(c(1,2,1:3)[.6*utf8ToInt(scan(,""))-28.4]) ``` [Try it online!](https://tio.run/##K/r/v7g0VyNZw1DHSMfQylgzWs9Mq7QkzSIk3zOvRKM4OTFPQ0dJSVNT18hCzyRW87@hkYm5xX8A "R – Try It Online") Same strategy as [Delfad0r's Haskell answer](https://codegolf.stackexchange.com/a/223318/86301), which is nicely explained. First, `scan(,"")` reads in input as a string. Then, `utf8ToInt(...)-48` takes a string of digits and converts it to a vector of integer digits. This works out shorter than taking input as an integer and splitting it into digits. The digits from 0 to 9 then have to be mapped to the vector `c(0,1,1,2,2,1,2,2,3,3)`. To do this, consider the vector `a=c(1,2,1,2,3)`. For digit `d`, `a[.4+d*.6]` is the value we want. This uses the fact that when calling a non-integer index in a vector (say `a[2.8]`), R rounds down the index (here `a[2]`), and also the fact that `a[0]` returns `NULL` which will be ignored in the sum. Putting this operation with the operation to convert the string to digits simplifies to `.6*utf8ToInt(...)-28.4`. Note that Dominic van Essen has a [solution](https://codegolf.stackexchange.com/a/223321/86301) of (currently) the same length with a different strategy. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` S<•δ¬Èº•sèO ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/2OZRw6JzWw6tOdxxaBeQWXx4hf///4ZGJuYWAA "05AB1E – Try It Online") Same approach as my [Jelly answer](https://codegolf.stackexchange.com/a/223315/66833). ## How it works ``` S<•δ¬Èº•sèO - Program. Input: n S - Cast n to digits < - Decrement •δ¬Èº• - Compressed integer: 1122122330 sè - Using n's digits, index into the digits of 1122122330 O - Sum ``` Kudos to [Kevin Cruijssen's excellent integer compressor](https://codegolf.stackexchange.com/a/166851/66833)! [Answer] # [Husk](https://github.com/barbuz/Husk), 23 bytes ``` L◄Lfo=⁰Σ↑o≤⁰LṖƒ(+İ€m*10 ``` [Try it online!](https://tio.run/##yygtzv7/3@fR9BaftHzbR40bzi1@1DYx/1HnEiDb5@HOaccmaWgf2fCoaU2ulqHB////jQwA "Husk – Try It Online") Extremely slow past 11. ## Explanation ``` L◄Lfo=⁰Σ↑o≤⁰LṖƒ(+İ€m*10 ƒ( create an infinite list using: İ€ currency denomination builtin: [1,1/2,1/5,...200] + plus m*10 the input mapped to *10 this gives [1,1/2,...100] + 10*([1,1/2,...100] + (10*[1,1/2,...100]...)) Ṗ powerset(unordered) ↑o≤⁰L take all sequences which have length ≤ input this makes sure everything till [1]*n is in the list fo=⁰Σ filter out the ones which do not sum to the input ◄L maximum element by length L take the length ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 39 bytes ``` ⌈.4#⌉-⌊#/5⌋&@*IntegerDigits/*Tr ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7/1FPh56J8qOeTt1HPV3K@qaPerrVHLQ880pS01OLXDLTM0uK9bVCiv4HFGXmlUQr69qlOSjHqtUFJyfm1VVzGehwGepwGelwGetwmehwmepwmelwmetwWehwWQKlQNIgeSBtDMJAGUuwGFDQ0MQcpMLAAEwagUiweiMTcwuu2v8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 37 bytes ``` f=lambda n:n and n/5%2-n%5/-2+f(n/10) ``` [Try it online!](https://tio.run/##FYpBCsMgFET3cwo3AaWE6I/WJNDDWFKJkP5KsZSe3ioMD@bN5F85Xky1xtsZnvc9CN5YBN4FT26gkQc3jXSJkiejVf0e6XwIs@V34iKiTJw/RSpVNQwIMywcrvBYsMI02azG3OKx9mpgrG@L1h3U0F9k/fIH "Python 2 – Try It Online") Uses a formula rather than a lookup table for each digit. `n/5%2` counts the five-cent coin, and subtracting `-n%5/-2` is equivalent to adding `(n%5+1)/2` for the one- and two-cent coins. ``` n%10 0 1 2 3 4 5 6 7 8 9 ----------------------------- n/5%2 0 0 0 0 0 1 1 1 1 1 0-n%5/-2 0 1 1 2 2 0 1 1 2 2 Total 0 1 1 2 2 1 2 2 3 3 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 39 bytes ``` f(n){n=n?f(n/10)+""[n%10]:0;} ``` [Try it online!](https://tio.run/##PY5Pa8MwDMX75@ZPYQQpMfOo7KTr0hB62mmHQq7rDiVtt8AiRpqxQ@m@eqbUjoUNPz/pPat6/Kiqvj/HpK5U0JZhaVA9wGQ6nc34zOfwRpHB9w3mt76mTjaHmmIlr0JyDQLpJr8/fj/rr1P8d6kOdI4hOkZH0AvSi0ap75Yn7@K@C/eyJ9Bsl42WwwYMRTHAFnavsIGXstyVoFx4e@p@WpKYi1uP0hUK48kIGyjxZEUaaBW6T0FbB3r2lIgskMHRYcw4Z4OW4KglPiYVGQavtzClrr3iPESfh2id16D7hcmm62GL7B8 "C (gcc) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 37 bytes ``` f=n=>n&&+"0112212233"[n%10]+f(n/10|0) ``` [Try it online!](https://tio.run/##PY5Rb4MgFIXf@RWmSStEqxewa@1CH/cH9tiZ1Cg2Lg6d2sWl6293bCA3JHw5h3Mu7/lXPhR93Y1b1ZZyniuhxEltNsEKKGVMH85XZ7WmkAUVVjGFHyBzLz9vdS@xXw0@iXqZly91I1@/VYEhvEtVtGWtrkf/NlYH/0GioWvq8fKmLtFH3uFJnO7I0zOJyVg49oKYPP@LRauGtpFR015xMJ0hC73KAAk9fdNMiEXQkQeZwTMDiFqiiDnilhhKHO2c@@S0vaODJY5SRxSWBKXLO@Y0DovGbU2CUnBZG9GUGHun@wBsHwAzWQpmiyaW7P9@kf4C "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 48 bytes ``` f=lambda x:x and int("0112212233"[x%10])+f(x/10) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRocKqQiExL0UhM69EQ8nA0NDICIiMjZWiK1QNDWI1tdM0KvQNDTT/FxQBVSikaRgamZhbaP4HAA "Python 2 – Try It Online") 49 bytes in Python 3 because you'd need `//` for floor division. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes ``` IΣ⭆S⭆↨Iι⁵L↨λ³ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0VyO4BMhP900s0PDMKygtgXA1NHUUEBJOicWpEA2ZQHFTIPZJzUsvyYBI5OgoGGtCgPX//4ZGJuYW/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` S Convert input to a string ⭆ Map over characters and join ι Current character I Cast to integer ↨ ⁵ Convert to base 5 ⭆ Map over base 5 digits and join λ Current digit ↨ ³ Convert to base 3 L Take the length Σ Take the (digital) sum I Cast to string Implicitly print ``` Table of base 5 digit to base 3 length: ``` Decimal Base 3 Length 0 [] 0 1 [1] 1 2 [2] 1 3 [1, 0] 2 4 [1, 1] 2 ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), `d`, 5 bytes ``` 5vτ½⌈ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=d&code=5v%CF%84%C2%BD%E2%8C%88&inputs=37&header=&footer=) A port of the Jelly answer which is a port of short husk answer. ## Explained ``` 5vτ½⌈ 5vτ # convert each digit of the input to base 5 ½ # halve each item in that list (halving vectorises all the way down) ⌈ # ceiling each item in that list # -d deep sums the list and implicitly outputs ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~20~~ 15 bytes ``` . $*1, 1{5}|11? ``` [Try it online!](https://tio.run/##FYo7CoBAEEP7nENBRGSyH3e3svQaWljYWIidevZxFsKDvOTa7@PctO2WVUc0PQfwid9LzqoCwsEjIGJCQkYBTZoVeEtCqZVgSLaIVDhDfbmQ8g8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` . $*1, ``` Convert each digit to unary separately. ``` 1{5}|11? ``` Count the number of 5s, 2s and 1s needed to make each digit. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 5δв˜;îO ``` Port of [*@Dominic van Essen*'s Husk answer](https://codegolf.stackexchange.com/a/223323/52210), so make sure to upvote him as well! Uses the legacy version of 05AB1E to get rid of a leading `S` that would be required in the new version of 05AB1E in this case, due to the way the `δ` acts on strings/integers. [Try it online](https://tio.run/##MzBNTDJM/f/f9NyWC5tOz7E@vM7//39DIxNzCwA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeV/03NbLmw6Pcf68Dr//zr/ow10DHWMdIx1THRMdcx0zHUsdCx1DIGCQFEDHWMgMtexBHENdQxNzIEyBgYgwghIgFQZmZhbxAIA). **Explanation:** ``` δ # Map each digit in the (implicit) input-integer to: 5 в # A base-5 list ˜ # Flatten this list of lists ; # Halve each integer î # Ceil each float O # Sum the integers in the list together # (after which the result is output implicitly) ``` ]
[Question] [ *[Related](https://codegolf.stackexchange.com/questions/15934/find-a-fractions-position-in-the-stern-brocot-tree)* From [Wikipedia](https://en.wikipedia.org/wiki/Calkin%E2%80%93Wilf_tree): > > In number theory, the Calkin–Wilf tree is a tree in which the vertices correspond one-to-one to the positive rational numbers. The tree is rooted at the number \$1\$, and any rational number expressed in simplest terms as the fraction \$\frac{a}{b}\$ has as its two children the numbers \$\frac{a}{a+b}\$ and \$\frac{a+b}{b}\$. > > > ![Calkin-Wilf tree](https://upload.wikimedia.org/wikipedia/commons/thumb/8/82/Calkin%E2%80%93Wilf_tree.svg/600px-Calkin%E2%80%93Wilf_tree.svg.png) > > > The Calkin–Wilf sequence is the sequence of rational numbers generated by a breadth-first traversal of the Calkin–Wilf tree, > $$\frac11, \frac12, \frac21, \frac13, \frac32, \frac23, \frac31, \frac14, \frac43, \frac35, \frac52, \ldots$$ > > > For this challenge, you are given a fraction found in the \$i\$th position of the Calkin-Wilf sequence, and must output \$i\$. You can start from either 0 or 1. ## Test cases (Starting from 1.) | \$a\_i\$ | \$i\$ | | --- | --- | | \$\frac11\$ | \$1\$ | | \$\frac13\$ | \$4\$ | | \$\frac43\$ | \$9\$ | | \$\frac34\$ | \$14\$ | | \$\frac{53}{37}\$ | \$1081\$ | | \$\frac{37}{53}\$ | \$1990\$ | Standard loopholes are forbidden. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code wins. [Answer] # JavaScript (ES6), 33 bytes Expects a pair of integers `(p,q)` representing the fraction \$p/q\$. ``` f=(p,q)=>p&&1+f(q+p-(q%p||p)*2,p) ``` [Try it online!](https://tio.run/##bctBDkAwEEDRvXuQGYakSqy4S0MrRHSqYuXuZa22L/@v6lJ@PBY@y91OOgTTA5PDfuAsE4UBV3AJLuX7ZsxrYgyj3b3ddLXZGQwIEojJ12RkzY9JaiJrJckuLjtq3z88 "JavaScript (Node.js) – Try It Online") ### How? This version is based on the nice recurrence formula found by [alephalpha](https://codegolf.stackexchange.com/a/260482/58563): $$\begin{align}f(0)&=0\\f(x)&=1+f(2\lceil1/x\rceil-1-1/x)\end{align}$$ It was modified to work with two integers \$p/q=x\$ instead of a native fraction and without an explicit ceiling function: $$\lceil q/p\rceil=\begin{cases} q/p,&q\equiv 0\pmod p\\ (q+p-(q \bmod p))/p,&q\not\equiv 0\pmod p\end{cases}$$ We have: $$f(2\lceil1/x\rceil-1-1/x)=f(2\lceil q/p\rceil-p/p-q/p)$$ which is turned into the following JS code: ``` f(q % p ? q + p - q % p * 2 : q - p, p) ``` which can be further simplified to: ``` f(q + p - (q % p || p) * 2, p) ``` --- # JavaScript (ES6), 40 bytes Expects a pair of integers `(p,q)` representing the fraction \$p/q\$. ``` f=(p,q)=>p-q?p>q?f(p-q,p)+1:2*f(p,q-p):1 ``` [Try it online!](https://tio.run/##bctRCoAgEATQ/07i1hqYhSBUZ4nKKETXiq5v9Zv9DW9mtuEajnFf6eTOT3OMpmWEAdqOeOipC71hT0KCQugqN2/JCbSIo3eHt3Np/cIMEygAsq/JxOofk1gn1kiUKl0qbJ5/vAE "JavaScript (Node.js) – Try It Online") ### Commented ``` f = (p, q) => // (p, q) = input pair p - q ? // if p is not equal to q: p > q ? // if p is greater than q: // we're located on the right branch f(p - q, p) // turn it into the corresponding left branch + 1 // and add 1 : // else: // we're located on the left branch 2 * // double the result of f(p, q - p) // a recursive call with the parent fraction : // else: // we've reached the root 1 // stop and return 1 ``` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 29 bytes ``` f(x)=if(x,1+f(-1\-x*2-1-1/x)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWe9M0KjRtM4GkjqF2moauYYxuhZaRrqGuoX6FpiZEzU2nxIKCnEqNCgVdO4WCosy8EiBTCcRRUgBp19RRiDbUUTDUN9ZRMAERxvomOgqmxvrG5kC2ub6pcSzUJJitAA) \$\begin{align}f(0)&=0\\f(x)&=1+f(2\lceil1/x\rceil-1-1/x)\end{align}\$ [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes ``` g-¨£∨)↔vÞṘṘB ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJ+IiwiIiwiZy3CqMKj4oioKeKGlHbDnuG5mOG5mEIiLCIiLCJbMSwxXSA9PiAxXG5bMSwzXSA9PiA0XG5bNCwzXSA9PiA5XG5bMyw0XSA9PiAxNFxuWzUzLDM3XSA9PiAxMDgxXG5bMzcsNTNdID0+IDE5OTAiXQ==) Takes input as a pair of numbers. ``` g-¨£∨)↔vÞṘṘB # function taking a pair and returning its parent: g- # subtract minimum ¨£∨ # zip and return the last truthy element from each pair ) # end function ↔ # apply until fixed point and collect intermediate results vÞṘ # vectorizing is sorted in reverse? Ṙ # reverse B # convert from binary ``` [Answer] # [Python](https://www.python.org), 34 bytes (@Neil) ``` f=lambda Q:Q and 1+f(1/Q-1-2/Q%-2) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NZC_bsMgEId3P8UJqRKk5wZiR4kjZe3uOfJA_qAiBbAOMuRZumRpX6hT36bnyEUCfffdb7jj83u8l48UH4-vW3H19le4_dWG49lCv-vBxjOYVyfNsq9NvVr2L_VKzckfRymAI3sqPsUMPoyJCrzPAmxmrmab77ni-5YvhS6nG2VOXH3wRbZaa1W5RBDRg49wOAhjBJoBGRqB7QQtQzdB03JrUlKs2YlmIxQavTVPxRVOnlXX6WHYVcDHEex5FrkIdpQ-FoxKPRsjcSUdoeNHoZ9X-_-MPw) Port of @Arnauld's latest and greatest which ports @alephalpha's. Expects a Python Fraction object. #### Previous [Python](https://www.python.org), 44 bytes (@xnor) ``` f=lambda Q:Q==1or(Q>1)+2*f(max(Q/(1-Q),Q-1)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY_BasMwDEDv_Qrhk90prFoy2hTS4-4-hxy8DTFDbQfXhe5beullPfWH9jdTQqaDeHpCSLrex-_yleLt9nMuXO1-kbujC--fDuzedh2lrO2BzNPLmnVwF22fNVXWoK3ImGXmwTkF4Ow-ik_xBD6MKRd4WwS4k_CKU4aIHnyEvldECmlAgVphM0Ej0E5QN9KalFav4lS9VQZps6NZSYWTF9W2m2HYr0CCM3SyRK-DG7WPBaMxc2PMUmnOyJIM-uXm_3__AA) #### Original [Python](https://www.python.org), 46 bytes ``` f=lambda Q:Q==1or(Q>1)+2*f([Q/(1-Q),Q-1][Q>1]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY-xbgIxDEB3vsLKlFAfxdwhOKRjZM98ypBSWY3US04hDP2WLix04of6N_Whqwfr-VmW7e-f8at8pHi73a-Fq_3virtPP7y9e7AH23WUsrZHMi-bJevevmqqrEFbketFOzNPPTinATj7cwkpXiAMY8oFTrMAfxFecMoQMUCI0PeKSCE5FKgVNhM0Au0EdSOtSWm1FafqnTJI6z09lVQ4eVFtu3busAAJztDJEr0c_KhDLBiNeTbGLJXmjCzJYJhv_v_4Dw) Expects a Python Fraction object. Similar but as far as I can tell not identical to @Arnauld's approach. [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 25 bytes ``` +*o{{1/$_-1-2/$_%-2}...0} ``` [Try it online!](https://tio.run/##HcVNCoMwEAbQfU7xCW1RQzIZJ9Zm0ZsIpVADBf/QlYhnT6Wb9@Zu6e9p2HCLeCLpctp3psvLsKnOrqY6rLXuSOt7Q8z1kOXtRxct/csKxGlB/x27NTExWDEJvPKnQQl5sFe1kDRg92AlDdUCDsH9AA "Perl 6 – Try It Online") Port of [@loopy walt's answer](https://codegolf.stackexchange.com/a/260477/76162), which is a port of @Arnauld's, which is a port of @alephalpha's. [Answer] # [J](https://www.jsoftware.com), 24 bytes ``` *`(1+%$:@-~_1+2*>.@%)@.* ``` -4, port of [@Jo King's answer](https://codegolf.stackexchange.com/a/260512/110888), which is a port of @loopy walt's, which is a port of @Arnauld's, which is a port of @alephalpha's. [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxQytBw1BbVcXKQbcu3lDbSMtOz0FV00FPCyJ9U0OTKzU5I19BR09DJ01Tzc5QwbDIWMEEiI2LTBRMjYuMzRWMzYtMjSHqFyyA0AA) ``` *`(1+%$:@-~_1+2*>.@%)@.* * NB. signum, 0 for 0, 1 for everything else @. NB. index into the gerund list and execute * NB. if 0, use signum again to return 0 ( ) NB. if 1, execute the recursive function NB. uses the formula in alephalpha's PARI/GP answer $:@ NB. recurse here ``` ### Original 28 bytes ``` [:#[(1%1+]-~2*<.@])^:~:^:a:* ``` In short, returns the length of the sequence up to the input. Expects a rational number. [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxJ9pKOVrDUNVQO1a3zkjLRs8hVjPOqs4qzirRSgui5KaGJldqcka-go6ehk6appqdoYJhkbGCCRAbF5komBoXGZsrGJsXmRpD1C9YAKEB) ``` [:#[(1%1+]-~2*<.@])^:~:^:a:* * NB. signum, returns 1 for all inputs to give initial value [ NB. input unchanged ( )^:~:^:a: NB. form for a do-while that uses a: to collect results into an array NB. u^:v^:_ v is a boolean function and u modifies the initial value a: NB. empty box ~: NB. continue if input is not equal to current value <.@] NB. floor the right arg (qᵢ) 2* NB. double ]-~ NB. subtract by qᵢ 1+ NB. increment 1% NB. reciprocal [: NB. then # NB. take the length ``` [Answer] # [Arturo](https://arturo-lang.io), 49 bytes ``` f:$[p q][(p=q)?->1->(p>q)?->1+f p-q p->2*f p q-p] ``` [Try it](http://arturo-lang.io/playground?z0ch2i) Port of Arnauld's [JavaScript answer](https://codegolf.stackexchange.com/a/260473/97916). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Uses [AndrovT](https://codegolf.stackexchange.com/users/116074/androvt)'s method from their [Vyxal answer](https://codegolf.stackexchange.com/a/260476/53748), go upvote! ``` _ṂoƊƬ</€¬ṚḄ ``` A monadic Link that accepts a pair of co-prime positive integers, `[numerator, denominator]` and yields the 1-indexed index of that fraction in **[Try it online!](https://tio.run/##y0rNyan8/z/@4c6m/GNdx9bY6D9qWnNozcOdsx7uaPl/dNLDnTN0DrdnPWqYo2Brp/CoYa5m5P//0dGGOgqGsTpcCiCGMZhhAmMY6yiYgBmmQJaxOUTMXEfB1Dg2FgA "Jelly – Try It Online")** ### How? ``` _ṂoƊƬ</€¬ṚḄ - Link: pair of positive, coprime integers, [N,D] Ƭ - start with C=[N,D] and collect until a fixed-point applying: Ɗ - last three links as a monad - f([N,D]): Ṃ - minimum ([N,D]) _ - ([N,D]) subtract (that) (vectorises) -> [0,D-N] or [N-D,0] o - (that) logical OR ([N,D]) (vectorises) -> [N,D-N] or [N-D,D] € - for each ([numerator, denominator] pair in the collected results): / - reduce by: < - is (the numerator) less than (the denominator)? ¬ - logical NOT (vectorises) Ṛ - reverse Ḅ - convert from binary ``` --- Loads of \$11\$s, is there a \$10\$? e.g.: ``` _ṂoƊƬṚUṢƑ€Ḅ _ṂoƊƬṚZ</¬Ḅ _ṂoƊƬIF<1ṚḄ ``` [Answer] # [Rust](https://www.rust-lang.org), ~~91~~ ~~84~~ ~~81~~ 77 bytes Based on the recursive relation: $$ a\_n = b\_{n-1} $$ $$ b\_n = 2\cdot b\_{n-1} \cdot \left \lfloor \frac{a\_{n-1}}{b\_{n-1}} \right \rfloor - a\_{n-1} + b\_{n-1}$$ 0-indexed. Recursion is very verbose in rust so I hope this is shorter than the recursive version most other answers use. ``` |m|{let mut d=(1,1,1);while(d.0,d.1)!=m{d=(d.1,d.0+d.1-d.0%d.1*2,d.2+1)};d.2} ``` * -7 bytes thanks to [AlephaAlpha](https://codegolf.stackexchange.com/questions/260472/find-index-of-rational-number-in-calkin-wilf-sequence/260488#comment573282_260488) * -4 bytes thanks to [Neil](https://codegolf.stackexchange.com/questions/260472/find-index-of-rational-number-in-calkin-wilf-sequence/260488?noredirect=1#comment573300_260488) [Attempt This Online!](https://ato.pxeger.com/run?1=RY5RbsIwDIbfcwqDhBaPFJF2G4iq7AScYJomRBMtUpuhNhUSIdfgZS99GIfiNjNQSqzk-_3Hsv37VzW1a89P2kK5NpYj-EI50AvQlnPz9iLoIkbLpjZ7lZ0ap6P5eXUoD9e6snGQZ1wKCkx336ZQPJ9MRT6ROMhKT38kKZ2OiRFxRHyOyYnHEkNKDF3TY8qY_qnAqdp9bda1AmPhgwEdLi-bXB4UNyOmeZ2UInnI-C4T0dcmM_GaIPsEf823lbGusAM-9P2oxXsAH4YCNO89xJQF1m3Xtjf-Aw) [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), ~~59~~ 53 bytes *Thanks [@Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) for -6 bytes and fixing the floating point issue* ``` 0+0. N+X:-A is 2*ceiling(1/N)-1-1rdiv N,A+B,X is B+1. ``` Took the recursive formula from [@alephalpha's answer](https://codegolf.stackexchange.com/a/260482/96039), so make sure to upvote his answer as well! [Try it online!](https://tio.run/##Xcy7CoQwEAXQfr9isEo2E9cYRbAQ4gdYB8RC9iEBH0Flt/PXsw@MxRYDl3sPY@epnzq@vIxzEYvCU8V0zhWYBeLz9W56M3ZEXCrKBRfzzTyhQsVK1F9RMhG6nA@t7c2yklo1RUEU0/iY5qFdSbBZ4AVsdhsDrBXqhlKsBQr4fYox9lGiPLqj8WOCyZ9KMfVcegPpHmWGn9uhbGjo3g "Prolog (SWI) – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 72 bytes Golfed version. [Try it online!](https://tio.run/##bYyxCsIwEIb3PsW55TQFYyqFQgVHBydxEodY2xKpMUmzSOmzx6Ru1ht@7vv47/pKdMK/bo@6cnAUUsGQANzrBp4BiLBtX8DeWvG@nJyVqr1iAWclHZQw@NhriC4OylETE2OUMrjULMo1xm1ncGKqccWg7voaNstgqEk1Tsg8hNHhvesUaQijDDH5dXzmsj@O02zmtpzyfN7M6fZ7Pyaj/wA) ``` def f(p:Int,q:Int):Int=if(p-q!=0)if(p>q)f(p-q,p)+1 else 2*f(p,q-p)else 1 ``` Ungolfed version. [Try it online!](https://tio.run/##dY@xDoIwEIb3PsXv1mpNRDAkJJg4OjgZJ@NQkRIM1gJdjOHZEUpADbrc5b77/mtaRiITdX0/X@PIYCdShScBLrHErRmoKJIywKYoxOO4N0WqkhMLcFCpQWjNzpVUB9gqw5HbzmwdFCCVoBpz5JiEWLCB95s18k@I9mKrc2iGGZxhUyHOyvhLXWLa6s3bTUKzt0r@RPprnVAR23TzOZMpKqnDHcZGzB0x7wdzuTdiK5e7/tj0@arLV6Sq6xc) ``` object Main { def main(args: Array[String]): Unit = { def f(p: Int, q: Int): Int = { if (p - q != 0) { if (p > q) { f(p - q, p) + 1 } else { 2 * f(p, q - p) } } else { 1 } } println(f(1,1)) println(f(1,3)) println(f(4,3)) println(f(3,4)) println(f(53,37)) println(f(37,53)) } } ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~34~~ 24 bytes ``` NθNηWθ«≦⁻⁻η⊗﹪η±θθ≔ιη→»Iⅈ ``` [Try it online!](https://tio.run/##TYw/C8IwFMTn9lO88RXiVESwk@gimCJOrmn7bAIxqflTB/Gzx1QXbzl@d9z1UrjeCp3S0UwxtPHekcNH1ZT/LDM/pdIEuYJXWXAx7bxXoznRLSBXJnoGX0PJ4GBjp2lAboeo7ZK0NIpAeZzFYLkvfntUDJb3gtuZcHtRowwZ3@XZKRNwL3zAK1ZVk9K6hnqTVrP@AA "Charcoal – Try It Online") Link is to verbose version of code. 1-indexed. Takes input as two integers. Explanation: Port of @Arnauld's port of @alephalpha's answer. ``` NθNη ``` Input the numerator and denominator. ``` Wθ« ``` Repeat until the numerator is zero. ``` ≦⁻⁻η⊗﹪η±θθ ``` Calculate the next numerator. This uses true modulus, so instead of writing `q + p - (q % p || p)` I can write `q - q % -p`; the final expression is then `q - q % -p * 2 - p`. ``` ≔ιη ``` Save the copy of the numerator that conveniently happens to be in the loop variable to the denominator. ``` → ``` Increment the count. ``` »Iⅈ ``` Output the final count. Previous 34-byte version based on @AndrovT's answer: ``` ≔E²NθW↨θ±¹«⊞υ‹ι⁰UMθ∨⁻κ⌊θκ»⊞υ¹I↨⮌υ² ``` [Try it online!](https://tio.run/##NY1BDoIwFETXcIq//E1qIhDjgpWyMhEk3qBiAw20QD/FhfHstcS4mplk5k3TCduMYvD@RKRag6WYMOVwMZNbKqcf0iJjHGaWx69ODRLwLEjizKGSrVgkJowxeMdR7ahDx@EqiVBx2LMwiQKuGLUW5rlNbhZLZRxhzyEYpZ3GecP3W/kT/xlJSLVVZsFC0PJ7vMtV2qAu1NPwmXt/yCA7@t06fAE "Charcoal – Try It Online") Link is to verbose version of code. 1-indexed. Takes input as two integers. Explanation: ``` ≔E²Nθ ``` Input the fraction. ``` W↨θ±¹« ``` Repeat until the numerator and denominator are equal. ``` ⊞υ‹ι⁰ ``` If the numerator was larger than push a `1` bit otherwise push a `0` bit. ``` UMθ∨⁻κ⌊θκ» ``` Subtract the smaller element from the larger. ``` ⊞υ¹ ``` Push a final `1` bit. ``` I↨⮌υ² ``` Convert from base `2`. I could have done better by generating the sequence (~~36~~ 33 bytes): ``` ≔⮌E²NθF²⊞υ¹W¬⁼θυ«≔⁺⁻Συ⊗﹪⊟υυυυ→»Iⅈ ``` [Try it online!](https://tio.run/##LU49C8IwFJybX/HGF4iDigh2EnVwqBRdXFONTSA2bZJXB/G3x/ixHHcH93HR0l@ctCmtQzBth0c1Kh8UVrLHmYB911M80L1RHjnnAgZespvzgDMONQWNJGCavYc2VgEeXMTdQNIGHARQjsCTFf/u2lLAynQZT3RHynVbR41VV6zclazD2vVfm75bP1ayonKjwtXRtDpm@WK1N13EjQwRz59bZUqLOcyXaTLaNw "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Takes input as two integers. Explanation: ``` ≔⮌E²Nθ ``` Input the fraction in reverse. ``` F²⊞υ¹ ``` Start with `1` as the fraction. ``` W¬⁼θυ« ``` Repeat until the fraction is found. ``` ≔⁺⁻Συ⊗﹪⊟υυυυ ``` Find the next fraction. (And yes, that is legitimately `4` `υ`s in a row.) ``` → ``` Increment the loop count. ``` »Iⅈ ``` Output the final count. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~38~~ 28 bytes ``` ->m{m>0?1+f[1/m-1-2/m%-2]:0} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y63OtfOwN5QOy3aUD9X11DXSD9XVdco1sqg9n@BAlCwSN8wlgvEMinSN4awjIv0TaAs8yJ9U@PY/wA "Ruby – Try It Online") Using @alephalpha/@Arnauld formula like most of the answers. [Answer] # [><>](https://esolangs.org/wiki/Fish), 36 bytes ``` ii$\l2-nao; :?!\$&:::&+:@$:@%:?$~2*- ``` [Try it online!](https://tio.run/##S8sszvj/PzNTJSbHSDcvMd@ay8peMUZFzcrKSk3bykHFykHVyl6lzkhL9/9/VVMA "><> – Try It Online") Port of [Arnauld's answer](https://codegolf.stackexchange.com/a/260473/76162). Takes input as codepoints, e.g. 53/37 is `5%` [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), 59 bytes ``` 1ii11$4[:{:{:{:\ @=r@={+2(?v]{n;\ *-+{1+}40.\r{]$:@$:@$:@%2 ``` [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiMWlpMTEkNFs6ezp7Ons6XFxcbkA9ckA9eysyKD92XXtuO1xcXG4qLSt7MSt9NDAuXFxye10kOkAkOkAkOkAlMiIsImlucHV0IjoiNTMgMzciLCJzdGFjayI6IiIsInN0YWNrX2Zvcm1hdCI6Im51bWJlcnMiLCJpbnB1dF9mb3JtYXQiOiJudW1iZXJzIn0=) Despite not having a easy way to check tuple equality still shorter than rust. Uses the formula [Neil](https://codegolf.stackexchange.com/questions/260472/find-index-of-rational-number-in-calkin-wilf-sequence/260488?noredirect=1#comment573300_260488) suggested under my Rust answer. ## Explanation `1ii11` pushes the initial state. `$4[:{:{:{:@=r@={+2(?vr{]` Checks if the 2 tuples are equal `$:@$:@$:@$2*-+` Performs the basic calculation of the next value for `B` `{1+}` Adds one to the counter `]{n;` Prints the result and exits, if the tuples are equal. [![enter image description here](https://i.stack.imgur.com/AFnMf.png)](https://i.stack.imgur.com/AFnMf.png) ]
[Question] [ This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") puzzle, the cops' thread can be found [here.](https://codegolf.stackexchange.com/questions/107012/hidden-inversions-cops-thread) Your task will be to find an anagram of the provided programs in the cops' thread that performs its left inverse. Once you crack an answer post the solution as an answer below and notify the original answerer. You will be scored on the number of programs you are the first to crack. [Answer] ## Python 3, 46 bytes, [Lynn](https://codegolf.stackexchange.com/a/107017/18535) ``` lambda x0223334566789:(x0223334566789*89)//178 ``` [Answer] ## Python 2, 225 bytes, [orlp](https://codegolf.stackexchange.com/a/107028/21487) ``` p=90930641353124136621573325641513715557077985927835294018496194596645372722158;q=101979812089012306249375934082966806799688507587087308196267706260111970225882#--223444799 lambda n:pow(n,pow(65537,(p*q-2*(p+q))/4,p*q),~p*~q) ``` Guess I [got lucky](https://github.com/eniac/faas) after [guessing](https://i.stack.imgur.com/jQwcE.png) random prime divisors [all day](http://pastebin.com/TdLG2vcJ)... (Default c4.8xlarge spot limit is 4, but I managed to bump it to 10 last year. Had to tweak the FAAS config from 16 slaves to 6 though (+3 mpi, 1 master). 20m polyselect, 12h 50m sieving, 2h 25m linalg, 30m sqrt. Total cost ~$70. At least @orlp was nice enough to pick a solvable size, but I'm not doing this again! Thanks to @IlmariKaronen for the last step, and yes I'm joking about the guessing :P) [Answer] # Python 2, 83 bytes, [orlp](https://codegolf.stackexchange.com/a/107030) **Original:** ``` #((()))****+,,---/2289;==oppppppqqqqqw~~ lambda n:pow(n,65537,10998167423251438693) ``` **Crack:** ``` p=3207399658;q=3428998126#--11 lambda n:pow(n,pow(65537,(p*q-2*(p+q))/4,p*q),~p*~q) ``` [Try it online!](https://tio.run/nexus/python2#bY7LCoMwFET3fsWlIOTaSPM2sdh/sY0tQhsTKdSVv24j3XYzcGA4M9sQbtDBs39dfQ@hjdOHBGq0lg3lzDnLTaOEFJoraY2TWBSxk4I10jmj7Tl1Ugm794Qp/PDHtefPR2KValGReEyIJ0UzIl1jtaZsvU8zLDAGmPvwGAhnDFuI8xjecCg91Bco/QFKIAuFvEPyb7Ig4rZ9AQ "Python 2 – TIO Nexus") RSA cracking done by [Wolfram Alpha](https://www.wolframalpha.com/input/?i=factor+10998167423251438693). ;) [Answer] ## Python 3, 80 bytes, [Wolfram](https://codegolf.stackexchange.com/a/107187/32014) ``` from bisect import* q=int(input()) print(bisect([(h+1)**2 for h in range(q)],q)) ``` This was really hard to crack! I use the [bisect library](https://docs.python.org/3/library/bisect.html), which is included in the Python 3 distribution. The `bisect` function takes a sorted list and an element, and returns the rightmost index where the element could be inserted to maintain order. We just give it the length-`q` list of squares starting from `1` and the element `q`. [Answer] # Javascript, 21 bytes, [Arnauld](https://codegolf.stackexchange.com/a/107022/47066) **Original** ``` b=>Math.pow(b,torc=3) ``` **Crack** ``` o=>Math.cbrt(o,pbw=3) ``` Returns the cube root. [Answer] ## 7, 9 bytes, [ais523](https://codegolf.stackexchange.com/a/107033/18535) ``` 00000000: 0173 dc25 7e13 dcb6 1f .s.%~.... ``` Because brute force always wins, and 9! is only 362880 [Answer] # Processing.js, 59 bytes, [Kritixi Lithos](https://codegolf.stackexchange.com/a/107034) **Original:** ``` float igetuwebaoli(int p){return p*(((17*-4*-3)))+0+0;}//,, ``` **Crack:** ``` int loabewuteg(float p,i){return (i+0**+0,(p/17/(-4*-3)));} ``` Well, that was easy enough. The hardest part was figuring out where to stick the extra commas and asterisks. Fortunately, it seems that Processing allows extra unused function parameters as well as C-style comma expressions. [Answer] # JavaScript (ES6), 63 bytes, [SLuck49](https://codegolf.stackexchange.com/a/107144) **Original:** ``` x=>eval(atob`eCp4KzEvLyAgfXBModLS4TvEn4wp1iys9YRRKC85KLIhNMC=`) ``` **Crack:** ``` x=>eval(atob`CgpNYXRoLnBvdyh4LTEsMC41KSAvLw4589CEIKKMRefipyz=`) ``` The base64 code above decodes to: ``` Math.pow(x-1,0.5) //... ``` where the `...` stands for a bunch of random garbage that is ignored by the JS interpreter, since it's in a comment. I found this solution by trial and error. In the end, the only really tricky part were the two newlines at the beginning of the code, needed to make the rest line up properly and to get the `M` in `Math` to base64-encode into something that was available in the original character set. I first tried spaces, but `" M"` base64-encodes into `"ICBN"` and I needed the only available `B` to encode `".po"` later in the code. `"0+M"`, `"1*M"`, `"1?M"` or any other similar no-op prefixes I could think of didn't work either, but newlines did. I suspect this may not be exactly the intended solution, but whatever — it works. :) **Demo:** ``` var f = x=>eval(atob`eCp4KzEvLyAgfXBModLS4TvEn4wp1iys9YRRKC85KLIhNMC=`) var g = x=>eval(atob`CgpNYXRoLnBvdyh4LTEsMC41KSAvLw4589CEIKKMRefipyz=`) for (var i = -0; i <= 10; i++) console.log(i, '->', f(i), '->', g(f(i))) ``` [Answer] # Brain-Flak, 26 bytes, [Wheat Wizard](https://codegolf.stackexchange.com/a/107037/20059) ### Original (adds 13) ``` ((((()()())){}[()]){}{}{}) ``` ### Crack (subtracts 13) ``` ([(((()())()){}){}{}](){}) ``` [Answer] # J, 8 bytes, [miles](https://codegolf.stackexchange.com/a/107025/31957) ``` [:]-:[+: ``` Simple swapping of `+:` for `-:` (double for halve). [Answer] # Javascript, 15 bytes, [insertusernamehere](https://codegolf.stackexchange.com/a/107099/47066) **Original** ``` t=>(!!0+~~t+~0) ``` **Crack** ``` t=>(~~!!~0+t+0) ``` [Answer] # Python 2, 47 bytes, [Wheat Wizard](https://codegolf.stackexchange.com/a/107276/62346) ``` lambda x:sorted(a**2for a in range(x)).index(x) ``` [Answer] # JavaScript (ES6), 46 bytes, [SLuck49](https://codegolf.stackexchange.com/a/107255/42545) **Original (calculates ln(x+1))** ``` x=>Math.log(x+(+String(t=985921996597669)[5])) ``` **Crack** ``` x=>Math[(lg=19979699+55686).toString(9+25)](x) ``` I never would have cracked this if I hadn't realized that the inverse is a [`Math` built-in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/expm1). `(lg=19979699+55686).toString(9+25)` is just a convoluted way of returning `"expm1"`. [Answer] ## J, 10 bytes, [miles](https://codegolf.stackexchange.com/a/107094/18535) ``` 1%:@*~>:[< ``` I have to write something here because the answer is too short. [Answer] # J, 29 bytes, [Zgarb](https://codegolf.stackexchange.com/a/107108/6710) ## Original ``` 5#.[:,(3 5&#:(-$]-)7)#.inv"0] ``` ## Crack ``` [:(](07-5)"3 #.-:&#$,)5#.inv] ``` [Try it online!](https://tio.run/nexus/j#JcqxCoAgEADQ3a84PJETVAwR4aAvEadIa6mt3zey7Q1vNFgZEvrCliIkjUxOVWeyQX9ejwxV9K8Upkohu2RkBPSONSpr0kxViH07bmiw5F99eowX) Another crack equivalent is ``` [:((3 ]7-5)#.-:&#$,)5#.inv"0] ``` ## Explanation ``` [:(](07-5)"3 #.-:&#$,)5#.inv] Input: integer n ] Get n 5 The constant 5 #.inv Get the digits of n in base 5 [:( ) Operate on those digits D , Flatten D (does nothing since it is already a list) # Get the length of D -:& Halve it $ Reshape D to half its length (only the base 2 digits) (07-5)"3 The constant 2 with rank 3 #. Convert the front-half of D to a decimal from base 2 ] Return the right result ``` ]
[Question] [ ### Introduction The [sign](https://en.wikipedia.org/wiki/Sign_(mathematics)) of a number is either a `+`, or a `-` for every non-zero integer. Zero itself is signless (`+0` is the same as `-0`). In the following sequence, we are going to alternate between the **positive sign**, the **zero** and the **negative sign**. The sequence starts with `1`, so we write `1` with a positive sign, with zero (this one is weird, but we just multiply the number by 0) and the negative sign: ``` 1, 0, -1 ``` The next number is `2`, and we do the same thing again: ``` 2, 0, -2 ``` The sequence eventually is: ``` 1, 0, -1, 2, 0, -2, 3, 0, -3, 4, 0, -4, 5, 0, -5, 6, 0, -6, 7, 0, -7, ... ``` Or a more readable form: ``` a(0) = 1 a(1) = 0 a(2) = -1 a(3) = 2 a(4) = 0 a(5) = -2 a(6) = 3 a(7) = 0 a(8) = -3 a(9) = 4 ... ``` ### The Task Given a non-negative integer *n*, output the *n*th term of the above sequence. You can choose if you use the **zero-indexed** or **one-indexed** version. ### Test cases: Zero-indexed: ``` a(0) = 1 a(11) = -4 a(76) = 0 a(134) = -45 a(296) = -99 ``` Or if you prefer one-indexed: ``` a(1) = 1 a(12) = -4 a(77) = 0 a(135) = -45 a(297) = -99 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the smallest number of bytes wins! [Answer] # Jelly, 7 bytes ``` +6d3’PN ``` Zero-indexed. [Test cases here.](http://jelly.tryitonline.net/#code=KzZkM-KAmVBOCjAsMSwyLDMsNCw1w4figqw&input=&args=OQ) Explanation: ``` +6 Add 6: x+6 d3 Divmod: [(x+6)/3, (x+6)%3] ’ Decrement: [(x+6)/3-1, (x+6)%3-1] P Product ((x+6)/3-1) * ((x+6)%3-1) ``` [Answer] # JavaScript ES6, 18 bytes ``` n=>-~(n/3)*(1-n%3) ``` Turned out very similar to @LeakyNun's answer but I didn't see his until after I posted mine. ## Explanation and Ungolfed `-~` is shorthand for `Math.ceil`, or rounding up: ``` n => // input in var `n` Math.ceil(n/3) // Get every 3rd number 1,1,1,2,2,2, etc. * (1-n%3) // 1, 0, -1, 1, 0, -1, ... ``` ``` function f(n){n=i.value;o.value=-~(n/3)*(1-n%3);} ``` ``` Input: <input id=i oninput="f()"/><br /><br /> Output: <input id=o readable/> ``` [Answer] # MarioLANG, ~~93~~ 81 bytes *one-indexed* [**Try It Online**](http://mariolang.tryitonline.net/#code=OygtKSkrKC0KIj09PT09PT09PT09PTwKPjooIVs8OiFbPDopIVsKICE9Iz0iISM9IiE9Iz0KISAgPCAhLTwgIS0gPAojPT0iICM9IiAjPT0i&input=OTY) ``` ;(-))+(- "============< >:(![<:![<:)![ !=#="!#="!=#= ! < !-< !- < #==" #=" #==" ``` **Explanation :** we begin by taking the imput ``` ; ``` wich give us ``` v ... 0 0 input 0 0 ... ``` we then decrement the left byte and increment the right byte with ``` ;(-))+( ======= ``` we end up with ``` v ... 0 -1 input +1 0 ... ``` we then set up the loop ``` ;(-))+(- "============< > ![< ![< ![ #=" #=" #= ! < !-< !- < #==" #=" #==" ``` the loop will go until the memory look like ``` v ... 0 -X 0 +X 0 ... ``` we then only need to output the result ``` ;(-))+(- "============< >:(![<:![<:)![ !=#="!#="!=#= ! < !-< !- < #==" #=" #==" ``` [Answer] # Python 2, 24 bytes ``` lambda n:(n/3+1)*(1-n%3) ``` ## Full program: ``` a=lambda n:(n/3+1)*(1-n%3) print(a(0)) # 1 print(a(11)) # -4 print(a(76)) # 0 print(a(134)) # -45 print(a(296)) # -99 ``` [Answer] # MATL, ~~15~~ 12 bytes ``` 3/XkG3X\2-*_ ``` This uses one based indexing. [Try it online!](http://matl.tryitonline.net/#code=My9Ya0czWFwyLSpf&input=NA) or [verify test cases](http://matl.tryitonline.net/#code=My9Ya0czWFwyLSpf&input=WzEgMiAzIDQgNSA2IDcgOCA5XQ) Explanation: ``` G #Input 3X\ #Modulus, except multiples of 3 give 3 instead of 0 2- #Subtract 2, giving -1, 0 or 1 3/Xk #Ceiling of input divided by 3. * #Multiply _ #Negate ``` [Answer] # Haskell, 27 bytes ``` f x=div(x+3)3*(1-mod(x+3)3) ``` Slightly more interesting 28 byte solution: ``` (((\i->[i,0,-i])=<<[1..])!!) ``` (Both are `0`-indexed) [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` :t~y_vG) ``` The result is 1-based. [**Try it online!**](http://matl.tryitonline.net/#code=OnR-eV92Ryk&input=MTM1) ### Explanation This builds the 2D array ``` 1 2 3 4 5 ... 0 0 0 0 0 ... -1 -2 -3 -4 -5 ... ``` and then uses linear indexing to extract the desired term. Linear indexing means index down, then across (so in the above array the first entries in linear order are `1`, `0`, `-1`, `2`, `0`, ...) ``` : % Vector [1 2 ... N], where N is implicit input t~ % Duplicate and logical negate: vector of zeros y_ % Duplicate array below the top and negate: vector [-1 -2 ... -N] v % Concatenate all stack contents vertically G) % Index with input. Implicit display ``` [Answer] # Perl 5, 22 bytes 21 plus one for `-p`: ``` $_=(-$_,$_+2)[$_%3]/3 ``` Uses 1-based indexing. Explanation: `-p` sets the variable `$_` equal to the input. The code then sets it equal to the `$_%3`th element, divided by 3, of the 0-based list `(-$_,$_+2)` (where `%` is modulo). Note that if `$_%3` is two, then there is no such element, and the subsequent division by 3 numifies the undefined to 0. `-p` then prints `$_`. [Answer] ## 05AB1E, 7 bytes **Code:** ``` (3‰`<*( ``` **Explained:** ``` ( # negate input: 12 -> -12 3‰ # divmod by 3: [-4, 0] ` # flatten array: 0, -4 < # decrease the mod-result by 1: -1, -4 * # multiply: 4 ( # negate -4 ``` [Answer] # Bash, 28 25 Bytes ``` echo $[(1+$1/3)*(1-$1%3)] ``` [Answer] # [Perl 6](http://perl6.org), ~~26~~ 23 bytes ``` ~~{({|(++$,0,--$)}...\*)[$\_]}~~ {($_ div 3+1)*(1-$_%3)} ``` ( The shorter one was translated from other answers ) ## Explanation (of the first one): ``` { # bare block with implicit parameter 「$_」 ( # start of sequence generator { # bare block |( # slip ( so that it flattens into the outer sequence ) ++$, # incrementing anon state var => 1, 2, 3, 4, 5, 6 0, # 0 => 0, 0, 0, 0, 0, 0 --$ # decrementing anon state var => -1,-2,-3,-4,-5,-6 ) } ... # repeat * # indefinitely # end of sequence generator )[ $_ ] # get the nth one (zero based) } ``` ### Test: ``` #! /usr/bin/env perl6 use v6.c; use Test; # store it lexically my &alt-seq-sign = {({|(++$,0,--$)}...*)[$_]} my &short-one = {($_ div 3+1)*(1-$_%3)} my @tests = ( 0 => 1, 11 => -4, 76 => 0, 134 => -45, 296 => -99, 15..^30 => (6,0,-6,7,0,-7,8,0,-8,9,0,-9,10,0,-10) ); plan @tests * 2 - 1; for @tests { is alt-seq-sign( .key ), .value, 'alt-seq-sign ' ~ .gist; next if .key ~~ Range; # doesn't support Range as an input is short-one( .key ), .value, 'short-one ' ~ .gist; } ``` ``` 1..11 ok 1 - alt-seq-sign 0 => 1 ok 2 - short-one 0 => 1 ok 3 - alt-seq-sign 11 => -4 ok 4 - short-one 11 => -4 ok 5 - alt-seq-sign 76 => 0 ok 6 - short-one 76 => 0 ok 7 - alt-seq-sign 134 => -45 ok 8 - short-one 134 => -45 ok 9 - alt-seq-sign 296 => -99 ok 10 - short-one 296 => -99 ok 11 - alt-seq-sign 15..^30 => (6 0 -6 7 0 -7 8 0 -8 9 0 -9 10 0 -10) ``` [Answer] # J, ~~19~~ 15 bytes ``` >.@(%&3)*1-3|<: ``` Probably need to golf this further... 1-indexed. ### Ungolfed: ``` >> choose_sign =: 1-3|<: NB. 1-((n-1)%3) >> choose_magnitude =: >.@(%&3) NB. ceil(n/3) >> f =: choose_sign * choose_magnitude >> f 1 12 77 << 1 _4 0 ``` Where `>>` means input (STDIN) and `<<` means output (STDOUT). [Answer] ## Pyke, ~~8~~ 7 bytes (old version) ``` 3.DeRt* ``` [Try it here!](http://pyke.catbus.co.uk:3434/?code=3.DeRt%2a&input=10) - Note that link probably won't last for long ``` 3.D - a,b = divmod(input, 3) e - a = ~a -(a+1) t - b -= 1 * - a = a*b - implicit output a ``` Newest version ``` 3.DhRt*_ ``` [Try it here!](http://pyke.catbus.co.uk/?code=3.DhRt%2a_&input=10) ``` 3.D - a,b = divmod(input, 3) h - a+=1 t - b-=1 * - a = a*b _ - a = -a - implicit output a ``` [Answer] # J, 27 bytes Whilst not the golfiest, I like it better, as it uses an agenda. ``` >.@(>:%3:)*1:`0:`_1:@.(3|]) ``` Here is the tree decomposition of it: ``` ┌─ >. ┌─ @ ──┤ ┌─ >: │ └────┼─ % │ └─ 3: ├─ * ──┤ ┌─ 1: │ ┌────┼─ 0: │ │ └─ _1: └─ @. ─┤ │ ┌─ 3 └────┼─ | └─ ] ``` This is very similar to Kenny's J answer, in that it chooses the magnitude and sign, but it's different in that I use an agenda to choose the sign. [Answer] # MATL, 8 bytes ``` _3&\wq*_ ``` This solution uses 1-based indexing into the sequence. [**Try it Online**](http://matl.tryitonline.net/#code=XzMmXHdxKl8&input=MQ) [Modified version showing all test cases](http://matl.tryitonline.net/#code=YF8zJlx3cSpfRFRd&input=MQoxMgo3NwoxMzUKMjk3) **Explanation** ``` % Implicitly grab the input _ % Negate the input 3&\ % Compute the modulus with 3. The second output is floor(N/3). Because we negated % the input, this is the equivalent of ceil(input/3) w % Flip the order of the outputs q % Subtract 1 from the result of mod to turn [0 1 2] into [-1 0 1] * % Take the product with ceil(input/3) _ % Negate the result so that the sequence goes [N 0 -N] instead of [-N 0 N] % Implicitly display the result ``` [Answer] # Pyth, 10 bytes ``` *h/Q3-1%Q3 ``` [Try it online!](https://pyth.herokuapp.com/?code=%2Ah%2FQ3-1%25Q3&test_suite=1&test_suite_input=0%0A11%0A76%0A134%0A296&debug=0) Explanation: ``` * : Multiply following two arguments h/Q3 : 1 + Input/3 -1%Q3 : 1 - Input%3 ``` Note: I've assumed the zero-indexed sequence. [Answer] ## Actually, 10 bytes ``` 3@│\u)%1-* ``` [Try it online!](http://actually.tryitonline.net/#code=M0DilIJcdSklMS0q&input=MTE) Explanation: ``` 3@│\u)%1-* 3@│ push 3, swap, duplicate entire stack ([n 3 n 3]) \u) floor division, increment, move to bottom ([n 3 n//3+1]) %1- mod, subtract from 1 ([1-n%3 n//3+1]) * multiply ([(1-n%3)*(n//3+1)]) ``` [Answer] # GeoGebra, 44 bytes ``` Element[Flatten[Sequence[{t,0,-t},t,1,n]],n] ``` where `n` is one-indexed. Explanation: ``` Element[ , n] # Return the nth element of the list . Flatten[ ] # Strip all the unnecessary braces from the list /|\ Sequence[{t,0,-t}, t, 1, n] # Generate a list of lists of the form {t, 0, -t} | # This list will start with {1,0,-1} and end with {n,0,-n} | ``` It is not necessary to generate all triplets through `{n, 0, -n}`, but it's shorter than writing `ceil(n/3)` or something to that effect. Note that `n` must be defined to create this object (if it isn't defined at the time this is run, GeoGebra will prompt you to create a slider for `n`). [Answer] ## [Labyrinth](https://github.com/mbuettner/labyrinth), ~~17~~ ~~15~~ 14 bytes *Saved 3 bytes using Sok's idea of using `1-(n%3)` instead of `~(n%3-2)`.* ``` 1?:#/)}_3%-{*! ``` The program terminates with an error (division by zero), but the error message goes to STDERR. [Try it online!](http://labyrinth.tryitonline.net/#code=MT86Iy8pfV8zJS17KiE&input=Mjk2) ### Explanation The program is completely linear, although some code is executed in reverse at the end. ``` 1 Turn top of stack into 1. ?: Read input as integer and duplicate. # Push stack depth (3). /) Divide and increment. } Move over to auxiliary stack. _3% Take other copy modulo 3. - Subtract from 1. This turns 0, 1, 2 into 1, 0, -1, respectively. {* Move other value back onto main stack and multiply. ! Output as integer. ``` The instruction pointer now hits a dead end and turns around, so it starts to execute the code from the end: ``` * Multiply two (implicit) zeros. { Pull an (implicit) zero from the auxiliary to the main stack. - Subtract two (implicit) zeros from one another. Note that these were all effectively no-ops due to the stacks which are implicitly filled with zeros. % Attempt modulo, which terminates the program due to a division-by-zero error. ``` [Answer] ## Erlang, 40 bytes ``` F=fun(N)->trunc((N/3+1)*(1-N rem 3))end. ``` Sadly Erlang has no '%' modulo operator and 'rem' requires the spaces, even before the 3. [Answer] # [Hexagony](http://esolangs.org/wiki/Hexagony), 25 bytes ``` ?'+}@/)${':/3$~{3'.%(/'*! ``` Or, in non-minified format: ``` ? ' + } @ / ) $ { ' : / 3 $ ~ { 3 ' . % ( / ' * ! . . . . . . . . . . . . ``` [Try it online!](http://hexagony.tryitonline.net/#code=PycrfUAvKSR7JzovMyR-ezMnLiUoLycqIQ&input=Mjk2) My first foray into Hexagony, so I'm certain I've not done this anywhere near as efficiently as it could be done... Calculates `-(n%3 - 1)` on one memory edge, `n/3 + 1` on an adjacent one, then multiplies them together. [Answer] # R, 28 bytes ``` -((n=scan())%%3-1)*(n%/%3+1) ``` Looks like this is a variation of most of the answers here. Zero based. ``` n=scan() # get input from STDIN ( )%%3-1 # mod by 3 and shift down (0,1,2) -> (-1,0,1) -( ) # negate result (1,0,-1), this handles the alternating signs *(n%/%3+1) # integer division of n by 3, add 1, multiply by previous ``` The nice thing about it is that it handles multiple inputs ``` > -((n=scan())%%3-1)*(n%/%3+1) 1: 0 3 6 9 1 4 7 10 2 5 8 11 13: Read 12 items [1] 1 2 3 4 0 0 0 0 -1 -2 -3 -4 > ``` Originally I wanted to do the following, but couldn't trim off the extra bytes. ``` rbind(I<-1:(n=scan()),0,-I)[n] ``` Uses `rbind` to add 0's and negatives to a range of 1 to `n` then return the `n`'th term (one based). ``` # for n = 5 rbind( ) # bind rows n=scan() # get input from STDIN and assign to n I<-1:( ) # build range 1 to n and assign to I ,0 # add a row of zeros (expanded automatically) ,-I # add a row of negatives [n] # return the n'th term ``` [Answer] # Batch (Windows), 86 bytes ## Alternate.bat ``` SET /A r=%1%%3 SET /A d=(%1-r)/3+1 IF %r%==0 ECHO %d% IF %r%==1 ECHO 0 IF %r%==2 ECHO -%d% ``` This program is run as `Alternate.bat n` where `n` is the number you wish to call the function on. [Answer] ## APL, 12 chars ``` -×/1-0 3⊤6+⎕ ``` `0 3⊤` is APL's `divmod 3`. [Answer] # Java 7, 38 37 36 bytes My first golf, be gentle ``` int a(int i){return(1+i/3)*(1-i%3);} ``` [Try it here!](https://ideone.com/t52W7d) (test cases included) Edit: I miscounted, and also golfed off one more character by replacing `(-i%3+1)` with `(1-i%3)`. [Answer] # Retina, 45 bytes ``` .+ 11$&$* (111)+(1)* $#2$#1 T`d`+0-`^. ^0.+ 0 ``` [Try it online!](http://retina.tryitonline.net/#code=LisKMTEkJiQqCigxMTEpKygxKSoKJCMyJCMxClRgZGArMC1gXi4KXjAuKwow&input=MTI) [Test suite.](http://retina.tryitonline.net/#code=JShgLisKMTEkJiQqCigxMTEpKygxKSoKJCMyJCMxClRgZGArMC1gXi4KXjAuKwow&input=MQoxMgo3NwoxMzUKMjk3) Takes input/output in base-ten. 1-indexed. ### Unary input, base-ten output, 1-indexed: 40 bytes ``` $ 11 (111)+(1)* $#2$#1 T`d`+0-`^. ^0.+ 0 ``` [Try it online!](http://retina.tryitonline.net/#code=JAoxMQooMTExKSsoMSkqCiQjMiQjMQpUYGRgKzAtYF4uCl4wLisKMA&input=MTExMTExMTExMTEx) [Test suite.](http://retina.tryitonline.net/#code=JShgJAoxMQooMTExKSsoMSkqCiQjMiQjMQpUYGRgKzAtYF4uCl4wLisKMA&input=MQoxMTExMTExMTExMTEKMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEKMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExCjExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMQ) [Answer] # MATLAB / Octave, 27 bytes ``` @(n)ceil(n/3)*(mod(-n,3)-1) ``` This creates an anonymous function that can be called using `ans(n)`. This solution uses 1-based indexing. [All test cases](http://ideone.com/WsepZL) [Answer] # Mathematica 26 bytes With 4 bytes saved thanks to Martin Ender. ``` ⎡#/3⎤(-#~Mod~3-1)& ``` Uses the same approach as Suever. [Answer] # Octave, 23 bytes With no mod cons... ``` @(n)(-[-1:1]'*[1:n])(n) ``` Uses 1-based indexing magic. --- **Explanation** Creates an anonymous function that will: ``` (-[-1:1]'*[1:n])(n) [-1:1] % make a row vector [-1 0 1] - ' % negate and take its transpose making a column vector [1:n] % make a row vector [1..n], where n is the input * % multiply with singleton expansion (n) % use linear indexing to get the nth value ``` After the multiplication step we'll have a 3xn matrix like so (for n=12): ``` 1 2 3 4 5 6 7 8 9 10 11 12 0 0 0 0 0 0 0 0 0 0 0 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 ``` Making `n` columns is overkill, but it's a convenient number that is guaranteed to be large enough. Linear indexing counts down each column from left to right, so the element at linear index `4` would be `2`. All test cases on [ideone](http://ideone.com/LwePaM). [Answer] # dc, 10 ``` ?2+3~1r-*p ``` Uses 1-based indexing. ``` ? # Push input to stack 2+ # Add 2 3~ # divmod by 3 1r- # subtract remainder from 1 * # multiply by quotient p # print ``` ]
[Question] [ Given a string consisting of `()[]{}`, print the paired brackets in the same order as they appear in the string. Any opening bracket `([{` can be paired with any closing bracket `)]}`. For example: ``` ({()[}]] returns: (], {], (), [} ``` # Rules * A string consisting of `()[]{}` should be received as the input * The bracket-pairs should be returned as a list, or separated by a distinct character (or nothing), etc. * The bracket-pairs should be in the same order as the starting brackets in the string * The brackets will be balanced, i.e. the number of opening brackets and the number of the closing brackets will be the same * [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 code wins! # Examples ``` [In]: () [Out]: () [In]: (}{] [Out]: (}, {] [In]: ([{}]) [Out]: (), [], {} [In]: {]([(}]{)} [Out]: {], (}, [], (}, {) ``` [Answer] # x86-64 machine code, ~~16~~ 15 bytes ``` 57 57 AA 5A 88 02 AC 3C 22 7B F8 AA 79 F2 C3 ``` [Try it online!](https://tio.run/##VVI9b9swEJ15v@LKwgCZKIHhtBmsukvmLp0KKBpkirIYSKSgo1MZgv561bMMG8lC3r33@O4DNF33cDBmngtqUeFvqeDx0IR90WAFtBXdkWrsSwcfIoqB9tAzGTpGBhBteMeMozzBooFqK5pQskSYtmMgwfWw2YB46wL21@fizRMSiN5G0BJ1CnaItvcoXySO78GVWClTFz3e9ZaOTUzQBE8RLxjpFBcRKZ1OAF@dN82xtPiDYunCY/0T4KM@WoqmIEtZjjscpdIyQammMV/ubJxy/Tkac5WpKR/1JKcUnI/YFs4rDSOIKvSoPtnjFm8lNAjWiIW59J5tvj/nKWOVug4T9TnvejaulFwRrujVc12mLpIzP8FN8ep/FaZ23vIaSruVZ/rc1MDjrBM8cVoGHK9yXK03f9jutFPq6MkdvC2XXu806Wy4v895bfi3do1FdcIvbDK8PJ1Nbw5q5XB/4qn00tjA5DTP/0zVFAeaH9rnb3zwt9mx3jb/AQ "C++ (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string; and the address of the input, as a null-terminated byte string, in RSI. The starting point is after the first 6 bytes. In assembly: ``` s: push rdi # (Left brackets) Push the current output address push rdi # onto the stack twice. stosb # Add AL to the output string again as a placeholder, # advancing the pointer. # (Right brackets enter here.) r: pop rdx # Pop from the stack into RDX. mov [rdx], al # Place AL at that address. # For right brackets, this puts them in the spot reserved previously. # For left brackets, this does nothing: the value there is the same. f: # (START HERE.) lodsb # Load a byte from the input string into AL, advancing the pointer. cmp al, 0x22 # Set flags from that number minus 0x22. jpo r # Jump if it has an odd number of 1 bits, true for right brackets. stosb # (Left & null) Add AL to the output string, advancing the pointer. jns s # Jump if the result was nonnegative. ret # (Null terminator) Return. ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 144 bytes ``` {(({}(<()>))<<>(()()()()){(({})){<>({}[()])}{}}>)<>({}[{}])((){[()](<{}>)}){{}{}<>(<({}<<>{({}<>)<>}{}>)>)}{}<>{({}<>)<>}{}}<>{({}<({}<>)>)<>}<> ``` [Try it online!](https://tio.run/##TY5BCsNADAO/Ix3yA@OPhD2kgUBp6SFXobdvvbsUig/CM8L4cR/Pz3a9j1fvAmQEmGREAlzDKSqKyTvYaNnJtcuN1dUQCBU3pWqUjirUKY0YfQ@dnPIf/taFJoysjxp2uInu2/kF "Brain-Flak – Try It Online") Every bracket matching challenge needs a Brain-Flak submission. ``` # For each character in the input { # Push zero below character, and keep another copy of character on third stack (({}(<()>))< # Compute character mod 4 <>(()()()()){(({})){<>({}[()])}{}} # Push character back onto left stack >) # Is character equal to 1 mod 4? <>({}[{}]) # If so: ((){[()](<{}>)}){ {}{}<>(<({}< # Move to first 0 in right stack <>{({}<>)<>}{} # Push character, along with zero to break conditional >)>) }{} # Move elements back to right stack (or move character above an earlier pushed zero if was opening bracket) <>{({}<>)<>}{} } # Move bracket pairs to left stack to output in correct order <>{({}<({}<>)>)<>}<> ``` [Answer] # [Python](https://www.python.org), ~~77~~ 72 bytes Returns a string without separators. ``` f=lambda s,a='':s and f(s[:-1],(r:=s[-1]+a)[(q:=6-ord(s[-1])&2):])+r[:q] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3PdJscxJzk1ISFYp1Em3V1a2KFRLzUhTSNIqjrXQNY3U0iqxsi6OBLO1EzWiNQitbM938ohQNsJCmmpGmVaymdlG0VWEs1DzPgqLMvBKNNA11DU11TU0uBLe2OhZVILq6NhZVTXWsRrRGbWy1Zi1QGGIgzKEA) `6-ord(x)&2` is 2 for opening brackets and 0 for closing ones. [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 45 bytes ``` f[]=[] f(a:b++c:d)|elem c")]}"=[a,c]:f b++f d ``` [Try it online!](https://tio.run/##NYy9CsMgFIV3n@Lm0kFJ8gJCsncoHTrKpVgTS2gTJDFDsT67NUKnc/jOj9nX9dM6/TJbSlZRp4hZruWjro0cxHd8jzMYFBSxU7oxJC3kzMKQ/Lh5kBJufp2WJ7Q9nK/ABSt8gw7c7nOWbd//PR41PAB3eeXhVFVgATbB2KynJa9m7S53KCcKucAGkMdARVWIVEggrnikICJS@gE "Curry (PAKCS) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` RvyžuykÈiìˆ]¯R ``` -3 bytes thanks to *@ovs*. [Try it online](https://tio.run/##yy9OTMpM/f8/qKzy6L7SyuzDHZmH15xuiz20Puj/f41qDc3o2thYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn2l0v@gssqj@0orsw93ZB5ec7ot9tD6oP9KemE6h7b816jW0IyujY3l0tDk0qitBtLR1bWxmlzVsRrRGrWx1Zq1AA). **Explanation:** ``` R # Reverse the (implicit) input v # Pop and loop over each character `y`: y # Push the character žuykÈi # If the character is an opening bracket: žu # Push constant string "()<>[]{}" yk # Get the (0-based) index of the character in this string Èi # If this index is even: ì # Prepend the top two characters together ˆ # Pop this pair and add it to the global array ] # Close both the if-statement and loop ¯ # Push the global_array R # Revert it # (after which it is output implicitly as result) ``` [Answer] ## Pyth - 23 bytes Uses the fact that all the closing brackets (and none of the opening brackets) are 1 modulo 4 in ascii. ``` tMt#S.e?t%Cb4aY,kb+.)Yb tM map "removing the first element" t# filter on a no-op (its no-op in this case) S sort .e map over enumerate (k is idx, b is element) ? ternary (0 is falsey) t subtract 1 % 4 modulo 4 Cb convert b to char code aY append to Y (Y is global starting at []) ,kb [k, b] + concatenate .)Y pop from back of Y b ``` [Try it online](http://pythtemp.herokuapp.com/?code=tMt%23S.e%3Ft%25Cb4aY%2Ckb%2B.%29Yb&test_suite=1&test_suite_input=%22%28%7B%28%29%5B%7D%5D%5D%22%0A%22%28%29%22%0A%22%28%7D%7B%5D%22%0A%22%28%5B%7B%7D%5D%29%22%0A%22%28%5B%7B%7D%5D%29%22%0A%22%7B%5D%28%5B%28%7D%5D%7B%29%7D%22&debug=0). [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt#L189), ~~13~~ 11 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` x{_$4%┴┌Å▌¬ ``` -2 bytes by outputting without delimiter, which is apparently allowed (see "*(or nothing)*" in the second rule) [Try it online.](https://tio.run/##y00syUjPz0n7/7@iOl7FRPXRlC2PpvQcbn00refQmv//lTSqNTSja2NjlbiUNDRBRG01mB1dXRsL4lfHakRr1MZWa9YqAQA) **Explanation:** ``` x # Reverse the (implicit) input-string { # Foreach over each character: # (implicitly push the current character we're looping over) _ # Duplicate this character $4%┴┌Å # If this character is an opening bracket: $ # Pop the copy, and push its codepoint-integer 4% # Modulo-4 ┴ # Check if this is equal to 1 ┌ # Invert this boolean Å # Loop that many times, # using 2 characters as inner code-block: ▌ # Prepend the top two characters together ¬ # Rotate the entire stack once towards the right # (implicitly output the entire stack joined together) ``` There are a bunch of alternatives possible for `4%┴┌Å▌¬`, like for example `Z+¶¿⌐▌¬`: [try it online](https://tio.run/##y00syUjPz0n7/7@iOl4lSvvQtkP7H/VMeDSt59Ca//@VNKo1NKNrY2OVuJQ0NEFEbTWYHV1dGwviV8dqRGvUxlZr1ioBAA). ``` Z+ # Add 38 to the codepoint-integer ¶ # Check if this is a prime number ¿ # If this is truthy, thus a closing bracket: ⌐ # Rotate the entire stack once towards the left ¿ # Else: ▌ # Prepend the top two characters together ¬ # Then rotate the entire stack once towards the right ``` [Answer] # [Mathematica/Wolfram Language](https://www.wolfram.com/language/), 90 88 bytes ``` Transpose@MapAt[Reverse,GatherBy[Characters@#,Mod[First@ToCharacterCode@#,4]==1&]&@#,2]& ``` Uses the Mod-4 trick from the Pyth answer to split the characters into opening and closing brackets. Takes me 20 characters to reverse the closing list (so that the first opening bracket matches the last closing) which is annoying. Then, we transpose the lists and output. Shaved two characters by keeping the characters as characters and simply comparing their char codes. 11 more characters can be removed if we allow input as a list of chars instead of as a string. [Try it online!](https://tio.run/##y00syUjNTSzJTE78/9@tKD/XOSOxKDG5JLXIOT8lVd8hpCgxr7ggvzjVwTexwLEkOii1LLWoOFXHHaSvyKkyOiQfRYeDso5vfkq0so5JrK2toVqsGlDACEgqaVRraEbXxsYq6esHFGXmlfz/DwA) [Answer] # [Bash](https://www.gnu.org/software/bash/), 104 99 94 bytes ``` awk '/[[{(]/{s[i++]=NR$1;next}{a[j++]=s[i---1]$1}END{for(x in a)print a[x]}'|sort -n|tr -d 0-9 ``` [Try it online!](https://tio.run/##TYoxC8IwEIX3/IoDC00poWYUcdO1g@uRIaJiFdKSBCxc77fHNA56cO99995dbHikZN8vqDtEkqajgEPbmkN/rvTe3ebIZPG5JrlQSmlTaT71R7qPXs4wOLDN5AcXweJsuF7C6CMot0QP6gpbtUsbyENmVcmr4h9TU7gkxL9P4kTCCCkwL2ci0WSX2b9X8Q8 "Bash – Try It Online") *-5 thanks to m90 for `tr` idea!* Bash translation of my JS answer. Was a nicer fit for awk than JS. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 73 bytes ``` s=>s.map(c=>[c]).filter(c=>/[([{]/.test(c)?s.push(c):!s.pop().push(c[0])) ``` [Try it online!](https://tio.run/##jYwxDsIwDEV3bsEUe8Blpmo5iOWhCim0Kk1UpyxRzh6KxIQYur3/9fTG7tWpXYYQT7O/udI3RZtW6dkFsE3LVpD6YYpu@cyKgZNUFJ1GsHhVCqs@NrocN/QB8HvwWRBLfbB@Vj85mvwdemAiMoBma45@mMHUBvG/lJPs0Thl2dNLAgxZEuYfubwB "JavaScript (Node.js) – Try It Online") I/O is lists of characters, but the examples in the footer convert from and to strings for convenience. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 70 bytes ``` s=>s.map(c=>s[/[[({]/.test(c)?s.push([c])-1:s.pop()[0]+=c]||[]).flat() ``` [Try it online!](https://tio.run/##dYtLDsIwDAX3XKS2UF3YggIHsbyIQsJHpYlwYJPm7KFiTXfzNG8e9mPVve4p91O8@BZMU3NSetoEbgEemKHIQNlrBodnpfTWG7AT7PeHZcUEyDvZGifzzIIURpsBm4uTxtHTGK8QgImoA@wE8bj5p2qRdcmlynpbBBiqFKy/S/sC "JavaScript (Node.js) – Try It Online") Input array of characters. The idea about reusing `s` as the stack is learnt from [Neil](https://codegolf.stackexchange.com/users/17602/neil)'s [answer](https://codegolf.stackexchange.com/a/246293/44718). [Answer] # [PHP](https://www.php.net/), 93 bytes ``` $i=0;foreach(str_split($argn)as$v){if(strpos(" ({[",$v)){$a.=$v;}else{echo"$a[$i]$v ";$i++;}} ``` [Try it online!](https://tio.run/##FclBCsMgEEDRqwSZxUja0r0N3fUSIkWCqQMhDipuBq9em27@4n2OPB5PPgu03M2WcvBrxFLzu/BOFcHnz6F9gaaFtv/gVFBNKFZdTtQC/rZAMz3sJUhYY1LgLZCDNikDNM@m9zHEocXuRPdv4krpKOP6@gE "PHP – Try It Online") Explanation: As opening brackets are encountered in the given string they're appended to a second string, then later paired up with closing brackets as the latter are encountered in the given string. [Answer] # Python3, 155 bytes: ``` lambda x:f(x)[0] def f(s): t,r=[],[] while s and s[0]in'([{': if s[1]in')]}':t+=[s[:2],*r];r=[];s=s[2:] else:x,y=f(s[1:]);r+=x;s=s[0]+y return t+r,s ``` [Try it online!](https://tio.run/##VY2xDsIgFEV3vuJtgGXQuhga1v7E8w01pbFJxQYwtiF8e6UuxvGenJw7r/H@dOfL7LfWXLepe9z6DhY9iEXikVhvBxhEkJpBVN4gKSQG7/s4WQjQuR5C0UbHBSZeJBiHQk47kZS5jpXBgLomdfDU7IEmmIC1LhWwU7B6UaspD3jSJBtfmeUrHKlaGXgbX95BrLwK2@xHF0UruJBcSvabOdE/wJTp30kkUGRKMhe8fQA) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 43 bytes ``` M!&`[({[](([({[])|(?<-2>).)*. (.).+(.) $1$2 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7w31dRLSFaozo6VkMDTGnWaNjb6BrZaeppaulxaehp6mkDCS4VQxWj//81NLm4NGqrY4FkdHVtrCaCro4Faq@NrdasBQA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` M!&` ``` List all overlapping matches... ``` [({[](([({[])|(?<-2>).)*. ``` ... match an opening bracket, then any number of matched brackets, and then another character. ``` (.).+(.) $1$2 ``` Remove the inner matched brackets from each result. [Answer] # [Ruby](https://www.ruby-lang.org/), 103 bytes ``` ->d{s,a=[],[];i=-1;d.chars.map{|x|i+=1;/[\[{(]/=~x ?s<<[i,x]:[t=s.pop,t[1]+=x,a<<t]};a.sort.map{_1[1]}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY1BCsIwFET3nqK7pjRNyUIQk-hBvh-JlmoX0tCkEEnjRdwU0UN5G8VKV_PgMTP3Z9cfruOjVq_e1cXqfSo2VbBUK0AKKBpVcFGx41l3ll20CYMfmlxxUcIOAsFS3XyytVJCQz2uwSnLTGuoA4658lRL6TAKzWzbud_Ann9VjP-7pUlqSEmW4mKiGHBmCBFnE5AAiRiymOJUHscpPw) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~24~~ 22 bytes ``` FS¿№)]}ιUM⊟υι«ι⊞υKD¹↙↙ ``` [Try it online!](https://tio.run/##RcuxCoMwEIDhWZ/icLqADl3rqEuhQqBjcQj2rKGaCzGxg@TZU526fvz/MCk3sJpTGtkB3owN/uGdNm8UAvQI2HAwHgvRx6IEfWCnbMPLoswLJVsM4uQ6p3kl2PNMHrPHUzIZ1glDCZLo02pHg9ds8FLCteWvudPoxZl1vBH@qc5jSnuPT4z9LmKqtvkH "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FS ``` Loop over the characters in the input string. ``` ¿№)]}ι ``` If this is a close bracket, then... ``` UM⊟υι« ``` ... pop a peeked cell and replace it with the close bracket, otherwise: ``` ι ``` Output the open bracket. ``` ⊞υKD¹↙ ``` Peek the cell now under the cursor, but as a list whose elements can be modified. ``` ↙ ``` Move to the start of the next line. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ ~~15~~ 14 bytes ``` O’4ḍ-*Ä+ƲỤs2Ṣị ``` [Try it online!](https://tio.run/##AUYAuf9qZWxsef//T@KAmTThuI0tKsOEK8ay4bukczLhuaLhu4v/4biyw4figqxL//8oKSAofXtdIChbe31dKSB7XShbKH1deyl9 "Jelly – Try It Online") Function returning a list of pairs, or full program smash-printing with no separator. Uses Maltysen's mod 4 trick. ``` O’ Decrement the codepoints of the input, 4ḍ and test divisibility by 4. O’4ḍ That is, for each bracket, is it closing? -* Raise -1 to the power of each, Ä take cumulative sums, +Ʋ and add the ones back in. O’4ḍ-*Ä+Ʋ This gives the depth of each bracket. Ụ Grade up: sort the indices by the obtained depths. s2 Split the indices into adjacent pairs, Ṣ sort the pairs lexicographically, ị and index back into the original list. ``` [Answer] # [Julia](https://julialang.org), 60 bytes ``` !x=x>"" ? !((m=match(r"(.*)([([{].)(.*)",x))[1]m[3])m[2] : x ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY1BDoIwEEX3PcXQ1YwREnVjjOBBmlkQgVhDi6mQNGl6EjdsOIRH8TbW4F_9xfv_vZb71Ot6npdp7PLj55z50ldSwgUyRFOaerze0EksNoQKVeCCfl1uPZHasVEHJqP2DCfw_4-8Gxx40BZcWze9tu0TSUDKw2k79hY9lBVknkRrm3U0vxOCMbBIjsgkAidd5EBxBb4) Similar to other answers, using a regex to capture the last open bracket + the next character [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~122~~ 111 bytes *6 bytes, 1 byte, and 2 bytes saved thanks to @ceilingcat, @m90, and @ovs* ``` i;f(s,l,n)char*s,*n;{for(n=s;i+=~-(-*n&2)%~*n;n++);l-=printf("%c%c",*s,*n)+(n-++s?f(s,n-s),n-s:0);l&&f(n+1,l);} ``` [Try it online!](https://tio.run/##RYzBasMwEETP9VcYFZtdSyJNjhWmP5Gb0UEoViJQtsFy6UEon15VNpQedtmZN7NWXq0txSsHUQRBaG9mGaIYSCX3uQCNUXk@PiXIgfoTds9KiHNUQY6PxdPqgHW2s0zsLeRAkvP4sf0jGXFb72813vcOiB9FQJXL62V2nub2DAZbB0bEdQkzVYXi8bVGYAybu/EEmJozMECG6uVwaAF3mZP@M@q5W1PK@j816ZQ3O2mYIOuEuaJKqs5TnYRNLj/WBXONRX7/Ag "C (gcc) – Try It Online") Takes input as a pointer to a character array and its length `f(array,length)` (the third parameter is unused). Outputs the mashed-together brackets to stdout. [Answer] # [Perl 5](https://www.perl.org/), 59 bytes ``` sub{$_=pop;1while s/(.*)([({[][)}\]])/unshift@_,$2;$1/e;@_} ``` [Try it online!](https://tio.run/##TY9PT8QgEMXv/RSThhUw6FqjlyXV3k3cizeWNFGp27i22D9RQ/jsdWhJthwI8@b33gzWdKf7iVT51I@vjpS5ba3Mfo71yUC/ZdeXnCnmlFbcH7Tm27Hpj3U1FKUgt5JkWyOL0k8yqdqOJQAKKHOMK681BYD8AWtNBVA334yHW3kKWkSaB245M81XPe80Xfd8TDoTynkdE6I75C8TV1Ocxl947ThqgYvb@DMds5fp3KHt64@RurGiML@W5wUp5SwWH@2QX5BqbvKg2a5uhird9LgEauOwg81VdhNKtJq3wbzPyl1Q0I1Ff2hSAWmITsF84wv1FB6Btp8UdkCf9y@wf8KV5hUWUCyUTPz0Dw "Perl 5 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 123 113 129 bytes ``` d=>(s=a=[],[...d].map((x,i)=>/[[{(]/.test(x)?s=[...s,[i,x]]:a.push((t=s.pop(),t[1]+=x,t))),a.sort((a,b)=>a[0]-b[0]).map(x=>x[1])) ``` [Try it online!](https://tio.run/##dVFBbsMgELz7FdyymxLcXiORnnvqA9AeiE0SN66xDKmQkN/urpO6kar0wLLMDDOL@LBfNlRD08dN52s3HfRU6x0EbbUhaZRSNalP2wMk2aDelcZkoFJFFyIkfA161gRpGpmItlb1l3ACiDqo3veAMpoXetJJRkSUVgU/RAAr9@xlzTNt9lzwmpD0LrEYcap8F3zrVOuPcIAV4Aqx@AuOmR7BJo/0SJ8JDIyUcZzJoixF67ujG8T8ElHZ4ETnXO1qEb3YD86eRetSU/njYPtTU4l58v9NgWMzr5v5ujBvHW0FYGHeL/HWLRgP/ouOUvBpYa6z329IwV8g8rjw97RFk5mfPczPnjklE7eMzDWjAGIHFs4@63L6Bg "JavaScript (Node.js) – Try It Online") *-10 thanks to Steffan!* *+16 thanks to allxy for pointing out I need to explicitly specify numeric sort* Uses a stack `s` which tracks open characters along with their index of occurence. On each close character, moves the top stack element to an answer array `a`, modifying it to include the close character. At the end, sorts according to start index and returns the pairs. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 67 bytes ``` f=lambda s:s and f(s[:(q:=len(s.strip(']})'))-1)]+s[q+2:])+s[q:q+2] ``` [Try it online!](https://tio.run/##PcoxCgIxEEbh3lOkyz8sCmojA3uSMEVkDS6sMZtJIyFnj7Gxe3y89CnPd7zeUu49zJt/3RdvlNX4uJgAdYyd5@0RoScteU2w0sgSHc8kk7p9urDQL3ik9JTXWBBgUUGuiYz18McqcGhSqQ3uXw "Python 3.8 (pre-release) – Try It Online") Finds the rightmost opening bracket, which by definition must be paired with a closing bracket. Then, it recursively prepends the remaining brackets in the same way. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 45 bytes [SBCS](https://github.com/abrudz/SBCS) while this does change the order of brackets i found this approch very intersting ``` {{⍵[a,⍨(⍳≢⍵)~a←0 1+1⍳⍨2-/⍵∊'({[']}⍣(2÷⍨≢⍵)⊢⍵} ``` explanation ``` {f⍣n⊢⍵} ⍝ rubs the function f , n tikes which half its length 0 1+1⍳⍨2-/⍵∊'({[' ⍝ finds the index of first pair of brackets a,⍨(⍳≢⍵)~a ⍝ puts those brackets at the end of the array ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q65@1Ls1OlHnUe8KjUe9mx91LgLyNesSH7VNMFAw1DYEifWuMNLVBwo/6uhS16iOVo@tfdS7WMPo8HagDFTDoy4QVQsA&f=AwA&i=AwA&r=tryapl&l=apl-dyalog&m=tradfn&n=f) A full program which \_\_\_\_. ]
[Question] [ ### Introduction A normal checkers board contains 8 x 8 = 64 squares: [![enter image description here](https://i.stack.imgur.com/Z41aH.jpg)](https://i.stack.imgur.com/Z41aH.jpg) You can see that in total, there are **12 white pieces**. Black and white always have the same amount of pieces. If there are any more pieces on the board, the pieces would neighbouring, which is not allowed for this challenge. To clarify things, here are some examples: The smallest board possible for this challenge is **3 x 3**: [![enter image description here](https://i.stack.imgur.com/35aKG.jpg)](https://i.stack.imgur.com/35aKG.jpg) You can see that the maximum amount of pieces is equal to **2**. So, when given **N = 3**, you need to output **2**. If the input is **N = 4**, we get the following: [![enter image description here](https://i.stack.imgur.com/v3YUA.jpg)](https://i.stack.imgur.com/v3YUA.jpg) You can see that the maximum amount is also 2. So for **N = 4**, the output should be **2**. For **N = 5**, the output should be equal to **5**: [![enter image description here](https://i.stack.imgur.com/JoSBg.jpg)](https://i.stack.imgur.com/JoSBg.jpg) ### Examples ``` STDIN: 3 STDOUT: 2 STDIN: 4 STDOUT: 2 STDIN: 5 STDOUT: 5 STDIN: 6 STDOUT: 6 STDIN: 8 STDOUT: 12 ``` ### Rules * Your submission must be a program, or function etc. that takes one integer and outputs or returns the number of pieces on the board * You can safely assume that the input is an non-negative integer > 2 * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the program with the least amount of bytes wins! * *Note that the square in the lower left of the board is always dark. Pieces are only placed on dark squares* * You have to occupy a full row with pieces [Answer] ## [Hexagony](https://github.com/mbuettner/hexagony), 19 bytes ``` ?({{&2'2':{):!/)'*/ ``` [Try it online.](http://hexagony.tryitonline.net/#code=ICA_ICggewogeyAmIDIgJwoyICcgOiB7ICkKIDogISAvICkKICAnICogLw&input=OA) ### Explanation This is still the same computation as I've used in my CJam and Labyrinth answers, but due to Hexagony's... special... memory model, it's a bit trickier to squeeze the computation into 19 bytes (so that it fits inside a side-length 3 hexagon). Like my Labyrinth answer, this terminates with a division-by-0 error. Here is the unfolded code: [![enter image description here](https://i.stack.imgur.com/1hKKG.png)](https://i.stack.imgur.com/1hKKG.png) As I said the code is entirely linear. You can piece the executed path together in order grey-purple-green-red-blue. The path actually continues a bit further until it hits the `:` on the left. Removing the `/` (which only redirect control flow), the entire program unrolled linearly is: ``` ?({2':{)'*){&2':!:&?': ``` So the question is how does it work. Hexagony's memory is the line graph of a hex grid, where each edge of the grid contains an integer value (initially zero). The memory pointer (MP) is always on one edge and points in a certain direction along that edge. Arithmetic operations are generally applied to the two edges pointed *at* and stored in the edge the MP is on. For this program, we'll be using the three edges labelled **A**, **B**, **C**, with the MP starting as shown here: [![enter image description here](https://i.stack.imgur.com/YZRA7.png)](https://i.stack.imgur.com/YZRA7.png) So here is how this works: ``` ? Read an integer N from STDIN into edge A. ( Decrement to get N-1. { Move the MP forwards onto edge B. 2 Set the edge to 2. ' Move the MP backwards onto edge C. : Divide edge A by edge B (rounding down) to compute (N-1)/2. { Move the MP forwards onto edge A. ) Increment to restore value of N. ' Move the MP backwards onto edge B. * Multiply edges A and C to compute N*(N-1)/2. ) Increment to compute N*(N-1)/2 + 1. { Move the MP forwards onto edge C. & This actually a copy operation, but we use it to reset the edge to zero. 2 Set the edge to 2. ' Move the MP backwards onto edge A. : Divide edge B by edge C to compute (N*(N-1)/2 + 1)/2. ! Output the result as an integer. We're basically done now. : no-op (we already have this value) & Copy either B or C into A (doesn't matter). ? Read a zero (EOF) into A. ' Move the MP backwards onto an unused cell. : Divide some unused cell by A (which is zero), terminating with an error. ``` [Answer] # LabVIEW, ~~28~~ 20 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490) [![](https://i.stack.imgur.com/mKFmV.jpg)](https://i.stack.imgur.com/mKFmV.jpg) [![](https://i.stack.imgur.com/cf93o.jpg)](https://i.stack.imgur.com/cf93o.jpg) [Answer] ## CJam, 10 bytes ``` ri_(2/*)2/ ``` [Test it here.](http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%3B%0A%0AQi_(2%2F*)2%2F%0A%0A%5DoNo%7D%2F&input=3%0A4%0A5%0A6%0A8) ### Explanation ``` ri e# Read input and convert to integer N. _ e# Duplicate N. (2/ e# Decrement, integer divide by two, to determine the number of rows that can be used. * e# Multiply by the input to determine the number of cells that can be used. )2/ e# Increment, integer divide by two, which essentially ceil()s the result of the e# division. ``` [Answer] ## [Labyrinth](https://github.com/mbuettner/labyrinth), 11 bytes Woohoo, only one byte [behind CJam](https://codegolf.stackexchange.com/a/65444/8478). ``` ?:(#/*)_2/! ``` [Try it online.](http://labyrinth.tryitonline.net/#code=PzooIy8qKV8yLyE&input=OA) It's essentially the same thing: ``` ? reads an integer value. : duplicates the result. ( decrements it. # pushes the stack depth which happens to be 2. / is integer division. * is multiplication. ) increments the result. _ pushes a 0. 2 turns it into a 2. / is once again integer division. ! prints the result as an integer. ``` However, at this point the program doesn't terminate yet. Instead, the instruction pointer has hit a dead end and turns around. But now `/` tries to compute `0/0` which [terminates with an error](https://codegolf.meta.stackexchange.com/questions/4780/should-submissions-be-allowed-to-exit-with-an-error/4781#4781). [Answer] # [Par](http://ypnypn.github.io/Par), 8 bytes ``` ✶″½↓┐*½┐ ``` [One byte is used per character.](https://github.com/Ypnypn/Par/blob/gh-pages/README.md#the-encoding) ## Explanation ``` ## [implicit: read line] Example ✶ ## Convert to number 7 ″ ## Duplicate 7 7 ½ ## Divide by two 7 3.5 half the board ↓ ## Minus one 7 2.5 leave one row empty ┐ ## Ceiling 7 3 a whole number of rows * ## Multiply 21 total number of spaces ½ ## Divide by two 10.5 only the blue squares ┐ ## Ceiling 11 starts with blue, so round up ``` [Answer] ## [Seriously](https://github.com/Mego/Seriously), 8 bytes ``` ,;D½L*½K ``` Seriously has the handy `½` (float divide by 2), and `K` (ceiling), so we don't need to add one before division. Try it [here](http://seriouslylang.herokuapp.com/link/code=2c3b44ab4c2aab4b&input=8) with explanation. [Answer] # Python 2, 22 21 bytes ``` lambda n:~-n/2*n+1>>1 ``` I first separate in two cases, odd N and even N. With odd N we can fill (N - 1)/2 rows, containing on average N/2 pieces. Since the first row always has more pieces we should ceil this result. So when N is odd we have ceil((N-1)/2 \* N/2) pieces. With even N we can fill N/2 - 1, or floor((N - 1)/2) rows, each row containing N/2 pieces. We can combine these two expressions by ceil(floor((N-1)/2) \* N/2). Since ceil(x/2) = floor((x+1)/2) we can use flooring division: `((N - 1) // 2 * N + 1) // 2`. [Answer] # JavaScript, ~~37~~ 35 bytes ``` alert(((n=prompt()/2)-.5|0)*n+.5|0) ``` ## Explanation Uses a similar technique to the rest of the answers. This is the ungolfed algorithm: ``` var n = parseInt(prompt()); var result = Math.ceil(Math.floor((n - 1) / 2) * n / 2); alert(result); ``` [Answer] # dc, 12 ``` ?d1-2/*1+2/p ``` ### Test output: ``` $ for t in 3 4 5 6 8; do echo $t | dc -e?d1-2/*1+2/p; done 2 2 5 6 12 $ ``` [Answer] # Pyth, 9 bytes ``` /h*/tQ2Q2 ``` Same algorithm as my Python 2 answer. [Answer] # [Japt](https://github.com/ETHproductions/Japt), ~~16~~ 14 bytes ``` U-1>>1 *U+1>>1 ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=VS0xPj4xICpVKzE+PjE=&input=OA==) ### How it works Pretty simple: ``` // Implicit: U = input number U-1>>1 // Subtract 1 from U and integer divide by 2. *U+1>>1 // Multiply the result by U, add 1, and integer divide by 2. // Implicit: output last expression ``` I wish there were some way to take into account that the two halves of the code are so similar. Suggestions welcome! Old version (16 bytes): ``` U*½-½|0 *U*½+½|0 ``` [Answer] # Java, ~~230~~ ~~155~~ 52 Golfed: ``` int f(int s){return(int)Math.ceil(s*((s-1)/2)/2.0);} ``` Ungolfed: ``` public class NumberOfPiecesOnACheckersBoard { public static void main(String[] args) { // @formatter:off int[][] testData = new int[][] { {3, 2}, {4, 2}, {5, 5}, {6, 6}, {8, 12} }; // @formatter:on for (int[] data : testData) { System.out.println("Input: " + data[0]); System.out.println("Expected: " + data[1]); System.out.print("Actual: "); System.out.println(new NumberOfPiecesOnACheckersBoard().f(data[0])); System.out.println(); } } // Begin golf int f(int s) { return (int) Math.ceil(s * ((s - 1) / 2) / 2.0); } // End golf } ``` Program output: ``` Input: 3 Expected: 2 Actual: 2 Input: 4 Expected: 2 Actual: 2 Input: 5 Expected: 5 Actual: 5 Input: 6 Expected: 6 Actual: 6 Input: 8 Expected: 12 Actual: 12 ``` [Answer] ## Zilog ez80 machine code, 9 bytes In hex: ``` 6C 2D CB3D ED6C 2C CB3D ``` In assembly: ``` ld l,h dec l srl l mlt hl inc l srl l ``` Input is in register `h`, and output is in `l`. The Zilog ez80 is an 8-bit processor with an 8 bit accumulator and 24-bit registers. Unlike the z80, it has a `mlt` (8-bit multiply) instruction, which, in 16-bit mode, multiplies the high and low bytes of a register pair, here `hl`, and stores back in `hl`. This only works for values for which twice the result fits in 8 bits; that is, n≤23. [Answer] ## TI-BASIC, 13 bytes ``` ⁻int(⁻.5Ansint(Ans/2-.5 ``` TI-BASIC's implicit multiplication helps, but it doesn't have integer division. `⁻int(⁻X` is a shorter form of ceil(x). [Answer] # vba, 46 ``` Function f(x) f=(((x-1)\2)*x+1)\2 End Function ``` Call with ?f(x), or =f(A1) in a formula [Answer] ## Pyth, 17 14 13 bytes -3 bytes thanks to [Ypnypn](https://codegolf.stackexchange.com/users/16294/ypnypn)! Rearranged the numbers of the \* operator to save 1 byte. ``` /+*Q-/Q2-1%Q2 1 2 (original) /h*Q-/Q2!%Q2 2 /h*-/Q2!%Q2Q2 ``` Explanation: When n is even, we can occupy n/2-1 rows with n/2 pieces, making a total of n\*(n/2-1)/2 pieces. This expression is equivalent to (n\*(n/2-1)+1)/2 When n is odd, we can find how twice the number of pieces would look like, twice the number of pieces will span n-1 rows, and if I take away one piece, we can divide the n-1 rows into (n-1)/2 groups of 2 rows such that each group has n pieces, so the expression for this case is (n\*(n/2)+1)/2 Now that both expressions are quite similar, we can write the code. ``` /h*-/Q2!%Q2Q2 %Q2 Check if the number is odd ! Logical not to make 1 if even and 0 if odd /Q2 n/2 - n/2-1 if even, and n/2 if odd * Q n*(n/2-1) if even, n*(n/2) if odd h Add one / 2 Divide the result by two. ``` My first time using a golfing language. [Answer] ## Javascript, 33 bytes ``` a=prompt();alert(a*(a-1>>1)+1>>1) ``` If an ES6 function is allowed then 18 bytes: ``` a=>a*(a-1>>1)+1>>1 ``` [Answer] # MATLAB, ~~37~~ 25 bytes ``` @(a)ceil(fix(a/2-.5)*a/2) ``` I believe this should work, does for all test cases. It also works on **Octave**. You can try [online here](http://octave-online.net/?s=QHPazBNGkfyhbhbdFrYAnJeGZmDvKMKYapOgHyikJRbmUTQP). --- For the old code I added the program to that workspace in a file named `checkerboard.m`. You can run it by simply entering `checkerboard` at the prompt, then when it starts, enter the required size at the prompt. The result will be printed. For the new code, simply enter the code posted here into the prompt, then call the anonymous function as `ans(n)`. [Answer] ## [Retina](https://github.com/mbuettner/retina), 18 bytes ``` 11(..?$)? $_ 11? 1 ``` Input and output is [in unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary). [Try it online!](http://retina.tryitonline.net/#code=MTEoLi4_JCk_CiRfCjExPwox&input=MTExMTExMTE) The latest version of Retina (newer than this challenge) could handle decimal I/O for four additional bytes: ``` .+ $* 11(..?$)? $_ 11? ``` [Try it online!](http://retina.tryitonline.net/#code=LisKJCoKMTEoLi4_JCk_CiRfCjExPw&input=OA) With unary input and decimal output, we can do 16 bytes, but that seems like a bit of a stretch: ``` 11(..?$)? $_ 11? ``` ### Explanation Still the same approach as anyone elses, but using regex replacement on a unary representation of the number. ``` 11(..?$)? $_ ``` This computes `n*((n-1)/2)`. We do this by matching two characters at a time (division by two) and replacing them with the entire string (multiplication by `n`). The decrement of `n` is done by skipping the remainder of the string, if only one or two characters are left. ``` 11? 1 ``` This is integer division by 2, rounded up. We simply replace two characters with one (division by 2), but allow the last match to consist of only one character (rounding up). [Answer] # Python 3, 39 bytes This is a little bloated, but I'm not sure I could golf much further than this. [A link for testing.](http://ideone.com/belMUV) ``` n=int(input());print(((n-1)//2*n+1)//2) ``` [Answer] # Prolog, ~~39~~ 38 bytes **Code:** ``` p(N):-X is ((N-1)//2*N+1)//2,write(X). ``` **Explanation:** ``` Subtract 1 from input and integer divide by 2 to get number of rows available. Multiply that number by input to get number of squares available. Add one and integer divide by 2 to round up, since at at least half the rows will have a checker at the first square. Print. ``` **Example:** ``` p(8). 12 ``` Try it online [here](http://swish.swi-prolog.org/p/nWVeEUza.pl) **Edit:** Saved 1 byte by replacing ceil/2 with +1//2 [Answer] # Mumps, 17 bytes ``` R I W I-1\2*I+1\2 ``` Thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) for the simple algorithm explanation. This exploits Mumps' mathematics "deficiency" that operations are executed strictly left-to-right (not PEMDAS) so parenthesis are not required. :-) Output does look a tad odd, however, as Cache's Ensemble (the Mumps environment that I have access to) does not automatically output carriage returns even when pressed on input. If you want it prettier, add 4 characters for pre/post carriage returns: ``` R I W !,I-1\2*I+1\2,! ``` Thanks! [Answer] ## Bash, 32 bytes ``` read a;echo $((a*(a-1>>1)+1>>1)) ``` [Answer] ## Pyke, 8 bytes, noncompeting ``` Dt2f*h2f ``` dup,dec,half,mult,inc,half [Try it here!](http://pyke.catbus.co.uk/?code=Dt2f*h2f&input=8) [Answer] ## Batch, 30 bytes ``` @cmd/cset/a(%1*((%1-1)/2)+1)/2 ``` 38 bytes if input on stdin is required: ``` @set/pa= @cmd/cset/a(a*((a-1)/2)+1)/2 ``` ]
[Question] [ ## Introduction During work with [BMP (bitmap)](https://en.wikipedia.org/wiki/BMP_file_format) generator I face problem of converting number to little endian hex string. Here is function which I create in JavaScript - but wonder how small code can works similarly ``` let liEnd= num => num.toString(16).padStart(8,'0').match(/../g).reverse().join``; console.log(liEnd(304767)) // 304767 dec = 0x4a67f hex ``` ## Challenge Write function which will take 32bit unsigned integer number on input, and produce 8-digit hexadecimal string with little endian order. The example algorithm which do the job: * convert numb to hex string e.g: `304767 -> '4a67f'` * add padding zeros to get 8-char string: `'0004a67f'` * split string to four 2-char pieces: `'00','04','a6','7f'` * reverse order of pieces `'7f','a6','04','00'` * join pieces and return as result: `'7fa60400'` ## Example Input and Output Input number (or string with dec number) is on the left of `->`, output hex string is on the right ``` 2141586432 -> 0004a67f 304767 -> 7fa60400 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes ``` žJ+h¦2ôRJ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6D4v7YxDy4wObwny@v/f0MjYxNQMAA "05AB1E – Try It Online") -1 byte by inspiration of the Jelly answer. ``` žJ+ add 2^32 to input h convert to hex ¦ drop leading 1 2ô split in groups of 2 R reverse groups J and join them ``` [Answer] # [Python 3](https://docs.python.org/3/), 37 bytes ``` lambda n:n.to_bytes(4,"little").hex() ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKk@vJD8@qbIktVjDREcpJ7OkJCdVSVMvI7VCQ/N/QVFmXolGmoaRoYmhqYWZibGRpiYXTNDYwMTczFxT8z8A "Python 3 – Try It Online") **Arithmetic-based recursive solution (~~50~~ 49 bytes, works also for [Python 2](https://docs.python.org/2/))**: ``` f=lambda n,i=4:i*'1'and"%02x"%(n%256)+f(n>>8,i-1) ``` [Try it online!](https://tio.run/##NchLCoAgFADAfaeIQPSVQX7SCPQuRkhCvSJc1Olt1SznevN2oioluj0cyxpq5MnpObVU0IBrQwb5NIQhkaOBLjL0fuKpF1CuO2FmkUmhxTgZrSRA9acatDUWoHw "Python 3 – Try It Online") *-1 byte thanks to @JonathanAllan* [Answer] # [R](https://www.r-project.org/), ~~54~~ 53 bytes ``` format.hexmode(scan()%/%256^(0:3)%%256%*%256^(3:0),8) ``` [Try it online!](https://tio.run/##K/r/Py2/KDexRC8jtSI3PyVVozg5MU9DU1Vf1cjULE7DwMpYUxXEVNWCCBhbGWjqWGj@NzI0MTS1MDMxNvoPAA "R – Try It Online") Each group of 2 characters is actually the hex representation of a digit in base 256. `scan()%/%256^(0:3)%%256` converts to a base 256 number with 4 digits reversed, `...%*%256^(3:0)` joins them as a single integer, and `format.hexmode(...,8)` converts that number to its hex representation with 8 digits. [Answer] # JavaScript (ES7), ~~ 59 ~~ 57 bytes String manipulation. ``` n=>(n+2**32).toString(16).match(/\B../g).reverse().join`` ``` [Try it online!](https://tio.run/##VcwxEsIgEEDR3lOkhDgumwTBJhZewdYiDEIkExeHMLk@Yumv3/zF7GazKXzyieLTFT8WGq@Mjn3bDj2HHO85BZpZpzi8TbYvJh43ADFzSG53aXOMwxIDTVOxkba4OljjzDzrO9mdL0rWDW@EaBBRGqX94Z8NKLXSlfyqTHujUCKWLw "JavaScript (Node.js) – Try It Online") ### How? We first convert \$n + 2^{32}\$ to hexadecimal to make sure that all leading \$0\$'s are included: ``` (304767 + 2**32).toString(16) // --> '10004a67f' ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1ecn5Oql5OfrvFfw9jAxNzMXEFbwUhLy9hIU68kP7ikKDMvXcPQTPO/5n8A "JavaScript (Node.js) – Try It Online") We use the regular expression `/\B../g` to match all groups of 2 digits, ignoring the leading \$1\$ thanks to `\B` (non-*word boundary*). ``` '10004a67f'.match(/\B../g) // --> [ '00', '04', 'a6', '7f' ] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1ecn5Oql5OfrvFf3dDAwMAk0cw8TV0vN7EkOUNDP8ZJT08/XfO/5n8A "JavaScript (Node.js) – Try It Online") We `reverse()` and `join()` to get the final string. --- # JavaScript (ES6), 61 bytes Recursive function. ``` f=(n,k=4)=>k?[(x=n&255)>>4&&'']+x.toString(16)+f(n>>8,k-1):'' ``` [Try it online!](https://tio.run/##Vcq7DoMgFADQvV/hJBBfF72AaQL9iI5NB2LF@Ag0ahr/ntqxZz6T/ditW8f3Xvjw6mN0mvp81si0mW8Pemif1kIwYzBNCXlmR7mH@76OfqBcssxRb0ybzwVnV0JiF/wWlr5cwkAdrTly0UpsasaSqkoAAK1U7vLfGkAl1Vl@zqaclYAA8Qs "JavaScript (Node.js) – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 46 bytes ``` i=$1 repeat 4 printf %02x $[j=i%256,i=i/256,j] ``` [Try it online!](https://tio.run/##qyrO@J@moVn9P9NWxZCrKLUgNbFEwUShoCgzryRNQdXAqEJBJTrLNlPVyNRMJ9M2Ux9EZ8X@r@XiSssvUshTyMxTMDYwMTczVzAyNDE0tTAzMTayruZSUEhTUMkDUqnJGflctf8B "Zsh – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 54 bytes ``` x=>$"{(x=x>>16|x<<16)>>8&16711935|(x&16711935)<<8:x8}" ``` Saved 4 bytes thanks to @PeterCordes [Try it online!](https://tio.run/##Sy7WTS7O/O9WmpdsU5qZV6JTXFKUmZdul2b7v8LWTkWpWqPCtsLOztCspsLGxtBM087OQs3QzNzQ0NLYtEajAs7WtLGxsKqwqFX6b80VXpRZkuqTmZeqkaZhZGhiaGphZmJspKkJlQGKGhuYmJuZA0X@AwA "C# (Visual C# Interactive Compiler) – Try It Online") ### Explanation ``` x=> //Lambda taking in an uint (x=x>>16|x<<16) //Swap the first two and the last two bytes of the uint (0x7fa60400 -> 0x04007fa6) >>8&16711935|(x&16711935)<<8 //Swap each pair of bytes in every group of 2 bytes (0x04007fa6 -> 0x0004a67f) $"{ :x8}" //Format as hex string, padded with leading zeroes to length 8 ``` [Answer] # [Red](http://www.red-lang.org), 37 bytes ``` func[x][reverse/skip form to-hex x 2] ``` This breaks TIO because of the outdated compiler it uses. ## [Red](http://www.red-lang.org), 43 bytes ``` func[x][load next mold reverse to-binary x] ``` [Try it online!](https://tio.run/##FcxbDkAwEAXQrdwNSDxKxTL8Nv1Ap4mEjoySWn2xgHOEXB7JwVh45iH7KywmWbPx5BAoRey8OQjdJCchcjGvYZIHyeZD1hBhPoemVLrTf4G6UlXbd6qpbX4B "Red – Try It Online") [Answer] # x86 32-bit machine code, ~~24~~ 21 bytes changelog: -3 bytes: replace standard add/cmp/jbe/add with a DAS hack by @peter ferrie 64-bit: still 24 bytes. Long mode removed the DAS opcode. 16-bit mode: the default operand-size is 16-bit but the problem spec is inherently 32-bit. Including hard-coded 8 hex digits. --- **Byte-reverse with `bswap` then manual int->hex in standard order** (most-significant nibble first, writing hex digits to a char output buffer in ascending order.) This avoids needing to unroll the loop to switch order between nibbles within a byte vs. across bytes. Callable as `void lehex(char buf[8] /*edi*/, uint32_t x /*esi*/);` like x86-64 System V, except this doesn't work in 64-bit mode. (It needs the output pointer in EDI for `stosb`. The input number can be in any register other than ECX or EAX.) ``` 1 lehex: 2 00000000 0FCE bswap esi 3 00000002 6A08 push 8 ; 8 hex digits 4 00000004 59 pop ecx 5 .loop: ;do{ 6 00000005 C1C604 rol esi, 4 ; rotate high nibble to the bottom 7 8 00000008 89F0 mov eax, esi 9 0000000A 240F and al, 0x0f ; isolate low nibble 10 0000000C 3C0A cmp al, 10 ; set CF according to digit <= 9 11 0000000E 1C69 sbb al, 0x69 ; read CF, set CF and conditionally set AF 12 00000010 2F das ; magic, which happens to work 13 14 00000011 AA stosb ; *edi++ = al 15 00000012 E2F1 loop .loop ; }while(--ecx) 16 17 00000014 C3 ret ``` size = 0x15 = 21 bytes. [TIO FASM 32-bit x86 test case](https://tio.run/##bVRda9swFH33r7iPbeqExEnbuGaFsK1Q6Dro9lZKkO3rWNSWjCTXCWO/PbuSPcdJI2gVS/fznHPFtMYyLnbjjOlyv8@kKpmB708PgFtMasPiAmHuRfCw@vUDWFHIRkOtwUgo2TtdBeOYm4GxBing9@NPH2pRcLJ4JkfPKzDH7Z0HtGLdsAoANXefVa1z2pYwWBF9kj2kfMONbs1kZTdMtt6kkLK6g5MVpfKPs1SycJaa@7DoAyppmEHI@SYHwWPbFvVgcoRYGiNLz/mW8sP5sq3fF8hE6rbCh@l2mnXxuJaFDUiAdPGccVJWznI2HXaj0cDXB2BJIlXKxcamdr3dh85Lx3EX/yY8eClkKbn5vTsVkkiRcsOlICp27mJFBvamUYTq6smGvocwzF3glGn4BBQxt@GJD03OkxxyVlUoHKONVO8tDtpIHX/yG2HKr67gC9XqrCwPAJN262z@UtQCL8ZjYuqyDabQ7CMwqEknH6h2B2ohU7KEqc2d@cBFUtQOHuY6CoGk2DJUi5SpnYfCkPtaG6aM126tpg5CGgAfgcCm4AJ7E13HThmVD8v@sOWcWrOUVyT1o2OromC2mF0vbxbz4NTJ3pIoZsF8cX1z298mxA7BYzXv9YdR1J5T22zDuPDJwBjbLp1IAqZRnATF1CZx7dOPjwnAytLToRLQsTaKPibDsC6RhblWRGTDTQ4v3x5pZLhw8aXAccW0GROYYwoGMnO4kpdVASqEBgk/KuwTZJSgRU1Z1MIzakpIp7ZuISmm6uoDRYNmYBQjDcjIZcu4IgUo1HVhhuFbKOMdxaiMgldKdLV860YoOldQ66EsY2Tc35B@WiLh/KI5fOeVq0UWaR/4DOHz6eJ2QOcR2cuQxUmK2Vmyjz1cT69U0Nvxg2BLcVOX9qj9L@Y0p32IDo/Y@vll3aqknZxacG3S9TyY5KeOMTnOescsPb1P3AtXdfdxnX2aBzIIR0FnUKCguQ8HM2ph7Kr2wfCSXv4AYkxYrZ2cLCyYWm2bhidInt17q1mJNmGGajLgztB/QvcEJtftxcy3DlTP5VmAZkcA4ZYf9LWVqkOD/s5k2/8D "Assembly (fasm, x64, Linux) – Try It Online") with an asm caller that uses a `write` system call to write the output after calling it twice to append 2 strings into a buffer. Tests all hex digits 0..F, including 9 and A at the boundary between numeral vs. letter. **The [`DAS`](https://github.com/HJLebbink/asm-dude/wiki/DAS) hack** - x86 has a half-carry flag, for carry out of the low nibble. Useful for packed-BCD stuff like the DAS instruction, intended for use after subtracting two 2-digit BCD integers. With the low nibble of AL being outside the 0-9 range, we're definitely abusing it here. Notice the `if (old_AL > 99H) or (old_CF = 1)` THEN `AL ← AL − 60H;` part of the Operation section in the manual; sbb *always* sets CF here so that part always happens. That and the ASCII range for upper-case letters is what motivates the choice of `sbb al, 0x69` * `cmp 0xD, 0xA` doesn't set CF * sbb `0xD - 0x69` wraps to AL=`0xA4` as input to DAS. (And sets CF, clears AF) * no AL -= 6 in the first part of DAS (because 4 > 9 is false and AF=0) * AL -= 0x60 in the second part, leaving `0x44`, the ASCII code for `'D'` vs. a numeral: * `cmp 0x3, 0xA` sets CF * sbb `3 - 0x69 - 1` = AL = 0x99 and sets CF and AF * AL -= 6 in the first part of DAS (9 > 9 is false but AF is set), leaving 0x93 * AL -= 0x60 in the second part, leaving 0x33, the ASCII code for `'3'`. Subtracting `0x6a` in SBB will set AF for every digit <= 9 so all the numerals follow the same logic. And leave it cleared for every alphabetic hex digit. i.e. correctly exploiting the 9 / A split handling of DAS. --- [Normally](https://stackoverflow.com/questions/53823756/how-to-convert-a-number-to-hex) (for performance) you'd use a lookup table for a scalar loop, or possibly a branchless 2x `lea` and `cmp/cmov` conditional add. But 2-byte `al, imm8` instructions are a big win for code-size. --- **x86-64 version version**: just the part that's different, between `and al, 0xf` and `stosb`. ``` ;; x86-64 int -> hex in 8 bytes 10 0000000C 0430 add al, '0' 11 0000000E 3C39 cmp al, '9' 12 00000010 7602 jbe .digit 13 00000012 0427 add al, 'a'-10 - '0' ; al = al>9 ? al+'a'-10 : al+'0' 14 .digit: ``` Notice that the `add al, '0'` *always* runs, and the conditional add only adds the difference between `'a'-10` and `'0'`, to make it just an `if` instead of `if`/`else`. Tested and works, using the same `main` caller as [my C answer](https://codegolf.stackexchange.com/questions/193793/little-endian-num-2-string-conversion/193831#193831), which uses `char buf[8]` and `printf("%.8s\n", buf)`. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` sG ùT8 ò w ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=c0cg%2bVQ4IPIgdw&input=MzA0NzY3) ``` sG ùT8 ò w :Implicit input of integer s :Convert to string G : In base-16 ù :Left pad T : With 0 8 : To length 8 ò :Split into 2s w :Reverse :Implicitly join and output ``` [Answer] # x86 SIMD machine code (AVX512-VBMI), 36 bytes (16 bytes of which are a hex lookup table) This is a function that takes an integer in `xmm0` and returns 8 bytes of ASCII char data in `xmm0`, for the caller to store wherever it wants. (e.g. to video memory after interleaving with attribute bytes, or into a string under construction, or whatever) From C, call it as `__m128i retval = lehex(_mm_cvtsi32_si128(x))` with the x86-64 System V calling convention, or MS Windows `vectorcall`. ``` # disassembly with machine-code bytes (the answer) and NASM source code. 0000000000401000 <lehex>: 401000: c5 f1 72 d0 04 vpsrld xmm1, xmm0, 4 ; AVX1 401005: c5 f1 60 c8 vpunpcklbw xmm1, xmm1, xmm0 ; AVX1 401009: 62 f2 75 08 8d 05 01 00 00 00 vpermb xmm0, xmm1, [rel .hex_lut] 401013: c3 ret 0000000000401014 <lehex.hex_lut>: 401014: 30 31 ... 61 62 ... .hex_lut: db "0123456789abcdef" ``` Total = 0x24 = 36 bytes. **See [How to convert a number to hex?](https://stackoverflow.com/questions/53823756/how-to-convert-a-number-to-hex) on SO for how this works.** (SSE2 for the shift / punpck, then `vpermb` saves work that we'd need for `pshufb`. AVX1 instead of SSE2/SSSE3 also avoids a `movaps` register copy.) Notice that `punpcklbw` with the source operands in that order will give us the most-significant nibble of the low input byte in the lowest byte element, then the least-significant nibble of the lowest source byte. (In that SO answer, a `bswap` is used on the input to get a result in standard printing order with only SSE2. But here we *want* that order: high nibble in lower element within each byte, but still little-endian byte order). If we had more data constants, we could save addressing-mode space by doing one `mov edx, imm32` then using `[rdx+16]` or whatever addressing modes. Or `vpbroadcastb xmm0, [rdx+1]`. But I think a 16-byte hex LUT + `vpermb` is still better than implementing the `n>9 : n+'a'-10 : n+'0'` condition: that requires 3 constants and at least 3 instructions with AVX512BW byte-masking (compare into mask, `vpaddb`, merge-masked `vpaddb`), or more with AVX1 or SSE2. (See [How to convert a number to hex?](https://stackoverflow.com/questions/53823756/how-to-convert-a-number-to-hex) on SO for an SSE2 version of that). And each AVX512BW instruction is at least 6 bytes long (4-byte EVEX + opcode + modrm), longer with a displacement in the addressing mode. Actually it would take at least *4* instructions because we need to clear high garbage with `andps`, (or EVEX `vpandd` with a 4-byte broadcast memory operand) before the compare. And each of those needs a different vector constant. AVX512 has broadcast memory operands, but only for elements of 32-bit and wider. e.g. [EVEX `vpaddb`](https://www.felixcloutier.com/x86/paddb:paddw:paddd:paddq)'s last operand is only `xmm3/m128`, not `xmm3/m128/m8bcst`. (Intel's load ports can only do 32 and 64-bit broadcasts for free as part of a load uop so Intel designed AVX512BW to reflect that and not be able to encode byte or word broadcast memory operands at all, instead of giving them the option to do dword broadcasts so you can still compress your constants to 4 bytes :/.) **The reason I used [AVX512VBMI `vpermb`](https://www.felixcloutier.com/x86/vpermb) instead of SSSE3 / AVX1 `pshufb` is twofold:** * `vpermb` ignores high bits of the selectors. `(v)pshufb` zeros bytes according to the high bit of the control vector and would have needed an extra `pand` or `andps` to actually isolate nibbles. With XMM / 16-byte size, `vpermb` only looks at the low 4 bits of the shuffle-control elements, i.e. bits `[3:0]` in Intel's notation in the [Operation section](https://www.felixcloutier.com/x86/vpermb). * `vpermb` can take the data to be shuffled (the lookup table) as a memory operand. `(v)pshufb`'s xmm/mem operand is the shuffle-control vector. Note that AVX512VBMI is only available on CannonLake / Ice Lake so you probably need a simulator to test this, like Intel's SDE. [Answer] # [C (gcc)](https://gcc.gnu.org/), 30 bytes ``` f(x){printf("%.8x",htonl(x));} ``` [Try it online!](https://tio.run/##dcrdCsIgGIDhc69CFrFPqLEf2wZGV9LJ0NmE9TlMYzB27SbRae/hwyvPDylj1LCybXEGvYbsWPRrdpq8xTkxE3s8GJRzUCO9vrwytphuhKSXPgeD8LZGMbIRmtJQV7y69C1vaia@tAQvp8FBfsf8Rxqakndt9/9wow8OaSnIHj8 "C (gcc) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 43 bytes ``` lambda n:[("%08x"%n)[i^6]for i in range(8)] ``` [Try it online!](https://tio.run/##FcjRCsIgFAbge5/iIAwURmzOnAx6EjMwyjpRv0N2UU9v7Lv81t/2LDAtn87tnT7XWyIsQclu8F/ZQQe@uJhLJSYG1YTHXXkd217YKwgyox2P3tnJ9IKmwc5u7kVcBK2VsZGUh1dhqKygdfsD "Python 2 – Try It Online") *-4 bytes thanks to [benrg](https://codegolf.stackexchange.com/users/89587/benrg)* Outputs a list of characters. Computed by retrieving, in order, the hex digits of the input at indices `6, 7, 4, 5, 2, 3, 0, 1`. [Answer] # [C (gcc)](https://gcc.gnu.org/) endian agnostic, no standard libs, ~~92~~ 91 bytes `h(n)` is a single-digit integer->hex helper function. `f(x,p)` takes an integer and a `char[8]` pointer. The result is 8 bytes of `char` data. (*Not* 0-terminated unless the caller does that.) Assumptions: ASCII character set. 2's complement `int` so right shift eventually brings down the sign bit, and converting a `uint32_t` to `int` doesn't munge the bit-pattern if the high bit is set. `int` is at least 32-bit. (Wider might let it work on 1's complement or sign-magnitude C implementations). Non-assumptions: anything about implementation byte-order or signedness of `char`. ``` i;h(n){n&=15;return n>9?n+87:n+48;}f(x,p)char*p;{for(i=5;--i;x>>=8)*p++=h(x>>4),*p++=h(x);} ``` [Try it online!](https://tio.run/##hZHdcpswEIXv9RQ7ybRAMP6JcUyi4rxAO73IRS7STEcGCdTShZGE48TDq5dIYGcm03aqK1bLnj3fURYVWdafS8yqNufwSZtc1tNy00ta@hgc8GO6WFHFTasQcHN9i2GyvsEwTmgn/P2kCbKSqYuGHkStfJmuaBRJut9s0iS4aMIwLX1bxMHkVAS06yUakJTMZuc5FxI5uFWAdcMngJznGvjeKAYNUxw1abGoK8Hz7391BLeAoce8aDGHG/c592gHw5nNQEssKg65LKTdiYYXXEG0gZLvCdnVMoc39fc4xAmcmMBBwUg16n6@g@2z4SCk0gZYpmqthxtN4Hje4b8Z@nIHKLfb6jT6JE0p8R@jASUdIX@@DnEJ/mISfYcQkNGtsw7bVjxcP6aHh@Qx9V68jo5r3RpgYFOVlY0EMoZMPY8MprajPPvpcN28sBHVO65EVT/ZutDTMQz/chEvVslVvLycuP@sO3ffKOtG@Gcfpon@hmfH1rh26MGP1oKakkMCO1bZzAfak@pyHq@v1v9XHFrHd5@7YPrfmahYofvo67KP7llVvQI "C (gcc) – Try It Online") including test caller using `printf("%.8s\n", buf)` to print output buffer without 0-terminating it. **Ungolfed:** ``` int h(n){n&=15;return n>9 ? n+'a'-10 : n+'0';} // single digit integer -> hex int i; void ungolfed_f(x,p)char*p;{ for(i=5; --i; x>>=8) // LS byte first across bytes *p++=h(x>>4), // MS nibble first within bytes *p++=h(x); } ``` Doing `n&=15;` inside `h(x)` is break-even; 6 bytes there vs. 3 each for `&15` to isolate the low nibble at both call sites. `,` is a sequence point (or equivalent in modern terminology) so it's safe to do `*p++= stuff` twice in one statement when separated by the `,` operator. `>>` on signed integer is implementation-defined as either arithmetic or logical. GNU C defines it as arithmetic 2's complement. But on any 2's complement machine it doesn't really matter because we never look at the shifted-in 0s or copies of the sign bit. The original MSB will eventually get down into the low byte unchanged. This is not the case on sign/magnitude, and I'm not sure about 1's complement. So this may only be portable to 2's complement C implementations. (Or where `int` is *wider* than 32 bits so bit 31 is just part of the magnitude.) unsigned -> signed conversion also munges the bit-pattern for negative integers, so `&15` on an `int` would only extract nibbles of the original unsigned value on 2's complement. Again, unless `int` was *wider* than 32-bit so all inputs are non-negative. The golfed version has UB from falling off the end of a non-void function. Not to return a value, just to avoid declaring it `void` instead of default `int`. Modern compilers will break this with optimization enabled. --- Motivation: I was considering an x86 or ARM Thumb asm answer, thought it might be fun to do it manually in C, maybe for compiler-generated asm as a starting point. See <https://stackoverflow.com/questions/53823756/how-to-convert-a-number-to-hex> for speed-efficient x86 asm, including an AVX512VBMI version that's only 2 instructions (but needs control vectors for vpmultishiftqb and vpshufb so wouldn't be great for golf). Normally it takes extra work for SIMD to byte-reverse into printing order on little-endian x86 so this byte-reversed hex output is actually easier than normal. --- **Other ideas** I considered taking the integer by reference and looping over its bytes with `char*`, on a little-endian C implementation (like x86 or ARM). But I don't think that would have saved much. Using `sprintf` to do 1 byte at a time, 64 bytes after golfing: ``` int i; void f(x,p)char*p;{ for(i=4;sprintf(p,"%.2x",x&255),--i;x>>=8) p+=2; } ``` But if we're using printf-like functions we might as well byte-swap and do a `%x` printf of the whole thing like [@JL2210's answer](https://codegolf.stackexchange.com/questions/193793/little-endian-num-2-string-conversion/193801#193801). [Answer] # [Scala](http://www.scala-lang.org/), ~~58~~ ~~40~~ 36 bytes ``` "%08X"format Integer.reverseBytes(_) ``` [Try it online!](https://tio.run/##XcpBC4IwGIDhu7/iQwq2S0xdToQFdevQKYIgIr5sE0NnbEMQ8bfboFu3F97HVdji0j/fqvJwwsbAFL2Uhi4kQVu7EvbW4ng7e9uY@k5LuJjGgwxuwBZ0SY7GU7n7fbnEa1ZcY93bDj2EpWplN1YNyjp1GL1y5EGX6BOwbw1x8WrSJE14si1ynqV0BimBMcYxFzqmfzBjXOTih4TGnHHGAormefkC "Scala – Try It Online") Still uses the builtin to reverse the bytes of an `Int`, but uses `format` to format the `Int` as a Hex. No need to call `toHexString`. Removed the parens on `format`. This now means that the argument can be taken implicitly using `_`. [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 52 51 40 bytes ``` : f hex 0 4. do <# # # 0. #> type loop ; ``` [Try it online!](https://tio.run/##FYvBCoMwFMDufkXQs6XVTmWK/zJsOwdKH8XB9vVVySGXJMR0rPU73Mr5SWD1PzRW4SJTxY1WVDPHXzxbjMJ4hYL7CkajEqqEeqa8bueXz/7aWBJj0RhrHkNn2wakaLXtux7JJw "Forth (gforth) – Try It Online") ### Code explanation ``` : f \ start a new word definition hex \ set the current base to base 16 0 \ convert the input number to a double-cell integer 4. do \ start a counted loop from 0 to 3 <# # # \ start a formatted numeric string and move last 2 digits to format area 0. \ move remaining digits down the stack #> \ delete top two stack value and convert format area to string type \ output string loop \ end loop ; \ end word definition ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` +Ø%b⁴Ḋs2Ṛ‘ịØh ``` [Try it online!](https://tio.run/##ASkA1v9qZWxsef//K8OYJWLigbThuIpzMuG5muKAmOG7i8OYaP///zMwNDc2Nw "Jelly – Try It Online") A full program that takes an integer as its argument and prints a string. [Answer] # APL+WIN, ~~36~~ 34 bytes 2 bytes saved by converting to index zero Prompts for integer: ``` '0123456789abcdef'[,⊖4 2⍴(8⍴16)⊤⎕] ``` [Try it online! Courtesy Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tv7qBoZGxiamZuYVlYlJySmqaerTOo65pJgpGj3q3aFgACUMzzUddS4DaYv8DdfxP4zI2MDE3M@dK4zIyNDE0tTAzMTYCAA "APL (Dyalog Classic) – Try It Online") [Answer] # Excel, 91 bytes ``` =RIGHT(DEC2HEX(A1,8),2)&MID(DEC2HEX(A1,8),5,2)&MID(DEC2HEX(A1,8),3,2)&LEFT(DEC2HEX(A1,8),2) ``` [Answer] # [K4](https://kx.com/download/), ~~12~~ 11 bytes **Solution:** ``` ,/$|4_0x0\: ``` **Examples:** ``` q)k),/$|4_0x0\:304767 "7fa60400" q)0W "0004a67f" ``` **Explanation:** Pretty much exactly what the question asks: ``` ,/$|4_0x0\: / the solution 0x0\: / split to bytes 4_ / drop first 4 bytes | / reverse $ / convert to string ,/ / flatten ``` **Notes:** * **-1 byte** as K4 numbers are longs (64bit) by default, so dropping 4 bytes (32bits) [Answer] # [PHP](https://php.net/), 31 bytes ``` <?=unpack(H8,pack(V,$argn))[1]; ``` [Try it online!](https://tio.run/##K8go@P/fxt62NK8gMTlbw8NCB0yH6agkFqXnaWpGG8Za/09NzshXUIrJU7L@b2RoYmhqYWZibMRlbGBibmb@L7@gJDM/r/i/rhsA "PHP – Try It Online") Taking advantage of PHP's [pack](https://www.php.net/manual/en/function.pack.php) and [unpack](https://www.php.net/manual/en/function.unpack.php), I pack the unsigned input with "32 bit little endian byte order" format (`V`) into a binary string and then unpack it with "hex string, high nibble first" format (`H`) and print the result. This seems to be one of the rare cases where PHP's built-ins are actually shorter than implementing a simple algorithm! [Answer] # [J](http://jsoftware.com/), 10 bytes ``` 8{._1{3!:3 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Lar14g2rjRWtjP9rcnGlJmfkK6QpGBuYmJuZw3hGhiaGphZmJsZG/wE "J – Try It Online") ## how `3!:3` is a J "foreign conjunction" for hex representation, documented [here](https://www.jsoftware.com/help/dictionary/dx003.htm). That is, it's a builtin for converting to hex. However, it's output it not quite what we want. Eg, running: ``` 3!:3 (304767) ``` produces: ``` e300000000000000 0400000000000000 0100000000000000 0000000000000000 7fa6040000000000 ``` The meaning of the other lines is explained on the doc page I linked to above. In any case, it's clear we want the first 8 chars of the last line. `_1{` get the last line. `8{.` gets the first 8 characters of it. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes ``` ⪫⮌⪪﹪%08xN²ω ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMrPzNPIyi1LLWoOFUjuCAns0TDNz@lNCdfQ0nVwKJCSUfBM6@gtMSvNDcptUhDU1NHwQhElGtqWv//b2xgYm5m/l@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input as a number ﹪%08x Format using literal string ⪪ ² Split into pairs of characters ⮌ Reverse ⪫ ω Join Implicitly print ``` 19 bytes without resorting to Python formatting: ``` ⪫…⮌⪪⍘⁺X²¦³⁶N¹⁶¦²¦⁴ω ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMrPzNPw7kyOSfVOSO/QCMotSy1qDhVI7ggJ7NEwymxODW4BKguXSMgp7RYIyC/PLVIw0hHwdhMU0fBM6@gtMSvNDcJKKYJ5BuCBI1ALBMgLtfUtP7/39jAxNzM/L9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input as a number ⁺ Plus ² Literal 2 X To power ³⁶ Literal 36 ⍘ Convert to base ¹⁶ Literal 16 ⪪ ² Split into pairs of digits ⮌ Reverse the list … ⁴ Take the first 4 pairs ⪫ ω Join together Implicitly print ``` [Answer] # [Perl 5](https://www.perl.org/) (-p), 22 bytes ``` $_=unpack H8,pack V,$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3rY0ryAxOVvBw0IHTIfpqMT//29kaGJoamFmYmzEZWxgYm5m/i@/oCQzP6/4v25BDgA "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~31~~ 27 bytes Ended up being a port of [Night2's PHP answer](https://codegolf.stackexchange.com/a/193910/52194) because Ruby has the same pack/unpack functionality. ``` ->*i{i.pack(?V).unpack'H8'} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf104rszpTryAxOVvDPkxTrzQPxFT3sFCv/V@ekZmTqpCeWlLMpVBQWlKskBatEq9Xkh@fGcuVmpfy38jQxNDUwszE2IjL2MDE3MwcAA "Ruby – Try It Online") My original 31-byte answer that didn't take advantage of the H8 unpack mode because I didn't know about it: ``` ->*i{'%02x'*4%i.pack(?V).bytes} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf104rs1pd1cCoQl3LRDVTryAxOVvDPkxTL6myJLW49n95RmZOqkJ6akkxl0JBaUmxQlq0SrxeSX58ZixXal7KfyNDE0NTCzMTYyMuYwMTczNzAA "Ruby – Try It Online") [Answer] ## Windows Batch, 90 bytes ``` @for /l %%x in (24,-8,0)do @set/aa=%1^>^>%%x^&255&cmd/cexit !a!&<nul set/p=!=exitcode:~-2! ``` Run the command-line with /v to enable the delayed expansion. [Answer] # [Rust](https://www.rust-lang.org/), 34 bytes ``` |n|print!("{:08x}",n.swap_bytes()) ``` [Try it online!](https://tio.run/##KyotLvmflqeQm5iZp6FZzaWgkJNaopBmlZanUWpspKlgq/C/Jq@moCgzr0RRQ6naysCiolZJJ0@vuDyxID6psiS1WENT8781V5qGsYGJuZm5JlftfwA "Rust – Try It Online") Rust has built-in hex formatting, but it displays in big-endian format, so I reversed the byte order first. Capitalize the `x` if you want uppercase hex digits instead of lowercase ones. [Answer] # [Python 3.11+](https://www.python.org), 34 bytes ``` lambda n:n.to_bytes(4)[::-1].hex() ``` This is a version of [Joel's Python 3](https://codegolf.stackexchange.com/a/193802/70305) solution that works only on Python 3.11 and higher. Pre-3.11, the `byteorder` argument to `int.to_bytes`/`int.from_bytes` was mandatory; in 3.11 it is now defaulted to `'big'`, so, golf-wise, you can omit it, let `to_bytes` produce the big-endian version, then reverse it with a slice, saving three characters. (Side-note: The Attempt This Online link actually cheats and just uses Joel's solution when the Python version is below 3.11; ATO is still on 3.10.6 so it can't run this code as of April, 2023) [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwRKuNNuYpaUlaboWN5VyEnOTUhIV8qzy9Ery45MqS1KLNUw0o62sdA1j9TJSKzQ0oSqrMnML8otKFIori7ky00CUXllqUXFmfl58Zl5avoKNgoaxjqGhphWXAhCk2WI1WEc9J7OkJCdVXRNiNldBUWZeiUaahpGhiaGphZmJsZEmQtDYwMTczFwT6oIFCyA0AA) ]
[Question] [ Given an input string containing only alphanumeric ASCII characters and starting with a letter, swap each letter run with the digit run which follows. A *run* is a sequence of consecutive letters or digits. Note that in the case where the input string ends with a run of letters, this run is left untouched. **Walk-through example** For instance, given the input string `uV5Pt3I0`: 1. Separate runs of letters and runs of digits: `uV 5 Pt 3 I 0` 2. Identify pairs of runs: `(uV 5) (Pt 3) (I 0)` 3. Swap pairs of runs: `(5 uV) (3 Pt) (0 I)` 4. Concatenate: `5uV3Pt0I` **Examples** ``` uV5Pt3I0 -> 5uV3Pt0I J0i0m8 -> 0J0i8m abc256 -> 256abc Hennebont56Fr -> 56HennebontFr Em5sA55Ve777Rien -> 5Em55sA777VeRien nOoP -> nOoP ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins. Explanations are encouraged. [Answer] # [Retina](https://github.com/m-ender/retina), 15 bytes ``` (\D+)(\d+) $2$1 ``` This replaces the regex `(\D+)(\d+)` with `$2$1`. Let's break that down if you don't know what that means. The `\D` means 'match anything that isn't a number'. `\d` means 'match everything that is a number'. The `+` sign means 'match this at least once but try to match it as many times as possible'. The brackets define a group. The first group is `(\D+)` and the second is `(\d+)` In the second line we say that we want to put whatever was matched by the second group, followed by whatever was matched by the first group. This effectively swaps the letter and digit runs. [Try it online!](https://tio.run/##K0otycxL/P9fI8ZFW1MjJkVbk0vFSMXw///EpGRDI@OU1DQTUzMA "Retina – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ~ṠŒg⁸ṁṭ2/ ``` [Try it online!](https://tio.run/##AV8AoP9qZWxsef//fuG5oMWSZ@KBuOG5geG5rTIv/@G7tMOH4oKsWf//dVY1UHQzSTAKSjBpMG04CmFiYzI1NgpIZW5uZWJvbnQ1NkZyCkVtNXNBNTVWZTc3N1JpZW4Kbk9vUA "Jelly – Try It Online") ### How it works ``` ~ṠŒg⁸ṁṭ2/ Main link. Argument: s (string) ~ Apply bitwise NOT. Bitwise operators attempt to cast to int, so if c is a digit, this yields ~int(c), a negative number. If c cannot be cast to int, ~ will yield 0. Ṡ Take the sign. We've now mapped digits to -1, non-digits to 0. Œg Group consecutive equal elements. ⁸ṁ Mold s as the result, grouping run of digits and runs of non-digits. 2/ Reduce all pairs of runs by... ṭ tack, appending the first run of the pair to the second run. ``` [Answer] ## [Haskell](https://www.haskell.org/), ~~58~~ 56 bytes *Thanks to @Laikoni for shaving off 2 bytes* ``` f""="" f s|(a,(b,y))<-span(<':')<$>span(>'9')s=b++a++f y ``` [Try it online!](https://tio.run/##bc5BC4IwFMDxc36KxyPQsQIpphUqdCiqS9HB@1aTpJzR7CD03RclpcV2G7/3396J67O8XIzJEGNEJwP98PjAE4OakGior1x5kTtzSdRP3pfEnbpEx4JSTmkGtSl4riCGYwnXW64q6APeU7arxmsfPmeYAAKlkLWGzlfbcOPnfjFpoRs2Zs24OIxYYM8aQ6fXmV9JpaQoVcWC5e1v/sesvy0KpueMpTIMw30uVbf@N@sDalvuAOzrvgyNeQI "Haskell – Try It Online") Ungolfed: ``` f "" = "" f string | (letters, afterLetters) <- span (> '9') string , (numbers, afterNumbers) <- span (< ':') afterLetters = numbers ++ letters ++ f afterNumbers ``` [Answer] # JavaScript (ES6), 34 bytes ``` s=>s.replace(/(\D+)(\d+)/g,"$2$1") ``` --- ## Try it ``` o.innerText=(f= s=>s.replace(/(\D+)(\d+)/g,"$2$1") )(i.value="uV5Pt3I0");oninput=_=>o.innerText=f(i.value) ``` ``` <input id=i><pre id=o> ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 15 bytes ``` ss_Mc:z"(\d+)"3 2 ``` **Explanation** ``` :z"(\d+)"3 # Split the input z onto matches of numbers (\d+) c 2 # Split the resulting list in pieces of length 2 _M # Reverse each pair ss # Concatenate ``` [Test suite](http://pyth.herokuapp.com/?code=ss_Mc%3Az%22%28%5Cd%2B%29%223+2&test_suite=1&test_suite_input=uV5Pt3I0%0AJ0i0m8%0Aabc256%0AHennebont56Fr%0AEm5sA55Ve777Rien%0AnOoP&debug=0). [Answer] # [Python 2](https://docs.python.org/2/), 49 bytes Every non-regex solution I tried was longer. :P ``` lambda s:re.sub('(\D+)(\d+)',r'\2\1',s) import re ``` [Try it online!](https://tio.run/##TckxDsIgFADQvadg@5A2pmJojYmDiRp1sXHoxFJaGknk0wAdPD1uhvW95RvfDnmajzJ9BqumgYSD15uwKgpUnktG5VQyqDxILrdQBVYYuzgfiddp8QYjmSmsveji7l4DK/72qE1t97kMauSiyeWmEbVyGEVz9XlcrAgnIXrdtu3LaMwPn64Dln4 "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) (v2.0a0), 16 bytes ``` q/(\d+/ ò mw c q ``` [Test it online!](http://ethproductions.github.io/japt/?v=2.0a0&code=cS8oXGQrLyDyIG13IGMgcQ==&input=InVWNVB0M0kwIg==) Note: this is an unstable alpha, so if this link breaks, you can use a slightly longer version in v1.4.4: [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=cSQvKFxkKykvJCDyIG13IGMgcQ==&input=InVWNVB0M0kwIg==) ### Explanation ``` q/(\d+/ ò mw c q : Implicit input "uV5Pt3I0" q : Split input on /(\d+/ : runs of digits, keeping each run. (This compiles to the regex /(\d+)/g) : This gives ["uV","5","Pt","3","I","0",""] ò : Take every pair of items. [["uV","5"],["Pt","3"],["I","0"],[""]] m : Map each pair by w : reversing. [["5","uV"],["3","Pt"],["0","I"],[""]] c : Flatten into one array. ["5","uV","3","Pt","0","I",""] q : Join into a single string. "5uV3Pt0I" : Implicit: output result of last expression ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~32~~ ~~30~~ 28 bytes ``` q{i_64>X\:X^{])[}&c}/]]2/Wf% ``` CJam has no regex and no "split into digits and letters" or whatnot, so this was kind of painful. [Try it online!](https://tio.run/##S85KzP3/v7A6M97MxC4ixioirjpWM7pWLblWPzbWSD88TfX/f9dc02JHU9OwVHNz86DM1DwA "CJam – Try It Online") ### Explanation ``` q e# Read the input. { e# Do the following for every char c: i e# Get c's codepoint. 64> e# Check if it's greater than 64 (i.e. if it's a letter), pushing 1 or 0. X e# Push X (variable predefined to 1). \:X e# Store whether c was a letter or digit into X. ^{ e# If (old X) XOR (new X) is 1: ] e# Close the current array. ) e# Pull out its last character. [ e# Open a new array. }& e# (end if) c e# Turn the codepoint back into a character. This also shoves it into the new array, e# in case one was opened. }/ e# (end for) ] e# Close the final array, since it hasn't been closed yet. ] e# Wrap the whole stack into an array. 2/ e# Split elements into groups of 2. Wf% e# Reverse each group. e# Implicitly flatten and print. ``` [Answer] # [Gema](http://gema.sourceforge.net/new/index.shtml), 11 characters ``` <L><D>=$2$1 ``` Sample run: ``` bash-4.4$ gema '<L><D>=$2$1' <<< 'Em5sA55Ve777Rien' 5Em55sA777VeRien ``` [Answer] # Java 8, 38 bytes ``` s->s.replaceAll("(\\D+)(\\d+)","$2$1") ``` Not much to explain. Uses the same method as [*@Okx*'s Retina answer](https://codegolf.stackexchange.com/a/129844/52210), which can't be any shorter in Java. [Try it here.](https://tio.run/##hY5RS8MwEMff9ymOsIeEuVInWYWhMFBRwTkU9uJ8SNMomemlNNeBSD97jZpXKdwdd5ff//I/qKOa@8bgofoYtFMhwIOy@DUBsEimfVPawOZnBHim1uI7aJ6aIFZx38eMEUiR1bABhAsYwvwyZK1pXJSvneOM7/dXMxFrNRPshE0X01MmhtWftulKF7XpxNHbCupoIv3z8gpKJAefgUyd@Y6yJj6RQ46Z5qzbyS2d3eVM/Fr6H7zPbV6fj2Kq1Au5HMVuDaIpPZJc3rSj9HUtw1rKnSmK4skaHBXgo98mqJ/0wzc) [Answer] # Sed, 29 bytes ``` s/([^0-9]+)([0-9]+)/\2\1/g ``` Run with -r. Uses capture groups and replaces them in the opposite order. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` e€ØDŒg⁸ṁs2Ṛ€ ``` [Try it online!](https://tio.run/##y0rNyan8/z/1UdOawzNcjk5Kf9S44@HOxmKjhztnAcX@///vmmta7GhqGpZqbm4elJmaBwA "Jelly – Try It Online") Explanation: ``` e€ØDŒg⁸ṁs2Ṛ€ Accepts a string e€ØD Check if each char is in ['0'..'9'] Œg Split runs of 0s and 1s (respectively letter and digit runs) ⁸ṁ Replace with input, keeping the split s2 Get pairs of runs, last left alone if letter run Ṛ€ Swap each pair ``` [Answer] # PHP, no regex, 73 bytes ``` for(;a&$c=$argn[$i++];$p=$c)$c<A?print$c:$s=($p<A?!print$s:$s).$c;echo$s; ``` Run as pipe with `-nR` or [test it online](http://sandbox.onlinephpfunctions.com/code/6ee06a58206b0ba87cc23be45620b5d8e636a4cc). **breakdown** ``` for(;a&$c=$argn[$i++]; # loop through input $p=$c) # 2. remember character $c<A # 1. if digit ?print$c # then print it :$s=($p<A # else if previous character was digit ?!print$s # then print and reset string :$s # else do nothing ).$c; # append current character to string echo$s; # print remaining string ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~18~~ 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` r"(%D+)"pv ÏiZ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciIoJUQrKSJwdiDPaVo&input=InVWNVB0M0kwIg) ``` r"(%D+)"pv ÏiZ :Implicit input of string r :Replace "(%D+)" :Literal string p :Append v : Lowercase resulting in the Regex /(\D+)(\d+)/g Ï :Pass each match through a function i : To the first matched group prepend Z : The second matched group ``` [Answer] # [PHP](https://php.net/), 45 bytes ``` <?=preg_replace("#(\D+)(\d+)#","$2$1",$argn); ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6vkmmta7GhqGpZqbm4elJmap2TNZW8HVGJbUJSaHl@UWpCTmJyqoaSsEeOirakRk6Ktqayko6RipGKopAM2QtP6/38A "PHP – Try It Online") [Answer] # C#, 71 bytes ``` s=>System.Text.RegularExpressions.Regex.Replace(s,@"(\D+)(\d+)","$2$1") ``` Just a shame regular expressions are so long in C#. [Try it online!](https://tio.run/##fc5RS8MwEAfw5@ZThLCHhNVSJ1mFuaHohoqyUmW@7CVLbyPQJqOXSkX22Wu3vezFvtzB/353nMar0lnX1mjsjn78oIdyQoguFCJNyS8J0CtvNP12JqfvylguSNDFwaK2@g591e2F9NxndEunLU5n5zvRJzQ@ymBXF6qaN/sKEI2zeIyg6eq@UBo4hveMr5@Ggq/zoWAhG4wG10y03RtB8Nh5V0D0VRkPb8YC33JWr2Tqb15iJsTkP/Mam7i87RNqo0dy3CeewVrYOOvleFH1wXkp8UHKFSRJkhmwfdYuXXqaX4AMVH6aH9cO5ND@AQ "C# (Mono) – Try It Online") Full/Formatted version: ``` using System; class P { static void Main() { Func<string, string> f = s => System.Text.RegularExpressions.Regex.Replace(s, @"(\D+)(\d+)", "$2$1"); Console.WriteLine(f("uV5Pt3I0")); Console.WriteLine(f("J0i0m8")); Console.WriteLine(f("abc256")); Console.WriteLine(f("Hennebont56Fr")); Console.WriteLine(f("Em5sA55Ve777Rien")); Console.WriteLine(f("nOoP")); Console.ReadLine(); } } ``` [Answer] ## Clojure, ~~104~~ 88 bytes Oh regex is really handy... anyway ([TIO](https://tio.run/##TYyxCsIwEED3fsURES6gixji4NLBH3BwKR2ivcBJmsTkFPr1sTj5tje89wjp@S7UGk7kwcMGXc5hgSoFfXAiFHF2GQp9qFTC7IqwcIp7FwIc/vy@oI8Dj3iGo0WOAqzNSeut/tF1OKVKLxgYBnWZTe2NuZG19soU1Q6UUBU1joC5rHWIgH5daN3aFw)): ``` #(apply str(flatten(map reverse(partition-all 2(partition-by(fn[i](< 47(int i)58))%))))) ``` `partition-by` splits into consecutive runs based on the return value of that function, `partition-all` splits into partitions of 2 (the pairs we'll be swapping), `map reverse` reverses them, `flatten` gets rid of nested list structure and finally we'll output a string. If `partition` was used instead of `partition-all` and we had odd number of chunks then the last one would be discarded. Original used verbose but fun `(juxt second first)` and `(set"0123456789")` instead of `reverse` and ASCII integer ranges. ``` #(apply str(flatten(map(juxt second first)(partition-all 2(partition-by(comp not(set"0123456789"))%))))) ``` [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 15 bytes ``` (\D+)(\d+) \2\1 ``` [Try it online!](https://tio.run/##KyxNTCn6/18jxkVbUyMmRVuTK8YoxvD//8SkZEMj45TUNBNTMwA "QuadR – Try It Online") ### Explanation [blatantly stolen from Okx](https://codegolf.stackexchange.com/a/129844/43319): This replaces the regex `(\D+)(\d+)` with `\2\1`. Let's break that down if you don't know what that means. The `\D` means 'match anything that isn't a number'. `\d` means 'match everything that is a number'. The `+` sign means 'match this at least once but try to match it as many times as possible'. The brackets define a group. The first group is `(\D+)` and the second is `(\d+)` In the second line we say that we want to put whatever was matched by the second group, followed by whatever was matched by the first group. This effectively swaps the letter and digit runs. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 40 bytes ``` $args|%{$_ -replace '(\D+)(\d+)','$2$1'} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyWxKL24RrVaJV5Btyi1ICcxOVVBXSPGRVtTIyZFW1NdR13FSMVQvfb///95/vkB/11zTYsdTU3DUs3NzYMyU/P@e6Tm5aUm5eeVmJq5Ff1PTEo2MjX772WQaZBr8b80zDSgxNjTAAA "PowerShell – Try It Online") --- PowerShell is pretty ideal for this, seeing that it supports regex search-and-replace out of box. Props go to [@Okx](https://codegolf.stackexchange.com/users/26600/okx) for the regex solution. [Answer] # [Pip](https://github.com/dloscutoff/pip), 17 bytes ``` aR-C+XL.C+XD{c.b} ``` Takes input as a command-line argument. [Try it online!](https://tio.run/##K8gs@P8/MUjXWTvCRw9IuFQn6yXV/v//vzTMNKDE2NMAAA "Pip – Try It Online") ### Explanation This uses the standard regex-replacement strategy, somewhat golfed. The regex is `-C+XL.C+XD`, which evaluates to ``(?i)([a-z]+)(\d+)``: ``` XL Preset regex variable for lowercase letter: `[a-z]` + Apply + to the regex: `[a-z]+` C Wrap the regex in a capturing group: `([a-z]+)` - Apply the case-insensitive flag: `(?i)([a-z]+)` XD Preset regex variable for digit: `\d` + Apply + to the regex: `\d+` C Wrap the regex in a capturing group: `(\d+)` . Concatenate the two regexes: `(?i)([a-z]+)(\d+)` ``` The replacement is `{c.b}`, a callback function that concatenates the second group (`c`) and the first group (`b`). (The first argument to the function, `a`, contains the whole match.) This is three bytes shorter than the naive `aR`(\D+)(\d+)``\2\1``. [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 98 bytes ``` ,[>>----[---->+<<<-[>]>]>>[.[[-]<]<<[-]+>>]<[[-<<<+>>>]<<<<[-<[<]>[.[-]>]]>[-<+>]>],]<[-]<[<]>[.>] ``` [Try it online!](https://tio.run/##LYuxCoAwDEQ/SONWuhwBB3/AwSVkUKlQxA6K31@vYAK5l1xuu9dcjnc/a@1NVVjWhnYAxNTZaoOZOBygdKoO7vSJZLQzDN7@hAGC0CP13hK/p17rdIVnDGFJMcY5p/IB "brainfuck – Try It Online") ### Explanation This program maintains a queue of letters than haven't been output yet, and outputs them when appropriate. The key to this program is `>>----[---->+<<<-[>]>]`. The three cells right of the input cell start out at zero. If the input is a code point between 1 and 63 inclusive, this moves the pointer one space right and places the input two spaces right of this new position. Otherwise, the pointer moves two spaces right, the cell one space right of the new position becomes 63, and the same 63 is subtracted from the input cell. This neatly divides the input into letters (65-122) and digits (48-57). ``` ,[ Take first input byte and start main loop >> Move two cells to the right ----[---->+<<<-[>]>] (See above) >> Move two cells to the right This cell contains the input if it was a digit, and 0 if input was a letter [ If input was a digit: . Output digit immediately [[-]<] Zero out digit and working cell <<[-]+>> Set flag so we know later that we've output a digit ] < Move one cell left This cell contains 63 if input was a letter, and 0 if input was a digit [ If input was a letter: [-<<<+>>>] Add 63 back to input letter <<<< Move to flag [ If a digit has been output since the last letter read: - Clear flag <[<]> Move to start of queue [.[-]>] Output and clear all queued letters ] >[-<+>]> Move input to end of queue ] ,] Repeat until no input remains <[-] Clear flag if present <[<]> Move to start of queue [.>] Output all queued letters ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 31 bytes ``` ->x{x.gsub /(\D+)(\d+)/,'\2\1'} ``` [Try it online!](https://tio.run/##KypNqvxfbPtf166iukIvvbg0SUFfI8ZFW1MjJkVbU19HPcYoxlC99n9BaUmxQnG0umuuabGjqWlYqrm5eVBmap56LBdMyiM1Ly81KT@vxNTMrQhJPM8/P0A99j8A "Ruby – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 40 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 5 bytes ``` ⁽±Ḋ2ẇvṘ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyLhuaA9IiwiIiwi4oG9wrHhuIoy4bqHduG5mCIsIiIsInVWNVB0M0kwIl0=) Bitstring: ``` 1111001101110011001010001110010110010110 ``` [Answer] # Mathematica, 129 bytes ``` (n=NumberString;l=Length;s=Riffle[a=StringCases[#,n],b=StringSplit[#,n]];If[l@a==0,s=#,If[l@a<l@b,AppendTo[s,b[[-2;;]]]]];""<>s)& ``` [Answer] # [Scala](http://www.scala-lang.org/), 89 bytes A port of [@Julian Wolf's Haskell answer](https://codegolf.stackexchange.com/a/129857/110802) in Scala. --- Golfed version. [Try it online!](https://tio.run/##bY7BSsNAEIbveYphEbJLq4TKNtq6gR4UFaRFodcyiRuNbCahu4oQ8uwxMVrapnOZ4f/mY8YmaLAp4g@dOHjCjEB/O02vFhZlCZXnAXyhgXTGX9w2ozcV9V2AaqyKLOTokvcqQasZUxFj826EFlWtx80YhbIXtkTim8i/9sW8i2mME6HwL7/xZ21OIzNKeZvXdQNQtkecIW7Z51qu3OVDAP91HsFZlfIdYKJmwttXHoMsyK8ABkoPfgU4MDBOJnJ6wujB8MS9JtJxQU5O77b7wgEYere5tAsp1zoMw@dM0847BkOVlsUK4MSPHejXvbr5AQ) ``` s=>s match{case""=>"";case s=>{val(l,a)=s.span(_>'9');val(n,a2)=a.span(_<':');n+l+f(a2)}} ``` Ungolfed version. [Try it online!](https://tio.run/##bY9ra4MwGIW/@ysOMjCyC7KRupVV6IeNbexSNujXEW3cHBrFpGNQ/O0uGu10NpDbe85z3kRGLGV1nYdfPFJ4YokA/1FcbCSWRYGdZQEbHiMmUpWJ@Jjjrd3d/oCFNkEPoyNjKvrsSkDEJIdtYxHodVjT7qbYlYBvloKkXCleyhOwWO@P5ubqDtp9JgsmyDsCOFeOO@bENgv/uGdza7hhTh9wDWc@COhYHKPrrk8xGQe15spqpl4K/U@VCiLt7Zqu1MW912fhNMDRLiZ7wXYr2x0hD17iZZfABDFCC2BEsDA6p7MDhBGmLe64EDzMhaKz23IIjIQpd5NRuaR0zX3ff0242HP/hSkqXvIVcOCNjWDsVlXXvw) ``` object Main extends App { def f(string: String): String = { string match { case "" => "" case str => val (letters, afterLetters) = str.span(_ > '9') val (numbers, afterNumbers) = afterLetters.span(_ < ':') numbers + letters + f(afterNumbers) } } println(s"uV5Pt3I0 -> ${f("uV5Pt3I0")}") println(s"J0i0m8 -> ${f("J0i0m8")}") println(s"abc256 -> ${f("abc256")}") println(s"Hennebont56Fr -> ${f("Hennebont56Fr")}") println(s"Em5sA55Ve777Rien -> ${f("Em5sA55Ve777Rien")}") println(s"nOoP -> ${f("nOoP")}") } ``` ]
[Question] [ A fairly simple challenge: You will receive two inputs, a string and a number (the number may be taken as a string, ie `"123"` instead of `123`) If the string does not end in a number (ie, it does not match the regex `\d$`), just append the number to the end of the string. If the string does end in a number (ie, it matches the regex `\d+$`), you should first delete that and then append the number. Neither of the inputs will ever be invalid or empty (invalid is defined by the numerical input not containing only digits) The number will never contain a `-` or a `.`. The string will never contain a newline, or unprintable non-whitespace characters. ## Test Cases: ``` abc123 + 345 -> abc345 123 + 1 -> 1 hello + 33 -> hello33 123abc123 + 0 -> 123abc0 ab3d5 + 55 -> ab3d55 onetwo3 + 3 -> onetwo3 99ninenine + 9999 -> 99ninenine9999 ``` [Answer] # [Retina](https://github.com/m-ender/retina), 5 bytes ``` \d*¶ ``` Takes two strings as input, separated by a newline. [Try it online!](https://tio.run/##K0otycxL/P8/JkXr0Dau//8Tk5INjYy5jE1MAQ "Retina – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 30 bytes ``` lambda a,b:a.rstrip(`56**7`)+b ``` [Try it online!](https://tio.run/##RYzRCoIwGEbvfYr/7te1Il0rEOxFTHBLxcHahltIT79oFl2e73A@9wqzNVWcmlvU4iEHAYLKWhwWHxbl8p6fCbn0xU7GdVZ6hBLqDHyjjHuGvMjALcoE8BT3V6RTTnwRWxTyXlYMKSA7ceyyFr9YJphHrW2y7Cf/xTFNQrKBf5BvvTVjWO12iR28AQ "Python 2 – Try It Online") [Answer] # PHP, 37 36 35 33 bytes ``` <?=chop($argv[1],3**39),$argv[2]; ``` Saved 1 byte thanks to [Jörg Hülsermann](https://codegolf.stackexchange.com/users/59107/j%c3%b6rg-h%c3%bclsermann). [Answer] ## Perl 5, 12 bytes **11 bytes code + 1 for `-p`.** ``` s/\d*$/<>/e ``` [Try it online!](https://tio.run/##K0gtyjH9/79YPyZFS0Xfxk4/9f//xKRkQyNjLmMTUy4QbciVkZqTk89lbAziQiUNuBKTjFNMuUxNufLzUkvK84Hq/@UXlGTm5xX/1y0AAA "Perl 5 – Try It Online") [Answer] # Java 8, 32 bytes ``` a->b->a.replaceAll("\\d*$","")+b ``` Takes input `a` as a String, and for `b` it doesn't matter whether it's a String or integer (although I use Integer in the TIO-link below). [Try it here.](https://tio.run/##jZAxT8MwEIX3/IqTxRBDYlFCpkAkFiQGpo6U4eKY4uDYVnIpqlB/ezBKoFUXInk439P33t01uMPUeWWb@mPUrXcdQRN6YiBtxNtgJWlnxeNcFJE02PfwjNp@RQA9IWkJv/Ldmjptt8mx8WRJbVWXwKSUJch7GDEtq7RE0SlvUKoHY2K22dSXFyxhjF9VYxG8w/NDZYL9nLJzuoY2JMeT2csrIP@ZAmC970m1wg0kfJDI2FgK9N7sY4aVXN1kjM//7DbnvPiXOkVWS4B3ZYw7pmQLQ86mu16CYZXV@R@SL9rHWUWf7uQME3SIDuM3) [Answer] # [Python 2](https://docs.python.org/2/), 32 bytes ``` import re re.compile("\d*$").sub ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PzO3IL@oRKEolSvNtihVLzk/tyAzJ1VDKSZFS0VJU6@4NOl/QVFmXolGmoZWZl5BaYmGpqbmfyUTUzMlHaWM1JycfEMjYyUA "Python 2 – Try It Online") Takes the inputs in reverse order, both as string. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` DvTFNÜ}}« ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fpSzEze/wnNraQ6v//zc0Mk5MSgaSXAYA "05AB1E – Try It Online") Probably a bad solution but it's the best I could come up with ### Explanation ``` DvTFNÜ}}« Dv } # For each character in input1 TF } # 10 times NÜ # Get 0-9 and trim it from input1 « # Concatenate with input2 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 bytes ``` r"%d*$" +V ``` [Try it online!](https://tio.run/##y0osKPn/v0hJNUVLRUlBO@z/f6XEpGQlHQUlE1MzJQA "Japt – Try It Online") ``` r"%d*$" +V Ur"%d*$" +V # Implicit input (U and V) r # Remove "%d*$" # any trailing digits U # from the first input +V # And append the second input # Implicit output ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~44~~ ~~41~~ 39 bytes **EDIT:** -4 bytes thanks to @Dom Hastings. I don't use regular expressions much. **EDIT 2**: -2 bytes thanks to @totallyhuman pointing out that the number could be taken as a string Had to be expected... ``` lambda x,y:re.sub("\d*$",y,x) import re ``` Just removes the digits at the end of the string and appends the number [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFCp9KqKFWvuDRJQykmRUtFSSehMkGnQpMrM7cgv6hEoSj1f0FRZl6JRppGZl5BaYmGpo4CiAvlAMF/pYzUnJx8QyNjJS4TUzMA "Python 2 – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~9~~ 7 bytes ``` a<|XD.b ``` *@DLosc saved me 2 bytes!* [Try it online!](https://tio.run/##K8gs@P8/0aYmISYlQS/p////5jmJOYmGBv8tLQE "Pip – Try It Online") Explanation ``` a<| Strip all matches off the end of 'a' (the first cmd line arg) XD of the pattern \d (ordinarily, a regex would be entered as '\d', but digits have a pre-existing constant XD) .b Then concatenate 'b' (the second cmd line arg) PIP implicitly prints the results of the last operation. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` œrØD; ``` [Try it online!](https://tio.run/##y0rNyan8///o5KLDM1ys/x9erv@oaU3k///R0UqJScmGRsZKOgoKSsYmpkqxOlwK0UpQETBQMoQKZgANyYcIKxkbI1TCTVAygAomJhmnmEJVmsLMzM9LLSnPh5irBNQeCwA "Jelly – Try It Online") ### How it works ``` œrØD; Main link. Left argument: s. Right argument: t ØD Digits; yield "0123456789". œr Trim these characters from the right of s. ; Append t. ``` [Answer] # JavaScript (ES6), ~~28~~ ~~26~~ 25 bytes ``` x=>y=>x.replace(/\d*$/,y) ``` * 1 byte saved thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) reminding me why I shouldn't golf early in the morning! [Answer] # [Ruby](https://www.ruby-lang.org/), 21 bytes ``` ->a,b{a=~/\d*$/;$`+b} ``` Takes two strings in input. [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6k60bZOPyZFS0XfWiVBO6n2f0FpSbFCWrRSYlKyoZGxko6SsYmpUiwXTBgiZogkkpGak5MPUmeMqgxugAGSeGKScYopUMwU2cz8vNSS8nywXUqx/wE "Ruby – Try It Online") [Answer] # C#, 45 bytes ``` s=>n=>s.TrimEnd("0123456789".ToCharArray())+n ``` Explanation: ``` s=>n=> // Take input s.TrimEnd( // Trim the end of the string with the specified chars "0123456789" // Create a string of the digits .ToCharArray()) // Turn the string into a char array +n // Append the integer onto the end ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~7~~ 4 bytes ``` óä*î ``` [Try it online!](https://tio.run/##K/v///Dmw0u0Dq/7/7@4pCgzL10hPy9VoSQjsUQhOTFPITk/ryQxM08hMa@yJAMoa2hkzJWYlMxlYmoGAA "V – Try It Online") This uses the same regex as the Retina answer above: ``` s:/\d*\n// ``` [Answer] # [Perl 6](http://perl6.org/), 20 bytes ``` ->$_,\n{S/\d*$/{n}/} ``` [Answer] ## Tcl 32 bytes ``` proc s a\ b {regsub \\d*$ $a $b} ``` I'm not sure about the expected interface. This is done as a procedure that accepts the two inputs as call arguments. To turn it to a standalone script that reads input from stdin and outputs the result to stdout, one would need the extra line: ``` puts [s [gets stdin] [gets stdin]] ``` or would do it all "inline": ``` puts [regsub \\d*$ [gets stdin] [gets stdin]] ``` regsub takes an RE, the original string and a string to replace the matching part with. [Answer] ## Mathematica, 48 bytes There is already a Mathematica solution (84 bytes). ``` StringDrop[StringTrim["."<>#,_?DigitQ..]<>#2,1]& ``` [Answer] # [Carrot](https://github.com/kritixilithos/Carrot), ~~16~~ 21 bytes ``` $^//^.*?(?=\d*$)/S0^# ``` [Try it online!](http://kritixilithos.github.io/Carrot/) (input is linefeed separated) ### Explanation ``` $^ Set the stack-string to be equal to the first line in the input / Set the stack-array to be equal to the matches of this regex: /^.*?(?=\d*$)/ The beginning of the string followed by non-digit characters at the end that are not included in the match. S0 Convert to a string with 0 as the delimiter ^# Append the rest of the input to the stack-string ``` I had to increase the bytecount by 5 because the code did not work for testcases like `a5b3` with multiple digits. [Answer] # Haskell, ~~75 bytes~~ ~~95 bytes~~ ~~91~~ ~~79~~ 61 bytes ``` b=(`notElem`['0'..'9']) r=reverse d#e=r(snd$break b$r d)++e ``` I tried doing this without regex so maybe that would be a dramatically improved answer. Also there are a couple ways I could go about this so I am unsure if I can shave a few bytes with a different approach. UPDATE: I went up in bytes because I realized I was failing the test case where numbers exist in the string that are not the suffix. Now I am sure that regex would provide a much better answer. UPDATE2: After some great feedback, more bytes were golfed! [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 18 bytes ``` sub("[0-9 ]*$",$2) ``` [Try it online!](https://tio.run/##SyzP/v@/uDRJQynaQNdSIVZLRUlHxUjz/39Ly7zMvFQQVrAEAq7EpGRDI2MFYxNTAA "AWK – Try It Online") This just replaces a string composed of any number of digits and spaces that ends the arguments to the command with the second argument to the command. It's effectively stripping the commandline and adding back the second argument. And since there's guaranteed to be a non-empty second argument, the result is truthy and `$0` is printed, which is the modified commandline arguments. [Answer] # Mathematica, 84 bytes ``` (k=#;T=ToCharacterCode;L=T@k;While[47<Last@L<58,w=k~StringDrop~-1;k=w;L=T@w];w<>#2)& ``` input 2 strings > > ["ab3d5", "55"] > > > output > > ab3d55 > > > [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~99~~ ~~98~~ ~~96~~ 95 bytes Should be able to golf this down a bit... ``` main(c,v)char**v;{for(c=strlen(v[1]);~c*isdigit(v[1][--c]);v[1][c]=0);printf(v[1]),puts(v[2]);} ``` [Try it online!](https://tio.run/nexus/c-gcc#JcpLDoMgFEbh7QCRpL5GxJUYB/Svj5tYNIBMGt11x7fEzk6@HH5bcgJFklisVyqZz7R5gS5Ev45OpL4cpLmgKLxopnhDrzWy3omhe0ize3Jx@t/FfsSQs8rLycz2ibKquW7ar9s0LJbxBw "C (gcc) – TIO Nexus") [Answer] # [Noether](http://github.com/beta-decay/noether), 11 bytes ``` I"\d+$"-I+P ``` [**Try it here!**](https://beta-decay.github.io/noether?code=SSJcZCskIi1JK1A&input=ImFiYzEyMyIKIjM0NSI) When inputting a string, enclose it in quotation marks ***Explanation:*** ``` I - Push input to stack "\d+$" - Push string to stack - - Remove characters from first string which match the regex I - Push input to stack + - Append to the first string P - Print top item of stack ``` [Answer] # [Arturo](https://arturo-lang.io), 25 bytes ``` $=>[++replace&{/\d+$}""&] ``` [Try it](http://arturo-lang.io/playground?Bdi1O1) [Answer] # [Go](https://go.dev), 77 bytes ``` import."strings" func a(s,n string)string{return TrimRight(s,"0123456789")+n} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70oPX_BzoLE5OzE9FSF3MTMPK7M3IL8ohIFpbTcEqWlpSVpuhY3fSFiekrFJUWZeenFSlxppXnJCokaxTp5ChAxTQhVXZRaUlqUpxBSlJkblJmeUQJUomRgaGRsYmpmbmGppKmdVws11BhsBshKDU2Fai4FIABaqRcANKYkJ08jUUMpMSkZqFNJR0EJqF1JU5MLqnXBAggNAA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` DþRvyÜ}« ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f5fC@oLLKw3NqD63@/z8/L7WkPN@YyxgA "05AB1E – Try It Online") **Explanation:** ``` DþRvyÜ}« D Duplicate input. þ Get the digits of the input. R Reverse the digits of the input. v } For each of the digits in the input: y Push the current digit Ü Trim that from the right of the input. « Concatenate to 2nd input. ``` [Answer] # Google Sheets, 28 bytes ``` =REGEXREPLACE(A1,"\d+$",)&B1 ``` ]
[Question] [ A paragraph of text has numbers and alphabetic letters mixed. Your task is to separate the numbers to the left side and the alphabetic letters to the right side in the same order of each line. Rules: 1. Numbers are plain integers; so no decimal point, and no negative/positive signs. 2. Numbers may or may not be contiguous, but whatever the case may be, they have to be pushed to left side in the same order. 3. Numbers may occur in between words. 4. The text contains only ASCII alphabetic letters and numbers, along with spaces, underscores, commas and dots. 5. The one who does this with minimum keystrokes (like vim macros) or least amount of bytes in case of scripting is the winner. Example Text: ``` A word can have any number of text like 433884, but all the numb89ers has to be moved left side but alph6abetical va9lues has to be pas46ted on right side. The text might con4tain chara29cters s2huffled like hlep or dfeintino or even meaningless1 words co43mbined togeth81er. ``` Expected output: ``` 433884A word can have any number of text like , 89but all the numbers has to be moved left side 6946but alphabetical values has to be pasted on right side. 4292The text might contain characters shuffled like hlep or dfeintino or even 14381meaningless words combined together. ``` [Answer] ## [Retina](https://github.com/mbuettner/retina/), 14 bytes ``` O%$`\d|(.) $#1 ``` [Try it online!](http://retina.tryitonline.net/#code=TyUkYFxkfCguKQokIzE&input=QSB3b3JkIGNhbiBoYXZlIGFueSBudW1iZXIgb2YgdGV4dCBsaWtlIDQzMzg4NCwKYnV0IGFsbCB0aGUgbnVtYjg5ZXJzIGhhcyB0byBiZSBtb3ZlZCBsZWZ0IHNpZGUgCmJ1dCBhbHBoNmFiZXRpY2FsIHZhOWx1ZXMgaGFzIHRvIGJlIHBhczQ2dGVkIG9uIHJpZ2h0IHNpZGUuClRoZSB0ZXh0IG1pZ2h0IGNvbjR0YWluIGNoYXJhMjljdGVycyBzMmh1ZmZsZWQgbGlrZSBobGVwIG9yIGRmZWludGlubyBvciBldmVuCm1lYW5pbmdsZXNzMSB3b3JkcyBjbzQzbWJpbmVkIHRvZ2V0aDgxZXIu) ### Explanation `O` introduces a sorting stage. `%` tells Retina to apply the transformation to each line separately. `$` tells it to sort the matches by the result of the specified substitution. The regex itself is `\d|(.)` which either matches a digit, or anything else which is captured into group `1`. This is substituted with `$#1` which is the number of captures of group `1`. That is, the sorting key for digits is `0` and the sorting key for everything else is `1`. Since sorting in Retina is stable, this simply moves digits to the left and everything else to the right. [Answer] ## 05AB1E, ~~14~~ 10 bytes **Code:** ``` |vyþyyþ-¶J ``` **Explanation:** ``` | # push all lines in input as array of strings v # for each line in array yþ # push only digits from line yyþ- # push line without digits ¶ # push newline char J # join as string # end loop and print explicitly ``` **Example Input:** > > A word can have any number of text like 433884, > > but all the numb89ers has to be moved left side > > but alph6abetical va9lues has to be pas46ted on right side. > > The text might con4tain chara29cters s2huffled like hlep or dfeintino or even > > meaningless words co43mbined togeth81er. > > > **Example Output:** > > 433884A word can have any number of text like , > > 89but all the numbers has to be moved left side > > 6946but alphabetical values has to be pasted on right side. > > 4292The text might contain characters shuffled like hlep or dfeintino or even > > 4381meaningless words combined together. > > > [Try it online](http://05ab1e.tryitonline.net/#code=fHZ5w755ecO-LcK2Sg&input=QSB3b3JkIGNhbiBoYXZlIGFueSBudW1iZXIgb2YgdGV4dCBsaWtlIDQzMzg4NCwKYnV0IGFsbCB0aGUgbnVtYjg5ZXJzIGhhcyB0byBiZSBtb3ZlZCBsZWZ0IHNpZGUgCmJ1dCBhbHBoNmFiZXRpY2FsIHZhOWx1ZXMgaGFzIHRvIGJlIHBhczQ2dGVkIG9uIHJpZ2h0IHNpZGUuClRoZSB0ZXh0IG1pZ2h0IGNvbjR0YWluIGNoYXJhMjljdGVycyBzMmh1ZmZsZWQgbGlrZSBobGVwIG9yIGRmZWludGlubyBvciBldmVuCm1lYW5pbmdsZXNzIHdvcmRzIGNvNDNtYmluZWQgdG9nZXRoODFlci4) [Answer] # Python 3, 64 bytes Three equivalent solutions! I can’t pick. ``` while 1:print(*sorted(input(),key=lambda x:-x.isdigit()),sep='') while 1:print(*sorted(input(),key=lambda x:x<'0'or'9'<x),sep='') while 1:print(*sorted(input(),key=str.isdigit,reverse=1),sep='') ``` [Answer] ## Perl, 17 bytes **16 bytes code + 1 switch** ``` s/\d/!print$&/ge ``` Requires `-p`. ### Usage ``` perl -pe 's/\d/!print$&/ge' <<< 'a1b2c3d4e5f6' 123456abcdef ``` --- Alternatively: ``` print/\d/g,/\D/g ``` Requires `-n`. ### Usage ``` perl -ne 'print/\d/g,/\D/g' <<< 'a1b2c3d4e5f6' 123456abcdef ``` [Answer] ## [Hoon](https://github.com/urbit/urbit), ~~92~~ 83 bytes ``` |* * (turn (lore +<) |=(@ `tape`(welp (skid (trip +<) |=(@ !=(~ (rush +< nud))))))) ``` `++lore` splits a multi-line cord into a `(list cord)`, `(trip +<)` turns it into a tape. `++skid` seperates a list in two: one side where the function returns yes, one side where it returns no. Our function tries to parse the character with `++nud` (numeric) and checks if it parses fully, and then we weld the two lists back together into a tape. ``` > %. ''' A word can have any number of text like 433884, but all the numb89ers has to be moved left side but alph6abetical va9lues has to be pas46ted on right side. The text might con4tain chara29cters s2huffled like hlep or dfeintino or even meaningless1 words co43mbined togeth81er. ''' |* * (turn (lore +<) |=(@ `tape`(welp (skid (trip +<) |=(@ !=(~ (rush +< nud))))))) << "433884A word can have any number of text like ," "89but all the numbers has to be moved left side " "6946but alphabetical values has to be pasted on right side." "4292The text might contain characters shuffled like hlep or dfeintino or even" "14381meaningless words combined together." >> ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~13~~ 12 bytes ``` `jt4Y2m&)hDT ``` Exits with an error (allowed by default), producing the correct output. [**Try it online!**](http://matl.tryitonline.net/#code=YGp0NFkybSYpaERU&input=QSB3b3JkIGNhbiBoYXZlIGFueSBudW1iZXIgb2YgdGV4dCBsaWtlIDQzMzg4NCwKYnV0IGFsbCB0aGUgbnVtYjg5ZXJzIGhhcyB0byBiZSBtb3ZlZCBsZWZ0IHNpZGUgCmJ1dCBhbHBoNmFiZXRpY2FsIHZhOWx1ZXMgaGFzIHRvIGJlIHBhczQ2dGVkIG9uIHJpZ2h0IHNpZGUuClRoZSB0ZXh0IG1pZ2h0IGNvbjR0YWluIGNoYXJhMjljdGVycyBzMmh1ZmZsZWQgbGlrZSBobGVwIG9yIGRmZWludGlubyBvciBldmVuCm1lYW5pbmdsZXNzIHdvcmRzIGNvNDNtYmluZWQgdG9nZXRoODFlci4) ### Explanation ``` ` T % infinite loop j % input one line as a string t % duplicate 4Y2 % predefined literal: '0123456789' m % true for elements of string that are digits, false for the rest &) % two-output indexing: push digits, then non-digits h % concatenate the two strings D % display ``` [Answer] # V, 12 bytes ``` òí¨Ä©¨ä©/²± ​ ``` V, is an unfinished, 2D string based golfing language. Although it is unfinished, this program works as of [commit 45](https://github.com/DJMcMayhem/V/commit/5223c1a85427b79f7c6766a43f16818a2f8e7a3f), which was published last night, making this a competing answer. (Most of my previous V answers were non-competing.) Note, the trailing newline is necessary, although this is due to a bug. [Try it online!](http://v.tryitonline.net/#code=w7LDrcKow4TCqcKow6TCqS_CssKxCg&input=QSB3b3JkIGNhbiBoYXZlIGFueSBudW1iZXIgb2YgdGV4dCBsaWtlIDQzMzg4NCwKYnV0IGFsbCB0aGUgbnVtYjg5ZXJzIGhhcyB0byBiZSBtb3ZlZCBsZWZ0IHNpZGUgCmJ1dCBhbHBoNmFiZXRpY2FsIHZhOWx1ZXMgaGFzIHRvIGJlIHBhczQ2dGVkIG9uIHJpZ2h0IHNpZGUuClRoZSB0ZXh0IG1pZ2h0IGNvbjR0YWluIGNoYXJhMjljdGVycyBzMmh1ZmZsZWQgbGlrZSBobGVwIG9yIGRmZWludGlubyBvciBldmVuCm1lYW5pbmdsZXNzMSB3b3JkcyBjbzQzbWJpbmVkIHRvZ2V0aDgxZXIu) Explanation: ``` ò #Recursively, do: í #Substitute on every line ¨Ä©¨ä©/²± #The following regex. ``` `¨Ä©¨ä©/²±` expands into the vim regex: ``` :%s/\(\D\)\(\d\)/\2\1 ``` which is a non-digit `(\D)` followed by a digit `(\d)`, and swap them. Since this is filled with gross unicode characters, here is a reversible hexdump: ``` 00000000: f2ed a8c4 a9a8 e4a9 2fb2 b10a ......../... ``` [Answer] # Javascript ES6, 40 bytes `a=>a.replace(/\D/g,'')+a.replace(/\d/g,'')` Tried several other solutions, but couldn't get it smaller than this. My first try was `a=>[...a.match(/\d/g),...a.match(/\D/g)].join``` but that's 5 bytes longer Try it here ``` f= a=>a.replace(/\D/g,'')+a.replace(/\d/g,'') a.innerHTML='<pre>'+ ['A word can have any number of text like 433884,', 'but all the numb89ers has to be moved left side', 'but alph6abetical va9lues has to be pas46ted on right side.', 'The text might con4tain chara29cters s2huffled like hlep or dfeintino or even', 'meaningless words co43mbined togeth81er.'].map(b=>f(b)).join('<br>')+'</pre>' ``` ``` <div id=a> ``` [Answer] # CJam, ~~9~~ ~~13~~ 16 bytes ``` qN/{{A,s-,}$}%N* ``` There isn't `f$`... This 13 bytes version nearly works: ``` {l{A,s-,}$N}h ``` [Answer] ## PowerShell v2+, 55 bytes ``` $args[0]-split"`n"|%{($_-replace'\D')+($_-replace'\d')} ``` Due to the need to support multi-line input, we have to encapsulate our `-replace` statements with a loop and `-split` on newlines. Otherwise basically equivalent to the [JavaScript solution](https://codegolf.stackexchange.com/a/80643/42963). [Answer] # Pyth - 11 bytes Don't like my grouping test. Takes input as list of lines, tell me if that's not ok. ``` jms_.g}k`MT ``` [Try it online here](http://pyth.herokuapp.com/?code=jms_.g%7Dk%60MT&input=%5B%22A+word+can+have+any+number+of+text+like+433884%2C%22%2C%22but+all+the+numb89ers+has+to+be+moved+left+side%22%2C%22but+alph6abetical+va9lues+has+to+be+pas46ted+on+right+side.%22%2C%22The+text+might+con4tain+chara29cters+s2huffled+like+hlep+or+dfeintino+or+even%22%2C%22meaningless1+words+co43mbined+togeth81er.%22%5D&debug=0). [Answer] ## Pyth, ~~16~~ 15 bytes 1 byte thanks to [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman). ``` jms+@J`MTd-dJ.z ``` [Try it online!](http://pyth.herokuapp.com/?code=jms%2B%40J%60MTd-dJ.z&input=A+word+can+have+any+number+of+text+like+433884%2C%0Abut+all+the+numb89ers+has+to+be+moved+left+side+%0Abut+alph6abetical+va9lues+has+to+be+pas46ted+on+right+side.%0AThe+text+might+con4tain+chara29cters+s2huffled+like+hlep+or+dfeintino+or+even%0Ameaningless1+words+co43mbined+togeth81er.&debug=0) Sample input: ``` A word can have any number of text like 433884, but all the numb89ers has to be moved left side but alph6abetical va9lues has to be pas46ted on right side. The text might con4tain chara29cters s2huffled like hlep or dfeintino or even meaningless1 words co43mbined togeth81er. ``` Sample output: ``` 433884A word can have any number of text like , 89but all the numbers has to be moved left side 6946but alphabetical values has to be pasted on right side. 4292The text might contain characters shuffled like hlep or dfeintino or even 14381meaningless words combined together. ``` ## How it works ``` jms+@J`MTd-dJ.z m .z for each line (d): d yield d (the line) J assign J to T [0,1,2,3,...,9] `M with each number converted to string @ intersect with J + append: -dJ filter d for characters not in J s convert to one string j join by newline ``` [Answer] # Retina, 16 bytes Stable bubble sort. ``` %+`(\D)(\d) $2$1 ``` Sample input: ``` A word can have any number of text like 433884, but all the numb89ers has to be moved left side but alph6abetical va9lues has to be pas46ted on right side. The text might con4tain chara29cters s2huffled like hlep or dfeintino or even meaningless1 words co43mbined togeth81er. ``` Sample output: ``` 433884A word can have any number of text like , 89but all the numbers has to be moved left side 6946but alphabetical values has to be pasted on right side. 4292The text might contain characters shuffled like hlep or dfeintino or even 14381meaningless words combined together. ``` [Try it online!](http://retina.tryitonline.net/#code=JStgKFxEKShcZCkKJDIkMQ&input=QSB3b3JkIGNhbiBoYXZlIGFueSBudW1iZXIgb2YgdGV4dCBsaWtlIDQzMzg4NCwKYnV0IGFsbCB0aGUgbnVtYjg5ZXJzIGhhcyB0byBiZSBtb3ZlZCBsZWZ0IHNpZGUgCmJ1dCBhbHBoNmFiZXRpY2FsIHZhOWx1ZXMgaGFzIHRvIGJlIHBhczQ2dGVkIG9uIHJpZ2h0IHNpZGUuClRoZSB0ZXh0IG1pZ2h0IGNvbjR0YWluIGNoYXJhMjljdGVycyBzMmh1ZmZsZWQgbGlrZSBobGVwIG9yIGRmZWludGlubyBvciBldmVuCm1lYW5pbmdsZXNzMSB3b3JkcyBjbzQzbWJpbmVkIHRvZ2V0aDgxZXIu&debug=on) [Answer] ## C#, 59 bytes ``` I=>Regex.Replace(I,"[^0-9]","")+Regex.Replace(I,@"\d+",""); ``` A simple C# lambda function using regex. ## Sample output ``` 433884A word can have any number of text like , 89but all the numbers has to be moved left side 6946but alphabetical values has to be pasted on right side. 4292The text might contain characters shuffled like hlep or dfeintino or even 14381meaningless words combined together. ``` [Answer] # C# (LINQ), 110 bytes ``` s=>string.join("",s.Where(c=>"0123456789".Contains(c).Concat(s.SelectMany(c=>new[]{c}.Except("0123456789")))); ``` Not the shortest solution, by far, but I thought this would be a good use of LINQ. [Answer] # [Factor](http://factorcode.org) 61 ``` [ "\n"split [ [ digit? ] partition [ write ] bi@ nl ] each ] ``` It's a naive approach. `"\n"split` splits the string on top of the stack into lines. Then, for `each` line: 1. `[ digit? ] partition` splits each line into digits-only and non-digits-only 2. `[ write ] bi@` outputs both, and `nl` prints a newline. PS: **As a word 90 bytes** (71 if you replace the-factorish-long-name with 1 letter): ``` : numbers-to-the-front ( s -- ) "\n"split [ [ digit? ] partition [ write ] bi@ nl ] each ; ``` [Answer] # Pyth, 14 bytes ``` FG.zo_:N"\d"0G ``` [Try it online!](https://pyth.herokuapp.com/?code=FG.zo_%3AN%22%5Cd%220G&input=A+word+can+have+any+number+of+text+like+433884%2C%0Abut+all+the+numb89ers+has+to+be+moved+left+side+%0Abut+alph6abetical+va9lues+has+to+be+pas46ted+on+right+side.%0AThe+text+might+con4tain+chara29cters+s2huffled+like+hlep+or+dfeintino+or+even%0Ameaningless1+words+co43mbined+togeth81er.&debug=0) Explanation: ``` FG : For every G in ... .z : the-list-where-lines-of-input-are-stored ... : (implicitly print) o G : sorted G ... _N : where, a negative key is given ... :"\d"0 : to the individual character if it is a digit ``` The logic of the solution is the same as in [Lynn's answer](https://codegolf.stackexchange.com/a/80646/47253). [Answer] # Java 8, ~~130~~ ~~126~~ 86 bytes ``` a->{for(String s:a)System.out.println(s.replaceAll("\\D","")+s.replaceAll("\\d",""));} ``` -4 bytes converting Java 7 to 8 and removing an unused character -40 bytes converting program to function and changing `[^\\d]` to `\\D` **Explanation:** [Try it here.](https://tio.run/##XZHNTsMwEITvPMUop0aUSNAItVQgIXGFC9yAwybZNAZnHdmbAEJ99uKk5UdcLHnWM/vt@oUGOnEdy0v1uisthYBbMvJ5BBhR9jWVjLvxCgzOVChn9@qNbB6fQek66tujeAQlNSXuILjEjk6uPmvnDy8RLii9/wjKbeZ6zbooqpVZyDx3NuZfWztLnp5uknmSpMf/5WqS0/V2tx47dX1hY6dDwwmpjcA/VOQ3Id3zSlbOhN/wXdqrQHKNN@fjKCRoaGCQfED6tmAPV0P5XWHNKyNfLJbLfJ7Mv41FryBroQ1PhuWKfYgZAepQMFo3cAXLtSKYivHf2TXnVHAEJ4uBVrbnv@6OQn6uMcAJvNk0@5DsN@Qhtp3o2qlaOsk1zo6yIU9nq1JHmnDW9HVtR45xhsZyB@dR1RzXbsSNFx5YfmNbJokLshzC6bSZEKPzRVsYiSnqNqzN8pR9lkyO7eHbt7sv) ``` a->{ // Method with String-array parameter and no return-type for(String s:a) // Loop over the array System.out.println( // Print with a trailing new-line: s.replaceAll("\\D","") // All digits, +s.replaceAll("\\d","")); // plus all non-digits ``` [Answer] # GNU Sed, 28 Score includes +1 for `-r` option to sed. ``` : s/([^0-9])([0-9])/\2\1/ t ``` Repeatedly switches one non-number character followed by one number character until no more substitutions are made. Sadly sed regexes don't have `\d` or `\D`, so these have to be written out longhand. [Ideone.](https://ideone.com/0uQ8C6) [Answer] # Octave, ~~37~~ 32 bytes ``` @(s)disp([s(x=s>47&s<58),s(~x)]) ans('The text might con4tain chara29cters s2huffled like hlep or dfeintino or even') 4292The text might contain characters shuffled like hlep or dfeintino or even ``` [Answer] ## Clojure, 113 bytes ``` (fn[s](map(fn[x](println(apply str(sort-by #(when-not(Character/isDigit %)1)x))))(clojure.string/split-lines s))) ``` Sorts digits to the beginning of the line. [Answer] # Oracle SQL 11.2, 131 bytes The lines in the input string are separated by '¤'. That way it is not necessary to create a table to use as the input. ``` A word can have any number of text like 433884,¤but all the numb89ers has to be moved left side ¤but alph6abetical va9lues has to be pas46ted on right side.¤The text might con4tain chara29cters s2huffled like hlep or dfeintino or even¤meaningless1 words co43mbined togeth81er. ``` Query : ``` SELECT REGEXP_REPLACE(COLUMN_VALUE,'[^0-9]')||REGEXP_REPLACE(COLUMN_VALUE,'[0-9]')FROM XMLTABLE(('"'||REPLACE(:1,'¤','","')||'"')); ``` Un-golfed ``` SELECT REGEXP_REPLACE(COLUMN_VALUE,'[^0-9]')|| -- Every number REGEXP_REPLACE(COLUMN_VALUE,'[0-9]') -- Every character not a number FROM XMLTABLE(('"'||REPLACE(:1,'¤','","')||'"')) -- Split on ¤ ``` [Answer] ## APL, 28 chars ``` {⍵[⍋(~⍵∊⎕D)++\¯1⌽⍵=⎕UCS 13]} ``` [Answer] # Haskell, 60 bytes ``` import Data.List;g(n,l)=n++l;f=g.partition(`elem`['0'..'9']) ``` ### Usage ``` f "A word can have any number of text like 433884," ``` [Answer] # Sed, 35 bytes ``` h s/[0-9]//g x s/[^0-9]//g G s/\n// ``` This makes a copy of the line, removes digits from one copy and letters from the other, before recombining them. [Answer] # Bash, 42 bytes ``` read a&&echo "${a//[^0-9]}${a//[0-9]}"&&$0 ``` Be warned that this recursive implementation forks a new process for each line of input! [Answer] # [Japt v2](https://github.com/ETHproductions/japt), ~~14~~ 12 bytes *-2 bytes thanks to ETHproductions* ``` ®o\d +Zr\d}R ``` [Run it](https://ethproductions.github.io/japt/?v=2.0a0&code=rm9cZCArWnJcZH1S&input=IkEgd29yZCBjYW4gaGF2ZSBhbnkgbnVtYmVyIG9mIHRleHQgbGlrZSA0MzM4ODQsCmJ1dCBhbGwgdGhlIG51bWI4OWVycyBoYXMgdG8gYmUgbW92ZWQgbGVmdCBzaWRlIApidXQgYWxwaDZhYmV0aWNhbCB2YTlsdWVzIGhhcyB0byBiZSBwYXM0NnRlZCBvbiByaWdodCBzaWRlLgpUaGUgdGV4dCBtaWdodCBjb240dGFpbiBjaGFyYTI5Y3RlcnMgczJodWZmbGVkIGxpa2UgaGxlcCBvciBkZmVpbnRpbm8gb3IgZXZlbgptZWFuaW5nbGVzczEgd29yZHMgY280M21iaW5lZCB0b2dldGg4MWVyLiIK) [Answer] # [Julia 0.6](http://julialang.org/), 77 bytes ``` x->(l=r="";for c=x c=='\n'?(println(l*r);l=r=""):'/'<c<':'?(l*=c):(r*=c) end) ``` Anonymous function taking a string and printing output. Loops over characters, adding them to the left `l` or right `r` buffers until it finds a newline, then it prints and empties buffers. Lots of potential useful constructs like `sort`, `filter` and logical indexing (indexing with an array of boolean values) don't work on Strings. [Try it online!](https://tio.run/##TVG7ctswEOz5FTtKwccoim1xNBJtJhOncpoUdukGBI8CbDw4wFGWvl4B6RRpgMHh9nZv920yWuyu2o4@MB5FpAZVVlRlEZvmmYN2x7Vsml9KhBItYhWXWiFLfAErHWGJle9BZx05Qjv8nkfiZrODd7AXSG/HiSms8YS3KTJE30MzrHCTMOYCRYEQPV6e/uBDG4MPH96zoe3oqN31/PV7YdrQrlb3gw@Q7TmTbZu/uvxHMSYtbFxhqlDefzaVTf4tf5APeZP@TdXKsinCfGXk@vKajmwoVj9njh5SOChxIgh3gZtsRwF@ANOZYfQ7od5u9/t6nXVTkp2UsaKlb3@gEBM0gj06gvUn6mFoYETdE/4BRrUTHbGWwuAkDmai/0GjiPWOEy75FPRRfWI32UsiWSTYpSi9q1kkY2UKQdwdJM/c8U5Nw2Bm1lmoMjQi2dMPlCzRzs8POpHLLAmXEjMU4@2ydUwT663ttEtg9seU3/6WwmZVXv8C "Julia 0.6 – Try It Online") [Answer] # Vim, 30 keystrokes ``` qr:%s/\v(\D+)(\d+)/\2\1/<Enter>@rq@r ``` Record a search and replace action that moves digits to the left of non-digits. Call the macro recursively until an exception is thrown by the pattern not being found (when there are no more digits to the right of any non-digits). [Answer] # [C (gcc)](https://gcc.gnu.org/), 106 bytes ``` g(s,x)char*s;{for(;*s;s++)isdigit(*s)^x&&putchar(*s);}f(s,n)char**s;{for(;n--;puts(""))g(*s,0),g(*s++,1);} ``` [Try it online!](https://tio.run/##TZBBboMwEEXXcIoRiwgHEjUNjYhQF71Dd1UrGTPGVo2NbENTRTk7tYlUZWWP5r@ZP5/tesaWpc9deSFMULt1zZUbmzfh44qCSNfJXvp868jXZbMZJx9VsWxuPFD6Tv1jerdrgsjlWUZIH3TlEynjWxTlITCL1B4GKnVO0muaRBi2Smp0H5/wCtfsDX6M7YBRDYLOCFT/gp6GFi0YDh4vHpT8RqiOx7quyqxMk6ydPFClwAtctfUZrQu4A2@gRRjMjB0o5B6c7BAeoFGcaIteMqpgpmc14SM4UledfGCNBit7cef3K/8elq12hrXBjK58uAviSfT5zHz04J7FxLmK26NpoXAEY6HjGHKQ2sQCZ9TrxAGplrpX6NxhTcGFqdVxaEM8XXDUoxf1Ae0@uzVpkiY8X4Mr4YU06W35Aw "C (gcc) – Try It Online") ]
[Question] [ **This question already has answers here**: [Mountain range numbers](/questions/199055/mountain-range-numbers) (25 answers) Closed 4 years ago. An ***undulant*** number is a number where its digits alternate between *up* and *down* like the following number: 461902 or 708143, or even 1010101, but not 123, because 2 < 3. Write a program or function which returns a truthy value if a number is *undulant*, and a falsy value otherwise. The shortest code wins. **Note**: Single digit numbers are a valid input but are not considered *udulant*, thus `isUndulant` returns false for n < 10. [Answer] **(pdf)eTeX, 129 chars** ``` \def\a#1#2{\if#2?\ifx\r\s\def\s{1}\else True\end\fi\fi\edef\t{\pdfstrcmp{#2}{#1}}\ifx\s\t False\end\fi\let\s\t\a#2}\expandafter\a ``` Compiling with `pdfetex filename.tex 1324?` gives a pdf output. TeX is primarily a typesetting language, and outputting instead to stdout would take around 20 more chars. Also the strange requirement for one-digit numbers (false rather than true) takes me 26 chars. [Answer] ## J, 45 ``` *./(n>9),(}:(=-)}.)(}:*@-}.)n#:~10$~>.10^.n=. ``` Sample use: ``` *./(n>9),(}:(=-)}.)(}:*@-}.)n#:~10$~>.10^.n=. 461902 1 *./(n>9),(}:(=-)}.)(}:*@-}.)n#:~10$~>.10^.n=. 708143 1 *./(n>9),(}:(=-)}.)(}:*@-}.)n#:~10$~>.10^.n=. 1010101 1 *./(n>9),(}:(=-)}.)(}:*@-}.)n#:~10$~>.10^.n=. 123 0 *./(n>9),(}:(=-)}.)(}:*@-}.)n#:~10$~>.10^.n=. 5 0 ``` I'm pretty sure there's a finer way of twisting Insert `/` to do more of the work in a go, but I've been J-less for months, I need to get back to it. [Answer] ### Ruby, 72 70 characters ``` Q=10;k=->n,v{(n%Q-n/Q%Q)*v<0?k[n/Q,-v]:n<Q};u=->n{n>9&&k[n,-1]|k[n,1]} ``` Usage and testcases: ``` p u[10101] # <= true p u[708143] # <= true p u[2421] # <= false p u[1231] # <= false p u[873] # <= false ``` Single digits yield *false*: ``` p u[5] # <= false ``` Consecutive identical digits also return *false*: ``` p u[66] # <= false p u[1221] # <= false ``` [Answer] # J, 30 bytes ``` */0<(#,]*{.*1 _1$~#)2-/\a.i.": ``` A different approach than the other J answers. ``` */0<(#,]*{.*1 _1$~#)2-/\a.i.":461902 1 */0<(#,]*{.*1 _1$~#)2-/\a.i.":708143 1 */0<(#,]*{.*1 _1$~#)2-/\a.i.":1010101 1 */0<(#,]*{.*1 _1$~#)2-/\a.i.":123 0 */0<(#,]*{.*1 _1$~#)(}.-}:)a.i.":5 0 ``` Would be 3 characters shorter if 5 were considered undulant. [Answer] ## Haskell, 88 77 73 65 characters ``` z=tail>>=zipWith compare q[]=0>1 q s=all(/=EQ)$s++z s u=q.z.show ``` This requires the commonly used language pragma (or `-X` flag): `NoMonomorphismRestriction`. If you don't admit that, we have to add 4 characters and define `z` thus: ``` z s=zipWith compare s$tail s ``` [Answer] # Sage, 83 76 bytes ``` f=lambda x:uniq(cmp(*`x`[i-2:i][::(-1)^i])for i in[2..len(`x`)])in[[1],[-1]] ``` Got the idea to use cmp(\*[..]) from JBernardo. In Sage, `uniq(...)` is an alias for `list(set(...))`. Edit: just noticed that for x < 10, `uniq(cmp(...)) == []`, which isn't on `[[1],[-1]]`. If x were input as a string, instead of an integer, I could get another 4 characters out! [Answer] ### Python: ~~101~~ 100 characters Before minification: ``` undulate = (lambda n: n > 9 and all(cmp(*digits) == (i % 2) * 2 - 1 for i, digits in enumerate(zip(min(`n`,`n`[1:]), max(`n`,`n`[1:]))))) ``` After minification: ``` a=lambda b:b>9and all(cmp(*c)==d%2*2-1 for d,c in enumerate(zip(min(`b`,`b`[1:]),max(`b`,`b`[1:])))) ``` [Answer] ## Python, ~~134~~ 129 chars ``` def f(x):d=[cmp(*i)for i in zip(`x`,`x`[1:])]if x>9 else[0];n=d[0]>0;return all(i<0 for i in d[n::2])&all(i>0 for i in d[n<1::2]) ``` Ungolfed: ``` def f(x): if x>9: d = [cmp(*i)for i in zip(`x`,`x`[1:])] #difference of x[i] and x[i+1] else: d = [0] #trick to return False if x<10 using less chars n = d[0]>0 #First digit is -1 or 1? neg = d[n::2] #negative numbers if x is Undulant pos = d[not n::2] #positive numbers if x is Undulant #check if all negs are -1 and all pos are 1 and return value return all(i<0 for i in neg) and all(i>0 for i in pos) ``` [Answer] ## JavaScript, 88 chars ``` function _(i){i+='';c=i[0];f=i[a=x=1];for(g=f<c;d=i[x++];c=d)g^=a&=g?d<c:d>c;return!f^a} ``` In essence, turn the number into a string and compare adjacent characters, flipping the expectation for each. [Answer] # K, 41 bytes ``` {(x>9)&~max(=). 1_'-':'1_'(<':;>':)@\:$x} ``` E.g. ``` {(x>9)&~max(=). 1_'-':'1_'(<':;>':)@\:$x}1212130659 1b ``` [Answer] # CoffeeScript, ~~98~~ ~~67~~ 53 bytes ``` (n)->0!in((n[i]>=c^(n[0]<n[1])+i)%2for c,i in n[1..]) ``` Tests: ``` [ '01010101' # true '12345' # false '1010101' # true '887685' # false '9120734' # true '090909' # true ] ``` Uncompressed: ``` undulant = (n) -> direction = n[0] < n[1] return n.split('').every (cur, i) -> prev = arr[i-1] or 10 * direction +(prev >= cur) is (direction+i)%2 ``` [Answer] # J, 44 39 36 31 bytes ``` */2(0<#@],0>*/\)*2-/\".;' ',.": ``` Usage as before. I hadn't noticed that my last edit made the inequality with 0 check completely unnecessary. :-) Previous answer (+ explanation): ``` (0=+/2=/\u)*(1<#u)**/2~:/\2<:/\u=.".;' ',.": ``` Usage: ``` (0=+/2=/\u)*(1<#u)**/2~:/\2<:/\u=.".;' ',.":461902 1 ``` The answer has four parts: 1. `u=.".;' ',.":` This reads in the number as a string `":`, splits it into a list of characters preceded by spaces `' ',.`, stitches it back together `;`, converts it back to numbers `".` and then stores the result `u=.` This basically turns 461902 into 4 6 1 9 0 2 which I find easier to process in J. 2. `*/2~:/\2<:/\` This operates on the value stored in u. It takes each pair of characters and checks if the left one is less than or equal to the right one `2<:/\` so 4 6 1 9 0 2 becomes 1 0 1 0 1. It then takes the result of this and checks each pair of numbers for inequality `2~:/\` so 1 0 1 0 1 becomes 1 1 1 1. Finally it multiplies them all together to get either a 0 or a 1 `*/` At this point we could return the answer if it weren't for 2 things: a single digit returns 1 when the question requires a 0; and equal numbers are treated the same as 'less than' so 461900 returns 1 instead of 0. Bummer. On we go... 3. `(1<#u)` This checks if the number of items stored in u `#u` is greater than 1 and returns false if it's just a single digit number. 4. `(0=+/2=/\u)` This takes each pair of numbers stored in u and checks for equality `2=/\u`. It then sums the answers and checks if it has 0. The results of parts 2, 3 and 4 are then multiplied together to (hopefully) produce a 1 when the number meets the requirements specified in the question. [Answer] # Haskell, 82 bytes ``` c=cycle[(<),(>)] l!n=n>9&&and(zipWith3($)l(show n)$tail$show n) u n=c!n||((>):c)!n ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P9k2uTI5JzVaw0ZTR8NOM5YrRzHPNs/OUk0tMS9FoyqzIDyzJMNYQ0UzR6M4I79cIU9TpSQxM0cFyuEqVcizTVbMq6nRAOq2StZUzPufm5iZp2CrUFCUmVeioKJQqmBiZmhpYPQfAA "Haskell – Try It Online") [Answer] # Python, ~~119~~ 108 bytes ``` def u(x):l=[cmp(i,j)for i,j in zip(`x`,`x`[1:])];print x>9and all([i*j<0 for i,j in zip(l,l[1:])])and l!=[0] ``` [Answer] ## Python, 155 chars ``` g=lambda a,b:all(x>y for x,y in zip(a,b)) u=lambda D:g(D[::2],D[1::2])&g(D[2::2],D[1::2]) def U(n):D=map(int,str(n));return(n>9)&(u(D)|u([-d for d in D])) ``` [Answer] # C++, 94 chars ``` bool u(int N){int K,P,Q,U=1,D=1;while(N>9)P=N%10,Q=(N/=10)%10,K=D,D=U&Q<P,U=K&Q>P;return U^D;} ``` same method as my Erlang awnser with a for loop rather than recursion. [Answer] ## Python ~~105~~ ~~101~~ 100 chars ``` c=lambda r,t:len(r)<2 or(cmp(*r[:2])==t and c(r[1:],-t)) u=lambda x:x>9and c(`x`,cmp(*`x`[:2])or 1) ``` Recursive solution. `c(r,t)` checks if first char of `r` is less `(t==-1)` or greater `(t==1)` of second char, and call opposite check on shortened string. [Answer] # Perl/re, 139 bytes Doing **everything** in regex is kind of a bad idea. ``` /^(?:(.)(?{local$a=$1}))?(?:(?>((.)(?(?{$a lt$3})(?{local$a=$3})|(?!)))((.)(?(?{$a gt$5})(?{local$a=$5})|(?!))))*(?2)?)(?(?{pos>1})|(?!))$/ ``` I'm using Perl 5.12 but I think this will work on Perl 5.10. Pretty sure 5.8 is out though. ``` for (qw(461902 708143 1010101 123 5)) { print "$_ is " . (/*crazy regex goes here*/ ? '' : 'not ') . "undulant\n"; } 461902 is undulant 708143 is undulant 1010101 is undulant 123 is not undulant 5 is not undulant ``` [Answer] # GolfScript, 48 bytes ``` [`..,(<\1>]zip{..$=\-1%.$=-}%(\{.@*0<*}/abs ``` Hoping to beat J, my first time using GolfScript. Didn't quite succeed. [Answer] # JavaScript, ~~66~~ ~~65~~ ~~62~~ 60 bytes Takes input as a string, returns `true` for undulant numbers, an empty string (falsey) for single digit numbers and `false` otherwise. ``` ([s,...a])=>a+a&&a.every(x=>eval(s+"<>"[++y%2]+x,s=x),y=s<a) ``` --- ## Try it Run the Snippet below to test `0-9` and 25 random numbers `<10,000,000`. ``` f= ([s,...a])=>a+a&&a.every(x=>eval(s+"<>"[++y%2]+x,s=x),y=s<a) tests=new Set([...Array(10).keys()]) while(tests.add(Math.random()*1e7|0).size<35); o.innerText=[...tests].map(x=>(x=x+``).padStart(7)+` = `+JSON.stringify(f(x))).join`\n` ``` ``` <pre id=o></pre> ``` --- ## Explanation A few fun little tricks in this one so I think it warrants a rare explanation to a JS solution from me. ``` ()=> ``` We start, simply, with an anonymous function which takes the integer string as an argument when called. ``` [s,...a] ``` That argument is immediately destructured into 2 parameters: `s` being the first character in the string and `a` being an array containing the remaining characters (e.g. `"461902"` becomes `s="4"` and `a=["6","1","9","0","2"]`). ``` a+a&& ``` First, we concatenate `a` with itself, which casts both occurrences to strings. If the input is a single digit number then `a` will be empty and, therefore, become and empty string; an empty string plus an empty string is still an empty string and, because that's falsey in JS, we stop processing at the logical AND and output our empty string. In all other cases `a+a` will be truthy and so we continue on to the next part of the function. ``` a.every(x=>) ``` We'll be checking if every element `x` in `a` returns `true` when passed through a function. ``` y=s<a ``` This determines what our first comparison will be (`<` or `>`) and then we'll alternate from there. We check if the string `s` is less than the array `a`, which gets cast to a string in the process so, if `s` is less than the first character in `a`, `y` will be `true` or `false` if it's not. ``` s+"<>"[++y%2]+x ``` We build a string with the current value of `s` at the beginning and `x` at the end. In between, we index into the string `"<>"` by incrementing `y`, casting its initial boolean value to an integer, and modulo by 2, giving us `0` or `1`. ``` eval() ``` Eval that string. ``` s=x ``` Finally, we pass a second argument to `eval`, which it ignores, and use it to set the value of `s` to the current value of `x` for the next iteration. [Answer] ## PowerShell, 88 Naïve and trivial. I will golf later. ``` filter u{-join([char[]]"$_"|%{if($n){[Math]::Sign($n-$_)+1}$n=$_})-notmatch'1|22|00|^$'} ``` [My test cases](http://svn.lando.us/joey/Public/SO/CG3134/test.ps1). [Answer] # JavaScript, 112 ``` function(n,d,l,c,f){while(l=n%10,n=n/10|0)d=n%10,c?c>0?d>=l?(f=0):(c=-c):d<=l?(f=0):(c=-c):(c=d-l,f=1);return f} ``` You only need to pass it one argument. I could probably golf this further with a for loop. [Answer] # Erlang, 137 123 118 chars ``` u(N)->Q=N div 10,u(Q,N rem 10,Q>0,Q>0). u(0,_,D,U)->D or U;u(N,P,D,U)->Q=N rem 10,u(N div 10,Q,U and(Q<P),D and(Q>P)). ``` [Answer] # CJam, 30 bytes CJam is newer than this challenge, so this does not compete for the green checkmark, but it's not a winner anyway (although I'm sure this can actually be golfed quite a bit). ``` l"_1=\+{_@-\}*;]"_8'*t+~{W>},! ``` [Test it here.](http://cjam.aditsu.net/) ## How it works Firstly, I'm doing some string manipulation (followed by eval) to save 5 bytes on duplicate code: ``` "..."_8'*t+~ "..." "Push this string.": _ "Duplicate."; 8'*t "Replace the 8th character (the -) with *."; +~ "Concatenate the strings and evaluate."; ``` So in effect my code is ``` l_1=\+{_@-\}*;]_1=\+{_@*\}*;]{W>},! ``` First, here is how I deal with the weird special case of a single digit. I copy the digit at index `1` and prepend it to the number. We need to distinguish 3 cases: * The first two digits are different, like `12...`, then we get `212...`, so the start is undulant, and won't affect whether the entire number is undulant. * The first two digits are the same, like `11...`, then we get `111...`. Now the start is not undulant, but the number wasn't undulant anyway, so this won't affect the result either. * If the number only has one digit, the digit at index `1` will be the first digit (because CJam's array indexing loops around the end), so this results in two identical digits, and the number is *not* undulant. Now looking at the code in detail: ``` l_1=\+{_@-\}*;]_1=\+{_@*\}*;]{W>},! l "Read input."; _1=\+ "Prepend second digit."; {_@-\}* "This fold gets the differences of consecutive elments."; ;] "Drop the final element and collect in an aray."; _1=\+ "Prepend second element."; {_@*\}* "This fold gets the products of consecutive elments."; ;] "Drop the final element and collect in an aray."; {W>}, "Filter out non-negative numbers."; ! "Logical not."; ``` I'm sure there is a shorter way to actually check digits (of length greater 1) for whether they are undulant (in particular, without using two folds), but I couldn't find it yet. [Answer] ### Prolog 87 bytes ``` u(X) :- number_codes(X,C),f(C). f([_,_]). f([A,B,C|L]) :- (A<B,B>C;A>B,B<C),f([B,C|L]). ``` To run it, just save it as golf.pl, open a prolog interpreter (e.g. gprolog) in the same directory then do: ``` consult(golf). u(101010). ``` It will give `true` if the number is undulant, otherwise just no. [Answer] # Mathematica, 46 bytes ``` #!=Sort@#&&#!=Reverse@Sort@#&[IntegerDigits@n] ``` Examples (spaces are not required): ``` # != Sort@# && # != Reverse@Sort@# &[IntegerDigits@5] # != Sort@# && # != Reverse@Sort@# &[IntegerDigits@123] # != Sort@# && # != Reverse@Sort@# &[IntegerDigits@132] # != Sort@# && # != Reverse@Sort@# &[IntegerDigits@321] (* out *) False False True False ``` [Answer] ## Scala, 141 133 129 97 bytes ``` def u(n:Int):Boolean=n>9&&{ val a=n%10 val b=(n/10)%10 a!=b&&n<99||(a-b*b-(n/100)%10)<0&&u(n/10)} ``` With a = n % 10, b = (n/10) % 10, c = (n/100) % 10 ``` if a > b and b < c or a < b and b > c ``` Then `a-b * b-c` is either `x*-y` or `-x*y` with `x` and `y` as positive numbers, and the product is in both cases negative, but for `-x*-y` or `x*y` (a < b < c or a > b > c) the product is always positive. The rest of the code is handling special cases: one digit, two digits, two identical digits. [Answer] # Perl, 78 bytes ``` sub u{@_=split//,$_=shift;s/.(?=.)/($&cmp$_[$+[0]])+1/ge;chop;$#_&&!/00|1|22/} ``` [Answer] # Q, 71 bytes ``` {$[x>9;any all a=#[;(1 -1;-1 1)](#)a:1_signum(-':){"I"$x}each -3!x;0b]} ``` Sample usage: ``` q){$[x>9;any all a=#[;(1 -1;-1 1)](#)a:1_signum(-':){"I"$x}each -3!x;0b]} 5 0b q){$[x>9;any all a=#[;(1 -1;-1 1)](#)a:1_signum(-':){"I"$x}each -3!x;0b]} 10101 1b q){$[x>9;any all a=#[;(1 -1;-1 1)](#)a:1_signum(-':){"I"$x}each -3!x;0b]} 01010 1b q){$[x>9;any all a=#[;(1 -1;-1 1)](#)a:1_signum(-':){"I"$x}each -3!x;0b]} 134679 0b q){$[x>9;any all a=#[;(1 -1;-1 1)](#)a:1_signum(-':){"I"$x}each -3!x;0b]} 123456 0b q){$[x>9;any all a=#[;(1 -1;-1 1)](#)a:1_signum(-':){"I"$x}each -3!x;0b]} 132436 1b ``` [Answer] # [Julia 0.6](http://julialang.org/), 62 bytes ``` f(x,a=sign.(diff(digits(x))))=x>9&&-a*a[1]==(-1).^(1:endof(a)) ``` Takes in a number, returns `true` for Undulant, and `false` for not. Eg `f(163)` returns `true`. ``` f(x,a=sign.(diff(digits(x))))=x>9&&-a*a[1]==(-1).^(1:endof(a)) f(x, ) # function definition a=sign.(diff(digits(x))) # default 2nd argument is array of differences of signs of digits x>9&& # short circuiting and to catch cases under 10 -a*a[1] # make the first element of a always -1 ==(-1).^(1:endof(a)) # check that a is an array of alternating -1 and 1 of correct length ``` [Try it online!](https://tio.run/##VY7BCsIwEETv/YrYQ9mILaSRgEJE/AZvohBtElIkHjaF/H1cESHuwDCP2cPMyzMYVYqDvDEag48DTME5Mh8SQuZ0Oh92XdebtbmIq9bQCz7cQOxtnF4ODOdlwRA9Oxm0w9liao6JHG1i7SewBxXYsrv1IX47tnIgeJWl@hGBkn@wrR@VrMuRJIUcSbyhPeUN "Julia 0.6 – Try It Online") ]
[Question] [ Your task, should you choose to accept it, is to take two input values \$a\$ and \$b\$, where \$a\$ and \$b\$ are in the set \$\{T, U, F\}\$, and compute and output their logical conjunction in a [three-valued logic system](https://en.wikipedia.org/wiki/Three-valued_logic#Logics). A three valued logical conjunction is this transformation: | a | b | output | | --- | --- | --- | | U | U | U | | U | F | F | | F | U | F | | U | T | U | | T | U | U | | F | F | F | | F | T | F | | T | F | F | | T | T | T | ## I/O Rules You have to take as an input two characters \$a\$ and \$b\$, where \$a\$ and \$b\$ are `T`, `U`, or `F`. You have to output one of `F`, `T`, or `U`, with an optional trailing newline. These very restrictive I/O rules help prevent [trivial solutions](https://chat.stackexchange.com/transcript/message/61033556#61033556). ### Example Program (in Nim) ``` proc f(s: string): char = if s[0]=='F' or s[1]=='F':return 'F' if s[0]=='U' or s[1]=='U':return 'U' if s[0]=='T' and s[1]=='T':return 'T' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m704LzN3wYKlpSVpuhY3JxcU5ScrpGkUWykUlxRl5qVrWikkZyQWKdhyKShkpikURxvE2tqqu6kr5BcBOYYQjlVRaklpUZ4CkImiLBRZWShCWSiqshB1hcS8FJi6EIS6EJA6BajTjFOTM_KBTlMKCVHS5IJz3JA5oUicUCAHohXmOwA) [Answer] # Python, 22 bytes ``` lambda s:s["T"<s<"UT"] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYqjhaKUTJpthGKTREKfZ/Wn6RQqJCZp6CkhuQb8WlAAQgsSQ0MRAoKMrMK9FI1FFI0lFI00hU0FZI0tT8DwA "Python 3 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 24 bytes ``` lambda s:s[s in'TUF TF'] ``` [Try it online!](https://tio.run/##LYqxCoQwEERr8xXTqZxYXCmk3S9YK@@KiMoFNAlJrvDrc6scA8vbNxPO/PHuWTb9Krs55sUgDWlKsK7mkcBUv4s9go8Z6Uxq8xFXeT19yot1fVzNslu3pqYdFEyHuYP/5gANmYTd5qZVCNG6jK0xeGBuofW9KWMlUWNFFSkSJmEWw7env2e5fDML8w8 "Python 2 – Try It Online") **Alternative Solution** ``` lambda s:s[hash(s)/22%2] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 6 bytes ``` O%4µÞṪ ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJPJTTCtcOe4bmqIiwiIiwiIixbIlRVIl1d) ``` O%4µÞṪ Main Link Þ Sort by O ord (codepoint) %4 modulo 4 Ṫ Take the last character ``` -1 byte thanks to emanresu A by not closing the string -3 bytes thanks to Kevin Cruijssen by sorting the original characters instead of indexing back into "FUT" This at its core works the same as the original "map by `O%4` → take max → index back into `FUT`" but instead of actually indexing it just sorts by the `O%4` key which puts the max (the answer) at the end which is extracted with `Ṫ`. [Answer] # x86 32-bit machine code, 9 bytes ``` 37 38 D1 37 91 0F 42 C2 C3 ``` [Try it online!](https://tio.run/##XVJNa@MwED1bv2LqEioldgnNrdnspbC3vSwtLCQlyLJkCxTZWHJXJs1fr3fkhH5dLM2beW/mjSzaNq@EGMdrbYXpSwk/nC91c1v/JF8go4vvWKdtFTEig5edhfQhheN@zz1mit7L/Z5SxZ0X3BjGQNS8A0Wng2fnsGDrE@HuABT@pJTcVqYpuAFF1H3COSeJOLQgTAalIWcgiLoCKUIGkoeYb15EvGJcYtxJT1gKbE2Ith4OXFsaL7yrxKXnfI7BCyNHksQMMoc1CjXW@UuBgw2kv54eU8RbdOkVTeF15nY2X@R5vrNpBg5bJKrpgAasXq4hwNUGVnguFowkKJ60vY961G3Dc6x@B25eb6Z4og9n@nChDxP9o1ZN9Mxth2f2VWRnJ5XTx4w7@5uLWlsJoinlfRrT5@lIUjZwfPcyW979RQ/DhtLeOl1ZWU7W50yxLRrAcU/wr9ZGxvlwsGV4WLHP26AzDcXgpWPTNkJM4u57/A2w24mM45tQhlduzA@rO/zgI2@QK81/ "C++ (gcc) – Try It Online") Uses the `fastcall` calling convention, this takes two characters in CL and DL and returns a character in AL. In assembly: ``` f: aaa cmp cl, dl aaa xchg ecx, eax cmovc eax, edx ret ``` The character codes of F, U, T are 0x46, 0x55, 0x54 respectively. Notice that the low [nybbles](https://en.wikipedia.org/wiki/Nybble) are in descending order. `cmp cl, dl` sets flags based on the subtraction of the two given characters. In particular, the auxiliary carry flag (AF) is set based on carries across the centre of the byte, and it exactly indicates which character should be the result. The difficulty lies in getting that information out of AF. Unlike the rest of the status flags, AF cannot be used as the condition for a jump, move, or `SETcc`. It is used mainly by several instructions intended for handling [binary-coded decimal](https://en.wikipedia.org/wiki/Binary-coded_decimal). `aaa` is one of those instructions. (Its mnemonic stands for ASCII Adjust after Addition.) Helpfully, its opcode is only one byte. Its effect is: If AF=1 or the low nybble of AL is at least 10, add 0x106 to AL. Also, set both AF and CF based on the same condition. Afterwards, zero the high nybble of AL. The first `aaa` makes sure that the low nybble of AL is less than 10, so that after the `cmp cl, dl`, the second `aaa` sets CF to equal AF. Finally, the value of CF can be used to select the correct result. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` hox1C ``` [Try it online!](https://tio.run/##K6gsyfj/PyO/wtD5/3@lkFAlAA "Pyth – Try It Online") ``` Q implicit input o sort by key lambda N: N implicit element C character code point x1 bitwise XOR with 1 h first element ``` [Answer] # JavaScript (ES6), 18 bytes ``` s=>s[s>"T"^s>"UF"] ``` [Try it online!](https://tio.run/##ZYxBCoMwFET3nuKTVYTUC0jcNSf4WYUUxMbWIkZMdFN69vTXCoV0MwOPN/NotzZ0yzDH0@SvLvUyBdkEExqG7EKpFbOpNgWAAaY1E5QMrDiA@gD1A0pnQGM2wfxD/X1gBjA3cDeQQGGLqvfLue3unBsYpnmNAvwaqcGWIBt40mZ0ERYXQELPd6esiXZ@Cn501ehv/FiSJL6mPF7IfJXpDQ "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 7 bytes ``` 'FDl‡àu ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f3c0l51HDwsMLSv//D3EDAA "05AB1E (legacy) – Try It Online") Explanation: ``` 'F Push literal character `F` D Duplicate l Lowercase the duplicate ‡ Transliterate `F` to `f` in the input à Take the maximum u Uppercase ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 24 bytes ``` ->n{"FFTU"[n.sum/13-10]} ``` Input is taken as a single string. `n.sum` Adds together the ASCII codes of the input. This sum is modified by arithmetic, then used to index the string. [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsnNLSRUKTpPr7g0V9/QWNfQILb2f4FCWjRQQimWC8wKDYWxQkLgYnBZN4QsQgyhDs4CWhP7HwA "Ruby – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` ≬C4%Þ↑ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiaxDNCXDnuKGkSIsIiIsIlRGIl0=) ## How? ``` ≬C4%Þ↑ ≬ # Three element lambda: C # Convert to character code 4% # Modulo 4 # Lambda implicitly ends here Þ↑ # Maximum of the (implicit) input by this function ``` Also 6 bytes: ``` µC4%;t ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCtUM0JTt0IiwiIiwiVEYiXQ==) ## How? ``` µC4%;t µ ; # Sorting lambda C # Character code 4% # modulo four t # Last item ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 6 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` áÉ$4%╞ ``` Port of [hyper-neutrino♦'s Jelly answer](https://codegolf.stackexchange.com/a/246927/52210), after I golfed it a bit more. [Try it online.](https://tio.run/##y00syUjPz0n7///wwsOdKiaqj6bO@/9fKTRUiUsp1A1IuIFZIUAiBMRyA4uBuSBWSIgSAA) **Explanation:** ``` á # Sort the (implicit) input-string by, É # using the following 3 character as inner code-block: $ # Convert the character to a codepoint-integer 4% # Modulo-4 ("F"→70→2; "T"→84→0; "U"→85→1) ╞ # Remove the first character of the sorted string # (after which the entire stack is output implicitly as result) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 22 bytes ``` f(a,b){a=a%4<b%4?b:a;} ``` [Try it online!](https://tio.run/##bZHRToMwFIbv9xQnJISylWh0XmiHXhh5gu1KiGm7MolaFkoikfDqYoGu2zqbcNJz/v5f6F8e7Tjv@xxRzMKWxtRfrpi/fGIPlHR9IWv4ooVEIbQz0Iu/0wpqoeo3@ppBDG2wCTBMJbG7tW0T266DjjgIdopw3Jtzd3KJEM1e8FpsLyBHkjNzIKVU9Yia6yr4h6gmlJc2Lzdpc/@svzsPw2l/6xl3XlaAhngKuRWNtl0Ts12BKn5EmaPDD4ZXZjC3EwKLxXg6HGFTtvZmVONMxuOhjJzr7KCz/3Wl9eFBgYWOIrRic3O9@0rfJ0eezzH4HKLHofoqlTqDAYZBYZuUimORGXw36/pfnn/Sneqj7z8 "C (gcc) – Try It Online") Inputs two characters. Returns their logical conjunction. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 22 bytes ``` $0=/F/?"F":/U/?"U":"T" ``` [Try it online!](https://tio.run/##SyzP/v9fxcBW303fXslNyUo/FEiHKlkphSj9/x8ayhXqxuUGJEO4QkK53IBsIMONKyQEAA "AWK – Try It Online") *As short as Python!* #TeamAWK Sets the input `$0` to the result of that ugly conditional. Because the assigned value is not false (i.e., not null/empty nor zero), AWK considers it a true pattern, and prints `$0`. ``` $0= Assigns to $0 the result of: /F/? Is there an F in the input? "F" If so, it's now F. : Otherwise... /U/? Is there an U in the input? "U" If so, it's now U. : Otherwise... "T" It's T, then. ``` [Answer] # [Vyxal](https://vyxapedia.hyper-neutrino.xyz), 7 bytes ``` \F:ɽĿGɾ ``` Ported from [Neil's 05AB1E answer](https://codegolf.stackexchange.com/a/246939/111322); make sure to upvote that answer as well! Explanation: ``` \F Push literal character `F` : Duplicate ɽ Lowercase the duplicate Ŀ Transliterate `F` to `f` G Take the maximum ɾ Change to uppercase ``` [Try it online!](https://vyxapedia.hyper-neutrino.xyz/tio#WyIiLCJcXEY6yb3Ev0fJviIsIiIsIiIsIlRUIl0=) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~15~~ 13 bytes ``` 1`T O`. 1!`. ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7w3zAhhIvLP0GPy1AxQe///9BQrlA3LjcgGcIVEsrlBmQDGW5cISEA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` 1`T ``` Delete the first `T`, if any. ``` O`. 1!`. ``` Take the minimum. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~8~~ 7 bytes ``` ⌊∨⁻θT¦T ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3My8ztzRXw78IxCwt1ijUUVAKUdKEkJrW//@HhPzXLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: If the string only contains `T`s then output `T` otherwise output the minimum of the other character(s). ``` θ Input string ⁻ Remove any occurrences of T Literal string `T` ∨ Logical Or T Literal string `T` ⌊ Take the minimum Implicitly print ``` [Answer] # [brainfuck](https://esolangs.org/wiki/Brainfuck), 97 bytes ``` ,[->+>+<<]>>>,[->+>+<<]++++++++++[-<------->>>-------<<]<[>>>[<<+++++[-<--->>>---<<]<[>>>[-]]]]<. ``` Takes in inputs as you would expect, and outputs as you would expect. Copy the input characters to do math on them while preserving the original. The math is just subtracting 70 ('F'), returning 'F' if either is 0 now, then subtracting 15 ('U' - 'F' == 15), returning 'U' if either is 0 now, otherwise return 'T'. It's 3:30 a.m. as I'm writing this, so I may comment the code when I wake up. [Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ1rXTttO28Ym1s7ODsHRhoNoXRtdCAAqgLKACmyigdxoGxskNRB5uJxuLBDY6P3/HxICAA "brainfuck – Try It Online") A slightly different approach with 98 bytes ``` ,[->+>>+<<<],[->>+>>+<<<<]>>>>>++++++++++[-<-------<------->>]<[<[>>+++++[-<---<--->>]<[-]]]<<. ``` [Answer] Since this function's output is always one of the inputs, it can be executed using a pure regex. This is done by picking an `F` if one exists, or otherwise picking a `U` if one exists, or otherwise picking a `T`. # Regex (Perl / PCRE / Boost), ~~13~~ 11 bytes ``` .?\KF|T?\K. ``` -2 bytes thanks to m90! Returns the result in the match. [Try it online!](https://tio.run/##LYzBCoJAFEX38xUPGTApHVu0GrUEm03QamaVMVQkCKYyY4swW/YBfWI/Yo9qc@897/JuezbVYrzcgBoOfdWcDhVQxhHjKEtlmgykaMyE2jjkUcK9HsoCyetbU9YdOHnt8AHbOb5oiB9gWV4zHPj1VHNg1DBO4H9x4f18gRvY69F2OKxnsPJ34R5tiuZ/weOD1uttpvUYLPONuEvUYByVIkoQgSqJVERgxiCIlB8 "Perl 5 – Try It Online") - Perl [Try it on regex101](https://regex101.com/r/YAnkSV/3) - PCRE [Try it online!](https://tio.run/##XVFNT@MwED3Xv2LoHnAgLXSROCQtSEibCxKHVSrtqlSRcd3EIrUt21Ghpdf9AfsT94ds1h@gBXwYTWbevPdmQpUa1ZT2X7igbbdiMH2Q0tgzzWr2NG6UukK0IRoqtVjCDL4Pb7bbx4eL7ufz84@yudw2uB9f398WL6WL4z753B6mcKJmlTqd5Oi/BncSmpHNFeLCgtIuVkxrqTGVwlgIkicbZgypWbI3dpVl1AFgOoXXqk9DnYlVm4NmttMCJvkhUG4IFziBPQL31MKptUxglYwmy9l5Dp3DXHytLEj/5QdqlwRw4HR4LmrXUJ3NIXoKd8mycBgnh1X6oZRlnBLDkvytajbE0ga2DbGReS01YK@186JBp2a25YLhuCAXaZR0JLvZ5M2@f3wNeJfEISo767c/vhfHORr41tF7J5VhRNMGB6o0GEid4SRBg8EHguE3f/IjuJMQvUoBQ9@Ie6MBaw37PBR6YRr@/Pod8V5icb6Max5CfP0f7qiHfj5H8wIVLpaonKPC5S4pUFn@peuW1KYftWGBKvj/Bw "C++ (gcc) – Try It Online") - Boost The `\K` feature is used to discard the first character of the input if `.?` or `T?` needed to be used to skip it. # Regex (Java / Python / Ruby / .NET / ECMAScript 2018), ~~18~~ 15 bytes ``` (.?(?=F)|T?)(.) ``` -3 bytes thanks to m90's idea Returns the result in capture group 2. [Try it online!](https://tio.run/##bVJLbtswEN3rFBMBQUjXZYBuBcFAgGjVBEUtr9ouKImy6VCkSlKxC9fbHqBH7EWcIaUYTWAJEIcz896bj7b8mX/cNk8n2fXGetjinUnDZhn87xm8VBd9VqzFHiNJP1RK1lAr7hw8cKnhAJPPee7xeDaygQ4jZOmt1Gvgdu2@/aDgN9bsHNzva9F7aRCZABRSCWhzLXbRJCmrTSMYxlOa3Q1tK6xovgreCAtVTHvrJK/I6dpSmk26bu6z3SaQEpdX2AJvPkstCKVXuR6UorIljomfA1eOpLez2Syl9PA29ZXAXyQ4IIM/MyDBLTJUmPeUuQ/5zXd9E06fHUff8Qv3XlgNNp8sbLbrg4CjGQ5jWXOtsVGp@8FDDqG3yUeWv5wXHZOaZlAZowTXoPMWlUWAxjqBRCTbcPco9h4Lxe1gjZpOaIPBHofjlcbeEO/tEOGoPQ5NYYOoPPJoJJnmEHMeuK83WF@HGZZ1440EyJQgWyAda6VuRu33si1Jrx38@/MXrl06j2Jz6NjamqEnn3B1cIw8AruC83OR595aY6/g0UCsA/B/OnMGnvAek7DVE2ELssgL@rtcUMLoKSzqtFolqyIp8Fsm5Sop0EajSMryBQ "Java (JDK) – Try It Online") – Try It Online") - Java [Try it online!](https://tio.run/##NY1BCsIwFET3OcWnmyZYQ4u7ltBdTpCuaheiUSNpUn4iKrj2AB7Ri9RUcDN/GP6bmR7x7N1mNuPkMUJ4hAL1Sd@LS/CuARSYZdlMeUtbIdlTtYxyNqesr@p1NTRgREmOHsGCcQvOQzwYVxMwR7DaUctg5w5g@/QtRL51eQ1W2L5ccAKj@M3xoHe4P1MswLIfO6aK5ZoaJjQuUtYsgaia/4q/Rn5DEzW1qxw@rzfkq5Gf0F@nQFlfDWzuOtJJIpMqojoik09GEqW@ "Python 3 – Try It Online") - Python [Try it online!](https://tio.run/##NY5BCsIwEEX3OcVYhLZQQ@vSEErRRtxU0HSlpShGLYRSYkUFcekBPKIXqRPFxQx/Hv9/xpy3t84Ah4U6qGtDa3WBSSITatRmF/zgaDSbZvNFOk6WKYOKhwwux0or0Pyg2hOiPejVICo4d9a1w5DrVUjpYFgwUPWOEbCWqmeTzdkmLMWmCG9T1S1o69H4Bs4DzB@78H6@wA36w2@ElGWaTcqy82jsxVz4dxn7HvW7Ls9JLojALYnMiUCNQhApPw "Ruby – Try It Online") - Ruby [Try it online!](https://tio.run/##RY09CoMwHMX3nCJIwASqtB0VUShk6xYncRD7twZiIlGxaF17gB6xF7GBDl0e7wN@rzcz2KEFpXZik8LCHR5lFGmYaebvNExpmnD2FCmjIdv97OBdTNdLBTePxWRJjnFjLFR1S4nCUmMidT@NbJUNJV1CbHitxrqFwc3s1y5sna0cIWjNMG4OcYr/GQfauG8lNWDPET@vNyaOFN6tmfqhOJfM27Y9z1HOEXcqkMgRd94ZjoT4Ag "PowerShell – Try It Online") - .NET [Try it on regex101](https://regex101.com/r/YAnkSV/6) - ECMAScript 2018 This is based on the PCRE regex, using lookahead and group capture to replace the inavailability of `\K`. ## Regex (.NET), 15 bytes ``` .?(F)|T?(?<1>.) ``` Returns the result in capture group 1. [Try it online!](https://tio.run/##RY09CsIwHMX3nCKUQBOwwa7W2oKQzS2dxEH0bxtIk5KmVKpdPYBH9CI14ODyeB/we50dwfUNaL0Qlx8d1HA/bTYGRlrGCy@oYE9Z0GKb7jhb4nIV7W3bKQ3XiGVkytfZzTo4XxpKNFYGE2W6wbOHulHS5sTxw9lfGujDzH7txB6jUx6SxvZ@Dog0@2ecGBu@tTKAo0D8vN6YBBKvnR26/pieWDTPS1WhSiARVCJZIRF8MAJJ@QU "PowerShell – Try It Online") It was only possible to make a shorter .NET version thanks to m90's suggestion. This is done using the .NET-specific feature of aliasing a capture group. It could be done in PCRE using a Branch Reset Group, `(?|.?(F)|T?(.))`, but that's 15 bytes, longer than the existing 11 byte solution. This is now merely tying with the above solution. [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 67 bytes ``` i =input i 'F' . x :s(o) i 'U' . x :s(o) x ='T' o output =x end ``` [Try it online!](https://tio.run/##K87LT8rPMfn/XyFTwTYzr6C0hAvIUndTV9BTqFCwKtbI1wQLhKIIVCjYqoeoc@Ur5JeWALUo2FZwpeal/P8fEgIA "SNOBOL4 (CSNOBOL4) – Try It Online") [Answer] # C, 25 bytes ``` f(x,y){return y-x&8?x:y;} ``` [Try it online!](https://tio.run/##VZC7boMwFIZn@ylOqZrYYFeRslSlJFueoJmAATnhIrUmsk1kK@HZiXFRq07n9n3/cARvhJimmljm6E2dzaAkOG5Xb3v77tJxeu6k@BpOZ/jQ5tT1r@0Od9LAd9VJMjeVagQD0VYK4tgPV4pvGM0Xy8ClGIlearMAGjKIDsfPyO8vykM1ieD@ogvJE855ISMGmvpj3Ssg1tObFCw8ZbD1NUkoRj4cXQYz5xGd23Kmfxfr@zrMQXc/ult0F/Q/tg4607kr6f@QQoaUEaPlH5sUj9MD "C (gcc) – Try It Online") This uses the same observation as my previous answer: the character codes of F, U, T are 0x46, 0x55, 0x54 respectively, and their low [nybbles](https://en.wikipedia.org/wiki/Nibble) are in descending order. The low nybble of the result of the subtraction is -2, -1, 0, 1, or 2 (modulo 16), and its high bit (the 8s bit) indicates whether it is one of the negative possibilities. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~75~~ 69 bytes 6 bytes saved by improving `U -> F` conversion from subtract 1x15 to subtract 3x5. ``` ,>,[<<+>->-]<[>-[--->+<]<-[>]>[>+<<]<++[>]>[>+<<]>>-[++[<----->-]]]<. ``` [Try it online!](https://tio.run/##RYsxCoBADAQflFtfsGzpC@xCChUEObA4uPfHWLnVDMweY7@fa549s6k5aYIQdMEByBiEK@SFxWa/qJpy4ludIrhkrtsL "brainfuck – Try It Online") Developed at <https://minond.xyz/brainfuck/> (additional `>` characters are needed at the beginning and end of the program there due to lack of support of negative memory indices and to avoid auto re-run.) Subtracts one input from the other. * If they are the same, output one of the inputs * If they differ by 1 (`UT` or `TU`) output `U` * Otherwise output `F` **Commented** ``` ,>, Input into cells 0 and 1 [<<+>->-] Decrement cell 1 while copying its contents into cell minus 1; Simultaneously decrement cell 0 < Leave the pointer at cell 0 which contains the difference between the inputs [ If difference is nonzero >-[--->+<] Subtract 1 from cell 1 giving 255 then loop until cell 1 is 0 and cell 2 is 255/3 = 85 ASCII U <-[>]>[>+<<] Subtract 1 from cell 0; If nonzero take step to right; now take a further step right If cell 0 was nonzero we are now at cell 2 containing 85; add 1 to cell 3 then step back left <++[>]>[>+<<] Add 2 to cell 0; if nonzero use the same procedure as above to increment cell 3 >> Move to cell 3; If cell 2 remained nonzero through all steps above cell 3 is now 2 otherwise 1 -[++[<----->-]] Subtract 1 from cell 3; If nonzero boost it to 3 then subtract 3x5=15 from cell 2 ] changing it to 70 ASCII F <. Take 1 step left from current position and output result ``` [Answer] # [Python](https://www.python.org), 37 bytes ``` lambda s:s=="TT"and"T"or"UF"["F"in s] ``` Or alternatively for the same byte count ``` lambda s:["UF"["F"in s],"T"][s=="TT"] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3VXMSc5NSEhWKrYptbZVCQpQS81KUQpTyi5RC3ZSildyUMvMUimOhitsKijLzSjTSNJRCQ5U0NbkQXDcUrhuabAgKNwRV1g1NL5piVNkQkCzENQsWQGgA) [Answer] # [C (GCC)](https://gcc.gnu.org), ~~38~~ ~~33~~ 29 bytes ``` f(char*s){*s=s[*s%4<s[1]%4];} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBgqWlJWm6FnvTNJIzEou0ijWrtYpti6O1ilVNbIqjDWNVTWKtayFqbi7JzCtRyE3MzNPQrObiBKlXKI6OVbBVUAoJdVOyhgpVQIQiIoAiXJxp-UVgkxW0Em2LrYGktYK2dqImFyeSTBJYJgkkkwSS4ayINoi11UrUAZplCGQk6SikaVRo6igUFAFdkKahpJqsAEYxeUo6CiB1ICVaFZrWnFxQt8L8BQA) Returns the desired output in `*s`. [Answer] # [Nim](https://nim-lang.org/), 55 bytes ``` proc f(a,b:char):char=(if int(a)%%4<int(b)%%4:b else:a) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m704LzN3wYKlpSVpuhY3zQuK8pMV0jQSdZKskjMSizTBpK1GZppCZl6JRqKmqqqJDYiVBGJZJSmk5hSnWiVqQrRvSE3OyAfqVg9R11FQD1WHCsNMBwA) Port of [this](https://codegolf.stackexchange.com/a/246961/104836) C answer. [Answer] # [A0A0](https://esolangs.org/wiki/A0A0), 92 bytes ``` I1L84S2M2V0G0 G-1G-1G-1G-1G-1 I1 G5 I1V0P0 G-1G-1 I1L84S2M2V0G0 G-1G-1G-1G-1G-1 P70 G2 P85 ``` We first read input from stdin and then compare the ascii value of the character against 84 ('T'). ``` I1 L84 S2 M2 V0 G0 G-1 G-1 G-1 G-1 G-1 ``` 'F' will be less than this and the operand becomes -1. 'T' is the same, so the opernad becomes 0 and 'U' is higher, so the operand becomes 1. We then jump to three different places depending on this value. The first place is when the character is 'F'. ``` I1 G5 ``` Since every comparison against F will be an F, we only ask input because we must read two numbers - the input is never stored. We then jump five lines below which prints F. ``` I1 V0 P0 G-1 G-1 ``` If the first input was T, then the result will simply by the second input. We read the second input and print it. ``` I1 L84 S2 M2 V0 G0 G-1 G-1 G-1 G-1 G-1 ``` If the input is U, then we need to do a slightly more complex check. We read input and do another comparison against 84, jumping to three different places. Since we now know that the first input is U, each of these places can directly print the appropriate result: 'F' for 'F' and 'U' for both 'T' and 'U'. There are some slight optimizations made by only having a print instruction for each character once and then jumping towards this print from other places. Since the code has few lines, the instructions for jumping will be two bytes, whereas printing will be three bytes due to the double digit ascii value. [Answer] # [Factor](https://factorcode.org/), 25 bytes ``` [ [ 4 mod ] supremum-by ] ``` [Try it online!](https://tio.run/##JY6xDsIwDET3fsUpUkeQQEwgGEEsLNCpdEhTl0Y0SYmTga8vVpmsu/d0cq9NCnGu7tfbZQ@n0wCmTyZviJe4NsG11muxrGG8KXoa0YcoMFn/Aqcoh3EoCnWuHgpbWRjJJBs8zzVq7OBChwacp0guu1X7RSOky5O00k2BSbzNfwqqZBxPKPnplWDrUy@e/LF4pM0w/wA "Factor – Try It Online") [Answer] i matched the best `awk`'s 20-bytes with a very different approach ``` echo 'U\nB\nF' U B F echo 'U\nB\nF' | mawk -F\[^FU] NF=NF OFS=T | gcat -n 1 U 2 T 3 F ``` ]
[Question] [ # Loading Circle Animation ## Challenge Write a full program that takes no input (or has an unused input) that displays exactly the following ASCII animation for as long as possible or only 8 frames. Frame 1: ``` # # # # ## ``` Frame 2: ``` ## # # ## ``` Frame 3: ``` ## # # # # ``` Frame 4: ``` ## # # # # ``` (Note that the line at the end is empty.) Frame 5: ``` ## # # # # ``` Frame 6: ``` ## # # ## ``` Frame 7: ``` # # # # ## ``` Frame 8: ``` # # # # ## ``` (Note that the line at the start is empty.) ## Rules * The program takes no input (or has an unused input). * The animation can start at any frame, but must animate in sequential order. * The animation can be in reverse order. * The program has to run as long as possible or for exactly 8 frames. * The animation has to be displayed at the same position on screen for every frame. * Trailing/leading whitespace is okay, as long as the animation looks right. * `#` and space can be replaced with different (not a newline) distinct characters that are each 1 byte. * There should be an additional pause of any length but more than 0 ms after an entire frame is drawn. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # [convey](http://xn--wxa.land/convey/), 108 bytes You never said that the program must have an output, you said in fact "a program that displays exactly the following ASCII animation" And my program has that animation inside it: ``` >>,'######'[ ^<v ^< >>>v >>>v >,<<< ,<<< ^ >v'######'[ ^<< >^,'######'[ >>^ ^<< '######'[ ``` [Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiICAgID4+LCcjIyMjIyMnW1xuICAgIF48dlxuICAgICBePCBcbiA+Pj52ICA+Pj52XG4+LDw8PCAgLDw8PFxuXiAgICA+dicjIyMjIyMnW1xuXjw8ID5eLCcjIyMjIyMnW1xuPj5eIF48PFxuJyMjIyMjIydbIiwidiI6MSwiaSI6IiJ9) Here is the program runing: [![enter image description here](https://i.stack.imgur.com/Kxebi.gif)](https://i.stack.imgur.com/Kxebi.gif) And in the center you can see... THE LOAD ANIMATION :v [![enter image description here](https://i.stack.imgur.com/MOyEi.gif)](https://i.stack.imgur.com/MOyEi.gif) Really the programs doesn't start by an state of the animation, it waits 2 cycles before start but... its cool... i supose? [Answer] # [CP-1610](https://en.wikipedia.org/wiki/General_Instrument_CP1600) machine code, 33 DECLEs1 ≈ 42 bytes2 *1. A CP-1610 opcode is encoded with a 10-bit value (0x000 to 0x3FF), known as a 'DECLE'.* *2. As per the exception described in [this meta answer](https://codegolf.meta.stackexchange.com/a/10810/58563), the exact score is **41.25 bytes** (330 bits)* Uses `$`'s and spaces. Loops forever. Each frame is displayed during ~650 ms. This is a full program mapped in the memory range $4800-$4820. (The Intellivision bootstrap code will jump at $4800 after a reset if it finds something there.) ``` BT EQU $200 ; BACKTAB address ROMW 10 ; 10-bit ROM ORG $4800 ; map the program at $4800 4800 0002 EIS ; enable interrupts 4801 02B8 007E MVII #$7E, R0 ; load %01111110 in R0 4803 0044 SWAP R0, 2 ; expand it to %0111111001111110 4804 00BD loop: MOVR R7, R5 ; \_ R5 = pointer to 4805 02FD 0013 ADDI #p-$, R5 ; / BACKTAB positions 4807 0081 draw: MOVR R0, R1 ; copy R0 to R1 4808 03B9 0020 ANDI #32, R1 ; isolate the 6th bit 480A 02F9 0007 ADDI #7, R1 ; add 7 to draw in white 480C 02AA MVI@ R5, R2 ; load the position in R2 480D 0251 MVO@ R1, R2 ; write the character 480E 0058 SLLC R0 ; \_ rotate the pattern 480F 0028 ADCR R0 ; / to the left 4810 0092 TSTR R2 ; is R2 equal to 0? 4811 022C 000B BNEQ draw ; if not, draw again 4813 0012 idle: DECR R2 ; idle loop: decrement R2 4814 022B 0002 BMI idle ; until it looks positive 4816 0220 0013 B loop ; restart ; positions 4818 0229 023D ... p: DECLE BT+41, BT+61, BT+82, BT+83 481C 0240 022C ... DECLE BT+64, BT+44, BT+23, BT+22 4820 0000 DECLE 0 ``` ## Output [![output](https://i.stack.imgur.com/QdOyL.gif)](https://i.stack.imgur.com/QdOyL.gif) *made with [jzIntv](http://spatula-city.org/%7Eim14u2c/intv/)* [Answer] # HTML5 + CSS3, ~~190 + 98 = 288~~ ~~162 + 102 = 264~~ 86 + ~~170~~ ~~166~~ 165 = ~~256~~ ~~252~~ 251 bytes ``` tt{--c:1}div{--c:2}div tt{--c:3}a+a{--d:calc(7 - var(--c,0))}a{animation:a steps(4,start)1s calc(var(--d,var(--c,0))/8*-1s)infinite}@keyframes a{to{visibility:hidden ``` ``` <pre> <a>#</a><a>#</a> <tt><a>#</a> <a>#</a><div><a>#</a> <a>#</a> <tt> <a>#</a><a># ``` Explanation: This is based on my Stack Overflow answer to Imitating a blink tag with CSS3 animations, however the number of steps is set to 4 to reduce the duty cycle from 80% to 75% and CSS variables are used to offset the animation of each `#` character. Edit: Saved at least 24 bytes thanks to @IsmaelMiguel. Saved 1 byte by stealing @ccprog's `1s/8` trick. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~21~~ 19 bytes ``` RFχ⁸GH*²⮌…“⊟4«L”⁺⁸ι ``` [Try it online!](https://tio.run/##FcFBCoQwDADArwS9RMnC6kn0KIhH8QdSohWCkRYrvj67zji/BKeLmM28Bo5@0IDVl6ApYFJ5Nj1GFdEb25KgJpg5cYiM/eOEe68nZvkLIM8IJrkiNgR78deZ2SfJDw "Charcoal – Try It Online") Link is to verbose version of code. Outputs 8 frames. Explanation: ``` RFχ⁸ ``` Repeats 8 times with a 10ms delay in between each repeat, dumping the canvas to the terminal each time. (Note that this just shows up as control characters in TIO.) ``` GH*²⮌…“⊟4«L”⁺⁸ι ``` Draw an octagon using the multidirectional `*`, which means all directions in turn, in the order right, down right, down, down left, left, up left, up, up right. Each side of the octagon is 2 characters long, and the octagon is drawn using a cyclic permutation of the string `# #####` (obtained through reversing the cyclic extension of `##### #` which then gets implicitly truncated to 8 characters) depending on the loop index. For offline use you may prefer 1 second frames for the same byte count: ``` RFφ⁸GH*²⮌…“⊟4«L”⁺⁸ι ``` The animation can be extended to 1000 frames (125 whole cycles) at a cost of two bytes: ``` RFχφGH*²⮌…“⊟4«L”⁺⁸﹪ι⁸ ``` [Try it online!](https://tio.run/##FcHBCoJAEAbgV/nRyxgTrJ2kjkJ0EcQ3kG1qg6GJXVR8@gm/L6Y5R5vVfZJXlpLulqkNjDaE0GA03d/2fZiqbXQ9MS6MSVbJRajfo0qf7EdVfQDqijHqUqhjDPZc1OjD6JrDzd3Pq/4B "Charcoal – Try It Online") Link is to verbose version of code. Or with 1s frames: ``` RFφφGH*²⮌…“⊟4«L”⁺⁸﹪ι⁸ ``` An infinite animation would take ~~27~~ 25 bytes (10ms and 1s frames): ``` RWχ¹«GH*²⮌…“⊟4«L”⁺⁸﹪φ⁸≦⊕φ RWφ¹«GH*²⮌…“⊟4«L”⁺⁸﹪φ⁸≦⊕φ ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~39~~ 34 bytes ``` `3&Xx0'=<.Ic^w'FO8:@YShZah4eH>ZcDT ``` Try it at [MATL online!](https://matl.io/?code=%603%26Xx0%27%3D%3C.Ic%5Ew%27FO8%3A%40YShZah4eH%3EZcDT&inputs=&version=22.4.0) ### How it works ``` ` % Do..while 3&Xx % Pause for 300 ms and clear screen 0 % Push 0 '=<.Ic^w' % Push this string (*) F % Push false (**) O % Push 0 8: % Push [1 2 ... 8] @ % Push current iteration index, k YS % Rotate right by k units. For example, in the 1st iteration % (k=1) this gives [8 1 2 3 4 5 6 7] h % Concatenate: prepends 0. This gives [0 8 1 2 3 4 5 6 7] % in the 1st iteration Za % Base conversion. Converts the string (*) from the base % formed by all printable ASCII chars except single quote % (represented by the false input, (**)) to the base (***). % This gives [6 5 0 7 0 0 4 8 0 0 3 0 1 2] in the 1st iteration h % Concatenate: prepends 0. Gives [0 6 5 0 7 0 0 4 8 0 0 3 0 1 2] 4e % Reshape into 4-row matrix in column-major order. This pads with % a 0 at the end to have a number of entries multiple of 4. Gives % [ 0 7 8 0 ; % 6 0 0 1 ; % 5 0 0 2 ; % 0 4 3 0 ] % in the 1st iteration. For other iterations the nonzero values % will be rotated with respect to the above H> % Greater than 0? Gives % [ 0 1 1 0 ; % 1 0 0 0 ; % 1 0 0 0 ; % 0 1 1 0 ] Zc % Convert nonzeros to '#' and zeros to char 0 (shown as space) % [ ' ## ' ; % '# ' ; % '# ' ; % ' ## ' ] D % Display T % Push true % End (implicit). A new iteration is run because the top of the % stack is true ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~60~~ 55 bytes Full program. Requires 0-based indexing. Uses `0` and `1` instead of and `#`. Waits 1 seconds between frames and stops after the 8th. ``` ⎕ED&'a'⋄{⎕DL≡a∘←⊃⍤⍕¨4 4⍴'012080037004065'∊⍕1+8|⍵+⍳6}¨⍳8 ``` `'a'` the (eventual) variable name "a" …`&` in a background thread:  `⎕ED` open an EDit window on that name `⋄` then: `⍳8` generate the **i**nteger sequence 0…7 `{`…`}¨` on each element of that, apply the following anonymous lambda:  `⍳6` generate the **i**nteger sequence 0…5  `⍵+` add the argument to that  `8|` find the division remainder of that when divided by 8  `1+` increment that  `⍕` format as space-separated text  `'012080037004065'∊` for each character in this string, check if it is a member (`1`) or not (`0`) of that string  `4 4⍴` reshape those 16 `1`s and `0`s into a 4-by-4 matrix  `⍕¨` format each of those numbers as a 1-character list `⊃¨` get the first character of each  `a∘←` globally assign that value to the variable `a` (the edit window will update)  `≡` get the nesting depth of that matrix (it is 1)  `⎕DL` DeLay that many seconds Old version in action: [![screencast](https://i.stack.imgur.com/BkHyP.gif)](https://i.stack.imgur.com/BkHyP.gif) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [2¾6×2úN._7Ý.Λ,т.W’IEx.Helpers.Ї’.E ``` If only 05AB1E had a builtin to clear the console.. :/ Starts at frame 6, and rotates indefinitely in reversed order. Uses `0` instead of `#` as character, although could alternatively use `1`/`2` for the same byte-count by replacing the `¾` with `X`/`Y` respectively. Sleeps for 100 ms between each print, but could alternatively sleep any of these times for the same byte-count: `1`/`2`/`3`/`4`/`5`/`6`/`7`/`8`/`9`/`T` (10)/`₂` (26)/`₆` (36)/`₃` (95)/`₅` (255)/`₁` (256)/`₄` (1000), by replacing the `т`. **Explanation:** ``` [ # Loop indefinitely: 2 # Push 2 ¾ # Push 0 6× # Repeat it 6 times as string: "000000" 2ú # Pad with 2 leading spaces: " 000000" N._ # Rotate the string the loop-index amount of times towards the left 7Ý # Push list [0,1,2,3,4,5,6,7] .Λ # Use the modifiable Canvas builtin with these three options , # Pop and print it with trailing newline т.W # Sleep for 100 ms ’IEx.Helpers.Ї’ # Push dictionary string "IEx.Helpers.clear" .E # Evaluate and execute it as Elixir code ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `’IEx.Helpers.Ї’` is `"IEx.Helpers.clear"`. The Canvas Builtin uses three arguments to draw a shape: * Length of the lines we want to draw * Character/string to draw * The direction to draw in, where each digit represents a certain direction: ``` 7 0 1 ↖ ↑ ↗ 6 ← X → 2 ↙ ↓ ↘ 5 4 3 ``` `2¾6×2úN._7Ý` creates the following Canvas arguments: * Length: `2` * Characters: `" 000000"` (potentially rotated) * Directions: `[0,1,2,3,4,5,6,7]`, which translate to \$[↑,↗,→,↘,↓,↙,←,↖]\$ [Try the first two steps online.](https://tio.run/##yy9OTMpM/f//SOO5red2WhxeE6wUZ1dmo2R2uPVwx6OGhf//l9mBBOJsAA) Step 1: Draw 2 characters (`" "`) in direction 0/`↑`: ``` ``` Step 2: Draw 2-1 characters (`"0"`) in direction 1/`↗`: ``` 0 ``` Step 3: Draw 2-1 character (`"0"`) in direction 2/`→`: ``` 00 ``` Step 4: Draw 2-1 character (`"0"`) in direction 3/`↘`: ``` 00 0 ``` etc. Step 7: Draw 2-1 character (`"0"`) in direction 6/`←`: ``` 00 0 0 00 ``` Step 8: Draw 2-1 character (`" "`) in direction 7/`↖`: ``` 00 0 0 00 ``` [See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210) I don't have a gif to see the animation in action, because `IEx.Helpers.clear` (or any clear through Elixir-eval for that matter) doesn't seem to work on Windows machines.. I tried to enable ANSI escape codes in the Windows Console by modifying the Registry on my PC, but wasn't able to get it to work. This should work as intended on a non-Windows machines, though. As alternative, here the outputs where the clear-command is ignored and the infinite loop `[` is replaced with a loop of eight `8F`: [Try it online](https://tio.run/##yy9OTMpM/f/fws3o0D6zw9ONDu/y04s3PzxX79xsnYtNeuGPGmYqebpW6Hmk5hSkFhXrHV3wqGGhElBUz/X/fwA). [Answer] # [Stax](https://github.com/tomtheisen/stax), 32 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` éÄû?*&╬_ÅuQ☼Ñï|Σ░♦ë♣∞î,↑&èå#QWÉ╡ ``` [Run and debug it](https://staxlang.xyz/#p=828e963f2a26ce5f8f75510fa58b7ce4b0048905ec8c2c18268a8623515790b5&i=) Uses JS `requestAnimationFrame` to delay a frame between each step. Here is one which uses a 30-frame delay for better inspection: [link](https://staxlang.xyz/#c=8F%7B%7C,%7D30*%7C%3A8Rs%5E%7C%287%28%22+%7Ec-vxUP%22%25EZ%2B%3AI%7B0%3Em%244%2Fm&i=) Idea is similar to MATL. Lack of vectorization makes it somewhat bulky. [Answer] # [Python 2](https://docs.python.org/2/), 158 bytes ``` import time while 1: for w in range(8): print'\n'*99 for x in'48966886698469906912611621960996'[w*4:w*4+4]:print('000'+bin(int(x))[2:])[-4:] time.sleep(1) ``` [This version does not work on Try it online!](https://tio.run/##HY5BCsMgFAXX8RTu1IQWFfn4vUqaRQu2ERIVIyQ9vU26mMWD4TH5W@cUdWthzalUWsPqyT6HxVPlCH2nQncaIi3P@PHcCke6XEKs7BFZj0i6yzhOgxmLANYCoDWAKAGVBqVAKwSJCGzce@NOBjO5/wdnUko2vELk1zqEGLWbxHgzbiLdVXLfFu8zV6K1Hw "Python 2 – Try It Online") Uses `0` for and `1` for `#`. Here is a version **(non competing)** without the clear screens and pauses (one of which blows up TIO) which displays each stage of the animation for each cycle and allows users without a Python 2.7 environment to see the output. For me, this covers the most important and interesting part of the challenge. Clearing the screen and adding delays is really just commentary IMHO. # [Python 2](https://docs.python.org/2/), 118 bytes ``` for w in range(8): for x in'48966886698469906912611621960996'[w*4:w*4+4]:print('000'+bin(int(x))[2:])[-4:] print ' ' ``` [Try it online!](https://tio.run/##HYq7CsQgEAD7fMV2qxcOVJbF9VfEIgf3sNkECST5ei9JMcUMsxzrb9bQ@2dusEFVaJN@3ybaNMDV9rMhRWGOkVkisYhj8YG95@CFnQhj3h6UTkYqaWlVV4POORxfVc1lu7U5pGLzk1IZ4F4AAXv/Aw "Python 2 – Try It Online") [Answer] # [Wolfram Mathematica](https://www.wolfram.com/mathematica/) 89 bytes ``` ListPlot[CirclePoints@8~RotateLeft~u~Drop~2,PlotRange->{{-1,1},{-1,1}}]~Animate~{u,0,7,1} ``` This gif is a bit glitchy, but the above animation does appear correctly, and play automatically and continuously, within a Mathematica notebook. [![enter image description here](https://i.stack.imgur.com/J6x6C.gif)](https://i.stack.imgur.com/J6x6C.gif) How it works: The ASCII characters in the challenge are arranged as vertices on an octagon rather than points on a circle (the left and right pairs are vertically aligned, and the top and bottom pairs are horizontally aligned), so I used `CirclePoints@8` to get the coordinates of the 8 vertices of a regular octagon centered about {0,0}. I rotated this coordinate list successively to the left by `u`, and then dropped the first two points. I used `ListPlot` to plot these, and then animated this, increasing u from 0 to 7 in increments of 1. The characters are displayed as plot points. Even though `,PlotRange->{{-1,1},{-1,1}}` costs 27 bytes, an explicit plot range specification was needed to maintain the aspect ratio of the plot as the points were rotated, so that the points would always appear at the same position on the screen. Alternately, for three less bytes (86), one could use `ListPolarPlot` to put the six points on an actual circle (separated by angles of Pi/4), rather than the vertices of an octagon: ``` ListPolarPlot[1 &~Array~6,DataRange->{u,5*Pi/4+u},PlotRange->Full]~Animate~{u,0,7,Pi/4} ``` This latter code would have been longer than the former, except that here the position and aspect ratio can be fixed using `PlotRange->Full` instead of `PlotRange->{{-1,1},{-1,1}}`. [Answer] # [pug](https://pugjs.org) + CSS, ~~81 + 135 = 216~~ 87 + 123 = 210 bytes ``` -o=54060,i=0 while o>>=1 if o&1 a(style=`--i:-${((i&1?7:0)^i++>>1)/8}s`) 0 else b ``` ``` body{display:grid;grid:none/repeat(4,1ch)}a{animation:a steps(4,start)1s var(--i)infinite}@keyframes a{to{visibility:hidden ``` [Watch it on CodePen.](https://codepen.io/ccprog/pen/oNGoJWg?editors=1100) Click on the downward arrow in the HTML area to see the compiled HTML. The animation is inspired by Neil's answer, but the custom CSS variables are injected by pug. The characters are ordered with a CSS [grid](https://developer.mozilla.org/en-US/docs/Web/CSS/grid), four items per row with a width of `1ch` each. `1ch` is defined as the exact advance of the `0` character in that font. That is the reason for displaying it, so the output is exactly aligned as if it was formatted with `<pre>`. Edit: saved 6 bytes with the help of Ismael Miguel. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~162~~ 149 bytes * -13 thanks to ceilingcat Loops forever. Each line is encoded in 4-bit segments and shifted to produce the line for the current frame, with increasingly long `sleep()` values. The screen is cleared with a form feed character, which should work in most terminal emulators. It would be possible to save 3 bytes by not initializing the starting frame, but there is a chance that a negative number could be entered before the function is called, resulting in a frame with a 0-second delay. ``` i,h;f(c){for(c=0;puts("\f");sleep(++c))for(i=4;i--;puts(""))for(h=L"\x66402666\x98891199\x88999119\x46666620"[i]>>c%8*4&15;h;h/=2)printf(L" #"+h%2);} ``` [Try it online!](https://tio.run/##LYrRCoIwGEbvfYqxMLZM0rGG40efwDdoXcRybVAqajEQn30p9V0dzvl0@tA6BHe0YIims@kGossM@vc0EqwMpjA@m6YnSaIp3aorObg0/T/wT9qyxsoLwTMmhFBeFoXMcymVX0FuqDwX21iGL@5aVTouDnyfn8GCPZWM9oNrJ0NqjHY4sTGjsITVoNfNteTTuTtFc4SQIRSiJXwB "C (gcc) – Try It Online") [Answer] # HTML5 + CSS3 - 78 + 156 = 234 bytes This answer is entirely based on [@Neil's answer](https://codegolf.stackexchange.com/a/240122/). This was offered as a size reduction of his original answer, which he allowed me to share as an answer. This answer includes a 1 byte trick as well, taken from the original answer. ``` pre>*{animation:a steps(4,start)1s calc(var(--c,0)*-125ms)infinite}c{--c:7}d{--c:1}e{--c:6}f{--c:2}h{--c:5}j{--c:3}k{--c:4}@keyframes a{to{visibility:hidden ``` ``` <pre> <a>#</a><c>#</c> <d>#</d> <e>#</e> <f>#</f> <h>#</h> <j>#</j><k>#</k> ``` This relies entirely on invalid tags, to calculate the CSS animation delays. This allows to shorten the selectors a lot, and is shorter than pre-calculating the delays. --- If we're allowed to take certain liberties with the presentation of the loading animation, it's possible to reduce the size a few more bytes. Using `opacity` instead of `visibility`, it's possible to have 2 hidden and all others partially visible. If the timing can be flexible, it is possible to save some bytes as well. This also includes a suggestion by @Neil, to use `1s` steps for `8s`, shaving this one down by 2 bytes. As such, here's a 78 + 145 = **223 bytes** long solution, which might not be valid (but looks prettier, in my opinion): ``` pre>*{animation:a steps(4,start)8s calc(var(--c,0)*-1s)infinite}c{--c:7}d{--c:1}e{--c:6}f{--c:2}h{--c:5}j{--c:3}k{--c:4}@keyframes a{to{opacity:0 ``` ``` <pre> <a>#</a><c>#</c> <d>#</d> <e>#</e> <f>#</f> <h>#</h> <j>#</j><k>#</k> ``` --- Please remember to upvote [@Neil's answer](https://codegolf.stackexchange.com/a/240122/) before considering upvoting mine. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 91 bytes Not my favorite because there's no delay... Also this only works with a terminal that supports moving the cursor with \x1b[r;cH, and clearing the terminal with \x1b[2J (... It works for me in termux on Android so far...) ``` [print('\x1b[2J','\x1b[%c;%cH*'*6%(*('2131424334241312'*2)[b*2:b*2+12],))for b in range(8)] ``` [Try it online!](https://tio.run/##JcZNCoAgEEDhq7iR0amNY0TUBaIrmIuU/jYm0qJOb0KL9/jiex9X0F1MOZuYznALmB/lDE1Q/@J@4H5EwJYLFEBKq4YarcsKCZCkcUh9qVJkaym3KzHHzsDSEvZVdNLm/AE "Python 3.8 (pre-release) – Try It Online") # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 119 bytes Here's a more realistic answer with the most obvious delay. ``` import time;[print('\x1b[2J','\x1b[%c;%cH*'*6%(*('2131424334241312'*2)[b*2:b*2+12],))or time.sleep(1)for b in range(8)] ``` [Try it online!](https://tio.run/##JYxBDsIgEEWvwoYMjI3JDI1p7AWMV8AupEElsUCQhZ4eiS7ez8tfvPypjxTNlEtrYcupVFHD5mebS4hVweVNzvIZhr/JdZbrCQEPUqECJkMjj8b06cqArK1DPnZ2xMugdSq/4P719D4r0rd@OBGiKNd492rSS2tf "Python 3.8 (pre-release) – Try It Online") [Answer] # JavaScript, 93 bytes ``` setInterval(_=>console.log(` 01 7 2 6 3 54`.replace(/\S/g,n=>(i-n)%8<6?'#':' ',i++)),i=99) ``` ]
[Question] [ We had a challenge on Multiplicative Persistence [here](https://codegolf.stackexchange.com/questions/181958/multiplicative-persistence). As a recap, to get a multiplicative persistence of a number, do these steps: 1. Multiply all the digits of a number (in base \$10\$) 2. Repeat Step 1 until you have a single digit left. 3. Then count the number of iterations. More here on *Numberphile*: * [*Numberphile* "What's special about 277777788888899?"](https://www.youtube.com/watch?v=Wim9WJeDTHQ) * [*Numberphile* "Multiplicative Persistence (extra footage)"](https://www.youtube.com/watch?v=E4mrC39sEOQ) See the [previous challenge](https://codegolf.stackexchange.com/questions/181958/multiplicative-persistence). # Rules The last challenge was all about seeing the intermediate results, but here: * The input should be a positive integer \$n\$. * The output should be the integer with the greatest multiplicative persistence among numbers from \$0\$ to \$n-1\$, choosing the smallest option in case of a tie. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins. # Example ``` [inp]: 10 [out]: 0 [inp]: 100 [out]: 77 [inp]: 50 [out]: 39 [inp]: 31 [out]: 25 ``` Note: Numbers *somewhat* randomly chosen. Good Luck! [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` ►ȯLU¡oΠd↔ŀ ``` [Try it online!](https://tio.run/##AR0A4v9odXNr///ilrrIr0xVwqFvzqBk4oaUxYD///81MA "Husk – Try It Online") ## Explanation ``` ►ȯLU¡oΠd↔ŀ ↔ŀ reverse the range 0..n-1 ►ȯ max-by, returning the last maximal element for the following: ¡o create an infinite list using: Πd product of digits. U longest unique prefix L take its length ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ḶDP$ƬL$ÐṀḢ ``` [Try it online!](https://tio.run/##y0rNyan8///hjm0uASrH1vioHJ7wcGfDwx2L/h9uf9S05v//aC5OQwMdBUMDIGEKxMaGXLEA "Jelly – Try It Online") # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ḶDP$Ƭ€ẈMḢ’ ``` [Try it online!](https://tio.run/##y0rNyan8///hjm0uASrH1jxqWvNwV4fvwx2LHjXM/H@4Hcj//z@ai9PQQEfB0ABImAKxsSFXLAA "Jelly – Try It Online") ## How they work ``` ḶDP$ƬL$ÐṀḢ - Main link. Takes n on the left Ḷ - Unlength; [0, 1, 2, ..., n-1] $ÐṀ - Return the maximal elements under the previous 2 links: $Ƭ - Iterate the previous 2 links until reaching a fixed point, collecting all steps: D - Digits P - Product L - Length; Number of steps Ḣ - Take the lowest maximal element ``` ``` ḶDP$Ƭ€ẈMḢ’ - Main link. Takes n on the left Ḷ - Unlength; [0, 1, 2, ..., n-1] € - Over each integer, 0 ≤ i < n: $Ƭ - Iterate the previous 2 links until reaching a fixed point, collecting all steps: D - Digits P - Product Ẉ - Lengths of each M - 1-indices of maximal elements Ḣ - Take the first (lowest) one ’ - Decrement to 0-index ``` [Answer] # [Python 2](https://docs.python.org/2/), 70 bytes ``` lambda n:max(range(n),key=g) g=lambda x:x<10or-~g(eval('*'.join(`x`))) ``` [Try it online!](https://tio.run/##LclBDsIgEEDRPadg18GoYTRuiNzERTFSitKBEGzpxqtjTfyrn7y0ljHSqQ361oKZ7g/DSU2mQjbkLJDYv@yqnWBO/7mqekUZ8@HjwM4mQLfrjs/oCfraCyHaMvpgOaqUPRU@gKf0LrABSoZSsotkZ/zd1hc "Python 2 – Try It Online") The helper function `g` recursively computes multiplicative persistence, and the main function in the top line finds value that maximizes `g` among the half-open range from `0` to `n`. It works out that `max` chooses the earlier element in case of a tie for greatest. [Answer] # [R](https://www.r-project.org/), ~~94~~ ~~91~~ 87 bytes *Edit: thanks to Kirill L. for spotting 2 (!) bugs, and also saving 3 bytes, and -4 more bytes thanks to Robin Ryder* ``` which.max(Map(f<-function(x)`if`(x>9,1+f(prod(utf8ToInt(c(x,""))-48)),0),1:scan()-1))-1 ``` [Try it online!](https://tio.run/##DcgxDoQgEAXQu1j9ibBhki3UmO0tttsDSNhMoBCIYuT26Cvf3trlg/OvzVZ8bYbMWs7oSkgRldYgK@pnVNwL8p7@OIsMv7TEAoequo5IvwciZUjxdDgbQZqf5MbGtBs "R – Try It Online") Started as a rather unimaginative construction based around [Giuseppe's 'Multiplicative persistence' answer](https://codegolf.stackexchange.com/a/181968/95126), which deserves most of the credit. Now adjusted (in response to bug-spotting by Kirill L.) into a recursive version that saved all the bytes needed for the bug-fix (I hope)... [Answer] # [Julia 0.7](http://julialang.org/), ~~58~~ ~~54~~ 49 bytes ``` n->argmax(.!(0:n-1))-1 !n=n>9&&!prod(digits(n))+1 ``` [Try it online!](https://tio.run/##yyrNyUw0/59m@z9P1y6xKD03sUJDT1HDwCpP11BTU9eQSzHPNs/OUk1NsaAoP0UjJTM9s6RYI09TU9vwf0lqcUmxgq1CtKGBjqGBgY6pgY6xYSyXg55CQVFmXklOngZUhZ1CGoSpqfkfAA "Julia 0.7 – Try It Online") Thanks to MarcMush for -5 bytes. [Answer] # JavaScript (ES6), 77 bytes ``` f=(n,m)=>n--?f(n,m>(g=n=>v=n>9&&-~g(eval([...n+''].join`*`)))(n)?m:(x=n,v)):x ``` [Try it online!](https://tio.run/##ZcjRCoIwFAbg@x5Ez19uJNFFwpkPEoHDtqHomWQMr3r1Rbd59/GNNtm1fw3LW0l8upw9k1Qz2IhSrf/ZUGBhk1jMrSjUJ5BLdqK71lpOZfnQYxykO3YASNDODW0sVQKaLfdR1jg5PcVAnuozcPiv/V33damB/AU "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` L<ε.ΓSP}g]Zk ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fx@bcVr1zk4MDatNjo7L//zc0MAAA "05AB1E – Try It Online") **Commented:** ``` L< # push [1 .. input] - 1 ε } # map over each integer: .Γ } # cumulative fixed-point: # run until the result doesn't change and collect results SP # take the product (P) of the digits (S) g # get the length of the resulting list Zk # find the index (k) of the minimum length (Z) ``` Alternative 12 byters: [`FN.ΓSP])€gZk`](https://tio.run/##yy9OTMpM/f/fzU/v3OTggFjNR01r0qOy//83NDAAAA) and [`<1ŸΣ.ΓSP}g}θ`](https://tio.run/##yy9OTMpM/f/fxvDojnOL9c5NDg6oTa89t@P/f0MDAwA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` FN⊞υ∧›ι⁹⊕§υΠιI⌕υ⌈υ ``` [Try it online!](https://tio.run/##HcxBCsIwEIXhvafIcgIR6lJcFUHpQskVYjLSQDOR6Yz09jH1LX8@XpwDxxqW1t6VDUz0UXlqeSGDtcbrOoM6M1KCO2OQnrMzZ@vMRJGxIAkmGGWihNsuPdekUSDbfZeD50wC17AK3HJ/6eQRtly0gP5Fa6dhaMfv8gM "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FN ``` Loop over the range `0..n-1`. ``` ⊞υ ``` Push to the predefined list... ``` ∧›ι⁹ ``` ... zero if the current index is less than 10, otherwise... ``` ⊕§υΠι ``` ... increment the previously calculated persistence of the digital product of the current index. ``` I⌕υ⌈υ ``` Print the first entry with maximal persistence. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 68 bytes ``` g=n=>n>9&&-~g(eval([...n+''].join`*`));f=n=>n--?g(h=f(n))<g(n)?n:h:0 ``` [Try it online!](https://tio.run/##ZcrBCoJAEIDhew@iM8UOSnRIW32QCFxsd1SWmVDx2Ktv0TEv/@Hjn9zmln4eX6sRffqU2IptpLlmmXkz@M1FuBORnPL8QZOO0h07xDr8NmNahsEGEMQbf9tKNVRF6lUWjZ6iMgQoC8TDP@3tsqdziZg@ "JavaScript (Node.js) – Try It Online") [Answer] # [Scratch](https://scratch.mit.edu/), 454 bytes [Try it online!](https://scratch.mit.edu/projects/514018590/) This one was fun to make! It takes 13 seconds to process the first 100,000 numbers. Alternatively, 48 blocks. ``` when gf clicked set[H v]to( set[M v]to( set[N v]to(-1 ask()and wait repeat(answer change(N)by(1 set[C v]to( delete all of[B v repeat(length of(N change[C v]by(1 add(letter(C)of(N))to[B v end set[P v]to( repeat until<(length of[B v])=(1 set[R v]to(1 repeat(length of[B v set[R v]to((R)*(item(1)of[B v delete(1)of[B v end set[C v]to( repeat(length of(R change[C v]by(1 add(letter(C)of(R))to[B v end change[P v]by(1 if<(P)>(H)>then set[H v]to(P set[M v]to(N ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 110 bytes ``` param($n)filter f{$_ if($_-gt9){("$_"|% t*y)-join'*'|iex|f}} ($k=0..$n|%{($_|f).count}).indexof(($k|sort)[-1]) ``` [Try it online!](https://tio.run/##DcvRCoIwFADQd79C5Iq7wkbSUw9@ScSQ2q2VbTIXGbv79uX7OYv/mrA@zDyXskxhegtwSHaOJtSUQFeWBGh5jydMogHdcFvH/ofy6a3r@o6t2ZhyrgS8xoNS4LhN@2BCdfUfFzMq625m8yR2wqsPEc9yuGAp5Tj8AQ "PowerShell – Try It Online") Thanks to @mazzy for the function and -24 bytes [Answer] # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), ~~107~~ ~~105~~ 108 bytes +3 for a bugfix with the tiebreaks. Definitely some golfing left to do... ``` < v:-1_;# $ <;v#:& e:p1 9;j`N' <^;#1p4 ;\0:<v; +1:$<^ +\1\v>:9`! #^_\1 >$$ ^ @.N'< ^#::<X'*%ap55/a_ ``` [Try it online!](https://tio.run/##HcHBCgIhFAXQWfsVN7SEhql5kJDPx9BntBCdCSxoEW7y9w0651Ge38@rTP7auwBoPFEOGgYSmuaDKlwJPrzXwQKSgqZ6USHOLC1gJDaS1BgptoX9uoNOOZJajAES/m6nwYpKmlnu9rjfqnPnLffu5h8 "Befunge-98 (FBBI) – Try It Online") The code contains two null bytes, indicated by `N` above ### How? slightly outdated **Product of the digits:** [![product of the digits of 123](https://i.stack.imgur.com/LU1RX.gif)](https://i.stack.imgur.com/LU1RX.gif) Accessing more than the top two values on the stack is quite hard in Befunge, which is why we save the remaining digits in the cell where the `X` is initially in. `1\` inserts a 1 (initial product) below the input value, then the product is calculated by repeatedly multiplying with last digit of the remaining input. **Computing the multiplicative persistence:** [![multiplicative resistance of 25](https://i.stack.imgur.com/8gNT1.gif)](https://i.stack.imgur.com/8gNT1.gif) `0\` inserts the initial value of `0` below the input integer. `:9`! #^_` continues east to increment the persistence and calculate the next product of digits as long as the top of the stack is larger than `9`, and exits to the top at `^` once a value less or equal to `9` is reached. For a more compact version of this which prints the intermediate results, see [my answer](https://codegolf.stackexchange.com/a/223271/64121) to the other challenge. **Storing intermediate results:** The highest persistence gets stored at the `N` at index `1, 9`, and this is directly used to be compared with new results. If the new results is not larger than the current record `;` skips the update code `91p:d4p`, which updates the record and stores the record index at `4, 13`. **The main loop:** [![enter image description here](https://i.stack.imgur.com/mNxD2.gif)](https://i.stack.imgur.com/mNxD2.gif) The loop counts down to `0` and sends the IP off to the other code in between. Once `0` has gone around the loop, the value stored at `4, 13` is printed and the program exits. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `Ṁ`, 9 bytes ``` ƛ⁽Π↔L;:Gḟ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=%E1%B9%80&code=%C6%9B%E2%81%BD%CE%A0%E2%86%94L%3B%3AG%E1%B8%9F&inputs=31&header=&footer=) Never have I had to use both `m` and `M` flags in the same challenge. ## Explained ``` ƛ⁽Π↔L;:Gḟ ƛ # over the range [0, input) - managed by the m and M flags ⁽Π↔ # get the iterations of the multiplicative persistance - repeatedly take the product of the digits of each number in the range, collecting results until it doesn't change L; # and take the length :G # push the maximum element and ḟ # get the first index where it occurs ``` [Answer] # [Python 2](https://docs.python.org/2/), 85 bytes ``` d=[] for x in range(input()):d+=x<10or-~d[eval('*'.join(`x`))], print d.index(max(d)) ``` [Try it online!](https://tio.run/##JY67DsIwEAT7@4pTmti85IBoEClDS0MXRSLEBxiCbZ0MOA2/HrDYZqcYrdYP4erscuycJiwxy7JRl3UDZ8cY0Vjk1l5IGOufQUi50dMybgvleP7RNb3aXuSTfHFzxopjPErZzMCzsQH1wlhNUTzaKLSU428Z4H01PeGBn7QBxMBDKkSK1GF6AIk78gGr/a5idvwXTkztfSwUFErBWsGqSPTLFw "Python 2 – Try It Online") Using a function to calculate the persistence came in at [87 bytes](https://tio.run/##JY6xDoIwGIT3PsUfFlqjpGgcJMENVxcfgEp/pApt0xQti69eabzlvlwul7OLH4zex85IhBqyLIt9PYrpLgWEKpxPQsvdt6f4FiPNN3nxNErTNrSMMSLrSVjab53QD6RK29nTlFuntAdZKC0x0EkEKhmL6zYhn0GNCDc3Y0UAvFuSAWDADtIHkrhD66G5XhrnjPsX7g7FK5aclJyTIyeHMtGqHw), but there might be way to do everything in a single function. [Answer] # [Haskell](https://www.haskell.org/), 82 bytes ``` f n=snd$minimum$((,)=<<p)<$>[0..n-1] p n|n>9=p(product$read.pure<$>show n)-1 p n=0 ``` [Try it online!](https://tio.run/##HY2xCoMwFEX3fMVDMigYSSoignHr1j8ohUoTa6h5CTHi0n@3jdsZzj13HtePXpbjmADliopag8ZuluZ5Wci@90VPhzuvKmTiQTzgF4dO@twHp7ZXpEGPqvJb0H9tnd0OWDCRPMkPOxoECcoRgLsp3aNndvRwTnYX1FpNZok65E908bpo@8zYkKXDt443g/q/88FgpBMYKVMmJQ/BgQ3AieAntC2Q5qS6I7VIcGl@ "Haskell – Try It Online") Golfing [Delfad0r's solution](https://codegolf.stackexchange.com/a/223265/20260) by using the [decorate-sort-undecorate idiom](https://en.wikipedia.org/wiki/Schwartzian_transform) to find the maximizing value. It's easier to see how it works in this slightly longer version. **83 bytes** ``` f n=snd$minimum[(-p i,i)|i<-[0..n-1]] p n|n>9=1+p(product$read.pure<$>show n) p n=1 ``` [Try it online!](https://tio.run/##HYyxCoMwFAD3fMVDHJQ2YipSCsatW/9ABKWJ9VHzEmKki/9u1e2Guxv7@aunadsGIDmTig0SmsU0CXeAV0xXrHiTZxlx0bbMAa1UP6S4uMR5q5Z3iL3uVeYWr6u4nkf7A0oPT4rN9EggQVkG0ODVthU3vYMz@Fmv5mzAKWifdGTDc9Kmi3gdpfvno8MLSe@d80ghHgClPDbHchM58BpyJvIT7ndg5UnFgxXigFv5Bw "Haskell – Try It Online") For each candidate value `i`, we create the pair `(-p i,i)`, take the minimum of all of them which compares first by `-p i`, the call `snd` to get just the value `i`. My first draft did `maximum[(p i,i)|i<-[0..n-1]]`, but this tiebreaks equal `p i`'s to higher `i`'s whereas we want lower. Negating `p i` and finding the minimum fixes this. We can negate `p i` directly in its definition without costing any bytes by subtracting `1` each step rather than adding `1`. It doesn't hurt to start from `0` rather than `-1` for the base case, since shifting `p` by a constant doesn't affect comparisons. **82 bytes** ``` f n=snd$minimum[(p i,i)|i<-[0..n-1]] p n|n>9=p(product$read.pure<$>show n)-1 p n=0 ``` [Try it online!](https://tio.run/##HYyxCoMwFAD3fMWjOCg0klRECsatW/9ABKWJ7aPmJcRIF//dqtsNd/cZ5q@Zpm0bgdRMOrFIaBfbph7witmKNW9FnhOXXcc80ErNXfnUB6eXV0yCGXTul2DqpJk/7geUcXl4Smx2QAIF2jGAFq@uq7kdPJzJzwU95yNO0YS0Jxcfk7H9hTeXbD@9TXwimb3zASkmI6BSx@ZYblIAb0AwKU6oKmDlScWdFfKAW/kH "Haskell – Try It Online") The code at the top implements `\i->(p i,i)` as `(,)=<<p` and maps it over the range, but unfortunately doesn't save any bytes with the parens it needs. [Answer] # [Haskell](https://www.haskell.org/), ~~86~~ ~~85~~ 84 bytes * -1 byte thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for removing the `f 1=0` case. ``` f n|n>1,x<-f$n-1,p x>=p(n-1)=x f n=n-1 p n|n>9=1+p(product$read.pure<$>show n) p n=1 ``` [Try it online!](https://tio.run/##HYzRCoMgGEbvfYqf0UWxjFxEBOnd7vYGY5AsW7JSMaMu9u5OuzvwfedMfP2KefZ@BPVTjORHh8dEYZIbOBg1acCMHijMNCAy562l5GpSY/WwvV1iBR8Ks1nRJWyd9A4qiz9K/MKlAgqDRgBPmetXhxdu4BR2bYe1GOXshE17pd19Fkt/weyShc5HuIdUInjGSuWSESSlMROTnpSAGZSIlCc0DaD6pKpFFYlwq/8 "Haskell – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 60 bytes ``` .+ * L$`. $.` +/\d.+/_~(`. $&$* )`^ .+¶#$$.( . # D`#+ ¶*$ ¶ ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8F9Pm0uLy0clQY9LRS@BS1s/JkVPWz@@TgMkoKaixaWZEMelp31om7KKip4Glx6XMpdLgrI216FtWipcQPL/f0MDLkMDAy5TAy5jQwA "Retina – Try It Online") Link includes test cases. Explanation: ``` .+ * L$`. $.` ``` List the numbers up to `n`. ``` +/\d.+/_ ``` Repeat while there are numbers of at least two digits... ``` ~(`. $&$* )`^ .+¶#$$.( ``` ... convert the numbers into Retina expressions that calculate their digital product and evaluate them. (As in my Retina answer to the previous challenge, an ungrouped version is actually a byte longer.) ``` . # D`#+ ``` Keep only the the new record multiplicative persistences. ``` ¶*$ ¶ ``` Retrieve the value with the highest new record persistence. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~57~~ 56 bytes ``` MaximalBy[Range@#-1,#>9&&1+#0@@Times@@@RealDigits@#&,1]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zexIjM3McepMjooMS891UFZ11BH2c5STc1QW9nAwSEkMze12MHBISg1McclMz2zpNhBWU3HMFbtf0BRZl5JtLKuXZqDcqxaXXByYl5dNZehgQ4QAwlTIDY25Kr9DwA "Wolfram Language (Mathematica) – Try It Online") Returns the value wrapped in a list. Since `MaximalBy` chooses the maximum based on Mathematica's internal ordering, choosing a value for the base case (when n≤9) isn't necessary. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~95~~ 94 bytes Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` a;b;c;d;r;f(n){for(b=0;n--;r=c>=b?b=c,n:r)for(c=0,d=n;a=d,d=d>9;++c)for(;a;a/=10)d*=a%10;d=r;} ``` [Try it online!](https://tio.run/##XVDRbsIwDHznK6xKSC1NRQpCiHlmD9O@YvCQJimrtgWUVFo11F9fZ2ipxiLZSe7Odi46O2jddQoL1GjQYxm75FwefVyQRJdl6ElvqXgqSAv34JMLpUkKQw4VGd7NdoNpqq8MKlRzymViZqSmuURDHtvuU1UuTibnCfCqXA21DXV43QPBOZcCcslpxbHMWxxFtjlZXVvT65hdr1mxEbBYDSr9pvyMs9Xv1veyaNe8LHbN5pljFQn4e19GQx0/FeLLiMoZ23CZxOH4CKH6tscyvg1P5gMwGxGENL2qE@gd3R7suFPv7Erv8Y4NzF5@9x61jI5G/5edPEvKOJoayLbAeRp2jk05AUGMvi1R2A9t20nb/ejyQx1Cl339Ag "C (gcc) – Try It Online") ]
[Question] [ The task is to write code to identify which key is pressed on the keyboard. You can assume that only one key is pressed at a time and that there is a standard US keyboard layout. That is the layout with the @ over the 2. Your code should output a unique identifier for any key pressed. This includes PrtScn, Scroll Lock, Pause, left Shift, right Shift, left Ctrl, right Ctrl, Caps Lock, Tab, Enter, Enter on the number pad, Num Lock, Insert, Ins on the number pad, Backspace, Del, F1...F12, Esc, left Windows key, right Windows key, Alt, AltGr, application key (context menu) and so on. Your code should carry on waiting for key presses and outputting their identity until it is killed. It should output the identifier as soon as a key is released however. It shouldn't carry out any other action from the key presses it receives and it shouldn't output anything apart from the unique identifier. In your answer, please show what you code outputs for the following key presses: Tab, Pause, Enter, Enter on the number pad, left Windows key, right Windows key, Insert and Ins on the number pad. If you have a very different keyboard, the challenge is still to output a different identifier for every single key on your keyboard. [Answer] ## x86 machine code, DOS executable, ~~29~~\* 28 bytes ``` FAE464D0E873FAE460D0E073F4D41005212192B402CD2188F2CD21EBE3 ``` This is a [COM executable](https://en.wikipedia.org/wiki/COM_file) for [MS-DOS](https://en.wikipedia.org/wiki/DOS), it requires a [IBM PC compatible](https://en.wikipedia.org/wiki/IBM_PC_compatible) hardware. Particularly an [8042 PS/2 controller](http://wiki.osdev.org/%228042%22_PS/2_Controller) or more likely an [emulation of it](https://superuser.com/questions/303365/what-does-legacy-usb-mouse-support-in-a-bios-mean) through [SMM](https://en.wikipedia.org/wiki/System_Management_Mode). Long story short, it should work out of the box in any mainstream PC. The source code is ``` BITS 16 ;Disable the interrupts so we don't compete with the IRQ 1 (the 8042 main ;device IRQ) handler (the ISR n. 9 by default) for the reading of the codes. cli _wait: ;Is 'Output buffer full (OBF)' bit set? in al, 64h ;Read the 8042 status register shr al, 1 ;Move bit 0 (OBF) into the carry flag jnc _wait ;Keep spinning if CF = OBF not set ;Read the scan code S in al, 60h ;Is S a break code? shl al, 1 ;Bit 7 is set if it is jnc _wait ;PART 2 ;AL = S mod 10h := y, AH = S / 10h := x aam 16 add ax, 2121h ;Make both quantities in the printable ASCII range (skip space though) ;Print y xchg dx, ax mov ah, 02h int 21h ;int 21/ah=02 prints the char in DL ;DH is still valid here, it holds x. We print it now mov dl, dh int 21h ;Never terminate jmp _wait ``` I've divided the program into two parts. The first part deals with the reading of the [scancodes](https://en.wikipedia.org/wiki/Scancode). Scancodes are numeric values associated with every key. Note that these are hardware code, they don't depend on the OS or the charset. They are like an encoded pair (column, row) of the key. Every key has a scancode, even those non-standard weird function keys found on some keyboard (e.g. the "open calc" key). Some key has multi-byte scancode, they have prefixes designed to make the stream decodificable by just looking at the sequence of bytes. So each key gets its unique identifier, even CTRL, SHIFT, WinKeys and so on. Only the "break codes", sent when a key is released, are processed, the "make codes" are ignored. The formers have the higher bit (bit 7 for a byte) set, so it's easy to recognise them. The second part deals with the printing of a byte. Printing is always lengthy in assembly, we have no builtins. To keep it short, and since it was required to write *an identifier* of the key, I abandoned decimal or hex numerals in favour of a personal encoding. A byte xy, where x is the higher nibble and y the lower is printed as two successive chars c0 and c1 defined as: c0 = 0x21 + y c1 = 0x21 + x Note that the lower nibble is printed *first* (this spared me a swap). The rationale is to map the each one of the 16 possible values of a nibble into consecutive ASCII characters from '!'. Simply put this is a hex numeral but with 1. The nibbles swapped 2. `!"#$%&'()*+,-./01` as digit(als) instead of `0123456789abcdef` Running it in [DOSBox](https://www.dosbox.com/) and pressing some random key (some of which is a special key but note that as a Windows process DOSBox can't capture all the keys) yields [![DOSBox running the key identifier](https://i.stack.imgur.com/N0vjr.png)](https://i.stack.imgur.com/N0vjr.png) Note that this program never terminates (further, it takes complete control of the PC by disabling the interrupts) as I believe was intended by the question (simply there is no killing of processes in DOS). --- \* Reduced thank to [CodyGray](https://codegolf.stackexchange.com/questions/132240/what-key-did-i-press/132330?noredirect=1#comment324850_132330). [Answer] # Java 7 or Higher, ~~246~~ 228 bytes ``` import java.awt.event.*;class K{public static void main(String[]a){new java.awt.Frame(){{addKeyListener(new KeyAdapter(){public void keyPressed(KeyEvent e){System.out.println(e);}});show();setFocusTraversalKeysEnabled(0<0);}};}} ``` Ungolfed: ``` import java.awt.event.*; class K{ static void main(String[]a){ new java.awt.Frame(){ { addKeyListener(new KeyAdapter(){ public void keyPressed(KeyEvent e){ System.out.println(e); } }); show(); setFocusTraversalKeysEnabled(0<0); } }; } } ``` *-18 thanks to @OlivierGrégoire for `show()`, `0<0` and `import java.awt.event.*;`* Which results in: [![enter image description here](https://i.stack.imgur.com/yHG2T.png)](https://i.stack.imgur.com/yHG2T.png) Even handles shift-presses for capitalized characters, the windows key, cap locks, etc... You can see it printing the 'modifiers' as well, which are 'held keys'. ``` java.awt.event.KeyEvent[KEY_PRESSED,keyCode=27,keyText=Escape,keyChar=Escape,keyLocation=KEY_LOCATION_STANDARD,rawCode=27,primaryLevelUnicode=27,scancode=1,extendedKeyCode=0x1b] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=192,keyText=Back Quote,keyChar='`',keyLocation=KEY_LOCATION_STANDARD,rawCode=192,primaryLevelUnicode=96,scancode=41,extendedKeyCode=0xc0] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=9,keyText=Tab,keyChar=Tab,keyLocation=KEY_LOCATION_STANDARD,rawCode=9,primaryLevelUnicode=9,scancode=15,extendedKeyCode=0x9] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=20,keyText=Caps Lock,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=20,primaryLevelUnicode=0,scancode=58,extendedKeyCode=0x14] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=16,keyText=Shift,keyChar=Undefined keyChar,modifiers=Shift,extModifiers=Shift,keyLocation=KEY_LOCATION_LEFT,rawCode=16,primaryLevelUnicode=0,scancode=42,extendedKeyCode=0x10] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=17,keyText=Ctrl,keyChar=Undefined keyChar,modifiers=Ctrl,extModifiers=Ctrl,keyLocation=KEY_LOCATION_LEFT,rawCode=17,primaryLevelUnicode=0,scancode=29,extendedKeyCode=0x11] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=524,keyText=Windows,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_LEFT,rawCode=91,primaryLevelUnicode=0,scancode=91,extendedKeyCode=0x20c] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=18,keyText=Alt,keyChar=Undefined keyChar,modifiers=Alt,extModifiers=Alt,keyLocation=KEY_LOCATION_LEFT,rawCode=18,primaryLevelUnicode=0,scancode=56,extendedKeyCode=0x12] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=32,keyText=Space,keyChar=' ',keyLocation=KEY_LOCATION_STANDARD,rawCode=32,primaryLevelUnicode=32,scancode=57,extendedKeyCode=0x20] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=18,keyText=Alt,keyChar=Undefined keyChar,modifiers=Alt,extModifiers=Alt,keyLocation=KEY_LOCATION_RIGHT,rawCode=18,primaryLevelUnicode=0,scancode=56,extendedKeyCode=0x12] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=17,keyText=Ctrl,keyChar=Undefined keyChar,modifiers=Ctrl,extModifiers=Ctrl,keyLocation=KEY_LOCATION_RIGHT,rawCode=17,primaryLevelUnicode=0,scancode=29,extendedKeyCode=0x11] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=37,keyText=Left,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=37,primaryLevelUnicode=0,scancode=75,extendedKeyCode=0x25] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=16,keyText=Shift,keyChar=Undefined keyChar,modifiers=Shift,extModifiers=Shift,keyLocation=KEY_LOCATION_RIGHT,rawCode=16,primaryLevelUnicode=0,scancode=42,extendedKeyCode=0x10] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=38,keyText=Up,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=38,primaryLevelUnicode=0,scancode=72,extendedKeyCode=0x26] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=39,keyText=Right,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=39,primaryLevelUnicode=0,scancode=77,extendedKeyCode=0x27] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=96,keyText=NumPad-0,keyChar='0',keyLocation=KEY_LOCATION_NUMPAD,rawCode=96,primaryLevelUnicode=48,scancode=82,extendedKeyCode=0x60] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=110,keyText=NumPad .,keyChar='.',keyLocation=KEY_LOCATION_NUMPAD,rawCode=110,primaryLevelUnicode=46,scancode=83,extendedKeyCode=0x6e] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=10,keyText=Enter,keyChar=Enter,keyLocation=KEY_LOCATION_NUMPAD,rawCode=13,primaryLevelUnicode=13,scancode=28,extendedKeyCode=0xa] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=107,keyText=NumPad +,keyChar='+',keyLocation=KEY_LOCATION_NUMPAD,rawCode=107,primaryLevelUnicode=43,scancode=78,extendedKeyCode=0x6b] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=109,keyText=NumPad -,keyChar='-',keyLocation=KEY_LOCATION_NUMPAD,rawCode=109,primaryLevelUnicode=45,scancode=74,extendedKeyCode=0x6d] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=106,keyText=NumPad *,keyChar='*',keyLocation=KEY_LOCATION_NUMPAD,rawCode=106,primaryLevelUnicode=42,scancode=55,extendedKeyCode=0x6a] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=34,keyText=Page Down,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=34,primaryLevelUnicode=0,scancode=81,extendedKeyCode=0x22] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=33,keyText=Page Up,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=33,primaryLevelUnicode=0,scancode=73,extendedKeyCode=0x21] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=35,keyText=End,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=35,primaryLevelUnicode=0,scancode=79,extendedKeyCode=0x23] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=36,keyText=Home,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=36,primaryLevelUnicode=0,scancode=71,extendedKeyCode=0x24] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=127,keyText=Delete,keyChar=Delete,keyLocation=KEY_LOCATION_STANDARD,rawCode=46,primaryLevelUnicode=0,scancode=83,extendedKeyCode=0x7f] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=155,keyText=Insert,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=45,primaryLevelUnicode=0,scancode=82,extendedKeyCode=0x9b] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=123,keyText=F12,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=123,primaryLevelUnicode=0,scancode=88,extendedKeyCode=0x7b] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=122,keyText=F11,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=122,primaryLevelUnicode=0,scancode=87,extendedKeyCode=0x7a] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=121,keyText=F10,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=121,primaryLevelUnicode=0,scancode=68,extendedKeyCode=0x79] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=120,keyText=F9,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=120,primaryLevelUnicode=0,scancode=67,extendedKeyCode=0x78] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=119,keyText=F8,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=119,primaryLevelUnicode=0,scancode=66,extendedKeyCode=0x77] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=118,keyText=F7,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=118,primaryLevelUnicode=0,scancode=65,extendedKeyCode=0x76] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=117,keyText=F6,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=117,primaryLevelUnicode=0,scancode=64,extendedKeyCode=0x75] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=116,keyText=F5,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=116,primaryLevelUnicode=0,scancode=63,extendedKeyCode=0x74] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=115,keyText=F4,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=115,primaryLevelUnicode=0,scancode=62,extendedKeyCode=0x73] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=114,keyText=F3,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=114,primaryLevelUnicode=0,scancode=61,extendedKeyCode=0x72] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=113,keyText=F2,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=113,primaryLevelUnicode=0,scancode=60,extendedKeyCode=0x71] on frame0 java.awt.event.KeyEvent[KEY_PRESSED,keyCode=112,keyText=F1,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=112,primaryLevelUnicode=0,scancode=59,extendedKeyCode=0x70] on frame0 ``` [Answer] # HTML (with Javascript), ~~46~~ 31 chars, ~~46~~ 31 bytes ~~Using [this](https://stackoverflow.com/questions/5418313/how-to-differentiate-between-enter-and-return-keys-in-javascript) to differentiate numpad enter and return, LControl and RControl...~~ Not anymore since apsillers found a way to do it with a signle function call. ``` <body onkeyup=alert(event.code) ``` Specific outputs: OUTPUTS THAT ARE STILL WITH THE NUMBERS ARE THOSE I CAN'T TEST ON MY LAPTOP PLEASE WAIT FOR ME TO HAVE ACCESS TO THOSE KEYS PrtScn -> PrintScreen Scroll Lock -> ScrollLock Pause -> Pause left Shift -> ShiftLeft right Shift -> ShiftRight left Ctrl -> ContrlLeft right Ctrl -> ControlRight Caps Lock -> CapsLock Tab -> Tab Enter -> Enter Enter on the number pad -> NumpadEnter Num Lock -> NumLock EDITs : 1 byte saved on `;` after func call 18 bytes saved thanks to Lil' Bits and ETHproductions, they noticed I forgot to shorten func and var names. 32 bytes saved thanks to RogerSpielker, he noticed I was doing sparated code for no reason; and again -2 bytes : `onkeydown` -> `onkeyup` 1 byte saved : no need for final slash 2 bytes saved thanks to CraigAyre : `with()` function 2 bytes saved thanks to ASCII-only : `key` in place of `which` 4 bytes saved, since we have text, there is no need for `'-'+` (every identifier is unique without this) 1 byte saved thanks to ASCII-only (again) : no more closing symbol `>` 15 bytes saved thanks to apsillers, as said at the top of my answer. ``` <body onkeyup=alert(event.code) ``` [Answer] # Tcl/Tk, 22 characters ``` bind . <Key> {puts %K} ``` Sample run: ![keys identified by Tcl/Tk](https://i.stack.imgur.com/LDeq6.png) Notes: * No right Windows key on [my keyboard](https://linustechtips.com/main/uploads/monthly_2016_10/20161011_190137.thumb.jpg.f3aec315be58e07c731a74adb08b5473.jpg) ☹ (~~clever~~ designer put the backlight switch in its place) * The numeric pad's Insert generates different code based on NumLock's status * The volume knob generates X.org specific codes, all other are just regular [keysyms](http://tcl.tk/man/tcl8.6/TkCmd/keysyms.htm) [Answer] # Bash with X.org, 21 bytes ``` xev|awk 'NR%2&&/\(k/' ``` Unfortunately, I can't test it since I'm on MacBook on Linux - no PrntScr, no numeric keyboard &all. `xev` is a tool that outputs mouse and keyboard events under `X.org`. I pipe it to awk, filter even lines (since every key is shown when key is pressed, and then when it's released), and select only those that contain `(k` - this string is in every line that describes pressed key. [Answer] # C and Win32, 240 224 216 205 202 194 191 bytes ``` #include<d3d.h> #include<stdio.h> w[9];p(x,y,a,b){printf("%X",a^b);}main(){w[1]=p;w[9]=p;CreateWindow(RegisterClass(w),0,1<<28,0,0,0,0,0,0,0,0);for(;GetMessage(w,0,16,0);)DispatchMessage(w);} ``` ## Outputs `TAB`: `F0008C00F0008` `PAUSE`: `450012C0450012` `ENTER`: `1C000CC01C000C` `NUMPAD-ENTER`: `11C000CC11C000C` `WINDOWS-LEFT`: `15B005AC15B005A` `WINDOWS-RIGHT`: `15C005DC15C005D` `INSERT`: `152002CC152002C` `NUMPAD-INSERT`: `52002CC052002C` ## Explanation ``` #include <d3d.h> // shortest built-in header that includes windows.h #include <stdio.h> // for printf w[9]; // space for wndclass-data array // function castable to the signature of WNDPROC p(x,y,a,b) { // key and state are encoded in the last two 4-byte arguments to wndproc printf("%X",a^b); } main(m) { // set minimal window class equivalent data pointing to wndproc above w[1]=p;w[9]=p; // create the window using the class, with WS_VISIBLE flag CreateWindow(RegisterClass(w),0,1<<28,0,0,0,0,0,0,0,0) for(;GetMessage(w,0,16,0);) // filter messages 15 and lower, which fire without input DispatchMessage(w); } ``` ## Edits -16 thanks to @ugoren -8: changed `WNDCLASS` to `int` array since all 10 members are 4 bytes -11: partial initialization of wndclass-data array, reduced to 9 elements -3: use implicit `int` decl for wndclass-data array -8: remove newline from output format (not required in spec and printf flushes immediately without it); move `RegisterClass` into `CreateWindow` arg, using returned `ATOM`; set wndclass name to `m` which just needs a zero-byte in it to be a valid string. -3: reuse `w` var for `MSG` data [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 369 bytes ``` import java.awt.event.*;import javax.swing.*;class F{public static void main(String[] a){JFrame f=new JFrame();f.addKeyListener(new KeyListener(){public void keyPressed(KeyEvent e){System.out.print(e.getKeyCode()*8+e.getKeyLocation());}public void keyTyped(KeyEvent e){}public void keyReleased(KeyEvent e){}});f.setVisible(true);f.setFocusTraversalKeysEnabled(false);}} ``` This cannot be run with TIO because it uses a graphical interface, but it works on my computer. ``` Pause: 153 Enter: 81 Enter on NumPad: 84 Left Super key: 193 (After disabling the Menu shortcut for my desktop) Right Super key: 201 Insert: 241 Insert on Numpad: 522948 (I don't have one, but that's what you get when you press 5 with Num lock off. When Num lock is on, you get 812.) ``` # Ungolfed / Explanation: ``` import java.awt.event.*; // KeyListener, KeyEvent import javax.swing.*; // JFrame class F implements KeyListener { public static void main(String[] a) { JFrame f=new JFrame(); // creates a new GUI frame f.addKeyListener(new KeyListener() { // puts a KeyListener in the frame with the following properties: // Method that runs whenever a key is pressed public void keyPressed(KeyEvent e) { // getKeyCode returns an integer that uniquely identifies the key, // but not the location (e.g. LShift and RShift have the same key code) // To fix this, I scale up the key code by 8 and add the location, // which is always 0-4 (Standard, Left, Right, NumPad, or Unknown) // I could have scaled by 5 instead but I wasn't really thinking System.out.print(e.getKeyCode() * 8 + e.getKeyLocation()); // If you want nicer-looking output, just change "print" to "println" } // Method that runs whenever a printable character is typed (does nothing) public void keyTyped(KeyEvent e){} // Method that runs whenever a keyboard key is released (does nothing) public void keyReleased(KeyEvent e){} }); f.setVisible(true); // the frame will only except key presses if it is visible f.setFocusTraversalKeysEnabled(false); // disables "focus traversal" keys (such as Tab) from actually traversing focus } } ``` [Answer] # Scala 2.10+, 279 chars, 279 bytes Now this is a scala response :) even though it feels like I'm doing Java. Anyway we can't test it on TIO. ``` import scala.swing._ import java.awt.event._ object M extends SimpleSwingApplication{def top=new MainFrame{this.peer.addKeyListener(new KeyListener(){def keyPressed(e:KeyEvent){print(e.getKeyCode+"-"+e.getKeyLocation)} def keyReleased(e:KeyEvent){} def keyTyped(e:KeyEvent){}})}} ``` It's sad we need to declare all inherited methods even if we don't use them :l can I remove them from byte count, since some compiler flags can permit not declaring them? This prints (as for my html-js response) the keyPressed, "-" and then its "location". For instance : PrtScn -> not verifyable Scroll Lock -> 145-1 Pause -> 19-1 left Shift -> 16-2 right Shift -> 16-3 left Ctrl -> 17-2 right Ctrl -> 17-3 Caps Lock -> 20-1 Tab -> not verifyable Enter -> 10-1 Enter on the number pad -> 10-4 Num Lock -> 144-4 Insert -> 96-1 Ins on the number pad -> 96-4 Backspace -> 8-1 Del -> 127-1 F1...F12 -> 112-1 to 123-1 Esc -> 27-1 left Windows key -> 524-2 right Windows key -> 524-3 Alt -> 18-2 AltGr -> 18-3 (kind of buggy, it detects 17-2 and then 18-3, but it is indeed 18-3) application key (context menu) -> 525-1 Though I think it depends on the computer :/ I'm on an azerty laptop right now. [Answer] # TI-BASIC, 19 bytes > > **PROGRAM:S** > > > ``` If Ans Disp Ans getKey prgmS ``` * Enter: 105, * Left key: 24, * Right key: 26, * Ins[ert] is a little different because it would normally take two key presses to get to, but those would be 21 followed by 23. **Here's an illustration of the rest of the keys:** [![enter image description here](https://i.stack.imgur.com/FmFLY.jpg)](https://i.stack.imgur.com/FmFLY.jpg) **Explanation:** > > **PROGRAM:S** The editor displays the name at the top apart from the code; the name is "S" > > > ``` If Ans // If the last input isn't zero Disp Ans // Display the last input getKey // Input a key press prgmS // Call the same program in a recursive fashion ``` This, unfortunately, isn't possible to do in Arnold C, so I had to stick to TI-BASIC. [Answer] # PowerShell, 34 bytes ``` $Host.UI.RawUI.ReadKey().Character ``` Outputs on the same line as the input, which can be a tad confusing. [Answer] # C#, 144 + 601 = 745 bytes Consists of two classes, I couldn't manage to successfully combine them into one class. Main class: ``` namespace System.Windows.Forms{class P:Form{static void Main(){Application.Run(new P());}P(){new Reflection.M().U+=k=>Console.Write(k.f+k.v);}}} ``` Hook class: ``` namespace System.Reflection{using Runtime.InteropServices;public class M{public delegate void d(s s);event d u;public event d U{add{if(h<1){j=m;h=SetWindowsHookEx(13,j,Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),0);}u+=value;}remove{u-=value;}}public struct s{public int v;public int c;public int f;}[DllImport("user32.dll")]static extern int SetWindowsHookEx(int idHook,p lpfn,IntPtr hMod,int dwThreadId);delegate int p(int c,int w,IntPtr l);p j;int h;int m(int c,int w,IntPtr l){if(c>=0&u!=null&(w==257|w==261))u.Invoke((s)Marshal.PtrToStructure(l,typeof(s)));return -1;}}} ``` Outputs: * Tab: `137` * Pause: `147` * Enter: `141` * NumPad Enter: `142` * Left Windows: `220` * Right Windows: `221` * Insert: `174` * NumPad Insert: `224` [Answer] # [AutoHotkey](https://autohotkey.com/docs/commands/Input.htm), 26 Bytes ``` loop{ input,x,L1M send %x% } ``` Can't test (win-only), but the `M` option says > > M: Modified keystrokes such as Control-A through Control-Z are recognized and transcribed if they correspond to real ASCII characters. > > > So it should do fine. [Answer] # WinApi C ([gcc](https://nuwen.net/mingw.html)), 156 bytes ``` #include <d3d.h> #define b GetStdHandle(-10) BYTE i[20];main(){SetConsoleMode(b,0);a:ReadConsoleInput(b,i,1,i+5);*i^1||*(i+4)||printf("%X\n",i[10]);goto a;} ``` This program prints out the [Windows Virtual-Key Code](https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx) assciocated with each keyboard key of input. The `\n` in the `printf` format-string is optional (but makes output human-friendly) and can be dropped for a total score of **154 bytes**. An easy way to kill the program (without taskmgr) is with `CTRL + PAUSE`. If you have a keyboard with a Fn key, this program cannot pick it up since it isn't even noticed by Windows. * Credit to MooseBoys's answer for the `#include <d3d.h>` trick and inspiration for the `BYTE` array. The program with local variables, readability, and without compiler warnings looks like this: ``` #include <windows.h> #include <stdio.h> int main(void) { HANDLE conIn = GetStdHandle(STD_INPUT_HANDLE); INPUT_RECORD ir; DWORD useless; SetConsoleMode(conIn, 0); for(;;) { ReadConsoleInput(conIn, &ir, 1, &useless); if(ir.EventType == KEY_EVENT && !ir.Event.KeyEvent.bKeyDown) printf("%X\n", ir.Event.KeyEvent.wVirtualKeyCode); } return 0; } ``` [Answer] # C (gcc) + Win32, 94 ~~95~~ ~~98~~ ~~105~~ ~~107~~ ~~110~~ bytes ``` #import"d3d.h" j;f(){for(;;)for(j=191;j--;)GetAsyncKeyState(j)&(j<16||j>18)?printf("%d",j):0;} ``` The code captures keys even after focus is lost. The following screenshots are recorded adding spaces between outputs (`printf("%d ",j);` +1 byte) for better readibility: [![key screenshot](https://i.stack.imgur.com/ZUH6p.png)](https://i.stack.imgur.com/ZUH6p.png) `Left-ctrl` `Left-win` `Left-alt` `Space` `Right-alt` `Right-win` `Right-menu` `Right-ctrl` `Left-shift` `Z` `X` `C` `Right-shift` `Left-shift` `1` `2` `3` `Num 1` `Num 2` `Num 3` `Left-shift` `+/= (on the main part)` `Num +` `Left-alt` `PrtScn` The code uses `GetAsyncKeyState` to query key state without checking message queue, usually more real-time than other user-mode approaches (except DirectInput). This approach is widely used in keyloggers. `(j<16||j>18)` filters regular Ctrl/Alt/Shift. 16/17/18 is triggered whenever left or right one is pressed, along with location-specified vkey value. ]
[Question] [ This challenge is to take an alphabetical string as input and to apply the following conversion: The first of each type of character of the string must stay, and must be immediately followed by an integer representing how many of these characters were in the original string. Any repeating characters must be omitted. All inputs will be entirely lower-case letters (no spaces). Outputs must be ordered in the same way as the inputs (input `hi` must give output of `h1i1`, not `i1h1`) # Examples Input: `potato` Output: `p1o2t2a1` Input: `pqwertyuiop` Output: `p2q1w1e1r1t1y1u1i1o1` Input: `thisisanexample` Output: `t1h1i2s2a2n1e2x1m1p1l1` Input: `oreganoesque` Output: `o2r1e3g1a1n1s1q1u1` Input: `aaaaaaabaaaaaa` Output: `a13b1` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer wins! [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 [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. ``` ,,∘⍕∘≢⌸ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X0fnUceMR71TQWTnokc9O/6nPWqb8Ki371FX86PeNY96txxab/yobeKjvqnBQc5AMsTDM/h/mnpBfkliSb46F5BVWJ5aVFJZmplfAOKWZGQWZxYn5qVWJOYW5KSChPKLUtMT8/JTiwtLU9UB "APL (Dyalog Unicode) – Try It Online") `⌸` apply the following function between each unique character and the indices where it occurs:  `,` concatenate the character   `∘` to    `⍕` the stringification     `∘` of      `≢` the indices' count `,` flatten [Answer] # [PHP](https://php.net/), 63 bytes ``` foreach(array_count_values(str_split($argn))as$a=>$b)echo$a.$b; ``` [Try it online!](https://tio.run/##JY07DsIwEAV7n4LCRVLABcKnAlEgkRtYm2iJLQXvxrsGcnlMUF4xM91jz2V/4oUPSgi9ryAlmF1POap7wZhRKtHkhMeglYU0xLoGsXA42q7G3pOFne2a8s9Ne23d@X5rCpOCkuHpjUnnHIiN@iBBIOIHnjyiWf4GiIQyZTSwrlv1JdZAUcr28gM "PHP – Try It Online") Built-ins and a whole lot of glue. Input via `STDIN`, output to `STDOUT`. [Answer] # [Python 3](https://docs.python.org/3/), ~~58~~ \$\cdots\$ ~~50~~ 57 bytes Added 3 bytes and switched to Python 3 to fix bugs. Added 7 bytes to make output a string. ``` lambda s:''.join(c+f'{s.count(c)}'for c in{}.fromkeys(s)) ``` [Try it online!](https://tio.run/##NZDRbsIwDEXf@xURL2k0huR00iSk7keAh1BcyNbGaZwKKsS3d2kq8uLca9lXx36KN3LV3NbHuTP9@WIE76Xc/ZJ1ZfPRyifvGhpdLBv1ki0F0Qjrnq9dG6j/w4lLVmqOyJFFLQ4bT9FE2mzFxg93DHEaLflFxptly8bhw/S@w8WigFfjCHkYszbrO68lOacCHx6biJd1N5CO2kDerge4A0KACBOMYIGyH@EGVrM22gHqB/Tgocsd0gGwuoIBBwxDmsmZUJ0hR4WUUY7yOOrvr0ZuxfqFSqpiwbYJWwTjrlh26MpMrNS@EAt3u@qDPalC@GDTud5GyhCfPyJF8FaEwxsodeqaT2r@Bw "Python 3 – Try It Online") Outputs a string. Outputting a list of strings is [50 bytes](https://tio.run/##NZDBjoMgEIbvPgXpBcl2mwxuskkT90WsB7Rjy64CMphqmj67i5hygfkmzJ9v3BLu1hRrV17WXg3NVTE6V@1Hx590au1kQt6KF@@sZy3T5vk6dd4Of7hQTqJeA1IgVrLq4GxQwR6O7ODGB/qwTNq6rQx3TZqUwVkNrscNWY83ZSzSOKVa7afZr0jqDGeHbcDrPhusDFJBmi5HeACChwALTKDBJh7gDlqSVNIAyhkGcNCnjpUesLiBAgMEY/yTMqFoIEX5mJFP/DLJ76@WH9n@hIKLbNPWUZt5ZW6Y92jyZCzEOWObN@enX6tN3u280rUQGXNex729SQxjnz8sZtGR@eptFjtlSbVY/wE). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes This is the dreaded *obvious chain-the-built-ins*. `Print` can accept multiple arguments and will print them without any separators. ``` Print@@Flatten@Tally@Characters@#& ``` More scary version, for the same number of bytes: ``` Print@@(##&)@@@Tally@Characters@#& ``` I suspect that a better hack consisting entirely of the characters `#&/()` can be used to get rid of Flatten, but I couldn't come up with one. Of course, Mathematica has both `LetterCounts` *and* `CharacterCounts`, and there's also `Counts` instead of `Tally`, but all of these seem to return association objects that seem excessively complicated to work with. [Try it online!](https://tio.run/##DcY7CoAwEAXA3mNE8BbCgpDawk5TPGQhgfxIXqGnj041CfSawHBj2PUaewuZIjaC1CwHYnxl82i4qa3LvAx7mloIFuOm//Shh46sD1KNatz4AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 49 bytes ``` lambda s:''.join({c+str(s.count(c)):1for c in s}) ``` [Try it online!](https://tio.run/##XZDRasMwDEXf/RWmL4lZV5AzGBTSH2n74KZq65HajqXQhLFvzxyHQje9WLrCutwTRr55V02X@jC15n46G0nboth8eevK7@aNOJa0aXzvuGyU2sLFR9lI6yT9qImRmGQt96vg2bBfreUqdA@MPPbWh3nkmyVLxuFg7qHFWfIRr8Z5pK7Ps1nqtDxJOQocAjaM5@U2eM3aQL6uO3gAQgSGEXqw4LPOcAOrSRvtAPUAdwjQ5o3XEbC6ggEHBF36kz2hOkG2ismj7ItDrz8/mmItlxaqQok5q52zRuOuWLboypw4cRByzv0EdVn0vT0qJWSINtF6KslMvu9k8qK1jPtnsrSpazqqaSEnXrCJf8zEKzDxl9Yv "Python 3 – Try It Online") Outputs a string. Based on [Noodle9's solution](https://codegolf.stackexchange.com/a/205837/20260), which uses a nice idea of a dictionary to deduplicate while preserving order, which they do in Python 3 but not Python 2. Note that `set` doesn't preserve order. The idea is to make the character-with-count strings be keys of a dictionary so that only the first instance is used. The values in the dictionary don't matter, since dictionaries iterate over keys by default. I had thought at first that the deduplication must be applied to the characters of the input string, but realized that it also works on the strings to be joined in the output, since a given character is always attached to the same count. Outputting a list of strings without joining takes [43 bytes](https://tio.run/##XZDRasMwDEXf/RWmL0m2riBnMChkP5LmwU3V1iO1HUuhCWPfnjkOhW56sXSFdbnHT3x1tpzP1WHu9O140pL29ct3@0occtq1brCct0Wxh7MLspXGSvppZkZikpWsN96xZrfZyo3v7xh4Gozzy8hXQ4a0xVHffIeL5AJetHVI/ZBmvdZxfaLSCBw9toyn9TY4xUpDuq56uANCAIYJBjDgks5wBaNIaWUB1Qg38NCljVMBsLyABgsEffyTPKE8QrIK0SMfssOgPt7bbCvXFsqsEEtWs2QN2l4w79DmKXHkIOSSO8t2X87Y/LzqtWmKQkgfTKT1UKKZfPuU0Yu2MtSPZHFTVdQU80pOPGET/5iJZ2DiL61f). [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~23~~ 18 bytes ``` {,/t,'$+/x=\:t:?x} ``` [Try it online!](https://tio.run/##JYjRCkAwFED/ZSmEvE/yI16uuljDHbvLJN8@tPNyOkdXpEMY5V3WXKZJUfu2lyw7/4QxzYQhBibRCLOfePDlFJmveFZWWdjQw2oW/A4dOMFGaHf3J0SGKJGHFw "K (oK) – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~15~~ 17 bytes Thanks to Jonah for finding and fixing a bug! ``` [:;~.<@,&":"0#/.~ ``` [Try it online!](https://tio.run/##ZY/BisJADIbvPkWo4CBo13@8zSoIgqc9ed1TXKKdRZtpZ4p68dW7grbCGgjhD99HyG@b5WZPS0eGJjQjd@9pTuvt16b9dp@3fLGajDKXzYYf@a0dDwbyUyjtyQRNnNT0mR@1e4zn3gSoTZZhaOreLBNshTMENRKuaOChL7I6S52ujdfQ4QkFvI2WbQmxF5wQcOyFVPjoI5dy4VM4SieprSHzAxglIqr7lU7QWg5cqsSq6WnGfNcD/15q/wA "J – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ùε¢yì? ``` [Try it online](https://tio.run/##yy9OTMpM/f//8MxzWw8tqjy8xv7//4L8ksSS/P@6unn5ujmJVZUA) or [verify all test cases](https://tio.run/##AWYAmf9vc2FiaWX/fHZ5PyIg4oaSICI/ecKp/8OZzrXCrnPConnDrD//fcK2P/9oaQpwb3RhdG8KcHF3ZXJ0eXVpb3AKdGhpc2lzYW5leGFtcGxlCm9yZWdhbm9lc3F1Zf8tLW5vLWxhenk). **Explanation:** ``` Ù # Uniquify the (implicit) input-string ε # For-each over each character in this string: ¢ # Count the amount of times the current character occurs in the (implicit) input yì # Prepend the current character before this count ? # Print it without newline ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Lƙż@Q ``` A full program printing the result (or a monadic Link yielding a list of pairs of characters and integers). **[Try it online!](https://tio.run/##y0rNyan8/9/n2MyjexwC////X5KRWZxZnJiXWpGYW5CTCgA "Jelly – Try It Online")** There are loads of ways to achieve this in 6 bytes (e.g. `Qżċ@€¥`). ### How? ``` Lƙż@Q - Main Link: list of characters, S e.g. "cabbage" ƙ - for groups of identical elements (of S): (c aa bb g e) L - length [1,2,2,1,1] Q - de-duplicate S "cabge" @ - with swapped arguments: ż - zip [['c',1],['a',2],['b',2],['g',1],['e',1]] - implicit, smashing, print c1a2b2g1e1 ``` [Answer] # [Python 3](https://docs.python.org/3/), 62 bytes ``` f=lambda s:s and s[0]+str(s.count(s[0]))+f(s.replace(s[0],'')) ``` [Try it online!](https://tio.run/##HcpLCoAgEADQq7jTwYigXdBJosXkhwJTcaZFpzdt@3j55TPFuVa/BrwPi4IWEhitoG3aNXFRNJr0RFYdALRvUFwOaNxPg5QANZerFa9kToycOn0 "Python 3 – Try It Online") [Answer] # JavaScript (ES6), 55 bytes ``` s=>[...new Set(s)].map(c=>c+~-s.split(c).length).join`` ``` [Try it online!](https://tio.run/##Zc2xbsJAEATQPl9hUdmKODRHbX4iJYrE4iz2ofPt@W4dQ5Nfd0xIUsA008zTnOmTcpNc1HWQD55P9Zzr3d4YE3gq3ljLXL2bnmLZ1Lvm9WudTY7eadlUxnNotavMWVw4HOZGQhbPxktbnspVFCWVVVUV/9lsigixagkvj@th4qTX0Un8I7e1HTCBkaC4YoSDPEntXHaZAl@oj55vepGKDs5mSzaA7QU9IvyTlcQtBeE8jPx7u1ixCbxtQQjIGJbfR0f3HO/1IxdH2B4xfwM "JavaScript (Node.js) – Try It Online") ### Commented ``` s => // s = input string [...new Set(s)] // create a set from the input string and split it, // resulting in an array of characters arranged in // order of first appearance .map(c => // for each character c in this array: c + // append c ~-s.split(c).length // followed by the number of occurrences in the // original string ) // end of map() .join`` // join everything ``` [Answer] # perl -p, 52 50 bytes ``` s/./$&1/g;1while s/(\D)\K(\d+)(.*)\1\d/($2+1).$3/e ``` [Try it online!](https://tio.run/##BcGxDsIgEADQna9wIA3YyAWNU1c3f4GFpJeWBLkrR1P9eel7jDU/exdwoAcPy@SPNWW8CJjwsuFtwjxa4642@DCD0ffRW6cfgL0ztdhI8XZgbb89Eau2JkkSC37jhzMqqrjEQijbjn/ilqhIv/EJ "Perl 5 – Try It Online") Starts off by adding 1 to each character. Then, as often as possible, find a letter followed by a number, with the same letter elsewhere in the string followed by a digit (which has to be 1). Increment the count, and remove the same letters followed by its 1. Initial solution, following a very different technique: # perl -nF//, 52 bytes ``` $F{$_}++for@F;$F{$_}&&print$_,$F{$_}xor$F{$_}=0for@F ``` [Try it online!](https://tio.run/##XY5Ba8JQEITv@RWDBi9W0h48BcHTOxd6rCKvsNGFuLu@tyGWYn96U2Ogh85phhn4xii168HUsA3gBmXA@@plj803qp1UNYA53jyxQRsI9S0LjUMW6xynmME@lOGrPNyWy0bTNtRTWiwssXh5eJryVdNkNs@P2VA/@tlOZiPln@Z4HVvEP@YHeU8k0M7v5Hz/7NG1sEtPyT87Viv8xJlzFLrGs7VUaKJjFKV86ehHzVklDysJVfUL "Perl 5 – Try It Online") Reads a line from `STDIN`, assuming it's **not** newline terminated. Splits the input into characters, available (in order), in `@F` (due to the `-F//`). Counts the occurrence of each character in the hash `%F`. Then loops over `@F`: if present in `%F` with a true value, print the character and its count, then set the corresponding entry in `%F` to 0. This ensures each character is only outputted once. The TIO code has some header and footer code so we can handle multiple test inputs. They're not needed if we just have one line of input. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` ọ∋∋w⊥ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpkcdKx7u2vFwV2ftw60T/j/c3fuooxuIyh91Lf3/P1qpIL8ksSRfSUepoLA8taiksjQzvwDIK8nILM4sTsxLrUjMLchJBYrkF6WmJ@blpxYXloK4iRCQBKGUYgE "Brachylog – Try It Online") Full program, or alternatively a predicate which prints the output then fails. Could be [one byte shorter](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/w939z7q6Iag//@jlQrySxJL8pV0lAoKy1OLSipLM/MLgLySjMzizOLEvNSKxNyCnFSgSH5RanpiXn5qcWEpiJsIAUkQSikWAA) if it could generate the characters as a mix of strings and integers, but that seems like a bit too far out there of an output format. ``` w Print (without a newline) ∋ an element of ∋ an element of ọ a list of pairs [element, # of occurrences] in order of first appearance, ⊥ then try it again some other way. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~105~~ \$\cdots\$~~93~~ 90 bytes Saved ~~2~~ 5 bytes from the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! ``` d;c;f(char*s){for(;d=1,c=*s;c-1&&printf("%c%d",c,d))for(char*q=s++;*++q;d+=*q==c?*q=1:0);} ``` [Try it online!](https://tio.run/##ZZHRboIwFIbvfYqGRFMEEk6NF1vHdrHsKcSLWgpilJa2RIzx1ccKqGPZSdrmnP5f/uYvjwrOuy6jnOaY75leGv@aS41plkDIk6WhPILFQumysjn25nyeeSEPM9/vVQNRJyYI6DIIapoFiWsT/uF2eI19eutOrKywj64z5GrQI73ZogRdvbT9Imn78unW2gvRtF95NzohrDDW3CklLbOy16v6LLS9NKVUfWv3pSkNq0TLTuoo@pHUomCVFKZuhp6NtRuPvx6iVaK1Ihtseh@QxBIGgxOp4QwCNFi4QAMlyGFuYQ8lMYSRCgRp4QQKjsONJBrEqgAGFRioHTP4w2oHU1u0a/Jc6A3Ecbwdxy5XhF3a6ODeEVN3vKE1RUFweKTYl7Gaqwse8fAe0GHr06fi8WWpNzeph6J3lHruDSMx0eX43@gXRXjE/bRy7DOip9Ftduu@eX5khemi8w8 "C (gcc) – Try It Online") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html) + `-F ''`, 65 + 4 = 69 bytes ``` {while(i++<NF)if(!a[$i]++)b[i]=$i;while(j++<i)printf b[j]a[b[j]]} ``` [Try it at awk.js.org](https://awk.js.org/index.html?gist=ac8b7f486b4843f801f434197914da9d) A shorter ~~64~~ 59+4 byte program, which runs on GNU awk with `-F ''`, is this: ``` {while(i++<NF)if(!a[$i]++)b[i]=1;for(i in b)printf$i a[$i]} ``` Annoyingly, though, while 'Try it online' links to the GNU awk manual page, it doesn't seem to use GNU awk, and refuses the `-F ''` command-line option. The alternative link above (to awk .js.org) accepts the command-line option, but then outputs in a different order, which costs a frustrating additional ~~one~~ six bytes to correct (which I have included above as the price of verifiability). [Answer] # [CJam](https://sourceforge.net/p/cjam), 12 bytes Port of the Pyth answer. ``` q:A_&{_Ae=}% ``` [Try it online!](https://tio.run/##S85KzP3/v9DKMV6tOt4x1bZW9f//gvySxJJ8AA "CJam – Try It Online") ## Explanation ``` q Take the whole input :A Assign to a variable _& Set union w/ itself { }% Map: _ Join the uniquified character Ae= With the count of the character in the input string. ``` # [CJam](https://sourceforge.net/p/cjam), 16 bytes CJam has the built-in, so I guess it simplifies the question. Unfortunately the built-in does it in the wrong order... ``` q:A{A#}$e`{-1%}% ``` [Try it online!](https://tio.run/##S85KzP3/v9DKsdpRuVYlNaFa11C1VvX//4L8ksSSfAA "CJam – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, 28 bytes ``` s|.|($b=s/$&//g)?$&.$b:''|ge ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4Rq9GQyXJtlhfRU1fP13TXkVNTyXJSl29Jj31//9ECEiCUP/yC0oy8/OK/@sWAAA "Perl 5 – Try It Online") [Answer] # [Ruby 2.7](https://www.ruby-lang.org/en/news/2019/12/25/ruby-2-7-0-released/) -paF|, 17 bytes ``` $_=[*$F.tally]*'' ``` [Try it online!](https://techiedelight.com/compiler/ruby?CpL5) This is more or less built in to the recent Ruby release as the `tally` method. [Answer] # [K4](https://kx.com/download/) ~~17~~ 16 bytes **Solution:** ``` {,/(?x),'$#:'=x} ``` **Examples:** ``` q)k){,/(?x),'$#:'=x}"potato" "p1o2t2a1" q)k){,/(?x),'$#:'=x}"pqwertyuiop" "p2q1w1e1r1t1y1u1i1o1" q)k){,/(?x),'$#:'=x}"thisisanexample" "t1h1i2s2a2n1e2x1m1p1l1" q)k){,/(?x),'$#:'=x}"oreganoesque" "o2r1e3g1a1n1s1q1u1" q)k){,/(?x),'$#:'=x}"aaaaaaabaaaaaa" "a13b1" ``` **Explanation:** ``` {,/(?x),'$#:'=x} / the solution { } / lambda function taking implicit 'x' argument =x / group x (dict of unique chars => indices) #:' / count length of each group $ / cast to string ,' / join each-both ( ) / do this together ?x / distinct x ,/ / flatten ``` [Answer] # [R](https://www.r-project.org/), ~~72~~ 71 bytes ``` cat(rbind(z<-unique(y<-el(strsplit(scan(,""),""))),table(y)[z]),sep="") ``` [Try it online!](https://tio.run/##FcoxDoAgDEDRuzC1CdwAT2IcCjKQEEBaBrl8xeEvL3@oRhIYIdcblnez5mcmeL1LBVgG95IFOFIFawz@IVqhUPaE57rQcurHZu1NSJp@ "R – Try It Online") [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 96 bytes ``` I =INPUT N I LEN(1) . X :F(O) N = S I X = :F(B) N =N + 1 :(S) B O =O X N :(N) O OUTPUT =O END ``` [Try it online!](https://tio.run/##K87LT8rPMfn/n9NTwdbTLyA0hMsPyPRx9dMw1FTQU4jgtHLT8Nfk4vRTsOUKBspEKNiChJwgQn4K2gqGnFYawZpcTpz@Crb@QHk/IN9Pk8uf0z80BGgeUJDL1c/l//@SjMzizOLEvNSKxNyCnFQA "SNOBOL4 (CSNOBOL4) – Try It Online") ``` I =INPUT ;* Read input, set to I N I LEN(1) . X :F(O) ;* Get the first character of I as X; if I is empty then goto O N = ;* set N to empty string (evaled as 0 in arithmetic) S I X = :F(B) ;* remove the first occurrence of X from I. If none exist, goto B N =N + 1 :(S) ;* increment N and goto S B O =O X N :(N) ;* Add to the output string and goto N to get the Next character O OUTPUT =O ;* print the result END ``` [Answer] # T-SQL, 111 bytes Added a line change to make it readable ``` WHILE @+@ like'_[a-z]%' SELECT @=concat(s,left(@,1),len(@)-len(s))FROM(SELECT replace(@,left(@,1),'')s)s PRINT @ ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1249018/special-string-reformatting)** [Answer] # [JavaScript (V8)](https://v8.dev/), ~~106~~ 102 bytes ``` e=>{for(o="",i=0;i<e.length;i++)o.includes(e[i])||(o+=e[i]+e.match(RegExp(e[i],"g")).length);return o} ``` [Try it online!](https://tio.run/##LYzBCgIhFEV/JVwpTtIyMNv1A22jhdjTMcwn@mYImr7dpmh34Zxz73a2zdVYaDvvuzcdzPHlsXI0jA3R7HQ8gEqQA406SilQxezSdIPG4RKvYlk4SvOdEtTDkhv5GcLpWX54YIEJ8e@FrkBTzRt8d4e5YVqfMXDPWUGyhKvaPw "JavaScript (V8) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~8~~ 7 bytes *-1 byte thanks to @isaacg* ``` s+R/Qd{ ``` [Try it online!](https://tio.run/##K6gsyfj/v1g7SD8wpfr/f6X8otT0xLz81OLC0lQlAA "Pyth – Try It Online") ``` s+R/Qd{ { Deduplicate: keep the first occurrence of each unique character R For each of these unique characters: + - append the character /Qd - to its count in the original input s Join the resulting strings ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ô!Ω;òá☺ ``` [Run and debug it](https://staxlang.xyz/#p=9321ea3b95a001&i=potato%0Apqwertyuiop%0Athisisanexample%0Aoreganoesque%0Aaaaaaaabaaaaaa&a=1&m=2) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 31 bytes ``` +`(.)(.+)\1 $1$1$2 (.)\1* $1$.& ``` [Try it online!](https://tio.run/##JYhLCoAwDAX3OYdIq1Co5@nCCEEL2vQTUU9flb5ZDPMyiQ9Y6zgro5UZtbPQ2Y8JvsPZ4S/T1xpZUBhiuijLc3qOIJsvvmCgG4@4E3CmFQNTSScBti1NLw "Retina 0.8.2 – Try It Online") Link includes test cases, unusually without even needing a header. Explanation: ``` +`(.)(.+)\1 $1$1$2 ``` Collect all repeated characters into a single run at the first appearance. ``` (.)\1* $1$.& ``` Replace each run with its first character and its length. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` ⭆Φθ¬№…θκι⁺ι№θι ``` [Try it online!](https://tio.run/##JYpBCoAgEEWv4nIEO0FLoV0RdAIRSWlozMag00@Gm/fh/eejK54ciqwlnQwbt9lnl2FKyKHAZdRCDJZqe@3rMdhI@deHNipp3bhivSEZ1aOraz2KZGLHJMODHw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input string Φ Filter over characters № Count of ι Current character in θ Input string … Truncated to length κ Current index ¬ Is zero ⭆ Map over unique characters and join ι Current character ⁺ Concatenated with № Count of ι Current character in θ Input string Implicitly print ``` [Answer] ## [Kotlin](http://kotlinlang.org), ~~69~~ 67 bytes ``` fun String.f()=groupBy{it}.map{(a,b)->"$a"+b.size"}.joinToString("") ``` [Try it online!](https://pl.kotl.in/Yc2JZ5MDK) [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 57 bytes ``` s=>s.GroupBy(c=>c).Aggregate("",(r,g)=>r+g.Key+g.Count()) ``` [Try it online!](https://tio.run/##NY3PSgMxEMbP5ilC8JDgug/gmoVaUETBowfxEMNsGqhJmplYl7LPvjYNzmG@P3zws3hr0a@PJdh7pOyD63jTkU9cr6hH7J9yLOlhllaPVvUb5zI4QyCF6GTunNJjvnH9C8znv40lkFRqHRj7MZkTICHXPMDx45Od2JVIkQxF0VV7OEKmufiYLpl2Hj2aAL/mO@3h0sUKCxHwUFph2n01EWwZ2HQeGbvj8p/IfWhkVZHbGDDuoX/PnuDVB5DX4jmkQnf8VFcLfyvU4iRroRahBrasfw "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # SimpleTemplate, ~~54~~ 47 bytes This was a very easy, but incredibly fun challenge! The code simply loops through every character and counts how many times it shows, and presents it all again. Nothing fancy at all... ``` {@eachargv.0}{@incR.[_]}{@/}{@eachR}{@echo__,_} ``` Hey, I didn't say the code was readable! --- Here's an ungolfed and readable version: ``` {@each argv.0 as char} {@inc by 1 result.[char]} {@/} {@each result as times key char} {@echo char, times} {@/} ``` Should be easy to understand ... `{@inc}` increments the value or creates a new one, if it doesn't exist. (this keeps key ordering). --- You can try this on <http://sandbox.onlinephpfunctions.com/code/a180782e659c29674fbb0d77dc82d90d238c6e08> Older version: <http://sandbox.onlinephpfunctions.com/code/6ee5077eaf38ec445d84086cc07966026ca7c565> (There, you have an example on how to use this in a function, with multiple tests.) ]
[Question] [ ## Intro/Background I was looking at a Flybuys card at Coles recently and noticed that if I took something like this: ![Flybuys](https://i.stack.imgur.com/zMG2F.jpg) [Source, randomly found on the Internet](http://moneyoff.com.au/images/fly-buys4.jpg) And swapped some words around, I'd get this: ![Buyflys](https://i.stack.imgur.com/4y0dN.jpg) After I finished laughing (don't judge my sense of humour please), I said to myself: "I need a program that can generate text like that". So I devised a set of rules for substring swapping and wrote yet another CGCC challenge! ## The Challenge Given a single string as input, output a string with its substrings swapped. This can be done by: * Splitting the string into chunks of three. The last triplet can possibly be shorter. (`abcdefgh => [abc, def, gh]`) * Swap every triplet with every other triplet, leaving the last triplet in place if there is an odd amount of triplets. The above bullet point more succinctly: > > [D]ivide the list into adjacent pairs and swap each pair ~ @FlipTack > > > ## Test Cases ``` Input->Output flybuys->buyflys Once->eOnc Triplet->pleTrit Code Golf->e GCodolf TopAnswers!->AnsTops!wer Never gonna let you down->er Nevna gon yoletownu d I'm Sorry, I Haven't a Clue-> SoI'm, Irryven Haa C't lue Can I please have my vegetables back?-> I Canasepleve havegmy bleetaacks b? You are filled with determination-> arYouille fwited eteh dnatrmiion -> ``` [Reference Program](https://tio.run/##bVKxboMwEJ3DV1xZAgqNmmaLFFVVhjZLM6RLFTE4cAa3xkbGBPH19GySCkX1Yt97T@/dHdS9LbVaD0OOHHjU6NZkGG@CmTWilmgb2MIppRKrmp5hGMy4NpCVzIBQMOpJDnQEB4kqctIYtltYX3F3bnZLVteo8lE0oUd7ZzuCKBvc3PGLmyCYUZSDror/zcdOhWvTMFVg9JSM/V3VMTzCKoHn@M7lJNJkUsACVin1dodMJSllGbStUbSg5bcWk5BgyFiDfo0hl/257ZswgfCgMnT356hzz53OEd605B7X9atqOjTNgys/8IIGCq0Uoxks9LqFXHfKcft5BUdtTJ/AHt7ZBdXcAoOdbH3CjinCKYTagJJoqHq4YIGWnSU1dmbZz4sTfpEnMwhcSIk5dMKWkKNFUwnFrNA@LKRZA/8HODtarZ@ONlgboWwUHowoSC43IW3JcfEfdezc58k9wyPPxcMv) ## Some Test Cases Explained ``` flybuys [fly, buy, s] (split) [buy, fly, s] (swapped) buyflys Once [Onc, e] (split) [e, Onc] (swapped) eOnc Triplet [Tri, ple, t] (split) [ple, Tri, t](swapped) pleTrit Code Golf [Cod, e G, olf] (split) [e G, Cod, olf] (swapped) e GCodolf TopAnswers! [Top, Ans, wer, s!] (split) [Ans, Top, s!, wer] (swapped) AnsTops!wer ``` ## Rules * Input/output can be taken/given in any reasonable and convenient format * The input will not contain newlines * Strings can be of any length, and can be empty * Input will only contain printable ASCII characters * All standard loopholes are forbidden ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with the lowest bytes wins [Answer] # [J](http://jsoftware.com/), 13 bytes ``` [:;_2|.\_3<\] ``` [Try it online!](https://tio.run/##Pc9RS8MwFAXg9/2KM1@CsA3Rt6oMKagDUdC9iBsjW2@3apaMJN0o@N/rqSx9KNye8@WGfLcXE1XiPoPCCFfI@I0nyN9fHtuv7HZ1/TtZrG7uFsv2cjCQzc5BreumNE1QGGcooTgzCercypvdpIqjpPxgZO6rmCrOTGJ/Ck@5K5wpU88/Zl1wFg82zN0hDE/i@x3uwJRBGPZ7PF7laDW2zqJxvMGdbI0iHWFJwpKEJQlLknQeH26m1H6EmffNUSyetUauVISpJS3pBCEFHQVdJwg7lDbNkGurg/CZRwF2ZNt9g7URiVpvfgLW0/612tJT0v9LUNJT0lPST/vN2n@6ujJGUJ6qKAUkyg6F1dHvq8rZtJWKlqqzBWipaKloO9j@AQ "J – Try It Online") Example input: 'flybuys' * `_3<\]` Box every group of 3 ``` ┌───┬───┬─┐ │fly│buy│s│ └───┴───┴─┘ ``` * `_2|.` Split *that* into groups of 2, and reverse each one: ``` ┌───┬───┐ │buy│fly│ ├───┼───┤ │s │ │ └───┴───┘ ``` * `[:;` Raze the result: ``` buyflys ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 24 bytes ``` {S:g/(...)(..?.?)/$1$0/} ``` [Try it online!](https://tio.run/##HZCxbsIwEIZ3P8WPhAhIJMDSoVIdVQyUpR1gqaoOhlyCVWNHtgFFVZ@d/u1yvrvvO@vsXqJ7uJ8HTFo83b93j91iWlXVjKGu6tlivBovFz/3ZAZUH8vPatLOUcAmFHM2Vp9oQ4SzXpLWVeqdzdOi1MXs3rrhcBlSqRmZJ/Xmj1Jq4aH20fZOcqkZmWe1Do1gE1xLARtWTNU@9M8@3SSmUamZsU4jlupVrhLRBe8NeA2GcEETbp7DEYRsE7JNyDah2hZn7EKMwxxbvJir@CLDYO0u3ImEnISchJyEnFCtjecE9zRJcOIg@FdX6SSbg5OEgzl@1bxiC5p0aNL5NzuadGjSoVmrdy5qoqC1zkmDm80nNJIlnq032Qa@gJzWH0dLToucFjktKqrUvw "Perl 6 – Try It Online") Simple regex substitution that swaps every pair of three and up to three. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` s3ṭ2/ ``` A full program accepting a string which prints the result. **[Try it online!](https://tio.run/##y0rNyan8/7/Y@OHOtUb6////j8wvVUgsSlVIy8zJSU1RKM8syVBISS1JLcrNzEssyczPAwA "Jelly – Try It Online")** ### How? ``` s3ṭ2/ - Main Link: list of characters s3 - split into threes 2/ - 2-wise reduce with: ṭ - tack - implicit, smashing print ``` [Answer] # [Gema](http://gema.sourceforge.net/), 13 characters ``` <u3><u3>=$2$1 ``` Sample run: ``` bash-5.0$ echo -n 'flybuys' | gema '<u3><u3>=$2$1' buyflys ``` [Try it online!](https://tio.run/##S0/NTfz/36bU2A6EbVWMVAz//0/LqUwqrSwGAA "Gema – Try It Online") / [Try all test cases online!](https://tio.run/##lZFNb9NAEIbP2V8xsUy3lYgChVtrSlWhkguVgAtKLbSxx4lVZ9faXSdYhd8e3tlIhQMcevDOx/vM7Mx6ZcLmUHPVGc80u6bIIX6vTODiVE2WuunG1TAGXRYaFlHQkr6zFUuO4aTEV9/2HUfJwSKKKX3jaqZb1zUJplvEEqQK11/bsGcfpiLCRyZMkUjyJ96xp7Wz1hAa0@gGqt3epkaeIEOADAEyBMhSmC30lr4478eXtKCPZsdWRzJ00w2clUUGDQQ0ENBAQAMhcprYWNRhBzwBbVBO25F2vOZoVh0HWpnq4UqGAAUWFFhQiV2DBQUWFNirtMo3jC6v27RdxzXt27ihmiP7bWtNbF3aCQQ4IagBAQ4EOBDgBFJnSvW@tbEh/ZNezN6@CvQPe47z3mrSC9sPEfYzh6ET58OPnit0hnv3oJVqnKdWIJyU5Y/Tp3@/fF/@yi7w3mriU3WR5afE1cbRTNBUleG2uevjfM1bMw@@Sg7pw@Xw5p18RX6evz5oOsuUmjxj8qf@WX68XbzHP8MdZUxIMtVy@RdXFP9Dy5JOTo4ryPYyVO0sH34D "Bash – Try It Online") [Answer] # Brainfuck, ~~37~~ 33 bytes ``` ,[>,>,>>,>,>,<<[.>]<[<]<<<[.>]>,] ``` -4 bytes thanks to @JoKing You can [try it online](https://tio.run/##SypKzMxLK03O/v9fJ9pOBwjBhI6NTbSeXaxNtE2sDYRppxP7/39IUWZBTmqJQnB5YkFBZl46AA) Cell layout is `|a|b|c|0|d|e|f|`, I read unconditionally and then print what is there to be printed. Probably still golfable... [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 17 bytesSBCS ``` ⍬∘(⍋⍋-6×3≤6|⍋)⊃¨⊂ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/x/1rnnUMUPjUW83EOmaHZ5u/KhziVkNkKP5qKv50IpHXU3/04AqH/X2QTQBBdcbP2qbCOQFBzkDyRAPz@D/aQrqIUWZBTmpJQrB5YkFBZl56epcQMG0nMqk0spidQA "APL (Dyalog Unicode) – Try It Online") Uses `⎕IO←0`, i.e. 0-based indexing. ### How it works Uses [`⍬⍋` generating index](https://codegolf.stackexchange.com/a/155586/78410) trick, though [simply using `⍳≢` gives the same byte count here](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qn/6O2CQb/04CkxqPe7ke9m3XNDk83ftS5xKwGyNF81DHjUeeiR13Nh1Y86mr6/z9NQT2kKLMgJ7VEIbg8saAgMy9dnQsomJZTmVRaWawOAA) (thanks @ngn for pointing this out). ``` ⍬∘(⍋⍋-6×3≤6|⍋)⊃¨⊂ ⍬∘( ⍋-6×3≤6|⍋) ⍝ Generate some numbers to apply "sortBy" on the input ⍬∘ ⍋ ⍝ Generate 0-based indexes 6| ⍝ Modulo 6 3≤ ⍝ 1 if 3≤x is true, 0 otherwise 6× ⍝ 6 times ⍬∘ ⍋- ⍝ Subtract from the original 0-based indexes; ⍝ the result looks like 0 1 2 ¯3 ¯2 ¯1 6 7 8 3 4 5 12 13 .. ⍋ ⊃¨⊂ ⍝ "sortBy"; sort the input in the increasing order of above ``` [Answer] # [PHP](https://php.net/), ~~60~~ 57 bytes ``` for($a=str_split($argn,3);$b=$a[$i++|0];)echo$a[$i++],$b; ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNFQSbYtLiuKLC3IyS4CcovQ8HWNNa5UkW5XEaJVMbe0ag1hrzdTkjHwoP1ZHJcn6//@0nMqk0srif/kFJZn5ecX/dd0A "PHP – Try It Online") [Answer] # [W](https://github.com/A-ee/w), 5 bytes ``` "jC?┐ ``` Uncompressed ``` 3,2,_r ``` # Explained ``` 3,%Split the input into chunks of three 2,%Group the inputs into chunks of two _r%Reverse every two-chunk of the input ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` s3s2Ṛ€ ``` [Try it online!](https://tio.run/##y0rNyan8/7/YuNjo4c5Zj5rW/P//P6QosyAntUQhuDyxoCAzLx0A "Jelly – Try It Online") A full program taking a string and implicitly printing the rearranged string. This could be turned into a monadic link that returns a Jelly string by adding `F` (flatten) to the end. ## Explanation ``` s3 | Split into sublists length 2 s2 | Split into sublists length 2 Ṛ€ | Reverse each ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 36 bytes ``` x=>x.replace(/(...)(..?.?)/g,"$2$1") ``` [Try it online!](https://tio.run/##PZHBbsIwDIbveQqDkGglWsauqEUTB8ZlO4zLhJBqilu6haRKQqFPz37YtEvi@Puc2s0Xd@xL17QhMfYgtyq7XbP8mjppNZcSTaM0TWMsi3QRT@vJcPQ8mg3jW8eOSvbiKaOi0v3@3Pskx4rYq3dTSpILNrXB3VpCkmNFHNQSn6GV1RUEWuGEUG1s@2L8RZwfJDkinP0AR/UmnTiqrTFMuIZ6e6aDvRgUOwJEGhBpQKQB1Xp8og/rXD@hNb1yJ2YciGmpz@gJBBwEHAQcBBxQLdmgAn1iLjqikE49dVJL4L3GpHsuvxe4Yk0w4cCE8zBrmHBgwoG5UJ9olJ1Q1WgtB7o04UgHCeJOjeHQWEwADuvOqQKHBQ4LHBYUleRF6lvdhEIV6Ynb6EpZTte/HGg8V5V1FN2fg8lWv28SKyqt8fgnqbZ1xNun3YSqxx7/B5RlxNvZLp7ffgA "JavaScript (Node.js) – Try It Online") Simple regex substitution. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 3ô2ôíS ``` Outputs as a list of characters. [Try it online](https://tio.run/##yy9OTMpM/f/f@PAWo8NbDq8N/v8/JL/AMa@4PLWoWBEA) or [verify all test cases](https://tio.run/##FY0xTsNAEEWv8tkmILkiB7CQkSAUpAgNQhTjeJysWO9Eu2tb21FxAGquQJeewjfJRcy4mj//f70vkWrL85BLg8vXN0yZ5/V0vp3O0@9uvi@fLp8/uDbTn7lRVcxvpnW57nM0hdn6Pet5CfbkOKmqpGE8iGsXV053Po4c4pV@zzxwwEG8J2gXWXo0MnqNNqsOOwkhF9jgkQb2qwRC5foFXpFXW/kUGUdN0WUMfOBEteOImvYfpfZeFUiB0VrnuMFo0xENJw6d9ZSsLEvm/R8). **Explanation:** ``` 3ô # Split the (implicit) input-string into parts of size 3 2ô # Split this list into parts of size 2 í # Reverse each inner pair of triplets S # Convert it to a flattened list of characters # (after which this is output implicitly) ``` [Answer] # [Factor](https://factorcode.org/), 62 bytes ``` : f ( s -- s ) 3 group 2 group [ reverse concat ] map concat ; ``` [Try it online!](https://tio.run/##NZAxT8MwEIX3/opHl4JEGGBLB1RlKFnCEBgQYrgml9TCsY3jJIoQvz1cVceD7ed3fp99DVXB@uW9zItjitbbwSnTouefgU3FPZznEGbnlQnYb/IixZtXTnNIyoncpXhJ0eAWPZJEpjs8XWPwGNdPeB7Z94zKmooCvtCRW8V@@d1AxrbR82mY@@1VvQo8biMvqszWjKPVzepadzD9JPk38aS40NBaYwhyD7MdUNvJRDvfdSit9/M9crzQyGYXQMj0sAIzMmIJk@TNZ6lAN2PklgOdtLTkRNX3c6z9kHDyjEZpzTUmFc6oObDvlKGgrFD/pANN/PTD8g8 "Factor – Try It Online") [Factor](https://factorcode.org/) defies golfing :) [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 10 bytes ``` 3/2/{-1%}% ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/31jfSL9a11C1VvX//7ScyqTSymIA "GolfScript – Try It Online") # Explanation ``` 3/ # Split the input into chunks of three 2/ # Group the inputs into chunks of two {-1%}% # Reverse every two-chunk of the input # This deals with the last two-chunk, in which # no reversing is done ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes ``` ⭆⪪S⁶⪫⮌⪪ι³ω ``` [Try it online!](https://tio.run/##LYpBCsJADEX3niLLCdSV4KYnUBDEniC0qQ3EmSGmLZ4@Duji8@C9Py5kYyGNuJtkT4M3PG9U01BVPF1yXf0nE3ZwbrsWyenBG9ub/y/p4IQt7YjYR3zKCmQMs6jyBLv4AhM720syuZR8iOOmXw "Charcoal – Try It Online") Link is to verbose version of code. Splitting into groups of 6 and splitting those works out shorter because it keeps the two numbers separate. Explanation: ``` S Input string ⪪ ⁶ Split into substrings of 6 characters ⭆ Map over substrings and join ι Current substring ⪪ ³ Split into substrings of 3 characters ⮌ Reverse the substrings ⪫ ω Join together Implicitly print ``` [Answer] # [Haskell](https://www.haskell.org/), ~~50~~ 42 bytes ``` s(a:b:c:d)=take 3d++a:b:c:s(drop 3d) s x=x ``` -8 bytes thanks to [Post Rock Garf Hunter](https://codegolf.stackexchange.com/users/56656/post-rock-garf-hunter). [Try it online!](https://tio.run/##RVDBbsIwDL3nK94qJECFXXZDotPUaRvSNA7sMm3T5BIXItKkSlJov74L7YGTn/1sv2cfyZ9Y615VtXUBzxTo/sVqSYVmzErr/uZCBPYhJ88ea3wLJKXuiqbzySLirdnzAD6dqjWHAedWMl6tLkfG1k/GX9j5uyH/4DM7HKwxhDiBzjaQ9mIGcjOtsLPOdQts8EZnNtMAQq6bUSYnE4moFP3gGHlUHc584HC17FHQ/vQ4dH7FteQYpdKaJS4qHCE5sKuUoaDsqJf8ClGRMvE0aQXqJuyCezfRiIl4mW2bEGMicP0Fbp@Y4KfFMrsNTNAiTZEss@QaPdrez2hVrPYrOV8HOjEeZJqOFT@TztaxMBexcd32/T8 "Haskell – Try It Online") [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 15 bytes ``` ,//|'0N 2#0N 3# ``` [Try it online!](https://tio.run/##JY/LTsMwEEX3fMU0RQpIRUWwSxYV6qJ0UxawQVWkOs04jeLYle0@LB6/Hq7xxvbcc2Y07h90q8dRFrP5/Dt/3NDTFMfzdPTF1@02/NpC0rXcmb6820nRqfJahtLeVz83fptJFepTcFmZ4ULhsirGb3rPyBh3Cj5sd1TskeFC4VO8NA3TyigZZVqhjO/UYY4v2l3YugkgngjcBHXCGz6zpdZoLQiDKZgTNeai4yBLoMhBkYMiB02N63ygd2NtmNGaXsWZde5J0FKd4sZAEIAgAEEAghBp2lho9OETwjEd0E5DoDO37EWt2FEt9v0iDloTVEhQIf2rLVRIUCFBXaSRn1hdWCbZKcUNXTp/oIY926HTwncm/gkCtCiQhAANAjQI0KJTjX8 "K (ngn/k) – Try It Online") `0N 3#` chunks of 3; last may be shorter `0N 2#` pairs of chunks; last may be a singleton list `|'` reverse each `,//` flatten [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 13 bytes ``` 3co2co)<-FL\[ ``` [Try it online!](https://tio.run/##SyotykktLixN/f/fODnfKDlf00bXzScm@v9/T/VcheD8oqJKHQVPBY/EstQ89RKFRAXnnNJUAA "Burlesque – Try It Online") ``` 3co # Chunks of 3 2co # Chunks of 2 )<- # Map - Reverse FL # Flatten \[ # Concatenate ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ò3 ò cw ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=8jMg8iBjdw&input=IkNvZGUgR29sZiI) [Answer] # [PHP](https://php.net/), 153 bytes ``` $c=($h='array_chunk')($h(str_split($argn),3),2);foreach($c as&$i)count($i)-1&&[$i[0],$i[1]]=[$i[1],$i[0]];echo implode(($m='array_merge')(...$m(...$c))); ``` [Try it online!](https://tio.run/##NY3BS8MwGMXv@Ss@R1gb6IbTYx1DBuouenAXmWWk6dcmLE1Ckm70n7fGgpf34L3H7znppqedkw4mKrY5lduMe8/Hs5CDuWQsJXmI/hycVjGn3HeGFY@seGBlaz1yIXMqgIclVUzYwaSNYqvNcnmi6nRfFUk3VbU9zV7MWVWikBZU77RtMM9p///Zo@8wfa7Xa9rPKhhj5TTvF99mUU6tHuthDOTDCCRHr5zGSPaJA69Wt@Ro3bMJN/ThjrzjFT101hgOaQWjHaCxN0MOWQ@f1vuxgAO88SuaLAKHvR6Q7LlJYaLygCBTB/0IV@ww8lpjgJqLy458JRT3CK3SGhu4qSihwYi@V4ZHZc2PdX8WptXLLw "PHP – Try It Online") [Answer] # [Lua](https://www.lua.org/), 43 bytes ``` print(((...):gsub('(...)(.?.?.?)','%2%1'))) ``` [Try it online!](https://tio.run/##RZJBi9swEIXPq18xSzGSwQ5sj4E4lFC2ubSFbg/Fm1LFHjtmZSlIcrb59emzsptisEfzvnmSR2MmfTGu0YY6WpFxuq3ry9EPNiqlFotFvuzDtFcyxWqxnp9cFjL7mD3IPM8vu50QVwPP2nyfKwuEYTIRhslJiPTBsptsEwdnk5u40yGwjyqw4SYq@UEWNAu0WtFDQfJnGGxPo2teuL060esQD8h4pnjQlpxl0r6fRrZRwvC2L2wE2/b9aJFDDEjXtejMeT@dQ1nhjTiIb7bhsmJ8xJMfjoZjWeGNOIqNa5kenekA0CNWCMWTO36y4ZV9uC8rRFiHeyzFVz6xp95Zqwk2dHYTte7VotgTRKQhIg0RaYhiK0f64bw/F7SlL/rEVkbStDETzgQFOhToUKBDgQ5RbPD3W8I5dWA6oJDGM52456j3hgPtdfOyhsWWQIIBCSaRPUgwIMGAXItfOKhGT7vBGLQ6NbnlyH4crJ7vC0bag5p16qCDgg4KOiggoqzEPAud8zTYY0FuigiurV/2o47NAWNU/362Wbkr86ys0gLhs5U5GiXuOoXK/3Pxfpur2asgVdefvXd@SX@yIIn/HjE13BZoakyp3S5fYntspVLBtT5Pc/E2mkrJDHcP@Iamw95QDM3l8jYH/wA "Lua – Try It Online") Take input as argument, print result to stdout. TIO link include program that check all testcases given in question. Uses Lua patterns to capture three and up to three characters, then swap those groups. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 21 bytes ``` s/(...)(..?.?)/$2$1/g ``` [Try it online!](https://tio.run/##FYxBS8QwFITv@RUjLKwL2qLguUgPuhc9uBePr9vXbjB9LyRpS/68MV5mYL7h8xzcSymxvW@a5lSja7pTe3g@PLVzKZPLw5qj@ZQrm0uw3nEyvY6MN3WTuah/lbhziHfmgzcOmFWEUF/IumLUXcz5uOBLQ8gPOOOdNpZjAqF3K5uepI7VSpFxqwxLxsYzJxocRwx0/enMd1VRYEzWOR6x23TDyInDYoWSVflV/1@xPPo/ "Perl 5 – Try It Online") [Answer] # [Red](http://www.red-lang.org), 59 bytes ``` func[s][until[move/part skip s 3 s 3""= s: skip s 6]head s] ``` [Try it online!](https://tio.run/##NU@xasMwEN3zFa9asrR0CHQItKV4SLOk0HYpQsPZOsUismQk2cZf76rUPji4997dPV5kvXyylmpnjljM4BuZlBx8tk52YeTHnmJGutkeCYe/FuIZ6bhRT6pl0khqMSEyNS0y5A6lhHFzPcxJ/KMP3/A6fkfbO84rqoJmnIIzmxr6N58mjuluZS48csQ1eE8od5jDAB0mv8rnfYevEON8jzPeaWS/zyBUbtgMK/JFKp6UGG3ZQDdj5Ctnqh0n1NTcXtfdn/KcIsNY51hjsrmF5syxs56yDcVVSfTR@hK0ZO5KYPHwImCQlVp@AQ "Red – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 33 bytes ``` ->s{s.gsub /(...)(.{,3})/,'\2\1'} ``` [Try it online!](https://tio.run/##LdExbtswGAXg3ad4YQfHgKKg6dbCNgIPbpZ0aJei6kDZv2SiMmmQlB1B0S2CTj1dL@I82prM/72PBGX6tuzO1fx8twh9yOvQlri/zfN8dpv32adhdp9Ni4fi43Q4RwkxYI5@oqqmK9suKMwXUFxxDiqbqG92I9dQuEzJD28OjcRryBXnmPKV2wrWrqlGjjWTNKY97vBow0l8uLm2nJiFG0apf5ajeNTOWg2ejc612LqTHY/yIGBFwIqAFUHa@TTd47vzvsvwhK/6KHYaobFq2vHabGnY0rClYUuTQLq1ttzIz9BBsON@7DscpZaoy0YCSr35s0wnKTJiMmKyC66JyYjJiJfpyJ@8vPaCyjSNbHEycYetRPF7Y3U0bvwqGspkUNFQ0lDSUCbGs65UTYbJ5a1y0Zsd@leTuVd4vlz1y/z@gkPLZ1QfeiZzOCyh/v97U/icfv@qoYgFSzMUCvJykE00tkaKHKOM/2q8TJ6TwnB@Bw "Ruby – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~67 77 75~~ 63 bytes ~~`s` is the variable holding the string to manipulate.~~ ``` ''.join(sum([(s[k+3:k+6],s[k:k+3]) for k in range(0,len(s),6)],())) ``` [Try it online!](https://tio.run/##NZLBaoNAEIbP@hRTLyqRUgj0EAih9NDm0h7SSwmhbHQ02@iu7K5JJLSvnv4r3ZM7830zOs72oztoNb9VXFPZfNWDymy@uEWG3WAUpen9t5bIDV22zez2OJsvjrPHXUE44zTf5VRrQ0eSioxQDWcPRcu@SfGYQ8vyPL/Fjq2ztKRtHEVZUrfjfhhtUlCCJyKb5MVE3lXJPs04hNyHkX3LzqfxROQCedYV04tu66mEXhD7INTp/knZMxt75znOyNg7JILxxic21GilBOENNOqBKn1WUztDwADAAMAAwKF2nXa00caMBa3pVZxYpY4EPbfDNMBGQwCCAAQBCIKn4eOFQiUmEpbpgAbUjXTihp3Yt2xpL8rjyrdaE1RIUCFNagMVElRIUFeh6ScmEIaplm3LFZ2lO1DFjk0nlXBST6MJA80LVEOABgEaBGjeyeNdHPut@rX5xU7rW8TRpaARW/RhHPVGKpcl6ZUvPZfo85PSL6VXwyXLkw@TezTphMuCscTfCnj5f9suuCDx7Q8 "Python 3 – Try It Online") **Edit**: 77 bytes to respect the rules of Code Golf ``` f=lambda s:''.join(sum([(s[k+3:k+6],s[k:k+3])for k in range(0,len(s),6)],())) ``` [Try it online!](https://tio.run/##NZI9a8MwEIbn@FdcvVgmphQCHQKhlAxtlnZIlxIyKPY5USNLRlI@TGj/evrKoEl39zw6@3zuh3CwZna/twstu10jyc@L4vHHKiP8qRMb4TfH6Wx@nD5vK4QIZtuytY6OpAw5afYsnirN0MvqudxWoizLexbYB08L2mSTichbPexOg88rynEi83lZjeTT1BzLjCDVvpzqNYdYxoksJLK0DdOb1e14hd6QxyTds/2r8Rd2/iFyxKj4BxSS8cFndrS3xkjCE2iwJ2rsxYztHAEDAAMAAwCnu6uio7V1bqhoRe/yzKYIJGmpT@MAawsBCAIQBCAIkaaXlwY3MZH0TAc0oG6gM@85yJ1mTztZH19iqxVBhQQV0qjuoUKCCgnqS2r6jQmkY2qV1tzQRYUDNRzYdcrIoOw4mnTQokAtBGgQoEGAFp0y22ZZXGpcW9zruL55NrlWNGCLMc0mvVMmiLy48bXnGn1@C/qj4ua4ZnWOaf6IJp0MIhkLfK2EF6244t/I7v8 "Python 3 – Try It Online") **Edit 2**: Dropped the `f=` ``` lambda s:''.join(sum([(s[k+3:k+6],s[k:k+3])for k in range(0,len(s),6)],())) ``` [Try it online!](https://tio.run/##NZI9b8IwEIZn8iuuWeKIqKqExICEUMXQsrRDu1SUwZALuDh2ZJuPCLV/nb6O5Ml39zy@5HLp@nCwZnJv5t93LdttLcnPiuLxxyoj/KkVa@HXx/FkdhxPNxVCBJNN2VhHR1KGnDR7Fk@VZuhlNS03lSjL8p4F9sHTnNbZaCTyRvfbU@/zinKcyHxeVgN5NzuOZUaQap9OdZpDLONEFhJZ2prpxepmuEIvyGOS7tnu2fgLO/8QOWJU/AMKyXjjMzvaW2Mk4QnU2xPV9mKGdo6AAYABgAGA091V0dKHda6vaEWv8symCCRpqU/DAB8WAhAEIAhAECJNLy8NbmIi6ZkOaEBtT2fec5BbzZ62cndcxFYrggoJKqRB3UOFBBUS1EVq@oUJpGNqlNZc00WFA9Uc2LXKyKDsMJp00KJADQRoEKBBgBadMttkWVxqXFvc67C@WTa6VtRjizHNRp1TJoi8uPG14x36/Bb0R8XN8Y7VOab5I5q0MohkzPG1Ep434op/I7v/Aw "Python 3 – Try It Online") **Edit 3**: [Post Rock Garf Hunter](https://codegolf.stackexchange.com/users/56656/post-rock-garf-hunter) made this version which gets rid of the `sum(...,())` call, bringing the byte count down to 63! ``` lambda s:''.join(s[k+3:k+6]+s[k:k+3]for k in range(0,len(s),6)) ``` [Try it online!](https://tio.run/##NZFNb8IwDIbP9FeYXtqKCk1C2gEJoYkD47Id2GVCHELrQkaaVEn4qND219mbSjnV9vPYreuu9yejZ89ns1CiPdSC3DzLpj9G6tztzpPZ/Dx53U8QIpjtG2PpTFKTFfrI@UupGF5RvhbFM/HsvKMF7ZLRKE8b1R8uvUtLSvFE5tKiHMinrjiUGUGsfVnZKfahjCcyH8nK1Exro5qhhdbIQxL7TPem3Y2tGweOGBU3RiEaH3xlS0ejtSC8gXpzodrc9DDOEjAAMAAwAHDs3WQtbY21fUkbehdX1pknQSt1GRbYGghAEIAgAEEINH680OjERsIxnTCA2p6ufGQvDoodHUR1XoZRG4IKCSqkQT1ChQQVEtRlHPqNDYRlaqRSXNNN@hPV7Nm2UgsvzbCasNCCQA0EaBCgQYAWnCLZJ0m4ZzhbOOlwvnkyupfU44ohTUadldrnafbge8cV5vxm9EfZw3LF8hrSdIohrfB5NBb4WxEvmvxeFEXy/Ac "Python 3 – Try It Online") [Answer] # [naz](https://github.com/sporeball/naz), ~~210~~ 190 bytes ``` 2a2x1v1x1f1r3x1v2e2x2v1r3x1v3e2x3v1r3x1v4e2x4v1r3x1v5e2x5v1r3x1v6e2x6v1r3x1v7e2x7v5v1o6v1o7v1o2v1o3v1o4v1o1f0x1x2f0a0x1x3f2v1o0x1x4f2v1o3v1o0x1x5f2v1o3v1o4v1o0x1x6f5v1o5f0x1x7f5v1o6v1o5f0x1f ``` I finally fixed the bug in the linked implementation that made solving challenges like this one impossible! The main part of this program uses a *ton* of conditional instructions to properly split strings of any length, so I've split it onto multiple lines in the below explanation to aid readability. Works for any input string terminated with the control character STX (U+0002). Edit: Saved 20 bytes by calling function 5 directly from functions 6 and 7 instead of repeating its logic verbatim. **Explanation** (with `0x` commands removed) ``` 2a2x1v # Set variable 1 equal to 2 1x1f1r3x1v2e2x2v # Function 1 # Read a byte of input # Jump to function 2 if it equals variable 1 # Otherwise, store it in variable 2 1r3x1v3e2x3v # This pattern continues for the next 5 bytes of input 1r3x1v4e2x4v # ... 1r3x1v5e2x5v # ... 1r3x1v6e2x6v # ... 1r3x1v7e2x7v # ... 5v1o6v1o7v1o2v1o3v1o4v1o # Output variables 5, 6, and 7, then variables 2, 3, and 4 1f # Then, jump back to the start of the function 1x2f0a # Function 2 # Add 0 to the register 1x3f2v1o # Function 3 # Output variable 2 1x4f2v1o3v1o # Function 4 # Output variables 2 and 3 1x5f2v1o3v1o4v1o # Function 5 # Output variables 2, 3, and 4 1x6f5v1o5f # Function 6 # Output variable 5, then variables 2, 3, and 4 1x7f5v1o6v1o5f # Function 7 # Output variables 5 and 6, then variables 2, 3, and 4 1f # Call function 1 ``` [Answer] # [Kotlin](https://kotlinlang.org), 64 bytes ``` {chunked(3).chunked(2).fold(""){a,v->a+v.getOrElse(1){""}+v[0]}} {chunked(3) // split string into triplets .chunked(2) // group triplets by two .fold(""){a,v->a+ // join to string v.getOrElse(1){""}+v[0]}} // putting second before first (if exists) ``` [Try it online!](https://tio.run/##NY4/D4IwEMV3PsWlUxuk8c9GAk5uJg6OxqHKgQ21EDgaScNnx2Lwlncvv8t7VzdktJ2dMtAapE5TCtcgtpJcQJKvBrLZP1@DrbHgByH/617IsjEFZ0x4tXFJrmInK6RLdzI98p3wjE2xu23v0zSXg4W30jbk@gjCLKWEH4IMOlTFWVsM7JgCYz/ehmbi61t8uRQiCjlmfAxj/wU "Kotlin – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` Σṁ↔C2C3 ``` [Try it online!](https://tio.run/##yygtzv7//9zihzsbH7VNcTZyNv7//79zfkqqgnt@ThoA "Husk – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `s`, 5 bytes ``` 3ẇy$Y ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=3%E1%BA%87y%24Y&inputs=flybuys&header=&footer=) ``` 3ẇ # Divide into chunks of three y$Y # Swap each pair ``` ]
[Question] [ Given a list of integers, create a boolean mask such that the true indices can be used to filter the distinct values from the list. Which index is selected as the true one does not matter as long as only one of them is selected for each set of indices corresponding to identical values. The input will be a non-empty list of non-negative integers in a format suitable for your language and the output will be a list of boolean values following the specification above. You are allowed to use your own definitions of truthy and falsy values in the output list. In my examples below, I define `1` to be truthy and `0` to be falsy. ``` [5, 4, 7, 1] Input [1, 1, 1, 1] Output Select only the values with with true indicies in the sieve [5 4 7 1] Contains zero duplicate values [5, 9, 7, 5, 6, 0, 5] [0, 1, 1, 1, 1, 1, 0] [ 9, 7, 5, 6, 0 ] ``` ## Test Cases When there is an `or`, it means that there are multiple valid outputs. If there is a trailing ellipsis `...` after the `or`, it means that not all of the possible outputs were listed. ``` [0] = [1] [55] = [1] [32, 44] = [1, 1] [0, 0] = [1, 0] or [0, 1] [9001, 9001, 9001] = [1, 0 , 0] or [0, 1, 0] or [0, 0, 1] [5, 4, 7, 1] = [1, 1, 1, 1] [1, 2, 3, 4, 3, 5] = [1, 1, 1, 1, 0, 1] or [1, 1, 0, 1, 1, 1] [5, 9, 7, 5, 6, 0, 5] = [1, 1, 1, 0, 1, 1, 0] or [0, 1, 1, 1, 1, 1, 0] or [0, 1, 1, 0, 1, 1, 1] [0, 8, 6, 6, 3, 8, 7, 2] = [1, 1, 1, 0, 1, 0, 1, 1] or [1, 0, 0, 1, 1, 1, 1, 1] or [1, 0, 1, 0, 1, 1, 1, 1] or [1, 1, 0, 1, 1, 0, 1, 1] [45, 47, 47, 45, 24, 24, 24, 8, 47, 41, 47, 88] = [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1] or ... [154, 993, 420, 154, 154, 689, 172, 417, 790, 175, 790, 790, 154, 172, 175, 175, 420, 417, 154, 175, 172, 175, 172, 993, 689, 993, 993, 790] = [1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] or ... ``` ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest solution wins. * Builtins are allowed! * You are allowed to use your own definitions of truthy and falsy values in the output list. If you choose to do so, please state your definitions. * The input will be a non-empty list of non-negative integers. * You are free to choose between outputting only one of the sieves or multiple or even all of them. As long as each sieve is valid, it will be accepted. [Answer] # MATL, ~~7~~ ~~6~~ 4 bytes *1 byte saved thanks to @Luis* *2 bytes saved thanks to @Dennis* ``` &=Rs ``` We define `1` to be truthy and all other values as falsey [**Try it Online**](http://matl.tryitonline.net/#code=Jj1Scw&input=WzEgMiAzIDMgMiA0XQ) [All test cases](http://matl.tryitonline.net/#code=YCAgICAgICAgJSBMb29wIHRocm91Z2ggYWxsIGlucHV0cwomPVJzCkRUICAgICAgICUgRGlzcGxheSBhbmQgZ28gdG8gdGhlIG5leHQgdGVzdGNhc2U&input=WzBdCls1NV0KWzMyLCA0NF0KWzAsIDBdCls5MDAxLCA5MDAxLCA5MDAxXQpbNSwgNCwgNywgMV0KWzEsIDIsIDMsIDQsIDMsIDVdCls1LCA5LCA3LCA1LCA2LCAwLCA1XQpbMCwgOCwgNiwgNiwgMywgOCwgNywgMl0KWzQ1LCA0NywgNDcsIDQ1LCAyNCwgMjQsIDI0LCA4LCA0NywgNDEsIDQ3LCA4OF0KWzE1NCwgOTkzLCA0MjAsIDE1NCwgMTU0LCA2ODksIDE3MiwgNDE3LCA3OTAsIDE3NSwgNzkwLCA3OTAsIDE1NCwgMTcyLCAxNzUsIDE3NSwgNDIwLCA0MTcsIDE1NCwgMTc1LCAxNzIsIDE3NSwgMTcyLCA5OTMsIDY4OSwgOTkzLCA5OTMsIDc5MF0) **Explanation** ``` % Implicitly grab input array &= % 2D array of equality comparisons R % Get the upper triangular portion s % Sum down the columns % Implicitly display the result ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ĠṪ€Ṭ ``` Favors last occurrences. [Try it online!](http://jelly.tryitonline.net/#code=xKDhuarigqzhuaw&input=&args=WzUsIDksIDcsIDUsIDYsIDAsIDVd) or [verify all test cases](http://jelly.tryitonline.net/#code=xKDhuarigqzhuawKw4figqxH&input=&args=WzBdLCBbNTVdLCBbMzIsIDQ0XSwgWzAsIDBdLCBbOTAwMSwgOTAwMSwgOTAwMV0sIFs1LCA0LCA3LCAxXSwgWzEsIDIsIDMsIDQsIDMsIDVdLCBbNSwgOSwgNywgNSwgNiwgMCwgNV0sIFswLCA4LCA2LCA2LCAzLCA4LCA3LCAyXSwgWzQ1LCA0NywgNDcsIDQ1LCAyNCwgMjQsIDI0LCA4LCA0NywgNDEsIDQ3LCA4OF0sIFsxNTQsIDk5MywgNDIwLCAxNTQsIDE1NCwgNjg5LCAxNzIsIDQxNywgNzkwLCAxNzUsIDc5MCwgNzkwLCAxNTQsIDE3MiwgMTc1LCAxNzUsIDQyMCwgNDE3LCAxNTQsIDE3NSwgMTcyLCAxNzUsIDE3MiwgOTkzLCA2ODksIDk5MywgOTkzLCA3OTBd). ### How it works ``` ĠṪ€Ṭ Main link. Argument: A (array) Ġ Group; paritition the indices of A according to their corresponding values. Ṫ€ Tail each; select the last index of each group. Ṭ Untruth; generate a Boolean array with 1's at the specified indices. ``` [Answer] ## Python 3, ~~47~~ ~~35~~ ~~39~~ 36 bytes ``` lambda n:[n.pop(0)in n for x in n*1] ``` Pops the first item from the list, checks if it exists elsewhere in the list, and inserts `True` or `False` into a new list. For this function, `False` indicates a distinct value, and `True` is otherwise (`True=0` and `False=1`) *Thanks to Dennis for a ton of bytes* Original, 47 bytes: ``` lambda n:[(1,0)[n.pop()in n]for x in[1]*len(n)] ``` [Try it](https://repl.it/C8Nk/1) [Answer] # Pyth, 6 bytes ``` .eqxQb ``` Outputs a list of bools (`True` and `False`). Checks for each element in the input, if its index is equal to the index of the first occurence of the value. In other words, this is checking if each element is the first occurence. In pythonic pseudocode: ``` .e enumerated_map(lambda b,k: # maps with b as value and k as index q equal( xQb Q.index(b), k), # implicit lambda variable Q) # implicit argument to map ``` [Test it here.](http://pyth.herokuapp.com/?code=.eqxQb&input=%5B1%2C1%2C2%2C1%5D&test_suite=1&test_suite_input=%5B0%5D%0A%5B55%5D%0A%5B32%2C%2044%5D%0A%5B0%2C%200%5D%0A%5B9001%2C%209001%2C%209001%5D%0A%5B5%2C%204%2C%207%2C%201%5D%0A%5B1%2C%202%2C%203%2C%204%2C%203%2C%205%5D%0A%5B5%2C%209%2C%207%2C%205%2C%206%2C%200%2C%205%5D%0A%5B0%2C%208%2C%206%2C%206%2C%203%2C%208%2C%207%2C%202%5D%0A%5B45%2C%2047%2C%2047%2C%2045%2C%2024%2C%2024%2C%2024%2C%208%2C%2047%2C%2041%2C%2047%2C%2088%5D%0A%5B154%2C%20993%2C%20420%2C%20154%2C%20154%2C%20689%2C%20172%2C%20417%2C%20790%2C%20175%2C%20790%2C%20790%2C%20154%2C%20172%2C%20175%2C%20175%2C%20420%2C%20417%2C%20154%2C%20175%2C%20172%2C%20175%2C%20172%2C%20993%2C%20689%2C%20993%2C%20993%2C%20790%5D&debug=1) [Answer] # [J](http://www.jsoftware.com), 2 bytes ``` ~: ``` This was where the idea for this challenge originated from. The builtin `~:` is called `Nub-Sieve` in J and creates a boolean list that performs the operation described in the challenge. Here, `1` represents `true` and `0` represents `false`. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 8 bytes Code: ``` v¹ykN>Qˆ ``` Explanation: ``` y # For each in the array ¹yk # Get the index of that element in the array N>Q # And see if it's equal to the index ˆ # Add to the global array and implicitly output ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=dsK5eWtOPlHLhg&input=WzEsIDIsIDMsIDMsIDMsIDVd). [Answer] # APL, 6 bytes ``` ⍳∘⍴∊⍳⍨ ``` [Try it](http://tryapl.org/?a=%28%u2373%u2218%u2374%u220A%u2373%u2368%29%205%209%207%205%206%200%205&run) Explanation: ``` ⍳⍨ For each character in the string, get the index of its first occurrence ⍳∘⍴ Make a list 1 .. length of input ∊ Check if each index is present ``` [Answer] ## C#, 63 bytes ``` int[]l(List<int> i)=>i.Select((m,n)=>i.IndexOf(m)-n).ToArray(); ``` I could also make it return 1 or 0 and therby make the parameter and return type the same one therby allowing me to make this a lambda expression by itself? *some guidance would be appreciated* **same type code** ``` public static List<int>l(List<int>i){ return i.Select((m,n)=>i.IndexOf(m)==n?1:0).ToList(); } ``` [Answer] ## Python, 35 bytes ``` f=lambda l:l and[l.pop(0)in l]+f(l) ``` Uses `True` as the falsy value and `False` for the truthy value. Marks the last appearance of each element. Selects the first element only if it doesn't appear among the remaining elements, then recurses to the rest of the list as long as it's non-empty. The `l.pop(0)` extracts the first element while also removing it. [Answer] ## [Retina](https://github.com/m-ender/retina), 23 bytes ``` (\d+)((?!.* \1\b))? $#2 ``` Input is a space-separated list. (Actually, other formats like `[1, 2, 3]` will also work as long as there's a space in front of each number except the first.) [Try it online!](http://retina.tryitonline.net/#code=KFxkKykoKD8hLiogXDFcYikpPwokIzI&input=MAo1NQozMiA0NAowIDAKOTAwMSA5MDAxIDkwMDEKNSA0IDcgMQoxIDIgMyA0IDMgNQo1IDkgNyA1IDYgMCA1CjAgOCA2IDYgMyA4IDcgMgo0NSA0NyA0NyA0NSAyNCAyNCAyNCA4IDQ3IDQxIDQ3IDg4CjE1NCA5OTMgNDIwIDE1NCAxNTQgNjg5IDE3MiA0MTcgNzkwIDE3NSA3OTAgNzkwIDE1NCAxNzIgMTc1IDE3NSA0MjAgNDE3IDE1NCAxNzUgMTcyIDE3NSAxNzIgOTkzIDY4OSA5OTMgOTkzIDc5MA) (Works on multiple linefeed-separated test cases at once.) We simply turn each element into `0` if there's another copy of it later on in the input and into `1` otherwise. [Answer] ## PowerShell v2+, 40 bytes ``` $a=@();$args[0]|%{(1,0)[$_-in$a];$a+=$_} ``` Creates an empty array `$a`. Then we take the input list via `$args[0]` and pipe that into a loop `|%{...}`. Each iteration we select either `1` or `0` from a pseudo-ternary based on whether the current element is in `$a` or not. Those selections are left on the pipeline. We then add the current element into the array `$a`. The pipeline elements are gathered up, and output as an array is implicit. ### Example: *(output here with a newline separator, since that's the default `.ToString()` for an array)* ``` PS C:\Tools\Scripts\golfing> .\distinct-sieves.ps1 1,2,3,4,1,3,5,7 1 1 1 1 0 0 1 1 ``` [Answer] ## JavaScript (ES6), 31 bytes ``` f=a=>a.map((e,i)=>i-a.indexOf(e)) ``` Zero is truthy and other numbers are falsy. [Answer] ## Mathematica, ~~53~~ 31 bytes *Thanks to miles for giving me an idea that saved 22 bytes.* ``` s[[;;x++]]~FreeQ~#&/@(x=0;s=#)& ``` [Answer] ## Perl 5 ``` push@o,map{$b=pop@a;(grep{/^$b$/}@a)?1:0}(1..~~@a); ``` [Answer] # Java, 96 bytes ``` void s(int[]a){for(int i=0,j,n=a.length,b=1;i<n;a[i++]=b,b=1)for(j=i+1;j<n;)b=a[i]==a[j++]?0:b;} ``` Modifies the array in-place. Favours the last occurrence. The truthy value is `1` while the falsey value is `0`. [Verify all testcases](http://ideone.com/UPpjKx). Ungolfed: ``` void sieve(int[]a){ int n = a.length; for(int i=0;i<n;i++){ int b = 1; for(int j=i+1;j<n;j++){ if(a[i] == a[j]){ b = 0; } } a[i] = b; } } ``` [Answer] ## Actually, 11 bytes ``` ;╗ñ`i@╜í=`M ``` [Try it online!](http://actually.tryitonline.net/#code=O-KVl8OxYGlA4pWcw609YE0&input=WzUsIDksIDcsIDUsIDYsIDAsIDVd) Explanation: ``` ;╗ñ`i@╜í=`M ;╗ save a copy of input in reg0 ñ enumerate `i@╜í=`M for each (index, value) pair: i@ flatten, swap ╜í first index in input of value = compare equality ``` [Answer] ## Pyke, 4 bytes ``` F@oq ``` [Try it here!](http://pyke.catbus.co.uk/?code=F%40oq&input=%5B9001%2C+9002%2C+9001%2C+9003%2C+9002%5D&warnings=0) ``` - o = 0 #(Implicit) F - for i in input: @ - input.index(i) q - ^==V o - o+=1 ``` [Answer] # C++, 242 bytes Admittedly an overkill solution, as it works on *any* standard container of *any* ordered type: ``` #include<algorithm> #include<list> #include<set> template<class T>auto f(T a){using V=typename T::value_type;std::set<V>s;std::list<bool>r;std::transform(a.begin(),a.end(),std::back_inserter(r),[&](V m){return s.insert(m).second;});return r;} ``` ## Ungolfed: (and further generalised) ``` template<class T> auto f(T a) { using std::begin; using std::end; using V=typename T::value_type; std::set<V>s; std::list<bool>r; std::transform(begin(a),end(a),std::back_inserter(r),[&](V m){return s.insert(m).second;}); return r; } ``` ## Test suite: ``` int test(const std::list<bool>& expected, const auto& x) { return f(x) != expected; } #include<array> #include<chrono> #include<forward_list> #include<initializer_list> #include<string> #include<vector> using namespace std::literals::chrono_literals; int main() { return 0 + test({}, std::vector<short>{}) + test({1}, std::array<int,1>{}) + test({1}, std::vector<char>{55}) + test({true,true}, std::vector<unsigned>{32,44}) + test({1,0}, std::list<std::string>{"zero", "zero"}) + test({1,0,0}, std::vector<long>{9001,9001,9001}) + test({1,1,1,1}, std::array<char,4>{5,4,7,1}) + test({1,1,1,1,0,1}, std::initializer_list<std::string>{"one","two","three","four","three","five"}) + test({1,0,1,0,0}, std::forward_list<std::chrono::seconds>{60s, 1min, 3600s, 60min, 1h}); } ``` [Answer] # TSQL 52 bytes ``` DECLARE @ TABLE(i int identity, v int) INSERT @ values(1),(2),(3),(4),(3),(5) SELECT i/max(i)over(partition by v)FROM @ ORDER BY i ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/507966/distinct-sieves)** [Answer] # PHP, ~~66~~ ~~62~~ 39 bytes * accepts all atomic values (boolean, integer, float, string) except for values evaluating to false (false, 0, "") and numeric strings ("1" equals 1) * flags first occurence **new version** (program, 37+2 bytes) beats Java and (now again) C#. Even almost beats Python now. Happy. ``` <?foreach($a as$v)$u[$v]=print$u[$v]|0; ``` * +6 for PHP>=5.4, +16-3 for a function * prints undelimited list of `0` (true) and `1` (false) insert `!` after `print` to invert * usage: set `register_globals=On`, `short_open_tags=On` and `error_reporting=0` in `php.ini` for `php-cgi` then call `php-cgi -f <filename> a[]=<value1> a[]=<value2> ...;echo""`; * for PHP>=5.4: replace `$a` with `$_GET[a]` (+6), set `short_open_tags=On` and `error_reporting=0` * or replace `$a` with `array_slice($argv,1)` (+19), remove `<?` (-2) and call `php -d error_reporting=0 -r '<code>' <value1> <value2> ...;echo""` **old version** (function, 62 bytes) ``` function f($a){foreach($a as$v)$u[$v]=1|$m[]=$u[$v];return$m;} ``` * returns array of `false` for true and `true` for false; (ouput as empty string or `1`) insert `!` after `$m[]=` to invert * There is another way for a qualified function with 55 bytes, too. **tests** (on old version) ``` function out($a){if(!is_array($a))return$a;$r=[];foreach($a as$v)$r[]=out($v);return'['.join(',',$r).']';} function test($x,$e,$y){static $h='<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';echo"$h<tr><td>",out($x),'</td><td>',out($y),'</td><td>',out($e),'</td><td>',(strcmp(out($y),out($e))?'N':'Y'),"</td></tr>";$h='';} $samples=[ [0],[1], [55],[1], [32,44],[1,1], [9001,9001,9001],[1,false,false], [5,4,7,1],[1,1,1,1], [1,2,3,4,3,5],[1,1,1,1,false,1], [5,9,7,5,6,0,5],[1,1,1,false,1,1,false], [0,8,6,6,3,8,7,2],[1,1,1,false,1,false,1,1], [45,47,47,45,24,24,24,8,47,41,47,88],[1,1,'','',1,'','',1,'',1,'',1], [154,993,420,154,154,689,172,417,790,175,790,790,154,172,175, 175,420,417,154,175,172,175,172,993,689, 993,993,790], array_merge([1,1,1,false,false,1,1,1,1,1],array_fill(0,18,false)) ]; for($i=count($samples);$i--;--$i)for($j=count($samples[$i]);$j--;)$samples[$i][$j]=!$samples[$i][$j]; while($samples) { $a=array_shift($samples); $em=array_shift($samples); test($a,$em,$ym=s($a)); $eu=[];foreach($em as$i=>$f)if($f)$eu[]=$a[$i]; $yu=[];foreach($ym as$i=>$f)if($f)$yu[]=$a[$i]; # sort($eu); sort($yu); test('unique values',$eu,$yu); } echo '</table>'; ``` [Answer] ## Haskell, ~~29~~ 27 bytes ``` f a=[elem x t|x:t<-tails a] ``` Uses `False` as true, `True` as false value: ``` λ> let f a=[elem x t|x:t<-tails a] in f [5, 9, 7, 5, 6, 0, 5] [True,False,False,True,False,False,False] ``` You might have to `import Data.List` to use `tails` but, [tryhaskell.org](https://tryhaskell.org/) runs the code as is. [Answer] # Perl 5 + [Perligata](//metacpan.org/pod/Lingua::Romana::Perligata), 343 bytes 315 bytes, plus 28 for `-MLingua::Romana::Perligata` Use as `perl -MLingua::Romana::Perligata foo.pl`; input (from stdin) and output (to stdout) are underscore-separated strings of decimal integers. Tested on Strawberry 5.20.2 with version 0.6 of Perligata; I don't know whether it works with Perligata version 0.50. ``` huic vestibulo perlegementum da.qis _ scindementa da.dum qis fac sic ao qis decumulamentum da.ao aum tum nullum addementum da.meo io.meo ro.per ium in qis fac sic si ium tum aum aequalitas fac sic ro I da cis cis ro nullum tum non rum addementum da.capita bis rum cis per in bis fac sic hoc tum _ egresso scribe cis ``` --- Obviously this is clear as a bell. In case it's not, run it with `-MLingua::Romana::Perligata=converte` instead of `-MLingua::Romana::Perligata`, and `perl` will, instead of running the script, output a translation into regular Perl: ``` $_ = Lingua::Romana::Perligata::getline (*STDIN ); @q = split ( '_'); while (@q) { $a = pop (@q ); $a = ($a + 0); my $i ; my $r ; for $i (@q) {if ( ($i eq $a)) { $r = 1} } ; $r = (0 + ! ($r)); unshift (@b, $r)} ; for $_ (@b) {print (STDOUT $_, '_')} ``` For a token-by-token analysis, use `-MLingua::Romana::Perligata=discribe`. --- Golfing notes: * Undocumented (but unsurprising), you don't need a space after `.`. * (Also unsurprising,) `scinde` doesn't need a second argument, and uses `hoc`. * I had to use `ao aum tum nullum addementum da` because I couldn't get `morde` to work. * Similarly, I used `per ium in qis... ro I da` because I couldn't get `vanne` to work. * Instead of `huic vestibulo perlegementum da`, I tried `-pMLingua::Romana::Perligata`, but couldn't get it to work, either. --- Just for kicks (although this whole answer was just for kicks): * After cleaning it up to `Huic vestibulo perlegementum da. Qis lacunam scindementa da. Dum qis fac sic ao qis decumulamentum da. Ao aum tum nullum addementum da. Meo io. Meo ro. Per ium in qis fac sic si ium tum aum aequalitas fac sic ro I da cis cis. Ro nullum tum non rum addementum da. Capita bis rum cis. Per in bis fac sic hoc tum lacunam egresso scribe cis.`, Google Translate gives `This court perlegementum grant. QIS gap scindementa grant. While QIS QIS decumulamentum do so ao da. Ao sum and no addementum grant. My io. My ro. Through ium in QIS do so if the sum ium equality do so ro 1 from cis. Ro was not any rum addementum grant. The heads of the bis side. Write, do so as soon as he at that time that in the gap by the Kish was taken.`. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 19 bytes ``` ..|:i;{i,\i\-:i,-}% ``` Explanation! ``` ..|:i;{i,\i\-:i,-}% #Distinct sieve .. #Duplicate twice. Stack is [A A A] | #Binary OR. Removes duplicates. Stack is [A (A|A)] :i; #Call this A|A i, and remove it from the stack. [A], i=A|A { }% #Block notation. For each element in the top array, perform this on it. {i, }% #Size of i. Element in array is [E (i,)]. { \ }% #Swap the top two elements. [(i,) E] { i\ }% #Put i in the actual second position. [(i,) i E] { - }% #Remove all instances of the top element from the second. [(i,) (i-E)] { :i }% #This (i-E) is our new i (for the next loop). { , }% #Size of topmost element (either i, or i,-1 if index was found). { -}% #Subtract. This gives us 1 if E was removed from i, 0 otherwise. ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPkfbapgqWCuYKpgpmCgYBr7X0@vxirTujpTJyYzRtcqU0e3VvX/fwA "GolfScript – Try It Online") [Answer] # [jq](https://stedolan.github.io/jq/), 41 bytes ``` .[:range(length)+1]|[.[:-1][]!=.[-1]]|all ``` [Try it online!](https://tio.run/##yyr8/18v2qooMS89VSMnNS@9JENT2zC2JhooqGsYGx2raKsXDWTE1iTm5Pz/H22oo2Cko2Cso2ACJk1jAQ "jq – Try It Online") Takes an array, outputs a stream of jq booleans corresponding to its distinct sieve. -10 from ovs. ]
[Question] [ This is an [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") challenge where every part of your answer should aim to be unique from every other answer. This question will work in the following way: * I will post the first answer. The next answer will stem from that, and all other answers will originate from it. * In this answer I will include a program and specify three things: + The language the program is written in + The integer it outputs + The bytes the next program must use * The next user will then write an answer, and specify the same three things - the language they used, the integer they output and the bytes the next program must use * And so on, until the chain ends. Each answer will do the following: * It will include a program, written in a language that hasn't been used by any previous answer. * The program outputs an integer, through one of our [standard I/O formats](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), that no previous answer in the chain has outputted before. This integer must be deterministic and consistent between executions, and may be positive, negative or \$0\$. * It will take either no input, or [an empty input](https://codegolf.meta.stackexchange.com/a/7172/66833) if necessary, and will output nothing more than the integer to a standard output method (STDOUT, function return, Javascript's `alert` etc.) * It only uses the bytes allowed to it by the previous answer. It may use each byte as many times as it likes, but **each byte must be used at least once**. * The answer will specify a set of bytes (containing no duplicates) that the next answer must use. This set of bytes may not have been used by any previous answer, and can be any subset of the integers between \$0\$ and \$255\$. There must be a minimum of 1 and a maximum of 256 bytes in this subset, and the number of bytes must be unique of all existing answers (i.e. if one answer allows the next to use 120 bytes, no other answer may allow 120 bytes). Through this, each new answer will determine how difficult (or easy) the next answer is; only allowing a small subset of bytes will make it substantially more difficult than if allowing a larger set. "Bytes" means that you may use languages with non-UTF-8 encodings, by simply taking the characters those bytes represent in that code page. For the sake of fairness, the first answer (which I'll post) will have all 256 bytes available to it, so that the answers truly are unique in all the specified ways. ## Scoring Your score is the number of answers you have in the chain, with a higher score being better. ## Formatting Please format your answer in the following way: ``` # [N]. [Language], [# of bytes available] available bytes [program] This outputs [output] This uses the characters [characters/bytes], allowed by [previous answer](link) The next answer may use the following bytes: [list of bytes] ``` ## Rules * You must wait an hour between posting two answers * You may not post two answers in a row * So long as they're unique, the language, integer and bytes are up to your choice * You are under no obligation to golf your code * You may submit either a full program or function * Different versions of languages (e.g Python 2 and Python 3) are **not** considered separate languages. As a general rule, if the only way the language names differ is by a version number, or if the languages are usually thought of as versions of each other, they are considered the same language. * You may use any language that wasn't specifically invented to answer this challenge * The chain ends when 14 days pass with no new answers being posted or after 256 answers have been posted (as no new byte sets will be available). Good luck! [Answer] # 5. [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d) `-m`, 8 available bytes The code is given as three separate files. Here are their hexdumps: ``` 00000000: 002a 0f2a 062a 092a 042a 142a .*.*.*.*.*.* 00000000: 4545 4545 4545 EEEEEE 00000000: 45 E ``` This outputs `6`. [Try it online!](https://tio.run/##K0otycxL/P/fVatCi1OLyxUMuFz//wcA "Retina 0.8.2 – Try It Online") The first file uses bytes 0, 15, 6, 9, 4, 20, and 42, and the other two files consist entirely of `E` (byte 69), covering the list specified by the [previous answer](https://codegolf.stackexchange.com/a/212348/16766). --- Normally, Retina takes patterns and replacements in a single file separated by newlines, but we don't have newlines available. Fortunately, Retina 0.8.2 still makes available the language's original multi-file code format.\* This program has two stages, a replacement stage and a count stage: * Find all regex matches of `_*_*_*_*_*_*` in the input, where `_` represents the various unprintable characters. Since the input is empty, this matches once. Replace that match with `EEEEEE`. * In the resulting string, count the number of matches of `E` (six). \* IIRC, Retina was originally designed this way to take advantage of a PPCG scoring loophole. Now I'm using it to take advantage of a different kind of loophole. Seems appropriate. --- The next answer may use the 54 bytes whose codepoints are prime numbers: ``` 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251 ``` [Answer] # 2. [Python 3](https://docs.python.org/3/), 94 available bytes ``` values = {(k,): ord(k) for k in "ABCDEFGHIJKLMNOPQRSTUVWXYZ@"};combined = [~values[g.upper(),] + 1 // 2 - 3 * 4 & 5 % 6 > 0 < 7 ^ 8 for g in 'hjqwxyz'];_ = sum(combined) | 7 + 9;_ += ord("$") + ord("\n");print(_ + ord("`"))#!? ``` [Try it online!](https://tio.run/##NY5rVwFRGIX/ynZSzjGESDS5hIrkErpKgwzGcGYaJpcuf306xvLtXXvv9TyvuV6MDR51nK/e1FbnSOGb6gF2DsMaUJ1haFjQoXGQy1y@cHV9Uyzdlu8q1Vr9vtFsPTw@Pb@8Zsmv/GHM@hpXBwLQ/tux2qNj2zRVi7JABxIiCIVwgiCi8COGI5ziEHGkEcYFzvCOhCsbbWW@8eRzuVpvfB1ZEcS5PaN7AcOPWEtIikZKuW8SL2Eicc83TphsWhpfUGWfdQljB56M4/wD "Python 3 – Try It Online") Outputs `163` I could've just printed a number and stuck everything else in a comment, but I thought I'd add some unnecessary fluff to it to make it more interesting :P This uses all printable ASCII bytes as required by [the previous answer](https://codegolf.stackexchange.com/a/212329/68942). Python is a unique language, and 163 is a unique number. --- The next answer must contain all bytes *except* the printable ASCII characters; that is, codepoints 0 through 31 and 127 through 255. [Answer] # 3. x86 machine code (MS-DOS .COM), 161 available bytes ``` B8 19 0E 04 17 BB 01 00 CD 10 C3 02 03 05 06 07 08 09 0A 0B 0C 0D 0F 11 12 13 14 15 16 18 1A 1B 1C 1D 1E 1F 80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F 90 91 92 93 94 95 96 97 98 99 9A 9B 9C 9D 9E 9F A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 AA AB AC AD AE AF B0 B1 B2 B3 B4 B5 B6 B7 B9 BA BC BD BE BF C0 C1 C2 C4 C5 C6 C7 C8 C9 CA CB CC CE CF D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 DA DB DC DD DE DF E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 EA EB EC ED EE EF F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 FA FB FC FD FE FF ``` Relevant code (the rest is filler): ``` B8 19 0E MOV AX,0E19H 04 17 ADD AL,17H BB 01 00 MOV BX,0001H CD 10 INT 10H C3 RET ``` The DOS functions that print use printable characters (INT 21H and INT 29H), so I use INT 10H instead. This program outputs `0`. --- The next answer must use every codepoint except for the digits `0` through `9` (48 through 57 inclusive). [Answer] # 21. [Incident](https://esolangs.org/wiki/Incident), 9 available bytes Decoded as codepage 437: ``` £ñ¥££₧Ç£¢£%₧£%¢£ñ¥ñÇ¢£$¥ñ£¥ñ£¥%Ç₧ñ$¥%ñƒ%ñ¢Ç$₧%Ç¢%ñƒñ$ƒñ$ƒ%ǃñÇ₧ñ%₧ññƒ%%₧%%₧Ç$¥%%ƒ%£ƒ%£¢Ç$¢ñ%¥%£₧ññƒññ¥ñ%¢ñ£¥£$¥£$¥ñÇ¥£%¥Ç£¢Ç£¢££ƒ££¥£ñ¢Ç%ƒÇ%¢Ç%¢ÇñƒÇñ¥Çñ ``` or as an xxd reversible hexdump: ``` 00000000: 9ca4 9d9c 9c9e 809c 9b9c 259e 9c25 9b9c ..........%..%.. 00000010: a49d a480 9b9c 249d a49c 9da4 9c9d 2580 ......$.......%. 00000020: 9ea4 249d 25a4 9f25 a49b 8024 9e25 809b ..$.%..%...$.%.. 00000030: 25a4 9fa4 249f a424 9f25 809f a480 9ea4 %...$..$.%...... 00000040: 259e a4a4 9f25 259e 2525 9e80 249d 2525 %....%%.%%..$.%% 00000050: 9f25 9c9f 259c 9b80 249b a425 9d25 9c9e .%..%...$..%.%.. 00000060: a4a4 9fa4 a49d a425 9ba4 9c9d 9c24 9d9c .......%.....$.. 00000070: 249d a480 9d9c 259d 809c 9b80 9c9b 9c9c $.....%......... 00000080: 9f9c 9c9d 9ca4 9b80 259f 8025 9b80 259b ........%..%..%. 00000090: 80a4 9f80 a49d 80a4 ........ ``` [Try it online!](https://tio.run/##VZAxEoIwEEV7T7EFGSqk0BmtvIsiCIXAKDoWVjb0HoEMY50rJDMexIvg3w2OmuLNz2725yeb9TEfhjTJK4pKCq12xvZWW/26PVwL0VmtoEGW3HUGDeiAJU6MVK7lGROwNM87YDvXBigqHpAi2iNQYzUOKaGMsRRgFlYKJasFYgcYhbpPaLypj6W4x1Ek2xgQV/ccvvev@byJLZnc9EFxESCKIcatGIMhXalIqvJMUUanJouWFDWU1PPZglZUH6rdYb2fYk0ul@3fnr92Eld1ExdlUmzT8it@zw3DGw "Bash – Try It Online") Prints `33`. This is a) because 33 is by far the easiest two-digit number to print in Incident, b) because I already had a program to print 33 handy, and all I needed to do was try to fit it into the given set of available bytes. This program was harder to write than I expected (given that I'd already written it); 9 bytes is not a lot (the more the better with Incident, although it can work with very restricted sets if necessary), and working with character encoding issues is annoying. I started working with UTF-8, planning to change to Latin-1 later, but a) the program parses differently in UTF-8 (Incident looks at the raw bytes, so the encoding matters), b) I couldn't figure out what encoding @Razetime's currency symbols were in (euro isn't normally at 0x9C), and c) TIO apparently feeds UTF-8 to Incident so the program didn't work there directly, and I had to write my own wrapper in the TIO link above. A much more fruitful technique was to work with ASCII (`abcde,.:;`), and `tr` it into the set of available bytes at the end (Incident is `tr`-invariant; consistently replacing one codepoint in the program with another unused codepoint makes no difference to the program's behaviour). ## Explanation ### Parsing the program In the rest of this explanation, I'm going to represent the program in a more readable, equivalent, ASCII form (which is just a consistent replacement of the 9 available bytes): ``` cb,cc:dc.ca:ca.cb,bd.ce,bc,bc,ad:be,ab;ab.de:ad.ab;be;be;ad; bd:ba:bb;aa:aa:de,aa;ac;ac.de.ba,ac:bb;bb,ba.bc,ce,ce,bd,ca, dc.dc.cc;cc,cb.da;da.da.db;db,db ``` This program uses 17 different commands. The original program represented each command as a single byte: ``` lm3kklijhhdebbodbeedifgaaoaccofcggfhjjik33mml111222 ``` but this uses 17 different bytes, and we only have 9 available. So instead, each of the commands is represented as a pair of letters from `abcde` (i.e. the first five our our currency symbols). This would lead to a huge number of accidental mis-parses if I just wrote it out directly (in fact, Incident fails to parse a single token!), so additional characters drawn from `.,:;` (i.e. the last four of our currency symbols) were inserted in between them in order to ensure that it recognised the correct pairs of bytes as tokens. (As a reminder, Incident tokenises the source by treating each substring of bytes that occurs exactly three times as a token, with a few adjustments for overlapping tokens and tokens that are subsets of each other.) To translate the original program into the form with command pairs separated by additional characters, I used the Jelly program ``` O%38+10%25b€5ị“abcde”j”. ``` I then used simulated annealing to choose appropriate separating characters to make sure that none of the tokens ended up overlapping (usually these characters weren't part of the token, but in a few cases they became part of an adjacent token, without changing the behaviour of the program). ### Program behaviour ``` cb, Call subroutine cb (which prints a 3) cc: Goto label cccc (used to call cb a second time) dc. Goto label dcdc (apparently unused?) ca:ca. Jump target cb, Entry/exit point for subroutine cb (which prints a 3) bd. Call subroutine bd (which prints half a 3) ce, Goto label cece bc,bc, Jump target ad: Call subroutine ad (which prints a 0 bit) be, Goto label bebe ab;ab. Jump target de: Output a 0 bit (and jump to the centre of the program) ad. Entry/exit point for subroutine ad (which prints a 0 bit) ab; Goto label abab be;be; Jump target ad; Call subroutine ad (which prints a 0 bit) bd: Entry/exit point for subroutine bd (which prints half a 3) ba: Call subroutine ba (which prints a 1 bit) bb; Goto label bbbb CENTRE OF THE PROGRAM: aa:aa:de,aa; After outputting a bit, jump back to where you were ac;ac. Jump target de. Output a 1 bit (and jump to the centre of the program) ba, Entry/exit point for subroutine ba (which prints a 1 bit) ac: Goto label acac bb;bb, Jump target ba. Call subroutine ba (which prints a 1 bit) bc, Goto label bcbc ce,ce, Jump target bd, Call subroutine bd (which prints half a 3) ca, Goto label caca (i.e. return from subroutine cb) dc.dc. Jump target cc;cc, Jump target cb. Call subroutine cb (which prints a 3) da;da.da. No-op to ensure "de" is in the centre of the program db;db,db No-op to ensure "de" is in the centre of the program ``` This is pretty straightforward as programs go: we define a subroutine `cb` to print `3`, and it does so in terms of a subroutine `bd` which prints half a `3` (Incident prints a bit at a time, and the bit pattern of `3` is `11001100` in Incident's bit order, so to print half a `3` you just need to print `1100`). Unfortunately, the behaviour of an Incident command (except for unconditional jumps, which go from `x` to `xx`) depends on its position in the program, so a huge number of jumps are required in order to make the program's control flow run all the commands in the right order. The sequence in which the commands that actually do something must be given is fairly fixed (e.g. a subroutine must be called from exactly 2 locations, with the first location before it is defined, and the second location after it is defined; and I/O behaviour depends on which command is in the centre of the program), so because we can't reorder the commands to say which order we want to run them in, we reorder the control flow instead, putting jumps just before and after pretty much all of them. I'm not completely sure why I put two different jump labels `cccc` and `dcdc` back when I originally wrote this program, but Incident is sufficiently hard to write that I'm not sure I want to change things now. (Perhaps it was in an attempt to get the centre of the program into the right place.) ## Restriction Time for a change of pace, given how unreadable the programs in this answer are. The next answer must use all 26 lowercase ASCII letters, plus the ASCII space character: `abcdefghijklmnopqrstuvwxyz` , i.e. 0x61-0x7a, plus 0x20. (Please try to keep the restrictions fairly reasonable from now on; one of the inspirations behind Incident was "escaping from tricky situations in [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") puzzles", but now that it's been used, we won't have our get-out-of-jail card to free us from such situations if they happen again.) [Answer] # 4. [Vyxal](https://github.com/Lyxal/Vyxal), 245 available bytes ``` #λ¬∧⟑∨⟇÷«»°․⍎½∆øÏÔÇæʀʁɾɽÞƈ∞⫙ß⎝⎠ !"#$%&'()*+,-./:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_abcdefghijklmnopqrstuvwxyz{|}~⎡⎣⨥⨪∺❝𣥧¦¡∂ÐřŠč√∖ẊȦȮḊĖẸṙ∑Ṡİ•Ĥ⟨⟩ƛıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘŚśŜŝŞşšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƊƋƌƍƎ¢≈Ωªº ij ``` This outputs `10`. This uses every character except in the range `[48, 57]`. After everything is ignored in the comment, simply push `10` to the stack and auto print. --- The next answer may only have bytes in this list: `[69, 42, 0, 15, 6, 9, 4, 20]` [Answer] # 7. [Charcoal](https://github.com/somebody1234/Charcoal), 16 available bytes ``` 11»;∧”″⟲⌊$@Qdy✂Dα ``` [Try it online!](https://tio.run/##AS8A0P9jaGFyY29hbP//MTHCu@@8m@KIp@KAneKAs@KfsuKMiiRAUWR54pyC77ykzrH//w "Charcoal – Try It Online") Outputs the integer `11`, after which the `»` ends the block (program), ignoring the remaining 14 bytes. --- The next answer must not use any bytes which code for ISO-8859-1 characters with an alphanumeric appearance i.e. `0-9`, `A-Z`, `_`, `a-z`, but also `¢¥©ª®°²³µ¹º¼½¾`, `À-Ö`, `Ø-ö`, or `ø-ÿ`. [Answer] # 12. [05AB1E](https://github.com/Adriandmen/05AB1E), 62 available bytes ``` 5oCsnqaDZbOSF10u69pWEjBAf2KUMkLIgePzG8dTyHwNX3lRtmir7cQxhJ4YvV ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fNN@5OK8w0SUqyT/YzdCg1MyyINw1y8kxzcg71DfbxzM9NaDK3SIlpNKj3C/COCeoJDezyDw5sCLDyySyLOz/fwA "05AB1E – Try It Online") Outputs `64`. I got this by scrambling the bytes until it eventually gave me a nice number. --- The next answer must use the byte set of powers of two and three: `[1, 2, 3, 4, 8, 9, 16, 27, 32, 64, 81, 128]` (12). [Answer] # 1. [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 256 available bytes ``` > 1 >> Output 1    !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ ``` [Try it online!](https://tio.run/##DcZlVxMAAAXQI0o4PKQSIjhCROmWmoBBCILS3TEUGAtSkI3u7u7uHnXOez9scD/dmlKxTFIklXlpNCKhp0AkEsYp5BKF/PFPtJ4@09bR1Xsu0H8hMDA0MjYxffnKzNzC8rXVG2ubt0JbO3uHd47vnT58dHZxdXP38PTy9vH18/8UEBgUHCL6HBoW/uXrt@8RkVHRP2Jif8bF//qdkJiUnJKalp6RmZWdk5uXX1BYVFxSKi7787e8olJSJZXJFdU1tXX1Df8am/6jGUqo0IJWtKEdHehEF7rRg170oR8DGMQQhjGCUYxhHBOYxBSmMYNZzGEeC1jEEpaxglWsYR0b2MQWtrGDXexhHwc4xBGOcYJTnOEcF7jEFdS4xg1ucYd7NlNJFVvYyja2s4Od7GI3e9jLPvZzgIMc4jBHOMoxjnOCk5ziNGc4yznOc4GLXOIyV7jKNa5zg5vc4jZ3uMs97vOAhzziMU94yjOe84KXvKKa17zhLe94r9E8AA "Whispers v2 – Try It Online") Outputs `1` This uses all 256 bytes (from `0x00` to `0xFF`). The next answer must use the printable ASCII bytes (`0x20` to `0x7E`, to `~`, \$32\$ to \$126\$ etc.). Note that this *does not* include newlines. --- ## How it works Only the first two lines are actually executed. Every other line doesn't begin with `>` so it's ignored. From there, it's kinda simple. The first line returns `1` and the second outputs it. [Answer] # 6. [Jelly](https://github.com/DennisMitchell/jelly), 54 available bytes ``` ¦¬£¿Æ×Œçøþ%)/;=CGISYaegkmq³⁹⁻ⱮƤṣɗɲʂḌṂḂ¤ḊḢĿạẉẓḋOṁỌȯ»+¶5 ``` [Try it online!](https://tio.run/##AXEAjv9qZWxsef//wqbCrMKjwr/DhsOXxZLDp8O4w74lKS87PUNHSVNZYWVna21xwrPigbnigbvisa7GpOG5o8mXybLKguG4jOG5guG4gsKk4biK4biixL/huqHhuonhupPhuItP4bmB4buMyK/CuyvCtjX//w "Jelly – Try It Online") This outputs `5`. Why? Because `¶` counts as a newline in Jelly (like, `\n` and `¶` are the exact same thing), and only the last link (line) is run in Jelly, everything except the `5` is ignored. Actually, moving the `¶` to other places works too, because Jelly's really forgiving and just puts 0 through the chain of evaluation a bunch and since there's a number, I'm able to output something besides 0. --- The next answer must use the 16 bytes with square codepoints: `0,1,4,9,16,25,36,49,64,81,100,121,144,169,196,225` [Answer] # 8. [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), 184 available bytes ``` (?@) !"#$%&'*+,-./:;<=>[\]^`{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡£¤¦§¨«¬®¯±´¶·¸»¿×÷ ``` *The code outputs the integer `34`, the ASCII value of the character `"`.* This uses the characters specified by [previous answer](https://codegolf.stackexchange.com/a/212380/98140). [Try it online!](https://tio.run/##AcgAN/9lY25kcGNhYWxybHD//yg/QCkBAgMEBQYHCAkKCwwKDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicqKywtLi86Ozw9PltcXV5ge3x9fn/igqzCgeKAmsaS4oCe4oCm4oCg4oChy4bigLDFoOKAucWSwo3FvcKPwpDigJjigJnigJzigJ3igKLigJPigJTLnOKEosWh4oC6xZPCncW@xbggwqHCo8KkwqbCp8KowqvCrMKuwq/CscK0wrbCt8K4wrvCv8OXw7f//w) ## How does it work? The starting `(?@)` indicates that the code will run `?@` while the stack is not zero. Since the stack is zero at the start, the code does not excecute. Both of these characters print some sort of thing, which makes it necessary to put them in brackets. The code then pushes a few codepoints, including the codepoint of `"`, which is `34`. `#` prints out that number. Since there are no more printing commands, the rest of the code can be thought as filler. ## Next set of bytes! **The next answer should use all characters with an odd ASCII value, or:** ``` !#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} ``` [Answer] # 11. [Lenguage](https://esolangs.org/wiki/Lenguage), 2 available bytes [The program is too long to be displayed] Big thanks to the bois who made this Lenguage! The program prints `2` by the way. The program is basically a whopping `73788735513442661331` tabs and an acknowledgement. (Yes, an acknowledgement. It is in a program simply for it to follow the byte set of allowed by the [previous answer](https://codegolf.stackexchange.com/a/212429/98140)) --- The next program should use only and all alphanumeric characters upto `0x5A`, or: `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` [Answer] # 15. [Neim](https://github.com/okx-code/Neim), 1 available byte ``` A ``` [Try it online!](https://tio.run/##y0vNzP3/3/H/fwA "Neim – Try It Online") Outputs `42`. I don't know why. I've never used this language before. I was literally just clicking through random languages on TIO and this happened to work... It seems that repeating `A` just repeats the `42`, so I could've done an arbitrarily large integer in the form `42424242...` --- The next answer should use the byte set `[48, 49, 50]` (characters `['0', '1', '2']`). [Answer] # 17. [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 32 available bytes The available bytes were `0x01` through `0x20` inclusive. ```    ``` [Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgROMFDhJBlycXAqcXFxcjEzMLKxs7BwgNhcfv4CgkLCIqJi4hKSUtIysnLzC//8A "Whitespace – Try It Online") STN translation: ``` SSSTSSTSSS[50 copies of T]N # Push a big number TN STN # Print as integer? Not quite sure, I just copied this part from esolangs NN # Terminate the program [Garbage from 0x01 to 0x20] ``` Prints `82190693199511551`. As the code is easy enough to output larger numbers, I figured I'd output something large enough so no one needs to bother with output clashes. So I made a working program and padded the number literal with tabs until the program became exactly 100 bytes :) --- Next answer: Use only `[]{}`, which is `0x5b 0x5d 0x7b 0x7d` in hex. [Answer] # 9. [Bash](https://www.gnu.org/software/bash/), 64 available bytes Prints -13579. ``` /us?/???/ec?o -13579 #  !%')+;=ACEGIKMOQSUWY[]_agikmqwy{} ``` Hexdump for clarification: ``` 00000000: 2f75 733f 2f3f 3f3f 2f65 633f 6f09 2d31 /us?/???/ec?o.-1 00000010: 3335 3739 0923 0103 0507 0b0d 0f11 1315 3579.#.......... 00000020: 1719 1b1d 1f21 2527 292b 3b3d 4143 4547 .....!%')+;=ACEG 00000030: 494b 4d4f 5153 5557 595b 5d5f 6167 696b IKMOQSUWY[]_agik 00000040: 6d71 7779 7b7d 7f mqwy{}. ``` [Try it online!](https://tio.run/##S0oszvj/X7@02F7f3t5ePzXZPp9T19DY1NySU5mRmZWdm4tfUFhUXFJaVl5RVV1T29rW0dnV3dPb1z8wODQ8Mjo2PjE9Mzu3sLyyurb@/38A "Bash – Try It Online") `/us?/???/ec?o` is a *glob*, which searches for a filename matching that pattern (where `?` can be any one character). The file this finds is `/usr/bin/echo` which is very useful for printing integers. Next is a tab character, separating the executable from its argument, which is `-13579` (I thought I'd shake things up with a negative number!) Then another tab character and a `#`, starting a comment. Then are all the remaining odd ASCII bytes (from 0x01 to 0x7F, excluding the ones already used), which Bash dutifully ignores. (although with a little bit of stderr moaning, at least on TIO's version) --- Next arbitrary byte set is all bytes **except**: * bytes greater than or equal to 0x9A * ASCII lowercase letters * ASCII uppercase letters C, T and S * ASCII digits * ASCII space, new line feed, and horizontal tab * ASCII closing parenthesis, closing square bracket, and closing curly brace This makes a total of 107 available bytes? [Answer] # 10. [Keg](https://github.com/JonoCode9374/Keg), 107 avaliable bytes ``` E[``F;.#{(`ϧ∑¿∂•ɧ÷Ë≬ƒß‘“„«®©ëλº√₳¬≤Š≠≥Ėπ!"#$%&'*+,-./:<=>?@ABDEFGHIJKLMNOPQRUVWXYZ\\^_ ⊂½‡™±¦→←↶↷✏█↗↘□²ⁿ║ṡ⟰⟱⟷ℤ ``` [Try it online!](https://tio.run/##AcwAM/9rZWf//0VbYGBGOy4jeyhgw4/Cp@KIkcK/4oiC4oCiyafDt8OL4omsxpLDn@KAmOKAnOKAnsKrwq7CqcOrzrvCuuKImuKCs8Ks4omkxaDiiaDiiaXEls@AISIjJCUmJyorLC0uLzo8PT4/QEFCREVGR0hJSktMTU5PUFFSVVZXWFlaXFxeXwniioLCveKAoeKEosKxwqbihpLihpDihrbihrfinI/ilojihpfihpjilqHCsuKBv@KVkeG5oeKfsOKfseKft@KEpAkK//8 "Keg – Try It Online") This outputs `69` (HA!) Now, you're gonna say "but Lyxal... the answer said YOU CAN'T HAVE ASCII NEWLINE/TAB!! AND YET YOU STILL HAVE THOSE CHARACTERS!!!" Normally, you'd be right to say that this is invalid, but this time you're wrong. Keg's *special*. We play with a SBCS... A SBCS which just happens to have the newline and tab in a different spot than they usually are. [Codepage](https://github.com/Lyxal/Keg/blob/master/Codepage.txt) Don't judge my Poor Design Choices™ --- The next answer can only use the bytes with values `6` and `9` (haha funny number) [Answer] # 16. [Bitwise Cyclic Tag But Way Worse](https://github.com/MilkyWay90/Bitwise-Cyclic-Tag-But-Way-Worse), 3 [available bytes](https://codegolf.stackexchange.com/a/213485/16766) ``` 111011112000000 ``` This outputs `7`. [Try it online!](https://tio.run/##S0ouSSov///f0NDQAIgNjQzA4P9/AA "Bitwise Cyclic Tag But Way Worse – Try It Online") --- I found a language that used `0`, `1`, and `2`, took an educated guess at what an "output one character" program would look like, and tweaked it until it was a digit. ~~I'm... not really sure how this works.~~ After some investigation, it turns out that BCTBWW doesn't actually work like Bitwise Cyclic Tag (maybe that's why it's way worse). When BCT encounters an instruction like `10`, it conditionally enqueues a `0` to the data-string and moves to the next instruction after the `0`. BCTBWW uses the same enqueuing logic, but it doesn't skip over the bit that was enqueued--it executes the `0` as the next instruction. Here's how the above program works: ``` Instruction Data-string Comment 1 With empty input, data-string starts as 1 11 11 11 111 10 1110 0 110 11 1101 11 11011 11 110111 12 110111 12 is a no-op 2 110111 2 converts the data-string to bytes and outputs it 0 10111 0 0111 0 111 0 11 0 1 0 Data-string is empty, program halts ``` The output is thus the single byte `0b110111` = `0x37`, which is the digit `7`. --- The next answer must use the byte set `0x01` through `0x20` (1 through 32, inclusive). [Answer] # 18. [{} (Level 8)](https://esolangs.org/wiki/%EF%BD%9B%EF%BD%9D), 4 available bytes ``` {}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{{}{}{}{}{}}[] ``` `{} (Level 8)` is a brainfuck clone. According to the esolangs wiki page, `{}` evaluates to `+` in brainfuck, and `{{}{}{}{}{}}` evaluates to `.`. Here's the same program, translated to brainfuck: [Try it online!](https://tio.run/##SypKzMxLK03O/v9fm1yg9/8/AA "brainfuck – Try It Online") This program prints `9`. `[]` does nothing in this program, since it isn't a command. The next program must use the following 13 bytes taken from [this thread](https://www.reddit.com/r/AskReddit/comments/45gq2q/besides_69_what_is_the_funniest_number_and_why/): `[2,5,8,10,22,25,31,40,77,80,96,101,137]` Or, as hex: `02 05 08 0A 16 19 1F 28 4D 50 60 65 89` (courtesy of PkmnQ) [Answer] # 19. [Beatnik](https://esolangs.org/wiki/Beatnik), 13 available bytes ``` Pee MeMeMeMeMeMeMeMeeMeMeMeMe Pee MeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeP MeeeP MeeeP eeeeeeeeeeeeeeeee (`‰ ``` Yes, I deliberately used the words "Pee", "Meme", "Meep", and "E". This (abominable) program outputs the integer `21`. [Try it online!](https://tio.run/##S0pNLMnLzP7/PyA1lcs3FRXCGVwQWRJAAFg5jMSQVuDSSHjUsOH/fwA) --- ## Next byte set... Only use all of the non-alphabetic and non-whitespace characters which can be typed while pressing the shift key on a standard QWERTY keyboard: `!"#$%&()*+:<>?@^_{|}~` [Answer] # 20. [MAWP v1.1](https://esolangs.org/wiki/MAWP), 21 available bytes ``` !!!!!!::::::"#$%&()*+<>?@^_{|}~ ``` [Try it!](https://8dion8.github.io/MAWP/v1.1?code=!!!!!!%3A%3A%3A%3A%3A%3A%22%23%24%25%26()*%2B%3C%3E%3F%40%5E_%7B%7C%7D%7E&input=) Prints `111111`, Using the bytes `!"#$%&()*+:<>?@^_{|}~`. The first 12 bytes do the hard work(cloning the existing 1 and printing it), then the rest do a whole lot of nothing. `()` does othing since nothing is on the stack, and the rest fo the characters don't change anything since `:` needs to be there for outputting their result. ## Restriction The next answer must only use the currency symbols shown [here](https://usefulshortcuts.com/alt-codes/currency-symbol-alt-codes.php), and %: `¤£€$¢¥₧ƒ%` `[37,164,156,128,36,155,157,158,159]` `[0x25,0xa4,0x9c,0x80,0x24,0x9b,0x9d,0x9e,0x9f]` or `0x24-0x25, 0x80, 0x9b-0x9f, 0xa4` (from Bubbler) [Answer] # 22. [StupidStacklanguage](https://esolangs.org/wiki/StupidStackLanguage), 27 available bytes ``` abaacdaiiiiiiiqmiiiiiiiqqqqfffffeghjklmnopqrstuvwxyz ``` [Try it online!](https://tio.run/##rVZNj5swEL3nV7iuqoWEUKKqUrVZWlXVttpLW3V7i6jkgBPYEHCM2ST751PzTYgHclifwOP33vBmkjE7Cj@OPnxi/BRsWcwFSo6JgTgdjRhfIxthjE9kSYjrkaBYu231INcqW3TtP23CbRSzHU9E@rw/HF/QSSJHiSDuRrIsnJJO49R04y0LQqrdvNW@2OZYN8c3htx@@PHz15/7b18f73UzSZcaxobE6LoKufhHlq5HV2s/uFB2JB1S86Ga8HecSE5rlPhxGnqPm4DJ1@8kTOSH732pgYpDdyGNtAx1O0JyBSvUIIqtbClYsm0qH5pDrk@4DEuyRcHtmGG8p1zT6yOSvjglfSe4geYamZVmECWUC80yrAZFwzZuqcSxmGkgxO2Xyl8XloOmRWQxcyAmT8UkoVN7BiDoldrvBrVXHSbGg0hors@1ikQ3aOTZGEMM6ytzmQzm4vczZYkFEUuFpusQRQBYOQGtfOoXjbk3KLrpUGT9XuratnUeu2j8vzylAG/Y4RV0myEqGxUfOnPquOUojZDxjAZQ3PabUfcEGjfFhFyJhqvZuDTIFoM/0LpPASS7sj/fD/bn7jomCM774dl/Zr4FepD09UOl7swVda@DrfaY9/XHHEhBwK2exRXNHjMaUS8fG91QOVEmNppdxNrjBN2h84HSXTKL1oDIE00xIpFXqytTa60lp2SjPJB//yU7zFZKKr8KJBTDhFOIUGXjedXSnqq9UVrjhnHSX7XpYNU@g6YrDcjrVen21usVi1XqvV6xSsKhYk3hYj2DI@wjgNiD9wcIcVBO/Qo3MPCPKrniuqoGvHQBx8Skh0Cc363at74mJ/wQPZMw8HI24grKb7GRPRuYiPyuK@3U5738xSF5BTj9Bw "Python 3.8 (pre-release) – Try It Online") This prints `88888`. This uses `abcdefghijklmnopqrstuvwxyz` (Printable ascii alphabets and space) from the previous answer. The next answer must use the following bytes which are palindromes in base 2: `!-3?AIU]ckw¥½ÃÛçÿ` `[33,45,51,63,65,73,85,93,99,107,119,127,165,189,195,219,231,255]` `[0x21,0x2d,0x33,0x3f,0x41,0x49,0x55,0x5d,0x63,0x6b,0x77,0x7f,0xa5,0xbd,0xc3,0xdb,0xe7,0xff]` --- ## How it works: `ab` pushes a 0 and pops it. `aacd` pushes two 0's and subtracts them and decrements the result. `aiiiiiii` pushes a 0 and adds 7 to it. `qm` squares it. `iiiiiii` adds 7 to that. `qqqq` duplicates it 4 times. `fffff` then displays that as printable ascii. `e` takes in input. Since there is no input, the program errors and ends execution, and the rest of the program does nothing. [Answer] # 23. [Trigger](http://yiap.nfshost.com/esoteric/trigger/trigger.html), 17 available bytes ``` 333!333-333?AIU]ckw¥½ÃÛçÿ ``` [Try it online!](https://tio.run/##KynKTE9PLfr/39jYWBGIdYHY3tEzNDY5u/zQ0kN7Dzcfnn14@eH9//8DAA "Trigger – Try It Online") Outputs `333`. Not sure if these are the correct characters to show, but even if they aren't, the language spec says it doesn't matter. The next answer must use all bytes except: * Alphanumeric characters `0x30 to 0x39, 0x41 to 0x5A, 0x61 to 0x7A` * The null byte `0x00` * Brackets `0x40, 0x41, 0x5B, 0x5D, 0x7B, 0x7D` * Mathematical operators `0x25, 0x42, 0x43, 0x45, 0x47` * Bitwise operators `0x21, 0x26, 0x5E, 0x7C` * Whitespace `0x09, 0x0A, 0x0C, 0x0D, 0x20` * Common punctuation `0x22, 0x27, 0x2C, 0x2E, 0x3F` Which leaves 167 bytes. [Answer] # 13. [Poetic](https://esolangs.org/wiki/Poetic), 12 available bytes ``` QQQQQQQQQQQQQQQQQQQQQQQQ QQQQQQQQQQQ@QQQQQ€QQQ QQQQQ QQQ QQQQQ QQQ QQQQQ QQQ QQQQQ QQQ QQQQQ QQQ QQ QQQQQQQ QQQQQQQQQQ ``` This code outputs the number `4`! Uses the `Q`'s and `@`'s and other stuff specified by the [previous answer](https://codegolf.stackexchange.com/a/213452/98140). --- ## Next byte set... Only use every accented ASCII alphabets and all the accents or diacritics in your code, or: ``` ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ`´^~¨° ``` *Note: The degree (`°`) symbol has to be used as a diacritic* [Answer] # 14. [V](https://github.com/DJMcMayhem/V), 68 [available bytes](https://codegolf.stackexchange.com/a/213471/16766) ``` ÁÀÁÂÁÃÁÅÁÆÁÇÁÈÁÉÁÊÁËÁÌÁÍÁÎÁÏÁÐÁÑÁÒÁÓÁÔÁÕÁÖÁÙÁÚÁÛÁÜÁÝÁÞÁßÁàÁáÁâÁãÁäÁåÁæÁçÁèÁéÁêÁëÁìÁíÁîÁïÁðÁñÁòÁóÁôÁõÁöÁøÁùÁúÁûÁüÁýÁþÁÿÁ`Á´Á^Á~Á¨Á°ØÄ ``` This outputs `65`. [Try it online!](https://tio.run/##Dc1JTkJBAEXRnRJXwdBYKCAoKI1GATsaBaX52BBExYRaWHEGJ7mDl7x8SjHEIwocU6REmVMqVDnjnBp1LrikQZMWba645pYOXXrccc8DjzzRZ8CQEc@8MGbCK29MmTFnQcaSdz745IsVa77Z8MMvf2z5j@Eghp15LoZD5WiXxZt4ktIe "V (vim) – Try It Online") --- V is the perfect language for using accented letters. * `Á` inserts the character that follows it into the buffer. We use this command over and over to insert 65 out of our 68 characters. * `Ø` counts matches of the following regex and replaces the buffer with the count. * `Ä` is a compressed regex that stands for `\D`. Thus, in the characters we inserted previously, we count the ones that are not digits--which is all 65 of them. --- Let's get the hard one out of the way. The next answer must use only byte 65 (`0x41`), `A`. ]
[Question] [ Inspired by an old manual... ### The challenge I define the *a*th suffix vector of *b* as the boolean list of length *a* with *b* trailing truthy values. Write a program or function that, given *a* and *b* by any means, returns the *a*th suffix vector of *b* by any means. Now this may seem trivial, but here is the catch: Your score is the byte count plus the earliest year your solution would have worked. ### Rules All standard rules apply, except that languages and language versions that were released after this challenge, may also be used. Output using whatever representation of boolean values that your language uses, e.g. `1`/`0`, `True`/`False`, `TRUE`/`FALSE`, `"True"`/`"False"`, etc. Output using whatever representation of lists that your language uses, e.g. `0 0 1`, `[False,False,True]`, `(FALSE;FALSE;TRUE)`, `{"False","False","True"}`, etc. You may assume that *a* ≥ *b* is always true and that they are of an appropriate data type. ### Test cases Given *a* = 7 and *b* = 3, return `0 0 0 0 1 1 1` Given *a* = 4 and *b* = 4, return `[True,True,True,True]` Given *a* = 2 and *b* = 0, return `(FALSE;FALSE)` Given *a* = 0 and *b* = 0, return `{}` ### Example solution and scoring I might want to submit the solution `{⌽⍺↑⍵⍴1}` using Dyalog APL. That would be a bytecount of 8. This is a dynamic function, which works from version 8.1 of Dyalog APL, released in 1998, so my total score is 2006. My submitted answer should look something like: ``` # Dyalog APL 8.1, 1998 + 8 = 2006 {⌽⍺↑⍵⍴1} Optional explanation... Recommended: Link to documentation showing when the features you used were released. ``` Lowest score wins! [Answer] # SAS, 1966 + 45 = 2011 ``` data;a=;b=;do i=1to a;c=a-i<b;put c@;end;run; ``` Time for SAS to shine! SAS wasn't first published until 1972, but this data step only uses very basic features that I'm fairly confident would have been available even in the earliest pre-release versions from 1966 onwards, so I believe it would have worked then. Input goes after `a=` and `b=`, and output is printed to the log. I would be amazed if anyone still had an [IBM System/360](https://en.wikipedia.org/wiki/IBM_System/360) with the right version of SAS to actually verify this! [Answer] # Forth, 1970 + 38 = 2008 ``` :s tuck +do 0 . loop 0 +do -1 . loop ; ``` usage: `7 3 s` prints "0 0 0 0 -1 -1 -1" [Answer] ## APL, 1968+5=1973 Down to 5 chars: ``` ⌽⎕≥⍳⎕ ``` --- Older version: ``` ⌽⎕↑⎕⍴1 ``` Well, you actually already gave the answer, i just removed the dynamic function definition and checked that this one worked in 1968. For reference here is the manual: <http://www.softwarepreservation.org/projects/apl/Books/APL360ReferenceManual> [Answer] ## APL\360, 1968 + 3 bytes = 1971 ``` ⎕⍵⎕ ``` A builtin from the [tutorial](http://www.jsoftware.com/papers/APL360TerminalSystem.htm) @NBZ linked to. I don't know why @NBZ said it would score 1970, because APL\360 wasn't implemented until 1968, and earlier APLs like APL\1130 didn't have the suffix vector function (see page 208 of [here](http://www.softwarepreservation.org/projects/apl/Manuals/APL1130Primer)). [Answer] # [Mouse-1979](http://mouse.davidgsimpson.com/mouse79/index.html), 1979 + 19 = 1998 ``` ??&TUCK (0.a)0(1-.) ``` Translation of: [Forth](https://codegolf.stackexchange.com/a/75307/46231). The spec is really cryptic to me but I think this does the right thing. [Answer] # TI-Basic, 1990 + 21 = 2011 The first TI calculator that this program works on is the TI-81, introduced in 1990. ``` Prompt A,B:"{} seq(I>A-B,I,1,A ``` **Edit:** noticed that I must support an empty list... increased code by 4 bytes # Test Cases ``` A=?7 B=?3 {0 0 0 0 1 1 1} A=?4 B=?4 {1 1 1 1} A=?2 B=?0 {0 0} A=?0 B=?0 {} * throws an error but still returns successfully ``` [Answer] # Mathematica 1.0, 1988+22 bytes=2010 ``` Array[#>m&/.m->#-#2,#]& ``` I'm not sure if this works, just went through the documentation on 10.3 and looked for things that said *Introduced in 1988 (1.0)* [Answer] # 68k TI-Basic, 1995 + 25 = 2020 The first TI calculator that this program works on is the TI-92, introduced in 1995. ``` define f(a,b)=seq(x>a-b,x,1,a) ``` Unlike the TI-83 series, 68k TI-Basic supports the empty list. [Answer] # Python 1.0, 1994 + 26 = 2020 Saved 2 bytes thanks to DSM. Lambda was introduced with the first major release, 1.0 ``` lambda a,b:[0]*(a-b)+[1]*b ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 2015 + 1 + 4 = 2020 ``` :P<~ ``` This works since [release 6.0.0](https://github.com/lmendo/MATL/releases/tag/6.0.0) of the language (it uses implicit input, which was introduced in that release), dated December 31, 2015. I've added `1` to the score in accordance with @drolex comment on possibly different locales. [**Try it online!**](http://matl.tryitonline.net/#code=OlA8fg&input=Nwoz) ### Explanation ``` : % take first input implicitly. Generate inclusive range from 1 to that P % flip that array <~ % take second input implicitly. True for elements of flipped array that % exceed second number. Display implicitly ``` [Answer] # J, 1990 + 8 = 1998 ``` |.a{.b#1 ``` Argh. Was researching this answer and someone got to APL before I could hope to understand the language. Here's my J solution instead. [Answer] # Prolog, 1972 + 57 = 2029 ``` a(0,_,[]). a(A,B,[H|L]):-Z is A-1,a(Z,B,L),(Z<B,H=1;H=0). ``` **Usage:** `a(7,3,L).` will unify `L` with `[0,0,0,0,1,1,1]`. I'm really not quite sure when `is` was implemented in the language, and I doubt you can actually find the exact date. It's a pretty basic built-in though so I assume it was already existing when the language first appeared in [1972](https://en.wikipedia.org/wiki/Prolog). Not that it really matters though, I'm far from winning with this answer. [Answer] # [SMP](http://www.stephenwolfram.com/publications/smp-symbolic-manipulation-program/smp-reference-manual.pdf), 1983+28 bytes=2011 ``` Map[S[$1>x,x->$1-$2],Ar[$1]] ``` I think I got this right... `S`:2.10, page 48 `Ar`:7.1, page 102 `Map`:7.2, page 106 `$1`:7.1, page 104 And if you're familiar with Mathematica, no, `Ar` doesn't work like *that*. More like `Range`+`Select`. [Answer] # Vim, 1991 + 21 = 2012 ``` "adwj<c-x>"bdw@ai0<esc>v@bhr1 ``` Input looks like this: ``` 7 3 ``` And output looks like this: ``` 0000111 ``` Explanation: ``` "adw 'Delete a word into register a j<c-x> 'Go down a line, and decrement the next number to occur "bdw 'Delete a word into register b @ai0<esc> 'Insert a '0' "a" times v 'Enter visual mode @bh 'Move "b" characters left r1 'Replace the whole selection with the character '1' ``` [Answer] # [B](https://en.wikipedia.org/wiki/B_%28programming_language%29), 1971 + 54 = 2025 ``` s(l,t){while(t<l--)printn(0,8);while(t--)printn(1,8);} ``` See "[The User's Reference to B](https://web.archive.org/web/20150611114427/https://www.bell-labs.com/usr/dmr/www/kbman.pdf)" for the manual for this typeless C precursor. [Answer] # Pyth, 2015 + ~~9~~ 4 = ~~2024~~ 2019 Thanks to @FryAmTheEggman for his help! ``` gRQE ``` [Try it here!](http://pyth.herokuapp.com/?code=gRQE&input=3%0A7&test_suite=1&test_suite_input=3%0A7%0A4%0A4%0A0%0A2%0A0%0A0&debug=0&input_size=2) ## Explanation ``` gRQE # Q = amount of trailing truthy values # E = length of the vector R E # map over range(E) g Q # d >= Q ``` [Answer] ## [><>](http://esolangs.org/wiki/Fish), 2009 + 14 + 3 for -v = 2026 `b` and `a` should be provided directly on the stack with `-v`, in reverse order. The output isn't space separated as in the examples, but that does not seem to go against any stated rule. It uses 0 and 1 to represent false and true, as used by the language. ``` :?!;{:0(n1-}1- ``` It doesn't work with the current version since `?` now pops its test value from the stack. I'm not confident every feature was implemented from day 1, `-v` for example could have been provided later as a commodity. I'll try to make sure my answer is correct this weekend. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 2016 + 9 = 2025 This can definitely be golfed further, but here's a start :p. Code: ``` -0s×1¹×«S ``` [Try it online!](http://05ab1e.tryitonline.net/#code=LTBzw5cxwrnDl8KrUw&input=Mwo3) The input is given as *b, a*. Also 9 bytes: [`0×1I×0ñRS`](http://05ab1e.tryitonline.net/#code=MMOXMUnDlzDDsVJT&input=Nwoz). [Answer] ## PowerShell v1, [2006](https://blogs.msdn.microsoft.com/powershell/2006/11/14/its-a-wrap-windows-powershell-1-0-released/) + 28 = 2034 ``` param($a,$b),0*($a-$b)+,1*$b ``` Uses the [comma operator](https://blogs.msdn.microsoft.com/powershell/2007/01/23/array-literals-in-powershell/) to construct the array(s), which has been in PowerShell since the beginning. [Answer] # Mathcad, 1998 + 42 = 2040 "bytes" are interpreted as number of distinct keyboard characters (eg, 'for' operator (including one programming line) is a single character ctl-shft-#, or a click on the Programming toolbar)). The above byte count assumes that the a and b definitions don't count towards the total; add 4 bytes for definitions if this assumption is invalid. The function version shown below adds 5 bytes for the definition and a further 3 bytes for each use (assuming the a and b values are directly typed in). As my Mathcad solution should clearly be playing off the red tees and not the competition ones, I've added a table of solutions. Note that as Mathcad has no empty array, I've used an empty string ("") instead; I've used 0 to indicate where I haven't calculated the b>a pairs. [![enter image description here](https://i.stack.imgur.com/YsK9I.jpg)](https://i.stack.imgur.com/YsK9I.jpg) [Answer] ## PHP, 1995 + 56 bytes = 2051 ``` function s($a,$b){while($i++<$a)$v[]=$i>$a-$b;return$v;} ``` **Exploded view** ``` function s($a,$b) { while ($i++ < $a) $v[] = $i > $a - $b; return $v; } ``` [Answer] # Javascript ES6, 2015 + 46 = 2061 Returns array of 0 and 1 ``` (a,b)=>Array(a-b).fill(0).concat(Array(b).fill(1)) ``` # Javascript ES6, 2015 + 50 = 2065 Returns a string of `0` and `1` chars ``` (a,b)=>Array(a-b+1).join(0)+Array(b+1).join(1) ``` # Javascript, 1995 + 61 = 2056 Returns a string of `0` and `1` chars ``` function(a,b){return Array(a-b+1).join(0)+Array(b+1).join(1)} ``` [Answer] # [k](https://en.wikipedia.org/wiki/K_(programming_language)) ([kona](https://github.com/kevinlawler/kona)), 1993 + 15 = 2008 ``` ((a-b)#0b),b#1b ``` Creates list of b True values, and concatenates it to a list of (a-b) False values. [Answer] # [R](https://www.r-project.org/), 20 bytes + 1993 = 2013 ``` function(a,b)1:a>a-b ``` [Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP08jUSdJ09Aq0S5RN@l/moaZjpHmfwA "R – Try It Online") Possibly this might work in S, which would drop the score to 2008, but I haven't been able to verify it. [Answer] # SmileBASIC 3, 2014 + 25 = 2039 The first publicly available version of SmileBASIC 3 launched in Japan with the SmileBASIC app for Nintendo 3DS in November 2014. Prints a string where 0 is false and 1 is true (as they are in the language itself.) ``` INPUT A,B?"0"*(A-B)+"1"*B ``` ]
[Question] [ # Challenge You task for this question is to split an input array of integers on the second occurrence of every integer in that array. **Not clear enough ? Here is an example to help** Input array: ``` [2 1 1 2 3 2 2 4 5 6 7 3 7 0 5] ``` Output: ``` [[2 1] [] [3 2 2 4 5 6 7] [] [0] []] ``` Explanation: Here is the array with just the second element highlighted in bold: [2 1 **1** **2** 3 2 2 4 5 6 7 **3** **7** 0 **5**] Now we put the splitting array blocks around these bold second occurrences: [2 1] **1** [] **2** [3 2 2 4 5 6 7] **3** [] **7** [0] **5** [] and wrap these splitted arrays in an array to get the final ``` [[2 1] [] [3 2 2 4 5 6 7] [] [0] []] ``` *Note that when adjacent second occurrences occur, there will be empty arrays.* # Rules As usual, you have to write a full program or a function taking the input array via STDIN, ARGV or function argument. **Input** The input consists on any convenient array (or array-like) format of integers. For instance, any of the following would be acceptable: ``` 2 1 1 1 4 5 6 [2 1 1 1 4 5 6] [2, 1, 1, 1, 4, 5, 6] ``` **Output** When outputting to STDOUT, your array can also be printed in any convenient (nested) array format, e.g. one of ``` [[2 1] [1 4 5 6]] [[2, 1], [1, 4, 5, 6]] {{2, 1}, {1, 4, 5, 6}} ``` (This will usually be the native string representation of arrays in your language.) Also note that trailing empty arrays should be printed as the part of the array. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes win! [Answer] ## APL (Dyalog 14) (31) ``` {1↓¨(1,(⍳⍴⍵)∊2⍳⍨¨↓+\∘.=⍨⍵)⊂0,⍵} ``` This is a function that takes an array and returns a nested array. Test: ``` +V← {1↓¨(1,(⍳⍴⍵)∊2⍳⍨¨↓+\∘.=⍨⍵)⊂0,⍵} 2 1 1 2 3 2 2 4 5 6 7 3 7 0 5 ┌───┬┬─────────────┬┬─┬┐ │2 1││3 2 2 4 5 6 7││0││ └───┴┴─────────────┴┴─┴┘ ⍝ this return value is a real nested array: ⎕←'Length: ',⍴V ⋄ (⍳⍴V){⎕←'Array #',⍺,': (', ⍵, ')'}¨V Length: 6 Array # 1 : ( 2 1 ) Array # 2 : () Array # 3 : ( 3 2 2 4 5 6 7 ) Array # 4 : () Array # 5 : ( 0 ) Array # 6 : () ``` Explanation: * `0,⍵`: Add a `0` to the front of `⍵`, for easier processing. (It does not count as an occurrence.) * `(`...`)⊂`: Split the array according to the given bitmask. A new group starts at each `1` in the bitmask. + `+\∘.=⍨⍵`: for each value in (the original) `⍵`, find all occurrences in `⍵`. Then make a running sum for each value, giving a square matrix showing for each position in `⍵` how many of each value have already occurred. + `↓`: Split the matrix by its rows, giving for each value an array showing the amount of times it has occurred by each position. + `2⍳⍨¨`: In each of these arrays, find the index of the first `2`. + `(⍳⍴⍵)∊`: For each possible index into `⍵`, see if it is contained in the list of indices of second occurrences. (These start each group, except the first one.) + `1,`: Add an `1` to the front, marking the start of the first group. * `1↓¨`: Remove the first element from each group. (These are the added `0`, and the second occurrence of each value.) [Answer] # J, ~~28~~ 24 char Special thanks to [randomra](/u/7311). ``` (1&,<;._1~1,2=+/@(={:)\) ``` It works like this. Over all prefixes (`\`) of the input array, we look at how many (`+/@`) elements of the prefix are equal to the last element (`={:`) of that prefix. When this number is 2, we know this is the second occurrence of that item in the array, so we split the array there using `<;._1`. ``` a=.2 1 1 2 3 2 2 4 5 6 7 3 7 0 5 (={:)\ a 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 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 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 1 0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 1 0 1 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 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 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 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 1 0 0 0 0 0 1 +/@(={:)\ a 1 1 2 2 1 3 4 1 1 1 1 2 2 1 2 ``` Old thing using sort tricks: `(1&,<;._1~1,1=i.~(]-{)/:@/:)`. [Answer] # APL 25 ``` 1↓¨(1,∨⌿<\2=+\∘.=⍨a)⊂1,a← ``` Example: ``` ]display 1↓¨(1,∨⌿<\2=+\∘.=⍨a)⊂1,a←2 1 1 2 3 2 2 4 5 6 7 3 7 0 5 ┌→──────────────────────────────────────┐ │ ┌→──┐ ┌⊖┐ ┌→────────────┐ ┌⊖┐ ┌→┐ ┌⊖┐ │ │ │2 1│ │0│ │3 2 2 4 5 6 7│ │0│ │0│ │0│ │ │ └~──┘ └~┘ └~────────────┘ └~┘ └~┘ └~┘ │ └∊──────────────────────────────────────┘ ``` ***Old One:*** ``` {1↓¨(1,(⍳⍴⍵)∊,{1↑1↓⍵}⌸⍵)⊂1,⍵} ``` This is a nice question for the key operator (⌸) which was introduced with Dyalog APL v14. It takes the left argument function ({1↑1↓⍵}) and gives it for each unique argument, the indices in the vector for that argument. Here I'm taking the second index, then i check which of the indices is present in this list ((⍳⍴⍵)∊) and use the resulting boolean for splitting the original vector. Can be tried online here: [http://tryapl.org](http://tryapl.org/) [Answer] # Mathematica, ~~58~~ ~~51~~ 49 bytes ``` Rest/@SplitBy[(f@#=0;#)&/@{a}~Join~#,++f[#]==3&]& ``` This is an unnamed function which takes a list like ``` Rest/@SplitBy[(f@#=0;#)&/@{a}~Join~#,++f[#]==3&]&[{2,1,1,2,3,2,2,4,5,6,7,3,7,0,5}] ``` and returns a nested list like ``` {{2, 1}, {}, {3, 2, 2, 4, 5, 6, 7}, {}, {0}, {}} ``` ## How it works This uses some pretty obscure magic with `SplitBy`. I'm keeping track of the occurrences of each number in a function `f`. In Mathematica, you can define the value of a function for each input separately, and you don't need to specify the value for all possible inputs (it's more like a hash table on steroids). So I start out by initialising `f` to 0 for values that are present in the input with `(f@#=0;#)&/@`. Now `SplitBy` takes a list and a function and "splits list into sublists consisting of runs of successive elements that give the same value when `f` is applied" (note that `SplitBy` does not *remove* any elements). But the (undocumented) catch is, that `f` is called *twice* on each element - when comparing it to its predecessor and its successor. So if we do ``` SplitBy[{1,2,3,4},Print] ``` we don't just get each number once, but instead this prints ``` 1 2 2 3 3 4 ``` which is 6 calls for 3 comparisons. We can split the list *before* each second occurrence, if we write a function which always returns `False` but returns `True` when a second occurrence is compared to the element before it. That is the *third* check on that element (two checks on the first occurrence, plus the first check on the second occurrence). Hence, we use `++f[#]==3&`. The nice thing is that this already returns `False` again on the second check of the second occurrence, such that I can return `True` for consecutive second occurrences, but *still split between them*. Likewise, this *won't* split *after* second occurrences, because the function already returns `False` again on the second check. Now, the question wants us to also remove those second occurrences, so we drop the first element from each list, with `Rest/@`. But of course, we don't want to remove the very first element in the input, so we actually start off, by adding an element `a` to the beginning of the list with `{a}~Join~#`. `a` is an undefined variable, which Mathematica just treats as an unknown, so it won't affect any other values of `f`. This also ensures that the first *actual* element in the input gets its two checks like every other element. [Answer] # Python, 148 bytes ``` def s(a):z=len(a);x=[-1]+sorted({[i for i in range(z)if a[i]==n][1]for n in a if a.count(n)>1})+[z];return[a[x[i]+1:x[i+1]]for i in range(len(x)-1)] ``` Pretty horrendous solution. There's got to be a better way... Call with `s([2, 1, 1, 1, 4, 5, 6])`. ## Ungolfed version ``` def split(array): indices = [-1] second_occurrences = set() for n in array: if array.count(n) > 1: occurrences = [i for i in range(len(array)) if array[i] == n] second_occurrences.add(occurrences[1]) indices += sorted(second_occurrences) indices += [len(array)] return [array[indices[i]+1:indices[i+1]] for i in range(len(indices)-1)] ``` [Answer] # Haskell, ~~115~~ ~~113~~ ~~106~~ 88 ``` f?(x:s)|1<-f x=[]:x%f?s|a:b<-x%f?s=(x:a):b f?x=[x] (x%f)h=sum$f h:[1|x==h] r s=(\_->0)?s ``` this stores the amount every element appeared so far as a function from elements to their respective amount, which is an interesting trick. this works using `%`, a function that given a function f and an argument `x` returns a new function that returns `f` applied to it's argument if it is different than `x`, and `1 + f x` otherwise. for example, `3 % const 0` is a function which returns 0 for every argument except 3, for which it returns 1. **update:** fused the `foldl` to get a much smaller program. [Answer] ## Ruby 66 [demo](http://ideone.com/obA0Y6) ``` f=->a{c=Hash.new 0 r=[[]] a.map{|e|2==(c[e]+=1)?r<<[]:r[-1]<<e} r} ``` Ruby stabby lambda that takes an array as a parameter and returns an array of arrays. [Answer] # Python: 100 byte ``` def g(l): i=j=0;o=[] for e in l: if l[:i].count(e)==1:o+=[l[j:i]];j=i+1 i+=1 return o+[l[j:]] ``` Straightforward solution. I iterate over the list, count how many times a character appeared before, and append the part since the last check to the output list. [Answer] # Ruby, 66 ``` f=->a{s=Hash.new 0 r=[[]] a.map{|e|(s[e]+=1)==2?r<<[]:r[-1]<<e} r} ``` ## Explanation * `e` is a Hash of occurrence counts for each element, `r` is an Array in which the result is stored. * Loop trough the input, increment the occurrence count for each element by `1`. + If the occurrence count is `2`, we need to split. Add an empty `Array` to the result. + Otherwise just add the element to the last `Array` in result. [Answer] # CJam, ~~25~~ 24 bytes ``` q~{_L+:L1$a/,3=S@?}%Sa/p ``` Takes input from STDIN like ``` [ 2 1 2 1 0 2 2 1 1 3 4 3] ``` and outputs like ``` [[2 1] "" [0 2 2 1 1 3 4] ""] ``` I am basically iterating over all elements of the array, one by one putting them into another array. Then I get the count of the current element in the other array. If its 2, I start another array from that location. This kind of random array starting can only be achieved in a stack based language. **Code expansion**: ``` q~{_L+:L1$a/,3=S@?}%Sa/p q~{ }% "Evaluate the input array and map it on this block"; _ "Copy the current element in iteration"; L+:L "Add the copy to an initially blank array L and update L"; 1$a/ "Make another copy of the element and split L on it"; ,3= "This checks if the splitted array is of length 3"; "which indirectly means that L contains the element twice"; S@? "If the above is true, replace the element by space"; Sa/ "Split the final array on space. This final array contains"; "second occurrence of every integer replaced by a space"; p "Print the stringified version of the final nested array"; ``` [Try it online here](http://cjam.aditsu.net/) *1 byte saved from Martin's tip on chat* [Answer] # Ruby, 64 bytes ``` s=->a{x=[];b=[[]];a.map{|e|x<<e;x.count(e)==2?b<<[]:b[-1]<<e};b} ``` [Answer] # Perl 5: 36 Not sure if this is acceptable as no actual splitting happens here. ``` #!perl -pa $x{$_}++-1or$_=']['for@F;$_="[[@F]]" ``` Example: ``` $ perl spl.pl <<<"2 1 1 2 3 2 2 4 5 6 7 3 7 0 5" [[2 1 ][ ][ 3 2 2 4 5 6 7 ][ ][ 0 ][]] ``` [Answer] # CJam, 28 bytes ``` Lq~{1$1$a/,3=S2$?@++}/-2%S/` ``` Takes input on STDIN like ``` [2 1 1 2 3 2 2 4 5 6 7 3 7 0 5] ``` and prints the output to STDOUT like ``` [[2 1] "" [3 2 2 4 5 6 7] "" [0] ""] ``` Note that empty strings and empty arrays are the same thing in CJam, and are displayed as `""` by default (this *is* the native representation of empty arrays). (I started working on this a bit before the challenge was posted, because we were discussing how difficult the challenge would be.) ## Explanation Basically, I'm duplicating each element in the array, unless it's the second occurrence, in which case I replace the first copy with a space. For golfing reasons, this modified array is constructed in reverse. So `[2 1 1 2 3 2 3]` becomes ``` [3 S 2 2 3 3 2 S 1 S 1 1 2 2] ``` Then I pick out every second element from the end, which is the original array, but with second occurrences replaced by spaces, i.e. ``` [2 1 S S 3 2 S] ``` Finally, I simply split the array on spaces. Here is a breakdown of the code: ``` L "Push empty array."; q~ "Read STDIN an evaluate."; { }/ "For each element of the input."; 1$1$ "Copy the array and the element."; a/ "Split the array by that element."; ,3= "Check that it's split into 3 parts."; S2$? "If so, push a space, else, copy the current number."; @++ "Pull up the array from the bottom and add both to the beginning."; -2% "Pick every second element from the end."; S/ "Split on spaces."; ` "Get the string representation."; ``` [Answer] ## Unix tools, 100 bytes ``` grep -o '[-0-9]*'|awk '{print(++A[$0]-2)?$0:"] ["}'|paste -sd' '|sed -e '/]/s/.*/[\0]/' -e's//[\0]/' ``` Excepts the input via stdin. It basically just replaces every second occurrence with `"] ["`. Does not work with empty strings, `[]` will give an empty string, which I think is a convenient representation of an empty array :) [Answer] # APL, 42 characters ``` {'(',')',⍨⍵[(2=+/¨(↑=↓)¨⌽¨,\⍵)/⍳⍴⍵]←⊂')('} ``` Example: ``` {'(',')',⍨⍵[(2=+/¨(↑=↓)¨⌽¨,\⍵)/⍳⍴⍵]←⊂')('}2 1 1 2 3 2 2 4 5 6 7 3 7 0 5 ``` Output: ``` ( 2 1 )( )( 3 2 2 4 5 6 7 )( )( 0 )( ) ``` [Tested here.](http://ngn.github.io/apl/web/#code=%7B%27%28%27%2C%27%29%27%2C%u2368%u2375%5B%282%3D+/%A8%28%u2191%3D%u2193%29%A8%u233D%A8%2C%5C%u2375%29/%u2373%u2374%u2375%5D%u2190%u2282%27%29%28%27%7D2%201%201%202%203%202%202%204%205%206%207%203%207%200%205) If I must output a string that is interpreted exactly as the right structure in APL... 49 characters ``` {'1↓1(',',⍬)',⍨⍵[(2=+/¨(↑=↓)¨⌽¨,\⍵)/⍳⍴⍵]←⊂',⍬)('} ``` [Answer] # Java, 223 This only works on Oracle or OpenJDK JRE, since I make use of [this quirk](https://stackoverflow.com/questions/1536915/regex-look-behind-without-obvious-maximum-length-in-java) in their implementation of quantifier and length check in look-behind to implement variable-length look-behind. ``` class W{public static void main(String a[]){System.out.print("["+new java.util.Scanner(System.in).nextLine().replaceAll(" *\\b(\\d+)\\b(?=(.*))(?<=^(?=(.*\\b\\1\\b){2}\\2).*)(?<!^(?=(.*\\b\\1\\b){3}\\2).*) *","] [")+"]");}} ``` Most of the work is done in the regex, which is shown below in raw form: ``` *\b(\d+)\b(?=(.*))(?<=^(?=(.*\b\1\b){2}\2).*)(?<!^(?=(.*\b\1\b){3}\2).*) * ``` Before we look at the regex above, let us look at equivalent .NET regex, which is simpler, since it directly supports variable-length look-behind (.NET look-behind is most likely done by right-to-left matching mode): ``` *\b(\d+)\b(?<=(.*\b\1\b){2})(?<!(.*\b\1\b){3}) * ``` * `*\b(\d+)\b` and `*` at the end matches a number and the surrounding spaces (if any). The bound checks are to prevent partial number from being matched, since spaces on both sides are optional. It also captures the number to check whether it is the 2nd appearance in the array. * `(?<=(.*\b\1\b){2})` checks that 2 instances of the number captured above can be found. `(?<!(.*\b\1\b){3})` checks that no 3 instances of the number captured can be found. Both conditions combined asserts that there are only 2 instances of the number so far. The bound checks are there to make sure the whole number is tested. Back to the Java version. To implement variable-length look behind, we transform ``` (?<=var-length-pattern) ``` to ``` (?<=^(?=.*var-length-pattern).*) ``` I am a bit hand-waving regarding the fact that `.` excludes line separators, but it can be fixed easily and I don't want to further complicate the syntax. The look-ahead is always 0 in length, and the length check passes due to the implementation of `*` quantifier. The `^` is not necessary to make it work, but it is there to make the failing case fails faster. Look-behind in Oracle/OpenJDK implementation is done by stepping back the minimum length of the pattern, then match, then rinse and repeat by incrementing the length until a match is found, or in the worst case, to the maximum length of the pattern. With `^`, I make sure the prefix string is only matched once. However, the look-ahead inside the look-behind is not limited by look-behind's right-boundary, so it can match all the way to the end of the string. In order to assert the boundary, I capture the rest of the string into another capturing group inside a look ahead, and use it to limit the reign of the variable length pattern. ``` (?=(.*))(?<=^(?=.*var-length-pattern\m).*) ^--^ ^ mth capturing group m is the number of the capturing group marked ``` Since my pattern already starts with `.*`, I don't need to add another `.*` in front. [Answer] ### Perl 108 ``` map{$e[$_]==1?do{push@a,[@b];@b=();}:push@b,$_;$e[$_]++}split" ";push@a,[@b];s/.*/Data::Dumper->Dump(\@a)/e; ``` In action: ``` perl -MData::Dumper -pe ' $Data::Dumper::Terse = 1; $Data::Dumper::Indent = 0; @a=@b=@e=(); map{$e[$_]==1?do{push@a,[@b];@b=();}:push@b,$_;$e[$_]++}split" "; push@a,[@b]; s/.*/Data::Dumper->Dump(\@a)/e; ' <<<$'2 1 1 2 3 2 2 4 5 6 7 3 7 0 5\n2 1 1 1 4 5 6\n'"$( sed 's/./& /g;w/dev/stderr' <<< ${RANDOM}${RANDOM}${RANDOM}$'\n'${RANDOM}${RANDOM})" 2 4 4 7 7 2 9 8 8 4 6 0 1 8 1 0 3 9 3 7 9 [2,1][][3,2,2,4,5,6,7][][0][] [2,1][1,4,5,6] [2,4][7][][9,8][4,6,0,1,8] [1,0,3,9][7][] ``` Nota: The two first lines `$Data::...` are there only for nicer presentation and third line `@a=@b=@e=();` is there for making the tool working on multiple lines. [Answer] ## R, 76 ``` y=scan();r=split(y,cumsum(ave(y,y,FUN=seq)==2));c(r[1],lapply(r[-1],"[",-1)) ``` Output for the example: A list of five elements, including three empty vectors. (`numeric(0)`). ``` $`0` [1] 2 1 $`1` numeric(0) $`2` [1] 3 2 2 4 5 6 7 $`3` numeric(0) $`4` [1] 0 $`5` numeric(0) ``` By the way: The code generates a warning message that can be ignored. [Answer] # awk 29 ``` a[$1]++==1{print"-";next}1 ``` This takes a bit of liberty with the input and output formats. Input "array" is vertical, one number per line. Output is also vertical, one number per line, with dashes separating arrays. Input: ``` 2 1 1 2 3 2 2 4 5 6 7 3 7 0 5 ``` Output: ``` 2 1 – – 3 2 2 4 5 6 7 – – 0 – ``` [Answer] # Pyth 30 ~~32~~ This is my first time experimenting with Pyth. It's the same solution as in my Python solution. ``` VQIq/<QN@QN1~Y]:QZN=ZhN;+Y]>QZ ``` You can try it online: [Pyth Compiler/Executor](http://isaacg.scripts.mit.edu/pyth/index.py) E.g. The input ``` [2,1,1,2,3,2,2,4,5,6,7,3,7,0,5] ``` will print ``` [[2, 1], [], [3, 2, 2, 4, 5, 6, 7], [], [0], []] ``` ## Explanation: ``` # Q = input(), Y = [], Z = 0 VQ # for loop: N iterates over the indices of Q I # if q\<QN@QN1 # Q[N] appears exactly once in Q[:N] ~Y]:QZN # append the list [Q[Z:N]] to Y =ZhN # and assign Z = N + 1 ; # end if and for loop +Y]>QZ # print Y + [Q[Z:]] ``` [Answer] # Python 2, 84 ``` l=[[]];p=[] for x in input():p+=[x];b=p.count(x)==2;l+=[[]]*b;l[-1]+=[x][b:] print l ``` The list `l` is the output so far. We iterate over the elements. If the current one is the second appearance, we start a new empty sublist; otherwise, we add it to the latest sublist. The list of elements seen so far is stored in `p`. Strangely, reconstructing the list seems shorter than slicing the input. [Answer] ## Pure bash ~~111~~ 94 **81** for only splitting: ``` for i;do [ "${b[i]}" == 7 ]&&c+=("${d# }") d=||d+=\ $i;b[i]+=7;done;c+=("${d# }") declare -p c ``` The second line `declare -p c` just dumping the variable Sample: ``` splitIntFunc() { local b c d i for i;do [ "${b[i]}" == 7 ]&&c+=("${d# }") d=||d+=\ $i b[i]+=7 done c+=("${d# }") declare -p c } ``` Nota: the line `local b c d i` is only required for running the function several times. ``` splitIntFunc 2 1 1 2 3 2 2 4 5 6 7 3 7 0 5 declare -a c='([0]="2 1" [1]="" [2]="3 2 2 4 5 6 7" [3]="" [4]="0" [5]="")' splitIntFunc 2 1 1 1 4 5 6 declare -a c='([0]="2 1" [1]="1 4 5 6")' splitIntFunc $(sed 's/./& /g;w/dev/stderr' <<<${RANDOM}${RANDOM}${RANDOM}) 1 6 5 3 2 2 4 3 9 4 2 9 7 7 4 declare -a c='([0]="1 6 5 3 2" [1]="4" [2]="9" [3]="2" [4]="7" [5]="4")' splitIntFunc $(sed 's/./& /g;w/dev/stderr' <<<${RANDOM}${RANDOM}${RANDOM}) 2 4 5 2 9 1 1 4 8 7 8 1 0 3 declare -a c='([0]="2 4 5" [1]="9 1" [2]="" [3]="8 7" [4]="1 0 3")' ``` ### For sexiest presentation (+26) ``` splitIntFunc() { local b c d i for i;do [ "${b[i]}" == 7 ]&&c+=("${d# }") d=||d+=\ $i b[i]+=7 done c+=("${d# }") printf -v l "(%s) " "${c[@]}" echo "<$l>" ``` Will render something like: ``` splitIntFunc 2 1 1 2 3 2 2 4 5 6 7 3 7 0 5 <(2 1) () (3 2 2 4 5 6 7) () (0) () > splitIntFunc $(sed 's/./& /g;w/dev/stderr' <<<${RANDOM}${RANDOM}${RANDOM}) 4 3 8 1 4 5 7 9 2 7 8 4 0 <(4 3 8 1) (5 7 9 2) () (4 0) > splitIntFunc $(sed 's/./& /g;w/dev/stderr' <<<${RANDOM}${RANDOM}${RANDOM}) 3 1 3 0 2 5 3 6 6 9 2 5 5 <(3 1) (0 2 5 3 6) (9) () (5) > splitIntFunc $(sed 's/./& /g;w/dev/stderr' <<<${RANDOM}${RANDOM}${RANDOM}) 2 2 2 9 1 9 5 0 2 2 7 6 5 4 <(2) (2 9 1) (5 0 2 2 7 6) (4) > } ``` [Answer] # Scala, ~~122~~111 Take character collection, print in form of `[21][][3224567][][0][]`, ~~122~~111: ``` def s(a:Any*)=print((("[","")/:a){case((b,c),d)=>if(b.indexOf(d)==c.indexOf(d))(b+d,c)else(b+"][",c+d)}._1+"]") ``` ...or take a character collection and return nested lists, ~~135~~129: ``` def s(a:Char*)=(("",List(List[Any]()))/:a){case((b,c),d)=>b+d->(if(b.count(d==)==1)List()::c else(c.head:+d)::c.tail)}._2.reverse ``` I'm sure there are some savings I could get, I have not looked too hard. [Answer] ## Java: 563 bytes note this uses Java 8, pre-JDK8 would be a few bytes longer due to the foreach. ``` import java.util.*;public class a{static String c(String[]b){List<String>d=new ArrayList<>(Arrays.asList(b));Set<String>e=new HashSet<>();Set<String>f=new HashSet<>();for(int i=0;i<Integer.MAX_VALUE;i++){String g;try{g=d.get(i);}catch(IndexOutOfBoundsException ex){break;} if(e.contains(g)&&!f.contains(g)){d.remove(i);d.add(i,"]");d.add(i+1,"[");f.add(g);i++;}else{e.add(g);}} d.add(0,"[[");d.add(d.size(),"]]");StringBuilder sb=new StringBuilder();d.forEach(sb::append);return sb.toString();} public static void main(String[]args){System.out.println(c(args));}} ``` ]
[Question] [ Given a list of positive integers, partition the list into two sublists such that the absolute value of the difference of the sums over the two sublists is minimal. The output of the program should be the (non-negative) difference of these sums. ## Examples: ``` [1,2,3] -> 0 # [1,2], [3] [2,3,5,7,11] -> 0 # [2,5,7], [3,11] [13,17,19,23] -> 0 # [13,23], [17,19] [1,2,3,4] -> 0 # [1,4], [2,3] [2,2,2,3,3] -> 0 # [2,2,2], [3,3] [1,2,3,4,5] -> 1 # [1,2,4], [3,5] [1,2,3,4,5,6] -> 1 # [1,2,3,4], [5,6] [1,1,2,5] -> 1 # [1,1,2], [5] [1,3,9,27] -> 14 # [1,3,9], [27] ``` ## Rules * The sublists do not need to be contiguous * Every element of the list has to be in (exactly) one of the two sublists * The list can contain duplicate elements * You can assume that the list contains at least 3 elements * You are allowed to assume that the list is sorted (using any convenient ordering) * The ordering of two numbers should be the same for all lists * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest solution wins --- [related challenge](https://codegolf.stackexchange.com/questions/48486/the-partition-problem-sorting-stacks-of-boxes) [Answer] # [Python](https://www.python.org), 57 bytes ``` f=lambda A,B,*a:min((z:=[abs,f][a>()])(A+B,*a),z(A-B,*a)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZBNTsMwEIXFNqcYCRZ2maAmTgiNlErpNaxZuGojLOVPbUCiV2GTDdwJToMnTkvBG9vvfXrz7PfP_m147tpx_HgZqvDpa1UVtWm2OwMlbnBh8sa2QpzyQpvtESvSZi0kSVHesyvxJMpwOsk5YFN1B6jBttD1-1YsZR6AxQ4KaEwv9q-mxvrh2Nd2EFLnKo9JBtAfbDuISiysxG5OGr9v7nSEMSoCv8I1LAFugVVC0IoC7WxMMcMooisgZm1C2Ah05HbHrDB2Yb8xiu-OmjzGeBom9H9awhAXuSCYkkeicyEPuTLXED7SX0h5jA3GWEov487Y_DyfpNC1zuiMJB5x6tQpo8D_1g8) Takes splatted input. Input must have at least 2 elements. ### How? Recursively builds up all possible differences by successively adding or subtracting each element (except the first which is allowed to break symmetry). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 5 bytes ``` æOÂαß ``` [Attempt this online!](https://ato.pxeger.com/run?1=m73MwDQxyTB1wYKlpSVpuhYrDy_zP9x0buPh-UuKk5KLoaILVkcb6hjpGOuY6JjGQoQA) or [try all testcases](https://ato.pxeger.com/run?1=m73MwDQxyTB1weqySnslBV07BSX7yqWlJWm6FisPL_M_3HRu4-H5S4qTkosX6kCEF9xMiY421DHSMY7VUYgGUjqmOuY6hoYgnqGxjiGQbaljBJYEq9IxQWLqmKJwdMwgXJAAVMZYB6jbPDYWYhkA) ## Explanation Utilizes the fact that 05AB1E's powerset builtin returns the sets in the same order as looking at the numbers \$0\$ - \$2^n-1\$ in binary reversed, so the opposite of each element when reversing is its complement. ``` æ # all subsets of the input O # the sum of each  # Bifurcated, push the reverse without popping α # take the absolute difference (vectorizes) ß # the minimum of that ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 16 bytes ``` &//|/-:\+/:/+-:\ ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs1LT16/R17WK0da30tcG0lxcaQqGCkYKxkAaSCqYKpgrGBqCBI0VDIFMSwUjY5gSBRMES8EUma1gBuaB+BBxYwWgRnOwmUZgRcYAqVIWaw==) ``` +-:\ ± each +/:/ outer sum |/-:\ abs &// min ``` [Answer] # [Uiua](https://uiua.org), 10 [bytes](https://codegolf.stackexchange.com/a/265917/97916) Same idea as loopy walt's Python answer. ``` /↧⌵/(⊂⊃+-) ``` [Try it!](https://uiua.org/pad?src=ZiDihpAgL-KGp-KMtS8o4oqC4oqDKy0pCgpmIFsxIDIgM10KZiBbMiAzIDUgNyAxMV0KZiBbMTMgMTcgMTkgMjNdCmYgWzEgMiAzIDRdCmYgWzIgMiAyIDMgM10KZiBbMSAyIDMgNCA1XQpmIFsxIDIgMyA0IDUgNl0KZiBbMSAxIDIgNV0KZiBbMSAzIDkgMjddCg==) ``` /↧⌵/(⊂⊃+-) # Function taking a vector from the stack and leaving a number /( ) # Reduce the vector by ... ⊂ # Concatenate the results from ... ⊃+- # both adding and subtracting the new value from all intermediate values. ⌵ # Take the Absolute Value of each number /↧ # Reduce by Minimum ``` [Answer] # [R](https://www.r-project.org), 56 bytes ``` f=\(x,s=0)`if`(any(x),f(x[-1],c(s,-s)+x[1]),min(abs(s))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY9BDoJADEX3nqSNfxLLiOCCkyAJSNKEhSwcTcZ4FDaw8FDexsEwGt399_vb_A7TeRwf14ua_JlrcSAPV2y47rSmpr-RZyj50kiFlhyM47UvpWKcup6aoyPHzMv-XaklQQLLvJp1UEiRQWQxxEIC7pHEyDuO7S8h_WfsPs7sfecW4VgWK8RXXg) A recursive function, partly inspired by [@loopywalt’s Python answer](https://codegolf.stackexchange.com/a/266489/42248) so be sure to upvote that one too! Takes an integer vector and returns an integer. # An alternative non-recursive approach R, ~~60~~ 57 bytes ``` \(x)min(abs((1:max(s<-2^seq(x))%o%(2/s)%/%1%%2*2-1)%*%x)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3LWM0KjRzM_M0EpOKNTQMrXITKzSKbXSN4opTC4Eymqr5qhpG-sWaqvqqhqqqRlpGuoaaqlqqQBmoAdVpGskahjpGOsaamlwgNpClY6pjrmNoCBUwNNYxBHItdYxgSsDKdUxQeTqm6HwdM7gISAwhb6wDNMwc5oQFCyA0AA) This one avoids recursion, but uses an outer multiplication table and matrix multiplication. *Thanks to @Giuseppe for saving three bytes!* [Answer] # [JavaScript (Node.js)](https://nodejs.org), 55 bytes ``` f=([c,...x],y=0)=>c?1/Math.max(1/f(x,y+c),1/f(x,y-c)):y ``` [Try it online!](https://tio.run/##ddBLDoIwEAbgvado4qaNQ7EUJJqgJ/AEpAtSwUcQjBgDp8cOTxXtqpm/X2aml@gZFfp@vj2sLD/EdZ0ENNTAOS8VVMGSBVu9E/Y@epz4NSqpsBNaQrXQDLqrpRnbVLXOsyJPY57mR5rQUIADUjFm26Q91pYsCZkTTBSQUKrZFzEAPPBBiM4NxMF6gzD8dsJUjVqD0zUcW0msGdfkU4gzgjtO@TajiwxX@IPA65lBol@sZWaN/wxWw5Ajky3EcArxgfcxZA@7r/zVTYL5D39QiNwWmaTZzVf1Cw "JavaScript (Node.js) – Try It Online") -1B from tsh [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` żNŒp§AṂ ``` [Try it online!](https://tio.run/##y0rNyan8///oHr@jkwoOLXd8uLPp/9FJAYeWP9y1MFQFyOOC8HYsAQoEg/g@h2doP9w5/fD0R407IBq4Hu7cZ/2oYY6Crp3Co4a51g93zj6y/9HGdSZAcRWuh7u3PNyx6eGORWGH249tetS0JvL/fyUlpWhDHSMd41gFCADqNFBQUFYAicbqKEQbx3JFA6V1THXMdQwNY5EUGIHEwEpAElzRhkAaqMZSxwhoGMIYYxAfqAosB1IGsk3HJBZmmyHUNhOQIpBD4Ep0TGNRlRhBFAEdg6xIxywWVZExRBlIAqQMJGSKYR3UexCTjHWArjaPhSkxgSgBioLdZB4LDCUA "Jelly – Try It Online") A monadic link that takes a list of integers and returns an integer. Works by zipping the original list with its negation, taking the Cartesian project, and finding the minimum absolute sum. ## Alternative 7-byters and a 9-byter: ``` ŒP§ạU$Ṃ ŒP§ḤạSṂ LØ+ṗ×⁸§AṂ ``` The first two are variants on [@CommandMaster’s 05AB1E answer](https://codegolf.stackexchange.com/a/266480/42248). The third works similarly to [my non-recursive R answer](https://codegolf.stackexchange.com/a/266495/42248). Note the [TIO link above](https://TIO-lolo9wo1) includes all 4 versions. [Answer] # [Scala](http://www.scala-lang.org/), ~~98~~ 82 bytes Saved 16 bytes thanks to @corvus\_192 --- Golfed version. [Try it online!](https://tio.run/##hc9Nb8IwDAbgO7/Cx0QzH6F0iEhtteOkcUI7IYRCViBTybYmB6qqv72YrjA0jc4XR8lj643TKlP1x@Y91R7mylgo67d0m7BMLtKv5bP1KywktWjEm5bBQXm9L7VyKWgpj1EMCTti8aD5wdjm2Ne8eV5HcTFQG1fVALSUJo1lKt85CU95rorlwufG7lZcwqs1HiIoe0D1Sbc@syxhL8Z5JnCMAeccLjUcQj@G0V@WJIY4RSHagQ4rAhQkZzhut3fZcwac/KT432J40d9WdFp8vM1wx551@DvDHRsgfWx6xa2dEK56VX0C) ``` def?(l:Seq[Int],y:Int=0):Int=l match{case c::x=> ?(x,y+c)min?(x,y-c)case _=>y.abs} ``` Ungolfed version. [Try it online!](https://tio.run/##hdFPS8MwGAbw@z7Fc0zw3Z@sq2OBDTwK6kU8jR2y2G6RtkqTw4rss9fEpW6Iq4WUN@nvTZ5Qq1Wh2vZ9@5Zph0dlKnwOgNcsR84KY53Eg3@v7yu3ITQSvsASE95VQQNBolRO7@MCoJXNoCElDliuwsf9qDQVy9nBb4QbaE6Ik6Gf8Mu@J1OEuutTW8uaEzgOwogRS5@XqXpnJe7qWjXrZ1ebarfx6V4qc4734VddEc4Ol2GCppRwztE94zGGK0z@sl5SSnMSIjb0WJGQ8HJB07h7nw0ZaHZO8b@ltNMnK3ot3V5muGKDTn9nuGIT8heb/@BoZ9//49i2Xw) ``` object Main { def f(list: List[Int], y: Int = 0): Int = { list match { case c :: x => math.min(f(x, y + c), f(x, y - c)) case Nil => math.abs(y) } } def main(args: Array[String]): Unit = { println(f(List(1,2,3))) // -> 0 println(f(List(2,3,5,7,11))) // -> 0 println(f(List(13,17,19,23))) // -> 0 println(f(List(1,2,3,4))) // -> 0 println(f(List(1,2,3,4,5))) // -> 1 println(f(List(1,2,3,4,5,6))) // -> 1 println(f(List(1,1,2,5))) // -> 1 println(f(List(1,3,9,27))) // -> 14 } } ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `g`, 31 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 3.875 bytes ``` ṗṠḂε ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJnPSIsIiIsIuG5l+G5oOG4gs61IiwiIiwiMSwzLDksMjciXQ==) Bitstring: ``` 1001111110100111110010001110010 ``` Ports 05ab1e exactly, command for command. ## Explained ``` ṗṠḂε­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢⁡​‎‏​⁢⁠⁡‌­ ṗ # ‎⁡Powerset, in infinite list friendly order Ṡ # ‎⁢Vectorised sums Ḃ # ‎⁣Bifurcated ε # ‎⁤Absolute differences # ‎⁢⁡The g flag returns the smallest item. 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Uiua](https://uiua.org), 18 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` /↧⌵-⇌.≐(/+▽)⋯⇡ⁿ⧻,2 ``` [Try it!](https://uiua.org/pad?src=UCDihpAgL-KGp-KMtS3ih4wu4omQKC8r4pa9KeKLr-KHoeKBv-KnuywyCgpQIFsxIDIgM10KUCBbMiAzIDUgNyAxMV0KUCBbMTMgMTcgMTkgMjNdClAgWzEgMiAzIDRdClAgWzEgMiAzIDQgNV0KUCBbMSAyIDMgNCA1IDZdClAgWzEgMSAyIDVdClAgWzEgMyA5IDI3XQpQIFsyIDIgMiAzIDNdICAjIGF0dCBzdWdnZXN0aW9uCg==) ``` /↧⌵-⇌.≐(/+▽)⋯⇡ⁿ⧻,2 ⁿ⧻,2 # 2 to the <length of input> power ⇡ # create a range from that number ⋯ # binary (vectorizing big-endian) ≐( ) # tribute (apply (...) to each binary list and the input) ▽ # keep (forming an element of the power set of the input) /+ # sum . # duplicate (the sums) ⇌ # reverse ⌵- # absolute difference /↧ # minimum ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 5 bytes ``` ŋ∑Aaṁ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FquOdj_qmOiY-HBn45LipORiqPCCm-nRhjpGOsaxXNFAUsdUx1zH0BDIMTTWMQQyLXWMQFJgJTomYEVGYDaSqI4pMlvHDMwD8SHixjpAQ8xjIfYBAA) A port of [@att](https://codegolf.stackexchange.com/users/81203/att)'s [K (ngn/k) answer](https://codegolf.stackexchange.com/a/266510/9288). ``` ŋ∑Aaṁ ŋ Optionally negate each element of the input ∑ Sum A Absolute value a All possible values ṁ Minimum ``` [Answer] # [J](http://jsoftware.com/), 14 13 bytes ``` [:<./(+|@,-)/ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o61s9PQ1tGscdHQ19f9rcqUmZ@QrpCkYKhgpGMM4QKaCqYK5gqEhXNpYwRDIt1QwMkbRoWCC0GMEFkCXVzDFEFAwQwiBBJFUGCsArTD/DwA "J – Try It Online") A port of [ovs's Uiua answer](https://codegolf.stackexchange.com/a/266491/78410) thanks to Bubbler. -1 thanks to att. ## [J](http://jsoftware.com/), 18 bytes ``` [:<./[:|@,]+//@,.- ``` [Try it online!](https://tio.run/##ZY27CsJAFET7fMWgkGTJvjcxuKgsClZiYRtSiSHY@AOSX1@vAY2P4sKdMzPMNc5k1mHtkYFDw9MJid3psI@NX0nV@HvgbaFU4FJElhy3EqMR8vmw8almPOSFarlgA2VSnVzO/Q0dDCzcS9CLCjWMedsOhvQS1n01UE4dO4JfH9UfwGJCT/iRcKCJOj4A "J – Try It Online") A port of [att's nice K answer](https://codegolf.stackexchange.com/a/266510/15469). [Answer] # [Python](https://www.python.org), 86 bytes *-10 bytes by [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* *-4 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)* ``` def f(s,l={0}): for i in s:l|={i+j for j in l} return min(abs(a+a-sum(s))for a in l) ``` First time golfing in Python! [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3w1JS0xTSNIp1cmyrDWo1rbgU0vKLFDIVMvMUiq1yamyrM7WzwEJZIKGcWi6FotSS0qI8hdzMPI3EpGKNRO1E3eLSXI1iTU2QskSwMk2I6VsKijLzSjTSNKINdYx1LHWMzGM1oVIwBwAA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~24~~ 20 bytes ``` ⊞υ⁰Fθ≔⁺υ⁺υιυI⌊↔⁻Σθ⊗υ ``` [Try it online!](https://tio.run/##NYrLCsIwEEX3fkWWExhB62PTVdGtEHBZukhrtYFpQjOZ/n5MBe/mwjlnmGwcgqWcjfAEguqg6907RAWLVg2z@3gwJLyp/zutUUnpTHQ@wc1ygofzbpYZmp4DSRo3UOpnQUup70F6Gl8g@rc657Y9YoUnPOMFr12X9yt9AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @mathscat's Python answer. ``` ⊞υ⁰ ``` Start with the sum of the empty sublist. ``` Fθ ``` Loop over the input list. ``` ≔⁺υ⁺υιυ ``` Calculate the sums of the subsets including the current element and any subset of the previous elements and append those to the list of subset sums. ``` I⌊↔⁻Σθ⊗υ ``` Calculate the minimum difference between each subset and its complement, using the equation \$ | \sum (U \setminus A) - \sum A | = | \sum U - \sum A - \sum A | = | \sum U - 2 \sum A | \$. Previous 24-byte solution: ``` I⌊↔⁻Σθ⊗EX²LθΣEθ×λ﹪÷ιX²μ² ``` [Try it online!](https://tio.run/##RYu5DsIwEAV/xeVGWgrC0VAh0kTCUiToohROYpGVfBAf4fON3cArZ@ZNi3CTFSqlzpEJcBM@ACdDOmq4jt6qGGQB0cMjo7VC1tg4KjkDF2/o7Ec6qJHdpXmFJfsclLDIFdmTtPSgkHE7R2WhNaGhjWYJhOx31uVVV/9dUur7PdZ4wCOe8DwMabepLw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input list Σ Take the sum ⁻ Vectorised subtract ² Literal integer `2` X Raised to power θ Input list L Length E Map over implicit range θ Input list E Map over elements λ Current element × Multiplied by ι Outer value ÷ Integer divided by ² Literal integer `2` X Raised to power μ Inner index ﹪ Modulo ² Literal integer `2` Σ Take the sum ⊗ Doubled ↔ Vectorised absolute ⌊ Take the minimum I Cast to string Implicitly print ``` 19 bytes using the newer version of Charcoal on ATO: ``` I⌊↔⁻Σθ⊗EX²Lθ↨¹×θ↨κ² ``` [Attempt This Online!](https://tio.run/##RYu5DsIwEAV/xeVGWgrC0VAh0kTCUiToohROYpGVfBAf4fON3cArZ@ZNi3CTFSqlzpEJcBM@ACdDOmq4jt6qGGQB0cMjo7VC1tg4KjkDF2/o7Ec6qJHdpXmFJfsclLDIFdmTtPSgkHE7R2WhNaGhjWYJhOx31uVVV/9dUur7PdZ4wCOe8DwMabepLw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⁻Σθ⊗EX²Lθ As above θ Input list × Zipped multiply with κ Current value ↨ Converted to base ² Literal integer `2` ↨¹ Take the sum I⌊↔ As above ``` (`Sum` doesn't work on empty lists because it needs to know what type of list it's summing.) [Answer] # APL+WIN, 46 bytes Prompts for vector of integers: ``` ⌊/|(+/i×m)-+/(i←(b,n)⍴v)×~m←⍉(n⍴2)⊤⍳b←2*n←⍴v←⎕ ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3t/6OeLv0aDW39zMPTczV1tfU1MoFyGkk6eZqPereUaR6eXpcLFHjU26mRBxQw0nzUteRR7@YkoJiRVh5YZksZiOqb@h9oHtf/NC5DBSMFY640LiCpYKpgrmBoCOQYGisYApmWCkYgKbASBROwIiMwG0lUwRSZrWAG5oH4EHFjBaAh5gA "APL (Dyalog Classic) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒṖ§ḅ-AṂ ``` A monadic Link that accepts a list of integers and yields the smallest partition difference. **[Try it online!](https://tio.run/##y0rNyan8///opIc7px1a/nBHq67jw51N/w@3P2pa8/9/dLShjpGOcawOl0I0kNYx1THXMTQEcw2NdQyBHEsdI4g0WKGOCVSpEZiHIqNjisrTMYPyQSIwOWMdoIHmQE4sAA "Jelly – Try It Online")** ### How? Creates all partitions then treats every other part as being in the first of the two sets. Calculates the difference by converting the sums of the parts from base one (which takes the negative of every other part-sum). ``` ŒṖ§ḅ-AṂ - Link: list of integers e.g. [4,5,6] ŒṖ - all list partitions [[[4],[5],[6]],[[4],[5,6]],[[4,5],[6]],[[4,5,6]]] § - sums [[4,5,6],[4,11],[9,6],[15]] ḅ- - from base -1 [5,7,-3,15] i.e. 6-5+4=5 11-4=7 6-9=3 15=15 A - absolute values [5,7,3,15] Ṃ - minimum 3 ``` --- Alternatives ``` ŒP§ạṚ$Ṃ - sum every subset absolute difference with its own reverse, minimum żNŒp§AṂ - zip with negative, take the Cartesian product, get sums, absolute values, minimum ``` [Answer] # Excel, 106 bytes ``` =LET( a,A1#, b,ROWS(a), c,MOD(INT(SEQUENCE(2^b,,)/2^SEQUENCE(,b,)),2), MIN(ABS(MMULT(c,a)-MMULT(ABS(1-c),a))) ) ``` Input is spilled, *vertical* array in cell `A1`. [Answer] # [C (GCC)](https://gcc.gnu.org), 66 bytes ``` A,B;d(a,n)int*a;{for(A=B=0;n--;)A<B?A+=a[n]:(B+=a[n]);a=abs(A-B);} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lZBBbsIwEEXFEk4xAorsMqmahADFuMi-BkXIxAQsgVNBYBPlJN1kw6HoaWqUSixaWrGa0R-9P3_m4xTPV3FcntstY-PNQS9hvM-0SZ_Wr42rtFXZ2imnQ5Z4w7MUKJkmCi01NntULE_SHRFc8mdmPY9RMZYT0eVqamcjIquGMsXVYk-EJykrKqfPWscZwFYZS46p0RTyRj2Hi6amM-CQg48hvmAwgILB-85NEtJ80G-2iXBJAD1KGRQ_KR8DjO6FAreshxH2b4H9v8FbWPQ7FqI_QN9dF_4T9PtdZVnVLw) -1 thanks to Arnauld. A simple greedy algorithm. The program uses a wide assortment of tricks: * K&R function declarations * Assumes that the input is sorted, per challenge specs. * Global variables assumed zero & permitted to omit the type specifier due to implicit int. * Implicit int in function declaration * `~i` will check if `i` is not `-1`. * Ternary operator replaces an if. * A return statement is avoided by assuming `-O0` and exploiting the load to `a` writing to `rax`, the return value register on x86. [Answer] # [Desmos](https://desmos.com/calculator), 86 bytes ``` f(l)=[abs(l.total-2total(mod(floor(2i/{2^{[1...L]}),2)l))fori=[1...2^L]].min L=l.count ``` [Try It On Desmos!](https://www.desmos.com/calculator/3ushwge0sx) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/nmxl53bldq) ]
[Question] [ For this challenge, we will define the "complement" of a list of integers `A` as being any list `B` such that the union of `A` and `B` is a list of consecutive integers with no repeats. In other words, `B` is the complement of `A` if * `B` has all of the integers between the minimum and maximum of `A` which are missing from `A`, and * `B` has none of the integers present in `A` For example: `[2, 4, 6, 7]` is a complement of `[1, 3, 5, 8, 9]`, `[1, 3, 5]`, and `[3, 5]`, but it is *not* a complement of `[1, 2, 3, 5]` or `[1, 3, 5, 9]`. Worth noting: For a list of consecutive integers, a complement may be the empty list, as no integers are "missing" between the minimum and maximum. Any given list of integers with no repeats has infinitely many complements (proof left as an exercise for the reader), but has exactly one smallest complement, which itself has this very same property. For example, if we start with the list `[1, 2, 3, 5, 8, 13]` and repeatedly find the smallest complement, we get this chain of lists: ``` [1, 2, 3, 5, 8, 13] [4, 6, 7, 9, 10, 11, 12] [5, 8] [6, 7] [] ``` The smallest complement of the empty list is the empty list, so we can stop here. ## Challenge Given a list of non-repeating *positive* integers `A`, output the `A`'s smallest complement, followed by that list's smallest complement, all the way until the empty list. ## Rules * You may choose to include or omit the input list in your output. * You may choose to include or omit the empty list in your output. * The input list will always have complements. (i.e. the list will never contain duplicates) * The input will be sorted. * The input will never be the empty list. * The input will never contain 0 or negative integers. (although they are well defined) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. ## Examples Outputs will include both the original list and the empty list, for clarity ``` input => output [1, 3, 5, 7, 9] => [[1, 3, 5, 7, 9], [2, 4, 6, 8], [3, 5, 7], [4, 6], [5], []] [5, 10, 15, 20] => [[5, 10, 15, 20], [6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19], [10, 15], [11, 12, 13, 14], []] [5, 10, 15] => [[5, 10, 15], [6, 7, 8, 9, 11, 12, 13, 14], [10], []] [1, 2, 6, 7, 11, 12] => [[1, 2, 6, 7, 11, 12], [3, 4, 5, 8, 9, 10], [6, 7], []] [1, 2, 3] => [[1, 2, 3], []] [5, 6, 7] => [[5, 6, 7], []] ``` [Answer] # [R](https://www.r-project.org), ~~45~~ 44 bytes ``` f=function(r)r&f(print(setdiff(r:max(r),r))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMG-zJLUosSSzLLU-OLcxJyc1OKS-OT83IKc1NzUvBLbpaUlaboWN3XSbNNK85JLMvPzNIo0i9TSNAqKMvNKNIpTS1Iy09I0iqxyEyuAMjpFmpqaUD16eE3WSNYw1DHSMdYx1bHQMTSG6VqwAEIDAA) Derived without peeking at [pajonk's R answer](https://codegolf.stackexchange.com/a/248975/95126), but ended-up with a pretty similar approach ... [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` U¡S-… ``` [Try it online!](https://tio.run/##yygtzv5/aFvuo6bG/6GHFgbrPmpY9v///@hoQx0jHWMdUx0LHUPjWB0gF8Qx17EEsk11DA10DE11jAwQHLASIx0zoBJDQx1DIyjfGKwCKBobCwA "Husk – Try It Online") ``` ¡ # Apply function repeatedly, collect values in infinite list: - # list difference of S # last result (or input for first iteration) S … # and last result with gaps filled with numeric ranges; U # Finally, get longest prefix of the list with all unique elements. ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 18 bytes Includes input and empty list (`!0`) in the output. ``` {(x,/x_!0^*|x)^x}\ ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6rWqNDRr4hXNIjTqqnQjKuojeHiSlMwVDBSMFYwVbBQMDQGc0EccwVLINtUwdBAwdBUwcgAwYHqMAMqMTRUMDSCmQBWARQFALqQFQQ=) `{ ... }\` Converges; Call the lambda repeatedly until the value doesn't change. `( ... )^x` The range computed in the parentheses without the elements in x. `*|x` Last (largest) value in x. This returns `0N` if x is empty, then `0^` replaces `0N` with 0. `!` range from 0 to this value value (exclusive). `x_` cut this range at the indices given by x. Because the first slice is omitted, this gets rid of the numbers up to the minimum of x. `x,/` Flatten the cutted list, prepending x. We need to prepend x to get the shape right for the empty list. Instead of *converges* we could use *whiles* to avoid dealing with the empty list. This would save 3 bytes in the lambda, but add 4 on the outside: ``` (::){(,/x_!*|x)^x}\ ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs9KwstKs1tDRr4hX1Kqp0IyrqI3h4kpTMFQwUjBWMFWwUDA0BnNBHHMFSyDbVMHQQMHQVMHIAMGB6jADKjE0VDA0gpkAVgEUBQCiVxTD) [Answer] # [R](https://www.r-project.org/), ~~55~~ 50 bytes *Edit: -5 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).* ``` f=function(v)if(s<-setdiff(v:max(v),print(v)))f(s) ``` [Try it online!](https://tio.run/##jZLPjoIwEMbvPMUkXNpkTBzw35rFi49BOBhstQdxU7pkN8ZnZ6eV1WAUPUCHzjfz@/IF27Y6099V6cyxEo00WtSfo1q5rdFaNMvD5odv8cuaynEhJfdl6@zveuPKvdCiFISQIkwR5ggfUqKy9mhvO5U8nWUM2QryvCctEPIEYYIwQ1j4r67nS3/rz6l/FUXUI7KIxvzwmYyHiT2p3zUL8AXz@Zb9EFsgBhMTiZvEXeI2BX@X2VD1tIOu3nQ07OZCf8RhWRIym//PvAz9Tt9lPQlxd/BrOM@R6Tuc9Ek0fvXLYDp@WBDFMdRKgdsrCFOm2i2jBz9c@wc "R – Try It Online") Prints the inital list but not the empty one. Terminates with an error. In [R](https://www.r-project.org/)==4.1 replace `function` with `\` to achieve **43 bytes** (still longer than [@Dominic van Essen's answer](https://codegolf.stackexchange.com/a/248985/55372) working in [R](https://www.r-project.org/)>=4.1 after also [implementing this notation there](https://ato.pxeger.com/run?1=m72waMG-zJLUosSSzLLU-OLcxJyc1OKS-OT83IKc1NzUvBLbpaUlaboWN1XTbGM0ijSL1NI0Cooy80o0ilNLUjLT0jSKrHITK4AyOkWamppQxXp4jdRI1jDUMdIx1jHVsdAxNIbpWrAAQgMA)). This doesn't work in [R](https://www.r-project.org/)>=4.2.0 (and consequently in [ATO](https://ato.pxeger.com/run?1=jZJNTsMwEIUlljnFSNnY0oDqpD-hUthwA7YhiyrY1AtSZLsRCHEETsAmLFhwJDgNYydUCmrTLpyZeN7MN3ry-4dpv24uGmms3tSfW6fOs29U-S1r0OZWujutFGuWD6sn1nB8NLp2lHCuFbPcn67n5-zNmefrlavWTLGKCYQUYYawQLjkHKUxG5OrbV054jDJX155DPkVFMVAWiIUCcIUYY6Q-b--5lN_6-PMf8oyGhBJJCZ0KCaTceJA6mfNAzwjPt3SPoJWEAQWRBRUFFQVVBZhv643ZAPt6FYnbjS-TUffxyFZEjxb_PUcNf2fvvd6Guzu4TtzDiPTUzjpAWv86KPG9PwwIIpjsFKCW0sIXbq-X0Z7Hlz3Ktu2i78)), due to introduction of a strict check for argument length for `if`. ### Explanation outline 1. Compute sequence from min to max with `v:max(v)` (`:` takes first element of a vector and as input is sorted, this is the minimum). 2. Take set difference `setdiff` of this and input (we print it here and `print` conveniently returns its argument). 3. Assign this to `s`. 4. `if` takes the first element of a vector and checks if it's truthy (not `0` or `FALSE`) and errors for empty input. Essentially, check if `s` is nonempty. 5. Recurse. [Answer] # [Python 3](https://docs.python.org/3/), 56 bytes ``` f=lambda l:l and[l]+f(sorted({*range(l[0],l[-1])}-{*l})) ``` [Try it online!](https://tio.run/##VY3BCsIwEETv@Yo9pnULSYtKC37JkkMkjRbWpMRepPTbYyqCeFhmZ@bBzK/lHkOXs7@wfVydBR4YbHDE5uDlM6ZldHKtkw23UTIpg0yNNtXWrDVvVZV9TMAwBSBBGqFDOCKcEXqDgsqrVbmirfoLdlPwFuH0wXUxuv2l3ZfeWyPMAHOawiK95LL5Bg "Python 3 – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ≬₌gGṡ⊍İ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiazigoxnR+G5oeKKjcSwIiwiIiwiWzEsIDMsIDUsIDcsIDldIl0=) or [Try all the tests](https://vyxal.pythonanywhere.com/#WyJhIiwixpsiLCLiiazigoxnR+G5oeKKjcSwIiwiU25TJFwiYCUgPT4gJWAkJTtcXFxuaiIsIlsxLCAzLCA1LCA3LCA5XVxuWzUsIDEwLCAxNSwgMjBdXG5bNSwgMTAsIDE1XVxuWzEsIDIsIDYsIDcsIDExLCAxMl1cblsxLCAyLCAzXVxuWzUsIDYsIDddIl0=) Input list not included, empty list is. ## Explained ``` ≬₌gGṡ⊍İ ≬----- # Next three elements as a function: ₌gG # Get the smallest and largest item of the argument ṡ # Create an incluse range between those values ⊍ # and set xor with the original argument İ # Repeat that function until the result is no longer unique, collecting results ``` [Answer] # [J](http://jsoftware.com/), 18 bytes ``` (-.~{:-.&i.{.)^:a: ``` [Try it online!](https://tio.run/##Zcq9CsJAEATgfp9isPAM7K25xN8FQRSsxMI2JCCSYGxsLIRAXv3cK8ViGJhvnnEirsNO4cDIoRYvOF7PpzjzMg7qZdrLIFmjN40ZXQ6CX9jPdUxI7f3xQofAKBglY8nYMEJJ1H76t3NU/VFN1YKxYqwZWxtyi51CYZA@Vgmt6vgF "J – Try It Online") thejonymyster has allowed this output... since J only supports heterogeneous lists with boxing, and since 0 is disallowed in the input, I am displaying the output as a homogeneous matrix with 0 fill, so that the successive lists are simply each row, without the 0 fill: ``` 1 2 3 5 8 13 0 4 6 7 9 10 11 12 5 8 0 0 0 0 0 6 7 0 0 0 0 0 0 0 0 0 0 0 0 ``` Note that, if desired, we could [add boxing for 3 more bytes](https://tio.run/##Zcq9CsJAEATgfp9isMgZ2Ftzib@LiihYiYVtiCCSYGxsLIRAXv3clGIxDMw3zzgS12CjcGBkUIsXHC6nYxx76Tv1krTSSZrI9qo3jSmd94Jf2020H5Dq@@OFBuvAyBkFY8ZYMkJBVH/at3NU/lFF5ZQxZywYKxsyi51CbjB8rAa0quIX). * `(...)^:a:` Until a fixed point is reached, collecting results, do the following... * `-.~{:-.&i.{.` Remove `-.` the input from `0 1 ... <largest element - 1>` without `0 1 ...<smallest element - 1>` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~9~~ 8 bytes ``` #p=-rhQe ``` [Try it online!](https://tio.run/##K6gsyfj/X7nAVrcoIzD1//9oQx0FIx0FYx0FUx0FCx0FQ@NYAA "Pyth – Try It Online") ``` #p=(Q)-rhQe(QQ) // Implicitly initialize Q as the input # // Repeat until an error occurs: rhQeQ // Range from first to last element of Q... - Q // ...with elements of Q removed =Q // Set Q to the result p // Print ``` [Answer] # [Zsh](https://www.zsh.org/), 44 bytes ``` <<<$@ a=({$1..$@[$#]}) (($#))&&$0 ${a:|argv} ``` [Try it online!](https://tio.run/##qyrO@J@moanx38bGRsWBK9FWo1rFUE9PxSFaRTm2VpNLQ0NFWVNTTU3FQEGlOtGqJrEovaz2vyYXV5qCoYKRgimUNlYwVbBQMDT@DwA "Zsh – Try It Online") ``` <<<$@ # output arguments a=({$1..$@[$#]}) # all integers between first and last args (($#)) && # if there was at least one argument $0 ${a:|argv} # recurse with set difference between $a and the arguments ``` Using $argv is needed in the `${a:|b}` notation, `${a:|@}` does not work. [Answer] # JavaScript (ES10), 66 bytes The empty list is included. The input list is not. ``` f=a=>a+a&&[b=a.flatMap(p=g=v=>++p-v?[p,...g(v)]:(p=v,[])),...f(b)] ``` [Try it online!](https://tio.run/##fYxBDoIwEEX3nqIr0oahoRA1mhRP4AkaFgNSgmloI6TXr4NLgy4mk/nvz3tixKV/TWEtZv8YUrIadYM5ZpnpNErrcL1j4EGPOuomz0MRbyaAlHLkUbRXIhFMK8QWWd6JNvV@XrwbpPMjt9woYDWwI7AzsAsVD1@ciCppaFflP77DyF0BO33cig5V/SzV@@rtl0h6Aw "JavaScript (Node.js) – Try It Online") Or as **ES6** (also 66 bytes): ``` f=a=>a+a&&[a.map(p=g=v=>++p-v?g(v,b.push(p)):p=v,b=[])&&b,...f(b)] ``` [Try it online!](https://tio.run/##fYxBDoIwEEX3nqKrpg1DQyFqNBk8CGExICAGaSPa69fRpUEXP5OfN/9dKdDS3kf/SGd37mLskbCkhKSsyNzIK48DBiyTxKfhNKgAjfHP5aK81kePXLGqtZQNGGN61eg6tm5e3NSZyQ2qV5UFUYDYgtiDONRab744E5tx@ObZP77C2J2D2H3clovNfz4V6@r3lkl8AQ "JavaScript (Node.js) – Try It Online") [Answer] # BQN, 23 bytes ``` {𝕊¬∘∊⟜𝕩⊸/𝕩⊑⊸↓↕⌈´•Show𝕩} ``` [Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge/CdlYrCrOKImOKIiuKfnPCdlaniirgv8J2VqeKKkeKKuOKGk+KGleKMiMK04oCiU2hvd/Cdlal9CgpGIOKfqDEsIDIsIDMsIDUsIDgsIDEz4p+p) Terminates with error. ## Explanation Input is *x*. * `•Show𝕩` output *x* * `↕⌈´` exclusive range from 0 to max of *x* * `𝕩⊑⊸↓` drop (first element in *x*) elements * `¬∘∊⟜𝕩⊸/` filter elements not in *x* * `𝕊` recurse [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, ~~51~~ 50 bytes ``` [ [ 3 dupn . minmax [a,b] swap ∖ ] until-empty ] ``` Input list is included; empty list is omitted. [Try it online!](https://tio.run/##bZBBTsMwEEX3OcVnD1WnadICgi1iwwaxirow6bS1SJxgO6Klyp4TcEAuUuy4qhK1WTjj7/nve7wSua304e31@eXpDh@sFReoNVu7q7VUFqWwm5GxwkpjZW7CXgu1ZgPD1i@fDauczYi3VoueAFlhzYq1KOS3A1TqaG@UzKsl4z6K9hHctwchRoIZbtF6AVd4eHTy8GCPCaZIMe/qoPvKa/6fdGuL9ghNQGNQgsk4UE/Q1BnnDkkEmoBi0BSUgmagOShEBWtX9bouB4Q79wKSnv1S2DFgSCM3nm8OjW3/DYYHfvapy@io41PIOS0@3QxDWnw2SADgfJA@uY0OGTLnXja1wgilVKXYIhPX7wuYL1Hj7@cXCzTKyuKGy9rusHAWVTgxr8q6MgwW@ebwDw "Factor – Try It Online") * `[ ... ] until-empty` Call `[ ... ]` on the input repeatedly until it is empty. ``` ! { 1 3 5 7 9 } 3 ! { 1 3 5 7 9 } 3 dupn ! { 1 3 5 7 9 } { 1 3 5 7 9 } { 1 3 5 7 9 } . ! { 1 3 5 7 9 } { 1 3 5 7 9 } ((output to stdout)) minmax ! { 1 3 5 7 9 } 1 9 [a,b] ! { 1 3 5 7 9 } { 1 2 3 4 5 6 7 8 9 } swap ! { 1 2 3 4 5 6 7 8 9 } { 1 3 5 7 9 } ∖ ! { 2 4 6 8 } ((set difference)) ! ((and so forth...)) ``` [Answer] # Haskell, ~~65~~ 49 bytes *-10 bytes thanks to [@Lynn](https://codegolf.stackexchange.com/users/3852/lynn)* ``` g[]=[];g x=x:g[e|e<-[head x..last x],notElem e x] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` Wθ«≔⁻…⌊θ⌈θθθ⟦Iθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUGjUFOhmovTsbg4Mz1Pwzczr7RYIygxLz0VxM7MLc0FKtBR8E2sgLKBnEIwtubiDCjKzCvRiHZOLC4BysQChWr//4@ONtRRMNJRMNZRMNVRsNBRMDSOjf2vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Does not output the initial list. Would output the final list except that Charcoal has no output for an empty list. Explanation: ``` Wθ« ``` Repeat until the list is empty. ``` ≔⁻…⌊θ⌈θθθ ``` Subtract the list from the range of its lowest to highest elements. ``` ⟦Iθ ``` Output the new list with separation from the previous list. [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 39 bytes ``` 1{sa1.>{Jl_g_/vjr@j\\}q{}IE}C~J{}Fi+..+ ``` [Try it online!](https://tio.run/##fZDbCoJAEIbve4qhWzdzPIcoQRTkK6iIgUTijYrdLPbqNrseSoMudnd2/pnv351bW5d5U7V5X2lNufWDreftkjrrkTcZqgEPy/Se7p9FfSziuKt4dz13p1fIu8tDUVWl7yNkYDCwGDgMDgn4AUSrHINIZ2AysBm44jZqIhRZcVpiS5JNRAJqtOjUtRG3zFGhLckuwSlLZkh8JCoSDklEUpFklOZDr4wWtT@Wa7v/VgN6gpCkyx86U91nFmthGIEppzCS528tecYCYny9WNbO7x07hfoG "Burlesque – Try It Online") The only bit which is required to compute this is ``` 1{Jl_g_/vjr@j\\}C~ ``` Unfortunately, this crashes on reaching a 0/1 element block because it tries to pull head/tail from an empty list. ``` 1 # Number of elements Continue forever keeps from the top of the stack { sa1.> # Length of block at least 2 elements { J # Duplicate l_g_/v # Get head and tail of list jr@ # Range head..tail j\\ # List difference with original } q{}IE # If list too short return empty list }C~ # Continue forever J{}Fi # Find the first occurrence of empty list +..+ # Take that many (including an empty element) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Δ=WsàŸyK ``` Outputs the intermediate lists separately to STDOUT; includes both the input-list and empty-list. Stops with an error. [Try it online](https://tio.run/##yy9OTMpM/f//3BTb8OLDC47uqPT@/z/aUEfBSEfBWEfBVEfBQkfB0DgWAA) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GdWibvZJnXkFpiZWCkr0Ol5J/aQmQUwzk6fw/N8U2vPjwgqM7Kr3/g9RylWdk5qQqFKUmpihk5nGl5HMpKOjnF5ToQ4yEUmi22CiogNXmpf6PNtQx1jHVMdexjOWKNtUxNNAxNNUxMkBwgCxDHSMdM6ASQ0MdQyMo3xisAigKpI10TKAssAzQOAsdQ6ACAA). **Explanation:** ``` Δ # Loop until the result no longer changes # (although it'll basically loop until the error in this case) = # Print the current list with trailing newline (without popping) # (which will use the implicit input-list in the first iteration) W # Push its minimum (without popping) s # Swap so the list is at the top again à # Pop and push its maximum Ÿ # Pop both, and push a list in the range [min,max] # (the min/max of an empty list are ""; so here it'll error) y # Push the current list again K # Remove all those values from the [min,max]-ranged list ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 34 bytes ``` f=->a{a[0]&&f[p [*a[0]..a[-1]]-a]} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y6xOjHaIFZNLS26QCFaC8TW00uM1jWMjdVNjK39nxYdbahjrGOqY65jGRvLVVBaUswFFDPVMTTQMTTVMTJAETTTMY@N/Q8A "Ruby – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 80 bytes ``` $ ;¶$%` \d+ $* %(M!&`^.+;|(1+)$(?<!^\1.*)(?<!\b\1\b.*) O` )`¶ , 1+ $.& }`;¶$ ; ``` [Try it online!](https://tio.run/##K0otycxL/P9fhcv60DYV1QSumBRtLhUtLlUNX0W1hDg9besaDUNtTRUNexvFuBhDPS1NECsmKcYwJgnI4fJP4NJMOLSNS4fLEKhPT42rNgFkEBeXNdf//4Y6RjrGOqY6FjqGxgA "Retina 0.8.2 – Try It Online") Explanation: ``` $ ;¶$%` ``` Duplicate the last line and mark the previous line as not to be altered. ``` \d+ $* ``` Convert to unary. ``` %(` )` ``` Run the next three commands separately for each line, so that they don't accidentally clobber one another. ``` M!&`^.+;| ``` Just output the previous lines in full, so nothing happens... ``` (1+)$ ``` ... but for the last line, output overlapping substrings of the final run of `1`s... ``` (?<!^\1.*) ``` ... that are greater than the first run of `1`s... ``` (?<!\b\1\b.*) ``` ... and do not match any of the runs of `1`s. ``` O` ``` Sort the lines into ascending order. ``` ¶ , ``` Join them with commas. ``` 1+ $.& ``` Convert to decimal. ``` ;¶$ ``` If the were no matching runs of `1`s, then just undo everything, so that the loop stops repeating. ``` }` ``` Repeat the above commands until the buffer stops changing. ``` ; ``` Remove the markers on the previous lines. [Answer] # Rust, 138 bytes ``` let f=|l:Vec<u8>|std::iter::successors(Some(l),|l|if l.len()>0{Some((l[0]..l[l.len()-1]).filter(|i|!l.contains(i)).collect())}else{None}); ``` Returns a generator. Goal was to get the longest answer possible, right? [try it yourself](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=a36abd216eec52f39cdb66a5c361bad1) [Answer] # [GeoGebra](https://www.geogebra.org/calculator), 93 bytes ``` l={ InputBox(l a=IterationList(Remove(Min(L)...Max(L),L),L,{l},Length(l Take(a,1,IndexOf({},a ``` Input as comma separated numbers in the input box. Output is the list `l1`. [Try It On GeoGebra!](https://www.geogebra.org/calculator/dddran77) [Try It On GeoGebra! (with example test case)](https://www.geogebra.org/calculator/nmqfbgtd) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 55 bytes ``` NestWhileList[Complement[Range@@MinMax@#,#]&,#,#!={}&]& ``` [Try it online!](https://tio.run/##VYo9C8IwEIb/ykkg04lNi4pDJeBqRVwcSoYgaRtootgMQshvj1cRxOHeez8ep8NgnA72pnNX55OZwnWwoznaKbSHu3uMxhkf2ov2vZGysb7RL8mQKY6kizomrng@Py1BbLnvWqYUh5WEGAVChbBG2CLsEkIkKwo6@mXxV8yB8BJh88EFBVH@2upLz2tK@Q0 "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 50 bytes ``` f=lambda K:[*K]and[K]+f({*range(min(K),max(K))}-K) ``` [Try it online!](https://tio.run/##VYrNCgIhFIX3PsVd6nSDUalooCfwEcSFMVmC4wwyi0J8dnMiiBaH8/ctr/UxR1mruwQ7XUcLatCdMjaOWpmdo7lLNt5vdPKRKoaTfTZjZa9YdXOCAD6CJpkjSIQDwgnhXJDkFnnf1Fz0f8NWGi4Qjh@ct8LFb5VfensLMQMsyceVOhoYq28 "Python 3 – Try It Online") Takes input as a set rather than a list so I can use the more efficient set difference operator. Output will not be sorted. Basic logic to build a list efficiently copied from @m90 ]
[Question] [ I'd love to take a number and know how many syllables are in it, when spoken in English. Let's limit this to positive integers which are less than one thousand. I'm British, so we're going to follow the hundreds column with an 'and' when there are any non-zero digits after it. # The Challenge * Write some code which will accept a positive integer lower than 1000 and output the number of syllables in the words which represent that number in British English. * It DOES NOT need to generate the words to represent the numbers, only the number of syllables they contain. * It's code golf, attempt to achieve this in the fewest bytes. * Use any language you like. * The standard loopholes are forbidden. # Test Cases ``` | N | In words | Syllables | | 1 | one | 1 | | 2 | two | 1 | | 3 | three | 1 | | 4 | four | 1 | | 5 | five | 1 | | 6 | six | 1 | | 7 | sev-en | 2 | | 8 | eight | 1 | | 9 | nine | 1 | | 10 | ten | 1 | | 11 | el-ev-en | 3 | | 12 | twelve | 1 | | 13 | thir-teen | 2 | | 14 | four-teen | 2 | | 17 | se-ven-teen | 3 | | 20 | twen-ty | 2 | | 21 | twen-ty one | 3 | | 42 | four-ty two | 3 | | 73 | sev-en-ty three | 4 | | 77 | sev-en-ty sev-en | 5 | | 100 | one hund-red | 3 | | 110 | one hund-red and ten | 5 | | 111 | one hund-red and el-ev-en | 7 | | 555 | five hund-red and fif-ty five | 7 | | 700 | sev-en hund-red | 4 | | 770 | sev-en hund-red and sev-en-ty | 8 | | 777 | sev-en hund-red and sev-en-ty sev-en | 10 | | 999 | nine hund-red and nine-ty nine | 7 | ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~84~~ ~~83~~ ~~74~~ 67 bytes ``` lambda n:4*(n>99)+2-n%~9/9-0x55561aaaab/4**(n%100)%4+`n`.count('7') ``` *Thanks to @xnor for golfing off ~~9~~ 16 bytes!* [Try it online!](https://tio.run/##HY5BDoJADEXXeoq/mcBAEWYcGIdET@IC1BBNtBACiW68OlaatIv33qLDZ7r3bJcOR5yXZ/u63Fpw7ZKYTyHo1GasviEPWfEuy7Iyrcwld4l4ZYpCK5c23Oyu/cxTHPlIL10/gvFgGIIl7AmOUBIqgiccCIFgClnxRgIjhZHEiLXCrXAn3Av3/t@u8XpEyRfC/8z79UgSQqi3m2F88IRI7WdkJyg7R1CImdDFrPXyAw "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), 79 bytes ``` lambda n:4*(n>99)+([-1]+10*[1]+[3,1]+7*[2]+8*([2]+9*[3]))[n%100]+`n`.count('7') ``` Straightforward, but longer. [Try it online!](https://tio.run/##HYzBboNADETP6VfMBbG7OBFeoM5Gan5kg5SkFWqk1kQRHPr11HDwjPTmyc@/6XvUuAz4wGX5uf3ev27QUxucnlPylct77iuuQ7bKDVlKyLGvjsGtlUJueu@zFlzXfXXV6@FznHVypZR@GcYXFA8FEyKhIbSEjvBOEMKRkAhc29nOJrAZbArbGo1H461xMS6yupu8hU1dZ79kZSJbmJJSOr3tnq@HTiiLZsb@jCLOJQo4JQxOvV/@AQ "Python 2 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~53~~ 51 bytes ``` $_=4*/.../+2*/[^0].$/+!/0$/+y/7//-/1[^1]$/-/00|12$/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tZES19PT09f20hLPzrOIFZPRV9bUd8ASFbqm@vr6@obRscZxqoAGQYGNYZGKvr//xsaGv3LLyjJzM8r/q/ra6pnYGjwX7fADQA "Perl 5 – Try It Online") **How** ``` -p commandline flag reads input into $_ $_=4*/.../ # Hundreds place has minimum of 4 sylables (__ HUN-DRED AND), # match fails on number <100, and would add 0 here +2*/[^0].$/ # Tens place has two syllables if not 0 (__-TY or __TEEN), # match fails on numbers <10, and would add 0 +!/0$/ # Ones place has one syllable if not 0 (__) # -- Now adjust for special cases -- +y/7// # add a syllable for every 7 present -/1[^1]$/ # remove a syllable for 10-19, except 11 -/00|12$/ # remove the syllable for AND if it's an even hundred # OR remove another syllable for 12 -p commandline flag outputs contents of $_ ``` [Answer] # JavaScript (ES6), 89 bytes ``` n=>(s='01111112111312222322',n>99&&+s[n/100|0]+3-!(n%=100))+~~(s[n]||+s[n/10|0]-~s[n%10]) ``` [Try it online!](https://tio.run/##ddFPS8MwFADw@z7F87Aloe3Mn9YuQipeBFHw4FF6KFsnykhHWzyVffX6UrqaHAyE5Jf38vIg39VP1e3br3Of2OZQj0czWlPQzhAupiFxKiFxKClJbAutN5uo@7C3gvOBl5FKbqhdGxRj0eVCMVQOw5yBCckFt2vBSzb2ddeDAWpjaBmYAvaN7ZpTvT01n5RaiIAQtj1Xh/e@anuqmDvBPIIrPVLL/sn4ixsDLTwAoW8vjMA9bp4en18ZYWy1cq9TABHjZFfJQCpQGigLdBcoR8lFuyCmfQkeyPWiFgW9COXXFKkvyQMFVVLpK3dV0kWuz2wWfpiXKabOltjUWT4ryzJP@XTvWjPPnXaL8AXBZ2mtp3vjLw "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~112~~ 108 bytes ``` f=lambda n:n>99and f(n/100)+3+f(n%100)-(n%100<1)or n>19and f(n/10)-~f(n%10)or int("01111112111312222322"[n]) ``` [Try it online!](https://tio.run/##ZdHRCoIwFAbg@55iCEGjop0z11pULxJdGCIFNUW86aZXX9OJrp2BOj7/7exo8@ketUXnqvOreN/LgtmjvRhT2JJVK7sDIfharv102U@34XkCXrfMXiDK8e03pPpXT9utMgHDQH9JQD8kYna1N@6a1gf8OsaAs42/L2ZBIpJITkQR2RPRg2AkB5Ixqfh@UglnlpGQM4NMa0FORKf7oEgzSGrlmIoOtfJIws5qkv7X/a@Csa8oM/alJ1FKJaLHfeZaWgc5RDJUBzGJMeGravcD "Python 2 – Try It Online") -4 bytes, thanks to Shaggy [Answer] # JavaScript, ~~86~~ 84 bytes A tweaked port of [TFeld's Python solution](https://codegolf.stackexchange.com/a/177588/58974). ``` f=n=>n>99?f(n/100)+3+f(n%=100)-!n:n>19?f(n/10)-~f(n%10):+"01111112111312222322"[n|0] ``` [Try it online](https://tio.run/##VU/RSsQwEHz3K9YDoaHbM5u05lJoffIHfD0KV3qpKL202Co@iL9eNzlOvLA7DDNDMnlrP9u5e3@dlsyPR7eufeWr2tfWPvaJvycpRapTpndV4NmtL31NF1NkP8FiUqYbSfEoXk2Kj1Zqs/ffslm70c/j4LbD@JIcnt38MSxzCQfcE4JC0Ag5QoHwgGAQdggWgSQv@8QB4gRxhNhVrCvWc9YN68aEbAxHYKso@C4TNGMicMRa22xP7ZT0Qtxc9Xn6mly3uGPJfSA8eD3qH9cX5Vz6jH/tdUQTJ4/fCI0MNGL9BQ) 2 bytes saved thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) [Answer] # Wolfram Language ~~101~~ 115 Bytes ``` s=StringSplit;Length[Join@@(WordData[#,"Hyphenation"]&/@Join@@s/@ s[IntegerName@#,"-"])]+Boole[#>100&&#~Mod~100!=0]& ``` ## Explanation (substituting `StringSplit` for `s`) ``` Length[Join@@(WordData[#,"Hyphenation"]&/@Join@@ StringSplit/@ StringSplit[IntegerName@#,"-"])]+Boole[#>100&&#~Mod~100!=0]& ``` `IntegerName` renders the number in American English (i.e. without "and" included in numbers greater than 100.) E.g. `777-> "seven hundred seventy-seven`. `StringSplit[IntegerName@#,"-"]` removes any hyphens in the rendering. `StringSplit/@` splits the rendering into words. `Join@@` leaves a simple list of words, without embedded list (in the case that a hyphen appeared). `WordData[#,"Hyphenation"]` breaks up a single word into its syllables. `Join@@` leaves a simple list of syllables in all of the words. `Length` counts the syllables `+Boole[#>100&&#~Mod~100!=0]` adds `1` to the syllable count for those numbers greater than 100 (because of the additional "and" employed in the British English rendering), excluding integral multiples of 100. [Answer] # Java 11, ~~105~~ 102 bytes ``` n->(""+"".repeat(8)).charAt(n%100)+(n+"").split("7",9).length-(n>99?2:6) ``` Contains loads of unprintable characters. -3 bytes thanks *@OlivierGrégoire*. [Try it online.](https://tio.run/##lVHBagIxEL0UFb9iCBQSdlzM6hp3rZZ@QL0IvaiHdI0au0bZjRYpfvs2WdvSQy99MBNmeMy8ednJs@zsVm9VlsuyhGepzUcbQBurirXMFEx9WTcgoz4bNnKda9ul0kqrM5iCgTFUpjOh5K7xg1ajeQMJSLP1DRIW6qikpUPGwmwriydLzT3vdllATUAIC8tjri0lgmDCwlyZjd12qJkkyWOUDlg18puPp9fcbf4ScD7oFeyddDqzhTab@RIku@leH4patYYUjHr3d8yXHxwj7GEfYxygwCEmyLvIOfIIeQ95H7nAqIsRx36EoodCOIJn@OAYxzEKVwvhQ2CSJFdWrwOYXUqr9uHhZMOj02JzQ3VA0oUlgQmdg4zVB/xJJAvzogq9voDMc5hzP3gJVpXOe1mqMiW197@uGvMR6Aeueu4Jgv9o8F94rT4B) **Explanation:** ``` n-> // Method with integer as both parameter and return-type ("" // Push string with ASCII-value digits 46666666666867777777 +"".repeat(8)) // Appended with 8 times a string with ASCII-value digits 7888888888 .charAt(n%100) // Take the (input modulo-100)'th character of this string (as integer) +(n+"").split("7",9).length // Count the amount of 7s in the input + 1 -(n>99? // And if the input is larger than 99: 2 // Subtract 2 (-1 for the 7s+1 count; -5 to map the ASCII-digits to: // 4 → -1; 6 → 1; 7 → 2; 8 → 3; // and +4 for the inputs above 99) : // Else: 6) // Subtract 6 (-1 for the 7s+1 count and -5 to map the ASCII-digits to: // 4 → -1; 6 → 1; 7 → 2; 8 → 3) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ ~~25~~ 23 bytes ``` 9ḊŻ;2+⁵Żċ%ȷ2$ạDṠḄƊ+Dċ7Ɗ ``` [Try it online!](https://tio.run/##y0rNyan8/9/y4Y6uo7utjbQfNW49uvtIt@qJ7UYqD3ctdHm4c8HDHS3HurRdjnSbH@v6b2iiEKRgrWBormNkoGNkqGNipGNurGNurmNoYKBjaAjChjqmpqY65kC@uTkIm@tYWloqHNqqcHSPwuH2R01rFNz/AwA "Jelly – Try It Online") ### How it works ``` 9ḊŻ;2+⁵Żċ%ȷ2$ạDṠḄƊ+Dċ7Ɗ Main link. Argument: n (integer in [1, ..., 999]) 9 Set the return value to 9. Ḋ Dequeue; yield [2, 3, 4, 5, 6, 7, 8, 9]. Ż Zero; yield [0, 2, 3, 4, 5, 6, 7, 8, 9]. ;2 Concat 2, yield [0, 2, 3, 4, 5, 6, 7, 8, 9, 2]. +⁵ Add 10; yield [10, 12, 13, 14, 15, 16, 17, 18, 19, 12]. Ż Zero; yield [0, 10, 12, 13, 14, 15, 16, 17, 18, 19, 12]. %ȷ2$ Yield n % 1e2. ċ Count the occurrences of the modulus in the array. Ɗ Combine the three links to the left into a monadic chain. D Decimal; convert n to its array of digits in base 10. Ṡ Take the sign of each decimal digit (0 or 1). Ḅ Convert the array of signs from base 2 to integer. ạ Compute the abs. difference of the results to both sides. Ɗ Combine the three links to the left into a monadic chain. D Decimal; convert n to its array of digits in base 10. ċ7 Count the number of 7's. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~34~~ 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` т%U7¢I€Ā`Iт@3*X_(X20@X12Q(X11QO ``` [Try it online](https://tio.run/##yy9OTMpM/f//YpNqqPmhRZ6PmtYcaUjwvNjkYKwVEa8RYWTgEGFoFKgRYWgY6P//v7mhIQA) or [verify all `[1,999]` test cases](https://tio.run/##AUUAuv9vc2FiaWX/4oKER07Cp8OQVlk/IiDihpIgIj//0YIlVTfColnigqzEgGBZ0YJAMypYXyhYMjBAWDEyUShYMTFRT/8s/zE). **Explanation:** With all checks mentioned it will result in 1 for truthy and 0 for falsey. ``` т% # Take modulo-100 of the (implicit) input # i.e. 710 → 10 U # Pop and store it in variable `X` 7¢ # Count the amount of 7s in the (implicit) input # i.e. 710 → 1 I€Ā # Trutify each digit in the input (0 if 0; 1 otherwise) ` # And push all of the mapped values to the stack # i.e. 710 → [1,1,0] Iт@ # Check if the input is larger than or equal to 100 # i.e. 710 → 1 (truthy) 3* # Multiply that result by 3 (for 'hund-red and') # i.e. 1 → 3 X_ # Check if variable `X` is 0 # i.e. 10 → 0 (falsey) ( # And negate that (to remove 'and' when #00) # i.e. 0 → 0 X20@ # Check if variable `X` is larger than or equal to 20 (for '-ty') # i.e. 10 → 0 (falsey) X12Q # Check if variable `X` is exactly 12 # i.e. 10 → 0 (falsey) ( # And negate that (to remove 'teen') # i.e. 0 → 0 X11Q # Check if variable `X` is exactly 11 (for 'el-ev-en' minus 'one one') # i.e. 10 → 0 (falsey) O # Sum everything on the stack (and output implicitly) # i.e. [1,1,1,0,3,0,0,0,0] → 6 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~39~~ 31 bytes ``` I⁻⁺↨E謬Iι²№θ7I§⁺”)∨∧⌈a¡↶”×0⁸⁰N ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczr7RYIyAHSDglFqdq@CYWaBTqKPjll2iAMFhNpiYQ6CgYAbFzfilQJ1CBkrkSSAws71jimZeSWgExRcnQAAYMDYwMIUBJRyEkMzcVKGsAZFoYgLR65hWUlviV5ialFmlogoH1///mhkb/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` I⁻⁺ ``` Calculate adjustments to the number of syllables and output the result as a string. ``` ↨E謬Iι² ``` Start by changing each non-zero digit to 1 and then decoding as base 2. This gives the correct answer for most inputs. ``` №θ7 ``` Add 1 for each `7`. ``` I§⁺”)∨∧⌈a¡↶”×0⁸⁰N ``` Take the literal string `10000000001021111111` and append 80 zeros, then cyclically index by the input, and subtract that digit. [Answer] # [PHP](https://php.net/), ~~190~~ ~~158~~ ~~145~~ ~~141~~ 137 bytes ``` <?for($j=$p=0;$p<strlen($i=$argv[1]);)$j+=str_split($i)[$p++]>0;echo$j+substr_count($i,7)+3*($i>99)-!($i%=100)+($i>19)-($i==12)+($i==11); ``` [Try it online!](https://tio.run/##HczRCoMgGIbhW9nAQc4Fuh1ImO0SdgER0VrLIvRHbZc/97uzl@@BDwykVN/fzhdk1QQ0VwTqEP022YIsmgx@/rSio4qSlWmEPsC2RDTaEmCsa7iaRuNQw/7MPrrdZr9Iym5njKaqaHnEOGnBOWV5Ejjlfy2u/wFDUJVSklJ@HcTF2ZDK1yEY52PvYLJ9HGb9sD8 "PHP – Try It Online") A port of Kevin Cruijssen's solution (unfortunately it doesn't have the same brevity in PHP :) ) -~~32~~ 45 thanks to Shaggy! -3 thanks to Kevin Crujissen! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 24 bytes Port of [Dennis' jelly answer](https://codegolf.stackexchange.com/a/177592/47066) ``` 8L>þšT+¾šsт%¢sSĀJCαs7¢+ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fwsfuSNuhfUcXhmiDyOKLTaqHFhUHH2nwcj63sdj80CLt//@NzAE "05AB1E – Try It Online") or as a [Test suite](https://tio.run/##yy9OTMpM/V9TVmmvpKBrp6BkX3lo@eEJ/y187I60Hdp3dGGINogsvtikemhRcfCRBi/ncxuLzQ8t0v6v89@Qy4jLmMuEy5TLjMucy4LLksvQgMvQkMvQiMvQmMvQhMvQnMvIgMvIkMvEiMvcmMvcHKgApAKEDblMTU25zIF8c3MQNueytLQEAA) **Explanation** ``` 8L> # push range [2 ... 9] Ć # enclose, append head ¾š # prepend 0 T+ # add 10 to each ¾š # prepend 0 sт%¢ # count occurrences of input % 100 in this list sS # push input split into a list of digits Ā # truthify, check each if greater than 0 JC # convert from base-2 to base-10 α # absolute difference s7¢+ # add the amount of 7's in the input ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` €ĀJCI7¢•Ž¢Γ}Þ±6u•¾80׫Iè(O ``` Port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/177617/52210), so make sure to upvote him as well if you like this answer! [Try it online](https://tio.run/##ATgAx/9vc2FiaWX//@KCrMSASkNJN8Ki4oCixb3Cos6TfcOewrE2deKAosK@ODDDl8KrScOoKE///zcxMQ) or [verify all test cases](https://tio.run/##yy9OTMpM/f@oqcXd79Byl7BIeyWFR22TFJTsgWJrjjR4OUeaH1r0qGHR0b2HFp2bXHt43qGNZqVA/qF9FgaHpx9aHXl4hYb/f53/hgA). Compressed integer `•Ž¢Γ}Þ±6u•` can alternatively be [`•8JA•b2TÌǝ`](https://tio.run/##yy9OTMpM/f@oqcXd79Byl7BIeyWFR22TFJTsgWJrjjR4OUeaH1r0qGGRhZcjkEwyCjncc3zuoX0WBoenH1odeXiFhv9/nf@GAA) for the same byte-count. **Explanation:** ``` €Ā # Trutify every digit in the (implicit) input # (0 remains 0; everything else becomes 1) J # Join it together to a single string C # Convert from binary to integer I7¢ # Count the amount of 7s in the input •Ž¢Γ}Þ±6u• # Push compressed integer 10000000001021111111 ¾80׫ # Append 80 "0"s Iè # Index the integer (with automatic wraparound) into it ( # Negate the result O # Sum all values on the stack (and output implicitly) ``` [See this 05AB1E answer of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•Ž¢Γ}Þ±6u•` is `10000000001021111111`. ]
[Question] [ A skyline is an array of positive integers where each integer represents how tall a building is. For example, if we had the array `[1,3,4,2,5,3,3]` this would be the skyline in ascii art: ``` # # # ## ### ###### ####### ``` Your task is to find the area of the largest rectangle in the skyline. In this case, the largest rectangle has area 12. Here is the rectangle, highlighted: ``` # # # ## ### RRRRRR #RRRRRR ``` You can assume that the input contains at least one building (the length of the array is >0). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), you know the drill. Inspired by [this](https://puzzling.stackexchange.com/questions/114797/minimum-rectangle-inside-of-city-skyline/114851) Puzzling-SE post. # Test cases ``` [1] -> 1 [2, 2] -> 4 [3, 2, 1] -> 4 [1, 2, 3] -> 4 [1, 5, 1, 5] -> 5 [1, 4, 1, 4, 1] -> 5 [1, 4, 5, 4, 1] -> 12 [1, 5, 4, 5, 1] -> 12 [1, 2, 3, 5, 1, 3] -> 6 [1, 3, 3, 1, 4, 5, 2] -> 8 [1, 3, 3, 1, 1, 1, 1] -> 7 ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 50 bytes ``` @(a)max(([c,v]=runlength([(a<=a').*a;0*a](:))).*v) ``` [Try it online!](https://tio.run/##DcdBCoAgEADAr3RrVxaprEsl9A/xsIjWoQzCpN@bp2Fulzj7EhotpSwbMF78ARhH2ernjaePezrAAK@aW5SCl06whRmxJmMJYHpSNNJAU1VZLD8 "Octave – Try It Online") Based on my PARI/GP answer, but more interesting. This worth writing a Jonah-style explanation. ### how Takes `a = [1,3,4,2,5,3,3]` as an example. * `a<=a'` creates a matrix where the entry at `(i,j)` is `a[j]<=a[i]`: ``` 1 0 0 0 0 0 0 1 1 0 1 0 1 1 1 1 1 1 0 1 1 1 0 0 1 0 0 0 1 1 1 1 1 1 1 1 1 0 1 0 1 1 1 1 0 1 0 1 1 ``` * `.*a` multiplies the `i`-th column of the matrix with `a[i]`: ``` 1 0 0 0 0 0 0 1 3 0 2 0 3 3 1 3 4 2 0 3 3 1 0 0 2 0 0 0 1 3 4 2 5 3 3 1 3 0 2 0 3 3 1 3 0 2 0 3 3 ``` * `[...;0*a]` appends a row of zeros to the matrix, so that the columns are separated when taking run length encoding: ``` 1 0 0 0 0 0 0 1 3 0 2 0 3 3 1 3 4 2 0 3 3 1 0 0 2 0 0 0 1 3 4 2 5 3 3 1 3 0 2 0 3 3 1 3 0 2 0 3 3 0 0 0 0 0 0 0 ``` * `...(:)` concatenates the matrix into a column vector (the actual output is the transpose of the following row vector): ``` 1 1 1 1 1 1 1 0 0 3 3 0 3 3 3 0 0 0 4 0 4 0 0 0 0 2 2 2 2 2 2 0 0 0 0 0 5 0 0 0 0 3 3 0 3 3 3 0 0 3 3 0 3 3 3 0 ``` * `[c,v]=runlength` gives the run length encoding, where each non-zero run corresponds to a rectangle in the skyline: ``` c = 7 2 2 1 3 3 1 1 1 4 6 5 1 4 2 1 3 2 2 1 3 1 v = 1 0 3 0 3 0 4 0 4 0 2 0 5 0 3 0 3 0 3 0 3 0 ``` * `([c,v]=runlength(...)).*v` multiplies `c` and `v` element by element, which gives the "area" of each run: ``` 7 0 6 0 9 0 4 0 4 0 12 0 5 0 6 0 9 0 6 0 9 0 ``` * Finally, `max` finds the maximum values of the result: ``` 12 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ẆṂ×LƊ€Ṁ ``` [Try it online!](https://tio.run/##y0rNyan8///hrraHO5sOT/c51vWoac3DnQ3/D7drRv7/H20YqxNtpKNgBKSMgZSOAkjAEMwyhrBMgWJAEsIxAXNM4MpMwPIIvilMCMkYmBFQ84zBCK7XCE0UimIB "Jelly – Try It Online") ``` Ẇ Ɗ€ For each contiguous sublist of the input, Ṃ× multiply its smallest element by L its length. Ṁ Return the largest product. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes -5 bytes thanks to @att. ``` Max[Tr[Min@#+0#]&/@Subsequences@#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@983sSI6pCjaNzPPQVnbQDlWTd8huDSpOLWwNDUvObXYASjyP6AoM68kWllB104hLVo5NlZBTUHfQaG62rBWR6HaSEfBCEQbA2kdBbCQIZhpDGWaAkWBJJRnAuaZIFSagFUgCZjCxJDNghkDM9QYjODajdCFoai29j8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 56 bytes basically by AnttiP ``` f=lambda x:x>[]and max(min(x)*len(x),f(x[1:]),f(x[:-1])) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRocKqwi46NjEvRSE3sUIjNzNPo0JTKycVROmkaVREG1rFQhhWuoaxmpr/C4oy80o00jSiDXUUTHUUTMAkWAYA "Python 3 – Try It Online") # [Python 3](https://docs.python.org/3/), 72 bytes ``` lambda x:max(min(x[i:j])*(j-i)for j in range(len(x)+1)for i in range(j)) ``` [Try it online!](https://tio.run/##Rck9DoAgDEDhq3Rs/RmIuph4EnXACFoi1RAHPD0SF5c3fO967v2UJtlhSof2y6oh9l5H9CwYR@7dTAW6msmeARywQNCyGTxM/lSqz/l3R5SuwHKjxVFV0FXQflVzPi8 "Python 3 – Try It Online") # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~86~~ 85 bytes ``` lambda x:(R:=range(0,len(x)+1))and max(min(x[i:j])*(j-i)for i in R for j in R if i<j) ``` [Try it online!](https://tio.run/##JchBCsIwEEDRq8xypkZoUEGCvUS3tYuRNjqhmYbQRTx9rLr5PH56b69VT9eUq@/udeH4mBiKw951mfU5Y2uWWbHQwRKxThC5YJT9DOLCSA2Go5BfMwiIQg9fhj/Fg9wC1ZRFN/Q4WAMXA@df7UhUPw "Python 3.8 (pre-release) – Try It Online") Avoid [something](https://tio.run/##K6gsycjPM7YoKPr/P9E2OlMhLb9IIVMhM08jycq2KDEvPVXDUFMz9v9/AA) by pxeger [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ŒεWsg*}à ``` Port of [*@UnrelatedString*'s Jelly answer](https://codegolf.stackexchange.com/a/242802/52210), so make sure to upvote him/her as well! [Try it online](https://tio.run/##yy9OTMpM/f//6KRzW8OL07VqDy/4/z/aUMdYx0THSMcUSBvHAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/o5PObQ0vTteqPbzgv87/6GjDWB2FaCMdIxBlrGOkA@YbAhnGEIapDhBDmCY6YAzjmCI4pmAuQitYF9QAYyCEKDdCFgBDmIAJUJMpSCI2FgA). **Explanation:** ``` Œ # Get all sublists of the (implicit) input-list ε # Map each sublist to: W # Push its minimum (without popping the sublist) s # Swap so the sublist is at the top again g # Pop and push its length * # Multiply it by the minimum }à # After the map: pop and push the maximum # (after which it is output implicitly as result) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` ÞSƛgnL*;G ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnlPGm2duTCo7RyIsIiIsIlsxLCAzLCAzLCAxLCA0LCA1LCAyXSJd) Port of Unrelated String's Jelly answer. ``` ÞSƛ ; # For each contiguous sublist g * # Multiply the smallest element nL # The length. G # Get the largest product. ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 18 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` {⌈´(+´≠⥊⌊´)¨∾↓¨↑𝕩} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge+KMiMK0KCvCtOKJoOKliuKMisK0KcKo4oi+4oaTwqjihpHwnZWpfQoKPuKLiOKfnEbiiJjigKJKc8KoIOKfqAoiWzFdIgoiWzIsIDJdIgoiWzMsIDIsIDFdIgoiWzEsIDIsIDNdIgoiWzEsIDUsIDEsIDVdIgoiWzEsIDQsIDEsIDQsIDFdIgoiWzEsIDQsIDUsIDQsIDFdIgoiWzEsIDUsIDQsIDUsIDFdIgoiWzEsIDIsIDMsIDUsIDEsIDNdIgoiWzEsIDMsIDMsIDEsIDQsIDUsIDJdIgoiWzEsIDMsIDMsIDEsIDEsIDEsIDFdIgrin6k=) `↑𝕩` Prefixes of the input (includes the empty prefix) `↓¨` Suffixes of each prefix `∾` Flatten into a list of sublists `( )¨` For each sublist: `≠⥊⌊´` Reshape the minimum to the length of the sublist `+´` Sum the resulting list `⌈´` Get the maximum result Instead of `+´≠⥊⌊´` other answers use `≠×⌊´`, but that results in `0×∞ = NaN` for empty sublists, which ends up as the result of `⌈´`. [Answer] # [R](https://www.r-project.org/), 63 bytes ``` function(l,r=rle(c(t(cbind(outer(l,l,`<=`)*l,0)))))max(r$l*r$v) ``` [Try it online!](https://tio.run/##ZY/fCsIgFIfvewqhXegwyH/VRfYsK5swMAfiorc3Na2tyUHw@zy/oy5oGfRklR9GCw120pkeKuihug32DsfJ9y5yg7uz7FBr8B6l9bi@oGtM65onCjo2EIS2YHcBZJNOFANaAM@ARYABWTCSGftnIt6Le8GiYp4x/4XMjVgYQmdZH7tWaXQdVt9wqJLl@mbXv5xWvlTxx/AG "R – Try It Online") Port of [alephalpha's solution](https://codegolf.stackexchange.com/a/242812/55372). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes ``` sᶠ⟨⌋×l⟩ᵐ⌉ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv/jhtgWP5q941NN9eHrOo/krgWKPejr//4@ONozViTbSUTACUsZASkcBJGAIZhlDWKZAMSAJ4ZiAOSZwZSZgeQTfFCaEZAzMCKh5xmAE12uEJgpFsbEA "Brachylog – Try It Online") ``` sᶠ ᵐ For each contiguous sublist of the input, ⟨⌋× ⟩ multiply its smallest element by l its length. ⌉ Return the largest product. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~17~~ ~~15~~ 14 bytes ``` &<~G!*"@Y'*vX> ``` [Try it out](https://matl.suever.net/?code=%26%3C%7EG%21%2a%22%40Y%27%2avX%3E&inputs=%5B1%3B+2%3B+3%3B+5%3B+1%3B+3%5D&version=22.4.0) or [Test all cases](https://tio.run/##y00syfmfkKkQ4aEQ5adgr6CnEKvg8V/Nps5DUUvJIVJdqyzC7n9shItCVIVCSOz/aMNYrmgjawUjIGUMpKwVQAKGYJYxhGUKFAOSEI4JmGMCV2YClkfwTWFCSMbAjICaZwxGcL1GaKJQFMtloG/ABQA) *(Edit: turns out alephalpha's idea is very similar, this just uses a loop instead of zero padding + linearization)* With input [1; 2; 3; 5; 1; 3] ``` &<~ % make a boolean matrix, each column denoting % which buildings are >= current one ``` 1 0 0 0 1 0 1 1 0 0 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 0 1 0 1 1 1 0 1 1 ``` G!* % multiply by input ``` 1 0 0 0 1 0 1 2 0 0 1 0 1 2 3 0 1 3 1 2 3 5 1 3 1 0 0 0 1 0 1 2 3 0 1 3 ``` "@Y' % for each column, take its run-length encoding ``` eg. for second column, [0 2 0 2] [1 3 1 1] ``` * % multiply to get rectangle areas vX> % cumulatively, keep finding the maximum area % implicit loop end, implicit output ``` -1 byte thanks to @LuisMendo. [Answer] # [Factor](https://factorcode.org/), 58 bytes ``` [ all-subseqs [ dup infimum swap length * ] map supremum ] ``` [Try it online!](https://tio.run/##ZY/NCsIwEITveYo5Cxba2os@gHjxIp5KD7GmWmxjzA8qpc8etz/SohkWZr4lC1Pw3N61Px52@@0aRjyckLkwgXhZzQ1uQktRTRw1t1coLax9K11Kiw1jDQO9BiHa0UWkr4/JT5uQUjxLST9TXo0zJ8kPSXr2e7Mj88sxafgd/dFBLWt9Cl5VS@NOVNEgxdkplLIoa1fDPLlCJeSFKi@QUXcF46h8t8x8FwP/AQ "Factor – Try It Online") Port of @UnrelatedString's [Jelly answer](https://codegolf.stackexchange.com/a/242802/97916). * `all-subseqs` Get every possible grouping of contiguous skyscrapers. * `[ dup infimum swap length * ] map` Get the area of each grouping by multiplying the height of the shortest skyscraper in the grouping by the number of skyscrapers in the grouping. * `supremum` Return the largest area. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 50 bytes ``` a->m=vecmax;m([m([c=(t>=s)*c+=s|t<-a*!c=0])|s<-a]) ``` [Try it online!](https://tio.run/##XU7RCsIwDPyVuKd2tuDa@qTdj4w@hOJkYKWsQxT27zUrm6JwJHfHXUjEcZDXmHuwGWUb7OPiAz5PgXUEb9nU2sRrv7dpns4S6523B8fnRNzxjDHeXgxBthDH4T4RrRZRQc@QcwFd1ziaSoBatqYtoFhNoXqlR3JprsoUZb5JUxLmt7q1thu64JNW//YKR3@/AQ "Pari/GP – Try It Online") --- # [Pari/GP](http://pari.math.u-bordeaux.fr/), 50 bytes ``` a->m=0;[[m=max(m,c=(t>=s)*c+=s)|t<-a*!c=0]|s<-a];m ``` [Try it online!](https://tio.run/##XUxBCsMgEPzKNidNFRK1p9R8RDwsgZRALZLk0EL@bjdiWloYZmeGmY04T/IW0wg2oeyDbTrngg34ZEEMlq29XXg9nIm39SqxPg228dtC0nchYYz3F0OQPcR5eqwkq91UMDLkXIBzrSdWAtR@NV0BOWqz1EVeKCUuzmRnvk2TG@Z3eqyOHzrj01b/cYH3PL0B "Pari/GP – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` I⌈Eθ⌈E⊕κ×⁻⊕κλ⌊✂θλ⊕κ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexIjO3NBdIF2gU6iggcz3zkotSc1PzSlJTNLI1dRRCMnNTizV8M/NKizHkcoAYKAPWG5yTmZwKMixHRwFVHRxY//8fHW2oo2AMRkCGiY6CqY6CUWzsf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @l4m2's Python answer. ``` θ Input array E Map over elements κ Current index ⊕ Incremented E Map over implicit range κ Outer index ⊕ Incremented ⁻ Subtract λ Inner index × Multiplied by θ Input array ✂ Sliced from λ Inner index to κ Outer index ⊕ Incremented ⌊ Take the minimum ⌈ Take the maximum ⌈ Take the maximum I Cast to string Implicitly print ``` [Answer] # JavaScript (ES6), 69 bytes ``` f=a=>+a||Math.max(Math.min(...a)*a.length,f(a.slice(1),a.pop()),f(a)) ``` [Try it online!](https://tio.run/##jc9BDoIwEAXQvafostVa0gLqBm/gCUwXEyyIQUqEGBfcvQJFjVgJk8mkaV4mfy5whyq@ZWW9LvRJGZNEEO1X0DQHqM/sCg9sH1mBGWNAlsByVaT1mSYYWJVnscKcUGClLjEh3S8hJtZFpXPFcp3iBB@5RD9FCPI8xBcjKigS0kmDMfVbStH37j@U99SfScN2azvliIYOGvQ0@MSYpKGDcuFOYPkM2x32ytxfaO3GQf2@31mEtHQ3RYce6NY8AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` f = // f is a recursive function taking: a => // a[] = skyline array +a || // if a[] is a singleton, return its unique value Math.max( // otherwise, return the maximum of: Math.min(...a) // 1) the smallest value of a[] * a.length, // multiplied by the length of a[] f( // 2) the result of a recursive call a.slice(1), // with the 1st item removed a.pop() // (remove the last item for the next call) ), // f(a) // 3) the result of a recursive call // with the last item removed ) // end of Math.max() ``` [Answer] # Python3, 78 bytes: ``` f=lambda x,c=0,j=1:j>len(x)or max([min(x[c:j])*(j-c),f(x,c,j+1),f(x,c+1,j+1)]) ``` [Try it online!](https://tio.run/##VVBZboMwEP0upxjxg904Uc3SRkjOEXoBiipDjGrEYmGroqengwlRIlnWvGVm7Gf@3M84JGczLUsjOtlXVwkzq8UbawXP20unBjLTcYJezqToNaKiztuSvpL2WFPWEHSz9sBv5YF7UNJF92acHEjrAivCMCx4CccL8KCIGcS@ToMiwZoB3yH3MHmAGap4eybzTOqZdO@6k9kDyeO9eROe2HXDPnhb9e75xJ/7sO2N52fpdrz0gb8KGsxGgx6g0Z1TE/kcB8XAnqzptCPR1xBRmgcvklUgMERDMJATSmqS3bf6lR0DvZvXoWhHt7UKs2uIpCAEVIGZ9IAGp6yzYFb5GtHlHw) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~108~~ 97 bytes ``` m;s;j;k;f(a,n)int*a;{for(m=0;n--;)for(j=a[n];s=j;--j,m=s>m?s:m)for(k=n;k--;)s+=a[k]<j?k=0:j;j=m;} ``` [Try it online!](https://tio.run/##ZZTdrqIwEMfvz1M0JCagkOVTxJ4eLzb7FMoFwXIOsNQTS7JmDa@@7NAWbJUAY@f378x0Wiy9z7Icxw5z3OAWV3bhMqdm/brA9@pytTviY@Z52JkGDSmOLMecNNjzGrcj/KM78H0nYEsYbicl34Cszd@bQ0v8fYMb0uFhhJioK2pmO@j@huCaHD3lfXDMEUH3YMCLK5Su0EWh5o2kNwKvi3R5rCIIEGkgWUACM@Ctse3CYsFiM2aq4@QF7/TIUqHjzKhoTq@XFviLJBL3kklfchC8qtQ94LmLayHlUilmubKL0kTSxNIk0mylSaXZSZO5qjRltRzCwWQKXv@ll8oWEueHGq3l0EUaDU0amjQyaWTS2KSxSROTJibdmnRr0tSkqUl3Jt2ZNDNpZtLAf2qH/8Sf2xU4Wofp7ZuWPT3rBy@eD8V0gEL5wNbBfqVqZnlhvEflV3Fdw5uWLb3KANbp9is83bKf8CSWi/RxZKnZ8N0ie0peszO9wTQfq5/vc@FzWY/SFw9Gm41QOyKY/KwfhxLCyYMpNDnWMWKKshf6qEnVA7UwkcpZNNP1fQVRZVsrvjrD@urDtMi9dQTTH@vcMfNxCAa7AH9upp@Cf@n8cylzihx5H2h1Rit@YhCeu0urOSF0TjW8DeO/svpdfPLR@/Mf "C (gcc) – Try It Online") Inputs a pointer to an array of positive integers and its length (because pointers in C carry no length info). Returns the area of the largest rectangle in the skyline. [Answer] # APOL, 29 bytes `M(ƒ(z(Ŀ(s(i))) *(m(∋) l(∋))))` A port of [UnrelatedString's Jelly answer](https://codegolf.stackexchange.com/a/242802/108218). ## Explanation ``` M( Largest element of ƒ( For z(Ŀ(s(i))) every contiguous sublist of the input, *(m(∋) l(∋)) multiply its smallest item by its length ) and make a list of the results. ) implicit print ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` ▲m§*▼LQ ``` [Try it online!](https://tio.run/##yygtzv7//9G0TbmHlms9mrbHJ/D////RhjrGOiY6RjqmQNo4FgA "Husk – Try It Online") ### Explanation ``` ▲m§*▼LQ m Q for each contiguous sublist §* multiply it's ▼L minimum value by it's length ▲ maximum of that ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 64 bytes ``` a=>Math.max(...a.map((n,i)=>(g=d=>a[i+=d]>=n&&g(d)+n)(-1,g(1)))) ``` [Try it online!](https://tio.run/##jc9LDoIwEAbgvafoykwDlJSHuik38ASki4aXGCxEiPH2tRbUiJUwmUxm8WXyz1ncRJ9d627wZJsXqmRKsOQohhO5iDsQQoReOgDp1pglULGcJSKtHZbzhMnttoIcOxKDR90KKNalslb2bVOQpq2ghJRy9FMYI99HdDOjgYsCbqXRnIaauuj79h9KDQ1X0lhf1ZPPaGyhkaHRJ8YijS2UBvYEI19hn4@9MpsPR7uz0ND0O0vAR3pYolNPdK8e "JavaScript (Node.js) – Try It Online") [Related](https://codegolf.stackexchange.com/a/242995/44718) [Answer] # Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 13 bytes ``` xM(mn*×l)<cg ``` In the interested of transparency, since hgl is under heavy development some features used in this answer were only merged into master recently. ## Explanation We just use the most straightforward possible algorithm. `cg` gets all contiguous sublists we take these as the footprints for potential boxes. We then for each of these multiply it's length by it's minimum element with `mn*×l` and take the maximum overall. This is just a simpler version of the algorithm employed in [the more interesting version of this challenge](https://codegolf.stackexchange.com/q/242982/56656). [Answer] # [Haskell](https://www.haskell.org/), 65 bytes ``` f l=maximum[x*(minimum$take x t)|t<-scanr(:)[]l,x<-[1..length t]] ``` [Try it online!](https://tio.run/##fZDLDoIwEEX3/YpZsAADJOWhxoA/QrpoFITQVgM1YeG/Y0FeYjGZNJ1zp525k9O6TBlr2wxYzGlT8CdPmp3JC9FdDUnLFBqQ1ktGTn2hojJPVkKY3UROgl2XpeImc5CEtJwWAmK43hHAoyqEBAMySDCBb@DZ4K2Zr5gNP6W4x74Gh6panRol6JVA/1vQv9wQw1HfmmNsqxvI72Nq4f0rGYJA223HOQNGw1bUPUDzNj7ptIUpndwrEqK16yUMFxB7aG1zpit/StgjvS8lHZHej5IObw "Haskell – Try It Online") ]
[Question] [ I was answering one challenge here and this task was part of the challenge. I've got a 73 bytes solution in javascript. But I think it is too much for a simple thing. ### Challenge Given as input two integers: * `N` the length of the expected array * `R` the interval's range starting in one: `1..R`, not `0..R-1` Output in each run of your program/function one different array of length `N` with values between `1..R` in such a way no one value occurs more than once. You must use `R-value` in your code. ### Restrictions You can assume: `2 <= N <= R`. I really would like to see a javascript solution shorter than mine 73 bytes. But of course, it is open to all languages! If your language can not return an array, you can print all the numbers ;) [Answer] ## Dyalog APL, 1 byte ``` ? ``` Just a builtin. Try it [here](http://tryapl.org/?a=4%3F10&run). [Answer] # JavaScript (ES6), ~~68~~ 66 bytes ``` n=>r=>G=(s=new Set)=>s.size<n?G(s.add(Math.random()*r+1|0)):[...s] ``` Called as `F(N)(R)()`, where `F` is the function assignment, and `N`/`R` are the values. You asked for shorter than 73 bytes in Js ;) EDIT: The answer by @C5H8NNaO4 works within the fact that the rules don't specify the values must be uniform across `1..R`. Given that, here's a version works in 63 bytes (called as `F(R)(N)`): ``` r=>G=(n,s=[])=>n--?G((s[n]=n+1,n),s):s.sort(a=>new Date/a%1-.5) ``` [Answer] # Octave, ~~22 19~~ 9 bytes ``` @randperm ``` `randperm(r,n)` does exactly what is requested. Note that this does not work (at least not in oldder versions) in Matlab. [Answer] ## TI-84 BASIC OS 4.0, 12 bytes ``` Prompt N,R:randIntNoRep(1,R,N ``` The TI-84+ CSE (2013) and the CE (2015) are essentially the same limited BASIC dialect as the TI-84+, but there are a few new features. One of them is randIntNoRep's third argument. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 2 bytes ``` Zr ``` Inputs are: first `R`, then `N`. [**Try it online!**](http://matl.tryitonline.net/#code=WnI&input=OAo1) ### Explanation The function `Zr` takes two inputs (implicitly in this case) and does a random sampling without replacement. The first input, `R`, specifies that the population is `[1,2,...,R]`; and the second input, `N`, indicates the number of samples to take from the population. [Answer] # J, ~~4~~ 3 bytes One byte saved thanks to Zgarb! ([Crossed out four is still a regular four :D](https://codegolf.stackexchange.com/questions/73580/swap-delete-and-repeat/73584#73584)) ``` 1+? ``` call like `N (1+?) R`, e.g., `3 (1+?) 10`. This uses the "Roll" operator, and does exactly what is described, except under `0...n-1`. If we were allowed to do this, then the answer would be 1 byte, ``` ? ``` [Answer] # Pyth, 6 bytes ``` <.SSQE ``` [Try it here!](http://pyth.herokuapp.com/?code=%3C.SSQE&input=10%0A6&debug=0) Range comes on the first line and the length on the second. # Explanation ``` <.SSQE # Q = range, E = length SQ # generate the range 1...Q .S # shuffle the list < E # take the first E elements ``` ## Non-competing 5-byte version The lastest addition to Pyth adds implicit `Q`s at the end of the program if needed. We can use this here by reversing the input format, so the length comes first and then the range. ``` <.SSE ``` [Try it here!](http://pyth.herokuapp.com/?code=%3C.SSE&input=6%0A10&debug=0) Here `E` is the range, which we turn into a 1-based list with `S`, shuffle it with `.S` and take the first `Q` elements with `<`. `<` expects an integer which is implicitly added with a `Q`. [Answer] # Reng v.2.1, ~~140~~ ~~103~~ ~~98~~ 97 bytes This should work in earlier versions, too. ``` v v $/$'l#y0#z>(:)):(ez+#z zt>a$;! >i#ci#x>cu1+lxetv j21\!q yy#-1y($/^ >n?~v ^oW < ``` [You can try it here!](https://jsfiddle.net/Conor_OBrien/avnLdwtq/) Input is `maximum length`, such as `10 3`. I am so proud of this, you don't even know. If someone beats me with a Java answer, that will make my day. If I beat a Java answer, consider my day made as well. I will explain it more later, once I recover. Generally, though: ``` v v $/$r$ >i#bbi1+#x>:u1+lxet ``` This generates the random numbers. The other part checks if there are duplicates, and, if there are, the process is repeated. Else, the results are printed, with spaces joining the results. Here are some examples: [![long gif](https://i.stack.imgur.com/8PyMa.gif)](https://i.stack.imgur.com/8PyMa.gif) [Answer] # CJam, 8 bytes ``` {,:)mr<} ``` [Try it here!](http://cjam.tryitonline.net/#code=NiAxMAoKeyw6KW1yPH0KCn5w&input=) This is an unnamed block which expect the range on top of the stack and the length at the bottom and leaves a list on the stack. # Explanation ``` , e# 0-based range :) e# inkrement each element of the list so its 1-based mr e# shuffle the list < e# take the first n elements ``` [Answer] ## Common Lisp, 90 **52** for the expression only ``` (use-package :alexandria)(lambda(R N)(coerce(subseq(shuffle(iota R :start 1))0 N)'vector)) ``` ### Ungolfed ``` ;; Well known library (use-package :alexandria) (lambda(R N) (coerce ; make a vector from a list (subseq ; take the sublist from 0 to N (shuffle ; shuffle a list (iota R :start 1)) ; build a list from 1 to R 0 N) 'vector)) ``` Like other answers, if I don't count *use-package* and *lambda*, the remaining expression is `(coerce(subseq(shuffle(iota R :start 1))0 N)'vector)`, for 52 bytes. [Answer] # Ruby, ~~27~~ 23 bytes Anonymous function, reasonably short and sweet. -4 bytes from @manatwork ``` ->n,r{[*1..r].sample n} ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟, 10 chars / 13 bytes ``` Ѩŝ⩤⁽1í)ą-î ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=%5B3%2C5%5D&code=%D1%A8%C5%9D%E2%A9%A4%E2%81%BD1%C3%AD%29%C4%85-%C3%AE)` # Explanation ``` // implicit: î=input1, í=input2 ⩤⁽1í) // Inclusive range from 1 to í Ѩŝ // Shuffle resulting range ą-î // Get last îth items ``` [Answer] # Bash + coreutils, 16 I think this is self-explanatory: ``` seq $2|shuf -n$1 ``` Input `N` and `R` as command-line parameters. Or as @rici points out, for the same score: ``` shuf -n$1 -i1-$2 ``` [Ideone.](https://ideone.com/p5QVrC) [Answer] ## PowerShell v2+, 30 bytes ``` param($n,$r)1..$r|Random -c $n ``` Takes input `$n` and `$r`, constructs a range `1..$r`, pipes that to `Get-Random` with a `-C`ount of `$n`, which will select `$n` unique elements from the range. Output is left on the pipeline as an implicit array. [Answer] ## Seriously, 5 bytes ``` ,,R╨J ``` [Try it online!](http://seriously.tryitonline.net/#code=LCxS4pWoSg&input=Mgo1) Explanation: ``` ,,R╨J ,,R push N, range(1, R+1) ╨ push a list containing all N-length permutations of range(1, R+1) J select a random element from the list ``` [Answer] # Clojure, 38 bytes ``` #(take %1(shuffle(map inc(range %2)))) ``` An anonymous function taking N first and R second. [Answer] # Perl 6, 32 bytes ``` {(^$^a).permutations.pick[^$^b]} ``` [Answer] # Python 3.5 - 54 53 bytes: ``` from random import*;lambda a,c:sample(range(1,c+1),a) ``` This uses the random module's `sample()` function to return an array with length "a" consisting of random, unique elements in the range `1 => c`. [Answer] # D, 29 bytes (expression only) Assuming that std.random and std.range have been imported and that n and r are defined as variables, the program can be solved in the single expression: ``` iota(1,r).randomCover.take(n) ``` [Answer] **ES6, 72** ``` r=>n=>[...Array(-~r).keys()].sort(a=>new Date/a%1-.5).filter(a=>a&&n-->0) ``` Like in @Mwr247's [answer](https://codegolf.stackexchange.com/a/76208/8372), you can call it with `F(R)(N)`, `F` being the function expression [Answer] # Mathcad, 67 "bytes" creates a column vector of consecutive integers in range 1..R, joins it to a column vector of length R of (uniform) random numbers, sorts the resulting Rx2 matrix on the random number column, and then extracts the first n numbers from the randomized column of integers. [![enter image description here](https://i.stack.imgur.com/tpOLz.jpg)](https://i.stack.imgur.com/tpOLz.jpg) [Answer] # Python, 56 (the obvious way) ``` lambda N,R:__import__('random').sample(range(1,R+1),k=N) ``` [Answer] # Perl 5, ~~51~~ 43 bytes ``` sub{@a=1..pop;map{splice@a,rand@a,1}1..pop} ``` Pretty straightforward anonymous sub that generates an array from 1 to R and then splices N random elements from it to return. Call with `->(N, R)`. [Answer] # TI-84 BASIC, 21 bytes ``` Prompt R,N:randIntNoRep(1,R→A:N→dim(ʟA:ʟA ``` ]
[Question] [ Surprised that we don't have a symmetric difference challenge yet. Given two lists only containing positive integers, return all items among these two lists that aren't contained in both of the lists. ## Rules From the set definition: > > A set is a collection of definite distinct items. > > > * So you can assume the items in the input lists are always unique. * You can also take input as a set if your language supports it. ## Test cases [Here](https://tio.run/##bY2xCsMgFAD39xVv9JFnIG2nUAr6FYI4pEWKEE1RIRTy7zZZSofecNPB@TxP6Sl9eeTwqq1BeUehWBPKG@CONbhtaPAqUTGmpeIcSi1j9PHuszCMmhxg1/2W@n@pyPUAcQpJWPc9hGVcc6heHGs78InPju1uvjiivrUP) is a sample program that generates the test cases. ``` [1,2,3],[2,3,4] -> [1,4] ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 3 [bytes](https://codegolf.meta.stackexchange.com/a/9429/78410) ``` ∪~∩ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HHqrpHHSv/pz1qm/Cot@9RV/Oh9caP2iY@6psaHOQMJEM8PIP/GyoYKRgrpIFJEwA "APL (Dyalog Unicode) – Try It Online") ### How it works ``` ∪~∩ ⍝ Input: two sets as vectors ∪ ⍝ Set union ~ ⍝ Set minus ∩ ⍝ Set intersection ``` --- The rest is just for fun. # [APL (Dyalog Unicode)](https://www.dyalog.com/), 4 [bytes](https://codegolf.meta.stackexchange.com/a/9429/78410) ``` ~∪~⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v@5Rx6q6R70r/qc9apvwqLfvUVfzofXGj9omPuqbGhzkDCRDPDyD/xsqGCkYK6SBSRMuGM9EwVLBCAA "APL (Dyalog Unicode) – Try It Online") ``` ~∪~⍨ ~ ⍝ Set difference (a~b) ∪ ⍝ Set union ~⍨ ⍝ Set difference reversed (b~a) ``` # [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 [bytes](https://codegolf.meta.stackexchange.com/a/9429/78410) ``` ~⍨∪⍨~ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v@5R74pHHauAZN3/tEdtEx719j3qaj603vhR28RHfVODg5yBZIiHZ/B/QwUjBWOFNDBpwgXjmShYKhgBAA "APL (Dyalog Unicode) – Try It Online") This one is palindromic! ### How it works ``` ~⍨∪⍨~ ~⍨ ⍝ Set difference reversed (b~a) ∪⍨ ⍝ Set union reversed ~ ⍝ Set difference (a~b) ``` [Answer] # [Python 3](https://docs.python.org/3/), 11 bytes ``` set.__xor__ ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzvzi1RC8@viK/KD7@f0FRZl6JRppGtaGOkY5xrU41kNQxqdXU/A8A "Python 3 – Try It Online") For built-in `set` objects, `a^b` computes symmetrical set difference. `__xor__` is the magic name for that operator, and it is shorter than `lambda a,b:a^b`. Also works in [Python 2](https://tio.run/##K6gsycjPM/qfZhvzvzi1RC8@viK/KD7@f0FRZl6JRppGtaGOkY5xrU41kNQxqdXU/A8A). [Answer] # [J](http://jsoftware.com/), ~~8~~ 6 bytes -2 bytes thanks to Bubbler! ``` -.,-.~ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/dfV0dPXq/mtyKXClJmfkKxgqGCkYK6SBSZP/AA "J – Try It Online") # [K (oK)](https://github.com/JohnEarnest/ok), 11 bytes ``` {(x^y),y^x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWqMirlJTpzKuovZ/WrShgpGCsTUQK5jE/gcA "K (oK) – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~22~~ 19 bytes *-3 bytes thanks to @user41805* ``` rs 0 1|sort|uniq -u ``` [Try it online!](https://tio.run/##S0oszvj/v6hYwUDBsKY4v6ikpjQvs1BBt/T/f0MFIwVjLiBWMAEA "Bash – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes ``` Join@##~Complement~Intersection@##& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773ys/M89BWbnOOT@3ICc1NzWvpM4zryS1qDg1uSQzHySl9j@gKDOvRMEhPbraUMdIx7hWpxpI6pjUxv7/DwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` «¹²ÃK ``` **[Try it online!](https://tio.run/##yy9OTMpM/f//0OpDOw9tOtzs/f9/tKGOkY5xLFc0kNQxiQUA "05AB1E – Try It Online")** ### How? ``` « - merge the two input lists -> a+b ¹ - push 1st input list a,a+b ² - push 2nd input list b,a,a+b à - intersection b&a,a+b K - discard (a+b)-(b&a) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~98~~ 96 bytes ``` *d;f(a,b,c)int*a,*b,*c;{for(;*c=*a++;c+=!(*d=-*d))for(d=b;*d&&*d-*c;d++);for(;*c=*b++;c+=*c>0);} ``` [Try it online!](https://tio.run/##PY7dCsIwDIXvfYo6UJq0g/pzF@qLiBdp6uZAp6jgYPjq1naCNzmEnHPySd2KpISRGs02WIGufyJbDBaFxuZ614TikY0hMX6uMfoaI0C5RB8I43KJsc7maAzQPxB@AZSdA3qnC3e9hjGXK96vnDvY8BOZhFrNkEeAP8dUVWAGL4QD3e55aXS1iKqyOORnuXdWchMxja9Tdz7qh3A/uSrLkNG4UL3TSq3VRrlZmVvlPtKcuX2k@vUF "C (gcc) – Try It Online") *-2 bytes thanks to @ceilingcat* Input is in two 0-terminated arrays `a` and `b`, output as a 0-terminated array into preallocated buffer `c`. [Answer] # [R](https://www.r-project.org/), ~~45~~ 39 bytes ``` function(x,y,`-`=setdiff)union(x-y,y-x) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQqdSJ0E3wbY4tSQlMy1NszQPLKpbqVOpW6H5P03D0MpYx8jKRPM/AA "R – Try It Online") Thanks to [user Kirill L.](https://codegolf.stackexchange.com/users/78274/kirill-l)'s [comment](https://codegolf.stackexchange.com/questions/203364/symmetric-difference/203484#comment484073_203484). The original was the following. ``` function(x,y){s=setdiff;union(s(x,y),s(y,x))} ``` [Try it online!](https://tio.run/##K/r/P600L7kkMz9Po0KnUrO62LY4tSQlMy3NujQPJFgMFtYp1qjUqdDUrP3/HwA "R – Try It Online") Straightforward, definition coded in R. Note: the following function is also 45 bytes. I thought that to define `s=setdiff` first would save a few bytes but as it turns out the function will need a semi-colon instruction separator and to be between braces. For the same byte count a no-tricks function is more natural. ``` function(x,y)union(setdiff(x,y),setdiff(y,x)) ``` [Answer] # [Red](http://www.red-lang.org), 25 bytes ``` func[a b][difference a b] ``` [Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85OlEhKTY6JTMtLbUoNS85VQHE/19QlJ@UqpCmEG2oYKRgHBsNJBRMYv8DAA "Red – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` «©ʒ®s¢ ``` How does it work? ``` « merge lists © store in the global register ʒ keep only items which ®s¢ the number of times which they appear in the merged list is truthy, which is only 1 in 05AB1E ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0OpDK09NOrSu@NCi//@jDXWMdIxjuaKBpI5JLAA "05AB1E – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes ``` I⁺⁻θη⁻ηθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyCntFjDNzMPSBbqKGRo6ihAOBk6CoWaQGD9/390tKGOkY5xrE40kNQxiY39r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ First input η Second input ⁻ Remove matching elements η Second input θ First input ⁻ Remove matching elements ⁺ Concatenate I Cast to string Implicitly print ``` [Answer] # JavaScript (ES6), 46 bytes Takes input as `(a)(b)`, where \$a\$ and \$b\$ are Sets. Returns a list. JS has very few set built-ins, so this a bit verbose. ``` a=>b=>[...a,...b].filter(x=>a.has(x)^b.has(x)) ``` [Try it online!](https://tio.run/##RchBCsMgEEDRq7icATvQplu9RJeSwpiMrUW0RGlze5NCIZvP5734w3Va4rudcpmlB9PZWG@sIyLWe/xIIaYmC6zGMj25wop3/x/sU8m1JKFUHhAgy1fdpIE7a3XRahgRD/uBVtfdsG8 "JavaScript (Node.js) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 2 bytes ``` X~ ``` [Try it online!](https://tio.run/##y00syfn/P6Lu//9oQx0jHeNYrmggqWMSCwA "MATL – Try It Online") ### Explanation Built-in. Implicit inputs, implicit output. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~16~~ 14 bytes ``` ->a,b{a-b|b-a} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6k6UTepJkk3sfZ/gUJatEK0oY6RjnGsjkI0kNIxiVWI/Q8A "Ruby – Try It Online") [Answer] # [Julia](http://julialang.org/), 7 bytes ``` symdiff ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/v7gyNyUzLe1/QVFmXokGlKcRbaijYKSjYByroxANonUUTGI1Nf8DAA "Julia 1.0 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` «Ð¢Ï ``` [Try it online.](https://tio.run/##MzBNTDJM/f//0OrDEw4tOtz//3@0oY6RjnEsVzSQ1DGJBQA) **Explanation:** ``` # i.e. inputs: [1,2,3] and [2,3,4] « # Merge the two (implicit) input-lists together # STACK: [[2,3,4,1,2,3]] Ð # Triplicate this merged list # STACK: [[2,3,4,1,2,3],[2,3,4,1,2,3],[2,3,4,1,2,3]] ¢ # Count all occurrences of the values in the list # STACK: [[2,3,4,1,2,3],[2,2,1,1,2,2]] Ï # Only leave the values at the truthy (count = 1) indices # STACK: [[4,1]] # (after which the result is output implicitly) ``` [Answer] # [Haskell](https://www.haskell.org/), 36 bytes ``` x%y=filter(`notElem`y)x x#y=x%y++y%x ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v0K10jYtM6cktUgjIS@/xDUnNTehUrOCq0K50hYop61dqVrxPy1NwVZBQ1mTKzcxMw/ILCjKzCtRUFEAikcb6hjpGMcqRANJHZPY/wA "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` œ^ ``` It's a two-byte dyadic atom (i.e. a built-in). **[Try it online!](https://tio.run/##y0rNyan8///o5Lj///9HG@oY6RjH/o8GkjomsQA "Jelly – Try It Online")** [Answer] # [Icon](https://github.com/gtownsend/icon), 38 bytes ``` procedure f(a,b) return a++b--a**b end ``` [Try it online!](https://tio.run/##TYw7DoAgEAV7ToHdri6Fn9sYC5AloRDMihpPr8bKV80kkxfnnO57lTyz34V1AEsOlXDZJWnbNM4YW9dOcfK/bLExASr9jg@WS58SC0MVYOMCY0sd9RPSJy/SMCHi9/EA "Icon – Try It Online") [Answer] # [Groovy](http://groovy-lang.org/), 18 bytes ``` f={a,b->a-b+(b-a)} ``` [Try it online!](https://tio.run/##Sy/Kzy@r/P8/zbY6USdJ1y5RN0lbI0k3UbP2f0FRZl6JQppGtKGOkY5xrE40kNQxidX8DwA "Groovy – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 39 bytes ``` param($a,$b)$a+$b|group|? c* -eq 1|% n* ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRRyVJUyVRWyWpJr0ov7Sgxl4hWUtBN7VQwbBGVSFP6////4Y6RjrG/4FYxwQA "PowerShell – Try It Online") unrolled: ``` param($a,$b) $a+$b|group|where count -eq 1|% name ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` -sQ@F ``` [Try it online!](https://tio.run/##K6gsyfj/X7c40MHt//9qQx0jHeNanWogqWNSCwA "Pyth – Try It Online") ``` sQ sum inputs (union since inputs are sets) - minus @F intersection of inputs ``` [Answer] # [Perl 5](https://www.perl.org/), 42 bytes ``` sub u{map$k{$_}++,@_;grep$k{$_}==1,keys%k} ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4NEmhtDo3sUAlu1olvlZbW8ch3jq9KBXKt7U11MlOrSxWza79X1BanOGQqOPgVltdnFipkJZfpFDqkPjfUMFIwZgLiBVM/uUXlGTm5xX/1/U11TMwNPivm5gDAA "Perl 5 – Try It Online") [Answer] ## Pascal, ≥ 4 B The symmetric difference operator denoted `><` is defined by ISO standard 10206 “Extended Pascal” as part of the programming language. ``` A><B { where `A` and `B` are assignment-compatible `set` expressions } ``` In “Standard Pascal”, defined by ISO standard 7185, you will need to resort to basic operators: ``` (A−B)+(B−A) ``` [RosettaCode](https://rosettacode.org/wiki/Symmetric_difference#Pascal) │ [FreePascal Compiler wiki](https://wiki.FreePascal.org/symmetric_difference) │ [Pascal programming WikiBook](https://en.WikiBooks.org/wiki/Pascal_Programming/Sets#Operations) [Answer] # [Python](https://www.python.org), 49 bytes (no built-in set operations) ``` lambda s,t:[a for a in s+t if(a in s)*(a in t)<1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3DXMSc5NSEhWKdUqsohMV0vKLFBIVMvMUirVLFDLTNCBsTS0Io0TTxjAWqnFyui2SVo1i3RLNGo0S3WJNrgxUiZoSTV2NEjWgREFRZl6JRppGtKGOkY5xrE60sY6JjmmsJkwmXaM4tQQmq6kD5sCUwNRk4FMDcdqCBRAaAA) takes two lists as input, returns symmetric difference of those lists (concatenation without elements that appear in both lists) ## Python, 22 bytes ``` lambda s,t:(s-t)|(t-s) ``` ``` lambda s,t:(s|t)-(t&s) ``` build symmetric difference as union of differences / union without intersection [Answer] # [Factor](https://factorcode.org/) + `sets.extras`, 14 bytes ``` symmetric-diff ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqVQnFpSrJdaUVKUWKxQUJRaUlJZUJSZV6JgzcVVrWCoYKRgrFCrUA2mTRRq/xdX5uamlhRlJuumZKal/df7DwA "Factor – Try It Online") --- **No builtin:** # [Factor](https://factorcode.org/) + `math.unicode`, 25 bytes ``` [ 2dup ∪ -rot ∩ ∖ ] ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqVQUJRaUlJZUJSZV6KQnVqUl5qjkJtYkqFXmpeZnJ@SqmDNxVWtYKhgpGCsUKtQDaZNFGr/RysYpZQWKDzqWKWgW5RfAmSsBOJpCrH/kxNzchT0/gMA "Factor – Try It Online") ]
[Question] [ So we're all hopefully familiar with Spreadsheet 'A1' cell notation. It's simply an alphanumeric representation of the positioning of said cell within a grid. The letter(s) represent the column positioning of the cell, and the number represents the row. The 'letter' part can consist of 1 or more letters from the 26 letter English alphabet, all of which must be capital letters. These map to numbers through the use of 26-adic bijective numeration. The 'number' part can consist of any positive, non-zero integer. --- The challenge, write a program that given the A1 notation of any cell as a single string, can output a string containing the column position represented as a number, followed by a space and then the row number. Sample Input/Outputs below: ``` A1 >>1 1 B10 >>2 10 AC4 >>29 4 AAC753 >>705 753 F123 >>6 123 GL93 >>194 93 ``` This is my first challenge, hence the relative simplicity and potential poorness of the criteria. **EDIT**: String must be letters followed by numbers and the winning criteria is the shortest code length (if that can be a thing) **EDIT**: Related to [this](https://codegolf.stackexchange.com/questions/3971/generate-excel-column-name-from-index) but does the reverse process with a different starting index. Some may argue that this fact makes the linked puzzle more interesting. [Answer] # Microsoft Excel, 43 Bytes. ``` =COLUMN(INDIRECT(A1))&" "&ROW(INDIRECT(A1)) ``` I couldn't help myself, I just had to use the right tool for the job. Takes input on A1. ## Test Cases ![](https://i.gyazo.com/ad9bc4d2a21af11b1d5bf4420f5498e9.png) [Answer] ## Microsoft Excel, 40 bytes **Brasilian Portuguese language version.** ``` =COL(INDIRETO(A1))&" "&LIN(INDIRETO(A1)) ``` Translated (and therefore golfed) version of [ATaco's solution](https://codegolf.stackexchange.com/a/139223/55372). [Answer] # [Python 2](https://docs.python.org/2/), ~~94~~ ~~91~~ 73 bytes -3 bytes thanks to Jonathan Allan -18 bytes thanks to tsh ``` s=input().strip a=s(`3**39`);t=0 for n in a:t=t*26+ord(n)-64 print t,s(a) ``` [Try it online!](https://tio.run/##BcFLCoAgFADAvadw56cPoWVUuJAuohCRm6foa9HpbSZ/@CRQrVUbIb/IxVixxEyCrdxrKfXmxYF2IncqFGgEGna0KJXpUrk4iMHMJJcISLGvPIjWmHPnumj2Aw "Python 2 – Try It Online") This abuses the way that `.strip` works, removing all digits wtih `a=s(`3**39`)` where ``3**39`` is just a shorter way to generate the digits from `0` to `9`, this will store only the chars on `a` that will be used to strip the chars from the numbers on `s(a)` [Answer] # Google Sheets, 43 bytes ``` =COLUMN(INDIRECT(A1))&" "&ROW(INDIRECT(A1)) ``` [Try it online!](https://docs.google.com/spreadsheets/d/12ZvkXGomOgv7DbMCsxDYttmWzOe2t4HN2N3h01iJYuY/copy?usp=sharing) `A1` is the input cell. Hopefully the above link works, I've never tried code golf with Google Sheets before. [Answer] # JavaScript, 72 bytes ``` x=>x.replace(/\D+/,s=>[...s].reduce((n,v)=>n*26+parseInt(v,36)-9,0)+' ') ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes ``` áÇ64-₂βð¹þJ ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##ASEA3v8wNWFiMWX//8Ohw4c2NC3igoLOssOwwrnDvkr//0dMOTM "05AB1E – Try It Online") [Answer] # [Proton](https://github.com/alexander-liao/proton), 113 bytes ``` k=>{b=(s=k.strip)('0123456789');str(sum(map((a=>26**a[1][0]*(ord(a[1][1])-64)),enumerate(b[to by-1]))))+' '+s(b)} ``` [Try it online!](https://tio.run/##HYlLCsMgFACvkp3vmabEfFuKgdBjiAulBkJIFDWLUnp2K53dzDhvoz3SwtPGp4/mEPh2DdGvDoHUrGm7fhhvd4KPHCGcO@zKASg@NQOlSjApaknB@hf8hUmshg7xYo5zN15FA1pEW@h3lVemJAUpA2j8JufXI8ICZJ6fY98SxPQD "Proton – Try It Online") -19 bytes borrowing Rod's algorithm (*note to self: add listcomps*) [Answer] # Dyalog APL, 44 bytes ``` (26⊥¯65+⎕AV⍳(a~⎕D)),⎕A~⍨a←⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtEzSMzB51LT203sxUGyjgGPaod7NGYh2Q6aKpqQMSqXvUuyIRqPBR77z//x0dnS2MDAA) [Answer] # Pyth - 31 bytes First attempt, very naive. ``` jd,s*V.u*26NQ1_hMxLGr-QK@`UTQZK ``` [Try it online here](http://pyth.herokuapp.com/?code=jd%2Cs%2aV.u%2a26NQ1_hMxLGr-QK%40%60UTQZK&input=%27AAC7537%27&debug=0). [Answer] # [Perl 5](https://www.perl.org/), 35 + 1 (-p) = 36 bytes ``` map$r=$r*26-64+ord,/\D/g;s/\D*/$r / ``` [Try it online!](https://tio.run/##K0gtyjH9/z83sUClyFalSMvITNfMRDu/KEVHP8ZFP926GEhp6asUKej//@/o6Gxh8C@/oCQzP6/4v66vqZ6BocF/3QIA "Perl 5 – Try It Online") The `map` statement treats the column like a base26 number and converts it to decimal. The substitution replaces the letters with the numbers. The input and output are implicit in the `-p` flag. [Answer] ## Mathematica, 108 bytes ``` StringReplace[c:LetterCharacter..~~r:DigitCharacter..:>ToString@FromDigits[ToCharacterCode@c-64,26]<>" "<>r] ``` Operator form of `StringReplace` which takes the alphabetic part `c` of the string, converts it to a list of character codes, subtracts `64` from each code point, interprets the result as a base `26` integer, converts that integer to a `String`, then `StringJoin`s a space followed by the numeric part `r`. Using a regex (also `108` bytes): ``` StringReplace[RegularExpression["([A-Z]+)(.+)"]:>ToString@FromDigits[ToCharacterCode@"$1"-64,26]<>" "<>"$2"] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ØAɓi@€ḟ0ḅ26,⁸Kḟ ``` A full program accepting the string as an argument and printing the result **[Try it online!](https://tio.run/##y0rNyan8/z/T4VHTmsMzHB/umG/wcEerkZkOkAXkq3j////f0dHZ3NQYAA "Jelly – Try It Online")** ### How? ``` ØAɓi@€ḟ0ḅ26,⁸Kḟ - Main link: list of characters, ref e.g. "AAC753" ØA - uppercase alphabet yield = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ɓ - dyadic chain separation, call that B and place it on the right i@€ - first index for €ach (swap arguments) [1,1,3,0,0,0] ḟ0 - filter discard zeros [1,1,3] ḅ26 - convert from base 26 to integer 705 ⁸ - chain's left argument (ref) "AAC753" , - pair [705,['A','A','C','7','5','3']] K - join with spaces [705,' ','A','A','C','7','5','3'] ḟ - filter discard those in right (B) [705,' ','7','5','3'] - implicit print >>>705 753 ``` Note: conversion from a list of numbers using the base conversion atom `ḅ` allows places to be outside of the expected range, so conversion from, say, `[2,26,1]` (`"BZA"`) using `ḅ26` is calculated as **2×262+26×261+1×260=2029** even though the "expected" representation would have been `[3,0,1]`. [Answer] # Mathematica, ~~77~~ ~~72~~ ~~69~~ 68 bytes ``` #/.{a__,b__?DigitQ}:>{f=FromDigits;f[LetterNumber@{a},26],f[b<>""]}& ``` Takes a list of characters. [Try it on Wolfram Sandbox](https://sandbox.open.wolframcloud.com/) ### Usage ``` #/.{a__,b__?DigitQ}:>{f=FromDigits;f[LetterNumber@{a},26],f[b<>""]}&[{"G", "L", "9", "3"}] ``` > > `{194, 93}` > > > or ``` #/.{a__,b__?DigitQ}:>{f=FromDigits;f[LetterNumber@{a},26],f[b<>""]}&[Characters["GL93"]] ``` > > `{194, 93}` > > > ### Explanation ``` #/. ``` In the input replace... ``` {a__,b__?DigitQ} ``` A list containing two sequences `a` and `b` (with 1 or more elements), where `b` consists of digit characters only... (Mathematica uses lazy pattern matching, so no check is required for `a`) ``` :> ``` into... ``` f=FromDigits; ``` Set `f` to digit-to-integer conversion function. ``` LetterNumber@{a} ``` Convert `a` to letter numbers (a -> 1, b -> 2, etc). ``` {f[ ... ,26],f[b<>""]} ``` Convert the above from base-26 to decimal, and convert `b` to decimal. [Answer] # Haskell, 67 bytes ``` (\(l,n)->show(foldl(\a->(a*26-64+).fromEnum)0l)++" "++n).span(>'9') ``` [Try it online.](https://tio.run/##ZU5La8JAEL7nV3wMBXe7RtRqJIEE0qJFDHjw6sENSYh0s7F54MX/nq6NhUjnMAzfc3JZf6VKdV3msyNTY83toM7LK8tKlSh2lHbA5OvcsZ2F4JOsKou1bgs@VVwIAgmh@aS@SM2CkTvinbG2KnlP4Xlg62/IMQ4mDZLDDyBhP9Z2D8YtidOf4YQYN0jfj/E7Pi5tc2iqSIP2O7LwPDeUTZ5W13OdDqUvoE24jTwQhACrH9XmJvRNiNMhGXPLKuRZm5CkNCUZKAw/Vss3Gr5Gq@kSd7BXbGbzZx4gB3ew5z8j9x8/cxcwaPcD) [Answer] # [Retina](https://github.com/m-ender/retina), 85 bytes ``` [A-Z] $& [T-Z] 2$& [J-S] 1$& T`_L`ddd \d+ $* {`\G1(?=.* .* ) 26$* }` (.* ) $1 1+ $.& ``` [Try it online!](https://tio.run/##K0otycxL/P8/2lE3KpZLRU2BKzoExDJSUeOK9tINjuUyBLJCEuJ9ElJSUrhiUrS5VLS4qhNi3A017G31tBSASJPLyAwoWJugoAHmqRhyGQKV6an9/@/uY2kMAA "Retina – Try It Online") Explanation: ``` [A-Z] $& ``` Separate the letters from each other and the final number. ``` [T-Z] 2$& [J-S] 1$& T`_L`ddd ``` Convert the letters to decimal. ``` \d+ $* ``` Convert everything to unary. ``` {`\G1(?=.* .* ) 26$* }` (.* ) $1 ``` While there are at least three numbers, multiply the first by 26 and add it to the second. ``` 1+ $.& ``` Convert everything to decimal. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~50~~ 48+1 = ~~51~~ 49 bytes Uses the `-p` flag. -2 bytes from `m-chrzan`. ``` sub(/\D+/){i=0;$&.bytes{|b|i=26*i+b-64};"#{i} "} ``` [Try it online!](https://tio.run/##KypNqvz/v7g0SUM/xkVbX7M609bAWkVNL6myJLW4uiapJtPWyEwrUztJ18yk1lpJuTqzVkGp9v9/R0MuJ0MDLkdnEy5HR2dzU2MuN0MjYy53H0vjf/kFJZn5ecX/dQsA "Ruby – Try It Online") [Answer] # ><>, 42 Bytes ``` 0i88*-:0(?\$2d**+! $n88*+48*o\ oi:0(?; > ``` [**Try It Online**](https://tio.run/##S8sszvj/3yDTwkJL18pAwz5GxShFS0tbkUslDyikbWKhlR/DlZ8JkrJWUFCw@//fycPMEgA) ### Explanation: ``` 0i88*-:0(?\$2d**+! Read in the Letters part of the input 0 Push an initial 0 to the stack i Read a character of input 88*- Subtract 64 to get from the ascii code to its value ('A'=1,'B'=2 etc.) :0(?\ If the value is less than 0, break out of this loop $2d** Multiply our accumulator by 26 + Add our new number to the accumulator ! don't add a new zero to the stack ``` The above loop will read in the first number of the numbers part (eg. '3' in "AB34") before breaking, and will have already subtracted 64 from it, so the next bit of code has to deal with that ``` $n88*+48*o\ Output a space, and prepare to output the first number we read in during the previous loop \ Loop round to the left end of this line $n Output the value of the letters part as a number 88*+ Add the 64 we subtracted from the first number 48*o Output a space \ Enter the next loop ``` This loop starts by outputting a character which will either be the 1st character read in by the first loop, or the character read in by the previous iteration of this loop. ``` oi:0(?; > Output the numbers part, by just echoing it > Loop round to the start of the line o Output the character i Read in the next character :0(?; If the value read in was less than 0, terminate ``` [Answer] # Ruby, ~~64~~ ~~61~~ 59 bytes ``` ->s{s.sub(/\D+/){"#{$&.bytes.reduce(0){|t,b|t*26+b-64}} "}} ``` Saved 2 bytes thanks to Value Ink. [Answer] # Excel-VBA Immediate window, ~~44~~ 45 Bytes (~~36~~ 35) ``` Set v=Range([A1]):?trim(v.Column &" "&v.Row); ``` 1 byte added to suppress the trailing newline --- Or for 35 with leading whitespace ``` Set v=Range([A1]):?v.Column""&v.Row ``` 1 byte saved thanks to @TaylorScott! Both take input from cell A1, output to the VBE Immediate window [Answer] ## Lua, 127 Bytes Some nice string manipulations going there, I'm using some function that are usually never used while golfing in lua :D. The best way to golf this would be to find an other way to iterate over the column part of the input while being able to retain the position of each letter. I didn't ^^'. [Try it online!](https://tio.run/##Pc1LCsIwEADQfU5RRoSMpkMj0kUgC3HVY6QkaiA2ZZoqnj5@Fu4fvLS6WgdLRMkO5rqso4StBwWAhsMj8BIksu3EJXMTrVabJHwWbHkvk/nyqCKa8VU@ru2PuLu7cqM5P@WhV7HVGCYvZo5TkUwEDRD9H/d7sNZ6OuvuDQ "Lua – Try It Online") ``` I=...l=I:gsub("%d",""):reverse()r=0 for i=1,#l do r=r+(l:sub(i,i):byte()-64)*math.pow(26,i-1)end print(r.." "..I:gsub("%a","")) ``` ### Explanation ``` I=... -- shorthand for the input l=I:gsub("%d","") -- shorthand for the column part :reverse() -- letters are put in reverse order to calculate their weight r=0 -- column number for i=1,#l -- iterate over the letters of the input do r=r+ -- add to the column number (l:sub(i,i):byte()-64)-- the byte value of the current letter minus 64 (A=1 this way) *math.pow(26,i-1) -- then apply its weight in base 26 end print(r -- output the column number .." " -- a space ..I:gsub("%a","")) -- and the row number ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2) `ṡ`, 9 bytes ``` ⌊ẆhøA₄β?⌊ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyLhuaEiLCIiLCLijIrhuoZow7hB4oKEzrI/4oyKIiwiIiwiQUMzOCJd) whoa [Answer] # [JavaScript (Node.js)](https://nodejs.org), 67 bytes ``` x=>(a=0,b=x.replace(/\D/g,u=>(a=a*26+parseInt(u,36)-9,'')),a+' '+b) ``` [Try it online!](https://tio.run/##Hc3NDoIgAADgO0/RDUjEv7K5RhvZam09ggfQ0NkImGjz7al1/g7fS36k76bRzbGxTxV6FlZ2QpKlpGUrnZTTslMoaS7JQJa/yG1eRk5OXt3NjBZSlDiuCIQYExnBDYxaHI6CZ@CcpYDXO8B5fdgX4JrlBbg9qkJQ7/Q4i8YI@pYO/cLOGm@1otoOqEcrxjh8AQ "JavaScript (Node.js) – Try It Online") Lots of code formatting ]
[Question] [ **Not a dupe to [this](https://codegolf.stackexchange.com/questions/63834/count-up-forever). That question asks *specifically* for counting up forever, while this question allows many other approaches.** Write a program or function which, given infinite time and memory, would print an infinite non-periodic output. ## Clarifications * 'Infinite' means the solution keeps outputting something without any further inputs or operations after successfully started the program or function. * 'Non-periodic' means the output has **no** possibility of eventually repeating the same section forever (regardless of how long that period is). An example of a valid solution would be printing the digits of an irrational number. * Random solutions would **not** count unless you can prove that it fits the requirements. Date/time-based solutions may also be invalid if they are not stored with arbitrary precision. ## Winner Shortest code (in bytes) wins. [Answer] # [Python 2](https://docs.python.org/2/), 23 bytes ``` while 1:print id;id=id, ``` [Try it online!](https://tio.run/nexus/python2#@1@ekZmTqmBoVVCUmVeikJlinZlim5mi8/8/AA "Python 2 – TIO Nexus") Prints ``` <built-in function id> (<built-in function id>,) ((<built-in function id>,),) (((<built-in function id>,),),) ((((<built-in function id>,),),),) ``` and so on. Starts with the built-in function `id`, the shortest pre-initialized variable name, and repeatedly turns it into a tuple of itself. In Python 3, this solution is one byte longer because of `print()`, but the byte can be recovered from `print` outputting `None`: ``` while 1:id=print(id),id ``` or ``` while[print(id)]:id=id, ``` [Answer] ## [Hexagony](https://github.com/m-ender/hexagony), 2 bytes ``` (! ``` [Try it online!](https://tio.run/nexus/hexagony#@6@h@P8/AA "Hexagony – TIO Nexus") The unfolded source code looks like: ``` ( ! . . . . . ``` This just runs these two commands in a loop, which are decrement (`(`) and print (`!`). Hence, the output is: ``` -1-2-3-4-5-6-7-8-9-10-11-12... ``` We need to use decrement instead of increment to ensure that the program loops back to the first line (if the memory value was positive, Hexagony would loop between then second and third line, and end up in an infinite loop without doing anything). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes ``` ẉ⊥ ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9wV@ejrqX//wMA "Brachylog – TIO Nexus") This prints all integers ordered by magnitude. This will never overflow and print already seen integers since Brachylog uses unbounded integers by default. ### Explanation ``` ẉ Writeln: the Input is anything, so we label it implicitely to an integer and write it ⊥ False: backtrack and try another integer value for the Input ``` [Answer] ## [Labyrinth](https://github.com/m-ender/labyrinth), 3 bytes ``` #:! ``` [Try it online!](https://tio.run/nexus/labyrinth#@69spfj/PwA "Labyrinth – TIO Nexus") Prints all non-negative even integers without separator: ``` 024681012141618202224262830323436384042... ``` The IP bounces back and forth on the code, so this is really `#:!:` in a loop: ``` # Push stack depth. : Duplicate. ! Print. : Duplicate. ``` A bunch of alternatives: ``` :#! Prints all positive odd integers. :)! Prints all positive integers. ):! Prints all positive integers. :(! Prints all negative integers. (:! Prints all negative integers. ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + [coreutils](https://www.gnu.org/software/coreutils/), 6 bytes ``` yes|sh ``` [Try it online!](https://tio.run/##S0oszvj/vzK1uAZEAwA "Bash – Try It Online") ## Explanation `yes` produces an infinite stream of newline-separated `y`s. `|` sends the output to `sh`, which tries to execute it line by line as it arrives. The first `y` is not valid code, so it produces the error message `sh: line 1: y: command not found`. The second `y` is also invalid, but it's part of the same stream (the output from `yes`), so it's treated as "line 2", making the error message `sh: line 2: y: command not found`. This continues forever, producing a different error message each time: ``` sh: line 1: y: command not found sh: line 2: y: command not found sh: line 3: y: command not found sh: line 4: y: command not found sh: line 5: y: command not found ... ``` [Answer] # Haskell - 10 bytes ``` print[1..] ``` Although in ghci you could just type [1..] and that would automatically start printing. [Answer] ## ><>, 3 bytes `l:n` Outputs a stream of numbers, counting from 0. I believe incrementing numbers don't cycle... Explanation: `l` pushes stack length onto stack `:` duplicates top stack value on top of stack `n` outputs value as number When the line is finished it goes back to the beginning, so it does it again, but now the stack is longer... [online](https://fishlanguage.com/playground/CTsNwWM8GLDLtceft) [Answer] # [Befunge](https://github.com/catseye/Befunge-93), 4 bytes ``` 1+:. ``` [Try it online!](https://tio.run/nexus/befunge#@2@obaX3/z8A "Befunge – TIO Nexus") In Befunge, the stack is bottomless and has infinite zeros. That said: `1+` adds one to the top of the stack `:` duplicates the top of the stack `.` prints the ascii value of the top of the stack as a number And it continues infinitely, because there's no `@` to stop execution. This is actually one of those problems made easier to solve by the way befunge works... weird. [Answer] # PHP, 20 bytes ``` for(;;)echo$argc.=0; ``` Outputs this: ``` 101001000100001000001000000100000001000000001000000000... ``` If command line arguments are provided, the output will be different, but still non-periodic. As far as I understand the documentation, the language itself doesn't restrict length of strings. [Answer] # JavaScript, 26 22 20 bytes ``` for(;;)alert(Date()) ``` (Warning: it's evil) [Answer] # [7](https://esolangs.org/wiki/7), 2 bytes The characters that make up this program are: ``` 240223 ``` When viewing the file in an editor, it'll likely try to interpret it as ASCII, in which case it looks like this: ``` P$ ``` [Try it online!](https://tio.run/nexus/7#@29kYmBkZPz/PwA "7 – TIO Nexus") The program takes input. I've assumed here that the input is at EOF; if you provide it input, it's possible it will crash. ## Explanation **Zeroth iteration** ``` 240223 240223 Append **240223** to the top stack element ``` The entire program here is passive, so it'll append an active version of itself to the top stack element (which is initially empty). The program's in an implicit loop, which evaluates the top stack element (while leaving it on the stack) every iteration. So the active version will run. (Pretty much all 7 programs start like this.) **First iteration** ``` **240223** **2** Copy the top stack element **40** Escape the second stack element, swapping it to the top **2** Copy the top stack element **23** Output the top stack element ``` Before the output command, the stack contains two copies of `240223` (i.e. passive). The top one gets output (with no observable effect other than selecting output format 2, "numbers"), the one below stays and becomes the program for the next iteration. **Second iteration** ``` 240223 240223 Append **240223** to the top stack element ``` The same as the zeroth iteration, right? Not quite; the stack had different contents. The stack is now **`240223`** below `240223**240223**`. **Third iteration** ``` 240223**240223** 240223 Append **240223** to the top stack element **2** Copy the top stack element **40** Escape the second stack element, swapping it to the top **2** Copy the top stack element **23** Output the top stack element ``` This outputs a stack element that has three more 6s-and-0s than it does 7s-and-1s. Output format 2 interprets this as a request to *input* a number. We read EOF, with the consequence that the next element on the stack is reduced to a zero-length string. However, due to a bug (which seems mildly useful and may be promoted to a feature?), this only happens *after* it starts executing. The stack once again has two elements, **`240223`** below `240223**240223240223**`, but the escaped version of this top element, `**7**240223**6**240223240223`, is now executing. **Fourth iteration** ``` **7**240223**6**240223240223 **7**240223**6**240223240223 Append 240223**240223240223** to the top of stack ``` The top of stack was a zero-length string, so we're basically just unescaping the program that ended up there. **Fifth iteration** ``` 240223**240223240223** 240223 Append **240223** to the top stack element **2** Copy the top stack element **40** Escape the second stack element, swapping it to the top **2** Copy the top stack element **23** Output the top stack element **2** Copy the top stack element **40** Escape the second stack element, swapping it to the top **2** Copy the top stack element **23** Output the top stack element ``` This is very similar to the third iteration. There are two changes, though. First, there are now 4 more 0s-and-6s than there are 1s-and-7s, so we'll try to input a character from standard input rather than a number. We still get EOF, though, and still end up reducing the top of stack to a zero-length string as a result. Next, there's code running *after* the reduction, so the next iteration doesn't start immediately. Rather, we do a bunch of operations on that zero-length element, ending up with three zero-length elements. We output one, the other two disappear (because it's the end of an iteration), and we end up basically where we were at the end of the third iteration. **Sixth iteration** The program we copy from the top of stack is now `240223**240223240223240223**`. Everything works like in the previous iteration until we reach the first output instruction (the first **`23`**). This now has five more 0s-and-6s than there are 1s-and-7s, so it sets a mode in which the next output instruction will be interpretted as a request to change the output format. This also leads to a notable change in behaviour; as there was no input request, we didn't read EOF, and thus didn't trigger the consequence of reading EOF (the new top stack element being blanked), and as such the escaped version of the original stack element stays rather than being removed. This means that the next **`2402`** is no longer a no-op, creating two escaped copies of the escaped stack element (i.e. they're now double-escaped). We output one, setting the output format to 7 ("same as the input"); this output format has no I/O commands, and no commands to change the format, so we'll stay in it for the rest of the program. We also output `724022362402232402232402232402236` (in the same encoding as the input) to standard output. Anyway, it's fairly clear what the program's going to be doing from this point onwards: it's a combination of appending various number of copies of variously escaped `240223` to the top of the stack, escaping the top of the stack, and outputting copies of the top of the stack. From this point onwards, the top stack element is never cleared (because we never read EOF), so it just grows and grows and grows. The periodic escaping ensures that the output never repeats (because it means that each iteration, the first output starts with at least one more `7` than it did on the previous iteration). [Answer] # Brainfuck, 13 Bytes, assuming no upperbound but output mod 256 ``` +[[->+++.<]>] ``` output char code 2 2 4 6 2 4 6 8 10 12 14 16 18 ... sorry that the old code print loop 0 2 4 6 ... 254, # Brainfuck, ~~13~~ 12 Bytes (-1 from Jo King) ``` +[[>.]<[<]+] ``` output char code 0 1 0 1 1 0 1 1 1 0 ... [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ‘Ȯß ``` **[Try it online!](https://tio.run/nexus/jelly#@/@oYcaJdYfn//8PAA "Jelly – TIO Nexus")** - truncates the output and raises an error, but will go far longer locally (until memory runs out). With an implicit input of zero this program consists of a single link which increments, `‘`, prints `Ȯ`, and then calls itself with the new value, `ß`. [Answer] # MATL, 4 bytes ``` `@tD ``` This solution creates a `while` loop which pushes the index of the loop to the stack, duplicates it, prints the value and then checks that the loop index is non-zero to repeat again. [Try it Online!](https://tio.run/nexus/matl#@5/g4BLy/z8A) [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 13 bytes ``` 2{22.`2=2p2}: ``` There are many twos in the output, separated by progressively more sparce newlines. ``` 2{22.`2=2p2}: 2 # Push a two to the stack { }: # While the top of the stack is truthy 22. # Push the value of "2" twice, and concatenate them together. `2= # Set the value of "2" to this. 2p # Print the value of "2" 2 # And push the value of "2" ``` Which prints 2^n 2s followed by a newline for each iteration. [Try it online!](https://tio.run/nexus/rprogn-2#@29UbWSkl2Bka1RgVGv1/z8A "RProgN 2 – TIO Nexus") [Answer] # [APL (Dyalog APL)](https://www.dyalog.com/), 8 bytes ``` {∇⎕←0⍵}1 ``` `{`emsp;an anonymous function...  `∇` recurse on  `⎕ ←` output to STDOUT  `0 ⍵` the two element list consisting of a zero and the argument `}` applied to the number one This outputs (on separate lines) `[0,1]`, `[0,[0,1]]`, `[0,[0,[0,1]]]`, etc. [Answer] # Processing, ~~30~~ 29 bytes *1 byte saved thanks to QwerpDerp for using `millis()` instead of `frameRate`* ``` void draw(){print(millis());} ``` Continuously prints the number of milliseconds since the start of the program. Sample output: ``` 3573743914054244404574734925085205375585755916... ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~83~~ 81 bytes ``` *p,*t,*g;f(){for(t=p=malloc(1),g=--t;t<p?putchar(55):(t=g,*p++,putchar(9));t++);} ``` First allocating a pointer on the heap, the function then counts off into the memory addresses ahead until a segfault from `*p++`, therefore is limited by the amount of memory in the system rather than the data types used which would otherwise eventually overflow and repeat the series. Given infinite memory with infinite addressing capability it would go on forever. [Try it online!](https://tio.run/nexus/c-gcc#NY07DoNADAV7TuHS9pqCgiJxVjnLCokNEh8LOUVAnH0DBd3TzEivsAm7cNYeae@XFT1anNI4Lh02JDnWtau/7G1f7z5pxbal5xllYQtBbvogUg@B9CjD7DClYcZrbAKXZ/4R7BUAnDdaHeUP "C (gcc) – TIO Nexus") [Answer] ## Bourne Shell, 11 bytes ``` yes date|sh ``` [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), 4 bytes (CP437) ``` ¼,¡∞ ``` Prints the counter variable, increments it, and goes into an infinite loop! Simple enough. **EDIT** (Mar 1 '17): While I was in the process of doing some other updates (after I posted this answer), I changed the behavior of `∞`. The updated answer would be `∞^,`. [Answer] # "modern" [DC](https://rosettacode.org/wiki/Category:Dc), 9 bytes Infinite memory? Then a continuously growing stack is ok? ]:-) ``` [zprdx]dx ``` Commented: ``` [ # start string constant z # push current stack depth p # print TOS without removing r # swap TOS and NOS d # duplicate TOS x # pop TOS and interprete it ] # end string constant, push it d # duplicate TOS x # pop TOS and interprete it ``` Because of using the `r` command, [this](https://tio.run/nexus/dc#@x9dVVCUUhGbUvH/PwA) will not run on some anicent DCs. [Answer] ## Ruby, ~~21~~ 12 bytes ``` loop{p$.+=1} ``` Print all natural numbers. As far as I understand the problem description, this should be ok. [Answer] # PHP, 21 bytes ``` for(;;)echo uniqid(); ``` Usage: `php -r "for(;;)echo uniqid();"` Outputs unique IDs based on the current time in microseconds: `58b3e065e4b4c58b3e065e4b6358b3e065e4b7b58b3e065e4b9458b3e065e4bac58b3e065e4bc458b3e065e4bdc58b3e065e4bf558b3e065e4c0e58b3e065e4c2658b3e065e4c3e58b3e065e4c5658b3e065e4c6f58b3e065e4c8758b3e065e4c9f...` as a continuous sequence of: `58b3e09390617` `58b3e09390651` `58b3e0939068a` `58b3e093906c3` `58b3e093906fc` `...` [Answer] # [Perl 6](https://perl6.org), 11 bytes ``` say($++)xx* ``` Prints the natural numbers. [Try it online!](https://tio.run/nexus/perl6#@1@cWKmhoq2tWVGh9f8/AA "Perl 6 – TIO Nexus") [Answer] # Python 2, 24 bytes Prints 9 times each power of 2. ``` n=9 while 1:print n;n+=n ``` [**Try it online**](https://tio.run/nexus/python2#@59na8lVnpGZk6pgaFVQlJlXopBnnadtm/f/PwA) [Answer] # Batch, 7 bytes ``` time|%0 ``` Or: ``` %random%|%0 ``` [Answer] # Powershell, 19 Bytes Boring counting up answer. ``` for(){[bigint]$i++} ``` Improved version of answer from [Count Up Forever](https://codegolf.stackexchange.com/a/63877/59735) [Answer] # [stacked](https://github.com/ConorOBrien-Foxx/stacked), 9 bytes ``` $out0 ani ``` [Try it online!](https://tio.run/nexus/stacked#@6@SX1pioJCYl/n/PwA "stacked – TIO Nexus") Similar to my [Count up forever](https://codegolf.stackexchange.com/a/111595/31957) answer, this outputs natural numbers from `0`, the counter. [Answer] # TI-Basic, 11 Bytes ``` While 1 Ans+1 Disp Ans End ``` [Answer] ## [GNU sed](https://en.wikipedia.org/wiki/Sed), 13 bytes This is an arbitrary precision counter in unary. That's a fancy way of saying that I append one `0` to the pattern space and print it on every iteration (infinite loop). ``` : s:0*:&0:p b ``` After some time this would normally run into a memory allocation error and stop printing, because it can't store anymore the ever growing pattern space. That's not a problem for this challenge, since the memory is assumed to be infinite. [**Try it online!**](https://tio.run/nexus/sed#@2/FVWxloGWlZmBVwJX0/z8A) (this interpreter further limits the available resources by design) **Output preview:** only the first 5 lines ``` me@LCARS:/PPCG$ echo | sed -f infinite_non_periodic.sed | head -5 0 00 000 0000 00000 ``` ]
[Question] [ Your task: write a program/function that when given a string containing only ASCII characters, outputs/returns the string in reverse-ish. **Example:** 1) Input ``` Hello, World! ``` 2) Number unique characters in input. (Input string separated by pipes (`|`) for readability) ``` H|e|l|l|o|,| |W|o|r|l|d|! 1 2 3 4 5 6 7 8 9 10 ``` 3) For duplicate characters, find the first occurrence of that character and number the duplicate character with the same number as the first. ``` H|e|l|l|o|,| |W|o|r|l|d|! 1 2 3 3 4 5 6 7 4 8 3 9 10 ``` 4) Reverse the string, but not the numbers. ``` !|d|l|r|o|W| |,|o|l|l|e|H 1 2 3 3 4 5 6 7 4 8 3 9 10 ``` 5) Delete the characters above repeat numbers. (Deleted characters represented with an asterisk.) ``` !|d|l|*|o|W| |,|*|l|*|e|H 1 2 3 3 4 5 6 7 4 8 3 9 10 ``` 6) Replace the deleted characters with the character that appears over the first occurrence of the number that the deleted character is over. ``` !|d|l|l|o|W| |,|o|l|l|e|H 1 2 3 3 4 5 6 7 4 8 3 9 10 ``` 7) Output ``` !dlloW ,olleH ``` **Test cases:** ``` Input -> Output "Hello, World!" -> "!dlloW ,olleH" "18464399" -> "99343488" "Code Golf" -> "floG eloC" "abcdefgABCDEFG" -> "GFEDCBAgfedcba" "Mmm, marshmallows" -> "swwllwmhsrwm mms" "15147" -> "74751" ``` [Answer] # [Pyth](https://pyth.readthedocs.io), 1 byte ``` X ``` **[Verify all the test cases.](https://pyth.herokuapp.com/?code=X&input=%22Hello+World%21%22&test_suite=1&test_suite_input=%22Hello+World%21%22%0A%2218464399%22%0A%22Code+Golf%22%0A%22abcdefgABCDEFG%22%0A%22Mmm%2C+marshmallows%22%0A%2215147%22&debug=0)** Pyth has wonderful built-ins :-) --- # [Pyth](https://pyth.readthedocs.io), ~~8~~ 7 bytes ``` sm@_QxQ ``` **[Verify all the test cases.](https://pyth.herokuapp.com/?code=sm%40_QxQ&input=%22Hello+World%21%22&test_suite=1&test_suite_input=%22Hello+World%21%22%0A%2218464399%22%0A%22Code+Golf%22%0A%22abcdefgABCDEFG%22%0A%22Mmm%2C+marshmallows%22%0A%2215147%22&debug=0)** ### How it works This is the more interesting non-built-in approach. ``` sm@_QxQ - Full program. m - Map over the input. @_Q - Get the index in the reversed input. xQ - Of the first index of each character in the String. s - Join the list. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~46~~ 41 bytes -5 bytes thanks to Artyer ``` lambda x:''.join(x[~x.find(n)]for n in x) ``` [Try it online!](https://tio.run/##JY8/b4MwFMT3fooXL4DkRqI4BSJRKSEJWTpnoAwmtgOV/yBMBV361Skm2939Tnrvut@hMfptFtnXLKmqGYVp73nbb9Nqfyr/pq1oNfN1UAnTg4ZWwxTMTre6w2B@BheVJbpyKQ2Gm@kl2yAMaMOW4AbYSMmvqMIlChPyTqI0dTRNIxKRJFlBbhiHwkjhiJCmAC5NviJa3xkXj8MxP50vhePF5XzKj4eH4Oxe07X0qRQGRXvbKLocHa3r2XGUclSN7UcFoJR9/rALSexwTOJdiKpq/wJd3@ph3eO9fngYhL/oYDEefsosW3bO/w "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` iЀịṚ ``` [Try it online!](https://tio.run/##y0rNyan8/z/z8IRHTWse7u5@uHPW////lQxNDU3MlQA "Jelly – Try It Online") [Answer] ## [CJam](https://sourceforge.net/p/cjam), 7 bytes ``` q__W%er ``` [Try it online!](https://tio.run/##S85KzP3/vzA@Plw1tej/f9/cXB2F3MSi4ozcxJyc/PJiAA "CJam – Try It Online") ### Explanation ``` q e# Read all input. __ e# Make two copies. W% e# Reverse the third copy. er e# Transliterate the input, mapping the input to its own reverse. Due e# to the way transliteration works in CJam, if a character in the source e# of the mapping is repeated, all but the first occurrence of that e# character are ignored. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` PGt&m) ``` [Try it online!](https://tio.run/##y00syfn/P8C9RC1X8/9/dY/UnJx8HYXw/KKcFEV1AA "MATL – Try It Online") ``` implicit input P flip Gt paste input back to stack and dup &m alternate ismember, returns duplicated indices ) apply indices to the reversed char array implicit output, print as char ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` R‡ ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/6FHDwv//DU0NTcwB "05AB1E – Try It Online") Explanation: ``` R‡ R Reverse input ‡ Transliterate the input with itself and its reverse (as above) (it only keeps first occurrences) ``` [Answer] ## [Alice](https://github.com/m-ender/alice), 17 bytes ``` /?.R?y.@ \i.!yDo/ ``` [Try it online!](https://tio.run/##S8zJTE79/1/fXi/IvlLPgSsmU0@x0iVf//9/39xcHYXcxKLijNzEnJz88mIA "Alice – Try It Online") ### Explanation ``` /...@ \.../ ``` This is just the usual template for linear code in Ordinal mode. If we unfold this, the actual program simply becomes: ``` i.!?D.?.Ryyo ``` The idea here is similar to that of [my CJam answer](https://codegolf.stackexchange.com/a/144551/8478). Since Alice has no easy way of indexing into strings with integers, it's easiest to replicate this behaviour with transliteration (`y` in Alice). However, Alice's transliteration semantics are a lot more general than CJam's, which means that Alice doesn't just disregard repeated mappings. For example, if we just wanted to transliterate `Mmm, marshmallows` to its reverse, this would represent the following list of mappings: ``` M -> s m -> w m -> o , -> l -> l m -> a a -> m r -> h s -> s h -> r m -> a a -> m l -> l -> , o -> m w -> m s -> M ``` Note that we've got, for example, `m -> w`, `m -> o`, `m -> a` and `m -> a`. CJam would just discard all except the first mapping, but Alice would instead cycle through these. So the first `m` would be mapped to `w`, the second to `o`, the fifth again to `w` and so on. In this case that isn't helpful, because in general if we perform `y` on `AAB` (for some strings `A` and `B`) as we did in CJam, we'll always just get `B` in Alice. So how do we compute a mapping that works for `y` (i.e. how do we discard the repeated mappings manually)? Of course, by using another transliteration. :) The source of the mapping we want has to be the nub of the input (i.e. the deduplicated input). If we apply the above mapping to the nub, then each character only appears once, so we're only making use of the first of each of the repeated mappings. So by transliterating the nub with the input and its reverse, we're effectively simply discarding the duplicated mappings. We can then use the nub and this new result as a mapping for the original input. I'm sure that made sense to someone... So the code: ``` i Read input. ["Mmm, marshmallows"] .! Store a copy on the tape. ?D Push the nub of the input. ["Mmm, marshmallows" "Mm, arshlow"] . Duplicate. ["Mmm, marshmallows" "Mm, arshlow" "Mm, arshlow"] ? Retrieve input. ["Mmm, marshmallows" "Mm, arshlow" "Mm, arshlow" "Mmm, marshmallows"] .R Push its reverse. ["Mmm, marshmallows" "Mm, arshlow" "Mm, arshlow" "Mmm, marshmallows" "swollamhsram ,mmM"] y Transliterate. ["Mmm, marshmallows" "Mm, arshlow" "swllmhsr mm"]] y Transliterate. ["swwllwmhsrwm mms"] o Output. [] ``` [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 7 bytes ``` L@Q_M@s ``` [Try it here!](http://pyke.catbus.co.uk/?code=L%40Q_M%40s&input=%22Mmm%2C+marshmallows%22&warnings=0&hex=0) ``` L@ - Get the index of the first index of each character. Q - Push the input to the stack. _ - Reverse it. M@ - Get the element at (each) position in ^^^ in ^. s - Join. ``` [Answer] # [Perl 5](https://www.perl.org/), 23 + 1 (`-p`) = 24 bytes ``` eval"y/$_/".reverse."/" ``` [Try it online!](https://tio.run/##K0gtyjH9/z@1LDFHqVJfJV5fSa8otSy1qDhVT0lf6f9/39xcHYXcxKLijNzEnJz88uJ/@QUlmfl5xf91CwA "Perl 5 – Try It Online") *Thanks to @MartinEnder's Alice entry for the transliteration idea* [Answer] # JavaScript ES6 50 bytes 3 bytes saved thanks to Justin Mariner ``` s=>[...s].map(x=>s.slice(~s.indexOf(x))[0]).join`` ``` ### Test it: ``` f=s=>s.split``.map(x=>s.slice(~s.indexOf(x))[0]).join`` let inp = document.getElementById("inp"); let out = document.getElementById("out"); function change() { out.innerText = f(inp.value); } change(); ``` ``` <input id="inp" type="text" oninput="change()" value="Hello, World!" /><br> <p id="out"></p> ``` [Answer] # [R](https://www.r-project.org/), ~~68~~ 65 bytes ``` function(s)chartr(paste(rev(el(strsplit(s,''))),collapse=''),s,s) ``` [Verify test cases!](https://tio.run/##FYy7jsIwEEV7vsK4YSwNRUSAjQQFb5qttzaOvYk0xtaMAfH1IXT36BxdHqi/seU3RF@61IqZBLWZD@Fxd6VPdxDjOsuFIVspHtg/wRNIYcnUFxCczYwx6BKRzeK3I6KgmEFszvQGB/rqiRKqv8TUTjXq6qde1YumGechtV5dEgWNStuba3343@0Px9P5MtrfGFFFy9JFO1685FtVy6pea4PBDB8 "R – Try It Online") Ports [Erik's 05AB1E](https://codegolf.stackexchange.com/a/144554/67312) method for 3 bytes less. It wasn't the first, but it was the first one I saw. ## old version: ``` function(s)paste(rev(s<-el(strsplit(s,'')))[match(s,s)],collapse='') ``` [Verify all test cases](https://tio.run/##FYw7D8IgFEZ3fwWyFBI6NNZXooPW1@LsYBwoD9vkUggXNf76itv5cr6cOELfRhm/zJnUeY18YsmmHO1rUKn3A0MeJCbDonkz3JQGGKaIAfrEUBQF5/zuZFJdXsgfQnkAGdBssxpRhgBfphi9GAAvyM1H0FMqaLWqF/Vsvc7YeG3I2YOlglDZKm3sc7dvDsfTOdurc4I4GbFzMic@@H9V86peUi4sH38 "R – Try It Online") -- prints out the vector with the input as names and the output in quotes below. A fairly naive implementation, but I don't think this gets shorter in R (and I look forward to being wrong about that). It's essentially an R port of [Rod's python answer](https://codegolf.stackexchange.com/a/144546/67312) but it was developed independently. Ungolfed explanation: ``` function(s){ s <- el(strsplit(s,'')) # string to characters r <- rev(s) # reverse s idx <- match(s,s) # indices of first matches r <- r[idx] # do the replacement of duplicates paste(r, collapse = "") # characters to string } # implicit return of last evaluated statement ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 98 bytes ``` i,n,a[256];char*f(char*c){n=strlen(c);for(i=n;i>0;i--)a[c[i-1]]=c[n-i];for(;i<n;i++)c[i]=a[c[i]];} ``` [Try it online!](https://tio.run/##fZBPT8IwGIfP66eoMyYdbCIKKCkjUVS8ePYwdyjdur2xa5duSAjhs89SvGjEU98/T355@vKo4Lw7B8XlOsvxrGkzCavLco5@zED/HhlQhZ11EKqQJdfjSUp5yUxPEPfwYKdiS8lcER5QoQ2BWFGYX1GIooAlPIFomKYxT1QEqQMozCzR7wd2l8YOSVO671wg3hhWu2zca4Id8gYDXLGPHLdljo86uNIZCGArmSPvSBocW0pKzcm3TBMEFHm24fWWmLA5dC6M1bXcujSxVrwFrZAniDnuTd6ujcKGoj1CoFobCoocCmYKHjrDni0/D2a1lWkF8S@ad@WHztt/ya1EiN@0kdmZ7xz@woZ3o8noZjo9TSy0vf9SS3EaYSue5aK4f1g8Pj0vT3OvVRXaj5imdCfaNP94jYejW7fed18 "C (gcc) – Try It Online") Argument must be a modifiable string; string is modified in-place. [Answer] # Java 10, ~~100~~ ~~99~~ 97 bytes ``` s->{var a=new char[256];int l=s.length,i=l;for(;i>0;a[s[--i]]=s[l+~i]);for(;i<l;s[i]=a[s[i++]]);} ``` Port of [@LeakyNun's C answer](https://codegolf.stackexchange.com/a/144564/52210). I doubt it can be done shorter without doing something similar in Java. -1 byte thanks to *@ceilingcat*. Input as `char[]` (character-array), and modifies this input instead of returning a new one to save bytes. [Try it here.](https://tio.run/##XZExb8IwEIX3/oorUxAkKi3QojRING3pAgtDhyjDkThg6tjINkEIwV9PncRITSVbsu89@Xt33mGBrtgTvkt/yoShUrBAys93AJRrIjNMCCyrK0AhaAqJk2xRRjGorm@qF7PNUho1TWAJHAIolTs9FygBA06OUPsfR@PYNy8CC5THCN/obZ8GzM@EdHw6ffAxUpHr0jgOVMR6Vxp3rfbKfBXROKgMtNeLjXAp/Qa7P6yZwVp6nS836Z2VlpRvTEjsNtE1UdrpfBHGRB@@hWTpfafOf5MGL8Px8GkyaVdDkRKYC5a1y7hOUpJtZm/h@8fnvK0t8rxvQki1zdHQjuofZzQYPnf@jm4vaYGatJqovU0T9TlERWwndvooJZ7MrG@qp0VolFlVdiyRe4lT@@x9dVKa5J44aM9AuWbcqf6n4VinTXYpfwE) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes ``` Ṙ$Ŀ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZgkxL8iLCIiLCJNbW0sIG1hcnNobWFsbG93cyJd) [Answer] # [Röda](https://github.com/fergusq/roda), 27 bytes ``` f x{x|[x[-1-indexOf(_,x)]]} ``` [Try it online!](https://tio.run/##K8pPSfz/P02horqiJroiWtdQNzMvJbXCP00jXqdCMza29n9uYmaeQjUXZ5qGkkdqTk6@jkJ4flFOiqKSvpKSJlftfwA "Röda – Try It Online") This takes a list of characters as input and returns a stream of characters. Using string datatype (40 bytes): ``` f x{x=x/""x|[x[-1-indexOf(_,x)]]|concat} ``` [Try it online!](https://tio.run/##K8pPSfz/P02horrCtkJfSamiJroiWtdQNzMvJbXCP00jXqdCMza2Jjk/LzmxpPZ/bmJmnkI1F2eahpJHak5Ovo5CeH5RToqikiZX7X8A "Röda – Try It Online") [Answer] # [Arturo](https://arturo-lang.io), 39 bytes ``` $->s->map s'n->s\[dec-size s index s n] ``` [Try it](http://arturo-lang.io/playground?IWyhxE) [Answer] # [Scala](https://www.scala-lang.org/), 61 bytes [Try it online!](https://tio.run/##VZBda8IwFIbv/RVnxYsE2kKxzg9WQavWi8kuxvBi7CK2ae2WNJLEtUP87S792OYC4cB5n3Py5lUxYeQq9u801rAleQHna0JTSFE1fdYyLzIcVC4nRxQHswpVLqNFpg@O51RuXiS0ekpRjDF2@UeLXwHqeW5WISIzNYW5lOTrtVXf8BReilxDAOcemPNJGGiqdEgUVab7mCuNGgUAWRvKmLBhJyRL7iwbrLvENHZgC8boxsL2L@mN/Xt/MJnU0GQy8Af@eHyrhyKhEAmW1kDKRASUifCWIPvYGM/mi3C5Wkc1Fq1Xy3Axz1KaxHtyy245t80XpTpwYgyVqsZVWTJW8oOSJQfgXP3zN/T8UU2N/NHQs3Aj4F5TUiEBobw4nrQN4qRNxfDg/OWCu7DauCRVJ1YnmLYzuNOOJmDNCqSsftMHZwb9Dnagf/6ZC7o3Lp2LS6@@l971Gw) ``` def f(x:String)=x.map(c=>x(x.length-1-x.indexOf(c))).mkString ``` ]
[Question] [ Input a non-empty array of positive (greater than 0) integers. Output another non-empty array of positive integers which *encode* the input array. Output array does not use any numbers used in the input array. ## Rules * Output array should not contain any numbers used in the input array. + Both input and output array may contain duplicate numbers. * Output array may have same length, may be longer, may be shorter than the original one. * It should be able to decode the original array from the output array. + You only need to decode arrays your encoder output. You are not required to implement a one-to-one mapping. + Your decoder may only use any info encoded with numbers in the array and its length. You are not allowed to pass extra info by using other properties of the array (whenever your language support it). + Input array is not sorted. And after decode, you should keep the order of input numbers. `[3, 2, 1]`, and `[1, 2, 3]` are two different arrays. + You may implement your decoder in a different language. * Encoding to a single integer is allowed. If your encoder always encode to a single integer, it may output an integer instead of an array. * The word "array" talked in this post does not include SparseArray (in case your language support it). SparseArray is a special kind of array while there may be gaps between array items. * You may output integers as strings of their decimal representation, if your output integers are too large, or you just prefer so. + Leading zeros in the output strings are allowed. But if there are any, after removing leading zeros or padding more leading zeros, your decoder should still output the original array. Or in the other words, your decoder should not relay on the number of leading zeros to work. * Your program should at least support any array of 100 numbers, while every number in 1~100. + The word "support" here means it should be able to decode the original array without any errors introduced by integer overflow or floating point precision. Your program may however timeout on TIO as long as it will output correct result when given enough resources. * Your encode algorithm should in theory work for any size array with any large numbers. Task is **code-golf the encoder program**. The decoder does not contribute to your byte count. But you should also include the decoder program for a reference, so we can verify it. (Please include it in the post directly, not only in TIO link.) ## Testcases The output array may vary from answer to answer. So we only include input array here. You can verify your answer by checking if `decoder(encoder(input))` may result the original `input`, and `encoder(input)` does not contain any numbers in `input`. ``` [1] [10] [1,2] [2,1] [1,1] [11] [1,11] [11,1] [1,2,3,4,5,6,7,8,9,10] [93,29,47,3,29,84,19,70] ``` [Answer] # [Python](https://docs.python.org/2/), 29 bytes ``` lambda l:[x+max(l)for x in l] ``` [Try it online!](https://tio.run/##VY/BboMwEETv/oqVegF1qwSHhhCJL6EcXHCK1cVGi5PSr6cOWGl7Ga/stzPj8dv3zspF29Z1mqu3hdTw3imgcz0/D2pOKL04hhmMBWqWTm9cpDhQL3eK091OwoPkRoiv3pCG7CyAKmPHq09SAVzFpOArQMATtL1uP8E6cDfNpEa4sBvAsfkwVhGQmbwANU2aPSiixDof2/yJS8Wvle@V/78PZgIOxUOA7h5m8SuhOlQVUHAY2VgPvNRZI@psfxeUQSWuF5vGcZvjg8QD5viKRyzwhCWuu@UBZYl5get5yjErsdg3Pw "Python 2 – Try It Online") Just adds the list maximum to each element, producing values greater than any in the original list. The max of the resulting list is double the original max, so we can invert by lowering each element by half the new max. ``` decoder=lambda r:[x-max(r)//2 for x in r] ``` You can encode with `sum` in place of `max` (with a different decoder), in case `sum` is shorter in your language. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` ÆẸ ``` Decoder: ``` ÆE ``` [Try it online!](https://tio.run/##y0rNyan8//9w28NdO/4fblc43Oaq8Khxj@b//9GGsTrRhgYgQscISBrpgAUgJJQJYUMljHSMdUx0THXMdMx1LHQsdcB6LY11jCx1TMx1wLSFiY6hpY65QSwA "Jelly – Try It Online") A built-in. > > `ÆE`: Compute the array of exponents of z's prime factorization. Includes zero exponents. > > > `ÆẸ`: Inverse of `ÆE`. > > > In other words, `ÆẸ` maps \$[a,b,c,d,\dots]\$ to \$2^a 3^b 5^c 7^d \cdots\$. This trick is also used in the [Gödel numbering](https://en.wikipedia.org/wiki/G%C3%B6del_numbering#G%C3%B6del%27s_encoding). [Answer] # [Haskell](https://www.haskell.org/), 13 bytes ``` map=<<(+).sum ``` [Try it online!](https://tio.run/##LY7NDoIwEITvPsUePECcGkAUSKhv4BNUDgSKEguSFo0Hn91afi6zszvZzHcvzUMqZRt@tV058Dz3dv7evDpby@pZS02crpqdxYfV7dtzAWnfC3dK9rfx7vz3kzNdbDajNKPhQoQFRBhMgshphPmw6GoXvwYRDohxxAkJUmSYf7MDogxxgnmmMcIMSVC4mq5se4fkUC806LYfaUvCa0iBVuBp8TlXPn1J5WzmKuyvalR5M5ZVw/AH "Haskell – Try It Online") Decoder: ``` \r->[x-div(sum r)(1+length r)|x<-r] ``` The code is pointfree for `f l=[x+sum l|x<-l]`, that is `f l=map(+sum l)l`. It increases each element by the sum of the list. This puts each element above the maximum of the original list. The function `sum` was used rather than `maximum` because `sum` is shorter. To invert this, note that the resulting list then has sum equal to that of the original list times one plus its length. So, subtracting this recovers the original list. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes ``` G+ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJHKyIsIiIsIlsxLDIsMyw0LDUsNiw3LDgsOSwxMF0iXQ==) Add the maximum of the input list to each number - just like xnor's python answer. ## Decoder ``` G½vε ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJHwr12zrUiLCIiLCJbMTEsMTIsMTMsMTQsMTUsMTZdIl0=) Get the absolute difference of each item and half of the maximum of the list. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~4~~ 2 bytes -2 bytes from [xnor's answer](https://codegolf.stackexchange.com/a/240598/64121) ``` +Ṁ ``` [Try it online!](https://tio.run/##y0rNyan8/1/74c6G/4fbFYCUx8NdC491KTxq3KP5/3@0YaxOtKEBiNAxApJGOmABCAllQthQCSMdYx0THVMdMx1zHQsdSx2wXktjHSNLHRNzHTBtYaJjaKljbhALAA "Jelly – Try It Online") ``` +Ṁ -- Encoder +Ṁ -- Add the Ṁaximum to each value ṀHạ -- Decoder ṀH -- Halve of the Ṁaximum ạ -- ạbsolute difference between this and each value ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 13 bytes ``` a->2*a*lcm(a) ``` Decoder: ``` a->a/sqrtint(2*lcm(a)) ``` [Try it online!](https://tio.run/##PYxBDoIwEEX3nGLCqiWfCAWFmshFkMUEiCFBrMjG01dowc38mfcm3/A8xA9j@6l9dT3dLMeVijga26dgabveY1oxnz7veRmmRahdyyBgY8avYIorMvPmmML75Nu6K4Xk1/V5477Ocb@Kv3Y@lKC6Tpt1pombUFsoeLbHcezXIRUy5DjjggIlNHyFzqA08gIuyxypRpE0jbQ/ "Pari/GP – Try It Online") Inspired by [@xnor's Python answer](https://codegolf.stackexchange.com/a/240598/9288). `lcm` is shorter than `vecsum` and `vecmax`. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~10~~ 7 bytes ``` 9 , 00 ``` [Try it online!](https://tio.run/##HcoxDoAwDEPRPfdAYvhD0hZKTsA1YGBgYUDcP7QdrGdZfq/vfs6Y5v0IcUFUI0xMxUiSaLVn0B1DIlNYWKlsOO3tmeSUynArmFP1Bw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Inserts `9`s everywhere, then changes commas into double zeros. The decoder is ~~12~~ 13 bytes: ``` 00 , 9(.?) $1 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7w38CAS4fLUkPPXpNLxfD/f0tDSy4gNoCQBpZGQIYRiGEIE4EwkLgwAWRFYC3GIMIERJiCCDMQYQ4iLECEJUQDyCZLiFIjiJgJRBGykAXEGEMIDyhtCQA "Retina 0.8.2 – Try It Online") Link includes encoded test cases. [Answer] # [R](https://www.r-project.org/), 19 bytes Or **[R](https://www.r-project.org/)>=4.1, 12 bytes** by replacing the word `function` with a `\`. ``` function(v)v+max(v) ``` [Try it online!](https://tio.run/##XY5NDoIwFIT3PQVhVeIQpaCl/tzEDSk1YWEhWIiJ8ey1oRhbV28m37zMjFZp2bdqvNjbpKXpek3nbN7cm6e7tlULTM55EuLc4y0jxKiH@cMvIhtD004PkzledZqdhrHTxhEPfGMbonWEi6wZXxxl1i1hNiNvv4BKWjj3lbtAg/0MQ5iKTAwiEj8xlKiwxwEcNQTCMlGCCVQcy60rFALccfsB "R – Try It Online") Port of [@xnor's answer](https://codegolf.stackexchange.com/a/240598/55372). [Answer] # [Ruby](https://www.ruby-lang.org/), 20 bytes ``` ->a{a.map{_1+a.max}} ``` **[Try it online](https://ato.pxeger.com/run?1=XU1LDoIwFNz3FF240PhQKCh0gRchDalSPwkiqaAQ0pO4YaGJB_Ay3EZoWRg38yYz82YeT1lu6_Ytst0lETJ8lcXeCj7Whjd8ceZ5EzvzgVRKGaurEmGivxlLZ5ZEKYTux1Mq8EEUV4Qxl5LXOMTixtPpJJ71Uo6jcS3SLgM8Vv7pDIehKWBIZInZbzsWOQxFjj0AkB4JaMHgSA0fDQIueLCCNfgQAAX9S10gFDwf9A08cCj4NjMrXw)** [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 11 bytes ``` L,bUMVB]G€+ ``` [Try it online!](https://tio.run/##S0xJKSj4/99HJynUN8wp1v1R0xrt/yo5iblJKYkKhnb2XP7//0cbKhgpGCuYKJgqmCmYK1goWCoYGsQCAA "Add++ – Try It Online") Decoder: ``` L,bUM2/VB]dbLGiXz£_€| ``` [Try it online!](https://tio.run/##S0xJKSj4/99HJynU10g/zCk2JcnHPTOi6tDi@EdNa2r@q@Qk5ialJCoY2tlz@f//H21oqGBopGBorGBoomBoqmBopmBormBooWBoqWBkEAsA "Add++ – Try It Online") Basically, a really convoluted way of porting Python - to encode, add the maximum to each item, and to decode, get the absolute value of subtracting half the maximum from each item [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` m+Σ¹ ``` [Try it online!](https://tio.run/##yygtzv7/P1f73OJDO////x9tqGOkY6xjomOqY6ZjrmOhY6ljaBALAA "Husk – Try It Online") [Decoder](https://tio.run/##AToAxf9odXNr///huaDhuYAtwqfDt2/ihpJMzqP///9bNTYsNTcsNTgsNTksNjAsNjEsNjIsNjMsNjQsNjVd) ### Explanation adds sum to each element ``` m+Σ¹ translates to m+Σ⁰⁰ Σ⁰ sum of input m ⁰ for each element in input + add the sum Decoder ṠṀ-§÷o→LΣ ``` alternate 4-byte ``` SM+Σ S hook: call with input and of input M Σ M sum M+Σ map + over input with sum as right argument ``` alternate 6-byte with short decoder ``` J0MR¹Σ [1,2] -> [3, 0, 3, 3] \1/ \ 2 / Decoder mLx0 ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 23 bytes ``` a=>a.map(x=>a.join``+x) ``` [Try it online!](https://tio.run/##PY7LDoIwEEX3/YrubMO1CqJASNn5FcaEBnmUICViiInx2xGouJlzH5PJ1GpQffbQ3XPbmls@FnJUMlHirjr2mkVtdJumzouPpST/apCJM4i@0VnO7A7bbLho8rZ8VrspsspxOecxIRdyca@Yxn6Z8GZ4sNkPq/m5tfRwgI8jTggQIoI9ER3gRfADLAx9uBGCubmKwjzOKquYpjKhb0JpZtreNLloTMkKpjmoJZdSO9PXMfnwePwC "JavaScript (Node.js) – Try It Online") ``` a=>a.map(v=>+v.slice(a.join('').length/(a.length+1))) ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~65~~ ~~57~~ 56 bytes ``` i;s;f(*a,n){for(s=i=0;i<n;)s+=a[i++];for(;n--;)a[n]+=s;} ``` [Try it online!](https://tio.run/##rVPbjtowEH3nK6aRWOXiaHMlSb1pH6p@RchDFMLWFAzCSKVF9NNLJ3YgNrsPFSoSmXjOOTPHE7v123XDXy8XRgVd2m5DuHNabve2KFkZUPbCqSO8sqmY59W0Byj3feo0Fa@9UtDzZfEvIvFc@r/5KPV76YTxA2waxm0HThPAX584dOIQVjWUcArP9JaKhlSg5eIhRyDSsonKRgR0fXrj6tnZkNVz2cjU0/mValYoRg8EYgIJgZTAjEBGICdQIFu3HAaKXyA1QjDJpKp/zVEaYsyQf52GK0VCaaSeqGmoEKuQqJCqMFMhUyFXoSBD@7G2THBVWrBf3XZpS4rzPKxctSSgoZGJRiYam2hsoomJJiaammhqojMTnZloZqKZieYmmptoYaKFiYbB3TgCZ5hgu@XiAO23Zu/is2u/d3s1S2t@/BrNj8UX/KcWAX0dW4MaLwXY/UdgfNEdURbQ4fVFby/M7sKh4HmS58gy6tqMhwULqQMjOTXVYeADyt9DXegQ3jTr9ba1E5c7I7rpNu3up93hEcIDa0C7PUqXtlVZWnLc27Av3BOXxh3NsC6fiukCJ8U@9@P6aOHzULFaK3kei9toQrfQN9o1QmCv8K2xGvxP8KC7G3OlmKsrc3XPlB2VBxmenuQG4EMJXbXSBm3u5cERLO5H8D82@579srfP7uw/YHj0NxVzjszrfem7XSXnyfnyp12um1dx8X/8BQ "C (clang) – Try It Online") Inputs a pointer to an array of positive integers and its length (becasue pointers in C carry no length info). Encodes the array in place by adding the sum of all the array elements to each element. ### Decoder ``` i;s;d(*a,n){for(s=i=0;i<n;)s+=a[i++];for(s/=-~n;n--;)a[n]-=s;} ``` [Try it online!](https://tio.run/##rVPbjtowEH3nK6aRWOXiaHMlSb1pH6p@RchDFMLWFAzCSKVF9NNLJ3YgNrsPFSoSmXjOOTPHE7v123XDXy8XRgVd2G5DuHNabve2KFkZUPbCqSO8sqmY59VUAs@l/5tT7vvUaSpe@6Wg58vyX6SjyOtFE8YPsGkYtx04TQB/feLQiUNY1VDCKTzTWyoaUoGWi4ccgUjLJiobEdD16Y2rZ2dDVs9lI1NP51eqWaEYPRCICSQEUgIzAhmBnECBbN1yGCh@gdQIwSSTqv41R2mIMUP@dRquFAmlkXqipqFCrEKiQqrCTIVMhVyFggztx9oywVVpwX5126UtKc7zsHLVkoCGRiYamWhsorGJJiaamGhqoqmJzkx0ZqKZiWYmmptobqKFiRYmGgZ34wicYYLtlosDtN@avYvPrv3e7dUsrfnxazQ/Fl/wn1oE9HVsDWq8DmD3H4HxRXdEWUCH1xe9vTC7C4eC50meI8uoazMeFiykDozk1FSHgQ8ofw91oUN406zX29ZOXO6M6KbbtLufdodHCA@sAe32KF3aVmVpyXFvw75wT1wadzTDunwqpgucFPvcj@ujhc9DxWqt5HksbqMJ3ULfaNcIgb3Ct8Zq8D/Bg@5uzJVirq7M1T1TdlQeZHh6khuADyV01UobtLmXB0ewuB/B/9jse/bL3j67s/@A4dHfVMw5Mq/3pe92lZwn58ufdrluXsXF//EX "C (clang) – Try It Online") Inputs a pointer to an array of positive integers and its length (becasue pointers in C carry no length info). Decodes the array in place by subtracting from each element the sum of all the elements divided by the length plus one. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 5 bytes ``` I⁺⌈θθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyCntFjDN7EiM7c0V6NQU0ehUFNT0/r//@hoS2MdI0sdE3MdMG1homNoqWNuEBv7X7csBwA "Charcoal – Try It Online") Another port of @xnor's answer. Explanation: ``` θ Input array θ Input array ⌈ Maximum ⁺ Vectorised sum I Cast to string Implicitly print ``` Decoder, 7 bytes: ``` I⁻θ÷⌈θ² ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczr7RYo1BHwTOvxCWzLDMlVcM3sSIztzRXo1BTR8FIEwis//@Pjja0MNMxNDLSMTQx0LGEMs3NdQwNgbSZcWzsf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array ⁻ Vectorised subtract θ Input array ⌈ Maximum ÷ Integer divided by ² Literal integer `2` I Cast to string Implicitly print ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 25 bytes ``` ,[>+>+<<-]>[[>.<-]>-.+<,] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ9pO207bxkY31i462k4PROvqadvoxP7/b2msY2SpY2KuA6YtTHQMLXXMDQA "brainfuck – Try It Online") If you are working on strings. You can simply encode each character by its ASCII value. ``` ,>>>++<,[<<[->+>-<<]>[-<+>]>[>-.[-]<+]>+<,] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fx87OTlvbRifaxiZa107bTtfGJtYuWtdG2w5I2enqRevG2mjH2gFVxP7/b0kusKC1Hgv6uIk@LiPfbRajkUJbaywGodMGeZiRrM8CAA "brainfuck – Try It Online") ]
[Question] [ A positive integer may be represented in an integer base \$1 \le b < \infty\$. When converted to that base it has some number of distinct digits. Any positive integer in base \$1\$ has \$1\$ distinct digit. Most positive integers in base \$2\$ have \$2\$ distinct digits, the exceptions being those of the form \$2^n - 1\$, which only have \$1\$. So the first positive integer that may be represented in an integer base with \$1\$ unique digit is \$1\$ and the first that may be represented with \$2\$ distinct digits is \$2\$. We can say that \$1\$ is the first integer with digital diversity \$1\$ and \$2\$ is the first integer with digital diversity \$2\$. ### Challenge: Given a positive integer \$n\$ return the first positive integer (in base ten\*) that has a digital diversity of \$n\$. \* if your language only supports a specific base (e.g. unary or binary) then you may output in that base. Your algorithm must *work in theory* for any positive integer input: it *may* fail because the precision of your language's integer is too small for the output; but *may not* fail because base conversion is only defined up to some limit. ### Test cases ``` input output 1 1 2 2 3 11 4 75 5 694 6 8345 7 123717 17 49030176097150555672 20 5271200265927977839335179 35 31553934355853606735562426636407089783813301667210139 63 3625251781415299613726919161860178255907794200133329465833974783321623703779312895623049180230543882191649073441 257 87678437238928144977867204156371666030574491195943247606217411725999221158137320290311206746021269051905957869964398955543865645836750532964676103309118517901711628268617642190891105089936701834562621017362909185346834491214407969530898724148629372941508591337423558645926764610261822387781382563338079572769909101879401794746607730261119588219922573912353523976018472514396317057486257150092160745928604277707892487794747938484196105308022626085969393774316283689089561353458798878282422725100360693093282006215082783023264045094700028196975508236300153490495688610733745982183150355962887110565055971546946484175232 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest solution in bytes wins. [**OEIS: A049363**](http://oeis.org/A049363) - also smallest pandigital number in base n. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṖaWḅ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmWYVfhuIU&input=) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmWYVfhuIUKxbzDh-KCrEc&input=&args=MSwgMiwgMywgNCwgNSwgNiwgNywgMTcsIDIwLCAyNSwgNjMsIDI1Nw) ### How it works ``` ṖaWḅ Main link. Argument: n Ṗ Pop; yield [1, 2, 3, ..., n-1]. W Wrap; yield [n]. a Logical AND; yield [n, 2, 3, ..., n-1]. ḅ Convert the result from base n to integer. ``` [Answer] # Python, 40 bytes ``` f=lambda n,k=1:n*(n<k+2)or-~f(n,k+1)*n-k ``` Test it on [Ideone](http://ideone.com/c1Y66V). ### How it works A number with **n** distinct digits must clearly be expressed in base **b ≥ n**. Since our goal is to minimize the number, **b** should also be as small as possible, so **b = n** is the logical choice. That leaves us with arranging the digits **0, …, n-1** to create a number as small as possible, which means the most significant digits must be kept as small as possible. Since the first digit cannot be a **0** in the canonical representation, the smallest number is **(1)(0)(2)...(n-2)(n-1)n = nn-1 + 2nn-3 + … + (n-2)n + (n-1)**, which **f** computes recursively. [Answer] # Python 2, ~~54~~ 46 bytes This is a very *very* ***very**!* fast, iterative solution. ``` n=r=input();k=2 while k<n:r=r*n+k;k+=1 print r ``` [**Try it online**](https://repl.it/Dwfr) There's no recursion, so it works for large input. Here's the result of `n = 17000` (takes 1-2 seconds): <http://pastebin.com/UZjgvUSW> [Answer] ## JavaScript (ES6), 29 bytes ``` f=(b,n=b)=>n>2?f(b,--n)*b+n:b ``` [Answer] # J, 9 bytes ``` #.],2}.i. ``` Based on @Dennis' [method](https://codegolf.stackexchange.com/a/96231/6710). ## Usage ``` f =: #.],2}.i. (,.f"0) >: i. 7 1 1 2 2 3 11 4 75 5 694 6 8345 7 123717 f 17x 49030176097150555672 ``` ## Explanation ``` #.],2}.i. Input: n i. Get range, [0, 1, ..., n-1] 2}. Drop the first 2 values, [2, 3, ...., n-1] ] Get n , Prepend it, [n, 2, 3, ..., n-1] #. Convert that to decimal from a list of base-n digits and return ``` There is an alternative solution based on using the permutation index. Given input *n*, create the list of digits `[0, 1, ..., n]`, and find the permutation using an index of *n*!, and convert that as a list of base-*n* digits. The corresponding solution in J for **12 bytes** ``` #.]{.!A.i.,] Input: n i. Make range [0, 1, ..., n-1] ] Get n , Join, makes [0, 1, ..., n-1, n] ! Factorial of n A. Permutation index using n! into [0, 1, ..., n] ] Get n {. Take the first n values of that permutation (This is to handle the case when n = 1) #. Convert that to decimal from a list of base-n digits and return ``` [Answer] # Ruby, ~~37~~ ~~35~~ 34 bytes ``` ->n{s=n;(2...n).map{|d|s=s*n+d};s} ``` The answer for a given `n` takes the form `10234...(n-1)` in base `n`. Using `n=10` as an example: Start with `n`: `10` Multiply by `n` and add 2: `102` Mutliply by `n` and add 3: `1023` And so on. EDIT: Shorter to use map, it seems. EDIT 2: Thanks for the tip, m-chrzan! [Answer] ## [CJam](http://sourceforge.net/projects/cjam/), 9 bytes ``` ri__,2>+b ``` [Try it online!](http://cjam.tryitonline.net/#code=cmlfXywyPiti&input=MTc) ### Explanation ``` ri e# Read input N. __ e# Make two copies. , e# Turn last copy into range [0 1 2 ... N-1]. 2> e# Discard up to two leading values. + e# Prepend a copy of N. b e# Treat as base-N digits. ``` [Answer] ## CJam (9 bytes) ``` qi_,X2$tb ``` [Online demo](http://cjam.aditsu.net/#code=qi_%2CX2%24tb&input=17) ### Dissection Obviously the smallest number with digital diversity `n` is found by base-converting `[1 0 2 3 ... n-1]` in base `n`. However, note that the base conversion built-in doesn't require the digits to be in the range `0 .. n-1`. ``` qi e# Read integer from stdin _, e# Duplicate and built array [0 1 ... n-1] X2$t e# Set value at index 1 to n b e# Base conversion ``` Note that in the special case `n = 1` we get `1 [0] 1 1 tb` giving `1 [0 1] b` which is `1`. [Answer] ## Haskell, 31 bytes ``` f n=foldl((+).(*n))n[2..n-1] ``` Converts the list `[n,2,3,...,n-1]` to base `n` using Horner's method via folding. A less golfed version of this is given [on the OEIS page](http://oeis.org/A049363). Thanks to nimi for 3 bytes! [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 9 bytes ``` DL¦¨v¹*y+ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=REzCpsKodsK5Knkr&input=MjU3) **Explanation** `n = 4` used for example. ``` D # duplicate input # STACK: 4, 4 L # range(1, a) # STACK: 4, [1,2,3,4] ¦¨ # remove first and last element of list # STACK: 4, [2,3] v # for each y in list ¹* # multiply current stack with input y+ # and add y # STACK, first pass: 4*4+2 = 18 # STACK, second pass: 18*4+3 = 75 ``` [Answer] # C++ - 181 55 Was about to post that real cool solution using `<numeric>`: ``` #import <vector> #import <numeric> using namespace std;int f(int n){vector<int> v(n+1);iota(v.begin(),v.end(),0);swap(v[0],v[1]);return accumulate(v.begin(),v.end()-1,0,[n](int r,int a){return r*n+a;});} ``` and then i realized it is **way** easier: ``` int g(int n){int r=n,j=2;for(;j<n;)r=r*n+j++;return r;} ``` [Answer] # [Perl 6](https://perl6.org), ~~34 31~~ 30 bytes Translated from the Haskell example on [the OEIS page](https://oeis.org/A049363). ``` {(1,0,|(2..^$^n)).reduce: $n×*+*} # 34 {(1,0,|(2..^$^n)).reduce: $n* *+*} # 34 {reduce $^n×*+*,1,0,|(2..^$n)} # 31 {[[&($^n×*+*)]] 1,0,|(2..^$n)} # 31 {reduce $_×*+*,1,0,|(2..^$_)} # 30 ``` * `[&(…)]` turns `…` into an in-place infix operator * The `[…]` shown above turns an infix op into a fold (left or right depending on the operator associativity) ## Expanded: ``` { reduce # declare the blocks only parameter 「$n」 ( the 「^」 twigil ) # declare a WhateverCode lambda that takes two args 「*」 $^n × * + * # a list that always contains at least (1,0) 1, 0, # with a range slipped in |( 2 ..^ $n # range from 2 up-to and excluding 「$n」 # it is empty if $n <= 2 ) } ``` ## Usage: ``` my &code = {reduce $_×*+*,1,0,|(2..^$_)} say code 1; # 1 say code 2; # 2 say code 3; # 11 say code 4; # 75 say code 7; # 123717 # let's see how long it takes to calculate a largish value: my $start-time = now; $_ = code 17000; my $calc-time = now; $_ = ~$_; # 25189207981120412047...86380901260421982999 my $display-time = now; say "It takes only { $calc-time - $start-time } seconds to calculate 17000"; say "but { $display-time - $calc-time } seconds to stringify" # It takes only 1.06527824 seconds to calculate 17000 # but 5.3929017 seconds to stringify ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~84~~ 76 bytes *Thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard) for golfing 8 bytes* ``` (({})<>){(({}[()]))}{}(<{}{}>)((())){{}({<({}[()])><>({})<>}{}{})([][()])}{} ``` [Try it online!](http://brain-flak.tryitonline.net/#code=KCh7fSk8Pil7KCh7fVsoKV0pKX17fSg8e317fT4pKCgoKSkpe3t9KHs8KHt9WygpXSk-PD4oe30pPD59e317fSkoW11bKCldKX17fQ) ## Explanation The program pushes the values from `0` to `n-1` to the stack replaces the top `0` and `1` with `1` and `0`. Then it multiplies the top of the stack by `n` and adds the value below it until there is only one value remaining on the stack. Essentially it finds the digits for the smallest number in base `n` that contains `n` different digits (for `n` > 1 it's always of the form `1023...(n-1)`). It then calculates the number given the digits and the base. ### Annotated Code ``` (({})<>) # Pushes a copy of n to the right stack and switches to right stack {(({}[()]))}{} # While the top of the stack != 0 copy the top of the stack-1 # and push it (<{}{}>) # Discard the top two values (0 and 1 for n > 1) and push 0 ((())) # Push 1 twice (second time so that the loop is works properly) {{} # Loop while stack height > 1 ( # Push... {<({}[()])><>({})<>}{} # The top value of the stack * n {} # Plus the value below the top of the stack ) # End push ([][()])}{} # End loop ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` o1 hU ìU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bzEgaFUg7FU&input=Nw) [Answer] # [Rockstar](https://codewithrockstar.com/), 79 bytes ``` listen to N cast N X's1 let T be N while N-X-1 let X be+1 let T be T*N+X say T ``` [Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in) [Answer] # Julia, 26 bytes ``` \(n,k=n)=k<3?n:n\~-k*n+~-k ``` [Try it online!](http://julia.tryitonline.net/#code=XChuLGs9bik9azwzP246blx-LWsqbit-LWsKCmZvciBuIGluIGJpZyhbMTo3OyBbMTcsIDIwLCAzNSwgNjMsIDI1N11dKQogICAgQHByaW50ZigiJXVcbiV1XG5cbiIsIG4sIFwobikpCmVuZA&input=) [Answer] # [ShapeScript](http://github.com/DennisMitchell/shapescript), 25 bytes ``` _0?1'1+@2?*1?+@'2?2-*!#@# ``` Input is in unary, output is in decimal. [Try it online!](http://shapescript.tryitonline.net/#code=XzA_MScxK0AyPyoxPytAJzI_Mi0qISNAIw&input=MTExMTExMTExMTExMTExMTE) [Answer] # PHP, 78 Bytes ``` for(;$i<$a=$argn;)$s=bcadd($s,bcmul($i<2?1-$i:$i,bcpow($a,$a-1-$i++)));echo$s; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/d753331f5d752c706587d73459ae4b9b5606a377) 60 Bytes works only till n=16 with the precision in the testcases For n=144 INF n=145 NAN ``` for(;$j<$a=$argn;)$t+=($j<2?1-$j:$j)*$a**($a-1-$j++);echo$t; ``` [Answer] # k, 12 bytes Based off of [Dennis' answer](https://codegolf.stackexchange.com/a/96231/42775). ``` {x/x,2+!x-2} ``` [Answer] # JavaScript (ES6), 39 bytes Does not use `=>` ``` function f(b,n){throw f(b,n>2?--n:1)*b} ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` B¹ṙ_1tḣ ``` [Try it online!](https://tio.run/##yygtzv7/3@nQzoc7Z8Ybljzcsfj///@mAA "Husk – Try It Online") ]
[Question] [ It's a three players game, play with one hand. At same time, each player show his hand with 0 to 5 fingers extended. If all player show same kind of (even or odd) number, there is no winner. But else, the player showing different kind the two other win. ``` P l a y e r s A B C Winner Even Even Even No winner Odd Odd Odd No winner Even Odd Odd Player A Odd Even Even Player A Even Odd Even Player B Odd Even Odd Player B Odd Odd Even Player C Even Even Odd Player C ``` The requested tool could use arguments (3 arguments as numeric between 0 and 5) or STDIN (3 values by line, separated by spaces). There is no need to check input: Irregular input could produce unexpected output. Arguments or values on line is given from left to right, from *player A* to *player C*. Output must only contain `A`, `B` or `C` (capitalized) or the string `no one` (in lower case, with a regular space). Tool may work only once or as a filter on all input lines. Shortest code win. [Answer] ## APL (~~34~~ 30) ``` (1⍳⍨+/∘.=⍨2|⎕)⊃'ABC',⊂'no one' ``` Explanation: * `2|⎕`: read a line of input, take the mod-2 of each number (giving a list, i.e. `1 0 1`) * `∘.=⍨`: compare each element in the vector to each element in the vector, giving a matrix * `+/`: sum the rows of the matrix, giving for each element how many elements it was equal to. If there were two the same and one different, we now have a vector like `2 1 2` where the `1` denotes who was different. If they were all the same, we get `3 3 3`. * `1⍳⍨`: find the position of the `1`. If there is no `1`, this returns one more than the length of the vector, in this case `4`. * `⊃'ABC',⊂'no one'`: display the string at the given index. [Answer] # Mathematica, ~~45 43 42~~ 41 chars ``` f="no one"[A,B,C]〚Mod[Tr@#-#,2].{2,1,0}〛& ``` ### Example: ``` f[{0 ,0, 0}] ``` > > no one > > > ``` f[{1, 3, 5}] ``` > > no one > > > ``` f[{2, 3, 5}] ``` > > A > > > ``` f[{2, 3, 4}] ``` > > B > > > --- ### Another solution with ~~43~~ 42 chars: ``` f=Mod[Tr@#-#-1,2].{A,B,C}/._+__->"no one"& ``` [Answer] ## Powershell, 65 ``` param($a,$b,$c)"@ABCCBA@"[$a%2+$b%2*2+$c%2*4]-replace"@","no one" ``` [Answer] # C: 88 characters Unfortunately C, as always, requires quite a lot of unnecessary junk. But still, in which other language can one write `=**++b+**(++` and it actually means something? Quite simply sublime. ``` main(int a,char**b){(a=**++b+**(++b+1)&1|2*(**b+**++b&1))?putchar(a+64):puts("no one");} ``` Simply pass three numbers as arguments, and voilà! [Answer] ## Befunge-98, ~~61 50~~ 45 characters ``` &&&:11p+2%2*\11g+2%+:"@"+#@\#,_0"eno on">:#,_ ``` Uses Fors' clever expression to shave off yet a few more characters. Now single-line (i.e. Unefunge-compatible)! Reads until a game is won; add `@` at the end for a one-shot program. ~~Treats input mod 2 as a binary number, as with my JS answer, then relies on lookup for A-C and falls back to 'no one' if out-of-bounds (by testing if the character is ≥'A', which allows me to use nearby code as data :D).~~ Variation that reads a line of input, produces output, reads a new line of input, etc until a game is decided (i.e. not 'no one'): ``` &2%4*&2%2*&2%++1g:" "#@-#,_0"eno on">:#,_ CBAABC ``` [Answer] ## APL, 30 ``` (1+2=/2|⎕)⊃'BA'('C',⊂'no one') ``` If I am allowed to change system variables by configuration, 2 chars can be shaved off. (Specifically, changing index origin `⎕IO` to 0) **The crucial bit** If we represent all odds the same way and all evens the same way, then a pair-wise equality operation can distinguish all 4 cases: `0 0` for B wins, `0 1` for A wins, etc. **Explanation** `2|⎕` Takes input and mod 2 `2=/` Pair-wise equality `1+` Add 1 for indexing (APL arrays are 1-based by default) `'BA'('C',⊂'no one')` Nested array `⊃` Picks out the correct element from the nested array [Answer] ## GolfScript (31 chars) ``` ~]{1&}%.$1=!?)'no one A B C'n/= ``` Very simple logic: reduce the input modulo 2, then sort a copy. The middle item of the sorted array is in the majority, so look for an index which is different (and hence in the minority). [Answer] # Ruby (function body), 42 chars Assuming 3 numerical arguments `a`, `b`, and `c`: ``` ['zCBAABCz'[a%2*4|b%2*2|c%2],'no one'].min ``` # Ruby (command line tool), 61 chars Version 1 comes in at 62 chars: ``` $><<["zCBAABCz"[$*.reduce(0){|i,n|i*2|n.to_i%2}],'no one'].min ``` But, by piggybacking off of [Darren Stone's answer](https://codegolf.stackexchange.com/a/15562/10826), Version 2 gets down to 61 chars: ``` i=0;$*.map{|n|i+=i+n.to_i%2};$><<['zCBAABCz'[i],'no one'].min ``` [Answer] ## Ruby, 61 chars ``` w=0 $*.map{|p|w+=w+p.to_i%2} $><<%w(no\ one C B A)[w>3?w^7:w] ``` [Answer] # Python 2, 54 ``` f=lambda a,b,c:[['no one','C'],'BA'][(a^b)&1][(a^c)&1] ``` [Answer] ### JavaScript (node), 87 characters ``` p=process.argv;console.log("ABC"[3-Math.min(x=p[2]%2*4+p[3]%2*2+p[4]%2,7-x)]||"no one") ``` To get the ball rolling... expects input as three extra arguments. Makes use of the following pattern for input/output (`/` represents "no-one"): ``` A B C res # ─────────────── 0 0 0 / 0 0 0 1 C 1 0 1 0 B 2 0 1 1 A 3 1 0 0 A 4 1 0 1 B 5 1 1 0 C 6 1 1 1 / 7 ``` [Answer] ### GolfScript, 36 35 33 characters ``` ~]0\{1&\.++}/'no one C B A'n/.$+= ``` Takes input as described from STDIN. You can also test the code [online](http://golfscript.apphb.com/?c=OyIwIDAgMSIKCn5dMFx7MSZcLisrfS8nbm8gb25lCkMKQgpBJ24vLiQrPQ%3D%3D&run=true). [Answer] ## Haskell, 97 ``` main=interact$(["no one","A","B","C"]!!).(\x->min x$7-x).foldr(\y x->x*2+mod y 2)0.map read.words ``` [Answer] Perl, 84 characters. ``` $x=oct"0b".join"",map{$_%2}<>=~/(\d)/g;print"",('no one','C','B','A')[$x>=4?7-$x:$x] ``` * `<>=~/(\d)/g` parses the input line into distinct digits * `map{$_%2` takes this list and computes value mod 2 (even or odd) * `oct"0b".join"",` takes this list of mod values, joins them into a string, appends an octal specifier, and converts the string to a number. Basically what I did was to create a truth table, and then carefully reordered it so I had an inversion operation around `$x == 4`. So if `$x >=4`, we did the inversion `[$x>=4?7-$x:$x]` which we used to index into the array `('no one','C','B','A')` Its not the shortest possible code, but its actually not line noise ... which is remarkable in and of itself. Perl: 74 characters + 3 flags = 77, run with `perl -anE '(code)'` ``` s/(\d)\s*/$1%2/eg;$x=oct"0b".$_;say"",("no one","C","B","A")[$x>3?7-$x:$x] ``` This is an improvement, by leveraging autosplit (the -a), say (the -E), and finally figuring out what was wrong with the comparison. [Answer] # Common Lisp, 114 106 70 chars From the three values create a pair representing difference in parity between adjacent elements. Treat that as a binary number to index into result list. ``` (defun f(a b c)(elt'(no_one c a b)(+(mod(- b c)2)(*(mod(- a b)2)2))))) ``` Older algorithm: ``` (defun f(h)(let*((o(mapcar #'oddp h))(p(position 1(mapcar(lambda(x)(count x o))o))))(if p(elt'(a b c)p)"no one"))) ``` [Answer] # Mathematica ~~100 94~~ 89 ``` f=If[(t=Tally[b=Boole@OddQ@#][[-1,2]])==1,{"A","B","C"}[[Position[b,t][[-1,1]]]],"no one"]& ``` --- **Testing** ``` f[{5, 3, 1}] f[{2, 0, 4}] f[{0, 1, 2}] f[{0, 1, 3}] f[{1, 3, 0}] ``` > > "no one" > > "no one" > > "B" > > "A" > > > > [Answer] ## R 67 ``` z="no one";c("A","B","C",z,z)[match(2-sum(x<-scan()%%2),c(x,2,-1))] ``` [Answer] # C, 85 chars ``` main(int j,char**p){puts("C\0A\0B\0no one"+((**++p&1)*2+(**++p&1)^(**++p&1?0:3))*2);} ``` Not as short as my Ruby answer but I'm happy with it, considering the `main` cruft. [Answer] **Fish - 41** ``` :&+2%2*$&+2%+:"@"+!;$!o :?#"eno on"!;ooo< ``` Stole FireFly's befunge answer and ported it to fish because using registers in fish allows us to shave off some characters. Lost a few characters on not having the horizontal if operator though. This takes parameters in through arguments. ``` python fish.py evenodd.fish -v 2 2 2 no one python fish.py evenodd.fish -v 2 3 2 B python fish.py evenodd.fish -v 2 3 3 A python fish.py evenodd.fish -v 3 3 4 C ``` [Answer] # Smalltalk, 128 characters ``` [:c|o:=c collect:[:e|e odd].k:=o collect:[:e|o occurrencesOf:e].u:=k indexOf:1.^(u>0)ifTrue:[#($a $b $c)at:u]ifFalse:['no one']] ``` send `value:` with a collection [Answer] # C ~~101~~ 96 C, probably the most trivial example (some ternary operations): ``` main(int v,char** c){(v=c[1]==c[2]?c[1]==c[3]?0:3:c[1]==c[3]?2:1)?puts("no one"):putchar(v+64);} ``` [Answer] ## JavaScript (ES6) / CoffeeScript, 50 bytes Uses the truth table as per [Firefly's answer](https://codegolf.stackexchange.com/a/15549/22867) but takes a more direct approach in character access: ``` f=(a,b,c)=>'CBAABC'[(a%2*4+b%2*2+c%2)-1]||'no one' // JavaScript ``` ``` f=(a,b,c)->'CBAABC'[(a%2*4+b%2*2+c%2)-1]||'no one' # CoffeeScript ``` ### Demo ``` // Translated into ES5 for browser compatibility f=function(a,b,c){return'CBAABC'[(a%2*4+b%2*2+c%2)-1]||'no one'} //f=(a,b,c)=>'CBAABC'[(a%2*4+b%2*2+c%2)-1]||'no one' for(i=6;i--;) for(j=6;j--;) for(k=6;k--;) O.innerHTML += i + ', ' + j + ', ' + k + ' => ' + f(i,j,k) + "\n" ``` ``` <pre id=O></pre> ``` [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 18 bytes ``` eB"0CBA"ṁi0"5FZᵃ”r ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIjWzF8MHw0I11cbiNbMHwzfDAjXVxuI1sxfDB8MCNdXG4jWzB8Mnw1I11cbiNbMXwwfDAjXVxuI1swfDJ8MyNdXG4jWzB8MHwwI11cbiNbMXwzfDUjXVfGmyIsImVCXCIwQ0JBXCLhuYFpMFwiNUZa4bWD4oCdciIsIiIsIiIsIjMuMS4wIl0=) -11 bytes thanks to [@Aaroneous MIller](https://codegolf.stackexchange.com/users/101522/aaroneous-miller) ### Explanation (Outdated): ``` euL1=["5FZᵃ”|:1Cv[0Ḟ|1Ḟ}kAi­⁡​‎‎⁡⁠⁡‏⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤⁡‏⁠⁠⁠⁠⁠‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁤⁢‏⁠⁠⁠‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁢⁣⁣‏‏​⁡⁠⁡‌­ e ## ‎⁡Calculate every element of list if it's even uL1= ## ‎⁢Contains only even or odd integers? ["5FZᵃ” ## ‎⁣If so, print "no one" 😔 | ## ‎⁤else : ## ‎⁢⁡duplicate 1C ## ‎⁢⁢how many even integers the list has v ## ‎⁢⁣decremented [0Ḟ ## ‎⁢⁤If the number of the even integers is 1, find 0 |1Ḟ} ## ‎⁣⁡if not, find 1 kA ## ‎⁣⁢uppercase alphabet i ## ‎⁣⁣index 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Perl 5](https://www.perl.org/) `-p`, 49 bytes ``` $_=(0,C,B,A,A..C)[oct"0b".s/./$&%2/ger]||"no one" ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lbDQMdZx0nHUcdRT89ZMzo/uUTJIElJr1hfT19FTdVIPz21KLamRikvXyE/L1Xp/38DAwMuAwNDLgNDIG1oyGUI5BsC@YZAvqGh4b/8gpLM/Lzi/7q@pnpANf91C3IA "Perl 5 – Try It Online") Takes input as three digits with no spaces between. [Answer] # Python 3, 115 ``` l=[int(x)%2for x in input().split()];0if[print("ABC"[i])for i,x in enumerate(l)if l.count(x)%2]else print("no one") ``` [Answer] # Python 3, 114 ``` r=[0,3,2,1,1,2,3,0][int("".join(map(str,(int(x)%2for x in input().split()))),2)];print("ABC"[r-1]if r else"no one") ``` [Answer] ## Two different method in two different languages + variations -> 6 answers There are essentially 2 way for this operation: * **`array`** based: Built a binary number of 3 digit, than take answer from an array * **`count`** based: Count even and odd, and look if there is a `count == 1` ### Perl 71 (array based + variation) ``` s/(.)\s*/$1&1/eg;$==oct"0b".$_;$==$=>3?7-$=:$=;say$=?chr 68-$=:"no one" ``` One of *my* shortest perl: * `s/(.)\s*/$1&1/eg;` transform a string like `1 2 3` into `101` * `$==oct"0b".$_;` transform binary to oct (same as dec, under 8) * `$==$=>3?7-$=:$=;` if *`> 3`* oper `7-`. (From there `no one` == 0) * `say$=?chr 68-$=:"no one"` if not `0`, print char from value, else print `no one`. ### Perl 71 (array based) ``` s/(.)\s*/$1&1/eg;$==oct"0b".$_;say@{["no one",qw{A B C}]}[$=>3?7-$=:$=] ``` slightly different in the print step: The output is based on an *'array'*. ### Perl 81 (count based) ``` $c=A;map{$a[$_%2]=$c++;$b[$_%2]++}split;say$b[0]==1?$a[0]:$b[0]==2?$a[1]:"no one" ``` Different meaning: * `$c=A` Initialise a counter *c* with `A`. * `map{$a[$_%2]=$c++;$b[$_%2]++}split` Counter *b* count even and odd, *a* only store which one * `say$b[0]==1?$a[0]:` if *even* counter == 1 ? also print *even* player. * `$b[0]==2?$a[1]:` if *even* counter == 2 ? also print *odd* player. * `:"no one"` else print `no one`. ### Bash 85 (array based) ``` c=$((($1%2)<<2|($2&1)*2+($3%2)));((c>3))&&c=$((7-c));o=("no one" C B A);echo ${o[c]} ``` This is based on my second perl version: * `c=$((($1%2)<<2|($2&1)*2+($3%2)))` make the index pos. + $1%2 transform first arg in binary by using `mod` + $2&1 transform second arg in binary by using `and` + <<2 *shift-to-the-left* is same than `*4` + \*2 *multiply by 2* is same than `<<1`. * `((c>3))&&c=$((7-c))` if c >= 4 then c = 7-c. * `o=()` declare an array * `echo ${o[c]}` based on array ### Bash 133 (count based) ``` a[$1&1]=A;a[$2&1]=B;a[$3&1]=C;((b[$1&1]++));((b[$2&1]++));((b[$3&1]++)) case $b in 1)echo ${a[0]};;2)echo ${a[1]};;*)echo no one;esac ``` * `a[$1&1]=A;a[$2&1]=B;a[$3&1]=C` store player into variable *a[even]* and *a[odd]* * `((b[$1&1]++));((b[$2&1]++));((b[$3&1]++))` count *even/odd* into b. * `case $b in 1) echo ${a[0]}` in case even counter==1 print even player * `2)echo ${a[1]};;` case even counter==2 print odd player * `*)echo no one;esac` else print `no one`. ### Bash 133 (count based) ``` a[$1&1]=A;a[$2&1]=B;a[$3&1]=C;((b[$1&1]++));((b[$2&1]++));((b[$3&1]++)) ((b==1))&&echo ${a[0]}||(((b==2))&&echo ${a[1]}||echo no one) ``` Same version, using bash's condition and command group instead of `case ... esac` [Answer] ## Game Maker Language, 116 My new answer relies heavily on FireFly's formula: ``` a[1]="no one"a[2]='A'a[3]='B'a[4]='C'return a[(3-min(b=argument0 mod 2*4+argument1 mod 2*2+argument2 mod 2,7-b)||1)] ``` The **old** code compiled with uninitialized variables as 0, **183** characters: ``` a=argument0 mod 2b=argument1 mod 2c=argument2 mod 2if((a&&b&&c)||(!a&&!b&&!c))return "no one" else{if((a&&b)||(!a&&!b))return "C" else{if((a&&c)||(!a&&!c))return "B" else return "A"}} ``` **Edit #1** - Whole different code [Answer] # Clojure, 116 ``` (fn[& h](let[a(map #(bit-and % 1)h)](["no one"\A\B\C](+(.indexOf(map(fn[x](reduce +(map #(if(= x %)1 0)a)))a)1)1)))) ``` [Answer] ## vba, 116 ``` Function z(q,r,s) a="A":b="B":c="C":d="no one" z=Array(d,c,b,a,a,b,c,d)((q And 1)*4+(r And 1)*2+(s And 1)) End Function ``` call with `?z(1,2,3)` or assign to a variable with `q=z(1,2,3)`, or even use as a UDF within excel, and use `=z(1,2,3)` in your excel formula ]
[Question] [ [SVG](https://en.wikipedia.org/wiki/SVG) is an XML vector graphics markup language embeddable in web content. Your tips should be at least somewhat specific to SVG. Please post one tip per answer. [Answer] # Know your transforms *Note: this answer talks about the implementation of transforms described in the SVG 1.1 standard, not the CSS standard.* In SVG there are [five main types](https://www.w3.org/TR/SVG11/coords.html#TransformAttribute) of affine transforms that can be used in the `transform` attribute of an object. * `matrix(a,b,c,d,e,f)` is the most general one. It transforms using the affine transformation matrix $$\begin{bmatrix}x'\\y'\end{bmatrix}\leftarrow\begin{bmatrix}a&c\\b&d\end{bmatrix}\begin{bmatrix}x\\y\end{bmatrix}+\begin{bmatrix}e\\f\end{bmatrix}$$ where the coordinate system is the usual "x right, y down" one *in the frame of the deepest enclosing group of the object in question*, which may be the document root. Thus (for example) groups of groups of clones can be arranged in a tree with *one* simple transformation per group to achieve fractal-like effects. * `translate(x,y)` does as you would expect. Note that `translate(x)` works and is equivalent to `translate(x,0)`. * Ditto for `scale(x,y)`, but here `scale(x) = scale(x,x)`. Negative values can be provided, and indeed `scale(-1)` is shorter than `rotate(180)` (see below). * `rotate(d)` means rotation by `d` degrees clockwise about the origin (of the current coordinate frame). `rotate(d,x,y)` means rotation by `d` degrees clockwise about `(x,y)`. * Define `skew(a,b) = matrix(1,tan(b),tan(a),1,0,0)` where `a,b` are again in degrees. This is not in SVG, but `skewX(a) = skew(a,0)` and `skewY(b) = skew(0,b)` are. My experience with [compressing](https://gitlab.com/parclytaxel/Kinross) *My Little Pony: Friendship Is Magic* [cutie marks](https://codegolf.stackexchange.com/q/258642/110698) has taught me that in the most general case using `matrix` is the best. When the transform is only a similarity (angle-preserving) using `rotate(a,b,c)scale(s)` (transforms are applied right-to-left) is usually better, and for yet more special cases composing two of the non-matrix primitives above is usually better, but never three. --- A particularly egregious example of transform compression can be seen in [Fluttershy's cutie mark](https://gitlab.com/parclytaxel/Selwyn/-/blob/master/Cutie%20Marks/Main%20Six%20%2B%20Royalty/Cutie%20Marks%20of%20the%20Mane%20Six.svg) from the relevant section of my [Selwyn](https://gitlab.com/parclytaxel/Selwyn) repository. (The actual file over there duplicates groups because clones don't play well with the path effects of Inkscape; I often use the Envelope Deformation path effect to slightly bend cutie marks to fit the curving flanks of ponies, as can be seen e.g. [here](https://derpibooru.org/images/1810117).) ``` <svg viewBox=-50,-50,100,100><g id=a><path d=m15-33.8c-3.8-4,10.2-9.1-3,16.3,14.4-25.5,18.3-11.7,12.6-12.2 fill=none stroke=#69c8c3 stroke-width=.9 /><path d=m17.1-14.3c12.5,13.7-8.1,27-9.7,4-21.6,12.5-21.9-12.6-3-11.6-11.9-12.7,10-31.6,8.4,2.7,28.5-19.9,19.3,2.4,4.3,4.9z fill=#f3b5cf /><path d=m5.9-7.6c4.4-11.9,8.7-17.7,10-17.1,1.3.6-1,7.8-10,17.1z fill=#69c8c3 /></g><use href=#a transform=matrix(.83,0,0,.83,11.9,37.3) /><use href=#a transform=rotate(-65,22.3,22)scale(.94) /> ``` Here one of the cloned butterflies is transformed using the `rotate()scale()` pattern, but the other clone is not because `matrix(.83,0,0,.83,11.9,37.3)` is shorter than `translate(11.9,37.3)scale(.83)`. [Answer] # Path data: The art of spaces The most curious term in the [BNF grammar](https://www.w3.org/TR/SVG2/paths.html#PathDataBNF) is the production `comma_wsp?`. What it means is: separate numbers with commas and/or whitespace as you wish, or leave them off completely. I'll quote from the spec directly: > > The processing of the EBNF must consume as much of a given EBNF production as possible, stopping at the point when a character is encountered which no longer satisfies the production. Thus, in the string `"M 100-200"`, the first coordinate for the "moveto" consumes the characters "100" and stops upon encountering the minus sign because the minus sign cannot follow a digit in the production of a "coordinate". The result is that the first coordinate will be "100" and the second coordinate will be "-200". > > > Similarly, for the string `"M 0.6.5"`, the first coordinate of the "moveto" consumes the characters "0.6" and stops upon encountering the second decimal point because the production of a "coordinate" only allows one decimal point. The result is that the first coordinate will be "0.6" and the second coordinate will be ".5". > > > Implied here is that adjecent to command letters no space is needed to separate a number (and commas are forbidden). The same rules apply to transform functions, but not to the `viewBox` attribute. Another small note is about writing SVG content inline in a HTML page. It is legal to leave off the surrounding quotes for an attribute, as long as the attribute contains no whitespace. This applies also to path data, but you might be forced to replace spaces with commas ``` <path d="M0,0 1,1" /> == <path d=M0,0,1,1 /> ``` [Answer] # Coordinates: use default (0,0) positioning Transforming the origin is often cheaper than giving explicit coordinates. ``` <svg viewBox=-4,-4,8,8><circle r=3 fill=red ``` [Answer] # Path data: Path fills close automatically If a path has a fill, but no stroke, you can leave out closing the path ``` M0,0H5V5H0V0Z == M0,0H5V5H0V0 == M0,0H5V5H0 for stroke="none" or in a clip-path == M0,0H5V5H0Z for stroke="<paint>" ``` But the automatic closing last segment is alway straight, so if you have a curve as the last command, the repetition of the last coordinate might be inevitable ``` M0,0H5V5Q0,5 0,0Z == M0,0H5V5Q0,5 0,0 ``` ...unless you are able to use another point as the start ``` M0,0H5V5Q0,5 0,0Z == M5,0V5Q0,5 0,0 ``` [Answer] # `<rect>` is never the answer The equivalent path for a rectangle is always shorter than `<rect>` ``` <rect x=5 y=5 width=2 height=1 fill=red /> <path d=M5,5h2v1h-2 fill=red /> ``` If either the width or height is equal to `1` (or otherwise the local line width), `<line>` is shorter when either the x or y coordinate is `0` ``` One coordinate is 0: <rect x=5 width=2 height=1 fill=red /> <path d=M5,0h2v1h-2 fill=red /> <line x1=5 x2=7 stroke=red /> Both coordinates are 0: <rect width=2 height=1 fill=red /> <path d=h2v1h-2 fill=red /> <line x2=2 stroke=red /> ``` [Answer] # Path data: Try out the `A` command Grafical editors tend to approximate elliptical arcs with (sequences of) cubic Bezier curves. For example, Inkscape perfectly understands ``` M0,0A10,15-20 0 1 10,12 ``` But move the handle of the end point, even if you immediately move it back to its original position, and suddenly you will have a cubic Bezier. ``` M 0,0 C 4.3412,1.4378 8.2913,6.1779 10,12 ``` This also happens with quadratic Beziers, with the small difference that the result of the conversion is mathematically equal. Conversions from `C` to `A` or `C` to `Q` on the other hand are impossible most of the time. With reasonable rounding, you might (almost) regain the original length, but you will have to test this manually ``` M0,0C4.3,1.4 8.3,6.2 10,12 ``` But take note: the above arc command has extra opportunities for minification. (This is something that the available tools all miss.) The `large_arc` and `sweep` parameters are **flags**. As they can only be `0` or `1`, no space needs to follow them ``` M0,0A10,15-20 0 1 10,12 == M0,0A10,15-20 0110,12 ``` I know this looks strange, but it is really part of the grammar. Note the `comma_wsp?` ``` elliptical_arc_argument::= number comma_wsp? number comma_wsp? number comma_wsp flag comma_wsp? flag comma_wsp? coordinate_pair ``` [Answer] # Path data: Use automatic tools The [grammar](https://www.w3.org/TR/SVG2/paths.html#PathDataBNF) for the path data microsyntax is especially aimed at a minimal representation, but leaves room for a lot of variants. Because of that, there are tools available that try to automatically minimize the path data. Notably Adobe Illustrator will automatically try to apply minification on SVG export, and the [SVGOMG](https://jakearchibald.github.io/svgomg/) optimization tool contains a module for the same purpose. The latter one is included in a number of online tools, including for example Figma. These tools are a good start, but still fall short in some aspects. [Answer] # Path data: Use `H` and `V` instead of `L` If your path contains straight lines that are horizontal or vertical, the following sequences are equal: ``` M0,0L1,0 == M0,0H1 M0,0L0,1 == M0,0V1 ``` [Answer] # Path data: Concatenate paths Path strings can contain multiple substrings. If they * have the same styles, * are defined in the same userspace coordinate system and * do not overlap, instead of writing two elements, you can just concatenate the path data strings. ``` <path d="M0,0 5,5" /><path d="M10,10 15,15" /> == <path d="M0,0 5,5M10,10 15,15" /> ``` In this case, you could even take advantage of relative commands ``` <path d="M0,0 5,5m5,5 5,5" /> ``` [Answer] # Path data: Don't overestimate relative commands Adobe Illustrator writes all path commands as relative commands, obviously assuming they will lead to shorter strings. While this is true in a lot of cases, most of the time they will lead to nothing, and sometimes even take up extra space ``` M10,10 15,16 == M10,10l5,6 M10,10 25,26 == M10,10l15,16 M25,26 10,10 == M25,26l-15-16 ``` In an extra note, relative commands are relative not to the previous (control) point, but to the previous **stop point**, which might be a further distance away ``` M0,0C0,2 8,10 15,15 != M0,0c0,2 8,8 7,7 WRONG! == M0,0c0,2 8,10 15,15 ``` [Answer] # You have all of unicode There's a built-in library of thousands upon thousands of graphic primitives, which cost you just a couple of bytes each, plus an up-front cost of `<text></text>` In production SVGs, this is horrible practice since you will of course be at the mercy of font rendering and support, and are mixing up graphics and semantics. But good practice has never stopped code golfing! Interesting unicode blocks: * [Arrows](https://www.unicode.org/charts/PDF/U2190.pdf) * [Geometric shapes](https://www.unicode.org/charts/PDF/U25A0.pdf) * [Symbols for legacy computing](https://www.unicode.org/charts/PDF/U1FB00.pdf) * [Dingbats](https://www.unicode.org/charts/PDF/U2700.pdf) * [Miscellaneous Technical](https://www.unicode.org/charts/PDF/U2300.pdf) * [Block elements](https://www.unicode.org/charts/PDF/U2580.pdf) * [Box drawing](https://www.unicode.org/charts/PDF/U2500.pdf) * [Geometric shapes extended](https://www.unicode.org/charts/PDF/U1F780.pdf) [![unicode](https://i.stack.imgur.com/mMOa7m.png)](https://i.stack.imgur.com/mMOa7m.png) [Answer] # Path data: Do not repeat command letters If there are multiple path segments with the same command, you can leave out the letters on the repetitions. ``` M0,0Q0,1 1,1Q1,2 2,2 == M0,0Q0,1 1,1 1,2 2,2 ``` [Answer] # Path data: Mirror symetrical Bezier curves There are special commands that mirror the Bezier control points around a stop coordinate. ``` M0,0Q0,1 1,1 1,2 2,2 2,3 3,3 == M0,0Q0,1 1,1T2,2 3,3 M0,0C0,1 1,2 2,2 3,2 4,3 4,4 == M0,0C0,1 1,2 2,2S4,3 4,4 ``` This even works when mixing quadratic and cubic Beziers: ``` M0,0C0,1 1,2 2,2Q3,2 3,3 == M0,0C0,1 1,2 2,2T3,3 ``` ]
[Question] [ Implement a function or program which raises `x` to the power of `y`. Inputs are 16-bit signed integers. That is, both are in the range [-32768, 32767]. The output should be in the same range. I chose this range because it should make it possible to do exhaustive testing to ensure all edge-cases are covered. If the output can't be represented (it's too negative, too positive or not an integer), do one of the following: * Throw an exception * Print an error message * Return a special value (-1, 0 or any other specific value) Please document what your implementation does in case of error; the behavior should be identical for all error cases — the same exception, message or exceptional value! By definition, 0 to the power of 0 is 1 (not "error"). I am most interested in non-trivial solutions, but if your language has a suitable `pow` function, you are allowed to use it! Test cases: ``` pow(-32768, -32768) = error pow(-32768, -1) = error pow(-32768, 0) = 1 pow(-32768, 1) = -32768 pow(-32768, 2) = error pow(-32768, 32767) = error pow(-100, 100) = error pow(-180, 2) = 32400 pow(-8, 5) = -32768 pow(-3, -2) = error pow(-3, 9) = -19683 pow(-2, 15) = -32768 pow(-1, -999) = -1 pow(-1, -100) = 1 pow(-1, 100) = 1 pow(-1, 999) = -1 pow(0, -100) = error pow(0, -1) = error pow(0, 0) = 1 pow(0, 999) = 0 pow(1, -999) = 1 pow(1, 10000) = 1 pow(1, 9999) = 1 pow(2, 14) = 16384 pow(2, 15) = error pow(8, 5) = error pow(4, 7) = 16384 pow(181, 2) = 32761 pow(182, 2) = error pow(10000, 1) = 10000 ``` [Answer] # [Rust](https://www.rust-lang.org), 68 bytes ``` |x:i16,y:i16|x.checked_pow(match x{1|-1=>y&1,_=>y}.try_into().ok()?) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dZJLTsMwEIYlljnF0AWyJaey05IHVWHDmg3Lqoqq1lGj0gRSVyS0PQmbLuACcAtuAKfBseM2SSELOzOe-eb3eF7fsvVKfIw6ts1nsYjTZOhQh3XGn1ECy0mcIAwbeOACIhi-r0Vk-9-32_wqZi4pynWbd6dzPl3wWfiYPqPlREznkG_Y1mbD6-KCkVBuu67IijBORIpwN10gfIM16-fsa2BFaQYoJ1AQeMEQJzCyQH7I7jme65eVoPZ7lyYcE3Mqj9ipjxK4T5ccMZmBManjCLDqUNu4nuecosrNM-4KxKgsoJZDNPOpSlfkntOnVIMl4bJdz8iR2hsFCQQmlAWu39MEGcL-Q8ir2EFwzNIZpVep0z04OP_ytbI1lxqA0Uabbaa1DuPKcQTRA6cpT4dqHS0lWkgjUBPKy_eN2-35fRVetcTI0T02lgz3WhmVGp_Vn8hzq9q-03j4Sp2ZEmVibI1hozCT1YpnIuRP5yhSQ4vLqR1YO2unR3q_1_sv) Probably not the best language to golf in, but when I saw the description I immediately thought that `checked_pow` would be a perfect built-in for this task. The equivalent doesn't exist in every single other language I know of. Returns `Some(x**y)` if the result is well-defined and fits in the `i16` range, `None` otherwise. ``` |x:i16,y:i16| A closure that takes two i16 values x.checked_pow(...) Raise x to the power of ... (but the power must be u32) The only cases where negative power makes sense are 1 and -1 match x{ so let's match on x and 1|-1=>y&1, if it is 1 or -1, use y modulo 2 (non-negative) _=>y} and simply use y otherwise .try_into() and try converting to u32 (inferred) .ok() and convert the Result<u32,E> to Option<u32> ? and return None immediately if the conversion fails ``` [Answer] # JavaScript (ES7), ~~46~~ 41 bytes *Saved 5 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)* Expects `(x)(y)`. Returns `false` for errors. ``` x=>y=>(q=x**y/(y>=0|x*x<2))==q<<16>>16&&q ``` [Try it online!](https://tio.run/##jZRfa4MwFMXf9yl8KonQeW/UGMHku5TOjo1Spx1DYd/dJUoh5k@dL4Hw45yccxM/Tz@n@3n4@Po@3rq3dr7IeZRqkor0ckzTKSOTkvA7pmPDKJWybxrkSiE/HPr53N3u3bV9vXbv5EKOOau4oI@VJkmWJe0wdMNLBEQDmW8HhAdnQIxAaEPrZoRkNvnM1yzVAsdABNDOALuKKMA2XsCcFQAuqG1LC3uWRjdoK8bTUFJ7klhzkbsk02FKRzJsjtq8ri3ZRTNE2e0E54fbBqPQxi7oB65drBKwL98OCBsudDhwz2Ygd7BeYSGltYqdwtYqdpTMJAs3IfJcFAGw/E8V3sWMgQUlld9ZwBoFbt/E@igq7iUWzAdD1mt51q9gsTab8x8 "JavaScript (Node.js) – Try It Online") ### Commented ``` x => // given x y => // and y ( // q = // compute and save in q: x ** y / // x ** y ( // leave it unchanged if: y >= 0 | // y is non-negative x * x < 2 // or x² is 0 or 1 ) // otherwise: divide by 0, leading to +/- Infinity ) == // test whether the result is invariant by shifting it ... q << 16 >> 16 // ... by 16 positions to the left and then to the right && q // if it is: return q (or return false otherwise) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~30~~ 29 bytes ``` ->x,y{[x**=y][x>>15]rescue p} ``` [Try it online!](https://tio.run/##VVFBDoMgELz3FZwbbHapVjnoRwiH1mh6NDYmGvXtdM0iwonZ3ZlhB8bps7i@dlkzy2U18/1eL9bMTYOFHbtfO3Vi2J25CZM9VfmqpODTyriFSQlJlc5UUh1HyR0EIC54LVYQuMQrvIquUgFqRopkfo4011pfxeUXe5PUkyDiQMgBZwS4mLE1m3kZu/HgWCUPiJcK2@dScFSs8MyGlQrwcOTXso/u3X7FutGXbGIQvSFgd/cH "Ruby – Try It Online") Returns `nil` for errors. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 36 bytes ``` f(x,y)=iferr([z=x^y,z][2+z>>15],t,e) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVFLDoIwEI03aYgLiCWZVpGykIsQNI0RQ0JMQ9AAV3HjxngmPY1th2Jd9c3Me28-vb-UbOvDWT0ez2tXxeK9rMKeDtGurk5tGxbjrt8PdCwLvhrznCUl7egpQu5ncZNKNUMoSZwT1daXTsPABAE5yqYJK0pkFFFSFPGap1tBCb6lTs0Z5kfgB38V7gfmSW2CAWgioI4JcERNSlChW3CHMgu4VmCR6WKWZTOejTxPrUIG_Ajg5oZpZJhZniW6oAJtbNq03zhg53DDbiixWzHBpj2Y4A4ZJ3OTcjq_-7Iv) A port of [Dingus's Ruby answer](https://codegolf.stackexchange.com/a/249693/9288). Returns `e` for errors. [Answer] # [Python 3](https://docs.python.org/3/), 41 bytes ``` lambda x,n:int([x**n][x*x>1and x**n>>15]) ``` [Try it online!](https://tio.run/##bVPLjoMgFF3LVxA3SgcnoNZHE/sjrQtaNWNi1aAzY6fptzuAVmvtBriHe849XKC@tl9V6fR19Rsd@4JdTgmDHS53edmah26zKWMxdnvKygTKcL@n2xj1bdq0DYygYRhAcE3LsX0vwHCYkdhJOa/4co@@x4mE6QJSmUOwwO33CnLyX7YoIUKHkFc4IKOMY7uEDKCQ2K4qCsOrchiGKo@GXuAMmC2qrMhUkMNwzJ2h0c6MrIAlicyc2QVZd5IsmkgmmeF4T2boAxCqz6WHyk8p8lSuCj0ncCdou6z76NuMuBj6SxoN6NRw3xvLBfbqLpWj8ebVGsi3BfJLXfEW8hT8sOI7lW@Op59ZXiasKExDMI@meSBWaMUfCMNpeZQ6KmLWnwQMDNWjRQBkFYcMn/AZ5iUcZHdAa/lVjFoieE3LTelJfgImVOV8QggBLe3Oad0@8nRlXwdAq7n6MHrG8kLHes2aRo8P5yhKYgwzXYrd2B3D2@kujd2Su45A/w8 "Python 3 – Try It Online") TIO link using codes from movatica's answer. This function throw errors when failed. But different errors for different testcases. Code `lambda x,n:[x**n][x**n>>15]` failed when \$\lvert x\rvert=1 \land n<0\$. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 114 bytes ``` ^(-?1,)- $1 /,-/(K` T`-`_`.+[02468]$ ~`-?(.+),(.+) \d.+¶$$.($2*$($1$*)_ A`\d{6} \d+ *_# A`^(-_)?_{32768} (_*)# $.1 ``` [Try it online!](https://tio.run/##PU0xUgMxDOz1jZgZ@05yLOdysasbKgpaOgI2M6FIQ8HQZcKzeAAfOyRfjkLSarW7@nz/On@88XxnH@r8amlidASGYYu0tY8VnirVUn3/HOIwphcD35Um63uH2uB48v3vjzHemtgZa9h0rsB9PZ4u41WuPXRlI7tEFzeVyy4exnQFWzq3AeN5nqlR2AasC68orOCfiStYDBwCSglIQW8J9yJAUhlmoIgsBCPlnNtcxDcPKhsWUoc0BcreLE0p1ybNIHEDtEx9NOABOLH85RS1qxT5Dw "Retina – Try It Online") Link includes test cases modified to run in a reasonable amount of time on TIO. Outputs nothing in case of error. Explanation: ``` ^(-?1,)- $1 ``` Negating the exponent of `1` or `-1` has no effect. ``` /,-/(K` ``` Other negative exponents are an error, otherwise: ``` T`-`_`.+[02468]$ ``` Even exponents always produce a non-negative result. ``` ~`-?(.+),(.+) \d.+¶$$.($2*$($1$*)_ ``` Perform the exponentiation by evaluation of repeated multiplication of `1` by the base. ``` A`\d{6} ``` Values of six or more digits are an error. ``` \d+ *_# ``` Convert to unary, with a marker to make it golfier to convert negative numbers back to decimal. (Conveniently it also makes it possible to distinguish between `0` and error.) ``` A`^(-_)?_{32768} ``` Values of `32768` or `-32769` or greater absolute value are an error. ``` (_*)# $.1 ``` Convert to decimal. [Answer] # [Desmos](https://desmos.com/calculator), ~~86~~ ~~78~~ 77 bytes ``` k=32768 g(n)=\{-k<=n<k\}\{\mod(n,1)=0\} f(a,b)=g(a)g(a^b)g(b)a^b\{b>=0,aa=1\} ``` Returns `undefined` for errors. Not sure if this is fully correct, but it at least passes all the test cases. [Try It On Desmos!](https://www.desmos.com/calculator/vctyq9udgb) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/yi1teei5an) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~43~~ 42 bytes ``` f(a,b){float c=pow(a,b);a=c-(short)c?0:c;} ``` [Try it online!](https://tio.run/##hZJBboMwEEXX4RQjdQMSVGMgYEJpz@K6kCARqLCjLqJcvdTg0oRgNytLfn/@/PGYB3vOh6e65c3po4QXJkTZy@fD61C5zH/3zlXTMQm8@Oy@poucFTxwxaHrpcffcMfzy1C3Eo6sbl0Pzs5GSCZrDrxrhYQRlX3f9VAA5s5G@7uVG0RhmlAf9OlBUWidZxSRBwKcODEyXfvbxyQIH5iPR2rTEETVAtHKKc4dojBWugVV7lt7PDW4PZsPma4kWUKjJQxVJLsvUb5ZNlev2TzNGtmJxQ9v7NZD4D@bRfNS8dpq@ZS3Q5F7oiIYk@vgpqLxBWN9n0Q0XrGtJfbfQtco9iG1OBJKrp8kTe5C0tD@R6fJ5j@ux8wd5zJ886phezEEzfEH "C (gcc) – Try It Online") 1 byte shaved off thanks to ceilingcat. Uses the standard library's [`pow()`](https://en.cppreference.com/w/c/numeric/math/pow), which works on `double`s, which themselves might overflow but will then become ±infinity, and then checking if the result is representable as a `short`. [Answer] # x86-16 machine code, 12 bytes Could save 1 byte by using opcode `CE` ([`into`](https://www.felixcloutier.com/x86/intn:into:int3:int1)) to trap on OF=1, instead of jumping to return from the function. * 32-bit mode: 13 bytes: need a 66 operand-size prefix for `imul si`, rest can use the same machine code bytes, which will give 32-bit operand-size. (So in source you'd write it as `xor eax,eax`/`inc eax`. And `jecxz`. `loop` automatically uses the address-size as the width of CX/ECX/RCX it uses, so the mode-sized width of that register is significant as an arg.) * 64-bit mode, 14 bytes: like 32-bit plus `inc eax` is a 2-byte instruction. (Negative exponents will run nearly 2^64 iterations, so rather impractical, unlike 32-bit bit mode where it only takes a couple seconds when the base is `-1` so it doesn't overflow.) **Fixme: non-competing, doesn't handle `pow(0, -100) = error`, instead returns 0**. Handles any non-zero base with any exponent, or any base with any non-negative exponent. I don't see why it's interesting to have an integer power function allow negative exponents in the first place; unsigned or guaranteed non-negative would make more sense. But I think this is interesting because `0 ** (unsigned)n` with overflow-checked multiply comes so close to handling everything without any special work to deal with negative exponents. NASM listing: address, machine-code (the answer proper), source ``` checked_pow: ; x in SI, n in (ER)CX 00 31C0 xor ax,ax 02 40 inc ax ; mov [e]ax,1 and clear OF 03 E306 jcxz .exit .loop: ;do{ 05 F7EE imul si ; total *= x; 07 7002 jo .exit ; break on signed overflow of the low half (i.e. if cwd would change DX) 09 E2FA loop .loop ;}while(--n!=0); .exit: 0B C3 ret ``` Function taking args in SI and CX, returning an out-of-band error status in OF (the overflow flag), and a value in AX. **The AX value is meaningful if OF=0, otherwise there was overflow.** (So just like an instruction like `add`; the caller can `into` to trap on overflow if they want, or `jo` like this function did.) Widening multiply can't actually lose any bits, so x86's `mul` and [`imul`](https://www.felixcloutier.com/x86/imul) instructions set FLAGS according to whether the low half is the same as the full result. i.e. whether the high half is the zero- or sign-extension of the low half respectively. i.e. after `imul`, if `cwd` to sign-extend AX into DX:AX would change anything. If the result doesn't fit in the low half, CF=OF=1, otherwise they're cleared to zero. Corner case handling: * `x^0` (including 0^0) correctly returns 1, detected with `jcxz`. If not for this, could save 2 bytes * `x^negative` correctly overflows for `|x| > 1`, because **`loop` treats the count as unsigned**. Any negative exponent is treated as an unsigned exponent of at least 32768 (in 16-bit mode; much higher in 32 or 64-bit mode if sign-extended into ECX or RCX as required, instead of zero-extended to be large positive). Any base other than 1, 0, or -1 will result in signed overflow in at most 16 iterations. * `-1^negative` correctly returns 1 or -1, according to the exponent being odd or even. Negative even two's complement signed integers have their low bit clear, so represent even unsigned numbers. To put it another way, `-1^-n = -1^|n|`, and 2's complement absolute value doesn't change the low bit. * `0^negative`: **unhandled**, we just do `0 ** (unsigned)n`, producing zero without overflowing like we should for 1/0. --- Semi-related: [Implement Binary Exponentiation](https://codegolf.stackexchange.com/questions/249463/implement-binary-exponentiation/249723#249723) shows a more efficient algorithm (more bytes, but much faster for large `n`. Of course overflow happens so fast that it's not a big deal except for degenerate cases like `1` and `-1` with huge exponents. Since we don't need performance here, it's of course smaller code to just use the O(n) algorithm. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes ``` NθNη¿∨⁼¹↔謋η⁰IΦ⟦Xθ↔η⟧№…±X⁸¦⁵X⁸¦⁵ι ``` [Try it online!](https://tio.run/##VYw/C8IwEEf3foobLxBBh0KhkxQFQWJxFYe0xCYQE5s/@vHjFZd62@Pe741ahtFLW8rJvXIS@TmogDNrqzVrYvMAvAQ8zFnaiDsO@yF6m5Mim3EQPuFZxYiaw5bRQR@MS9jJmPBobKLMrfefpb7aasbuHDqfSb1KNykUapL0@KkNh3qp/5NZ@m0pTVWXzdt@AQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs nothing in case of error. Explanation: ``` NθNη ``` Input `x` and `y`. ``` ¿∨⁼¹↔謋η⁰ ``` If the absolute value of `x` is `1` or `y` is non-negative, then: ``` IΦ⟦Xθ↔η⟧№…±X⁸¦⁵X⁸¦⁵ι ``` Output `x` to the power of `y` if it lies in the range `[-32768,32768)`. [Answer] # [C (gcc)](https://gcc.gnu.org/), 73 bytes ``` c;f(a,b){c=b?b>0||!(a+1&~2)&&(b=-b)?a*f(a,b-1):0:1;return(short)c-c?0:c;} ``` [Try it online!](https://tio.run/##XVLtcoIwEPzPU1zt6CQUOpdoKx9FHqEv0D8QRJmx0IHYqaP20UsTGTDwa7OX3b3cgXB3QrSPRSkOx2wLb43Miup5v7GsRiayEK0Ic5I4KT2LKI3TDV4uDyR5YotfThcLkkZuSuPEvmlcRgMMWFhv5bEuSbOvakmFK2IMRHhtv6siA0mKUsKPAxpOFM4WwFetSE5mZJ5RsG24YQTz7KOcOVp7ciAnGikNratlae9nUpSk80viLvn61XOgQyUaFdmkgBM@vecTrmHd1xiicuCQwTw0HEr9MrhVa24Qvz9zFTComFL5vm9SM33cS4UMUhwp0ZgT7yOi6Ri36qKHgC67v9RPXBnn/rnGfCsH@qUwj913wDxuEN2h33D3XwCqb9j@ifyQ7JrWfV/@Aw "C (gcc) – Try It Online") (-1 bytes @ceilingcat) (-5 bytes @JuanIgnacioDíaz) Returns `0` for error. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~13~~ 11 bytes ``` S&€hṡ32768^ ``` [Try it online!](https://tio.run/##yygtzv7/P1jtUdOajIc7FxobmZtZxP3//9/ov66hhQEA "Husk – Try It Online") or [try some of the test-cases](https://tio.run/##yygtzv7/cGfjw11dj5oa/werPWpak/Fw50JjI3Mzi7j///9HR@uC2ToQKlYnWtcQwTZAMJFEjRBMEG2OpMgAqANIQBQZWhiAzTCAmGoQGwsA) Outputs `0` as 'special value' for error. ``` ^ # pow without overflow/error checking; ṡ32768 # range from -32768 to 32768 h # without the last element # (so: -32768 to 32767); € # is the pow a member of this range? S& # if yes, output the pow # if no, output falsy = zero ``` [Answer] ## Pascal, 52 B The ISO standard 10206 “Extended Pascal” defines the integer power operator `pow`. NB: [Zero to the power of zero](https://en.wikipedia.org/wiki/Zero_to_the_power_of_zero) causes an error. Provided that the implementation-defined value of the required constant `maxInt` is greater than or equal to `32768` you can wrap `pow` into a function like this: ``` function f(x,y:integer):integer;begin f:=x pow y end ``` The standard specifies that > > It shall be an error if an integer operation or function is not performed according to the mathematical rules for integer arithmetic. > > > An *error* is > > A violation by a program of the requirements of this International Standard that a processor is permitted to leave undetected. > > > Thus *whether* and *how* an overflow is signaled is at the compiler developer’s discretion. ]
[Question] [ You will be given a nested array. Your program has to visualize the array. --- # But.. How? For example, let's assume we have a nested array, like `[["1","2"],[["1","2"],"3"],"4",[[[["5"]]]],"6"]`. This nested array can be visualised as: ``` ->1 ->2 -->1 -->2 ->3 >4 ---->5 >6 ``` --- # Examples ``` Input 1: ["Atom",["Proton",["Up Quark", "Up Quark", "Down Quark"], "Neutron", ["Up Quark", "Down Quark", "Down Quark"], "Electron"]] Output 1: >Atom ->Proton -->Up Quark -->Up Quark -->Down Quark ->Neutron -->Up Quark -->Down Quark -->Down Quark ->Electron Input 2: [["1","2"],["3","4"]] Output 2: ->1 ->2 ->3 ->4 ``` --- # Rules * You may use string (or other types which work like a nested array) as input. * The maximum level of "layers" is 2^32-1. [Answer] # APL, 32 bytes ``` {1=≡⍺:⎕←⍺,⍨⍵↑1↓⍵/'->'⋄⍺∇¨⍵+1}∘0 ``` Test: ``` r ┌────┬─────────────────────────────────────────────────────────────────────────────────────────┐ │Atom│┌──────┬──────────────────────────────┬───────┬────────────────────────────────┬────────┐│ │ ││Proton│┌────────┬────────┬──────────┐│Neutron│┌────────┬──────────┬──────────┐│Electron││ │ ││ ││Up Quark│Up Quark│Down Quark││ ││Up Quark│Down Quark│Down Quark││ ││ │ ││ │└────────┴────────┴──────────┘│ │└────────┴──────────┴──────────┘│ ││ │ │└──────┴──────────────────────────────┴───────┴────────────────────────────────┴────────┘│ └────┴─────────────────────────────────────────────────────────────────────────────────────────┘ {1=≡⍺:⎕←⍺,⍨⍵↑1↓⍵/'->'⋄⍺∇¨⍵+1}∘0 ⊢ r >Atom ->Proton -->Up Quark -->Up Quark -->Down Quark ->Neutron -->Up Quark -->Down Quark -->Down Quark ->Electron ``` Explanation: * `{`...`}∘0`: run the following function with `0` bound to `⍵`: + `1=≡⍺:`: if the input has depth 1 (i.e. an array that does not contain other arrays): - `⍵/'->'`: create a string containing `⍵` `-`s and `⍵` `>`s, - `1↓`: drop the first element, - `⍵↑`: and take the first `⍵` elements. This results in a string containing `⍵-1` dashes and one `>`. - `⍺,⍨`: append the input to it, - `⎕←`: and output that to the screen + `⋄`: otherwise, - `⍺∇¨⍵+1`: add 1 to `⍵` and apply the function to each nested array [Answer] ## Mathematica, ~~58~~ ~~57~~ 56 bytes *Thanks to Greg Martin for saving 1 byte.* *Thanks to ngenisis for saving 1 byte.* ``` MapIndexed[Print[Table["-",Tr[1^#2]-1]<>">",#]&,#,{-1}]& ``` [Answer] # Java 7, ~~153~~ ~~141~~ 114 bytes ``` String r="";<T,S>S c(S s,T o){for(T x:(T[])o)if(x instanceof Object[])c("-"+s,x);else r+=s+">"+x+"\n";return(S)r;} ``` -39 bytes thanks to *@Barteks2x* **Explanation:** ``` String r=""; // Result String outside the method / on class-level <T,S> S c(S s, T o){ // Recursive Method with generic String and Object parameters and String return-type for(T x : (T[])o) // Loop over the input-array if(x instanceof Object[]) // If the current item is an array itself: c("-"+s, x); // Recursive method-call with this array else // Else: r += s+">"+x+"\n"; // Append return-String with stripes String-input, ">", current item, and a new-line // End of loop (implicit / single-line body) return (S)r; // Return the result-String } // End of method ``` **Test code:** [Try it here.](https://tio.run/nexus/java-openjdk#rVHLTsMwELz3K0Z7spUQieeB0EpIcCwPJZxKD2lwUSCxK9uhQVW@vZgQSltIpUr44F3PPmZ3nOaJMRgulpHVmXyG7hOFF7EfDSKkLILxYyi@mCrNYlTnLB6NueLZlFXIpLGJTIWa4nbyIlLrQimjA/KMX/FQ5EZAe33j0YC8yqNHSaEWttSSRVyH9RKYlZM8S@H6WGfeVPaEIslcvBlmNEbCFz24M0SBPqSYY8h42EDRu7GiCFRpg5nLtrlkReD4yW/yvkf6qscmhkMfR6j9v2IttrsCOG69FXSyR7cV2o1v85@iXov@@PX2HGeNrXkrU3MVgXbyuZ/tUm49eU9h6dKqgnYvT3daWSXJ7xCXHma4LxP96jg2/Cs1l@3r96YdXDeitPrfyeg6d/Wffdf1rXv18gM) ``` class M{ String r="";<T,S>S c(S s,T o){for(T x:(T[])o)if(x instanceof Object[])c("-"+s,x);else r+=s+">"+x+"\n";return(S)r;} public static void main(String[] a){ M m = new M(); System.out.println(m.c("", new Object[]{new Object[]{1,2},new Object[]{new Object[]{1,2},3},4,new Object[]{new Object[]{new Object[]{new Object[]{5}}}},6})); m.r = ""; System.out.println(m.c("", new Object[]{"Atom",new Object[]{"Proton",new Object[]{"Up Quark","Up Quark","Down Quark"}},new Object[]{"Neutron",new Object[]{"Up Quark","Up Quark","Down Quark"}},"Electron"})); } } ``` **Output:** ``` ->1 ->2 -->1 -->2 ->3 >4 ---->5 >6 >Atom ->Proton -->Up Quark -->Up Quark -->Down Quark ->Neutron -->Up Quark -->Up Quark -->Down Quark >Electron ``` [Answer] # PHP, ~~77 74~~ 73 bytes 4 bytes saved thanks @manatwork. ``` function f($a,$p=">"){foreach($a as$e)"$e"!=$e?f($e,"-$p"):print"$p$e ";} ``` recursive function, requires PHP 7.1 or newer for the negative string index. `"$e"` is `Array` for arrays; so `"$e"!=$e` is the same as `is_array($e)`. * start with prefix `>` * prepend a `-` to the prefix for each level * print prefix+element+newline for atoms [Answer] # C99 (GCC), 201 187 140 112 109 ``` f(char*a){for(long d=1,j;j=d+=*++a>90?92-*a:0;)if(*a<35){for(;j||*++a^34;)putchar(j?"->"[!--j]:*a);puts("");}} ``` expanded form: ``` f(char*a){ for(long d=1,j;j=d+=*++a>90?92-*a:0;) if(*a<35){ for(;j||*++a^34;)putchar(j?--j?45:62:*a); puts(""); } } ``` This takes a string in the correct format and terminates when finding the last matching `]`. It doesn't use recursion and uses long types to **actually achieve the second rule: 2^32-1 levels**. Most scripting languages have a limited recursion depth or simply crash on stack overflow. I'm not used to golf in C any help is appreciated :) Thanks at bolov for his tips ! Specially thanks to Titus who's always up for a good round of golfing (even in C) ! Another two bytes saved by the fact that we can finish once we match the last `]` and don't need to match a null char. It can be tested at [Wandbox](https://wandbox.org/permlink/W1HQsXyHBdkaiTlQ). [Answer] ## JavaScript (ES6), ~~58~~ 51 bytes ``` f=(a,s='>')=>a.map(e=>e.map?f(e,'-'+s):s+e).join` ` ``` Edit: Saved 7 bytes when @Arnauld pointed out that I could combine my two approaches. [Answer] # PHP, ~~129 123 112 109 95 93~~ 91 bytes ``` for(;a&$c=$argn[++$i];)$c<A?$c<"-"?a&$s?$s=!print"$p>$s ":0:$s.=$c:$p=substr("---$p",$c^i); ``` iterative solution takes string from STDIN: Run with `echo '<input>' | php -nR '<code>'` or [test it online](http://sandbox.onlinephpfunctions.com/code/2b011d0744a2927cd2d74461c201fc68359decd7). **breakdown** ``` for(;a&$c=$argn[++$i];) // loop $c through input characters $c<A // not brackets? ?$c<"-" // comma or quote? ?a&$s?$s=!print"$p>$s\n":0 // if $s not empty, print and clear $s :$s.=$c // digit: append to $s :$p=substr("---$p",$c^i) // prefix plus or minus one "-" ; ``` Happy that the numbers are in quotes; so I only need one action at a time. **ASCII fiddling** ``` char ascii binary/comment " 34 , 44 [ 91 0101 1011 ] 93 0101 1101 A 65 $c<A true for comma, quote and digits - 45 $c<"-" true for comma and quote =0011 1010 -> 50 -> "2" i^"[" 105^91 ^0101 1011 i 105 0110 1001 i^"]" 105^93 ^0101 1101 =0011 0100 -> 52 -> "4" ``` Adding 3 dashes to `$p` and removing 2 for `[`, 4 for `]` adds one for `[` and removes one for `]`. [Answer] # Python 2, 65 64 bytes ``` f=lambda o,d=0:o<''and'\n'.join(f(e,d+1)for e in o)or'-'*d+'>'+o ``` Right now my answer consistently starts with no dashes, so `["foo", "bar"]` is: ``` >foo >bar ``` [Answer] # [Perl 5](https://www.perl.org/), 55 bytes 53 bytes of code + `-nl` flags. ``` /"/?print"-"x~-$v.">$_":/]/?$v--:$v++for/]|\[|".*?"/g ``` [Try it online!](https://tio.run/nexus/perl5#dY49C8IwFEV3f0W9ZrJNg59DB4ugq@jgFB8iUkWsSQlpdSj@9ZqIg0V8w@Ne3jnwet0iM3nAVd4IiLQwF2XB8XhyVsWYsT0SQSJlFecJq8LwpI2geidrxP0U4tw0EnOrb4gk1kZbrXzaFsGmPJgroqCVF/quPo1cXWWlNd4I5D/sV1rm2fFtEXWkxAARhu7wFTHya@wecYOJA8n1Kdq8ozxE9AI "Perl 5 – TIO Nexus") Not optimal for regex because of some edgy cases that could potentially occur (in particular, if an element of the array contains brackets inside). A recursive anonymous function would be barely longer though (61 bytes): ``` sub f{my$v=pop;map{ref?f(@$_,$v+1):"-"x$v.">$_"}@_}sub{f@_,0} ``` [Try it online!](https://tio.run/nexus/perl5#dYyxDoIwGIR3nqL@doAIRldRrImuRgcnJA2aQlBomwpV0/TZEYyLMW53l@@74UAyVba35oQyUz2xXkghwyqVRrFsmbkEUx/r0dSbQQAPrMcQYQqWUNspJiPUn9g2iFwvdPqP/DM5UhW8RhdRcARHDj7KXWKYTst5ZL02hlUtKvBj2ClRC96ng0T7JlXXjv3Ka3Hnn5Z0dcuaWvUGiv9hv9KmZOe3lSQv "Perl 5 – TIO Nexus") But the way Perl deals with parameters isn't optimal for golfing functions: no optional parameters means I have to do a second function (anonymous) calling the first one, and I have to explicitly get the last parameter with that long `my$v=pop`. [Answer] # Ruby, ~~49 45~~ 46 bytes ``` f=->c,p=?>{c.map{|x|x==[*x]?f[x,?-+p]:p+x}*$/} ``` Example: ``` puts f[["Atom",["Proton",["Up Quark", "Up Quark", "Down Quark"], "Neutron", ["Up Quark", "Down Quark", "Down Quark"], "Electron"]]] >Atom ->Proton -->Up Quark -->Up Quark -->Down Quark ->Neutron -->Up Quark -->Down Quark -->Down Quark ->Electron ``` ### Explanation: Recursive function: if `x==[*x]` then x is an array, and we iterate over it. If not, indent it. [Answer] ## Haskell, 104 bytes ``` l@(x:y)#(a:m)|[(h,t)]<-reads$a:m=y++h++l#t|a<'#'=l#m|a<'-'='\n':l#m|a>'['=y#m|q<-'-':l=q#m l#_="" (">"#) ``` Haskell doesn't have nested lists with different depths, so I have to parse the input string on my own. Luckily the library function `reads` can parse Strings (i.e. `"`-enclosed char sequence), so I have a little help here. Usage example: ``` *Main> putStrLn $ (">"#) "[[\"1\",\"2\"],[\"3\",\"4\"]]" ->1 ->2 ->3 ->4 ``` [Try it online!](https://tio.run/nexus/haskell#fZBfa4MwFMXf/RThphBFfdjfBzFlg@1tjI2xp0SGrJaWJqbVGzah391dlUGR0rx4zu@cG7zpzUP4m3URD8vMRkcVbhKMijxtqnLVLojJLo43cWw4HstccCENt4NKhRS6Ftlol0IJ2ZE65CklmZEHbgPDvyRAsJYhLIFHPSKTDJTScKUh0XCtoUhmVsPN9LklptSQ3hGgQ@yeFARtO16j4RGdHVoa3hqHrp705569@7LZkWNz9@R@6n9fDOC18tiMk0xdKp8dfjbV9zRd0G95f267cZ9pnaEU2HJbU2/lAsb2Hj@weanZgq0Z4imhZ5vlbXs5955I/wc "Haskell – TIO Nexus"). How it works: The function `#` goes through the string char by char and keeps the nesting level (the first parameter `l`) as a string of `-` with a final `>`. If the head of the list can be parsed as a String, take `l` and the String followed by recursive call with the String removed. If the first char is a Space, skip it. If it's a `,`, take a newline and go on, if it's `]`, lower the nesting level and go on and else (only `[` left) raise the nesting level and go on. Recursion ends with the empty input string. The main function `(">"#)` sets the nesting level to `">"` and calls `#`. [Answer] ## SWI-Prolog, 115 bytes ``` p(L):-p(L,[>]). p([],_):-!. p([H|T],F):-p(H,[-|F]),p(T,F),!. p(E,[_|F]):-w(F),w([E]),nl. w([]). w([H|T]):-write(H),w(T). ``` Line breaks added for readability only, not included in byte count. `p` predicate recursively traverses the arrays, adding a '-' to the prefix `F` when moving a level deeper. `w` is used to write the prefix array as well as the actual element to the output. Example: ``` ?- p(["Atom",["Proton",["Up Quark", "Up Quark", "Down Quark"], "Neutron", ["Up Quark", "Down Quark", "Down Quark"], "Electron"]]). >Atom ->Proton -->Up Quark -->Up Quark -->Down Quark ->Neutron -->Up Quark -->Down Quark -->Down Quark ->Electron ``` [Answer] ## Batch, 249 bytes ``` @echo off set/ps= set i= :t set t= :l set c=%s:~,1% set s=%s:~1% if "%c%"=="[" set i=-%i%&goto l if not "%c%"=="]" if not "%c%"=="," set t=%t%%c%&goto l if not "%t%"=="" echo %i:~1%^>%t% if "%c%"=="]" set i=%i:~1% if not "%s%"=="" goto t ``` Annoyingly Batch has trouble comparing commas. Sample run: ``` [Atom,[Proton,[Up Quark,Up Quark,Down Quark],Neutron,[Up Quark,Down Quark,Down Quark],Electron]] >Atom ->Proton -->Up Quark -->Up Quark -->Down Quark ->Neutron -->Up Quark -->Down Quark -->Down Quark ->Electron ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~63~~ ~~54~~ 52 bytes *Saved 2 bytes thanks to Martin Ender* ``` .*?".*?" $`$&¶ T`[] -~`-]_`.(?=.*".*") -] -" > T`]" ``` [Try it online!](https://tio.run/nexus/retina#@6@nZa8EwlwqCSpqh7ZxhSRExyro1iXoxsYn6GnY2@ppAaWVNLl0Y7m4dJW47IAKYpX@/49WcizJz1XSiVYKKMovyc8DsUILFAJLE4uylXSQmS755XlQTqyOkl9qaUkRhnIkNegaXHNSk8E6YmMB "Retina – TIO Nexus") **Explanation** ``` .*?".*?" $`$&¶ ``` First, the array is broken up by replacing each quoted string with everything that came before it, plus itself, plus a newline. By breaking it up like this, it's possible to find the unmatched opening brackets before each string. ``` T`[] -~`-]_`.(?=.*".*") ``` This transliteration will replace `[` with `-`, leave `]` unchanged, and delete every other character (`-~` is all printable ASCII). However, it only replaces characters appearing before the final string on each line. ``` -] ``` Next all instances of `-]` are removed. These correspond to matching bracket pairs, and we only want unmatched brackets. After these are removed, each line has a number of `-`s equal to how many unmatched opening brackets came before it. ``` -" > ``` The last `-` before a `"` is replaced with `>`, to form the arrows. ``` T`]" ``` Finally, all remaining `]`s and `"`s are deleted. [Answer] # [Röda](https://github.com/fergusq/roda), 54 bytes ``` f d=""{{|n|{n|f d=`$d-`}if[n is list]else[`$d>$n `]}_} ``` [Try it online!](https://tio.run/nexus/roda#dU89C8IwFJzbX/F4dIyDn1sEQVfRwSkEW7SFYJuUNMUhyW@viXSoqG943B13j3dDBXeKaK2TzkoXWZ7dZ7kXFZMgOqhFZ3hZdyUL@jaTac791Q9NISTYNGEM50hwgZxMIC7jWmHQgrpGHobgBjk4qNKk1UIaQEophgu4M6oJVjxpZZSM6NLCuS/0Awl84L16ypHxQI9lb3RMAPtn@w4d6vL2TvGf30z6hBaxxOjzwws "Röda – TIO Nexus") It's a function that reads the input array from the stream. For each item, it either calls itself recursively or prints the item. [Answer] # Python 3, 80 Bytes Python's lambdas support recursion it seems, who knew ? ``` p=lambda l,d=1:[p(i,d+1)if isinstance(i,list)else print("-"*d+">"+i)for i in l] ``` This is a counter/compliment to [orlp's](https://codegolf.stackexchange.com/a/113438/59826) answer. [Answer] # Groovy, 92 bytes ``` x={a,b->if(a instanceof List){a.each{x(it,b+1)}}else{y(a,b)}};y={a,b->println("-"*b+">$a")}; ``` [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 27 bytes ``` [@.1-'-'*\'>'\,,out]deepmap ``` [Try it online!](https://tio.run/nexus/stacked#01B3LMnPVVfQUA8oyi/JzwOxQgsUAksTi7LVFZCZLvnleVCOpoK6X2ppSRGGciQ16Bpcc1KTwTo0Nf9HO@gZ6qrrqmvFqNupx@jo5JeWxKakphbkJhb8/w8A "Stacked – TIO Nexus") Takes input from the top of the stack and leaves output on STDOUT. This is simple as doing a depth map, repeating `-` `d` times, concatenating with '>' and the element itself. [Answer] # Gema, 63 characters ``` \A=@set{i;-1} [=@incr{i} ]=@decr{i} "*"=@repeat{$i;-}>*\n ,<s>= ``` Like the other parsing solutions, assumes there will be no escaped double quotes in the strings. Sample run: ``` bash-4.3$ gema '\A=@set{i;-1};[=@incr{i};]=@decr{i};"*"=@repeat{$i;-}>*\n;,<s>=' <<< '[["1","2"],[["1","2"],"3"],"4",[[[["5"]]]],"6"]' ->1 ->2 -->1 -->2 ->3 >4 ---->5 >6 ``` [Answer] # jq, ~~70~~ 67 characters (~~67~~ 64 characters code + 3 characters command line option) ``` def f(i):if type=="array"then.[]|f("-"+i)else i+. end;.[]|f(">") ``` Sample run: ``` bash-4.3$ jq -r 'def f(i):if type=="array"then.[]|f("-"+i)else i+. end;.[]|f(">")' <<< '[["1","2"],[["1","2"],"3"],"4",[[[["5"]]]],"6"]' ->1 ->2 -->1 -->2 ->3 >4 ---->5 >6 ``` [On-line test](https://jqplay.org/s/5QqUX7JEIF) ]
[Question] [ > > The challenge involve simply toggling a string within another string. > > > ## Explanation If the **toggle string** is a substring of the **main string**, remove all instances of the **toggle string** from the **main string**; otherwise, append the **toggle string** at the end of the **main string**. ## Rules * All string are composed of printable ASCII characters * The function should take two parameters: the **main string** and the **toggle string**. * The **main string** can be empty. * The **toggle string** cannot be empty. * The result should be a string, which can be empty. * The shortest answer wins. ## Examples ``` function toggle(main_string, toggle_string){ ... } toggle('this string has 6 words ', 'now') => 'this string has 6 words now' toggle('this string has 5 words now', ' now') => 'this string has 5 words' ``` ## Tests cases ``` '','a' => 'a' 'a','a' => '' 'b','a' => 'ba' 'ab','a' => 'b' 'aba','a' => 'b' 'ababa', 'aba' => 'ba' ``` [Answer] # Java 8, ~~80~~ ~~70~~ ~~65~~ 34 bytes ``` t->m->m==(m=m.replace(t,""))?m+t:m ``` Probably my shortest Java 'codegolf' so far.. xD with some help from the comments.. ;) **Explanation:** [Try it online.](https://tio.run/##nY5BC4JAEIXv/orB00q6PyDTbt06eYwO42qxtrsuOgoS/nbb0IJuGgzMg3nvzVdhj1FtS1MVj0kobFs4ozRPD6AlJCmgcg7ekVT81hlBsjb8tIhDRo0093CVZ95pCgISmChKtZskYTrRvCmtQlEyCn0/CI56R3s9xZ6DsF2uHMTC0teyAO342Nx2uWLwRgXIhpZKzeuOuHUXUoYJjtaqgfnoBx/p2uMtftwayDd/@COxkir/DX1jozdOLw) ``` t->m-> // Method with two String parameters and String return-type // (NOTE: Takes the toggle `t` and main `m` in reversed order) m==(m=m.replace(t,""))? // If `m` equals `m` with all `t`-substrings removed: // (And set `m` to `m` with all `t`-substrings removed) m+t // Output this new `m` concatted with `t` : // Else: m // Output just this new `m` ``` [Answer] # MATL, 11 bytes ``` yyXf?''YX}h ``` [Try it Online!](http://matl.tryitonline.net/#code=eXlYZj8nJ1lYfWg&input=J2FiYWJhJwonYWJhJw) [All test cases](http://matl.tryitonline.net/#code=YGlpeXlYZj8nJ1lYfWhdRFRd&input=JycKJ2EnCidhJwonYScKJ2InCidhJwonYWInCidhJwonYWJhJwonYScKJ2FiYWJhJwonYWJhJw) **Explanation** ``` % Implicitly grab the main string % Implicitly grab the toggle string y % Copy the main string y % Copy the toggle string Xf % Check to see if the toggle string is present in the main string ? % If so ''YX % Replace with an empty string } % else h % Horizontally concatenate the two strings % Implicit end of if...else % Implicitly display the result ``` [Answer] # Python 3, 38 bytes ``` lambda s,t:(s+t,s.replace(t,""))[t in s] ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` œṣȮ⁸e⁹ẋ ``` [Try it online!](http://jelly.tryitonline.net/#code=xZPhuaPIruKBuGXigbnhuos&input=&args=J3RoaXMgc3RyaW5nIGhhcyA2IHdvcmRzICc+J25vdyc) ### How it works ``` œṣȮ⁸e⁹ẋ Main link. Arguments: s (string), t (toggle string) œṣ Split s at occurrences of t. Ȯ Print the result. ⁸e Check if s occurs in the split s. Yields 1 (true) or 0 (false). ⁹ẋ Repeat t that many times. ``` [Answer] ## JavaScript (ES6), ~~39~~ 37 bytes ``` (s,t,u=s.split(t).join``)=>u==s?s+t:u ``` [Answer] ## Pyke, 14 bytes ``` DX{iIXRk:)i!IJ ``` [Try it here!](http://pyke.catbus.co.uk/?code=DX%7BiIXRk%3A%29i%21IJ&input=%5B%22this+string+has+5+words+now%22%2C%22now%22%5D) Given that Pyke has no `else` structure, I think this is pretty reasonable score Explanation: ``` D - Duplicate input X - a,b = ^ { - a in b i - i = ^ I - if i: XRk: - a = b.replace(a,"") i!I - if not i: J - a = "".join(input) - print a ``` [Answer] # CJam, 9 ``` q~:B/2Be] ``` [Try it online.](http://cjam.aditsu.net/#code=q%7E%3AB%2F2Be%5D&input=%22code%20golf%22%20%22o%22) Thanks jimmy23013 for chopping off 1 byte :) **Explanation:** ``` q~ read and evaluate the input (given as 2 quoted strings) :B store the toggle string in B / split the main string by the toggle string 2Be] pad the array of pieces to the right with B, up to length 2 (if shorter) ``` [Answer] # Javascript (ECMAScript 6): 47 bytes ``` (a,b)=>(c=a.replace(RegExp(b,'g'),''))!=a?c:a+b ``` [Answer] ## [Retina](https://github.com/mbuettner/retina/), ~~38~~ 31 bytes Byte count assumes ISO 8859-1 encoding. ``` (.+)(?=.*¶\1$) · 1>`·|¶.+ T`·¶ ``` The trailing linefeed is significant. Input format is both strings separated with a linefeed. [Try it online!](http://retina.tryitonline.net/#code=JShHYAooLispKD89Lio7XDEkKQohCjE-YCF8Oy4rCgpUYCE7&input=dGhpcyBzdHJpbmcgaGFzIDYgd29yZHMgO25vdwp0aGlzIHN0cmluZyBoYXMgNSB3b3JkcyBub3c7IG5vdwo7YQphO2EKYjthCmFiO2EKYWJhO2EKYWJhYmE7YWJhCmFiYWJhYmFiYTthYmE) The first line allows running several test cases at once (for the test suite, use `;` to separate the strings and linefeeds to separate test cases; the first line takes care of the conversion). ### Explanation ``` (.+)(?=.*¶\1$) · ``` In this first step we replace all occurrences of the toggle string in the main string with `·`. We need to insert these markers so that we can determine afterwards if any substitution happened. ``` 1>`·|¶.+ ``` This is another substitution which removes a `·` marker, or the second line (including the separating linefeed). However, the `1>` is a limit which means that only matches *after* the first are considered. Hence, if the toggle string did not occur in the main string, we won't have inserted any `·`, so the second line will be the first match and won't be removed. Otherwise, we remove the second line along with all but the first marker. ``` T`·¶ ``` While this uses a transliteration stage, it's also used simply for removing characters. In particular, we move both `·` and linefeeds. We need the first one, in case there was a match (because then the first `·` will have been left behind by the previous stage) and we need the second one in case there wasn't a match (to join the two lines together and thereby append the toggle string to the main string). [Answer] # Python (3.4): ~~55~~ ~~54~~ ~~47~~ 44 Bytes ``` lambda m,t:m.replace(t,'')if t in m else m+t ``` Testing: ``` toggle=lambda m,t:m.replace(t,'')if t in m else m+t print('', 'a', toggle('','a')) print('a', 'a', toggle('a','a')) print('b', 'a', toggle('b','a')) print('ab', 'a', toggle('ab','a')) print('aba', 'a', toggle('aba','a')) print('ababa', 'aba', toggle('ababa','aba')) ``` The Test output ``` a a a a b a ba ab a b aba a b ababa aba ba ``` ~~Using a def would be longer because you have to use a return statement, if it were possible without return it would save 2 Bytes~~ Since explicit declaration of the function is not needed (sorry I didn't know that) 7 Bytes were saved. [Answer] # C#, 63 ``` string F(string s,string t)=>s.Contains(t)?s.Replace(t,""):s+t; ``` Better than Java :) Test code: ``` public static void Main() { Console.WriteLine(F("", "a")); Console.WriteLine(F("a", "a")); Console.WriteLine(F("b", "a")); Console.WriteLine(F("ab", "a")); Console.WriteLine(F("aba", "a")); Console.WriteLine(F("ababa", "aba")); Console.ReadLine(); } ``` Output: ``` a ba b b ba ``` [Answer] # Pyth, ~~13~~ ~~11~~ 10 bytes ``` ?/Qz:Qzk+z ``` [Test suite.](http://pyth.herokuapp.com/?code=%3F%2FQz%3AQzk%2Bz&test_suite=1&test_suite_input=%22%22%0Aa%0A%0A%22a%22%0Aa%0A%0A%22b%22%0Aa%0A%0A%22ab%22%0Aa%0A%0A%22aba%22%0Aa%0A%0A%22ababa%22%0Aaba%0A&debug=0&input_size=3) Input format: first string in quotes, second string without quotes. ### This is also 10 bytes: ``` ?tJcQzsJ+z ``` [Test suite.](http://pyth.herokuapp.com/?code=%3FtJcQzsJ%2Bz&test_suite=1&test_suite_input=%22%22%0Aa%0A%0A%22a%22%0Aa%0A%0A%22b%22%0Aa%0A%0A%22ab%22%0Aa%0A%0A%22aba%22%0Aa%0A%0A%22ababa%22%0Aaba%0A&debug=0&input_size=3) ### This is 11 bytes: ``` pscQz*!}zQz ``` [Test suite.](http://pyth.herokuapp.com/?code=pscQz*!%7DzQz&test_suite=1&test_suite_input=%22%22%0Aa%0A%0A%22a%22%0Aa%0A%0A%22b%22%0Aa%0A%0A%22ab%22%0Aa%0A%0A%22aba%22%0Aa%0A%0A%22ababa%22%0Aaba%0A&debug=0&input_size=3) ### Previous 13-byte solution: ``` ?:IQzk+Qz:Qzk ``` [Test suite.](http://pyth.herokuapp.com/?code=%3F%3AIQzk%2BQz%3AQzk&test_suite=1&test_suite_input=%22%22%0Aa%0A%0A%22a%22%0Aa%0A%0A%22b%22%0Aa%0A%0A%22ab%22%0Aa%0A%0A%22aba%22%0Aa%0A%0A%22ababa%22%0Aaba%0A&debug=0&input_size=3) [Answer] # Jolf, 12 bytes ``` ?=iγρiIE+iIγ ``` Or, if we must include regex-sensitive chars: ``` ?=iγρiLeIE+iIγ ``` [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=Pz1pzrPPgWlMZUlFK2lJzrM&input=SGVsbG8sIHBlcnNvbiEKCiwgcGVyc29uIQ) ## Explanation ``` ?=iγρiIE+iIγ if(i === (γ = i.replace(I, E))) alert(i + I); else alert(γ); i i = === ρ .replace( , ) iI i I E E γ (γ = ) ? if( ) +iI alert(i + I); else γ alert(γ); ``` [Answer] # JavaScript (ES6), 37 Bytes ``` (m,t)=>(w=m.split(t).join``)==m?m+t:w ``` Slightly shorter than @nobe4 's answer by taking advantage of split and join [Answer] # Racket, 70 bytes Pretty straight forward. ``` (λ(s t)((if(string-contains? s t)string-replace string-append)s t"")) ``` [Answer] # Scala, 72 70 bytes ``` def x(m:String,s:String)={val r=m.replaceAll(s,"");if(r==m)m+s else r} ``` Online interpreter: [www.tryscala.com](http://www.tryscala.com) [Answer] # Oracle SQL 11.2, 66 bytes ``` SELECT DECODE(:1,s,s||:2,s)FROM(SELECT REPLACE(:1,:2)s FROM DUAL); ``` [Answer] # Ruby, ~~33 bytes~~ ~~27 bytes (28 if using global subtitution)~~ definitely 28 bytes ``` ->u,v{u[v]?u.gsub(v,''):u+v} ``` [Answer] # Ruby, ~~35~~ ~~37~~ 28 bytes ``` ->m,t{m[t]?m.gsub(t,''):m+t} ``` Hooray for string interpolation! It even works in regexes. The rest is simple: if the string in `t` matches to `m`, replace `t` with `''`, else return `m+t`. **Edit:** Fixed a bug. **Edit:** I applied Kevin Lau's suggestion, but it appears that I have reached the same algorithm as the one used in [Luis Masuelli's answer](https://codegolf.stackexchange.com/a/80303/47581). [Answer] # Perl, ~~37~~ 30 bytes ``` {$_=shift;s/\Q@_//g?$_:"$_@_"} ``` Regular expressions inside the toggle string are not evaluate because of the quoting with `\Q`...`\E`. `sub F` and `\E` are removed according to the [comment](https://codegolf.stackexchange.com/questions/80243/toggle-a-string/80306?noredirect=1#comment197404_80306) by msh210. It is not entirely free of side effects because of setting `$_`. Using a local variable will cost six additional bytes: ``` {my$a=shift;$a=~s/\Q@_//g?$a:"$a@_"} ``` On the other hand, with switched input parameters two bytes can be saved by using `pop` instead of `shift` (28 bytes): ``` {$_=pop;s/\Q@_//g?$_:"$_@_"} ``` Test file: ``` #!/usr/bin/env perl sub F{$_=shift;s/\Q@_//g?$_:"$_@_"} sub test ($$$) { my ($m, $t, $r) = @_; my $result = F($m, $t); print "F('$m', '$t') -> '$result' ", ($result eq $r ? '=OK=' : '<ERROR>'), " '$r'\n"; } test '', 'a', 'a'; test 'a', 'a', ''; test 'b', 'a', 'ba'; test 'ab', 'a', 'b'; test 'aba', 'a', 'b'; test 'ababa', 'aba', 'ba'; test 'ababa', 'a*', 'ababaa*'; test 'foobar', '.', 'foobar.'; __END__ ``` Test result: ``` F('', 'a') -> 'a' =OK= 'a' F('a', 'a') -> '' =OK= '' F('b', 'a') -> 'ba' =OK= 'ba' F('ab', 'a') -> 'b' =OK= 'b' F('aba', 'a') -> 'b' =OK= 'b' F('ababa', 'aba') -> 'ba' =OK= 'ba' F('ababa', 'a*') -> 'ababaa*' =OK= 'ababaa*' F('foobar', '.') -> 'foobar.' =OK= 'foobar.' ``` [Answer] # C# (58 bytes) `string F(string s,string t)=>s==(s=s.Replace(t,""))?s+t:s;` It uses an inline assignment to shave a few bytes off [Answer] # bash + sed, 28 bytes ``` sed "s/$2//g;t;s/$/$2/"<<<$1 ``` The script lives in a toggle-string.bash file, which we call with `bash toggle-string.bash mainstring togglestring`. `s/$2//g` removes the toggle string from the main string `t` jumps to the end if the previous substitution was successful (ie. the main string contained the toggle string) `/$/$2/` adds the toggle string at the end (`$`), if we didn't jump to the end bash is required for the herestring [Answer] # Julia, ~~33~~ 31 bytes ``` s|t=(r=replace(s,t,""))t^(s==r) ``` [Try it online!](http://julia.tryitonline.net/#code=c3x0PShyPXJlcGxhY2Uocyx0LCIiKSl0XihzPT1yKQoKcHJpbnRsbigidGhpcyBzdHJpbmcgaGFzIDYgd29yZHMgInwibm93IikKcHJpbnRsbigidGhpcyBzdHJpbmcgaGFzIDUgd29yZHMgbm93InwiIG5vdyIpCnByaW50bG4oIiJ8ImEiKQpwcmludGxuKCJhInwiYSIpCnByaW50bG4oImIifCJhIikKcHJpbnRsbigiYWIifCJhIikKcHJpbnRsbigiYWJhInwiYSIpCnByaW50bG4oImFiYWJhInwiYWJhIik&input=) [Answer] ## PowerShell v2+, 47 bytes ``` param($a,$b)(($c=$a-replace$b),"$a$b")[$c-eq$a] ``` Takes input `$a,$b` and then uses a pseudo-ternary `(... , ...)[...]` statement to perform an if/else. The inner parts are evaluated first to form an array of two elements. The 0th is `$a` with all occurrences of `$b` `-replace`d with nothing, which is stored into `$c`. The 1st is just a string concatenation of `$a` and `$b`. If `$c` is `-eq`ual to `$a`, meaning that `$b` wasn't found, that's Boolean `$true` or `1`, and so the 1st element of the array (the concatenation) is chosen. Else, it's Boolean `$false`, so we output `$c`, the 0th element. Note that `-replace` is greedy, so it will replace from the left first, meaning the `ababa / aba` test case will properly return `ba`. [Answer] # Java 8, 65 bytes ``` BinaryOperator<String>l=(m,t)->m.contains(t)?m.replace(t,""):m+t; ``` The same logic as the Java 7 solution, written with a lambda. [Try it here](http://ideone.com/v5Uh0G) [Answer] # Mathematica, 45 bytes ``` If[StringContainsQ@##,StringDelete@##,#<>#2]& ``` Anonymous function that takes the main string and the toggle string (in that order) and returns the result. Explanation: ``` & Anonymous function returning... If[StringContainsQ@##, , ] if its first argument contains its second argument, then... StringDelete@## its first argument with its second argument removed, else... #<>#2 its second argument appended to its first argument. ``` [Answer] **TSQL, 143 129 121 Bytes** ``` DECLARE @1 VARCHAR(10)='',@2 VARCHAR(10)='a'SELECT CASE WHEN @1 LIKE'%'+@2+'%'THEN REPLACE(@1,@2,'')ELSE CONCAT(@1,@2)END ``` Readable: ``` DECLARE @1 VARCHAR(10) = '' , @2 VARCHAR(10) = 'a' SELECT CASE WHEN @1 LIKE '%' + @2 + '%' THEN REPLACE(@1, @2, '') ELSE CONCAT (@1, @2) END ``` `**[`Live Demo`](https://data.stackexchange.com/stackoverflow/query/edit/488831)**` **114 Bytes** with strictly 1 character input ``` DECLARE @1 CHAR(1) = 'a' , @2 CHAR(1) = '.' SELECT CASE WHEN @1 LIKE '%' + @2 + '%' THEN REPLACE(@1, @2, '') ELSE CONCAT (@1, @2) END ``` [Answer] # TSQL(Sqlserver 2012), 49 bytes ``` DECLARE @ VARCHAR(10) = 'hello',@x VARCHAR(10) = 'o' PRINT IIF(@ LIKE'%'+@x+'%',REPLACE(@,@x,''),@+@x) ``` [Try it online!](https://data.stackexchange.com/stackoverflow/query/488976/toggle-a-string) [Answer] # k (23 bytes) ``` {$[#x ss y;,/y\:x;x,y]} ``` Examples: ``` k){$[#x ss y;,/y\:x;x,y]}["aba";"a"] ,"b" k){$[#x ss y;,/y\:x;x,y]}["this string has 6 words ";"now"] "this string has 6 words now" k){$[#x ss y;,/y\:x;x,y]}["this string has 5 words now";"now"] "this string has 5 words " k){$[#x ss y;,/y\:x;x,y]}["ababa";"ba"] ,"a" k){$[#x ss y;,/y\:x;x,y]}["";"a"] ,"a" ``` [Answer] ## Kotlin, 61 Bytes ``` {m:String,t:String->var n=m.replace(t,"");if(m==n)m+t else n} ``` This is would be shorter if assignment was an expression in Kotlin,and parameters were mutable,and there was a ternary conditional operator, sadly this isn't the case :( [Try it Online!](http://try.kotlinlang.org/#/UserProjects/imoa5gjbnol7adr9n38tqja56a/q2a6ai0gv7gqjialn6rkrpo2bg) ### UnGolfed ``` fun t(m:String, t:String):String{ var n=m.replace(t, "") return if(m==n)m+t else n } ``` ]
[Question] [ Because the coronavirus is still at large, I thought it would be fitting to have a epidemic-themed challenge. ## Challenge You are given a 2D array of people, where `1` represents someone with the virus, and `0` represents someone without the virus. Every day, the people with the virus infect their neighbours. You must calculate, given such a grid, how many days it will take to infect the population (i.e., every item is `1`). ## Rules * The input counts as Day 0, and every day after increases by 1 (you can count the first day as Day 1 if you want, but indicate that in your answer). * The grid items don't have to be `1`s and `0`s, they can be any truthy/falsy values. Every item in the grid is randomized to one of those values. Please specify which truthy/falsy values your program will/will not accept. * The input grid can be any size between 2x2 and 100x100. The grid does not have to be square. The grid size is randomized (i.e. you can't choose). * Diagonal squares do not count as adjacent. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins! ## Examples ``` [[1, 0, 0, 0, 1], # Input [0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0]] [[1, 1, 0, 1, 1], # Day 1 [1, 1, 1, 0, 1], [0, 1, 0, 1, 0], [0, 0, 1, 1, 1]] [[1, 1, 1, 1, 1], # Day 2 [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 1, 1, 1]] [[1, 1, 1, 1, 1], # Day 3 [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]] output = 3 ``` ``` [[1, 0], # Input [0, 0], [0, 0]] [[1, 1], # Day 1 [1, 0], [0, 0]] [[1, 1], # Day 2 [1, 1], [1, 0]] [[1, 1], # Day 3 [1, 1], [1, 1]] output = 3 ``` --- [Answer] # [Stencil](https://github.com/abrudz/Stencil) `≢`, 2 bytes ``` ×v ``` [Try it online!](https://tio.run/##Ky5JzUvOzPn///D0sv//H7VNfNQ31SvY3089OtpQxwAMDWN1ooEkhAdmG6CxgXKxsepc6Loh8lAyVv1ffkFJZn5e8f9HnYsA "Stencil – Try It Online") `≢` tallies the number of necessary steps (including the initial state) until stability is reached. This command line argument isn't counted towards the byte count, as per [Meta consensus](https://codegolf.meta.stackexchange.com/questions/14337/command-line-flags-on-front-ends). Each cell's next state is determined by: `×` the sign of `v` the sum of all values in its **v**on Neumann neighbourhood (including itself) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ŒJạ€ŒṪ§Ṃ€Ṁ ``` [Try it online!](https://tio.run/##y0rNyan8///oJK@HuxY@alpzdNLDnasOLX@4swnIebiz4f///9HRhjoKBjBkGKujwKUQDWLBReFCBriEQGpjYwE "Jelly – Try It Online") -2 bytes thanks to Sisyphus Calculate the Manhattan differences from all 0s to all 1s, and the answer is the maximum of the minimums (each row's minimum is the number of stages until it gets infected, so the number of stages needed is the maximum of the stages needed for each person). Conveniently, if all elements are 1, this returns 0 since that's the default value for minmax. If no person is infected in the initial state, this also returns 0. # Explanation ``` ŒJạ€ŒṪ§Ṃ€Ṁ Main Link ŒJ Get all indices in the grid (2D indices in a matrix) ŒṪ Get all truthy indices in the grid (finds all infected people) ạ€ § Manhattan distance between each point to each truthy point Ṃ€ Minimum of each (minimum number of days for each person to get infected) Ṁ Maximum (of each point's required days to get infected) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~90~~ 78 bytes ``` f=Length@FixedPointList[ListConvolve[CrossMatrix@1,#,{2,2},0,Times,Max]&,#]-2& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/N1ic1L70kw8EtsyI1JSA/M6/EJ7O4JBpEOOfnleXnlKVGOxflFxf7JpYUZVY4GOoo61Qb6RjV6hjohGTmphbr@CZWxKrpKMfqGqn9T4uurjbUUTCAIcNaHYVqEA0XgwoYYBcAqautjVXQ11cIKAK65T8A "Wolfram Language (Mathematica) – Try It Online") -12 bytes, because of course there is a built-in `CrossMatrix` to construct the kernel \$K\$. Defines a pure function `f` that takes a matrix as input. If no one is infected, return `0`. Uses list convolution to spread the disease day-by-day and a Mathematica built-in to loop until a fixed point is reached (i.e. everyone is infected). Explanation: To spread the disease, use a kernel $$K=\begin{pmatrix} 0 & 1 & 0 \\ 1 & 1 & 1 \\ 0 & 1 & 0 \end{pmatrix}$$ and list convolution. For example, if we start at $$I\_0=\begin{pmatrix} 0 & 0 & 0 & 0 \\ 0 & 1 & 1 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ \end{pmatrix}$$ then applying ``` ListConvolve[{{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}, #, {2, 2}, 0] & ``` results in $$\begin{pmatrix} 0 & 1 & 1 & 0 \\ 1 & 2 & 2 & 1 \\ 0 & 1 & 1 & 0 \\ 0 & 0 & 0 & 0 \\ \end{pmatrix}.$$ We don't actually need to know whether a person is infected multiple times, so within the list convolution, instead of summing, we'll just take the maximum ``` ListConvolve[{{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}, #, {2, 2}, 0, Times, Max] & ``` which gives $$\begin{pmatrix} 0 & 1 & 1 & 0 \\ 1 & 1 & 1 & 1 \\ 0 & 1 & 1 & 0 \\ 0 & 0 & 0 & 0 \\ \end{pmatrix}.$$ Then we just need to iterate it until a fixed point is reached, i.e. everyone is infected to no new infections can occur. There's (as usual) a handy built-in in Mathematica, `FixedPointList`, which gives a list of all the iterations until a fixed point is reached. Since this list contains the input and the fixed point twice, just subtract two from the list length to get the answer. As a sidenote, the parameters in `ListConvolve` ensure that the convolution works well with the kernel. With the default parameters, convolving $$\begin{pmatrix} 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \end{pmatrix}$$ with the kernel $$\begin{pmatrix} a & b & c \\ d & e & f \\ g & h & i \end{pmatrix}$$ gives rather uselessly $$\begin{pmatrix} 0 & 0 \\ b & c \end{pmatrix}.$$ To at least preserve the dimensions, we'll add the parameter `{1,1}`, which now gives $$\begin{pmatrix} 0 & d & e & f \\ 0 & g & h & i \\ 0 & 0 & 0 & 0 \\ 0 & a & b & c \\ \end{pmatrix}.$$ This time, the problem is that the convolution starts at the top-left corner instead of at the center of the kernel, so let's change the `{1,1}` to `{2,2}`, which gives $$\begin{pmatrix} g & h & i & 0 \\ 0 & 0 & 0 & 0 \\ a & b & c & 0 \\ d & e & f & 0 \\ \end{pmatrix}.$$ This is almost what we need, but the bottom of the kernel overflows to the top. To fix this, we'll just add a padding parameter `0`. Finally $$\begin{pmatrix} 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ a & b & c & 0 \\ d & e & f & 0 \\ \end{pmatrix}.$$ [Answer] # [Octave](https://www.gnu.org/software/octave/), 26 bytes ``` @(x)max(bwdist(x,'ci')(:)) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzN7FCI6k8JbO4RKNCRz05U11Tw0pT83@aRjSXoY6CAQwZWnOBSLiItQKXAZI0Ch@kyporVpOLC2YKWDOcjNX8DwA "Octave – Try It Online") For each cell, compute the distance to the nearest nonzero cell under the \$L\_1\$ norm (taxicab metric). The solution is the maximum value. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 20 bytes ``` {⌈/⌊⌿⍵∘.(1⊥∘|-)⍥⍸~⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pRT4f@o56uRz37H/VufdQxQ0/D8FHXUiCjRlfzUe/SR7076oAStf/THrVNeNTb96ir@VHvmke9Ww6tN37UNvFR39TgIGcgGeLhGfw/TcFEwVQBKKlgqGAAhoZQjA0CxbnSFIwVjFB0ACEA "APL (Dyalog Extended) – Try It Online") Uses the Manhattan Distance method from HyperNeutrino's Jelly answer. Input is a binary matrix. ## Explanation ``` {⌈/⌊⌿⍵∘.(1⊥∘|-)⍥⍸~⍵} ⍵ ~⍵ input and input negated ⍥⍸ coordinates of truthy values ∘. outer product using (1⊥∘|-) Manhattan distance function (APLcart) ⌊⌿ Minimum of each column ⌈/ Maximum of the minima ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~270~~ \$\cdots\$ ~~214~~ 213 bytes Saved a whopping ~~31~~ ~~39~~ ~~40~~ ~~44~~ ~~56~~ 57 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` z;C;i;j;n;d;*p;f(a,r,c)int*a;{p=calloc(C=c+2,4*r+8);for(n=d=0;d<r*c;++n){for(d=0,i=r;i--;)for(j=c;j--;)a[i*c+j]?p[i*C-~j]=p[(i+2)*C-~j]=p[z=j-~i*C]=p[z+2]=1:0;for(;++i<r*c;)d+=a[i/c*c+i%c]=p[1-~(i/c)*C+i%c];}d=n;} ``` [Try it online!](https://tio.run/##lVTbjpswEH3PV4yQImEwXXJT2zjWPqR973uCVsjAxiwFZKg2myj59XRsIJdNUqXIscczZ84ZzDjCexXicNiwOZMsZTmLmFOyxA6pooLIvHZCti25CLOsEPacC3dIx45yvxGWFMrOecR9Fs2UI5jr5mSrneiikismPY8R7Ui5YKnehAvpCDcNnks05t4@DXi5sKU7JMfdhqfeHoPGdocBH0x9I4X80uiQyOVI9CSQSvaFBg68vY0OZDEetot4znaHUuELvIRKhR@2fhUwJgW0QRXvVWOJIqtIb9sDfFAINBQkcPAZLjODZIDqBBrQBTBtgCkCNZEGpgSMcmJb/aofWRTs9Blna2pZhDZF6INAOLiQBoQdabu8ZW613l1v19M6v0OZ212Z2gF1XNUvg0WAew7bAQW/G4Oz@d9DY3bsE@fwFqd/Czm6h3x8XHGOO07/wfof4FQd55jCiALO4yuM6DATCkMKOE9OGMdgKgPRmObsaXte7Tpq1wvueF3Goo4jTMW8kdH/etIXqxB7ehWLt9gUiRhruf45XK6/z/E30W1zth9Zbd6pUfMoXrfNaswZVHITF4ndKZOn1uEcPaadNfq8pc1lR6bmTU04YOdRUG0Uz/NWWHRhcRXu@vpXUf7JwloWObwqGU1PfX5Etfc1pKAoCHIpUaFEcicWY@x42vcK@BF@VCBreJdZBnX4FkNdYHaCWVCvYihPBcoK@tEX6FdYJAX8s@g@U8V5fOvSev/9XFzzw18 "C (gcc) – Try It Online") Inputs the population grid as a pointer to an array of `int`s, that are either \$1\$ for infected or \$0\$ otherwise, along with the number of rows and columns. Returns the number of days it will take to infect the population. ### How? Creates a shadow array `p` that has a one element boarder around it so we don't have to worry about the neighbours not being there when we're at the edges. Initialises all of its elements to \$0\$. For each day we then go though the input population grid row-by-row and column-by-column checking for infected elements. For everyone found we mark that position in the shadow array and its \$4\$ neighbours as infected. After that, on the same day, we then go through the input array again, copying over the corresponding shadow elements and counting the total number of infected for that day. Returns the number of days passed until all are infected. [Answer] # [J](http://jsoftware.com/), 35 bytes ``` 1-~&#<@_>./@:(|.!.0)~&(0,(,-)=i.2)] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DXXr1JRtHOLt9PQdrDRq9BT1DDTr1DQMdDR0dDVtM/WMNGP/a3JxpSZn5CtoWKdpKijpWevFGylogI3R5DIEmgWChlxADGFzGUDFYCygOBcBM7igqrk0/wMA "J – Try It Online") * `(0,(,-)=i.2)`: `0 0,1 0,0 1,-1 0,0 -1` * `<@_ f&dirs ]` repeat `input f dirs` until the result does not change, and return all intermediate steps. * `>./@:(|.!.0)~` shift the board along the directions (with `0`s getting shifted in at the borders), and take the maximum of them all. * `1-~&#` count the steps minus 1. [Answer] # JavaScript (ES6), ~~97~~ 95 bytes ``` f=m=>/0/.test(a=[1,...m,1])&&1+f(m.map((r,y)=>r.map((v,x)=>v|r[x-1]|r[x+1]|a[y][x]|a[y+2][x]))) ``` [Try it online!](https://tio.run/##dY3NCsMgEITveQpPQdFstHfzIuJB0lhaYgwaQgJ9d6v9Cb0EFmbmY3fnYVYT@3Cfl2by1yElK53sWt7CMsQFG6kEAwDHhCZ1LajFDpyZMQ5sJ7ILn7CyLYf1GdTWCF2EZjFq12p7K70URwhJvZ@iHwcY/Q1brCqEcgPivxGaFVTcQTVDX8ZPWdnWVW6oTgqOv/@uHKQX "JavaScript (Node.js) – Try It Online") ### Commented ``` f = m => // m[] = matrix /0/.test( // if there's still a zero in a = [1, ...m, 1] // a[] which is defined as m[] with two dummy border rows ) && // then: 1 + f( // increment the final result and do a recursive call: m.map((r, y) => // for each row r[] at position y in m[]: r.map((v, x) => // for each value v at position x in r[]: // the cell is set if: v | // it's already set r[x - 1] | // or the cell on the left is set r[x + 1] | // or the cell on the right is set a[y][x] | // or the cell above is set a[y + 2][x] // or the cell below is set // NB: both a[0][x] and a[a.length - 1][x] are // undefined (falsy) for any x ) // end of inner map() ) // end of outer map() ) // end of recursive call ``` [Answer] # [Python 3](https://docs.python.org/3/), 131 bytes ``` lambda a,e=enumerate:max([min([abs(x-X)+abs(y-Y)for X,I in e(a)for Y,J in e(I)if J]or[0])for x,i in e(a)for y,j in e(i)if j<1]+[0]) ``` [Try it online!](https://tio.run/##dY1NCoMwEIX3nmKWCY6gdFfqAewJlDSLSBMaqVFSC3r6tDFotaUwi/fzMa@fhltnDk7lF3cXbX0VIFDm0jxbacUgj60YCWu1IUzUDzImJY29mJKKqs5CiQVoA5KI2VZ4DragWsGZd5alfG5G1FtwwiZY7cHmlPHYk6632gxEEcYyhHS5jGMEzIs15AghSv9FnuWc0ijaP11@bcQvFRZn8VWuY5@tnX7j7gU "Python 3 – Try It Online") If nobody is infected in the original, this will return 0. -11 bytes thanks to caird coinheringaahing [Try it online!](https://tio.run/##dYxBCoMwEEX3nmKWCZ2C0l2pB9ATKGkWIyY0olFsBD19ahSLXRRm8f@bxx8W9@rtzev06VvqqpqAUKXKTp0ayal7RzMTnbFMUPVm87XglxCWa8l1P0KBGRgLitFWS8z3mnGjIZdYK01T69J4e89ozvaCzV5NsJtHcvb9MBrrmGZCJAjxcasTgQjhCyXCjuJ/KLhSch5Fv6PH1imslv8A "Python 3 – Try It Online") Older method using recursion: # [Python 3](https://docs.python.org/3/), 199 bytes ``` f=lambda a,c=0:all(sum(a,[]))and c or f([[g(a,x,y+1)+g(a,x,y-1)+g(a,x+1,y)+g(a,x-1,y)+g(a,x,y)for y in range(len(a[x]))]for x in range(len(a))],c+1) g=lambda q,x,y:len(q)>x>=0<=y<len(q[x])and q[x][y] ``` [Try it online!](https://tio.run/##dY7LCoMwEEX3@YpZRowQ6U7UHwlZpL4qxPioheTr7UyrfUEhi5M7M4c7hfUyutO2tYU1w7k2YERVyMxYy6@3gRuhdBQZV0MF4wItV6rD0IsQp1G8Y3JgnIqwY/JGhBZvA/QOFuO6htvGcaM8mjVN/M8EY1Ghn3VHqZksGQ3nqPRlIfMi5I8vWagegQp6m5berZx6pgLk8VItGCiCV6gFPCP5L6JdjR0Z@5Yerg/Are0O "Python 3 – Try It Online") If there is nobody infected in the original, this will recursion overflow. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes ``` I⌈Eθ∨⌈E⌕Aι⁰∨⌊ΦEθ⌊E⌕Aν¹⁺↔⁻ξκ↔⁻πλ¬⁼νIν⁰¦⁰ ``` [Try it online!](https://tio.run/##dY7BCsIwDIbvPkWOLUTYzp6GuJu6e@mhzoHF2G1tJ3v72s5tqGAIafL9/UPqm7J1qyiEymrj2V45z45q1I/hEd@O9Qhn@0VKba4FEdMIGX@r2kxqqck3drEt9NNjEPLoqWhwrLi4lgbfJHscR4Q7j9oP7hCIT4Fwaj079IMilxZNp5pZytbK@S4EIUQexyVziRsAkbqVSoSZZX9Z@i2lDNsnvQA "Charcoal – Try It Online") Link is to verbose version of code. Uses the Manhattan distance method again. Charcoal can't flatten lists, plus it returns `None` for the minimum or maximum of an empty list, which complicates the code somewhat. Explanation: ``` Eθ For each row E⌕Aι⁰ For each `0` value in that row Eθ For each row E⌕Aν¹ For each `1` value in that row ↔⁻ξκ↔⁻πλ Calculate the Manhattan distance ⌊ Take the minimum Φ ¬⁼νIν Filter out `None` values ⌊ Take the minimum ∨ ⁰ Or zero if the list was empty ⌈ Take the maximum ∨⌈ ⁰ Or zero if the list was empty ⌈ Take the maximum I Cast to string Implicitly print ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 41 bytes ``` {|/&/{+/x|-x}''u-\:/:(1=x.)#u:+!(#x),#*x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qukZfTb9aW7@iRreiVl29VDfGSt9Kw9C2Qk9TudRKW1FDuUJTR1mrovZ/moKGoYIBGBpagwgIxxoqhsQEymj@BwA "K (oK) – Try It Online") Maximum of the minimums of the Manhattan distance of each point to each truthy point. ``` { } \ a function with parameter x #*x \ length of the first row , \ appended to (#x) \ the number of rows ! \ odometer (coordinates of the points) + \ transpose u: \ assign to u # \ filter (1=x.) \ the coordinates of the truthy points u-\:/: \ find the differences of the cooridinates \ of each point to each truthy point {+/x|-x}'' \ find the absolute value and sum &/ \ minimum of the Manhattan distances \ to each truthy point |/ \ maximum ``` [Answer] # Java 8, 204 bytes ``` m->{int r=0,f=1,l=m[0].length,i,t,I,J,n;for(;f>0;r++)for(n=f,f=0,i=m.length*l;i-->0;)for(t=4;m[I=i/l][J=i%l]==n&t-->0;)try{m[I-=t-t%3*t>>1][J-=t<2?1-2*t:0]+=m[I][J]<1?f=n+1:0;}finally{continue;}return r;} ``` Minor modification of [my answer here](https://codegolf.stackexchange.com/a/154563/52210). Outputs the result including the first step. [Try it online.](https://tio.run/##rVVLb9swDL7vV7ACOti17FpdT3GVYhg2IAXWw3oMfPASuVMmy4FMdw0C//ZMfrRNBjupgUF@gBT5ifxskqvkKfHztdCr5e/dQiVFAd8TqbcfAKRGYdJkIeC@FhsFLBz7nMfzGDI3strK3vYqMEG5gHvQwGGX@dNtbWx4SFPOqOLZPIwDJfQj/qKSIp3RO6qjNDdOlE7DyHieWwuap9YhpJJnnfWFiqTvW5NmH/l1lM1nXF6qeH7H5bmKOdcfsbVAs9naXZ@jj@efLnA6ZdbKijdXt8y/usBJGHs2lJnVxjfsNuXaY5MwqlKpE6U220WuUepSRJURWBoNJqp2UZvhuvypbIZdok@5XEJmiXIe0Ej9aPlI3JYlFAU6WvyBjqgtXF7CTK9LnDT7AFtGw2axir6orNAq91Vhv8paVo2monDtRjX@1@e1WKBYghFFqXBEIAfgh8L/OeM1jZGL9TAxdr1BsNPnNV@Ade9eCHYS4HCFg5/0ZAQv7mwsxBtQOJTIvyH3R3GUzncY72mPcNEb6nGODiH2KXsvRF9FjYjhKBfDf0Y4/GsNUzc6ipFFtlfmLByq88Mm3/S@pvBfRoGsC54280F0zj8a364lPmwKFFmQlxisbbdEpR3SNgkgzRQBqLt7AwfPMGkBO@de95UdW0GJUgWfjUk2RYB524idZzcwYq3s2HIIEEqI251Qvc6wNi87qHRQj7P6qGgoztbWI@AQrxM4P0zylnzJjbEKMiHfEqnE8uyMuB5xyTBsNzur3V8) **Explanation:** ``` m->{ // Method with integer-matrix parameter and integer return-type int r=0, // Result-integer, starting at 0 f=1, // Flag-integer, starting at 1 l=m[0].length, // Amount of rows i,t,I,J,n; // Temp integers for(;f>0; // Loop as long as the flag is NOT 0: r++) // After every iteration: increase the result by 1 for(n=f, // Set `n` to the current flag-value f=0, // And then reset the flag to 0 i=m.length*l;i-->0;) // Loop over the cells of the matrix: for(t=4; // Set the temp integer `t` to 4 m[I=i/l][J=i%l]==n // If the current cell contains value `n` &t-->0;) // Loop `t` in the range (4,0]: try{m // Get the cell at a location relative to the current cell: [I-=t-t%3*t>>1] // If `t` is 3: // Take the cell above // Else-if `t` is 2: // Take the cell below [J-=t<2?1-2*t:0] // Else-if `t` is 0: // Take the cell left // Else-if `t` is 1: // Take the cell right +=m[I][J]<1? // And if this cell contains a 0: f=n+1 // Fill it with `n+1`, // And set the flag to `n+1` as well : // Else: 0; // Keep the value the same by increasing with 0 }finally{continue;} // Catch and ignore ArrayIndexOutOfBoundsExceptions // (saves bytes in comparison to manual boundary checks) return r;} // And after the loop: return the result ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ΔĀ2FøJT‚12‚:€S]N ``` Outputs the result including the first step. [Try it online](https://tio.run/##yy9OTMpM/f//3JQjDUZuh3d4hRxuetQwy9AITFk9aloTHOv3/390tKGOARgaxupEA0kID8w2QGMD5WJjAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU3lotw6Xkn9pCYRvX6n0/9yUIw1Gbod3eIUcbnrUMMvQCExZPWpaExzr919JL0zn0Db7/9HR0YY6BmBoGKsTDSQhPDDbAI0NlIuN1VEAa4EIQkmwIFw9idAQ2S5SIVCvIWEbwL4yhNKoeg0J6kSFBpjhQ9BOmD5DovUiTDDAcDO667Dbiz2siFCFJIrNv1hdhT8coHqRw4NYvShpjwRbsfsXdwwbYEkbuMOFeHtJzAmgrBQLAA). **Explanation:** ``` Δ # Loop until the result no longer changes, # using the (implicit) input-matrix in the first iteration Ā # Python-style truthify each integer, changing all potential 2s to 1s 2F # Loop 2 times: ø # Zip/transpose; swapping rows/columns J # Join each row of digits together to a string T‚ # Pair 10 with its reversed: ["10","01"] 12‚ # Do the same for 12: ["12","21"] : # Replace all "10" with "12" and all "01" with "21" in all rows €S # And convert each row back to a list of digits ] # Close the nested loops N # And push the 0-based index of the outer loop # (note that the loop until the result no longer changes will loop an # additional time, which is why this results in the correct result # despite having 0-based indexing instead of 1-based) # (after which it is output implicitly as result) ``` [Answer] # [R](https://www.r-project.org/), ~~105~~ 101 bytes *Edit: -4 bytes thanks to Giuseppe* ``` function(m)max(apply(as.matrix(dist(which(m<2,T)[order(-!m),],"man"))[f<-1:sum(!m),-f,drop=F],1,min)) ``` [Try it online!](https://tio.run/##XY7LCsIwFET3/Yra1b1wK426knbrF7grXaRJSwPmQZJq/fqIUvHBbA7DYRifhL0qGeLgQpPG2YiorAGNmi/AnbvcgYet5tGrBaQKEW6TEhPoekdnbK2Xg4dyo5E6KjQ3BWI71iU7hlnDsy5Hkt665tQRI60MYuLNuieAUfVKXhF7Q/UNjPLVQTpg9jkLHLP@fyhfzf2P2WN6AA "R – Try It Online") ``` covidsteps= function(m, # m is input matrix e=m<1) # e is uninfected cells max( # get the max of the distances from each uninfected cell # to its closest infected cell, by apply(...,1,min) # getting the minima of as.matrix( dist(...,"man") # the pairwise manhattan distances between which(m<2,T) # all coordinates [order(-e),]) # ordered with infected cells first [ # and selecting only distances between f<-1:sum(e), # uninfected cells (rows in the distance matrix) -f, # and infected cells (cols of the distance matrix) drop=F]) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 100 bytes ``` ^ ¶ {1s`¶(1.*0|0.*1) _$& }`(?<=(.)*)0(?=(.*¶(?<-1>.)*(?(1)$))?1|(?<=10|¶(?(1)^)(?<-1>.)*1.*¶.*)) 1 _ ``` [Try it online!](https://tio.run/##PYsxDoNAEAP7fQeKdlfKye4J@xMgRQoaCkiXy7d4AB877qQojW3Z4@31XtZnKaOch3y4z@ehTI6M5DSZupt8Z43@ocncoFGDVyb6O4daaSitMwvmRhG5jbUb7c@wPZKbCWUqhQAoaCbAT4kL "Retina 0.8.2 – Try It Online") Takes input as a rectangular digit array. Explanation: ``` ^ ¶ ``` Prepend a newline to provide a work area to build up the result. (While I can append the result instead, that complicates the regular expressions, so it's not any golfier.) ``` {` }` ``` Repeat until a stable position is reached (either all `0`s or all `1`s). ``` 1s`¶(1.*0|0.*1) _$& ``` If the position contains a mixture of `0`s and `1`s then increment the number of days. ``` (?<=(.)*)0 ``` If there is a `0` that ... ``` (?=(.*¶(?<-1>.)*(?(1)$))?1| ``` ... is directly next to a `1` which either to the right or below, or ... ``` (?<=10|¶(?(1)^)(?<-1>.)*1.*¶.*)) ``` ... is either directly to the right of a `1` or directly below a `1`... ``` 1 ``` ... then replace it with a `1`. ``` _ ``` Output the number of days in decimal. The above/below checks are made using .NET balancing groups. The initial `(?<=(.)*)` grabs the column number into `$#1`, and then we have two cases: * `.*¶(?<-1>.)*(?(1)$)1` advances to the next line, advances one character for every column, checks for the correct column (`$` can't possibly match before `1`, so `(?(1)$)` can only match if there are no columns left to advance), and then matches `1`. * `(?<=¶(?(1)^)(?<-1>.)*1.*¶.*)` is a lookbehind, so is matched right-to-left: first it advances to the previous line, then finds a `1`, then advances and checks for the correct column (`^` can't match after `¶` because we're not in multiline mode, but `$` would also work), then checks for the start of the line (it won't be the start of the buffer because of the `¶` added at the beginning of the program). [Answer] # [CJam](https://sourceforge.net/p/cjam), 68 bytes ``` {__{,,:)}:M~\zMm*\_{{_M.*}%\z}2*..{_{a+}{;;}?}:~f{\f{.-:z:+}$0=}$W=} ``` [Try it online!](https://tio.run/##S85KzP1fWPe/Oj6@WkfHSrPWyrcupso3Vysmvro63ldPq1Y1pqrWSEtPrzq@OlG7ttrauta@1qourTomrVpP16rKSrtWxcC2ViXctvZ/3f/oaAMFEmAslwJYgyEYwlgQGkYaIstDNBjCTUBVhqwBysOtAVUxmgZsTkKwsTiJFE/HAgA "CJam – Try It Online") If only I knew how to properly manipulate 2D arrays in this language... Calculates the maximum of each minimum Manhattan distance from each point to each infected point. [Answer] # [Perl 5](https://www.perl.org/) `-00p`, ~~63~~, 60 bytes Saved some bytes thanks to Dom Hastings. ``` / /;$,='.'x"@-";$\++while s/(?<=1$,)0|1\K0|0(?=$,1|1)/1/gs}{ ``` [Try it online!](https://tio.run/##K0gtyjH9X5xYqRKTmaYSY60SY6uubv1fn0vfWkXHVl1PvULJQVcJKKytXZ6RmZOqUKyvYW9ja6iio2lQYxjjbVBjoGFvq6JjWGOoqW@on15cW/3/v6GBAZcBBP/LLyjJzM8r/q9rUPBf19dUz8AQAA "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 115 bytes ``` f=lambda a,e=enumerate:all(map(all,a))or-~f([[1in[0,*r][j:j+3]+[0,*c][i:i+3]for j,c in e(zip(*a))]for i,r in e(a)]) ``` [Try it online!](https://tio.run/##dY3BCsMgDIbvPoVHbTOw9Fbok0gOWafM0lqR7rAd9upOWzrG2CCQ//@S/An39br4NiXbTzSfL8QJTG/8bTaRVtPRNImZgsgdSMolnp5WaN04rxVUEfXYjXWLdXEDate57OwS@QgDd54b8XBBVPl0ow7iTkmiTCE6vworWA4Ero5qEBjXRbwhAt@R@ofKLiKTkrGv2CPtQ/za279uoozTCw "Python 3 – Try It Online") 1-indexed recursive solution. Replaces each item with `True` if itself or any of its orthogonal neighbours are `1` (==`True`). Recursion stops when all values in the array are `True`. ]
[Question] [ What I would like to see is a fractal tree being drawn where the you can input an integer, and the output will be a fractal tree with the entered amount of branch steps. Rules: * The fractal should be a line fractal tree: ![line fractal tree](https://i.stack.imgur.com/WMRSU.gif) * the shape of the fractal should also be the same as this picture. * Each branch should decrease by 25% in width for each time it splits * The final layer of branches should be an 1px wide line * Shortest code wins Tip: [this site](http://rosettacode.org/wiki/Fractal_tree) might be useful. [Answer] ## [Context Free](http://www.contextfreeart.org/), ~~82~~ ~~65~~ 57 characters ``` rule T{9*[y 1]SQUARE[]2*{f 90}T{s.75y 8r 25}}startshape T ``` ![A Tree](https://i.stack.imgur.com/6w23I.png) See: <http://www.contextfreeart.org/gallery/view.php?id=3384> Golf'd further with help from Context Free Art users *minimaleye, MtnViewJohn,* and *kipling*. [Answer] # Logo, ~~88~~, 86 ``` to t:d if:d=0[stop]setpensize:d*.75 fd:d*7 rt 25 t:d-1 lt 50 t:d-1 rt 25 bk:d*7end t [numsteps] ``` ![Tree - size 11](https://i.stack.imgur.com/Rz4DA.png) Edit: Made the branches decrease as pointed out in the comments. [Answer] # Mathematica 127 ``` k=12; r=#2/.{x__Real}:>.1{{7,-#},{#,7}}.{x}+y&; f@n_:={f@1=N@Polygon@{y={0,.7^k},0y,x={.002,0},x+y},r[-4,p=f[n-1]],4~r~p} Graphics@f@k ``` ![enter image description here](https://i.stack.imgur.com/j4kk1.png) Value `.002` adjusted to produce 1 pixel width of the final branches. [Answer] # HTML+CSS (no JavaScript) ~~14791~~ 14630 (multiplatform), 294 (webkit only) You can't specify how many levels you go.. And yes it is pretty big. But it is pure HTML/CSS, without any JavaScript. ``` <style>q{background-color:#000}q::before{content:""}q.start{width:15px;height:100px;position:absolute;top:500px;left:500px}q q{position:absolute;width:75%;height:75%;top:-55%}q q:nth-child(1){left:-90%;transform:rotate(-27deg)}q q:nth-child(2){left:110%;transform:rotate(27deg)}</style><q class="start"><q><q><q><q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q></q><q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q></q></q><q><q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q></q><q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q></q></q></q><q><q><q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q></q><q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q></q></q><q><q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q></q><q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q></q></q></q></q> <q><q><q><q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q></q><q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q></q></q><q><q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q></q><q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q></q></q></q><q><q><q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q></q><q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q></q></q><q><q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q></q><q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q><q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q><q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q><q><q><q><q></q><q></q></q><q><q></q><q></q></q></q><q><q><q></q><q></q></q><q><q></q><q></q></q></q></q></q></q></q></q></q></q></q> ``` Webkit short version: ``` <style>b{background:#000;-webkit-box-reflect: left;}b.i{width:7px;height:100px;position:absolute;top:500px;left:500px}b b{position:absolute;width:75%;height:75%;top:-70%}b b{right:300%;transform:rotate(-27deg)}</style><b class="i"><b><b><b><b><b><b><b><b></b><b></b></b></b></b></b></b></b></b> ``` ![Fractaltree](https://i.stack.imgur.com/2k7xo.png) **Edit:** removed the cross browser prefixes, firefox and google chrome render it properly without it. **Edit 2:** Added a much shorter version that uses -webkit-box-reflect. Only works in webkit based browsers though. [Answer] # Python - 215 ``` import turtle t=turtle.Turtle() def f(w): if w>=1: s=t.pensize() t.pensize(w) t.fd(w*9) t.rt(20) f(w*.75) t.lt(40) f(w*.75) t.right(20) t.bk(w*9) t.pensize(w) t.speed(9) f(9) t.ht() raw_input() ``` Close enough? ![image](https://i.stack.imgur.com/d85Lk.png) [Answer] # Mathematica 199 ``` f[p : {_, _}, r_, s_, d_] := Module[{q}, If[d == 0, Return[]]; q = p + {Cos@r, Sin@r}*d; DeleteCases[ Flatten@{{Thickness[.002*1.25^d], Line@{p, q}}, f[q, r - s, s, d - 1], f[q, r + s, s, d - 1]}, Null]] g@d_ := Graphics[f[{0, 0}, Pi/2, Pi/9, d]] ``` **Example** 8 is the depth of the tree. ``` g[8] ``` ![tree](https://i.stack.imgur.com/ZlEhh.png) [Answer] # Postscript ~~216~~ ~~214~~ 209 Uses the criteria "linewidth==1 pixel" as the recursion bound. *Edit:* juggled some constants. *Edit:* tweak, tweak. ``` /b{gsave dup scale rotate 0 0 0 12 0 0 moveto translate lineto stroke currentlinewidth 0 dtransform dup mul exch dup mul add sqrt 1 ge {28 .75 b -28 .75 b}if grestore}def 2 setlinewidth 200 20 translate 0 6 b ``` binary-token workfile: ``` 0 6 200 20 2 /.{<920>dup 1 4 3 roll put cvx exec}def/${//. 73 .}def %/b{gsave dup scale rotate % gsave=78(N)<4E> dup=56(8)<38> scale=139<8B> rotate=136<88> /b{ %(N8)$<8B88>$ <4E388B88>$ 0 0 0 12 0 0 %moveto translate lineto stroke % moveto=107(k)<6B> lineto=99(c)<63> translate=173<AD> stroke=167<A7> %(k)$<AD>$(c)$<A7>$ %<6B63ADA7>$ % <--this typo makes a pot leaf. :-) <6BAD63A7>$ %currentlinewidth 0 dtransform % clw=38(&) dxfm=55(7) 0(&7)$ %dup mul exch dup mul add sqrt 1 ge % mul=108 sqrt=355 ge=74 add=1 exch=62 (8l>8l)$ add sqrt 1 ge {28 .75 b -28 .75 b} %if grestore}def % grestore=77(M) if=84(T) def=51(3)<33> (TM)$ } %(3)$ %setlinewidth % slw=155<9B> %translate % trsl8=173<AD> <339BAD>$ b ``` # Postscript ~~172~~ 169 Same program using binary token strings. ``` /.{<920>dup 1 4 3 roll put cvx exec}def/${//. 73 .}def 0 6 200 20 2/b{<4E388B88>$ 0 0 0 12 0 0<6BAD63A7>$ 0(&78l>8l)$ add sqrt 1 ge{28 .75 b -28 .75 b}(TM)$}<339BAD>$ b ``` ![output2](https://i.stack.imgur.com/hKRiB.png) [Answer] # CoffeeScript (using Canvas) (289 bytes) [![enter image description here](https://i.stack.imgur.com/aPiEL.png)](https://i.stack.imgur.com/aPiEL.png) The following creates branches until the pixel width is less than 1px. The width and height of the image created is 500px. To see the virtual image that the program draws, add `document.body.appendChild(c)` to the last line of the code. ``` c=document.createElement 'canvas' c.width=c.height=500 t=c.getContext '2d' m=Math b=m.PI/8 f=(w,l,x,y,a)-> t.beginPath() t.moveTo x,y X=x+m.cos(a)*l Y=y+m.sin(a)*l t.lineWidth=w t.lineTo X,Y t.stroke() if w >= 1 f w*3/4,l*3/4,X,Y,a+b f w*3/4,l*3/4,X,Y,a-b f 10,90,250,0,m.PI/2 ``` ]
[Question] [ **This question already has answers here**: [Work it harder, make it better](/questions/57549/work-it-harder-make-it-better) (14 answers) Closed 6 years ago. > > Meta discussion: [Is "(The other day) I met a bear" a duplicate?](https://codegolf.meta.stackexchange.com/q/12490/12012) > > > Your challenge is to output this text: ``` The other day, The other day, I met a bear, I met a bear, A great big bear, A great big bear, Oh way out there. Oh way out there. The other day, I met a bear, A great big bear, Oh way out there. He looked at me, He looked at me, I looked at him, I looked at him, He sized up me, He sized up me, I sized up him. I sized up him. He looked at me, I looked at him, He sized up me, I sized up him. He said to me, He said to me, "Why don't you run? "Why don't you run? I see you ain't, I see you ain't, Got any gun." Got any gun." He said to me, "Why don't you run? I see you ain't, Got any gun." I says to him, I says to him, "That's a good idea." "That's a good idea." "Now legs get going, "Now legs get going, get me out of here!" get me out of here!" I says to him, "That's a good idea." "Now legs get going, get me out of here!" And so I ran, And so I ran, Away from there, Away from there, But right behind me, But right behind me, Was that bear. Was that bear. And so I ran, Away from there, But right behind me, Was that bear. In front of me, In front of me, There was a tree, There was a tree, A great big tree, A great big tree, Oh glory be! Oh glory be! In front of me, There was a tree, A great big tree, Oh glory be! The lowest branch, The lowest branch, Was ten feet up, Was ten feet up, So I thought I'd jump, So I thought I'd jump, And trust my luck. And trust my luck. The lowest branch, Was ten feet up, So I thought I'd jump, And trust my luck. And so I jumped, And so I jumped, Into the air, Into the air, But I missed that branch, But I missed that branch, A way up there. A way up there. And so I jumped, Into the air, But I missed that branch, A way up there. Now don't you fret, Now don't you fret, And don't you frown, And don't you frown, I Caught that branch, I Caught that branch, On the way back down! On the way back down! Now don't you fret, And don't you frown, I Caught that branch, On the way back down! This is the end, This is the end, There aint no more, There aint no more, Unless I see, Unless I see, That bear once more. That bear once more. This is the end, There aint no more, Unless I see, That bear once more. ``` ## Pattern: First, each line is repeated once, linebreak-separated, and then 2 newlines, and then the above stanza is printed without the repetition. Then the next stanza. ## Rules * Trailing whitespace is allowed at the end of the output, but the rest must be printed as-is. [Answer] ## JavaScript (ES6), 690 bytes ``` f=(n=0)=>n<139?[...'DEFJKLMPQRVXYZ~0123456789'].map(c=>s=(e=s.split(c)).join(e.pop()),s=`P2other day9Xme8a 03 09Oh ~F8t6.|H2Yme9XYM9H2VZXV M.|H2said4oZ"Why7run?|Xse2yFEin't9Go8anyDun."|Xsays4o M9"That'sEDood idea."|"Now legsDe8going9ge8m2F8of 6!"1ran9A~Lm469Bu8riKbehindZWasQa80.|In Ln8ofZT6 wasE4Re34Re9OhDlory be!P2lowes5Was4en fee8up9So IQFKI'd jump9J4rus8my luck.1jumped9IntoQ2air9Bu8XmissedQa5A ~up46.|Now7fRt9J7Lwn9XCauKtha5OnQ2~back down!Pis isQ2end9T6Ein8no moR9Unless Xsee9Tha80 onc2moR.9,|8t 7 don'8yF 6heR58branch94 t39ADRa8big2e 1|J so X0bear~way Z me9YlookedE8XI Vsized upRreQ4hP|ThMhimLfroKgh8JAndFouE aD g`)&&s.split`|`[(i=+'11223344012340'[n%14])&&i+(n/14<<2)]+` `+f(n+1):'' console.log(f()) ``` ### How? The 41 unique lyric lines (including the empty one) are stored in a pipe-separated string ***s***. ``` "|The other day,|I met a bear,|A great big bear,|...|Unless I see,|That bear once more." ``` This string is compressed by replacing the most frequent sub-strings with characters that are not used anywhere else. The character set is `"DEFJKLMPQRVXYZ~0123456789"` and the substitutions are processed as follows (note that this is the decompression order): ``` 1. "D" -> " g" | 10. "R" -> "re" | 19. "3" -> "9A grea8big" 2. "E" -> " a" | 11. "V" -> "sized up" | 20. "4" -> " t" 3. "F" -> "ou" | 12. "X" -> "I " | 21. "5" -> "8branch9" 4. "J" -> "And" | 13. "Y" -> "looked a8" | 22. "6" -> "here" 5. "K" -> "gh8" | 14. "Z" -> " me9" | 23. "7" -> " don'8you " 6. "L" -> "fro" | 15. "~" -> "way " | 24. "8" -> "t " 7. "M" -> "him" | 16. "0" -> "bear" | 25. "9" -> ",|" 8. "P" -> "|Th" | 17. "1" -> "|And so I " | 9. "Q" -> "4h" | 18. "2" -> "e " | ``` The compressed format is the one used in several popular JS packers such as [RegPack](https://siorki.github.io/regPack.html): the substituted string is stored just after a last occurrence of the substitution character. Below is an example for `"TwoBearsThreeBearsFourBearsFiveBears!"`, where `"Bears"` is packed as `"~"`: [![compression format](https://i.stack.imgur.com/DGVfP.png)](https://i.stack.imgur.com/DGVfP.png) Hence the decompression formula: ``` c => s = (e = s.split(c)).join(e.pop()) ``` Once ***s*** has been decompressed, we rebuild the original verses by applying the pattern: ``` 00 - Line A 01 - Line A 02 - Line B 03 - Line B 04 - Line C 05 - Line C 06 - Line D 07 - Line D 08 - (empty) 09 - Line A 10 - Line B 11 - Line C 12 - Line D 13 - (empty) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~508~~ ~~491~~ ~~434~~ ~~432~~ 443 bytes ``` “€€€¶‚Ž, I™¬€…Ÿâ, Aƒ‰„¥Ÿâ,Šçƒƒ€Ä€Ç.€½Ÿà€›€á, IŸà€›„š,€½¼¸€¾€á, I¼¸€¾„š.€½‚Þ€„€á, "Why¥Ú't€î‡Ð? I€È€î ain't,†«€Æ©ª." IˆÍ€„„š, "That's€…‚¿Ž©." "Now©Ý€Õ…ì, xget€á€Ä€‚€Î!"€ƒ€Ê I³Þ,‡ë€š€Ç,€³ƒ©•¦€á,€¥€ŠŸâ.€†ˆæ€‚€á,€Ç€¥€…íÍ, Aƒ‰„¥íÍ,Šç»¦€ï!€€™…›ì,€¥—¿î°€¾,€Ê IŠã I'dïÅ,€ƒî瀯³†.€ƒ€Ê IïÅed,‚퀀…Ö,€³ I°‡€Š›ì, Aƒƒ€¾€Ç.€Ó¥Ú't€î fret,€ƒ¥Ú't€î frown, I Caught€Š›ì,€‰€€ƒƒ‚ƒ„‹!€Œ€ˆ€€„–,€Ç ain't€¸€£,•Õ I€È,€ŠŸâˆ…€£.“#•:}nιÉ.sšžD•4вÌ£4ôvyvyðýª'XK})©€Dõ®õ)˜», ``` [Try it online!](https://tio.run/nexus/05ab1e#VVNNa9tAEP0rinoQgUWnnHoppbmYQk@F9mqIG/fiQKMm9SGwGMduSlOK0/RgUiHJ2MGpY5u6KflyAjPIF0Pob9g/4s7Myo0DQpKf3rx5b2c8M/rIVHr2gj9GN9OxcnKmmoCAupOeY6Kcp5OG0UOjQ2gLkEZ4PGkQWOlhlW91nwXG9DGSuksGY5JaQHSYxkpocA3n/HIzZ90DTLJaZAZDKQ0zmvuqWIY2Nr2Agb7RMX59Qm7px0dBnPzbkhcooyP4yUANunDiu05uWsP9TEpcOO7LYj7wNm1G6gS36Ri6RHVfbGxDF39w@SF9w55yPqwXpGM8j0sF/PplyaWHPYVPFGKEoWJT3DsVcl3yjiYN6BqdQMcGYazNnIgP0xfBiCx27qWFhPU5k42c4v6DQQjAg4ArKzxYykZZTSTUJXm3Avob3GIfhnLEKrNLpS0n563hAHeV5MA@HjNlACMy5C9mY1JhTfFMTrMuZOm7jUfRyVIsiWxb9im1dsSyHXiwMDvnzbtCYLs@RDe2S7QPzrP8@/VisKAoHYe2tWjrJt9onhccO@Vm09rcGsEH9gTtSrATWbAWRUjwMFsa9X8IVKo7QvDpL/GISI93SncXuOdvpnF6s0rAyt9f@BlaK/h7q7xVxiGO4cR7/XxnmWZb6a3iGfTxbHl6BFdqNvsH "05AB1E – TIO Nexus") This was painful. [Answer] # Python, ~~897~~ ~~891~~ 875 bytes *6 bytes saved thanks to @Emigna* ``` for x in[['The other day,','I met a bear,','A great big bear,','Oh way out there.'],['He looked at me,','I looked at him,','He sized up me,','I sized up him.'],['He said to me,','"Why don\'t you run?',"I see you ain't,",'Got any gun."'],['I says to him,','"That\'s a good idea."','"Now legs get going,','get me out of here!"'],['And so I ran,','Away from there,','But right behind me,','Was that bear.'],['In front of me,','There was a tree,','A great big tree,','Oh glory be!'],['The lowest branch,','Was ten feet up,',"So I thought I'd jump,",'And trust my luck.'],['And so I jumped,','Into the air,','But I missed that branch,','A way up there.'],["Now don't you fret,","And don't you frown,",'I Caught that branch,','On the way back down!'],['This is the end,','There aint no more,','Unless I see,','That bear once more.']]:print(*(y+'\n'+y for y in x),'',*x,'',sep='\n') ``` [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 23913 bytes ``` -[--->+<]>-.[---->+++++<]>-.---.--[--->+<]>-.+++++[->+++<]>.+++++.------------.---.+++++++++++++.[-->+++++<]>+++.+[->+++<]>+.---.+[--->+<]>+++.-[-->+++++<]>.>++++++++++.>-[--->+<]>-.[---->+++++<]>-.---.--[--->+<]>-.+++++[->+++<]>.+++++.------------.---.+++++++++++++.[-->+++++<]>+++.+[->+++<]>+.---.+[--->+<]>+++.-[-->+++++<]>.>++++++++++.++[++++>---<]>.-[->++++<]>.+[----->+<]>.--------.[--->+<]>---.[---->+<]>+++.[->+++<]>+.-[->+++<]>.[->+++<]>++.+++.----.--[--->+<]>---.[++>---<]>+.>++++++++++.++[++++>---<]>.-[->++++<]>.+[----->+<]>.--------.[--->+<]>---.[---->+<]>+++.[->+++<]>+.-[->+++<]>.[->+++<]>++.+++.----.--[--->+<]>---.[++>---<]>+.>++++++++++.+++[->+++++<]>.-[-->+<]>.++[->+++<]>+.+++++++++++.-------------.----.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.+++++++.--.-[--->+<]>--.[->+++<]>++.+++.----.--[--->+<]>---.[++>---<]>+.>++++++++++.+++[->+++++<]>.-[-->+<]>.++[->+++<]>+.+++++++++++.-------------.----.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.+++++++.--.-[--->+<]>--.[->+++<]>++.+++.----.--[--->+<]>---.[++>---<]>+.>++++++++++.[->++++++++<]>-.-[--->++++<]>.--[--->+<]>--.--[->++++<]>-.-[->+++<]>-.+[--->+<]>+++.-[---->+<]>++.+++++[->+++<]>.++++++.-.[---->+<]>+++.---[->++++<]>.------------.---.+++++++++++++.-------------.[->+++<]>-.>++++++++++.[->++++++++<]>-.-[--->++++<]>.--[--->+<]>--.--[->++++<]>-.-[->+++<]>-.+[--->+<]>+++.-[---->+<]>++.+++++[->+++<]>.++++++.-.[---->+<]>+++.---[->++++<]>.------------.---.+++++++++++++.-------------.[->+++<]>-.>++++++++++..>-[--->+<]>-.[---->+++++<]>-.---.--[--->+<]>-.+++++[->+++<]>.+++++.------------.---.+++++++++++++.[-->+++++<]>+++.+[->+++<]>+.---.+[--->+<]>+++.-[-->+++++<]>.>++++++++++.++[++++>---<]>.-[->++++<]>.+[----->+<]>.--------.[--->+<]>---.[---->+<]>+++.[->+++<]>+.-[->+++<]>.[->+++<]>++.+++.----.--[--->+<]>---.[++>---<]>+.>++++++++++.+++[->+++++<]>.-[-->+<]>.++[->+++<]>+.+++++++++++.-------------.----.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.+++++++.--.-[--->+<]>--.[->+++<]>++.+++.----.--[--->+<]>---.[++>---<]>+.>++++++++++.[->++++++++<]>-.-[--->++++<]>.--[--->+<]>--.--[->++++<]>-.-[->+++<]>-.+[--->+<]>+++.-[---->+<]>++.+++++[->+++<]>.++++++.-.[---->+<]>+++.---[->++++<]>.------------.---.+++++++++++++.-------------.[->+++<]>-.>++++++++++..++[->++++++<]>.-[->+++++<]>++.--[--->+<]>-.++[--->++<]>.+++..----.------.-.-[--->+<]>-.[->+++<]>+.--[--->+<]>-.[---->+<]>+++.+[----->+<]>.--------.-[->+++<]>.>++++++++++.++[->++++++<]>.-[->+++++<]>++.--[--->+<]>-.++[--->++<]>.+++..----.------.-.-[--->+<]>-.[->+++<]>+.--[--->+<]>-.[---->+<]>+++.+[----->+<]>.--------.-[->+++<]>.>++++++++++.++[++++>---<]>.-[->++++<]>.++[--->++<]>.+++..----.------.-.-[--->+<]>-.[->+++<]>+.--[--->+<]>-.[---->+<]>+++.-[--->++<]>--.+.++++.+[----->++<]>.>++++++++++.++[++++>---<]>.-[->++++<]>.++[--->++<]>.+++..----.------.-.-[--->+<]>-.[->+++<]>+.--[--->+<]>-.[---->+<]>+++.-[--->++<]>--.+.++++.+[----->++<]>.>++++++++++.++[->++++++<]>.-[->+++++<]>++.--[--->+<]>-.---[->++++<]>-.----------.-[--->+<]>++.---[->+++<]>.-.-[--->+<]>-.---[->++++<]>+.-----.[------->++<]>.+[----->+<]>.--------.-[->+++<]>.>++++++++++.++[->++++++<]>.-[->+++++<]>++.--[--->+<]>-.---[->++++<]>-.----------.-[--->+<]>++.---[->+++<]>.-.-[--->+<]>-.---[->++++<]>+.-----.[------->++<]>.+[----->+<]>.--------.-[->+++<]>.>++++++++++.++[++++>---<]>.-[->++++<]>.---[->++++<]>-.----------.-[--->+<]>++.---[->+++<]>.-.-[--->+<]>-.---[->++++<]>+.-----.[------->++<]>.-[--->++<]>--.+.++++.+[----->++<]>++.>++++++++++.++[++++>---<]>.-[->++++<]>.---[->++++<]>-.----------.-[--->+<]>++.---[->+++<]>.-.-[--->+<]>-.---[->++++<]>+.-----.[------->++<]>.-[--->++<]>--.+.++++.+[----->++<]>++.>++++++++++..++[->++++++<]>.-[->+++++<]>++.--[--->+<]>-.++[--->++<]>.+++..----.------.-.-[--->+<]>-.[->+++<]>+.--[--->+<]>-.[---->+<]>+++.+[----->+<]>.--------.-[->+++<]>.>++++++++++.++[++++>---<]>.-[->++++<]>.++[--->++<]>.+++..----.------.-.-[--->+<]>-.[->+++<]>+.--[--->+<]>-.[---->+<]>+++.-[--->++<]>--.+.++++.+[----->++<]>.>++++++++++.++[->++++++<]>.-[->+++++<]>++.--[--->+<]>-.---[->++++<]>-.----------.-[--->+<]>++.---[->+++<]>.-.-[--->+<]>-.---[->++++<]>+.-----.[------->++<]>.+[----->+<]>.--------.-[->+++<]>.>++++++++++.++[++++>---<]>.-[->++++<]>.---[->++++<]>-.----------.-[--->+<]>++.---[->+++<]>.-.-[--->+<]>-.---[->++++<]>+.-----.[------->++<]>.-[--->++<]>--.+.++++.+[----->++<]>++.>++++++++++..++[->++++++<]>.-[->+++++<]>++.--[--->+<]>-.---[->++++<]>-.++[->+++<]>++.++++++++.-----.-[--->+<]>-.---[->++++<]>.-----.[--->+<]>-----.+[----->+<]>.--------.-[->+++<]>.>++++++++++.++[->++++++<]>.-[->+++++<]>++.--[--->+<]>-.---[->++++<]>-.++[->+++<]>++.++++++++.-----.-[--->+<]>-.---[->++++<]>.-----.[--->+<]>-----.+[----->+<]>.--------.-[->+++<]>.>++++++++++.+[->+++<]>+.>+[--->++<]>+.+++[->++++<]>.[--->+<]>+.-[---->+<]>++.+[->+++<]>+.+++++++++++.-.[++>---<]>++.[->+++<]>-.[---->+<]>+++.--[->++++<]>+.----------.++++++.-[---->+<]>+++.---[----->++<]>.+++.-------.[------>+<]>++.>++++++++++.+[->+++<]>+.>+[--->++<]>+.+++[->++++<]>.[--->+<]>+.-[---->+<]>++.+[->+++<]>+.+++++++++++.-.[++>---<]>++.[->+++<]>-.[---->+<]>+++.--[->++++<]>+.----------.++++++.-[---->+<]>+++.---[----->++<]>.+++.-------.[------>+<]>++.>++++++++++.++[++++>---<]>.-[->++++<]>.---[->++++<]>-.++++[->+++<]>..--[--->+<]>-.--[->++++<]>+.----------.++++++.-[---->+<]>+++.[->+++<]>+.++++++++.+++++.[++>---<]>++.[->+++<]>-.[++>---<]>--.>++++++++++.++[++++>---<]>.-[->++++<]>.---[->++++<]>-.++++[->+++<]>..--[--->+<]>-.--[->++++<]>+.----------.++++++.-[---->+<]>+++.[->+++<]>+.++++++++.+++++.[++>---<]>++.[->+++<]>-.[++>---<]>--.>++++++++++.[->+++++++<]>+.[--->+<]>++.+++++.[---->+<]>+++.[->+++<]>+.+++++++++++++.[--->+<]>-.-[---->+<]>++.++[->+++<]>+.--[--->+<]>--.-------.[----->++<]>++.------------.>++++++++++.[->+++++++<]>+.[--->+<]>++.+++++.[---->+<]>+++.[->+++<]>+.+++++++++++++.[--->+<]>-.-[---->+<]>++.++[->+++<]>+.--[--->+<]>--.-------.[----->++<]>++.------------.>++++++++++..++[->++++++<]>.-[->+++++<]>++.--[--->+<]>-.---[->++++<]>-.++[->+++<]>++.++++++++.-----.-[--->+<]>-.---[->++++<]>.-----.[--->+<]>-----.+[----->+<]>.--------.-[->+++<]>.>++++++++++.+[->+++<]>+.>+[--->++<]>+.+++[->++++<]>.[--->+<]>+.-[---->+<]>++.+[->+++<]>+.+++++++++++.-.[++>---<]>++.[->+++<]>-.[---->+<]>+++.--[->++++<]>+.----------.++++++.-[---->+<]>+++.---[----->++<]>.+++.-------.[------>+<]>++.>++++++++++.++[++++>---<]>.-[->++++<]>.---[->++++<]>-.++++[->+++<]>..--[--->+<]>-.--[->++++<]>+.----------.++++++.-[---->+<]>+++.[->+++<]>+.++++++++.+++++.[++>---<]>++.[->+++<]>-.[++>---<]>--.>++++++++++.[->+++++++<]>+.[--->+<]>++.+++++.[---->+<]>+++.[->+++<]>+.+++++++++++++.[--->+<]>-.-[---->+<]>++.++[->+++<]>+.--[--->+<]>--.-------.[----->++<]>++.------------.>++++++++++..++[++++>---<]>.-[->++++<]>.---[->++++<]>-.++[->+++<]>++.+[--->+<]>+++.------.+[---->+<]>+++.---[->++++<]>.-----.[--->+<]>-----.-[--->++<]>--.+.++++.+[----->++<]>.>++++++++++.++[++++>---<]>.-[->++++<]>.---[->++++<]>-.++[->+++<]>++.+[--->+<]>+++.------.+[---->+<]>+++.---[->++++<]>.-----.[--->+<]>-----.-[--->++<]>--.+.++++.+[----->++<]>.>++++++++++.+[->+++<]>+.>-[--->+<]>-.[---->+++++<]>-.-------.--[--->+<]>-.+[--->+<]>.-[->+++<]>+.+[---->+<]>+++.[->+++<]>+.-[->+++<]>.++[->+++<]>+.++++++++..-----------.-[--->+<]>-.-[--->++<]>-.-----.+.----.-[-->+<]>--.------------.>++++++++++.+[->+++<]>+.>-[--->+<]>-.[---->+++++<]>-.-------.--[--->+<]>-.+[--->+<]>.-[->+++<]>+.+[---->+<]>+++.[->+++<]>+.-[->+++<]>.++[->+++<]>+.++++++++..-----------.-[--->+<]>-.-[--->++<]>-.-----.+.----.-[-->+<]>--.------------.>++++++++++.+[->+++<]>+.[------->+<]>.-[--->+<]>.++++++++.+[---->+<]>++.++[--->++<]>.-------.++.++++++++++++.+[---->+<]>+++.++[->+++<]>+.--.[--->+<]>---.[---->+<]>+++.++[->+++<]>+.++++++++.------.+++++.-------.---[->+++<]>.>++++++++++.+[->+++<]>+.[------->+<]>.-[--->+<]>.++++++++.+[---->+<]>++.++[--->++<]>.-------.++.++++++++++++.+[---->+<]>+++.++[->+++<]>+.--.[--->+<]>---.[---->+<]>+++.++[->+++<]>+.++++++++.------.+++++.-------.---[->+++<]>.>++++++++++.--[----->+<]>-.--.[--->+<]>---.[---->+<]>+++.+[----->+<]>.--------.--[--->+<]>-.+++++[->+++<]>.++++++.-.[---->+<]>+++.+++++[->+++<]>.---------.[--->+<]>--.-[--->++<]>--.---.+++++++++++++.-------------.--[--->+<]>.+.>++++++++++.--[----->+<]>-.--.[--->+<]>---.[---->+<]>+++.+[----->+<]>.--------.--[--->+<]>-.+++++[->+++<]>.++++++.-.[---->+<]>+++.+++++[->+++<]>.---------.[--->+<]>--.-[--->++<]>--.---.+++++++++++++.-------------.--[--->+<]>.+.>++++++++++..++[++++>---<]>.-[->++++<]>.---[->++++<]>-.++[->+++<]>++.+[--->+<]>+++.------.+[---->+<]>+++.---[->++++<]>.-----.[--->+<]>-----.-[--->++<]>--.+.++++.+[----->++<]>.>++++++++++.+[->+++<]>+.>-[--->+<]>-.[---->+++++<]>-.-------.--[--->+<]>-.+[--->+<]>.-[->+++<]>+.+[---->+<]>+++.[->+++<]>+.-[->+++<]>.++[->+++<]>+.++++++++..-----------.-[--->+<]>-.-[--->++<]>-.-----.+.----.-[-->+<]>--.------------.>++++++++++.+[->+++<]>+.[------->+<]>.-[--->+<]>.++++++++.+[---->+<]>++.++[--->++<]>.-------.++.++++++++++++.+[---->+<]>+++.++[->+++<]>+.--.[--->+<]>---.[---->+<]>+++.++[->+++<]>+.++++++++.------.+++++.-------.---[->+++<]>.>++++++++++.--[----->+<]>-.--.[--->+<]>---.[---->+<]>+++.+[----->+<]>.--------.--[--->+<]>-.+++++[->+++<]>.++++++.-.[---->+<]>+++.+++++[->+++<]>.---------.[--->+<]>--.-[--->++<]>--.---.+++++++++++++.-------------.--[--->+<]>.+.>++++++++++..+++[->+++++<]>.[--->+<]>+++.----------.-[--->+<]>-.---[->++++<]>-.----.[--->+<]>-----.++++[->++<]>+.-[->++++<]>.---[----->++<]>.+++[->+++<]>++.+++++++++++++.[----->++<]>.>++++++++++.+++[->+++++<]>.[--->+<]>+++.----------.-[--->+<]>-.---[->++++<]>-.----.[--->+<]>-----.++++[->++<]>+.-[->++++<]>.---[----->++<]>.+++[->+++<]>++.+++++++++++++.[----->++<]>.>++++++++++.+++[->+++++<]>.[------->+<]>.-[->+++<]>-.+[--->+<]>+++.-[---->+<]>++.++[->+++<]>.++++++++++++.---.--.[->+++++<]>-.---[->++++<]>.------------.---.+++++++++++++.-------------.-[->+++<]>.>++++++++++.+++[->+++++<]>.[------->+<]>.-[->+++<]>-.+[--->+<]>+++.-[---->+<]>++.++[->+++<]>.++++++++++++.---.--.[->+++++<]>-.---[->++++<]>.------------.---.+++++++++++++.-------------.-[->+++<]>.>++++++++++.+[->++++++<]>.++[----->+<]>+.-.[---->+<]>+++.---[----->++<]>.---------.--.+.++++++++++++.[---->+<]>+++.[->+++<]>++.+++.+++.+.+++++.----------.-[--->+<]>-.+[----->+<]>.--------.-[->+++<]>.>++++++++++.+[->++++++<]>.++[----->+<]>+.-.[---->+<]>+++.---[----->++<]>.---------.--.+.++++++++++++.[---->+<]>+++.[->+++<]>++.+++.+++.+.+++++.----------.-[--->+<]>-.+[----->+<]>.--------.-[->+++<]>.>++++++++++.[------>+<]>.++++++++++.--[--->+<]>--.+[---->+<]>+++.---[->++++<]>.------------.-------.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.+++.----.--[--->+<]>---.++[++>---<]>.>++++++++++.[------>+<]>.++++++++++.--[--->+<]>--.+[---->+<]>+++.---[->++++<]>.------------.-------.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.+++.----.--[--->+<]>---.++[++>---<]>.>++++++++++..+++[->+++++<]>.[--->+<]>+++.----------.-[--->+<]>-.---[->++++<]>-.----.[--->+<]>-----.++++[->++<]>+.-[->++++<]>.---[----->++<]>.+++[->+++<]>++.+++++++++++++.[----->++<]>.>++++++++++.+++[->+++++<]>.[------->+<]>.-[->+++<]>-.+[--->+<]>+++.-[---->+<]>++.++[->+++<]>.++++++++++++.---.--.[->+++++<]>-.---[->++++<]>.------------.---.+++++++++++++.-------------.-[->+++<]>.>++++++++++.+[->++++++<]>.++[----->+<]>+.-.[---->+<]>+++.---[----->++<]>.---------.--.+.++++++++++++.[---->+<]>+++.[->+++<]>++.+++.+++.+.+++++.----------.-[--->+<]>-.+[----->+<]>.--------.-[->+++<]>.>++++++++++.[------>+<]>.++++++++++.--[--->+<]>--.+[---->+<]>+++.---[->++++<]>.------------.-------.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.+++.----.--[--->+<]>---.++[++>---<]>.>++++++++++..++[++++>---<]>.+[--->+<]>.-[->+++++<]>-.++[->+++<]>.++++++++++++.---.-.++++++.[---->+<]>+++.+++++[->+++<]>.---------.[--->+<]>--.+[----->+<]>.--------.-[->+++<]>.>++++++++++.++[++++>---<]>.+[--->+<]>.-[->+++++<]>-.++[->+++<]>.++++++++++++.---.-.++++++.[---->+<]>+++.+++++[->+++<]>.---------.[--->+<]>--.+[----->+<]>.--------.-[->+++<]>.>++++++++++.>-[--->+<]>-.[---->+++++<]>-.---.+++++++++++++.-------------.--[--->+<]>-.--[->++++<]>-.-[->+++<]>-.--[--->+<]>--.+[---->+<]>+++.[->+++<]>+.-[->+++<]>.---[->++++<]>.--.-------------..-[->+++<]>.>++++++++++.>-[--->+<]>-.[---->+++++<]>-.---.+++++++++++++.-------------.--[--->+<]>-.--[->++++<]>-.-[->+++<]>-.--[--->+<]>--.+[---->+<]>+++.[->+++<]>+.-[->+++<]>.---[->++++<]>.--.-------------..-[->+++<]>.>++++++++++.+++[->+++++<]>.-[-->+<]>.++[->+++<]>+.+++++++++++.-------------.----.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.+++++++.--.-[--->+<]>--.---[->++++<]>.--.-------------..-[->+++<]>.>++++++++++.+++[->+++++<]>.-[-->+<]>.++[->+++<]>+.+++++++++++.-------------.----.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.+++++++.--.-[--->+<]>--.---[->++++<]>.--.-------------..-[->+++<]>.>++++++++++.[->++++++++<]>-.-[--->++++<]>.--[--->+<]>--.++[->+++<]>+.+++++.+++.+++.+++++++.-[---->+<]>++.[->+++<]>++.+++.--[--->+<]>.[--->+<]>-.[->++++++++<]>-.-[--->++++<]>.--[--->+<]>--.++[->+++<]>+.+++++.+++.+++.+++++++.-[---->+<]>++.[->+++<]>++.+++.--[--->+<]>.[--->+<]>-..++[++++>---<]>.+[--->+<]>.-[->+++++<]>-.++[->+++<]>.++++++++++++.---.-.++++++.[---->+<]>+++.+++++[->+++<]>.---------.[--->+<]>--.+[----->+<]>.--------.-[->+++<]>.>++++++++++.>-[--->+<]>-.[---->+++++<]>-.---.+++++++++++++.-------------.--[--->+<]>-.--[->++++<]>-.-[->+++<]>-.--[--->+<]>--.+[---->+<]>+++.[->+++<]>+.-[->+++<]>.---[->++++<]>.--.-------------..-[->+++<]>.>++++++++++.+++[->+++++<]>.-[-->+<]>.++[->+++<]>+.+++++++++++.-------------.----.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.+++++++.--.-[--->+<]>--.---[->++++<]>.--.-------------..-[->+++<]>.>++++++++++.[->++++++++<]>-.-[--->++++<]>.--[--->+<]>--.++[->+++<]>+.+++++.+++.+++.+++++++.-[---->+<]>++.[->+++<]>++.+++.--[--->+<]>.[--->+<]>-..>-[--->+<]>-.[---->+++++<]>-.---.--[--->+<]>-.++[--->++<]>.+++.++++++++.[->+++<]>.[--->+<]>----.+.[---->+<]>+++.[->+++<]>++.[--->+<]>----.+++[->+++<]>++.+++++++++++++.-----------.+++++.----[->+++<]>.>++++++++++.>-[--->+<]>-.[---->+++++<]>-.---.--[--->+<]>-.++[--->++<]>.+++.++++++++.[->+++<]>.[--->+<]>----.+.[---->+<]>+++.[->+++<]>++.[--->+<]>----.+++[->+++<]>++.+++++++++++++.-----------.+++++.----[->+++<]>.>++++++++++.[------>+<]>.++++++++++.--[--->+<]>--.+[---->+<]>+++.---[->++++<]>.+++[->+++<]>.+++++++++.-[->+++++<]>-.++[->+++<]>.-..[--->+<]>---.[---->+<]>+++.---[->++++<]>+.-----.-[->+++++<]>+.>++++++++++.[------>+<]>.++++++++++.--[--->+<]>--.+[---->+<]>+++.---[->++++<]>.+++[->+++<]>.+++++++++.-[->+++++<]>-.++[->+++<]>.-..[--->+<]>---.[---->+<]>+++.---[->++++<]>+.-----.-[->+++++<]>+.>++++++++++.>-[--->+<]>--.[--->+<]>--.[--->+<]>-----.++++[->++<]>+.-[->++++<]>.---[->++++<]>.------------.+++++++.++++++.++[->+++<]>++.+.++++++++++++.[---->+<]>+++.++++[->++<]>+.+[-->+<]>++.-[--->+<]>++.-[--->+<]>-.-[--->++<]>.+++++++++++.--------.+++.-[->+++++<]>+.>++++++++++.>-[--->+<]>--.[--->+<]>--.[--->+<]>-----.++++[->++<]>+.-[->++++<]>.---[->++++<]>.------------.+++++++.++++++.++[->+++<]>++.+.++++++++++++.[---->+<]>+++.++++[->++<]>+.+[-->+<]>++.-[--->+<]>++.-[--->+<]>-.-[--->++<]>.+++++++++++.--------.+++.-[->+++++<]>+.>++++++++++.+++[->+++++<]>.[--->+<]>+++.----------.-[--->+<]>-.---[->++++<]>.--.+++.--.+.[---->+<]>+++.+[----->+<]>.--[--->+<]>.-[---->+<]>++.++[--->++<]>.+++++++++.+[->+++<]>+.++++++++.[->++++++++++<]>.>++++++++++.+++[->+++++<]>.[--->+<]>+++.----------.-[--->+<]>-.---[->++++<]>.--.+++.--.+.[---->+<]>+++.+[----->+<]>.--[--->+<]>.-[---->+<]>++.++[--->++<]>.+++++++++.+[->+++<]>+.++++++++.[->++++++++++<]>.>++++++++++..>-[--->+<]>-.[---->+++++<]>-.---.--[--->+<]>-.++[--->++<]>.+++.++++++++.[->+++<]>.[--->+<]>----.+.[---->+<]>+++.[->+++<]>++.[--->+<]>----.+++[->+++<]>++.+++++++++++++.-----------.+++++.----[->+++<]>.>++++++++++.[------>+<]>.++++++++++.--[--->+<]>--.+[---->+<]>+++.---[->++++<]>.+++[->+++<]>.+++++++++.-[->+++++<]>-.++[->+++<]>.-..[--->+<]>---.[---->+<]>+++.---[->++++<]>+.-----.-[->+++++<]>+.>++++++++++.>-[--->+<]>--.[--->+<]>--.[--->+<]>-----.++++[->++<]>+.-[->++++<]>.---[->++++<]>.------------.+++++++.++++++.++[->+++<]>++.+.++++++++++++.[---->+<]>+++.++++[->++<]>+.+[-->+<]>++.-[--->+<]>++.-[--->+<]>-.-[--->++<]>.+++++++++++.--------.+++.-[->+++++<]>+.>++++++++++.+++[->+++++<]>.[--->+<]>+++.----------.-[--->+<]>-.---[->++++<]>.--.+++.--.+.[---->+<]>+++.+[----->+<]>.--[--->+<]>.-[---->+<]>++.++[--->++<]>.+++++++++.+[->+++<]>+.++++++++.[->++++++++++<]>.>++++++++++..+++[->+++++<]>.[--->+<]>+++.----------.-[--->+<]>-.---[->++++<]>-.----.[--->+<]>-----.++++[->++<]>+.-[->++++<]>.-[--->++<]>.+++++++++++.--------.+++.-----------.-.[->+++<]>.>++++++++++.+++[->+++++<]>.[--->+<]>+++.----------.-[--->+<]>-.---[->++++<]>-.----.[--->+<]>-----.++++[->++<]>+.-[->++++<]>.-[--->++<]>.+++++++++++.--------.+++.-----------.-.[->+++<]>.>++++++++++.++[++++>---<]>.+[--->+<]>.++++++.-----.[--->+<]>-----.---[->++++<]>.------------.---.--[--->+<]>-.[->+++<]>+.++++++++.+++++++++.[++>---<]>+.>++++++++++.++[++++>---<]>.+[--->+<]>.++++++.-----.[--->+<]>-----.---[->++++<]>.------------.---.--[--->+<]>-.[->+++<]>+.++++++++.+++++++++.[++>---<]>+.>++++++++++.+[->++++++<]>.++[----->+<]>+.-.[---->+<]>+++.++++[->++<]>+.-[->++++<]>.+[----->+<]>.----.++++++++++..++++[->+++<]>.-.-[--->+<]>-.---[->++++<]>.------------.-------.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.[--->+<]>----.+++[->+++<]>++.+++++++++++++.-----------.+++++.----[->+++<]>.>++++++++++.+[->++++++<]>.++[----->+<]>+.-.[---->+<]>+++.++++[->++<]>+.-[->++++<]>.+[----->+<]>.----.++++++++++..++++[->+++<]>.-.-[--->+<]>-.---[->++++<]>.------------.-------.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.[--->+<]>----.+++[->+++<]>++.+++++++++++++.-----------.+++++.----[->+++<]>.>++++++++++.+++[->+++++<]>.-[-->+<]>.--[->++++<]>-.-[->+++<]>-.+[--->+<]>+++.-[---->+<]>++.---[->++++<]>+.-----.[------->++<]>.---[->++++<]>.------------.---.+++++++++++++.-------------.[->+++<]>-.>++++++++++.+++[->+++++<]>.-[-->+<]>.--[->++++<]>-.-[->+++<]>-.+[--->+<]>+++.-[---->+<]>++.---[->++++<]>+.-----.[------->++<]>.---[->++++<]>.------------.---.+++++++++++++.-------------.[->+++<]>-.>++++++++++..+++[->+++++<]>.[--->+<]>+++.----------.-[--->+<]>-.---[->++++<]>-.----.[--->+<]>-----.++++[->++<]>+.-[->++++<]>.-[--->++<]>.+++++++++++.--------.+++.-----------.-.[->+++<]>.>++++++++++.++[++++>---<]>.+[--->+<]>.++++++.-----.[--->+<]>-----.---[->++++<]>.------------.---.--[--->+<]>-.[->+++<]>+.++++++++.+++++++++.[++>---<]>+.>++++++++++.+[->++++++<]>.++[----->+<]>+.-.[---->+<]>+++.++++[->++<]>+.-[->++++<]>.+[----->+<]>.----.++++++++++..++++[->+++<]>.-.-[--->+<]>-.---[->++++<]>.------------.-------.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.[--->+<]>----.+++[->+++<]>++.+++++++++++++.-----------.+++++.----[->+++<]>.>++++++++++.+++[->+++++<]>.-[-->+<]>.--[->++++<]>-.-[->+++<]>-.+[--->+<]>+++.-[---->+<]>++.---[->++++<]>+.-----.[------->++<]>.---[->++++<]>.------------.---.+++++++++++++.-------------.[->+++<]>-.>++++++++++..+++[->++++++<]>.-[--->+<]>.++++++++.+[---->+<]>++.+[->+++<]>+.+++++++++++.-.[++>---<]>++.[->+++<]>-.[---->+<]>+++.--[->++++<]>+.----------.++++++.-[---->+<]>+++.++[->+++<]>.++++++++++++.-------------.[--->+<]>---.[++>---<]>--.>++++++++++.+++[->++++++<]>.-[--->+<]>.++++++++.+[---->+<]>++.+[->+++<]>+.+++++++++++.-.[++>---<]>++.[->+++<]>-.[---->+<]>+++.--[->++++<]>+.----------.++++++.-[---->+<]>+++.++[->+++<]>.++++++++++++.-------------.[--->+<]>---.[++>---<]>--.>++++++++++.+++[->+++++<]>.[--->+<]>+++.----------.-[--->+<]>-.+[->+++<]>+.+++++++++++.-.[++>---<]>++.[->+++<]>-.[---->+<]>+++.--[->++++<]>+.----------.++++++.-[---->+<]>+++.++[->+++<]>.++++++++++++.---.++++++++.---------.[----->++<]>.>++++++++++.+++[->+++++<]>.[--->+<]>+++.----------.-[--->+<]>-.+[->+++<]>+.+++++++++++.-.[++>---<]>++.[->+++<]>-.[---->+<]>+++.--[->++++<]>+.----------.++++++.-[---->+<]>+++.++[->+++<]>.++++++++++++.---.++++++++.---------.[----->++<]>.>++++++++++.++[++++>---<]>.-[->++++<]>.+[->++<]>+.-[-->+++<]>--.--[--->+<]>.++[->+++<]>++.+.++++++++++++.[---->+<]>+++.---[->++++<]>.------------.-------.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.[--->+<]>----.+++[->+++<]>++.+++++++++++++.-----------.+++++.----[->+++<]>.>++++++++++.++[++++>---<]>.-[->++++<]>.+[->++<]>+.-[-->+++<]>--.--[--->+<]>.++[->+++<]>++.+.++++++++++++.[---->+<]>+++.---[->++++<]>.------------.-------.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.[--->+<]>----.+++[->+++<]>++.+++++++++++++.-----------.+++++.----[->+++<]>.>++++++++++.[->++++++++<]>-.--[--->+<]>-.-[->+++++<]>-.---[->++++<]>.------------.---.--[--->+<]>-.--[->++++<]>-.-[->+++<]>-.+[--->+<]>+++.-[---->+<]>++.[->+++<]>++.-.++.++++++++.-[++>---<]>+.+[->+++<]>+.+++++++++++.++++++++.---------.-[->+++++<]>.[--->+<]>-.[->++++++++<]>-.--[--->+<]>-.-[->+++++<]>-.---[->++++<]>.------------.---.--[--->+<]>-.--[->++++<]>-.-[->+++<]>-.+[--->+<]>+++.-[---->+<]>++.[->+++<]>++.-.++.++++++++.-[++>---<]>+.+[->+++<]>+.+++++++++++.++++++++.---------.-[->+++++<]>.[--->+<]>-..+++[->++++++<]>.-[--->+<]>.++++++++.+[---->+<]>++.+[->+++<]>+.+++++++++++.-.[++>---<]>++.[->+++<]>-.[---->+<]>+++.--[->++++<]>+.----------.++++++.-[---->+<]>+++.++[->+++<]>.++++++++++++.-------------.[--->+<]>---.[++>---<]>--.>++++++++++.+++[->+++++<]>.[--->+<]>+++.----------.-[--->+<]>-.+[->+++<]>+.+++++++++++.-.[++>---<]>++.[->+++<]>-.[---->+<]>+++.--[->++++<]>+.----------.++++++.-[---->+<]>+++.++[->+++<]>.++++++++++++.---.++++++++.---------.[----->++<]>.>++++++++++.++[++++>---<]>.-[->++++<]>.+[->++<]>+.-[-->+++<]>--.--[--->+<]>.++[->+++<]>++.+.++++++++++++.[---->+<]>+++.---[->++++<]>.------------.-------.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.[--->+<]>----.+++[->+++<]>++.+++++++++++++.-----------.+++++.----[->+++<]>.>++++++++++.[->++++++++<]>-.--[--->+<]>-.-[->+++++<]>-.---[->++++<]>.------------.---.--[--->+<]>-.--[->++++<]>-.-[->+++<]>-.+[--->+<]>+++.-[---->+<]>++.[->+++<]>++.-.++.++++++++.-[++>---<]>+.+[->+++<]>+.+++++++++++.++++++++.---------.-[->+++++<]>.[--->+<]>-..>-[--->+<]>-.[---->+++++<]>-.+.++++++++++.+[---->+<]>+++.-[--->++<]>-.++++++++++.+[---->+<]>+++.---[->++++<]>.------------.---.--[--->+<]>-.+[->+++<]>++.+++++++++.----------.[->+++<]>.>++++++++++.>-[--->+<]>-.[---->+++++<]>-.+.++++++++++.+[---->+<]>+++.-[--->++<]>-.++++++++++.+[---->+<]>+++.---[->++++<]>.------------.---.--[--->+<]>-.+[->+++<]>++.+++++++++.----------.[->+++<]>.>++++++++++.>-[--->+<]>-.[---->+++++<]>-.---.+++++++++++++.-------------.--[--->+<]>-.[->+++<]>+.++++++++.+++++.++++++.[---->+<]>+++.+[----->+<]>+.+.[--->+<]>-----.+[----->+<]>.++.+++.-------------.-[->+++<]>.>++++++++++.>-[--->+<]>-.[---->+++++<]>-.---.+++++++++++++.-------------.--[--->+<]>-.[->+++<]>+.++++++++.+++++.++++++.[---->+<]>+++.+[----->+<]>+.+.[--->+<]>-----.+[----->+<]>.++.+++.-------------.-[->+++<]>.>++++++++++.>-[--->+<]>.--[--->+<]>---.--.-------.[--->+<]>----..+[---->+<]>+++.++++[->++<]>+.-[->++++<]>.---[->++++<]>-.++++[->+++<]>..-[->+++<]>.>++++++++++.>-[--->+<]>.--[--->+<]>---.--.-------.[--->+<]>----..+[---->+<]>+++.++++[->++<]>+.-[->++++<]>.---[->++++<]>-.++++[->+++<]>..-[->+++<]>.>++++++++++.>-[--->+<]>-.[---->+++++<]>-.-------.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.+++.----.--[--->+<]>---.[-->+++++<]>+++.+++++[->+++<]>.-.-----------.++.--[--->+<]>-.+[----->+<]>.++.+++.-------------.[->+++<]>-.>++++++++++.>-[--->+<]>-.[---->+++++<]>-.-------.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.+++.----.--[--->+<]>---.[-->+++++<]>+++.+++++[->+++<]>.-.-----------.++.--[--->+<]>-.+[----->+<]>.++.+++.-------------.[->+++<]>-.>++++++++++..>-[--->+<]>-.[---->+++++<]>-.+.++++++++++.+[---->+<]>+++.-[--->++<]>-.++++++++++.+[---->+<]>+++.---[->++++<]>.------------.---.--[--->+<]>-.+[->+++<]>++.+++++++++.----------.[->+++<]>.>++++++++++.>-[--->+<]>-.[---->+++++<]>-.---.+++++++++++++.-------------.--[--->+<]>-.[->+++<]>+.++++++++.+++++.++++++.[---->+<]>+++.+[----->+<]>+.+.[--->+<]>-----.+[----->+<]>.++.+++.-------------.-[->+++<]>.>++++++++++.>-[--->+<]>.--[--->+<]>---.--.-------.[--->+<]>----..+[---->+<]>+++.++++[->++<]>+.-[->++++<]>.---[->++++<]>-.++++[->+++<]>..-[->+++<]>.>++++++++++.>-[--->+<]>-.[---->+++++<]>-.-------.--[--->+<]>-.[---->+<]>+++.[->+++<]>++.+++.----.--[--->+<]>---.[-->+++++<]>+++.+++++[->+++<]>.-.-----------.++.--[--->+<]>-.+[----->+<]>.++.+++.-------------.[->+++<]>-. ``` [Try it online!](https://tio.run/nexus/brainfuck#7VwNkusgCD6QAyd4k4tk3v2P0Y0xUUA0Zpt2o6EznTatRVD4wp99wQwAk/v3fwL0b5f3/rFeL1fLkwxYv5rXIct1uPSj4mP9iaMPTzSS9Nfp9y6MjvRXYnQ4ToTO1A2ny8T@dVpG@68gkAl8rIwHIpEdTHxDFG2bhbKQxEmf@tmCYEx@Tydy4Lriblv1QCoscthBMhndNZC7KjShxHGkgv4XhLlH878zHw1r3g0t6ASdB4juAFEAzVLipWqZyxghJ1DiR4bLl5Dw8QzJDBoNfEZX8bQzjirOxpbQ703sjUPEuDn@Bfn@EDUu7puumkTphIr3w2nRGC/nDBJBrwLoGLu98da6wyDMDOieJLOKw1Z6WKSwWUtgnyzCh/TzntyX9OI73B7rinOdc2wQZjAxuNoKEah/lxw8lEKB5tkwF3V3hT8Pxn/HMjGWidgYdZ@DI76rgvQhS7409Wsd9QSld5npzibGRkdxRoFDAY0uCGdPFLPZzLnnL3XzFK/KymxhaHFp4ucAQ/GfQraV3CxjLTycOQ2bSNRHqBRubiDUY0qoQxagV14NWQ1yzGTx1GIztZ/FTidtrqV5pP5fF/XfkVtqrwcp2Dw1mHgmeOAk13qSU81HIoLqinO5Nsn3xOKc6VauRE@UMwUjJBZJKU8nBODRZoIiZvJSZmHntVy3vhAU8cjiN9xeBhQv3Yy27a9OqN@Xj8okeapbjAKtcCFw5SgFDnQ7niai3QIMGg07PmNYrLipmEs9wNnKmzLA2clS/UzWyqMDLa4iLrPuEQ7CNSimflRrlRqUthxjqdQVY9HWkmsxNTmADCwH4KjlFqrWkEFVYFTAVbWuH55ZYwVm0H8yMdC7GDQngBn67oDnzvQSnOy4ULspVo9j9zd65tfA0oDmWRYqo4Xcoc5jBUU9UF3sJvfsnZrqzbk97CpsdERrvWZVxdIDH6luYuJnSHOHTsXnsX6mvzKXBskzL1EoQJjgIWtV@VseDMjM9Hu1n9PN8qKLTAjDqYe0Wnk9xciauwyypLl@8ksF70@kCzxRp6JPBaEW5aik/dSeNdZWMJYAkziWoL5viA/1yIDV4J3M5ddiID6dm0nDIes@1JPfKjCiXFZbCX0l3k0w4D5Djinijj7zAoNeTNDrE9rt5vrE8o1EMfw3@DTQ@IqlfT3D2rT0dGZsrub0wngp1GR9mbKMX8/wQuHwB28NlO2BffB1JhNd3r8swEZhBq7pbMdb6eAP3VpshQ5XqJRi@N2h4abTPpcfGR5CCMNtw0ez/jcNp7VP7bunJ2q5cYDCH2CUj0E9VNpWULyRuJjLfmn/W7@i1v4bhoBwZFz0O7YHwR1gsK1FsWokchPtjT2Ntbza3YyKxLqYl3HE4yjZoGIPoNo3PFVsu5UZvhumjWrc1UoFJZul9un5lcqwE4ulbyVqsUV7tX0EGU61xJQPVuvlBxZvu@p5edIRetiAO7JAsh1WnANP8JSfomoqLeUH7XtkqfHM3fnu4@y/L7PsDgN@5Yhfdf8LCYxxJTMANbx5oHG/Xj8 "brainfuck – TIO Nexus") Did I win? [Answer] # [SOGL](https://github.com/dzaima/SOGL), 395 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ev~½ΠΥ≠ļ‚ļ╚■.ō1Τ⁾⁶J1⅓⁶ζ⅝:‚$η╬Μīβ╚ø○θωΔβ}%⁴šσƧxeρ}∙-Pē§′ī□0▼⅞∫╤Κī,└#%℮Δ:╤╝XN3¾3≤Β╚⌡ææ3─벉7y⅜Η⁸‘→≥℮⅓ƨ9$►,cS|kņ═C⁷Ρv ητΕ▓«⁸○!FΩ§@f▒2čļΓμ±'aΖ[A±wdM∙ξ↓I┐η)℮∙↕↑|G-█lz◄xΖp⁴╤§¬╝╔5ξΣ█⅟Q╗Πψū→iT\]ļ⌡Kōnō╗═↓ΝX~⁶←±;ΔÆ▼η╤→=ō>○ξlζ║╥⌠čø▼e≤ā‼1²ζ∑%′`u¤¹ZΕ⅓╚Ƨ╚═′ž⁽μOģΤΒΨs⅜≡8γ¾:╝ss1⅟p?╬¾⌡░WƧΛφ].zΜ╔D/dσ←╝ΣΡ $β]¤λƨ█‼□nZ⁰⁴ERāv⅔⅔Lv<-ε÷׀@∫νυPθšΦ‚Υ«HΠ¤⅝⅓→∙UWv∞⁵⁾JΕ∙9ø(»≡ΧVδ█∙~³A⁄└υ℮‘+ ¶ΘL{øO4{aIAawa8«-?⁾}≥}≥4{tt≥}≥øO4{O ``` [pastebin of the code because tabs](https://pastebin.com/vBwtkZPS) Explanation: ``` ...‘...‘+ push two compressed strings and joins them together (dunno why one doesn't work) ¶Θ split on newlines L{ repeat 10 times øO output a newline 4{ } repeat 4 times aIA increase variable A, current line of the 40 (default = 0) aw get the Ath (1-indexed) item of the lines a8«- subtract from A 16 ? } if [isn't 0] ⁾ sentence-case it ≥ put the top item of the stack at the bottom (so ontop would be the line array) ≥ put the top item (line array) of the stack at the bottom, so 1st line is ontop 4{ } 4 times do tt output the current line twice ≥ put the top item (current line) on the bottom (so next line is ontop) ≥ put the top item (line array) of the stack at the bottom, so 1st line is ontop øO output a newline 4{O 4 times output current line ``` [Answer] # PHP, 636 Bytes String representation of the 2D array compressed and base64 encoded ``` foreach(explode(8,gzinflate(base64_decode("VVK7ktswDPwVnBo3GtVWlXFSJG5yRZy5mjZhkrFE3PAxGuXrs6CUONeJwALYhy6eSYrnRNas/XimmQsZurJJ/Xgil9gUuga3V149LWYlqYV0iIfjN6ZJ5MGWAJxZVzzfPsz9CEQOv1Go7zvg3xP9tiGbYKlIa3dvfiUr8VBolUqpxk86wtyeJqDRj18FLONKrsahO6Jt1qwL2sHu4k05ZMhwIpaCZTN0Y/ddFprYZXKQ6CRE14/6OXPTI3dSRS/d8RQtZaEzJRNhggq+J5k3xf34GeAUnIcv7AOwyvrN4L5Xr+DTcDxHHYltq7YvOgrrlFRJzB+93Srw1k2SVqx4OWIAPi6cgQCNm99PMBYzSNf3fvyhHIuXqlzOB0u/6oyy0i+pYnJeaaq3x/BUpAi2yCDCLOiBn2lThORDzohlU7HfPLW4kdSetnr4zOaeuGz3/q/JEjXkL6bx+rDuNbajuvNqbg+MLVG1hkwhtxZH+9ctRF0o4qcQdf1nnDhnan+CInarSeKNG2T4Aw==")))as$z) echo strtr("0 0 1 1 2 2 3 3 0 1 2 3 ",explode(9,$z)); ``` [Try it online!](https://tio.run/nexus/php#NZLLrppQAEXnfkVjOtBwE0AQJW3T8FAEERAEgUlzhMNDkMfhzc/feps0a7J3VvZs//xdJdVnVCIIgmQFxyovQ7jaf8RzWkQ5aOHqARrI0H9CGHyZpeOcd1nbDKIxOAVfUlLr3HP3aCnSdjL9aft6@kmGjgfK4Eapc1HDCLauQWXgVC@ZGGh5qDA10OBu@npdG79DioK7cZqzsd3FgHJImlXvXl57DpHK0VNjfGV7ke6cMvrOPEdGM7PC4ar3pFTu5j6mRoNtU@nhnXMZUGEfpTbaO3yZ23U1ZntmaCeo1KL5JPdHVdfOqAGJzigtWQ/qpjl1dEZs/UsyyBUQ/JtGeHgYHivk@e75ygjmgaRxRneNm0yFlmnh4d68tj44zIqpJXFcY8o2o8aIoiXI2YUc9DtOH6YeabS6dREm3gJxPJ28vK13Xq/HCOVHU5l5jKUsNJDZxnLqkdbvMmekTBBfBe3FssaF92ZLi6ion5KT3Ll1Pus80eFMOU1EilVeoUAAamrEebvi0s0kiIKqp3yxyW@JbopzmeT27hQZ6p3OQgu2BaJnHcBOmim8xpXD081U5jFiSOy0B3h2vVY/YuyiOhKZZEPSjv4JY4PWPBIlXQfXMCKLQkwKUGCCXABkwbMmbW40N/z6tVyv16D5Pq8XMEjKb02LWrRaEgtiQb7ZvKHe/KtfcbH8@H8y9uO9Wv/4/PwL "PHP – TIO Nexus") # PHP, 651 Bytes Json encoding of the unique array compressed and base64 encoded ``` foreach(json_decode(gzinflate(base64_decode("XVK7UgMxDPwVcU2aTH6BCRSQBgpgKBIKJ1ZskzuJ8WNujq9HspMLUHq9knZX2m67V4/A2WMEa6Zlt+w2MGAGA3s0Ud9rcBFNhn1wM/bsYTQTcMmgpbjqPpbb7hGhZz6hBaEP2JpdER8GhYSVwrdA5WsmzYBw5l7JBAuZz6Rd9+4nsEyLDBMXiIVuWy1iBUyQL2U+sMinCVyh1a6r3YRlpqTNziJ24tvkRRKfjtlCsGiUrD9PPEKPLoGTHBwHclqhjwGrZT6Cmr45N1+ThcSwgWioBqbRHCMPLRuF7qQqBuclRfRB+M3TuxFNXrOVXJvvDWkp1SGN9KpNJG7VmiPi/51cMNmJ6zlO0uymttLN9jxiEp5IO/h5JMoQFD/lS6EX1Z49F9W3WVj4LEP9UGM5FqkfJujL4bT661d5aOsGSaIVt7KEePErdxRSkrU2h7OCdT0d2fWvy9HIr6s9RsyX+b9RHqmdy72pWv81fqYqQbvvzeEkpSNdkggJQqrfSPaaqtxMBpIT47anN+oxJahH1Vjn5QDTAStNBH/8AA==")))as$z) echo strtr("0 0 1 1 2 2 3 3 0 1 2 3 ",$z); ``` [Try it online!](https://tio.run/nexus/php#NYrZrppQAEXf/YrG9EHjTRRkkLQ3DUcRZJIZ9KVhnsfDIPz8rW3SrJe9V9bPX03SfEV1F7p@sslgXf0OQr8Owk28pFVUuH248VwYEth/v3YsgTRj6XVRJss3UdfgCHDWdBXETSyAm8AjT5gvA3@y5SFrKQ42kmhyLZVXTwctCdLC9jRqS4xLPIt@N6ESS7P0ER7MgOp8cJWTCpmkvQcfhmr4Uhk3XtYqjeeRCZs8FyIBLqOgfBMw2olNHro1dQGN27BcHmDCC5IH9PDOtIDaYRVkZvECJCe9WYM9IykwZ1VEzR2U0upszQniEt3xoRVNa8hLyqNYP@aaJkRZX5whm5rdhVIURlDEmjU4MHF@0SbZxHZPgziXHYbLyM5IfH2K7bQGradxZ0kRteFKtmoLBr/QIg3spKMxvK6y090thx/Hi503iM7KlNDIPEtaZaqkexzxJbnkiaW4H4a57HtRprJXyjT47b5PcF6q1etlX@gE4yBPjLpS9tG2MkxkFMpkJfza5hE/ZCLmGQSBBLh7h6zu3qyeFJhQYbrgpel5Z6IJeT8HxiFAI3ucKe7WEZDS4OzsPErj2jKYSbSxxxMStY9W9cZxCZm80eUgj2NebbtIV1y37V8SaG4GRrqVvKtfvJtwiJVVuHoxaL2XAbc/0fTn53q73brw@7JdhX5Sf4N913eb9WF1WCFv0DfHN//u37laf7zbH19ffwA "PHP – TIO Nexus") # PHP, 720 Bytes Only compressed and base64 encoded ``` <?=gzinflate(base64_decode("lZTBkpswDIbvPIWSSy4Mr9BJe2i5dA+ls2cnKLYbsHZsMwx9+srebBOIKe4t/2dbvyIkNQqBvEILrZjKopnLGnr0IOCEwi7VEaRF4eGk5Sp5UTCKCWjwEIJilSD/9syJWXxD6Iiu2ALf7LF8BvWDVrpPAH7i9G8Gw9tHiJmu75LvV086w3MrZLwgdAue/qbwIPevaoKWzMHDRAPYwXxKMg6LGKXQfFA+g6/EBTYTyMFU+4XKcd0IGM7F5EKEW61nct8o4Q+OP7EkakG3KPjRCv1OI3QoHUhuCknayDINw88eY1vQBUJj7PZpmJlPtklxNC04ghqsMOVShV69WOrfmzUBPnMwq6XiHkel+XG/Bl8FJ63CMPAgVEu5ZZwTsqhNeGPi34stutBNiMXzF6rlLSbJ48iuER5i2ZGd2Hc3FxmWG+HiQuloRMdXuBZnVaZQ/OvIZsgfdXhLgB+hmF7REIpWH1r4NfTrOJTf24Ed+gm64XytUigrk3yH+0cPV7Atn0FtuNG5B3hW7VKFnuB9q53jNfTeB7ec1k+Ocf3yzrpt36XeyiA/chFG8L56LhZ51aRYcHxkNJoVWMMXEas6M07TFxOTDjmdxPnKwUazW6H5af2PFzeLdqBdPEPTlikQpoPXsAfDC5ssptlP06FzEDf3UjUfCwDInDE+qNIwz387+h8=")); ``` [Try it online!](https://tio.run/nexus/php#DdJHkptAAADAv@xpXRyECAMqe8tFzjCSSOLiQjAEgcj58@t9QN/6@8/fr/wom6yOJ/T5jEcEqH8pStoUfX7UkctX3biK2nOBWnC/75Q1XHgdESWdclg9EkljmI/nqEajtW4XbBzQk3c0A1HTiUify65V9rXnF0kzh@hltF1jKs2Aa44grSXjS/FNppBS0feO9lzBEILXKml6Wd/F02Xc9SDcRKCVM8GZGWPKLL8Eoj90kFOZ8qKwynqZ1FJ/zwxtLj7OgpW0hshc85Sb0al/rhpES9wawWGp4o2DjzXcDCsHpmKE10zmsBycJN59uLslexgVGkmKa4rFyLRkSAE4N8nEttQVcyAjVXGlkAZ83YTl7GjktVW9YhaqJt5FzV5ZFj3Oy5X39BcDo@6t13Cq6s0WcCov@tFy/Hvhg0vgDNn78HjYWGsPwlKtUI2FyomvWVkHpGBBLvelmY6i1R37wkYKLElqnOaJt0srPGQw1Ob9qVNsOUs3uiQiJSXUhJS3d6Bganmd6/ZmpeHMR40fR9eTs2jRmGdpWJg5jxVvmblJWheo54GyM3dwdDcjKCnF8jegwn3yynyoyF3F8AT6DDc1uDzNtkLzZBEwviE3M3/pafL1YxHPoORcYU6SkfsxdBMJQrSX3CkpZIU1aWAWEX2Ob49E3Spbb/3AskIpHoGFM668Oa74eqcbbIzVi48AqHScEVA@kJn2fAol6NZlde1aGI5cJgr0OHZTDXEgH5KYkd7Ly4SflY0oYb2trQfJMljBfn38@vX7@/s/ "PHP – TIO Nexus") # PHP, 870 Bytes ``` $b="t branch,";$h=here;foreach([["The other day,","I met a bear,","A great big bear,","Oh way out t$h."],["He looked at me,","I looked at him,","He sized up me,","I sized up him."],["He said to me,",'"Why don\'t you run?',"I see you ain't,",'Got any gun."'],["I says to him,",'"That\'s a good idea."','"Now legs get going,','get me out of $h!"'],["And so I ran,","Away from t$h,","But right behind me,","Was that bear."],["In front of me,","There was a tree,","A great big tree,","Oh glory be!"],["The lowes$b","Was ten feet up,","So I thought I'd jump,","And trust my luck."],["And so I jumped,","Into the air,","But I missed tha$b","A way up there."],["Now don't you fret,","And don't you frown,","I Caught tha$b","On the way back down!"],["This is the end,","T$h aint no more,","Unless I see,","That bear once more."]]as$z)echo strtr("0 0 1 1 2 2 3 3 0 1 2 3 ",$z); ``` [Try it online!](https://tio.run/nexus/php#XVLBbtswDL3nK1jBgDvAKLrtmBVF1sOWy3pYhh7SHmSbsdTYYiDJCNyfz0ip9opBF/vp8Ynvkd/uT@Z0Keo7FaH22jWmUuvC3Bn0uD6QR92Y6/1e7QwCRUah1VOlKrWFASNoqFF7@d9Ax2QWsd2CPRo46wlojBALc6Neqr36idATHbEFJg@Ypf4hxg4CMSvYN4bG00JaAOYsWkHbFiJlUqmezAQtuecywkQj@NHdl6kWMQHaujIK8wdx826CbnQ3qhQxJukpiFbuoWTPOj6XgU12RC3YFjVz@eIXnaHHLkDHEXRkXVcxLD8DJrd0gMJcZd2NayEQbIHTTUFJJAdPg2QiwHcu8LYznB0ay@xs@ElzM0YS5TSz362TQpf0M2knc@KQpcnoEf@fxIzxJLqe/MRiV0lK5tnTGUNRz28hqyN7GE9S8VtajoZGaWxbtvA6DulC/EQ/BjY7QT82x9zbYlN42KaROQ6Td4ZT97NRXhsbAs@RraWnN2lFeKqyXJi1JF@e4vsQDx7j/PBHlM4uL8aDTk3Oio8uPSqytW6OXHN2s2kbwIZ0jS71uCuMLEUExzvE6y7YH9djCJC2Jof8PgUg12CicZ8vOhRvn7AxBCH66K/V7ep29ZnPFz5f@aRf@Vypiqnry@Uv "PHP – TIO Nexus") Expanded ``` $b="t branch,";$h=here; foreach([["The other day,","I met a bear,","A great big bear,","Oh way out t$h."] ,["He looked at me,","I looked at him,","He sized up me,","I sized up him."] ,["He said to me,",'"Why don\'t you run?',"I see you ain't,",'Got any gun."'] ,["I says to him,",'"That\'s a good idea."','"Now legs get going,','get me out of $h!"'] ,["And so I ran,","Away from t$h,","But right behind me,","Was that bear."] ,["In front of me,","There was a tree,","A great big tree,","Oh glory be!"] ,["The lowes$b","Was ten feet up,","So I thought I'd jump,","And trust my luck."] ,["And so I jumped,","Into the air,","But I missed tha$b","A way up there."] ,["Now don't you fret,","And don't you frown,","I Caught tha$b","On the way back down!"] ,["This is the end,","T$h aint no more,","Unless I see,","That bear once more."]]as$z) echo strtr("0 0 1 1 2 2 3 3 0 1 2 3 ",$z); ``` [Answer] # JS (ES6), ~~909~~ 905 bytes ``` x=>(n=` `,a=[[`The other day,`,`I met a bear,`,`A great big bear,`,`Oh way out there.`],[`He looked at me,`,`I looked at him,`,`He sized up me,`,`I sized up him.`],[`He said to me,`,`"Why don't you run?`,`I see you ain't,`,`Got any gun."`],[`I says to him,`,`"That's a good idea."`,`"Now legs get going,`,`get me out of here!"`],[`And so I ran,`,`Away from there,`,`But right behind me,`,`Was that bear.`],[`In front of me,`,`There was a tree,`,`A great big tree,`,`Oh glory be!`],[`The lowest branch,`,`Was ten feet up,`,`So I thought I'd jump,`,`And trust my luck.`],[`And so I jumped,`,`Into the air,`,`But I missed that branch,`,`A way up there.`],[`Now don't you fret,`,`And don't you frown,`,`I Caught that branch,`,`On the way back down!`],[`This is the end,`,`There aint no more,`,`Unless I see,`,`That bear once more.`]],s="",a.map(i=>(i.map(z=>s+=(z+n).repeat(2),s+=n,i.map(z=>s+=z+n)),s+=n)),s) ``` [Answer] ## Batch, ~~984~~ 923 bytes ``` @echo off set s="The other day,_I met a bear,_A great big bear,_Oh way out there._He looked at me,_I looked at him,_He sized up me,_I sized up him._He said to me,_""Why don't you run?_I see you ain't,_Got any gun.""_I says to him,_""That's a good idea.""_""Now legs get going,_get me out of here!""_And so I ran,_Away from there,_But right behind me,_Was that bear._In front of me,_There was a tree,_A great big tree,_Oh glory be!_The lowest branch_Was ten feet up,_So I thought I'd jump,_And trust my luck._And so I jumped,_Into the air,_But I missed that branch_A way up there._Now don't you fret,_And don't you frown,_I Caught that branch_On the way back down!_This is the end,_There aint no more,_Unless I see,_That bear once more." call:c %s:_=" "% exit/b :c for %%l in (%1 %1 %2 %2 %3 %3 %4 %4 "" %1 %2 %3 %4 "")do call:l %%l shift shift shift shift if "%~1"=="" exit/b goto c :l set s=(%~1 echo%s:""="% ``` The quotes really messed me up, but that gave me an idea that saved 61 bytes. [Answer] # C, ~~961~~ 952 bytes ``` #define P(s)puts(s)+ char*s="The other day,I met a bear,A great big bear,Oh way out there.He looked at me,I looked at him,He sized up me,I sized up him.He said to me,_Why don't you run?I see you ain't,Got any gun._I says to him,_That's a good idea.__Now legs get going,get me out of here!_And so I ran,Away from there,But right behind me,Was that bear.In front of me,There was a tree,A great big tree,Oh glory be!The lowest branch,Was ten feet up,So I thought I'd jump,And trust my luck.And so I jumped,Into the air,But I missed that branch,A way up there.Now don't you fret,And don't you frown,I Caught that branch,On the way back down!This is the end,There aint no more,Unless I see,That bear once more.";char a[99],b[99],c[99],d[99];i,j,k,l;f(){char*t[4]={a,b,c,d};for(i=j=k=0;l=s[i++];){t[j][k++]=l-95?l:34;if(l<65&&l-32&&l-39){if(s[i]==95&&l-44)t[j][k++]=34,++i;k=t[j++][k]=0;(j%=4)||P(a)P(a)P(b)P(b)P(c)P(c)P(d)P(d)P("")P(a)P(b)P(c)P(d)P("")0;}}} ``` [Try it online!](https://tio.run/nexus/c-gcc#VVLfb9owEH7nr7gyrU2Gi6qVTmJZVLE9bLyslcbUB4SQiS@JSWIj2xHKKH97d3ZY6SLZyf347r77Li/vBOZSITxGNt61ztJrNMhKbj7YdLgoEbQr0YDgHZtDgw44bJAbNoPCIHewkUXveChhzzvQrQOPwPEPhFrrCgVQWoMEP5ulbBjFrfxDdrvrw68WRT3acinAaR9cP5UdCK2uHHS6BdOqe8pHDBaX5GffNXFTHRStGq8pyDvrwb7TelFyd2WJeqG1ACmQj9frn3oPNRYWCpqq0FIVzH81GGbQOfgpLtYzJcBqmIPhis38iLnRTT8j@0qZRhYl6YClpEzi@sSpcemlIVnGc@XzVShIwYWHkVCejDOI/@kYHKRjUWvTEfzC61/rPVqKU/us7Isj1USi2u7YL8/Mlbr1HOZXArZts2OeszMtwZoO6jarxq9T@DgKNlekDc1A4pkwBS1XWkv699T7brOwUtpIv1Gv2HkJuUEXOr116b2iTX7jgc/bUg8qtPP1NjyrCLRXNJ@0IG2IoBIndWifDhTtXZPCv1WN1kLYNlv8kxW0yjAkjIeJ/1uBL6fTFduEOwu38Hci2ZZVrE7yKD6E39otJ6v0wNmGZUwck1ybSKbbtEpvkjq1SzkarZL44Jbb1bKi77S@nt7d159vJ4nMo/rLp7vLy/r69mO4p/GBnARapek0BCaT@Ay9nbDRSCZVSi6yl9WKmkTb9@kkfn5@jHjcn83pZKcjTmc4fJOQnZ03yfF4fPEiNSRVFA8OA6CHJkwGx5e/) ``` #define P(s)puts(s)+ char*s="The other day,I met a bear,A great big bear,Oh way out there.He looked at me,I looked at him,He sized up me,I sized up him.He said to me,_Why don't you run?I see you ain't,Got any gun._I says to him,_That's a good idea.__Now legs get going,get me out of here!_And so I ran,Away from there,But right behind me,Was that bear.In front of me,There was a tree,A great big tree,Oh glory be!The lowest branch,Was ten feet up,So I thought I'd jump,And trust my luck.And so I jumped,Into the air,But I missed that branch,A way up there.Now don't you fret,And don't you frown,I Caught that branch,On the way back down!This is the end,There aint no more,Unless I see,That bear once more."; char a[99],b[99],c[99],d[99]; i,j,k,l;f() { char*t[4]={a,b,c,d}; for(i=j=k=0;l=s[i++];) { t[j][k++]=l-95?l:34; if(l<65&&l-32&&l-39) { if(s[i]==95&&l-44)t[j][k++]=34,++i; k=t[j++][k]=0; (j%=4)||P(a)P(a)P(b)P(b)P(c)P(c)P(d)P(d)P("")P(a)P(b)P(c)P(d)P("")0; } } } ``` [Answer] # Python3.6, ~~707~~ 648bytes First attempt at code-golf, adopting [@uriel's answer](https://codegolf.stackexchange.com/a/119787/18787) to include compression of the string ``` import zlib,base64 n='\n' for x in zlib.decompress(base64.a85decode("Gaqc3]9:o&%.*X%3&PS1qM!!^OgrLJETV#iKLs/rEPohAPcrDb;W:q/!XiBX3dW2&SeG85%c)sW/nF1_-4Sdn>[gXq'&6f=p%0pg8M-`*4AOe$As#/Z!cVRRnU15<$lom>r'mBomsom`o\\5+:Ju'Znh7rcNXMdK\"<@Xg`5NrGpH^]K)d!ZY5N%;FWa*pA0XB?@HKDjJmEla@$6nAMbB'd//]0'b=QcVOfP7ZQsl0#oXO5*8@^%Bc.>09/Z8g_CX'mrZ[Cl4#91VbG!%q!ro@$UDS_0rLn_5D9673.5%X1$>8$L<pU8^&9ih(%pFc&u,/GaU5c+!7#(!0+&::G<P?8D!U0qk5!fQ`=:c#>;hsK!NfXWFBmNBs-(bpf+$p[`BT./EhYWBiB]G6dCL!;mG4B[^_ILT!it?biY5$D\"mq4aWkQA?VKMQ@GP^87s4\"6>jiMV7+E22L\"oiOm9d=6FeOV`6Ib\#ETWdjr<\A6XX8m+DNOB!%e&\J)")).decode().split('@'):print(*(y+n+y for y in x.split(n)),'',x,'',sep=n) ``` # edit * Changed from base64 to base85 * removed some unnecessary escapes in the compressed string * removed the `ansi` argument from the `decode()` * changed from `$` between verses to `\n` (from @alexis' answer) So this has become a hybrid of my orignal submission, [@uriel](https://codegolf.stackexchange.com/a/119787/18787)'s and [@alexis](https://codegolf.stackexchange.com/a/119923/69140)'s # Compression make one big `bytes`, seperating lines in a verse by `$` and verses by `@` ``` begin_s = """The other day,','I met a bear,','A great big bear,','Oh way out there.'],['He looked at me,','I looked at him,','He sized up me,','I sized up him.'],['He said to me,','"Why don\'t you run?',"I see you ain't,",'Got any gun."'],['I says to him,','"That\'s a good idea."','"Now legs get going,','get me out of here!"'],['And so I ran,','Away from there,','But right behind me,','Was that bear.'],['In front of me,','There was a tree,','A great big tree,','Oh glory be!'],['The lowest branch,','Was ten feet up,',"So I thought I'd jump,",'And trust my luck.'],['And so I jumped,','Into the air,','But I missed that branch,','A way up there.'],["Now don't you fret,","And don't you frown,",'I Caught that branch,','On the way back down!'],['This is the end,','There aint no more,','Unless I see,','That bear once more.""" new_line = '\n' new_s = begin_s.replace("','",new_line).replace('","',new_line).replace("',\"",new_line).replace("\",'",new_line).replace("'],['",'@').replace("\"],['",'@').replace("'],[\"",'@') ``` then compress this with zlib ``` comp_s = base64.a85encode(zlib.compress(new_s.encode())).decode() ``` I tried other algorithms, but this seemed smallest Afterwards checked which characters needed escaping. There were 4`"` and 6 `'` in the string so I used a `"`string. ## base64 vs base85 Base64 gives these lengths ``` original 715 lzma 500 677 zlib 400 544 bz2 436 592 ``` Base85 ``` original 715 lzma 500 625 zlib 400 500 bz2 436 545 ``` lists the `len` of the resulting `bytes` after compression and then after conversion to `base64` [Answer] # C#, ~~560~~ 532 bytes ``` using System;using B=System.IO.MemoryStream;using System.IO.Compression;using System.Text;class p{static void Main(){B i=new B(Convert.FromBase64String("lZXBktowDIbvzPAOgguXTF6hs+2hzaV7aDp7NkTELom9YzuTSZ++khlKIDaYG/pi6xfKL6WWCMZLtNCIqViv6ru4gh49CNijsMvwDVqLwsNetQ/Qu4RRTGAGD5wZyyh6qp2Xeb36gdAZc8IG6HCPRYxUMyBVHyV0y6m/RIbP/2luQXWN6UoZAXnazxOfzwjVgDfXYubx9kNO0Bi98zCZAeygvyQgJUcMsVD0pIiR74YarydoB11uF2Gm+tO04YiYHKe5vIXbeFtL4XeOTNAa04BqUPDFFP5pRuiwddCScVqjdFukKP/uMVjHHIHNs9mmaH5dL0iRoXUDzkAFVuhiGbKzj9b0Z2tHyVdKaVUraShQKrrfp+mHoPolzw/NTrmMMwrIS0zd0nxPh7979vM9qDkjzS530FtMoPnEpxEtgbYzdiL9zX2UJ/006Xk3dWZER6eoPQdZxFloBpIm0ksfPqPkF/fYSzNwJ6tdA3+G/hHn9+LtQDL9BN1wOJVxllvRKzozV/ApbIoYqTRNBrmEBt0uQ7YN7XLlHK20s1MuxT149BZWO23Ay2ZfgIxKXsm/XvH0XpfY0SLvrChk4Tk0o07SCr6J0Opb/QR+16F8rm0vDifKN+pNEr9U3muK7CblQLnwFHVTxAlPE+13D5q+BcZiCv7WHToH4aOwDOvLAgGjDxjulCmaXUeGxj8="));B o=new B();DeflateStream d=new DeflateStream(i,CompressionMode.Decompress);d.CopyTo(o);Console.WriteLine(Encoding.ASCII.GetString(o.ToArray()));}} ``` My second time code golfing! The code converts base64 to byte array then decompress the result in binary. The code of the compression is not displayed. This could be golfed more though! Feel free to suggest. [Answer] # Bash, 863 Bytes ``` echo "/Td6WFoAAATm1rRGAgAhARwAAAAQz1jM4Ah2AjFdACoaCKIDFOe+dP7cKbcEyTzAAg/QvMEQtP11rhlXqhWE7NPlaNhmeElNuKpOqq6JMNkqj/pQaRrgjApagvENO+FmVZT3Wj6eCMH0j29MwN052EeRFsBXigZDjw7DuGAAef52a68lQCl1tH9dnkYyu8k93NXn5exbhDpGUPbcH4kY5+aVF/SCLBHspumKrlX/uqfuYLKPPX+YE7UTFSJ9zPi4Vd2qjgQAbBIIPLx+m2f6ubLOMyS+Bx8OskndeGJ+NL5Hs7/ZK+5yQY9xYTFDPVtEosrkl6WmXgE+UYWkggu+hDaYM+4ci8czabYN5t8lGZVasz1iH4lBS4OzKzj0k/bspdOUXCgDdjBQzazQ82H4fSOX43X6Lp4KnpMV2NoSs334m0s/tuHadQtfRtrHhbjWT2+VPptrA3VMfnBhOYVe6PSmQOhr7s8Oaogin9CtoQmCnmqfhC0Ee8Wn8wnKqy53Vm5vXnl2nkdlciwS+6doHAJAxFWDIo9n+4CxwR6zEd3hy1fdjii5htgnIE4UTCTzBsu/29ftkam+/LBQgL5/VMD/l7rveujYLqwkJEb/OBkd02+Bh7jDA+9DSNEBzCFDTswMAjPb/E18Y8+YhkgWTV953E3n6AgygJhf73EQOJLq8fIjC3Ugn686kpPX2mUlAMVjqOIwlDV7vxXGKCveA2vUXn4t7FGIN/JGYQXKkQgeLnKsi7A9wX+wqMWVmVil61Y0iG717WRjApb+0MtpBgAAAABf85wHBdXu8QABzQT3EAAAGfI0nLHEZ/sCAAAAAARZWg=="|base64 -d|xz -d ``` [Answer] ## C, ~~889~~ 874 bytes ``` char*s="The other day,\0I met a bear,\0A great big bear,\0Oh way out there.\0He looked at me,\0I looked at him,\0He sized up me,\0I sized up him.\0He said to me,\0\"Why don't you run?\0I see you ain't,\0Got any gun.\"\0I says to him,\0\"That's a good idea.\"\0\"Now legs get going,\0get me out of here!\"\0And so I ran,\0Away from there,\0But right behind me,\0Was that bear.\0In front of me,\0There was a tree,\0A great big tree,\0Oh glory be!\0The lowest branch,\0Was ten feet up,\0So I thought I'd jump,\0And trust my luck.\0And so I jumped,\0Into the air,\0But I missed that branch,\0A way up there.\0Now don't you fret,\0And don't you frown,\0I Caught that branch,\0On the way back down!\0This is the end,\0There aint no more,\0Unless I see,\0That bear once more.\0",*p,*w;i;f(){for(w=p=s;*p;++i%4||puts(""),p=(i+4)%8?p+=strlen(p)+1:w,w=i%8?w:p)i%8>3||puts(p),puts(p);} ``` Compile with enabled signed integers wrap-around(-fwrapv). This is needed because function answers must produce repeated output on subsequent calls, and the function could conceivably be called repeatedly until global variable i overflows. Since the code only cares about the whether the remainder of division i by 4 and 8 is 0, it doesn't matter what the actual value of i is as long as it is left divisible by 8 after the function returns (and of course it is left divisible by 8). See it [work here](https://tio.run/nexus/c-gcc#XVJNb5wwEL3vr5ggRQu7NErVHKogGm17aPfSHJoqFy5eGMBdsC1/xKJJ/nq3Y7ObpOUCHt6bee95DnXP9MqUyV2PIG2PGho25dXlFka0wGCHTNNxA51GZmHHu1PptgfPJpDOQuDhRXX5DWGQco8NEHTE2Oa10PMxjxjDf1PFqRPk5UyIuYthvAErZ0CV3PcTNFIsLUzSgXbiJtIQ45lx@kO4r5IEiwk6Jy6qJCLYZEKbeXJFJpldGnLVSdkAb5BFYJV8lx4G7Ax0ZLqTXHSED98jRoOyhWDxLKA3ogEjYQuaiZBMCKHVcpxToMpnImje9ZQW9pzQ0cU9Iyl9iJDiI5dbEVgi9o6Au0CnSIM@qxH/S/1YotS7QeqJ2pxFDgXs0RCG5NT9aRBSdyT9TlHlR1Bre@mCpu2ygV9uDPXgxGpH5HGCwdX7izfuAgabcD@CEiRvlLM@uqPl4MbQnc2GTpM3cSHoHk/7EGJ9vbdWoz1OfVuUXsQt@MKivn9b3oo4OvTdsXpPRC@ib26Am/gPRfOSHq2CBUF7I@NN/BQDGgNxVSLmGD9IUWMEkcgkX6l85QtetGn22Eqd@lKVplipYr3m51dPT8pZkyZJlqsy5eur7PzjjVqXxuoBRaqy9ftrn/uSU9lfq4zenz4cSYo487t4PgRtIylM4UHSemeLxwXQQ1OhWDwvDn/qdmCdObxrvWbq4S8). [Answer] # Python 3.4, ~~779~~ ~~651~~ 649 bytes ``` import zlib,base64 n='\n' for x in zlib.decompress(base64.a85decode("Gaqc3]9:o&%.*X%3&PS1qM!!^OgrLJETV#iKLs/rEPohAPcrDb;W:q/!XiBX3dW2&SeG85%c)sW/nF1_-4Sdn>[gXq'&6f=p%0pg8M-`*4AOe$As#/Z!cVRRnU15<$lom>r'mBomsom`o\\5+:Ju'Znh7rcNXMdK\"<@Xg`5NrGpH^]K)d!ZY5N%;FWa*pA0XB?@HKDjJmEla@$6nAMbB'd//]0'b=QcVOfP7ZQsl0#oXO5*8@^%Bc.>09/Z8g_CX'mrZ[Cl4#91VbG!%q!ro@$UDS_0rLn_5D9673.5%X1$>8$L<pU8^&9ih(%pFc&u,/GaU5c+!7#(!0+&::G<P?8D!U0qk5!fQ`=:c#>;hsK!NfXWFBmNBs-(bpf+$p[`BT./EhYWBiB]G6dCL!;mG4B[^_ILT!it?biY5$D\"mq4aWkQA?VKMQ@GP^87s4\"6>jiMV7+E22L\"oiOm9d=6FeOV`6Ib\\#ETWdjr<\\A6XX8m+DNOB!%e&\\J")).decode().split("@"):print(n.join(y+n+y for y in x.split(n))+n+n+x+n) ``` [Try it online](https://tio.run/nexus/python3#LZJZW6JQAEDf51d42ZECTEHcgVDKDc0FUlzY1GtyQbDvq/nzzTTT6znn8XzBOE2yW@H3Bfp3vpdHcuUXatEuon8dkqzwUYDon@PDKEjiNIvynPmf8Z4ifcMwYjDTuwblTa2eUCRfdMgyNZmVriMAttYxG/a78yUOB8NcyLqT5KRNgszwG3b9KgAH6k45tB@oWWQqEhmwuS2gXml3X5mFqL0@Oleakg@tlBTTozK63xcrmhURWo4LKxAsX17QoiQ1iUsStzM61pM4T@J94roSV@@/0yt0qmbB2BmFAxdrqs5xL40zM33abgZsCFav0phs9GyvmGqio3fUp4Fx7sfdi6cSMtJGvk6HgrARab81DZbWYVJdTfOLiCeOJRUVdUvqAd8Wa8JKOe4eHTrOVuvHSwWvlZa@CcgryBKVWBiznZgN0U4yanK1zEukUyLaCjFspgtlS9XgiSHTXkC93wmmt5ACDlRxBogcVa@bzUlHMcBCvL5J4DDdt@oB3m6c8gEYHxy7p8djPb9n/PTAEel6r895oXt6tXWob0w5fByCRmxW9PV29zycA3jr@PBVIgwXi68Vz36bap3lYDRVzclWqeYVF5PbZzhaVrnuw8PQxRJoxbWwJfcia7mXn33XxbtzOzxnTdfVZMdRYs4YWzogI8p1@xjL8j8fsHyeXuCNwVSMracZRDcG8ecEIuaTQ9xn4fuoz@@jPn5CxLJ/BeI@OMR@ff0B) **Approach** Here's the version without compression: 796 bytes, already a lot shorter than [the original Python answer](https://codegolf.stackexchange.com/a/119787/18787), by @Uriel. That's mainly due to using a single string for the song: An extra `split()` is much more economical than all the brackets of a long list. As a bonus, the non-repeating stanzas are ready to print without reassembly: just print `x`. ``` n='\n' for x in'''The other day, I met a bear, A great big bear, Oh way out there.@He looked at me, I looked at him, He sized up me, I sized up him.@He said to me, "Why don't you run? I see you ain't, Got any gun."@I says to him, "That's a good idea." "Now legs get going, get me out of here!"@And so I ran, Away from there, But right behind me, Was that bear.@In front of me, There was a tree, A great big tree, Oh glory be!@The lowest branch, Was ten feet up, So I thought I'd jump, And trust my luck.@And so I jumped, Into the air, But I missed that branch, A way up there.@Now don't you fret, And don't you frown, I Caught that branch, On the way back down!@This is the end, There aint no more, Unless I see, That bear once more.'''.split("@"):print(n.join(y+n+y for y in x.split(n))+n+n+x+n) ``` I ran the above string literal through `base64.a85encode(zlib.compress(...))` to get the encoded string of the final solution. ### Previous version This version cut the size down to 779 bytes by abbreviating some letter sequences common enough to make up for a huge `replace(...)` to unabbreviate them. No more-- that's what compression software is for. ``` n='\n' for x in'''The other day,I me~a bear,A grea~big bear,Oh way out%ere.@He looked a~me,I looked a~him,He sized up me,I sized up him.@He said to me,"Why don'~you run? I see you ain't,Go~any gun."@I says to him,"That's a good idea." "Now legs ge~going,ge~me ou~of here!"@And so I ran,Away from%ere,Bu~righ~behind me,Was%a~bear.@In fron~of me,There was a tree,A grea~big tree,Oh glory be!@The lowes~branch,Was ten fee~up,So I%ough~I'd jump,And trus~my luck.@And so I jumped,Into%e air,Bu~I missed%a~branch,A way up%ere.@Now don'~you fret,And don'~you frown,I Caught%a~branch,On%e way back down!@This is%e end,There ain~no more,Unless I see,Tha~bear once more.'''.replace("~","t ").replace("%"," th").replace(",",",\n").split("@"):print(n.join(y+n+y for y in x.split(n))+n+n+x+n) ``` [Answer] # Groovy, ~~769~~ 745 bytes ``` a="The other day,xI met a bear,xA great big bear,xOh way out there.xHe looked at me,xI looked at him,xHe sized up me,xI sized up him.xHe said to me,x\"Why don't you run?xI see you ain't,xGot any gun.\"xI says to him,x\"That's a good idea.\"x\"Now legs get going,xget me out of here!\"xAnd so I ran,xAway from there,xBut right behind me,xWas that bear.xIn front of me,xThere was a tree,xA great big tree,xOh glory be!xThe lowest branch,xWas ten feet up,xSo I thought I'd jump,xAnd trust my luck.xNow don't you fret,xAnd don't you frown,xI Caught that branch,xOn the way back down!xThis is the end,xThere aint no more,xUnless I see,xThat bear once more.".split("x") x=0 f={g->x.upto(x+3){print((a[it]+"\n")*g)};println""} 1.upto(9){f(2);f(1);x+=4} ``` Doesn't use any compression. Still working hard on this. **Explaination** ``` a="super long string...".split("x") //a string containing all different verses that gets splitted at each character "x", creating an array with one verse at each position x=0 //used to index the verse array. Starts at 0 f={g->x.upto(x+3){print((a[it]+"\n")*g)};println""} //a shortcut function that prints four consecutives verses starting from verse at position x in the array. The argument g says how many times each verse will be printed. Then adds a new line (stanza finished) 1.upto(9){ //a loop that repeats 8 times f(2) //print a group of four verses two times each one f(1) //print a group of four verses one time each one x+=4 //go to the next group of four } ``` ]
[Question] [ *Adapted from [this](https://stackoverflow.com/questions/70002842/expand-list-of-lists-by-adding-element-once-to-every-list) StackOverflow question* In this challenge you will take a list of lists of integers, e.g. ``` A = [[1,2],[3,4],[5],[]] ``` And an additional single integer (e.g. `n = 7`). If you were to add `n` to the front of one of the lists in `A` there would be as many ways to do that as there are lists in `A`. In this example `4`: ``` A' = [[7,1,2],[3,4],[5],[]] A' = [[1,2],[7,3,4],[5],[]] A' = [[1,2],[3,4],[7,5],[]] A' = [[1,2],[3,4],[5],[7]] ``` In this challenge you will output all possible ways to do this, in the order of how early `n` is inserted. So for the example the output is just: ``` [ [[7,1,2],[3,4],[5],[]] , [[1,2],[7,3,4],[5],[]] , [[1,2],[3,4],[7,5],[]] , [[1,2],[3,4],[5],[7]] ] ``` This is [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'") so answer answers will be scored in bytes with fewer bytes being better. ## Test cases ``` 9, [] -> [] 9, [[]] -> [[[9]]] 10, [[1,2,3]] -> [[[10,1,2,3]]] 7, [[1,2],[3,4],[5],[]] -> [[[7,1,2],[3,4],[5],[]],[[1,2],[7,3,4],[5],[]],[[1,2],[3,4],[7,5],[]],[[1,2],[3,4],[5],[7]]] 2, [[1,2],[2,2],[2]] -> [[[2,1,2],[2,2],[2]],[[1,2],[2,2,2],[2]],[[1,2],[2,2],[2,2]]] ``` [Answer] # [Rust](https://www.rust-lang.org/), 185 184 bytes My first ever code golf submission ``` fn r(a:Vec<Vec<u8>>,n:u8){let mut x:Vec<Vec<Vec<u8>>>=Vec::new();for i in 0..a.len(){let mut b=a.clone();let c=&vec![n];b[i].splice(0..0,c.iter().cloned());x.push(b);}print!("{:?}",x)} ``` **Explanation** This code copies the list for every sublist, then appends the number to the front of it, adds it to a final list which it then prints. We can also get away with returning the print statement to save a ;! [Try it online!](https://tio.run/##RY7dCoMwDIVfJe5ipFCK@2NSp3uL3YgX2nWsoFVquwnis7vqcLtI@EjOOYlxnZ2mhwaDBb9JcZnLRWlKNXcRGSppoXYW@t9yFaSJJ861fCOJH40BBUpDyFjBKqnxby2Tgomq0dLr5plIti8pgkzncZmpnHVtpYRE7wypYMpKg@RruCMhcc9a1z2xJPHYGqVtgJuBX8cN7ck4P14Xyl@DweCSurQdhX1OYeEDhePKpxVyD2efOH0A) Edit: Kevin Cruijssen pointed out a space in my print. Edit: @Bubbler showed me what it's like to truly golf in Rust and got it down to 90 bytes! I won't be updating the byte count in the header since I don't believe that his edits counts as "edits" rather an entire new submission and it doesn't reflect my work. ``` |a:&mut[Vec<_>],n|{for i in 0..a.len(){a[i].insert(0,n);print!("{:?}",a);a[i].remove(0);}} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` UεXšNǝ ``` [Try it online](https://tio.run/##yy9OTMpM/f8/9NzWiKML/Y7P/f/fnCs62lDHKFYn2ljHBEiaAnFsLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXCoZXF/0PPbY04uvDQumK/43P/1@poxvyPjrbUiY6N1VGINjTQiY421DHSMY4F880h3FidaGMdEyBpGgtSGBsLAA). **Explanation:** ``` U # Pop the store the first (implicit) input-integer in variable `X` ε # Map over the second (implicit) input-list of lists: Xš # Prepend `X` in front of the current part Nǝ # And replace the item at the current map-index in the second (implicit) # input-list with this modified part # (after which the result is output implicitly) ``` [Answer] # [Haskell](https://www.haskell.org/), 37 bytes This is [Willem Van Onsem's SO answer](https://stackoverflow.com/a/70002937/4040600) with a couple of trivial golfs. ``` n!(a:b)=((n:a):b):map(a:)(n!b) _!_=[] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P09RI9EqSdNWQyPPKlETyLLKTSwACmlq5CkmaXLFK8bbRsf@z03MzLMtKMrMK1ExV4yONtQxitWJNtYxAZKmQBwb@x8A "Haskell – Try It Online") [Answer] # APL+WIN, 36 bytes Prompts for the list of lists as a nested vector then the integer to be added. Index origin = 0 ``` m←((⍴n)*2)⍴n←,⎕⋄m[(1+⍴n)×⍳⍴n]←⎕,¨n⋄m ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tfy6QqaHxqHdLnqaWkSaIBgroABU96m7JjdYw1AZLHZ7@qHcziBULlAVK6hxakQdS8B9oBtf/NK5HvWu4LLmAdFeToYKRgjGXoQGQpwFkaypoGCuYAElTIAYq0@Qy5@ICAA "APL (Dyalog Classic) – Try It Online") [Answer] # [J](http://jsoftware.com/), 22 17 21 20 bytes ``` (<@#"0~[:=#\),&.>"1] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NWwclJUM6qKtbJVjNHXU9OyUDGP/a3JxcaUmZ@QrmCukKRgqGCkYW1soWFobQgQNDYCiOlY2YAmEOpNqPaCItbGCibXpfwA "J – Try It Online") Could save 4 bytes if we can assume each element of the input is unique. Consider `7 f 1 2 3; 1 2; 4`: * `[:=#\` Create an identity matrix whose sides equal our list length: ``` 1 0 0 0 1 0 0 0 1 ``` * `<@#"0~` Use that as a mask to copy our new element, and box each result. Zeros become empty boxes: ``` ┌─┬─┬─┐ │7│ │ │ ├─┼─┼─┤ │ │7│ │ ├─┼─┼─┤ │ │ │7│ └─┴─┴─┘ ``` * `,&.>"1]` For each row, join elementwise to the original input: ``` ┌───────┬─────┬───┐ │7 1 2 3│1 2 │4 │ ├───────┼─────┼───┤ │1 2 3 │7 1 2│4 │ ├───────┼─────┼───┤ │1 2 3 │1 2 │7 4│ └───────┴─────┴───┘ ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 41 bytes ``` t=>a=>a.map(u=>a.map(v=>u==v?[t,...u]:v)) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/E1i4RiPRyEws0SmGMMlu7UlvbMvvoEh09Pb3SWKsyTc3/yfl5xfk5qXo5@ekaaRqWmhrRsZqaXKiihgZA4WhDHSMd41hMWXOoZKxOtLGOCZA0BWIs6owQ6owgJEjRfwA "JavaScript (Node.js) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes ``` (i=1;x##~Insert~{i++,1})/@#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@18j09bQuuL9pIXKynWeecWpRSV11Zna2jqGtZr6Dspq/wOKMvNKHNKiq6sNdRSManUUqo11FExAtCmIqAUS5rH/AQ "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 54 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 6.75 bytes ``` vJ¨2¹^Ȧ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwidkrCqDLCuV7IpiIsIiIsIltbMSwyXSxbMyw0XSxbNV0sW11dXG43Il0=) Bitstring: ``` 100010101100011111000100110100010110110111100010110010 ``` [Answer] # [Uiua](https://uiua.org), ~~13~~ 12 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` ≡⍜(⇌⊔⊡)⊂⇡⊃⧻¤ ``` [Try it!](https://uiua.org/pad?src=0_3_1__ZiDihpAg4omh4o2cKOKHjOKKlOKKoSniioLih6HiioPip7vCpAoKZiB7fSA5CmYge1tdfSA5CmYge1sxIDIgM119IDEwCmYge1sxIDJdIFszIDRdIFs1XSBbXX0gNwpmIHtbMSAyXSBbMiAyXSBbMl19IDIK) -1 thanks to Bubbler ``` ≡⍜(⇌⊔⊡)⊂⇡⊃⧻¤ ⊃⧻¤ # fix the array and get its length ⇡ # range (of length) ≡⍜(⇌⊔⊡) # change each unboxed reversed row by... ⊂ # join (the integer input) # then unreverse, re-box, and put each item back ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 33 bytes ``` L$`\[+(?=(.+),(.+)) $>`$2,$1 ,] ] ``` [Try it online!](https://tio.run/##K0otycxLNPz/30clISZaW8PeVkNPW1MHRGhyqdglqBjpqBhy6cRyxf7/Hx1tqGMUqxNtrGMCJE2BODZWxxwA "Retina – Try It Online") Takes `n` as the second argument. Explanation: ``` L$`\[+(?=(.+),(.+)) ``` Find the beginning of each list. ``` $>`$2,$1 ``` For each occurrence, output the list with `n` moved to that position. ``` ,] ] ``` Fix up the list if it was originally empty. [Answer] # [Python 3](https://docs.python.org/3/), 50 bytes ``` lambda a,L:[[[a][:l is k]+l for l in L]for k in L] ``` [Try it online!](https://tio.run/##bY9BC8IwDIXv/RWhp1WjqFOKgwkeBcGLt9hDxQ3H6ja2IvjrZ@rUix4a3vteQpPm4a91Ffd5euqdvZ0vFizuEyKyhhIHRQelGTvI6xbYVbA3QZaD7MUxlVKuEcjAZMNVzGdsaI4LjM3A2M3wDYzQ79ggxbjkuuL37dT4G@GnX@NfPECNf3GAmv/lLadd4wofyVMlFe9NNLrZJsru1qH/ZGENqdTrRh9uPBoR9A4PL5fYrstaD3k02qk0PYimLSqe2zoHdSlV/wQ "Python 3 – Try It Online") Will not work on lists with multiple references to the same object. I..e.: `L = [[10],[10]]` fine (same value but different objects) but `L = 2*[[10]]` fail (twice the same object) [Answer] # [R](https://www.r-project.org/), 58 bytes Or **[R](https://www.r-project.org/)>=4.1, 44 bytes** by replacing two `function` occurrences with `\`s. ``` function(x,A)Map(function(i){A[[i]]=c(x,A[[i]]);A},seq(A)) ``` [Try it online!](https://tio.run/##bY5BCsJADEX3nmLATQIRrLUMIhXmAJ4gZCGDAwNSra0giGcfJ61KF13kJ7z/P@SeQp3Co/F9vDbwJIfH0w3@IOLLMUeR2qs5nLh3b@rOLTjEFGBH5hK7HhCXZnUwLIsAxfoLPRS0oRJ/JnO2BiSiQTvNIXkoaaurUpm0rJaEONtZqzySh0doaRaP0NIsVmjzD@kD "R – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), 47 bytes ``` n\l=(k=keys(l)).|>i->k.|>j->[fill(n,i==j);l[j]] ``` [Try it online!](https://tio.run/##bc3BCsIwDAbg@54khU6sU6RI@yJZDwMV0oYy3AQHe/cu4mVCD38C@X5IfDMN5lNK7tlBcumxTMBKHVZPrU@yYuvxScyQNTkX1Y0xhlDuNI08LGB7DKoZX5RnzqCa3R1DVcxRyOiT7up@/XHQ2OmzzIuk3rT2@8WI/2dfLhs "Julia 1.0 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 60 bytes ``` ->n,l{(0...t=l.size).map{|i|[*l[0,i],[n]+l[i],*l[i+1...t]]}} ``` [Try it online!](https://tio.run/##bY5NDoIwEIX3nqKJG5WhoQXSuICLTGahiSRNKiH@LBQ4e50KKFEW8zr93pt2Lvfjw1eFj8saXLtJpJS3wsmrfZ628nxo2s52uHOYgCXAmiKH3DCwkQpZor73jagwB0TFEc2VcmVEtArGHgQSrUVc8vkmQiXMUIGGlCaL7wlMaIiZMRVehIw155oGwoSBfxemEQOLeIAGFnGA5vO/0N8F9KCzdTX8ODDLLrFRifwL "Ruby – Try It Online") [Answer] # [ayr](https://github.com/ZippyMagician/ayr), 15 bytes Beats J by 5 bytes, so I'm happy :) ``` ],`"\:]:#":i:&# ``` # Explanation ``` i:&# Construct an NxN identity matrix (N = # lists) #": Foreach num I in that, replace with left arg I times ]: Convert that to a hook \: For each item on the right and entirety of left ,`" Concatenate left to back of right on an element x element basis ] Where the left is the list ``` Takes the number on the left and the list of lists on the right. [Answer] # jq, 51 bytes ``` . as$a|[range(length)]|map(. as$i|$a|.[$i]|=[$n]+.) ``` Where `$n` is `n`. [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/index.html), 21 bytes ``` n!(a++b:c)=a++(n:b):c ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m706ubSoqDK-IDE7uXjBgqWlJWm6FlvzFDUStbWTrJI1bYG0Rp5VkqZVMkRuf25iZp6CrYK5gqJCdLShjlGsTrSxjgmQNAXi2FiIKphJAA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` IEηEη⎇⁼κμ⮌⊞O⮌λθλ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQCNDRwFKhaQW5SUWVWq4FpYm5hRrZOso5GrqKASllqUWFadqBJQWZ/gXpBYlluQXacAEc4AKCjWBRI4mCFj//x9trhMdbahjFKsTbaxjAiRNgTg2Nva/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` η Input list of lists E Map over each list η Input list of lists E Map over each list κ Outer index ⁼ Equal to μ Inner index ⎇ If true then λ Current list ⮌ Reversed θ Input `n` ⊞O Appended ⮌ Reversed λ Otherwise current list I Cast to string Implicitly print ``` Charcoal's default output format might be a little tricky to read, so here's a 17-byte version with prettier output: ``` Eη⭆¹Eη⎇⁼κξ⮌⊞O⮌νθν ``` [Try it online!](https://tio.run/##NYpNC8IwEET/So4bWA/1Aw@ePYqlegs5LGUxYkjbTVr0168p6MAMvMf0gaQfKKq28kwFLjRCQHMrlR4rNGh@7s6SSD5wnmaKGV5o3hZNxwtLZmjnHK4jC5VB4C9TPUy2TrJrTqruiM41uPXodrive6j13utmiV8 "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # JavaScript (ES6), 44 bytes Expects `(n)(list_of_lists)`. ### Version 1 ``` n=>a=>a.map((v,i,[...b])=>(b[i]=[n,...v],b)) ``` [Try it online!](https://tio.run/##ZYrBCsIwEETvfskurIttFfGQ/siyh6S2EqlJaSW/H1foRYSZObw3T1/8NqxxeR9Tvo91cjW53lv45ReAQpGEmYOi6yFIVCeJDBSlgFiHnLY8jzznB0xwQxBFPPzS5mRYGmqp03973aWSdHS2vVi/v/oB "JavaScript (Node.js) – Try It Online") ### Version 2 ``` n=>a=>a.map((_,i)=>a.map(v=>i--?v:[n,...v])) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i4RiPRyEws0NOJ1MjVhnDJbu0xdXfsyq@g8HT09vbJYTc3/yfl5xfk5qXo5@ekaaRqWmhrRQFEuVFFDA6BwtKGOkY5xLKasOVQyVifaWMcESJoCMUjdfwA "JavaScript (Node.js) – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 48 bytes ``` (n,a)->matrix(#a,,i,j,concat([n][1..i==j],a[j])) ``` [Try it online!](https://tio.run/##Fco7CoAwEEXRrQg2E3gK/rCKGxmmGARlAsYQUrj7qMU91U2arTtTPRpfKUJdt11asj3UKmAI2O@4ayGOwkPfm/dBoBzEuZqyxUIHrWAeMAp4wvy5fMk/vA "Pari/GP – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip) `-xP`, 13 bytes ``` aRA_(BPEb)MEa ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSbkWAUuyCpaUlaboWaxODHOM1nAJckzR9XRMhYlCp3dFK0dGG1kax1tHG1iZA0hSIY2OVdBTMYboB) ### Explanation The `-x` flag evaluates the inputs, meaning we can treat `[[1];[2;3]]` as a list rather than a string. ``` aRA_(BPEb)MEa a First command-line input (the nested list) ME Map the following function to that list, enumerated (first function arg is index, second function arg is sublist): a The whole list RA Replace the element at index given by _ first function arg ( ) with B second function arg PE with the following value prepended: b Second command-line input ``` The `-P` flag prints each sublist of the result, formatted as a list, on a separate line. Other formats that could work include `-p` and `-S`. [Answer] # [Ruby](https://www.ruby-lang.org/), 42 bytes ``` ->n,l{i=-1;l.map{|w|z=*l;z[i+=1]=[n]+w;z}} ``` [Try it online!](https://tio.run/##bY7NCoMwEITvfYpAb3UsJlpCkfgiyx7agyBYkUKR@vPsaVJNK62HnZBvZpK9P65PWxobFw3qoTKxzOvj7dIOYzf25lDnPVWRkWyo4ajL@2myrSjpBCLJIOUmdZMx884bZwhi3ou4cOebCJk4RhIKKQfL3RMENMf0kvIvInN6chMKvqHx7yJUNDbxDDU2sYf6879Q3wXUrKt1FX4crLJbbFFm@wI "Ruby – Try It Online") [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 24 bytes ``` 1svsa.*zi{{1gv+]}x/ap}^m ``` [Try it online!](https://tio.run/##SyotykktLixN/V@Q@t@wuKw4UU@rKrO62jC9TDu2tkI/saA2Lvd/ccF/oJCCUa1CtbGCCZA0BeLaWgVLAA "Burlesque – Try It Online") I'm sure there's a better way... ``` 1sv # Save input as 1 sa.* # Repeat arr len(arr) times zi # Zip with indices { { 1gv # Get input (value1) +] # Prepend } x/ # Reorder local stack ap # Apply function to index (from zip) }^m # Push and map each ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü↨○◘╞Q┐p☺Ç ``` [Run and debug it](https://staxlang.xyz/#p=81170908c651bf700180&i=9,+%5B%5D%0A9,+%5B%5B%5D%5D%0A10,+%5B%5B1,2,3%5D%5D%0A7,+%5B%5B1,2%5D,%5B3,4%5D,%5B5%5D,%5B%5D%5D%0A2,+%5B%5B1,2%5D,%5B2,2%5D,%5B2%5D%5D&m=2) ]
[Question] [ For this challenge, you will be given a long string as an input. With this string, you must create a dictionary. ## Details: This dictionary will contain all the words from the string - a word being any sequence of letters surrounded by non-letter characters (ASCII). Letter case of the entries of the dictionary should always be consistent (i.e. all lower case or all upper case, or only the first letter of each word is capitalised). The dictionary can be a list, array, or any other type so long as the words are distinct from each other. Finally, as this is a dictionary, the words must be in alphabetical order, and there may not be any duplicates. You can assume no contractions will be used (the input will never contain `it's`, `there's`, etc.), and that there will always be at least one word ## Some examples: ``` "this is an eXaMpLe of an Input" -> ["an","example","input","is","of","this"] "Here is another example of an input, this time with Punctuation!" -> ["an","another","example","here","input","is","of","punctuation","this","time","with"] "290(&79832aAa(*& *79 --=BBBb)bbBb ( x )*d -cxaAa_" -> ["aaa","bbbb","cxaaa","d","x"] ``` ## Scoring Shortest code wins [Answer] # JavaScript (ES6), ~~57~~ 51 bytes Returns a Set of words in lower case. NB: In JS, the elements of a Set are guaranteed to appear in insertion order. In this case, this is the order defined in the sorted array the Set is built from. ``` s=>new Set(s.toLowerCase().match(/[a-z]+/g).sort()) ``` [Try it online!](https://tio.run/##jZBBS8NAEIXv/opxD2U3NonUQ@0hgvGiUEHwIpQgk3TSRNrdkN2Y4J@P0zSlqD247M7bgdn3PvYDP9FmdVk5X5s19XnU2@hOUwuv5KQNnFmaluoHtCRVsEOXFTJcof@VXIUbFVhTO6lUnxltzZaCrdnIXApXlBZ4owZ6w@dqSWDyffekq8YJpeAfKwxhJVCLqaAOd9WW@FYO71ktF5Nz2UeJ5OIXwCPVdAAwrqAaRoeRYnCZwkDpyh1BW7oCXhqduQZdafTlgHgCGG1@oHB/nqg6@Rz5WDiGZR/0l3a2uJaT@eL2Zob3KL0JePMF@H4Ux3Gq0jROQUIHyluDn3U88n7uBw@0iJyS8mLh2aFd8@lE0n8D "JavaScript (Node.js) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) `-nl`, 33 bytes ``` p$_.upcase.scan(/[A-Z]+/).sort|[] ``` [Try it online!](https://tio.run/##NYxBC4IwHMXvfYp/EKLWNOxgHjroqaCgYyQi21o40G24jQz67C0tgnf58X7v9ZY8nVOLOrKKYs0iTbHw4zJH12oZB5GWvXmVlXOm4RrGYAHsgk/qyEDeJzoIZc1sz3r2q6VpWA9swJ1q/w6fnBV8PwzvGDy4aeBsBTUWGy7FfJZka99Ls@0mwTn2Qw/CNAOEdkVRkICQgoAPAwThDRAdRqV@SzUttUOi/QA "Ruby – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` èñ≤!á~¬ ``` [Run and debug it](https://staxlang.xyz/#p=8aa4f321a07eaa&i=%22this+is+an+eXaMpLe+of+an+Input%22%0A%22Here+is+another+example+of+an+input,+this+time+with+Punctuation%21%22%0A%22290%28%2679832aAa%28*%26+*79+--%3DBBBb%29bbBb+%28+x+%29*d+-cxaAa_%22&a=1&m=2) The output dictionary is produced as a space separated word list. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 16 bytes ``` S{c:r0Q"[^a-z]"d ``` [Try it online!](https://tio.run/##K6gsyfj/P7g62arIIFApOi5RtypWKeX/fyUjSwMNNXNLC2OjRMdEDS01BS1zSwVdXVsnJ6ckzaQkpyQFDYUKBU2tFAXd5AqgknglAA "Pyth – Try It Online") ``` S{c:r0Q"[^a-z]"d Implicit: Q=input(), d=" " r0Q Convert input to lowercase : "[^a-z]"d Regex replace non-alphas with a space c Split on spaces { Deduplicate S Sort, implicit print ``` [Answer] # gawk -F[^a-zA-Z]+, 93 bytes ``` {for(i=1;i<=NF;i++){if($i!=""){a[tolower($i)]=1}}n=asorti(a,b);for(j=1;j<=n;j++){print b[j]}} ``` [Try it online!](https://tio.run/##FcuxCoMwFIXhV7lKB4M6OMcMXUqn0rliIZaI12oS4hVLJa/eNE4Hfs4nt3cIe29chqLiWIvbhWOesx377ISJSFO2y4bMZDblYmGtqLzXQi7GEWay6Bg/9Bj1WAvNxwNbh5qga8bW@xCuyinABaQ2NCgH6iNnOykwfUyA2q5UAA3xQTgr2JAGuK/6RaskNDr5GXvsEspL85Tl91w@2vwP "AWK – Try It Online") Works for GNU AWK, not regular AWK, due to the use of the `asorti` function. The input is split on anything which isn't a letter, leaving the words in `$1`, `$2`, etc. We iterate over the numbered variables, and, if they aren't equal to the empty string†, we put them, lowercased, into an associative array `a` as an index. Once done, we sort the indices of the array `a` and put the result into an array `b`. Finally, we print the elements of `b`, in order. †We need the test for an empty string, because if the input string ends with a non-letter, the last numbered variable will be an empty string. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~24~~ ~~23~~ 19 bytes thanks to @FryAmTheEggman and @Neil for -5 bytes! ``` T`Llp`ll¶ D` G`. O` ``` [Try it online!](https://tio.run/##K0otycxLNPz/PyTBJ6cgISfn0DYulwQu9wQ9Lv@E//@NLA001MwtLYyNEh0TNbTUFLTMLRV0dW2dnJySNJOSnJIUNBQqFDS1UhR0kyuASuIB "Retina – Try It Online") `T`Llp`ll¶` convert the letters to lowercase and everything else to newlines. `D`` deduplicates lines. `G`.` removes empty lines. `O`` sorts the lines. [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, ~~12~~ 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Two bytes can be saved if we can include the empty string in the "dictionary". Will update explanation upon confirmation. ``` v q\L f â n ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=diBxXEwgZiDiIG4&input=WwoidGhpcyBpcyBhbiBlWGFNcExlIG9mIGFuIElucHV0IiAKIkhlcmUgaXMgYW5vdGhlciBleGFtcGxlIG9mIGFuIGlucHV0LCB0aGlzIHRpbWUgd2l0aCBQdW5jdHVhdGlvbiEiCiIyOTAoJjc5ODMyYUFhKComICo3OSAtLT1CQkJiKWJiQmIgKCB4ICkqZCAtY3hhQWFfIgpdLW1S) - Includes all test cases ``` v f"%a+" â n :Implicit input of string v :Lowercase f :Match "%a+" : RegEx /[a-z]/g â :Deduplicate n :Sort ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~89~~ \$\cdots\$ ~~61~~ 60 bytes Saved 2 bytes thanks to [640KB](https://codegolf.stackexchange.com/users/84624/640kb)!!! ``` lambda s:sorted({*re.findall("[a-z]+",s.lower())}) import re ``` [Try it online!](https://tio.run/##bZFta4MwEMff@yluedEmTsvWDvoAHayvNthgLwdWRqyRBmwMMVJX8bO782nrYEFzufN35/9y@sseM7Voku2@SfkpijnkmzwzVsS0co2YJVLFPE0pCbh/CW@Jl8/S7CwMZaxmjjxpZMGIxorc5rAF6gAuYo8yB3y4AvHB3/SrgCxpvRelC0u8nnoWRvRUZo/CgCj5SacjKlvUg66UlScBZ2mP8F6ogy24lZm6GevM13d0slyvFnP@xKk7AXe5Bt/f7na7iEXRLgIKJTA3Bv9QIvKJicwRpRYHbPRHdUC4Ih4ZVOBJ9mKJzHHLEtxaMST0rvFB/J9E9P/P17/qx2posDk0bXtXtTnHWIQLDaru3BjfsmWYY1B2UEz3xXx5v5p6MBwfpqGTZAbaeXjQt4g3CRepaTejMShitul@1U4t6b6xztdGKksTUrWhGvxHqPIaKhMguB2Sw5qw5hs "Python 3 – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 13 bytes ``` ⇩`[a-z]+`$ẎUs ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%87%A9%60%5Ba-z%5D%2B%60%24%E1%BA%8EUs&inputs=%60%22290%28%2679832aAa%28*%26%20*79%20--%3DBBBb%29bbBb%20%28%20x%20%29*d%20-cxaAa_%22%20-%3E%20%5B%22aaa%22%2C%22bbbb%22%2C%22cxaaa%22%2C%22d%22%2C%22x%22%5D%60&header=&footer=) -3 thanks to Razetime. +1 because I forgot to sort it. [Answer] # perl -Mfeature=say -MList::Util=uniq -n, 31 bytes ``` say for sort@e=uniq lc=~/\pL+/g ``` [Try it online!](https://tio.run/##NY/BCsIwEETvfsV6kVoNiiJaoaA9KVTwIngQJK1bG6hJTDZYL366sVWEuczO22VHo6lm3lv@hEIZsMrQCmMnxR2qPH6NTjodjK7eUyksNOIS8Mh3OkVQReu2UjvqbNDgL1ZUogGs@U1Xf0a0zBC@N0jcEB6CStg7mZPjJJTsdibROOjNo8V0wtc8CHsQziNgLE6SJOtnWZJBADX0wwuwvG6Q81vpdtN6tkuFpeXyQKL6Pu6ZbIYFcnIG46bZBw "Perl 5 – Try It Online") Lowercases the input string (read from `STDIN`), extracts sequences of letters, removes duplicates, sorts and prints them. [Answer] # [Raku](http://raku.org/), 29 bytes ``` {sort unique m:g/<:L>+/».lc} ``` [Try it online!](https://tio.run/##NczfioJAHMXxVzlB@K@saGFLN4O8Kijocu9kdH@uAzpj4wwZ0ZN114u5uRGcmwMfvjWp8rOrLrByRN21kUrDCH4yhCr8na7C/Xo0fdwnZXbrGnZB7gwTF7lUsHXBGzzHBOibHeo9Qeb924naaHsMe0uKXkLqghSoZVVdvhnv2Rj/Gc0rwpnrAkcjMm2Y5lIM@sY8mDnWIlh@zNmGOZ4FbxHA96M4jlM3TeMUDlq43g/8rH2SxP7q/gA "Perl 6 – Try It Online") `m:g/<:L>+/` returns an array of match objects, one for each sequence of letters in the input. `».lc` calls the `lc` (lowercase) method on each of those match objects, coercing them to strings in the process. `sort` and `unique` are self-explanatory, hopefully. [Answer] # [Red](http://www.red-lang.org), 93 bytes ``` func[s][a: charset[#"a"-#"z"]sort unique parse lowercase s[collect[any[keep some a | skip]]]] ``` [Try it online!](https://tio.run/##RY9bS8NAEIXf@yuOWyhtMSD1oaagYJ4UFMQnYQky2UzI0mR33d3QKP73urFehnmYy8eZOZ7r4zPXspw1OxybwSgZSkk7qJZ84CjngkQ2Fx@iDNZHDEa/DQw3LdHZA3tFqQpS2a5jFSWZd7lndgi2ZxA@EfbalSmOjfVMqkVgE9kohpwhhYitDkhJBvxCj@6BYZupuzduiOIE3bHnE2Rjyx48Uu@6X1JP5Dm@laJOhw86tnhKduJAUVtz9iOzyS@Wi21@dbmhW1quF1hvc2TZdVEU1aqqigpLjFita2RqTMirmJUSzmsTIZOB/v97kd0I9Lar0fwNk8sv "Red – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `MList::Util=uniq -F'[^a-zA-Z]+'`, 27 bytes ``` say for uniq sort map{lc}@F ``` [Try it online!](https://tio.run/##FY27CsJAEAB/Za1S6Eks0gQEbYKFgo2NonCEDVm4l3d7@MJfd71UA8PABIymEUn6BYOPkB3dIfnIYHX4mP676UR2GBEogXaeR4yAT22DQfBDUUAuZF4Aj6VgsggP4hGO2fWcNZN3s58PE5OoQ7OsV3XhnhK37YnJrKelqK663LR6b9X5Oq/@ "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes 05AB1E has a built-in that I don't even know! ``` l.γa}ʒa}ê ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/R@/c5sTaU5MSaw@v@v/fI7UoVSGzWCExL78kI7VIIbUiMbcgJ1UhPw0opJCZV1BaoqNQkgFUUZKZm6pQnlmSoRBQmpdcUppYkpmfp6gIAA "05AB1E – Try It Online") ## Explanation ``` l Lowercase .γ Group by: a} Is alphabetic? ʒa} Filter: is alphabetic? ê sorted uniquify ``` [Answer] # PostgreSQL, 80 bytes ``` SELECT regexp_split_to_table(lower($1),'[^a-z]')UNION SELECT''ORDER BY 1OFFSET 1 ``` Input is given as a query parameter and output is given as one word per row. Changing `lower` to `upper` outputs in uppercase instead. `initcap` also works but is 2 more bytes. ## Explanation `regexp_split_to_table` splits a string based on the regular expression provided. `UNION SELECT''` is used to add the empty string and also remove duplicates. `ORDER BY 1` is used to sort the results `OFFSET 1` is used to not output the empty string. If the empty string is sometimes allowed, the following 67 byte solution works: ``` SELECT DISTINCT regexp_split_to_table(lower($1),'[^a-z]')ORDER BY 1 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~13~~ 12 bytes ``` ↓¬uO†_mf√ġK√ ``` [Try it online!](https://tio.run/##yygtzv7//1Hb5ENrSv0fNSyIz0171DHryEJvIPn//38jSwMNNXNLC2OjRMdEDS01BS1zSwVdXVsnJ6ckzaQkpyQFDYUKBU2tFAXd5AqgkngA "Husk – Try It Online") -1 byte from Jo King. ## Explanation ``` ↓¬uO†_mf√ġK√ ġK√ Group the input on non alphabet chars mf√ filter out non-alphabet chars. †_ convert all characters to lowercase O sort in ascending order u uniquify ↓¬ drop all empty strings at the beginning ``` [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 16 bytes ``` zz"[a-z]+"~?NB>< ``` [Try it online!](https://tio.run/##SyotykktLixN/f@/qkopOlG3KlZbqc7ez8nO5v9/I0sDDTVzSwtjo0THRA0tNQUtc0sFXV1bJyenJM2kJKckBQ2FCgVNrRQF3eQKoJJ4AA "Burlesque – Try It Online") Explanation: ``` zz # Lowercase input "[a-z]+"~? # Get list of all regex matches NB # Remove duplicates >< # Sort ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes ``` F⪫ ↧S¿№βι⊞§υ±¹ι⊞υ⟦⟧≔⟦⟧ζW⁻υζ⊞ζ⌊ι✂Eζ⪫ιω¹ ``` [Try it online!](https://tio.run/##NY7BasMwEETv/oolh7AyMrTpITUmB7unlKYEcgyhSIpiLzhSsKTa@OdVuaV7m3nDzqhODMqKPsabHQDfLRlcAaw4fNhRD0o4jXvzCP7kBzItsnRAN8A3G4xHyYGScQyuw9rvzVVPGDh86lZ4jc@MLbwC3Tv9F0rwfGFVVjtHrcHzhcOc5NhRrwEPZIJbMvP/05lDMuke7piKquyYVng89aQ0HsRj4b@bicO4tKXKKsZN@YTrbfn6shG1wHwN@baEotg1TSOZlI0EhAlYfoVCTSnylcXiu/8B "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⪫ ↧S ``` Wrap the lowercased input in spaces and loop over the characters. ``` ¿№βι ``` If this is a letter, ... ``` ⊞§υ±¹ι ``` ... then append it to the last entry, ... ``` ⊞υ⟦⟧ ``` ... otherwise start a new entry. ``` ≔⟦⟧ζ ``` Start a list of unique entries. ``` W⁻υζ ``` While there are more entries, ... ``` ⊞ζ⌊ι ``` ... add the lexicographically first entry to the list of unique entries. This also ends up sorting the deduplicated list. ``` ✂Eζ⪫ιω¹ ``` Join the entries back into strings and print all but the first (which is always empty). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes 13 bytes if we may include the empty word as a leading entry - exclude the trailing `Ḋ` (maybe?). 11 bytes if we may output an empty word, but not always - exclude `⁸Ż` also (probably not). ``` e€ØẠa⁸Żṣ0ŒlQṢḊ ``` A monadic Link accepting a list of characters which yields a list of lists of characters. **[Try it online!](https://tio.run/##AVgAp/9qZWxsef//ZeKCrMOY4bqgYeG5ozDFkmxR4bmi4biK/8OHS///IjI5MCgmNzk4MzJhQWEoKiYgKjc5IC0tPUJCQmIpYmJCYiAoIHggKSpkIC1jeGFBYV8i "Jelly – Try It Online")** ### How? ``` e€ØẠa⁸Żṣ0ŒlQṢḊ - Link: list of charachters, S e.g. "I((or))a" ØẠ - Latin alphabet characters "AB...Zab...z" e€ - for each (c in S): exists in (ØẠ)? [1,0,0,1,1,0,0,1] a⁸ - logical AND (vectorises) (with chain's left argument = S) ['i',0,0,'o','r',0,0,'a'] Ż - prepend a zero (for S like "abc") [0,1,0,0,1,1,0,0,1] ṣ0 - split at zeros [[],['I'],[],['o','r'],[],['a']] Œl - lower-case [[],['i'],[],['o','r'],[],['a']] Q - deduplicate [[],['i'],['o','r'],['a']] Ṣ - sort [[],['a'],['i'],['o','r']] Ḋ - dequeue (remove the empty word) [['a'],['i'],['o','r']] ``` [Answer] # [J](http://jsoftware.com/), 44 bytes Drops the potential empty word, otherwise -4 bytes. ``` }.@~.@/:~@([;._2~2|1+'@Z'&I.)@toupper@,&' ' ``` [Try it online!](https://tio.run/##NczBasJAGATge59i2kP@3TRZbXqwiQjbFETBQulJ7EE2dkO21GRJNzQHzavHqAgzh4GP@ekfBOWYJSAEGCMZGgq8fa7m/VHITshR0kn2NRXbqIsOT48kN@QtBZeuaqzVtQw8AqjnPZvmHOQK84chqoReq3e70qjy81qWtnF0d1ULXeurqlyha@hW7e3vjZozDXC5cmav8W9cgY@m3LlGOVOV97efKB4zbxK/PEfqVTHfgz@JEYazNE0znmVpBoYW3P9GuGsHsqUT "J – Try It Online") ### How it works ``` }.@~.@/:~@([;._2~2|1+'@Z'&I.)@toupper@,&' ' ,&' ' append two spaces toupper one of the few functions, non J user can guess by name :) ( '@Z'&I.) index into intervals …@](A…Z](_… 2|1+ add 0 and mod 2, so A-Z is 0, else 1 [;._2~ partition the string into groups, each group ends with 1 (exclusive). the end is based on the last item, which is space -> 1 /:~ sort the strings ~. remove duplicates }. remove head, which will be the space group ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~13~~ 8 bytes *5 bytes removed thanks to [@Sanchises](https://codegolf.stackexchange.com/users/32352/sanchises)!* ``` k3Y4XXuS ``` Output is in lowercase. [Try it online!](https://tio.run/##y00syfn/P9s40iQiojT4/391I0sDDTVzSwtjo0THRA0tNQUtc0sFXV1bJyenJM2kJKckBQ2FCgVNrRQF3eQKoJJ4dQA) Or [verify all test cases](https://tio.run/##NcxBC4IwGMbxe5/i7eJUGoQG5qFDo0NBQVCHdap3tnCkU@wd@e2XFsFzeeDHv0aq/M0/08tCSnfyjHMmN2fPqDQvGIYWtMRDu9fQPMa3s60jNmFb3ekfaKjUHege67b6KzOqGXwrZGoNb0MlHJ0tyCGZxk6HRJLPwyDLl2mCawzjAOIsB85XQggVKSUUhNBDFN@BF/1AruwD). ### How it works ``` k % Implicit input: string. Convert to lowercase 3Y4 % Push string '[A-Za-z]+' (predefined literal) XX % Regexp match. Gives a cell array of substrings u % Unique S % Sort. Implicit display ``` [Answer] # [R](https://cran.r-project.org/), 60 bytes ``` sort(setdiff(strsplit(tolower(readline()),"[^a-z]")[[1]],"") ``` Used `setdiff` to remove possible empty strings, but it deduplicates as well. [Answer] # [Haskell](https://www.haskell.org/), 88 bytes ``` import Data.Char import Data.List s=sort.nub.words.map f f x|isAlpha x=toLower x f _=' ' ``` Replace non-alpha characters with spaces so we can use `words` to split it. [Try it online!](https://tio.run/##bZJRb5swEMff@RQ3q2ohBVZ1D12kUinpHjYpkSb1YZO6qjLBFGvGRvYxeNh3zw4MJJtmgc@@O//ur7Mr7n4KpY6yboxFeDQarVHp3mheQFhKhcLuY@gqoaM56RNHnj5W3Abnjp10GLjMkSPVbZ52xhYurXkDZVBC/1u6jWoqDn2GZmc6YaEn/2t2BVfHmksNGRQmAFACQfSNOKAoHDmfyTePkGElHdDHNYjvfN/sBJhy2H3RTYsshmfGNYuZ6HndKEEr6QNMOppMSdPAYC/Rwo2J@1lY4bkGK9I2nZ/gIyOGsTjKWkAnsYKvrT5gy1Ea/e5UeSL8pYH2/5fSnBCzMDJUgcxQ41@Zt@ub8PJu/fHDLd/wcHUJq7s1JEm23W7zKM@3OYTQQ7QqIDn0lPLqdXFOvJwGGfKP24L@/pz/Ekzdd0b9EtR5R/vOGv0G9wmUStJN@vdwdj8X8COcumNaJBtB8uAv0sOscK3CgTZSx9wlKN23kZ/Nae@zCTOmDK9uybmYhFLwCe1OU2nmmQyurz14WDDouPM@V5luJo@RnFLI2aoCKk4nc0EFTqlnpa3A1i7Fh86MYkLdKuWbEk2KFj1sQ6E3Y4qUHf8A "Haskell – Try It Online") [Answer] # [Rust](https://www.rust-lang.org/), 201 bytes ``` fn main(){let y=&mut"".into();std::io::stdin().read_line(y);y.retain(|c|c.is_alphabetic()||c==' ');*y=y.to_lowercase();let mut v=y.split(" ").collect::<Vec<_>>();v.sort();v.dedup();println!("{:?}", v)} ``` [Try it online!](https://tio.run/##HY5BbsMgEEWvMmXhgFWjKl2kxiFVfYhuEcZERSLGgrEbK87ZXdzdG82b@T9OCbftOsBNu4Gyh7cIiyxuExLC3YCBsiZhL4QLQmTYJR6t7pV3g6ULa5Y84n68mtVwl5T244/uLDpD2boaKQ9wYE25yIVjUD782mh0svnxHpaTYM6rNHqHlABh3ATvrUEhzt/WnNXlktWZpxDxH3rbT2OmMeZ@fnih5CE@n@QVZvbctmP9RotT/fF@1F@algWUpxqqSrZt27GuazugcAdW9lCZe1bUHw "Rust – Try It Online") ``` fn main(){ let y = &mut"".into();std::io::stdin().read_line(y); //Get input into string y.retain(|c|c.is_alphabetic()||c==' '); //Retain spaces and letters in string *y=y.to_lowercase(); //Convert to lowercase let mut v=y.split(" ").collect::<Vec<_>>(); //Split string by space and collect into vector v.sort(); //sort Vec v.dedup(); //delete duplicates (only works on sorted Vec) println!("{:?}", v) //debug-print vector (because no std::fmt::Display for Vec<&str>) } ``` [Answer] # [Haskell](https://www.haskell.org/), 93 bytes ``` import Data.List s=sort.nub.words.map(((do c<-"q69";(" "<*['1'..c])++['a'..'z'])!!).fromEnum) ``` [Try it online!](https://tio.run/##bZL/i9MwGMZ/31/xLhy3ZGurd@LO4SbcVFDYQPAHhVokXbNrME1qktohd3/7fPttm2LZmi/vk8/z8KY5dz@EUkdZlMZ6eGu0t0ZFW6N5BnQvlRd2G0CdC80G0TvuebSRzo/cyuFGpKs0qo3NXFTwklKaGdgtQ/JzviCvKQGynMaTm0kU7RI2m8UTjtPJ70nCxmMW7a0p3uuqYMeCSw0ryMwIoLRSe4i7Y8l4THV4w@ARNCzDeP4ymAeLJEGdEh7EoRQ7LzKHh2PcGx5KfC4d4I9rEF/5ttwIMPtm9VGXlScBxIRrEhBx4EWpBM5kVyDS4cvs8dUwSMJO3AC5H4QVHdf4XFjoz/fwlhFAa@5lIaCWPodPld75intp9Pjs3BP@yoDr/0cpz4ghGA7ogEPj8W/M28Vzen23ePXilt9zOr2G6d0CwnC1Xq9TlqbrFCgcgE0zCHcHlHx/6oJxjsAUHxyw0C4z/B8uDZJR335n1C@BrXe4rq3RD3hFsFeyhP7rubigK/hG@/aYyuPIIHzT3XgHs8JVyje0ltpqT0XpvrT81SB7tuoxraT5Rk@aqz4oFj97u9FoTTomgdmsAzcTAjV33Z7LTT2Q20qKEtysVAY5x5OpQIOz9MLaCl/Zk3nTmTYM1ZVSXVNYn@iUh9xj6cGYLCLHPw "Haskell – Try It Online") It's not shorter than the other Haskell answer, but I thought this approach was pretty fun. It creates a big string like `"... abc...xyz abc...xyz ..."` so that indexing into this string performs the same mapping as `f` in the other answer. I'm including `s=` because the other answer also is. [Answer] # [QuadS](https://github.com/abrudz/QuadRS), 15 [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")) ``` ∪⍵[⍋⍵] \pL+ \l& ``` [Try it online!](https://tio.run/##KyxNTCn@//9Rx6pHvVujH/V2A6lYrpgCH22umBy1//@NLA001MwtLYyNEh0TNbTUFLTMLRV0dW2dnJySNJOSnJIUNBQqFDS1UhR0kyuASuIB "QuadS – Try It Online") `∪` **U**nique elements of `⍵[`…`]` the data reordered to:  `⍋⍵` the order that would sort it ascending where the data is: `\pL+` all runs of **L**etters `\l&` mapped to **l**owercase [Answer] # [PHP](https://php.net/), 82 bytes ``` $a=array_filter(array_unique(preg_split("/[^a-z]+/",strtolower($argn))));sort($a); ``` [Try it online!](https://tio.run/##JcrRCoIwGIbhWxkislnDsIMSk2gH3UTU@JdmA3Pr3yzr4rOB38EHD7z2bqfd3oaPoQJE@Mib7nyDdMbQ6@fQUItNK53ttKdRdroA/54XWbR0Hr3pzDvkMWDbs7DSGfSBrJxegLIeHnZWXqxosim26xwOQNOEpJuCcF4JIRRTSihCyUhYWhN@HUMif8Z6bXo38eMf "PHP – Try It Online") I'm still not satisfied by it, but so far the best I could find.. Yeah array functions names are looooong in PHP :S The question doesn't ask to display the dictionary, so it's in the footer ;P [Answer] # [Clojure](https://clojure.org/), ~~59~~ 46 bytes ``` #(sort(set(re-seq #"[a-z]+"(.toLowerCase %)))) ``` [Try it online!](https://tio.run/##Nc5BS8NAEAXge37Fc4tlEl2Reqg59NB4UajgUQhBNsmErKS7cTOhwT8fE8XhXR58PKbq/OcYeKaaGzTzhgYfhAYWCqwH/sJG5UZ/FzeK7sSf/IXDkxkY1/FycxxR7VeVT8gjJa0dsMQ48Lt57U8M36ztxfWjqEg9c@A/4KXlAJ7Mue/@lV3VLX5XxJ4ZFyst3kZXyWjEene1TOzSe9ru08eHnTkaSrZI9im0PmRZVsZlmZUgTIiTGrqaFvKhoqIA9cE66RyowbR@/gM "Clojure – Try It Online") 13 bytes saved by NikoNyrh. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` áмS¡lê ``` [Try it online](https://tio.run/##MzBNTDJM/f//8MILe4IPLcw5vOr/fyNLAw01c0sLY6NEx0QNLTUFLXNLBV1dWycnpyTNpCSnJAUNhQoFTa0UBd3kCqCSeAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9TpuSZV1BaYqWgZF@pw6XkX1oC4x2e8P/wwgt7gg8tzDm86r/OoW32/0syMosVgCgxTyE1ItG3wCdVIT8NxAObweWRWpQKkc4vyUgtUkitSMwtyIGpyQSp0VEAm1GSmZuqUJ5ZkqEQUJqXXFKaWJKZn6fIZWRpoKFmbmlhbJTomKihpaagZW6poKtr6@TklKSZlOSUpKChUKGgqZWioJtcAVQSz1WSWlwCAA). **Explanation:** ``` á # Only leave letters of the (implicit) input-string м # Remove all those letters from the (implicit) input-string S # Convert the remaining characters to a list of characters ¡ # Split the (implicit) input-string on those characters l # Convert everything to lowercase ê # Sort and uniquify the words ``` NOTE: This doesn't work in the new version of 05AB1E for two reasons: 1. The `¡` would also keep empty string items. 2. A single word wouldn't be wrapped into a list, so something like input `"test"` would result in output `"est"` due to the `ê` working directly on this single string instead of a list. [See the result of all test cases in the new version of 05AB1E.](https://tio.run/##yy9OTMpM/V9TpuSZV1BaYqWgZF@pw6XkX1oC4x2e8P/wwgt7gg8tzDm86r/OoW32/0syMosVgCgxTyE1ItG3wCdVIT8NxAObweWRWpQKkc4vyUgtUkitSMwtyIGpyQSp0VEAm1GSmZuqUJ5ZkqEQUJqXXFKaWJKZn6fIZWRpoKFmbmlhbJTomKihpaagZW6poKtr6@TklKSZlOSUpKChUKGgqZWioJtcAVQSz1WSWlwCAA) [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html) (+"sort" callout), 87 bytes ``` gsub("[^a-zA-Z]"," ")&&$0=tolower($0){for(;$++a;)!b[$a]++?c=c $a"\n":0;printf c|"sort"} ``` [Try it online!](https://tio.run/##DcrdCoIwGADQV/kaY2yuwbALU5Fwj5FZfJsZUbiYhtLPs6/O9cH5FuNlfFpOmiOqV632LVkTIIIxqqvJ3/18Dpxq8e594CWVEkuxsg3FVsqdqxxQJIeBFLp8hOsw9eA@ZPRhIt8Y01xzluXbTYo18oRBkuUFIoJSlTHGCmtNZ4HDAiLpQLnl/04/ "AWK – Try It Online") This AWK version is longer than the entry Abigail submitted (once it's golfed a bit) but it shows a trick I thought was worth highlighting. ``` gsub("[^a-zA-Z]"," ")&&$0=tolower($0){ ... } ``` The `gsub` call translates all the non-alphabetic characters to spaces, then the `$0=tolower($0)` bit does two things. It converts everything to lowercase, then the assignment effectively re-maps the string to positional parameters, dealing with all the added spaces. As a result if `$1` was `=BBBb)))bbBdb` originally, after running through those calls, the data would set `$1="BBBd"` and `$2="bbDdb"`. Once the input line has been cleaned up, ``` for(;$++a;)!b[$a]++?c=c $a"\n":0 ``` loops through all the words via `$++a`, and for each one increments a frequency counter array for that word `b[$a]++`. If the value of that frequency counter is 0, the ternary appends the word plus a LF to an accumulator string. Then the code prints the accumulated string and pipes it to "sort" with this line. ``` printf c|"sort" ``` ]
[Question] [ Write a program that takes two numbers as its input. The first one is the number of dimensions - 0 for a dot, 1 for a straight line, 2 for a circle, 3 for a sphere. The second number is the radius of the object, or, if it's 1-dimensional, the number itself. Output 0 for 0 dimensions. The output is the length/area/volume of the object. If we call the first number `n`, the second one `r`, and the output `x`, we get that: * for n = 0, x = 1 * for n = 1, x = 2×r * for n = 2, x = r2×π * for n = 3, x = (4/3)×r3×π * and so on... if you want, though. Notes: * Cases when one or both numbers are negative, or when the first number is not whole, don't need to be covered. * The program must not read from any file and the only input are those two numbers. * The output should use only numerals (e.g. not "14\*pi"), and should be accurate to at least two decimal digits. * As for n = 0, you can output 0 if it makes the code shorter. * **Extra swag for an answer covering even 4 and more-dimensional "spheres"!** * It's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! Examples: ``` 1 1 -> 2 2 3 -> 28,27 3 1 -> 4,19 3 4,5 -> 381,70 1 9.379 -> 18.758 0 48 -> 1 ``` [Answer] # Mathematica, 18 bytes, up to ~168.15 trillion dimensions ``` Pi^(a=.5#)/a!#2^#& ``` Anonymous function. Takes two numbers as input, and returns an inexact number as output. Works with any number of dimensions. Outputs `1.` for *n* = 0. Uses the formula from [Volume of an n-ball](http://enwp.org/Volume_of_an_n-ball) on Wikipedia. ### Explanation We are attempting to compute π*n*/2/*Γ*(*n*/2 + 1)·*R**n*, or `N[Pi^(n/2)/Gamma[n/2 + 1] R^n]` in Mathematica. In our case, `#` (first argument) is *n* and `#2` (second argument) is *R*. This leaves us with `N[Pi^(#/2)/Gamma[#/2 + 1] #2^#] &`, which can be golfed as follows: ``` N[Pi^(#/2)/Gamma[#/2 + 1] #2^#] & Pi^(.5#)/Gamma[.5# + 1] #2^# & (* replace exact with approximate numbers*) Pi^(.5#)/(.5#)! #2^# & (* n! == Gamma[n + 1] *) Pi^(a=.5#)/a! #2^# & (* replace repeated .5# *) Pi^(a=.5#)/a!#2^#& (* remove whitespace *) ``` and thus, our original program. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) + extra swag ``` ÷2µØP*÷! ç×*@ ``` **[Try it online!](http://jelly.tryitonline.net/#code=w7cywrXDmFAqw7chCsOnw5cqQA&input=&args=Mw+NC41)** Works for any dimension, so long as the fixed value of π yielded by `ØP` (`3.141592653589793`) is accurate enough. ### How? ``` ÷2µØP*÷! - Link 1: n, r ÷2 - n / 2 µ - monadic chain separation ØP - π (3.141592653589793) * - exponentiate: π^(n/2) ! - Pi(n/2): Gamma(n/2 + 1) ÷ - divide: π^(n/2) / Gamma(n/2 + 1) ç×*@ - Main link: n, r ç - call last link (1) as a dyad: π^(n/2) / Gamma(n/2 + 1) *@ - exponentiate with reversed @rguments: r^n × - multiply: r^n * π^(n/2) / Gamma(n/2 + 1) ``` [Answer] # JavaScript (ES6), 45 bytes + extra swag Recursive formula from [wikipedia](https://en.wikipedia.org/w/index.php?title=Volume_of_an_n-ball&section=3#Recursions), should work for any number of dimension ``` f=(n,r)=>n<2?n?2*r:1:f(n-2,r)*2*Math.PI*r*r/n ``` [Answer] # R, ~~75~~ ~~40~~ 38 bytes (plus extra swag) Well, looks like I could golf this down by giving in and using the gamma function rather than recursive functions. ``` function(n,r)pi^(n/2)/gamma(n/2+1)*r^n ``` Defines an anonymous function to calculate the volume of an `n`-dimensional hypersphere of radius `r`. Some examples: > > 1 1 -> 2 > > > 0 48 -> 1 > > > 2 3 -> 28.27433 > > > 3 4.5 -> 381.7035 > > > 7 7 -> 3891048 > > > 100 3 -> 122051813 > > > # Swagless solution, ~~38~~ 34 bytes For a few bytes less, you can have an anonymous function that only works for dimensions 1 to 3. Returns `numeric(0)` for `n=0`, and `NA` for `n>3`. (`numeric(0)` is a numeric vector of length 0; `NA` is for "not available".) Performance is otherwise identical to the general solution above. ``` function(n,r)c(1,pi,4/3*pi)[n]*r^n ``` [Answer] # Haskell, ~~74~~ ~~65~~ 36 bytes + extra swag ``` 0%r=1 1%r=2*r n%r=2*pi*r^2/n*(n-2)%r ``` Recursive formula, works for all dimensions that can be presented exactly as a double-precision floating point number but will loop infinitely for non-integral dimensions. The old version for posteriority's sake: ``` n%r=(max 1$1-(-1)**n)*(2*pi)^(floor$n/2)*r**n/product[n,n-2..1.1] ``` ~~Works for all dimensions. Uses the formula from [the tau manifesto](http://tauday.com/tau-manifesto#sec-volume_of_a_hypersphere). `product[n,n-2..1.1]` is a [double factorial](https://en.wikipedia.org/wiki/Double_factorial) hack that won't count zero for `n==2`~~ [Answer] # JavaScript, ~~61~~ ~~51~~ ~~49~~ 43 bytes **0-3 dimensions are supported because [there is no 4th dimension](https://www.youtube.com/watch?v=M9sbdrPVfOQ)**. Thanks to @Hedi for saving 7 bytes ``` d=(n,r)=>r**n*(n<2?n+1:Math.PI*(n<3?1:4/3)) ``` Creates function `d`. Then raises `r` to the `n`th power and then multiplies it with a number depending on `n` using ternary operators. Outputs `1` for `n=0` Gives output to at least 2 decimal places (10+ dp) ## Here's a snack snippet! ``` var N = document.getElementById("n"); var R = document.getElementById("r"); N.value="3";//default R.value="4.5";//default d=(n,r)=>r**n*(n<2?n+1:Math.PI*(n<3?1:4/3)); var b = document.getElementById("b"); b.onclick = function() { var s = document.getElementById("s"); var n = document.getElementById("n").value; var r = document.getElementById("r").value; s.textContent = d(parseFloat(n),parseFloat(r)); } ``` ``` span {border:1px solid black;padding:10px;font-size:30px;} ``` ``` Value of n: <input id="n" type="number"></input> Value of r: <input id="r" type="number"></input><br> <button id="b">Calculate!</button><br><br><br> <span id="s">THERE IS NO 4TH DIMENSION</span> ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 17 bytes ``` 3:^[2P4*P/3]*1hi) ``` This works up to 3 dimensions only. Inputs are in reverse order, that is: `r`, then `n`. [Try it online!](http://matl.tryitonline.net/#code=MzpeWzJQNCpQLzNdKjFoaSk&input=Mwoy) Consider `r=3`, `n=2` as an example. ``` 3: % Push array [1 2 3] % STACK: [1 2 3] ^ % Take r implicitly, and raise it to [1 2 3] element-wise % STACK: [3 9 27] [2P4*P/3] % Push array [2 pi 4*pi/3] % STACK: [3 9 27], [2 pi 4*pi/3] * % Multiply element-wise % STACK: [6 28.2743 113.0973] 1h % Append 1 % STACK: [6 28.2743 113.0973, 1] i) % Input n and use it as modular index into the array. Display implicitly % STACK: 28.2743 ``` [Answer] ## Java/C/C++/C#, 69 67 bytes + extra swag! Edit: Saved 2 bytes thanks to @AlexRacer A dyadic function - first argument is number of dimensions, second is the radius of the n-ball. `float v(int n,float r){return n<1?1:n<2?2*r:6.283f*r*r*v(n-2,r)/n;}` Recursive formula for the volume of an n-ball: Vn=(2πr2Vn-2)⁄n Whoa! Java (my test language) beats Scala here, thanks to the terse `?:` ternary syntax! This function is syntactically correct in all 4 languages in the heading, and I have tested it with C (MinGW GCC 5.4.0), & C# (VS Ultimate 2016, C# 6.0). I'm assuming that it will work in C++ too, so there. Since this function is pretty much library-independent, it should work in any C-like language with similar syntax. [Answer] ## Haskell, 52 bytes for tab indent 42 bytes + extra swag Edit: Saved 10 bytes thanks to @WChargin A dyadic curried function - first argument is number of dimensions, second is the radius of the n-ball. ``` v 0 r=1 v 1 r=2*r v n r=2*pi*r*r*v(n-2)r/n ``` Recursive formula for the volume of an n-ball: Vn=(2πr2Vn-2)⁄n Save this as a separate script file and run with GHCi, with a function for testing `v` for output, e.g., `show (v 3 4.5)`. I did not test this, please let me know if this doesn't work. Old program with 6.2832 approximation for 2π replaced (50 bytes with tab indent): ``` let v 0 r=1 v 1 r=2*r v n r=2*pi*r*r*(v(n-2)r)/n ``` This can be used with GHCi in multiline mode (using `:set +m` or enclosing the code between `:{` & `:}`, the enclosures being on their own lines. Tester function required. Static typing with full-program type inference comes into play here, allowing Haskell to do far better than Scala, and approaching Groovy, but not quite beating it thanks to the pattern match instead of a ternary, involving some character repetition. [Answer] ## Racket 69 bytes (plus extra swag) Uses recursive formula from <https://en.wikipedia.org/w/index.php?title=Volume_of_an_n-ball&section=3#Recursions> Including suggestions by @wchargin ``` (define(v d r)(match d[0 1][1(* 2 r)][_(/(* 2 pi r r(v(- d 2)r))d)])) ``` Ungolfed (v=volume, d=dimensions, r=radius): ``` (define(v d r) (match d [0 1] [1 (* 2 r)] [_ (/ (* 2 pi r r (v (- d 2) r) ) d)] )) ``` Testing: ``` (v 1 1) (v 2 3) (v 3 1) (v 3 4.5) (v 1 9.379) (v 0 48) ``` Output: ``` 2 28.274333882308138 4.1887902047863905 381.7035074111599 18.758 1 ``` [Answer] # Perl, 63 bytes + extra swag ``` @a=1..2;push@a,6.283/$_*@a[$_-2]for 2..($b=<>);say$a[$b]*<>**$b ``` Accepts two integers n and r, one at a time, then outputs the n-volume for given radius r of an n-sphere. When n = 0, V = 1, and when n = 1, V = 2r. All further dimensions are calculated by the following formula: ![Recursive volume formula](https://wikimedia.org/api/rest_v1/media/math/render/svg/f70051d53cb8d493152dc7988e1b98ac6400fd55) Since rn is the radius's factor in every formula, I leave it out of the base calculation and only apply it at the end. 2π is approximated in the code by 6.283. [Answer] # Scala, 53 bytes ``` {import math._;(n,r)=>pow(r,n)*Seq(1,2,Pi,Pi*4/3)(n)} ``` Sorry, no extra swag for me :( Explanation: ``` { //define a block, the type of this is the type of the last expression, which is a function import math._; //import everything from math, for pow and pi (n,r)=> //define a function pow(r,n)* //r to the nth power multiplied by Seq(1,2,Pi,Pi*4/3)(n) //the nth element of a sequence of 1, 2, Pi and Pi*4/3 } ``` [Answer] ## JavaScript (ES6), 39 bytes, no swag ``` (n,r)=>[1,r+r,a=Math.PI*r*r,a*r*4/3][n] ``` [Answer] ## Python 3, ~~76~~ ~~72~~ 68 bytes + extra swag! Recursive solution with extra swag! Returns `0` for `n=0` ``` from math import* f=lambda n,r:n*r*2*(n<2or pi*r/n/n*(f(n-2,r)or 1)) ``` Old approach (`1` for `n=1`): ``` from math import* f=lambda n,r:1*(n<1)or r*2*(n<2)or 2*pi*r*r/n*f(n-2,r) ``` Recursive formula from [Wikipedia](https://en.wikipedia.org/wiki/Volume_of_an_n-ball#Recursions). [Try it online.](https://repl.it/EPk2/0) [Answer] ## Python 3, 56 bytes + extra swag! Straightforward with extra swag! ``` from math import* lambda n,r:pi**(n/2)*r**n/gamma(n/2+1) ``` [Standard formula.](https://en.wikipedia.org/wiki/Volume_of_an_n-ball#The_volume) [Try it online](https://repl.it/EPgY/1) [Answer] # Scala, 81 79 bytes + extra swag! Edit: Saved 2 bytes thanks to @AlexRacer A dyadic function - first argument is number of dimensions, second is the radius of the n-ball. `def v(n:Int,r:Float):Float=if n<1 1 else if n<2 2*r else 6.2832f*r*r*v(n-2,r)/n` Recursive formula for the volume of an n-ball: Vn=(2πr2Vn-2)⁄n Scala's lack of type inference for return types of recursive functions and function parameters and verbose ternary syntax hurts quite a bit here :( [Answer] ## Groovy, 49 47 bytes + extra swag! Edit: Saved 2 bytes thanks to @AlexRacer A dyadic function - first argument is number of dimensions, second is the radius of the n-ball. `def v(n,r){n<1?1:n<2?2*r:6.2832*r*r*v(n-2,r)/n}` Recursive formula for the volume of an n-ball: Vn=(2πr2Vn-2)⁄n Dynamic Typing FTW! My Scala and Java answers use the same logic, but with static typing so higher byte counts due to type annotations :(. However, Scala and Groovy allow me to omit the `return` and the semicolon, so that helps the byte count, unlike Java/C... [Answer] # [Lithp](https://github.com/andrakis/node-lithp), 96 characters + extra swag Line split in 2 for readability: ``` #N,R::((if (< N 2) ((? (!= 0 N) (* 2 R) 1)) ((/ (* (* (* (* (f (- N 2) R) 2) 3.1416) R) R) N)))) ``` Thinking I need to upgrade my parser to require less spaces. Code size would be cut down nicely, especially in that `((/ (* (* (* (*` section. Usage: ``` % n-circle.lithp ( (def f #N,R::((if (< N 2) ((? (!= 0 N) (* 2 R) 1)) ((/ (* (* (* (* (f (- N 2) R) 2) 3.1416) R) R) N))))) (print (f 1 1)) (print (f 2 3)) (print (f 3 1)) (print (f 3 4.5)) (print (f 1 9.379)) (print (f 0 48)) ) #./run.js n-circle.lithp 2 28.274333882308138 4.1887902047863905 381.7035074111598 18.758 1 ``` Thanks to Rudolf for shaving a few bytes off. [Answer] ## CJam (27 bytes with extra credit) ``` {1$_[2dP]*<f*\,:)-2%./1+:*} ``` [Online test suite](http://cjam.aditsu.net/#code=%5B%5B1%201%5D%5B2%203%5D%5B3%201%5D%5B3%204.5%5D%5B1%209.379%5D%5B0%2048%5D%5D%7B~%0A%0A%7B1%24_%5B2dP%5D*%3Cf*%5C%2C%3A)-2%25.%2F1%2B%3A*%7D%0A%0A~p%7D%2F). This is an anonymous block (function) which takes arguments `d r` on the stack and leaves the result on the stack. ### Dissection The general n-dimensional formula can be rewritten as $$\frac{2^{\left\lceil\frac{d}{2}\right\rceil}\pi^{\left\lfloor\frac{d}{2}\right\rfloor} r^d}{d!!}$$ ``` { e# Begin block: stack holds d r 1$_[2dP]*< e# Build a list which repeats [2 pi] d times and take the first d elements f* e# Multiply each element of the list by r \,:)-2% e# Build a list [1 ... d] and take every other element starting at the end ./ e# Pointwise divide. The d/2 elements of the longer list are untouched 1+:* e# Add 1 to ensure the list is non-empty and multiply its elements } ``` ]
[Question] [ # The challenge Output an array or string representation of Dürer's famous [magic square](https://en.wikipedia.org/wiki/Magic_square#Albrecht_D.C3.BCrer.27s_magic_square): [![enter image description here](https://i.stack.imgur.com/BIs0R.jpg)](https://i.stack.imgur.com/BIs0R.jpg) that is, ``` 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 ``` Some [properties](http://mathworld.wolfram.com/MagicSquare.html) of this square, which can perhaps be exploited, are: * It contains each integer from `1` to `16` exactly once * The sum of each column or row, as well as the the sum of each of the two diagonals, is the same. This is the defining property of a [magic square](https://en.wikipedia.org/wiki/Magic_square). The sum is the *magic constant* of the square. * In addition, for this particular square, the sum of each of the four quadrants also equals the magic constant, as do the sum of the center four squares and the sum of the corner four squares. # Rules Bultins that generate magic squares are not allowed (such as Matlab's `magic` or Mathematica's `MagicSquare`). Any other builtin can be used. The code can be a program or a function. There is no input. The numbers must be in base 10. The output format is flexible as usual. Some possibilities are: * A nested array (either function output, or its string representation, with or without separators, any type of matching brackets): ``` [[16, 3, 2, 13], [5, 10, 11, 8], [9, 6, 7, 12], [4, 15, 14, 1]] ``` * A 2D array: ``` {16, 3, 2, 13; 5, 10, 11, 8; 9, 6, 7, 12; 4, 15, 14, 1} ``` * An array of four strings, or a string consisting of four lines. The numbers may be right-aligned ``` 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 ``` or left-aligned ``` 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 ``` * A string with two different separators for row and column, such as ``` 16,3,2,13|5,10,11,8|9,6,7,12|4,15,14,1 ``` The output format should clearly differentiate rows and columns. For example, it is not allowed to output a flat array, or a string with all numbers separated by spaces. Code golf. Shortest wins. [Answer] ## Pyth, 18 bytes ``` c4.PC"H#ût"_S16 ``` [Run the code.](http://pyth.herokuapp.com/?code=c4.PC%22%01%05H%23%C3%BBt%22_S16&input=1122196781940&debug=1) ``` c4.PC"H#ût"_S16 C"H#ût" Convert the packed string to the number 1122196781940 .P _S16 Take that-numbered permutation of the reversed range [16,15,...,1] c4 Chop into piece of length 4 ``` Reversing the range was meant to lower the permutation index, since the output starts with 16, but I think it only broke even. This beat out a more boring strategy of converting the table directly to base 17 and then a string ([link](http://pyth.herokuapp.com/?code=c4.PC%22%01%05H%23%C3%BBt%22_S16&input=1122196781940&debug=1)) for 20 bytes: ``` c4jC"úz(ás¸H"17 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 4Œ!.ịm0µZḂÞ’×4+ ``` [Try it online!](http://jelly.tryitonline.net/#code=NMWSIS7hu4ttMMK1WuG4gsOe4oCZw5c0Kw&input=) ### Background If we subtract **1** from the numbers in the square and divide them by **4** (computing quotient and remainder), a pattern becomes apparent. ``` quotients and remainders quotients remainders 3 3 0 2 0 1 3 0 3 0 0 3 3 2 1 0 1 0 2 1 2 2 1 3 1 2 2 1 0 1 2 3 2 0 1 1 1 2 2 3 2 1 1 2 0 1 2 3 0 3 3 2 3 1 0 0 0 3 3 0 3 2 1 0 ``` The remainder matrix follows an obvious pattern and is easy to generate. The quotient matrix can be obtained by transposing the remainder matrix and swapping the middle rows. ### How it works ``` 4Œ!.ịm0µZḂÞ’×4+ Main link. No arguments. 4Œ! Compute the array of all permutations of [1, 2, 3, 4], in lexicographical order. .ị Take the permutations at the indices adjacent to 0.5, i.e., the ones at indices 0 ([4, 3, 2, 1]) and 1 ([1, 2, 3, 4]). m0 Concatenate the resulting [[4, 3, 2, 1], [1, 2, 3, 4]] with a reversed copy, yielding the matrix M := [[4, 3, 2, 1], [1, 2, 3, 4], [1, 2, 3, 4], [4, 3, 2, 1]]. µ Begin a new, monadic chain. Argument: M Z Zip/transpose M, yielding the matrix [[4, 1, 1, 4], [3, 2, 2, 3], [2, 3, 3, 2], [1, 4, 4, 1]]. ḂÞ Sort the rows by the lexicographical order of their parities, yielding [[4, 1, 1, 4], [2, 3, 3, 2], [3, 2, 2, 3], [1, 4, 4, 1]]. ’ Subtract 1 to yield the matrix of quotients, i.e., [[3, 0, 0, 3], [1, 2, 2, 1], [2, 1, 1, 2], [0, 3, 3, 0]]. ×4+ Multiply the quotient by 4 and add the result to M (remainders). ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “¡6ṡƘ[²Ḳi<’ḃ⁴s4 ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=4oCcwqE24bmhxphbwrLhuLJpPOKAmeG4g-KBtHM0&input=)** Pretty boring, sorry: Prep: Took the square, read it by rows, converted from bijective base 16, convert that to base 250, looked up the code page indexes for those "digits" (`¡6ṡƘ[²Ḳi<`). Jelly then reads the indexes to make a base 250 number, converts to bijective base 16 (`ḃ⁴`) and splits into chunks of size 4 (`s4`). --- If we are allowed to output a different orientation, upside-down is possible in **14**: ``` “#⁷ƙ¤ṆWȷỤ’ḃ⁴s4 ``` [Test](http://jelly.tryitonline.net/#code=4oCcI-KBt8aZwqThuYZXyLfhu6TigJnhuIPigbRzNA&input=) --- In theory, given enough memory for `16!` integers the following would give us the correct orientation in **14**: ``` ⁴Œ!“ŒCġŀḌ;’ịs4 ``` This would create all permutations of [1,16] with `⁴Œ!` and pick the value at index 19800593106060 (1-based) with `ị` using the base 250 representation `ŒCġŀḌ;` and split it into chunks of length 4 with `s4`. --- Since then I have added four new atoms (`Œ?`, `Œ¿`, `œ?`, and `œ¿`) to Jelly to address such situations. The monad `Œ?` takes an integer (or iterable of integers) and returns the shortest possible permutation of running natural numbers which would have the given index (or indexes) in a list of lexicographically sorted list of all permutations of those numbers. ...and it does so without creating any permutation lists. As such the following would now work for **12** (obviously non-competing): ``` “ŒCġŀḌ;’Œ?s4 ``` [Give It A Go!](http://jelly.tryitonline.net/#code=4oCcxZJDxKHFgOG4jDvigJnFkj9zNA&input=) [Answer] # J, ~~37~~ 27 bytes *Saved 10 bytes thanks to miles!* ``` 4 4$1+19800593106059 A.i.16 ``` Now with less boring! This takes the `19800593106059` permutation of the list `i.16`, which is `15 2 1 12 4 9 10 7 8 5 6 11 3 14 13 0`. Then, that is incremented, then is shaped into a `4` by `4` list. Alternate version, with no whitespace: ``` _4]\1+19800593106059&A.i.16 ``` Output, for posterity: ``` _4]\1+19800593106059&A.i.16 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 4 4$1+19800593106059 A.i.16 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 ``` [Answer] # Ruby, 49 bytes (shorter than the naive solution!) It took quite a few attempts to write a snippet for this challenge in a mainstream language that was shorter than what it evaluated to! Per usual rules I've made a program out of it by adding a `p` to output it. ``` p [15,4,8,3].map{|i|[1+i,1+i^=13,1+i^=3,1+i^=13]} ``` It outputs (the string representation of) an array of arrays. It's longer than wat's Ruby solution that outputs a differently-formatted string, but one byte shorter than the naive program below that simply returns the literal array. ``` p [[16,3,2,13],[5,10,11,8],[9,6,7,12],[4,15,14,1]] #naive solution, 50 bytes p [15,4,8,3].map{|i|[1+i,1+i^=13,1+i^=3,1+i^=13]} #submission, 49 bytes ``` **Explanation: start with numbers 0..15 (38 bytes!)** This is where I started and it´s much easier. If we convert the 0..15 square into binary, we note that each cell contains the value at the bottom of its column XORed with the value at the right hand side of its row: ``` 15 2 1 12 1111 0010 0001 1100 4 9 10 7 0100 1001 1010 0111 8 5 6 11 1000 0101 0110 1011 3 14 13 0 0011 1110 1101 0000 ``` From this we derive the code below. But by using the first column instead of the last column, we save one byte, as shown. ``` p [12,7,11,0].map{|i|[i^3,i^14,i^13,i]} #0..15 square, 39 bytes p [15,4,8,3].map{|i|[i,i^13,i^14,i^3]} #0..15 square, 38 bytes ``` The required 1..16 version was more difficult. In the end I realised the way to do it was to add 1 to each cell of the 0..15 square. But as `^` has lower priority than `+` I needed a lot of parentheses, which ate bytes. Finally I hit on the idea of using `^=`. The new value of `i` is calculated by augmented assignment `^=` before the 1 is added to it, so the calculation is done in the correct order. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~18~~ 17 bytes Thanks to *Emigna* for saving a byte! ``` •3øÑ¼ž·Üý;•hSH>4ô ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=4oCiM8O4w5HCvMW-wrfDnMO9O-KAomhTSD40w7Q&input=) [Answer] # JavaScript (ES6), 43 bytes ``` _=>`16,3,2,13 5,10,11,8 9,6,7,12 4,15,14,1` ``` Separated by newlines, then commas. I doubt there's any shorter way... [Answer] # sed 39 bytes ``` c16,3,2,13|5,10,11,8|9,6,7,12|4,15,14,1 ``` [Try it Online!](http://sed.tryitonline.net/#code=YzE2LDMsMiwxM3w1LDEwLDExLDh8OSw2LDcsMTJ8NCwxNSwxNCwx&input=) It can't get much simpler than this. And, unfortunately, I don't think it can get any shorter either. [Answer] # Jelly, 20 bytes ``` “Ѥ£Æ¦½¿®µ©¬€¥ÐÇ¢‘s4 ``` [**Try it online!**](http://jelly.tryitonline.net/#code=4oCcw5HCpMKjw4bCpsK9wr_CrsK1wqnCrOKCrMKlw5DDh8Ki4oCYczQ&input=&args=) This simply looks up the Jelly code point of each character, then slices into subarrays of length 4 with `s4`. [Answer] # [DASH](https://github.com/molarmanful/DASH), 24 bytes ``` <|>4tc"................" ``` Replace the periods with the characters of charcodes 16, 3, 2, 13, 5, 10, 11, 8, 9, 6, 7, 12, 4, 15, 14, and 1 respectively. # Explanation Simply converts the characters to an array of charcodes and chunks by 4. [Answer] # [Actually](http://github.com/Mego/Seriously), 22 bytes ``` 4"►♥☻♪♣◙♂◘○♠•♀♦☼♫☺"♂┘╪ ``` [Try it online!](http://actually.tryitonline.net/#code=NCLilrrimaXimLvimarimaPil5nimYLil5jil4vimaDigKLimYDimabimLzimavimLoi4pmC4pSY4pWq&input=) Explanation: ``` 4"►♥☻♪♣◙♂◘○♠•♀♦☼♫☺"♂┘╪ "►♥☻♪♣◙♂◘○♠•♀♦☼♫☺" push a string containing the numbers in the magic square, encoded as CP437 characters ♂┘ convert to ordinals 4 ╪ chunk into length-4 slices ``` [Answer] # Groovy, 57 bytes / 46 bytes ``` "F21C49A7856B3ED0".collect{Eval.me("0x$it")+1}​.collate(4)​ ``` Parse each as hexidecimal digit and add 1, collate by 4 into a 2D array. ``` [[16, 3, 2, 13], [5, 10, 11, 8], [9, 6, 7, 12], [4, 15, 14, 1]] ``` Shorter, but also lamer: ``` print '16,3,2,13|5,10,11,8|9,6,7,12|4,15,14,1' ``` [Answer] # Javascript ES6, ~~66~~ ~~65~~ 55 bytes Yes, it isn't the shortest one. And yes, it can be reduced. ``` _=>`f21c 49a7 856b 3ed0`.replace(/./g,_=>'0x'+_-~0+' ') ``` For now, it isn't perfect. But is something! --- Thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)'s suggestion that could save 5-8 bytes, and that inspired [@ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions) suggestion that saves 10 bytes! This makes the answer only 12 bytes longer than [his 43 bytes solution](https://codegolf.stackexchange.com/a/98155/14732). [Answer] ## PowerShell v2+, 40 bytes ``` '16,3,2,13 5,10,11,8 9,6,7,12 4,15,14,1' ``` A literal multiline string, left on the pipeline. Output via implicit `Write-Output` happens at program completion. Nice and boring. --- Constructed version, 77 bytes ``` 'f21c59a7856b3dc0'-split'(....)'-ne''|%{([char[]]$_|%{"0x$_+1"|iex})-join','} ``` Takes the string, `-split`s it every four elements, loops on them, changes each to a hex `0x$_` and adds `1`, pipes that to `iex` (short for `Invoke-Expression` and similar to `eval`), then `-join`s the result into a string with `,` as the separator. Outputs four strings onto the pipeline, with implicit printing. [Answer] ## Ruby, 60 bytes - first attempt ``` %w(f21c 49a7 856b 3ed0).map{|i|i.chars.map{|i|i.to_i(16)+1}} ``` ## Ruby, 45 bytes - cheap ``` puts '16,3,2,13|5,10,11,8|9,6,7,12|4,15,14,1' ``` [Answer] # Pyth - 17 bytes Base conversion. This unfortunately beats @xnor's approach ``` c4jC"úz(ás¸H"17 ``` [Try it online here](http://pyth.herokuapp.com/?code=c4jC%22%02%C2%82%C3%BAz%28%C3%A1s%C2%B8H%2217&debug=0). [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 15 bytes ``` 16Lœ•iPNÍš¯•è4ä ``` **Explanation** ``` 16L # range [1 ... 16] œ # compute all permutations of the range •iPNÍš¯•è # take the permutation at index 19800593106059 4ä # split the permutation into 4 parts ``` The index of the permutation was found using the formula: `a*15! + b*14! + c*13!+ ... + o*1! + p*0!` Where the variables are replaced with the number of succeeding elements which are smaller than the number at the current index for each number in the target list `[16, 3, 2, 13, 5, 10, 11, 8, 9, 6, 7, 12, 4, 15, 14, 1]` which for our sought after permutation is `a=15, b=2, c=1, d=10, e=2, f=6, g=6, h=4, i=4, j=2, k=2, l=2, m=1, n=2 o=1, p=0` This gives us the formula: `15*15!+2*14!+1*13!+10*12!+2*11!+6*10!+6*9!+4*8!+4*7!+2*6!+2*5!+2*4!+1*3!+2*2!+1*1!+0*0!` which is equal to `19800593106059`. [Answer] ## Matlab, ~~38~~ 35 bytes Anonymous function: ``` @()['pcbm';'ejkh';'ifgl';'dnoa']-96 ``` Direct printing (38 bytes): ``` disp(['pcbm';'ejkh';'ifgl';'dnoa']-96) ``` In Matlab best way to produce an array of integers is though a string. [Answer] # Scala, 52 bytes ``` ()=>Seq(15,4,8,3)map(x=>Seq(x,x^13,x^14,x^3)map(1+)) ``` Ungolfed: ``` ()=> Seq(15, 4, 8, 3) .map(x=> Seq(x, x^13, x^14, x^3) .map(1+) ) ``` Inspired by Level River St's [ruby answer](https://codegolf.stackexchange.com/a/98267/46901). [Answer] # [Python 3](https://docs.python.org/3/), ~~51~~ 47 bytes ``` print("16,3,2,13|5,10,11,8|9,6,7,12|4,15,14,1") ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ8nQTMdYx0jH0LjGVMfQQMfQUMeixlLHTMdcx9CoxkTHECgKJJU0//8HAA "Python 3 – Try It Online") Some solutions @xnor mentioned in the comments. # [Python 3](https://docs.python.org/3/), 54 bytes (construction) ``` for a in 12,7,11,0:print([(a^b)+1for b in[3,14,13,0]]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFRITNPwdBIx1zH0FDHwKqgKDOvRCNaIzEuSVPbEKQgCagg2ljH0ETH0FjHIDZW8/9/AA "Python 3 – Try It Online") # [Python 3](https://docs.python.org/3/), ~~43~~ 41 bytes (0 to 15) ``` for a in 12,7,11,0:print(a^3,a^14,a^13,a) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFRITNPwdBIx1zH0FDHwKqgKDOvRCMxzlgnMc7QBEQAWZr//wMA "Python 3 – Try It Online") -2 thx to @Steffan ]
[Question] [ # Intro In most fonts all of the uppercase alphabet characters besides `BDO` have single lines approximately touching some of the four corners of the character's bounding rectangle: `ACEFGHIJKLMNPQRSTUVWXYZ`. For example, the two legs of an `A` "touch" the bottom left and bottom right corners of the character. Likewise, `C` touches its top and bottom right corners (it is a bit curved but it's close enough). `L` only touches it's top left and bottom right corners with single lines. The bottom left corner of `L` is a vertex, not the end of a single line. Here is a table of what characters touch which corners according to the Stack Exchange font I (and hopefully you) see. `1` is for upper left, `2` is for upper right, `3` lower left, `4` lower right. ``` A: 3 4 C: 2 4 E: 2 4 F: 2 3 G: 2 H: 1 2 3 4 I: 1 2 3 4 J: 1 3 K: 1 2 3 4 L: 1 4 M: 3 4 N: 2 3 P: 3 Q: 4 R: 3 4 S: 2 3 T: 1 2 U: 1 2 V: 1 2 W: 1 2 X: 1 2 3 4 Y: 1 2 Z: 1 4 ``` # Setup Pretend like these corner touching lines extend in the direction of the corner that they touch so that arrangements of these characters on a grid can be "connected". For example, all the characters in ``` A C X ``` are connected because the bottom left of `A` and top right of `C` connect, and the bottom right of `A` and top left of `X` connect. However, ``` CAX ``` has no connections because **connections only occur diagonally from one character to the next**. # Challenge Write the shortest program possible (in bytes) that outputs all of the characters in `ACEFGHIJKLMNPQRSTUVWXYZ` in one big fully connected tree, according to the rules above. **Each character must appear exactly once.** Use spaces for empty space. # Example Everything in this 23-letter tree can be reached from anything else via the diagonal connections defined above: ``` Q A J R C U S Y I M N E H X F L T G Z K P V W ``` # Notes * You may hardcode your solution. * Your output should only contain `ACEFGHIJKLMNPQRSTUVWXYZ`, spaces, and newlines. `BDO` will not be used. * Leading/trailing spaces are fine as long as all the connections are properly positioned. * The output grid should not be larger than 30 by 30 characters (including newlines and spaces). * Only corner connections are considered. The bottom of `Y` does not connect to anything. You must use the corner connections from the table above. * Not all connectable corners need to connect to something. Connectable and non-connectable corners may border each other. * Output to stdout. There is no input. * Including a connectivity graph made with slashes as [Peter Taylor](https://codegolf.stackexchange.com/a/35877/26997) has done is a helpful touch but not required. **Update:** githubhagocyte has made an alphabet tree validity checker [over on Github](https://github.com/phagocyte/Alphabet-tree-checker/blob/master/alphabet-tree-checker.py). [Answer] ## Python, 49 ``` print' '.join(' MQRCNAF\n XZHLKSIP\n\0GJWVUYET') ``` Example: ``` >>> print' '.join(' MQRCNAF\n XZHLKSIP\n\0GJWVUYET') M Q R C N A F X Z H L K S I P G J W V U Y E T ``` I think it connects up properly now, but I may have missed something again. [Answer] ## GolfScript (41 chars) ``` 'QZENRPMALHIFKSXJTUVWYGC'8/{' '*n' '+:n}/ ``` [Online demo](http://golfscript.apphb.com/?c=J1FaRU5SUE1BTEhJRktTWEpUVVZXWUdDJzgveycgJypuJyAnKzpufS8K) Connectivity graph: ``` Q Z E N R P M A \ \ \ / / \ / / \ / \ L H I F K S X J \ / \ / \ / / \ / / / T U V W Y G C ``` [Answer] # [Marbelous](https://github.com/marbelous-lang) ~~164~~ ~~158~~ 143 used [bmarks' tree](https://codegolf.stackexchange.com/questions/35862/make-me-an-alphabet-tree/35869#35869) since it almost perfectly optimized for [Marbelous](https://docs.google.com/document/d/1fAMDwPqtVgjINDny7BpcaO9tCnPJtXQWaFf4kzDhsdw/edit#). Code in this case is just the ascci codes for all characters (including spaces and newlines) from left to right, delimited by spaces. ``` 43 20 46 20 50 20 4D 20 51 20 52 20 45 20 41 14 20 58 20 48 20 4e 20 4C 20 4B 20 5A 20 49 20 53 14 47 20 59 20 56 20 20 20 55 20 4A 20 54 20 57 ``` *Output:* ``` C F P M Q R E A X H N L K Z I S G Y V U J T W ``` # A better Marbelous approach ~~135~~ 129 This one outputs the same tree with one extra space before and after each line, it works by feeding the literals into a subroutine that prints a space before printing the literal. And just printing a space if the literal is a space (20 HEX) ``` 57 54 4A 55 20 56 59 47 14 53 49 5A 4B 4C 4E 48 58 20 14 41 45 52 51 4D 50 46 43 Sp Sp: 20 I0 .. =V ``` [Answer] # BrainF\*ck 669 Made this one for giggles. Outputs the exact same as the example. Will provide another solution later. Can't think of a clever way to do this in Lua so I'll just stick to this one :) ``` ++++[->++++++++<]>..[-->+++++<]>+.>++++++++++.[->+++<]>++.[->++<]>+.-[-->+<]>.+++++[->++<]>.--[->++++<]>...>-[--->+<]>---.>++++++++++.+[->++++++<]>+.-[-->+<]>-.>-[--->+<]>.[----->++<]>--...>-[--->+<]>--.+[--->+<]>++++.--[->+++<]>-.[->+++<]>-.[->+++<]>++.++++[->++<]>+.-[->++++<]>.++++++[->++<]>+.-----[->++++<]>.[-->+++++<]>--.>++++++++++.[->+++++++<]>-.-[-->+<]>--.++++[->++<]>.[->++++<]>.[++++>---<]>.>++++++++++.[->+++<]>++.+++[->++<]>.[-->+<]>---.++++++[->++<]>.[-->+<]>------.>-[--->+<]>-.>++++++++++.[->+++++++<]>+.+[->++++<]>...--[->+++<]>.[--->+<]>++.--[-->+++++<]>.---[->++++<]>.[-->+++++<]>.>++++++++++.[->+++<]>++.....>+[--->++<]>.+[--->+<]>+++.---[->+++<]>. ``` ### Output ``` Q A J R C U S Y I M N E H X F L T G Z K P V W ``` [Answer] # PHP 46 This was more like puzzle solving rather than programming, so my answer is more like puzzle solution rather than code. However it's a valid PHP program, so I'm submitting it. ``` C A Q S R P M J X Z I F K N H G T U V W Y E L ``` **Update** the same in Perl. Length still remains 46: ``` print"CAQSRPMJ XZIFKNH GTUVWYEL"=~s/\S/$& /rg ``` [Answer] ## HTML, 55 code ``` <pre>C F P M Q R E A X H N L K Z I S G Y V U J T W ``` output: ``` C F P M Q R E A X H N L K Z I S G Y V U J T W ``` [Answer] # Bash+coreutils, 46 ``` sed 's/\S/ &/g'<<<"CAQSRPMJ XZIFKNH GTUVWYEL" ``` Now shamelessly borrowing [@core1024 optimal tree](https://codegolf.stackexchange.com/a/35899/11259): ### Output: ``` $ ./alphatree.sh C A Q S R P M J X Z I F K N H G T U V W Y E L $ ``` [Answer] ## STATA 63 Edit: now my own solution. Should be all the letters. ``` di 'C F P M Q R E A' di ' X H N L K Z I S' di 'G Y V U J T W' C F P M Q R E A X H N L K Z I S G Y V U J T W ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 32 ``` jd"QAPMFRLZ\nUINKSHXJ\n\0GTCVEWY ``` Output: ``` Q A P M F R L Z U I N K S H X J G T C V E W Y ``` Connections, thanks to @githubphagocyte's checker: ``` Q A P M F R L Z \ / \ / / \ / / \ \ \ U I N K S H X J / \ / / \ / / \ / \ / G T C V E W Y ``` Combines @grc's null byte trick and Pyth's extremely short syntax. Made my own grid for the hell of it. Explanation: `j` is python's string join. `d` is space. `\0` is the escape sequence for the null byte. It is a NOP when printed, so the third line has exactly two spaces in front. Also, note that strings can be EOL-terminated in Pyth, as well as quote-terminated. [Answer] # Javascript 83 I'll begin with hardcoding YOUR solution ``` console.log(' Q\n A J R\nC U S Y\n I M N\nE H X\n F L T\nG Z K P\n V W') ``` [Answer] # PHP, 69 ``` <?php echo preg_replace("/(\w)/",'\1 ',"CAQSRPMJ XZIFKNH GTUVWYEL"); ``` gives ``` C A Q S R P M J X Z I F K N H G T U V W Y E L ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 28 bytes ``` «⟑Eƈ↓Z↔⁺τ¾ꜝdB_ḣC«3/ƛṄ¥$꘍&›⇧, ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C2%AB%E2%9F%91E%C6%88%E2%86%93Z%E2%86%94%E2%81%BA%CF%84%C2%BE%EA%9C%9DdB_%E1%B8%A3C%C2%AB3%2F%C6%9B%E1%B9%84%C2%A5%24%EA%98%8D%26%E2%80%BA%E2%87%A7%2C&inputs=&header=&footer=) Yes, I stole @isaacg's grid. ``` «...« # Compressed string 'qapmfrlzuinkshxjgtcvewy ' (Note trailing space) 3/ # Into 3 pieces ƛ # Map... Ṅ # Join by spaces ¥$꘍ # Prepend (register) spaces &› # Increment register ⇧, # Output as uppercase. ``` ]
[Question] [ ## Introduction In a private chat, a friend of mine apparently recently stumbled across a security system which has the following two restrictions on its valid pins: * Each digit must be unique (that is "1" may only appear once) * The order of the digits doesn't matter ("1234"="4321") So to illustrate how bad this padlock system is, let's actually enumerate all valid PINs! ## Input Your input will consist of a single, positive integer, which denotes the length of the PIN. ## Output Your output consists of a list of non-negative integers or strings\*, which enumerate all valid PINs of the given length. \*More precisely something that a human can use to try all combinations if you would print it for them. This means set of sets of digits and arrays of arrays of digits are fine. ## Who wins? This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins! Standard rules and [loopholes](https://codegolf.meta.stackexchange.com/q/1061/55329) apply. ## Corner Cases * The output behaviour is undefined if an integer greater than 10 is input. * The ordering of the digits within each output entry is undefined, as entries with a zero actually contain said zero, that is you may not strip "0123" to "123" but "1230", "1203" and "1023" are all valid as is "0123". ## Test Cases ``` 1 [0,1,2,3,4,5,6,7,8,9] 2 [10,20,30,40,50,60,70,80,90,21,31,41,51,61,71,81,91,32,42,52,62,72,82,92,43,53,63,73,83,93,54,64,74,84,94,65,75,85,95,76,86,96,87,97,98] 3 [210,310,410,510,610,710,810,910,320,420,520,620,720,820,920,430,530,630,730,830,930,540,640,740,840,940,650,750,850,950,760,860,960,870,970,980,321,421,521,621,721,821,921,431,531,631,731,831,931,541,641,741,841,941,651,751,851,951,761,861,961,871,971,981,432,532,632,732,832,932,542,642,742,842,942,652,752,852,952,762,862,962,872,972,982,543,643,743,843,943,653,753,853,953,763,863,963,873,973,983,654,754,854,954,764,864,964,874,974,984,765,865,965,875,975,985,876,976,986,987] 4 [3210,4210,5210,6210,7210,8210,9210,4310,5310,6310,7310,8310,9310,5410,6410,7410,8410,9410,6510,7510,8510,9510,7610,8610,9610,8710,9710,9810,4320,5320,6320,7320,8320,9320,5420,6420,7420,8420,9420,6520,7520,8520,9520,7620,8620,9620,8720,9720,9820,5430,6430,7430,8430,9430,6530,7530,8530,9530,7630,8630,9630,8730,9730,9830,6540,7540,8540,9540,7640,8640,9640,8740,9740,9840,7650,8650,9650,8750,9750,9850,8760,9760,9860,9870,4321,5321,6321,7321,8321,9321,5421,6421,7421,8421,9421,6521,7521,8521,9521,7621,8621,9621,8721,9721,9821,5431,6431,7431,8431,9431,6531,7531,8531,9531,7631,8631,9631,8731,9731,9831,6541,7541,8541,9541,7641,8641,9641,8741,9741,9841,7651,8651,9651,8751,9751,9851,8761,9761,9861,9871,5432,6432,7432,8432,9432,6532,7532,8532,9532,7632,8632,9632,8732,9732,9832,6542,7542,8542,9542,7642,8642,9642,8742,9742,9842,7652,8652,9652,8752,9752,9852,8762,9762,9862,9872,6543,7543,8543,9543,7643,8643,9643,8743,9743,9843,7653,8653,9653,8753,9753,9853,8763,9763,9863,9873,7654,8654,9654,8754,9754,9854,8764,9764,9864,9874,8765,9765,9865,9875,9876] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ØDœc ``` [Try it online!](https://tio.run/##y0rNyan8///wDJejk5P/H26P/P/fGAA "Jelly – Try It Online") # Explanation ``` ØDœc Double-builtin; main link œc Number of combinations of of length ØD [digits] <right argument> ``` Behavior for `n > 10` is empty list. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` žhæsù ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6L6Mw8uKD@/8/98YAA "05AB1E – Try It Online") **Explanation** ``` sù # keep elements the length of the input æ # from the powerset žh # of 0123456789 ``` [Answer] # JavaScript (ES7), 89 bytes Returns a list of lists of digits (as characters), or an empty list if **n > 10**. ``` n=>[...2**29+'4'].reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).filter(a=>a.length==n) ``` [Try it online!](https://tio.run/##XY3BbsJADETv@QrfvCap1SIuKGx@JOzBChsaFLwo2SIQ4tvTXeipF3vG46c5yVXmbhou8UPDwS@9XdQ2LTOvV6v1tsQNOp784afzxkh1o3coVR58lou5p8st27sjV7Wtc8T9MEY/GbGN8Oj1GL@tVVqinyNYULAN9EbpxUt2wqcwqEEk@lMVEpSAe8W6KPowmUTBV53gXdqfSZQlwaMA6ILOYfQ8hqPB/IUJVKr/Rbk8dVLxXH4B "JavaScript (Node.js) – Try It Online") ### How? We first generate a list of all decimal digits as characters by computing **229 = 536870912**, adding the missing **'4'** and splitting: ``` [...2**29+'4'] → [ '5', '3', '6', '8', '7', '0', '9', '1', '2', '4' ] ``` We then compute the powerset: ``` .reduce( ,[[]]) // starting with a[] holding an empty list (a,x)=>[ ] // for each decimal digit x: ...a, // copy all previous entries in a[] ...a.map(y=> ) // and duplicate each previous entry y [x,...y] // with x prepended at the beginning ``` Finally, we filter the results on their length: ``` .filter(a=>a.length==n) ``` [Answer] # [Python 3](https://docs.python.org/3/), 57 bytes ``` lambda l:combinations(range(10),l) from itertools import* ``` [Try it online!](https://tio.run/##BcExDoAgDADA3VcwtsZB42biT1xQQZuUlpQuvh7v6uevytrzfnSO5bxj4O3ScpJEJ5UGFuVJsMw4MQ7ZtATyZK7KLVCpaj72aiQOTM0hw4qI/Qc "Python 3 – Try It Online") Finds all combinations of `0 .. 9` of length `l`. Behavior for `n > 10` is empty list. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 22 bytes ``` 0~Range~9~Subsets~{#}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8d@gLigxLz21zrIuuDSpOLWkuK5auVbtv6Y1V0BRZl5JtLKuXZqDso4Sl1Ksmr5DNReXoQ6XkQ6XsQ6XCRdX7X8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 62 bytes ``` f=lambda n:{d+s for d in`5**19`*n for s in f(n-1)if d>s}or{''} ``` Returns a set of strings. [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIc@qOkW7WCEtv0ghRSEzL8FUS8vQMkErDyxSDBRRSNPI0zXUzExTSLErrs0vqlZXr/0PkswDSRYl5qWnahjqKJhqWnFxFhRl5pUo5MEYxflFJakpGkADNDWhYv8B "Python 2 – Try It Online") [Answer] # Pyth, 4 bytes ``` .cUT ``` [Try it here](http://pyth.herokuapp.com/?code=.cUT&input=4&debug=0) ### Explanation ``` .cUT UT [0, 1, ..., 9]. .c Q All (implicit input)-element subsets. ``` [Answer] # [R](https://www.r-project.org/), 17 bytes ``` combn(0:9,scan()) ``` [Try it online!](https://tio.run/##K/r/Pzk/NylPw8DKUqc4OTFPQ1Pzv9F/AA "R – Try It Online") Errors for input greater than `10`. Returns a `matrix` where each column is a PIN. [Answer] # [Ruby](https://www.ruby-lang.org/), 30 bytes ``` ->n{[*[*0..9].combination(n)]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOlorWstAT88yVi85PzcpMy@xJDM/TyNPM7b2f4FCWrRR7H8A "Ruby – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` 4Y2wXN ``` [Try it online!](https://tio.run/##y00syfn/3yTSqDzC7/9/IwA "MATL – Try It Online") Returns nothing (empty array) for `k>10`. ``` % implicit input k 4Y2 % push '0':'9' w % swap top two elements of stack XN % nchoosek, select all k-combinations of '0':'9' as a char array % implicit output ``` [Answer] # [Haskell](https://www.haskell.org/), ~~56~~ 50 bytes -6 bytes thanks to [Hat Wizard](https://codegolf.stackexchange.com/users/56656/hat-wizard). ``` (10!) _!0=[[]] w!n=[0..w-1]>>=(map.(:)<*>(!(n-1))) ``` [Try it online!](https://tio.run/##BcFRCoQgEADQ/04xwn7MBIr2GY0XMVkk1jYykQq6/c6@903X/ilFMs@Czirq3spyCDF2j6ocrDGPdtF7xiM1gyNNvUeFVTsikiNtFRjaudUbXpBhkN@SS1ov0Utrfw "Haskell – Try It Online") [Answer] # [Java (JDK 10)](http://jdk.java.net/), 105 bytes ``` n->{var s="";for(int i=1024,j;i-->0;s+=" ")for(j=10;n.bitCount(i)==n&j-->0;)s+=(1<<j&i)>0?j:"";return s;} ``` [Try it online!](https://tio.run/##Lc4xa8MwEAXgPb/i8BCkNhZO6BTZ7lAodOiUsXRQHNucap@MdDKE4N/uKmmn43gfj2fNbHJ7@VlxnJxnsOlXkXFQXaSG0ZF60ptmMCHAp0GC2wZgiucBGwhsOJ3Z4QXGlIkTe6T@6xuM74NMNFmA9/@i8oO47Vu/@2M1dNVKeX2bjYdQZZnunBdIDFjti8PLzmrM87rQ4bnKIJP31KZEkzojv7lILFBWFW3tg8nkxL4s7RZlXbzaY2r0LUdPEPSy6seW0zVwOyoXWU1pBA8kOmWmabiKg5R3s2yW9Rc "Java (JDK 10) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 47 bytes ``` f 0=[[]] f n=[a:x|x<-f$n-1,a<-[0..9],all(/=a)x] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P03BwDY6OjaWK00hzzY60aqipsJGN00lT9dQJ9FGN9pAT88yVicxJ0dD3zZRsyL2f25iZp5tQVFmXomKQpqC0X8A "Haskell – Try It Online") ## Explanation When the number of digits is zero there is only one combination, that is the empty one: ``` f 0=[[]] ``` When the number of digits is `n` and `n/=0` the combinations are all the ways to add digits to combinations from `f$n-1` such that no digit is addded to a combination that already contains it. ``` f n=[a:x|x<-f$n-1,a<-[0..9],all(/=a)x] ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), ~~4~~ 3 bytes ``` ₸…K ``` [Try it online!](https://tio.run/##S0/MTPz/3@FR045HDcu8//83AgA "Gaia – Try It Online") It's been a while since I posted an answer in Gaia! *Thanks to Mr. Xcoder for saving a byte!* ``` % implicit input n ₸ % push 10 … % pop 10, push 0..9 K % all subsets of size n % print top of stack implicitly ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~51~~ 36 bytes ``` .+ 10* "$+"{%`^. *_$& L$v`_+ $.%`$%' ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0@by9BAi0tJRVupWjUhTo9LK15FjctHpSwhXptLRU81QUVV/f9/YwA "Retina – Try It Online") Outputs nothing for `n>10`. Explanation: ``` .+ 10* ``` Replace the input with 10 `_`s. ``` "$+"{ ``` Repeat the rest of the program `n` times. ``` %`^. *_$& ``` Prefix each number with `_` repeated according to its first digit. ``` L$v`_+ ``` Match all `_`s, but include all of the following `_`s in the match too, for which we need to enable overlapping matches. ``` $.%`$%' ``` For each `_` found, prefix the number of `_`s to its left to the number. This is a bit tricky so perhaps an actual case would be better. Let's suppose that we've already run the loop twice, so that all 2-digit PINs have been generated, and we're currently working through them to create 3-digit PINs. We'll look at what happens to `36`: The first digit is `3`, so three `_`s are prefixed, to make `___36`. This then creates the following matches, marked here with ``'`s: ``` Match $%` $.%` `___'36 0 _`__'36 _ 1 __`_'36 __ 2 ``` `$%'` evalutes to `36` in all three cases, resulting in the 3-digit PINs `036`, `136` and `236`. If we were then to go on to create 4-digit PINs, then `036` would not have any `_`s prefixed, and therefore would result in no matches at all in the final output. [Answer] # [Proton](https://github.com/alexander-liao/proton), 43 bytes ``` (0..9)&__import__("itertools").combinations ``` [Try it online!](https://tio.run/##BcExCoAwDAXQu3SQZCmCk4NnCSoWAm1@SXP/@N50BCzblbTXevImomPCQ4SKxucB9FW4vhiP2h0KWzldLajrCmp0MHP@ "Proton – Try It Online") Proton finally outgolfs Python :D I thought `(import itertools)` would return the value but apparently I failed at that. Also importing `*` afterwards doesn't work because it's not in a lambda, it's a top-level expression. [Answer] # Japt, 5 bytes Outputs an array of digit arrays. Outputs *all* combinations if input is `0` or an empty array if input is `<0` or `>10`. ``` Ao àU ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=QW8g4FU=&input=OAotUQ==) --- ## Explanation ``` :Implicit input of integer U A :10 o :Range [0,10) àU :Combinations of length U ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 4 bytes ``` Vd,S ``` [Try it online!](https://tio.run/##Ky5JrPj/PyxFJ/h/7n8jAA "Stax – Try It Online") `Vd` is `"0123456789"`. `,` pushes the input to the main stack. `S` gets combinations of the specified size. In the tio link, `m` is used in the footer to print each output. [Answer] # [Standard ML](http://www.mlton.org/), ~~124~~ ~~122~~ 121 bytes ``` open List;fun f(s:: &)m=(if exists(fn x=>x=m)s then[]else[m::s])@f&m|f&m= & fun!0=[[]]| !n=concat(tabulate(10,f(!(n-1)))) ``` [Try it online!](https://tio.run/##bc2xTsQwDAbgvU/xt0PlSHfoTmxBQaxIbIyhoHBK7iolTtX4oEPfvYRj5Zfswf5klxT3KUrmbcuTZ7yMRR7ClRGoaI1eJUNjgF/qvFBgLOZxMUkVyMWzHXws3iaty6CeQp/WWgZ9Uy@0B2PtMKxo2Zwyn5yQuM9rdOLpeNgFaon3R1Wz/f4rl/wNywNqDJ5Z7iS/yjzyGYx3dG/cNcD654i1ntW/btfVfkNz03y5iI/KkptAU0WCfFsqUIt7tf0A "Standard ML (MLton) – Try It Online") Example usage: `!2` yields `[[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8],[0,9],[1,0],[1,2],[1,3], ...]`. **Ungolfed:** ``` open List; (* int list list -> int -> int list list *) fun f (s::r) m = if exists (fn x => x=m) s then f r m else (m::s) :: f r m | f [] m = [] (* int -> int list list *) fun g 0 = [[]] | g n = concat(tabulate(10, f(g(n-1)))) ``` --- **Some alternatives:** ### ~~125~~ 123 bytes ``` fun f(s:: &)m=(if List.exists(fn x=>x=m)s then[]else[m::s])@f&m|f&m= & fun!m 0=[[]]| !10n=[]| !m n=f(!0(n-1))m@ !(m+1)n;!0; ``` [Try it online!](https://tio.run/##bY0xa8MwEIV3/4onD0ZHmmDTTUEla6BbR1UJGazG4DsHS2k9@L@7crLmwT0e3Hf3Ivdb7tMgyxLugqCjMaiIre4CPruYdu2UPeogmOzHZJki0rUV59s@to6NiZ4OoeI5j0VV5DeKUVvnvJ@hmlqsWwNDbNCq1rJtiPgApXnTkOxVvV9@Lz0ULLq03iNehz848ciyOErapeErjZ38QHBC@S1lAcxPTosxI73k3srsD2gsirXjnDG@3KBvGUoYHkuCVnin5R8 "Standard ML (MLton) – Try It Online") Defines an anonymous function which is bound to `it`. ### ~~127~~ 124 bytes ``` fun!0=[[]]| !n=let fun f(s:: &)m=(if List.exists(fn x=>x=m)s then[]else[m::s])@f&m|f&9=[]|f&m=f(!(n-1))(m+1)in f(!(n-1))0end ``` [Try it online!](https://tio.run/##bY3BTsMwEETv@YpJDtGuoFUrTlgy4orEjaMxqBJ2G8m7qWIDOeTfg1s4MocZafZpJ0vaSCqjrmv81HZnnfN@Qas2hYJaIVI2Bj2LpSHiechlG@bqmaJitg@zFc4op6DOh5SDE2Oy58fYyxL7e@t8DbGRWtLNnpnkZs/D5e9fsQv6cRlHPo3fcOpRZfGkZVvGlzINeoTiDd2rdg2w/HKkxkz8L3fbVb9CU9N8HRLeKyaHM@hcoYLxemRQiztefwA "Standard ML (MLton) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 53 bytes ``` f=(i,b='',k=10)=>k--?f(i-1,k+b,k)+f(i,b,k):i?'':b+`,` ``` [Try it online!](https://tio.run/##ZcrBDkAgAIDhuxepVlnhlMWrVMhSk2FeP7rq9u/bv@lHX9PpjpvucV5SshI6YiQAxEvOkBw8paOFjnLisSEeYZuHL4QbARAGq0qlvprifsWw1CGu0EKG0J94SU1JbUldpvQC "JavaScript (Node.js) – Try It Online") [Answer] # Oracle 18 SQL, 169 bytes Not a golfing language but: ``` WITH t(v)AS(SELECT*FROM SYS.ODCINUMBERLIST(0,1,2,3,4,5,6,7,8,9)),n(a,b,c)AS(SELECT a,-1,''FROM i UNION ALL SELECT a-1,v,v||c FROM n,t WHERE v>b)SELECT c FROM n WHERE a=0 ``` Expected the input to be in a table `i` with column `a`: ``` CREATE TABLE i (a INT); INSERT INTO i VALUES ( 3 ); ``` Try it online at [Oracle Live SQL](https://livesql.oracle.com) (a free login is required then copy-paste the solution into a worksheet) or [SQLFiddle](http://sqlfiddle.com/#!4/73b74/2) (no login but requires +7 bytes to work on the lower Oracle version). [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~13~~ 11 bytes ``` {Ae!f<:$_|} ``` [Try it online!](https://tio.run/##S85KzP3/v9oxVTHNxkolvqb2v1WEdWFdRMF/EwA "CJam – Try It Online") Technically doesn't run on tio.run, since heap space runs out. However, it works properly for up to 9 digit keypads, and should run just fine with more RAM. Saved 2 bytes thanks to Dennis [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~113~~ 99 bytes ``` p()(r $1 0 $[10-$1]) r()for i in `seq $2 $3`;{ (($1>1))&&r $[$1-1] $[i+1] $[$3+1] $4$i||echo $4$i;} ``` [Try it online!](https://tio.run/##HYxBCsMgFAX3PcVbfILSCvkxO6EXCYGkjSVuNNXuas9uo6t58Jh5rGkv5RBSRBCjB03cK@JZXqKQrxDh4DyWZN@gAaQX84UQxHeWsutOaSJWPJ901wbSjSO5nO1zD22aX6ktX1uMARqjwRZwgDwyjjV9LFTabgbVqZ@35Q8 "Bash – Try It Online") [Answer] ## JavaScript (Firefox 30-57), 67 bytes ``` n=>n?[for(x of f(n-1))for(y of Array(x?+x[0]:10).keys())y+x]:[''] ``` Port of my Retina answer, but works for `n=0` too (returning a list of an empty string, as distinct from an empty list for `n>10`). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` ⊞υωFχ≔⁺υEυ⁺κIιυΦυ⁼θLι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gtDhDo1RHoVzTmistv0hBw9BAU8GxuDgzPU8jIKe0GCTnm1gAosDcbB0F58TiEo1MTSDQUSgFagsoyswr0XDLzClJLQKpcy0sTcwp1ijUUfBJzUsvyYCotf7/P9o49r9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υω ``` Push the empty string to the predefined list. ``` Fχ ``` Loop over each digit. ``` Eυ⁺κIι ``` Append the digit to every string in the list. ``` ≔⁺υ...υ ``` Append the result to the original list. ``` Φυ⁼θLι ``` Print all strings with the correct number of digits. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 20 bytes ``` {combinations 10,$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJZq@786OT83KTMvsSQzP69YwdBARyW@9r81V3EiSFrDUBPONEIwjRFMS03r/wA "Perl 6 – Try It Online") This is exactly what `combinations` (as a subroutine, or `.combinations` on a list) is for. <https://docs.perl6.org/routine/combinations> [Answer] # [J](http://jsoftware.com/), 32 bytes .. frustratingly longer than [Mathematica](https://codegolf.stackexchange.com/a/166735/80062) and [R](https://codegolf.stackexchange.com/a/166737/80062) `f=:{[:(#@>"0]/.])[:<@I.@#:@i.2^]` [TIO](https://tio.run/##y/r/P83WqjraSkPZwU7JIFZfL1Yz2srGwVPPQdnKIVPPKC72f2pyRr6Cekl5vkJaUX6uQnFmhbq1gpFCmoIZF1jKQsHQVEXBGChgaPAfAA "try it online") ]
[Question] [ # Challenge [![enter image description here](https://i.stack.imgur.com/dqCkE.jpg)](https://i.stack.imgur.com/dqCkE.jpg) Write a program that takes an array of 4 integers (*which represents a sequence of numbers generated by a certain algorithm*) and returns the next integer that would follow. We will only be using simple addition, subtraction, multiplication and division algorithms with a constant (i.e non-variable) variation. For division we will use the `floor` integer values: `133/4 = 33` and `33/4 = 8` **You can assume that there will always be one single valid return value** # Test cases `[14,24,34,44]` should return 54 (addition Algorithm) `[105,45,-15,-75]` should return -135 (subtraction algorithm) `[5,25,125,625]` should return 3125 (multiplicative algorithm) `[256,64,16,4]` should return 1 (division algorithm) # General rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins the challenge. * [Standard loopholes are forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default?answertab=votes#tab-top) [Answer] ## Javascript (ES6), ~~44~~ ~~42~~ 44 bytes (fixed) ``` (a,b,c,d)=>a-b+d-c?d/(a<b?a/b:a/b|0)|0:d+c-b ``` *Saved 2 bytes, following IsmaelMiguel's advice.* *Fixed version for `[2,1,0,0]` and `[1,0,0,0]` as suggested by edc65* ### 30 bytes version For the record, my first attempt was ~~32~~ 30 bytes but was lacking floor() support for the division. It also fails for special cases such as `[2,1,0,0]` and `[1,0,0,0]`. ``` (a,b,c,d)=>c-2*b+a?d*c/b:d+c-b ``` ### Demo ``` var f = (a,b,c,d)=>a-b+d-c?d/(a<b?a/b:a/b|0)|0:d+c-b var test = [ [ 14, 24, 34, 44 ], // should return 54 (addition Algorithm) [ 105, 45, -15, -75 ], // should return -135 (subtraction algorithm) [ 5, 25, 125, 625 ], // should return 3125 (multiplicative algorithm) [ 256, 64, 16, 4 ], // should return 1 (division algorithm) [ 260, 65, 16, 4 ], // should return 1 (division algorithm with floor()) [ 2, 1, 0, 0 ], // should return 0 (special case of division algorithm) [ 1, 0, 0, 0 ] // should return 0 (special case of division algorithm) ]; test.forEach(l => console.log('[' + l.join`, `+ '] => ' + f(...l))); ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), ~~37~~ ~~33~~ 27 bytes ``` b:[E]cL,?:Iz{:+a|:*a|:/a}Lt ``` [Try it online!](http://brachylog.tryitonline.net/#code=YjpbRV1jTCw_Okl6ezorYXw6KmF8Oi9hfUx0&input=WzU6MjU6MTI1OjYyNV0&args=Wg) or [verify all test cases](http://brachylog.tryitonline.net/#code=OjFhOkB3YQpiOltFXWNMLD86SXp7OithfDoqYXw6L2F9THQ&input=W1sxNDoyNDozNDo0NF06WzEwNTo0NTpfMTU6Xzc1XTpbNToyNToxMjU6NjI1XTpbMjU2OjY0OjE2OjRdXQ). *Saved 10 bytes thanks to @LeakyNun*. ### Explanation ``` Input = [A:B:C:D] b:[E]cL, L = [B:C:D:E] ?:Iz Create the list [[B:I]:[C:I]:[D:I]:[E:I]] { Either… :+a Sum all couples of that list | or… :*a Multiply all couples of that list | or… :/a Integer divide all couples of that list }L The result is L t Output is the last element of L ``` As LeakyNun pointed out, we don't need the subtraction case because `I` can be any integer. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~18~~ ~~16~~ 18 bytes ``` D¥¬QPi`+s-ë`r/s\*î ``` **Explanation** ``` D # duplicate ¥ # delta's ¬Q # compare first delta to the other deltas P # product (1 if all deltas are equal, otherwise 0) i # if 1 (we're dealing with addition or subtraction) `+s- # add the difference between the elements to the last element ë # else (we're dealing with multiplication or division) `r/ # divide the 2nd element by the 1st s\* # multiply with the 4th element î # round up ``` [Try it online!](http://05ab1e.tryitonline.net/#code=RMKlwqxRUGlgK3Mtw6tgci9zXCrDrg&input=WzI2MSw2NSwxNiw0XQ) [Answer] # Haskell, 65 bytes ``` f l@[a,b,c,d]|[a,b..d]==l=d+b-a|z<-b+0^b=div(d*b)$a-mod(max b a)z ``` [Answer] # Python 2, 40 bytes ``` lambda(a,b,c,d):[d+c-b,d*c/b][c-2*b+a>0] ``` It's literally the JS answer ported into Python (thanks @LeakyNun!). My previous approach was ridiculously long, but here it is: ## Python 2, ~~169~~ 166 bytes The second and third levels are a raw tab and a raw tab plus a space, respectively, which plays *really* badly with Markdown, so the tabs have been replaced by 2 spaces. ``` x=input() q='%d%s%d' for i in range(max(x)): for o in'+-*/': a=1 for e,n in zip(x,x[1:]): try:1/(eval(q%(e,o,i))==n) except:a=0 if a:print eval(q%(x[-1],o,i)) ``` Pretty simple; tries every constant and operator it thinks could be the constant, then if the constant/operator combination works for every element in the list (using a `try`/`except` pair to avoid `ZeroDivisionError`s), it prints the result for the last element in the list. I'm sure there's a better method here, this is the naive method. [Answer] # TSQL, 55 bytes This script is trying adding and subtraction in the same check, then it tries to multiply, if that fails, it must be division. ``` DECLARE @1 INT=6561, @2 INT=729, @3 INT=81, @ INT=9 PRINT IIF(@2-@1=@-@3,@*2-@3,IIF(@1*@2=@3,@*@1,sqrt(@))) ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/530802/the-final-number)** [Answer] # C#, 63 bytes ``` int f(int[]x)=>2*x[1]-x[0]==x[2]?x[3]+x[1]-x[0]:x[3]*x[1]/x[0]; ``` Checks whether the difference between the first and second element is the same as the difference between the second and third element. If so, it does addition/subtraction, otherwise it does multiplication/division. [Answer] # JavaScript, 73 bytes ``` (a,b,c,d)=>(x=b-a,c-b==x&&d-c==x)?d+x:(x=b/a,b*x|0==c&&c*x|0==d)?d*x|0:-1 ``` **Tests**: ``` console.log(s.apply(null,[14,24,34,44]), 54); console.log(s.apply(null,[105,45,-15,-75]), -135); console.log(s.apply(null,[5,25,125,625]), 3125); console.log(s.apply(null,[256,64,16,4]), 1); console.log(s.apply(null,[2,1,0,0]),0); console.log(s.apply(null,[1,0,0,0]),0); console.log(s.apply(null,[-325,-82,-21,-6]),-1); console.log(s.apply(null,[-1,-1,-1,-1]),-1); console.log(s.apply(null,[0,0,0,0]),0); ``` Works for them all. [Answer] # GameMaker Language, 70 bytes ``` a=argument0;If a[3]+a[1]=a[2]*2return a[4]*2-a[3]return a[4]*a[4]/a[3] ``` [Answer] ## R, ~~68~~ 74 Array: 68 bytes ``` function(x)if(x[2]-x[1]==x[3]-x[2])x[4]+x[2]-x[1]else x[4]%/%(x[1]%/%x[2]) > (function(x)if(x[2]-x[1]==x[3]-x[2])x[4]+x[2]-x[1]else x[4]*x[2]/x[1])(c(14,24,34,44)) [1] 54 ``` 4 inputs: 45 bytes ``` function(a,b,c,d)if(b-a==c-b)d+b-a else d*b/a ``` Bonus solution with `log`, `exp`, `var`, 71 bytes ``` if(var(v<-diff(x<-scan(,1)))==0)x[4]+v[1]else x[4]*exp(diff(log(x)))[1] ``` update: integer division [Answer] # Java, ~~125~~ 123 bytes Golfed: ``` int m(int[]a){int r=(a[1]>a[0])?a[1]/a[0]:a[0]/a[1];return(a[0]-a[1]==a[1]-a[2])?a[3]-a[0]+a[1]:(a[0]<a[1])?a[3]*r:a[3]/r;} ``` Ungolfed: ``` int m(int[] a) { int r = (a[1] > a[0]) ? a[1] / a[0] : a[0] / a[1]; return (a[0] - a[1] == a[1] - a[2]) ? a[3] - a[0] + a[1] : (a[0] < a[1]) ? a[3] * r : a[3] / r; } ``` This code surely has some issues since it doesn't handle division by zero and such things. It also won't work of course if there are more (or less) than 4 integers in the input array `a`. Which makes it beyond stupid, but I had fun :) Try it out: <https://ideone.com/nELH5I> [Answer] # TI-Basic, 37 bytes *Works on any TI-83/84 calculator* ``` Input L1 gets input into an array L1(4)²/L1(3 calculate the fifth number in a geometric series If not(sum(ΔList(ΔList(L1 if ΔList(ΔList(L1)) yields an array of all zeroes L1(4)2-L1(3 calculate the fifth number in an arithmetic series Ans is implicitly returned ``` [Answer] # Python 2, ~~75 66 65~~ 61 bytes ``` lambda(a,b,c,d):d*2-c if d-c==b-a else d*b/a or b and d/(a/b) ``` Much longer than my previous 38 byte entry which did not cater for the division series correctly (just as most others didn't). Test cases and more edge cases are on [**ideone**](http://ideone.com/lcrrk4) *Note: integer division for a negative here is defined as having a remainder with the same sign as the divisor, so `-81/4` would be `-21` with a remainder of `3` and `-81/-4` would be `20` with a remainder of `-1`.* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` ṪḤ_ṪµṪ²:ṪµIE$? ``` [Try it online!](https://tio.run/##y0rNyan8///hzlUPdyyJB1KHtoKITVZgpqeriv3///8NdIx0THTMAA "Jelly – Try It Online") ``` ṪḤ_ṪµṪ²:ṪµIE$? Main Link = ? If IE$ [condition] I The differences between consecutive elements E Is equal ṪḤ_Ṫ [then] Ṫ The last element Ḥ Doubled _ Minus Ṫ The last element (second-last of original list) µṪ²:Ṫµ [else] Ṫ The last element ² Squared : Divided by Ṫ The last element (second-last of original list) ``` [Answer] # Pyth, 18 Bytes ``` ?-+vzJEyQ/^E2J-yEJ ``` Accepts input as a newline-separated list of values. [Try it online!](http://pyth.herokuapp.com/?code=%3F-%2BvzJEyQ%2F%5EE2J-yEJ&input=5%0A25%0A125%0A625&debug=0) Explanation: ``` ? If - the following are not equal: +vzJE the sum of first and third values (and call the third value J) yQ and the second value * 2; (i.e. if it is not an additive or subtractive formula) ^E2 Then: square the fourth value / J and divide by the third ? Else: yE double the fourth value - J and subtract the third ``` ]
[Question] [ Given a list of strings, output a single string formed by taking a character from each string at each position, sorting them by ASCII ordinal, and appending them in order to the output string. In other words, for `n` input strings, the first `n` characters of the output will be the first characters of each of the inputs sorted by ordinal, the second `n` characters of the output will be the second characters of each of the inputs sorted by ordinal, and so on. You may assume that the strings are all of equal length, and that there will be at least one string. All strings will be composed of only ASCII printable characters (ordinals 32-127). Reference implementation in Python ([try it online](http://ideone.com/fork/HDvjKH)): ``` def stringshuffle(strings): res = '' for i in range(len(strings[0])): res += ''.join(sorted([s[i] for s in strings],key=ord)) return res ``` Examples: ``` "abc","cba" -> "acbbac" "HELLO","world","!!!!!" -> "!Hw!Eo!Lr!Ll!Od" ``` ### Rules * Standard loopholes are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins # Leaderboard The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 64526; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] # [GS2](https://github.com/nooodl/gs2), 4 bytes ``` *Ü■/ ``` This reads the strings from STDIN, separated by linefeeds. The source code uses the [CP437](https://en.wikipedia.org/wiki/Code_page_437#Characters) encoding. [Try it online!](http://gs2.tryitonline.net/#code=KsOc4pagLw&input=SEVMTE8Kd29ybGQKISEhISE) ### Test run ``` $ xxd -r -ps <<< '2a 9a fe 2f' > zip-sort.gs2 $ echo -e 'HELLO\nworld\n!!!!!' | gs2 zip-sort.gs2 !Hw!Eo!Lr!Ll!Od ``` ### How it works ``` * Split the input into the array of its lines. Ü Zip the resulting array. ■ Map the rest of the program over the resulting array. / Sort. ``` [Answer] ## Haskell, ~~39~~ 36 bytes ``` import Data.List (>>=sort).transpose ``` Usage example: `((>>=sort).transpose) ["HELLO","world","!!!!!"]` -> `"!Hw!Eo!Lr!Ll!Od"`. Transpose the list of strings, map `sort` over it and concatenate the resulting list of strings (`>>=` in list context is `concatMap`). [Answer] # Pyth, 5 bytes Zips(`C`) the input(`Q`), `M`aps `S`ort, then `s`ums. ``` sSMCQ ``` [Try it online](http://pyth.herokuapp.com/?code=sSMCQ&input=%22abc%22%2C%22cba%22&test_suite=1&test_suite_input=%22abc%22%2C%22cba%22%0A%22HELLO%22%2C%22world%22%2C%22%21%21%21%21%21%22&debug=0). [Answer] # JavaScript (ES6), 57 bytes ``` a=>a[0].replace(/./g,(c,i)=>a.map(w=>w[i]).sort().join``) ``` [Answer] # [TeaScript](https://github.com/vihanb/TeaScript), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859) ``` _t¡ßlp¡)µ ``` TeaScript has all the right built-ins implemented in all the wrong ways. [Try it online](http://vihanserver.tk/p/TeaScript/) ## Ungolfed ``` _t()m(#lp())j`` ``` ## Explanation ``` _t() // Transposes input array m(# // Loops through inputs lp() // Sorts characters by char code ) j`` // Joins back into string ``` [Answer] # CJam, 5 bytes ``` q~z:$ ``` Try it [here](http://cjam.aditsu.net/#code=q~z%3A%24&input=%5B%22abc%22%20%22def%22%20%22cba%22%5D). [Answer] # Python, ~~50~~ 48 bytes ``` lambda x,y=''.join:y(map(y,map(sorted,zip(*x)))) ``` *Thanks to @xnor for -2 bytes!* [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `d`, 3 bytes ``` ∩vs ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJkIiwiIiwi4oipdnMiLCIiLCJbXCJIRUxMT1wiLFwid29ybGRcIixcIiEhISEhXCJdIl0=) [Answer] # Octave, 15 bytes ``` @(a)sort(a)(:)' ``` **Example:** ``` octave:1> (@(a)sort(a)(:)')(["abc";"cba"]) ans = acbbac octave:2> (@(a)sort(a)(:)')(["HELLO";"world";"!!!!!"]) ans = !Hw!Eo!Lr!Ll!Od ``` [Answer] # K, 10 bytes ``` ,/{x@<x}'+ ``` Join (`,/`) the sort of (`{x@<x}`) each (`'`) of the transpose (`+`) of a list of strings. In action: ``` ,/{x@<x}'+("HELLO";"world";"!!!!!") "!Hw!Eo!Lr!Ll!Od" ``` Simple, but K is hurt a bit here by not having a single-character sort function and instead dividing the operation into a scatter-gather index operator `@` and a primitive which yields the permutation vector which would sort a list `<`. [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 bytes ``` LMFop ``` So close to LMNOP :( [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#c=LMFop&i=abc%0Acba%0A%0AHELLO%0Aworld%0A%21%21%21%21%21&a=1&m=1) Put all inputs into one list of strings (`L`), and transpose this list (`M`). For each resulting string (`F`), sort (`o`) and print (`p`) it. [Answer] # [Pip](https://github.com/dloscutoff/pip), 5 bytes ``` SS*Zg ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZLg4O1otIhbKjQ7mglD1cfH38lHQWl8vyinBQQQxEElGKhSgA) [Answer] # Julia, 46 bytes ``` x->(j=join)(map(i->j(sort([i...])),zip(x...))) ``` This creates an unnamed function that accepts an array of strings and returns a string. To call it, give it a name, e.g. `f=x->...`. Ungolfed: ``` function zipsort{T<:AbstractString}(x::Array{T,1}) # Splat the input array and zip into an iterable z = zip(x...) # For each tuple consisting of corresponding characters # in the input array's elements, splat into an array, # sort the array, and join it into a string m = map(i -> join(sort([i...])), z) # Take the resulting string array and join it return join(m) end ``` [Answer] # C++14, 152 bytes ``` #include<iostream> #include<regex> [](auto s){for(int i=0;i<s[0].size();++i){auto r=""s;for(auto k:s)r+=k[i];std::sort(begin(r),end(r));std::cout<<r;}}; ``` Not using any advantage of map+zip (guess why) Ungolfed + usage ``` #include <iostream> #include <string> #include <algorithm> #include <vector> int main() { auto lambda = [](auto s) { for (int i = 0; i < s[0].size(); ++i) { auto r = ""s; for (auto k : s) r += k[i]; std::sort(begin(r), end(r)); std::cout << r; } }; std::vector<std::string> data = { "HELLO", "world", "!!!!!" }; lambda(data); } ``` [Answer] # Mathematica, 51 bytes ``` ""<>SortBy@ToCharacterCode/@Transpose@Characters@#& ``` String manipulation in Mathematica is expensive... [Answer] # [Japt](https://github.com/ETHproductions/Japt), 12 bytes ~~20~~ ``` Ny m_q n q)q ``` [Try it online!](https://codegolf.stackexchange.com/a/62685/42545) ## Explanation ``` Ny // Transpose inputs m_ // Maps through each new string q // Split string n // Sort string q // Join )q // Join again ``` [Answer] ## [Perl 6](http://perl6.org), 33 bytes ``` {[~] flat ([Z] @_».comb)».sort} ``` Example usage: ``` say {[~] flat ([Z] @_».comb)».sort}(< abc cba >) # acbbca my &code = my $code = {[~] flat ([Z] @_».comb)».sort} say code "HELLO","world","!!!!!"; # !Hw!Eo!Lr!Ll!Od say ((<cba abc>),(<testing gnitset gttseni>)).map($code); # (acbbac ggtentiststteisenngit) ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟, 15 chars / 30 bytes ``` Ѩťªï)ć⇀ѨŌ$ø⬯)ø⬯ ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=%5B%22HELLO%22%2C%22world%22%2C%22!!!!!%22%5D&code=%D1%A8%C5%A5%C2%AA%C3%AF%29%C4%87%E2%87%80%D1%A8%C5%8C%24%C3%B8%E2%AC%AF%29%C3%B8%E2%AC%AF)` Just realized that Lodash's sortBy function works on strings, too. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ZṢ€ ``` [Try it online!](https://tio.run/##y0rNyan8/z/q4c5Fj5rW/H@4c8bDnbMfNcxR0LVTeNQw98Q6IPfQ1sPtD3e2cB1uByqBSP//H62UmJSspKOUnJSoFKsTreTh6uPjD@SX5xflpABpRRAAy6CK6EBVxgIA "Jelly – Try It Online") Only valid if considered as a [full program](https://tio.run/##y0rNyan8/z/q4c5Fj5rW/P//XykxKVlJRyk5KVEJAA): the resulting value is a list of strings, but when it's printed Jelly [implicitly flattens it](https://tio.run/##y0rNyan8DwJKaUo60Uo5QAIIlBKVYmNjdZRKlEBEKojMA0mnpijFAgA). ``` € Map Ṣ sort Z over the columns of the input. ``` [Answer] # [PHP](https://php.net/), ~~92~~ 91 bytes ``` for($argv[0]='';$a=array_column(array_map(str_split,$argv),$i++|0);print join($a))sort($a); ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNFQSi9LLog1ibdXVrVUSbROLihIr45Pzc0pz8zQgnNzEAo3ikqL44oKczBIdsHpNHZVMbe0aA03rgqLMvBKFrPzMPKBJmprF@UUlIIb1////PVx9fPz/l@cX5aT8VwQBAA "PHP – Try It Online") I'm confident this could be done shorter by not trying to use PHP's built-in array functions, but had to try! ### Or 85 bytes @Night2's swing, done shorter by not trying to use PHP's built-in array functions: ``` for(;''<$argv[1][$i++];print join($a))for($a=[];''<$a[]=$argv[++$$i][$i-1];sort($a)); ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKzV1W1UEovSy6INY6NVMrW1Y60LijLzShSy8jPzNFQSNTVBqlQSbaNjIUqjY20h6rW1VVQyQXp0DWOti/OLSsCqrf///@/h6uPj/788vygn5b8iCAAA "PHP – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Õmñ ``` [Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=1W3x&input=WyJIRUxMTyIsIndvcmxkIiwiISEhISEiXQ) [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~56~~ 50 bytes ``` -join(($a=$args)[0]|% t*y|%{$a|% c*rs($i++)|sort}) ``` *-6 bytes thanks to mazzy* [Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SpmCrUP1fNys/M09DQyXRViWxKL1YM9ogtkZVoUSrska1WiURyEzWKirWUMnU1tasKc4vKqnV/F/LxaUG1K3k4erj46@koFSeX5STAqQVQUAJIpeYlAwUSU5KVPoPAA "PowerShell Core – Try It Online") [Answer] # [Factor](https://factorcode.org), 34 bytes ``` [ flip [ natural-sort ] map-flat ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=JY0xDsIwFEN3TmHYy4xgRoBUwYCYKobf8AsRaZKmiTpUPQlLFzgAt-ltSKkX-_tZ-q9PQcIb1w98OR-OuzVqrgJrwTVq47zUdwhTWqnYLYOXSnoZ0ZOdZgVpUDXYzGZt9BaUC4ic0P2v_TZNT2iMUzfMR8W-ewdfJKthkaFQ0iKDJh8cqWR8hitKskmhKMZp-Y1FXFkn9YiZxGMCfT_5Dw) [Answer] # [rSNBATWPL](https://github.com/Radvylf/rSNBATWPL), 39 bytes ``` x~strfor{flip$x}{y~y sort>}crush-with"" ``` [Try It Online!](https://dso.surge.sh/#@WyJyYWlzaW4tYmF0d2FmZmxlIixudWxsLCJmPXh+c3RyZm9ye2ZsaXAkeH17eX55IHNvcnQ+fWNydXNoLXdpdGhcIlwiOyIsImYgJCAoXCJIRUxMT1wiLFwid29ybGRcIixcIiEhISEhXCIpIiwiIiwiIl0=) [Answer] ## [Minkolang 0.13](https://github.com/elendiastarman/Minkolang), 46 bytes ``` $od0Z2:$zIz:$xd0G2-[i1+z[di0c*+c$r]xz$(sr$Ok]. ``` [Try it here.](http://play.starmaninnovations.com/minkolang/old?code=%24od0Z2%3A%24zIz%3A%24xd0G2-%5Bi1%2Bz%5Bdi0c%2A%2Bc%24r%5Dxz%24%28sr%24Ok%5D%2E&input=%22HELLO%22%22world%22%22%21%21%21%21%21%22) Expects input like `"HELLO""world""!!!!!"` (so no commas). ### Explanation ``` $o Read in whole input as characters d Duplicate top of stack (the ") 0Z Count how often this appears in the stack 2: Divide by two $z Store this in the register (z) Iz: Length of stack divided by z (k) $x Dump one element from the front/bottom of stack d Duplicate top of stack (which is k) 0G Insert it at the front/bottom of stack 2- k-2 [ Open for loop that repeats k-2 times i1+ Loop counter + 1 (i) z[ Open for loop that repeats z times d Duplicate top of stack (which is i) i Loop counter (j) 0c Copy k from front of stack * Multiply (j*k) + Add (j*k + i) c Copy character at position j*k+i to the top $r Swap top two elements of stack (so i is on top) ] Close for loop x Dump the top of stack (dump i) z$( Start a new loop with the top z elements s Sort r$O Reverse and output the whole (loop) stack as characters k Break - exits while loop ]. Close for loop and stop ``` [Answer] # GolfScript, 8 bytes ``` ~zip{$}% ``` Try it online on [Web GolfScript](http://golfscript.apphb.com/?c=OyAnWyJIRUxMTyIgIndvcmxkIiAiISEhISEiXScgIyBTaW11bGF0ZSBpbnB1dCBmcm9tIFNURElOLgoKfnppcHskfSU%3D). ### How it works ``` ~ # Evaluate the input. zip # Zip it. {$}% # Map sort ($) over the resulting array. ``` [Answer] # Clojure/ClojureScript, 43 bytes ``` #(apply str(mapcat sort(apply map list %))) ``` Creates an anonymous function. Written in a ClojueScript REPL, should also be valid Clojure. Enter it [here](http://clojurescript.net/), then call via `(*1 ["HELLO" "world" "!!!!!"])`. Or do `(def f *1)` and then use `(f ["abc" "cba"])`. [Answer] ## Ceylon, 166 `String z(String+l)=>String(expand(t(l).map(sort)));[T+]n<T>(T?+i)=>[for(e in i)e else nothing];{[X+]*}t<X>([{X*}+]l)=>l[0].empty then{}else{n(*l*.first),*t(l*.rest)};` While Ceylon has a [`zip` function](http://modules.ceylon-lang.org/repo/1/ceylon/language/1.2.0/module-doc/api/index.html#zip), it takes only two iterables instead of an iterable of them. [`unzip`](http://modules.ceylon-lang.org/repo/1/ceylon/language/1.2.0/module-doc/api/index.html#unzip), on the other hand, takes an iterable of tuples, and I don't want to convert my strings into tuples. So I implemented my own transpose function, inspired by a Haskell implementation which Google [found for me somewhere](https://hackage.haskell.org/package/Stream-0.4.7.2/docs/src/Data-Stream.html#transpose). ``` // zip-sort // // Question: http://codegolf.stackexchange.com/q/64526/2338 // My answer: ... // Takes a list of strings (same length), and produces // a string made by concatenating the results of sorting // the characters at each position. String z(String+ l) => String(expand(t(l).map(sort))); // Narrow an iterable of potential optionals to their non-optional values, // throwing an AssertionError if a null is in there. [T+] n<T>(T?+ i) => [for (e in i) e else nothing]; // Transpose a nonempty sequence of iterables, producing an iterable of // sequences. // If the iterables don't have the same size, either too long ones are // cut off or too short ones cause an AssertionError while iterating. {[X+]*} t<X>([{X*}+] l) => l[0].empty then {} else { n(*l*.first), *t(l*.rest) }; ``` The types of `n` and `t` could be defined much more general, but this is Codegolf ;-) (`n` is a special case of what [I proposed as `assertNarrow` two weeks ago](https://github.com/ceylon/ceylon-compiler/issues/2422#issuecomment-154812667)). [Answer] # [Red](http://www.red-lang.org), 85 bytes ``` func[b][repeat c length? b/1[foreach a sort collect[foreach m b[keep m/:c]][prin a]]] ``` [Try it online!](https://tio.run/##PYkxDsIwDEV3TmFygYq1CxMSQyUkVsuD4zgUkSaVCeL4Ie3AX97Xe6ah3TUgxbHFTxb0hKarcgWBpPlR5zP44YSxmLLMwPAu1mNJSaX@9QIeX6orLMMoRLjaMwMTUdtehQjo2IsDJ54dHfa@2@tlmm7df4ul0Hnc5qj9AA "Red – Try It Online") [Answer] ## Brev, ~~53~~ 41 bytes ``` (as-list flatten(over(sort args char<?))) ``` Example: ``` ((as-list flatten (over (sort args char<?))) "HELLO" "world" "!!!!!") ``` ]
[Question] [ One lane is closed, the vehicles have to thread their way in according to the zip-lock system: One car from one lane, the next car from the other lane, always taking turns. **Input**: Two vehicle queues, represented e.g. as strings, in which short cars are represented by individual symbols, lorries by several identical symbols. The queues may be of different lengths and may even be empty. Symbols may appear more than once. If your language does not support strings, you can also use two lists (see second set of test data) or other forms of input as long as the purpose of the task is not lost. **Output**: A vehicle queue in the same representation. The traffic jam is long enough, so at least the source code should be as short as possible! **Test data:** ``` Nzzll,iaaee --> Nizzaallee aabcddddeeeee,1112345555611 --> aa111b2c3dddd4eeeee5555611 foo+bar ooooooooooooooooooooo --> fooooooooooooooooooooooo+bar feeeuve553iiiiiiiiiii, --> feeeuve553iiiiiiiiiii UvtMCaegIYuiet,poeyhllnefoLkI --> UpvoteMyChallengeIfYouLikeIt ``` **Test data for languages that do not support strings:** ``` [1,3,5,7,9,11],[2,4,6,7,7,7,7,7] --> [1,2,3,4,5,6,7,7,7,7,7,7,9,11] [4,9,9,13,13],[41,41,41,1,11,44] --> [4,41,41,41,9,9,1,13,13,11,44] [] [2,6,4,3,3,56,8,5,4,3] --> [2,6,4,3,3,56,8,5,4,3] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ŒgZ ``` A full program that accepts a pair of the two strings as the first argument and prints the resulting single lane. **[Try it online!](https://tio.run/##y0rNyan8///opPSo////RyuFlpX4OiempntGlmamlijpKBXkp1Zm5OTkpabl@2R7KsUCAA "Jelly – Try It Online")** ### How? ``` ŒgZ - Main Link: pair of lists of characters Œg - group runs of equal elements of each Z - transpose - implicit, smashing print ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 33 bytes ``` f=->a,b{a[/(.)\1*/]?$&+f[b,$']:b} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y5RJ6k6MVpfQ08zxlBLP9ZeRU07LTpJR0U91iqp9n@BQlq0kl9VVU6Oko5SZmJiaqpS7H8A "Ruby – Try It Online") ### How it works: If the first queue is not empty, extract the first vehicle, then exchange the queues, and repeat. If the first queue is empty, return the whole second queue. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes ``` Flatten[Split/@#,{2,1,3}]& ``` [Try it online!](https://tio.run/##bY3LCoJAFIbX9hQxgpsmYjLbFYIQBBWBtAhpcbRjDk1O2DEosVe3SYM2fcv/egHK8AIkE2jSWbNQQIR5FF6VpJFv82rMBXfrg9NsC5lTZA/nqR9kUEBCWNx8@@C8wgTyV9Wr2OapFLMsi/eZBEBkNTcqQJwcDfiBfUwhxNideIapEF0o1XoQQ8Hasv7HN2c2yjt6nit/MNPp7N2d1gHgabkvJVJ7dtX4yJTKMdWr85LVvbp5Aw "Wolfram Language (Mathematica) – Try It Online") Input and output lists of characters. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` €γõζS ``` Input as a pair of strings; output as a list of characters. [Try it online](https://tio.run/##yy9OTMpM/f//UdOac5sPbz23Lfj//2iltPx87aTEIiUdpXxsQCkWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/R01rzm0@vPXctuD/LvZeSgoah/drKukc2mb/Pzpaya@qKidHSUcpMzExNVUpVidaKTExKTkFCFJBAChjaGhoZGxiCgRmhoZgFWn5@dpJiUVAuXxsAKIGqLm0LNXU1DgTAYA6wJKhZSW@zomp6Z6RpZmpJUDRgvzUyoycnLzUtHyfbE@l2FgA). **Explanation:** ``` € # Map over both strings in the (implicit) input-pair: γ # Split them into equal adjacent groups of substrings ζ # Zip/transpose this list of lists, õ # using an empty string ("") as filler for unequal length lists S # Convert this list of pairs of strings to a flattened list of characters # (which is output implicitly as result) ``` [Answer] # [Uiua](https://uiua.org), 16 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` ⊐/⊂♭⍉⬚∘⊟□[]∩⊜□∩. ``` [Try it!](https://uiua.org/pad?src=0_3_1__ZiDihpAg4oqQL-KKguKZreKNieKsmuKImOKKn-KWoVtd4oip4oqc4pah4oipLgoKZiBbMSAzIDUgNyA5IDExXSBbMiA0IDYgNyA3IDcgNyA3XQpmIFs0IDkgOSAxMyAxM10gWzQxIDQxIDQxIDEgMTEgNDRdCmYgW10gWzIgNiA0IDMgMyA1NiA4IDUgNCAzXQ==) Takes lists of postive integers as input (because this saves a few bytes over strings). * `∩.` duplicate both inputs [![enter image description here](https://i.stack.imgur.com/CPK3q.png)](https://i.stack.imgur.com/CPK3q.png) * `∩⊜□` split both into contiguous equal elements [![enter image description here](https://i.stack.imgur.com/jVV2r.png)](https://i.stack.imgur.com/jVV2r.png) * `⬚∘⊟□[]` couple lists to matrix, filling with boxed empty list [![enter image description here](https://i.stack.imgur.com/9IyPI.png)](https://i.stack.imgur.com/9IyPI.png) * `⍉` transpose [![enter image description here](https://i.stack.imgur.com/u9UtX.png)](https://i.stack.imgur.com/u9UtX.png) * `♭` deshape [![enter image description here](https://i.stack.imgur.com/x4VYA.png)](https://i.stack.imgur.com/x4VYA.png) * `⊐/⊂` join all [![enter image description here](https://i.stack.imgur.com/vXRiV.png)](https://i.stack.imgur.com/vXRiV.png) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes ``` F²⊞υ⪪⮌S¹W∧⌊υ⊟§υ⁰«ι¿⌕⮌§υ⁰ι≔⮌υυ»W⌈υ⊟ι ``` [Try it online!](https://tio.run/##VY5BC4JAEIXP@Sv2OAsG1dWTBIGQIEmHjlKjDq27su6aEf32bYwKmut73/fm3Fb2bCoVQm2sgI0UhR9a8LEoe0UODjiiHRAy3XtXOku6ASljsZYyiW4tKRSQ6gvkpKnzHXjOCtND6jJ9wWkWrSSfeESLgmkHxOCCagE7Yu7r/@/HghhJh4Ea/avMas/w87ubV9Nnk79@u@dlJpMQjqPLtxU22ckTuqg3eG@V0lib/TULy1G9AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Seems to be a similar idea to @l4m2's answer, but it just took me that long to think of it after writing my Retina answer that he got there first. ``` F²⊞υ⪪⮌S¹ ``` Input the two strings, reversing them and splitting them into characters so that they can be processed more easily. ``` W∧⌊υ⊟§υ⁰« ``` Until one queue is empty, remove the next character from the first queue, ... ``` ι ``` ... print it, and... ``` ¿⌕⮌§υ⁰ι ``` ... if the next character in this queue is from a different vehicle, then... ``` ≔⮌υυ ``` ... switch the queues. ``` »W⌈υ⊟ι ``` Output the remaining vehicles from the other queue. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~52~~ 48 bytes ``` f=([c,...a],b)=>c?[c,...c==a[0]?f(a,b):f(b,a)]:b ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZFBS8MwGIbx6q8oPbVYu3WdIoO6w06FbbcdxijsS_aliwv5hraF9a94KaJ3_47-GhMrqGvfS0jyvs8bvjy_atph8yKSt7IQ13cfQ5F4Gx6EYQhZwPzknk_bLU8S2AyzqfDAnE-ExwLwswlrc58X75z0EykMFeWe8Bx3WddKuYHjSgBE1_HDB5J6u_WdrgYDZynrGkApxMtzEgDjOyO0ssQoikbx-MboNor-kw0JwNyzEY9tZvwd-rF2yILoisGjZVKf_rINWfSaWkaXbXrLylTH8le2qWcUlt1n70BXVbGYAebpupRYWNqR8LRXSqOg-SE9e_DqWFGBi9Nsbyerc0zFmsq5PGBatB_XNO36BQ) Array IO, though inputting string usually work [Answer] # [J](https://www.jsoftware.com), 32 bytes ``` [:;(,/:,&(#\))&(<;.1~2~:/\'_'&,) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lVHNTsJAEI7XPsWgsdPGUtwWiSxyIjFpAh6MHIgYs63TUmlYIlsSeuDiY3jBgw-FT-PSQrhw8Us2m5nvZ2eyX9_vm-1lu8bZS6vG24jGuYsJdDkgOHANXJ-6C73H_v1PruL67RaeecdyGtwxrYuxbZvWXcdla2_NG2N8RdOxK93v2adtqK4LdW4YFE0kYCzlVSg-EBJAeQq4Fz7RQkEkFrQ4dB7SohAiy4gQlC6LIsvKnFQI3durhGCMhV7kv2k0aYcbjRZjpUuIMNoxJVG6tdzzmwfNccyTqGZX_9gj1u_kSz2Dnx5RRZxmdCACwN4-nC-losGqN9ltPksoiEcy76dTClSZMlyqQU9QEozylFRpn0taTbJsRrHsTwOs_mKzqe4_) The 2nd part of this is the only interesting insight: * `[:;...&(<;.1~2~:/\'_'&,)` This is the preprocessing step that breaks the lists down into the grouped sections. A standard J idiom which is unfortunately a bit verbose. I could save two bytes by using integers instead of strings as input. * `,/:,&(#\)` The main logic. Since we can't zip uneven lists in J using `,.`, we just cat the lists `,` and then sort them `/:` by `1..n` catted with `1..m` (where `n` and `m` are the two list lengths). This works because sort is stable. [Answer] # [C (clang)](http://clang.llvm.org/), ~~61~~ 60 bytes ``` f(a,b)char*a,*b;{*a?putchar(*a)-*++a?f(b,a):f(a,b):puts(b);} ``` [Try it online!](https://tio.run/##bZCxbsIwEIZ3nqLyZCdhMKEdyMDAFAnYGJBYzu45sXDtiDqRCOLZUxsqJUP@8e77v5NOLqUBWw2DopAJJmu4JZAlongksG1aHwc0AbZM0hS2iooM2ObNbsL6lwpWPIcf0Jayx0JRcux7Y0hGNAAi@WDFiyIXe9R9D2AM4sUSViwiDCDkdwjGhBLnfJWvP0O@OCdjFyBsxErmEV6/6H9odCnnUgG3YHFzmdiUm0@sT3zhSNuFO7keE@xT0RwyGk6dP@wAq/LcavSh2ji818ZYVG5/LSeiU9M5j4f7ro4PshWW6uzavb5i6d@@5/AH "C (clang) – Try It Online") * saved 1 Byte thanks to @l4m2 [Answer] # [Perl 5](https://www.perl.org/) + `-p0`, 29 bytes ``` 1while s/^(.)\1*/!print$&/gem ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiMXdoaWxlIHMvXiguKVxcMSovIXByaW50JCYvZ2VtIiwiYXJncyI6Ii1wMCIsImlucHV0IjoiVXZ0TUNhZWdJWXVpZXRcbnBvZXlobGxuZWZvTGtJIn0=) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 22 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 2.75 bytes ``` vĠ∩ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJBcz0iLCIiLCJ2xKDiiKkiLCJcXFxuSiIsIltcIk56emxsXCIsIFwiaWFhZWVpZW5zb2ViZW9vb29cIl1cbltcImFhYmNkZGRkZWVlZWVcIiwgXCIxMTEyMzQ1NTU1NjExXCJdXG5bXCJmb28rYmFyXCIsIFwib29vb29vb29vb29vb29vb29vb29vXCJdXG5bXCJmZWVldXZlNTUzaWlpaWlpaWlpaWlcIiwgXCJcIl1cbltcIlV2dE1DYWVnSVl1aWV0XCIsIFwicG9leWhsbG5lZm9Ma0lcIl0iXQ==) Bitstring: ``` 1000110100011111100101 ``` The footer inserts a newline for test case purposes. Port of the jelly answer. ## Explained ``` vĠ∩­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌­ vĠ # ‎⁡Vectorise group-by ∩ # ‎⁢Transpose 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # JavaScript (ES11), 62 bytes Expects `([str1, str2])`. ``` a=>[...a+a].map((_,i)=>a[i&1].match(/(.)\1*/g)?.[i>>1]).join`` ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZG_TsMwEIfFylNEGZBDiyM3BbEkDJ0itd06VCGi1_ScmJo4giRS8yIMLBGiDwVPg034I5R8iyXfz9-d7Ze3XO2wfeX-sSr5xfV7AH4QUUphBDF9gIKQu7Fw_AAiccbMTplkxCXUuWXnburc0EgEAYsdeq9Evtl0lo-T50TlT0oilSolnESWvWwaKe2xZQsARNuKHcfq47rWUjQNgJSIpz0JwDbZadBgZIyxiTe91Fwx9iPVEgBd2U4Sz6SnX_HvUF_KlRpt4dHo1BCdVkv5YLk7PaDVPatat_XEH6bJv7sb7VCw71vV5WIGmIbrSmBpRIXCQyZljlzN9-HvmKuiViUuDrPMvGKeYsjXqpqLPYZl9z9t262f) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 26 bytes ``` O$#`.(?<=(\2*(.))+) $#1 ¶ ``` [Try it online!](https://tio.run/##K0otycxL/K@qEZyg899fRTlBT8PexlYjxkhLQ09TU1uTS0XZkOvQNq7///2qqnJydDITE1NTuRITk5JTgCAVBHQMDQ2NjE1MgcDM0JArLT9fOymxSCcfG@BKA2ooLUs1NTXORAAdrtCyEl/nxNR0z8jSzNQSnYL81MqMnJy81LR8n2xPAA "Retina 0.8.2 – Try It Online") Takes input on separate lines but link is to test suite that splits on commas for convenience. Explanation: ``` O$#`.(?<=(\2*(.))+) $#1 ``` Sort each character by its vehicle index in its queue. This is a stable sort so that the first vehicle of the first queue sorts first followed by the first vehicle of the second queue etc. The newline is not considered for the sort but it's used by the lookbehind to find the front of the second queue. ``` ¶ ``` The vehicles were sorted without regard for the placement of the newline which is just unnecessary at this point. [Answer] # [Noulith](https://github.com/betaveros/noulith), 97 bytes ``` f:=\a,b->if (a.len<1)b else (c,d:=a.first,a.tail;c$if (d.len>0 and c==d.first)f(d,b)else f(b,d)) ``` [Try it online!](https://betaveros.github.io/noulith/#Zjo9XGEsYi0+aWYgKGEubGVuPDEpYiBlbHNlIChjLGQ6PWEuZmlyc3QsYS50YWlsO2MkaWYgKGQubGVuPjAgYW5kIGM9PWQuZmlyc3QpZihkLGIpZWxzZSBmKGIsZCkpCgo7CgpmKCJVdnRNQ2FlZ0lZdWlldCIsInBvZXlobGxuZWZvTGtJIik=) ### Explanation ``` f:=\a,b -> # recursive function if (a.len<1) b # return early when first input is empty else ( # otherwise c,d:=a.first,a.tail; # get first c(h)ar and the rest c $ # concat the first c(h)ar with if (d.len>0 and c==d.first) # if next is a truck f(d,b) # the rest of the truck else f(b,d)) # otherwise the next lane ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 12 bytes ``` ∾∾○(+`»⊸≠)⊔∾ ``` [Try it online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oi+4oi+4peLKCtgwrviirjiiaAp4oqU4oi+Cgoi8J2VqCLigL8i8J2VqSLigL8i8J2VqEbwnZWpIuKIvuKIvuKfnDzin5woRsK0KcuYWwoiTnp6bGwi4oC/ImlhYWVlIiwKImFhYmNkZGRkZWVlZWUi4oC/IjExMTIzNDU1NTU2MTEiLAoiZm9vK2JhciLigL8ib29vb29vb29vb29vb29vb29vb29vIgoiZmVlZXV2ZTU1M2lpaWlpaWlpaWlpIuKAvyIiCiJVdnRNQ2FlZ0lZdWlldCLigL8icG9leWhsbG5lZm9Ma0kiCl0=) Input `𝕨F𝕩`. Assumes the leading character isn't a null character. ``` traffic jaaam ∾ join trafficjaaam ⊔ group by +`»⊸≠ vehicle #s ∾○ (joined) 123445612223 tj raaa am ff i c ∾ join groups tjraaaamffic ``` Flattened group-by (`∾⊔`) is a little shorter than sort-by (`⍋⊸⊏`). [Answer] # x86-64 machine code, 21 bytes ``` AA 3A 06 74 03 48 87 D6 AC 84 C0 75 F3 52 5E 3A 06 A4 75 FB C3 ``` [Try it online!](https://tio.run/##bVPPb9owFD7Hf8VbpqoOuBWBwgHGLj1VWneYNGkT5WAcJ3Fn7MhOWKDiXx97TqDbqr1DpPe@H/n8ZIubQojTifstUPgSU3JbaLvhGnLi5pGvrd@QSGwr4JrBynm1JtGzRDRqRVkADhi4rCX5PNI2C@Ra@rpjc41UcwBHoqrxZaAtoLJVEBGXzt/abu0u6J@NBJeSyMmaJDEkC7KzKoOcipI7GDjpG10zENbgf/qZH73p02QBncpR1JP3ygjdZBI@@NopU9yWH/@ZZcqGEVGmhi1XhibkBU8dvJSpmnq0Gk9na9Y36bnpg3TNgkQ/S6UlUC@4yWl8hVMfnwWjBJZLSBMSoWnvOsjUTmXSwRIwkSgd7ZkMrtk1Jo6ivxij0Adate9pKYMLOkTfAOf0speLUc/swArPXIdU/snEl@ABOZJX7Mk8clEq3L2wmZzHAQ7raEMABntsMwsvFzpcjcbf0Gu/pLQxXhVGZt3yB4lLVu1wuE4WRzgvZQ/v0KS9nwTTVwd6pWCzx9uSdKlaBI@n0@fDQWumOJeScL4RGZYMxdI0HU/uplizNCW5tcMNd8z@r0iOgmYnp9OJ@lOMfN3Vj/dcFg/fGyVrVlm5L7U2Mreffjz8ErnmhT/dbGd3@MEXscSkUv8G "C (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string, and in RSI and RDX, addresses of the inputs, as null-terminated byte strings. The starting point is after the first 8 bytes. In assembly, rearranged for easier reading: ``` f: lodsb # Load a byte from address RSI into AL, advancing the pointer. test al, al # Check the value of that byte. jnz r # Jump if it's nonzero. ``` ``` (This section actually comes first.) r: stosb # Write that byte to the output string, advancing the pointer. cmp al, [rsi] # Compare that byte to the next byte in the string. je f # Jump if they are equal. xchg rsi, rdx # (Otherwise) Swap the pointers (in RSI and RDX). (From here, continue at the beginning.) ``` ``` (When the byte is zero, continue to here.) push rdx; pop rsi # Transfer the other pointer from RDX to RSI. r1: cmp al, [rsi] # Compare the value at that address to AL, which is 0. movsb # Write the byte from address RSI to the output string, # advancing both pointers. jne r1 # Jump back if the byte was not equal to 0. ret # Return. ``` [Answer] # [Go](https://go.dev), 133 bytes ``` func f(a,b string)string{if len(a)<1{return b} c,a:=a[0],a[1:] if len(a)>0&&c==a[0]{return string(c)+f(a,b)} return string(c)+f(b,a)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fVJfa9swEIc96lNcBSkW1ULdtGOEuTC6PQTaMLb0oWRhnD3JFXEsx5HDEuPHfYq9hMG-RL9J92l2stONQbZ70En3-8PppG_fU7t7KDCZY6pggSZnZlHY0vW5XjjOflROP3_5-FVXeQI6QBnDypUmT0WXaqMhU3mA4lVYl8pVZQ5xwxKJwwinpzOJ03A4Y79Zl6fHx0nUQk_0zihIxEnrLxp2AIgliqZr5uezodsUCiaeUCUOalJJ9aXYCxrG2m79ZQIBNXNq5VYwjGA6m9Ss5uPtNsu45AZRKcpjs90iZhkdGkk4Ypx8plA-CA_D8GxwfkHxIgzpjEiV-CwZeNJ5y3oCW7229iTGkpj2UFBdHwT2ss6DTKs1-Q7MnyClFx-EWtU_0f-qbtfu5gpVOrqrjHLELaza3GdZrrS9no-ocFusrVM3m6t7P6Y8VSN9Z6trM1cj5z1o5O9o9C7LAx5FEXyYvH4_AdpxwbQt4ZN0fv4lkhS656gZJm1RB66P0vVj4X-J6_uHPIrAozW0rjrgvaXsLSG6BFqD3lJ8zLkEr6Mllp4sO6mAhrr5qxl4O34D-2b2X2i36_Iv) Recursive function. ### Explanation ``` func f(a,b string)string{ if len(a)<1{return b} // return early when first input is empty c,a:=a[0],a[1:] // get the current c(h)ar if len(a)>0&&c==a[0]{ // if the next c(h)ar is the same... return string(c)+f(a,b)} // recurse to get the truck return string(c)+f(b,a)} // otherwise move on to the next lane ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 103 99 bytes The function. Input is parameters 1 and 2. Output is variable o. ``` f(){ o= while [ "$1$2" ] do c=`expr "$1" : "${1::1}*"` o+=${1::$c} set -- "$2" "${1:$c}" done } ``` [Try it online!](https://tio.run/##nZdfb@I4EMDf8ymmgTaBFhB07x6g9I/29iSkble6vXuooBTHcUrUELOJA9dS@tV74wkFgjAPN2oh8fg3Mx7bmsFj6fijdNTwwrjh4bNllUrw91hAkMVchTKuA/TiaaYgTGHKEjYRSiQpNIHFPrRQ@yNTK/WMJSHzIgGy/hG4lYUluwDWfBziUB/scrPcsuHB8iWO8u5I/DtN9KgNbfxaNNvt5rJqjyx52qW3Ml9aqVBQq6EaSZqDgzZaiIW1/LAChqb9bsCiVFgqeXErsLAAJcjtaozep0kYKxw8rrWaKXx@nrdSsDcz8UPm08MAlEgVDUAXv87zcTUWMT1oEXws4f7bTxoQOoKC5u7H@n0VpkPjPyVmcBzGT/AnDTt5wKG1pNSnCvPKEj8PwGeK6YWRmbvX1yiCkDEhYJ/cha@vjEWREGuEMY/7KEILNJvN1vmX31B@bzZXehzzWvxcT/pCs1bqtYlAylOPJSD3Sa7fKxraGEHD2Qxtn4cbAcdZZ2iffk3/M1PfvzLx1LvPQjwPUylexlEUi0DePve0fjqTSnx/@TrWq4@fRC@4l9lt@Cx6ipIqceOSTUahBnOm@BhUkvHnFLhkkUj5dtqY53mc862nbWEkHgknITcaR0@QjgVuVDoVPGQR8DHeGk6XRl@Zqb5XGdNXC1wPL06KO@OJSM4ra/82czw8jtzx7b07bTPuOJ5vrwGHHXkOOPzId/YCDuNHRx6etQ1gE2CbAdsuAiUCSmagVCoCZQLKZqBcLgLHBBybgePjInBCwIkZODnZAVbEfoSAXcQlwjX7cN0iUCGgYgYqlSJQJaBqBqrVInBKwKkZOD0tAjUCamagVisCDQIaZqDRKAJtAtpmoN3eAVZE27QT7fYu0iGiY/bR6ewAK6Jj8tHp7CIXRFyYfVxcFIEuAV0z0O0WgUsCLs3A5WURuCLgygxcXRWBawKuzcD1dRF4IODBDDw8FIFHAh7NwONjERgRMDIDo1ERWBCwMAOLRRF4eyPi7c20128oO0hOmH3sAksClmZguSwC7wS8m4H3dw1g6egF0AM/9GNHYW2KFdYRbKiUhLlMns9Qx2UW@ZCymQA1l9tFxXuBREzkDFsKKkJYgH5lWA9TwAqj36gBq2@FBRQWmMMC0GFZn71gIoDpf4iziYeFVAbU0mSJSM/Qd4TFDNsZDFZ7o66Oy8kEix11jCkq6ytLL4AVGpE0i7BjjPEvCONQCYiknKKxVDdH4QRjn4dqDCJJJK4QK@n800jP0RlIQuFrh77k2URQusQEdKR1CvoGp2CEOiztHvvPCoWMLliah5gILp/i8BV9hRQLVW60rNO4ypXjehUHGAeDOC72V5WtHcf59QNAPr@@DSBxwAXqNYEudlbl/q/lVDz34HIq6Mzdig7nH1wOzd9eDpY294AL1GvCzZfDYHBgFc6g6ugtnlCnxiDCY5JgO1XdLIcN6CAPzAd5MKCDTM76h1OGo3nKWKL0CWfYmKktX33y1Tf76vc3voYHfOFSBPP1Jg61eiJYrF9YjL8OEuGfaQu@SKf6WuiIArzn@MAUbWwKN7d/fbv5434N1LeCHFKQQ3OQw2F@s8v5bxLr4z8 "Bash – Try It Online") Uses `expr` to determine the repeats of the first character, "outputs" the repeats, swaps the strings, and repeats until empty. Due to limitations in `expr`, it can't handle characters `[`, `\`, or `^`, or trailing single parentheses. All of these cause infinite loops, possibly with errors spewing. See the TIO for details. I could save two characters by removing the quotes on the while statement, but this would make space not be a valid character. [Answer] # [Python](https://www.python.org), ~~160~~ 159 bytes ``` from itertools import* c,g,l=chain.from_iterable,groupby,list;f=lambda a,b:''.join(c(c(zip_longest([l(t)for r,t in g(a)],[l(t)for r,t in g(b)],fillvalue='')))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fVLNasJAEKbXPMXiJUm7FaK2FEtOngLqzYOIyCTuJlvXbNhsAsmr9FChtO_UPk1no1JKbb8cwnx_hJk8vxeNyVR-OLxVht8-fLxwrfZEGKaNUrIkYl8oba6dhKZUhkkGIu9by8ZaIJaMplpVRdxQKUrzyEMJ-3gLBGg8dt3-kxK5l-DTimIjVZ6y0ngr6RmfK000NUTkJPXAX9PfbIwsF1LWICsWuq6POH7m59WrY7CqJCFZOV5v3rZS9mhPADCG77loWwApcfAp6gBxskUwC9SDIBgMR3eI-yDAGQCZeJAMrWnUuc5il-dK3cSg0akuAXl-UTjFjh1YWtXYOxTfwKQNX5S61J_qv6lFbWYTYGm0rAQz6C0UazIpc8bVdBchsShqZdismWR2TXiXiC9VNRU7FhnbsXYcews8I9X2Gt22xw4hmhlcOvdQ8XEstMiNhyTVP8Yw1KdbnX-tLw) Edit 1: removed an extra space [Answer] # [Desmos](https://desmos.com/calculator), 96 bytes ``` C=sgn(L[2...]-L)^2 g(L)=∑_{n=1}^{[1...C.count]}C[n] f(A,B)=sort(join(A,B),join(0,g(A),0,g(B))) ``` Ok this can probably be improved somehow but for now this is good enough. [Try It On Desmos!](https://www.desmos.com/calculator/lemrskrmt0) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/clgda23xkr) [Answer] # GNU [sed](https://www.gnu.org/software/sed/) `-E`, ~~ 63 ~~ 59 bytes The first approach did build a third string behind the two strings to be merged, but it turned out it's cheaper to invest in introducing a mark `_` in the first string marking the position where to insert the chars from the second string: ``` s/^/_/ :1 s/_((.?)\2*)(.*,)((.?)\5*)/\1\4_\3/ /_,/!b1 s///g ``` The magic mainly takes place in the third line: The ERE `(.?)\2*` (and the same with `5`) match zero or more occurences of the same character (using a backreference, which is not required for ERE by POSIX, but supported by the GNU implementation. Thus, we move those matches in front of the `_`. We can't use `t` for looping, because an empty `s`ubstitution is always possible, but that's not too expensive, because the addess pattern `_,` can be reused for removing. [Try it online!](https://tio.run/##bcu9DoIwGIXhvXfhRrHwpfw4uDgYBxJ1czBpbIp8YGNDiQUSuXgrxsHFZ3uTcxxWUdMO3ju4gASy5sSBDIJ4Q0US0iAOGf1WHlIQXGRSpEBAMliUny1A4/1xmoxhWilEolR5rWb4wTjnSZrlsxXnpLZ2WaoHs/@Qej4MI@Z5qn8YYVlCTmN/2CpsivOgsWedxefNmBZru78XL9v12rbOR7s3 "sed – Try It Online") ]
[Question] [ A [Latin square](https://en.wikipedia.org/wiki/Latin_square) of order n is text which is arranged as a square of n lines by n columns, contains n different characters, and each character appears once in each line and column. For example, here is a Latin square of order 9: ``` Code gOlf ode gOlfC de gOlfCo e gOlfCod gOlfCode gOlfCode OlfCode g lfCode gO fCode gOl ``` Make a program which outputs a Latin square of order n (like in [this](https://codegolf.stackexchange.com/q/223590/25315) other challenge), but the program must also be a Latin square of order n. The output must be different (i.e. not a quine) - use different symbols and/or in different order. Some notes on formatting: 1. Output to stdout or return a string which could be printed to stdout directly (i.e. it should contain newline bytes). 2. Leading and trailing spaces are allowed only if the square doesn't otherwise contain spaces. 3. Leading and trailing newlines are allowed. 4. Tab and other control characters are allowed only if your system can print them without disturbing the square shape. 5. Usual Code Golf - your score is the number of bytes in your program, so a score should normally be n²+n-1 or n²+n. 6. Include your program's output in your answer, if you think it looks pretty. --- As noted by tsh, n = 1 is uninteresting, so let's add a restriction n > 1. [Answer] # C89 (using implicit `int`), 811 bytes (\$ n = 28 \$) ``` ps0,f;to(char/*1+){2-u9]y=}[ +,}2=s09f-(put1;*/oy[]){char u[9012]={f};/*c-as)rt(,op+hy th,+p-;])0r}a92{s1([fc*/oy=u ;for(ps0/*t]9y=u,h1-}2[c{a)+ o1ayc{-}[]f+th,r)(u*/=29;ps0 -=1;u[ps0/*2)fa+hrc,9o}(]ty{ }c2)y9rtp;,[so+h-0fu{a(1*/]= 92-ps0+/*h1t;)o}{=yc(ru,a][f s]+9a)1(}r-,[upy;f0=c{oht*/2 );for(/*1p9{]0[s2-}+a,=yhuct ]{(h[,ay+sp-}r)0ucto1*/f=29; f-=1;oy[29/*ps(,t{+0)}]arcuh au[=of,h;+{sc}y9(t2)p0r*/-1] =oy[0])puts/*c;(92r1+-h}f{,a 29cf]a[{,u0rh-stp*/(oy+=1);} /*r{th};-)=u,]920+pfy1a[so(c ,+s/h*{2]a;1=[0py9-trfc)u}o( {t]u+c2)s1yo-,/[r}a9=hp0(;f* 1(*c{/u+a2])o=}f[,9shty;-0rp y0t-/r(f={a9+1uoc][h*p;s},2) *)ha9}fcy,u({+r=o[]p;/0-21ts (/{]2yc-o}+hfpta=u*;s91r)[0, cy)t*=91r[2f0a-]};h/,s{u+(po [au*}+=rh(cy2{f)/o,]0;tp9s-1 0}/s,1hatyoc(;]*fp={u)-2[r+9 rp;()u*,co[=y2h/1as}]+ft09{- hrp}-tou9=)01({c]y;a2[s+,f*/ ``` [Try it online](https://tio.run/##HZFJqiUgDEXnrsQWm5mIKxEHIljWoEqxGUhw7e/7/jAhJ7mcZPEn58@/9Pc/JrAaJu5@@lS8uFfkmoakmhEwYtt4/A2I8Wv8VLYI3PfSjsp2QiTwnUU7WKVN9FCukzSLNMlYmLfO6kGrctaFi0SNm6yBqXEo@cv7jVxpA7/Dkq5oX4NXLa4JGRJhqOl0MogbYmFvyyB4U@mNdQ9Awmu3wy9qSEmsjsxtuziuA@hmQ44dqzseZmNVqLIhYU1l9Mga8TAmadXLkXbBn4zH5imGgmZkNhGN7xA87H5cUT5Dq4tKg8hv3KemW4gqTCMuS9yfuvNCEXANPB02u7iDqNdr72D5BkblG/cZM1bSPjFfwBS5MY28K0o7@FZ4dQxmvsfiZUhXg0qhI/KPUpE86fOpddiaoZmotwBPyNhcYgrAtxpVzNWpxO0wr98/kaQDVr1OkOc1WqNYL0enJwRnxNmUlYKJyWkfVD9WrFEy2bdhBCtu9hROfZrgMnwf52tX2BWKNKYZ5GbJRNL8LYHbWddxQo2OjlpCDlw8JMv0bjmGSrublxuCKKnJ3pIP3xjY8C3E7qQSRq@JsIRoThbtslr6Sn5TN60eJCiO8iGL@lcFU1QS8boq@YTNcG8opE0v86PifAwUIhuPyq1up9BIXTm5rmmdlrGLtHQPmwgTBrNodIfJpjy34I@pUqd5IytLWRCojn7Fatt6ojSGHI9LJkzGC5Wfzw8) This is a function called `to` which prints the following output: ``` ]\[ZYXWVUTSRQPONMLKJIHGFEDCB \[ZYXWVUTSRQPONMLKJIHGFEDCB] [ZYXWVUTSRQPONMLKJIHGFEDCB]\ ZYXWVUTSRQPONMLKJIHGFEDCB]\[ YXWVUTSRQPONMLKJIHGFEDCB]\[Z XWVUTSRQPONMLKJIHGFEDCB]\[ZY WVUTSRQPONMLKJIHGFEDCB]\[ZYX VUTSRQPONMLKJIHGFEDCB]\[ZYXW UTSRQPONMLKJIHGFEDCB]\[ZYXWV TSRQPONMLKJIHGFEDCB]\[ZYXWVU SRQPONMLKJIHGFEDCB]\[ZYXWVUT RQPONMLKJIHGFEDCB]\[ZYXWVUTS QPONMLKJIHGFEDCB]\[ZYXWVUTSR PONMLKJIHGFEDCB]\[ZYXWVUTSRQ ONMLKJIHGFEDCB]\[ZYXWVUTSRQP NMLKJIHGFEDCB]\[ZYXWVUTSRQPO MLKJIHGFEDCB]\[ZYXWVUTSRQPON LKJIHGFEDCB]\[ZYXWVUTSRQPONM KJIHGFEDCB]\[ZYXWVUTSRQPONML JIHGFEDCB]\[ZYXWVUTSRQPONMLK IHGFEDCB]\[ZYXWVUTSRQPONMLKJ HGFEDCB]\[ZYXWVUTSRQPONMLKJI GFEDCB]\[ZYXWVUTSRQPONMLKJIH FEDCB]\[ZYXWVUTSRQPONMLKJIHG EDCB]\[ZYXWVUTSRQPONMLKJIHGF DCB]\[ZYXWVUTSRQPONMLKJIHGFE CB]\[ZYXWVUTSRQPONMLKJIHGFED B]\[ZYXWVUTSRQPONMLKJIHGFEDC ``` I started with code like this: ``` i; to() { char u[100] = {0}; char *s = u; // Fill the string with some printable bytes for (i = 29; i -= 1; u[i] = 94 - i) ; for (i = 29; i -= 1; ) { puts(s += 1); // print the string s[29 - 1] = s[0]; // rotate the string } } ``` I arranged it as a sequence of strings which all have unique characters, padded with spaces in such a way that I could replace spaces with comments later. Then I tweaked the code repeatedly, until all columns also contained unique characters. This was not easy! The result was this: ``` ps0,f;to(char oy[]){char u[9012]={f}; oy=u ;for(ps0 =29;ps0 -=1;u[ps0 ]= 92-ps0+ 2 );for( f=29; f-=1;oy[29 -1] =oy[0])puts (oy+=1);} ``` I had to use multi-character variable names to make all the string fragments have different lengths. I tried to use a minimal subset of characters, but ultimately I failed to satisfy all constraints and added an extra character `y`. So it seems possible to golf this further (if you want to do this — good luck, I'm out!) Then, I made a script which completes any partially filled rectangle to a Latin square, randomizing characters inside the comments and doing backtracking. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 109 bytes Full program that prints to stdout. ``` (↑⍋⌽¨⊂) ⎕D ↑⍋⌽¨⊂) ⎕D( ⍋⌽¨⊂) ⎕D(↑ ⌽¨⊂) ⎕D(↑⍋ ¨⊂) ⎕D(↑⍋⌽ ⊂) ⎕D(↑⍋⌽¨ ) ⎕D(↑⍋⌽¨⊂ ⎕D(↑⍋⌽¨⊂) ⎕D(↑⍋⌽¨⊂) D(↑⍋⌽¨⊂) ⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L/Go7aJj3q7H/XsPbTiUVeTpsKjvqkuXNgENbgwhYDquDCFgOq4MIWA6riwiB1awYUpBFTHhU1QkwuboAKXCzZvgDz4vwAA "APL (Dyalog Unicode) – Try It Online") `⎕D` the digits `0` through `9` `(`…`)` apply the following tacit function:  `⊂` on the entire argument:   `⌽¨` rotate each of the following amounts:    `⍋` the grade (the permutation that would sort the argument, i.e. the indices 1 through 10)  `↑` mix the list of strings into a character matrix The first rotation ends up having unbalanced parentheses and therefore quits with an error, causing no further output on stdout. [Answer] # [Thunno](https://github.com/Thunno/Thunno), 11 bytes (\$ n = 3 \$) ``` drz rzd zdr ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuharU4qquIqqUriqUoogIlAJmAIA) Reads its own source code and reverses it. (I can't see anything in the question which disallows this.) #### Output ``` rdz dzr zrd ``` #### Explanation Only the last line matters: ``` zd # Read source code and push to stack r # Reverse so the output is different # Implicit output ``` [Answer] # [J](http://jsoftware.com/), 239 bytes (n=15) ``` choue=:i.+|~/15 i=:15.|+/~choue =echo|.u:i+/~51 51|i.+/~=:eouhc 15/.|~+:eui=coh +.5|:1=cu/~iheo |ih~/o51+c.:e=u o|ie15~/c.hu+:= ~+15cuoh|e/.=i: huec+/1o~5=|:.i u/~=hci|o1:e5+. /~.:=eu51hoci|+ :o+/~ihe5=u1.c| .cu+i:e=ho15|/~ e:=ouhc.i|5+1~/ ``` [Try it online!](https://tio.run/##HY4xikBBCEN7ryIoFjaCpxmEcRsrO/Hqf2e3CryEJD/fd251uCXhLItCuonSIO@/Ax5Ph9ryIRVQmZfldYvqe0CUaRYtOv3UBSQdEz/NmzcKJu9yqeAhC2@oyRBdPnQbzWFR9HTdCSZPg9txkKVWfYwSXo/fk1NioUjAS@bRKrceRbDC/yX1FjoDdBrzLd0SHV4I87@flKMoy9/3Cw "J – Try It Online") --- ## Explanation ``` choue=:i.+|~/15 ``` * `|~/` is a no-op on 15: it inserts `|~` between the items, but there's only one item. * `+` is complex conjugation, which is also a no-op on 15. * `i.` makes a list of the first 15 nonnegative integers. * That list is assigned to `choue`. ``` i=:15.|+/~choue ``` * `+/~` makes an addition table of the integers in `choue`. * `15.` `|` reduces it modulo 15; the full stop is used as a decimal point. * The result is assigned to `i`. ``` =echo|.u:i+/~51 ``` * `+/~` here ends up being the same as plain addition, adding 51 to each item of `i`. * `u:` converts numbers to characters. * `|.` reverses the result. (Something had to be put here to separate `echo` from `u:`.) * `echo` outputs the table of characters. * `=` doesn't matter because it is applied after the `echo`. ``` 51|i.+/~=:eouhc ``` * This line is a syntax error, ending execution. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes ``` Rṙ`Y5 ṙ`Y5R `Y5Rṙ Y5Rṙ` 5Rṙ`Y ``` [Try it online!](https://tio.run/##y0rNyan8/z/o4c6ZCZGmXBAqiAtEANlcECqBC0JF/v8PAA "Jelly – Try It Online") All lines but the last are ignored. ``` 5R [1 .. 5] ṙ rotated left ` each of [1 .. 5] times. Y Join on newlines. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 55 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) (\$ n = 7 \$) ``` 0oā._»2 oā._»20 ā._»20o ._»20oā _»20oā. »20oā._ 20oā._» ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fIP9Io178od1GXDCGAReMkc8FpY80csEYelwwRjyXEUzz//8A "05AB1E – Try It Online") #### Output ``` 0485761 4857610 8576104 5761048 7610485 6104857 1048576 ``` #### Explanation We can ignore everything but the last line. ``` 20 # Push 20 o # Push 2 ** 20 (1048576) ā # Push [1..7] ._ # Rotate 1048576 that many times » # Join by newlines # Implicit output ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 41 bytes (\$ n = 6 \$) ``` ∪:żvǓk :żvǓk∪ żvǓk∪: vǓk∪:ż Ǔk∪:żv k∪:żvǓ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwi4oiqOsW8dseTa1xuOsW8dseTa+KIqlxuxbx2x5Nr4oiqOlxudseTa+KIqjrFvFxux5Nr4oiqOsW8dlxua+KIqjrFvHbHkyIsIiIsIiJd) #### Output ``` eiouya iouyae ouyaei uyaeio yaeiou aeiouy ``` #### Explanation Only the last line matters, so everything else can be ignored. ``` k∪ # Push "aeiouy" :ż # Duplicate and push [1..6] vǓ # Rotate the string that many places # Implicit output, joined by newlines ``` ]
[Question] [ Consider a word/string of length \$n\$, only including the letters A-Z, a-z. A word/string is a double prime word if and only if n is prime and the sum of the letters, s, is also prime, using their numeric position in the alphabet (`a=1, B=2, c=3`, etc.). Input can be any combination of upper or lower case alphabetic characters, as there is no numeric difference between `a` or `A`. Output is any appropriate logical format related to your language. i.e. True or False, T or F, 1 or 0, etc. Specifying what format your output will appear is highly appreciated, but not required. (Output need not include n, s, but I include them below as demonstration and example) Winning condition is shortest code in bytes able to detect if a string is a double prime, fitting both conditions for n and s to be prime. (I've now included cases from all 4 possible situations of n, s.) ## Examples ``` Input -> Output (n, s) Prime -> True (5, 61) han -> True (3, 23) ASK -> True (3, 31) pOpCoRn -> True (7, 97) DiningTable -> True (11, 97) METER -> True (5, 61) Hello -> False (5, 52) SMILE -> False (5, 58) frown -> False (5, 76) HelpMe -> False (6, 59) John -> False (4, 47) TwEnTy -> False (6, 107) HelloWorld -> False (10, 124) Donald -> False (6, 50) telePHONES -> False (10, 119) A -> False (1, 1) C -> False (1, 3) {1 is not prime} d -> False (1, 4) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ŒuO_64µL,SẒP ``` [Try it online!](https://tio.run/##y0rNyan8///opFL/eDOTQ1t9dIIf7poU8P9w@6OmNZH//0crBRRl5qYq6SgoZSTmgSjHYG8Q5QHUmB@eX5STAuUV@IJV@bqGuAYpxQIA "Jelly – Try It Online") ## How it works ``` ŒuO_64µL,SẒP - Main link, takes string s as argument e.g. s = "Prime" Œu - Convert to upper case "PRIME" O - Convert to ordinals [80, 82, 73, 77, 69] _64 - Subtract 65 (call this L) [16, 18, 9, 13, 5] µ - Start a new link with L as the left argument L - Take the length 5 S - Take the sum 61 , - Pair the two values [5, 61] Ẓ - Take primality of each [1, 1] P - Take product 1 ``` [Answer] # [R](https://www.r-project.org/), ~~68~~ 71 bytes +3 bytes to correct a bug pointed out by Dominic van Essen ``` `?`=sum;s=?b<-utf8ToInt(scan(,""))%%32;l=?b^0;l-1&5>?c(!s%%1:s,!l%%1:l) ``` [Try it online!](https://tio.run/##K/r/P8E@wba4NNe62NY@yUa3tCTNIiTfM69Eozg5MU9DR0lJU1NV1djIOgcoHWdgnaNrqGZqZ5@soVisqmpoVayjmAOiczT/BxRl5qb@BwA "R – Try It Online") Notice that to convert both upper and lower case letters to the integers 1...26, we can take the ASCII codepoint modulo 32. `sum(!x%%1:x)` is a golfy way of counting the number of divisors of `x`, which will be equal to 2 iff `x` is prime. Ungolfed: ``` `?` = sum # shorthand for sum b = utf8ToInt(scan(, "")) %% 32 # take input and convert to ASCII, then take mod 32 s = sum(b) l = sum(b^0) # l = length(b) 5 > sum(c(!s%%1:s,!l%%1:l)) # sum the number of divisors of s and l, and check whether you get <5. & l!=1 # and that l is not 1 ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~27~~ 59 bytes ``` ->a{[a.size,a.upcase.bytes.map{|i|i-64}.sum].all? &:prime?} ``` +33 bytes after correcting the solution, thanks to DrQuarius. [Try it online!](https://tio.run/##ZZBdb4IwFIbv@ysaL@aaIAFFmEvULBuL@2AaJdmF8aLMgzQpbVckxqm/ncHMMnC3z/Oec95W59G@GEawYQLNNEsBd0Y41Dng676BXZughIo/1jNwt0fQ3eKlwXplTk3VvZzXsp6BBx5BD0wwsQlpxGu7bfssAz/05/9OoglwLiv8SHl25v0uQYvg6dW/wDcExVruRBN77nmLCqAm3DI/IOhZJvW4Y2CnrBLufBHum2nb8n7bvEvN1zVrW6XuOuX7pKANU12xCNoCh9lk@uYvLqfsssMQxBohDZ8504Dbqvr6NoqHRWdED0tqZuwLDGrm6oNmYEb7LWRmStXhyI6s4zonM8vTlUk5H@Or25/p8alQOF62mMhAb3ECGlqr4hs "Ruby – Try It Online") or [Verify all test cases](https://tio.run/##ZVFdb4IwFH3vr2h4mCNBIoowTdQsG4v7YBol2YPzocyqTWrp@Ihh6m9nBewE93bPuef23p4TJn6aDXy8IQxMQ7LDsDmEXphgeNvVoGWoYIvYhetosN1Rwf38tcZ1hI5P@EMwq2htDfZsFTwSRtjGQz6tvG0YZdN1PGf2byUYY0qDnH5CNCr5blsFc/f5zbmi71SwDoM9q9O2Vb7CXVxpWELfU8FLsK3KTQ2a4hRv7zAvrauNli2v@QhCuqp0jZZot03xv4ChWiff0lJBjCmejifvzvx6yhA3DDBbARDi74SEGDZ4bn0DrAdZc4gOC6RH5AdrSE/4F4qw7qcxjvQd4ocjOZKmZZ70KNktdUTpCN70i@nRKeNJHEFFWBlvUygm4qivAA7XC6WIVlmWQCQqSxGkLM/5SViJTVJFWAKAcs8nyz91tajwSg4UeUlQpCRBGY1EeSCyLmOo6M7W/91V2C3RxWRlmf0C "Ruby – Try It Online") [Answer] # perl -Mfeature=say -MList::Util=sum -pl, 95 bytes ``` s/[^a-z]//gi;$m=sum map-64+ord,split//,uc;$_=(1 x y===c)!~/^(11+)\1+$|^1$/&&(1x$m)!~/^(11+)\1$/ ``` [Try it online!](https://tio.run/##bY5NC4IwAEDv@xULhigqY1AdlB06CEEJ0QcdKkN01GBzY5tgEf30Ft46dHu8d3maGTHz3uJTVafPC8Y3niNJbS@hrHU6n8bKtInVgjuMk77J0ZWGBA7wQSltoskbVyEhcXQmMXpVBOEgCMmA5G9B2PuN4ZKBe92BxW4FlkwIBY/KiHZkDUsGymJfbD9KO64669Nyza3LsoPjYrz5I7T4Ag "Perl 5 – Try It Online") ## How does it work? ``` s/[^a-z]//gi; # Clean the input, remove anything which isn't an ASCII letter. uc; # Upper case the string split//, # Split it into individual characters -64+ord # Calculate its value: # subtract 64 from its ASCII value map # Do this for each character, return a list $m=sum # Sum the values, and store it in $m y===c # Returns the length of the input string (1 x y===c) # Length of the input string in unary /^(11+)\1+$|^1$/ # Match a string consisting of a composite # number of 1's, or a single 1 !~ # Negates the match, so (1 x y===c)1~/^(11+)\1+$|^1$/ # this is true of the input string (after # cleaning) has prime length (1x$m)!~/^(11+)\1+$/ # Similar for the sum of the values -- # note that the value is at least 2, so # no check for 1. ``` Combining this, and the program will print 1 on lines which match the conditions, and an empty line for lines which do not match. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` gAIlk>O‚pP ``` Input as a list of characters. [Try it online](https://tio.run/##yy9OTMpM/f8/3dEzJ9vO/1HDrIKA//@jlQKUdJSKgDgTiHOBOFUpFgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXwoZX/0x0PrcvJtvN/1DCrIOC/zv9opYCizNxUJR2ljMQ8IOkY7A0kC/wLnPODQHyXzLzMvPSQxKQckBpf1xDXICDtkZqTkw@kg309fVyBdFpRfnkeRLzAF6TQKz8DxA8pd80LqYRpCM8vykkBmZmflwhmlKTmpAZ4@Pu5BivFAgA). **Explanation:** ``` g # Get the length of the (implicit) input-list A # Push the lowercase alphabet I # Push the input-list of characters l # Convert the input to lowercase k # Get the (0-based) index of each character in the alphabet-string > # Increase each by 1 to make them 1-based indices O # Take the sum of that ‚ # Pair the length together with this sum p # Check for both whether they're a prime (1 if it's a prime; 0 if not) P # And check if both are truthy by taking the product of the pair # (after which the result is output implicitly) ``` [Answer] # [R](https://www.r-project.org/), 70 bytes ``` function(s,S=sum,t=S(utf8ToInt(s)%%32))S(!nchar(s)%%1:t)^S(!t%%1:t)==4 ``` [Try it online!](https://tio.run/##hZBNawIxFEX3/RVWERJwo3VRCllITVHrqJhAd5VUM51AfG/IB@Kvn1q7qFR5XSXcc3IvJDQubnaYP7zd1MHtrWjKDNvkEFjsKRHzvpeEYjmVjxqnkFjk3e7DgHPF7mFbmXAO@k@Jv5@S9HMVYvi3l7VX30ebtzqtFLK9u@KVAYKO1CtB62X9jGvq/diBg09tThFhFVLL9S@/FibWezwLpfHxRoMqpnNJCS8BD3Ah3NyoC0t1zLACiuuDBH38b8TjGwa/o4rGCIY2kvV2NVkupCLnRuQK@V8XsPkC "R – Try It Online") I forced myself not to peek at [Robin Ryder's answer](https://codegolf.stackexchange.com/questions/210733/double-prime-words/210808#210808) before having a shot at this, and (satisfyingly) it turns out that we've used some rather different golfing tricks. `t` is the total of all letter indices. This is certain to be greater-than-or-equal-to `nchar(s)` (it's only equal if the string `s` is "A" or "a"). So we can use modulo `1:t` to test for primality of the string length instead of modulo `1:nchar(s)`, and there's no need waste characters on a variable declaration to store `nchar(s)`. Both primality tests `sum(!t%%1:t)` and `sum(!nchar(s)%%1:t)` must be equal to 2 if both the sum-of-letter-indices and the string length are prime. We could check if they're both 2, but this requires `==2` twice (plus a `&` or equivalent), which seems wasteful. Is it ok to check that the total is 4? The edge-case we need to worry about is if one of them equals 1 and the other 3: this happens for the string "D" (length=1 and character-index=4 with divisors 1,2 and 4). So it's not Ok. Can we multiply them? Also no, because 1 and 4 will again give 4 (think about the string "F"). But - since we know that the string length must be less-than-or-equal to the sum-of-character-indices, we can use exponentiation: the only way to get 4 is 4^1 or 2^2, and since the sum-of-character-indices can't be 1 if the string-length is 4, 2^2 is the only possibility. So the final, combined check for double-primality is `sum(!nchar(s)%%1:t)^sum(!t%%1:t)==4`, saving 3 characters compared to testing them separately. [Answer] # [Rockstar](https://codewithrockstar.com/), ~~327~~ ~~321~~ ~~319~~ 294 bytes No built-in for testing primes! No case conversion! No way to get the codepoint of a character! Why do I do these things to myself?! Spent so long just getting the damn thing to work, I'm sure it's far from optimally golfed but it'll do for now. Outputs `0.25` for `true` and `0` for false. ``` F takes N let D be N let P be N-1 while P and D-2 let D be-1 let M be N/D turn M up let P be N/D-M give P G takes I N's 27 while N cast N+I in C if C's S at X give N let N be-1 give G taking 64 listen to S X's 0 T's 0 while S at X let T be+G taking 96 let X be+1 say F taking T*F taking X ``` [Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 77 bytes ``` \W|\d|_ $ ¶$` \G. 1 T`L`l [t-z] 55$& [j-z] 55$& T`_l`ddd . $* A`^(..+)\1+$ ¶ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPya8JialJp6LS4Xr0DaVBK4Ydz0uQ66QBJ@EHK7oEt2qWC5TUxU1rugsODMkIT4nISUlhUuPS0WLyzEhTkNPT1szxlAbZML//wFFmbmpXBmJeVyOwd5cHqk5OfkK4flFOSkgdoGCbyqXr2uIaxAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \W|\d|_ ``` Delete anything that isn't a letter. ``` $ ¶$` ``` Duplicate the letters. ``` \G. 1 ``` Replace the letters on the first line with `1`s, thus taking the length in unary. ``` T`L`l ``` Convert the remaining letters to lower case. ``` [t-z] 55$& [j-z] 55$& T`_l`ddd ``` Convert them to digits that will sum to their numeric position. ``` . $* ``` Convert the digits to unary, thus taking their sum. ``` A`^(..+)\1+$ ``` Delete any composite values. ``` ¶ ``` Check that both values are still present. [Answer] # [Python 3](https://docs.python.org/3/), ~~86~~ ~~78~~ 87 bytes Saved 8 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! Added 9 bytes to fix a bug kindly pointed out by [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder). ``` lambda s:~-len(s)*all(n%i for n in(len(s),sum(ord(c)&31for c in s))for i in range(2,n)) ``` [Try it online!](https://tio.run/##pZDfa8IwEIDf@1ccha3JqA/qYCB0MLYO98MpWtiD@hDbVAPxUpIUJ@L@9a6Jcw97GiyQ3Jfv7gK5am83CvtNmSwaybargoEZfHYkR2LoFZOS4IWAUmlAEEhOPjb1lihdkJxe9rsumbdJMJQ6Fo41wzUnvRgpbSw31iQknLAwhnCixZY72DB04W724kI1ru7V1JsHgQLXGVtJXzdKs3TqYMilVA5mo6fX1EGp1Q6/U9XIVz@rjTfZLsVs/9P2rrQs/OMK2Yksl3wyHL@lM3djIQ34R8Vzy4uEZLrmMfzlfGTS/DfQQCckWtS9m@s8Ag/dfkSDX9N0w/ezpHQQQLssJODFXCy9MK1AZf0uiaVe8laef3YurLRAS8ooPNhjCJ1bOJgjHPTcJAlfHiPafAE "Python 3 – Try It Online") Returns a truthy or falsey value. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes ``` ḷạ-₉₆ᵐ+ṗ&lṗ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSuVv2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8f7hj@8NdC3UfNXU@amoDCmg/3DldLQdI/P8frRRQlJmbqqSjlJGYByQdg72BZIF/gXN@EIjvkpmXmZcekpiUA1Lj6xriGgSkPVJzcvKBdHBuJlg8rSi/PA8iXuALEvDKzwDxQ8pd80IqYRrC84tyUkBm5uclghklqTmpAR7@fq7BIJuB2Fkp9j8A "Brachylog – Try It Online") ### How it works ``` ḷạ-₉₆ᵐ+ṗ&lṗ (is the implicit input) ḷ to lowercase ạ to list of char codes -₉₆ᵐ minus 96 (so 'a' -> 1) + summed ṗ prime? &l and is the input's length ṗ prime? ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes ``` PrimeQ@*Tr/@(LetterNumber@#&&1^#)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P6AoMzc10EErpEjfQcMntaQktcivNDcptchBWU3NME5ZUw2kJK9EQd8h3UHLOSOxKDEZqKZY36FaCaxXSUcpIzEPSDoGewNJj9ScnHyF8PyinBQIr8AXpMTXNcQ1SKn2/38A "Wolfram Language (Mathematica) – Try It Online") -22 bytes from **@att** [Answer] # [Japt](https://github.com/ETHproductions/japt), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Êj ©Uu ¬mc xaI j ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ymogqVV1IKxtYyB4YUkgag&input=IlByaW1lIg) [Answer] # [J](http://jsoftware.com/), 27 22 18 bytes ``` 1*/@p:#,1#.32|3&u: ``` [Try it online!](https://tio.run/##bc1NC4JAEAbgu79iKGjpa9OCDkKQ2UZfZqjQMazWNLbdRYoI@u8W1KGxDnOYZ96ZORUVShIY2ECgBSbYr2pTcIPlpLAanaG2qy2rSnvdR692tYu6sRpR@BpYzW7/4QidxtvTtpZRw@D7VIEFA0iArPPszAmiNJYYnHCBQfvaVUEpNc5kJo9RvBOlex6LWPAh801TLoTCFHqzJcOU5Oomfxa1x7HNVVpKRTcmo/uflxuViwP2sZJx2S5c8PXUX7EQu4NblxRP "J – Try It Online") *-5 bytes thanks to xash* *-4 bytes thanks to Dominic van Essen* * `32|3&u:` Turn each letter into its index by first converting to its ascii number, the modding by 32. * `1#.` Sum. * `#,` Prepend list length. * `1...p:` Are each of those two numbers prime? * `*/@` Multiply them together -- are they all prime? [Answer] # C - ~~119~~ ~~108 99~~ 98 bytes (gcc) @ceilingcat saved another byte! ``` b,t,e;p(c){for(;--e&&c%e;);c=e==1;}a(char*a){t=0;for(e=b=strlen(a);b;)t+=a[--b]%32;t=p(e)*p(e=t);} ``` [try it online](https://tio.run/##Xc6xboMwEMbxnac4URHZKVSmHa/uM3RPMhhzJJacA9nHhHh2Ct3a5Yaf7i99vrl7v21dLTXhpLxehjEpbBo6nXxFqNFbsrbF1Sn/cOns9CLW4PFFtrNZUiRWTmOHWl6tuzRNd6s@3lHspEif92NF47q9BPZx7gk@s/RhfHt8FX8ohu6/pcD3w4rAAk8XWOliKQCOIRD40hpjbrhD9o4HUGWVyzqwPmjaYxlUKZQFEuU5ClQ9gOJRCForaSYwdnAxk77ylcsanNrj3zqRzInBYLFu3yk86Qc) previously Many thanks to @DominicvanEssen and @ceilingcat for saving 20 bytes! - and particularly to Dominic for fixing error on n=1 (non-prime) ``` b,t,e;p(c){for(b=c;--b&&c%b;);c=b==1;}a(char*a){t=0;for(e=b=strlen(a);b;)t+=a[--b]%32;t=p(e)*p(t);} ``` first attempt below 119 bytes ``` a(char*a){int t=0,d=strlen(a),e=d;while(d)t+=a[--d]%32;return p(e)*p(t);} p(int c){int b=c;while(--b&&c%b);return b<2;} ``` In fact can save 3 bytes by using `while(c%--b)` in the second routine, but this fails for the case of p(1) e.g. 'a'. or other single characters. [try it online](https://tio.run/##XY89bsMwDIV3nYJw4UBy7UJJR0W9SJJBf44FKIwhyegQ@Oyu7KRDuxDkB77HR9NdjVnePJowWQfHlK2/fwxf5A8KXv9n0eN1ZcRjBkXNoCI0TGzjSEst/TbclEfKyIMAbEseT3vO@UUUkIzCHmhVp6r1yFY0FuPc0yq7lCG6NIUMtQWgeM8O9jLHyQGXvQrJsTOesWrL@SLe1NHlKSJwQeblGapR7LHGyJK3VpbcwSFVrHXSiu/BB0cty@9SnbrOXurPg3hZjNSxZqTljZls/4B5GmlpXsKu07udqTX71ejjQczLskZPPw) [Answer] # [Scala](http://www.scala-lang.org/), ~~75~~ ~~74~~ 69 bytes ``` | =>p(|size)&p(|map(_&95-64)sum) def p(n:Int)=(2 to n/2)forall(n%_>0) ``` [Try it online!](https://tio.run/##XcxBa8JAEAXge37FElBmQLFIKxjcgPZiEWkxP0BWnWhkMztmt1Ja@9vjCnrx8t47fDy/Nda0bnOkbVBLU7Gin0C882oq8pecjVVlVoSm4r3OZ85ZMqzbi9K5wMVXv4TdOGojsO6O3/qjV/TfNSY7KpUAZx8cUMNQBad4MMTSNcZa4M46f8H2hgL4@z1qiRUsQwkeMUkiBj/pF3SC9Kupakp76cFwzGmxiCmf8u5WnCLGkyc/J2tdNLFlSQ/y314B "Scala – Try It Online") [Answer] # [Factor](https://factorcode.org/), 78 bytes ``` : d ( s -- ? ) dup [ length ] dip >lower [ 96 - ] map sum [ prime? ] bi@ and ; ``` [Try it online!](https://tio.run/##NY/BTsMwEETv/YpRTnBIj0ikEgXRiAZIWjWpOFQc3NhtLBzb2I6iCvHtYZOKy8zO03q9e2J1MG7Yl1nxkoD5Wkp8CaeFQstCM8ncOtkKDy@@O6FrqqwTIVwI64DFLCsSrEx3VCLejp3xh3HcDwk4buARx1jiFryzOEAJfaaxn@DS4kGZXjii93eIibXMwnctgenHJaGjfATTHIvhB9E0PULUME36VL6R2o19Nrsxr6SW@lwx2oNSnlbpjnwtlDLkZZ69p@QnZ3p95TYfG19NM@aqT3V1@X9AFyg@zjSaTUUQSmzXmyItI/zODnTadd358Ac "Factor – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` uÇ64-Op¹gp& ``` [Try it online!](https://tio.run/##yy9OTMpM/f@/9HC7mYmuf8GhnekFav//BxRl5qYCAA "05AB1E – Try It Online") Bytes removed due to lack of input restrictions [Answer] # [JavaScript (Node.js)](https://nodejs.org), 88 bytes Returns **0** or **1**. ``` s=>(g=k=>n%--k?g(k):k==1)(Buffer(s).map(c=>x+=n<(n+=c>64&(c&=31)<27&&c),x=n=0)|n)&g(n=x) ``` [Try it online!](https://tio.run/##jc9BSwMxEIbhu78iFkxnqNvaKgrS2aKwIEhBWsGLB0M2G@umkyVpZQ/@99ViUatdcM4PH@@8qFcVdVhUq4R9bpqCmkgpWCop5aMkKScWSrwsiYYI1@uiMAEi9peqAk1p3SMeA/dIp@dnErSk0yGORxdSajyuiekE3xilBaYaG@05emf6zlsooHMXFkvTQRSfNxiIVVibg1/qWfG3aVVX89t/qBvjnBcPPrh8oz9UoVzcxyox/UprY9PsPpv97d9h3UfOcmuEVtHELu6ZeMpmh5PtSku2@vlae4/addux5h0 "JavaScript (Node.js) – Try It Online") ### Commented **Helper function** ``` g = k => // g is a helper function testing if n is prime n % --k ? // decrement k; if it does not divide n: g(k) // do recursive calls until it does : // else: k == 1 // test whether k = 1 ``` **Main function** ``` s => // s = input string g( // test if the 'sum of the letters' is prime Buffer(s).map(c => // for each ASCII code c in s: x += // increment x if ... n < ( // ... n is less than ... n += // ... the new value of n: c > 64 & // if c is greater than 64 (c &= 31) < 27 // and c mod 32 is less than 27: && c // add c mod 32 to n ), // x = n = 0 // start with x = n = 0 ) | n // end of map(); yield n ) // end of the first call to g & g(n = x) // 2nd call to g with the 'length' x ``` [Answer] # [Perl 5](https://www.perl.org/) `-pl`, 52 bytes Uses the prime identification regex from [@Abigail's answer](https://codegolf.stackexchange.com/a/210743/72767) ``` $_.=$".1x s/./1x(31&ord$&)/ge;$_=!/\b((11+)\2+|1)\b/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lXs9WRUnPsEKhWF9P37BCw9hQLb8oRUVNUz891Vol3lZRPyZJQ8PQUFszxki7xlAzJkn/v7VKrq2B9X9HRy5nroCizNxUrozEPC7HYG8uj9ScnHyF8PyinBQQu8A3lcvXNcQ1CCLxL7@gJDM/r/i/rq@pnoGhwX/dghwA "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~50~~ ~~55~~ 50 bytes ``` ->s{[s.size,s.upcase.sum-64*s.size].all? &:prime?} ``` [Try it online!](https://tio.run/##ZVFbb4IwFH4/v6LhYa4LElGEaaJm2Vh2cxol2YPzAWdVklq6FmLcst/OCqwR3Fu/y@m5fCJdHbPBimwjBlMR7QlqDlEgUoIuuyZybQy7kJ24jonaHQw38@ca11E@PuG38azi9UzU8zDcRSxi2yBc0crftl2KYz/wZ/9awgOhNM7p@5DKku@2MczHjy/@GX2NYSPiA6vTnlv@wsekIrjK38PwFO@qdsdEjholOPgsONbddsvT07zFgq4rqt1ScttR@8UsrCl5lxaGhFAyfZi8@vPzKlvNMCBsDSDIZxoJgho8P30DNoOsOZTfC2nJ6IuY0kr5RyiJJdN903WuSnpphZSO0EW/KBr9ZDxNJDLUBZPdESVEJrJvAEebhVEkaixLoILUT5Wffv7FpmElLU0VGSkAZZ93lu9y1qg4kS4oYtKgCEeD0yWNZfYL) +5 bytes due to a misunderstanding of whether arrays could be considered truthy. -5 bytes thanks to Razetime, using the nice trick of putting the " &:prime?" at the end instead of doing a ".map(&:prime?)" before the ".all?". Posted separately because Razetime's solution actually didn't sum the alphabet index but simply the ascii ordinals. [It fails for the double prime words "DiningTable" and "METER"](https://tio.run/##ZVFba8IwFH4/vyLkQQ1WsVbtHOgYW4e7OMUW9uBkVIxaqEmXtogb@@1dmi7Yuqec75Kck/OJdH3KRmu6CxjMRXCgqDVGnkgpavQNNDAJ7H125iwDdS0Ct@5zhbOkL5pFd3xR8toGGtoE7gMWsJ3nr8PS26ZZiFPHcxb/WsKEhiHP6Qc/jAu@3yXgTh9fnAv6isBW8COr0vageCWa0pIwkP4hgSe@L9t7BurJUbyjw7xT1W12bD3NGxfhpqSaHSl3e/J/nPkVJe/SIZDQkM4ns1fHvbxlyhlGlG0ABP1MA0FRPcpXX4ftKGuN/e9lw2/HwRet1eSZHkhbyTcGbuBmobQT/hEbSlVlExO8@smiNIkRlrtM9ieU0DiJrzFEaLvEKlu8KoCMVJcySV3@BahhKTdNqbQkgKLPO8t/ddFILUtfUIFpoGLS4LxTvMp@AQ). [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` &ṗL¹ṗṁȯ-64ca ``` [Try it online!](https://tio.run/##yygtzv6fm18enJpf/Kip8b/aw53TfQ7tBJIPdzaeWK9rZpKc@P///2ilgKLM3FQlHaWMxDwg6RjsDSQL/Auc84NAfJfMvMy89JDEpByQGl/XENcgIO2RmpOTD6SDfT19XIF0WlF@eR5EvMAXpNArPwPEDyl3zQuphGkIzy/KSQGZmZ@XCGaUpOakBnj4@7kGg2wGYmcgTlGKBQA "Husk – Try It Online") Outputs a truthy number if the word is a double prime word, and 0 otherwise. ]
[Question] [ ## Introduction In geometry, the [Peano curve](https://en.wikipedia.org/wiki/Peano_curve) is the first example of a space-filling curve to be discovered, by Giuseppe Peano in 1890. Peano's curve is a surjective, continuous function from the unit interval onto the unit square, however it is not injective. Peano was motivated by an earlier result of Georg Cantor that these two sets have the same cardinality. Because of this example, some authors use the phrase "Peano curve" to refer more generally to any space-filling curve. ## Challenge The program takes an input which is an integer `n`, and outputs a drawing representing the `n`th iteration of the Peano curve, starting from the sideways 2 shown in the leftmost part of this image: [![Three iterations of the Peano curve](https://i.stack.imgur.com/XVLbi.png)](https://i.stack.imgur.com/XVLbi.png) ## Input An integer `n` giving the iteration number of the Peano curve. Optional, additional input is described in the bonuses section. ## Output A drawing of the `n`th iteration of the Peano curve. The drawing can be both ASCII art or a "real" drawing, whichever is easiest or shortest. ## Rules * The input and output can be given [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963) (choose the most appropriate format for your language/solution). * No need to handle **negative** values or **invalid input** * Either a full program or a function are acceptable. * If possible, please include a link to an online testing environment so other people can try out your code! * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. ## Bonuses Since this shouldn't be a walk in the park (at least in most languages I can think of), bonus points are awarded for the following: * -100 bytes if your code generates a gif of the construction of the Peano curves up to `n`. * -100 bytes if your code draws a space-filling curve for any rectangular shape (the Peano curve only works for squares, obviously). You can assume that the input then takes on the form `n l w` where `n` has the same meaning as before (the number of the iteration), but where `l` and `w` become the length and width of the rectangle in which to draw the curve. If `l == w`, this becomes the regular Peano curve. Negative scores are allowed (but are they possible...). ## Edit Please include the output of your program in the solution for `n == 3 (l == w == 1)`. [Answer] # [GFA Basic 3.51](https://en.wikipedia.org/wiki/GFA_BASIC) (Atari ST), ~~156~~ ~~134~~ 124 bytes A manually edited listing in .LST format. All lines end with `CR`, including the last one. ``` PRO f(n) DR "MA0,199" p(n,90) RET PRO p(n,a) I n n=n-.5 DR "RT",a p(n,-a) DR "FD4" p(n,a) DR "FD4" p(n,-a) DR "LT",a EN RET ``` ### Expanded and commented ``` PROCEDURE f(n) ! main procedure, taking the number 'n' of iterations DRAW "MA0,199" ! move the pen to absolute position (0, 199) p(n,90) ! initial call to 'p' with 'a' = +90 RETURN ! end of procedure PROCEDURE p(n,a) ! recursive procedure taking 'n' and the angle 'a' IF n ! if 'n' is not equal to 0: n=n-0.5 ! subtract 0.5 from 'n' DRAW "RT",a ! right turn of 'a' degrees p(n,-a) ! recursive call with '-a' DRAW "FD4" ! move the pen 4 pixels forward p(n,a) ! recursive call with 'a' DRAW "FD4" ! move the pen 4 pixels forward p(n,-a) ! recursive call with '-a' DRAW "LT",a ! left turn of 'a' degrees ENDIF ! end RETURN ! end of procedure ``` ### Example output [![peano-gfa](https://i.stack.imgur.com/ZlrwB.gif)](https://i.stack.imgur.com/ZlrwB.gif) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 117 bytes ``` {map ->\y{|map {(((++$+y)%2+$++)%3**(y+$^v,*/3...*%3)??$^s[$++%2]!!'│')xx$_*3},<┌ ┐>,$_,<└ ┘>,1},^$_}o*R**3 ``` [Try it online!](https://tio.run/##HYm7DoIwAEV3v6KSVvqyRmpc1PIPrmIbBkk08ggkhgZZnB0cOvh9/EgFl3vuyaku9X3rcwsWGTj4Lk8rsFSJ7Z7T6zDGjEFmCYpGMIIkpdgyqB@crqQQgiJJ4hjq5jRmFJ3n83Bwr5C0LTRU9nw/uDcY3EdxaCZxo3wVX/dcQ9OX9Eip9LtZk1qQYWiIUuJWXov/4CApAsLBBJCVNdAb/wM "Perl 6 – Try It Online") 0-indexed. Returns a 2D array of Unicode characters. The basic idea is that for lower rows, the expression ``` (x + (x+y)%2) % (3 ** trailing_zeros_in_base3(3*(y+1))) ``` yields the pattern ``` |....||....||....||....||.. % 3 ..||....||....||....||....| % 3 |................||........ % 9 ..||....||....||....||....| % 3 |....||....||....||....||.. % 3 ........||................| % 9 |....||....||....||....||.. % 3 ..||....||....||....||....| % 3 |.......................... % 27 ``` For upper rows, the expression is ``` (x + (x+y+1)%2) % (3 ** trailing_zeros_in_base3(3*(y+3**n))) ``` ### Explanation ``` { ... }o*R**3 # Feed $_ = 3^n into block map ->\y{ ... },^$_ # Map y = 0..3^n-1 |map { ... },<┌ ┐>,$_,<└ ┘>,1 # Map pairs (('┌','┐'),3^n) for upper rows # and (('└','┘'),1) for lower rows. # Block takes items as s and v ( ... )xx$_*3 # Evaluate 3^(n+1) times, returning a list (++$+y)%2 # (x+y+1)%2 for upper rows, (x+y)%2 for lower rows ( +$++) # Add x (y+$^v,*/3...*%3) # Count trailing zeros of 3*(y+v) in base 3 3** # nth power of 3 % # Modulo ??$^s[$++%2] # If there's a remainder yield chars in s alternately !!'│' # otherwise yield '│' ``` [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), ~~37~~ ~~27~~ 26 bytes ``` {+y,(|'y:x,,~>+x),x}/1,&2* ``` [Try it online!](https://tio.run/##y9bNS8/7/z/Nqlq7UkejRr3SqkJHp85Ou0JTp6JW31BHzUjrf5qCERdXgoGVkoKykoOOvoaOkpKmjr5VmrqiyX8A "K (ngn/k) – Try It Online") returns a boolean matrix `|'y` is syntax specific to ngn/k. other dialects require a `:` to make an each-ed verb monadic: `|:'y` [Answer] # Mathematica, score 60 - 100 - 100 = -140 ``` Graphics[PeanoCurve@a~Reverse~3~Scale~#2]~Animate~{a,1,#,1}& ``` Pure function. Takes `n` and `{l, w}` (width and height) as input, and gives an animated graphic as output. It first creates a *n*th order Peano curve with `PeanoCurve`. Since the *l* = *w* case still needs to create a Peano curve, we flip the expression at level 3, similar to [DavidC's answer](https://codegolf.stackexchange.com/a/176175); for *l* ≠ *w*, we just `Scale` the curve to the rectangle. This curve will still be space-filling, satisfying the second bonus. For the first bonus, we just `Animate` it over all sizes. Note that OP suggested that this was sufficiently different from DavidC's to warrant its own answer. The result for *n* = 3, *l* = *w* = 1 is as follows: ![](https://i.stack.imgur.com/sSs3i.gif) [Answer] # HTML+SVG+JS, ~~224~~ 213 bytes The output is mirrored horizontally. ``` n=>document.write(`<svg width=${w=3**n*9} height=${w}><path d="M1 ${(p=(n,z)=>n--&&(p(n,-z,a(a(p(n,-z,d+=z)),p(n,z))),d-=z))(n*2,r=d=x=y=1,a=_=>r+=`L${x+=~-(d&=3)%2*9} ${y+=(2-d)%2*9}`)&&r}"fill=#fff stroke=red>`) ``` [Try it online!](https://tio.run/##NY9BboMwAATvfYWVUmQDjhRyapTlBe0bioVtcEpsZNyQgOjXaUiV285qpdWcxEX0lTdd4NZJtWgsFoV01c9Z2bAdvAmKlsf@UpPByNAgmgbsk8Qm7zNplKmbsFZzcexEaIjE5nNHool2oDYbGQrLeRzT7k58zAQVzyhTjIxl3WN2D5KvTG2SZx4SV9ywywS@UPgU5Uc0XVP8cipj7Nlbvr5H0y0Fzbn855LFsZ832rQtXrXWpA/efSt4JYuSLU8lAjKRh9aBVM72rlXb1tVkftE0Z8sf "JavaScript (Node.js) – Try It Online") (prints the HTML) ``` ( n=>document.write(`<svg width=${w=3**n*9} height=${w}><path d="M1 ${(p=(n,z)=>n--&&(p(n,-z,a(a(p(n,-z,d+=z)),p(n,z))),d-=z))(n*2,r=d=x=y=1,a=_=>r+=`L${x+=~-(d&=3)%2*9} ${y+=(2-d)%2*9}`)&&r}"fill=#fff stroke=red>`) )(3) ``` [Answer] # Wolfram Language ~~83~~ 36 bytes, (possibly -48 bytes with bonus) As of version 11.1, `PeanoCurve` is a built-in. My original, clumsy submission wasted many bytes on `GeometricTransformation` and `ReflectionTransform.` This much reduced version was suggested by **alephalpha**. `Reverse` was required to orient the output properly. ``` Graphics[Reverse/@#&/@PeanoCurve@#]& ``` **Example 36 bytes** ``` Graphics[Reverse/@#&/@PeanoCurve@#]&[3] ``` [![Peano curve](https://i.stack.imgur.com/yDw6h.png)](https://i.stack.imgur.com/yDw6h.png) --- ## Bonus If this qualifies for the 100 pt bonus, it weighs in at 52 - 100 = -48 The code `[5]` was not counted, only the pure function. ``` Table[Graphics[Reverse/@#&/@PeanoCurve@#]&@k{k,#}&[5] ``` [![sequence](https://i.stack.imgur.com/OJrMl.png)](https://i.stack.imgur.com/OJrMl.png) [Answer] # BBC BASIC, 142 ASCII characters (130 bytes tokenised) Download interpreter at <http://www.bbcbasic.co.uk/bbcwin/download.html> ``` I.m:q=FNh(m,8,8,0)END DEFFNh(n,x,y,i) IFn F.i=0TO8q=FNh(n-1,x-i MOD3MOD2*2*x,y-i DIV3MOD2*2*y,i)DRAWBY(1AND36/2^i)*x,y*(12653/3^i MOD3-1)N. =0 ``` [![enter image description here](https://i.stack.imgur.com/2GFln.png)](https://i.stack.imgur.com/2GFln.png) [Answer] # [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ∩▐j>♣←╙~◘∩╗╢\a╘─Ràô ``` [Run and debug it](https://staxlang.xyz/#p=efde6a3e051bd37e08efbbb65c61d4c4528593&i=1%0A2%0A3%0A4&a=1&m=2) Output for 3: ``` ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ █ █ █ █ █ █ █ █ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ █ █ █ █ █ █ █ █ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ ███ ███ ███ ███ ███ ███ █ █ ███ ███ ███ ███ █ █ █ █ ███ ███ ███ ███ ███ ███ ███ ███ █ █ ███ ███ ███ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ █ █ █ █ █ █ █ █ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ █ █ █ █ █ █ █ █ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ ███ ███ ███ █ █ ███ ███ ███ ███ ███ ███ ███ ███ █ █ █ █ ███ ███ ███ ███ █ █ ███ ███ ███ ███ ███ ███ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ █ █ █ █ █ █ █ █ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ █ █ █ █ █ █ █ █ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ``` [Answer] ## Logo, 89 bytes ``` to p:n:a if:n>0[rt:a p:n-1 0-:a fw 5 p:n-1:a fw 5 p:n-1 0-:a lt:a]end to f:n p:n*2 90 end ``` Port of @Arnauld's Atari BASIC answer. To use, do something like [this](http://logo.twentygototen.org/56yMrISL): ``` reset f 3 ``` ]
[Question] [ We all know that any positive integer can be represented as the sum of powers of two. This is how binary representations work. However there's not just one way to do this. The canonical method, used in binary representations represents it as the sum of *unique* powers of two. For example \$5=2^0+2^2\$. However since \$2^0=1\$ we can write any number just adding \$2^0\$. For example \$5=2^0+2^0+2^0+2^0+2^0\$. How many ways are there to write a given number as the sum of powers of two? Let's write a program to see. We don't want to double count methods that are equivalent under associativity or commutativity, so \$2^0+2^2\$ and \$2^2+2^0\$ count as the same way because we've just changed the order. Since this is sequence you may use any of the following IO formats where \$f(n)\$ is the number of ways to write \$n\$ : * Take \$n\$ as input and output \$f(n)\$. * Take \$n\$ as input and output \$f(x)\$ for \$x\$ up to \$n\$ in order. * Output all \$f(x)\$ for every positive integer \$x\$ in order. You may optionally choose to also include \$f(0)\$. 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 Here are the first 60 values: ``` 1, 2, 2, 4, 4, 6, 6, 10, 10, 14, 14, 20, 20, 26, 26, 36, 36, 46, 46, 60, 60, 74, 74, 94, 94, 114, 114, 140, 140, 166, 166, 202, 202, 238, 238, 284, 284, 330, 330, 390, 390, 450, 450, 524, 524, 598, 598, 692, 692, 786, 786, 900, 900, 1014, 1014, 1154, 1154, 1294, 1294, 1460 ``` More can be found at OEIS [A018819](https://oeis.org/A018819) [Answer] # [Haskell](https://www.haskell.org/), 22 bytes ``` l=scanl(+)1$(:[0])=<<l ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P8e2ODkxL0dDW9NQRcMq2iBW09bGJud/bmJmnoKtQkFRZl6JgopCSWJ2qoKhgYFCzv9/yWk5ienF/3WTCwoA "Haskell – Try It Online") Defines the infinite list `l` of `[f(1),f(2),...]`. The OEIS says the generating function satisfies \$A(x^2)=(1-x)A(x)\$, which rearranges to \$A(x) = \frac{1}{1-x}A(x^2) \$. Starting with \$A(x)\$, we can interpret \$A(x^2)\$ as interspersing a zero after each element, `(:[0])=<<` in Haskell. Then, multiplying by \$\frac{1}{1-x}\$ is taking the cumulative sum `scanl1(+)`. A small adjustment to omit the first initial `1` from the OEIS sequence is to do `scanl(+)1` instead. This also removes a circular dependency in defining that initial element, fixing the issue that \$A(x) = \frac{1}{1-x}A(x^2) \$ only defined \$A\$ up to a constant multiplier. Now we put these together as `l=scanl(+)1$(:[0])=<<l`, which defines the elements of the infinite list `l`. Haskell's lazy evaluation allows this infinite list to be defined in terms of itself, as long as each element depends only on earlier elements, which is the case here. [Answer] # [Python](https://www.python.org), 31 bytes ``` f=lambda n:n<2or f(n-2)+f(n//2) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhb702xzEnOTUhIV8qzybIzyixTSNPJ0jTS1gZS-vpEmRNVN9TSgTKZCZp5CUWJeeqqGoYGBplVBUWZeiUaaRqamTmpeiq2SghJUOcxwAA) This can be derived from the recursion below by taking the difference between f(n) and f(n-2) which cancels most of the terms in the sum. ### Old [Python](https://www.python.org), 42 bytes ``` f=lambda n:n<2or sum(map(f,range(n//2+1))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3tdJscxJzk1ISFfKs8myM8osUiktzNXITCzTSdIoS89JTNfL09Y20DTU1NaE61NOAijIVMvMUIPKGBgaaVgVFmXklGmkamZo6qXkptkoKSlDlMIsA) The "obvious" recursion. ### How? First decide how many 1s. The remainder must be even and we can halve it and any partition of it. This can be done for any even remainder <=n. The recurrence follows. ### Full program #### [Python](https://www.python.org), 40 bytes ``` t,*a=1,1 for i in a:print(i);t+=i;a+=t,t ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwU23zNyC_KISheLKYq78gqLMvBJbMMmVkpqmAGZpZGpacSnkw9hcCplpCpl2hgYGBlZATXqpFZklGppLS0vSdC1uapToaCXaGuoYcqXlFylkKmTmKSRawXRal2jbZlonatuW6JRA1C-AUlAaAA) #### EDIT: Just seeing that @xnor posted the [exact same](https://codegolf.stackexchange.com/a/249437/107561) program a bit earlier. In theory produces the entire sequence (from term #1). This can be either viewed as unrolling the recursion at the top of this post or --- as far as I understand --- as a port of the generating function approach a [few](https://codegolf.stackexchange.com/a/249427/107561) [answers](https://codegolf.stackexchange.com/a/249422/107561) have used. I can't know for sure because these languages are all esoteric to me. [Answer] # [Perl](https://www.perl.org/), ~~83~~ ~~75~~ ~~73~~ ~~59~~ 58 bytes *-14 bytes thanks to a recursive regex I discovered while working on [Sum of Powers of 2](https://codegolf.stackexchange.com/questions/179174/sum-of-powers-of-2/250059#250059)* ``` sub{my$i;1x pop~~/^((\1|^.)(\2((?3))\4|))*$(??{++$i})/;$i} ``` [Try it online!](https://tio.run/##VU1bbsIwELzKClnyLmlDeUkIN81FIqRAHVgpdizbtKAQPjkAR@xFAulHpf7MQzOacdrXy/4YNIToeRcVDPq79JbtPiiwzZ8BqU9OezbaxrJer4MpfTRl3B3ki/xq@FMqMGcQVdaH47Y1Z8FqegLXuOt1skEsppdNSljMEPM5UbG4EI0F5nmbJII7mqgn9urff9V4HIayt2f4nq0GShJqgSsUTK3zbOOosKMOfiUITiX83O4gUxTV68fQItX1Dw "Perl 5 – Try It Online") This is definitely not the shortest possible Perl function by any means. But the idea here was to make a partition counter with all the logic in a regex, like my previous [Fibonacci](https://codegolf.stackexchange.com/a/223243/17216) and [Padovan](https://codegolf.stackexchange.com/a/223250/17216) answers. This counts all the different ways the regex can make a complete match from start to finish, where the input number is provided to the regex in unary, as the length of a string of identical characters. ``` ^ # Anchor to the beginning of the string. ( # \1 # Match \1 multiplied by any power of 2; this will be captured in \1 for use # by the next iteration. As such, the value of \1 can only increase to a # higher power of 2, or stay the same, but can never go down. In this way we # ensure against double counting methods that are equivalent under # associativity or commutativity. (\1|^.) # \2 = the power of 2 used by the previous iteration, or 1 if # this is the first iteration (\2((?3))\4|) # Match \2 * ({any power of 2} - 1) )* $ # Assert we are at the end of the string. If we aren't, the # regex will backtrack and try different power(s) of two to # get here, and this failed attempt won't be counted. (?{++$i}) # Perl embedded code to increment the partition counter. \1 # Attempt to match something that can never match, to force # the regex engine to backtrack. A backreference is used # because if we tried to use "^" or "z", the regex engine # would do smart optimization, which we don't want. ``` The power of 2 logic is based on the regex `x(x((?1))\2|)` ([Try it online!](https://tio.run/##RY5fa8IwFMW/ykUuNhdbmhT2Yhqt4F73tLfpghsWAlFr0kFHzL56FzthL5d7zv1zft3R2afx9A3oJAR7@TxYwFImqert5nWzitBeHEOvuKxXkgKYNikKnTPnHma780xGaKzynTU9y4os918fvk8nOi9ELuh4vS@t/12efFqiJnn/5VPiwTW2rig09k3sVap8Lx@55iHR1Goap26xoGBaYCwbMhggLRGB@oESXUkB/Xw@wU1sCVzIP1Y0Em9KxBi1fn7Zaj2@D2xgbC2IdtWNcBx5UQnOfwE "Perl 5 – Try It Online")), except that the `x`s are replaced with `\2`, to ensure that it never matches a powers of 2 less than those matched on previous iterations of the main loop. # Regex `🐇` (Perl / PCRE2 v10.34+), ~~47~~ ~~39~~ 25 bytes ``` ^((\1|^x)(\2((?3))\4|))*$ ``` Takes its input in unary, as a string of `x` characters whose length represents the number. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method. It can yield outputs bigger than the input, and is really good at multiplying.) [Try it online!](https://tio.run/##RU/LTsMwELz3KyxrVXnJo0kBCdVxkkrlyokbaa0StZKFaYMTpEBijnwAn8iPBCcgcVntzs7uzFQHo6@H5zcChpNOn8u9JrDgbhTJZn2/Tu3seDYMahHxJOXYEXV0E3aVUaeG0OJEuSW5FnWlVcNoQP369bFu3In0g9iP8fAykrJ/NHI4rkAiH3/VTnFvcp0sscv1Q7wVrkZbbmeETMrqDwCViIngOs/DDkpniTDa0hYUio8Fy3qWrcAgyzrPg9Ji8ZRI@Z72wLKpCRHHaPV8PrmfzLtkMSe/aUCFlHx/fhEaQumIvVtZK@Xt3UbKYcdYEfe7FlmxZCy7RCyuesQLGIYouIl@AA "Perl 5 – Try It Online") - Perl v5.28.2 [Attempt This Online!](https://ato.pxeger.com/run?1=RU-7TsNAEBRtvuJ0WkW3-BE7UEQ5vyKFlooOJ6dgxdKJIzG2IxlsU_IBtDQpwkfwK5R8CWc7Es3u7Ozc7cznKdvm6vhzAU8vBHJOarVPNorAhOvR95aLu0XQjtJ9zqDwHe4FHGsiUz1hneVyVxIa7yhvSaT8IlOyZNSiZnF4KEr9RJiWa7q4fe5E4T_raB7nIJB3fxX64iaPlDfFOlL37srX1VnxdkRIf1meCZCe3ws0MgysIdGWCKMVrUCi_zZhYcPCOeTIwtowIGkxfvSEeA0aYGEPbMQuWjEe9-578zqZy8mQBqRNye_7B6E2JFrY6FXbCnFzuxTi61Cm1ux7zVjsNusKWTxlLLxCjK8bxEsY9sdzOznWzBnwHw "Perl – Attempt This Online") - Perl v5.36+ [Attempt This Online!](https://ato.pxeger.com/run?1=hVbNbttGED4W0FOMmdbelahUtNvAEE0bji3ABhI7UGQ0ja0QNLmUFqGWBLmMfxpf-wC99tJDe8wD9FHaY1-jl87-SKItASUsan9mvvn7ZuRfv8RFVlfqE07i-Mul082KuGTb3V1n_NfwWcJSLhi8ORoOtsOj8-NBeHF2Ogp_OD0encBu6xkXcVYnDPa00vPpfiueRiWExeUYAhg6L29uPl7v1D_e3b0bTV_cTMkftUy7u39-IOTK-_zhlpKrbUIOdii9-u4zpe2vzf3fX_1Ln6o6LrSLICw6nt-wW8mSi4kyvDzjOZ6yaLa_Irff4kJCgUsZsrLMSxLnopKgnW7PWFVFE0bhp0om_X6MErC3B_ZYLfU5E0nmQ8lkXQrw_IcVTLWP84S5cJ3nGeRBGmWVgtVmLNzl9vcvxn4L8OEpEJ2_cMIsRmiliMEhpgAXRyeHw902tZcuVPye5SlZOP7t_KQhTynVVtRDcjgwQcR5LaEPi0CpCs_RaqA96IPzJHit7Dio5VwJhy7ykSJ5piaSRVJaD61aVHwiWAJZLibmFYnqhpW-TtjsLoyjLEM3bOx2F15nefwR2rELn3KeQDuJZIS5U0lSSwgCIOqmTTeXGNRidzqLyvRsZWYRFwQBtIPFJRIhY4IUtOuNg55vQjDsgCIOHHLQd3xcdYLCfDmUHBzhZ4PieY2IO9uhxKKiroKf4EJDN4G4KGqp1HVgWEJol2y-n0UynoY6lvZybdBKVtWZdE0JfNt3b0_fD_RJmlYMLzFeDGEip48E2vknFkvUspXA_pvbnxU8Y8SS4u2b0ZAW8fM4RGcJdS3G-8HwPBwNhq9Pzw5Hg-P58eDdaHB2rPab2if7bT3p0SWDN0okoM19sxv028o1Qg9WshHiPpIsTMt8FhaRlKwUpESWn128emUBmjrYupLdSkzifBWsu7ewZAUFI1hQcA7hNnjpruPZUwBjKuMz3gTpetRvCCWskP8rVLK4Liuei7WC2myal6Cny_2CuTgxMpzQxDQyF67hHvXnjNflQRXRw_REMudEC8zLj_UXngtFXuG1ucGJn5Ct7pY1qh7hqdyizEbQ5Hm_L9ThwRpc6Gj5DngUB4boLbHMrFXmBLsxu0vhdbyxj8NmhpkglQtbt1vKMUxQhZfjoKG_SAIPhOrBvUB4PnQ6vBnxnJT3FNApZYRsXQkMCVOH0pqfKXG-SeCfn38B_GnheGVGCDrWsGZ6STXlY3ZpYjY7Cp3m2BD6b8lpXNsyUn_FOYO714PNTWtjI7BdNxyeD8Oz89eHo6MT-khR06_RXvOJIcuaPbHB8FdnRXc5_XF-24jXTHL1PLSW73WNlZaMkWV8qw1tBBZ72pyI5hJnxmJgm0jwp8P8D_Db773ubs-s_wM "C++ (GCC) – Attempt This Online") - PCRE2 v10.40+ # Regex `🐇` (Perl / PCRE2), 41 bytes ``` ^((?=(?(3)(\3)))((\2|^x)(\4((?5))\6|)))*$ ``` [Try it online!](https://tio.run/##RU9NT8JAEL3zKzabCZmxfLQgxrBdFhK8evJmYYMNJBtXwBYTtK1HfwA/0T9Sp9XEy2Temzcz7x23mZ/UL@8CMiUKf0g3XsBQMdTxcvGwmFWd3SFDyHWo4pmiQrgdIyqOmdufhEz2UlVi7nV@9O6Esi97@dtTfuIV2@tHvYi2r43I/LMh8zQFS6q5lfPHTTb38YiKuX@MVppruFJVR4j2s/sjwMW6FXAXBFRAypYEyrM8gyP9OURToplCRmiKIIC0ouQ5tvZjVgKathkQNdHybrd135rnZJESv2nADaT4/roIOYCUhSWPqsrau/ultfUa0Wg0OCZMxkSEmIzK9ZnRNU8mRMlNyfQV1HXYvw1/AA "Perl 5 – Try It Online") - Perl **[Try it online!](https://tio.run/##hVXrTuNGFP6fpzh4W5hJnG0CXYRiTERDJJB2wyob1O0Caxl7nIzWGVv2eLl0@dsH6CP2QZqeuSQxJFItcGbO5Tv34yjP29MoWryJWcIFg4@D8XA/GFyeDYOr0cUk@P3ibHIOR403XERpFTM4zqOC7b@dnTSiWVhAkF/fgg9j57f7@293B9Ufj4@fJ7PD@xlZfCWk75M@OaDk5oBSSsjN/o@vD3j7FTnvKL05/IHk5k8L@lrZcaGZ@0He6no1y6UsuJgq02saz5DKwvnJhtxJgwsJOR5lwIoiK0iUiVKCdrs5Z2UZThmFP0sZ93oRSsDxMViyOmo6E3HqQcFkVQjoes8bmOoeZTFz4S7LUsj8JExLBavNWLjr/XeHt14D8OEJEJ3BYMosRmCliMEhpgRXg/PT8VGTWqYLJX9iWUJWjv@ypNTkMZ3ainpIBn0TRJRVEnqwCpSq8BytBtqDHjivgtfKjoNazo1w6CofSVqVMxPJKimN50YlSj4VLIY0E1PzCkV5zwpPJ2z@GERhmqIbNnZ7C@7SLPoGzciF7xmPoRmHMsTcqSSpI/g@EMVp0t01BrXYrdaqMh1bmXnIBUEA7WB@jY2QMkFy2u7e@h3PhGC6A/LId0i/53h4avm5@XEo6Q/wf4civULEg/1AYlFRV8FP8aCh60Bc5JVU6jowLCE0C7a8z0MZzQIdS3N9NmgFK6tUuqYEnp28TxdfhpqSJCVDJsaLIUzl7IVAM/vOIolathI4gUv785ynjNim@PRxMqZ59DYK0FlCXYvxZTi@DCbD8YeL0elkeLYkDz9PhqMzdd/VPtlf60mHrjt4p8AGtLmvT4N@W7la6P5GNgK8h5IFSZHNgzyUkhWCFNjlo6v37y1AXQdHV7IHiUlcnvxtfAtLNlAwglULLiHcWl@62/rsNYAxlfI5r4O0u9SrCcUsl/8rVLCoKkqeia2C2mySFaC3y9Oqc3FjpLijiRlkLlzTe9RbdrwuD6qIDqYnlBknWmBZfqy/6LqQZyWyDQd3fkz22nvWqHpEV@UWZXb8ep/3ekIR@1twoaXlW9CluDBEZ41ldq0yJ9i9uV2Lbqt76@GymWMmSOnC3sOecgwTVCLz1q/pr5LAfaFm8NgXXQ9aLV6PeNmUTxTQKWWE7N0IDAlTh9K6PxPi/BzDP3/9Dfhp4cgyKwQdq1kzs6SG8mV36casTxQ6zXEg9N@6p/Fsy0i9DecM7nEHdnetjR3fTt14fDkORpcfTieDc/pCUbdfbbyWG0MWFXtlg@FXZ0N3vf1xf9uIt2xy9Tw31u9tg5UUjJF1fJsDbQRWd1rfiIaJO2O1sE0k@OlYdNpHnX@jJA2n5aKdap320X8 "C++ (gcc) – Try It Online") - PCRE2 v10.33** [Attempt This Online!](https://ato.pxeger.com/run?1=hVbNbttGED4W0FOMmdbelahUtNvAEE0bji3ABhI7UGQ0ja0QNLmUFqGWBLmMfxpf-wC99tJDe8wD9FHaY1-jl87-SKItASUsan9mvvn7ZuRfv8RFVlfqE07i-Mul082KuGTb3V1n_NfwWcJSLhi8ORoOtsOj8-NBeHF2Ogp_OD0encBu6xkXcVYnDPa00vPpfiueRiWExeUYAhg6L29uPl7v1D_e3b0bTV_cTMkftUy7u39-IOTK-_zhlpKrbUIOdii9-u4zpe2vzf3fX_1Ln6o6LrSLICw6nt-wW8mSi4kyvDzjOZ6yaLa_Irff4kJCgUsZsrLMSxLnopKgnW7PWFVFE0bhp0om_X6MErC3B_ZYLfU5E0nmQ8lkXQrw_IcVTLWP84S5cJ3nGeRBGmWVgtVmLNzl9vcvxn4L8OEpEJ2_cMIsRmiliMEhpgAXRyeHw902tZcuVPye5SlZOP7t_KQhTynVVtRDcjgwQcR5LaEPi0CpCs_RaqA96IPzJHit7Dio5VwJhy7ykSJ5piaSRVJaD61aVHwiWAJZLibmFYnqhpW-TtjsLoyjLEM3bOx2F15nefwR2rELn3KeQDuJZIS5U0lSSwgCIOqmTTeXGNRidzqLyvRsZWYRFwQBtIPFJRIhY4IUtOuNg55vQjDsgCIOHHLQd3xcdYLCfDmUHBzhZ4PieY2IO9uhxKKiroKf4EJDN4G4KGqp1HVgWEJol2y-n0UynoY6lvZybdBKVtWZdE0JfNt3b0_fD_RJmlYMLzFeDGEip48E2vknFkvUspXA_pvbnxU8Y8SS4u2b0ZAW8fM4RGcJdS3G-8HwPBwNhq9Pzw5Hg-P58eDdaHB2rPab2if7bT3p0SWDN0okoM19sxv028o1Qg9WshHiPpIsTMt8FhaRlKwUpESWn128emUBmjrYupLdSkzifBWsu7ewZAUFI1hQcA7hNnjpruPZUwBjKuMz3gTpetRvCCWskP8rVLK4Liuei7WC2myal6Cny_2CuTgxMpzQxDQyF67hHvXnjNflQRXRw_REMudEC8zLj_UXngtFXuG1ucGJn5Ct7pY1qh7hqdyizEbQ5Hm_L9ThwRpc6Gj5DngUB4boLbHMrFXmBLsxu0vhdbyxj8NmhpkglQtbt1vKMUxQhZfjoKG_SAIPhOrBvUB4PnQ6vBnxnJT3FNApZYRsXQkMCVOH0pqfKXG-SeCfn38B_GnheGVGCDrWsGZ6STXlY3ZpYjY7Cp3m2BD6b8lpXNsyUn_FOYO714PNTWtjI7BdNxyeD8Oz89eHo6MT-khR06_RXvOJIcuaPbHB8FdnRXc5_XF-24jXTHL1PLSW73WNlZaMkWV8qw1tBBZ72pyI5hJnxmJgm0jwp8P8D_Db773ubs-s_wM "C++ (GCC) – Attempt This Online") - PCRE2 v10.40+ This is a port of the 25 byte regex. PCRE v10.33 and earlier automatically makes any group containing a nested backreference atomic, so this port works around that by enclosing the main group in a top level group, and copying backreference `\3` into `\2` inside a lookahead before entering group 3. The copy is done inside a conditional, because there isn't necessarily even going to be enough space to match `\3` in a lookahead, and if there isn't, the match on that iteration needs to fail. # Regex `🐇` (Perl / PCRE), 55 bytes ``` ^((?=(?(3)(\3)))((\2|^x)(?=(.*))((?(?=\5)\4|\6\6))*))*$ ``` [Try it online!](https://tio.run/##RU9BbsIwELzzCstaoV0CIYGCKhxjkOi1p95qsGgEklUXaEIl2iQ99gE8sR9JnbRSL6uZ8ax35rTL3KR@eWeQCVa4Y7p1DIbCU5mslg/LedXZHzOEXEYimQsqmN17RsUps4cz4/rARcUWTuYnZ8/IB7yfvz3lZ79i@oO4H9PutTGpfzXyOs3AkGj@yv3FbbZwyYiKhXuM19LPaC2qDmPtZfsngE1ka/AoCKiA1EdiyC/8Apbk5xBViWoGGaEqggDSivRzYszHvARULQiJmmp5t9umb8P7ZrFgv23Ahpx9f10ZDyH1xtI/VZUxd/crY@oNopKocEyox0SEqEfl5kKNGvYarjzUE9I3pZ7qKZEXe1DX0eA2@gE "Perl 5 – Try It Online") - Perl **[Try it online!](https://tio.run/##fVRtb9MwEP7eX3ELbLWbdGooTKhpqMYY4kPZUNVJoLVEwXVSi9SJnIRuY/vKD@An8kMo57jpMt6qNrXPd88999w5LMu6MWObR0KypFxwGGZM8cPlixZbhgqC7HIOPkysl@v150/98sP19fvp8mi9JJuPhIx8MiJ9SmZ9Sikhsye3H6@oth529H6Ey9kzOnt6OzuaHVGKxs7jDf0dynKgk/lBZrte655GXixEqnk0TUrI@KFNpGjl4epPvxctIQvIcFkEXKlUEZbKvICqrs6K53kYc/oV8wwGDB1gOIStVS8rO5eLxAPFi1JJcL27VilzEUu@gCSVsXmEMl9z5VXZVtcBC5MkLQuiZaw3wackZZ@hwyh8Ne62vYPtIWwVGwpJ0KEF@MkusYiES5LRrjv3ex4YQqY0yJhvkdHA8nBl@5n5s1D6E/ztUbSXCNl/EhSQ6mCNH@Oiwm4CCZmVhQ5XHDqKe9DUCEXJCmWiFc/LpDBrrWYU5bxwAItDlnGxNCfpF86KVF325yYVovpglEhXmUg4ynLIAkxOqAPvTianwavz6fF4DLdmdzF9/dyBA5PZLOpUPWowRQRkT3Fa6xdVLY4IloXeDlgaqOKoIERKVTjsLwawn88kDlsD0@TZAjc7hrTve2mOI8QjusgbrWglYsyLREhOzAwJ6Rg9qYc@bt3KijOGyR6ChkUqSOVUy4A6SNeBLM3x2JxEQi5Iu9ve8tIf6Woh0WfPb/ZvMJDaOPoLLtiVvw1IZIDJ77FMc3U6yddmdyld2517OP8r1IXkDrSv2poYlpLj4dxvxO@EEL7UszX0peuBbYtmxXWnbiggKZ2EtGeybaTZyse00HjVhH5Y8OPbd8DJNRcE2TVSmlnSE1jPE7/ijCjuwNnFeOwAMhY4ItV3O4QO9Kn3Bx@DMuzBwUGNiJJWs3c6mZxPgrPzt8fTkzf0QeTu2tSUrVM9X9ZDfJ7k/P9h29rq10uUlPnyH1U2qr9rmWc10wMzjIpzrIXu3iLb@9m62/S6z3s/WZSEcb7pJlqsXw "C++ (gcc) – Try It Online") - PCRE1** [Try it online!](https://tio.run/##hVXrTuNGFP6fpzh4W5hxHJpAF6EYb0QhEki7sMoGdbuEtYw9TkbrjC17vFy6/O0D9BH7IKVnLkkMiVQLnJlz@c79OC6KzjSOn98kLOWCwceT0XAvPLk8HYZXF@fj8Pfz0/EZHLbecBFndcLgqIhLtrc7e9eKZ1EJYXF9AwGMnN/u7r7d7td/PDx8Hs8O7mbk@Sshg4AMyD4lk31KKSGTvR9f76mi7rrqPsDj5C2d/PpjcjA5oBSJ7k/P9DWU44FbBGHR7vkNPypZcjFVjqxoPEcqi@bv1uTetbiQUOBRhqws85LEuagk6CDcOauqaMoo/FnJpN@PUQKOjsCS1VHTmUgyH0om61JAz39aw1T3OE@YB7d5nkEepFFWKVhtxsJd7709uPFbgA9Pgeh8hlNmMUIrRQwOMQW5Ojk7Hh261DI9qPgjy1OydPyXBaUhjznXVtRDchiYIOK8ltCHZaBUhedoNdAe9MF5FbxWdhzUcibCoct8pFldzUwky6S0nlq1qPhUsASyXEzNKxLVHSt9nbD5QxhHWYZu2NjtLbzN8vgbuLEH33OegJtEMsLcqSSpIwQBEMVx6fYKg1rsdntZma6tzDzigiCAdrC4xkbImCAF7fRugq5vQjDdAUUcOGTQd3w8tYPC/DjYqif4v0WRXiPi/l4osaioq@CneNDQTSAuiloqdR0YlhDcki3u80jGs1DH4q7OBq1kVZ1Jz5TAt3P46fzLUFPStGLIxHgxhKmcvRBw8@8slqhlK4HzuLA/L3jGiG2KTx/HI1rEu3GIzhLqWYwvw9FlOB6OPpxfHI@Hpwvy8PN4eHGq7tvaJ/trPenSVQdvldiANvfNadBvK9cIPVjLRoj3SLIwLfN5WERSslKQErv84ur9ewvQ1MHRlexeYhIXp2AT38KSNRSMYNmCCwiv0Zfepj57DWBMZXzOmyCdHvUbQgkr5P8KlSyuy4rnYqOgNpvmJejt8rjsXNwYGW5sYgaZC8/0HvUXHa/Lgyqii@mJZM6JFliUH@sveh4UeYVsw8EvQEJ2OjvWqHpET@UWZbaCZp/3@0IRBxtwoa3l29CjuDBEd4Vldq0yJ9iduV2LXrt34@OymWMmSOXBzv2OcgwTVCHzJmjoL5PAA6Fm8CgQPR/abd6MeNGUjxTQKWWE7EwEhoSpQ2ndnylxfk7gn7/@Bvy0cGSZFYKONayZWVJD@bK7dGM2Jwqd5jgQ@m/V03i2ZaT@mnMG96gL29vWxlZgp240uhyFF5cfjscnZ/SFom6/xngtNoYsa/bKBsOvzpruavvj/rYRb9jk6nlqrd6bBistGSOr@NYH2ggs77S5EQ0Td8ZyYZtI8NPx3O0cdv@N0yyaVs@dTOt0Dv8D "C++ (gcc) – Try It Online") - PCRE2 PCRE1 complains `recursive call could loop indefinitely` on the 41 byte regex, and that can be worked around, as `^((?=(?(3)(\3)))((\2|^)(x\4((?5))\6|))x)*$` (42 bytes) which [works on PCRE2](https://tio.run/##hVXrTuNGFP6fpzh4W5hJnG0CXYRiTEQhEki7YZUN6nYJaxl7nIzWGVv2eAN0@dsH6CP2QUrPXJIYEqkWODPn8p37cZTn7WkUPb@JWcIFg49no8F@cHZ1Pgiuh5fj4PfL8/EFHDXecBGlVczgOI8Ktv92dtKIZmEBQX5zCz6MnN8Wi293B9UfDw@fx7PDxYw8fyWk75M@OaBkckApJWSy/@MrJfeTX5HzjtLJ4Q9K72nzp2f6WttxoZn7Qd7qejXTpSy4mCrbaxrPkMrC@cmG3EmDCwk5HmXAiiIrSJSJUoL2uzlnZRlOGYU/Sxn3ehFKwPExWLI6ajoTcepBwWRVCOh6TxuY6h5lMXPhLstSyPwkTEsFq81YuJv9d4e3XgPw4QkQncJgyixGYKWIwSGmBtdnF6ejoya1TBdK/siyhKwc/2VJqcljmrUV9ZAM@iaIKKsk9GAVKFXhOVoNtAc9cF4Fr5UdB7WciXDoKh9JWpUzE8kqKY2nRiVKPhUshjQTU/MKRblghacTNn8IojBN0Q0bu70Fd2kWfYNm5ML3jMfQjEMZYu5UktQRfB@I4jTp7hqDWuxWa1WZjq3MPOSCIIB2ML/BRkiZIDltd2/9jmdCMN0BeeQ7pN9zPDy1/Nz8OJT0z/B/hyK9QsSD/UBiUVFXwU/xoKHrQFzklVTqOjAsITQLtrzPQxnNAh1Lc302aAUrq1S6pgSeHb1Pl18GmpIkJUMmxoshTOXshUAz@84iiVq2EjiCS/vznKeM2Kb49HE8onn0NgrQWUJdi/FlMLoKxoPRh8vh6XhwviQPPo8Hw3N139U@2V/rSYeuO3inwAa0ua9Pg35buVro/kY2AryHkgVJkc2DPJSSFYIU2OXD6/fvLUBdB0dXsnuJSVye/G18C0s2UDCCVQsuIdxaX7rb@uw1gDGV8jmvg7S71KsJxSyX/ytUsKgqSp6JrYLabJIVoLfL46pzcWOkuKSJGWQuXNN71Ft2vC4PqogOpieUGSdaYFl@rL/oupBnJbINB5d@TPbae9aoekRX5RZldvx6n/d6QhH7W3ChpeVb0KW4MERnjWV2rTIn2MLcbkS31b31cNnMMROkdGHvfk85hgkqkXnr1/RXSeC@UDN47IuuB60Wr0e8bMpHCuiUMkL2JgJDwtShtO7PhDg/x/DPX38Dflo4sswKQcdq1swsqaF82V26MesThU5zHAj9t@5pPNsyUm/DOYN73IHdXWtjx7dTNxpdjYLh1YfT8dkFfaGo2682XsuNIYuKvbLB8Kuzobve/ri/bcRbNrl6nhrr97bBSgrGyDq@zYE2Aqs7rW9Ew8SdsVrYJhL8dDx32kedf6MkDaflczvVOu2j/wA "C++ (gcc) – Try It Online"), but the recursive method of matching arbitrary powers of 2 doesn't work on PCRE1 anyway, since it only has atomic subroutine calling. So this 55 byte regex is a port of the earlier **39 byte** non-recursive regex, `^((\1|^x)(?=(.*))((?(?=\3)\2|\4\4))*)*$`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` H߀S‘ ``` A recursive, monadic Link that accepts a non-negative integer and yields the number of binary partitions. **[Try it online!](https://tio.run/##y0rNyan8/9/j8PxHTWuCHzXM@P//v5kBAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/j8PxHTWuCHzXM@H@4Hcj6/78oMS89VcNAx8xAEwA "Jelly – Try It Online"). ### How? ``` H߀S‘ - Link: integer, n H - halve -> n/2 € - for each i in [1..floor(n/2)]: ß - call this Link with argument n=i S - sum ‘ - increment ``` [Answer] # [Python](https://www.python.org), 40 bytes ``` f=lambda n:sum(map(f,range(1,n//2+1)))+1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3NdJscxJzk1ISFfKsiktzNXITCzTSdIoS89JTNQx18vT1jbQNNTU1tQ2h6pULijLzSjSi0zTyNBXS8osU8hQy8xRg6hWMDDRjNSFKYVYAAA) [Answer] # [C (gcc)](https://gcc.gnu.org/), 27 bytes ``` f(n){n=n<2?:f(n/2)+f(n-2);} ``` [Try it online!](https://tio.run/##VZFhb4IwEIa/@ysuJCagEEspSIdsH5b9iukHU4sj26qhJCMz/PWxWq6o5N6H8vauoXciOgoxDJWvgosq1Ya@PJn1igZL84poUPRDrVr43tfKD@AyA/NcDdmdpWjl4X0HJVziEExQG8xGZiMmKDaKElQ2KkExVEZGrdkojorjCYw4ZBmCEuqQ5A45QyQJceAOLHVIKXPgOSLjFLHOMwQnBBET@x8j4/RGypF9YdskTkq3ID72zcJQik/ZjN3ytt0b3Xb81Sj1Qrj/Tjysrk4N@NdO1@ogO1NGClxuQNe/8lT5bgbBCo3F5BSwXNrswB42zs3NrjWn2c3iwdbGrvw2eHSlcadh26rdLeHcmJTK9@YHiJ7BcK5hq8yV2hB0ON1al6Xc4bn9rB/@RPW1P@oh@vkH "C (gcc) – Try It Online") *Port of [loopy walt](https://codegolf.stackexchange.com/users/107561/loopy-walt)'s [Python answer](https://codegolf.stackexchange.com/a/249407/9481)* [Answer] # [HOPS](https://akc.is/hops/), 17 bytes ``` A=1+x*(A+A@(x^2)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70kI7-geG20kq5uQVFqsq2ZgVLsgqWlJWm6FhsdbQ21K7Q0HLUdHTQq4ow0NSHiUOkFUBoA) Based on this formula on OEIS: > > G.f. A(x) satisfies A(x^2) = (1-x) \* A(x). - Michael Somos, Aug 25 2003 > > > [Answer] # [Python 3](https://docs.python.org/3/), 40 bytes ``` t,=l=[1] for x in l:print(x);t+=x;l+=t,t ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v0THNsc22jCWKy2/SKFCITNPIceqoCgzr0SjQtO6RNu2wjpH27ZEp@T/fwA "Python 3 – Try It Online") A program that prints the sequence forever. While longer than [loopy walt's recursive function](https://codegolf.stackexchange.com/a/249407/20260), I think this shows off an interesting method of generating the sequence on the fly by running an infinite loop by appending new elements to the list being iterated over, specifically, two copies of the current running sum starting at 1. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 22 bytes ``` .+ * +%Lw`^(_*)(?=\1) ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8F9Pm0uLS1vVpzwhTiNeS1PD3jbGUJPr/38DLkMuIy5jLhMuUy4zLnMuCy5LLkMDAA "Retina – Try It Online") Link includes test cases. Explanation: ``` .+ * ``` Convert to unary. ``` Lw`^(_*)(?=\1) ``` Replace the input `n` with a list `0..n/2` inclusive. ``` +%` ``` Repeat the above expansion on every value in the list until it turns into a list of all zeros. ``` ``` Output the length of the final list. [Answer] # APL, 19 bytes ``` {2≥⍵:⍵⋄1++/∇¨⍳⌊⍵÷2} ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` FN⊞υ∨¬ιΣ…υ⊕⊘ιIυ ``` [Try it online!](https://tio.run/##HYm7DoMwDAB3viKjI8HA3DFLWQCJL0hTV4mUBzI2El/v0t5yOl2InkLzWfXTyMBUd@FZygsJrDWrHBGkNwvB3BiS7c0mBdwVMrrY9t@baiAsWBnf8PT5vJXsn0e3UqoMzh8McrfqOOpw5i8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` values (0-indexed). Explanation: ``` FN ``` Repeat `n` times. ``` ⊞υ∨¬ιΣ…υ⊕⊘ι ``` On the first iteration, just push `1` to the predefined empty list, otherwise push the sum of the first half of the list (inclusive). ``` Iυ ``` Output the resulting list. [Answer] # [Ruby](https://www.ruby-lang.org/), 25 bytes ``` f=->n{1+(1..n/2).sum(&f)} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y6v2lBbw1BPL0/fSFOvuDRXQy1Ns/Z/gQJIzNRAUy83sUBBLY0LTSD9PwA "Ruby – Try It Online") The "original" recursion in Ruby is 1 byte shorter than the optimized function by loopy walt. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` λN;ï₅₂+ ``` Outputs the infinite sequence. (Should have been 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) without the `ï`, but apparently there is a bug in 05AB1E with decimal values and `₅`.) [Try it online.](https://tio.run/##yy9OTMpM/f//3G4/68PrHzW1Pmpq0v7/HwA) **Explanation:** ``` λ # Start a recursive environment, # to output the infinite sequence # (which is output implicitly at the end) # Implicitly starting at a(0)=1 # Where every following a(n) is calculated as: N; # Push n/2 ï # (bug workaround: truncate it to an integer) ₅ # Pop and push a(n//2) ₂ # Push a(n-2) + # Add them together: a(n//2)+a(n-2) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` λ½vx∑› ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOu8K9dnjiiJHigLoiLCIiLCI2MCJd) ``` λ½vx∑› λ # Open a lambda for recursion: f(n) ½ # Halve to n/2 vx # For each x in [1..floor(n/2)], call f(x) ∑ # Sum › # Increment ``` ]
[Question] [ Let \$L\$ be a list of positive integers with no particular ordering, and which can contain duplicates. Write a program or function which outputs a list of positive integers \$M\$ (whose ordering is unimportant) such that merging \$L\$ and \$M\$ results into the smallest list which can entirely split into identical ranges of integers \$[1..i]\$, where \$i\$ is the biggest element in \$L\$ ### Example Let `L = [5,3,3,2,7]`. The maximum element of `L` is `7`. The most times a specific integer occurs is `2` (`3` appears 2 times). Therefore, we need to output the list `M` that will allow to complete `L` so that we can construct `2` ranges of integers from `1` to `7`. Therefore, we need to output `M = [1,1,2,4,4,5,6,6,7]`, so that each integer from `1` to `7` appears `2` times. ### Inputs and outputs * Use anything in your language that is similar to lists. The data structure used for the input and the output must be the same. * The input list will contain only positive integers. * The input list will not be empty. * You **cannot** assume the input list is sorted. * The ordering in the output list is unimportant. ### Test cases ``` Input Output [1] [] [7] [1, 2, 3, 4, 5, 6] [1, 1, 1] [] [1, 8] [2, 3, 4, 5, 6, 7] [3, 3, 3, 3] [1, 1, 1, 1, 2, 2, 2, 2] [5, 2, 4, 5, 2] [1, 1, 3, 3, 4] [5, 2, 4, 5, 5] [1, 1, 1, 2, 2, 3, 3, 3, 4, 4] [5, 3, 3, 2, 7] [1, 1, 2, 4, 4, 5, 6, 6, 7] ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~37~~ 33 bytes *-4 bytes thanks to nwellnhof!* ``` {^.keys.max+1 xx.values.max∖$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzpOLzu1slgvN7FC21ChokKvLDGnNBXMf9QxTSW@9n9xYqVCmoZTYrqGoaamNReCa47KNdQBQnQhC1QBYx0wRBU01THSMdEx1TEFCv8HAA "Perl 6 – Try It Online") Anonymous code block that takes a Bag and returns a Bag of values. ### Explanation: ``` { } # Anonymous code block ^.keys.max+1 # Create a range from 1 to the maximum value of the list xx # Multiply the list by: .values.max # The amount of the most common element ∖$_ # Subtract the original Bag ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) Saved 1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). The footer calls the main link, sorts the result to match the test cases and formats the output as a grid. ``` RṀẋLƙ`Ṁœ- ``` [Try it online!](https://tio.run/##y0rNyan8/z/o4c6Gh7u6fY7NTACyjk7W/f//f7SpjjEQGumYxwIA "Jelly – Try It Online") or [Check out a test suite!](https://tio.run/##y0rNyan8/z/o4c6Gh7u6fY7NTACyjk7W/X@4/eHORSqPmta4//8fbRiroxBtDiIMdRRACMq0ANHGOgpQBOKZ6igY6SiY6CiAGOgCprEA) ### Alternatives ``` ṀRẋLƙ`Ṁœ- RṀẋṢŒɠṀƊœ- ṀRẋṢŒɠṀƊœ- LƙɓṀRẋṀœ-⁸ LƙɓRṀẋṀœ-⁸ ``` [Try one of them online!](https://tio.run/##y0rNyan8/z/o4c6Gh7u6H@5cdHTSyQVAzrGuo5N1/x9uB4qoPGpa4/7/f7RhrI5CtDmIMNRRACEo0wJEG@soQBGIZ6qjYKSjYKKjAGKgC5jGAgA "Jelly – Try It Online") ### Explanation ``` ṀRẋLƙ`Ṁœ- Full program. N = Input. ṀR Range from 1 to max(N): [1 ... max(N)] Lƙ` Map length over groups formed by identical elements. ẋ Repeat the range T times, for each T in the result of the above. Ṁ Maximum. Basically, get the range repeat max(^^) times. œ- Multiset difference with N. ``` [Answer] # [R](https://www.r-project.org/), ~~59~~ ~~49~~ 48 bytes ``` rep(s<-1:max(L<-scan()),max(y<-table(c(L,s)))-y) ``` [Try it online!](https://tio.run/##lY9NbsIwEIX3PsUIFngkZ5GQFJSmN@AI2bjGaSMRB8WOFIQ4e@of1eKnINWazXyeN@/NMM@DPFJdJWnZ8YnuqkQLrigic@2pSgz/PEgq6I5pRExOOKewJURwQ1e16s23HMBIbUBwLXUJtarVCt/J0tNWfUGY8d8wakcsAM07CaLfS@AaODSjEqbtFSyaBWk@fls64ZmAfS5VlUSMk6f/zU4uhDQWpIhw95Ygp6MURu5LUGMnh1ZQ9MOb18N2G4OMwZpBzqBg8BZklrq6Fj/3sJPbO5tbjxsDBpsgW3vqKoofosXKYgVx4ZuwMgv6v8TBIH/UFM810S0GzK9XBJS5MxBe5A5W8ehwN5l/AA "R – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~86~~ ~~83~~ ~~80~~ 72 bytes ``` def f(l):m=range(1,max(l)+1)*max(map(l.count,l));map(m.remove,l);print m ``` [Try it online!](https://tio.run/##dVDbDoIwDH3fVzTxhWlDssHEaPwS0geioCYMCEGjX49lU4OCbZN1vZyetnl057rSfX/MCyiCUm7tvs2qUx4otNmdAysll4NnsyYow0N9rTospdwNfxu2ua1vOQd2TXupOrB9EaQGI1aNCQGLXMBLUoWKwzGrwTVrQoLLFcFIRuUum/zLKgSNECHECAZh7bEQBqN5LE5taA7rCwjB84pccDCaTP6Y/pjrMc73QJomPR4vnpQamoPX7w2jN72Y@tF1BZ9OpO59rS38imLMXfyQEj@Tnw "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ ~~16~~ ~~17~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ZLŠ¢àиIð.;þ ``` -1 byte thanks to *@Mr.Xcoder*. +1 byte after bug-fixing the work-around.. -5 bytes by using the new 05AB1E version and -1 byte because ordering of the output is unimportant Maybe I completely look past it, but does 05AB1E even have a remove all elements of list **b** from list **a**.. (EDIT: It indeed doesn't..) I know how to remove all multiple times, but not once each.. (multiset difference) [Try it online](https://tio.run/##yy9OTMpM/f8/yufogkOLDi@4sMPz8AY968P7/v@PNtQBQoNYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/yifowsOLTq84MKOysMb9KwP7/t/eL3O/@how1gdhWhzEGGoA4QQhgWIMtYBQxDTVMdIx0QHSCJzTCEckCIjHZgJBkAjYgE). **Explanation:** ``` Z # Push the maximum of the (implicit) input-list (without popping) # i.e. [5,3,3,2,7] → 7 L # Pop and push a list in the range [1,max] # → [1,2,3,4,5,6,7] Š # Tripleswap: a,b,c → c,a,b, so input,[1,max] to [1,max],input,input ¢ # Count for each value in the input-list how many times it occurs # → [1,2,2,1,1] à # Pop and push the maximum count # → 2 и # Repeat the list [1,max] that many times # → [1,2,3,4,5,6,7,1,2,3,4,5,6,7] #Now the work-around bit because 05AB1E lacks a builtin for multiset difference.. Ið.; # Replace first occurrence of the values in the input-list with a space " " # → [1," "," ",4," ",6," ",1,2," ",4,5,6,7] þ # Remove all spaces by only keeping digits # → [1,4,6,1,2,4,5,6,7] # (after which the result is output implicitly) ``` [Answer] # [R](http://r-project.org), ~~59~~ 55 bytes Using the `vecsets` package we can drop the answer length some. With `gl` we can get the ordered output. This doesn't work in TIO. Following @digEmAll's style of (rather clever) solution without a function definition, this can be considered a 55 byte solution. ``` vecsets::vsetdiff(c(gl(m<-max(L<-scan()),sum(L==m))),L) f=function(x){scan<-function()x vecsets::vsetdiff(c(gl(m<-max(L<-scan()),sum(L==m))),L) } f(c(1)) # expected: integer(0) f(c(7)) # expected: c(1, 2, 3, 4, 5, 6) f(c(1, 1, 1)) # expected: integer(0) f(c(1, 8)) # expected: c(2, 3, 4, 5, 6, 7) f(c(3, 3, 3, 3)) # expected: c(1, 1, 1, 1, 2, 2, 2, 2) f(c(5, 2, 4, 5, 2)) # expected: c(1, 1, 3, 3, 4) f(c(5, 2, 4, 5, 5)) # expected: c(1, 1, 1, 2, 2, 3, 3, 3, 4, 4) ``` [Answer] # JavaScript (ES6), 98 bytes This turned out to be pretty hard to golf below 100 bytes. There may be a better approach. ``` a=>(a.map(o=M=m=n=>m=(c=o[M=n<M?M:n,n]=-~o[n])<m?m:c),g=k=>k?o[k]^m?[...g(k,o(k)),k]:g(k-1):[])(M) ``` [Try it online!](https://tio.run/##fZDdisIwEEbv9ynmMoFppH/rUpz2CfIEYYRQtezGJLKKl/vq3aoothXDd5PwnTNDfuzZHtvf78MpCXGz7XfUW6qFVd4eRCRNngLVnkRL0WgKK93oKmBgSv6iCSxXvvFVK7EjR7VronG89o1RSnXCYRROSnRcDZcklZVhKbTs2xiOcb9V@9iJnTApw9OREhYLMPwxaS1ftVKEDCFHKBBKhM8ZNRQu4ffuofLFU/dIjLCcUfm1cAmPNnoke2TGltf3mzzjEXtzFm@RkqfjsvtP5Pe1C@7/AQ "JavaScript (Node.js) – Try It Online") ### How? We first walk through the input array `a[]` to gather the following data: * `M` = highest element found in the input array * `m` = highest number of occurrences of the same element * `o[n]` = number of occurrences of `n` Note that `o` is primarily defined as a function, but the underlying object is also used to store the number of occurrences. ``` a.map( // a[] = input array() o = // o = callback function of map() M = m = // initialize m and M to non-numeric values n => // for each value n in a[]: m = ( // this code block will eventually update m c = o[ // c = updated value of o[n] M = n < M ? M : n, // update M to max(M, n) n // actual index into o[] ] = -~o[n] // increment o[n] ) < m ? // if o[n] is less than m: m // let m unchanged : // else: c // set it to c ) // end of map() ``` We then use the recursive function `g()` to build the output. ``` (g = k => // k = current value k ? // if k is not equal to 0: o[k] ^ m ? // if o[k] is not equal to m: [ ...g(k, o(k)), // increment o[k] and do a recursive call with k unchanged k ] // append k to the output : // else: g(k - 1) // do a recursive call with k - 1 : // else: [] // stop recursion )(M) // initial call to g() with k = M ``` [Answer] ## Haskell, 72 bytes ``` import Data.List f l=(last(sortOn(0<$)$group$sort l)>>[1..maximum l])\\l ``` [Try it online!](https://tio.run/##ZYmxCsIwGIT3PsUNHRIIwapFB9vJUfEB2iD/YDWYpKFJwbePhoqL8MHdffeg8LwZk5K2fpwijhRJnnSIxQDTMEMhsvA5Lo6tDiUv79M4@zIbGN62XSWlpZe2s4VRvO9NsqQdGljy5yuYn7SLcuDoCqCrlMixW6ISyPzGfmkbgS/LrgXWAluBXP5VraCQ3g "Haskell – Try It Online") ``` sort l -- sort input list group -- group identical elements sortOn(0<$) -- sort by length last -- take the last element, i.e. the list -- of the most common element >>[1..maximum l] -- replace each of it's elements -- with the list [1..maximum l] \\l -- remove elements of the input list ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~18~~ 17 bytes ``` ⌉⟦₁;Ij₎R⊇p?;.cpR∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FP56P5yx41NVp7Zj1q6gt61NVeYG@tl1wQ9Khj@f//0aY6RjomOqY6prH/owA "Brachylog – Try It Online") *Saved 1 byte thanks to @Kroppeb.* ### Explanation ``` ⌉ Take the largest element in the Input ⟦₁ Construct the range [1, …, largest element in the Input] ;Ij₎R Juxtapose that range to itself I times, I being unknown; call the result R R⊇p? The Input must be an ordered subset of R, up to a permutation ?;.c Concatenate the Input and the Output (the Output being unknown at this point) pR This concatenation must result in R, up to a permutation ∧ (Find a fitting value for the Output that verifies all of this) ``` [Answer] # Java 10, 186 bytes ``` import java.util.*;L->{Integer m=0,f=0,t;for(int i:L){m=i>m?i:m;f=(t=Collections.frequency(L,i))>f?t:f;}var r=new Stack();for(;m>0;m--)for(t=f;t-->0;)if(!L.remove(m))r.add(m);return r;} ``` [Try it online.](https://tio.run/##dZFNTwMhEIbv/RXjDcwu2mqjFneN8WSyGpMejQekoNQFKszWNE1/e2XXjbZGIRDeZ/iYeZmLpcjns7etsQsfEOZJswZNzQ45wNERPIhEvQZ8VfC8QpVL3zhUAcjwogORDmQtYoQ7Ydx6AGDasBZSwX0rYefOykS8vE3xFxVKkOS/SEV5OrkZpCmiQCPhHhwUsK3yct3vAlscZzoN5NoHkl4FM6no2hamtFdmYrkuCBY3vq6VRONdZDqo90Y5uSJVZigt9RVONN8sRYBQOPUBUxTyjdDuQm7LY27znLYCC80xzxOhRpODigVl/VIRS2lgYjZLCx4UNsFB4JstbzNfNM91yrwvYOnNDGyyiEwxGPfy@ASCfvmTPEQy7EruxdmuGGap74PzXXmSdX0XjbNRdpql@S843oft4VF21jsO8ON5l3K3q7ecMfad9HQVUVnmG2SLVA/WjjgmSeviz69ehyBW7deSXywyETsuaGpfT2@2nw) **Explanation:** ``` import java.util.*; // Required import for Collections and Stack L->{ // Method with Integer-list as both parameter and return-type Integer m=0, // Max, starting at 0 f=0, // Max frequency, starting at 0 t; // Temp integer for(int i:L){ // Loop over the input-List m=i>m?i:m; // If the current item is larger than the max, set it as new max f=(t=Collections.frequency(L,i))>f?t:f;} // If the current frequency is larger than the max freq, set it as new max var r=new Stack(); // Result-List for(;m>0;m--) // Loop the maximum in the range [m,0) for(t=f;t-->0;) // Inner loop the frequency amount of times if(!L.remove(m))// Remove `m` from the input list // If we were unable to remove it: r.add(m); // Add it to the result-List return r;} // Return the result-List ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes Saved 1 byte thanks to [BWO](https://codegolf.stackexchange.com/users/48198/bwo). ``` S-§*oḣ▲(▲Ṡm# ``` [Try it online!](https://tio.run/##yygtzv7/P1j30HKt/Ic7Fj@atkkDiB/uXJCr/P///2hTHWMgNNIxjwUA "Husk – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~24~~ 21 bytes ``` X>:GS&Y'X>yGhS&Y'q-Y" ``` [Try it online!](https://tio.run/##y00syfn/P8LOyj1YLVI9wq7SPQPEKNSNVPqvGm0Yq4AMuFSjzTFEDHUUQCgWRcQiFkWNsY4CFMVCRUx1FIx0FEx0FECMWHQR09j/6CoA "MATL – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 14 bytes Input is a column vector, with `;` as separator. ``` llXQtn:yX>b-Y" ``` [Try it online!](https://tio.run/##y00syfn/PycnIrAkz6oywi5JN1Lp//9oU2sFI2sFE2sFIMM0FgA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8D8nJyKwJM@qMsIuSTdS6b@6rq56hEvI/2jDWK5ocyA2tFYAIQjLAkgZWytAEZBjaq1gZK1gYq0AYqDxTWMB) (this displays `--` after each output so that empty output can be identified). ### Explanation Consider input `[5; 2; 4; 5; 5]` as an example. ``` llXQ % Implicit input. Accumarray with sum. This counts occurrences % of each number, filling with zeros for numbers not present % STACK: [0; 1; 0; 1; 3] tn: % Duplicate, number of elements, range % STACK: [0; 1; 0; 1; 3], [1 2 3 4 5] yX> % Duplicate from below, maximum of array % STACK: [0; 1; 0; 1; 3], [1 2 3 4 5], 3 b % Bubble up % STACK: [1 2 3 4 5], 3, [0; 1; 0; 1; 3] - % Subtract, element-wise % STACK: [1 2 3 4 5], [3; 2; 3; 2; 0] Y" % Repelem (run-length decode). Implicit display % STACK: [1 1 1 2 2 3 3 3 4 4] ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes ``` .-*SeSQeSlM.g ``` [Try it here!](https://pyth.herokuapp.com/?code=.-%2aSeSQeSlM.g&input=%5B5%2C3%2C3%2C2%2C7%5D&debug=0) or [Check out a test suite!](https://pyth.herokuapp.com/?code=.-%2aSeSQeSlM.g&input=%5B5%2C3%2C3%2C2%2C7%5D&test_suite=1&test_suite_input=%5B1%5D%0A%5B7%5D%0A%5B1%2C+1%2C+1%5D%0A%5B1%2C+8%5D%0A%5B3%2C+3%2C+3%2C+3%5D%0A%5B5%2C+2%2C+4%2C+5%2C+2%5D%0A%5B5%2C+2%2C+4%2C+5%2C+5%5D&debug=0) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` F…·¹⌈θE⁻⌈Eθ№θκ№θιIι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzMvOae0OLMsNSgxLz1Vw1BHwTexIjO3NFejUFNTUyGgKDOvRMM3sUDDNzOvtFgDJgkSKdRRcM4vBUoDGdlAxUjcTDAvsbhEA8jStP7/PzraVEfBSEfBREcBxIiN/a9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Would have been 16 bytes if the integers had been non-negative instead of positive. Explanation: ``` θ First input ⌈ Maximum …·¹ Inclusive range starting at 1 F Loop over range θ First input E Loop over values θ First input κ Inner loop value № Count occurrences ⌈ Maximum θ First input ι Outer loop value № Count occurrences ⁻ Subtract E Map over implicit range ι Current value I Cast to string Implicitly print on separate lines ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~18~~ 17 bytes ``` ∊{⊂⍳⌈/⍵}~¨∘↓∘⍉⊣¨⌸ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CYb/04Dko46u6kddTY96Nz/q6dB/1Lu1tu7QikcdMx61TQaRvZ2PuhYDBXp2/AcrT6tOjH7U250I0tm7C4y2xtYqPOqdq1CcX1SiUJRaXJpTwlUClK8GSj3qXFgE0gVUaKWen63@qLtFPS0xM0cdorOolktDx1BTAQRKgIasAXLNYVxDBSMFYwUTBVMFMy5DBRCEqzJUsFCAqoKrUTDnMlaAQLBmCDSCQC5TIAlSZgSRAqkygQualiCphhhhomACAA "APL (Dyalog Classic) – Try It Online") uses `⎕io←1` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 211 bytes It's been a while since I programmed in Prolog. Can definitely be golfed further, but I have an exam to study for hahaha. ### Code ``` f(L,X):-max_list(L,M),f(L,M,[],X,M). f([],0,_,[],_). f(L,0,_,A,M):-f(L,M,[],A,M). f([],I,H,[I|A],M):-N is I-1,f(H,N,[],A,M). f([I|R],I,H,A,M):-append(H,R,S),f(S,I,[],[I|A],M). f([H|R],I,G,A,M):-f(R,I,[H|G],A,M). ``` [Try it online!](https://tio.run/##dY9BC4JAEIXv/Yo9KoyRlRTePKVQHewiiCxCqy2YLu6CHfzvNrtq2SGYw7w337zdEW1TNaUjOz4MhXWGxPadZ/6iFZcK5cUG7V4gzSBBtV4VFrYboNqhRp@NDHDqOx84@MIRhJBGfZAZ4kq4JJHjYm4I1x806uORHrNyIVh9RyqGm/7GDWeIz1FmJRxXTp/nYw2F/WmKHQbJFBXmSFpUeWnltexYS7uWK0YboXhTS0j1yXcm1MPa2BlG62w3A5JM/WHRu0B0/TrHhdwBmWphekC2QPZAdPPH92b/DQ "Prolog (SWI) – Try It Online") ### Ungolfed version ``` f(List, Result) :- max_list(List, MaxIndex), f(List, MaxIndex, [], Result, MaxIndex). f([], 0, _, [], _). f(List, 0, _, Acc, MaxIndex) :- f(List, MaxIndex, [], Acc, MaxIndex). f([], Index, History, [Index | Acc], MaxIndex) :- NewIndex is Index - 1, f(History, NewIndex, [], Acc, MaxIndex). f([Index | Remaining], Index, History, Acc, MaxIndex) :- append(History, Remaining, Result), f(Result, Index, [], [Index | Acc], MaxIndex). f([Head | Remaining], Index, History, Acc, MaxIndex) :- f(Remaining, Index, [Head | History], Acc, MaxIndex). ``` [Answer] ## Clojure, 94 bytes ``` #(for[F[(frequencies %)]i(range 1(+(apply max %)1))_(range(-(apply max(vals F))(or(F i)0)))]i) ``` [Answer] # C++, 234 bytes ``` #include<vector> #include<map> using X=std::vector<int>; X f(X x){int q,z;q=z=0;std::map<int,int>y;X o; for(auto i:x)++y[i];for(auto i:y)q=q>i.second?q:i.second; for(;++z<=y.rbegin()->first;)for(;y[z]++<q;)o.push_back(z);return o;} ``` (Newlines in the function body are for readability). The function takes and returns a vector of ints. It utilizes `std::map` for finding the max element of the input list and also for counting the occurrences of each distinct element. Explanation: ``` // necessary includes. Note that each of these is longer than whole Jelly program! #include <vector> #include <map> // this type occurs three times in the code using X = std::vector<int>; // The function X f (X x) { // initialize some variables int q, z; // q will hold the max count q = z = 0; std::map <int, int> y; // The map for sorting X o; // The output vector // Populate the map, effectively finding the max element and counts for all of them for (auto i : x) ++y[i]; // find the max count for (auto i : y) q = q > i.second ? q : i.second; // Populate the output vector // Iterate all possible values from 1 to the max element (which is the key at y.rbegin ()) // Note that z was initialized at 0, so we preincrement it when checking the condition for (; ++z <= y.rbegin ()->first;) // for each possible value, append the necessary quantity of it to the output for(; y[z]++ < q;) o.push_back (z); return o; } ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), 12 bytes ``` ::⌉┅¤:C¦⌉&¤D ``` [Try it online!](https://tio.run/##S0/MTPz/38rqUU/noymth5ZYOR9aBmSrHVri8j/1UdvE/9GmCsZAaKRgHgsA "Gaia – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 177 bytes Input and output are done through stdin and stdout. Both arrays are capped at 2^15 elements, but they could be as large as 2^99 elements. ``` f(j){int n=0,m=0,i=0,a[1<<15],b[1<<15]={0};for(;scanf("%i",&a[i])>0;i++)j=a[i],m=j>m?j:m,b[j-1]++;for(i=m;i--;)n=b[i]>n?b[i]:n;for(i=m;i--;)for(j=n-b[i];j--;)printf("%i ",i+1);} ``` With some formatting: ``` f(j){ int n=0, m=0, i=0, a[1<<15], b[1<<15]={0}; for(;scanf("%i",&a[i])>0;i++) j=a[i], m=j>m?j:m, b[j-1]++; for(i=m;i--;) n=b[i]>n?b[i]:n; for(i=m;i--;) for(j=n-b[i];j--;) printf("%i ",i+1); } ``` [Try it online!](https://tio.run/##VU7LCsMgELz3KyTQoqgQW0IhG5MPCTkYwbKC25L2FvLtqYZeyjLszs4@xuuH9/seeBQr0oeRrVXKwAw3mq4zzaTmX2HXeoPwXDi8vaPAqzNW6uJGnERfA0opoi0sX4h9GmKb8mrUZpLyWEObALUGQXbOYz0NJbX0LxYSLemiQSyd15KtHe9YpVAaAdtezCaHxAVbT4wFLuC07Q275biy@xc "C (gcc) – Try It Online") ]
[Question] [ In this question, we will only focus on losing weight by doing exercise, although there are still many ways to lose weight. Different sports burn different amount of calories. For example, playing billiards for an hour can burn 102 calories[[1]](http://calorielab.com/burned/?mo=se&gr=15&ti=sports&q=&wt=150&un=lb&kg=68), while playing basketball for 15 minutes can already burn 119 calories [[1]](http://calorielab.com/burned/?mo=se&gr=15&ti=sports&q=&wt=150&un=lb&kg=68), which make weight loss by playing basketball easier, at least from some perspectives. The exact way to weigh the easiness is by dividing the amount of calories burnt by the time needed, which gives us the easiness index (EI). For example, fencing for 15 minutes can burn 85 calories, which gets an EI of 85/15. You will be given a list in this format: ``` [["fencing",15,85],["billiards",60,102],["basketball",15,119]] ``` or other format that you want. Then, you will output the sports which have the highest EI. ### TL;DR Given a list of tuples `[name,value1,value2]` output the `name` where `value2/value1` is the highest. ### Constraints * You may **not** produce any real number that is not integer in the process. * You may **not** use any fraction built-in. ### Specifications (Specs) * If there is more than one name that satisfy the result, you may output any non-empty subset of them or any element of them. * The name will match the regex `/^[a-z]+$/`, meaning that it will only consist of lowercase Latin standard alphabet. * The list will not be empty. ### Testcase Input: ``` [["fencing",15,85],["billiards",60,102],["basketball",15,119]] ``` Output: ``` basketball ``` ### References 1. <http://calorielab.com/burned/> [Answer] ## Python 2, 51 bytes ``` lambda l:max((10**len(`l`)*a/b,s)for s,b,a in l)[1] ``` Does the obvious thing of finding the entry with the biggest ratio, but sidesteps the prohibition against floats by first multiplying the numerator by a huge input-dependent power of 10 before floor-dividing. I'll prove this coefficient is big enough to make floor-division act the same difference as non-floor division. **Claim:** If a1/b1 > a2/b2, then floor(Na1/b1) > floor(Na2/b2) for any N≥b1b2. **Proof:** Note that a1/b1 - a2/b2 is a multiple of 1/b1b2, so a1/b1 - a2/b2 > 0 implies that > > a1/b1 - a2/b2 > ≥ 1/b1b2 > > > Then, multiplying both sides by N, > > Na1/b1 - Na2/b2 > ≥ N/b1b2 ≥ 1 > > > So, since Na1/b1 and Na2/b2 differ by at least 1, their respective floors are distinct. ∎ Now, note that the product b1b2 has digit length at most their total digit length, which is less than the string length of the input. Since the input is in base 10, its suffices to use 10 to the power of its length `N=10**len(`l`)` to produce a number with more digits than it, guaranteeing the condition. [Answer] ## JavaScript (ES6), 43 bytes ``` a=>a.sort(([p,q,r],[s,t,u])=>q*u-r*t)[0][0] ``` Or alternatively ``` a=>a.sort((v,w)=>v[1]*w[2]-v[2]*w[1])[0][0] ``` Sort is of course overkill for this, but `reduce` would take 46 bytes: ``` a=>a.reduce((v,w)=>v[1]*w[2]-v[2]*w[1]?v:w)[0] ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` pG/*&X<) ``` All computed numbers are integer values. First, the product of the denominators is computed (this is an integer). This product is divided by each denominator (which gives an integer too). Each result is then multiplied by the corresponding numerator. This gives an integer value proportional to the original fraction. Input format is: numeric array with denominators, numeric array with numerators, cell array of strings with sport names: ``` [85, 102, 119] [15, 60, 15] {'fencing', 'billiards', 'basketball'} ``` If there are several minimizers the first one is output. [**Try it online!**](http://matl.tryitonline.net/#code=cEcvKiZYPCk&input=Wzg1LCAxMDIsIDExOV0KWzE1LCA2MCwgMTVdCnsnZmVuY2luZycsICdiaWxsaWFyZHMnLCAnYmFza2V0YmFsbCd9) ``` p % Take first input. Compute the product of its entries G/ % Divide by first input element-wise * % Take second input. Multiply by previous array element-wise &X< % Argmax ) % Take third input. Index into it using previous result. Display ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 42 bytes ``` :{bh.}a*g:?z:2aott. [D:[S:I:J]]tt:D*:I/:S. ``` [Try it online!](http://brachylog.tryitonline.net/#code=OntiaC59YSpnOj96OjJhb3R0LgpbRDpbUzpJOkpdXXR0OkQqOkkvOlMu&input=W1siZmVuY2luZyI6MTU6ODVdOlsiYmlsbGlhcmRzIjo2MDoxMDJdOlsiYmFza2V0YmFsbCI6MTU6MTE5XV0&args=Wg) `/` above is integer division because both `J*D` and `I` are integers (`D` is a multiple of `I` in fact). ### Explanation * Main predicate: `Input = [["string":mins:cals]:...]` ``` :{bh.}a* Multiply all mins in the Input together g:?z Zip that number with the Input :2a Apply predicate 2 to that zipped list ott. Sort the list of lists on the values of the first element of sublists, Output is the string of the last sublist ``` * Predicate 1: ``` [D:[S:I:J]] Input = [D:[S:I:J]] tt:D* Multiply J by D :I/ Divide the result by I :S. Output = [That number:S] ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 18 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` ⎕⊃⍨(⊢⍳⌈/)⎕×(∧/÷⊢)⎕ ``` Prompts for times, then for calories, then for activity names. `⎕` prompt (for times) `(∧/÷⊢)` LCM `∧/` of the times divided by `÷` the times `⊢` (so no floats) `⎕×` prompt (for calories) and multiply by them `(⊢⍳⌈/)` in that `⊢`, get the position `⍳` of the maximum value `⌈/` `⎕⊃⍨` prompt (for activities), then pick the *n*th. Example run: ``` ⎕⊃⍨(⊢⍳⌈/)⎕×(∧/÷⊢)⎕ ⎕: 15 60 15 ⎕: 85 102 119 ⎕: 'fencing' 'billiards' 'basketball' basketball ``` [Answer] ## [Retina](https://github.com/m-ender/retina), ~~64~~ 62 bytes Byte count assumes ISO 8859-1 encoding. ``` \d+ $* %`\G1 0 1 :$_: Ts`0p¶`0_`:.+?: +`(0+) \1 @$1 O` !`\w+$ ``` Input is one sport per line, with the format `value1 value2 name`. Output is one of the maximal results (if there's a tie it will give the one with the largest `value1` and if those are tied as well if will give the lexicographically larger `name`). Note that this is *super* slow (for the exact same reasons as [yesterday's Stack Exchange outage](http://stackstatus.net/post/147710624694/outage-postmortem-july-20-2016)). To make it run in a reasonable amount of time, you can add a `\b` in front of the `(0+)` (which won't affect the way it processes the input at all but severely limits the backtracking of that regex). I've done that in the test link below. [Try it online!](http://retina.tryitonline.net/#code=XGQrCiQqCiVgXEcxCjAKMQo6JF86ClRzYDBwwrZgMF9gOi4rPzoKK2BcYigwKykgXDEKQCQxIApPYAohYFx3KyQ&input=MTUgODUgZmVuY2luZwo2MCAxMDIgYmlsbGlhcmRzCjE1IDg2IGJhc2tldGJhbGw) [Answer] # Python 2, ~~55~~ 54 bytes ``` lambda x:sorted(x,lambda(S,N,D),(s,n,d):N*d-n*D)[0][0] ``` *Thanks to @xnor for golfing off 1 byte!* Test it on [Ideone](http://ideone.com/9Fk7pr). [Answer] ## Haskell ~~72~~ 70 bytes ``` import Data.List (n,(x,y))%(m,(a,b))=compare(x*b)$y*a fst.minimumBy(%) ``` Usage : ``` main=putStr$(fst.minimumBy(%))[("fencing",(15,85)),("billiards",(60,102)),("basketball",(15,119))] ``` [Answer] ## Mathematica, 46 bytes ``` Last/@MaximalBy[#,g=LCM@@First/@#;g#2/#&@@#&]& ``` The order of the tuples should be `{value1,value2,name}`. Returns the full set of all maximal results. I work around the use of fractions by multiplying the numerator by the LCM of all `value1`s before the division. [Answer] # Ruby, 72 bytes ``` e=0;while gets;n=$_.split;f=eval n[2]+"/"+n[1];m,e=n[0],f if f>e;end;p m ``` I really thought this would be shorter... Input is taken from STDIN in the format of `name time calories` Oh well, any help to shorten it is appreciated. [Answer] # R, ~~42~~ 40 bytes ``` function(v)v[which.max(v[,3]%/%v[,2]),1] ``` Takes input in the form of a data frame with column types of string (it also works with factors), numeric, numeric. * `%/%` is integer division. This is my first submission, let me know if it's within the rules. **Edit:** Turns out you don't need the braces to define a one-line function. [Answer] # C++14, 89 bytes Lambda function: ``` [](auto s,int*a,int*b,int l){int r=--l;while(l--)r=b[l]*a[r]>a[l]*b[r]?l:r;return s[r];}; ``` Ungolfed: ``` [](auto s,int*a,int*b,int l) { int r = --l; while(l--) r = b[l] * a[r] > a[l] * b[r] ? l : r; return s[r]; }; ``` Usage: ``` #include <iostream> int main() { const char* s[] = {"fencing", "billiards", "basketball"}; int a[] = {15,60,15}; int b[] = {85,102,119}; std::cout << [](auto s,int*a,int*b,int l){int r=--l;while(l--)r=b[l]*a[r]>a[l]*b[r]?l:r;return s[r];}(s,a,b,3); } ``` [Answer] # Haskell, 46 bytes ``` s(n,(x,y))=(divMod y x,n) g =snd.maximum.map s ``` **EDIT:** This solution doesn't work as pointed out by Damien this doesn't solve the problem. I'm searching a nice fix. [Answer] # VBA Excel, 109 bytes ``` Function A(B) R=1 For I=2 To B.Rows.Count If B(R,2)*B(I,3)>B(I,2)*B(R,3) Then R=I Next A=B(R,1) End Function ``` Invoke in spreadsheet cell referencing a table of activities and parameters: [![enter image description here](https://i.stack.imgur.com/KiDYr.jpg)](https://i.stack.imgur.com/KiDYr.jpg) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~6~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` P¹÷*ZQÏ ``` +1 byte to bugfix my divmod approach ([see this comment on another answer](https://codegolf.stackexchange.com/questions/86056/how-to-weight-loss-easily/195916#comment211685_86245)) by porting [*@LuisMendo*'s MATL answer](https://codegolf.stackexchange.com/a/86074/52210), so make sure to upvote him! Input is similar as his answer: three separated lists, being an integer-list of denominators; an integer-list of nominators; and a string-list of names. [Try it online](https://tio.run/##yy9OTMpM/f8/4NDOw9u1ogIP9///H21oqWNqGssVbaJjaASklBKVdJSSlGIB) or [verify some more test cases](https://tio.run/##yy9OTMpM/W/s5hL6PyDi8HatqMDD/f91/kdbmOoYGhjpGBpaxnJFG5rqmBnoGJoCmUppqXnJmXnpSjpKSZk5OZmJRSnFIHZicXZqSVJiTo4SSL2ljilIsYmOoRFITyJIBVjCwEDHCIiNjY3BPCBHx9gArCQpGagoJTUNSKZnZCrFAgA). **Explanation:** ``` P # Take the product of the (implicit) input-list of denominators # i.e. [85,102,119] → 1031730 ¹÷ # (Integer)-divide it by each of the denominators of the first input-list # i.e. 1031730 / [85,102,119] → [12138,10115,8670] * # Multiply each (at the same positions) by the (implicit) input-list of nominators # i.e. [12138,10115,8670] * [15,60,15] → [182070,606900,130050] Z # Get the maximum of this list (without popping the list itself) # i.e. [182070,606900,130050] → [182070,606900,130050] and 606900 Q # Check which values are equal to this maximum # i.e. [182070,606900,130050] and 606900 → [0,1,0] Ï # Only leave the strings of the (implicit) input-list of names at the truthy indices # i.e. ["fencing","billiards","basketball"] and [0,1,0] → ["billiards"] # (after which the result is output implicitly) ``` [Answer] # [PHP](https://php.net/), 98 bytes Used a simpler input format than the example, just like this: **fencing,15,85,billiards,60,102,basketball,15,119** ``` $s=explode(",",$argn);for($x=0;$s[$x];$x+=3){if($y<$e=$s[$x+2]/$s[$x+1]){$y=$e;$z=$s[$x];}}echo$z; ``` [Try it online!](https://tio.run/##TVDLboMwELzzFRbyISgbxZCkakRQb7n2A9ocDFnAxbUt22khUX691JAe6oM9j51ZyaY14@HFhJu6Ansj9RkXMcRAuW1UktfaLmhfsJy6N9qfctovi01yE/WCDgeKxSwvs9P6AdJTcqNDQTGn1@Ivcr9j1Wp6zcfpJfG7ivPoohz60AGEXpOcrNfkVcmBKKzQOW4HEhYTiwa5Jx6dF6oh38K3xLdIVkdSS96MNaoqGJDu4HkHpZBScHt28MQgZRmU3HXoSy7lNJGm@ygoOPMwsWFQa@1mug124OVFyn@BHQPDhXoI26mTRR69FS7AkGfgsetQQcZgz@CTW6E7bv0Uzlj0wb@4q6wwfnJDGMI3z6sCLG1ori9VBynsw/nRxgut3Lg6/gI "PHP – Try It Online") [Answer] # 8086 opcode, 24 bytes ``` 31db 50ac f6e7 92ac f6e3 39d0 ad72 058b 1.P.......9..r.. 5cfc 5ab2 58e2 ebc3 \.Z.X... org 100h mov si, input mov cx, 3 call f mov dx, ax mov ah, 9 int 0x21 ret align 2 input: db 15, 85 dw .fencing db 60, 102 dw .billiards db 15, 119 dw .basketball .fencing db 'fencing$' .billiards db 'billiards$' .basketball db 'basketball$' db 100h+2000-$ dup ? ; Easy to measure size f: ; bx (record) ; dx (mul result 1) ; ax (result name, pushed) ; ax (mul result 2) ; cx (count) ; si (input array) xor bx, bx .L: push ax lodsb mul bh ; nl*bh xchg ax, dx lodsb mul bl ; nh*bl cmp ax, dx lodsw jb .a mov bx, [si-4] pop dx db 0xB2 ; Skip 1 byte .a: pop ax loop .L ret ``` [Answer] # Java 8, 128 Bytes ``` String f(List<Object[]>l){return l.stream().max((x,y)->(int)x[2]*1000/(int)x[1]-(int)y[2]*1000/(int)y[1]).get()[0].toString();} ``` [Answer] ## Clojure, 63 bytes ``` #((last(sort(fn[[x a b][y c d]](-(* b c)(* a d)))%))0) ``` ]
[Question] [ Given a matrix `A`, we can say that it is "sorted" if each row and column of `A` is sorted (ascending left-to-right for rows and top-to-bottom for columns). Thus, this matrix is sorted: ``` [ 1 2 3 4 5 ] [ 2 2 3 4 5 ] [ 3 3 3 4 5 ] [ 4 4 4 4 5 ] [ 5 5 5 5 5 ] ``` However, this matrix is not sorted: ``` [ 1 2 3 4 5 ] [ 2 1 3 4 5 ] [ 3 3 3 4 5 ] [ 4 5 4 5 5 ] [ 5 5 5 5 5 ] ``` The second column (transpose of `[2, 1, 3, 5, 5]`) and fourth row (`[4, 5, 4, 5, 5]`) are not sorted in ascending order. Given a matrix (either as a 2D rectangular nested list or a string with consistent, distinct delimiters between rows and between values) and optionally the width and/or height of the matrix, output a sorted matrix (in the same format) with the same dimensions and containing the same values as the input matrix. The values in the matrix will always be in the inclusive range `[-128, 127]` (8-bit signed two's complement integers). There is no limit on the dimensions of the input matrix. ## Examples Because there are multiple valid outputs for each input, these are possible outputs. Any output that fulfills the conditions is valid. The examples are given with Python list notation. ``` [[0, -29]] -> [[-29, 0]] [[-36, -18, 0], [8, 99, 112], [14, 6, -12]] -> [[-36, -18, 0], [-12, 6, 14], [8, 99, 112]] [[-20, -102, -41, -57, -73, 58], [49, 82, 60, -53, 58, 60], [-32, -127, -23, -70, -46, -108], [-56, -15, 98, -90, 73, -67], [97, 74, 59, 126, -7, 46], [-101, 42, -39, -52, 89, 29]] -> [[-127, -108, -101, -70, -53, -32], [-102, -90, -67, -52, -23, 42], [-73, -57, -46, -20, 46, 59], [-56, -41, -15, 49, 60, 74], [-39, -7, 58, 60, 82, 97], [29, 58, 73, 89, 98, 126]] [[23, 82, 94, 7, -39, 70, -31, -120], [-13, 78, -70, 28, -10, 30, 101, 48], [60, -111, 32, 93, 91, 77, -27, 7], [-37, -41, -8, 80, 102, 18, -16, -48], [97, -14, -102, -53, 108, -92, -83, 108], [-67, -121, -15, -9, 91, -89, -127, -109], [-127, -103, -48, -2, -106, 3, -114, 97], [28, -78, -40, 52, 39, 115, -88, 10]] -> [[-127, -127, -120, -109, -92, -70, -40, -14], [-121, -114, -106, -89, -67, -39, -13, 7], [-111, -103, -88, -53, -37, -10, 10, 32], [-102, -83, -48, -31, -9, 18, 39, 77], [-78, -48, -27, -8, 23, 48, 78, 91], [-41, -16, -2, 28, 52, 80, 93, 97], [-15, 3, 28, 60, 82, 94, 101, 108], [7, 30, 70, 91, 97, 102, 108, 115]] [[85, 90, -65, -38, -58, -71, 123, -83, 44], [55, -34, 21, 103, -10, 59, -109, 30, -41], [108, -106, -90, 74, 117, 15, -63, 94, -37], [43, -118, -126, -45, 77, -62, 22, 76, 9], [56, 31, 58, 51, -64, 125, -48, -123, -108], [77, -53, -61, 99, -16, -21, -98, -50, 60], [127, -113, -9, 33, -6, -102, -47, -122, 31], [-59, -23, 0, 21, 14, 61, 83, 47, -6], [97, -120, -111, 113, -68, -128, -81, 68, 88]] -> [[-128, -126, -122, -113, -106, -81, -62, -47, -16], [-123, -120, -111, -102, -71, -61, -45, -10, 21], [-118, -109, -98, -68, -59, -41, -9, 21, 44], [-108, -90, -65, -58, -38, -6, 22, 47, 60], [-83, -64, -53, -37, -6, 30, 51, 61, 77], [-63, -50, -34, 0, 31, 55, 68, 83, 94], [-48, -23, 9, 31, 56, 74, 85, 97, 108], [-21, 14, 33, 58, 76, 88, 99, 113, 123], [15, 43, 59, 77, 90, 103, 117, 125, 127]] [[-80, -42, 1, 126, -42, -34, 81, 73, 6, 9, 72], [-98, -98, -82, 63, -16, -116, 29, 61, 119, 20, 19], [-99, -70, 41, 44, 117, 61, 89, -117, 92, -3, -49], [18, 122, 126, 84, 79, 114, -61, 45, 80, 109, -107], [-77, 73, -62, -58, -25, -24, 126, -14, -13, -90, -60], [84, 1, 95, 21, -13, 26, 75, 78, -36, -76, -91], [54, -58, 79, -128, 63, 119, 79, 106, 103, 125, 98], [126, 37, -77, -15, -57, 63, 22, -98, 93, 67, 41], [93, -45, -91, 34, 29, -38, -103, 109, -92, 6, -115], [32, -112, -29, -65, 61, 20, 80, -41, -68, 28, 25], [56, -112, 47, -88, 56, -35, -26, 13, 122, 27, -70], [108, -69, -42, 24, 94, -20, -46, 90, -98, 112, 32]] -> [[-128, -117, -115, -107, -98, -91, -77, -62, -45, -29, -3], [-116, -112, -103, -98, -90, -76, -61, -42, -26, 1, 21], [-112, -99, -98, -88, -70, -60, -42, -25, 1, 22, 34], [-98, -92, -82, -70, -58, -42, -24, 6, 24, 37, 61], [-91, -80, -69, -58, -41, -20, 6, 25, 41, 61, 73], [-77, -68, -57, -38, -16, 9, 26, 41, 61, 75, 81], [-65, -49, -36, -15, 13, 27, 44, 63, 78, 84, 93], [-46, -35, -14, 18, 28, 45, 63, 79, 84, 94, 108], [-34, -13, 19, 29, 47, 63, 79, 89, 95, 109, 117], [-13, 20, 29, 54, 67, 79, 90, 98, 109, 119, 122], [20, 32, 56, 72, 80, 92, 103, 112, 119, 125, 126], [32, 56, 73, 80, 93, 106, 114, 122, 126, 126, 126]] [[53, 109, -41, 66, 63, -108, -24, 85, 28, 57, -11, -94, -16], [-28, -113, 58, 115, -28, -124, 71, -109, -65, 45, 75, 97, 107], [124, 23, 101, 112, -64, 19, 21, 34, 6, -2, -70, -92, 122], [19, 94, 80, -105, -3, -125, -2, 44, -24, 41, -30, 64, 32], [36, -44, 59, -28, -36, -11, 111, -64, 78, 120, 1, 102, 49], [-128, 67, 17, -9, -64, -86, 117, 7, 118, 7, -11, -82, 124], [5, -36, 22, 98, -78, -33, 100, 92, -55, 125, -28, 24, -6], [97, 31, -106, -15, 8, 80, -86, -107, -105, -5, -71, 76, 124], [-83, 24, -116, 66, 82, -32, -19, 111, -84, -77, -14, 67, -70], [77, -111, -101, -91, -23, 36, 24, -33, 13, -90, -9, 32, -54], [51, -31, 125, -25, -61, 5, 71, -81, -3, -39, 109, -17, -97], [61, -46, -122, 76, 13, -101, 24, 97, 39, -29, -22, -3, -116], [56, 0, -4, 71, -116, 115, 79, -83, 74, 44, -77, 42, -30], [-72, 45, -109, -82, 43, 38, -117, 1, 69, -66, -18, 108, 8]] -> [[-128, -125, -122, -116, -109, -105, -92, -83, -71, -55, -32, -24, -9], [-124, -117, -116, -109, -105, -91, -82, -70, -54, -31, -23, -9, 5], [-116, -113, -108, -101, -90, -82, -70, -46, -30, -22, -6, 5, 22], [-111, -107, -101, -86, -81, -66, -44, -30, -19, -5, 6, 23, 36], [-106, -97, -86, -78, -65, -41, -29, -18, -4, 7, 24, 38, 51], [-94, -84, -77, -64, -39, -28, -17, -3, 7, 24, 39, 53, 66], [-83, -77, -64, -36, -28, -16, -3, 8, 24, 41, 56, 67, 76], [-72, -64, -36, -28, -15, -3, 8, 24, 42, 57, 67, 76, 85], [-61, -33, -28, -14, -2, 13, 28, 43, 58, 69, 77, 92, 100], [-33, -25, -11, -2, 13, 31, 44, 59, 71, 78, 94, 101, 109], [-24, -11, 0, 17, 32, 44, 61, 71, 79, 97, 102, 111, 115], [-11, 1, 19, 32, 45, 63, 71, 80, 97, 107, 111, 117, 122], [1, 19, 34, 45, 64, 74, 80, 97, 108, 112, 118, 124, 124], [21, 36, 49, 66, 75, 82, 98, 109, 115, 120, 124, 125, 125]] [[47, -58, 7, -88, 126, -87, 103, 125, 83, 32, 116, 107, -92, -96, 110, -102], [-75, -81, 53, -93, 91, -5, -4, 104, 88, -73, -114, -113, 126, 78, -114, -3], [125, -68, -88, -17, 1, 53, -124, -59, -19, 87, -60, 55, -30, -6, 39, 37], [-38, -123, 125, 119, -43, 11, -25, -89, -57, 112, 123, 9, -76, -125, 118, 68], [-119, -97, -42, 73, 80, 108, -96, -54, -110, 115, -58, -67, -9, 94, 71, -56], [-25, 109, -51, 71, 61, 12, 122, -99, -16, -87, -127, -76, 46, 102, 52, 114], [97, 26, -112, 49, -44, -26, -93, -119, 21, 101, 83, -112, 14, 41, 120, 37], [90, 95, 89, 73, 51, -33, 3, -125, -106, -83, -5, -26, 33, -119, -74, 41], [9, -81, 116, -124, -8, -15, 65, 104, 41, -92, 2, 51, 33, 115, -47, 30], [87, -127, 121, 42, 33, -22, 28, -74, 26, 55, 126, -70, 0, -63, -40, -51], [-117, 79, -113, -4, 78, -33, -54, -40, -1, -48, 60, 91, 119, 117, -75, 114], [7, 102, 6, 77, -112, -128, 34, 112, -82, -17, -120, -96, -101, -79, -27, -84], [-74, -77, 67, -78, -72, 80, 59, 115, -76, -7, 66, -28, 120, 117, 56, -46], [80, 42, -121, -5, 73, -82, -115, -72, 10, -120, -26, -82, -22, 110, -7, -119], [10, -88, 39, 92, -16, 58, -40, 79, 116, 75, 96, -102, 4, 93, 46, -95], [20, -61, 110, 18, -103, -87, -67, -26, -74, -22, 1, -106, -81, -20, 10, 87]] -> [[-128, -127, -125, -124, -120, -117, -112, -102, -95, -87, -81, -74, -59, -43, -26, -7], [-127, -125, -123, -119, -115, -112, -102, -93, -87, -79, -74, -58, -42, -25, -7, 6], [-124, -121, -119, -114, -112, -101, -93, -87, -78, -73, -58, -40, -25, -6, 7, 26], [-120, -119, -114, -110, -99, -92, -84, -77, -72, -57, -40, -22, -5, 7, 28, 41], [-119, -113, -106, -97, -92, -83, -76, -72, -56, -40, -22, -5, 9, 30, 42, 55], [-113, -106, -96, -89, -82, -76, -70, -54, -38, -22, -5, 9, 32, 42, 56, 73], [-103, -96, -88, -82, -76, -68, -54, -33, -20, -4, 10, 33, 46, 58, 73, 80], [-96, -88, -82, -75, -67, -51, -33, -19, -4, 10, 33, 46, 59, 73, 83, 91], [-88, -81, -75, -67, -51, -30, -17, -3, 10, 33, 47, 60, 75, 83, 92, 102], [-81, -74, -63, -48, -28, -17, -1, 11, 34, 49, 61, 77, 87, 93, 103, 110], [-74, -61, -47, -27, -16, 0, 12, 37, 51, 65, 78, 87, 94, 104, 110, 115], [-60, -46, -26, -16, 1, 14, 37, 51, 66, 78, 87, 95, 104, 112, 115, 117], [-44, -26, -15, 1, 18, 39, 52, 67, 79, 88, 96, 107, 112, 116, 118, 120], [-26, -9, 2, 20, 39, 53, 68, 79, 89, 97, 108, 114, 116, 119, 121, 125], [-8, 3, 21, 41, 53, 71, 80, 90, 101, 109, 114, 116, 119, 122, 125, 126], [4, 26, 41, 55, 71, 80, 91, 102, 110, 115, 117, 120, 123, 125, 126, 126]] [[-88, -62, -59, -18, 118, -13, -93, 75, 44, 67, -122, -1, 117, -121, 118, 13, -33, 44], [-4, -75, 95, 25, 9, -104, 6, 79, -110, 3, -108, 117, 96, 113, 69, 55, 75, -95], [-69, 11, 87, -78, -18, -17, -52, 6, 88, 31, 39, 45, 61, -75, -83, 117, 85, -3], [-27, 83, -86, -69, -29, -15, 62, -90, -127, 53, -71, 77, -95, -86, -20, 69, 103, -111], [3, -6, -70, -121, -58, -72, 88, 105, 68, -31, 86, -28, 69, 78, 13, 88, 19, 75], [69, 73, 116, -2, -93, 15, 74, 58, 98, -100, -54, 95, 47, -126, -71, 63, 84, 113], [110, -42, -33, -87, 109, 86, -75, 25, 83, -25, -76, 84, -42, -57, -93, -9, -90, 3], [-100, 36, -83, 10, -85, 88, -15, 107, -76, -37, 109, 79, -120, 118, -60, 113, -124, -15], [123, 122, -94, 14, -16, 118, -57, -111, 80, 62, 56, 66, 27, -44, -53, -13, 94, -28], [116, -67, 8, -70, -54, -1, 53, 40, -78, 15, -121, -30, -125, -16, -74, 119, 97, 43], [-24, 109, -72, 16, 55, -51, -87, 46, -62, 69, -106, -49, -112, 71, -55, 104, -110, 62], [67, 13, -75, 106, -35, -54, 15, -104, 34, 93, 39, -126, -29, 61, 29, 4, 70, -28], [27, -89, -15, -32, -82, -72, 53, -22, -23, 49, -16, 76, -25, 31, 115, -88, -57, -97], [1, 29, 54, 88, 86, 77, -58, 100, -125, 117, 102, 41, 99, 115, 24, -16, -99, -116], [-85, -47, -108, 26, 18, -107, -88, 110, 27, -118, 88, -122, -85, -94, -33, 51, 40, 77], [-3, 52, -20, 12, 117, 101, 34, -8, -100, -23, 45, 83, -88, -90, -47, 70, 29, -111], [26, -68, 7, 38, -118, -53, -79, -48, 41, -88, 35, 86, 66, 24, 37, 72, -66, -77]] -> [[-127, -126, -125, -122, -121, -112, -108, -100, -93, -88, -83, -75, -68, -54, -37, -25, -15, 4], [-126, -125, -122, -120, -111, -108, -100, -93, -88, -83, -75, -67, -54, -35, -24, -15, 6, 18], [-124, -121, -118, -111, -107, -99, -93, -88, -82, -74, -66, -54, -33, -23, -13, 6, 19, 34], [-121, -118, -111, -106, -97, -90, -87, -79, -72, -62, -53, -33, -23, -13, 7, 24, 34, 45], [-116, -110, -104, -95, -90, -87, -78, -72, -62, -53, -33, -22, -9, 8, 24, 35, 45, 58], [-110, -104, -95, -90, -86, -78, -72, -60, -52, -32, -20, -8, 9, 25, 36, 46, 61, 69], [-100, -94, -89, -86, -77, -71, -59, -51, -31, -20, -6, 10, 25, 37, 47, 61, 69, 75], [-94, -88, -85, -76, -71, -58, -49, -30, -18, -4, 11, 26, 38, 49, 62, 69, 76, 83], [-88, -85, -76, -70, -58, -48, -29, -18, -3, 12, 26, 39, 51, 62, 69, 77, 84, 88], [-85, -75, -70, -57, -47, -29, -17, -3, 13, 27, 39, 52, 62, 70, 77, 84, 88, 96], [-75, -69, -57, -47, -28, -16, -2, 13, 27, 40, 53, 63, 70, 77, 85, 88, 97, 104], [-69, -57, -44, -28, -16, -1, 13, 27, 40, 53, 66, 71, 78, 86, 88, 98, 105, 110], [-55, -42, -28, -16, -1, 14, 29, 41, 53, 66, 72, 79, 86, 88, 99, 106, 110, 115], [-42, -27, -16, 1, 15, 29, 41, 54, 67, 73, 79, 86, 93, 100, 107, 113, 116, 117], [-25, -15, 3, 15, 29, 43, 55, 67, 74, 80, 86, 94, 101, 109, 113, 116, 117, 118], [-15, 3, 15, 31, 44, 55, 68, 75, 83, 87, 95, 102, 109, 113, 117, 117, 118, 119], [3, 16, 31, 44, 56, 69, 75, 83, 88, 95, 103, 109, 115, 117, 118, 118, 122, 123]] [[84, 18, -122, 74, -47, 17, -69, 121, -79, 110, 10, 122, 84, 19, 77, -57, 25, 87, -42], [95, 89, 10, -1, -24, -93, -26, -39, 11, -15, 47, 23, 114, 36, 121, -87, 106, 120, -86], [48, 66, 65, 28, 74, -22, -67, 77, -77, 19, 88, -24, -88, 85, -34, 13, 103, -102, 86], [108, -17, -122, -13, 63, 61, -56, 24, -48, -3, -85, -57, 11, -52, -26, -24, 48, 100, 18], [-91, -126, 124, 5, -118, 93, 94, -100, -24, 15, 77, -43, 64, 51, 64, 7, -22, -47, 79], [98, 80, 117, -19, -55, -95, -35, -48, -56, -122, -120, 52, 54, 37, -101, -38, -35, 101, -6], [72, 68, 26, -79, -1, 25, -3, -40, 2, 56, 119, 17, -95, 83, -94, -79, -88, -110, 85], [55, 39, 75, 127, 110, 0, 56, -1, 39, 116, 44, 120, -113, 81, 113, 10, 78, 114, -79], [103, 121, 78, -121, -17, 33, 117, 110, -26, 2, -79, 27, -117, 62, -27, -17, -20, 104, 115], [-11, 67, 76, 62, -14, 78, -94, -8, -71, 15, 77, 98, 127, 109, 61, 33, -51, 65, -103], [-91, 97, 83, -61, 22, -31, 20, -119, 40, -48, -3, 34, -70, 23, -80, -73, 5, 23, -102], [109, 78, 124, 118, -39, -3, -114, -50, 0, 79, -68, -34, -96, 104, -120, 41, 2, 108, -17], [-90, -30, -25, -29, -52, -37, -49, 20, 91, -48, -91, 80, -117, -6, -88, -68, 69, 103, 118], [-79, -118, -122, -112, 71, -4, 28, 78, -77, -33, 10, 21, -125, 69, -88, 18, 99, 11, -127], [-124, -53, -4, 80, -94, -44, -124, 94, 97, -55, -89, -78, -37, -38, -40, -11, -116, 84, 18], [44, 32, -44, 76, -101, 85, -67, 69, -4, 20, -89, -103, 117, 18, -121, 84, 18, -91, -106], [107, 58, 6, -72, 112, 96, 39, 77, -4, 104, 60, 112, 39, -102, -4, -11, 80, 36, -117], [96, -79, 119, -65, 80, -35, -60, 4, -63, 92, 76, -46, -2, 59, -86, -105, -76, 106, -102], [-88, -89, 69, -5, 63, 75, -59, -93, 101, 33, 64, 114, -126, -106, 33, 113, 50, 71, 82], [-94, 9, -3, 11, 115, -121, 111, -34, -11, 96, -34, 51, -44, -56, -20, -14, 1, 49, 100]] -> [[-127, -126, -125, -122, -121, -119, -116, -105, -101, -93, -88, -79, -71, -57, -48, -38, -26, -14, -3], [-126, -124, -122, -121, -118, -114, -103, -100, -93, -88, -79, -70, -56, -48, -37, -26, -14, -3, 10], [-124, -122, -121, -118, -113, -103, -96, -91, -88, -79, -69, -56, -47, -37, -25, -13, -3, 10, 19], [-122, -120, -117, -112, -102, -95, -91, -88, -79, -68, -56, -47, -35, -24, -11, -2, 10, 19, 33], [-120, -117, -110, -102, -95, -91, -88, -79, -68, -55, -46, -35, -24, -11, -1, 10, 20, 33, 48], [-117, -106, -102, -94, -91, -87, -79, -67, -55, -44, -35, -24, -11, -1, 11, 20, 33, 48, 62], [-106, -102, -94, -90, -86, -78, -67, -53, -44, -34, -24, -11, -1, 11, 20, 33, 49, 62, 69], [-101, -94, -89, -86, -77, -65, -52, -44, -34, -22, -8, 0, 11, 21, 34, 50, 63, 71, 77], [-94, -89, -85, -77, -63, -52, -43, -34, -22, -6, 0, 11, 22, 36, 51, 63, 71, 77, 80], [-89, -80, -76, -61, -51, -42, -34, -20, -6, 1, 13, 23, 36, 51, 64, 72, 78, 81, 86], [-79, -73, -60, -50, -40, -33, -20, -5, 2, 15, 23, 37, 52, 64, 74, 78, 82, 87, 96], [-72, -59, -49, -40, -31, -19, -4, 2, 15, 23, 39, 54, 64, 74, 78, 83, 88, 96, 101], [-57, -48, -39, -30, -17, -4, 2, 17, 24, 39, 55, 65, 75, 78, 83, 89, 97, 103, 107], [-48, -39, -29, -17, -4, 4, 17, 25, 39, 56, 65, 75, 78, 84, 91, 97, 103, 108, 111], [-38, -27, -17, -4, 5, 18, 25, 39, 56, 66, 76, 79, 84, 92, 98, 103, 108, 112, 114], [-26, -17, -4, 5, 18, 26, 40, 58, 67, 76, 79, 84, 93, 98, 104, 109, 112, 115, 117], [-15, -3, 6, 18, 27, 41, 59, 68, 76, 80, 84, 94, 99, 104, 109, 113, 115, 118, 120], [-3, 7, 18, 28, 44, 60, 69, 77, 80, 85, 94, 100, 104, 110, 113, 116, 118, 120, 121], [9, 18, 28, 44, 61, 69, 77, 80, 85, 95, 100, 106, 110, 114, 117, 119, 121, 122, 124], [18, 32, 47, 61, 69, 77, 80, 85, 96, 101, 106, 110, 114, 117, 119, 121, 124, 127, 127]] ``` Huge thanks to Sp3000 for helping me out with this challenge in chat [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~8~~ ~~6~~ 5 bytes *Thanks to randomra for saving 3 bytes.* ``` O#`.+ ``` Input format is a bit awkward. Both the delimiter within rows and between rows needs to consist of line-terminating characters (i.e. those not matched by `.`). E.g. you could use single linefeeds within rows and double linefeeds between rows. Output is printed in the same format. [Try it online!](http://retina.tryitonline.net/#code=TyNgLis&input=LTEyOAotMTI4Ci0xMTgKLTEwOAotNDAKLTEzCgotMTE5Ci0xMTEKLTEwOAotNDAKLTEyCjExCgotMTA5Ci02MQotMzUKLTEyCjExCjUyCgotNDgKLTE1Ci04CjE5Cjc0CjgzCgotMTQKLTEKMjgKNzQKODUKMTEyCgoxCjMyCjc2Cjg4CjEyNQoxMjc) ### Explanation The perfect challenge to show off Retina's latest addition: sort stages! Sort stages work as follows: the regex is matched against the entire string. The matches are then the things that are being sorted, whereas everything around them is treated as "list delimiters" and left unchanged. This challenge can be solved if we treat the input as a flat list, sort that and reshape it into the original matrix form. That's exactly how sort stages work, except there are no explicit steps for flattening and reshaping - Retina just ignores the 2D structure altogether. As for this code in particular, the regex is `.+` which simply matches all runs of non-linefeed characters, which is all the numbers due to the input format. By default, the matches are sorted lexicographically, but the `#` option tells Retina to sort them numerically (by the first signed integer that appears in the match). For three additional bytes, this could support any input format whatsoever, by using the regex `-?\d+`. [Answer] # Pyth, ~~6~~ 5 bytes *1 byte thanks to DenkerAffe* ``` cSsQE ``` [Demonstration](https://pyth.herokuapp.com/?code=cSsQE&input=%5B%5B-122%2C+-119%2C+-105%2C+-11%2C+5%5D%2C+%5B-113%2C+-63%2C+-6%2C+39%2C+1%5D%2C+%5B-34%2C+13%2C+47%2C+76%2C+0%5D%2C+%5B37%2C+66%2C+93%2C+126%2C+1%5D%5D%0A5&debug=0) Input is the matrix, followed by its width. To sort the matrix, I simply flatten it into a list, sort the list, and chop it into a matrix again. Since every subsequence of a sorted list is sorted, this results in a sorted matrix. [Answer] # Jelly, 3 bytes ``` FṢs ``` Takes matrix and width as left and right arguments. [Try it online!](http://jelly.tryitonline.net/#code=RuG5onM&input=&args=W1s1LCAyLCA4LCAxMV0sIFs5LCAxLCA3LCA2XSwgWzEyLCA0LCAzLCAxMF1d+NA) ### How it works ``` FṢs Main link. Arguments: M (matrix), w (width) F Flatten M. Ṣ Sort. s Split into rows of width w. ``` [Answer] ## Python, 43 bytes ``` lambda M:eval("map(sorted,zip(*"*2+"M))))") ``` The interesting question is how to apply `mapsort-transpose` twice. The shortest I found was to `eval` a string that has it twice. Compare some alternatives: ``` lambda M:eval("map(sorted,zip(*"*2+"M))))") lambda M:map(sorted,zip(*map(sorted,zip(*M)))) s="map(sorted,zip(*%s))";lambda M:eval(s%s%M) g=lambda M:map(sorted,zip(*M));lambda M:g(g(M)) f=lambda M,n=-1:n*M or f(map(sorted,zip(*M)),n+1) def f(M):exec"M=map(sorted,zip(*M));"*2;return M ``` (The second and fourth can be shortened by 1 byte by aliasing `sorted`, but it's not enough.) An alternative approach of converting to 1D, sorting, and reshaping to 2D, is very close, at 44 bytes. The width `w` is taken as an input. ``` lambda M,w:zip(*[iter(sorted(sum(M,[])))]*w) ``` [Answer] ## JavaScript (ES6), 67 bytes ``` a=>a.map(b=>c.splice(0,b.length),c=[].concat(...a).sort((d,e)=>d-e)) ``` Port of @isaacg's Pyth answer. [Answer] # Pyth, 7 bytes ``` CSMCSMQ ``` [Try it here!](http://pyth.herokuapp.com/?code=CSMCSMQ&input=%5B%5B-122%2C+-119%2C+-105%2C+-11%5D%2C+%5B-113%2C+-63%2C+-6%2C+39%5D%2C+%5B-34%2C+13%2C+47%2C+76%5D%2C+%5B37%2C+66%2C+93%2C+126%5D%5D&debug=0) First we sort all rows of the matrix, transpose the result, sort all rows again and transpose it back. [Answer] # CJam, 8 bytes ``` {:$z:$z} ``` [Try it online!](http://cjam.tryitonline.net/#code=W1stMTIyIC0xMTkgLTEwNSAtMTFdIFstMTEzIC02MyAtNiAzOV0gWy0zNCAxMyA0NyA3Nl1dCgp7OiR6OiR6fQoKfnA&input=) An unnamed block which expects a matrix on the stack and leaves the sorted matrix on the stack. Also just sorts each row (`:$`), transposes the result (`z`), sorts again and transposes it back. [Answer] # Octave, 19 bytes Isn't nice when two programs fulfill the requirement ``` @(a)sort(sort(a')') % or @(a)sort(sort(a)')' ``` Anonymous function that transposes the matrix twice to get the original dimensions back. I'm going to claim that this will be the shortest entry in a non-golfing language. Let's see if anyone proves me wrong :) [Answer] # Mathematica, 26 bytes ``` Nest[Sort@*Transpose,#,2]& ``` Function names are long. That sucks. [Answer] # [RETURN](https://github.com/molarmanful/RETURN), 10 bytes ``` [{␇␌}␅␆␎␉] ``` `[Try it here.](http://molarmanful.github.io/RETURN/)` Anonymous lambda that leaves result on stack. Usage: ``` ""{1 2 3 4}""{1 3 4 2}""{4 1 2 3}""{3 1 2 4}[{␇␌}␅␆␎␉]! ``` # Explanation ``` [ ] lambda {␇␌} push matrix width to stack2 ␅␆ flatten, sort ␎␉ chunk by matrix width (popped from stack2) ``` [Answer] # APL, ~~11~~ 9 bytes ``` ⍴⍴⊂∘⍋∘,⌷, ``` Hooks of three functions composed together :). example: ``` (⍴⍴⊂∘⍋∘,⌷,) 2 2⍴10 5 4 8 4 5 8 10 ``` [Answer] ## Python 3, 52 bytes A solution using numpy ``` from numpy import* lambda s:sort(sort(array(s)).T).T ``` *(`sort(s,None)` is longer as we need to reshape after sort)* ## Results ``` >>> f([[-5, -4, -3, -2, -1, 0], [-60, -70, -80, -9, 100, 110], [5, 4, 3, 2, 1, 0], [6, 7, 8, 9, 10, 11]]) array([[-80, -70, -60, -9, -1, 0], [ -5, -4, -3, -2, 4, 5], [ 0, 1, 2, 3, 10, 11], [ 6, 7, 8, 9, 100, 110]]) ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 4 bytes ``` S!S! ``` [Try it online!](http://matl.tryitonline.net/#code=UyFT&input=W1stMTIyLCAtMTE5LCAtMTA1LCAtMTFdOyBbLTExMywgLTYzLCAtNiwgMzldOyBbLTM0LCAxMywgNDcsIDc2XTsgWzM3LCA2NiwgOTMsIDEyNl1d) This just sorts (`S`) column-wise (sorting the contents of each column seperately) then transposes (`!`) and sorts the input again, quite straightforward. This program needs a semicolon (`;`) instead of a comma (`,`) as delimiter of rows. [Answer] # Ruby, 42 bytes ``` (m,w)->{m.flatten.sort.each_slice(w).to_a} ``` Arguments are the matrix and its width. It works exactly like it reads :) [Answer] # CJam, 6 bytes ``` {e_$/} ``` This is a code block (unnamed function) that expects the width and matrix on the stack, pops them and pushes the sorted matrix in return. [Try it online!](http://cjam.tryitonline.net/#code=cX4Ke2VfJC99Cn5w&input=MwpbWy0zNiAtMTggMF0gWzggOTkgMTEyXSBbMTQgNiAtMTJdXQ) ### How it works ``` e# STACK: w (width), M (matrix) e# e_ e# Flatten M. $ e# Sort the resulting, flat array. / e# Split the sorted array into rows of length w. ``` [Answer] # Perl 6, ~~28~~ 25 bytes ``` {.flat.sort.rotor(+.[0])} ``` This takes a list of lists (not arrays). [Answer] # C, 39 Bytes ``` f(x,m,n){qsort(x,m*n,4,"YZZ+QQQÃ");} ``` If the out-of-range char can't show use this instead, though longer ``` f(x,m,n){qsort(x,m*n,4,"YZ\x8B\2Z+\2QQQ\xC3");} ``` Usage: ``` int m, n, i, j; scanf ("%d%d", &m, &n); int arr[m][n]; for (i=0; i<m; i++) { for (j=0; j<n; j++) { scanf("%d", &arr[i][j]); } } f(arr,m,n); for (i=0; i<m; i++) { for (j=0; j<n; j++) { printf("%d ", arr[i][j]); } puts(""); } ``` Text's disassembler: `00000000: 59 POP ECX 00000001: 5A POP EDX 00000002: 8B02 MOV EAX,[EDX] 00000004: 5A POP EDX 00000005: 2B02 SUB EAX,[EDX] 00000007: 51 PUSH ECX 00000008: 51 PUSH ECX 00000009: 51 PUSH ECX 0000000A: C3 RETN` [Answer] # [Uiua](https://uiua.org), 7 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` ⍜♭(⊏⍏.) ``` [Try it!](https://uiua.org/pad?src=0_2_0__ZiDihpAg4o2c4pmtKOKKj-KNjy4pCgpmW1swIDMgOSAzIDldCiAgWzcgNCAzIDggNV0KICBbNCA0IDEgwq82IDNdCiAgW8KvOSAyIDAgNCAzXQogIFs4IDMgMCAyIDNdXQo=) ``` ⍜♭(⊏⍏.) ⍜♭( ) # under deshape (apply a function to a flattened array, but keep the shape) ⊏⍏. # sort ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` mÍyÍ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=bc15zQ&input=WwpbLTM2IC0xOCAgIDBdClsgIDggIDk5IDExMl0KWyAxNCAgNiAgLTEyXQpdLVE) [Answer] **Clojure, 39 bytes** ``` (fn[M w](partition w(sort(flatten M)))) ``` `M` is a nested list (the matrix) and `w` is its width (number of columns). ``` (f [[1 3 2 3][5 1 3 7][4 3 6 5]] 4) ((1 1 2 3) (3 3 3 4) (5 5 6 7)) ``` ]
[Question] [ Generate a 7 by 7 grid, filled with random numbers. However, in cells with an odd row and column number (starting at 0), you must use the sum of the surrounding cells. Here's a small example with a 3 by 3 grid (sum-square bolded): ``` 2 2 2 2 **16** 2 2 2 2 ``` And here's an example 7 by 7 grid: ``` 6 5 4 3 7 2 5 6 **43** 3 **50** 8 **43** 8 4 7 8 8 9 3 1 4 **36** 1 **43** 6 **40** 5 3 3 6 1 4 7 5 4 **35** 3 **45** 9 **42** 1 2 6 8 6 8 5 3 ``` ## Rules * Numbers that are not sums must always be between 1 and 9 inclusive. * Grid must be randomly generated. For each non-sum, every digit must have an equal chance of appearing, regardless of which cell it is in. * Numbers must be aligned. This means that either the first or last digit of each number in a column must line up vertically. (You may assume that the middle numbers will always be two digits.) * Surrounding cells includes diagonals. Therefore, each sum square will have eight numbers surrounding it, which you must add. * Shortest code wins, since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). [Answer] ## APL, ~~53 49 43 42 40 39~~ 36 I managed to replicate J's `;.` in APL, and used [Gareth's approach](https://codegolf.stackexchange.com/a/12444/7911), saving 13 chars. ``` {×5⌷⍵:5⌷⍵⋄+/⍵}¨3,⌿3,/×∘?∘9¨∘.∨⍨9⍴0 1 ``` Sample run: ``` {×5⌷⍵:5⌷⍵⋄+/⍵}¨3,⌿3,/×∘?∘9¨∘.∨⍨9⍴0 1 9 9 6 1 7 5 6 7 55 5 39 9 54 9 9 8 2 1 8 1 9 2 43 8 41 6 42 5 7 3 4 4 8 3 2 2 29 1 26 2 35 8 6 4 2 3 2 3 7 ``` --- Explanation: * `∘.∨⍨9⍴0 1` generates a bit mask. * `×∘?∘9¨` multiplies each bit by a random value from 1 to 9 inclusive, generating a masked grid of random numbers. * `3,⌿3,/` uses what can only be described as hackery to return all 3 by 3 overlapping boxes in the masked array. These are also flattened in the process. * `{×5⌷⍵:5⌷⍵⋄+/⍵}¨` iterates over the array, assigning each element to `⍵`. For each iteration, it takes the fifth (middle, remembering that APL indexing is 1-based), and returns its sign. In this case this is equivalent to testing if the number is greater than 0. If this returns 1 (for true), then return that element. Otherwise, return the sum of the elements in the flattened 3 by 3 box. It uses the `:⋄` ternary operator, which is the equivalent of `?:` in many languages. [Answer] ## J, 63 61 59 55 52 51 49 47 39 37 characters ``` 3 3(4&{+4{*|+/)@,;._3(**1+?)+./~9$0 9 ``` With thanks to [Volatility](https://codegolf.stackexchange.com/users/7911/volatility) for his 10 character saving. Explanation (each step will have different random numbers...): Generate the mask for generating the random numbers (uses [`$`](http://jsoftware.com/help/dictionary/d210.htm): ``` 9 9$9$0 9 0 9 0 9 0 9 0 9 0 0 9 0 9 0 9 0 9 0 0 9 0 9 0 9 0 9 0 0 9 0 9 0 9 0 9 0 0 9 0 9 0 9 0 9 0 0 9 0 9 0 9 0 9 0 0 9 0 9 0 9 0 9 0 0 9 0 9 0 9 0 9 0 0 9 0 9 0 9 0 9 0 ``` Now we have a [hook](http://jsoftware.com/help/learning/03.htm#12). This is actually a happy accident from when I was whittling down an earlier version. It was meant to be transpose [`|:`](http://jsoftware.com/help/dictionary/d232.htm) and OR [`+.`](http://jsoftware.com/help/dictionary/d101.htm) with the original. It made sense since I was using ones and zeroes at the time, but now I have nines and zeroes. It just so happens that it works in the same way with the GCD meaning of `+.`. Lucky for me. :-) ``` (+.|:)9 9$9$0 9 0 9 0 9 0 9 0 9 0 9 9 9 9 9 9 9 9 9 0 9 0 9 0 9 0 9 0 9 9 9 9 9 9 9 9 9 0 9 0 9 0 9 0 9 0 9 9 9 9 9 9 9 9 9 0 9 0 9 0 9 0 9 0 9 9 9 9 9 9 9 9 9 0 9 0 9 0 9 0 9 0 ``` So, now that we have a grid of 9s and 0s we want to generate some random numbers. [`?`](http://jsoftware.com/help/dictionary/d640.htm) generates a random number from 0 up to (but not including) a given number. Given a list it will generate one random number in this way for each member of the list. So in this case it will generate a number from 0 to 8 for every 9 in the table and a floating point number from 0 to 1 for each 0. ``` ?(+.|:)9 9$9$0 9 0.832573 7 0.926379 7 0.775468 6 0.535925 3 0.828123 7 0 5 5 4 3 4 5 4 0.0944584 2 0.840913 2 0.990768 1 0.853054 3 0.881741 3 8 7 0 8 3 3 4 8 0.641563 4 0.699892 7 0.498026 1 0.438401 6 0.417791 6 8 7 5 2 3 6 6 3 0.753671 6 0.487016 4 0.886369 7 0.489956 5 0.902991 3 4 7 8 1 4 8 0 8 0.0833539 4 0.311055 4 0.200411 6 0.247177 5 0.0464731 ``` But we want numbers from 1 to 9 not 0 to 8. So we add 1. ``` (1+?)(+.|:)9 9$9$0 9 1.4139 4 1.7547 7 1.67065 4 1.52987 1 1.96275 2 8 2 4 3 9 6 9 9 1.15202 7 1.11341 5 1.0836 1 1.24713 2 1.13858 9 3 3 2 4 7 3 8 6 1.06383 9 1.67909 4 1.09801 8 1.4805 6 1.0171 9 5 5 5 9 5 9 4 3 1.22819 1 1.85259 4 1.95632 6 1.33034 3 1.39417 4 2 5 1 3 7 2 5 6 1.06572 5 1.9942 5 1.78341 5 1.16516 6 1.37087 ``` This is very nice but we've lost the zeroes that I want, so we'll multiply it by the original mask after turning all the nines into ones. I do this by checking if the value is greater than 1. That gives us: `(1&<*1+?)`. There are a couple of things going on here: * We've created a [fork](http://jsoftware.com/help/learning/03.htm#13) which allows us to pack a lot of work into very few characters. * We've bonded ([`&`](http://jsoftware.com/help/dictionary/d630n.htm)) the 1 to the [`<`](http://jsoftware.com/help/dictionary/d630n.htm) verb. So all combined the `(1&<*1+?)` is generating random numbers, and zeroing all the numbers which where generated by zeroes in the original grid. ``` (1&<*1+?)(+.|:)9 9$9$0 9 0 3 0 2 0 7 0 1 0 9 5 2 7 7 1 4 5 7 0 6 0 8 0 3 0 1 0 4 8 7 5 9 7 7 9 4 0 9 0 6 0 9 0 9 0 6 1 2 1 4 6 8 9 4 0 3 0 8 0 6 0 6 0 2 5 2 2 2 2 3 9 3 0 9 0 3 0 5 0 3 0 ``` The next bit is the (in my opinion, anyway :-) clever bit. The cut [`;.`](http://jsoftware.com/help/dictionary/d331.htm) verb has a form `x u;._3 y` which cuts the input into boxes described by `x`, and then applies the verb `u` to them. In this case we have `3 3(4&{++/*0=4&{)@,;._3`. * The `3 3` is describing the boxes we want - 3x3. * The `(4&{++/*0=4&{)@,` is a verb train which describes what we want to do to each box. To demonstrate the `;.` verb I'll use `<` to show each box: ``` 3 3(<);._3(1&<*1+?)(+.|:)9 9$9$0 9 ┌─────┬─────┬─────┬─────┬─────┬─────┬─────┐ │0 8 0│8 0 7│0 7 0│7 0 4│0 4 0│4 0 3│0 3 0│ │9 1 3│1 3 2│3 2 3│2 3 8│3 8 5│8 5 5│5 5 9│ │0 6 0│6 0 1│0 1 0│1 0 2│0 2 0│2 0 4│0 4 0│ ├─────┼─────┼─────┼─────┼─────┼─────┼─────┤ │9 1 3│1 3 2│3 2 3│2 3 8│3 8 5│8 5 5│5 5 9│ │0 6 0│6 0 1│0 1 0│1 0 2│0 2 0│2 0 4│0 4 0│ │7 1 6│1 6 7│6 7 1│7 1 2│1 2 1│2 1 6│1 6 1│ ├─────┼─────┼─────┼─────┼─────┼─────┼─────┤ │0 6 0│6 0 1│0 1 0│1 0 2│0 2 0│2 0 4│0 4 0│ │7 1 6│1 6 7│6 7 1│7 1 2│1 2 1│2 1 6│1 6 1│ │0 7 0│7 0 5│0 5 0│5 0 9│0 9 0│9 0 7│0 7 0│ ├─────┼─────┼─────┼─────┼─────┼─────┼─────┤ │7 1 6│1 6 7│6 7 1│7 1 2│1 2 1│2 1 6│1 6 1│ │0 7 0│7 0 5│0 5 0│5 0 9│0 9 0│9 0 7│0 7 0│ │7 9 9│9 9 7│9 7 1│7 1 9│1 9 4│9 4 9│4 9 5│ ├─────┼─────┼─────┼─────┼─────┼─────┼─────┤ │0 7 0│7 0 5│0 5 0│5 0 9│0 9 0│9 0 7│0 7 0│ │7 9 9│9 9 7│9 7 1│7 1 9│1 9 4│9 4 9│4 9 5│ │0 3 0│3 0 2│0 2 0│2 0 7│0 7 0│7 0 9│0 9 0│ ├─────┼─────┼─────┼─────┼─────┼─────┼─────┤ │7 9 9│9 9 7│9 7 1│7 1 9│1 9 4│9 4 9│4 9 5│ │0 3 0│3 0 2│0 2 0│2 0 7│0 7 0│7 0 9│0 9 0│ │3 1 6│1 6 1│6 1 7│1 7 6│7 6 8│6 8 9│8 9 9│ ├─────┼─────┼─────┼─────┼─────┼─────┼─────┤ │0 3 0│3 0 2│0 2 0│2 0 7│0 7 0│7 0 9│0 9 0│ │3 1 6│1 6 1│6 1 7│1 7 6│7 6 8│6 8 9│8 9 9│ │0 9 0│9 0 3│0 3 0│3 0 4│0 4 0│4 0 3│0 3 0│ └─────┴─────┴─────┴─────┴─────┴─────┴─────┘ ``` Some things to notice: * The boxes overlap - the second and third columns in the top left box are the first and second in the box to the right of it. * There are 7x7 boxes. That's why we had a 9x9 grid initially. * Each place we require a sum has a `0` at the box's centre. Now we just need to either pass the value at the centre back (if it's non-zero) or sum the numbers in the 3x3 box (if the centre is zero). To do this we need easy access to the centre number. [`,`](http://jsoftware.com/help/dictionary/d320.htm) helps here. It turns the 3x3 grid into a list of 9 items with the centre number at number 4. `4&{` will use [`{`](http://jsoftware.com/help/dictionary/d520.htm) to pull out the centre value and then compare it with 0: `0=4&{`. This returns a `0` or `1` for true or false, which we then multiply by the sum [`+/`](http://jsoftware.com/help/dictionary/d420.htm). If it was zero at the centre we now have our sum as required. If it was not we have zero, so to finish off we just add the centre value `4&{+`. This gives the verb train `(4&{++/*0=4&{)@,` ``` 3 3(4&{++/*0=4&{)@,;._3(1&<*1+?)(+.|:)9 9$9$0 9 2 6 9 3 7 9 7 3 47 6 51 5 49 5 3 9 9 6 6 2 8 7 48 6 47 1 37 5 5 4 5 7 7 2 6 5 35 3 49 8 51 9 1 6 6 6 7 4 8 ``` [Answer] # Ruby (135 characters) ``` a=(0..48).map{rand(9)+1} ([0,0,j=8]*3).each{|l|a[j]=[0,1,6,7,8].inject{|s,e|s+a[j+e]+a[j-e]};j+=l+2} a.each_slice(7){|r|puts"%-3s"*7%r} ``` # Sample output ``` 2 1 6 9 4 5 1 9 34 4 37 2 31 3 7 2 3 1 8 1 7 5 42 4 40 2 47 9 3 9 9 4 9 4 7 3 44 4 41 2 47 4 6 9 1 5 7 6 8 ``` --- # Breakdown It's not too obvious how this works, so here's a quick breakdown. **NOTE:** You can probably skip some of these steps and jump to shorter versions more quickly, but I think it's educational enough to see different ways I shaved off characters, especially by spotting patterns in literals to turn 2-digit numbers into 1-digit versions. ## Naive version Unlike the [other Ruby solutions](https://codegolf.stackexchange.com/a/12433/9031) that rely on a two-dimensional array, you can (eventually) get a shorter version by starting with a 1-dimensional array and working with offset values, since the patterns repeat. ``` ary=(0..48).map { rand(9) + 1 } offsets = [-8,-7,-6,-1,1,6,7,8] 3.times do |i| [8,10,12].each do |j| ary[j + 14*i] = ary.values_at(*offsets.map { |e| j+14*i + e }).inject(:+) end end ary.each.with_index do |e,i| $> << ("%-3s" % e) $> << ?\n if i % 7==6 end ``` The key principle here is that we're working at index positions 8, 10, 12, just offset by multiples of 14. Positions 8, 10 and 12 are the centers of the 3x3 grids that we're summing up. In the sample output, 34 is position 8, 42 is position 8 + 14\*1, etc. We replace position 8 with 34 by positions offset from position 8 by `[-8,-7,-6,-1,1,6,7,8]` — in other words `34 = sum(ary[8-8], ary[8-7], ..., ary[8+8])`. This same principle holds for all the values of `[8 + 14*i, 10 + 14*i, 12 + 14*i]`, since the pattern repeats. ## Optimising it First, some quick optimisations: * Instead of `3.times { ... }`, and calculating `j + 14*i` each time, "inline" the positions `[8,10,12,22,24,26,36,38,40]`. * The `offsets` array is used once, so replace the variable with the literal. * Replace `do ... end` with `{...}` and switch around the printing to `$> << foo`. (There's a trick here involving `puts nil` and `() == nil`.) * Shorter variable names. The code after this is **177** characters: ``` a=(0..48).map{rand(9)+1} [8,10,12,22,24,26,36,38,40].each{|j|a[j]=a.values_at(*[-8,-7,-6,-1,1,6,7,8].map{|e|j+e}).inject(:+)} a.map.with_index{|e,i|$><<"%-3s"%e<<(?\nif i%7==6)} ``` For the next reduction, note that the `inject` doesn't need the offsets array to be in order. We can either have `[-8,-7,-6,-1,1,6,7,8]` or some other ordering, since addition is commutative. So first pair up the positives and the negatives to get `[1,-1,6,-6,7,-7,8,-8]`. Now you can shorten ``` [1,-1,6,-6,7,-7,8,-8].map { |e| j+e }.inject(:+) ``` to ``` [1,6,7,8].flat_map { |e| [j+e, j-e] } ``` This results in ``` a=(0..48).map{rand(9)+1} [8,10,12,22,24,26,36,38,40].each{|j|a[j]=a.values_at(*[1,6,7,8].flat_map{|e|[j+e,j-e]}).inject(:+)} a.map.with_index{|e,i|$><<"%-3s"%e<<(?\nif i%7==6)} ``` which is **176** characters. ## Shift by 8 and move to differences The two-character literal values seem like they can be shortened away, so take `[8,10,12,22,24,26,36,38,40]` and shift everything down by `8`, updating `j` at the start of the loop. (Note that `+=8` avoids needing to update the offset values of `1,6,7,8`.) ``` a=(0..48).map{rand(9)+1} [0,2,4,14,16,18,28,30,32].each{|j|j+=8;a[j]=a.values_at(*[1,6,7,8].flat_map{|e|[j+e,j-e]}).inject(:+)} a.map.with_index{|e,i|$><<"%-3s"%e<<(?\nif i%7==6)} ``` This is 179, which is bigger, but the `j+=8` can actually be removed. First change ``` [0,2,4,14,16,18,28,30,32] ``` to an array of differences: ``` [2,2,10,2,2,10,2,2] ``` and cumulatively add these values to an initial `j=8`. This will eventually cover the same values. (We could probably skip straight to this instead of shifting by 8 first.) Note that we'll also add a dummy value of `9999` to the end of the differences array, and add to `j` at the *end*, not the *start* of the loop. The justification is that `2,2,10,2,2,10,2,2` looks *awfully* close to being the same 3 numbers repeated 3 times, and by computing `j+difference` at the end of the loop, the final value of `9999` won't actually affect the output, since there isn't a `a[j]` call where `j` is some value over `10000`. ``` a=(0..48).map{rand(9)+1} j=8 [2,2,10,2,2,10,2,2,9999].each{|l|a[j]=a.values_at(*[1,6,7,8].flat_map{|e|[j+e,j-e]}).inject(:+);j+=l} a.map.with_index{|e,i|$><<"%-3s"%e<<(?\nif i%7==6)} ``` With this differences array, the `j+=8` is now just `j=8`, of course, since otherwise we'd repeatedly add `8` too many. We've also changed the block variable from `j` to `l`. So since the `9999` element has no effect on the output, we can change it to `10` and shorten the array. ``` a=(0..48).map{rand(9)+1} j=8 ([2,2,10]*3).each{|l|a[j]=a.values_at(*[1,6,7,8].flat_map{|e|[j+e,j-e]}).inject(:+);j+=l} a.map.with_index{|e,i|$><<"%-3s"%e<<(?\nif i%7==6)} ``` This is **170** characters. But now the `j=8` looks a bit clunky, and you can save 2 characters by shifting `[2,2,10]` down by 2 to conveniently get an `8` you can use for assignment. This also needs `j+=l` to become `j+=l+2`. ``` a=(0..48).map{rand(9)+1} ([0,0,j=8]*3).each{|l|a[j]=a.values_at(*[1,6,7,8].flat_map{|e|[j+e,j-e]}).inject(:+);j+=l+2} a.map.with_index{|e,i|$><<"%-3s"%e<<(?\nif i%7==6)} ``` This is **169** characters. A round-about way to squeeze 7 characters, but it's neat. ## Final tweaks The `values_at` call is actually sort of redundant, and we can inline an `Array#[]` call. So ``` a.values_at(*[1,6,7,8].flat_map{|e|[j+e,j-e]}).inject(:+) ``` becomes ``` [1,6,7,8].flat_map{|e|[a[j+e],a[j-e]]}.inject(:+) ``` You can also spot that `flat_map` + `j+e/j-e` + `inject` can be reduced to a more direct summation with an initial `0` in the array. This leaves you with **152** characters: ``` a=(0..48).map{rand(9)+1} ([0,0,j=8]*3).each{|l|a[j]=[0,1,6,7,8].inject{|s,e|s+a[j+e]+a[j-e]};j+=l+2} a.map.with_index{|e,i|$><<"%-3s"%e<<(?\nif i%7==6)} ``` Finally: * `map.with_index` can become `each_slice`. * Change the printing approach. **135**: ``` a=(0..48).map{rand(9)+1} ([0,0,j=8]*3).each{|l|a[j]=[0,1,6,7,8].inject{|s,e|s+a[j+e]+a[j-e]};j+=l+2} a.each_slice(7){|r|puts"%-3s"*7%r} ``` [Answer] **Python, 132** This doesn't technically satisfy the rules, because the last digits of each number are aligned rather than the first. But I thought I'd share anyway: ``` import numpy G=numpy.random.randint(1,10,(7,7)) G[1::2,1::2]=sum(G[i:6+i:2,j:6+j:2]for i in[0,1,2]for j in[0,1,2]if i&j!=1) print G ``` Sample output: ``` [[ 8 9 8 3 8 5 8] [ 6 53 4 45 8 53 8] [ 8 2 8 1 5 3 8] [ 2 40 6 34 1 32 7] [ 4 1 9 1 3 3 2] [ 4 35 7 35 6 31 1] [ 1 7 2 5 2 8 6]] ``` [Answer] **Mathematica, 108** ``` s=#-1;;#+1&;g=1+8~RandomInteger~{7,7};Column/@ ReplacePart[g,{i_?EvenQ,j_?EvenQ}:>g〚s@i,s@j〛~Total~2-g〚i,j〛] ``` ![result](https://i.stack.imgur.com/WDTok.png) For prettier output `Column/@` can be replaced with `TableForm@` at a cost of 2 characters. [Answer] ## GolfScript (79 78 72 70 68 66 65 60 chars) ``` 56,{13%5<,~9rand)}%9/`{>3<zip`{>3<(*(+(\{+}*or' '}+7,%n}+7,/ ``` NB This contains a literal tab, which Markdown may well break. The clever bit is due to Gareth: see his J solution. [Online demo](http://golfscript.apphb.com/?c=NTYsezEzJTU8LH45cmFuZCl9JTkvYHs%2BMzx6aXBgez4zPCgqKCsoXHsrfSpvcicJJ30rNywlbn0rNywv) [Answer] ### R: 114 characters ``` a=array(sample(1:9,49,r=T),c(7,7)) for(i in 2*1:3){for(j in 2*1:3)a[i,j]=sum(a[(i-1):(i+1),(j-1):(j+1)])-a[i,j]} a ``` First line create a 7 by 7 array filled with randomly chosen numbers from 1 to 9 (uniform distribution with replacement, hence `r=T` which stands for `replace=TRUE`). Second line, compute sums of 3 by 3 grids, substract center and replace it with the result. Third line print the resulting grid (by default, matrix and array columns are right aligned). Example output: ``` [,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 8 5 6 4 3 2 2 [2,] 1 37 6 41 7 38 8 [3,] 5 3 3 3 9 4 3 [4,] 4 31 3 41 3 44 9 [5,] 3 5 5 9 6 7 3 [6,] 3 32 2 40 4 37 5 [7,] 8 2 4 1 9 1 2 ``` [Answer] # J, 67 65 bytes A naïve and verbose solution in J. It is a straightforward implementation of the task. ``` (+/^:_"2((,&.>/@(<:,],>:)"0)&.>m){0 m}a)(m=.{;~1 3 5)}a=.>:?7 7$9 ``` First I create a 7 x 7 array of integers between 1 and 9. In fact J's ? verb generates numbers up to its argument, that's why we need to increment each element, >: in J ``` a=.>:?7 7$9 ``` ``` 2 8 7 4 4 5 1 4 5 4 1 6 7 9 3 8 3 6 5 3 3 6 8 6 3 7 7 1 7 7 4 4 5 9 9 2 3 6 5 2 2 9 2 2 6 8 8 1 3 ``` I prepare a mask to be used for zeroing of the odd row/col cells, a pairs of odd row/column indices: ``` m=.{;~1 3 5 ┌───┬───┬───┐ │1 1│1 3│1 5│ ├───┼───┼───┤ │3 1│3 3│3 5│ ├───┼───┼───┤ │5 1│5 3│5 5│ └───┴───┴───┘ ``` The Catalogue verb { combines items from the atoms inside the boxed list ``` ┌─────┬─────┐ │1 3 5│1 3 5│ └─────┴─────┘ ``` to form a catalogue, the 3x3 table of the pairs above Then I prepare a table of row/col indices to be used for selection of each of the 3x3 subarrays. ``` s=.(,&.>/@(<:,],>:)"0)&.>m ┌─────────────┬─────────────┬─────────────┐ │┌─────┬─────┐│┌─────┬─────┐│┌─────┬─────┐│ ││0 1 2│0 1 2│││0 1 2│2 3 4│││0 1 2│4 5 6││ │└─────┴─────┘│└─────┴─────┘│└─────┴─────┘│ ├─────────────┼─────────────┼─────────────┤ │┌─────┬─────┐│┌─────┬─────┐│┌─────┬─────┐│ ││2 3 4│0 1 2│││2 3 4│2 3 4│││2 3 4│4 5 6││ │└─────┴─────┘│└─────┴─────┘│└─────┴─────┘│ ├─────────────┼─────────────┼─────────────┤ │┌─────┬─────┐│┌─────┬─────┐│┌─────┬─────┐│ ││4 5 6│0 1 2│││4 5 6│2 3 4│││4 5 6│4 5 6││ │└─────┴─────┘│└─────┴─────┘│└─────┴─────┘│ └─────────────┴─────────────┴─────────────┘ ``` For each pair in the m array I make a pair of triplets, centered around each number of the m pair: ``` ┌─────┬─────┐ 1 3 -> │0 1 2│2 3 4│ └─────┴─────┘ ``` These pairs of triplets are used by the J From verb {, which can select multiple rows and columns simultaneously. 0 1 2 / 2 3 4 means that I select rows 0, 1 and 2 together with columns 2, 3 and 4, thus selecting the second 3x3 subarray on the top. Finally, I can use the 7x7 array and the masks to achieve the task: First I use m as a mask to set the corresponding elements to 0: ``` 0 m}a ``` Then I take all the 3x3 subarrays using s as a selector and find their sums: ``` +/^:_"2 s{0 m}a ``` Then I put these numbers back into the starting array. ``` (+/^:_"2 s{0 m}a)m}a ``` ``` 2 8 7 4 4 5 1 4 39 4 39 6 36 9 3 8 3 6 5 3 3 6 44 6 40 7 42 1 7 7 4 4 5 9 9 2 36 6 43 2 46 9 2 2 6 8 8 1 3 ``` [Try it online!](https://tio.run/##y/r/PzU5I19DWz/OKl7JSENDR03PTt9Bw8ZKJ1bHzkpTyUATKJCrWW2gkFubqKmRa6tXbV1nqGCsYKpZm2irZ2dlb65grmL5/z8A "J – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~32~~ ~~31~~ 30 bytes[SBCS](https://github.com/abrudz/SBCS) -1 byte thanks to @jslip ``` |a-m×+/+/⊢⌺3 3⊢a←?9⌈m←∘.⍱⍨2|⍳7 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgmGXI862tP@1yTq5h6erq2vrf@oa9Gjnl3GCsZARiJQgb3lo56OXCDjUccMvUe9Gx/1rjCqedS72fw/UOP/NAA "APL (Dyalog Unicode) – Try It Online") [Answer] ## Ruby, 207 I shall present my solution first (as I always do): ``` a=Array.new(7){Array.new(7){rand(9)+1}} s=[-1,0,1] s=s.product s s.slice!4 r=[1,3,5] r.product(r).map{|x|u=0 s.map{|y|u+=a[x[0]+y[0]][x[1]+y[1]]} a[x[0]][x[1]]=u} puts a.map{|x|x.map{|y|y.to_s.ljust 3}.join ``` [Answer] ### Ruby, 150 characters ``` v=(a=0..6).map{a.map{rand(9)+1}} (o=[1,3,5]).map{|i|o.map{|j|v[i][j]=0 (d=[0,-1,1]).map{|r|d.map{|c|v[i][j]+=v[i+r][j+c]}}}} puts v.map{|r|"%-3d"*7%r} ``` if the left justification requirement justification is just that `ljust` would have to be used... well, no. I love Ruby's formatting capabilities. Do not use `Array.new(7){...}`. `(0..6).map{...}` is both shorter and more readable *and* you get an assignable range for free. Line #3 inspired by [Doorknob's solution](https://codegolf.stackexchange.com/a/12431/7209). [Answer] ### GolfScript, 87 chars ``` 49,{.1&\7/1&!|9rand)*}%.7/{[..1>@0\+]zip{{+}*}%);}:^%zip{^~}%]zip{.0=!=}%{' '+3<}%7/n* ``` There are too many zips in there... (see [online](http://golfscript.apphb.com/?c=NDksey4xJlw3LzEmIXw5cmFuZCkqfSUuNy97Wy4uMT5AMFwrXXppcHt7K30qfSUpO306XiV6aXB7Xn59JV16aXB7LjA9IT19JXsnICAnKzM8fSU3L24q&run=true)) ``` 3 9 9 3 3 9 8 6 46 2 50 3 39 8 7 3 7 2 4 7 3 8 33 9 51 8 49 5 4 3 9 9 3 9 2 1 45 9 41 6 33 2 4 3 6 1 6 1 4 ``` [Answer] ### J, 58/64/67 characters ``` 0j_1":(7$0,:7$0 1){"0 1 |:>v;v-~7 7{.0,.0,3+/\"1]3+/\v=.1+?7 7$9 ``` While the specification requires the numbers to be left-aligned, there is no requirement to use the decimal notation, so I guess this is valid output: ``` 1.0e0 8.0e0 9.0e0 6.0e0 2.0e0 9.0e0 6.0e0 6.0e0 3.9e1 8.0e0 4.0e1 2.0e0 3.8e1 4.0e0 1.0e0 4.0e0 2.0e0 8.0e0 3.0e0 9.0e0 3.0e0 2.0e0 2.4e1 5.0e0 4.1e1 9.0e0 4.7e1 8.0e0 1.0e0 3.0e0 6.0e0 5.0e0 3.0e0 5.0e0 7.0e0 4.0e0 3.0e1 1.0e0 2.3e1 1.0e0 3.1e1 1.0e0 6.0e0 5.0e0 4.0e0 2.0e0 1.0e0 5.0e0 8.0e0 ``` If right alignment instead of left alignmnent is acceptable, we're at **58 characters** ``` (7$0,:7$0 1){"0 1 |:>v;v-~7 7{.0,.0,3+/\"1]3+/\v=.1+?7 7$9 ``` J's `":` (format) has three formatting modes: * right-aligned with n digits or with shrink-wrap (default display) * left-aligned scientific notation with n digits and m characters total * shrinkwrap boxed display with (left/center/right)-(top/middle/bottom) alignment (below, 69 characters) The most verbose but also most versatile and the only one able to produce the output as per the example is the `8!:2` formatting foreign, which takes a formatting string as its left argument. Also **67 characters**: ``` 'l3.'8!:2(7$0,:7$0 1){"0 1 |:>v;v-~7 7{.0,.0,3+/\"1]3+/\v=.1+?7 7$9 ``` Here is the boxed format: ``` 0 0":<"0(7$0,:7$0 1){"0 1 |:>v;v-~7 7{.0,.0,3+/\"1]3+/\v=.1+?7 7$9 ┌─┬──┬─┬──┬─┬──┬─┐ │2│6 │5│7 │5│7 │6│ ├─┼──┼─┼──┼─┼──┼─┤ │8│40│4│35│9│49│6│ ├─┼──┼─┼──┼─┼──┼─┤ │6│7 │2│2 │1│9 │6│ ├─┼──┼─┼──┼─┼──┼─┤ │8│41│9│35│3│45│7│ ├─┼──┼─┼──┼─┼──┼─┤ │3│1 │5│6 │7│8 │4│ ├─┼──┼─┼──┼─┼──┼─┤ │7│37│4│45│6│48│8│ ├─┼──┼─┼──┼─┼──┼─┤ │8│4 │5│4 │8│1 │6│ └─┴──┴─┴──┴─┴──┴─┘ ``` [Answer] ## Perl, 117 characters ``` print$_,++$j%7?$":$/for map{++$i/7&$i%7&1? eval join"+",@x[map{$i+$_,$i-$_}1,6,7,8]:" $_"}@x=map{1+int rand 9}$i--..48 ``` This is one of those Perl scripts where all but one of the for loops have been collapsed into `map` calls so that everything can be done in a single statement. Global variables also make some important appearances in this one. I guess what I'm trying to say here is, this program is a bit gross. Wait, it gets worse: There's a known bug in the script! It has less than a one-in-a-million chance of getting triggered, though, so I haven't gotten around to fixing it yet. [Answer] ## *Mathematica*, 106 / 100 I came up with something very similar to ssch's code, before seeing it. I am borrowing his idea of using `Column`. With ASCII only, **106**: ``` s=#-1;;#+1& a=8~RandomInteger~{7,7}+1 a[[##]]=a[[s@#,s@#2]]~Total~2-a[[##]];&@@@{2,4,6}~Tuples~2 Column/@a ``` With Unicode characters (as used by ssch), **100**: ``` s=#-1;;#+1& a=8~RandomInteger~{7,7}+1 a〚##〛=a〚s@#,s@#2〛~Total~2-a〚##〛;&@@@{2,4,6}~Tuples~2 Column/@a ``` [Answer] # Excel VBA, 74 bytes VBE immediate function that outputs to `[B2:H9]`. ``` [B2:H9]="=IF(ISODD(ROW()*COLUMN()),SUM(A1:C1,A2,C2,A3:C3),INT(RAND()*8)+1) ``` # Sample Output [![enter image description here](https://i.stack.imgur.com/ue0rt.png)](https://i.stack.imgur.com/ue0rt.png) [Answer] # Powershell, ~~149~~ 148 bytes *-1 byte thanks to @AdmBorkBork. It's cool!* ``` $i=-1 ($a=(,1*8+0,1*3)*3+,1*7|%{$_*(1+(Random 9))})|?{++$i;!$_}|%{6..8+1|%{$_,-$_}|%{$a[$i]+=$a[$i+$_]}} -join($a|%{if(!(++$i%7)){" "};'{0,3}'-f$_}) ``` Explanation: ``` $i=-1 # let $i store -1 ($a= # let $a is array of random numbers with zero holes (,1*8+0,1*3)*3+,1*7| # the one-dimension array equals # 1 1 1 1 1 1 1 # 1 0 1 0 1 0 1 # 1 1 1 1 1 1 1 # 1 0 1 0 1 0 1 # 1 1 1 1 1 1 1 # 1 0 1 0 1 0 1 # 1 1 1 1 1 1 1 %{ # for each element $_*(1+(Random 9)) # multiply 0 or 1 element to random digit from 1 to 9 } # now $a stores values like (* is a random digit from 1 to 9) # * * * * * * * # * 0 * 0 * 0 * # * * * * * * * # * 0 * 0 * 0 * # * * * * * * * # * 0 * 0 * 0 * # * * * * * * * )|?{++$i;!$_ # calc index $i and passthru values == 0 only }|%{ # for each zero value cell with index $i 6..8+1|%{ # offsets for the surrounding cells # . . . # . x +1 # +6 +7 +8 $_,-$_ # add the mirror offsets # -8 -7 -6 # -1 x +1 # +6 +7 +8 }|%{ # for each offset $a[$i]+=$a[$i+$_] # add surrounding values to the cell } } # display the $a -join( $a|%{ # for each value of $a if(!(++$i%7)){"`n"} # line break for each 7 cells '{0,3}'-f$_ # formatted value of $a with width = 3 char and align right } ) # join all values to string ``` [Answer] # Mathematica ~~142 151 172~~ 179 **Code** ``` z = (m = RandomInteger[{1, 9}, {7, 7}]; s = SparseArray; o = OddQ; e = EvenQ; i = {1, 1, 1}; (m + ArrayPad[ListCorrelate[{i, i, i}, m] s[{{i_, j_} /; o@i \[And] o@j -> 1}, {5, 5}], 1] - 2 m s[{{i_, j_} /; e@i \[And] e@j -> 1}, {7, 7}]) // Grid) ``` **Usage** ``` z ``` ![m8](https://i.stack.imgur.com/nCpAE.png) [Answer] # [Julia 0.6](http://julialang.org/), 127 (89) bytes ``` x=rand(1:9,7,7);[x[i,j]=sum(!(0==k==l)*x[i+k,j+l]for k=-1:1,l=-1:1)for i=2:2:7,j=2:2:7] Base.showarray(STDOUT,x,1<1;header=1<1) ``` [Try it online!](https://tio.run/##Jci9CsIwFEDh3afQLbFXMR0Mpt5F3B2sU8lwoZHmRwsJxfj0ser0HY6bgqV9KRkjPXsm1AEkSN50ubPgNKbpwVZsh@gRA1/Pt/LgqqDvY1x63AglIPzg32OxVrWS4P7qxYmS2aZhfFGM9GbX9ny5tZBBHEUzGOpNxDl5KR8 "Julia 0.6 – Try It Online") **89** bytes using native display, which might be admissible if additional lines can be printed: ``` 7×7 Array{Int64,2}: 6 6 8 2 3 2 3 7 44 5 33 4 23 5 3 8 1 9 1 3 2 4 41 2 37 5 22 2 7 8 8 8 3 4 2 9 53 6 44 7 36 3 7 7 1 9 2 6 9 ``` [Answer] # Java 10, ~~262~~ ~~260~~ ~~248~~ 239 bytes ``` v->{int a[][]=new int[7][7],i=49,j,k;for(;i-->0;)a[i/7][i%7]+=Math.random()*9+1;var r="";for(;++i<7;r+="\n")for(j=0;j<7;r+=(k=a[i][j])>9|j++%2<1?k+" ":k+" ")if(i*j%2>0)for(a[i][j]=k=0;k<9;k++)a[i][j]+=k!=4?a[i+k/3-1][j+k%3-1]:0;return r;} ``` -12 bytes thanks to *@ceilingcat*. **Explanation:** [Try it here.](https://tio.run/##LZBBbsIwEEX3PcXUUiQbkxAoEgrG4QSwqdRNmoUbQms7OMhxUlWUs6d2iTQazfyZ/xdPiUHE6qTHqhFdBwchze0JQBpX27OoajiGFeDVWWk@ocJvrTzBQJhX70@@dU44WcERDHAYhzi/eS@IoixKburvkFRsSl9zydfZXM01O7cWMxnHecqIKOTCn2W0KSk/CPeVWGFO7QWTWUaXbBAWLEfo4aFU7jbMUo7eDSJBUjxl6qFhzX1YWaiS5NmvojRa7ZZ7TRGgbeiAiDxjOVPRKk//zdM71z5E7zKmKSWTRrl@5uu936hevMRLr1EdhWGbMlu73hqw7D4GDL6u/UfjIUwshoDo4kniB7WiBEEmjD@dqy9J27vk6k@uMdgkFTZ905CJ6X38Aw) ``` v->{ // Method with empty unused parameter and String return-type int a[][]=new int[7][7], // Integer-matrix with 7x7 zeroes i=49,j,k; // Index integers (`i` starting at 49) for(;i-->0;) // Loop `i` in the range (49, 0]: a[i/7][j%7]+=Math.random()*9+1; // Fill the current cell with a random 1..9 integer var r=""; // Result-String, starting empty for(;++i<7; // Loop `i` in the range [0, 7): r+="\n") // After every iteration: append a new-line to the result for(j=0;j<7; // Inner loop `j` in the range [0, 7): r+= // After every iteration: append the result-String with: (k=a[i][j])>9 // If the current number has 2 digits, |j++%2<1? // or it's an even column (indices 0/2/4/6) k+" " // Append the current number appended with one space : // Else: k+" ") // Append the current number appended with two spaces if(i*j%2>1) // If both indexes `i` and `j` are odd for(a[i][j]=k=0; // Reset both the current item and index `k` to 0 k<9;k++) // Inner loop `k` in the range [0, 9): a[i][j]+= // Sum the item at location `i,j` with: k!=4? // If `k` is not 4 (the current item itself) a[i+k/3-1][j+k%3-1] // Sum it with the numbers surrounding it : // Else: 0; // Leave it the same by adding 0 return r;} // Return the result-String ``` ]
[Question] [ A [Fermi-Dirac Prime](https://en.wikipedia.org/wiki/Fermi%E2%80%93Dirac_prime) is a prime power of the form \$p^{2^k}\$, where \$p\$ is prime and \$k \geq 0\$, or in other words, a prime to the power of an integer power of two. They are listed as integer sequence [A050376](https://oeis.org/A050376). While a normal prime factorization generally does not contain a set of distinct primes (for example \$24=2 \times 2 \times 2 \times 3\$), a Fermi-Dirac prime factorization contains each Fermi-Dirac-prime at most once \$24=2 \times 3 \times 4\$. Your task is to write a program that takes an integer `n` as input and prints out the `n`'th Fermi-Dirac prime or chose any other options from the [standard sequence IO rules](https://codegolf.stackexchange.com/tags/sequence/info) Shortest code in bytes wins, [no funny business](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). **1-indexed** ``` 1, 2 2, 3 3, 4 4, 5 5, 7 6, 9 7, 11 8, 13 9, 16 10, 17 100, 461 1000, 7649 6605, 65536 10000, 103919 100000, 1296749 1000000, 15476291 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 2ƽƲ¿Ẓ$# ``` A monadic Link that accepts an integer, \$n\$, and yields the first \$n\$ Fermi-Dirac primes. **[Try it online!](https://tio.run/##y0rNyan8/9/ocNuhvUC86dD@h7smqSj////fzBAA "Jelly – Try It Online")** ### How? ``` 2ƽƲ¿Ẓ$# - Link: integer, n 2 # - count up, starting at 2, and find the first n integers for which: $ - last two links as a monad: ¿ - while... Ʋ - ...condition: is square? ƽ - ...action: integer square root Ẓ - is prime? ``` Note: The integer-square-root, `ƽ` could be square-root `½`, but we'd need to cast to an integer (e.g. floor, `Ḟ`) to use `Ẓ` anyway (e.g. `2.0` is not considered prime), but using `ƽ` avoids any floating point arithmetic entirely. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes (generator), 16 bytes (full program) ``` .ℕ₂ḋ=l~^h2∧ ``` [Try it online!](https://tio.run/##ATUAyv9icmFjaHlsb2cy/ztJ4oaw4oKB4bag4oG9/y7ihJXigoLhuIs9bH5eaDLiiKf//zEwMDD/Wg "Brachylog – Try It Online") ``` ;I{.ḋ=l~^h2∧}ᶠ⁽b ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/39qzWu/hjm7bnLq4DKNHHctrH25b8Khxb9L//4YGBob/owA "Brachylog – Try It Online") The generator is 1-indexed. The full program outputs the first `n` prime powers, 0 indexed. Actually not that slow. ### Explanation ``` .ℕ₂ Output is an integer in [2,+inf) ḋ Its prime decomposition… = …is a list of equal elements… l …with a length… ~^h2∧ …being a power of 2 ;I{ }ᶠ⁽ Find the first <Input> results of the following predicate: .ḋ The prime decomposition of the Output… = …is a list of equal elements… l …with a length… ~^h2∧ … being a power of 2 b Remove the first result (1, whose prime decomposition is the empty list) ``` [Answer] # [Python](https://www.python.org), 60 bytes ``` L={n:=1} while{n}<=L or[print(n),L:=L|{n*l for l in L}]:n+=1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NU9BTsMwELz7FSP1QEMBJZxQWvOC_ABxMI1DrDpey94ojUJewqUXeBJSf4NJy2VmNTM70nx--5FbcqfzzwrcmohWq1oHpEuBg9kfwIROHXSyNYxrjDOsYYk8IidQjEidhifjeCtWoBQMg4k6WYSaortJkZYGKDeCevY9C2E6TyHpYxTkQ3qVC4q9Y0jkotYNFmV9zEqBd0tvyiK54g-wkSgE6D8hYJpFf8ZjXqbSB300vM6zr56b-6fzrpKTK2Uxi6E1Vk9u3skKFF4uBS67q0pZfUzu1qKhAJuWoppfS7eRxaXjdKUr_wI) Outputs indefinitely. Complexity is exponential in N, the number of Fermi-Dirac primes to find. ## How? Exploits the factorisation property described in OP: Maintains the set of products of each subset of the set of Fermi-Dirac primes found so far. The smallest number not in this set is the next Fermi-Dirac prime *no matter whether it happens to be a conventional prime or a power-of-2th power of one*. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~9~~ 8 bytes ``` ʀEĖeæa)ȯ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiyoBFxJZlw6ZhKcivIiwiIiwiMVxuMlxuM1xuNFxuNVxuNlxuN1xuOFxuOVxuMTBcbjIwIl0=) Times out for numbers larger than 20. 1-indexed. *-1 thanks to @Shaggy* ## Explained ``` ʀEĖeæa)ȯ # takes a single integer n )ȯ # first n numbers where: ʀ # the range [0, that number] EĖe # to the power of 1/(2 to the power of each number in that range) æa # contains a prime number ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` >Åp¤Ýoδm˜êNè ``` 0-indexed. Brute-force approach, so slower the larger the input is. [Try it online](https://tio.run/##AR4A4f9vc2FiaWX//z7DhXBJPsOdb860bcucw6pJw6j//zk) or [verify the first 10 test cases](https://tio.run/##ASsA1P9vc2FiaWX/VEZOPyIg4oaSICI/Tv8@w4VwTj7DnW/OtG3LnMOqTsOo/yz/) (with `¤` replaced with `I>` to speed it up a bit, although still times out for \$n\geq15\$). **Explanation:** ``` > # Increase the (implicit) input by 1 (for edge-case n=0) Åp # Pop and push a list of the first input+2 amount of prime numbers ¤ # Push its last/largest prime (without popping the list) Ý # Pop and push a list in the range [0,max_prime] o # Get 2 to the power each value in this list δ # Apply double-vectorized on the two lists: m # Exponentiation ˜ # Flatten the list of lists ê # Sorted-uniquify it Iè # Get the input'th value of this list # (after which it is output implicitly as result) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~42~~ 26 bytes ``` ≔¹θ⊞υθFN«W№υθ≦⊕θ≔⁺υ×υθυ⟦Iθ ``` [Try it online!](https://tio.run/##LYyxDsIgFEXn9ive@Ejq4GicTKcOGoZuxgERhYRCCzwdjN@ObWC7uffcI7UI0gub8ylG83K472Bhx5ZT1EglP30AHNxM6ULTXQVkDL5t89HGKsDek0sFZXAWc/UMTgY1KZfUo1iaOnBLccNHM6lYfx3QRvBgVtW1FzHhwm5r9cv5kHdv@wc "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` Fermi-Dirac primes. Explanation: Now a port of @loopywalt's Python answer. ``` ≔¹θ⊞υθ ``` Start with a list of `[1]`. ``` FN« ``` Repeat `n` times. ``` W№υθ≦⊕θ ``` Find the smallest positive integer not already in the list, which is the next Fermi-Dirac prime. ``` ≔⁺υ×υθυ ``` Multiply all of the elements of the list by the prime and append them to the list. ``` ⟦Iθ ``` Output the prime on its own line. [Answer] # [Haskell](https://www.haskell.org/), ~~78~~ 51 bytes ``` (2![1]!!) n!l|elem n l=(n+1)!l|k<-l++map(*n)l=n:2!k ``` [Try it online!](https://tio.run/##DcixDkAwEADQ3VfcJYZWY2Aj@iUYGmmRXi@NGn27443vcCV6Igl2EdXj3K2IumKkx5NPwEBWsen0H3FqyZjksmpYk@WxxyjJnQwW8nXyDXWAQd4tkNuLtFvOHw "Haskell – Try It Online") * saved 27 Bytes using @loopy walt approach. Outputs n-th 0-indexed element [Answer] # [JavaScript (V8)](https://v8.dev/), 63 bytes *-1 byte thanks to [@jdt](https://codegolf.stackexchange.com/users/41374/jdt)* Prints the sequence indefinitely. ``` for(n=2;k=1;g(k),n++)for(g=k=>k-n?k>n||g(k*k):print(n);n%++k;); ``` [Try it online!](https://tio.run/##FcnBCoAgDADQrwlc5qFO0Zh9iwSJDZaYePLfV13fu0ILz1FSrq6tquddjNCCTDNGwzCJtfBjJCbPTnb20vtXI8OWS5JqBFAGaxkBVV8 "JavaScript (V8) – Try It Online") ### Commented ``` for( // infinite outer loop: n = 2; // start with n = 2 k = 1; // start each iteration with k = 1 g(k), n++ // after each iteration: invoke g and increment n ) // for( // inner loop: g = k => // start by defining the helper function g which // tests whether n = k ** (2 ** i) for some i k - n ? // if k is not equal to n: k > n || // abort if k is greater than n g(k * k) // otherwise, do a recursive call with k² : // else: print(n); // success --> print n n % ++k; // increment k until it divides n ); // end of inner loop // implicit end of outer loop ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 76 bytes ``` K` "$+"{`$ _ )/^(()(((?<-2>)|\4_)\4_)+\4_(?=\4__$))*(?!(__+)\5+$)__/^+`$ _ _ ``` [Try it online!](https://tio.run/##K0otycxLNPz/3zuBS0lFW6k6QYUrnktTP05DQ1NDQ8PeRtfITrMmxiReE4S1gYSGvS2QjFfR1NTSsFfUiI/X1owx1VbRjI/Xj9MG647//98CAA "Retina – Try It Online") No test cases because of the way the program uses history. Explanation: ``` K` ``` Clear the working area. ``` "$+"{` )` ``` Repeat `n` times. ``` $ _ ``` Increment the working area. ``` /^(()(((?<-2>)|\4_)\4_)+\4_(?=\4__$))*(?!(__+)\5+$)__/^+` ``` While the working area is not a Fermi-Dirac prime... ``` $ _ ``` Increment the working area. ``` _ ``` Convert to decimal. Explanation of the test: ``` ()(((?<-2>)|\4_)\4_)+\4_(?=\4__$) ``` Take the square root. A test for the square root is `((^_|__\2)+)$` but the square root is held in `$#1` which is inconvenient, so instead of summing odd numbers this sums pairs of consecutive integers, and the test is not repeatable, even with the adjusted version `((?(1)\1__|_))+` that can be used within a larger expression, so it is necessary to set a dummy group with `()` and then use `(?<-2>)` to consume it on the first pass through the main loop. The last loop iteration is unrolled to allow the remainder of the value to be the square root to satisfy either the next iteration of the square root loop or the primality test. ``` (...)* ``` Take the square root as many times as possible. (Although obviously this is necessary anyway for the final root to be prime.) ``` (?!(__+)\5+$) ``` Test that the remainder is not composite. ``` __ ``` Test that the remainder is at least `2`. [Answer] # [sclin](https://github.com/molarmanful/sclin), 45 bytes ``` $W2+"."fltr P/"len1="Q rev >A0:1:2log"I"Q = & ``` [Try it here!](https://replit.com/@molarmanful/try-sclin) Returns an infinite list. Feels very golfable... For testing purposes (use `-i` flag if running locally): ``` ; 100tk >A $W2+"."fltr P/"len1="Q rev >A0:1:2log"I"Q = & ``` ## Explanation Prettified code: ``` $W2+ \; fltr P/ ( len 1= ) Q rev >A 0:1: 2log \I Q = & ``` * `$W2+ \; fltr` filter range [2, ∞)... + `P/` prime factor - results in frequency map `{prime => frequency}` + `( len 1= ) Q rev` duplicate, check if frequency map has only one prime, swap to save for later + `>A 0:1:` get frequency - i.e. get value from 0th key-value pair + `2log \I Q =` check if power of 2 - i.e. check if log base 2 of the frequency is an integer + `&` AND [Answer] # PARI/GP 53 bytes ``` k=1;while(n,n-=2^#binary(j=isprimepower(k++))==j*2);k ``` 1-indexed; given n, returns n-th Fermi-Dirac prime. Revised version uses M.F. Hasler's is\_A050376(n) provided in [OEIS A050376](https://oeis.org/A050376). [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~49~~ ~~33~~ 32 bytes *-16 bytes thanks to DLosc's suggestions* ``` Wa{Yx:UoT(RT:x)%1Yxa-:1=0Ny%,y}o ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJXYXtZeDpVb1QoUlQ6eCklMVl4YS06MT0wTnklLHl9byIsIiIsIjIwIiwiIl0=) Ok I swear, the prime checking part of the code wasn't working before without the increment `U`, but now I test it again and it works?!?! Whatever, it's -1 byte. [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 40 bytes ``` grep {is-prime any $_,*.sqrt...*%1},2..* ``` [Try it online!](https://tio.run/##K0gtyjH7n1up4JCoYPs/vSi1QKE6s1i3oCgzN1UhMa9SQSVeR0uvuLCoRE9PT0vVsFbHCEj/t@ZySIyOMzWI1StOrLT@DwA "Perl 6 – Try It Online") This is probably not the best approach but whatever. Outputs as an infinite sequence. [Answer] # [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), ~~94~~ 81 bytes Saved 13 bytes thanks to the comment of [@lesobrod](https://codegolf.stackexchange.com/users/114511/lesobrod) --- This sequence is [A050376](https://oeis.org/A050376) 81 bytes. [Try it online!](https://tio.run/##HclRCsIwDADQwwjSwsC1v6OSI4yJ7CNkECRzJaYTKez4Vfx78IzrJsY1P7itqTlNYbiXvBeASfiN85Zfgs7SaXHhot5fY3fbDxw/2QQmLk@Bv8cMtigNmqISIcYuEPlz@2WpsELo@/YF) ``` (k=1;Union@@Reap[While[(m=#^(1/k))>2,Sow[Prime@Range@PrimePi@m^k];k=2k]][[2,1]])& ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes ``` (a={x=2};Do[While@Mod[Times@@a,++x]==0;AppendTo[a,x],#];a)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XyPRtrrC1qjW2iU/OjwjMyc12jc/JTokMze12MEhUUdbuyLW1tYg1tqxoCA1LyUkPzpRpyJWRznWOlFT7X9AUWZeiUOag6GBwX8A "Wolfram Language (Mathematica) [Dash] Try It Online") Print given number of sequence members. Based on the next statement from Wiki: > > Another way of defining this sequence is that each element is the > smallest positive integer that does not divide the product of all of > the previous elements of the sequence. > > > ]
[Question] [ Inspired by the recent [3Blue1Brown video](https://www.youtube.com/watch?v=bOXCLR3Wric) Consider, for some positive integer \$n\$, the set \$\{1, 2, ..., n\}\$ and its subsets. For example, for \$n = 3\$, we have $$\emptyset, \{1\}, \{2\}, \{3\}, \{1,2\}, \{1,3\}, \{2,3\}, \{1,2,3\}$$ If we take the sum of these subsets, we can then ask ourselves the following question: > > Of the sums of the subsets of \$\{1, 2, ..., n\}\$, how many are divisible by some given integer \$k\$? > > > Again, using \$n = 3\$ as an example, we have our subset sums as $$0, 1, 2, 3, 3, 4, 5, 6$$ For \$k = 2\$, there are \$4\$ subsets whose sum is divisible by \$k\$: \$\emptyset, \{2\}, \{1,3\}\$ and \$\{1,2,3\}\$. --- Given two positive integers \$n \$ and \$k\$, with \$2 \le k \le n\$, output the number of subsets of \$\{1, 2, 3, ..., n-1, n\}\$ such that their sum is divisible by \$k\$. You may take input and give output in any reasonable manner and format. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. --- ## Test cases ``` n k out 3 2 4 5 5 8 13 8 1024 2 2 2 7 7 20 14 4 4096 15 10 3280 9 5 104 7 2 64 11 4 512 15 3 10944 16 7 9364 13 5 1640 11 6 344 12 10 410 9 9 60 ``` And, a couple of larger ones, taken from the approach in the 3Blue1Brown video: ``` 200, 5 -> 321387608851798055108392418468232520504440598757438176362496 2000, 5 -> 22962613905485090484656664023553639680446354041773904009552854736515325227847406277133189726330125398368919292779749255468942379217261106628518627123333063707825997829062456000137755829648008974285785398012697248956323092729277672789463405208093270794180999311632479761788925921124662329907232844394066536268833781796891701120475896961582811780186955300085800543341325166104401626447256258352253576663441319799079283625404355971680808431970636650308177886780418384110991556717934409897816293912852988275811422719154702569434391547265221166310540389294622648560061463880851178273858239474974548427800576 ``` [Answer] # [Python 3](https://docs.python.org/3/), 54 bytes ``` f=lambda n,k,r=0:n and f(n-1,k,r)+f(n-1,k,r-n)or r%k<1 ``` [Try it online!](https://tio.run/##TU7RboQgEHz3K@alOUm9hgX01JSPsbmaM3pArJemufrtFjCYkuywDDOz636WmzVy23o9dfePawdTjMWseWvQmSv63JwpMOz1aM@G2Rnzy/hO2/dtmD5BbRZ9Fhr3zuWDWYrBuMeSs7cvNw3@ZhnsY/H/PqYY/cvNXpX3p6dpxYrnGNFL2nLFb@y0tuuJbQCkLwjEozIPJRIAtScoKmpfxEVUiH8WEYgLEkDwYFExLRRvqkCU0R7GiToo0BxTiKsjYw@tAkGUMlCSSBlhXeKNiooqjW3kbpEplCrFj4wok7tFpD2giP8B "Python 3 – Try It Online") [Answer] # JavaScript (ES6), 40 bytes Expects `(k)(n)`. ``` k=>g=(n,s=0)=>n--?g(n,s)+g(n,s-~n):s%k<1 ``` [Try it online!](https://tio.run/##bZDbisIwEIbv9ylys5BBa2eSMduI0WcRD2VXSRe77KWvXhsxVpIEQggf/2HmZ/e/6/fX79@/yneH43Byw9ltWif9vHcIbuOratuGH8weT3XzsOo/z2sa9p3vu8txcelaeZJCgRQaQNS1CIc/Er6EcF@8SXkDkqKeUGX64K8mvUr5F4QbucKU8@jPT85oTcIJRx77adVgqb@N/oTFflO@4VI@Rb6krL@e8gktc2E@Mk@91aa032l/hrP@5j1fZ/6P@V/7Zcr09n1@YXC4Aw "JavaScript (Node.js) – Try It Online") ### Commented ``` k => // outer function taking k g = ( // inner recursive function taking: n, // n s = 0 // s = sum of set entries ) => // n-- ? // if n is not equal to 0 (decrement it afterwards): g(n, s) + // do a recursive call with s unchanged g(n, s - ~n) // do a recursive call where n+1 is added to s : // else: s % k < 1 // increment the final result if k divides s ``` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 34 bytes ``` f(n,k)=prod(i=1,n,x^i+1)%(x^k-1)%x ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY9NCsIwEEavMhSEBKfQpL8u6kVKK0GphIY2lAr1LG66EU_gYbyNSUzA1bzJ92bIPF5azPJ01dv2vC19XH2inow40FrP04XImuGIayf3jO7I2g2xqas330JrdScC4iPoWY6Lwcg2EZyFUqRHEJQiNE2KwFsDOUJuKzMPlQXugxKhdEGGkDkwKkssHfxM6VXG_pTUQRGm07DfOIUDHtbwJLFhS3-fD-d-AQ) ## Longer but faster, 43 bytes: ``` f(n,k)=lift(prod(i=1,n,Mod(x^i+1,x^k-1)))%x ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TZBNCsIwEIWvMhSEhE6hSe2Pi3oDT1BaCUolNNRQKtSzuOlGvIbX8DYmMQFX88289wZmHi8tJnm86HV93uY-qT5xT0YcaK1kPxM9Xc9E1gxHPBhaOhkzXLohYZTSzeIjb6G1uhMByR70JMfZYGSbCE5CKdIjCEoRmiZD4K2BHCG3lZlBZYF7oUQonbBF2DowVpZa2vlM6a2M_VkyB0VIZ2G_8RQOeFjD09SLhhy29HdHeMEX) Using generating functions. Finds the constant term of the polynomial \$\prod\_{i=1}^n(X^i+1)\$ in the ring \$\mathbb{Z}[X]/((X^k-1))\$. [Answer] # BQN, 26 bytes `{+´0=𝕨|+´¨1+(⥊(↕2˘)/¨<)↕𝕩}` This block takes *n* as its right argument and *k* as its left one ## Explanation: ``` { +´ # count (sum of booleans) 0=𝕨| # values divisible by left argument (k) +´¨1+(⥊(↕2˘)/¨<)↕𝕩 # in the list of the sums of the subsets (⥊(↕2˘)/¨<) # get all the subsets of ↕𝕩 # all natural integers inferior to the right argument (n) +´¨1+ # +1 (otherwise values would go from 0 to (n-1) instead of the expected 1 to n) } ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `R`, 5 bytes ``` ṗṠ$Ḋ∑ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJSIiwiIiwi4bmX4bmgJOG4iuKIkSIsIiIsIjVcbjUiXQ==) ``` Ṡ # Sums of ṗ # Powersets of 1...input $Ḋ # Are divisible by other input? ∑ # Count those where they are ``` # [Vyxal](https://github.com/Vyxal/Vyxal) `Rrs`, 3 bytes ``` ṗṠḊ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJScnMiLCIiLCLhuZfhuaDhuIoiLCIiLCI1XG41Il0=) [Answer] # [Desmos](https://desmos.com/calculator), ~~74~~ 65 bytes *-9 bytes thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)* ``` f(n,k)=∑_{N=1}^{2^n}0^{mod(∑_{a=1}^namod(floor(2N/2^a),2),k)} ``` [Try It On Desmos!](https://www.desmos.com/calculator/mww77uuckj) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/qig3uhs71c) [Answer] # [R](https://www.r-project.org), 79 bytes ``` function(n,m)sum(!sapply(apply(expand.grid(rep(list(!1:0),n)),1,which),sum)%%m) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGqlMyy4tKk4tJc26WlJWm6Fjf900rzkksy8_M08nRyNYESGorFiQUFOZUaEDK1oiAxL0UvvSgzRaMotUAjJ7O4REPR0MpAUydPU1PHUKc8IzM5Q1MHqFNTVTVXE2LsOrg9GpY6plDBBQsgNAA) `expand.grid` generates all permutations of `n` elements of `TRUE`/`FALSE`; then `which` identifies the `TRUE` index in each permutation: this is the powerset of `1:n`; get the `sum` of each (using `sapply`), find those that are zero modulo `m`, and `sum` the results. Performing the `which` and `sum` calculations together costs more in R < 4.1, since we need to declare a new `function`, but this is offset in more-recent R versions that can use `\` as a short form: --- # [R](https://www.r-project.org)≥4.1, 72 bytes ``` \(n,m)sum(!apply(expand.grid(rep(list(!1:0),n)),1,\(x)sum(which(x)))%%m) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGqlMyy4tKk4tJc26WlJWm6Fjc9YjTydHI1gSIaiokFBTmVGqkVBYl5KXrpRZkpGkWpBRo5mcUlGoqGVgaaOnmamjqGOjEaFWD15RmZyRlAtqamqmquJsS8dXALNCx1TKGCCxZAaAA) --- I wrote all that, and then - before posting - browsed down to [Arnauld's](https://codegolf.stackexchange.com/a/247735/95126) and [att's](https://codegolf.stackexchange.com/a/247736/95126) answers, and realised that porting their beautiful recursive approach into R would be hugely shorter. Upvote them! # [R](https://www.r-project.org)≥4.1, ~~49~~ 47 bytes *Edit: -2 bytes thanks to a very nice golf by pajonk, using the indexing operator `[` as the recursive function name* ``` `[`=\(k,n,s=0)`if`(n,k[n-1,s]+k[n-1,s+n],!s%%k) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGqlMyy4tKk4tJc26WlJWm6Fjf1E6ITbGM0snXydIptDTQTMtMSNPJ0sqPzdA11imO1oQztvFgdxWJV1WxNiLZ1cHM0THUsoYILFkBoAA) [Answer] # [C (gcc)](https://gcc.gnu.org/), 79 bytes ``` a;p;s;b;f(n,k){for(a=b=0;++b<1<<n;a+=s%k<1)for(p=s=0;p<n;s+=1<<p++&b?p:0);++a;} ``` [Try it online!](https://tio.run/##bZLtToMwFIb/exUNyQysLJbC5rBUfxivwi0GujIJ2hFKInHh1sXT8pHNSGjped9znn4hVkch@j5lFdMsY7mr/NI756faTXnGCcM4S4IkUSzFXC/KJPCMV3ENXgWyxhzsCuPb7Kl6IB4UpKzrC9Wgz7RQrofONwgeIzRSN2/qdY84Ooc@WvsogA/10T2MImigxEMUDFGwGXJsTDt2jSoHFLWo7UQyIGIlaoPQqhAaFrlgyLaSopGHgRJZREBoZAspICISQ01It8QYoG@grQNqojiCcRwaJdhEkBAaIZonECelGyTe03oJvRSlrId5nF37Qndt/Axt7fjoMg6dsRrOGLlmjYU6yBbKCBuHCdLFtzzl7rR6724UlrPCEMY227Ow4QKmXSugjRdhc/bsyi4nu/zX1mCbfwSV3rUhwZgP9G9lVUNK7jqLA4J39Wj6hd4p2L5B@Uj78yFpzuV@hHc3Xf8j8o/0qPvV1y8 "C (gcc) – Try It Online") ### Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/247735/9481): # [C (gcc)](https://gcc.gnu.org/), ~~60~~ 59 bytes ``` t;g(n,s){n=n?g(n,s+n--)+g(n,s):s%t<1;}f(n,k){t=k;n=g(n,0);} ``` [Try it online!](https://tio.run/##bVHtaoMwFP3fp7gUCqYq02i7utTtx9hTrGWUNHbilhYTmEx89bmbRKUdE5Pcc869Jx@XhyfO@16zkycDRVqZyycb@jIMie/YB7XQ25h1BaKKtDqvmMyNFBHW9aXU8HkopUegnQF@htBC6Tf5uocc2iSAVQAxLjSAe4xSHMhkDsUOxWuXYzHt2K1V5ayotdqMTsYoshS1ILEsQuMVXXmI5iK4FkfnklqLOKKpLaRokUYZ1iR0ExkB@TWOVUwNylKMs8Qw8TrFhMQQ6bQBP0ulgb8f6iXOgleidvvMd80L3TXZM47VPIBrnMyH6uJcg2fOWMqjaLAsYkO4BVV@i3PhjacndwOxnBgGvm@ziTVzDRhvLdFtaITN2bMbuRrl6l9ZoWw6DhW5FQQK04P@rbzUmFJ488UR8A8fzbxQO4nXN1YBqGB6JJXnYj@Yd7Ou/@HFx@Gk@vDrFw "C (gcc) – Try It Online") *Saved a byte thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!!* [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/language/), ~~53 41~~ 38 bytes ~~-12~~ -15 bytes, thanks @att! ``` Tr[1##&@@@+++I^(4##&~Array~{##}/#)]/#& ``` [Try it online!](https://tio.run/##PY3NCsIwEITvfY2AKF1pk/THHpR4EbwpeisVgrQYaEVCeiihffXYJKWnb3Z2drbj6lN3XIk3N83RPGWJEdowxsIwvL62yTxMZyn5MGmExgjtqghtzL0XtWI3Kb6qtP7@dOnb9iG6XyuagTUlIoCqyvboQFMgIwQ6hdQCUzhYEu/mkDs3gcQxBRxbUfh07lMYr2vqmC1ndCnFkDmS9bxwT@LYB2ZhVTCaPw "Wolfram Language (Mathematica) – Try It Online") Previous solution by @att ``` Sum[1##&@@+++I^(4k/#2Range@#),{k,#2}]/#2& ``` [Try it online!](https://tio.run/##PYxNC4IwHMbvfo2BVP4jt/lSh2KnoFvlUQyGaA2dRMxDDP3q5jbp9Ht43iRXr0pyJUo@1ccp62WOEfIZC4Lg8lhFzQ6RO@@eFUNr0A0gMhSz5U@3XlSKXT@iUznans5922ZCvltRf9mmZgwV/piVvBu1pymQATwdQ2yAKewNiXNTSK0bQWQZAw6NOLh26loY/2NqmSwzupxiSCzJMidh6JJZGOUN0w8 "Wolfram Language (Mathematica) – Try It Online") Previous solution by me: ``` f=PolynomialMod;f[Product[1+x^i,{i,1,#1}],x^#2-1]~f~x& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/T/NNiA/pzIvPzczMcc3P8U6LTqgKD@lNLkk2lC7Ii5TpzpTx1BH2bA2VqciTtlI1zC2Lq2uQu1/tKGxjkVs7H8A "Wolfram Language (Mathematica) – Try It Online") First I forgot the `&` and Mathematica simplified the entire expression to `QPochammer[-1,x,1+#1]/2`. At first I was quite happy: a way to shorten the code! Before I realized that it can't be right because this removes an entire argument of the function. Sad times :( Using 58 bytes we can get code that is much faster at evaluating the answer for large inputs, with the only issue that it gives the answer as an expression involving exponentials of complex expressions: ``` Tr[Product[1+E^(2i I π k/#2),{i,1,#}]~Table~{k,1,#2}]/#2& ``` The expressions are equivalent to the correct number, but Mathematica only simplifies it down if we add `FullSimplify@` in front, resulting in a total of 71 bytes. [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS7VaakxOcmVuQk5lW6fA/pCg6oCg/pTS5JNpQ2zVOwyhTwVPhfINCtr6ykaZOdaaOoY5ybWxdSGJSTmpddTaIa1QbC5RU@x9tZGBgoGMaG/sfAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒP§ọTL ``` A dyadic Link that accepts \$n\$ on the left and \$k\$ on the right and yields the count of subset sums of \$[1,n]\$ divisible by \$k\$. **[Try it online!](https://tio.run/##y0rNyan8///opIBDyx/u7g3x@f//v6Hpf2MA "Jelly – Try It Online")** ### How? ``` ŒP§ọTL - Link: n, k ŒP - powerset of [1,n] § - sums ọ - how many times is each divisible by k? T - truthy indices L - length ``` --- Alternatively, using filter-keep: `ŒP§ọƇL` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` LæOsÖO ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f5/Ay/@LD0/z//zc05TIGAA "05AB1E – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ŒP§%ċ0 ``` [Try it online!](https://tio.run/##y0rNyan8///opIBDy1WPdBv8P7xc/1HTmv//o6ONdYxidaJNdUyBpKGxjgWQMgILmeuYg4RMdExAlKmOoQGQtgSrMwcrMDSESRmDKDOIemOISYY6ZiDKCKQtFgA "Jelly – Try It Online") ## How? ``` ŒP§%ċ0 Full program: Dyadic link f(n, k): ŒP Powerset of n, which is implicitly converted to range [1..n] § Sum of each % Modulo each by k ċ0 Count the number of zeros ``` Edit: Whoops, Jonathan Allan beat me by one minute. [Answer] # [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 50 bytes ``` [ [1,b] all-subsets swap '[ Σ _ mod 0 = ] count ] ``` [Try it online!](https://tio.run/##VZDLbsIwEEX3@Yq76wYQ5tmHWFds2KCuoqhyzBCsJrbrhxBCfE3/p7@Umkeo8d3cq5kzY3vLhde2/VgvV@@v4M5p4dBwvxtYriq6eaGbUioeO2UsV1YHI1WFrT3gi6yi@toWlBR6Q5cAR9@BlIgjjCXvD8ZK5fGWZccM8Rwxwhinm59Gdf4Z7L8wiur8PKrzE7DJPbAh2DSZ9ZLgDwi7h3FKzMFmCZ6sn6XMec35NqeszZGzXlmA13XfhdKRd3B7bvCU4/cHn2j0BkMsUEDoEN9dRGRwSY3Rjq4/3Scudu0f "Factor – Try It Online") Takes input as `k n`. [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 17 bytes ``` roR@{++dv}x/1iafl ``` [Try it online!](https://tio.run/##TY7NCsJADITvPkXuPZhkf@zefAYvnhVXUApqS1UoffZ1k5JiIHMYZr7kPPZdHl5jLtOEQPPweeZ76R@H/dQ0l/f83dLtdO3KfOwKgIM6DDp@UyWACUBbDdJEW5eQNcF/FRZjBybAKBWvNFlMUYyg9SqOW0lAWq8Q@pWxQKMYRMaAQGwMeZcweU1EO5vcUnEGpehxZWjMLRW2P8AT/gA "Burlesque – Try It Online") ``` ro # Range 1..n R@ # All subsets { ++ # Sum dv # Divides (a%b == 0) } x/ # reorder stack 1ia # Insert divisor in position 1 (zero-indexed) fl # Count of matches ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` I№﹪EX²N↨E⮌↨ι²∧λ⊕μ¹N⁰ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sRhI5JcCmb75KaU5@Rq@iQUaAfnlqUUaRjoKnnkFpSV@pblJQK6mpo6CU2JxKlhFUGpZahGQDRbI1FEwAsk65qVo5IA0JRel5qbmlaSmaORqgiQMQQS6WQZAKev//w1NuYz/65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ² Literal integer `2` X Raised to power N First input as an integer E Map over implicit range ι Current value ↨ Converted to base ² Literal integer `2` ⮌ Reversed E Map over bits λ Current bit ∧ Logical And μ Current index ⊕ Incremented ↨ ¹ Take the sum ﹪ Vectorised modulo N Second input as an integer № ⁰ Count the zeros I Cast to string Implicitly print ``` Base `1` conversion is used to sum as the first subset is empty and `Sum` doesn't like that. For 23 bytes, a much more efficient version: ``` ≔EN¬ιθFNUMθ⁺κ§θ⁻λ⊕ιI§θ⁰ ``` [Try it online!](https://tio.run/##VYy9DsIgFIX3PsUdLwkmxMTJqenE0KavgBSVCJeWH@PbI2y6nXznfEc/VdRBuVrHlOyDcFY7StpLXoq/mYiMwxIyWtbCwa7DPUT4HzBozhS8V7ThwWF1JeGLw5glbebT0WypMcdBko7GG8pm65esHa7RUsZJpYw/huhdrZfhLISop7f7Ag "Charcoal – Try It Online") Link is to verbose version of code. Takes arguments in the order `k, n`. Explanation: ``` ≔EN¬ιθ ``` Make a list of `k` elements where the first is `1` and the rest are `0`. ``` FN ``` For `i` from `1..n` (actually 0-indexed but I use `Incremented(i)` below)... ``` UMθ⁺κ§θ⁻λ⊕ι ``` ... cyclically rotate the list by `i` and vectorised add it back. ``` I§θ⁰ ``` Output the first element of the result. [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` #¦⁰mΣṖḣ ``` [Try it online!](https://tio.run/##ARsA5P9odXNr//8jwqbigbBtzqPhuZbhuKP///81/zk "Husk – Try It Online") ``` #¦⁰mΣṖḣ ḣ # get the sequence 1..arg2 Ṗ # and get the powerset (all finite subsets); m # now map over each subset: Σ # get the sum # # and count the number of results ¦ # that are divisible by ⁰ # arg1 ``` ]
[Question] [ # Description of the problem Imagine a quarter of an infinite chessboard, as in a square grid, extending up and right, so that you can see the lower left corner. Place a 0 in there. Now for every other cell in position `(x,y)`, you place the smallest non-negative integer that hasn't showed up in the column `x` or the row `y`. It can be shown that the number in position `(x, y)` is `x ^ y`, if the rows and columns are 0-indexed and `^` represents bitwise `xor`. ## Task Given a position `(x, y)`, return the sum of all elements below that position and to the left of that position, inside the square with vertices `(0, 0)` and `(x, y)`. # The input Two non-negative integers in any sensible format. Due to the symmetry of the puzzle, you can assume the input is ordered if it helps you in any way. # Output The sum of all the elements in the square delimited by `(0, 0)` and `(x, y)`. # Test cases ``` 5, 46 -> 6501 0, 12 -> 78 25, 46 -> 30671 6, 11 -> 510 4, 23 -> 1380 17, 39 -> 14808 5, 27 -> 2300 32, 39 -> 29580 14, 49 -> 18571 0, 15 -> 120 11, 17 -> 1956 30, 49 -> 41755 8, 9 -> 501 7, 43 -> 7632 13, 33 -> 8022 ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 19 bytes ``` {sum [X+^] 0 X..@_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv7q4NFchOkI7LlbBQCFCT88hvvZ/cWKlQpqCqY6Cidl/AA "Perl 6 – Try It Online") The sum of the bitwise xor between all numbers in the range 0 to all inputs. [Answer] # [Python 2](https://docs.python.org/2/), 49 bytes ``` lambda x,y:sum(k/-~x^k%-~x for k in range(~x*~y)) ``` [Try it online!](https://tio.run/##RY7daoQwEIXvfYphoWDKlObXRMHbPkEvSyGl2i7uxkVdUEp9dTuJu/QimXwz55zMZZm@@yC3tn7bTv788elhxqUar@e8e35a5/fugW5o@wE6OAYYfPhq8nV@XBfGtqH@eR2uTQUHPx4QXvxpjBD6Cajxm0UbxWETrXmWg0HQBUJhuGBIzBGERLAukrxNFS/sPiYQAsEInlAjSEUt5RILS9qSWDueAmK8tFHEk0DJXSBLc3NQgo4OZ@z/AiYusc/ps5gqSlOkAL7rtbDGJL1DAGrc9yetpo1soWTy01vRcVxGZlUGl@EYpnxGWBBaqgu717pu2PYH "Python 2 – Try It Online") The usual [div-mod trick for iterating over two ranges](https://codegolf.stackexchange.com/a/41217/20260). Unfortunately, since we want inclusive ranges, we need to raise each input by 1, which we do with `-~`. Thanks to Bubbler for saving 2 bytes by cancelling the minuses on `-~x*-~y`. Python 3 would be a byte longer using `//`. I tried to use the 3.8 walrus operator to cut down on the `-~x` repetition, without success. **55 bytes** ``` f=lambda m,n:m|n>0and(m^n)+f(m-1,n)+f(m,n-1)-f(m-1,n-1) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIVcnzyq3Js/OIDEvRSM3Lk9TO00jV9dQB8LQydM11NSFigCZ/wuKMvNKFNI0DHQMDTS5YDxjHVMEx1zHXPM/AA "Python 2 – Try It Online") A cute recursion, but unfortunately longer. This doesn't use anything particular about XOR -- this same method can be used to add up any two-variable function over a rectangle. The base case `m|n>0` terminates with zero when either `m` or `n` becomes negative, or (harmlessly) when both are zero. This will time out on larger test cases due to the huge degree of recursive branching. **52 bytes** ``` f=lambda m,n,b=1:m|n>0and(m^n)+f(m,n-1)*b+f(m-1,n,0) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIVcnTyfJ1tAqtybPziAxL0UjNy5PUztNAyiua6iplQRi6hoCFRlo/i8oyswrUUjTMNAxNNDkgvGMdUwRHHMdc83/AA "Python 2 – Try It Online") A similar shorter recursion. The idea is that we can recursively travel left or down, but once we've gone left, we set to flag `b` to zero and ignore the results of any further travel down. The result is that we travel to each cell in the rectangle exactly one, like this: ``` O < O < O < O v O < O < O < O v O < O < O < O ``` **Other ideas** Here are some partial ideas that didn't lead to decent golfs, but maybe someone can make use of them. The one-dimensional summation (on a half-open range) ``` w=lambda i,n:sum(i^j for j in range(n)) ``` can be expressed recursively as ``` w=lambda i,n:i+n and 4*w(i/2,n/2)+n%2*(n^i^1)+n/2 ``` (Python 2 used for floor division.) We also have an efficient formula $$f(m-1,n-1) = \sum\_{i=0}^{\infty} {\frac{m n - |m \odot 2^{i}||n \odot 2^{i}|}{2} 2^i}$$ where \$ \odot k\$ is the symmetric modulo-\$(2k)\$ operator mapping to the range from \$-k\$ to \$k\$. This summation can be truncated where \$2^i\$ is bigger than the inputs, since further terms will be zero. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes ``` Array[BitXor,{##}+1,0,Plus]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8d@xqCixMtopsyQiv0inWlm5VttQx0AnIKe0OFbtv6Y1V0BRZl5JNEhC1y7NQVk5Vs3BwaGai6vaVEfBxKxWh6vaQEfB0AjEMIIIcXHV/gcA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 36 bytes ``` ->x,y{(0..y+x*y+=1).sum{|r|r/y^r%y}} ``` [Try it online!](https://tio.run/##PZDbasMwEETf9yv00mLXiqzV3W2cH2nTkF4CAScNcgMWtr/dlRTSl4XDzOws668fYTm0y2oz0DAWnLFQDU@harFk/fU0Tn7ydXj3D2Gel/V6GAbWHc/fPTvtL@PUTTFFfdux/nN/Luq3r6ouk1Q8Pv/@7I7ly4W8JsshzS312xk0JcqQ1YYYzRE4JSgSWQfiX5LcWAQTNUyokYOiRMgEKB0HtJTIJqNy3KWlwiYUknOQ4q6KRid3DKub22l7K9UZRRQxUs5iow1IfvcqtFqDoyRTOjaWqnyDNVIAytiS0XEhIL5m@QM "Ruby – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 15 bytes ``` +/,{⊥≠/⊤⍵}¨⍳1+⎕ ``` [Try it online!](https://tio.run/##NY67SgNBFIZrz1OcPoacy9x2e4VUPkNgN4sQNkEsFLH1EojYWAoWCvbiC/go8yLrzM6m/Ob7@Oesdpt5c7vabLt5e3Pd9k3bDPHlbXkRH14J4tPjepgtTu/i/is@fyzi/jMefu//vuPhh2epG1KRqw7q8@0VXmK97DFLCydrqM/6Jj3nYOjAonGY5Ds6SwyELAV9ABllBiXnGRwyF2mZwKBoIdZAwB61KmgChTQsvmhRIlA5aqlszg2aKQ/Wjx/baU2SZUx7I1XWgdIxNuythYAVToekmz2a6RDvVIAVVUcMJPIP "APL (Dyalog Extended) – Try It Online") Full program. ### How it works ``` +/,{⊥≠/⊤⍵}¨⍳1+⎕ ⎕ ⍝ Take a pair [x y] from stdin ⍳1+ ⍝ Generate indices from [0 0] to [x y] inclusive { }¨ ⍝ For each pair, ⊤⍵ ⍝ Convert two numbers into two-column bit matrix ⍝ (each column is binary representation of each number) ≠/ ⍝ Reduce each row with not-equals (XOR) ⊥ ⍝ Convert the resulting binary representation back to integer +/, ⍝ Sum all elements and implicit print ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ý`δ^˜O ``` [Try it online](https://tio.run/##yy9OTMpM/f//8NyEc1viTs/x//8/2lTHxCwWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w3MTzm2JOz3H/7/O/@hoUx0Ts1idaAMdQyMgZQTlmukYGgIpEx0jYyBlaK5jbAmkTXWMzIGUsRGEa2iiY2IJ0WsK4hrqGIKlDSDCFjog0lzHBGyEsY6xcWwsAA). **Explanation:** ``` Ý # Push a list in the range [0,value] for each value in the (implicit) input-pair ` # Push both these lists separated to the stack δ # Apply double-vectorized: ^ # XOR them together ˜O # And then take the flattened sum # (after which the result is output implicitly) ``` [Answer] # [J](http://jsoftware.com/), ~~23~~ 17 bytes -6 bytes thanks to Bubbler! ``` 1#.1#.XOR/&(i.,]) ``` [Try it online!](https://tio.run/##HYu7CsJAFET7fMUhislC3OTuI3EDVoKVIKSysRKD2vj/1XpXmGGGeXxybZuV40xDx8Cs3FtOy@WcZWMVt@vS79q37e4mm4rq@Xh9WXtqgVYiji2RMOpRHO5vR0QIOI9M@KS9U3XFSiCkso1lU@qhBAcSE0EPHu9N/gE "J – Try It Online") # [K (oK)](https://github.com/JohnEarnest/ok), 25 bytes ``` {+/2/'~=/'(64#2)\''+!1+x} ``` [Try it online!](https://tio.run/##JYs7DoMwEESvMlGKBVnI7Md2yCo3SU1DQYsUJVc3xmlGejPztmnfal2fnxAl0u8Vach2l/FNFG4cjm9daUiw7JjB4pA/ZDA7DKIOLtDFkSDFodKBDbZ0JzXg9mnT3LsHWhTYZSpUx3oC "K (oK) – Try It Online") Most probably can be golfed further. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ^þ/;RSS ``` [Try it online!](https://tio.run/##y0rNyan8/z/u8D5966Dg4P8Pd@6zftQwR0HXTuFRw1zrw@1ch9sfNa2J/P8/OtpUR8HELFZHIdpAR8HQCMQwgguZAYUMQQwTHQUjYxDD0FxHwdgSxAIqMjIHMYyNYEKGQGUmljCzTMFChkAWRJkBTNJCRwFMA40ygRhqDDTBODYWAA "Jelly – Try It Online") A monadic link taking a pair of integers and returning an integer. A couple of alternative 7-byters: [`Ż€^þ/SS`](https://tio.run/##y0rNyan8///o7kdNa@IO79MPDv7/cOc@60cNcxR07RQeNcy1PtzOdbgdKBv5/390tKmOgolZrI5CtIGOgqERiGEEFzIDChmCGCY6CkbGIIahuY6CsSWIBVRkZA5iGBvBhAyBykwsYWaZgoUMgSyIMgOYpIWOApgGGmUCMdQYaIJxbCwA "Jelly – Try It Online") [`‘Ḷ^þ/SS`](https://tio.run/##y0rNyan8//9Rw4yHO7bFHd6nHxz8/@HOfdaPGuYo6NopPGqYa324netw@6OmNZH//0dHm@oomJjF6ihEG@goGBqBGEZwITOgkCGIYaKjYGQMYhia6ygYW4JYQEVG5iCGsRFMyBCozMQSZpYpWMgQyIIoM4BJWugogGmgUSYQQ42BJhjHxgIA "Jelly – Try It Online") [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 18 bytes ``` psqrzMPcp{q$$r[}ms ``` [Try it online!](https://tio.run/##PY69CsIwFIX3@xQZBJcU7k9uklLwDRT36qK4WbEtXSx99ppE6vjxncM5t2l4PsZ@eqzPVzfvq6aprnvbNJd2mdf32A@f4/n@nvvdbmiXblyXazedVrXGeVMdjFckQGuIM4UI/FeCPhD45CijEoKzhiUDSUSgYI3UBV3ECKnJISMLIghvlmvN6VR2v3TU8BvVgpwkJSpdqtWD4JZ1FFQhWlMon02jrnwIXhhI0krBiMxf "Burlesque – Try It Online") ``` ps # Parse to arr of ints qrz # Boxed range [0,N] MP # Map push cp # Cartesian product { q$$ # Boxed xor r[ # Reduce by }ms # Map sum ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 48 bytes ``` R;f(x,y){R=++x*++y;for(y=0;--R;y+=R%x^R/x);x=y;} ``` [Try it online!](https://tio.run/##jZLLasMwEEX3/YohELDjMdGMnka4H@F1KZQEhyzqltCFTci3u5IdeVl1I2ZzOHdG91RfTqd57nxfjDiV966tqvFQVZPvv27F1Apf152fqrbbj@/dcSz92E7@MX9@XIeivL98367DT1/s9nxGCA/Ur7A/vw07BI0AyiD0hUZlytIDHA9gtCA4HP8CRQCJIyiQOIHWZTAOwtXHSRgwKYzNCU0UUiQNEiWhJpHhVOBYRk4hy8SRdDmQLIJsIhgm2TyjknIit2Q8Ktv1qGyTkqXIKSUnZZg2JTc6HzasqdawCtUW1mn7r4/Uz4/U2304a6T1RMFISDYZG21yS4oUNUxbVEVW6wzpQlRYSIcLt1Yg21UbS75UwKLaKmCN5NyOAZILGCYpn1Gd4AV8zL8 "C (gcc) – Try It Online") [Answer] # Java 8, 58 bytes ``` (x,y)->{int t=++x*-~y;for(y=0;--t>0;)y+=t%x^t/x;return y;} ``` Port of [*@xibu*'s C answer](https://codegolf.stackexchange.com/a/200181/52210), so make sure to upvote him! [Try it online.](https://tio.run/##LVDRboIwFH33K25MlsC4MAqo0waTfcB88ZFg0lVccFhMKY6GsF9nLfhyTs5pe@7pvbIH86/nn5FXrGngk5WiXwCUQhXywngBBysnA7hjsUOL2qXGHxYGGsVUyeEAAtLR6VC7/r63d1Tqed2r/6fppZaOTkPq@2ofUld7qXrpTuqto7JQrRSg6TBSG3ZvvyoT9sx81OUZbqaTc1SyFN9ZDsydC9lIM8Q4HHYgil@YVJb3/QqT9YB9iCQyFD3lGgkxlGAUGyIbjLeGVxhtDMXRLEmCyXZ@u7KSIJmOw9l@R4sbTKaIGON4GNypDsBRN6q4BXWrgrvpqirhXM1yg1aVVfAhJdNNoOr5Hw53veUOlp4IuMOzMEeekdx97nQY/wE) **Explanation:** ``` (x,y)->{ // Method with two integer parameters and integer return-type int t=++x // Increase `x` by 1 first with `++x` *-~y; // Create a temp integer `t`, with value `x*(y+1)` for(y=0; // Reset `y` to 0 to reuse as result-sum --t>0;) // Loop as long as `t-1` is larger than 0, // decreasing it before every iteration with `--t` y+= // Increase the result-sum by: t%x // `t` modulo-`x` ^ // Bitwise XOR-ed with: t/x; // `t` integer-divided by `x` return y;} // And then return the result-sum `y` ``` [Answer] # [Clojure](https://clojure.org/), 72 bytes ``` (defn s[x y](apply +(for[a(range(inc x))b(range(inc y))](bit-xor a b)))) ``` Ungolfed: ``` (defn sumxy[x y] (apply + (for [a (range (inc x)) b (range (inc y)) ] (bit-xor a b)))) ``` Tests: ``` (println (s 5 46) " <-> " 6501) (println (s 0 12) " <-> " 78) (println (s 25 46) " <-> " 30671) (println (s 6 11) " <-> " 510) (println (s 4 23) " <-> " 1380) (println (s 17 39) " <-> " 14808) (println (s 5 27) " <-> " 2300) (println (s 32 39) " <-> " 29580) (println (s 14 49) " <-> " 18571) (println (s 0 15) " <-> " 120) (println (s 11 17) " <-> " 1956) (println (s 30 49) " <-> " 41755) (println (s 8 9) " <-> " 501) (println (s 7 43) " <-> " 7632) (println (s 13 33) " <-> " 8022) ``` [Try it online!](https://tio.run/##bZHLasMwEEX3@YpLVxIloBk9DaE/ErKwU6e4GNkoKdhf73gXSakWAsHh3Duj6zj9/qV@28R3f4u4nxesF9HO87jiE@I2pXMrUht/ejHEKxYpu@y5SnkR3fA4LlNCi07u53AQcxriY4wQd8DCOIkPnI5f@w1nFcmSUCDOCMCHkuDSoZXztcOBKHdYUhVhwDojSIeKIA/dvAgyQVU99lnYZw7WqnJoLhzc2LcUA5OnBOv/2YfNZyGuHbSXzWdprKt6qCLFkLe2SglAU2zs7V88TL4x7zRXPTR0TgTFLLftCQ "Clojure – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ô ï^Vô ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=9CDvXlb0&input=NSw0Ng) ``` ô ï^Vô :Implicit input of integers U & V ô :Range [0,U] ï :Cartesian product with Vô :Range [0,V] ^ :Reduce each pair by XORing :Implicit output of sum of resulting array ``` [Answer] # JavaScript (ES6), 41 bytes Takes input as `(x)(y)` (or the other way around). Computes the sum recursively, the obvious way. ``` x=>g=(y,Y=y)=>~x&&(x^y)+g(y?y-1:x--&&Y,Y) ``` [Try it online!](https://tio.run/##bZBBasMwEEX3PYVXZobGjWakkeSC0nN4UwhpYlJCXJpSrE2v7jpIJUXO@vH@nz/v2@/tZfd5/PhqzsPbfjqEaQybPkBcdSFi2PyMdQ3ja8THHuJLbOh5bJq67lYdTrvhfBlO@6fT0MMBKkEwFrFarysrih4KrBCIE3a@gPzP1cq6hWxnmRIXUiU1CKwTJe1LTA5Btxkbr8ry6@HsEmetSl3zTedWlvFzu/mL9@LuDpfMeWETXg9MtBVblqtbuCEnUoZ7hCrzOz@fl5v8GGc1l916XpaxV8zTLw "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~59~~ 58 bytes Saved a byte thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) and [HyperNeutrino](https://codegolf.stackexchange.com/users/68942/hyperneutrino)!!! ``` lambda x,y:sum(a^b for a in range(x+1)for b in range(y+1)) ``` [Try it online!](https://tio.run/##RZDNaoQwFIX3PsXFVUJTyK9RwS77BN31B2IntgMzKuqAIj67vYlTZiHxO/eck0v6ZfrtWrU31cd@cdf65GBmSznersR91dB0Azg4tzC49seT@UnQINUPaUGJ7kO1vg03X0LqxpTBq7uMAdpuAhS2JISwl/kQJAkBw0BnDDLDBWXInIGQDGweSN6nimf2GCMIwcAIHlEzkAollUcWFr0Fss55LAj10gYTjwYlD4MszD2BDTokcmMfC5iwxDHHy0KrKEwWC/jh18IaE/05A0Dhf3/0atzIZkrGPP4r/HIuA9MygX44txNp0nUu5cZgXfCA5xdYG4IvQ0uzwTq8H1BV/nMDP/f@e/KnlO5/ "Python 3 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~61~~ 52 bytes Saved 9 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! ``` b;s;f(x,y){for(s=b=y;~x;b--||(b=y,x--))s+=x^b;s-=y;} ``` [Try it online!](https://tio.run/##jZLPasMwDIfvewpRKCSdTC35bwjdk4zB2pHRw7rR7pDSdq@eyUmd47yLkUk@vp9k7dT7bjcM2/bUdlWP5/rSfR6r02a7Obc/fbtV6nqt5IK9UnV9etz0L/Kvkq@34eN1f6jqy8PXcX/47qrFkt8Q5AD1BMu358MCwSGA9Qhd5dD6um4B1ivwThOs1n@BWkDiBGokzmCIBYxFOPk4CwUz2oeS0CchJdIjURY60gXOCscmcRbZZI5MLIEUEEyTQKlMc49KNupSk2moHKahcshKNrqkNJyVUs1Kblw5rLRpp7AW7Rw2uvCvh3T3h3TzfLhopGlEYiSkkI2N86UmdY4q1RzVUnCuQEaJCiMZceSmFSjuakhLPq5AQDuvQPCGSz0KZEZQKmPuUaPmEbwNvw "C (gcc) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes ``` Sum[i~BitXor~j,{i,0,#},{j,0,#2}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P7g0NzqzzimzJCK/qC5LpzpTx0BHuVanOgtEG9XGqv0PKMrMK1FwSI821TExi/3/HwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 31 bytes ``` eval '<<<$[' +{0..$1}^{0..$2} ] ``` [Try it online!](https://tio.run/##qyrO@J@moanBVZxaoqBboaCgoKyQll@k4JKaVJquUJZZXJqYk1mVWJKZn6eQn5dT@T@1LDFHQd3GxkYlWl1Bu9pAT0/FsDYOTBvVKsT@1@TiSlMwVTAx@w8A "Zsh – Try It Online") Uses `eval` to expand the `<<<$[` `]` after expanding the lists. The TIO link adds `set -x` so you can see what the brace expansion looks like. [Answer] # [Perl 5](https://www.perl.org/) `-pa`, 36 bytes ``` map{//;map$\+=$_^$',0..$F[0]}0..<>}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saBaX98aSKnEaNuqxMepqOsY6OmpuEUbxNYCGTZ2tdX//5tymZj9yy8oyczPK/6v62uqZ2Bo8F@3IBEA "Perl 5 – Try It Online") Takes in inputs on separate lines. [Answer] # Oracle SQL, 126 bytes This isn't a golfing language and it doesn't have a bitwise XOR operator but: ``` SELECT SUM(x+y-2*BITAND(x,y))FROM(SELECT LEVEL-1 x FROM T CONNECT BY LEVEL<x+2),(SELECT LEVEL-1 y FROM T CONNECT BY LEVEL<y+2) ``` Assumes that there is a table `T` with columns `X` and `Y` containing one row that has the input values. So for the inputs: ``` CREATE TABLE t(x,y) AS SELECT 5,46 FROM DUAL; ``` This outputs: > > > ``` > > | SUM(X+Y-2*BITAND(X,Y)) | > | ---------------------: | > | 6501 | > > ``` > > *db<>fiddle [here](https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=48a954394774b113027ebb635c07d6a3)* --- As an aside, its only 81 characters in PostgreSQL: ``` SELECT sum(a#b)FROM t,generate_series(0,t.x)AS x(a),generate_series(0,t.y)AS y(b) ``` *db<>fiddle [here](https://dbfiddle.uk/?rdbms=postgres_12&fiddle=e34aca835030c0dea9a6ae26ef19c04c)* But its less fun as that has a built-in XOR operator and series generation. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ò@Vò^XÃc ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=8kBW8l5Yw2M&input=NQo0Ng) [Answer] # [Julia 1.0](http://julialang.org/), 33 bytes ``` (x,y)->sum(i⊻j for i=0:x,j=0:y) ``` [Try it online!](https://tio.run/##yyrNyUw0rPifZvtfo0KnUlPXrrg0VyPzUdfuLIW0/CKFTFsDqwqdLCBZqfm/oCgzryQnTyNNw1THxExTkwshYKBjaKSp@R8A "Julia 1.0 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 51 bytes ``` d,r;f(x,y){for(d=y;~d||(x--,d=y),~x;)r+=x^d--;d=r;} ``` [Try it online!](https://tio.run/##DcfBDYAwCAXQdSDyJyCs4gVSjyacaKxdHX2357jcu0NSB5VMfsadFDZ1x1pUgPxh2aWch9UZgIalvt0f "C (gcc) – Try It Online") ]
[Question] [ ### Introduction Sometimes, my boxes are too small to fit anything in it. I need you to make a box expander! So, what makes a box a box in this challenge. ``` OOOO O O O O O O OOOO ``` The corners of the box are **always** spaces. The box itself can be made out of the same character. That character can be any [printable ASCII character](http://meta.codegolf.stackexchange.com/q/5866/34718), except a space. So, that's these characters: ``` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` The side lengths of the box above are **4, 3**. You may assume that the side length is always **positive**. That means that this is the smallest box you need to handle: ``` # # # # ``` In order to expand a box, you need to increment each side length. Let's go through this, step by step, with the above example. We first take the upper side of the box, which is: ``` OOOO ``` We expand this by one, so we get: ``` OOOOO ``` This is the upper and lower part of the box now. After that, we do the same with the sides on the left and right: ``` O O O ``` Becomes: ``` O O O O ``` Now we reassemble the box, which results into: ``` OOOOO O O O O O O O O OOOOO ``` ### The task Given a box, expand it by 1. The box can be given in multiple lines, or in an array. ### Test cases ``` OOOO OOOOO O O > O O OOOO O O OOOOO XXXXXX XXXXXXX X X > X X X X X X XXXXXX X X XXXXXXX ~ ~~ ~ ~ > ~ ~ ~ ~ ~ ~~ ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! [Answer] # Vim, 7 bytes ``` ♥GYPjYp ``` where ♥ is Control-V. ``` The cursor starts on the first non-whitespace character of the first line. ♥G Enter visual block mode and go to bottom of document. YP Duplicate this column. j Move down to the second line of the file. Yp Duplicate this line. ``` [![enter image description here](https://i.stack.imgur.com/XiTxx.gif)](https://i.stack.imgur.com/XiTxx.gif) [Answer] ## JavaScript (ES6), ~~57~~ ~~53~~ 52 bytes ``` s=>s.replace(/^.(.)/gm,s="$&$1").replace(/(\n.*)/,s) ``` Explanation: The first regexp duplicates the second column and the second regexp duplicates the second row, thus enlarging the box as desired. Edit: Saved 4 bytes thanks to MartinEnder♦. [Answer] ## Python, ~~49~~ 42 bytes Anonymous lambda: -7 from **xnor** ``` lambda s:[t[:2]+t[1:]for t in s[:2]+s[1:]] ``` Previous version: ``` D=lambda s:s[:2]+s[1:] lambda s:D(list(map(D,s))) ``` D is a function that duplicates the second item of a sequence. [Answer] ## [Retina](https://github.com/m-ender/retina/), 20 bytes Byte count assumes ISO 8859-1 encoding. ``` 1`¶ ¶$%'¶ %2=`. $&$& ``` [Try it online!](http://retina.tryitonline.net/#code=wrYKwrcKU2DCt8K3CiUoU2DCtwoxYMK2CsK2JCUnwrYKJTI9YC4KJCYkJgpTYCQ&input=IE9PT08KTyAgICBPCiBPT09PCgogWFhYWFhYClggICAgICBYClggICAgICBYCiBYWFhYWFgKCiB-Cn4gfgogfg) (There's several additional lines which enable a test suite where the test cases are separated by two linefeeds.) ### Explanation ``` 1`¶ ¶$%'¶ ``` `1` is a *limit* which restricts Retina to apply the substitution only to the first match it finds. `¶` matches a single linefeed, so we only need to consider replacing the linefeed at the end of the first line. It is replace with `¶$%'¶`, where `$%'` inserts the entire line following the match (a Retina-specific substitution element). Hence, this duplicates the second line. ``` %2=`. $&$& ``` Here, `%` is per-line mode, so each line is processed individually, and the lines are joined again afterwards. `2=` is also a limit. This one means "apply the substitution only to the second match". The match itself is simple a single character and the substitution duplicates it. Hence, this stage duplicates the second column. [Answer] ## Haskell, 24 bytes ``` f(a:b:c)=a:b:b:c f.map f ``` Uses [RootTwo's](https://codegolf.stackexchange.com/a/89694/20260) idea of duplicating the second row and column. The `map f` does this to each row, and the `f.` then does this to the rows. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~6~~ 5 bytes ``` yêpjÄ ``` [Try it online!](http://v.tryitonline.net/#code=ecOqcGrDhA&input=IE9PT08KTyAgICBPCk8gICAgTwpPICAgIE8KIE9PT08) This is actually a byte longer than it should be. It should have been: ``` äêjÄ ``` But this has an unknown bug. :( Explanation: ``` yê "yank this colum p "paste what we just yanked j "move down to line 2 Ä "and duplicate this line ``` [Answer] ## PowerShell v2+, ~~57~~ ~~53~~ 52 bytes ``` param($n)($n-replace'^.(.)','$&$1')[0,1+1..$n.count] ``` Slightly similar to Neil's [JavaScript answer](https://codegolf.stackexchange.com/a/89676/42963). The first replace matches the beginning of the line and the next two characters, and replaces them with the first character and second-character-twice. Instead of a second replace, it's swapped out for array-indexing to duplicate the second line. Takes input as an array of strings. The resultant array slices are left on the pipeline and printing is implicit. *Saved 4 bytes thanks to Martin.* Some examples: ``` PS C:\Tools\Scripts\golfing> .\automatic-box-expander.ps1 ' oooo ','o o',' oooo ' ooooo o o o o ooooo PS C:\Tools\Scripts\golfing> .\automatic-box-expander.ps1 ' # ','# #',' # ' ## # # # # ## ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~28~~ 26 bytes **2 bytes thanks to Fatalize.** ``` {bB,?~c[A:C]hl2,A:Bc.}:1a. ``` [Try it online!](http://brachylog.tryitonline.net/#code=e2JCLD9-Y1tBOkNdaGwyLEE6QmMufToxYS4&input=WyIgT09PTyI6Ik8gICAgTyI6Ik8gICAgTyI6Ik8gICAgTyI6IiBPT09PIl0&args=Wg) [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` tZy"@:2hSY)! ``` Input is a 2D char array, with semicolon as row separator. For example, the first test case has input ``` [' OOOO ';'O O';' OOOO '] ``` **Try it online!** Test cases [**1**](http://matl.tryitonline.net/#code=dFp5IkA6MmhTWSkh&input=WycgT09PTyAnOydPICAgIE8nOycgT09PTyAnXQ), [**2**](http://matl.tryitonline.net/#code=dFp5IkA6MmhTWSkh&input=WycgWFhYWFhYICc7J1ggICAgICBYJzsnWCAgICAgIFgnOycgWFhYWFhYICdd), [**3**](http://matl.tryitonline.net/#code=dFp5IkA6MmhTWSkh&input=WycgfiAnOyd-IH4nOycgfiAnXQ). ### Explanation The code does the following twice: repeat the second row of the array and transpose. To repeat the second row of an `m`×`n` array, the vector `[1 2 2 3 ... m]` is used as row index. This vector is generated as follows: range `[1 2 3 ... m]`, attach another `2`, sort. ``` t % Take input implicitly. Duplicate Zy % Size of input as a two-element array [r, c] " % For each of r and c @ % Push r in first iteration (or c in the second) : % Generate range [1 2 3 ... r] (or [1 2 3 ... c]) 2hS % Append another 2 and sort Y) % Apply as row index ! % Transpose % End for. Display implicitly ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` L+<b2tbyMy ``` [Try it online!](http://pyth.herokuapp.com/?code=L%2B%3Cb2tbyMy&input=%22+OOOO%22%2C%22O++++O%22%2C%22O++++O%22%2C%22O++++O%22%2C%22+OOOO%22&debug=0) [Answer] # SED 69 19 (14 + 1 for -r) 15 ``` s/.(.)/&\1/;2p ``` [Answer] # [CJam](https://sourceforge.net/projects/cjam/), 14 bytes ``` q~{~\_@]z}2*N* ``` Similar to [my MATL answer](https://codegolf.stackexchange.com/a/89685/36398), but repeats the second-last row instead of the second. [**Try it online!**](http://cjam.tryitonline.net/#code=cX57flxfQF16fTIqTio&input=WyIgWFhYWFhYICIgIlggICAgICBYIiAiWCAgICAgIFgiICJYICAgICAgWCIgIiBYWFhYWFggIl0) ### Explanation ``` q e# Read input ~ e# Interpret as an array { }2* e# Do this twice ~ e# Dump array contents onto the stack \ e# Swap top two elements _ e# Duplicate @ e# Rotate ] e# Pack into an array again z e# Zip N* e# Join by newlines. Implicitly display ``` [Answer] # K, 15 bytes ``` 2{+x@&1+1=!#x}/ ``` Takes input as a matrix of characters: ``` b: (" OOOO ";"O O";" OOOO ") (" OOOO " "O O" " OOOO ") ``` Apply a function twice (`2{…}/`) which gives the transpose (`+`) of the right argument indexed (`x@`) by the incremental run-length decode (`&`) of one plus (`1+`) a list of the locations equal to 1 (`1=`) in the range from 0 up to (`!`) the size of the outer dimension of the right argument (`#x`). Step by step, ``` #b 3 !#b 0 1 2 1=!#b 0 1 0 1+1=!#b 1 2 1 &1+1=!#b 0 1 1 2 b@&1+1=!#b (" OOOO " "O O" "O O" " OOOO ") +b@&1+1=!#b (" OO " "O O" "O O" "O O" "O O" " OO ") 2{+x@&1+1=!#x}/b (" OOOOO " "O O" "O O" " OOOOO ") ``` Try it [here](http://johnearnest.github.io/ok/index.html?run=%202%7B%2Bx%40%261%2B1%3D%21%23x%7D%2F%28%28%22%20%23%23%20%22%3B%22%23%20%20%23%22%29%400%201%200%29) with oK. [Answer] # APL, ~~17~~ 15 bytes ``` {⍉⍵⌿⍨1+2=⍳≢⍵}⍣2 ``` Test: ``` smallbox largebox ┌───┬──────┐ │ # │ OOOO │ │# #│O O│ │ # │O O│ │ │O O│ │ │ OOOO │ └───┴──────┘ {⍉⍵⌿⍨1+2=⍳≢⍵}⍣2 ¨ smallbox largebox ┌────┬───────┐ │ ## │ OOOOO │ │# #│O O│ │# #│O O│ │ ## │O O│ │ │O O│ │ │ OOOOO │ └────┴───────┘ ``` Explanation: ``` ⍣2 run the following function 2 times: { } stretch the box vertically and transpose ⍳≢⍵ indices of rows of box 2= bit-vector marking the 2nd row ⍵/⍨1+ replicate the 2nd row twice, all other rows once ⍉ transpose ``` [Answer] ## [ListSharp](https://github.com/timopomer/ListSharp), 326 bytes ``` STRG a=READ[<here>+"\\a.txt"] ROWS p=ROWSPLIT a BY ["\r\n"] ROWS p=GETLINES p [1 TO p LENGTH-1] ROWS p=p+p[1]+p[0] STRG o=p[0] ROWS y=EXTRACT COLLUM[2] FROM p SPLIT BY [""] ROWS x=EXTRACT COLLUM[3] FROM p SPLIT BY [""] [FOREACH NUMB IN 1 TO o LENGTH-1 AS i] ROWS m=COMBINE[m,x] WITH [""] ROWS m=COMBINE[y,m,y] WITH [""] SHOW=m ``` I *definitely* need to add the nesting of functions, but this works very well comment if you want an explanation [Answer] # JavaScript, ~~160~~ ~~146~~ 141 bytes ``` s=>{a=s[1];r="";l=s.split("\n");m=l.length;n=l[0].length;for(i=0;i<=m;i++){for(j=0;j<=n;j++)r+=!(i%m)&&j%n||i%m&&!(j%n)?a:" ";r+="\n"}return r} ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 14 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) ``` (1 2,1↓⍳)¨∘⍴⌷⊢ ``` > > > > > > `(` > > > > > > > > > > > > `1 2,` {1, 2} prepended to > > > > > > > > > `1↓` one element dropped from > > > > > > > > > `⍳` the indices > > > > > > > > > > > > > > > `)¨` of each > > > > > > > > > `∘` of > > > > > > > `⍴` the {row-count, column-count} > > > > > > > > > `⌷` indexes into > > > > > > > `⊢` the argument > > > > > > > > > E.g. for ``` XX X X XX ``` we find the indices; {1, 2, 3} for the rows, and {1, 2, 3, 4} for the columns. Now we drop the initial elements to get {2, 3} and {2, 3, 4}, and then prepend with {1, 2}, giving {1, 2, 2, 3} and {1, 2, 2, 3, 4}. Finally, we use this to select rows and columns, simultaneously doubling row 2 and column 2. [TryAPL online!](http://tryapl.org/?a=f%u2190%281%202%2C1%u2193%u2373%29%A8%u2218%u2374%u2337%u22A2%20%u22C4%20%28f%20f%20f%20m%29%28f%20f%20m%29%28f%20m%29%28m%u21903%203%u2374%27%20%23%20%23%27%29&run) [Answer] # Ruby, 46 bytes ``` ->a{a.map{|r|r.insert(2,r[1])}.insert(2,a[1])} ``` Very straighforward solution, taking input as array of lines. I don't like duplicated `insert`s, so will try to golf it. [Answer] ## C#, ~~127~~ 124 bytes ``` s=>{int n=s.Count-1,i=0;s[0]=s[n]=s[0].Insert(1,s[0][1]+"");s.Insert(1,s[1]);for(;i++<n;)s[i]=s[i].Insert(1," ");return s;}; ``` Compiles to a `Func<List<string>, List<string>>`. Formatted version: ``` s => { int n = s.Count - 1, i = 0; s[0] = s[n] = s[0].Insert(1, s[0][1] + ""); s.Insert(1, s[1]); for (; i++ < n;) s[i] = s[i].Insert(1, " "); return s; }; ``` ]
[Question] [ Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details. Related to [AoC2017 Day 9](https://adventofcode.com/2017/day/9). *[Weekends are Bubbler's days off from posting these lol](https://chat.stackexchange.com/transcript/message/59839491#59839491)* --- A large stream blocks your path. According to the locals, it's not safe to cross the stream at the moment because it's full of garbage. You look down at the stream; rather than water, you discover that it's a stream of characters. You sit for a while and record part of the stream (the input). The characters represent groups - sequences that begin with `{` and end with `}`. Within a group, there are zero or more other things, separated by commas: either another group or garbage. Since groups can contain other groups, a `}` only closes the most-recently-opened unclosed group - that is, they are nestable. The input represents a single group which itself may or may not contain smaller ones. Sometimes, instead of a group, you will find garbage. Garbage begins with `<` and ends with `>`. Between those angle brackets, almost any character can appear, including `{` and `}`. Within garbage, `<` has no special meaning. In a futile attempt to clean up the garbage, some program has canceled some of the characters within it using `!`: inside garbage, any character that comes after `!` should be ignored, including `<`, `>`, and even another `!`. You don't see any characters that deviate from these rules. Outside garbage, you only find well-formed groups, and garbage always terminates according to the rules above. The following are some example streams with the number of groups they contain: * `{}`, 1 group. * `{{{}}}`, 3 groups. * `{{},{}}`, also 3 groups. * `{{{},{},{{}}}}`, 6 groups. * `{<{},{},{{}}>}`, 1 group (which itself contains garbage). * `{<a>,<a>,<a>,<a>}`, 1 group (containing four pieces of garbage). * `{{<a>},{<a>},{<a>},{<a>}}`, 5 groups. * `{{<!>},{<!>},{<!>},{<a>}}`, 2 groups (since all `>`s except the last one are cancelled, creating one large garbage). * `{{<!!>,{<abc>},<!!!>>,{{<{!>}>},<yes<<<no>}},<>}`, 5 groups. **Input:** A self-contained, well-formed group as a string. **Output:** The total number of groups it contains, including itself. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 12 bytes ``` !. <.*?> } ``` [Try it online!](https://tio.run/##ZY1BCoBACEX33mIWQYR0ArFl12iKFm0mqDYhnn3SghoI1M/7/4PbfCwp5qruhxxaAGqbjgE0Z1EQEVUXRdEH0cddQ/qQHSNjsd53wd@9k3BTed8ksNM4mWsQ2NB@WcmNc96JKK1WRmK9AA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: The first stage deletes `!`s and the character they protect, the second stage deletes garbage, and the final stage counts the number of remaining groups. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 41 bytes ``` x=>x.replace(/<(!?.)*?>|[^}]/g,'').length ``` [Try it online!](https://tio.run/##FchBDsIgEADAt3ACDNIPbLcPMTZB3KKGQFMaU4P7dsTjzMu9XfHbc93PKd@pLWM7RjzsRmt0ntQASkxWnyb8Xma@DsFIqW2kFPZH8zmVHMnGHNSiZK0gBJoK7uaRTYfAzgpVIP/jQwUAUkbuQJZatx8 "JavaScript (Node.js) – Try It Online") If it's acceptable to output in unary, remove the `.length` for 34 bytes. This removes garbage and characters that aren't `}`, then counts what's left. [Answer] # [Zsh](https://www.zsh.org), 35 bytes ``` tr -dc }<<<${1//<(!?|[^>])#>}|wc -c ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LYxLCsIwFEW3krQOKrQUwYGDx3MhpZYmfVahJJJE_KRZiZOCuKjuxogdnsM99_V-2tM0Z5acvjhGd0eqo67pBy3YuVfaUCMHbakRppVkP1d3LHZz6gwrOskCAKz8piwh4_uxOmC9TjGMN8kK-Z9OS7GtEu-Bc8w9tEJiyCNwjOjBcww_8SAb_5TGEAFDUi_xFw) Removes all matches of the pattern `<(!?|[^>])#>`, which matches all garbage. A few notes: * Zsh doesn't support greedy vs. non-greedy matching, so I have to use `[^>]` rather than just `?`. (`?` matches any single character, but in order to get the garbage properly, `>`s must not be matched) * I count closing braces rather than opening braces at the end - they give the same result since they're always balanced, but `}` does not need to be escaped thanks to the `ignore_closing_braces` option [Answer] # [Ruby](https://www.ruby-lang.org/), ~~39 36~~ 33 bytes ``` ->s{s.scan(/{(<(!?.)*?>)*/).size} ``` [Try it online!](https://tio.run/##bVHLboMwELz3K5b0AhElaqv05DofUvVg3AUsWTbyGiWpxbdT8xBNSQ9eaXfGM@O168rrUL0PT5wCFSSFSQ8hZWlyKrL9iWf7Q1aQ@sZ@aKH62IV@9wmP8Ay1s11bPMzDEPp@Bl5ngFakz8MCCU32Hp8I@SQw0942DPbL4H/MIT03SjagPKGuQFrjhTIEtXClqDFbBQTPb85GY7mmTA2V7Ry0CiUS2OpOZxSKObZ11jtu38WSiXBbV/LLQoaUlJEYN6OBE@BFYuvBNwhakAdrIuQQ4p9I1Bq/cpAOhR@zjpgWrsZ/YiYJH91KGV1jk/DYxjXGEOPgisQYMzaGyRnfph9@AA "Ruby – Try It Online") Thanks lonelyelk for -3 bytes, I suck at regex. [Answer] # TypeScript Types, 192 bytes ``` //@ts-ignore type M<T,N=[],A=[0]>=T extends`${infer C}${infer T}`?M<C extends"!"?T extends`${string}${infer T}`?T:0:T,C extends"{"?[...N,...A]:N,C extends"<"?[]:C extends">"?[0]:A>:N["length"] ``` [Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAWQB4AVAGgDkBeAbQF1KBBBgBkYD5bzD0AHuHSIAJpAAGAEgDesRADN0qQgGEAvrPlKV5dRID8ZVfyEjxAIgCEFg30HCxk2ZHCp58TXMXLCew+QAXOyBVCYO5pAWMrb0AHQJ1JQJcSyMgUnhZk4WpLHpWY6WXLGcgSxcGfQWADYi8OAAFhaMmNj4ROTshLQkeTLqFlyYIIRjAHoG7QR+AIw9fdEyA+qDw6MTU7gz5ABMC2RL6pQrQyPAY4ST050AzAf9y8cDJyurZxtXWx1+ACwP0VIL2BKy4a3Ol2u206AFYActSABDMEnJEomRo56Y8GfKE-cgANnhGKs6NIpKxFNRyPe6wumxufgA7MTyaTqQAjADGKLZpK4ryBFN5OHQkFIEpQYOOpDBH3pX0wQA) ## Ungolfed / Explanation ``` // Mode is [0] if parsing groups, or [] if parsing garbage type Main<Str, Count=[], Mode=[0]> = // Get the first character of Str Str extends `${infer Char}${infer Rest}` ? Main< // If char is "!", set Str to Str[2..]; otherwise, set Str to Str[1..] Char extends "!" ? Rest extends`${string}${infer RestRest}` ? RestRest : 0 : Rest, // If char is "{", add Mode to Count Char extends "{" ? [...Count, ...Mode] : Count, // If char is "<", set Mode to [] (garbage); if char is ">", set Mode to [0] (not garbage) Char extends "<" ? [] : Char extends">" ? [0] : Mode > // Str is empty; return Count : Count["length"] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes ``` ≔⁰η≔¹ζ≔⁰εFS«¿ε≔⁰ε≡ι!≔¹ε<≔⁰ζ>≔¹ζ}≧⁺ζη»Iη ``` [Try it online!](https://tio.run/##VY9NCsIwEEbX7SkmrhKooFsbAuLKhSB6ghhiEyhtaaKiIWePU1uoXb553/wpI3vVyjqlvXO2auimAMPKfKJtAZ@Z0Gmke9sDPTbdw199b5uKMgYhz@wdqGawyIKunQb3sl4ZoPaXUxJLK7LawbxkGDsJPovNuH0SYtHxJyKKk@xGd7GV8fRcPxxmxl@ymMf8jJd6epDOU8NYmVIInBBRBC5vSsQCgQjEwAMRcSi8teOcN62ICCKm9bP@Ag "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⁰η ``` Start off with no groups. ``` ≔¹ζ ``` Start off with no garbage. ``` ≔⁰ε ``` Start off without cancellation. ``` FS« ``` Loop over the input characters. ``` ¿ε≔⁰ε ``` If the previous character was a `!` then cancel this character. ``` ≡ι ``` Otherwise, switch on the current character. ``` !≔¹ε ``` If it's a `!` then cancel the next character. ``` <≔⁰ζ ``` If it's a `<` then turn on garbage. ``` >≔¹ζ ``` If it's a `>` then turn off garbage. ``` }≧⁺ζη ``` If it's a `}` that's not inside garbage then increment the number of groups. ``` »Iη ``` Output the final number of groups. [Answer] # [Python 3](https://docs.python.org/3/), 117 bytes ``` n=0;g=1;s=input() for x,y in zip(s,s[1:]): if '!'not in x+y: if y in'<>':g='<>'.index(y) if g:n+=y=='}' print(n) ``` [Try it online!](https://tio.run/##JcpBDsIgEIXhfU8xxAVt2hiNuwpcxLioiEhiBgI0KRLOXiGuJt//xqX4tnjZD4DAQXu7utAdQFag2iLIBaX61KLbvPjHolWVqZJ2xaj8jvx01fx8DdygW2M/dC/rYZsSGISvcX2Ywu0834e5A/MCSija2LZtTDW11l4pE3TWvJ2jwafa@jT8Vz3jyBPntNDOeYOxx2Hfc2aEiCmz5SFFmSqIqMwsE1FaSCowxtCKUiHKDw "Python 3 – Try It Online") A regex less solution, shorter than @Ajax1234 **[Python 2](https://docs.python.org/2/), 114 bytes (Unsure if allowed)** ``` n=0;g=1;s=input() for x,y in zip(s,s[1:]): if '!'not in x+y: if y in'<>':g='<>'.index(y) if g*y=='}':print 1, ``` [Try it online!](https://tio.run/##JcpBbsMgEIXhvU8xJAvsFFV1lw5wkSoLhxKKFA0IsGSCOLsD6mr0/W98Tn8Ov48zIAgwwW0@DmdQDaj3BGpFpZ@tmD6v4b4a3WSblNsw6XCg@LoaMV@jsOi3NE7DwwXYWQaL8LJ@jCz@zMttWgawD6CEokt92z9yS731V8olXYzo59Pir97HPP2v5pKFoJUuPlhMMLPjOJXCCZGs8PWuZGUNRDYWXoisPWQdOefoZG2Q9fQG "Python 2 – Try It Online") outputs in unary with space between each digit [Answer] # [Python 3](https://docs.python.org/3/), 74 bytes ``` f=lambda s,m=1:s>''and(s[0]=='{'*m)+f(s[1+('!'==s[0]):],m^('><'[m]==s[0])) ``` [Try it online!](https://tio.run/##ZY3BCoMwEETvfkVy2lhzUHqTJD8iFrQqFZpE1IuEfLvdtaUVCrs7vJmBnbb14d113wf9bGzbNWyRVhflYgAa14mlymutIcDFptmAWGQCOGhNQVrW0t4EGAWVrT9eug9@Zs/R9Wx0zE@9E3laJoxN8@hWMQiKsBViEkKIkSTKEN8oachFVD80hI2Rp6U@ify7R8IPOt9vwg1Re0cXgRtE/IUlMrZ@UUo5j2WpTHwB "Python 3 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 68 bytes ``` Fold[StringDelete,#,{"!"~~_,"<"~~Shortest@__~~">"}]~StringCount~"{"& ``` [Try it online!](https://tio.run/##ZY3PCoJAEMbvPsU6gqeJXmBbhKJz4FFEzLYU1AXdDrHsvrrNVqYRzL/v980wXalr2ZW6qcrpynbTUbWXLNVD098OspVaYoQGQnCuQODU0loNWo46KQrnQIDN3Xt9r@69dmAgnk6kdRaxjWDXLMpzFrNtEhgwFjBgYIyxdh4tGrtg9OHdD@ILEjMqBa5yvvUj/tWvG77Iuv64ofDkXJFDIhQk6TctevCQI@e8V3SAnB7a6Qk "Wolfram Language (Mathematica) – Try It Online") [Answer] # x86 32-bit machine code, 31 bytes ``` 56 96 31 d2 31 c9 4a 42 41 ac 3c 21 75 01 46 3c 3e 74 f1 e2 f3 7a f1 73 ee 48 7b ed 5e 92 c3 ``` [Try it online!](https://tio.run/##ZVJRb5wwDH7Pr/AxTYJTWvWuaqVxlKd2r/sB63QKIYVUIaCEa29C/PUxO1cBVRE4@T5/No4deVVJOU3ftJXmVCrIfF/q9rrO2SfK6II4djyKvne6OPXqeIxjp6pOuCbeJUkC2vZQ@d7FshZuCz45MOEbiFn0bK8r0xbCBH9EBG3SsAN8upOvQXk9E2dZV0RwUOK8sK0DVZ45mUDKXXohJZFyUZZKziL9mGJtC3YpXPCH3iA2bemLOVo2HQjD4ea8383kq1XgZxQSfBTs03XI7dMSokAuCUzbduAWZ6fWCPPpx8/1r07@2rVglnZhoq/dCo1ZxTjVRwyHQHNphLYxbYSrJAeaEGy3CN4SNrBwZqL87/3djz@HQLzX2iiIvRT2JY6@7@/ufcRxqrB5gKdfP5MgCtU4TEwS/WxREa6AT5JLFizi5CzcHNjIpmkY2TAM40jLyIfxAjm9xCLMFpgTFDlffaSnhX@xwbMJaG1nzyYnVEhkEWxyhPgvFBHxV/ksy2yLYp7l4z/5YkTlp6vmdo8GL/EDnlCZ/w) Following the `regparm(1)` calling convention, this takes the address of a null-terminated byte string in EAX. Assembly: ``` .text # In the main loop, EDX will count the number of { .global gstr # and ECX will be 1 outside garbage, 0 inside garbage. .intel_syntax noprefix gstr: push esi # Save the value of ESI onto the stack xchg esi, eax # Switch the string address into ESI xor edx, edx # Set EDX to 0 c1: xor ecx, ecx # Set ECX to 0 dec edx # (These two instructions have a net effect of nothing, iD: inc edx # but we can jump into the middle to add 1 to EDX.) r: inc ecx # Increment ECX, at first to 1 l: lodsb # Read a character from the string into AL cmp al, 0x21 # Check for ! jne s # Jump if not ! inc esi # If !, increment ESI to skip the next character s: cmp al, 0x3E # Compare with > je c1 # Jump on > to reset ECX to 1 loop r # Decrement ECX and jump (to restore it and proceed) # if it was 0 (within garbage) jpe r # Jump (same) to ignore } and , jnc iD # Jump on { to count up in EDX (and restore ECX) dec eax # Decrement EAX, setting PF from the low 8 bits jpo l # Jump on < to proceed (ECX remains 0) pop esi # NUL: Restore the value of ESI from the stack xchg edx, eax # Switch the count into EAX ret # Return ``` [Answer] # [Rust](https://www.rust-lang.org/), 170 166 bytes ``` |i:&str|{let(mut g,mut s)=(0,vec![123]);for c in i.bytes(){match&[s[s.len()-1],c]{b"<!"|b"{<"|b"{{"=>s.push(c),[33,_]|b"<>"=>{s.pop();}b"{}"=>{g+=1;s.pop();}_=>()}}g} ``` [Try it online!](https://tio.run/##bZLRboIwFIbveYqWC9JmVYdku5DSPQghBkhREq2Mli2m9tnZKTOOqU045Hz//5@eEPpBm7FR6Fi2ilBkAwTnIA1qUIbGS7uJtOkvFgg5DgbtmK@aZuSVfcka5/E6KWjanHpUo1ahdlmdjdSE2mNp6n2U61wvDxJGL@KC1YWtQo7DSxVaPlUbZkIvu0HvSU1ZniRsWwDnArgF4dQRmjowOg92L1mc3ug2E4Q6t3Oj3zkNptX9JqRV3WAYKpX@lj31e0X5pPpD/DCGYsrmyFrnPE7usGP2KZ8ENqW8/P5f5n@yeHIZLwWbPc/W8Zg9VO98u3fiSZ3Xq3P94MTCq1UNLmiwgBZ2hZAHZ6k55@oEYcbF/Kri@l/40/WtMgeFYeDmw6GFQP4N5v8fPb0FVitUai17g2/ot9/KT0yihkRTkt5FXeCC8Qc "Rust – Try It Online") * -4 bytes by not using `Option` (thanks @AnttiP) [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 56 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` {⌈2÷˜≠','⊸≠⊸/{𝕩/˜¬∨⟜»×{𝕨+𝕩×1⌈|𝕨}`-˝"<>"=⌜𝕩}𝕩/˜¬∨⟜»'!'=𝕩} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge+KMiDLDt8uc4omgJywn4oq44omg4oq4L3vwnZWpL8ucwqziiKjin5zCu8OXe/Cdlagr8J2VqcOXMeKMiHzwnZWofWAty50iPD4iPeKMnPCdlal98J2VqS/LnMKs4oio4p+cwrsnISc98J2VqX0KCj4o4ouI4p+cRinCqOKfqCAie30iCiJ7e3t9fX0iCiJ7e30se319Igoie3t7fSx7fSx7e319fX0iCiJ7PHt9LHt9LHt7fX0+fSIKIns8YT4sPGE+LDxhPiw8YT59Igoie3s8YT59LHs8YT59LHs8YT59LHs8YT59fSIKInt7PCE+fSx7PCE+fSx7PCE+fSx7PGE+fX0iCiJ7ezwhIT4sezxhYmM+fSw8ISEhPj4se3s8eyE+fT59LDx5ZXM8PDxubz59fSw8Pn0i4p+pCg==) -10 bytes from ovs. Individually removes each main pattern (`!`, `<>`, `,`) and checks length. Then divide that by 2 and take ceiling. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 78 bytes ``` s->a=b=0;#[1|d<-Vec(s),if(a,a=0,d=="!",!a=1,b,d==">"&&b=0,d=="<",!b=1,d=="{")] ``` [Try it online!](https://tio.run/##ZY1NCsMgEEavolMICYyQrKseo5uQheanBEoqSTfBevZ0TG0bKOjwzXuj48w8iqvbBqa2RWijrCrPp7p6dlJc@jZfChyH3KBRJXZKAQfkRlVo905DltlkJBlLJmYPRbMZ525rvjChmZvH6UERYgNsoG8LZDX4AMjAex9CSgF9@EKMJ7o3kT@iEzEaDzc9jAn/6kfyHRzrUXIdgW1JUMM1tbSX5iJY@0VKOd1pHiVta4rtBQ "Pari/GP – Try It Online") When your language doesn't have regexp or any string pattern matching built-in... [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '!š¬ìKDŒ€…<ÿ>K¤¢ ``` Despite 05AB1E's lack of regex, it turned out surprisingly short. :) [Try it online](https://tio.run/##yy9OTMpM/f9fXfHowkNrDq/xdjk66VHTmkcNy2wO77fzPrTk0KL//6urbRQV7XSqbRKTku1qdYAcRTsgt9qmWtGuFiRQmVpsY2OTl29XC@TY1QIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf3XFowsPrTm8xtvl6KRHTWseNSyzObzfzvvQkkOL/uv8j1aqrlXSUaqurq6thTBqdaprYUI6IASSAQvYIATsIAKJdjpIGKILxNDBIKFyimA@Mokkp2gH4iclA8WBHEU7IBdoJ1AZSKAytdjGxiYvH6hcxwZmlR1IIciAWAA). **Explanation:** ``` # Remove all "!" and the character after it: '!š '# Split the (implicit) input-string to a list of characters, and prepend a "!" ¬ # Push the first item (without popping), which is the "!" ì # Prepend this "!" in front of each character K # Remove all those 2-char strings from the (implicit) input-string # (the `š¬` is necessary to first remove all "!!") # Remove all "<...>" garbage groups: D # Duplicate the string Œ # Pop the copy, and push all its substrings € # Map each substring to: …<ÿ> # Prepend a "<" and append a ">" K # Remove all those from the string as well # Count how many groups are left: ¤ # Push the last character (without popping), which is "}" ¢ # Count how many "}" are in the string # (after which the result is output implicitly) ``` [Answer] # Python3, 156 bytes: ``` f=lambda x,g=0,c=0,i=0:c if not x else f(x[1:],(g:=(x[0]=='<'or(x[0]!='>'and g))),c+(not g and x[0]=='}' and not i),x[0]=='!'or(i and x[0]not in [",","}"])) ``` [Try it online!](https://tio.run/##bU7NjoIwEL7vU0y9tM3OAePFkLYvYjggAjZxC0EOGNJnZ2caowZMO5P5/ibTP8ZrFw7HfliWxt7Kv/OlhAlbm2FF5W2WV@AbCN0IE9S3ew2Nmk77vEDV5pbGrLBWGtkNaRZWOlmGC7Raa6x@FQdbYOZpjTIh5r3GJyk471@2JAY47ZBe3BVaL/3gw6gaJecotf55w3mOcU1FnOPWhvzZvZLMW3JrqXT4UeudTOGmb1wiKZ/9q0s4Vs4VOQgIR5BuowATj/pujAkdBdGkQ5Z/) [Answer] # [Python 3](https://docs.python.org/3/), 54 bytes ``` lambda x:re.sub('<(!?.)*?>','',x).count('{') import re ``` [Try it online!](https://tio.run/##FcixCsMgEADQvV8Rp/OKuHQr18uPZNHU0ECjYgwkiN9u7fhevPIn@EdbXlP7ms2@zXA@k9P7YSWQFKPG@8igANSJeg6HzxIK4G3dYkh5SK7FtPZcehcSglUhY2euqkNwZ6EiuP7jcjsR@cC1gysgth8 "Python 3 – Try It Online") Port of my JS answer. Go read that, it's almost the same thing. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 26 bytes ``` s/!.//g;s/<.*?>//g;$_=y;{; ``` [Try it online!](https://tio.run/##ZY1NCsJADIX33mLAlUxn6qKriekJPIOoFBFKZ3DclJCrG5MKWhDy9733IGV4jJ1IjS7EeEs1Qtj1aOf2dJgTJRHiDREx22JP/EFvZaoi/BANz@hXbXlb/m8ujltoPb@OQ6PLVVUFh4r6S0MmzEMFgClr2APyK5fnPU9VmjJKc@xCu2/f "Perl 5 – Try It Online") [Answer] # SM83, 24 bytes Input in `hl` as null-terminated string. Output in `bc`. ``` 2A B7 C8 FE 7B 20 01 03 FE 3C 20 F4 2A FE 3E 28 EF FE 21 20 F7 23 18 F4 ``` ``` f: ld a,(hl+) ;; 2A ;; load char or a ;; B7 ;; test for 0 ret z ;; C8 ;; if so, at end; return cp '{' ;; FE 7B jr nz,x ;; 20 01 ;; if not '{' inc bc ;; 03 ;; increment result x: cp '<' ;; FE 3C ;; if not '<' jr nz,f ;; 20 F4 ;; loop l: ;; degarbaging: ld a,(hl+) ;; 2A ;; load char cp '>' ;; FE 3E ;; if '>' jr z,f ;; 28 EF ;; go back to start cp '!' ;; FE 21 ;; if not '!' jr nz,l ;; 20 F7 ;; continue degarbaging inc hl ;; 23 ;; skip char jr l ;; 18 F4 ;; and continue degarbaging ``` ]
[Question] [ Given a natural number `n` write a program or function to get a list of all the possible two factors multiplications that can be used to achieve `n`. To understand better what is pretended you can go to <http://factornumber.com/?page=16777216> to see when `n` is `16777216` we get the following list: ``` 2 × 8388608 4 × 4194304 8 × 2097152 16 × 1048576 32 × 524288 64 × 262144 128 × 131072 256 × 65536 512 × 32768 1024 × 16384 2048 × 8192 4096 × 4096 ``` No need to pretty print things like here. The requirement is that each entry (pair of factors) is well distinguished from each other and inside each pair, the first factor is also well distinguished from the other. If you choose to return a list/array, the inside element can be a list/array with two elements, or some structure of your language that supports a pair of things like C++ `std::pair`. Do not print the multiplication by 1 entry, nor repeat entries with the first factor commuted by the second, as they are pretty useless. No winner; it will be a per language basis code golf. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~81~~ ~~66~~ 65 bytes * -15 Bytes thanks to Olivier Grégoire. * -1 Byte: `++j<=i/j` -> `j++<i/j`. ``` i->{for(int j=1;j++<i/j;)if(i%j<1)System.out.println(j+" "+i/j);} ``` [Try it online!](https://tio.run/##VY6xCsIwFEX3fsVDEBKK0SrYIeri5ODUURxibPXFNinNS0Gk316juLhezuUco3o1c21pzfUx6lp5D0eF9pUAeFKEGkwkRCCsRRWsJnRWHCztnfWhKTu4w3bE2e5VuY6hJTDbTJo03eDcSI4Vw6nZZLx4eiob4QKJtotYbZlJJzBJI8blMMokCttwqaPw5@0dXqGJLaygeLmdzqD4pwvuQmldtsSydZ7ny2zN5d@8WnyHIRnGNw "Java (OpenJDK 8) – Try It Online") --- Old one (for reference) # [Java (OpenJDK 8)](http://openjdk.java.net/), 126 bytes ``` i->{java.util.stream.IntStream.range(2,i).filter(d->d<=i/d&&i%d==0).forEach(e->System.out.println(""+e+"x"+i/e));return null;} ``` [Try it online!](https://tio.run/##RY9Ba4NAEIXv/opBaFgxbpoc4sHoLYEeegr0UnrYuhMdu46y7oaG4G@3Wxro7THzHnxfp64qG0bkTn8ttVHTBK@K@B4BTE45qqELDekdGXnxXDsaWJ4e4fDCDhu0a3gbSFfQQrlQVt3/J5OzqHoZeue/ZBU3KHZrSuSFjEMrdFbpQ0kbvVrRky7L5/AZ7FHVrcCsOt8mh70cvJOjJXaGRRynmMbfcUobTJLCovOWgb0xxbwUUSAf/acJ5A@Ba2CDPkiJwEDcvH@ASn4FoZVqHM1NbPd5nu@2@6QI1zmalx8 "Java (OpenJDK 8) – Try It Online") First codegolf submit and first lambda usage. Future self, please forgive me for the code. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` Ñ‚ø2äн¦ ``` [Try it online!](https://tio.run/##ASIA3f8wNWFiMWX//8ORw4LigJrDuDLDpNC9wqb//zE2Nzc3MjE2 "05AB1E – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~58~~ ~~54~~ 53 bytes * Saved a byte thanks to [Steadybox](https://codegolf.stackexchange.com/users/61405/steadybox). ``` f(N,j){for(j=1;j++*j<N;)N%j||printf("|%d,%d",j,N/j);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9Nw08nS7M6Lb9II8vW0DpLW1sry8bPWtNPNaumpqAoM68kTUOpRjVFRzVFSSdLx08/S9O69n9uYmaehmY1F2eahgIYGBtoWheUlhRrKClpWoOEDc3Mzc2NDM2QhWv/AwA "C (gcc) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 51 bytes ``` f=lambda n,k=2:n/k/k*[f]and[(k,n/k)][n%k:]+f(n,k+1) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIU8n29bIKk8/Wz9bKzotNjEvJVojWwfI14yNzlPNtorVTtMAqtE21PxfUJSZV6KQpmGmyQVjGiOxTQw0/wMA "Python 2 – Try It Online") --- **51 bytes** (thanks to Luis Mendo for a byte) ``` lambda n:[(n/k,k)for k in range(1,n)if(k*k<=n)>n%k] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKlojTz9bJ1szLb9IIVshM0@hKDEvPVXDUCdPMzNNI1sr28Y2T9MuTzU79n9BUWZeiUKahqEmF4xphmAaI7FNDDT/AwA "Python 2 – Try It Online") --- **51 bytes** ``` lambda n:[(n/k,k)for k in range(1,n)if n/k/k>n%k*n] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKlojTz9bJ1szLb9IIVshM0@hKDEvPVXDUCdPMzNNASinn22Xp5qtlRf7v6AoM69EIU3DUJMLxjRDMI2R2CYGmv8B "Python 2 – Try It Online") [Answer] ## Haskell, 38 bytes ``` f x=[(a,b)|a<-[2..x],b<-[2..a],a*b==x] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwjZaI1EnSbMm0UY32khPryJWJwnCSozVSdRKsrWtiP2fm5iZp2CrUFCUmVeioKKQpmBs8B8A "Haskell – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 28 bytes ``` {(⊢,⍵÷⊢)¨o/⍨0=⍵|⍨o←1↓⍳⌊⍵*.5} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqjUddi3Qe9W49vB3I0Dy0Il//Ue8KA1ugSA2QkQ9UYviobfKj3s2PerqAglp6prX//z/qXZWmYGjEpW5ra6vOBeGZmZubGxmaAQA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Perl 6](https://perl6.org), 38 bytes ``` {map {$^a,$_/$a},grep $_%%*,2.. .sqrt} ``` [Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszZVbqaCWnJ@SqmD7vzo3sUChWiUuUUclXl8lsVYnvSi1QEElXlVVS8dIT09Br7iwqKT2v15xYqVCWn6RAliboZm5ubmRodl/AA "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 map { $^a, $_ / $a }, # map the number with the other factor grep $_ %% *, # is the input divisible by * 2 .. .sqrt # from 2 to the square root of the input } ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` {~×≜Ċo}ᵘ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7ru8PRHnXOOdOXXPtw64/9/Y4P/UQA "Brachylog – Try It Online") ## Explanation ``` {~×≜Ċo}ᵘ { }ᵘ List the unique outputs of this predicate. ~× Pick a list of integers whose product is the input. ≜ Force concrete values for its elements. Ċ Force its length to be 2. o Sort it and output the result. ``` The `~×` part does not include 1s in its output, so for input **N** it gives **[N]** instead of **[1,N]**, which is later culled by `Ċ`. I'm not entirely sure why `≜` is needed... [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 bytes ``` â¬Å£[XZo] ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=4qzFo1tYWm9d&input=MjU2IC1S) Returns an array of arrays, with some nulls at the end; `-R` flag added to show output more clearly. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ½ḊpP⁼¥Ðf ``` A monadic link taking a number and returning a list of lists (pairs) of numbers. **[Try it online!](https://tio.run/##ARwA4/9qZWxsef//wr3huIpwUOKBvMKlw5Bm////MTQ0 "Jelly – Try It Online")** (times out on TIO for the `16777216` example since it would create a list of 68.7 billion pairs and filter down to those with the correct product!) ### How? ``` ½ḊpP⁼¥Ðf - Link: number, n e.g. 144 ½ - square root of n 12 Ḋ - dequeue* [2,3,4,5,6,7,8,9,10,11,12] p - Cartesian product** [[2,1],[2,2],...[2,144],[3,1],...,[3,144],...,[12,144] Ðf - filter keep if: ¥ - last two links as a dyad (n is on the right): P - product ⁼ - equals - [[2,72],[3,48],[4,36],[6,24],[8,18],[9,16],[12,12]] ``` \* `Ḋ`, dequeue, implicitly makes a range of a numeric input prior to acting, and the range function implicitly floors its input, so with, say, `n=24` the result of `½` is `4.898...`; the range becomes `[1,2,3,4]`; and the dequeued result is `[2,3,4]` \*\* Similarly to above, `p`, Cartesian product, makes ranges for numeric input - here the right argument is `n` hence the right argument becomes `[1,2,3,...,n]` prior to the actual Cartisian product taking place. [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` tüOSze↔Ḋ ``` [Try it online!](https://tio.run/##yygtzv7/v@TwHv/gqtRHbVMe7uj6//@/mQEA "Husk – Try It Online") ## Explanation ``` tüOSze↔Ḋ Implicit input, say n=30. Ḋ List of divisors: [1,2,3,5,6,10,15,30] ↔ Reverse: [30,15,10,6,5,3,2,1] Sze Zip with original: [[1,30],[2,15],[3,10],[5,6],[6,5],[10,3],[15,2],[30,1]] üO Deduplicate by sort: [[1,30],[2,15],[3,10],[5,6]] t Drop first pair: [[2,15],[3,10],[5,6]] ``` [Answer] # JavaScript (ES6), 55 bytes ``` n=>eval('for(k=1,a=[];k*++k<n;n%k||a.push([k,n/k]));a') ``` ### Demo ``` let f = n=>eval('for(k=1,a=[];k*++k<n;n%k||a.push([k,n/k]));a') console.log(JSON.stringify(f(6))) console.log(JSON.stringify(f(7))) console.log(JSON.stringify(f(16777216))) ``` [Try It Online!](https://tio.run/%23%23BcFRDoMgDADQ0yy2UzFunwwvYvxoGExX0hpRv7w7vvenk7LflnVvRb@hRFfEDeGkBFXUDdj1Dblxsvysa/6IlQdfF5n1yDOM3EjHE6KlCotXyZqCSfqDCP3rjVhu) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 7 bytes ``` ḊŒċP=¥Ƈ ``` [Try it online!](https://tio.run/##y0rNyan8///hjq6jk450B9geWnqs/b@xgQJQ4OGO@YfbghSsDU1MFHQUDrcfnfRw5wwVBZVHTWsUvIFE5H8A "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 59 bytes ``` lambda N:{(n,N/n,n)[n>N/n:][:2]for n in range(2,N)if N%n<1} ``` [Try it online!](https://tio.run/##FclBCoQgGAbQq/ybAQUhdJEg1RG8gNPCoZwR6jNMgiE6uzPtHrztWz4Jqob@WRe/viZP1pwMwjYQ4A7DH2Z0Ro0hZQJFUPZ4z0wJy2Mg@0Anr3rnceeecpknFphstdZKtpybLUcUOuoP "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ÆḌḊµżUṢ€Q ``` [Try it online!](https://tio.run/##ASAA3/9qZWxsef//w4bhuIzhuIrCtcW8VeG5ouKCrFH///8zMA "Jelly – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 42 bytes ``` @(n)[y=find(~mod(n,x=2:n)&x.^2<=n)+1;n./y] ``` [**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999BI08zutI2LTMvRaMuNz9FI0@nwtbIKk9TrUIvzsjGNk9T29A6T0@/MvZ/moahmbm5uZGhmeZ/AA "Octave – Try It Online") [Answer] # PHP, 70 bytes As string (70 bytes): ``` $i++;while($i++<sqrt($a=$argv[1])){echo !($a%$i)?" {$i}x".($a/$i):'';} ``` As array dump (71 bytes): ``` $i++;while($i++<sqrt($a=$argv[1]))!($a%$i)?$b[$i]=$a/$i:'';print_r($b); ``` (im not sure if i can use return $b; instead of print\_r since it no longer outputs the array, otherwise i can save 2 bytes here. ) The array gives the results like: ``` Array ( [2] => 8388608 [4] => 4194304 [8] => 2097152 [16] => 1048576 ``` [Answer] ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes ``` nRest@Union[Sort@{#,n/#}&/@Divisors@n] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P@/9pIVBqcUlDqF5mfl50cH5RSUO1co6efrKtWr6Di6ZZZnF@UXFDnmx/wOKMvNKHNKiDc3Mzc2NDM1i/wMA "Wolfram Language (Mathematica) – Try It Online") `` is the `Function` operator, which introduces an unnamed function with named parameter `n`. [Answer] # [Factor](http://factorcode.org), 58 Well, there has to be some Factor in this question! ``` [ divisors dup reverse zip dup length 1 + 2 /i head rest ] ``` It's a quotation. `call` it with the number on the stack, leaves an `assoc` (an array of pairs) on the stack. I'm never sure if all the imports count or not, as they're part of the language. This one uses: ``` USING: math.prime.factors sequences assocs math ; ``` (If they count, I should look for a longer solution with shorter imports, which is kind of silly) As a word: ``` : 2-factors ( x -- a ) divisors dup reverse zip dup length 1 + 2 /i head rest ; 50 2-factors . --> { { 2 25 } { 5 10 } } ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 43 bytes ``` ->n{(2..n**0.5).map{|x|[[x,n/x]][n%x]}-[p]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNITy9PS8tAz1RTLzexoLqmoiY6ukInT78iNjY6T7UitlY3uiC29n@BQlq0oZm5ubmRoVnsfwA "Ruby – Try It Online") ### How it works: For every number up to sqrt(n), generate the pair `[[x, n/x]]`, then take the `n%x`th element of this array. If `n%x==0` this is `[x, n/x]`, otherwise it's `nil`. when done, remove all `nil` from the list. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), ~~49~~ ~~34~~ 38 bytes ``` n->[[d,n/d]|d<-divisors(n),d>1&d<=n/d] ``` [Try it online!](https://tio.run/##K0gsytRNL/ifZvs/T9cuOjpFJ08/JbYmxUY3JbMsszi/qFgjT1Mnxc5QLcXGFiT1v6AoM69EI03D2ERTkwvCgdFAQVNsgmbYBM2xCBqamZubGxkC1f8HAA "Pari/GP – Try It Online") Set builder notation for all pairs `[d, n/d]` where `d` runs through all divisors `d` of `n` subject to `d > 1` and `d <= n/d`. Huge improvement by alephalpha. [Answer] ## Perl 5, 53 + 2 (`-p` flag) = 55 bytes ``` $_="@{[map{$_,$n/$_.$/}grep!($n%$_),2..sqrt($n=$_)]}" ``` Ungolfed: ``` while (defined $_ = <>) { $n = $_; $_ = qq(@{[ map{ ($_, ($n / $_) . "\n") } grep { !($n % $_) } (2 .. sqrt($n)) ]}); print($_); } ``` [Try it online](https://tio.run/##K0gtyjH9/18l3lbJoTo6N7GgWiVeRyVPXyVeT0W/Nr0otUBRQyVPVSVeU8dIT6@4sKgEyLUFcmNrlf7/NzQzNzc3MjTj@pdfUJKZn1f8X7cAAA). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` K~/Z's⁼ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=K%7E%2FZ%27s%E2%81%BC&inputs=4096&header=&footer=) (not anymore) messy. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~14~~ 12 bytes ``` tumoOSe`/⁰Ḋ⁰ ``` [Try it online!](https://tio.run/##yygtzv7/v6Q0N98/ODVB/1Hjhoc7uoDk////jQ0A "Husk – Try It Online") ### Explanation ``` tum(OSe`/⁰)Ḋ⁰ -- input ⁰, eg. 30 Ḋ⁰ -- divisors [1..⁰]: [1,2,3,5,6,10,15,30] m( ) -- map the following function (example on 10): Se -- create list with 10 and .. `/⁰ -- .. flipped division by ⁰ (30/10): [10,3] O -- sort: [3,10] -- [[1,30],[2,15],[3,10],[5,6],[5,6],[3,10],[2,15],[1,30]] u -- remove duplicates: [[1,30],[2,15],[3,10],[5,6]] t -- tail: [[2,15],[3,10],[5,6]] ``` [Answer] # APL+WIN, 32 bytes ``` m,[.1]n÷m←(0=m|n)/m←1↓⍳⌊(n←⎕)*.5 ``` Explanation: ``` (n←⎕) Prompts for screen input m←(0=m|n)/m←1↓⍳⌊(n←⎕)*.5 Calculates the factors dropping the first m,[.1]n÷ Identifies the pairs and concatenates into a list. ``` [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), ~~18~~ 15 bytes ``` L,F@pB]dBRBcE#S ``` [Try it online!](https://tio.run/##S0xJKSj4/99Hx82hwCk2xSnIKdlVOTgs2f3////GBgA "Add++ – Try It Online") ## How it works ``` L, - Create a lambda function - Example argument: 30 F - Factors; STACK = [1 2 3 5 6 10 15] @ - Reverse; STACK = [15 10 6 5 3 2 1] p - Pop; STACK = [15 10 6 5 3 2] B] - Wrap; STACK = [[15 10 6 5 3 2]] d - Duplicate; STACK = [[15 10 6 5 3 2] [15 10 6 5 3 2]] BR - Reverse; STACK = [[15 10 6 5 3 2] [2 3 5 6 10 15]] Bc - Zip; STACK = [[15 2] [10 3] [6 5] [5 6] [3 10] [2 15]] E# - Sort each; STACK = [[2 15] [3 10] [5 6] [5 6] [3 10] [2 15]] S - Deduplicate; STACK = [[[2 15] [3 10] [5 6]]] ``` [Answer] # Mathematica, 53 bytes ``` Array[s[[{#,-#}]]&,⌈Length[s=Divisors@#]/2⌉-1,2]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b737GoKLEyujg6ulpZR1e5NjZWTedRT4dPal56SUZ0sa1LZllmcX5RsYNyrL7Ro55OXUMdo1i1/wFFmXklDmnRhmbm5uZGhmax/wE "Wolfram Language (Mathematica) – Try It Online") [Answer] # Befunge-93, 56 bytes ``` &1vg00,+55./.: < +1< v`\g00/g00:p00 _ ^@_::00g%!00g\#v ``` [Try It Online](https://tio.run/##S0pNK81LT/3/X82wLN3AQEfb1FRPX89KQUHBhkvb0EahLCEGKKwPxFYFBgZc8QpxDvFWVgYG6aqKQCJGuez/f0MjAwA) [Answer] # [Julia 0.6](http://julialang.org/), 41 bytes ``` ~x=[(y,div(x,y))for y=2:x if x%y<1>y^2-x] ``` [Try it online!](https://tio.run/##yyrNyUw0@/@/rsI2WqNSJyWzTKNCp1JTMy2/SKHS1siqQiEzTaFCtdLG0K4yzki3IvY/UCY1MTlDo6AoM68kJ0@nztDM3NzcyNBM8z8A "Julia 0.6 – Try It Online") Redefines the inbuild unary operator `~` and uses an array comprehension to build the output. * `div(x,y)` is neccessary for integer division. `x/y` saves 5 bytes but the output is `~4=(2,2.0)`. * Julia allows chaining the comparisons, saving one byte. * Looping all the way to x avoids `Int(floor(√x))`. [Answer] # APL NARS 99 chars ``` r←f w;i;h r←⍬⋄i←1⋄→0×⍳0≠⍴⍴w⋄→0×⍳''≡0↑w⋄→0×⍳w≠⌊w⋄→0×⍳w≠+w A:i+←1⋄→A×⍳∼0=i∣w⋄→0×⍳i>h←w÷i⋄r←r,⊂i h⋄→A ``` 9+46+41+3=99 Test: (where not print nothing, it return something it return ⍬ the list null one has to consider as "no solution") ``` f 101 f 1 2 3 f '1' f '123' f 33 1.23 f 1.23 ⎕←⊃f 16777216 2 8388608 4 4194304 8 2097152 16 1048576 32 524288 64 262144 128 131072 256 65536 512 32768 1024 16384 2048 8192 4096 4096 f 123 3 41 ``` ]
[Question] [ Two random numbers `A` and `B` have been generated to be either 1, 2, or 3 your job is to randomly pick a third number `C` that can also be 1, 2 or 3. But, `C` cannot equal `A` or `B`. * `A` can equal `B`. * If `A = B`, then `C` has only two numbers left it can be. * If `A ≠ B`, `C` has only one number it can be. * Assume `A` and `B` have already been chosen for you This is how `A` and `B` would be created in Python ``` A = random.randrange(1,4) B = random.randrange(1,4) ``` Assume this is already in your code. This is the shortest I've come up with in Python ``` while True: C = random.randrange(1,4) if C != A and C != B: break ``` Here are some acceptable values for `A`, `B` and `C`. * `1,2,3` * `1,1,2` * `2,3,1` * `3,3,2` Here are some unacceptable values for `A`, `B` and `C`. * `1,2,1` * `2,3,3` * `1,1,1` * `3,2,3` [Answer] ## Ruby, 22 characters ``` ([1,2,3]-[A,B]).sample ``` Still not sure if I understood the question correctly ... [Answer] # C,26 ``` a-b?6-a-b:(rand()%2+a)%3+1 ``` If I've understood the question correctly: If `a` and `b` are different, there is no random. the answer must be the only one of 1,2,3 that is unused: `6-a-b`. IF `a` and `b` are the same there are 2 choices: ``` a=b= 1 2 3 return value rand()%2=0 2 3 1 rand()%2=1 3 1 2 ``` [Answer] ## Befunge (~~156~~ ~~89~~ ~~85~~ 74) Okay, this is terrible, I know. But it's my first Befunge attempt ever, so I'm still pretty happy that it even works. I'm sure there's a much, much better solution. ``` <v1p90&p80& <<@.g70_v#-g70_v#-g70g90g80p70 v < < ^1?v ^3<2 ^ < ``` [Answer] **Python, 14 characters** I tried it for every 9 possible cases and it seems to work fine! ``` C=A^B or A^1|2 ``` (edit): As edc65 pointed out, this isn't valid since it's not random... I missed that part of the question and I feel stupid right now. [Answer] # GolfScript, 13 chars ``` ~0]4,^.,rand= ``` This is a complete GolfScript program that reads two whitespace-separated numbers (each assumed to be either 1, 2, or 3) from standard input, and outputs a random number from the set {1, 2, 3} that does not equal any of the input numbers. [Try it online.](http://golfscript.apphb.com/?c=IyBDYW5uZWQgdGVzdCBpbnB1dCBpbiBhIGRvdWJsZS1xdW90ZWQgc3RyaW5nICh0cnkgY2hhbmdpbmcgdGhpcyk6CjsiMiAyIgoKIyBBY3R1YWwgcHJvZ3JhbSBjb2RlOgp%2BMF00LFwtLixyYW5kPQ%3D%3D) (Note: the link is to the previous version; I'm on a mobile device and can't fix it.) Here's a commented version of the program: ``` ~ # eval the input, pushing the input numbers onto the stack 0 # push the number 0 onto the stack ] # collect all the numbers on the stack into an array 4, # create another array containing the numbers 0, 1, 2 and 3 ^ # xor the arrays (i.e. take their symmetric set difference) .,rand= # choose a random element from the array ``` If you'd prefer a named function that takes the two numbers as arguments on the stack, that takes a few more chars: ``` {[\0]4,^.,rand=}:f; ``` The actual body of the function is only one char longer than the stand-alone code (because we need the `[` to make sure we consume only two arguments), but the overhead of wrapping the code in a block and assigning it to a symbol takes five more chars, for a total of 19. Alternatively, if you literally have the two numbers assigned into the variables `A` and `B`, and want the third number assigned to `C`, that can also be done in 19 chars: ``` 4,[0A B]^.,rand=:C; ``` (If leaving the third number on the stack instead is acceptable, you can leave the `:C;` off the end.) Ps. Thanks for the suggestion to use `^`, Howard. [Answer] # Python - 35 ``` C=random.sample({1,2,3}-{A,B},1)[0] ``` Assumes random is imported, which seems to be specified in the question. # PYG - 25 ``` C=RSm({1,2,3}-{A,B},1)[0] ``` [Answer] # Befunge - 99 bytes ``` &:01p&:11p-!!#v_v @,g2+g11g10< " 321 vv*2g<"v ^ 2v v v 5v*2^10<" v?v?v?vp5 ^< 2 3 1 2< > > > >.@ ``` Not very impressive. [Answer] ## PowerShell, 21 ``` 1..3-ne$A-ne$B|random ``` *Very* straightforward. Abusing the fact that comparison operators act differently with an array as their left operand. [Answer] ## Mathematica, 37 bytes ``` RandomChoice@DeleteCases[{1,2,3},a|b] ``` Basically the same as the Ruby answer, but considerably longer thanks to Mathematica's function names. I'm using lower-case variables, because upper-case names might clash with built-ins (they don't, in this case, but you simply don't do it in Mathematica). [Answer] ## R, 42 chars ``` x=c(1,1,1);x[c(A,B)]=0;C=sample(1:3,1,p=x) ``` Vector `x` is the vector of probability weights for obtaining the elements of the vector being sampled. It is set to 1 for each at first, then elements corresponding to A and B are set to 0, hence they have no chance of being picked. [Answer] # Rebol - 40 chars ``` random/only difference[1 2 3]reduce[A B] ``` [Answer] # CJam - 12 ``` 4,[AB0]-mr0= ``` This assumes the variables A and B have already been set, according to the question. You can try it at <http://cjam.aditsu.net/> To test it with random numbers, use: ``` "A="3mr):A", B="3mr):B", C=" 4,[AB0]-mr0= ``` To test it with specific values, use (for example): ``` "A="1:A", B="1:B", C=" 4,[AB0]-mr0= ``` **Explanation:** `4,` creates the array [0 1 2 3] `[AB0]-` removes the numbers A, B and 0 from the array `mr` shuffles the remaining array `0=` takes the first element In a future CJam version this program will be 2 bytes shorter :) [Answer] ## C 67 ``` int C(int a,int b){int c=0;while(c!=a&&c!=b)c=rand()%3+1;return c;} ``` [Answer] ## JS, 35 inspired by Brandon Anzaldi's answer ``` A=1; // init B=3; // init do{C=1+new Date%3}while(C==A||C==B) // 35b ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` O.-S3 ``` [Try it online!](https://tio.run/##K6gsyfj/319PN9j4//9oQx0Fw1gA "Pyth – Try It Online") ``` O.-S3 O.-S3Q - Implicitly read input S3 - Create range [1, 2, 3] .- - Subtract input elements from the range O - Select a random element. ``` [Answer] # [Arn](https://github.com/ZippyMagician/Arn), [9 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn) ``` ╚<<ٌԓÂj ``` [Try it!](https://zippymagician.github.io/Arn?code=Py4kdnshJnZ9fjM=&input=MSAyCjEgMQoyIDMKMyAz) # Explained Unpacked: `?.$v{!&v}~3` ``` ?. Random entry in $ Filtered list v{ With block; entry named v ! Boolean NOT _ Variable ≡ STDIN; implied & Contains (implicit casting to array) v Variable `v` } End block ~ On one-range to 3 Literal three ``` [Answer] # Julia, 32 or 56 depending on the rules ``` julia> r()=rand(1:3);f(x...)=(i=r();i in x?f(x...):i) julia> f(r(),r()) ``` 32 if I don't need to generate a and b. [Answer] ## JS, 43 ``` for(C=0;~[0,A,B].indexOf(C);)C=1+new Date%3 ``` [Answer] # Java - ~~126~~ ~~123~~ ~~83~~ 85 (using the clever `c=6-a-b`) ``` int c;if(a==b){int r=(int)(Math.random()*2);c=a==1?r+2:a==2?2*r+1:r+1;}else{c=6-a-b;} ``` Full version: ``` public void test(int a, int b) { int c; if (a == b) { // Random 0 or 1. int r = (int)Math.random()*2; c = // 1 -> 2 or 3 a == 1 ? r + 2 // 2 -> 1 or 3 : a == 2 ? 2 * r + 1 // 3 -> 1 or 2 : r + 1; } else { // Whichever is not taken. //int[][] r = {{0, 3, 2}, {3, 0, 1}, {2, 1, 0}}; //c = r[a - 1][b - 1]; // Using @steveverrill's clever c = 6 - a - b; } System.out.println("a=" + a + " b=" + b + " c=" + c); } ``` [Answer] ## R, 24 characters Initialize with ``` a = sample(1:3,1) b = sample(1:3,1) ``` Then ``` n=1:3;n[!n%in%c(a,b)][1] ``` Or just `n=1:3;n[!n%in%c(a,b)]` but then you return *both* numbers. [Answer] **R, 31 characters** ``` sample(rep((1:3)[-c(A,B)],2),1) ``` If you do `sample(x)` in R, then it is interpreted as a random sample from `1:x`. Repeating the vector `(1:3)[-c(A,B)]` twice is one way of stopping this from happening. [Answer] # Javascript - 76 ``` r=(y,z)=>Math.floor(Math.random()*(z-y+1)+y);a=b=r(1,3);while(c==a)c=r(1,3); ``` [Answer] # C - 38 ``` main(c){for(;c==a|c==b;c=rand()%2+1);} ``` [Answer] ## Java, 264 bytes ``` Random r = new Random();ArrayList<Integer> s = new ArrayList<>();ArrayList<Integer> q = new ArrayList<>();for(int i=0; i<n; i++) s.add(r.nextInt(k));q.add(s.get(r.nextInt(n)));q.add(s.get(r.nextInt(n)));int x;do{x = s.get(r.nextInt()); }while(!q.contains(x)); ``` This code generates `n` different random numbers from 0 to `k`. [Answer] # J (~~21~~ 19: too long for my liking) ``` ({~?@#)(>:i.3)-.A,B ``` ~~Are there any J wizards around to help remove that variable assignment?~~ It's only 2 chars shorter... Or, if it doesn't have to be random, you could do with this: ``` {:(i.4)-.A,B ``` 12 chars. [Answer] # Golfscript, 13 Characters ``` ~]4,^.,rand)= ``` [Answer] # JavaScript - 41 (up to 46) 37 35 34 30 Updated: Managed to get it down to 30 chars by modifying it, inspired by stevevarrill's answer in C. `C=A-B?6-A-B:1+(A+new Date%2)%3` --- Thank you nyuszika7h for getting me down to 34~: `C=A;while(C==A|C==B)C=1+new Date%3` Borrowing from xem's answer to at least fall on par with him: `C=A;while(C==A||C==B)C=1+new Date%3` Thanks for reminding me that `1+new Date%3 === (new Date%3)+1`! Previous Solution: `C=A;while(C==A||C==B)C=(new Date%3)+1` Ensure conditions of `while()` are satisfied, and loop through until they're not. --- Other solution: `C=A!=B?6-A-B:A%2!=0?4-B:new Date%2!=1?3:1;` This assumes that `C` has already been declared OR that the JavaScript interpreter can handle undeclared variables. However, if the JS interpreter can handle EOL without a semicolon, it could be bumped down to 41. `C=A!=B?6-A-B:A%2!=0?4-B:new Date%2!=1?3:1` If `C` hasn't been declared, and there is no error correction for it, that will bring the tally up to 46 characters. `var C=A!=B?6-A-B:A%2!=0?4-B:new Date%2!=1?3:1;` Test Program: ``` var iterations = 100; for(var i = 0;i<iterations;i++) { var A = Math.floor(Math.random() * 3) + 1; var B = Math.floor(Math.random() * 3) + 1; C=A!=B?6-A-B:A%2!=0?4-B:new Date%2!=1?3:1 if (C === A || C === B || C > 3 || C < 1) { console.log('FAILURE!'); console.log(A + ',' + B + ',' + C) return; } console.log(A+','+B+','+C); } ``` [Answer] ## Befunge-98 (57 bytes) This code assumes the numbers will be input on stdin. It will pick a random number if both of the first numbers are the same until it is different, otherwise it will choose the last available number. ``` 6&::11p&:12pw> ?1 >#<:11g-!_.@ @.-g21-<>3;#[2#;^ ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` 3Rḟ⁸X ``` [Try it online!](https://tio.run/##y0rNyan8/9846OGO@Y8ad0T8P9z@qGnN///RXJzRhjoKhrE6EIYRjGEMZhjBpIxgUkYwKWOYlDFMyhgiFQsA "Jelly – Try It Online") This takes `[A, B]` as input, as Jelly doesn't have the concept of variables ## How it works ``` 3Rḟ⁸X - Main link. Takes [A, B] on the left 3R - Yield [1, 2, 3] ⁸ - Yield [A, B] ḟ - Remove [A, B] from [1, 2, 3] X - Randomly select an element from the remaining list ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` 3õ kU ö ``` [Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=M/Uga1Ug9g&input=WzEsMl0) ]
[Question] [ You and a friend walk into a bar. The bartender treats you well, so you decide to tip him. So you pull out your trusty pocket computer and write a quick program to calculate a tip for you since it has no built in calculator. But wait! Your operator keys are broken! Your task is to calculate a 20% tip for any given input amount. The test inputs will be in the form of xx.xx e.g. 20.96. Here are the rules: * No use of the following in mathematical form operators: `+ - * / %` (Thanks Wally West) * No use of built in percent functions or APIs * No accessing the network * No use of `eval` or similar * No Windows Calculator (yes people have answered with it before) * No built in tip functions (Not that any language would have one) Output should be rounded up to two decimal places. Score is based on length in bytes. **-20%** if your program can accept any tip amount. Input for amount will be given in the form of xx e.g. 35 not 0.35 [Answer] ## Javascript 81 **EDIT** : The result is now a real rounding, not truncated. Do not use **ANY** math here, just string manipulation and bitwise operators. All the `+` char are string concatenation, or *string to float* conversion. Works for any xx.xx input and outputs in (x)x.xx format ``` s='00'+(prompt().replace('.','')<<1);(+s.replace(/(.*)(...)/,'$1.$2')).toFixed(2) ``` Trick explained : 20% is divided by 10 and multiplied by 2. * Make a division by 10 by *moving* the dot to the left (string manipulation) * Multiply each part by 2 by *moving* bits to the left (bitwise operation) [Answer] # J (9 characters) A short answer in J: ``` ^.(^.2)^~ 32 ``` [Answer] # Pure bash, 50 43 chars Pretty sure this'll be beat, but here's a start: ``` a=$[10#${1/.}<<1] echo ${a%???}.${a: -3:2} ``` As per the comments: * `/` is not a division operator here, it is part of a pattern substitution [parameter expansion](http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html) * `%` is not a modulo operator here, it is part of a parameter expansion * `-` is not a subtraction operator here, it is a negation, which was allowed as per the comments Output: ``` $ ./20pct.sh 0.96 .19 $ ./20pct.sh 20.96 4.19 $ ./20pct.sh 1020.96 204.19 $ ``` [Answer] ## Python 98\*0.8=78.4 ``` d=`len('X'*int("{}{:>02}".format(*(raw_input()+".0").split('.')))*2)`;print'%s.%s'%(d[:-3],d[-3:]) ``` ## Python 74 (without bonus) ``` d=len('X'*int(raw_input().replace('.',''))*2);print'%s.%s'%(d[:-3],d[-3:]) ``` **Note** * `+` is used for string concatenation * `*` used to create copies of string **Ungolfed** ``` def tip(): amount = raw_input() #Add an extra decimal point so that we can accept integer #amount amount += ".0" #Split the integer and decimal part whole, frac = amount.split('.') #Multiply amount by 100 :-) amount = "{}{:>02}".format(whole, frac) #Create amount copies of a character st = 'X'*amount #Double it st *= 2 #Calculate the Length d = len(st) #Display the result as 3 decimal fraction print'%s.%s'%(d[:-3],d[-3:]) ``` **Note** In spirit of the question, I believe the following solution though follows all rules of the question is an abuse ## Python 41 ``` print __import__("operator")(input(),0.2) ``` **Finally** If you insist that the mathematical symbols are forbidden, her is a 90 character solution ## Python 90 (without any mathematical symbol) ``` print' '.join(str(int(raw_input().replace(".",""))<<1)).replace(' ','.',1).replace(' ','') ``` [Answer] # APL (9 characters, new code with 7 characters, fixed with 13 characters) Compute 20% of the given amount. ``` {⍟⍵*⍨*.2} 32 ``` In APL `*` is the exponential operator. Try it [online](http://ngn.github.io/apl/web/index.html#code=%7B%u235F%u2375%2a%u2368%2a.2%7D%2032). But why use a function for that? See this new version: ``` ⍟(*.2)* 32 ``` Try it [online](http://ngn.github.io/apl/web/index.html#code=%u235F%28%2a.2%29%2a%2032). Please, before downvoting, the `*` is not forbidden as a KEY and it doesn't mean multiplication here. OK, here is the version rounding to 2 decimals (Dyalog APL): ``` ⎕PP←2⋄⍟(*.2)* 32.01 ``` [Answer] # **R, 30 27 36 34** *Updated to round to 2 decimal places* *Saved 2 characters thanks to plannapus* Creates a vector from 0 to x and takes the 2nd element. ``` a=function(x)round(seq(0,x,l=6)[2],2) ``` Example: ``` > a(20.36) [1] 4.07 ``` ## Further explanation: ``` seq(0,x,len=6) ``` creates a vector of length 6 from 0 to the input value x, with the values in between equally spaced. ``` > seq(0,5,len=6) [1] 0 1 2 3 4 5 ``` The first value is then 0%, the second 20%, third 40%, etc. [Answer] # dc + sed + pipes (44 characters) My third answer (one APL, one J, and now one with the old and venerable dc). ``` dc -e 5o?p|sed -e 's/\(.\)$/.\1/'|dc -e 5i?p ``` It will ask for an INTEGER input and compute 20% with a tricky way. Input is converted to base 5 (easy to do with many other tools but wait...); a dot is appended before the last digit with sed (unfortunately, dc can't handle strings very well), and THEN, dc converts back from base 5 on a float number (not all tools can do that). [Answer] ## Python, 88 This is no where near short, but this demonstrate how a normal mental division by five should be done. This assumes that the input must be of the form xx.xx ``` import math a,b=raw_input().split('.') print'%.2f'%math.ldexp(float(a[0]+'.'+a[1]+b),1) ``` Or for input of any length, an addition of 3 characters is required. ``` import math a,b=raw_input().split('.') print'%.2f'%math.ldexp(float(a[:-1]+'.'+a[-1]+b),1) ``` Explanation: We take the input as string, then move the decimal point one place forward (dividing by 10). We then cast it to a float, and use the `ldexp` function to multiply it by 2. Note that in this answer, the `+` are string concatenation operators, and the `%` are used to format `print`. If you insist on not using any of these characters, here is a 159 character solution: ``` import math a,b=raw_input().split('.') l=[a[0]] l.append('.') l.append(a[1]) l.append(b) c=str(math.ldexp(float(''.join(l)),1)) print ''.join([c[0:2],c[2:4]]) ``` [Answer] # dc + sed -- 45 \* 0.8 = 36 (Inspired by [the answer](https://codegolf.stackexchange.com/a/23842/8560) by [ברוכאל](https://codegolf.stackexchange.com/users/17641/17641)) * Handles any tip amount (integer or float) Example runs (input is accepted via STDIN): ``` $ dc -e 5o?.0+p|sed 's/\(.\)\./.\1/'|dc -e 5i?p 42 8.400 $ dc -e 5o?.0+p|sed 's/\(.\)\./.\1/'|dc -e 5i?p 20.96 4.1920 ``` [Answer] # Mathematica, 19 ``` Log[(E^.2)^Input[]] ``` No use of the mathematical operators of `+`, `-`, `*`, `/`, or `%`. Uses properties of logarithms to calculate the answer; when you simplify the expression, you get `.2*Input[]` With the bonus (**30 \* 0.8 = 24**): ``` Log[((E^.01)^Input[])^Input[]] ``` Input the percentage first, then the amount. When you simplify the expression, you get `Input[]*Input[]*.01`. Thanks to [ברוכאל](https://codegolf.stackexchange.com/questions/23814/calculate-a-tip/23821#comment49846_23821) for help with shortening the code. [Answer] # TI-89 Basic - 39 \* 0.8 = 31.2 ``` Input y:Input x:Disp ln(((e^y)^.01)^x)) ``` Works by inputting the two numbers, then using the logarithm properties to compute `x * y / 100`. If I can assume input from placement in global variables `x` and `y`, then this is much shorter, for a score of **17 \* 0.8 = 13.6**: ``` ln(((e^y)^.01)^x) ``` Without bonus (**12**): ``` ln((e^.2)^x) ``` But if it needs to be wrapped in a function, then this works (**38** chars, for **30.4**): ``` :f(x,y):Func:ln(((e^y)^.01)^x):EndFunc ``` [Answer] # PHP 107 \*.8 = 85.6 can't really run for code-golf with PHP, but at least I can operate on strings. accepts both numbers as command-line arguments. ``` <? @$r=strrev;unset($argv[0]);echo$r(substr_replace($r(str_replace('.','',array_product($argv)))),'.',2,0); ``` had to reverse it twice since I can't use -2 :( [Answer] # Python, 81 80 89 characters ``` a,b=map(str,raw_input().split('.'));c=str(int(a+b)<<1).zfill(4);print c[:-3]+'.'+c[-3:-1] ``` Explanation ``` x = raw_input() # say 20.96 a , b = x.split('.') # a = 20 , b = 96 c = a + b # c = '2096' # string concatenation , multiplying by 100 d = int(c)<<1 # multiply by 2 by bitshift left , c = 4096 e = str(d).zfill(4) # zfill pads 0's making the string # atleast 4 chars which is required # for decimal notation next # divide by 1000 (4) + . (4.) + fraction rounded to 2 decimals (4.09) print e[:-3] + '.' + e[-3:-1] ``` Technically, this is cheating as it truncates to two decimals rather than rounding it but I can argue that it rounds down(Better for you, less tip). [Answer] # JavaScript 251 (forced restriction: no +, -, \*, ? or % in any manner) While I know this won't win, I figured I'd try to get brownie points through taking a very strict approach and not even think about using the restricted operators in any shape or form... as a result, I came up with this beauty... ``` A=(x,y)=>{for(;x;)b=x^y,x=(a=x&y)<<1,y=b;return y};D=(x,y,i=x,j=0)=>{for(;i>=y;)i=A(i,A(~y,1)),j=A(j,1);return j};alert(parseFloat((x="00".concat(String(D(prompt().replace(".",""),5)))).substr(0,A(x.length,y=A(~2,1))).concat(".").concat(x.substr(y)))) ``` I used bitwise operations to create the Add function `A`, and then started chaining up from there: The integer division function `D` used a series of Negated Addition (subtraction in the form of `A(x,A(~y,1)` over a loop; the rest is string manipulation and concatenation so as to avoid using `+` concatenation operators... The number must be provided in decimal form with two decimal places for this to work... [Answer] ## Perl, 50 60 bytes ``` $_=<>;s|\.||;$_<<=1;$_="00$_";m|\d{3}$|;printf'%.2f',"$`.$&" ``` The input is expected at STDIN. It must contain the decimal separator with two decimal digits. The output is written to STDOUT. **Update:** The step `$_<<=1` removes leading zeroes. Therefore `m|\d{3}$|` would not match for bills < 1. Therefore ten bytes `$_="00$` were added, Now even `0.00` works. Examples: * Input: `20.96`, output: `4.19` * Input: `12.34`, output: `2.47` **Ungolfed version:** ``` $_=<>; s|\.||; # multiply by 100 $_ <<= 1; # multiply by 2 $_="00$_"; m|\d{3}$|; # divide by 1000 printf '%.2f'," $`.$&" ``` First the number is read from STDIN. Then the decimal dot is removed, that is multiplied with 100. Then the amount is doubled by a shifting operator. Then the decimal dot is reinserted and the result is printed and rounded to two decimal digits. **50 bytes, if bill ≥ 1:** If `x.xx` is greater or equal than `1.00`, then 10 bytes can be removed: ``` $_=<>;s|\.||;$_<<=1;m|\d{3}$|;printf'%.2f',"$`.$&" ``` [Answer] # JavaScript (ES6) (Regex) 142 Regex is great and it can do many things. It can even do maths! ``` a=('x'.repeat(prompt().replace('.', ''))+'xxxx').match(/^((x*)\2{99}(x{0,99}))\1{4}x{0,4}$/);c=a[3].length;alert(a[2].length+'.'+(c<10?'0'+c:c)) ``` --- Readable version: ``` function tip(m) { var s = 'x'.repeat(m.replace('.', '')) + 'xxxx'; var a = s.match(/^((x*)\2{99}(x{0,99}))\1{4}x{0,4}$/); var c = a[3].length; if (c < 10) c = '0' + c; return a[2].length + '.' + c; } ``` The `tip()` function expects String argument, rather than Number. All instances of `*`, `/`, `+` are not related to math operations. * `+` is string concatenation in all instances it is used. * `*` is part of RegExp syntax * `/` is the delimiter of RegExp literal The input **must** use `.` as decimal point, and there **must** be 2 digits after decimal point. # Stack Snippet ``` <button onclick = "a=('x'.repeat(prompt().replace('.', ''))+'xxxx').match(/^((x*)\2{99}(x{0,99}))\1{4}x{0,4}$/);c=a[3].length;alert(a[2].length+'.'+(c<10?'0'+c:c))">Try it out</button> ``` [Answer] ## Haskell 32 Chars -20% = 25.6 Chars ``` t y x=log $(^x)$(**0.01)$ exp y ``` Abuses the fact that exponents become multiplication in logarithms. ]
[Question] [ Given two inputs, a string \$s\$ and a decimal number \$n\$, output the string multiplied by that number. The catch is that the number can be a float or an integer. You should output the string \$\lfloor n \rfloor\$ times and then the first \$\lfloor (n - \lfloor n \rfloor) \cdot |\,s\,|)\rfloor\$ characters again. Other notes: * The input will not always be a float, it may be an integer. So `1.5`, `1`, and `1.0` are all possible. It will always be in base 10 though, and if you wish an exception please comment. * The string input may contain white space except newlines, quotes and other characters. Control characters are excluded, too, if this helps. * No built-ins for direct string repetition are allowed. That means for instance Python’s `'a'*5` is forbidden. Nevertheless string concatenation (frequently denoted by the `+` sign) is allowed. ## Test cases | \$s\$ | \$n\$ | result | | --- | --- | --- | | `test case` | `1` | `test case` | | `case` | `2.5` | `casecaseca` | | `(will add more later)` | `0.3333` | `(will` | | `cats >= dogs` | `0.5` | `cats >` | ## Final Note I am seeing a lot of answers that use builtin string multiplication or repetition functions. This is *not* allowed. The rule is: If it directly multiplies the string, you cannot do it. [Answer] ## Java 7, 89 ``` void g(char[]a,float b){for(int i=0,l=a.length;i<(int)(l*b);)System.out.print(a[i++%l]);} ``` takes char[] and float and outputs to STDOUT. basic looping. [Answer] # Pyth, ~~9~~ 8 ``` s@Lz*lzQ ``` Saved 1 byte thanks to Pietu1998 This takes `floor(n * len(string))` letters from the string, using cyclical indexing. I believe this is always equivalent to the given formula. [Test Suite](http://pyth.herokuapp.com/?code=s%40Lz%2alzQ&input=case%0A2.5&test_suite=1&test_suite_input=test+case%0A1%0Acase%0A2.5%0A%28will+add+more+later%29%0A0.3333%0Acats+%3E%3D+dogs%0A0.5&debug=0&input_size=2) [Answer] # JavaScript (ES6), 50 bytes **Edit** 2 bytes more to include definition of function `f`. 1 byte less using the tip of @manatwork. Note: using `~` we have more iterations than necessary, but this is code golf and even 1 byte counts ``` f=(s,n,l=s.length*n)=>~n?f(s+s,n-1,l):s.slice(0,l) ``` **TEST** ``` f=(s,n,l=s.length*n)=>~n?f(s+s,n-1,l):s.slice(0,l) //TEST console.log=x=>O.textContent+=x+'\n' ;[ ['test case', 1, 'test case'], ['case', 3.5, 'casecasecaseca'], ['(will add more later)', 0.3333, '(will '], ['cats >= dogs', 0.5, 'cats >']] .forEach(t=>{ var s=t[0],n=t[1],x=t[2],r=f(s,n); console.log("«"+s+"» "+n+' => «'+r+'» '+(x==r?'OK':'FAIL expected '+x)); }) ``` ``` <pre id=O></pre> ``` [Answer] # Jelly, 5 bytes ``` ×L}Rị ``` Doesn't use a repetition built-in. [Try it online!](http://jelly.tryitonline.net/#code=w5dMfVLhu4s&input=&args=Mi41+Y2FzZQ) ### How it works ``` ×L}Rị Main link. Left input: n (multiplier). Right input: S (string) L} Yield the length of S. × Multiply it with n. R Range; turn n×len(S) into [1, ... floor(n×len(S))]. ị Retrieve the elements of S at those indices. Indices are 1-based and modular in Jelly, so this begins with the first and jump back after reaching the last. ``` [Answer] # Vitsy, 9 bytes Expects the word as an argument, and the number to multiply by through STDIN. ``` zlW*\[DO{] z Grab all string argument input. l Get the length of the stack. W Parse STDIN. * Multiply the top two items (length of string and the number of repetitions) \[ ] Do the stuff in the loop. DO{ Output one char at a time, making sure to duplicate first. ``` [Try it online!](http://vitsy.tryitonline.net/#code=emxXKlxbRE97XQ&input=Mi41&args=Y2FzZQ) [Answer] ## CJam, 10 bytes ``` l_,l~*,\f= ``` The string is supplied on the first line of STDIN, the float on the second. [Test it here.](http://cjam.aditsu.net/#code=l_%2Cl~*%2C%5Cf%3D&input=cats%20%3C%3D%20dogs%0A0.5) ### Explanation ``` l e# Read string. _, e# Duplicate and get its length. l~ e# Read second line and evaluate. * e# Multiply them. If the result, N, was floored it would give us the number of e# characters in the required output. , e# Get range [0 1 ... ⌊N⌋-1]. \f= e# For each character in that range, fetch the corresponding character from the e# string using cyclic indexing. ``` [Answer] # Python 2, 71 bytes ``` lambda s,x:"".join(s for i in range(int(x)))+s[:int(len(s)*(x-int(x)))] ``` [Try it here!](https://repl.it/Bknh) Creates an unnamed lambda which takes the string as first argument and the float as second. Returns the repeated string. This could be 46 if string repetition builtins were allowed :( [Answer] # Ruby, ~~49~~ 48 characters ``` ->s,n{(0...(n*l=s.size).to_i).map{|i|s[i%l]}*''} ``` Sample run: ``` 2.1.5 :001 > ->s,n{(0...(n*l=s.size).to_i).map{|i|s[i%l]}*''}['case', 2.5] => "casecaseca" ``` [Answer] # [Perl 6](http://perl6.org), ~~46 41~~ 39 bytes ``` {([~] $^a xx$^b)~$a.substr(0,$a.chars*($b%1))} # 46 bytes {substr ([~] $^a xx$^b+1),0,$a.chars*$^b} # 41 bytes {substr ([~] $^a xx$^b+1),0,$a.comb*$b} # 39 bytes ``` Perl 6 has both a string repetition operator `x` and a list repetition operator `xx`. Since the rules disallow string repetition, we repeat it as if it was a single element list instead. Then the list gets concatenated together, and a substring of it is returned. ### Usage: ``` # give it a lexical name my &code = {substr ([~] $^a xx$^b+1),0,$a.chars*$^b} # {substr ($^a x$^b+1),0,$a.chars*$^b} say code('test case', 1).perl; # "test case" say code('case', 2.5).perl; # "casecaseca" say code('(will add more later)', 0.3333).perl; # "(will " say code('cats >= dogs', 0.5).perl; # "cats >" ``` [Answer] # osascript, 173 bytes Oh my days, this is worse than I thought. ``` on run a set x to a's item 1's characters set y to a's item 2 set o to"" set i to 1 set z to x's items's number repeat y*z set o to o&x's item i set i to i mod z+1 end o end ``` Returns the value of the string, another answer using cyclical indexing. Expects input as `"string" "repetitions"`. [Answer] ## Haskell, 44 bytes ``` c x=x++c x s#n=take(floor$n*sum[1|a<-s])$c s ``` Usage example: `"(will add more later)" # 0.3333` -> `"(will "`. How it works: `c` concatenates infinite copies of the string `x`. It behaves like the built-in `cycle`. `sum[1|a<-s]` is a custom length function that works with Haskell's strict type system as it returns a `Double` (the built-in `length` returns an `Int` which cannot be multiplied with `n`). `#` takes `floor (n * length(s))` characters from the cycled string `s`. [Answer] ## PHP 5, ~~96~~ 87 9 bytes saved thanks to @manatwork ``` <?for($i=$z=0;$i++<floor(strlen($a=$argv[1])*$argv[2]);$z++)echo$a[$z]?:$a[$z=0‌​]; ``` Pretty straight forward looping answer. ### Ungolfed ``` <? $a=$argv[1]; $z=0; for($i=0; $i < floor(strlen($a)*$argv[2]); $i++) { // if the string offset is not set // then reset $z back to 0 so we can // echo the beginning of ths string again @$a[$z] ?: $z=0; echo $a[$z]; $z++; } ``` [Answer] # R, 59 bytes ``` function(s,l)cat(rawToChar(array(charToRaw(s),nchar(s)*l))) ``` As an unnamed function. This uses charToRaw to split the string into a vector of raws. This is filled into an array of length \* l, converted back to char and output. I was going to use strsplit, but it ended up being longer. Test ``` > f= + function(s,l)cat(rawToChar(array(charToRaw(s),nchar(s)*l))) > f('test case', 1) # -> test case test case > f('case', 2.5) # -> casecaseca casecaseca > f('(will add more later)', 0.3333) # -> (will(space) (will > f('cats >= dogs', 0.5) # -> cats > cats > > ``` [Answer] ## Perl, 51 + 3 = 54 bytes ``` $l=<>*y///c;for$i(1..$l){push@a,/./g}say@a[0..$l-1] ``` Requires: `-n`, `-l` and `-M5.010` | `-E`: ``` $ perl -nlE'$l=<>*y///c;for$i(1..$l){push@a,/./g}say@a[0..$l-1]' <<< $'test case\n1' test case $ perl -nlE'$l=<>*y///c;for$i(1..$l){push@a,/./g}say@a[0..$l-1]' <<< $'case\n2.5' casecaseca $ perl -nlE'$l=<>*y///c;for$i(1..$l){push@a,/./g}say@a[0..$l-1]' <<< $'(will add more later)\n0.3333' (will $ perl -nlE'$l=<>*y///c;for$i(1..$l){push@a,/./g}say@a[0..$l-1]' <<< $'cats >= dogs\n0.5' cats > ``` Explanation: ``` $l=<>*y///c; # Calculate output length (eg. 2.5 * input length) for$i(1..$l){push@a,/./g} # Push a lot of chars from input into @a say@a[0..$l-1] # Slice @a according to output length ``` [Answer] # c (preprocessor macro), 71 ``` j,l; #define f(s,m) l=strlen(s);for(j=0;j<(int)(l*m);)putchar(s[j++%l]) ``` Not much tricky here. Just need to make sure `l*m` is cast to an `int` before comparing to `j`. [Try it online.](https://ideone.com/eOZpew) [Answer] # Oracle SQL 11.2, ~~154~~ 152 bytes ``` WITH v(s,i)AS(SELECT SUBSTR(:1,1,FLOOR(FLOOR((:2-FLOOR(:2))*LENGTH(:1)))),1 FROM DUAL UNION ALL SELECT :1||s,i+1 FROM v WHERE i<=:2)SELECT MAX(s)FROM v; ``` Un-golfed ``` WITH v(s,i) AS ( SELECT SUBSTR(:1,1,FLOOR(FLOOR((:2-FLOOR(:2))*LENGTH(:1)))),1 FROM DUAL UNION ALL SELECT :1||s,i+1 FROM v WHERE i<=:2 ) SELECT MAX(s) FROM v; ``` I went the recursive way, with the initialisation select taking care of the decimal part. Saved 2 bytes thanks to @MickyT [Answer] ## Seriously, 24 bytes ``` ,╗,mi@≈╜n╜l(*≈r`╜E`MΣ)kΣ ``` [Try it online!](http://seriously.tryitonline.net/#code=LOKVlyxtaUDiiYjilZxu4pWcbCgq4omIcmDilZxFYE3OoylrzqM&input=InRlc3QiCjIuNQ) Explanation: ``` ,╗,mi@≈╜n╜l(*≈r`╜E`MΣ)kΣ ,╗ get first input (string) and push it to register 0 ,mi@≈ get input 2 (x), push frac(x) (f), int(x) (n) ╜n push n copies of the string ╜l(*≈ push length of string, multiply by f, floor (substring length) (z) r`╜E`MΣ push s[:z] )kΣ move fractional part of string to bottom, concat entire stack ``` [Answer] ## Pyth, 9 bytes ``` V*Elzp@zN ``` Basically just doing ``` z = input() V*Elz for N in range(evaluatedInput()*len(z)): # flooring is automatic p@zN print(z[N], end="") # modular indexing ``` [Answer] ## Pascal, 138 B This full `program` requires a processor compliant with ISO standard 10206 “Extended Pascal”. Trivial cases have been excluded: It is presumed that the input string `s` is *non-empty* and `n` is *positive*. NB: The golfed version caps `s` at a reasonable length of `999`. ``` program p(input,output);var s:string(999);n:real;begin read(s,n);while n>1 do begin n:=n-1;write(s)end;write(s[1..trunc(length(s)*n)])end. ``` Ungolfed: ``` program decimalMultiplicationOfStrings(input, output); var { `string` is a schema data type defined by Extended Pascal. The `string(maxInt)` discriminates the schema data type. Henceforth the specific `string` has a capacity of `maxInt`. } s: string(maxInt); n: real; begin { You can specify `real` as well as `integer` literals for `n`. An `integer` value is automatically promoted to `real`. } read(s, n); { The `string` subrange notation used below in the last line may not specify an empty range (e. g. `1‥0` is illegal). Therefore the `while` loop’s condition is `n > 1`. If `n = 1`, the one copy is printed via the final line. } while n > 1 do begin n ≔ n − 1; write(s); end; { The subrange notation is defined by Extended Pascal. It cannot be used for strings that are `bindable`. } write(s[1‥trunc(length(s) * n)]); end. ``` Input is end-of-line separated. `s` can otherwise contain any character from `chr(0)` to (the implementation-defined) `maxChar` range. [Answer] # [Nim](https://nim-lang.org/), 75 bytes ``` func r[S,F](s:S,n:F):S= for i in 0..<int n*s.len.float:result&=s[i%%s.len] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY_NCoJAFEb3PsVFMJywwQohhmzppqVLcTHoTA2MMzF3pIdpI0QP1dskptS3POf-8D2eRnXD8Oq93BzeZ9mbBlxVJkUdIysTwwrCyjwAaR0oUAZSSo_KeDBrpFoYKrXlnjmBvfarHCsVRZOo55M30VwtuDj0Aj00HEWYwJamJFjEzHY0-7H4rrQG3rbQWSdAcy8cGYdSuh_zv-sRTjm09oKTzsj371LpAw) [Answer] # [Scala](http://www.scala-lang.org/), 68 bytes Golfed version. [Try it online!](https://tio.run/##JY6xCsIwEIb3PsUhCBepQQWXSgqCi4OTOIlDWtMaTZOSnIKUPnuM9Lbvvp@7P9TSyOiqp6oJTlJbGLIM4CMNNAWeyWvb5gf3roxiopwYRMSQ28TDP2dE4EbZlh47XAE5QLswjJM7WlquGe9kj1qUAfXcsISv6coYAe6qgS49RenbUMDee/m9TvrGCrhYTSBSI0jTpy0Ziw3OahnULIcN3zKW3JiN8Qc) ``` (s,n)=>{val l=s.length;(0 to (n*l).toInt-1).map(i=>s(i%l)).mkString} ``` Ungolfed version. [Try it online!](https://tio.run/##VY9BawIxEIXv/oqHUEiKLCJ4ESwUehHsSTxJD7NruqaNs0syCiL727djthV7msmb92a@pIoC9X1TfrlK8E6ecR0Be/eJ6FpHspHouTZpgaGbgBd4a05lcPZPwzKHgDMFBMf6ToXWWg53edi2zkPDeL75bCHNiiV7zBQnFv9gtMWRWuOxfEHS8pQTKn4PRzXVjX5Rj8ptKNZK@RojXXaD5UMJt@zlzteqKoHNv6@NK0puPMGsmFubt3Z9/wM) ``` object Main { def repeatString(s: String, n: Double): String = { val len = s.length val repeatLen = (n * len).toInt (0 until repeatLen).map(i => s(i % len)).mkString } def main(args: Array[String]): Unit = { println(repeatString("case", 2.5)) } } ``` ]
[Question] [ The goal of this challenge is to make a program that outputs the nth letter of its source code where n is given as input to the program. Like most quine challenges, you are not allowed to read your source code as a file or use any builtin quine functions. ## Input An integer 0 <= n < len(program). ## Output The nth character (not byte) of your program. ## Winning Like most codegolf questions, you win the challenge by using the lowest number of bytes to solve the challenge. ## Bonuses -5% If your program supports negative indices python style (e.g. -1 would be the last character of your program). If used with the below bonus, your ranges must support negative indices. -20% If your program supports ranges as input (any format) in addition to the above requirements. -25% If your program complete both bonuses. ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=70727,OVERRIDE_USER=32700;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?([\d\.]+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Pyth, 0.75 bytes (Also happens to be a CJam polyglot, and probably many other languages.) ``` 0 ``` Expects input on STDIN: ``` llama@llama:~$ echo 0..0 | pyth -c '0' 0 ``` Any single digit works, of course. Not exactly the most interesting challenge in Pyth. [Answer] # Javascript ES6, 31 bytes ``` $=_=>`$=${$};$()`[prompt()];$() ``` # Explanation The standard quine framework: ``` $=_=>`$=${$};$()`;$() ``` `[prompt()]`, which is the addon, gets the value at the input index of the resulting quine string. [Answer] # 𝔼𝕊𝕄𝕚𝕟, 9 chars / 19 bytes ``` ⟮ɕṡ+ᶈ0)⎖ï ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=3&code=%E2%9F%AE%C9%95%E1%B9%A1%2B%E1%B6%880%29%E2%8E%96%C3%AF)` *Ay, 19th byte!* `0` works too (and is much better), but it's way too trivial for my liking. In addition, `ℹ ï,⧺ï` would also work, but quine functions aren't allowed. ## Explanation The standard quine framework is `⟮ɕṡ+ᶈ0`. `)⎖ï` takes the resulting quine string and gets the character at the input index. --- # Bonus solution, 11.4 chars / 25.65 bytes ``` ⟮ᵖ…ɕṡ+ᶈ0;ôᵍï ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=-2&code=%E2%9F%AE%E1%B5%96%E2%80%A6%C9%95%E1%B9%A1%2B%E1%B6%880%3B%C3%B4%E1%B5%8D%C3%AF)` This one qualifies for the 5% bonus, but still does not beat my original submission. ## Explanation This one uses the stack. `ᵖ…ɕṡ+ᶈ0;` just pushes the quine string's individual characters to the stack, and `ôᵍï` directly outputs the character at the input index (positive or negative) in the stack. [Answer] # CJam, 12.35 bytes ``` {s"_~"+ri=}_~ ``` The program is **13 bytes** long and qualifies for the **× 0.95** bonus. [Try it online!](http://cjam.tryitonline.net/#code=e3MiX34iK3JpPX1ffg&input=LTI) ### How it works ``` { } Define a code block. _~ Push a copy and execute the copy. s Cast the original code block to string. "_~"+ Append "_~". ri Read an integer from STDIN. = Retrieve the character at that index. ``` [Answer] # Polyglot, 0 bytes ``` ``` [Try It Online!](https://tio.run) (you'll have to select a language yourself) The challenge specifies taking an integer \$ 0 \le n \lt \text{len}(\text{program}) \$, but with a 0-byte program there is no integer that is both ≥ 0 and < 0. This means the program can do whatever it wants. When I say polyglot, I mean that it works in any language whatsoever. [Answer] # Ruby, 53 \* 0.75 = 39.75 ``` $><<(<<2*2+?2)[eval gets] $><<(<<2*2+?2)[eval gets] 2 ``` Generates a HEREDOC string delimited by a `2` on its own line, concatenates it (`*2`) and then adds in the final `2` via a character literal. Slices into it using Ruby's built in `String#[]`, which supports positive integers, negative integers, and ranges (input in the form `m..n`). `$><<` is output. (`puts` would require an extra space here). [Answer] # Ruby, 38.25 bytes ``` a="a=%p;$><<(a%%a)[eval gets]";$><<(a%a)[eval gets] ``` Support negative indices and ranges. I blatantly picked up both `$><<` and the `eval` trick from histocrat, and the quine trick was someone else's to begin with, so I'll make this CW. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~11~~ 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) All of the following use 0-based, modular indexing and support negative indexing. ``` gg ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Z2c&input=MgotbVA) ``` gg :Implicit input of integer g :Index into g :Literal "g" ``` ## Original, 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Based on [one of ETH's standard Japt quines](https://codegolf.stackexchange.com/a/156362/58974). ``` gBîQi"gBîQi ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Z0LuUWkiZ0LuUWk&input=MTEKLW1Q) (Includes full test suite) ``` gBîQi"gBîQi :Implicit input of integer g :Index into B : 11 î : Repeat to length B Q : Quotation mark i : Prepend "gBîQi : String literal ``` ### Array input, 13 bytes Same as above with the `m` at the start being `map` and the `D` being `13`, in place of `11`. ``` mgDîQi"mgDîQi ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bWdE7lFpIm1nRO5RaQ&input=WzAgMSAyIDMgNCA1IDYgNyA4IDkgMTAgMTEgLTFdCi1Q) [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 6 bytes ``` «•.\ü ``` Includes a trailing space. ## Explaination ``` «•.\ü « # Push the remainer of the code as a function and continue execution •. # Append a space to the end of the function as a string \ # Swap the string under the input value ü # Get the character at that index # A trailing space is included to ensure quine validity. ``` [Try it online!](https://tio.run/##Kyooyk/P0zX6///Q6kcNi/RiDu9R@P//vwEA "RProgN 2 – Try It Online") [Answer] # Python 2, 46.55 bytes ``` a="a=%r;print(a%%a)[input()]";print(a%a)[input()] ``` Supports negative indices. [Answer] # Haskell, 122 bytes ``` main=getLine>>= \i->putChar$(!!(read i))$p++show p where p="main=getLine>>= \\i->putChar$(!!(read i))$p++show p where p=" ``` Ungolfed: ``` main=getLine>>= \i->putChar$(!!(read i))$p++show p where p="main=getLine>>= \\i->putChar$(!!(read i))$p++show p\n where p=" ``` [Answer] ## Befunge 93, 5 bytes This is pretty (very) late but I'll post it anyway: ``` &0g,@ ``` [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 32 \log\_{256}(96) \approx \$ 26.34 \* 0.75 \$ \approx \$ 19.75 bytes ``` "D34CXx+xs+s+sAI"D34CXx+xs+s+sAI ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhY3FZRcjE2cIyq0K4q1gdDRE50PUQdVvmBPtIGOgqmOgiGQMgTSuiAM4ugamsZC1AAA) Based on [*@lyxal*'s Thunno quine](https://codegolf.stackexchange.com/a/256337/114446). Supports negative indices and ranges. ]
[Question] [ What general tips do you have for golfing in MATLAB? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to MATLAB (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] Something that one must know before starting to golf: In MATLAB calculations a character behaves the same as its ascii code. ``` 'abc' - 'a' % Returns: [0 1 2] '123' - '0' % Returns: [1 2 3] '“' == 8220 % Returns: 1 (logical) 'a':'e'==100 % Returns: [0 0 0 1 0] (logical) ``` [Answer] Shortening property names In MATLAB, strings identifying properties can be shortened as long as it does not result in ambiguity. ``` plot(X,'C','k') % Ambiguous property found. plot(X,'Co','k') % Expands to Color (black) ``` This actually [won](https://codegolf.stackexchange.com/questions/45736/fifty-shades-of-grey/46871#46871) me a challenge :) [Answer] Casting as char can be done by concatenation with a char: ``` x='a'+magic(5) % Array with character codes of several letters char(x) % The standard way ['' x] % The compact way ``` Though it only saves one char, this can be used quite frequently. [Answer] Strings are just character row vectors. This means that instead of ``` for i=numel(str) a=str(i) ... end ``` you can simply write ``` for(a=str) ... end ``` First time I used this: <https://codegolf.stackexchange.com/a/58387/32352> [Answer] Related, but not identical [tips for Octave](https://codegolf.stackexchange.com/a/111980/31516). A little known and little used feature of both MATLAB and Octave is that most builtin functions can be called without parentheses, in which case they will treat whatever follows it as a string (as long as it doesn't contain spaces). If it contains spaces you need quotation marks. This can frequently be used to save a byte when using `disp`: ``` disp('Hello, World!') disp 'Hello, World!' ``` Other, less useful examples include: ``` nnz PPCG ans = 4 size PPCG ans = 1 4 str2num 12 ans = 12 ``` I've actually used this twice in the *["How high can you count?"](https://codegolf.stackexchange.com/q/124362/31516)*-challenge: ``` strchr sssssssssssssst t ``` is equivalent to `strchr('sssssssssssssst','t')` and returns `15`. ``` nnz nnnnnnnnnnnnnn ``` is equivalent to `nnz('nnnnnnnnnnnnnn')` and returns `14`. Stuff like `gt r s` works too (equivalent to `'r'>'s'` or `gt('r','s')`. [Answer] # Roots of unity via discrete Fourier transform Given a positive integer `n`, the standard way to generate the `n`-th [roots of unity](https://en.wikipedia.org/wiki/Root_of_unity) is ``` exp(2j*pi*(0:n-1)/n) ``` This gives the roots starting at `1` and moving in the positive angular direction. If order doesn't matter, this can be shortened to ``` exp(2j*pi*(1:n)/n) ``` --- Since `exp(2j*pi/4)` equals the imaginary unit (`j`), this can be written more compactly as follows (trick [due to @flawr](https://codegolf.stackexchange.com/a/101855/36398)): ``` j.^(4*(0:n-1)/n) ``` or ``` j.^(4*(1:n)/n) ``` --- But the [discrete Fourier transform](https://en.wikipedia.org/wiki/Discrete_Fourier_transform) provides an even shorter way (thanks to @flawr for removing two unnecessary parentheses): ``` fft(1:n==n) ``` which gives the roots starting at `1` and moving in the positive angular direction; or ``` fft(1:n==2) ``` which starts at `1` and moves in the negative angular direction. --- Try all of the above [here](https://tio.run/##y08uSSxL/f8/T8FWwdiaK7WiQMMoS6sgU0vDwCpP11BTP08TWdDQKg8slKUXp2GCrAYqAJNPSysBsW1tkdlGmv//AwA). [Answer] `nnz` can sometimes save you a few bytes: * Imagine you want the sum of a logical matrix `A`. Instead of `sum(sum(A))` or `sum(A(:))`, you can use `nnz(a)` (`nnz` implitictly applies `(:)`). * If you want to know the number of elements of an array, and you can be sure there are no zeros, instead of `numel(x)` you can use `nnz(x)`. This is applicable for instance if `x` is a string. [Answer] Iteration over vectors in matrices. Given a set of vector as matrix, you can actually iterate over them via a single for loop like ``` for v=M disp(v); end ``` while "traditionally" you probably would have done it like ``` for k=1:n disp(M(:,k)); end ``` I've only learned about this trick just now from @Suever in [this challenge](https://codegolf.stackexchange.com/a/82410/24877). [Answer] ### 2D Convolution Kernels This is maybe a niche topic, but apparently some people like to use convolution for various things here. [citation needed] In 2D following kernels are often needed: ``` 0 1 0 1 1 1 0 1 0 ``` This can be achieved using ``` v=[1,2,1];v'*v>1 %logical v=[1,0,1];1-v'*v %as numbers ``` which is shorter than ``` [0,1,0;1,1,1;0,1,0] ``` Another kernel often used is ``` 0 1 0 1 0 1 0 1 0 ``` which can be shortened using ``` v=[1,-1,1];v'*v<0 % logical [0,1,0;1,0,1;0,1,0] % naive verison ``` [Answer] The built-in `ones` and `zeros` are a typically a waste of space. You can achieve the same result by simply multiplying an array/matrix (of the desired size) by 0 (to get the output of `zeros`) and add 1 if you want the output of `ones`. ``` d = rand(5,2); %// Using zeros z = zeros(size(d)); %// Not using zeros z = d*0; %// Using ones o = ones(size(d)); %// Not using ones o = 1+d*0 ``` This also works if you want to create a column or row vector of zeros or ones the size of one dimension of a matrix. ``` p = rand(5,2); z = zeros(size(p,1), 1); z = 0*p(:,1); o = ones(size(p, 1), 1); o = 1+0*p(:,1); ``` If you want to create a matrix of a specific size you could use `zeros` but you could also just assign the last element to 0 and have MATLAB fill in the rest. ``` %// This z = zeros(2,3); %// vs. This z(2,3) = 0; ``` [Answer] I quite often find myself using `meshgrid` or `ndgrid`, let's say we want to compute a mandelbrot image, then we initialize e.g. ``` [x,y]=meshgrid(-2:1e-2:1,-1:1e-2,1) ``` Now for the mandelbrot set we need another matrix `c` of the size of `x` and `y` but initialized with zeros. This can easily be done by writing: ``` c=x*0; ``` You can also initialize it to another value: ``` c=x*0+3; ``` But you can actually save some bytes by just adding another dimension in `meshgrid/ndgrid`: ``` [x,y,c]=meshgrid(-2:1e-2:1,-1:1e_2,1, 0); %or for the value 3 [x,y,c]=meshgrid(-2:1e-2:1,-1:1e_2,1, 3); ``` And you can do this as often as you want: ``` [x,y,c1,c2,c3,c4,c5]=meshgrid(-2:1e-2:1,-1:1e_2,1, 1,pi,exp(3),1e5,-3i) ``` [Answer] Counting the number of non zero elements in a matrix ``` zeronum(i)=nnz C; zeronum(i)=nnz(C); zeronum(i)=sum(C~=0); zeronum(i)=sum(abs(C)>=eps); zeronum(i)=numel(find(C~=0)); zeronum(i)=prod(size(find(C~=0))); ``` Horizontal replication is 3 copies, vertical replication is 2 copies ``` repmat([1,2;3,4],2,3) kron(ones(2,3),[1,2;3,4]) ``` Multiple variables, all initialized with the same data ``` [A,B,C,D]=deal([1 4;2 5;3 6]); %%%% A = [1 4; 2 5; 3 6]; B=A; C=A; D=A; ``` Declare a zero matrix of the same size as matrix A ``` X=0*A(:,1); X=zeros(size(A)); X=zeros(size(A),'like',A); ``` [Answer] ## Summation of a sequence of functions * For summing up functions f(x\_n) where n is a vector of consecutive integers, feval is adviced rather than symsum. ``` Syms x;symsum(f(x),x,1,n); Sum(feval(@(x)f(x),1:n)); ``` Notice that an elementary operation `.*` and `./` is necessary instead of pairwise binary operations `*` and `/` * If the function can be naively written no one from either last ways is suitable. for example if the function is `log` you can simply do: `sum(log(1:n))` , which represents: ``` Sum(f(1:n)); ``` for relatively sophisticated functions as `log(n)/x^n` you can do: ``` Sum(log(1:n)./5.^(1:n)) ``` and even shorter in some cases when a function is longer as `f(x)=e^x+sin(x)*log(x)/x`.... ``` Sum(feval(@(y)e.^(y)+sin(y).*log(y)./y,1:n)) ``` that is remarkably shorter than `sum(feval(@(y)e.^(1:n)+sin(1:n).*log(1:n)./(1:n),1:n))` --- **Note:** This trick can be applied for other inclusive operators as `prod` or `mean` --- ]
[Question] [ **Story** (skip, if you prefer the naked task): You need five skills for an imaginary sport: Speed, strength, endurance, accuracy and tactics. If you achieve a score in each of these disciplines, you can work out how well you have mastered the sport as a whole. But, as your coach always says: concentrate on your strengths, because they count more! **Rule:** The weakest score counts to the second power, the second weakest to the third power and so on. The strongest score counts with the sixth power! Let's take an **example**: A beginner has the scores `3, 2, 4, 1, 2`. Then they achieve a total of `1*1 * 2*2*2 * 2*2*2*2 * 3*3*3*3*3 * 4*4*4*4*4*4 = 127401984`. And what should they train, their greatest strength, i.e. improve the third discipline from 4 to 5? That would give them a score of 486000000. Or would it be better to work on their weakness, the fourth discipline? Great, that would give them 509607936. But even better would be to work on the second or fifth skill, then they could achieve 644972544! So this is the **task: name the number of the skill that needs to be improved by 1 to achieve the highest score!** **Input:** a list of five positive integers **Output:** the index of the number to be increased for the maximum product (write in the answer whether the index is 0-based or 1-based). If more than one share the same result, name only one of them, no matter which. The shortest code wins! **Test data** (index 1-based) ``` 3, 2, 4, 1, 2 --> 2 7, 19, 12, 20, 14 --> 4 13, 12, 19, 9, 20 --> 1 13, 18, 12, 12, 14 --> 5 18, 19, 18, 16, 13 --> 2 14, 14, 19, 17, 11 --> 3 ``` [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 14 bytes [SBCS](https://github.com/abrudz/SBCS) ``` ⊃∘⍒(1+÷)*1+⍋∘⍋ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9TV/KhjxqPeSRqG2oe3a2oZaj/q7QaLdAMA&f=LYzbCQAxDMP@bwqNcE5DHwt1/xHqhkIwSHGyaQSJiG8z0EJB/CjNapfsltXjWSpfYdaFs3t5RdbY@ZcO&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f) ``` ⍋∘⍋ relative ranking 1+ exponents 1+÷ 1+1/n = (n+1)/n * power ⊃∘⍒ max index ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes ``` ‘÷*ỤỤ‘ƊM ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw4zD27Ue7l4CRED2sS7f/w937rN@1DBHQddO4VHDXOvD7VwPd8x/1Ljt4e4tYYfbHzWtifz/X0lJyVhHwUhHwURHwRDI4DIH0pZADBQyMgDSJlyGxhAuSNgSJAoRsYCKGkEUWUD1gWgzIDbmMgQZaQIVBhlrCLQMAA "Jelly – Try It Online") A monadic link taking a list of five integers and returning the index of the skill to improve (wrapped in a length 1 list). Run as a full program, will print the integer without any list braces. ## Explanation ``` ‘ | Increment by 1 ÷ | Divide by original list * Ɗ | To the power of: ỤỤ‘ | - The result of finding the indices needed to sort the list, repeating that process and then incrementing by 1 M | Indices of maximum ``` This should work even where there are ties either in the original list or created by increasing one of the skills. I’ve subsequently realised this uses the same method as the existing [APL answer](https://codegolf.stackexchange.com/a/267102/42248), so be sure to upvote that one! [Answer] # [Python](https://www.python.org), 69 bytes ``` lambda s:s.index(max(s,key=lambda t:(~t/-t)**sum(map(t.__ge__,s),1))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=Lc7BbsMgDADQO19h9QSVyUqSrU2k7LbLvmFSlKlkQ00AFTq1l33GLrtUmrZ_6t8MAkgWlh-2-f6zF_9u9PVn7F5-T37ku9vTNMyv-wFc6wql9_JM5-FMHR7kpcvkW_rp77hn67U7zcEt9UXfv8m-R8dQMMbysOfRHGFSWoLSYKzUdMNaAgoNdBD75McwYXxQODspT1ecP64YI2CPSnuqcKSKoeEiT7zeviqEEqFGECGB5YQmKMk2lJoQQctNuOsENRFVqkZtIiYQCXYZy6Ulwj1Zik3GhxBV3iHi3jpjXCgWqEj63j8) 0-based. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` āΣIāyQ+{ā>mP}θ ``` 1-based. [Try it online](https://tio.run/##yy9OTMpM/f//SOO5xZ5HGisDtauPNNrlBtSe2/H/f7SxjpGOiY6hjlEsAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf@PNJ5bfGjdkcbKQO3qI412uQG153b81/kfHW2sY6RjomOoYxSrE22uY2ipY2ikY2SgY2gC5Bsag3hAMUugEJRvARYygiqwAOsAkmY6hsYgAaBRJmAxoFmGsbEA). **Explanation:** ``` ā # Push a list in the range [1, input-length] Σ # Sort it by: I # Push the input-list again ā # Push a list in the range [1, input-length] again y # Push the current item we're sorting on Q # Equals check, so we have a list of 0s with a 1 at the current item + # Add the two lists together, so the current position is increased by 1 { # Now sort this updated input-list ā # Push a list in the range [1, input-length] once again > # Increase it by 1 m # Take the items in the sorted updated list to the power these values P # Take the product of that }θ # After the sort-by: pop and push the last item # (so `Σ...}θ` basically translates to a maximum-by builtin) # (which is output implicitly as result) ``` [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 11 bytes ``` ∥ϩėꜝ↑↑2+*ƓḞ ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLiiKXPqcSX6pyd4oaR4oaRMisqxpPhuJ4iLCIiLCJbMTQsIDE0LCAxOSwgMTcsIDExXSAiLCIzLjEuMCJd) Port of l'apl ## Explained ``` ∥ϩėꜝ↑↑2+*ƓḞ­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌­ ∥ # ‎⁡Apply both of these to the input: ϩėꜝ # ‎⁢ Reciprocals of each, incremented ↑↑ # ‎⁣ Grade up, twice 2+ # ‎⁤Increment the result of ^ by 2 * # ‎⁢⁡Power of reciprocals to ^ ƓḞ # ‎⁢⁢Find the maximum index by finding the maximum without popping and finding its position 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [R](https://www.r-project.org), 35 bytes ``` \(x,`-`=order)(-(1+1/x)^(--x+1))[5] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZBRasMwDIbZa04hPAo2tbc5SbvmIb3EHpOMmsZZC6E1sQdZ2U32kg12qO00k-3AqEHI_J9-Sejjc5i-uvL71XVi83Nb05HvxK48D60eGBVULuX9yJ6pEONSMlatmlj6e_Nk3WBNf3SUZBxSDjkHiR8IT4gtpMkjSgUG0vQBcx5Bnsgsqp4WHkYgI9jMMA0WD1ZJEIsZrjGyeYb0c_MZ-oEygIxwUp8IqyrZNPC-hf91AycsiMqY_o0etGrRya7r-HWRsnfHk9MveBivRhFXrOmFWTMg6yhZWMDmixbNRlmn6YXD_tz3ylgNJeBSjEOHDhaa7JWjVhtP_LLxttMU8x8) An anonymous function taking an integer vector and returning an integer. Uses the same method as [my Jelly answer](https://codegolf.stackexchange.com/a/267135/42248) (and therefore some other answers including [@att’s APL one](https://codegolf.stackexchange.com/a/267102/42248)). [Answer] # [Uiua](https://uiua.org), 13 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` ⊢⍖ⁿ+2⍏⍏:+1÷,1 ``` [Try it!](https://uiua.org/pad?src=0_3_1__ZiDihpAg4oqi4o2W4oG_KzLijY_ijY86KzHDtywxCgpmIFszIDIgNCAxIDJdCmYgWzcgMTkgMTIgMjAgMTRdCmYgWzEzIDEyIDE5IDkgMjBdCmYgWzEzIDE4IDEyIDEyIDE0XQpmIFsxOCAxOSAxOCAxNiAxM10KZiBbMTQgMTQgMTkgMTcgMTFdCg==) 0-indexed. Port of lyxal's [Vyxal 3 answer](https://codegolf.stackexchange.com/a/267101/97916). ``` ⊢⍖ⁿ+2⍏⍏:+1÷,1 1 # push 1 , # copy the input to top of stack ÷ # divide (reciprocals) +1 # increment : # flip (bring second copy of input to top) ⍏⍏ # rise (grade up) twice +2 # add two to each ⁿ # power ⊢⍖ # index of maximum ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 12 bytes ``` çᵚᶠ≥Mŗ→ᵐ∏x$Ṃ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FnsOL3-4ddbDbQsedS71PTr9Udukh1snPOror1B5uLNpSXFScjFU4YKbcdHGOkY6JjqGOkaxXNHmOoaWOoZGOkYGOoYmQL6hMYgHFLMECkH5FmAhI6gCC7AOIGmmY2gMEgAaZQIWA5plGAuxBgA) Based on [@att's APL answer](https://codegolf.stackexchange.com/a/267102/9288), with some hacks because Nekomata doesn't have built-ins for ranking, grade-up, or sort-by. ``` çᵚᶠ≥Mŗ→ᵐ∏x$Ṃ Takes [3,2,4,1,2] as an example ç Prepend 0 -> [0,3,2,4,1,2] ᵚ For each element of the original list: ᶠ≥ Filter the list by <= that element -> [[0,3,2,1,2],[0,2,1,2],[0,3,2,4,1,2],[0,1],[0,2,1,2]] M Element-wise max with the original list -> [[3,3,3,3,3],[2,2,2,2],[4,4,4,4,4,4],[1,1],[2,2,2,2]] ŗ→ 1 + 1 / that -> [[4/3,4/3,4/3,4/3,4/3],[3/2,3/2,3/2,3/2],[5/4,5/4,5/4,5/4,5/4,5/4],[2,2],[3/2,3/2,3/2,3/2]] ᵐ∏ Product of each -> [1024/243,81/16,15625/4096,4,81/16] x$Ṃ 0-based index of the maximum -> 1 or 4 ``` This returns all possible results. If you want only one result, you can add the `-1` flag. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 67 bytes ``` x=>x.map((t,i)=>[(t/++t)**x.filter(v=>v<t).push(0),i]).sort()[0][1] ``` [Try it online!](https://tio.run/##Lc/RboMgFAbge56COw8FUdStNRvuQYxLicXOhRaj1Pj2FtSTnED@L@QP/2pWUzv2g4uf9qbXTq6LrBb@UAOAYz2RVQ0uodSR02nhXW@cHmGW1fztCB9e0x@khPUN4ZMdHZA6bWrRrF/oinKGM4YLhoW/4G3iuMIZOvuo9Os1S/1Z7FAgke9p0DLgDmKHy4HZ9iTAB9rC8sBPv/nRIUJvcWAoFBvk6MpHPRjVakh@OYUf6WOSPO7Mf7u1z8kazY29Qwd6VgaiOqILjZqI@Fnf "JavaScript (Node.js) – Try It Online") 0-index [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` I⊟⌈Eθ⟦X∕⊕ιι⊕№÷θ⊕ι⁰κ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyC/QMM3sSIztzQXSBdoFOooRAfkl6cWabhklmWmpGp45iUXpeam5pWkpmhkauoogDCymHN@KdAsz7wSqPpCVOlMTaB6A00QmR2rCQLW//9HRxvrKBjpKJjoKBgCGbGx/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Explanation: Port of @l4m2's JavaScript answer. ``` θ Input list E Map over elements ι Current element ⊕ Incremented ∕ Divided by ι Current element X Raised to power № Count of ⁰ Literal integer `0` in θ Input list ÷ Integer divided by ι Current element ⊕ Incremented ⊕ Incremented κ Current index ⟦ Make into list ⌈ Take the maximum ⊟ Get just the index I Cast to string Implicitly print ``` [Answer] # [Desmos](https://desmos.com/calculator), 49 bytes ``` f(l)=[(1+1/i)^{6-l[l>i].\count}\for i=l].\argmax ``` Port of [Albert.Lang](https://codegolf.stackexchange.com/users/101374/albert-lang)'s [Python answer](https://codegolf.stackexchange.com/a/267103/96039), so make sure to upvote that answer too! [Try It On Desmos!](https://www.desmos.com/calculator/kxy4izf4cp) This uses a so-called fragile function `argmax` which means that the expression containing the function (which looks empty because it doesn't render properly) will break if basically any key is pressed when you are focused on that expression. Also, because `argmax` isn't an "official" function, I don't have a prettified version of the code as simply typing `argmax` into the calculator won't yield a valid function. For reference, this is the shortest answer I could come up with without the usage of the `argmax` fragile function (54 bytes): ``` f(l)=sort([1...5],[(1+1/i)^{6-l[l>i].count}fori=l])[5] ``` [Answer] # G[AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 104 101 bytes ``` {for(i=m=1;i<6;i++){++$i;split($0,_);asort(_,a);for(k=t=1;k<6;)if((t*=a[k]^++k)>m){m=t;n=i}--$i}}$0=n ``` [Try it online!](https://tio.run/##HYxBCoMwEEX3nmIWWSSNghOlVdLpRUor2QhDqhYNdCGePY3ZfOa/eXz38zHu47JKponQ8v1qWWu1ay3Ybt8PBynqclDWbcsa5FA6ZU/dU0i6T7riUcpwIff0r7fWXj0mtU8U7Ex8VJXg4xA1zTE2YKAFBFPcAHtAA6YGbAtszjuRPoHcugxMfnbZTXkFbApMA20maQP/ "AWK – Try It Online") * -3 bytes, forgot about default value of fieldsep for `split()` function. It's index 1-based. [Answer] # [Haskell](https://www.haskell.org), 111 bytes ``` import Data.List f y=snd$maximum[(product$zipWith(^)(sort$t++(x+1):d)[2..],i)|i<-[0..4],(t,x:d)<-[splitAt i y]] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZG9asMwEIB3P8UNHiQsm8hW27jEQ6Fj9w5CBZPYRNR_WGdwSt6kS5bSZ-rDFHpq3JQIDp30fScd0vvnvnSvVdOcTh8T1vH6q7ft0I8IjyWWyZN1GNRwKFy3C9tytu3UajaM_W7aYvhmh2eLe_bCmaOSEKOIzZHk9zuu0yQxwvKj3cR6lSTKCIZiJkJrNzQWHxAsHIxZrv1uS9tBAcNoO4QQdE24KKCHGCQcgVkBPYdNDFg53JauciYILjlV6gBoMJ0JSAUoAZISvwVGwA0XC74jkFOQk65oVh6rC5bZmXkn94rH8hqvF8WHujr8F-WLckuREU7_se9KLYpvRBLOuAnOj_D3Bz8) [Answer] # Python 3 (197 bytes) ``` e=enumerate x=lambda s:max((((lambda s:(f:=lambda n:n[0]if len(n)==1 else n[0]*f(n[1:]))([j**i for i,j in e(sorted(s),2)]))(j[:i]+[j[i]+1]+j[i+1:]),i)for i,j in e([s]*len(s))),key=lambda i:i[0])[1] ``` [Try it online](https://ato.pxeger.com/run?1=XZFRbsMgDIbfewo_QsKkQKItRcpJEA-ZajSyhFQhldKz7KUv20m2Q-w2w2qydUUyBvsz_i3ePo7n-WUMl8v7aXYP9fcXNhhOA07tjLul6dvh-dBC1EO7sLR-78zpLRl0MIX1DnoMLPCmkYB9RKBo5lgwUlvOmemyzIMbJ_CiAx8AWRynGQ8scqE4IZ3R3uamM2mXNk8-p1rh-b8yE21GvSLnXLzieRPitU8tuZF2HeazjRGnGRZmSgFKQCVApoMlkbu_5FMK75MlQhXJVwSUN4Asr1mi9gQRUNwD9Qqp7YnqlqjXJuQfk5X3KiSpq1aKJEki1HWW7YN-AA) [Answer] # [Scala](https://tio.run/##bZFBTxsxEIXv/Ip3tJXFym5CC6umEpU4IIE4oIoDqpCbdRJXZndlT2i2KL89jB0DStSD17PPn55nnsNcO73bdb//mDnhVtsWrydAYxZ45h@h/TLUuPReD4/35G27/CVr/GwtYZZI4EU7kAk018EEVm9sIJFOAJF@JgWqAtMCJRdJlwV/KlkcYF8ZuODFbDXmfRqx6RFUTvZEJC8iGKHyf9B5BuNiF5wdQ@f5vrh/4TVh6LinMnY9zWBskK/CRMqTj9G9CWtHcfCPENSz7vGKWEPYAp3E7DsWwvI@Q4dTlNjuHXqOlFwrsotkMZ3EB1iIoU5pPl63FGPn7SD1z6sXnc86YPHtFGOsW7IOZ1kMvUtPNqhUXRI38z4oFWi4M4h0pJ74lXJVqZXRzV1PtmvV0tCdv3LBiLHEiEeo60@OtHXvhqHzZJpoSBiN2FvtlXzc@65Zz2Mze1n9s/2DpdV125jNQXQvBWyzSeHdalqpvvubNb6/ktiq7JWctxiscQ1EFhnMz5RzYu/Nj0E88YSSe05Rb3e7Nw), 171 bytes A port of [@matteo\_c's Haskell answer](https://codegolf.stackexchange.com/a/267173/110802) in Scala. --- Golfed version. [Try it online!](https://tio.run/##bZFLawIxEMfvfoo5JpgG99FWV1aw0IPQ4qGUHkQkdaNGsg82o9WKn91O1qVQ6WF2Hvkx/5lZt1RWXcrPrV4ivCpTwKkDkOkV5JQwVa9dAuO6VsfZG9amWM95Au@FQUgbEmCvLKB2uFROO6q@GIeseQFgTRIJCAXEAgIKmjoX9Am5@IM9EjAgIzbskY89Ft9AQXQlPDnwoIeC/6B@C3qjLnB/C/VbPe8fyCKCbmcK/NRxC/oBSQoizju/q9fa7Sz6xX@PIHNVwQl8DMwIKDmkI1gxQz6FEu4ggPO1Q0UnRVuwtgunYvPiO6@S6xCzSYFzno7IkcrlmI5YD7Ck03ihk0lHRDMnLE@P0lXW4BhJa9j8mNR1u4xZudEqm1ZoykKuNU7rZ@s06/FuwJPESlTG8iFD6coadSa/TfVhcDMpMn1oRPwubC@2NEaucCOr8sun3ZCfZVWX2W6JwlCcq8PTkS3kIuByEV7Olx8) ``` y=>(0 to 4).map{i=>val(s,l)=y.splitAt(i);val t=s++((l.headOption.getOrElse(0)+1)::l.tail);(t.sorted.zipWithIndex.map{case(v,j)=>math.pow(v,j+2)}.product,i)}.maxBy(_._1)._2 ``` Ungolfed version. [Try it online!](https://tio.run/##bZFBTxsxEIXv/Ip3tJXFym5CC6umEpU4IIE4oIoDqpCbdRJXZndlT2i2KL89jB0DStSD17PPn55nnsNcO73bdb//mDnhVtsWrydAYxZ45h@h/TLUuPReD4/35G27/CVr/GwtYZZI4EU7kAk018EEVm9sIJFOAJF@JgWqAtMCJRdJlwV/KlkcYF8ZuODFbDXmfRqx6RFUTvZEJC8iGKHyf9B5BuNiF5wdQ@f5vrh/4TVh6LinMnY9zWBskK/CRMqTj9G9CWtHcfCPENSz7vGKWEPYAp3E7DsWwvI@Q4dTlNjuHXqOlFwrsotkMZ3EB1iIoU5pPl63FGPn7SD1z6sXnc86YPHtFGOsW7IOZ1kMvUtPNqhUXRI38z4oFWi4M4h0pJ74lXJVqZXRzV1PtmvV0tCdv3LBiLHEiEeo60@OtHXvhqHzZJpoSBiN2FvtlXzc@65Zz2Mze1n9s/2DpdV125jNQXQvBWyzSeHdalqpvvubNb6/ktiq7JWctxiscQ1EFhnMz5RzYu/Nj0E88YSSe05Rb3e7Nw) ``` object Main { def main(args: Array[String]): Unit = { val testcases = List( (List(3, 2, 4, 1, 2 ), 2), (List(7, 19, 12, 20, 14 ), 4), (List(13, 12, 19, 9, 20 ), 1), (List(13, 18, 12, 12, 14), 5), (List(18, 19, 18, 16, 13), 2), (List(14, 14, 19, 17, 11), 3)) val results = testcases.map { case (i, o) => f(i) == o - 1 } println(results) } def f(y: List[Int]): Int = { val results = for { i <- 0 until 5 split = y.splitAt(i) (t, d) = (split._1, split._2.headOption.getOrElse(0) + 1 :: split._2.tail) sorted = (t ++ d).sorted product = sorted.zipWithIndex.map { case (v, idx) => Math.pow(v, idx + 2) }.product } yield (product, i) results.maxBy(_._1)._2 } } ``` [Answer] # Excel (ms365), 89 bytes [![enter image description here](https://i.stack.imgur.com/t2sjH.png)](https://i.stack.imgur.com/t2sjH.png) Formula in `G1`: ``` =LET(x,BYROW(A1:E1+MUNIT(5),LAMBDA(y,PRODUCT(SORT(y,,,1)^{2,3,4,5,6}))),XMATCH(MAX(x),x)) ``` ]
[Question] [ Write a program that will output its own source code when run, and nothing else. Seems easy, right? The catch is that when the source code is reversed, your program must output "Hello, World!" exactly, without the quotes. This is code-golf, so lowest byte count wins. **Edit**: Your quine must be a proper quine. [Answer] # JavaScript (ES6), ~~42~~ 38 bytes ``` f=_=>/\//g&&"f="+f||"!dlroW ,olleH">=_ ``` ## Reversed ``` _=>"Hello, World!"||f+"=f"&&g//\/>=_=f ``` ## Explanation When reversed, it becomes an anonymous function that returns the string `Hello, World!`. The regex `/\//g` becomes a comment when it is reversed, which allows the syntactically invalid `>=_=f` to be commented out in the reversed code. [Answer] # Y, 19 bytes ``` Upxp"!dlroW ,olleH" ``` `U` captures a string with `U` at the beginning until the next `U` is met, in this case, the source code. `p` prints the item, and `x` is a termination link. When reversed, this looks like: ``` "Hello, World!"pxpU ``` This captures the string and prints it with `p`, again terminating the program with `x`. [Try it here!](http://conorobrien-foxx.github.io/Y/) [Answer] # JavaScript (ES6), 71 bytes ``` trela=a=>alert("trela="+trela+"\ntrela\n``")// `!dlroW ,olleH` trela `` ``` ### How it Works: Line 1 defines function `trela` that when run outputs the program's source code. Line 2 is an unassigned string, does nothing. Lines 3 and 4 call `trela` abusing the template string syntax. ## Reversed: ``` `` alert `Hello, World!` //)"``n\alertn\"+alert+"=alert"(trela>=a=alert ``` ### How it Works: Line 1 is an unassigned string, does nothing. Lines 2 and 3 abuse the template string syntax to print `Hello, World!`. Line 4 is a comment. [Answer] # GolfScript, 33 bytes ### Forwards ``` {`".;1$~]"}"!dlroW ,olleH".;1$~] ``` [Try it online!](http://golfscript.tryitonline.net/#code=e2AiLjsxJH5dIn0iIWRscm9XICxvbGxlSCIuOzEkfl0K&input=) ### Backwards ``` ]~$1;."Hello, World!"}"]~$1;."`{ ``` [Try it online!](http://golfscript.tryitonline.net/#code=Cl1-JDE7LiJIZWxsbywgV29ybGQhIn0iXX4kMTsuImB7&input=) [Answer] # GolfScript, ~~29~~ 28 bytes ``` "`'.~]'#\"!dlroW ,olleH".~] ``` It has one trailing newline. [Try it here.](http://golfscript.tryitonline.net/#code=ImAnLn5dJyNcIiFkbHJvVyAsb2xsZUgiLn5dCg&input=) Reversed: ``` ]~."Hello, World!"\#']~.'`" ``` [Try it here.](http://golfscript.tryitonline.net/#code=Cl1-LiJIZWxsbywgV29ybGQhIlwjJ11-LidgIg&input=) [Answer] # [RETURN](https://github.com/molarmanful/RETURN), 94 bytes ``` "34¤¤,,,,,,,,,,,,,% 'H'e'l'l'o',' 'w'o'r'l'd'!'"34¤¤,,,,,,,,,,,,,% 'H'e'l'l'o',' 'w'o'r'l'd'!' ``` Reversed: ``` '!'d'l'r'o'w' ','o'l'l'e'H' %,,,,,,,,,,,,,¤¤43"'!'d'l'r'o'w' ','o'l'l'e'H' %,,,,,,,,,,,,,¤¤43" ``` `[Try it here.](http://molarmanful.github.io/RETURN/)` Outputs to STDOUT. Until I find a better quine framework, this will have to do for now. # Explanation ``` "34¤¤,,,,,,,,,,,,,% 'H'e'l'l'o',' 'w'o'r'l'd'!'" ``` This contains the quine string. In reverse, this is pushed to the stack but not outputted. ``` 34¤¤,,,,,,,,,,,,, ``` This pushes a quote char to the stack and outputs the result twice until there is nothing left to output. In reverse, this will print the charcodes already on the stack. ``` % 'H'e'l'l'o',' 'w'o'r'l'd'!' ``` This one pops the top stack item (in reverse, this would pop a space char) and pushes a series of charcodes to the stack (in reverse, these charcodes would later be printed by the series of `,`'s). [Answer] # Fission 2, 42 bytes Shameless adaptation of a excellent quine by @MartinBüttner in this [answer](https://codegolf.stackexchange.com/a/50968/31347) ``` '!+O!'!d'!l'!r'!o'!W'! '!,'!o'!!l'!e'!H'R" ``` [Try it online](http://fission2.tryitonline.net/#code=JyErTyEnIWQnIWwnIXInIW8nIVcnISAnISwnIW8nISFsJyFlJyFIJ1Ii&input=) And reversed ``` "R'H!'e!'l!!'o!',!' !'W!'o!'r!'l!'d!'!O+!' ``` [Try it online](http://fission2.tryitonline.net/#code=IlInSCEnZSEnbCEhJ28hJywhJyAhJ1chJ28hJ3IhJ2whJ2QhJyFPKyEn&input=) In the quine version the atom starts at the `R` heading right. The `"`starts print mode which wraps to the next `"` (itself). This prints everything out except the `"`. `'!+` set the atom to char `"`. `O` prints it out and destroys the atom ending the program. The reversed version starts at the `R` again and for each character in `Hello, World` set the atom and prints `!` it out without destroying the atom. For the final character `!` the print `O` destroys the atom. [Answer] # Javascript ES6, 55 bytes ``` $=_=>`$=${$};$()//"!dlroW ,olleH"`;$()//"!dlroW ,olleH" ``` Quite simple, really. [Answer] # [Python 2](https://docs.python.org/2/), 60 bytes / [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 64 bytes ## Python 2: (60 bytes) * Normal : ``` a="print'a=%r;exec a#\\42'%a#'!dlroW ,olleH'tnirp;";exec a#" ``` * Reversed: ``` "#a cexe;";print'Hello, World!'#a%'24\\#a cexe;r%=a'tnirp"=a ``` [Try it online!](https://tio.run/##K6gsycjPM/qfnJ@SalukpKT0P9FWqaAoM69EPdFWtcg6tSI1WSFROSbGxEhdNVFZXTElpyg/XEEnPycn1UO9JC@zqMBaCaZK6T/QAC4QRwNkniaCGW1lpWsYq/kfAA "Python 2 – Try It Online") ## Python 3: (64 bytes) * Normal: ``` exec(a:="print('exec(a:=%r)#\\42'%a)#)'!dlroW ,olleH'(tnirp;")#" ``` * Reversed: ``` "#)";print('Hello, World!')#)a%'24\\#)r%=:a(cexe'(tnirp"=:a(cexe ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPqfnJ@SalukpKT0P7UiNVkj0cpWqaAoM69EQx3GVy3SVI6JMTFSV03UVNZUV0zJKcoPV9DJz8lJ9VDXKMnLLCqwVtJUVvoPNIQLrAlkpiaCGW1lpWsYq/kfAA "Python 3.8 (pre-release) – Try It Online") ## Explanation : * I used a modification of the quine `a="print'a=%r;exec a'%a";exec a` adding some comments `#` to isolate the "hello world" part. * I also used `\\42` to get the char `"` without breaking my strings or having some slashes `\` at the printing # * Thanks to the previous comments and a few well placed quotes, the reversed program is very straight forward [Answer] # Python 2, 131 bytes ### Forward: ``` print(lambda x:x+repr(x)+")#'!dlroW ,olleH' tnirp")('print(lambda x:x+repr(x)+")#\'!dlroW ,olleH\' tnirp")(')#'!dlroW ,olleH' tnirp ``` ### Reverse: ``` print 'Hello, World!'#)'()"print '\Hello, World!'\#)"+)x(rper+x:x adbmal(tnirp'()"print 'Hello, World!'#)"+)x(rper+x:x adbmal(tnirp ``` The first half is a one-line quine, followed by a `#` to form a comment separating the first half from the simpler second half. [Answer] # C, 108 bytes ``` char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";main(){printf(s,34,s,34);}//};)"!dlroW ,olleH"(stup{)(niam ``` [Answer] # Python 2, 70 bytes ``` _='_=%r;print _%%_#"dlroW ,olleH"tnirp';print _%_#"!dlroW ,olleH"tnirp ``` [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), 25 bytes ``` "r00g>o<o>'Hello, World!' ``` [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiXCJyMDBnPm88bz4nSGVsbG8sIFdvcmxkISciLCJpbnB1dCI6IiIsInN0YWNrIjoiMyIsInN0YWNrX2Zvcm1hdCI6Im51bWJlcnMiLCJpbnB1dF9mb3JtYXQiOiJjaGFycyJ9) ## Reversed ``` '!dlroW ,olleH'>o<o>g00r" ``` [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiJ2Rscm9XIG9sbGVIJz5vPG8+ZzAwclwiIiwiaW5wdXQiOiIiLCJzdGFjayI6IjMiLCJzdGFja19mb3JtYXQiOiJudW1iZXJzIiwiaW5wdXRfZm9ybWF0IjoiY2hhcnMifQ==) ]
[Question] [ ## Introduction Remember the roaring 80's? I mean, you know, like 30 years ago? No cell phones, no internet, no ATM's, fluorescent clothing (what was that?!) and **scrolling marqee's**! No, no, no! Not the online ones, but real ones, With LED lights. [![Scrolling marquee](https://i.stack.imgur.com/yISwz.gif)](https://i.stack.imgur.com/yISwz.gif) Since I'm in a nostalgic mood, I'd like you to create a scrolling marquee. ## Challenge Create a program where you can enter a one line string. You program needs to create a 80 character wide scrolling marquee, repeating the text if necessary. ## Rules * The user must be able to enter a string to your program as input. The string can be a command line parameter or a string entered while running the program. * Your program must continuously print a string of exactly 80 (visible) characters. * The string must be updated every 0.1 second (more or less; I won't be timing it), shifting the characters every iteration one position to the left. * The string "rotates". At the end of the user supplied string, another instance of the string must appear. * You program must print it's output on one line, without linefeeds (use a '\r' instead of a '\n') * Your program must run *ad infinitum*, until an user interrupt. * This is a codegolf, so shortest code in bytes wins. * There is a 10% bonus (rounded **up** to the next integer) for printing in red on a black background. * Standard loopholes apply. ## Reference implementation in Python 2.7 This program isn't golfed, but it provides a reference implementation (and thus an upper limit to the size). ``` import time,sys s=raw_input()*99 while 1: for i in range(80): print s[i:i+80]+'\r', sys.stdout.flush() time.sleep(0.1) ``` [Answer] ## PowerShell, 118 113 112 108 102 101 99 96 - 10% = 86 ### Code ``` $s=(Read-Host)*180;for(){Write-Host($s.substring(($i=++$i%80),80)+"`r")-N -F R -B 0;sleep -m 99} ``` With the caveat that it now begins the first loop with the second character; The rules don't say it has to start from the front of the string, and the first one is included overall, so that's fine by me. I will get it to 100 chars somehow - edit: thanks @ConnorLSW for the edits to get it below 100. ### Instructions 1. Run PowerShell (normal console, it doesn't work in PowerShell ISE) 2. Paste the single line version into PoSH, press enter 3. Type a message, press enter 4. Ctrl-C to break ### Output > > [![PowerShell marquee example output](https://i.stack.imgur.com/lRkJX.gif)](https://i.stack.imgur.com/lRkJX.gif) > > > ### Notes A more readable version with the variable names and parameters filled out a bit: ``` $test = (Read-Host) * 180 for () { Write-Host ($text.substring(($i=++$i%80), 80)+"`r") -NoNewLine -ForegroundColor Red -BackgroundColor Black sleep -Miliseconds 99 } ``` * The parameters only need to be long enough to be unique, so `-F R` is unique enough to set a Red ForegroundColor, for example. * 'Black' has to be 'Bla' to be unique compared to 'Blue', but `-B 0` sets it to color Enum value 0 which is interpreted as Black. ### Alternative, more 'correct' marquee: The reference code doesn't handle strings longer than 80 characters nicely, skipping anything in the message past ~160 characters, and it glitch-resets every 99\*len(string) characters. e.g. if the sign width was 5 characters long, it does this: ``` here is my long test input 0 |here | 1 |ere i| ^^^^ never shown 2 |re is| 3 |e is | 4 | is m| 0 |here | 1 |ere i| ... ``` This version indexes modulo the text length instead of the sign width, so it runs through the whole string. 106 - 10% = 95 chars. ``` $l=($s=Read-Host).Length;for(){Write-Host(($s*160).substring(($i=++$i%$l),80)+"`r")-N -F R -B 0;sleep -m 99} ``` ### Alternative: sign which cycles like the .gif in the question, 118-10%=106 Because it looks better. ``` $s=' '*80+(read-host)+' '*80;for(){write-host($s.Substring(($i=++$i%($s.length-80)),80)+"`r")-N -F R -B 0;sleep -m 99} ``` [![Alternative sign example animation](https://i.stack.imgur.com/H3vXK.gif)](https://i.stack.imgur.com/H3vXK.gif) [Answer] # Matlab, 76 bytes What I think is nice here is that you can have vectors as array indices. This returns a vector of the corresponding array entries, which makes it very easy to append the given string independently of the length. ``` a=input('');k=1:80;while 1;pause(.1);clc;k=mod(k+1,nnz(a));disp(a(k+1));end ``` Result: > > [![enter image description here](https://i.stack.imgur.com/5Mvay.gif)](https://i.stack.imgur.com/5Mvay.gif) > > > [Answer] # CJam, 31 bytes ``` l80*{Dco_80<o(+es99+{es1$<}g;}h ``` Waits for exactly 100 ms. This will only work with the official [Java interpreter](https://sourceforge.net/p/cjam/wiki/Home/), since the online interpreter only shows output after exiting the program. Red text on black background is possible in 40 (or 39) bytes, for a score of 36: ``` 0000000: 6c 38 30 2a 7b 22 0d 1b 5b 33 31 3b 34 30 6d 22 6f 5f l80*{"..[31;40m"o_ 0000012: 38 30 3c 6f 28 2b 65 73 39 39 2b 7b 65 73 31 24 3c 7d 80<o(+es99+{es1$<} 0000024: 67 3b 7d 68 g;}h ``` ### How it works ``` l80* Read a line and repeat it 80 times. { }h Do: Dco Print the character with code point 13. _80<o Print the first 80 characters of the string. (+ Rotate the string one charcter to the left. es99+ Push the current time (ms) plus 99. { }g Do: es1$< Compare the current time with the sum. Repeat the loop if 99 or less ms have passed. ; Discard the time stamp. Repeat the loop. ``` [Answer] # QBasic, ~~116~~ 113 bytes - 10% = ~~105~~ 102 ``` INPUT s$ COLOR 4 1CLS FOR i=a TO a+79 ?MID$(s$,i MOD LEN(s$)+1,1); NEXT ? a=a+1 t=TIMER+.1 2ON(TIMER<t)+2GOTO 2,1 ``` [![Marquee demonstration](https://i.stack.imgur.com/kjVUU.gif)](https://i.stack.imgur.com/kjVUU.gif) Here's a formatted version with some comments: ``` INPUT s$ COLOR 4 ' 4 is the color code for red (the background's already black) 1 CLS ' CLear Screen (and mark this as line number 1) ' The variable a represents an offset from the beginning of the string ' As a numeric variable, it is 0 at the beginning of the program FOR i = a TO a + 79 ' Print i'th character mod string length (+ 1 because QBasic strings ' are 1-indexed) PRINT MID$(s$, i MOD LEN(s$) + 1, 1); NEXT i PRINT a = a + 1 ' Do a busy-wait for .1 seconds ' (Unfortunately, QBasic's SLEEP command only takes integer values) ' Set t to the time we want to stop waiting, .1 seconds in the future t = TIMER + .1 ' We want to stay on line number 2 while TIMER < t; once that condition is ' no longer true, we want to goto the top of the outer loop (line number 1) ' Since true is -1 and false is 0 in QBasic, adding 2 to the conditional ' gives 1 for true and 2 for false; we can pass these values to the ' ON ... GOTO statement to branch conditionally 2 ON (TIMER < t) + 2 GOTO 2, 1 ``` A couple of notes: * I don't know why the `PRINT` after the `FOR` loop is necessary. `CLS` should reset the cursor to the top left corner each time. But on QB64, at least, if I don't put the extra `PRINT` in, the marquee ends up on the second line instead of the first. If anybody has QBasic set up on DosBox or somesuch, I'd be interested to know if the same thing happens there or if it's a QB64 bug. * The code has a small glitch because it relies on `TIMER` (number of seconds since midnight) for the delay. If the code is running at midnight, the marquee will get stuck because `TIMER` will reset to `0` and always be less than `t` thereafter. [Answer] ## Perl, 99 98 bytes (-10% = 89) ``` $|=@_=split('',pop);printf("\e[31m\r%.80s",join('',@_)x80)while select($a,$a,$a,.1)|push@_,shift@_ ``` Takes its input from command line parameter. ``` perl marquee.pl "Welcome to Programming Puzzles & Code Golf " ``` [Answer] # [pb](https://esolangs.org/wiki/Pb), ⌈(216 + 3)\*0.9⌉ = 198 +3 bytes for interpreter flag `d=1` ``` c^w[Y=-1]{w[B!0]{>}t[X]<[X-79]w[X!0]{t[T-1]w[T=-1]{t[0]}<}vw[T=0]{^w[B!0]{t[B]^b[T]>v}<[X]^w[B!0]{t[B]vw[B!0]{>}b[T]<[X]^w[B=0]{>}b[0]>}v}}^w[1=1]{<[X-80]w[X!0]{<t[B]vb[T]^}w[B!0]{t[B]<b[T]>>}<[X]<t[B]w[B!0]{>}<b[T]} ``` A pretty horrible score, but considering how hard it is to do anything in this language it could be worse. This answer's ratio of (bytes used to get red text) to (bonus from having red text) is really good, the whole output is turned red with only the `c` at the beginning! The time between each tick varies depending on the length of the input string but it's around 0.1 seconds. By the way, this program's output looks like total garbage because the interpreter is so bad. Every millisecond it clears the terminal and redraws everything, so it gets really flickery. With comments: ``` c # Change paint colour to red ^w[Y=-1]{ # While Y=-1 (arbitrary condition we can break later) w[B!0]{>} # Go to end of input t[X] # Save length of input in T # SET T TO MAX(T-79, 0) <[X-79] # Go to (79, -1) w[X!0]{ # While X is not 0 t[T-1] # Subtract 1 from T w[T=-1]{ # If T is now negative t[0] # Set it back to 0 } < # Move left (position doesn't matter except to end the loop eventually) } # DONE SETTING T TO MAX(T-79, 0) # If T == 0, the string needs to be doubled. Otherwise this part of the program is done v # Move down to break the loop unless this is specifically undone w[T=0]{ # While T == 0 ^w[B!0]{ # For each byte of input t[B]^b[T] # Copy it up 1 place >v # Go to the next byte } <[X]^ # First byte of the copy w[B!0]{ # For each byte of the copy t[B] # Save the byte's value vw[B!0]{>}# Go to the first empty spot after the original b[T] # Write the saved value <[X]^w[B=0]{>} # Go back to the first byte of the copy b[0]> # Erase it and go to the next one } v # Back to Y=-1 to reset the loop from the very beginning } } # After ALL OF THAT nonsense, we're now at (0, 0) and the input string is guaranteed to be # at least 80 characters long ^ w[1=1]{ # While 1=1 (should hold true until mathematics itself breaks down) <[X-80] # Go to the 81st character w[X!0]{ # While X!=0 <t[B]vb[T]^ # Go left and copy that character down } w[B!0]{ # For each byte in the string t[B]<b[T]>> # Copy that byte left } <[X]<t[B] # Go get the first value (copied to (-1, -1)) w[B!0]{>}<b[T]# Bring it to the end of the string } ``` [Answer] ## Perl - 120 bytes (-10% = 108) ``` $|=1;$_=<>;chomp;for(;;){print "\e[31m",substr(" "x80 .$_,$p++,80)," \r";select($z,$z,$z,0.1);if($p>length()+80){$p=0}} ``` [![Perl marquee](https://i.stack.imgur.com/XqdfI.gif)](https://i.stack.imgur.com/XqdfI.gif) [Answer] # Matlab, ⌈188\*.9⌉ = 170 This works in Matlab version R2014b or higher. The result is shown on a figure window. ``` h=text(.1,.1,repmat(' ',1,80),'fontn','courier','ba','k','co','r');set(1,'pos',[90 90 990 90]);axis off s=input('','s');n=0;while 1 n=n+1;pause(.1) h.String=s(mod((0:79)+n,numel(s))+1);end ``` In the following **example**, text is typed in boldface for better visualization (not done in the above code because it costs a few bytes). Note also that the speed of the GIF animation does not correspond to the required 0.1 s pause, but the timing is correct in the actual figure shown by running the program. [![enter image description here](https://i.stack.imgur.com/jNG9G.gif)](https://i.stack.imgur.com/jNG9G.gif) [Answer] # SpecBAS, 130 bytes (-10% = 117) Multiplies the original string to make it 80 or more characters, then chops it to exactly 80. `TEXT` is a command in SpecBAS that works the same way as `PRINT` (in this example) but saves one character. The `SCALE` command adds a few extra characters to the code, but makes it look more marquee-ish. The program keeps going until you press Esc. ``` 1 INPUT s$: LET s$=s$*CEIL(80/LEN s$) 2 TEXT PAPER 0;INK 2;SCALE 1,2;AT 1,1;s$( TO 80) 3 LET s$=s$(2 TO)+s$(1): PAUSE 5: GO TO 2 ``` [![enter image description here](https://i.stack.imgur.com/b45pI.png)](https://i.stack.imgur.com/b45pI.png) [Answer] ## Perl, 63 (70 chars - 10% for bonus) Not a hugely different solution to the others, but I wasted my time making it, so I thought I'd post it as well! ``` $_=<>;s/ / /;print"\x0d\x1b[91m",substr"$_"x80,$z++%y///c,80 until`sleep .1` ``` Relies on a Unix-compatible terminal for ANSI codes and the call to coreutils' `sleep`. The two `\x..` chars in the above are actually a literal line-feed and escape char as per this hex dump: ``` 0000000: 245f 3d3c 3e3b 732f 0a2f 202f 3b70 7269 $_=<>;s/./ /;pri 0000010: 6e74 220d 1b5b 3931 6d22 2c73 7562 7374 nt"..[91m",subst 0000020: 7222 245f 2278 3830 2c24 7a2b 2b25 792f r"$_"x80,$z++%y/ 0000030: 2f2f 632c 3830 2075 6e74 696c 6073 6c65 //c,80 until`sle 0000040: 6570 202e 3160 ep .1` ``` [Answer] # Ruby, ~~79~~ ~~76~~ 75 bytes ``` t,i=gets.chop*81,0 loop{system'cls' $><<t[(i=(i+1)%80)..i+79] sleep 0.1} ``` I'm still not a ruby expert, possibly can be golfed down. With red & black same score: ``` t,i=gets.chop*81,0 loop{system'cls&color 4' $><<t[(i=(i+1)%80)..i+79] sleep 0.1} ``` [Answer] ## Perl, 84 bytes (- 10% = 76) ``` $_=' 'x80 .pop;$|=print"\b \r\e[31m".substr$_,++$p% length,80until select$z,$z,$z,.1 ``` This takes a command line argument which is the text in the marquee. Explanation: 1. Prepend 80 spaces to the text and store in `$_` 2. Print backspace (`\b`) and a space (). This removes the last character from the previous print. Then print the carriage return and colour. 3. Print the 80 characters of the text from position `$p` 4. `$p = ($p+1) % length of text` 5. Sleep for 0.1 secs [Answer] # bash, 121 bytes ``` A=$(printf ' %.s' {1..80})$1 while :; do printf "%s \r" "${A:((P++)):80}" if [ $P == ${#A} ];then P=0 fi sleep 0.1 done ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs an integer before starting into the marquee. ``` Li@Oq80îUéV´ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=TGlAT3E4MO5V6Va0&input=Ik1ha2UgbWUgYSBzY3JvbGxpbmcgbWFycXVlZS4i) But, if that's not valid then ... ## [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Oq80îUéV´ Lt@ß ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=T3E4MO5V6Va0IEx0QN8&input=Ik1ha2UgbWUgYSBzY3JvbGxpbmcgbWFycXVlZS4i) ``` Oq80îUéV´ Lt@ß :Implicit input of string U Oq :Overwrite output with 80î : Mould the following to length 80 Ué : Rotate U right this many times V : Second input variable, defaulting to 0 ´ : Postfix decerement L :100 t :Set timeout for L milliseconds to @ : Run this function ß : Recursive call with implicit arguments U & (now decremented) V ``` [Answer] # Python 3, 96 bytes ``` import time;s=input()*80 while 1:print("\033[2J",end=s[:80],flush=1);s=s[1:]+s[0];time.sleep(.1) ``` This will only work on terminals that support ANSI escape sequences. If you are on Windows, try [ansicon](https://github.com/adoxa/ansicon). Hurrah for the `flush` keyword in Python 3, so we don't have to make an expensive `sys.stdout.flush()` call. [Answer] ## C, ~~293~~ 269 bytes (Newlines added for readability) This takes input from standard input terminated by EOF; so it's best to enter a string, a newline, and then the EOF (e.g., Ctrl^D). ``` #include<stdio.h> #include<string.h> #define Z '\0' main(){int i=0,j;char m[80],o[80],n[2]; while(~(j=getchar())&&i<80)j-'\n'?m[i++]=j:0;m[i]=Z; while(1){for(i=0;m[i]-Z;++i){strcpy(o,&m[i]); for(j=0;j<i;)*n=m[j++],n[1]=Z,strcat(o,n); printf("\x1b[40;31m%s\x1b[0m\r",o);}}} ``` Ungolfed: ``` #include <stdio.h> #include <string.h> #define ANSI_COLOR_SET "\x1b[40;31m" #define ANSI_COLOR_RESET "\x1b[0m" int main(void) { int i, j, c; char msg[80], out[80], next[2]; for (i = 0; (c = getchar()) != EOF && i < 80; ++i) { if (c != '\n') { msg[i] = c; } } msg[i - 1] = '\0'; while (1) { for (i = 0; msg[i] != '\0'; ++i) { strcpy(out, &msg[i]); for (j = 0; j < i; ++j) { next[0] = msg[j]; next[1] = '\0'; strcat(out, next); } printf(ANSI_COLOR_SET "%s\r" ANSI_COLOR_RESET, out); } } return(0); } ``` [Answer] # SmileBASIC BIG, 79 bytes ``` COLOR 3INPUT S$@L CLS FOR I=0TO 79?S$[(I+O)MOD LEN(S$)]; NEXT WAIT 6O=O+1GOTO@L ``` I had a nice graphical solution almost done when I realized it has to scroll 1 whole character at a time. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ ~~19~~ 18 bytes * -1 byte by replacing the first `80` by `⁹` (= 256) because it has to be multiplied by *at least* 80 * -1 byte by changing infinite loop to `Çß` (from `Ç1¿`). --- ``` ẋ⁹ḣ80ṙ1;”ÆṄœS.1 Çß ``` With some tricks from [@Dennis' answer here](https://codegolf.stackexchange.com/a/109952/63647). Jelly is newer than the challenge, but not really specifically tailored for it. Suggestions on how to improve are welcome! If your console is in utf-8, run `export LC_ALL=en_US` or similar before trying. ## Example [![https://gyazo.com/f3594391a6b4d459a9d30bd47cf598b1](https://i.gyazo.com/f3594391a6b4d459a9d30bd47cf598b1.gif)](https://gyazo.com/f3594391a6b4d459a9d30bd47cf598b1) ## Explanation ``` ẋ⁹ḣ80ṙ1;”ÆṄœS.1 Monadic helper link - Argument: s ẋ⁹ Repeat s 256 times. ḣ80 Head. Set {output} to first 80 characters from repeated s. ṙ1 Rotate. Rotates {output} one character to the left. ;”Æ Concatenate character 0D, the carriage return, to {output}. Ṅ Print and return {output}. œS.1 Wait 0.1 seconds before returning {output} from the helper link. Çß Monadic main link - Argument: s Ç Execute helper link with argument s. Replace s by result of helper link. ß Execute this link with argument s (while true). ``` [Answer] # LOVE2D Lua, 197-10% = 178 Bytes ``` f=io.open("t.t"):read().." "love.graphics.setColor(255,0,0)love.window.setMode(640,14)function love.draw()s=""for i=1,80 do n=i+os.clock()s=s..f:sub(n%#f,n%#f) end love.graphics.print(s,0,0)end ``` Requires the input to be in a file called 't.t' in the root, thus 3 extra bytes were added to the score. Really basic in functionality, just in a for loop of 80 iterations, append the character at index of i plus the current time in seconds modulated by the length of the current string, giving a repeated 80 character long string of the input, which shifts left as time goes on. I used LOVE2D For the laughs. [Answer] # Sinclair ZX81/Timex TS1000/1500 BASIC, 110 bytes 182 bytes (for the listing) ``` 1 LET A$="I LIKE TO SCROLL IT... HELLO MUM, BY DONKEYSOFT... THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG... STILL SCROLLING... " 2 PRINT AT 0,0;A$(1 TO 80) 3 LET A$=A$(2 TO )+A$(1) 4 GOTO 3 ``` It works by printing the first 32 80 characters of the string `A$` at screen position 0,0 in line two, and then manipulating the string from position 2 to the end of the sting in line 3 (Sinclair ZX81 BASIC indexes strings from 1 and not zero), therefore adding the first character to the end and passing it back to the `A$` variable; then there's a unconditional loop back to line 2. [Answer] # Commodore 64, 434 bytes ``` 0 A$="I LIKE TO SCROLL IT... SAMPLE SCROLLY ROUTINE FOR CODE-GOLF MADE BY DONKEYS 1 A$=A$+"OFT MMXVII... HELLO MUM... SCROLLING IS FUN, INNIT? GREETZ TO ALL... 2 POKE53280,6:PRINT"{CLEAR}"; 3 PRINTLEFT$(A$,40)"{HOME}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}"MID$(A$,41,40)"{HOME}"; 4 FORI=0TO99:NEXT:A$=RIGHT$(A$,142)+LEFT$(A$,1):GOTO3 ``` As this requires 80 characters to show, and the C64 by default is only 40 characters, then 40 characters of the scrolly is printed on the top line of the screen area whilst the other 40 are printed near to the bottom. To clear up what the `{HOME}` and other symbols translate into as PETSCII then here is a screen grab taken from my emulator: [![Commodore 64 scrolly over two lines](https://i.stack.imgur.com/x1Hzo.png)](https://i.stack.imgur.com/x1Hzo.png) I will do a full golfed-version when I get CBM PRG Studio installed (or when I'm not on lunch at work). [Answer] # Ruby, 79 77 chars ``` ->(s){t=0;loop{system("clear");puts (s*80)[t..(80+t)];t=(t+1)%80;sleep(0.1)}} ``` [Answer] ### PHP, 136 bytes ``` <?php $s="\e[0;31;40m".substr(str_repeat($argv[1],160),0,160); while(true){for($i=0;$i<=80;$i++){usleep(100000);echo substr($s,$i)."\r";}}die; ``` * Call it with `php -f marquee.php hello\ world` to marquee "hello world" string. * For some reason, I had to do 160 characters for the initial string, else the output would be something like `hello worlddddddddddddddddddddddddddddddddddddddd`, but it'll only loop through 80 characters - I hope that still counts. [![https://gyazo.com/4c433abf04d71ca7ebb63a0889ca705d](https://i.gyazo.com/4c433abf04d71ca7ebb63a0889ca705d.gif)](https://gyazo.com/4c433abf04d71ca7ebb63a0889ca705d) It's been a long day, there's probably something I can do to improve it [Answer] # PHP, 85 bytes ``` for(;;usleep(1e5))echo substr(str_repeat($s=$argv[1],80),$i=++$i%strlen($s),80),"\r"; ``` takes input from first command line argument; run with `-nr`. Starts scrolling with the second character. Add one byte to start at the first character: Replace `=++$i%` with `%=` and `;;` with `;;$i++,`. [Answer] # [Wolfram Language (Mathematica)], 110 bytes ``` (s=StringPadRight[#,80,#];Monitor[While[True,[[email protected]](/cdn-cgi/l/email-protection);s=StringRotateRight@s],Style[s,Red,Background->Black]])& ``` It works well with Mathematica desktop, but not with TIO/ATO ( So if someone can make a running string with TIO, it’ll be cool ]
[Question] [ This is a rewrite of the (currently closed) ["Debunking Stroustrup's debunking of the myth “C++ is for large, complicated, programs only”"](https://codegolf.stackexchange.com/questions/44278/debunking-stroustrups-debunking-of-the-myth-c-is-for-large-complicated-pro) challenge. ## Challenge Write the **shortest** program or function that will: 1. Download [`http://www.stroustrup.com/C++.html`](http://www.stroustrup.com/C++.html), and 2. List all URLs contained in the HTML document. A "URL" for this challenge is * some string of characters * contained in the `href` attribute of an `<a>` tag * that starts with `http://` or `https://`. So `<a href="someotherpage.html">` doesn't have a URL, but `<a href="http://someotherpage.html">` does. ## Additional Rules * You may assume the downloaded HTML is valid. * You may not assume the input is static: you must download the page each time your code is run. * (as a consequence of above) You may not hardcode the output URLs: this is not [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'"), this is [parsing](/questions/tagged/parsing "show questions tagged 'parsing'"). * You may use either `http://www.stroustrup.com/C++.html` or `https://www.stroustrup.com/C++.html` as your source URL. ## Validation The first 5 URLs on the page (based on a [snapshot of the site on April 3, 2023](https://web.archive.org/web/20230403161526id_/https://stroustrup.com/C++.html)) are: ``` https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md http://webhostinggeeks.com/science/programming-language-be https://coderseye.com/stroustrup-the-c-programming-language http://edutranslator.com/jazyk-programmirovanija-c/ https://pngset.com/uz-cplusplus ``` There are 91 URLs in this particular snapshot. [Answer] # [Windows PowerShell](https://github.com/PowerShell/PowerShell), ~~70~~ ~~63~~ 61 bytes Try it in a PowerShell Console (works in PowerShell Core 7.3 on Windows as well, but not in TIO) ``` (iwr www.stroustrup.com/C++.html|% L*).href-match'^https?://' ``` Ungolfed: ``` (Invoke-WebRequest -Uri 'http://www.stroustrup.com/C++.html' | ForEach-Object -MemberName Links).href -match '^https?://' ``` Nothing remarkable (except that PS is somewhat competitive here) going on; `iwr` is an alias for Invoke-WebRequest, the object returned is passed to `%` (an Alias for `ForEach-Object`) which will call the object's member `Links` (the only one matching `L*`). `href` contains the parsed URL, and the `-match` weeds out local links as requested. **Edit**: Removed the `http://` (-7 bytes), fixed the regex, replaced Link property with ForEach-Object; thanks to @Julian **Edit**: -2 bytes thanks to thanks to @spookycoder: removed the quotes around the uri (d'oh). [Answer] # [pup](https://github.com/ericchiang/pup), 72, 70, 63 bytes ``` curl -sL stroustrup.com/C++.html | pup 'a[href^=http] attr{href}' ``` [Answer] # [Factor 0.98](https://factorcode.org/) + `html.parser.analyzer http.client`, ~~143~~ ~~132~~ ~~128~~ ~~124~~ 93 bytes ``` [ "stroustrup.com/C++.html"http-get parse-html find-hrefs [ protocol>> "http"head? ] filter ] ``` [![enter image description here](https://i.stack.imgur.com/mgLCg.gif)](https://i.stack.imgur.com/mgLCg.gif) A function that returns a list of URLs. * `"stroustrup.com/C++.html"http-get` push the http response and the raw html (as a string) of the url on the data stack * `parse-html` parse the html into a sequence of [tag](https://docs.factorcode.org/content/word-tag%2Chtml.parser.html) tuples * `find-hrefs` get all hrefs on the page as URLs * `[ protocol>> "http"head? ] filter` select the URLs whose protocols start with `http` [Answer] # [Bash](https://www.gnu.org/software/bash/), 50 48 40 bytes ``` curl -L stroustrup.com/C++.html|grep tp ``` # [Bash](https://www.gnu.org/software/bash/), 64 56 bytes (-8 thanks to Tihit) With tags removed ``` curl -L stroustrup.com/C++.html|grep -oP '"\Khttp[^"]*' ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 53 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žZ.•‹Ìe¨¹w•’.ŒŒ/C++.ŠÎ’J.w'"¡ü2ʒ`žXžY‚Å?às…aØ·=Å¿*}€θ ``` `.w` is disabled on TIO, so here are two loose TIO's to verify it's working as intended: 1. `žZ.•‹Ìe¨¹w•’.ŒŒ/C++.ŠÎ’J` - Verify the url is correct: [try it online](https://tio.run/##yy9OTMpM/f//6L4ovUcNix417Dzck3poxaGd5WDeTL2jk45O0nfW1tY7uuBwH1DA6/9/AA). 2. `'"¡ü2ʒ`žXžY‚Å?às…aØ·=Å¿*}€θ` - Verify the extraction of the URLs from the HTML content and final output is correct: [try it online](https://tio.run/##7VxJcxtJdj4PfkUaE6PFjSoQ4M4WqQCpjWpxaZKiWnORE1UJoMRCVamyiiBkT8TERMwf8Mnh8MH2wae52wfHOGI65uKDf0T/kfb3XmYtWChKHeO5eCamxQIqM@vly7d8bynEWvYD9eOP95t/@Jfv/7P733//N3/8/Xd//P3bH379j9//9vH3/6x/@PW/ye//4Q//vvv9b//wX3/9qx9@87v/@Y8ff2w2m49G2TjcazwaKenjTxZkodo7z9I411maJzvi4KuvHrXN141HOpvSXz@4dn05FX/b@FkifT@Ihjsr7roaf934WT9OfZU6PHBHx2HgV19OAj8b7XSTG/pKeldDPCXyHS8O43QnHfYfdNe7rW630@psrD7EGDt@fYVnDMJYZjtpMBxljV81HrUtLY/alvR@7E9Ff8ir7TafPXu2/2y/ie89FWUqxYUUo1QNdptB5Ksbl/bd3BvFY/WoLfcaf1fdx47tXd777M2@fjeQH@z9Z71vl9/v2gGZ8kZR4MlQLBmayESl2o5M8n6IgVkQR3p@4Jvn3Y4dRpfCTJwftZaN7KAL0H36av5@FufpajEC14t7S9J4mMrxGOdpx51W38wP9iNlBz2593SBC0Fsb@Jq/mZA53EdqEmx9@qL@aHXga/iYpj5MD/kQx5nqhhiPswPkUlS8tYOrH81P3yUZYneabeHQTbK@64Xj9uBjr0kaR8kyUGcquc5KAmDSOl2P4z77bHU2MDiXXfsN/eG5cf552DhJAgrESg/88BH7VJwMftKpCoE67w4aopsmihcj@VQtZNo2LTrDeQ13XdWuzerXZdu1KV/1Nl71N@7GCnSaFE7WPFKRsMca0GTOnviUbs/8/BEyDAYRruseHuNo9gPBoHyxYmXxX2Vis52S3RXuh2M3GvQ0oEWUgxVpFIZOkmeJrFWoiZaIrTPExMwGGP7gdQiiycy9bXQU/ByrBv1CdlIZo1Hecis2MMDlqrjz0HYQKUq8hTOV/RVhg2IA8NMmqfzJInT7JbZXii1bu75MpNC9mH8pEfS8bnT4zhp7sX998rLnDgNiHt@fdefuw4zLvAgN@Zifg0XZ8OcALdP0pYIIhFnI2x0Ahurd6oTKLk8iFPhq0EQEStl5Itc8ynQeToTRX/qG9Zu4zATIxyJxrHjrD0ZZQK3VTTMRpoeKFOF2xM8VWFg6uPklBjDYYDp@CLyQ@xd4TCw4LUKp/zUjIfTyPq6JPOhugmyKSQAnxIjFW7jYhTQs7ww95UWYxlNoQEaZstTGBYRudApv5AXfsQ490bYLnwKKzasLn0bRINUkjPzsjylyb5yBfPvIpWRDo0R2GEBE3xEj2SjsgQwBBPVH8U6A9eGSl1ptgjaC0jS2rXjcQqWO31I4L6CH8q1DmRkzw0rLxoZIifVaqrMqqXjdcAvx3OWLd/cO09kFOjRbetiWeXnmd1dnPLS7@XH6VW1XhpfY4330vHazb2zu@mEOdEq45Xyj46XhLmm/5p7rz/21dUndxgGiUyzQYiz5/lZWs0v/FGeXlUbYgGHxYL5ORQPlvrt/fcyjZSogApNfdiQY5IziDvJGJSCzh/aOAxIGAIStTE0EwoRD8gMuo23cS4giALqwSJaqk2LPxn//SGHCJIaGc0JslYh0bUBDRpQPsKMI0K8NOgrkkIxntZUPo6vis3zNdHfatSHzMKD0uW3GlhqBBlPFcwl9sHTRX9q7IAuaANfcMEjzORqCGlXoYwDmULzYqNhUMEw0Bnup1MyzLQyuKXAQ7IoQT@V6dRt9CI9oQUzO422z0oEOxLnGTsYYmpfGW3E5ivzjT2KT6Kp1m3DuhUqw8ED/PFOL4oTKCHWwvRhGGtNlFfzi6/4gbSOmaUBB8XnAhX2S@IQFu9aiSEsXWRVgJzsvEJOJhPXoAg3TofQOfNBwLboIDMYFEc1P602hXnbLD34s9LOLWrNRZwEnjVp1qLZZX8eKihOQNjglb0y8qKkN6IPBeSdnVWBmObei3hCJz9JQbYYxjHsLtmw6JapOsP6cBKG8sPzE6a@@HbJhDo0a@71ap9aooRILaEyz10yW42hbb7C457aq8JFLBlsJDqgXb0qLm9d@fnrQyM7uBDlTMO9OA6XrW/skJllrnk4XBu0arpkQuHiQNBzg6BKr7dsfYOIm3uXFTKe42WaBV5Iyx3EYaiMgyeTUNxYSgOcBjHwzFxYNFqADiNhdcmK5BhwdPk5n9fOuQQnxdDgI04HVokGP@BZpF9R4byLuVqcpEM4q4984yHZPwR5IfQh5W8Mjiyn6XJaXJuGc9UEDwBcGr3j80PzwN6YMBZM1fHiQw8BMoIsz9TDVmO/mLAPqYejWj6M7ciTw2Mz9LlKYR3voushG@PKSdWVQ0xAbaB1bvxHZ3t7C88QAAOwx6m6hnGI6EZ3ZWXVmH3clO/JUSUwDfBhWK3Tac2tc66SjNQkxcROB@Z8QECZjJmZsGb@bJolcdldgZlKya2GsHLwO0J6HuAmY/MYD43URMhxH6yB1xGrzhSmRWhvBBQSKrNBD9iLcaTZWqsklfcBRhgqOQzWI0MowoqVHUOAW3MgtNxPtZX3jcSTyWWPDnAY45hYjHhS4w7DrTNI@LwVgxUgqIv9G41yG6/5AHzsbpgD@ITT29DR7NJtQn2VJo3ikNYWfioH2YzNdBvHiHSNB8oYKgMkA6MKT6UZkDFAdxQD1wtIJmRLhhXUGaqMoUs8AAbHHcI@@BcHS8cgBmlsQBRtEhw6Pjy/YFZ5Uo/MKoQb8igMrgjbQwAipXxDCr5VWoupHSRLg10hI1wzmjBGEKgTcgC/Kov4BBPhidS1qjnTRX5j3XGAAE@JB5QSeVguQgZ56RkitIjAWp9Z/T7zOoDw3W57Mux2ELgVvCh9MduUBelgxkCUC1nOiI38ZUUaAh@Ed26jeUTICWyJmB/YEYI0yXEheHYVwY1WayJ6uxJ4SmYltljObS7H93fsqO3Hnm4b3NeGlq@3o7W17a6b@IPm3tFUEIYhyid0aKzsQgMxhjDHvH2WgkYvSYOQjMR6XdwOhQ89gmyFEznVLE4T8z3tzqJP@nx/DGRIiiaHQ3gxDdtR2zEEAjEIi0SJxo2tgSgnKaL3qfBCyh2AW7xg0xiKZovR7XBkBQTbIaC6LDNFsvOk8rtPr@Mw58M0D@SDLiC6ZqoU6WrtMEGjRxLN4SVhXXvc1pv7ymOaKEL11S301BJzn8i@iAewUimE7qkfsGPgcyipY98JA8mRvHGbhZKWslJiwGTON38JfNsRR@QnGcPjBp0GjTURDfjojWTgCU6@wqeO4VboDp0q@KpCBdfmwfNoOVCZifwhhKxG@L6I68HQ6zjwZZ/cwyND9G1iXsXEHD0WeMghskMj0T0T4tDhjGa2l8uUNI5UbpqYeKHMIhCFxabdxi3m@U@TA@wJxM5EXXUQbFKJSuIeHUPLnkOLDEhA2YWsoI44@1MoA4jkQbfucDmHKVFcxFo9Qaliqy/igVZeDB6qmojuwJbDdqQZS7140F1bwWkMlX5IygOEas06dD0tzI6xODb9N8B3V2qKSNQLQnahxgdZv3@YsbgEY4IdGYQphiOBxYnZmdl8Rkv0IYBjzmVxOCYJLa1oUXvi7erxhRFHLa5q9DhgFnU0siTbzHGj4gwS83E@@4xdAmGFHkWfOh8Oi3CaZITqKzYvd/sJhuqGEmImP3MdRJS9bZcud4aWimKDv4LIp7OfzhA1G9WYk1Kl9UwkJQJhgS7Nk8Sr4vGWKYRKTWYvU7fnuws6jKmp5b7tMi9kpJ2XrtiP1Wh8Xy/d@KhPN11y1O0hpbJKZHdQoFcxlGmfDKxXhkBs@A1e9uKc5Alk0EyKjQYICXBOdnRMiROpIXzYONku8tSNB8tomYYAiq52cyeLr6axKz33fUJU@UPP1WbPr6OAgVbGnuSCxtmcx5IFhyomP@PRqVJCuPrE2a4CIEFaIDVMPYOuaxmEZFkNGyD4wL@pUDeSDmRn6ZOSMB@PZBiaJ53aT3z2nBtZNoVS7SxvrO2UCPVzL@PDxRJ0NwKimklOLKrepyPwGU2Dd7nJVMQwworOAmGeUyYWCRSZjGEySh7HCZ37Lsh9N85Spe4dIgQK/N31zeZegedIVkp6KhR0xzM4uqermuRWOlYdxszqDP/gTJcLNSzxOBnlqTb67JFi9nVRAiwgYrWYTXy5t9sHmGYsBiKbe/vFpTHePTjEJIZAxjABEJhGtexYEZ4jZ0rgFPYpNIZgHqNWicGlz9cZGOBKP@6b9G9z7/zilewXvqPSSk5VKpU6FBKqCdl7Qg9wLSUDresuaWw1QsLVcljksVhE2OX04xqpRbgujJCVFQnB3BCl6BE@ISdD5kKGmioSNqqgGhxnPHu0EUHYe5GaMsWQcfxvCjiHVKcrHrzAHVrIrFNj0SS4Ctp@ACGTUzj6sG3X@orX@squBfd@@Kp28M/Ia0JYsLwpg9FaO4uYhtR2blR7QlLW5k22SdjqfsLEGWavCzpS2Gq4XqcG9ESUm9RKWJNTgwcAsm88CBOpHGxWpm0gXrlISifM1P/KJPty6xXH9mlGI/HRQO0TU447Kcpxx3aUOOVqJ3yAqZTZfdbOEU@nqTaZjtgyNCUzUMuhEARy8SjTOIbCAsK53og/NPfOTk4uSksiDp6eHXM2RM8ITRlbjIHeWktsuA9bEcaSxPoTpvTuZGPdnHZXVjYcTrAsCogfwneNmZd@HLRlX7c7K26ns7beXl3d2ljtrhB/0@C6iAmEl8YT3yosAoSI9RFmI/Q5f0MZqo3v//WH3/zuh1//Ez2UJUfgf4YYYLWOQ2PqxADnOTKkpIbDGQoD9SmG4@fWKpyB2SmxihQvVZC62sPL1Wvy2tne3HboxtwTu0VA8cKwzeKTHVFOmDHzdGKMXaBJ1jURCt75icFoLeVxgEVzSpYUhBzlWuW3wSAdDzKqwoIODZjNII7PrxDktveOPBb/U0dJJt6tTKtJjz2gyK8FufPyEj@2bBnJeOeHFdSLQ9/A75yyJVkeyUzZ9FOBAfExgI@FrYZHaUG/YWJNQbVWEQsRQRXdGVxgolPmggwWlkEKIQMQRrw91jMsA3ROTXKCK8Z03Gv07UhC@GG7bDqCwphBoEIfokGJjrHkcrCOi8yVSfZg@CCEPmk7rK8YlUNX1df0KBj3SAacnbolmrijTnAVZHpeGZcd6SDMrozHfvbq4ps7/PswuxqPLRzh6zvGf8gcKxnmEd9mVeVs2fjJzSTwhyrTZvibmzfm4x3o7tPFmKUcqHUiOGCZM@a6lCrUEv54QE6rCPhNxgwAHY4WrkWyaJgyLRcbABqXPHmeMy/Pnzm9SyfNQ0AAfhK@Ia0nTcSlIPG7ViMqmRSZEZbOIk9ULSpqBdzKHV6cmWXrycwyhXlfi4sz2kptglnwUkHxOZFsKZ5n44ybhPiT0r2nRgycQOCNuFWCPNKOOMQlZSCDjJhyMJIJGZfuOgeCU7jYm2w2a/XJZrAdcQr19AJot5HsUz4znEvJ@ztEA5iVK76f1oW5DPlAfigKp/QZjGue5yQHtJq1BpwusO1HJj3dp/YjQjtUuWAmcPqbu2aIgjJt98mytHvbsM8sSy@ZjxkrN7hdLbByMz9cpppCMXFAGZ1brH8iU6lHwcCGC1995YAsJ4SNhzkwBZA7I4T3ZPN811fjmKI6N79qe9prV2yYwdFlzNGwAJkOnTHMtQxzBi4GMD8wLTylKcdxzKUl5hPoRTTxsHKGy@2j/KALodDtA9pym4vbzT3@43oOOEFYUlOfaVJSzD4yAuzkdqF6ip9NRy170DbxM7TqGqKtPxXGfl5VvS7nlCZWwEkQ1Pt6Du7eZOL/RBk/MwFIKb9l@b9l6b7O9mel@ygoClg1ua7XWXdF70@S0psNt8tiOR@iXbg4HKZjaUgPHjgjV4G5nhxT3gbSP1Jh0s6SsF3ATAhZ2RhsIJoc91Pyg6KW1XlK2FcZ8PJEUeMTiXodNNbzGLPBL3PUBL96toEmXl7Tkp6XG49MGtQ7OHhty9oaNjIohbpKhb0GOsRJFVWuT0j0XZ0InzTZddpggogwmvN1Q5aeD3gL3GIcWpTuTFWjefcG3GbjkLKQ1MNA1dUWiZaplXLAf/max5/gTChswgOG8iMn4wt5WWiXi1yKuU1XFhHNETgV8N4d/KK7j/@/O/SDeKyNmQ/4mqXuDjZ@VgNGnZcvVNoX5zn1rt7Xc/KxHPrF2QRiCzbP9HQMgN1taSYqiiKsCLYFVFU5EQuUZFEI4tqOZdU36hqGXLxQsFNTfX@WoMXUWJ7CdkNhbKLH1OkytgzxVdV/qgZ5ONuCYuqCXI6ai1/r1PQwZSzBl6XKwDeLjJkRVXNc5pqfQ32t8zknNk@WGEr4h/k4smHO7Qe72HpjT5Gi2qUKMcUO8yLBIzNv9Ph6d0sefjjcHx@/nB4xqTtkOoOICp0m@J/t8epZ05vJ8EpQKIe9fHuvV6XlegdHYFjuU27FsxgPFvaF9KgbOpmxVDjWXnQF6NAS1H6ppm7jmeqnOaXHqKHbte0@t2r4sg2dT16@PlVvvjl7EXPZi8mFepvkMDGcq7mKCjrani8CMVaJ2TokdpuOcKOiuFUFxeem@7ZmYYVW8IUydRtFYzrlGdwvJP/p2cenx4Nv1zsHV/ey3Q1tEPu@krmtZZ7GE1NnbMLnAr6DtmZF8UGSAA/xk8VJotjpfKOmQOWQ4HrbDVOWWGH5IgrjWI3Sq7dXz/3evUHfCwN/93DSO1t9t9ofvr189s7feL/xzfsX@ydr0Tg5yJ3N@MnV1tv@@cGWfJu@9MPn173r@F0v7A7evn23/WbN7JBQXBDlRK9ampeoyc2BhFXV4vDwUBxJHw5QHJxDYYuDcBsvZWSFqLPtfqkAnb52ulH2JH/WWanvr7M@WD8/G4@n6dSXm4fXeni4//HJq4PL77yjs48b716eXfS9zY2N7zrH33re8zP1rrv1YTxdG5LhhaQkmTbR3CDnsJ9qsYsN9uJBVg0BVqEu2Yd/ZgasrY710YfL9YPLXnPvmBpyyReAuL8yhFyQ7kOJikfDeOXkFAWjXL34dGu5GueZuibQkqawfgbkjiTMeuhsL8kBeubetjvWvjHn5/AiwEDbzvMY1FDD3LVqmz5sp@rDdg6LHllHZg6XpCMHpGw9rp/mdnr82jvw4m4SjQ4uorXeiw8X/ZPj8eDb67Un38SXvcvOlXp76l9uX15/M/x4dnNxeJn88ghGkmuL9gnG7i20grOiPpfAZioUT3BSZyqwXiYThiJizpZtRvGsfHABPg@Vrrq7laZIIZChwZNlwrHUEeqF9m34YrOF9IH9GCKyRFxKLd0/B3fx9XjXY/tzj@h0VLSLGeQBi1Om1yumRohmWgC36lLy2XL65Pr1q5W33X4y9WAqO91tGMs3tp2IK/ZgDPcFAZtNAkicyaSZ5xfG8coYR/JRR0oV9XEXFjcF7KBU@3VJ5sYXq5J6N9xYf/X6u2T/sLnXLOxAE/g7CQ3epHRhlxoq86woZ/xEOihtLm9y5X74YCAILCoV4Yu/gd/ubq9u2jSwzZ0/i6mmsq9GgYG3nMOgCKGz5RiixMXTJzfG31PnJqXWRzKoO7nb6elr7Wpv5PbHyh3lbUYs7b4RqfqLJtNEcaqt7KyhzhjHA6mTmB@t6Xz2c18mVGq@KN9prGxiAU@YUID48dRgLDnMAUr60MPzILqiMJrgqK/6@ZBLBGOVSWt/ScXCMJ6YKCCGRtM6ilN8ROFM845TNO/goVgdiJCfXPawceY5DzXpJEsDPawWEnKsCRkYm@TvRNmetjyFV8goe009Q4VlcEXjSE5/mgzK0@v@TX6y/@3migGjF7EvC35FjFqc6i3RzBr3g1FOXZCU9yE2Dmv1gHMERioDWKvGUO/ntBaO2jluY3WjkG13ZgdfrOy/PFk5/e7t0eXz89fNvRMKBmv1kaXv4gBM2nLMLZWMRhdhSU4voywD856dZKtXHJNVqF23Y9BgO0gRmBvRXl1ByGGgML365KVBki0xd@tffIY3XnL@6iw5OXoJB3Ry@zt@7I/IpQQRkEOQVYncpwcnJ6f3O@slGqQcDXQD3joPp5@m6jN9BV875oOz1nUWfUdQ9x3GVRBGZ@bVnKp9h8dA2cITmrA9VWL2ddbPZu3iJp5eUxKufXB62q782Hr7jWmJw9Zi3zlwOgCo/NWwDA47a9ZQT0WJt8HZq2U4myhign46RWARVIzf9WJTyBlNl/RKPbRl3RJSrJu6JvUQ3C9ehuqsrIgPuQz5FUdaYRnPblXIRSpVjUrn9NSxdK61VzqrzpG8wpFzhtW5kPpK2w/NPbojNH8AGbhjPyzh5dotvFy7zdF8mpV1Ir@EmWs/gZlrX6zb7598@Db3@1n@Ib43UFwT3OVxLr3ESeXNiKRdNHlLTVYIhNzWgOdDKrb8JN5Q369z/PS7i@rKnKM1Ec09@t49VjfZfRyJ/dYkGhhnOY4IBqBnmrF3w0dOk05swpMKmbaN8jE888aWdQUFmCC@YyNfTHfd5oDe1bbFco6lcNHwNPdqc@53Vmf3QnjoKeFsT5XF9jdkxJ@ahjXOGOPbLfNaCr0CY99qsTlB4n1PbG/cvr/klsrmdTBWMe9tdX21u7G5ujEbX5j@Nxa82q9DWM/kIM7q2HaBc1t@F0@gnWGccEKC4MbhzLvHn@rD/Sx@165JVrrtW3lOsUGn43A9ao7/3Vn@MzNN4Yr5uHI3H3uL2WiCMHYLrswym//rXdy7YLxYhJrMUVuAkbdlEZetRZ1QDnsq1xuMSfA67dX2ZpsWdw7phfBlcgdUxL1r/Bp4pqn0JL2sasiBIQrSz3q@6STEox@fK3pB5UIOd@nZv@iu8NMBlmmbfM3rIyQPaglnZmbMgrxys3j4vp6oftU7pOjtqnanu7K2tbb@OIx2FTw1hVZPz47NG6t1q7eyXesboQzgi5PTV04QBPOP4Va6qrcniz3eEYLyTnd1a2sN5rmca2DBrIU28vsyhznEUzfLzZnCJW@RX4MVcvE1Kk97Yd53c9hdysrHlLIeKz@QbZ4NPjr4rxfhnxNbOnKXtcy@sfNt3n1Bo0lCgBSGobK90D4hfjl97AM3@7vO6trm1vbK5srGZqezubbd2VzfIv2gCS1x/PbAOJ3SsNd2OXOEUIyAEgPBRxwB94WVWxdfTtV6d6O7trkNjV5d2Vjf2lrtrlVEHcU5l0cKi@SKWpq2pO@c@yBDe2wwjrkfxMJIEpS/SGqUwNjUXcmFthqJhKjbEdUrzstLZRyrqMyjZh3ff29eGIi8d57EYrGpTj4OIJvvsK9tbKPxJHXFk7jfpzaHanL5mle9IaMXqhuYIgWC4mubjJNcp7eJlfOLVw@Lpg8oM8mz9RtLG7Jr/p5yZO3etknXmwPQjweIN3eHCJru0Y53OwSTsDSVgz32O6cLP75hZIF6jAQFI7DqO5@f7t/YVv7JeGtr@3Jtph@syrSKB9x2WrQHm2rYIJzat0S0MctNwQhgJBP4XvOaaFa8gqXND4xo85oZFXqkyFSoEKeMqR7QQvAbkKnCdMQvLeqAmowguUEm@ml8pbjdkCaNAn4FlSoFNmlPz25xKwmF2dRsopUy6a8woN/poPcVIu79UvprS46lvg8Y5bucg6VOL5FRcoEeUXYAsILRDJ@i/yKWAt2JfQ/DtpKx6R6rMcWFYARItxRRBE9g6Kp8tQ10a0nR/E1GdCd5GKoiX5fa4phN2JkXzYZQNJEBFzx0G6fU05YUb1rdEsZWJaJlNdTFN6nvrJv2VRg6oexrK7Zp2x@ndKdNukRN9VqcBZTSoMYh@v2qxHazUr6iUTRjhLFR8Xpfba3XoVG9iGdDbHqj9qBFOZ0bYwkekPd@KPap7/uV7HM10rLA/vgJpWPYGwrza0GNB@Y3YShYpHPsx2n08BNtB0uCfPuO3HJe0ybv60aJtk5r3Y7iOaW//0TtkYv1wXp3pH1fgCSRiqw1MTLdlPT2Mzw/whjIWD@3L9TQT@RQr3nxns@DUnWKXkxf4fBC/bBWdaRX7a2Ec4uDNKNNJ0VfeZL0@9A2CXCDzS3nbX5@p0Wa2ajmVa@jwozEKdsK@x4HsKCN1MxrQgUL2bqEARUcONwg5lg5n@2liQy6Mq/VuI3DAb8FO1AqLGyVqQ3TC@S@b3fWMgMGqTKvfZLsjZXRZZNQnprC2V9@1e0vv@r2//hX3dr0Y4f824f0643NZvN/AQ). **Explanation:** ``` žZ # Push builtin constant "http://www." .•‹Ìe¨¹w• # Push compressed string "stroustrup" ’.ŒŒ/C++.ŠÎ’ # Push dictionary string ".com/C++.html" J # Join the three strings on the stack together to an URL .w # Pop and download the HTML content of this URL '"¡ '# Split it on double quotes '"' ü2 # Get all overlapping pairs ʒ # Filter this list of pairs by: ` # Pop and push the strings of the pair to the stack žX # Push builtin "http://" žY # Push builtin "https://" ‚ # Pair them together Å? # Check for both whether the second string starts with these substrings à # Pop and check if either of the two is truthy s # Swap so the first string is at the top of the stack …aØ·= # Push dictionary string "a href=" Å¿ # Check if the first string ends with this substring * # Check whether both were truthy }€ # After the filter: map over each overlapping pair: θ # Leave just the last/second string of each # (after which the list of URLs is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `’.ŒŒ/C++.ŠÎ’` is `".com/C++.html"`; `…aØ·=` is `"a href="`; and `.•‹Ìe¨¹w•` is `"stroustrup"`. [Answer] # [Go](https://go.dev), 218 bytes ``` import(."io";."net/http";."regexp") func f(){r,_:=Get("http://www.stroustrup.com/C++.html") b,_:=ReadAll(r.Body) for _,e:=range MustCompile(`<a[^>]+href="(http.+?)"`).FindAllStringSubmatch(string(b),-1){println(e[1])}} ``` [(you cannot) Attempt This Online!](https://ato.pxeger.com/run?1=LU_LTsMwEDyTr4h8spXUUW8oEBBUghMXeqxK66ROYuGX3LUCivolXCIkbhz5Gfia2i2X3R3t7OzMx2dnpm_LmlfW8VQxob88tLPL3z-hrHGAKRIGXVGkORQ9gI2z4x1_s4gkrddN2mIyunxTVo8cMIqcsiiGYaB7cMaH4i1tjCoWWUZ7UDLc1ZH-zNnuTkrs6L3ZvQcx49JNzsvKMR28PIXThVFWSI6312z1crPOesfbCuH4g2a3BG0JfRA6qizBCd0tfa0YND3enyCuST6bk9EGAFJjvpqvyeFwTvhzMh8TY5KOyUWIkfyvpuncjw) Prints all URLs to STDERR, separated by newlines. ATO doesn't allow web requests. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~49~~ ~~41~~ 39 bytes ``` `s≠ĿꜝǓ≥₂.•⅛/C++.°¤`¨U`₁(ṅ•s?://[^"]+)`Ẏ ``` [no point Trying it Online because web requests are disabled (if I've done things correctly - they were accidentally enabled once. Big brain)!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgc+KJoMS/6pydx5PiiaXigoIu4oCi4oWbL0MrKy7CsMKkYMKoVWDigoEo4bmF4oCicz86Ly9bXlwiXSspXCI+YOG6jiIsIiIsIiJd) Example output from Crosshatch. *-8 by remembering `https://www.` is automatically appended to links if not present when calling `¨U`* *-2 by not including the closing `"` and `>` in the regex* [![enter image description here](https://i.stack.imgur.com/mqTWa.png)](https://i.stack.imgur.com/mqTWa.png) ## Explained ``` `s≠ĿꜝǓ≥₂.•⅛/C++.°¤`¨U`₁(ṅ•s?://[^"]+)`Ẏ `s≠ĿꜝǓ≥₂.•⅛/C++.°¤` # stroustrup.com/C++.html ¨U # GET request `₁(ṅ•s?://[^"]+)` # <a href="(https?://[^"]+) Ẏ # All regex matches ``` [Answer] # Python3 + [`requests`](https://pypi.org/project/requests/), 109 bytes: ``` import requests as r,re re.findall('a href="(https*[^"]+)',r.get('https://www.stroustrup.com/C++.html').text) ``` [Answer] ## ****C#, 221 bytes**** **Golfed** ``` using System.Text.RegularExpressions;var r=await new HttpClient().GetStringAsync("https://www.stroustrup.com/C++.html");foreach(Match m in Regex.Matches(r,"<a.\\n?href=\"(https?.*?)(?=\")"))Console.WriteLine(m.Groups[1]); ``` **Ungolfed** ``` using System.Text.RegularExpressions; var r = await new HttpClient().GetStringAsync("https://www.stroustrup.com/C++.html"); foreach (Match m in Regex.Matches(r, "<a.\\n?href=\"(https?.*?)(?=\")")) Console.WriteLine(m.Groups[1]); ``` [Answer] # [hyperscript](https://hyperscript.org/), ~~130 101~~ 62 bytes ``` def f()fetch"C++.html"put it into me return<[href^=ht/>'s@href ``` This program [must be run from the site's root](https://codegolf.meta.stackexchange.com/a/13626/58974) to avoid CORS issues. There is a snippet below that uses a CORS proxy to do the same without running on a different domain. ``` <script src="https://unpkg.com/[[email protected]](/cdn-cgi/l/email-protection)"></script> <script type="text/hyperscript"> def f()fetch"//corsproxy.io/?https://stroustrup.com/C++.html"put it into me return<a[href^=ht/>'s@href init put f().join("<br />") into <body /> </script> ``` Ungolfed: ``` def f() fetch "C++.html" put it into me return @href of <a [href^="http"] /> end ``` Usually hyperscript is very verbose, but it's perfect for a challenge like this. This function fetches the HTML, throws it into the `<body>`, selects all `<a>` whose `href` starts with `http`, and returns each's `href`. I was somehow able to get rid of almost every single piece of whitespace in the program because hyperscript doesn't need whitespace before or after parenthesis, string, query literal, or attribute literal tokens. [Answer] # JavaScript (ES6), ~~193 … 121~~ 117 bytes Big port of [my hyperscript answer](https://codegolf.stackexchange.com/a/260514/108687), parsing HTML by chucking it into the `<body>`. This program [must be run from the site's root](https://codegolf.meta.stackexchange.com/a/13626/58974) to avoid CORS issues. You can test it by pasting it into the browser console at [this page](https://stroustrup.com/index.html). There is a snippet below that uses a CORS proxy to do the same without running on a different domain. ``` async _=>((d=document.body).innerHTML=await(await fetch`C++.html`).text(),[...d.querySelectorAll`[href*=":`].join` `) ``` ``` f= async _=>((d=document.body).innerHTML=await(await fetch`//corsproxy.io/?https://stroustrup.com/C++.html`).text(),[...d.querySelectorAll`[href*=":`].join` `) f().then(s => document.write(`<pre>${s}</pre>`)) ``` ``` async _ => ( // asynchronous function (d=document.body) // alias the <body> to d .innerHTML = // put into its html: await (await fetch`...`).text(), // fetch the document [...d.querySelectorAll`[href*=":`] // get all tags with href containing a “:” .join`\n` // join by newlines (<a> stringified is its href) ) ``` # JavaScript (ES6), ~~236 … 134~~ 130 bytes This parses HTML using the `DOMParser#parseFromString` method. Ditto for the CORS stuff. ``` async _=>[...new DOMParser().parseFromString(await(await fetch`C++.html`).text(),"text/html").querySelectorAll`[href*=":`].join` ` ``` ``` f= async _=>[...new DOMParser().parseFromString(await(await fetch`//corsproxy.io/?https://stroustrup.com/C++.html`).text(),"text/html").querySelectorAll`[href*=":`].join` ` f().then(s => document.write(`<pre>${s}</pre>`)) ``` ``` async _ => // asynchronous function [... // cast to an array: new DOMParser().parseFromString( // parse HTML from await (await fetch`...`).text(), // fetch the document "text/html" ).querySelectorAll`[href*=":` // get all tags with href containing a “:” ].join`\n` // join by newlines (<a> stringified is its href) ``` --- Saved 7 bytes on each version thanks to a cool trick pointed out by @tsh Saved 39 bytes by running the program from the site's root, as pointed out by @Shaggy. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 88 bytes ``` Import[s="https://www.stroustrup.com/";s<>"C++.html","Hyperlinks"]~Select~StringFreeQ@s& ``` [Answer] # Ruby 3 + [`nokogiri`](https://nokogiri.org/), 152 bytes ``` require'open-uri' require'nokogiri' p Nokogiri::HTML.parse(URI.open("https://www.stroustrup.com/C++.html").read).css("a[href^=http]").map{_1.attr"href"} ``` Outputs an array of strings of URLs. Doesn't assume anything about the structure of `<a>`s that might be deviously crafted to fudge regular expression approaches. We cannot use `Nokogiri::XML` because it doesn't correctly parse HTML URL query parameters. # Ruby 3, 113 bytes ``` require'open-uri' URI.open("https://www.stroustrup.com/C++.html").read.scan(/<a[^>]+href="(http.+?)"/).map{p *_1} ``` Outputs a string on each line. Uses a regular expression approach which might be fooled in some cases (e.g. `<a style=">" ...`), although it produces the same sequene of URLs. [Answer] # JavaScript, ~~79~~ 78 bytes Must be run from the root folder of the site ([consensus](https://codegolf.meta.stackexchange.com/a/13626/58974)), returns a `Promise` containing an array of URLs ([consensus](https://codegolf.meta.stackexchange.com/a/12327/58974)). ``` async _=>(await(await fetch`C++.html`).text()).match(/(?<=href=").+:.+(?=")/g) ``` Here's a snippet that uses a proxy to allow it to bypass the site's CORS policy: ``` f= async _=>(await(await fetch`//corsproxy.io/?https://stroustrup.com/C++.html`).text()).match(/(?<=href=").+:.+(?=")/g) f().then(a=>console.log(a.join`\n`)) ``` [Answer] # [Nim](https://nim-lang.org/) `-d:ssl`, 106 bytes Dirty solution which might break on a different webpage. ``` import httpclient,re echo newHttpClient().getContent"http://stroustrup.com/C++.html".findAll re"htt[^""]*" ``` [Don't Attempt This Online!](https://ato.pxeger.com/run?1=m704LzN3VbSSbopVcXGOUuyCpaUlaboWN7Mycwvyi0oUMkpKCpJzMlPzSnSKUrlSkzPyFfJSyz2Aos5gUQ1NvfTUEuf8vBIgRwmk2kpfv7ikKL8USJQW6CXn5-o7a2vrZZTk5ijppWXmpTjm5CgUpYKURscpKcVqKUFshFq8AEoDAA) # [Nim](https://nim-lang.org/) `-d:ssl` + [Nimquery](https://github.com/GULPF/nimquery), 201 bytes Should work on any possible webpage. ``` import htmlparser,httpclient,nimquery,re,xmltree for e in newHttpClient().getContent"http://stroustrup.com/C++.html".parseHtml.querySelectorAll"a[href^='http://'],a[href^='https://']":echo e.attr"href" ``` [Don't Attempt This Online!](https://ato.pxeger.com/run?1=VU87DoJAEO09xWYbNC5La0gsDA29JcGE4CAk-3N2iHoWGxJj4008grdxQRqb-bx5817e_WE6_Sp4fEy9V7wcnj018ebz7rSzSKwlrVyFHlC0RK5WHRgS4efcA94EgrhqRQiwaCwyYJ1hBi55oGYTdbmSJ6DMGgoLHyXSJPGEtg-ld7K2OsnWazn6cDk55WGUk_weFNRkcacUr4oWoTlso1kjKsUf5CeMp1C3loGsiJCPZ_4LNOca5v4F) [Answer] # [Scala](http://www.scala-lang.org/) + [jsoup](https://jsoup.org/), 220 bytes ## Golfed version(220 bytes) ``` object A{def main(args:Array[String])=org.jsoup.Jsoup.parse(scala.io.Source.fromURL("https://www.stroustrup.com/C++.html").mkString).select("a[href]").eachAttr("abs:href").toArray.toList.map(_.toString).foreach(println)} ``` ## Ungolfed version ``` import java.net.URL import scala.io.Source import org.jsoup.Jsoup import org.jsoup.nodes.Document import org.jsoup.select.Elements object UrlExtractor { def downloadHtml(url: String): String = { Source.fromURL(url).mkString } def extractUrls(html: String): List[String] = { val doc: Document = Jsoup.parse(html) val elements: Elements = doc.select("a[href]") elements.eachAttr("abs:href").toArray.toList.map(_.toString) } def main(args: Array[String]): Unit = { // println("This is in UrlExtrator object.") val url = "https://www.stroustrup.com/C++.html" val html = downloadHtml(url) // println(html) val urls = extractUrls(html) println("List of URLs:") urls.foreach(println) } } ``` [![enter image description here](https://i.stack.imgur.com/DoVS4.png)](https://i.stack.imgur.com/DoVS4.png) [Answer] # Bash + [Retina](https://github.com/m-ender/retina), 40 bytes ``` curl -L stroustrup.com/C++.html|retina p ``` File `p`: ``` s`a. S`href=" G`tp ".* ``` The tricky things are 1. `a` and `href` seperated by a newline 2. two links on the same line [Attempt This Online!](https://ato.pxeger.com/run?1=7VzJdttMdl6HT1Fhn7at_AQoUrPalg8lT_JvDZZk-Xdv3EWgSMICARgFiKKTnJN3yDKb3iTPkGWeI8s8Sb57qzBwkmyfTm_Sffq3QKKqcOvWHb47gP_2H6nKgkj--c__nmcDZ_c_9Z-k22hc_mmUqsGzZuP1n7Kk0XT_oWFu21F__u_3__V0lI3Dg8bTkZI-_mRBFqqDyyyNc52lebIvjn755WnbfN14qrMp_fWDW9eXU_GPjb9LpO8H0XB_3d1S4z80_q4fp75KHR64r-Mw8KsvJ4Gfjfa7yR19Jb2bIZ4S-Y4Xh3G6nw77T7pb3Va322l1tjfWMMaO31rnGYMwltl-GgxHWeOfG0_blpanbUt6P_anoj_k1Z41X716dfjqsInvPRVlKsWFFIYbQeSrO5f23TwYxWP1tC0PGv9U3ceO7V3e--zNvv48kF_t_Ve998vvd-2ATHmjKPBkKJYMTWSiUm1HJnk_xMAsiCM9P_Dj627HDqNLYSbOj9rMRnbQFeg-fzd_P4vzdKMYgevFvSVpPEzleIzztOPOq2_mB_uRsoNePHq5wIUgtjdxNX8zoPO4DdSk2Hv1xfzQ28BXcTHMfJgf8jWPM1UMMR_mh8gkKXlrB9a_mh8-yrJE77fbwyAb5X3Xi8ftQMdekrSPkuQoTtXrHJSEQaR0ux_G_fZYamxg8a479psHw_Lj_HOwcBKElQiUn3ng03YpuJh9I1IVgnVeHDVFNk0UrsdyqNpJNGza9Qbylu47G927ja5LN-rSP-ocPO0fXI0UabSoHax4J6NhjrWgSZ0D8bTdn3l4ImQYDKNnrHgHjZPYDwaB8sWZl8V9lYrOXkt017sdjDxo0NKBFlIMVaRSGTpJniaxVqImWiK0zxMTMBhj-4HUIosnMvW10FPwcqwb9QnZSGaNp3nIrDjAA5aq4-9A2EClKvIUzlf0VYYNiCPDTJqn8ySJ02zFbC-UWjcPfJlJIfswftIj6fje6XGcNA_i_hflZU6cBsQ9v77r712HGRd4kBtzMb-Gi7NhToDbZ2lLBJGIsxE2OoGN1fvVCZRcHsSp8NUgiIiVMvJFrvkU6DydiaI_9Q1rt3GciRGOROPYcdaejDKB2yoaZiNND5Spwu0JnqowMPVxckqM4TDAdHwR-SH2rnAYWPBWhVN-asbDaWR9XZL5UN0F2RQSgE-JkQq3cTUK6FlemPtKi7GMptAADbPlKQyLiFzolF_ICz9inHsjbBc-hRUbVpe-DaJBKsmZeVme0mRfuYL5d5XKSIfGCOyzgAk-oqeyUVkCGIKJ6o9iDf86HCp1o9kiaC8gSWvXjscpWO70IYGHCn4o1zqQkT03rLxoZIicVKupMquWjtcBvxzPWbZ88-AykVGgR6vWxbLKzzO7uzjlpb_Ib9Obar00vsUaX6TjtZsHFw_TCXOiVcYr5d8cLwlzTf81Dz5866ube3cYBolMs0GIs-f5WVrNL_xRnt5UG2IBh8WC-TkWT5b67cMvMo2UqIAKTV1ryDHJGcSdZAxKQecPbRwGJAwBidoYmgmFiAdkBt3GpzgXEEQB9WARLdWmxZ-M__6aQwRJjYzmBFmrkOjagAYNKB9hxhEhXhr0FUmhGE9rKh_HN8Xm-ZrobzXqQ2bhQenyWw0sNYKMpwrmEvvg6aI_NXZAF7SBL7jgEWZyNYS0q1DGgUyhebHRMKhgGOgM99MpGWZaGdxS4CFZlKCfynTqNnqRntCCmZ1G22clgh2J84wdDDG1r4w2YvOV-cYexb1oqrVqWLdCZTh4gD_e6VVxAiXEWpg-DGOtifJqfvEVP5DWMbM04KD4XqDCfkkcw-LdKjGEpYusCpCTnVfIyWTiGhThxukQOmc-CNgWHWQGg-Ko5qfVpjBvm6UHf1XauUWtuYqTwLMmzVo0u-zvQgXFCQgbvLNXRl6U9Eb0oYC8s7MqENM8eBNP6OQnKcgWwziG3SUbFq2YqjOsDydhKD--PGPqi2-XTKhDs-ZBr_apJUqI1BIq89wls9UY2uYrPO6lvSpcxJLBRqID2tW74nLlyq8_HBvZwYUoZxruxXG4bH1jh8wsc83D4dqgVdMlEwoXB4JeGwRVer1l6xtE3Dy4rpDxHC_TLPBCWu4oDkNlHDyZhOLGUhrgNIiBF-bCotECdBgJq0tWJMeAo8vP-bJ2ziU4KYYG33A6sEo0-AnPIv2KCuddzNXiLB3CWX3jG2tk_xDkhdCHlL8xOLKcpstpcW0azlUTPABwafROL4_NA3tjwlgwVaeLDz0GyAiyPFNrrcZhMeEQUg9HtXwY25EXx6dm6GuVwjo-RNcaG-PKSdWVQ0xAbaB1bvxHZ29vF88QAAOwx6m6hXGI6EZ3fX3DmH3clF_IUSUwDfBhWK3Tac2tc6mSjNQkxcROB-Z8QECZjJmZsGn-7Jglcdldh5lKya2GsHLwO0J6HuAmY_MYD43URMhxH6yB1xEbzhSmRWhvBBQSKrNBD9iLcaTZWqsklfcBRhgqOQzWI0Mowor1fUOAW3MgtNzP2srHRuLJ5LJHBziMcUwsRjxpAUnNGW6dQcLnrRisAEFd7N9olNv4wAfgY3fDHMAnnK5CR7NLtwn1VZo0ikNaW_ipHGQzNtNtnCLSNR4oY6gMkAyMKjyVZkDGAN1RDFwvIJmQLRlWUGeoMoYu8QAYHHcI--BfHCwdgxiksQFRtElw6PT48opZ5Uk9MqsQbsijMLghbA8BiJTyDSn4VmktpnaQLA12hYxwzWjCGEGgTsgB_Kos4hNMhCdSt6rmTBf5jXXHAQI8JZ5QSmStXIQM8tIzRGgRgbU-s_pL5nUA4bvd9mTY7SBwK3hR-mK2KQvSwYyBKBeynBEb-cuKNAQ-CO_cRvOEkBPYEjE_sCMEaZLjQvDsJoIbrdZE9HYj8JTMSmyxnNtcju8f2FHbjz3dNrivDS3fakebm3tdN_EHzYOTqSAMQ5RP6NBY2YUGYgxhjnn7LAWNXpIGIRmJrbq4HQsfegTZCidyqlmcJuZ72p1Fn_T58RjIkBRNDofwYhq2o7ZjCARiEBaJEo0bWwNRTlJE71PhhZQ7ALd4waYxFM0Wo9vhyAoItkNAdVlmimTnReV3X97GYc6HaR7IB11AdM1UKdLV2mGCRo8kmsNLwrr2uK0395XHNFGE6qsV9NQSc_dkX8QTWKkUQvfSD9gx8DmU1LHvhIHkSN64zUJJS1kpMWAy55t_BL7tixPyk4zhcYNOg8aaiAZ89EYy8AQnX-FTx3ArdIdOFXxVoYJr8-B5tByozET-EEJWI3xfxPVg6G0c-LJP7uGpIXqVmFcxMUePBR5yiOzQSHTPhDh0OKOZ7eUyJY0jlZsmJl4oswhEYbFpd9nz_3I5wJ5A7EzUVQfBJpWoJO7RMbTsObTIgASUXcgK6oizP0MZQCQPWrnD5RymRHERa_UEpYqtvognWnkxeKhqIroPWw7bkWYs9eJJd3MdpzFUeo2UBwjVmnXoelqYHWNxbPpvgO9u1BSRqBeE7EKND7J-_zhjcQnGBDsyCFMMRwKLE7Mzs_mMluhDAMecy-JwTBJaWtei9sTV6vGDEUctrmr0OGAWdTSyJNvMcaPiDBLzcT77jF0CYYUeRZ86Hw6LcJpkhOorNi-3-gRDdUcJMZOfuQ0iyt62S5c7Q0tFscFfQeTT2U9niJqNasxJqdJ6JpISgbBA1-ZJ4l3xeMsUQqUms5ep1fnugg5jamq5b7vMGxlp560rDmM1Gj_WSzc-6tNNlxx1e0iprBLZHRXoVQxl2icD65UhEBt-g5e9OCd5Ahk0k2KjAUICnJMdHVPiRGoIHzZOtos8dePJMlqmIYCiq93cyeKbaexKz_2SEFX-0HO12fOHKGCglbEnuaJxNuexZMGhisnPeHSqlBCuPnG2qwBIkBZIDVPPoOtWBiFZVsMGCD7wbyrUnaQD2V_6pCTMxyMZhuZJ5_YTnz3nRpZNoVQ7yxtrOyVC_dzL-HCxBN2NgKhmkhOLqnd_BD6jafAud5mKGEZY0VkgzHPKxCKBIpMxTEbJ8zihc38Gcj-Ps1SpR8cIgQL_2dZO86DAcyQrJT0VCnrgGRzd01VNcisdqw5jZnWGf3Cmy4UalnicjPJUG332SDH7uigBFhCxWswmvlakgmlFmGYsBiKbB4fFpTHePTjEJIZAxjABEJhGtexYEZ4jZ0rgFPYpNIZgHqNWicGlz9cZGOBKP-6b9G_z4PLqnewXvqPSSk5VKpU6FBKqCdl7Qg9wLSUDresuaWw1QsLVcljksVhE2OX04xqpRbgujJCVFQnB3BCl6BE-ISdD5kKGmioSNqqgGhxnPHu0EUHYe5GaMsWQcfxvCjjHVKcrHrzAHVrIrFNj0SS4Cdp-ACGTUzj6sG3X-oXX-sWuBfd-_K528K_Ia0JYsLwpg9Fa-4uYhtR2blR7QlLW5k22SdjqfsLEGWavCzpS2Gq4XqcG9ESUm9RKWJNTgwcAsu88CBOpHGxWpm0gXrlISifM1P_KJPty6xXH9mlGI_HRQO0zU447K8pxp3aUOOdqJ3yAqZTZfdbOEU-nqTaZjtgyNCUzUMuhEARy8SjTOIbCAsK53og_NA8uzs6uSksijl5enHI2RM8ITRlbjIHeWktsuA9bEcaSxPoeU_pwsrFuTrvr69sOJ1gWBcQP4bvGzEs_Dtqyr9uddbfT2dxqb2zsbm9014m_aXBbxATCS-OJbxUWAULE-gizEfqcv6EM1fb__Mu_0vNYaAT-Z-gATOs4dLtOByCeI0PKZzicnDAon8I3fmStuBmYTRKXSOdSBYGrPbdcvSaqnb2dPYduzD2xW8QSbwzHLDTZF-WEGQtPh8WwBUpkvRIB4P2fjENr2Y4jLJpTnqQg5CTXKl-FgHQ8yKgACzo0EDbjNz66Qobb3mdyVvxPHSCZULeyqiYz9oSCvhZEzstL6NiyFSTjmNcqlBeHvkHeOSVKsjySmbKZpwL-4WMA9wozDWfSgmrDuppaaq0YFiJ4KhozuLZEp8y1GCwsgxTyBQyMUHusZ1gG1JyavAQXi-m4N-nbkYTcw2zZTARFMINAhT5Eg3IcY8mVYB0XSSuT58HwQQhV0nZYXzEgh5qqP9CjYNcjGXBiakUg8UCJ4CbI9LweLjvSQZjdGGf96t3Vrw-49mF2Mx5bJMLXD4z_mjlWMswj3mdV0WzZ-MndJPCHKtNm-Me7j-bjA8Du_jrMUg7UmhAcsMwZc0lKFWoJVzwgf1XE-iZZBmwOHwuvIlk0TIWW6wzAi0uePM-Zt5evnN61k-YhvD8_Cd-Q1pMm4lKQ-N2qEVVLiqQIS2eRIqoWFbXabeUJry7MsvU8Zpm9fKzF1QVtpTbBLHitoPicQ7YUz7NxxkNC_EnpvlAPBk4g8EbcJUHOaF8c45KSj0FGTDkayYSMS3eLY8ApvOtdNpuwurcPbF-cQz29ANptJPuczwznUvL-AdEAXOVi7_26MJccH8ivRc2UPoNxzcuc5IBWs9aAMwW288hkpvvUeURAh4oWzATOfHPDDFFQZuzurUi7q4Z9Z0V6yXzMWL_D7WqB9bv54TLVFIWJI0rmrLD-iUylHgUDGyn88osDspwQNh7mwNQ-HgwOvpDN811fjWMK6Nz8pu1pr12xYQZCl-FGw2JjOnSGL7cyzBmzGKz8xHTvlKYcxzGXkZjPnReBxFrlDJfbR_lVF0Kh20e05TbXtZsH_Mf1HHCCYKSmFtOkpJh9ZATEyZ1C9ew-m45a4qBtQmdo1S1EW98XwX5fQb0u55QhVoBIENTHeg7p3mXi_0QZvzP3R9m-Zam_ZZm-zt53ZfooHgpYNbmk19lyRe8vks2bjbTLOjkfol24OBymY2k0Dx44I1eBuZ4cU8oG0j9SYdLOkrBdwEwIWdkTbCCaHPdT8oOiltB5SbBXGfDyQlHPE4l6HTTWUxizcS9z1MS9erZ3Jl5ezpKelxuPTBrUOzr6YCvaGjYyKIW6yoJ9ADrESRUFrnsk-qEmhHtNdp02mCAijOb8oSFLzwe8BW4xDi2qdqag0Xx4A26zcUwJSGpfoMJqi0TLlEk51r_-wOPPcCYUMeEBQ_mN8_CFvCx0ykUuhdumIYuI5uCbanefj37fPcT_Px_7QTzWxswHfM1S9wAbv6v3os7LNyrti8uc2lYf6zn5WA794mwCsQWbZ9o5BsDutioTFfUQVgTb_amqdIgFSrKoAXFZx7LqV3ULQy7eKNipqX48S9BiVixPYbuhMDbHY0p0GVuG-KZqPVWDPJztPjElQa5EzYWudWp6mDKW4MtSZeCbRbLMiKo5LnPNz6GW1vl0E5snSwzl-sN8HNkwZ_XBLnbd2FOkqHapQkyxw7zI7cjMGz2_fbYrj78eH45P305PmNR9Mp1BRDVOE_fPtnf1rOnNZHgjKJTDXt4_6lUZud7RCRiW-5RW8SzGg4V9Iz1qhE5mLBWOtRfdADq0BHVeqqnbeKX6aU6ZMerldm2nz0oNX7ahy8nbD-fq468Xb2KueDG5UG-TFyaGcyFXUS1H2_NFIMYqMVuCxG7TEW5UFLeqoPjSNN7WLKzQCr5Qpm6j6EmnPMOqhotV5L-8-PbydPB-q3N08yh7tq0NYj9UMrdlzPN4YkqMTfhcwHfQ1qwoPkoS4CF-sjhLFDudX9UUqBwSXO-4YcoSKyw_RGEcq1F68-nmtd97NOh7YeA_O570LjY-b_SHn65fffa3v2z_-uXN4dlmNE6OcmcnfnGz-6l_ebQrP6Vv_fD1be82_twLu4NPnz7vfdw0OyQUF0Q50auW5iVqcnMkYVW1OD4-FifShwMUR5dQ2OIg3MZbGVkh6uytrKmu2t_5B6cbZS_yV531-v46W4Oty4vxeJpOfblzfKuHx4ffXrw7uv7NO7n4tv357cVV39vZ3v6tc_re815fqM_d3a_j6eaQDC8kJcm0ieYGOYf9VIZd7K0XT7JqCLAKNciu_ZUZsLkx1idfr7eOrnvNg1PqxSVfAOL-3hByRboPJSoeDeOVk1MUjHL14tOt5WpcZuqWQEuawvoZkDuSMOuhs7ck_eeZe3vuWPvGnF_CiwAD7TmvY1BDvXK3qm1asJ2qBds5LtpjHZk5XI2OHJCy-7x-mnvp6QfvyIu7STQ6uoo2e2--XvXPTseD97ebL36Nr3vXnRv16dy_3ru-_XX47eLu6vg6-eMJjCSXFe0TjN1b6AJnRX0tgc1UKF7gpC5UYL1MJgxFxJxd24fiWfng2nseKl01ditNkUIgQ4Mny4RjqSPUBu3b8MVmC-kD-zFEZIm4llq6fw3u4uvxM4_tzyOi01HRM8wgD1icMr1ZMTVCNNP9t1uXku-W0xe3H96tf-r2k6kHU9np7sFYfrSdRFysB2O4JQjYbBJA4kwmzTy_MI43xjiSjzpRqiiNu7C4KWAHZdlvSzK3f1iV1Ofh9ta7D78lh8fNg2ZhB5rA30lo8CalC7vUS5lnRSXjJ-mgjLm8y5X79auBILCoVH8v_gZ-u7u3sWPTwDZt_iqmcsqhGgUG3nIOgyKEzq5jiBJXL1_cGX9PTZuUVR_JoO7kVtPT19rV3sjtj5U7ytuMWNp9I1L1d0ymieJUW9lUQ00xjgdSJzE_WtP5HOa-TKjKfFW-zljZxAKeMKEA8eOpwVhymAOU9KGHl0F0Q2E0wVFf9fMhVwfGKpPW_pKKhWE8MVFADI2mdRSn-IjCmb4dp-jbwUOxOhAhP7lsX-PMcx5q0kmWBnpYLSTkWBMyMDbJ34my7Wx5Cq-QUfaa2oUKy-CKxomc_pwMyvPb_l1-dvh-Z92A0avYlwW_IkYtTvWCaGaN-9EopwZIyvsQG4e1esAlAiOVAaxVY6jtc1oLR-0ct7GxXci2O7ODH1b2P56tn__26eT69eWH5sEZBYO1-sjS13AAJm05ZkUlo9FFWJLTeyjLwLxnJ9nCFcdkFWrX7Rg02OZRBOZGtDfWEXIYKExvPXlpkGRLzN3WD5_hnZdcvrtIzk7ewgGdrX69j_0RuZQgAnIIsiqR-_Lo7Oz8cWerRIOUo4FuwFvn4fR-qr7TV_C1Yz44m11n0XcEdd9hXAVhdGZezana13cMlC08oQnbUyVm32T9btYubuLlLSXh2kfn5-3Kj221P5puOGwt9p0jpwOAyl8Ny-Cws2kN9VSUeBucvVmGs4kiJujnKQKLoGL8mhebQs5ouqRXas1WdEtIsWXqmtQ-8Lh4D6qzvi6-5jLktxtphWU8W6mQi1SqGpXO-blj6dxsr3c2nBN5gyPnDKtzJfWNth-aB3RHaP4AMnDHfljCy80VvNxc5WjuZ2WdyB9h5uZPMHM5iffp9pcXX9_nfj_Lv8aPBoprgs94nEvvb1J5MyJpF03eUpMVAiG3NeD5kIotP8Ubavl1Tl_-dlVdmXO0JqJ5QN-7p-oue4wjsd-aRAPjLMcRwQD0TDP2bvjIadKJTXhSIdN2UD6HZ97eta6gABPEd2zkh-mu2xzQu9G2WM6xFC4anuZBbc7jzsbsXggPvSSc7amy2P6RjPhL06vGGWN8u2veSKG3X-wLLTYnSLzvib3t1ftbql3Y420wVjHvbWNro7u9s7E9G1-Y1jcWvNoPQ1jP5CDO6th2gUtbfhcvoJ1hnHBCguDG8cxrx_e14H4Xv2vXJCvd9kqeU2zQ6Thcj5rjf3eW_8xMU7hiPq4_zMfeYjaaIIzdgiuzzOb_elePrhgvFqEmc9QWYOSqLOKytagJymFP5XqDMQlep73R3mnT4s4xvQu-TO6Airhtjd8AzzSVnqSXVb04MERB-l3PN02EePTzS0XvplzJ4TN69u-76_x0gGXaJl_z-gjJg1rCmZkZsyCv3y0evq8nql-1DSl6sard6a5v7m5uPQ-jZwqemkKrlxen5mXVutVb36v1jVAG8M3Z-TsnCIL5x3AXXdXWk8Ue7whBeae7sbu7CfNczjWwYNZCG_l9m8Mc4qk75eZM4ZK3yG_ACrn4BpWnvTDvuznsLmXlY0pZj5UfyDbPBh8d_NeL8M-ZLR25y7plP9r5Nu--oNEkIUAKw1DZNmifEL-cPveBm_1nzsbmzu7e-s769k6ns7O519nZ2iX9oAktcfrpyDid0rDXdjlzhFCMgBIDwTccAbeElVtfTNM_SNVWd7u7ubMHjd5Y397a3d3oblZEncQ5l0cKi-SKWpq2pO-SWyBDe2wwjrkfxMJIEpS_SGqUwNjUXcmFthqJhKjbEdXbzctLZRyrqMyjZh3f_2LeFYi8z57EYrGpTj4PIJufsa89bKPxInXFi7jfpzaHanL5hle9IaMXqjuYIgWC4lubjJNcp7eJlcurd2tF0weUmeTZ-o2lvdg1f085snZvz6TrzQHo5wPEm8-GCJoe0Y6fdQgmYWkqB3vsd84XfnfDyAL1GAkKRmDV978_3b-9p_yz8e7u3vXmTD9YlWkVT7jjtOgMNtWwQTi1L4hoY5abghHASCbwveYN0ax4-0qb3xbR5g0zKvRIkalQIU4ZUz2gheA3IFOF6YhfWtQBNRlBcoNM9NP4RnGnIU0aBfz2KVUKbNKent3iVhIKs6nZRCtl0l9hQD_RQa8qRNz7pfQfLDmW-j5glO9yDpY6vURGyQV6RNkBwApGM3yK_otYCnQn9hUM20rGpnusxhQXghEg3VJEETyBoZvyrTbQrSVF83cZ0Z3kYaiKfF1qi2M2YWfeMRtC0UQGXLDmNs6ppy0pXrJaEcZWJaJlNdTFl6gfrJv2VRg6oexrK7Zp2x-ndKdNukT99FpcBJTSoMYh-umqxDayUr6iUTRjhLFR8XpLba3XoVG9g2dDbHqZ9qhFOZ07YwmekPdeE4fU8v1O9rkaaVlgf_eE0jHsDYX5oaDGE_NzMBQs0jn24zRau6ftYEmQb1-PW85r2uRj3SjR1nmt21G8pvT3X6g9crE-WO-OtK8KkCRSkbUmRqabkl58hudHGAMZ6-f2XRr6dRxqMy9e8XlSqk7Ri-krHF6o12pVR3rL3ko4tzhIM9p0UvSVJ0m_j22TADfYrDhv88s7LdLMRjWvehMVZiRO2VbYVziABW2kZt4QKljI1iUMqODA4QYxx8r5bC9NZNCVeaPGbRwP-AXYgVJhYatMbZjeHfd9u7OWGTBIlXnjk2RvrIwum4Ty1BTO_vaDbvb-337Q7f_jD7q16XcO-WcP-YcbzS85_i8) [Answer] # [R](https://www.r-project.org/), 122 bytes ``` u = unlist(strsplit(readLines('http://www.stroustrup.com/C++.html'),'href="')) regmatches(u,regexpr('(https?://[^"]+)',u)) ``` [Try it online!](https://tio.run/##7XzZchvJdu2z8RVpnLBIRqMKBDjziFSQ1ES1ODRJUS3f8FUkqhJAiTWpsoogZDvC4e/wk5/9F/4T/8i5a@/MGjBQlDqO/XJ94rSIIYedO/ew9lDI/vKXQhyIIg4Dna/qPNNpGOSrmZL@@yBWenVlnOfpfrc7mUxcfJ0U@KdIXS@Juie//OKO8yhcWeusjDM1PGivrK21MjWKZO6NMbfo4I16SLPVlVVaRr/AQv/n/7b/4Ze1lU6xtvaXv7Tb7ee0xGHr@Rhb4k8e5KE6vK522hfY5nnXfNx6rvMp/fWDe9eXU/GPrb9Jpe8H8Wh/3d1S0Z9bfzNIMl9lDg/c10kY@PWHk8DPx/v99IE@kt7dCLvEvuMlYZLtZ6PBan@r3@n3e53e9sYaxtjxW@s8YxgmMt/PgtE4b/1z63nX0vK8a0kfJP5UDEa82kH79evXx6@P2/jcU3GuMryQwrApiH31wKxrH46TSD3vysPWP9Xfl4xtH/LZZ78c6M9D@dV@//rot@Xf9@2AXHnjOPBkKJYMTWWqMm1HpsUgxMA8SGI9P/Djm37PDqOXwkycH7WZj@2gG9B9@X7@@zwpso1yBF4vni3NklEmowj3acdd1p/MD/ZjZQe9fPZqgQtBYr/Eq/kvA7qP@0BNyrPXH8wPvQ98lZTDzJv5IV@LJFflEPNmfohM04q3dmDzo/nhrCtQlVGQj4sB61qgEy9NuydpepJk6k0BSkLSz@4gTAbdSGocYPFbN/Lbh6Pq7fw@WDgNwloEqvc88Hm3ElzMvhOZCsE6L4nbIp@mCq8jOVLdNB617XpDeU/fOxv9h42@S180pX/cO3w@OLwZK9Jo0bhY8V7GowJrQZN6h@J5dzCzeSpkGIziA1a8w9ZZ4gfDQPniwsuTgcpEb68j@uv9HkYetmjpQAspRipWmQydtMjSRCvREC0R2v3EBAzG2EEgtciTicx8LfQUvIx0qzkhH8u89bwImRWH2GCpOv4JhA1VpmJP4X7FQOU4gDgxzKR5ukjTJMsfme2FUuv2oS9zKeQAxk96JB0/Oj1J0vZhMviivNxJsoC45zdP/aPrMOMCD3JjXsyv4eJumBPg9kXWEUEsknyMg05gY/V@fQMVl4dJJnw1DGJipYx9UWi@BbpPZ6LoT/PA2m2d5mKMK9G4dty1J@Nc4GsVj/Kxpg0l/JMWE@yqMDDzcXNKRHAYYDo@iP0QZ1e4DCx4r8Ip75rzcBrZXJdkPlQPQT6FBOBdaqTCbd2MA9rLCwtfaRHJeAoN0DBbnsKwmMiFTvmlvPAWUeGNcVz4FFZsWF36NIiHmSRn5uVFRpN95Qrm300mYx0aI7DPAib4ip7LVm0JyPmqwTjRObg2UupOs0XQXkCS1m1cj1Oy3BlAAo8V/FChdSBje29YedHIEDmZVlNlVq0crwN@OZ6zbPn24XUq40CPH1sXyyq/yO3pkoyX/iK/Te/q9bLkHmt8kY7XbR9ePU0nzIlWOa9UfHO8NCw0/dc@/PBtoO6@e8IwSGWWD0PcPc/Ps3p@6Y@K7K4@EAs4LBbMz6lYXeq3j7/ILFaiBio0da0lI5IziDvJGJSC7h/aOApIGAIStQiaCYVIhmQG3danpBAQRAH1YBGt1KbD74z//lpABEmNjOYEeaeU6MaAFg2otjDjiBAvCwaKpFBE04bKJ8ldeXh@TfR3Ws0hs/CgcvmdFpYaQ8YzBXOJc/B0MZgaO6BL2sAXvOARZnI9hLSrVMahzKB5idEwqCABUXyfTckw08rglgIPyaIEg0xmU7d1FOsJLZjbaXR8ViLYkaTI2cEQUwfKaCMOX5tvnFF8F011HhvWr1EZLh7gj096U95ABbEWpo/CRGuivJ5ffsQb0jpmlgYcFD8KVNgviVNYvHslRrB0sVUBcrLzCkkA3qAIN8lG0DnzRsC26CA3GBRXNT@tMYV52648@OvKzi1qzU2SBp41adai2WX/FCooTkDY4L19ZeRFSW9Mb0rIOzurBjHtw7fJhG5@koFsMUoS2F2yYfEjU3WO9eEkDOWn1xdMffnpkglNaNY@PGq864gKInWEyj13yWwVQdt8he1e2Veli1gy2Eh0QKd6X758dOU3H06N7OCFqGYa7iVJuGx9Y4fMLPOah8O1QaumSyaULg4EvTEIqvJ6y9Y3iLh9eFsj4zleZnnghbTcSRKGyjh4MgnlF0tpgNMgBl6ZFxaNlqDDSFhTsmIZAY4uv@frxj1X4KQcGnzD7cAq0eBVnkX6FZfOu5yrxUU2grP6xl@skf1DkBdCHzL@xODIapqupiWNabhXTfAAwKV1dH59ajY8ighjwVSdL256CpAR5EWu1jqt43LCMaQejmr5MLYjL0/PzdA3KoN1fIquNTbGtZNqKoeYgNpA68L4j97e3i72EAADsMeZuodxiOmL/vr6hjH7@FJ@IUeVwjTAh2G1Xq8zt861SnNSkwwTez2Y8yEBZTJmZsKm@bNjlsTL/jrMVEZuNYSVg98R0vMANxmbJ9g0VhMhowFYA68jNpwpTIvQ3hgoJFTmgB6wF@NIc7RORSqfA4wwVHIYrMeGUIQV6/uGALfhQGi5P2orV4zEk8lljw5wmOCaWIx4UusJw61zSPi8FYMVIKiL8xuNclsf@AJ8nG5UAPiE08fQ0ezSXUJ9tSaNk5DWFn4mh/mMzXRb54h0jQfKGSoDJAOjCk9lOZAxQHecANcLSCZkS4Y11BmpnKFLMgQGxzeEffAvLpauQQyzxIAoOiQ4dH56fcOs8qQem1UIN1DK6o6wPQQgVso3pOBTpbWY2kGyMtg1MsJrRhPGCAJ1Qg7gV2UZn2AiPJG6Vw1nushvrBsFCPCUWKWUyFq1CBnkpXeI0CIGa31m9Zfc6wHC9/vdyajfQ@BW8qLyxWxTFqSDGQNRLmU5JzbyhzVpCHwQ3rmt9hkhJ7AlZn7gRAjSJMeF4NldDDdar4no7U5gl9xKbLmc216O7584UddPPN01uK8LLd/qxpube3039Yftw7OpIAxDlE/o0ljZhQZiDGGO@fgsBa2jNAtCMhJbTXE7FT70CLIVTuRUszhNzOd0Oos@6f1KBGRIiiZHI3gxDdvRODEEAjEIi0SFxo2tgSinGaL3qfBCyh2AW7xg2xiKdofR7WhsBQTHIaC6LDNFsvOy9ruv7pOw4Ms0G/JFlxBdM1WKdLVxmaDRI4nm8JKwrr1u68195TFNFKH66hF6Gom572RfxCqsVAahe@UH7Bj4Hirq2HfCQHIkb9xmqaSVrFQYMJ3zzT8D3/bFGflJxvD4gm6DxpqIBnz0xjLwBCdf4VMjuBX6hm4VfFWhgmvz4Hm0HKrcRP4QQlYjfF7G9WDofRL4ckDu4bkh@jExn0t7l3jIIbJDI9FHJsShyxnPHK@QGWkcqdw0NfFClUUgCstDu61HzPNfJwd4JBA7E3X1RbBJJSqJe3QNHXsPHTIgAWUX8pI64uwfoQwgkgc9esLlHKZEcRlrHQlKFVt9EataeQl4qBoiug9bDtuR5Sz1YrW/uY7bGCm9RsoDhGrNOnQ9K82OsTg2/TfEZ3dqikjUC0J2ocYHWb9/mrO4BBHBjhzClMCRwOIk7MxsPqMjBhDAiHNZHI5JQkvrWjR2fFw9fjLiaMRVrSMOmEUTjSzJNnPcqDiDxHyczz7jlEBYoUfRpy5GozKcJhmh@orNyz1@g6F6oISYyc/cBzFlb7uVy52hpabY4K8g9unupzNEzUY15qZUZT1TSYlAWKBbs5N4X25vmUKo1GT2cvV4vrukw5iaRu7bLvNWxtp554rjRI2jFb304OMBfemSo@6OKJVVIbuTEr2KkcwGZGC9KgRiw2/wspcUJE8gg2ZSbDRESIB7sqMTSpxIDeHDwcl2kadurS6jZRoCKLraLZw8uZsmrvTcLylR5Y88V5szf4gDBlo5e5IbGmdzHksWHKmE/IxHt0oJ4fodZ7tKgARpgdQw9Qy67mUQkmU1bIDgA/9mQj1IupD9pTulYRGNZRianS7tO757zo0sm0KpdpY31nZKhPqFl/PlYgn6NgaimklOLKre9yPwGU2Dd3nIVcwwworOAmGeUyUWCRSZjGE6Tl8kKd37Acj9HOWZUs9OEQIF/sHWTvuwxHMkKxU9NQp6Yg@O7ulVQ3JrHasvY2Z1hn9wpsuFGpY4SsdFpo0@e6SYA12WAEuIWC9mE1/u4/YBphmLgcj24XH50hjvIzjENIFAJjABEJhWvWykCM@RMyVwCvsUGkMwj1HrxODS/XUOBrjSTwYm/ds@vL55Lwel76i1klOVSmUOhYRqQvae0ANcS8VA67orGjutkHC1HJV5LBYRdjmDpEFqGa4LI2RVRUIwN0QleoRPyMmQuZChpoqEjSqoBscZzyM6iCDsvUhNlWLIOf43BZxTqtOVGy9whxYy6zRYNAnugq4fQMjkFI4@7Nq1fuG1frFrwb2fvm9c/GvymhAWLG/KYLTW/iKmIbWdG9WdkJR1@ZBdEramnzBxhjnrgo6Uthqu12kAPREXJrUSNuTU4AGA7AcPwkQqB5uVaxuI1y6S0gkz9b8qyb7ceiWJ3c1oJN4aqH1hynEXZTnu3I4Sl1zthA8wlTJ7zsY9YneaapPpiC1DUzIDtRwKQSAXrzJLEigsIJzrjflN@/Dq4uKmsiTi5NXVOWdD9IzQVLFFBPTWWWLDfdiKMJEk1t8xpU8nG5vmtL@@vu1wgmVRQPwQvitiXvpJ0JUD3e2tu73e5lZ3Y2N3e6O/TvzNgvsyJhBelkx8q7AIEGLWR5iN0Of8DWWotv/z3//rX//jv/7l32hTlhyB/xligNV6Do1pEgOc58iQkhoOZygM1KcYjvdtVDgDc1JiFSlepiB1jc2r1Rvy2tvb2XPoi7kd@2VA8dawzeKTfVFNmDHzdGOMXaBJ1jURCt7/g8FoI@VxgkULSpaUhJwVWhWPwSCdDHOqwoIODZjNII7vrxTkrveZPBb/00RJJt6tTatJj61S5NeB3HlFhR87toxkvPNaDfWS0Dfwu6BsSV7EMlc2/VRiQLwN4GNhq@FROtBvmFhTUG1UxEJEUGV3BheY6Ja5IIOFZZBByACEEW9HeoZlgM6ZSU5wxZiue5M@HUsIP2yXTUdQGDMMVOhDNCjREUkuB@ukzFyZZA@GD0Pok7bDBopROXRV/Zm2gnGPZcDZqUeiiSfqBHdBrueVcdmVDsP8znjs1@9vfn3Cv4/yuyiycIRfPzH@a@5YyTBb/JbXlbNl4ycPk8AfqVyb4R8fPpq3T6C77xdjlnKg0YnggGVOxHUpVaol/PGQnFYZ8JuMGQA6HC1ci2TRMGVaLjYANC7ZeZ4z765fO0e3TlaEgAC8Ez4hrSdNxEtB4nevxlQyKTMjLJ1lnqheVDQKuLU7vLkyyzaTmVUKc0WLmys6SmOCWfBWQfE5kWwpnmfjjJuE@JPSfaFGDNxA4I25VYI80r44xUvKQAY5MeVkLFMyLv0tDgSncLEP@WzW6rvNYPviEurpBdBuI9mXfGe4l4r3T4gGMCtXfL@vC3MZ8qH8WhZO6T0Y174uSA5oNWsNOF1g249MenpA7UeEdqhywUzg9Dd3zRAFVdruu2Vp97FhP1iWXjIfM9Yf8HW9wPrD/HCZaQrFxAlldB6x/qnMpB4HQxsu/PKLA7KcEDYe5sAUQJ6MEL6QzfNdX0UJRXVucdf1tNet2TCDo6uYo2UBMl06Y5h7GRYMXAxgXjUtPJUpx3XMpSXmE@hlNLFWO8Pl9lF@1aVQ6O4JHbnLxe32If9xPQecICypqc80rShmHxkDdnK7UDPFz6ajkT3omvgZWnUP0dbfC2N/rKrelHNKEyvgJAjqip6Duw@5@G9Rxh9MAFLKb1n@b1m6r7f3Q@k@CooCVk2u6/W2XHH0V0npzYbbVbGcL9EuXF4O07E0pAcPnLGrwFxPRpS3gfSPVZh28zTsljBTd@vGYAPRZDTIyA@KRlbnFWFfZcDLS0WNTyTqTdDYzGPMBr/MURP86tkGmmR5TUt6XmE8MmnQ0cnJB1vW1rCRQSXUdSrsA9Ahbqqscn1Hop/qRPiuyW7SBhNEhNGcP7dk5fmAt8AtxqFl6c5UNdpPH8Btt04pC0k9DFRd7ZBomVopB/y3H3j8Be6EwiZsMJLfOBlfystCu1zsUsxturKIaI7AqYD3@eTv@sf4/@dTP0gibcx8wK9Z6p5g4w81YDR5@VZlA3FdUO/qip6Tj@XQL8knEFuweaanYwjsbkszcVkUYUWwLaCqzolYoCTLQhDXdiyrflX3MOTirYKdmuqVWYIWU2NFBtsNhbGJHlOny9kyJHd1/6kaFuFsC4qpC3I5ai5@bVJzhCmRBF@WKgN/WWbMjKia6zKveR/qa53PObF5ssRQwj8sotiGOY9f7GLrjb1FimqXKsQUJyzKBA89ovHi/mBXnn49PY7O303PmNR9Mp1BTIVOE/zP9ngdWdOby/BOUCiHs/z27KhOyx2dnIFhhU@5Fc9iPFjYt9Kjbuh0xlLhWo/iO0CHjqD2SzV1W6/VICsoPUYN3a5t93lUw5cd6Hry7sOl@vjr1duEy15MLtTbJIeJ4VzNVVTQ0fZ@EYixSszWIXHabIwvaoo7dVB8bbpvGxZWaAVfKDO3VTamU57B/UnyX119e3U@/G2rd3L3LD/Y1gaxHytZ2FrmZTIxdcY2fC7gO2hr1xSfpCnwEO8sLlLFTudXNQUqhwQ3226YstQKy09RmCRqnN19unvjHz0bDrww8A9OJ0dXG583BqNPt68/@9tftn/98vb4YjOO0pPC2Ule3u1@Glyf7MpP2Ts/fHN/dJ98Pgr7w0@fPu993DQnJBQXxAXRq5bmJRpycyJhVbU4PT0VZ9KHAxQn11DY8iLc1jsZWyHq7bk/K0CXH5x@nL8sXvfWm@frbQ23rq@iaJpNfblzeq9Hp8ffXr4/uf3dO7v6tv353dXNwNvZ3v69d/6b5725Up/7u1@j6eaIDC8kJc21ieaGBYf9VItdbLAXq3k9BFiFumTX/ocZsLkR6bOvt1snt0ftw3NqyCVfAOL@1hByQ7oPJSq3hvEqyCkKRrl6cXdruVrXubon0JJlsH4G5I4lzHro7C3JAXrmuz030r4x59fwIsBAe86bBNRQw9y96po@bKfuw3ZOyx5ZR@YOl6RjB6Tsvmje5l52/sE78ZJ@Go9PbuLNo7dfbwYX59Hwt/vNl78mt0e3vTv16dK/3bu9/3X07erh5vQ2/fszGEmuLdodjN1baAVnRX0jgc1UKF7ipq5UYL1MLgxFxJxd24ziWfngAnwRKl13dytNkUIgQ4Mnq4RjpSPUC@3b8MVmC@kN@zFEZKm4lVq6/xPcxcfRgcf25xnR6aj4ADPIA5a3TI9XTI0QzbQA7jal5Ifl9OX9h/frn/qDdOrBVPb6ezCWH207EVfswRjuCwI2mwSQOJNJM/uXxvHOGEfyUWdKlfVxFxY3A@ygVPt9Reb2T6uS@jza3nr/4ff0@LR92C7tQBv4Ow0N3qR0YZ8aKou8LGf8QToobS4fCuV@/WogCCwqFeHLv4Hf7e9t7Ng0sM2dv06opnKsxoGBt5zDoAiht@sYosTNq5cPxt9T5yal1scyaDq5x@kZaO1qb@wOIuWOiy4jlu7AiFTzQZNpqjjVVnXWUGeM44HUScJba7qf48KXKZWab6pnGmubWMITJhQgPpoajCVHBUDJAHp4HcR3FEYTHPXVoBhxiSBSubT2l1QsDJOJiQISaDStozjFRxTONO84ZfMONsXqQIS8c9XDxpnnItSkkywNtFkjJORYEzIQmeTvRNmetiKDV8gpe009Q6VlcEXrTE7/mAzKy/vBQ3Fx/NvOugGjN4kvS37FjFqc@inR3Br3k3FBXZCU9yE2jhr1gGsERioHWKvHUO/ntBGO2jlua2O7lG135gQ/rex/f7F@@funs9s31x/ahxcUDDbqI0ufxQGYtOWYRyoZrT7CkoIeRlkG5j07yVavOCarUbvuJqDBdpAiMDeivbGOkMNAYXr0ycuCNF9i7rZ@@g4fvPT6/VV6cfYODuji8Wf82B@RSwliIIcgrxO5r04uLi5XelsVGqQcDXQD3roIp9@n6gd9Bb92zBtns@8s@o6g6TuMqyCMzsxrOFX7DI@BsqUnNGF7psTs46w/zNrFQ7y6pyRc9@Tyslv7sa3uR9MSh6MlvnPi9ABQ@aNRFRz2Nq2hnooKb4Ozd8twNlHEBP1xisAiqBg/68WmkDOaLumVWrNl3QpSbJm6JvUQrJQPQ/XW18XXQob8iCOtsIxnjyrkIpWqQaVzeelYOje7670N50ze4co5w@rcSH2n7Zv2IX0jNL8BGfjGvlnCy81HeLn5mKP5PiubRP4MMzf/ADM3f1q3v7z8@lvhD/Lia/JsqLgmeMDjXHqIk8qbMUm7aPOR2qwQCLmtAS9GVGz5Q7yhvl/n/NXvN/Urc4/WRLQP6XP3XD3kK7gS@6lJNDDOchwRDEHPNGfvhrecJp3YhCcVMm0b5Qt45u1d6wpKMEF8x0F@mu6mzQG9G12L5RxL4aLhaR825qz0NmbPQnjoFeFsT1XF9o9kxF@ZhjXOGOPTXfNYCj0CY59qsTlB4v2R2Nt@/HzpI5XN@yBSCZ9tY2ujv72zsT0bX5j@Nxa8xq9DWM/kIM7q2XaBa1t@Fy@hnWGSckKC4MbpzLPH3@vD/SF@N16TrPS7j/KcYoNez@F61Bz/@7P8Z2aawhXzcf1pPh4tZqMJwtgjuDLPbf7v6ObZDePFMtRkjtoCjHwsi7hsLeqEcthTud4wIsHrdTe6O11a3DmlB8KXyR1QEfeu8WPguabSk/TyuiEHhijIfmh/00mIrV9cK3pA5UaODmjvv@uv8@4Ay3RMfs3rIyQPGglnZmbCgrz@sHj5vp6oQd07pOjpqm6vv765u7n1IowPFDw1hVavrs7NE6tNq7e@1@gboQzg24vL904QBPPbcCtd3duTJx6fCEF5r7@xu7sJ81zNNbBg1kIb@X1XwBxi153qcKZwyUfkx2CFXHyMytNeWAzcAnaXsvIJpawj5Qeyy7PBRwf/HcX458KWjtxlLbMf7Xybd1/QaJIQIIVRqGwvtE@IX05f@MDN/oGzsbmzu7e@s7690@vtbO71drZ2ST9oQkecfzoxTqcy7I1TzlwhFCOgxEDwDVfAfWHV0cXPU7XV3@5v7uxBozfWt7d2dzf6mzVRZ0nB5ZHSIrmikaat6LvmPsjQXhuMY@EHiTCSBOUvkxoVMDZ1V3KhnVYqIep2RP2I8/JSGccqKveoWcf3v5gHBmLvsyexWGKqky8CyOZnnGsPx2i9zFzxMhkMqM2hnlw95tVsyDgK1QNMkQJByb1Nxkmu09vEyvXN@7Wy6QPKTPJs/cbShuyGv6ccWfdoz6TrzQXoF0PEmwcjBE3P6MQHPYJJWJrKwR77ncuFH98wskA9RoKCEVj1/R9P92/vKf8i2t3du92c6QerM61ildtOy/ZgUw0bhlP7lIg2ZrktGAGMZQrfax4TzctHsLT5gRFtHjOjQo8UuQoV4pSI6gEdBL8BmSpMR/zSoQ6oyRiSG@RikCV3itsNadI44EdQqVJgk/a0d4dbSSjMpmYTrZRJf4UB/U4HPa8Qc@@X0n@25FjqB4BRvss5WOr0EjklF2iLqgOAFYxm@BT9l7EU6E7tcxi2lYxNd6QiigvBCJBuKaIInsDQXfVoG@jWkqL5h5zoToswVGW@LrPFMZuwMw@ajaBoIgcuWHNbl9TTlpZPWj0SxtYlomU11MUnqZ@smw5UGDqhHGgrtlnXjzL6pku6RE31WlwFlNKgxiH6/arUdrNSvqJVNmOEiVHxZl9to9ehVT@IZ0NseqL2pEM5nQdjCVbJe6@JY@r7fi8HXI20LLA/fkLpGPaGwvxaUGvV/CYMBYt0j4Mki9e@03awJMi3z8gt5zUdckW3KrR12eh2FG8o/f1Xao9crA82uyPt8wIkiVRkbYiR6aakp5/h@RHGQMYGhX2ghn4ih3rNy@d8VivVKXsxfYXLC/Vao@pIj9pbCecWB2lGm06KgfIk6fepbRLgBptH7tv8/E6HNLNVz6sfR4UZSTK2FfY5DmBBG6mZx4RKFrJ1CQMqOHC4Qcyxcj7bSxMbdGUeq3Fbp0N@CnaoVFjaKlMbpgfIfd@erGMGDDNlHvsk2YuU0WWTUJ6awtn//qrb//6q2//Hv@rWpR875N8@pF9vbLfb/w8 "R – Try It Online") Output looks like this: ``` [1] "https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md" [2] "http://webhostinggeeks.com/science/programming-language-be" [3] "https://coderseye.com/stroustrup-the-c-programming-language" [4] "http://edutranslator.com/jazyk-programmirovanija-c/" [5] "https://pngset.com/uz-cplusplus" [6] "https://clipartflare.com/tr-cplusplus.html" [7] "http://www.isocpp.org/" [8] "http://isocpp.org/about" [9] "http://isocpp.org/about" [10] "http://www.isocpp.org/std" [11] "https://isocpp.org/std/the-standard" [12] "http://www.open-std.org/jtc1/sc22/wg21" [13] "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4492.pdf" [14] "http://www.stroustrup.com/resource-model.pdf" [15] "https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md" [16] "https://github.com/isocpp/CppCoreGuidelines" [17] "http://www.stroustrup.com/tour2.html" [18] "http://www.lextrait.com/vincent/implementations.html" [19] "http://www.hboehm.info/gc/" [20] "http://www.yl.is.s.u-tokyo.ac.jp/gc/dgc.shtml" [21] "http://www.geodesic.com" [22] "http://www.plumhall.com" [23] "http://www.peren.com/pages/products.htm" [24] "http://c-plusplus.org/index.php?option=com_mtree&Itemid=57" [25] "http://c-plusplus.org/" [26] "http://www.trumphurst.com/cpplibs1.html" [27] "http://www.boost.org" [28] "http://stlab.adobe.com/" [29] "http://opensource.adobe.com/wiki/display/gil/Generic+Image+Library" [30] "https://en.cppreference.com/w/cpp/links/libs" [31] "http://www.oonumerics.org/oon" [32] "http://root.cern.ch/root" [33] "https://dl.acm.org/doi/abs/10.1145/3386320" [34] "http://www.softwarepreservation.org/projects/c_plus_plus/" [35] "http://www.fltk.org" [36] "http://www.gtkmm.org/" [37] "http://www.qt-project.org" [38] "http://www.wxwidgets.org" [39] "https://isocpp.org/faq" [40] "http://www.parashift.com/c++-faq-lite/" [41] "http://www.jamesd.demon.co.uk/csc/faq.html" [42] "http://www.faqs.org/faqs/C-faq/learn" [43] "http://www.stroustrup.com/Tour.html" [44] "http://www-h.eng.cam.ac.uk/help/tpl/languages/C++.html" [45] "http://www.accu.org" [46] "https://www.accu.org/" [47] "http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms" [48] "http://www.gotw.ca/" [49] "http://curbralan.com/" [50] "http://www.artima.com/cppsource" [51] "https://www.youtube.com/watch?v=8aIqIBmNJyM" [52] "https://www.youtube.com/watch?v=SwJUPeWKRHo" [53] "https://www.youtube.com/watch?v=ERzENfQ51Ck&t=6s" [54] "https://www.youtube.com/watch?v=ooehrkYkGdA&fbclid=IwAR3_3bgYVF_d6j6KjHBO4nmpCu-7oDk8YbSC8aYrJdlGvAvo_Al2fYY_9W4" [55] "https://www.youtube.com/watch?v=PU-2ntDuF10&fbclid=IwAR15f5SRmmyryda7IvsgIBzDLCVXcMRz6_JRTbc766X1NQccGRe_28qmy4g" [56] "https://www.youtube.com/watch?v=43msMqV5CVA" [57] "https://channel9.msdn.com/Shows/C9-GoingNative/Bjarne-Stroustrup-Interview-at-CppCon-2018?fbclid=IwAR19rNUcCco2pnhCTn4AHqTbONmfQv4DKoVAV1keYPdV9VvKgzRxTIVpZMM" [58] "https://channel9.msdn.com/Shows/C9-GoingNative/Bjarne-Stroustrup-Interview-at-CppCon-2018?term=cppcon&lang-en=true" [59] "https://www.youtube.com/watch?v=DvUL0Y2bpyc&t=129s" [60] "https://www.youtube.com/watch?v=e_g65LUXpBI" [61] "http://daxue.qq.com/content/content/id/2937" [62] "http://bss.sch.bme.hu/video/bjarne-stroustrup-type-and-resource-safe-c" [63] "https://www.youtube.com/watch?v=aPvbxuOBQ70" [64] "https://www.youtube.com/watch?v=ZO0PXYMVGSU" [65] "http://www.computerhistory.org/collections/oralhistories/video/30/" [66] "https://www.youtube.com/watch?v=xcpSLRpOMJM" [67] "https://channel9.msdn.com/Shows/C9-GoingNative/Going-Native-42-Bjarne-Stroustrup-interview-at-cppcon" [68] "https://channel9.msdn.com/Events/CPP/CppCon-2015/Writing-Good-C-14" [69] "https://channel9.msdn.com/Events/CPP/CppCon-2015" [70] "https://channel9.msdn.com/events/CPP/C-PP-Con-2014/013-Make-Simple-Tasks-Simple" [71] "http://channel9.msdn.com/Events/CPP/C-PP-Con-2014" [72] "https://www.youtube.com/watch?v=jDqQudbtuqo&feature=youtu.be" [73] "http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote" [74] "http://channel9.msdn.com/Events/GoingNative/2013/Opening-Keynote-Bjarne-Stroustrup" [75] "http://vimeo.com/35326736" [76] "http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Keynote-Bjarne-Stroustrup-Cpp11-Style" [77] "http://techchannel.att.com/" [78] "http://techchannel.att.com/play-video.cfm/2011/3/7/Tech-Icons-Bjarne-Stroustrup" [79] "http://techchannel.att.com/index.cfm?SearchTag=Tech%20Icons" [80] "http://cdsweb.cern.ch/record/1204845?ln=en" [81] "http://portal.acm.org/toc.cfm?id=1238844" [82] "http://csclub.uwaterloo.ca/media/C++0x%20-%20An%20Overview.html" [83] "http://video.google.com/videoplay?docid=-3478907067117491758" [84] "http://video.google.com/videoplay?docid=5262479012306588324" [85] "http://technetcast.ddj.com/tnc_catalog.html?item_id=94" [86] "http://www.youtube.com/user/A9Videos/videos?flow=grid&view=1" [87] "https://www.youtube.com/watch?v=69edOm889V4" [88] "https://www.bell-labs.com/usr/dmr/www/" [89] "http://www.computerhistory.org" [90] "http://www.softwarepreservation.org/projects/c_plus_plus/" [91] "https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md" ``` ]
[Question] [ Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details. --- Santa and the Elves are secretly preparing for a new tourist train service, called "North Pole Railroads". The train will travel through various sightseeing spots near the North Pole. As a part of this project, they want to know how many seats they will need. They already have the list of travels for each passenger (given as "from station X to station Y"), which is thanks to the same magic that lets Santa know which children are nice. Each station is numbered from 1, starting from the North Pole. The Elves are arguing over how to determine the number of seats. One option is to absolutely minimize the number of seats needed. Elves will decide which passenger will take which seat. Two passengers with strictly overlapping travel cannot share a seat (e.g. one is `(1, 3)` and the other is `(2, 4)`), but a travel that ends at X is not overlapping with another that starts at X. ## Task Given the list of `X, Y` pairs that represent the travel of each passenger, output how many seats will be needed for North Pole Railroads. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` (1, 2), (2, 3), (1, 3), (3, 4) -> 2 1---2---3---4 AAA BBB DDD CCCCCCC (1, 3), (1, 3), (3, 6), (3, 6) -> 2 1...3...6 AAA CCC BBB DDD (1, 5), (2, 8), (6, 9), (5, 7), (4, 6) -> 3 1...2...3...4...5...6...7...8...9 AAAAAAAAAAAAAAA DDDDDDD BBBBBBBBBBBBBBBBBBBBBBB EEEEEEE CCCCCCCCCCC ``` [Answer] # [Python 3](https://docs.python.org/3/), 48 bytes * 48 bytes answer suggested by [Albert.Lang](https://codegolf.stackexchange.com/users/101374/albert-lang). ``` lambda a:max(sum(p<x<[q]for*p,q in a)for x in a) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHRKjexQqO4NFejwKbCJrowNi2/SKtAp1AhM08hURPIUaiAMP8XFGXmlWikaURHG@ooGMXqKEQb6SgYg2hDKG2so2ASG6upqaCsYMSFohxdmRmcxqrcFGq6BYg201GwBNGmOgrmINoEoc34PwA "Python 3 – Try It Online") --- # [Python 3](https://docs.python.org/3/), 50 bytes ``` lambda a:max(sum(p<=x<q for p,q in a)for x,y in a) ``` [Try it online!](https://tio.run/##bczLCsIwEIXhvU9xwM0MzKZJWy@0T6IuIhIsmDStFdKnjwSLorj6OPDPhHm69l4n2x7TzbjzxcDsnYl0fzgKTRubAbYfEWRA52E4jyjza6Qwdn4iSwcqBIoFpAQ6WyxqQcknZqyhVl/5b1a//ZtXy/dtthbsspVgky0/Zzo9AQ "Python 3 – Try It Online") [Answer] # [J](https://www.jsoftware.com), 24 20 bytes ``` [:>./[:+/1=,.I."#./] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrsSXayk5PP9pKW9_QVkfPU09JWU8_FiJ1M0yTKzU5I1_BSMEWiI2B0EQhTcEQyDZUMEZIgSTMgBAkZQjiQaSMgVKmChYKlgrmUEkjIG2qYAIxfcECCA0A) Found independently, but conceptually very similar to tsh's python approach. * We find the "insert before" index of every left endpoint within every reversed range * This will be 1 iff the left endpoint is contained within the range * We sum all the ones for each left endpoint, giving us a count of how many ranges that endpoint is contained in * Take the max of all the counts ## [J](http://jsoftware.com/), 24 bytes ``` [:>./[:#/.~@;<@i.@-+&.>] ``` [Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o63s9PSjrZT19eocrG0cMvUcdLXV9Oxi/2typSZn5CsYKdgCsTEQmiikKRgC2YYKxggpkIQZEIKkDEE8iJQxUMpUwULBUsEcKmkEpE0VTP4DAA "J – Try It Online") * Generates all stops for each person (not including the endpoint), so eg `1 4` becomes `1 2 3`. * Groups the combined list of all stops by stop, and get a count. * Returns the max count. [Answer] # [R](https://www.r-project.org), 40 bytes ``` \(x,y)max(table(unlist(Map(seq,x,y-1)))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3NWI0KnQqNXMTKzRKEpNyUjVK83Iyi0s0fBMLNIpTC3WAkrqGmkAAVR-VppGsYahjpGOoY6ypk6xhpGMMhCaamgrKCkZcEElDkBhIEiRlpmOGImkEFDEFagBKm-pY6FjqmEMVGENsWLAAQgMA) Takes input as two vectors - of starts and ends of the travels. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` rfĊ↑t ``` [Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJyZsSK4oaRdCIsIiIsIigxLCAyLCA2LCA1LCA0KVxuKDUsIDgsIDksIDcsIDYpIl0=) Takes a list of start stations and a list of end stations. ``` r # range (vectorises) f # flatten Ċ # counts of every element ↑ # get the maximum element by its tail t # tail ``` --- ## [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ∩÷rfĊ↑t ``` [Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiKnDt3JmxIrihpF0IiwiIiwiWygxLCA1KSwgKDIsIDgpLCAoNiwgOSksICg1LCA3KSwgKDQsIDYpXSJd) The original solution, taking a list of pairs. This transposes `∩` then item splits `÷` first, before continuing with the solution above. [Answer] # [Factor](https://factorcode.org/), 56 bytes ``` [ [ last2 [a,b) ] map concat histogram values supremum ] ``` [Try it online!](https://tio.run/##XY/LasMwEEX3/oq7LbSCOI8@8gEhm25KViaLqZAdU70ijQsh@NvdifDCVFqcQToM97akOaTp9HX8PHxABxd7a5LiZIyKKUTqiPvglSZrX0zbGs1wxBeVyHcmI5vrYLyWqbxmFj1zrzMo5yCIyTDfYuo9Y19V9wpy7nJXqDEKa6wLVzPX2AjHhff/f7fg0tvO@94Kd3gv3OK1cDP749SggaXMNRp6/n7CWbJH6e41MS4SP3SJHH7JDo@Gg1Rwg8N5emjSUP@o6Q8 "Factor – Try It Online") ``` ! { { 1 5 } { 2 8 } { 6 9 } { 5 7 } { 4 6 } } [ last2 [a,b) ] map ! { { 1 2 3 4 } { 2 3 4 5 6 7 } { 6 7 8 } { 5 6 } { 4 5 } } concat ! { 1 2 3 4 2 3 4 5 6 7 6 7 8 5 6 4 5 } histogram ! H{ { 1 1 } { 2 2 } { 3 2 } { 4 3 } { 5 3 } { 6 3 } { 7 2 } { 8 1 } } values ! { 1 2 2 3 3 3 2 1 } supremum ! 3 ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 20 bytes ``` M:($+:{@_Na,b}MUa)Ma ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCJGIGEgW1xuW1tbMTsyXTtbMjszXTtbMTszXTtbMzs0XV1dO1xuW1tbMTszXTtbMTszXTtbMzs2XTtbMzs2XV1dO1xuW1tbMTs1XTtbMjs4XTtbNjs5XTtbNTs3XTtbNDs2XV1dO1xuXXtQKHtcbiAiLCJNOigkKzp7QF9OYSxifU1VYSlNYSIsIn1WYSlcbn0iLCIiLCItcCJd) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~19~~ ~~17~~ 15 bytes ``` I⌈EθΣEθ№…⌊λ⌈λ⌊ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexIjO3NBdIF2gU6igEI5jO@aVARUGJeempGr6ZeWBVOZo6CjAdOZogDlQiUxMKrP//j47WMNRRMAXKahjpKFiAaDMdBUsQbaqjYA6iTXQUzDRjY//rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 2 bytes by using `Minimum` and `Maximum` to obtain the starting and ending stations for each passenger. Saved a further 2 bytes by only checking the starting stations instead of all stations, which allowed me to rewrite the expression to make it work on TIO as well as ATO. Explanation: ``` θ Input journeys E Map over passengers θ Input journeys E Map over passengers № Count of ⌊ Starting station of ι Outer passenger in … Range from ⌊ Starting station of λ Inner passenger to ⌈ Ending station of λ Inner passenger Σ Take the sum ⌈ Take the maximum I Cast to string Implicitly print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ‘r"FĠẈṀ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw4wiJbcjCx7u6ni4s@H////RhjoKQGQMRLH/o43BLDMgigUA "Jelly – Try It Online") *-2 bytes: Takes start stations and end stations as separate lists.* ``` ‘r"FĠẈṀ ‘ - increment r" - vectorized range F - flatten Ġ - group indices by value Ẉ - lengths Ṁ - maximum ``` [Answer] # JavaScript (ES6), 61 bytes *-3 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* ``` a=>a.map(g=([p,q])=>p<q&&g([p+1,q],m+=m<(g[p]=-~g[p])),m=0)|m ``` [Try it online!](https://tio.run/##dc1LCsIwEIDhvafIqiR0WkxfKnR6kZBFqG1Qmia14kq8ekyguBBdfcwwP3NVD7X2t4u7Z7M9D35Er7BTuVGOaqTCwSIZdq5dkkSHMeVhASZF01ItnMTsFWEMDO7Z0/jezqudhnyymo5UCA6kkEBEAaSM8s0SSCVDt/sRfB82H/8E9fbhGG2AnKI1kEO02kL/Bg "JavaScript (Node.js) – Try It Online") [Answer] # Python3, 237 bytes: ``` lambda x:min(f(x)) def f(x): q=[(x,[])] while q: a,b=q.pop(0) if[]==a:yield len(b);continue for I,i in enumerate(b): if all(y<=a[0][0]or a[0][1]<=x for x,y in i):q+=[(a[1:],b[:I]+[[*i,a[0]]]+b[I+1:])] q+=[(a[1:],b+[[a[0]]])] ``` [Try it online!](https://tio.run/##ZZDLasMwEEX3/opZSvVQ4jivKtE24G9QZyHXMhHI8gOH2F/vSqkpfYDgjDTnDoO6eby1Pj91w3KV74vTTVlpmERjPavZxHlSmRpiJRLopWITKuKUwONmnYE@vILGUvavXduxDQ9XWyuSUovZGleBM56V/PzR@tH6uwn9uh2gQAvWg/H3xgx6NEGJk0IWtHNsvkitNhROcJ9VRhc5PaMTzjFquejTsI9WmSAslSgoVerFYtSJ0lIVaejEVeGnGKQvg9PSDdaP7MoUyxC2HIFtEfLIbGWOsOMUfuGX@lc5fPOful@nniIPCG@Re4Rj5G6NLJ8) [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 9 bytes (18 nibbles) ``` `/.=~+!$_~>$,@$,$] ``` Takes input as lists of start stations and end stations. ``` `/.=~+!$_~>$,@$,$] !$_ # zip input lists together ~ # using function: >$ # drop inp1 elements ,@ # from range 1..inp2 + # now flatten the list of lists =~ # and group elements $ # by their own values; . ,$ # get the length of each group `/ # and fold over this list ] # returning the maximum ``` [![enter image description here](https://i.stack.imgur.com/gBf09.png)](https://i.stack.imgur.com/gBf09.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` r/ṖṬ)SṀ ``` A monadic Link that accepts a list of pairs of station numbers for the passengers and yields the minimum seat count. **[Try it online!](https://tio.run/##y0rNyan8/79I/@HOaQ93rtEMfriz4f///9EahjoKppo6ChpGOgoWINpMR8ESRJvqKJiDaBMdBTPNWAA "Jelly – Try It Online")** ### How? ``` r/ṖṬ)SṀ - Link: list of pairs of positive integers, P ) - for each (board, alight) in P: / - reduce by: r - inclusive range -> [board, board+1, ..., alight] Ṗ - pop (the passenger does not need their seat at their destination) Ṭ - untruth - e.g. [3,4,5] -> [0,0,1,1,1] S - sum (the columns of that) Ṁ - maximum ``` [Answer] # Excel (ms365), 111 bytes [![enter image description here](https://i.stack.imgur.com/wKzvC.png)](https://i.stack.imgur.com/wKzvC.png) Formula in `D1`: ``` =MAX(BYROW(A1:B5,LAMBDA(a,LET(x,SEQUENCE(MAX(a)-MIN(a),,MIN(a)+1),MAX(COUNTIFS(A1:A5,"<="&x,B1:B5,">"&x),1))))) ``` [Answer] # [Haskell](https://www.haskell.org/), 86 bytes ``` import Data.Ix import Data.List s=maximum.map length.group.sort.concat.map(init.range) ``` [Try it online!](https://tio.run/##Tcy7CoNAEAXQ3q@YIoXCsOAzSWGXJpA/EItBRJe4D3ZH8O832WDE6jBz78xM/j0uSwhSWeMYHsQknltyHl/Sc@JbRZtUqxKKLCyjnngWkzOrFf7bFIPRA3EMU6klC0d6GrOgSGpowTqpGS4Qbz10XZojFBlCWiCU0Xy3RKiyHqE7NqekOfw36v3HLdog3KM1wjVa/Zp9@AA "Haskell – Try It Online") [Answer] # x86-64 machine code, 33 bytes ``` 92 99 31 C9 57 56 AF 75 02 FF C9 AF 75 02 FF C1 FF CE 75 F2 5E 5F 39 D1 0F 47 D1 FF C8 75 E5 92 C3 ``` [Try it online!](https://tio.run/##ZVPBcpswFDyjr3il4wwkigfb2E1M3UvOufTUGcfTUSQB6mBBkWhxGX697hPGjtte3gjtvtW@leBVdZ9xfjwys4cAPvsBmWZF@coKSEm6Jl7L8wykaClI1hKPi@@4V9YgudviLdGytV@NZVaVGvlVY3KohTqvjDoxKmaM1JmskWM4M4J437QEExFPSD4omegfbEY8pUdsth6JKIjoL/hbFY8rq@G008IZ4PtqtCmc8335g42ToOBJzI10ERuH@G/mWloS@hAmxNi64RZsrSrolLaALbVFmhZJnxAUkbUG/8k/oWnAS20c663tllFwmHZfZlyPJ5sw6Ql5jzMXjZDw0Vihymn@iZCBwC9C0liMSZLOBeS0KGokGN7VQWz7sEtIfyGb7Q420JEupjHtuhmd97Sb0wXW2VAXNO77njrCaiBcQ6uxDoQlfRwIy0HhAeuKPmJd0g9Y45GGgThze6Z0EDqrKT6bMRHW2BJuLKzf7IXE86oaO9LAn6gX7VPMz04xLjt1A2I1Id6Bd5q5xWEiCgfcOHc9M54rfDe8FHLtO6oooTujMInmX1D0sAmCRhuVaSmA56y@DdNw297d7TB9@JmrQkJwgHco3z4twit9CCYKXg/oOBzstQ7Ex9HgnUcY9fH4m6cFy8zxfr@KseA/tcFWWfwB "C++ (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes an array of pairs of 32-bit integers with the address in RDI and the length in ESI, and takes the number of stations in EDI. This program runs backwards through the stations, keeping track of the number of passengers on the train, and the answer is the highest that number has been. In assembly: ``` f: xchg edx, eax # Switch the number of stations into EAX. cdq # Set EDX to 0 by sign-extending EAX. xor ecx, ecx # Set ECX to 0. # EAX will hold the current station, ECX the current number of passengers, # and EDX the highest number of passengers so far. next_station: push rdi # Save the value of RDI onto the stack. push rsi # Save the value of RSI onto the stack. next_passenger: scasd # Compare EAX and the value at address RDI, advancing the pointer. jne s0 # (That value is the starting station.) Jump if they are unequal. dec ecx # (If they are equal) Subtract 1 from the current passenger count. s0: scasd # Compare EAX and the value at address RDI, advancing the pointer. jne s1 # (That value is the ending station.) Jump if they are unequal. inc ecx # (If they are equal) Add 1 to the current passenger count. s1: dec esi # Subtract 1 from ESI, counting down from the number of passengers. jnz next_passenger # Jump back, to repeat, if it's not zero. pop rsi # Restore the value of RSI from the stack. pop rdi # Restore the value of RDI from the stack. cmp ecx, edx # Compare the current passenger count and EDX. cmova edx, ecx # If the current passenger count is higher, set EDX to that. dec eax # Subtract 1 from EAX, progressing backwards through the stations. jnz next_station# Jump back, to repeat, if it's not zero. xchg edx, eax # Switch the highest passenger count into EAX (to be returned). ret # Return. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~137~~ ~~134~~ ~~133~~ 132 bytes *-2 byte thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* ``` m;n;k;i;q;l;main(c,v)int**v;{for(;++n-l;k=0)for(i=1;i++<c;m=fmax(k+=atoi(v[i++-1])<=n&n<q,m))l=fmax(q=atoi(v[i]),l);printf("%d",m);} ``` [Try it online!](https://tio.run/##Pc1BCsIwFATQuwhKftOAFa3KNCeRLkIkJTRJbS1FEK/uNyK4mxkejFWdtcwRCT08RgRE45Ow5UI@zUWx4OmGSUDKpAJ6vaVv9bqCl7KxiNpF8xC91GYevFgueVZVS41Om9SMZSQKPzL@RUtlINymfODEan1dZYUXM1d84B2fuOZzTkfec/22LpjuzirEDw "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εŸ¨}˜D¢à ``` [Try it online](https://tio.run/##yy9OTMpM/f//3NajOw6tqD09x@XQosML/v@PjjbUMY3ViTbSsQCSZjqWQNJUxxxImuiYxcYCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1uP7ji0ovb0HJdDiw4v@K/zPzo62lDHKFYn2kjHGEgagkljHZPYWB2FaCgXJmgGJaFSpmBdFkDSTMcSSJrqmANJE5CCWAA). **Explanation:** ``` ε # Map over each pair of the (implicit) input-list: Ÿ # Pop the pair, and push a list in the inclusive range of it ¨ # Remove the last item (the destination-seat) }˜ # After the map: flatten the list of lists D # Duplicate it ¢ # Pop both, and count how many times each occurs à # Pop and leave the maximum count # (which is output implicitly as result) ``` ]
[Question] [ Simpler version of [this](https://codegolf.stackexchange.com/questions/236812/triangle-of-triangles) ## Task You must create a program that outputs a triangle of a given size N. * A triangle is made of 3 identical triangles * A triangle of size N should be made of N lines * A triangle's line starts from 1 star, and increases by 2 stars each line ## Test Cases: ``` 1 -> * * * 3 -> * *** ***** * * *** *** ***** ***** 5 -> * *** ***** ******* ********* * * *** *** ***** ***** ******* ******* ********* ********* 10 -> * *** ***** ******* ********* *********** ************* *************** ***************** ******************* * * *** *** ***** ***** ******* ******* ********* ********* *********** *********** ************* ************* *************** *************** ***************** ***************** ******************* ******************* ``` ## Scoring: This is code-golf so shortest code size wins! Trailing whitespace is allowed Credits to Ninsuo for the [puzzle](https://www.codingame.com/ide/puzzle/may-the-triforce-be-with-you) [Answer] # Python 3, 74 bytes ``` lambda n:[print(i//n*f"{i%n*'**'+'*':^{8*n>>i//n}}")for i in range(n,3*n)] ``` [Try it online!](https://tio.run/##FcndCkAwGAbgW1lK2z7KgZQUN@KnJsZXvFvLieTaJ8/p4@9rdyhrH6Jth3iYc16MQNP7wLgUFwXIJg@nIEkkM0mymZ6a0HX/vW@irQuCBUMEg21VyEuCHqNVlY4f "Python 3.8 (pre-release) – Try It Online") Deera Wijesundara saved 2 bytes by suggesting `print`-based I/O instead of `"\n".join`. ## Explanation For each `i in range(n,3*n)`, we center `i%n*2+1` asterisks in `8*n>>i//n` spaces and repeat this string `i//n` times. | `i` | `i%n` | `i%n*'**'+'*'` | `8*n>>i//n` | `i//n` | | --- | --- | --- | --- | --- | | n | 0 | `*` | 4n | 1 | | n+1 | 1 | `***` | 4n | 1 | | n+2 | 2 | `*****` | 4n | 1 | | … | … | … | … | … | | 2n | 0 | `*` | 2n | 2 | | 2n+1 | 1 | `***` | 2n | 2 | | 2n+2 | 2 | `*****` | 2n | 2 | | … | … | … | … | … | * `i%n*'**'+'*'` is a byte shorter than `(i%n*2+1)*'*'`. * `f"{s:^{n}}"` is an icky but short way to write `(s).center(n)`. [Answer] # [Canvas](https://github.com/dzaima/Canvas), 11 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` *×[]:{│]∔/│ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=KiVENyV1RkYzQiV1RkYzRCV1RkYxQSV1RkY1QiV1MjUwMiV1RkYzRCV1MjIxNCV1RkYwRiV1MjUwMg__,i=MTA_,v=8) ##### Explanation: ``` *x[]:{|]+/| | Full code (replaced with ASCII) ------------+----------------------------------------- * | Push '*' x | Repeat <input> times horizontally [] | List of prefixes : | Duplicate { ] | Map over each element | | Palindromize horizontally with 1 overlap + | Add the two lists together / | Anti-diagonalize | | Palindromize horizontally with 1 overlap ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` NθF²«G⌊θ*↖‖O ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orLb9IQcNIU6GaizMgP6cyPT9Pw@pRT5eOQqGOgpKWElAFp29@WaqGVWiBT2paCYgflJqWk5pc4l@WWpSTWKABFKr9/9/0v25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input the size. ``` F²« ``` Repeat twice. ``` G⌊θ* ``` Draw half of a triangle. The first time, this draws the left half of the bottom left triangle; the second time, the left half of the top triangle. ``` ↖ ``` Move to the next triangle. (See below as to why this moves left instead of right. This command has no effect on the second iteration.) ``` ‖O ``` Reflect to complete the triangle. On the first iteration, this also reflects the current position to where it needs to be. On the second iteration, this also reflects the bottom left triangle to create the bottom right triangle. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ·ÅÉ'*×DāRúí.º«.c ``` [Try it online](https://tio.run/##ASQA2/9vc2FiaWX//8K3w4XDiScqw5dExIFSw7rDrS7CusKrLmP//zM) or [verify the test cases in the range \$[1,10]\$](https://tio.run/##yy9OTMpM/R/iquSZV1BaYqWgZO@nw6XkX1oC4en4/T@0/XDr4U51rcPTXY40Bh3edXit3qFdh1brJf/XObTN/j8A). **Explanation:** ``` # e.g. input=3 · # Double the (implicit) input-integer # STACK: 6 ÅÉ # Pop and push a list of all odd numbers below this # STACK: [1,3,5] '*× '# Map each to that many "*" as strings # STACK: ["*","***","*****"] D # Duplicate this list # STACK: ["*","***","*****"],["*","***","*****"] ā # Push a list in the range [1,length] (without popping) # (which is basically a list in the range [1,input]) # STACK: ["*","***","*****"],["*","***","*****"],[1,2,3] R # Reverse it to range [input,1] # STACK: ["*","***","*****"],["*","***","*****"],[3,2,1] ú # Pad the strings of the top copy with that many leading spaces # STACK: ["*","***","*****"],[" *"," ***"," *****"] í # Reverse each string in the list so the spaces are trailing # STACK: ["*","***","*****"],["* ","*** ","***** "] .º # Overlapping mirror each string # STACK: ["*","***","*****"],["* *","*** ***","***** *****"] « # Merge the two lists of lines together # STACK: ["*","***","*****","* *","*** ***","***** *****"] .c # Join each line by newlines, and centralize it # STACK: " *\n ***\n *****\n * *\n *** ***\n***** *****" # (after which the result is output implicitly) ``` [Answer] # Excel, 94 bytes ``` =LET(x,SEQUENCE(A1*2),a,REPT(" ",A1*2-x),b,REPT("*",MOD(x-1,A1)*2+1),a&b&REPT(a&" "&a&b,x>A1)) ``` [Link to Spreasheet](https://1drv.ms/x/s!AkqhtBc2XEHJnh0ulZdhbVmX3OTq?e=pSWBt1) [Answer] # [J](http://jsoftware.com/), 39 37 bytes ``` '* '{~](](=|.)/@,:{.)(>i.@-+/|@i:)@+: ``` [Try it online!](https://tio.run/##NYw9C8IwFEX3/IpHB5M0X0p1CbQ8FZzEwVUylJLSithSujX412ODONzL5cC5z5hp2kJpgYKELdg1SsP5fr1EmgNdPo45VgbNDUq7aM6qXqMSJmBvOQobObmdNBxfs5/e9eyhHsdpqJsuPebJr5w0yJKFD2GynZM2oOIi9UrzzZ74phugheI3KP2DA4lf "J – Try It Online") -2 thanks to Lynn! *Includes leading whitespace that can be removed with a few bytes.* Not super golfy but the concept is fun: ## how Let's take n=3 as our example: * `(>i.@-+/|@i:)@+:` Create a single triangle double the requested input size: ``` 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 ``` * `](..........{.)` Take the first n lines of that: ``` 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 ``` * `].......,:` And append it to the big triangle, auto-filling the extra rows with zeros: ``` 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 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 ``` * `(=|.)/@` Reverse rows of the little triangle and check where the planes are still equal: ``` 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 = elementwise? 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 v 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 0 0 0 1 1 1 0 0 0 1 1 1 0 0 0 0 0 1 0 0 0 0 0 1 ``` * `'* '{~` Convert to asterisks and spaces: ``` * *** ***** * * *** *** ***** ***** ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 114 bytes ``` def f(n,x=1):[print([n*(p:=" "),(t:=(s:=p*(~-n-i))+"*"+"**"*i+s)+p][x]+t)for i in range(0if x and f(n,0)else 0+n)] ``` [Try it online!](https://tio.run/##JY1BCsMgFET3PcXHlV8NGEKhCOlFjItAtBXKj0QXKaW9uo3tYhbDPN6kZ7mvNFzSVuviAwROah97NDZtkQq3JHgyIwOGihcz8mzGJPinoy4iSibYEcFElBllcnZ3smBYN4gQCbaZbp7rGGCHmZafXaN/ZA9aErrayOJzabDt1aDOqtfOnOD/HthEr7a/obtOxPB0KFrH@gU "Python 3.8 (pre-release) – Try It Online") ## Less-golfed version ``` def f(n, drawingTopPart=True): for i in range(n): space = " " spacing = space*(n-i-1) stars = spacing + '*' + '**' * i + spacing print(n*space + stars) if drawingTopPart else print(stars + space + stars) if drawingTopPart: f(n, False) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 70 bytes ``` ->n{a=[] n.times{|i|puts" "*n+b=(?**i-=~i).center(n*2) a<<b*2} puts a} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtE2OpYrT68kMze1uLoms6agtKRYSUFJK087yVbDXksrU9e2LlNTLzk1ryS1SCNPy0iTK9HGJknLqJYLpFQhsfZ/WrRp7H8A "Ruby – Try It Online") Prints the single triangle as it iterates while building up an array of double triangles. Then dumps a printout of the array at the end. [Answer] # JavaScript (ES6), 80 bytes ``` f=(n,x=y=h=n*2)=>y?` * `[--x+h?x>=y-h&x<=h-y^y<=n&x*x<y*y:(x=h,y--,2)]+f(n,x):'' ``` [Try it online!](https://tio.run/##ZcyxDoIwEADQna9wgl7pGcG4kB58iNFAkFoMaY0Yc/f1NY6G9Q3vMXyGdXzNzzeGeJtScqSCYRLyFHQN1ErX73TWnxG59B23JOhztuRRrmIp5KzZipZGMXkjiKaGS@l@CzRFkcYY1rhM@yXelVMVQPYvx42cNlIdANIX "JavaScript (Node.js) – Try It Online") ### Patterns Coordinates: * \$y\$ goes from \$2n\$ at the top to \$1\$ at the bottom * \$x\$ goes from \$2n-1\$ on the left to \$-2n+1\$ on the right The examples below are given with \$n=3\$. ``` x >= y - h x <= h - y XXXXXX----- -----XXXXXX -----X----- XXXXXXX---- ----XXXXXXX ----XXX---- XXXXXXXX--- AND ---XXXXXXXX --> ---XXXXX--- XXXXXXXXX-- --XXXXXXXXX --XXXXXXX-- XXXXXXXXXX- -XXXXXXXXXX -XXXXXXXXX- XXXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXX y <= n x² < y² ----------- XXXXXXXXXXX ----------- ----------- -XXXXXXXXX- ----------- ----------- AND --XXXXXXX-- --> ----------- XXXXXXXXXXX ---XXXXX--- ---XXXXX--- XXXXXXXXXXX ----XXX---- ----XXX---- XXXXXXXXXXX -----X----- -----X----- -----X----- ----------- -----X----- ----XXX---- ----------- ----XXX---- ---XXXXX--- XOR ----------- --> ---XXXXX--- --XXXXXXX-- ---XXXXX--- --X-----X-- -XXXXXXXXX- ----XXX---- -XXX---XXX- XXXXXXXXXXX -----X----- XXXXX-XXXXX ``` [Answer] # [Python](https://www.python.org) NumPy, 95 bytes ``` lambda n:where((t:=tril(1>tri(4*n)[::-1])[2*n:])^(t[::-1]&t[:,n:n+1]),*'* ') from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY1BCsIwFET3niIUsT-xFVtcSKBepK1SsaGR5ieEX6RncVMQvZO3MRBn84aZgXl-3EyDxeWlquY9kcqP38vYmeutYygfQ-97AJIVeT1CcQqAg0BeS5kXLa9LgbLlZ6AYbAIzlLgNXSZSwVK-Ut4ahpNxM9PGWU_if7N2XiNB0mCyu1uNYDoHSfSZgmLPg-J2WSJ_) #### Old [Python](https://www.python.org) NumPy, 99 bytes ``` lambda n:[r:=tri(n),z:=0*r,l:=1-r[::-1]]and where(bmat("z l r z;l r l r"),*'* ') from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LU1LCoMwFNz3FI9QMAmx6K6k5CTqIlaDKebDI1L0Kt0Ipb1Tb1OLHZjPYoZ5vOOchuDXp1H1a0omP3-uo3Ztp8HLCqVKaKlnYpGq4ChGqcocKynzsmm07-A-9NjT1ulEyQIjICyXn24kTPCMQ8YOBoMDP7k4g3UxYOL_q2NE67dl7cnpFqynTkdK9iwMLQu2Ye-u6-5f) Returns a numpy array of "\*"s and " "s. [Answer] # [Julia 1.0](http://julialang.org/), 86 bytes ``` n/k=1:n.|>j->((s=" "^(k-j))*" "*"*"^(2j-1)*s)^(1+(n==k)) ~n=n./[2n,n].|>l->println.(l) ``` [Try it online!](https://tio.run/##FYtBCsIwFET3nkK6mh9N6q@4EX4uIgZcNgmDWAUX0qvHlAePt5jJnzo/9Nsax2J6ZfjF7COw2LAfEorPIq6n6yRM2au4RRL0AJoVkd1KYxhvE4@893f18fma@a4MqNJWaJ/gvOmySU/S/g "Julia 1.0 – Try It Online") Golfing [David Scholz](https://codegolf.stackexchange.com/a/242928/101725)'s answer (cannot comment under other people solutions yet!) Basically got rid of `join` by nesting the `println` call. `println` also gives you trailing `\n` for free. Finally I removed `i` iteration index as it can be expressed in terms of `j` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 96 bytes ``` lambda n:'\n'.join(' '*(d:=2*n-1-i)+(c:='*'*(1+i%n*2))+(' '*d+' '+c)*(i>=n)for i in range(n+n)) ``` [Try it online!](https://tio.run/##DcpBCsIwEEbhq2QjM5NQoRVBAulJuomN0RH9E0I3nj5m9/h49Xe8Ci632noOW//E7z1FA08b6PwuCiZDlpMPi8U0TyqOdx/IDpydnmAXGURmXMmN1@1iWdcAyaUZNQrTIp4PhoNIr01xcObr6D8 "Python 3.8 (pre-release) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 54 bytes ``` .+ $** . $._$*_$.'$* $`*$`$.'$* ¶ _+ $&$%'¶$%' _ O` ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0VLi0uPS0UvXkUrXkVPXUVLQSVBSyUBwjy0jSseqERNRVX90DYgocAVz6XA5Z/w/78hlzGXKZehAQA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` .+ $** ``` Convert the input to a string of asterisks. ``` . $._$*_$.'$* $`*$`$.'$* ¶ ``` Create a triangle of asterisks indented by underscores. `$._$*_` is the string of asterisks replaced by underscores. `$.'$*` is the space padding on either side of the triangle. `$`*$`` is the triangle. ``` _+ $&$%'¶$%' ``` Duplicate each line. `$&$%'` ends up keeping the first line the same, while the `$%'` causes the second copies of the lines to have an extra copy of the triangle, but without the indent. ``` _ ``` Convert the underscores back to spaces. ``` O` ``` Sort the lines into order. This puts the lines with the most spaces first, thus grouping the top triangle's lines back together (and also the remaining lines of the bottom double triangle of course). [Answer] # APL+WIN, 41 bytes Prompts for n ``` (⌽0 1↓m),m←⊃(-⍳2×n)↑¨(m,¯1+2×m←⍳n←⎕)⍴¨'*' ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv8ajnr0GCoaP2ibnaurkAsUfdTVr6D7q3Wx0eHqe5qO2iYdWaOTqHFpvqA0UAMv3bs4DUX1TNR/1bjm0Ql1L/T/QJK7/aVyGXGlcxkBsCgA "APL (Dyalog Classic) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `C`, 35 bytes ``` λhd›×*;→ẋė:£ƛ←†;¥ƛ←†:?d‹nhd-ð*JȮJ;J ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJDIiwiIiwizrtoZOKAusOXKjvihpLhuovElzrCo8ab4oaQ4oCgO8KlxpvihpDigKA6P2TigLluaGQtw7AqSsiuSjtKIiwiIiwiNSJd) ## Explanation ``` λhd›×*;→ Simple Lambda λ Start lambda h Get head d› Double and add 1 ×* Repeat it "*" time ;→ Close lambda and set it to var. ẋė:£ƛ←†; Top triangle ẋė Make an empty list with length n and generate tuple (index, item) :£ Duplicate tuple and set it to the register ƛ Map through tuple of (index, item) ←†; Get var, call it and close lambda ¥ƛ←†:?d‹nhd-ð*JȮJ;J Bottom left ans right triangle ¥ƛ Get register (index, item) and start a mapping lambda ←†: Get var, call it and duplicate ?d‹ Double n and increment by one hd- Get head, double and decrement by one ð* Repeat space that many times J Join the left triangle row with spaces ȮJ Get second to last item (left triangle row) and join ;J Join the top triangle with the bottom triangles C flag centers everything with spaces. ``` [Answer] # [Julia](https://julialang.org/), 129 bytes ``` l="\n" △(n,k)=((i,j)->(" "^(k-j+1)*"*"^i*" "^(k-j))^(n==k ? 2 : 1)).(1:2:2n,1:n) ~n=print(join(△(n,2n),l),l,join(△(n,n),l)) ``` [Try it online!](https://tio.run/##Tcw7CkIxEEbh/q4iTDV/nCtOykB0IxKwzINRRMHqLsONuCM3EkURhFN9xanXXg56G6Mn2htNz/uDTRoSc5GKecvkKHOb60rhyVMu/idAZkupuZ0LLjoF1qwxxGCi0TAtlk7nYheux2L8PQeD9HfyZx/CWFg3GC8) I had a hard time with this one, any optimizations are highly appreciated! The function `△` takes two arguments `n,k` whereby `n` is the size of the triangle. The parameter `k` determines the number of whitespaces for each row of the triangle. I have not found a way to get rid of the `join` operator, which joins the array of strings with `\n` as a separator. This costs me 8 bytes already. [Answer] # [Julia 1.0](http://julialang.org/), 58 bytes ``` !n=1:2n.|>i->((s=' '^(2n-i))*'*'^2(~-i%n)*"* $s")^-~+(i>n) ``` [Try it online!](https://tio.run/##HcdBCsIwEAXQfU8xLUpmIhGTZaE5SqBQhS9hLE0FC6VXj@Lbvec7Y/SfWlsdfB/0uke4yFwGQyZxUAcRa6xJgQ@Hs4rtLJ1KJ8kdF0ZUqY/XQiAo@d7fGvqZUOY8btxC/p8X6JqVpbnrVL8 "Julia 1.0 – Try It Online") output is a list of strings [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 79 bytes ``` n->for(i=1,m=2*n,print(Strchr([32+10*(i<=n||i+abs(j)>m&&i>-j)|j<-[1-m..i-1]]))) ``` [Try it online!](https://tio.run/##JcyxCsIwEADQXzk6lLs2V5oWJ5v8hGPoEIXoFRND7CL036Pg@JaXfRG@5xrA1MQ2vAqK0SqaqUsqF0k7XvZyexR089TrsUNZTDoO6f31jRvZ2LZieaNjW9hpjsMgrNeViKrP@flBD2zhP3lofmjoDAE9KXBawazgpECPK9Uv "Pari/GP – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `C`, 12 bytes ``` d~∷×*øĊDZvṄJ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJDIiwiIiwiZH7iiLfDlyrDuMSKRFp24bmESiIsIiIsIjUiXQ==) ## How? ``` d~∷×*øĊDZvṄJøĊ⁋ d # Double the (implicit) input ~∷ # Filter-keep for only odd numbers (the number is implicitly converted into a range [1,n]) ×* # Repeat an asterisk that many times for each øĊ # Pad each with spaces to center D # Triplicate ZvṄ # Zip the top two copies together, and join by spaces J # Join these two lists together # C flag centers and joins by newlines ``` ]
[Question] [ [A001057](https://oeis.org/A001057) is one way to represent an integer as a natural number. It lists them according to the following pattern: ``` 0, 1, -1, 2, -2, 3, -3, 4, -4, ... ``` In this challenge, you'll take two distinct integers as input and return which is at a higher index in this enumeration. Take `-2` and `1` as an example: `-2` comes after `1`, so it would be returned. You may also choose to instead return the smaller integer, or one of two consistent values (such as `0` or `1`) to indicate which is higher or lower. Truthy/falsy values as output are not allowed. **Test cases:** ``` 0 1 1 1 0 1 0 -1 -1 -1 0 -1 -1 1 -1 1 -1 -1 1 -2 -2 1 2 2 -1 -2 -2 -1 2 2 ``` [Answer] # [Python](https://docs.python.org/2/), 20 bytes ``` lambda x,y:x*x>y*y-y ``` [Try it online!](https://tio.run/##NY0xDoMwEAR7v2LT2chEhFBZOj6SUBARK5YcgxDF3eudS0ExGk01mxyftfQ10rPm@ftaZrCXwA2P0kgrNdOj87h5tEqvUu4qZVANkzFx3cFIBTkY/EPOQIrgC0nY9lQO2HxNZXmzZYcRZ4hzIEK0OnZe95D6Aw "Python 2 – Try It Online") Checks whether \$x^2>y^2-y \$. Outputs `True/False` for whether `x` comes after `y` in the listing. Note that we're not asked handle the case `x==y`. To see that this works, note that each of the `x*x` value in the table is greater than all the `y*y-y` values to the left of it, but none to the right of it. ``` 0 1 -1 2 -2 3 -3 4 -4 ... x*x: 0 1 1 4 4 9 9 16 16 ... y*y-y: 0 0 2 2 6 6 12 12 20 ... ``` The idea is that the entries come in pairs `+n, -n` (except 0 once), so comparing squares works to check if one input has a bigger absolute value than the other. Then, changing \$y^2\$ to \$y^2-y\$ in the second entry, makes `+n` "lose" to `-n`, but is a small enough shift compared to the difference between consecutive squares that it doesn't mess up comparisons between different squares. [Answer] # [J](http://jsoftware.com/), 8 bytes ``` >&(-3^|) ``` [Try it online!](https://tio.run/##bY0xCsMwEAR7vWJJEUngM5bSCezGkCpVHpArjOWQJg9I/q7IPhtskeJgdxj2XulU64g2QKNCg5CPavT32zV1Z0OXx9cmq6Y2mPiprBqH5xvsEOEkz5GdkqKJSK/Z5KUJcBYUsNkm@xk2BZxNFpM3yDuzgIW5bPJf6AX6w3eB8PvN0uSDmX4 "J – Try It Online") Or verbose: `(x - 3 ^ abs(x)) > (y - 3 ^ abs(y))`. This maps the inputs to the following sequence to compare them in: ``` 0 1 _1 2 _2 3 _3 4 _4 5 _5 _1 _2 _4 _7 _11 _24 _30 _77 _85 _238 _248 ``` If sorted input as output is allowed, then 7 byte `/:*.@%:` is another fun way to sort `/:` the input list: `*.` generates `(length, angle)` pairs of the square root `%:` of `x` (which results in complex numbers for negative values): ``` 0 0 0 1 1 0 _1 1 1.5708 2 1.41421 0 _2 1.41421 1.5708 3 1.73205 0 _3 1.73205 1.5708 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` F>m€Θݱ ``` [Try it online!](https://tio.run/##yygtzv7/380u91HTmnMzjmw4tPH////RuoY6hrEA "Husk – Try It Online") Returns `1` if the second is larger than the first, `0` otherwise [Answer] # [Desmos](https://desmos.com/calculator), 21 bytes ``` f(x,y)=\{xx-x<yy,0\} ``` (Newline is required) *Edit: Just noticed that [xnor's answer](https://codegolf.stackexchange.com/a/231851/96039) is very similar to mines, but I found this independently.* Function is \$f(x,y)\$, and it returns \$0\$ if \$x\$ has a higher index, otherwise returns \$1\$. This seems to work, but I just randomly stumbled upon it, so I can't explain how it works. [Try It On Desmos!](https://www.desmos.com/calculator/v7pjc0sebx) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/aa6fqxkom4) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` ²?Ḣ+⇧ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C2%B2%3F%E1%B8%A2%2B%E2%87%A7&inputs=%5B-1%2C%202%5D&header=&footer=) Takes input as a list and returns [1,0] for first being bigger, [0,1] for second being bigger. ``` ² # [x^2, y^2] ?Ḣ # [y] + # [x^2+y, y^2] ⇧ # Grade up ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~29~~ 26 bytes Returns `True` if `a` is a at a higher index than `b`, `False` otherwise. ``` lambda a,b:a*a+(a<0)/2>b*b ``` [Try it online!](https://tio.run/##LY1NDoMgEIX3nmI2RKCQIt0Z60XaLiBIamLRAF309BSExcyX9978HL/43t0tWbjDM23qo40CxfSoqLpgNQlylbOmOsUlxJCHHliwgTA8MJG7YLwIXlVGjXiDPCFrxBsleXV291AuwupOhrED8Ev4bjH/sJgWk2Tv8KuLuEfSQCk@AzI9IKgTrO0Qkv4 "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 5 bytes ``` ²Ḥ_ṠỤ ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLCsuG4pF/huaDhu6QiLCLDh+KCrCIsIiIsWyJbWzAsIDFdLCBbMSwgMF0sIFswLCAtMV0sIFstMSwgMF0sIFsxLCAtMV0sIFsxLCAtMl0sIFsxLCAyXSwgWy0xLCAtMl0sIFstMSwgMl1dIl1d) -1 byte thanks to ovs -1 byte thanks to Unrelated String Returns `[1, 2]` if the first integer comes first and `[2, 1]` for the second integer. ``` ²Ḥ_ṠỤ Main Link; accepts a list ² x ** 2 Ḥ 2 * (x ** 2) _Ṡ 2 * (x ** 2) - sign(x) Ụ Grade up ``` ``` 0 => 0 1 => 1 -1 => 3 2 => 7 -2 => 9 3 => 17 -3 => 19 ... ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ȧ4*?±-⇧ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C8%A74*%3F%C2%B1-%E2%87%A7&inputs=%5B-1%2C%202%5D&header=&footer=) Oh yes, jelly port. Very fun. `⟨0|1⟩` for second integer being yes, `⟨1|0⟩` for first integer being yes. ## Explained ``` ȧ4*?±-⇧ ȧ4* # 4 * abs(input) [vectorised] # call this x ?± # sign_of(input) [vectorised - <0 = -1, =0 = 0, >0 = 1] # call this y - # x - y [vectorised element-wise] # call this z ⇧ # indexes of z in an order such that they would arrange z to be sorted ascending ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` Ḥc2Ụ ``` [Try it online!](https://tio.run/##y0rNyan8///hjiXJRg93L4Ew/v@PNtAx1NE11DHS0TXSMdbRNdYx0dE1iQUA "Jelly – Try It Online") Alternative grade-up solution. Uses `(2n)C2 = n(2n-1)` as the grade key function. This function maps `0, 1, -1, 2, -2, 3, -3, ...` to `0, 1, 3, 6, 10, 15, 21, ...`, i.e. the triangular numbers. This allows a shorter APL solution: # [APL(Dyalog Unicode)](https://dyalog.com), 5 bytes [SBCS](https://github.com/abrudz/SBCS) ``` ⍋2!+⍨ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9TbbaSo/ah3BQA&f=S1MwUDDkSlMwVDi0HkQDSSBfw0hR@1HvCk2QJFjICEgaKRgDSWMFEyBpAgA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f) [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs `true` for the first number being higher or `false` for the second. ``` ²+V>² ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=sitWPrI&input=LTEKMg) [Answer] # [COW](https://bigzaphod.github.io/COW/), 183 bytes ``` oomMMMmoOMMMmoOoomMMMmoOMMMmOomOoMMMmoOmoOmoOMMMMMMmoOMMMmOomOoMMMmoOmoOmoOMMMMMMmoOMMMmOoMOOmOomOomOomOomOomOoMOOMOomoOmoOMOOMoOmoOmoOMOOMoOmoOmoOMOoMMMOOOmooOOOmooOOOmooMMMmoomoOOOM ``` [Try it online!](https://tio.run/##jUyxDcAwDNp7TXsI4ojOEWPOd0iQqmSrhSywgVe9SmoAmph9SMqIDLDm5xdkPDt8hEn85l/24LOWjkv7XuUza2/VfT0D "COW – Try It Online") Returns the smaller integer. It increases and decreases both, the first to reach **0** (with precedence to the decreasing one) is the smaller. ``` [0]: n to be decreased [1]: n [2]: m to be increased [3]: m [4]: n to be increased [5]: n [6]: m to be decreased [7]: m i=>=>i=>=<<=>>>==>=<<=>>>==>=< | set up memory cells as above [ | loop until a cell reaches 0 <<<<<<[->>[+>>[+>>-=*]*]*]= | [0]-- [2]++ [4]++ [6]-- ]>o | print the redundant copy of the smaller moo ] mOo < MOo - OOO * OOM i MOO [ moO > MoO + MMM = oom o ``` [Answer] # [Python 2](https://www.youtube.com/watch?v=dQw4w9WgXcQ "I cannot be bothered to find a link to Python 2, so have a rickroll"), 30 bytes ``` lambda x,y:(x*x,x<0)>(y*y,y<0) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMHiNNuYpaUlaboW-3ISc5NSEhUqdCqtNCq0KnQqbAw07TQqtSp1KoEsiKKbzuUZmTmpCoZWQGU6SbaZeQWlJRqa1gVFmXkl0Up5-Uo6SvnZSrHRaRpABZq2thoVtrZJmrE6YOU6EFGIUQtuehroGOoYchnqAGkuAx1dQyDi0gVxITSYbwgVBxJGQASkjXSMQLIQri6YDzERAA) This is one of those irritating ones that can't be shortened with a loop because the loop is only over 2 items. The `abs(x)` -> `x*x` trick was taken from ovs' answer. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 6 [bytes](https://github.com/abrudz/SBCS) A port of [hyper-neutrino's Jelly answer](https://codegolf.stackexchange.com/a/231845/64121). Outputs are swapped. ``` ⍋×-4×| ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Fv9@HpuiaHp9f8T3vUNuFRb9@jvqme/o@6mg@tN37UNhHICw5yBpIhHp7B/9MVgGoUqoGyj3q3Rj/qnQfkpikA2bG1XBrpCgoGCgqGmgq2QBLMNQSKIHENFA6tB0sDKZAAkIIqQBZAVgE0AVULWMAIImAEswPMVzCCmYCqAGwmVAUA "APL (Dyalog Unicode) – Try It Online") `g` gets the *"higher"* number according to the output. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 19 bytes ``` Most@*SortBy[-# #&] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773ze/uMRBKzi/qMSpMlpXWUFZLfZ/QFFmXomCvkO6vkN1tYGOYa1OtaGOAZA00NEFcXQhPCAFkdKFUkZgyggipQuljWpr//8HAA "Wolfram Language (Mathematica) – Try It Online") -23 bytes from @att [Answer] # [C (gcc)](https://gcc.gnu.org/), 20 bytes ``` f(a,b){a=a*a>b*b-b;} ``` [Try it online!](https://tio.run/##jZHBToQwEIbv@xQjySaFbSOL8WCQvRifQohpS1mJym4KiUTCq4tToBU2HpZk0mH@@f6hg2RHKYehIJwKv@MJD/hBBIKJuB/KqoFPXlbEh24D@JhCo@rmlb9kkGChCynsKQAebD8FLGKq9fEaFhZGdQbN6YAI88ieC1i1ZyUblY/4YrKbGF7GHxyAfFPyXekJ9tL2OUrbhyeMe4/C8v3Om7HipIGYwWWVqxaxMJ7TR6jLb3UqiP0k/3YuBK4Sw243dtvl2WtwdJqXOOpZvJKFlcW/skbZ/CwQ/lpQKLgNXZJnjS0F8bZRDibYAbaY1WmFlzdmFDR1K9JJorKF/TQTe7h/paUYXdeWN86z3/TDjyw@@LEe2Ncv "C (gcc) – Try It Online") Port of [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [Python answer](https://codegolf.stackexchange.com/a/231851/9481). [Answer] # Scala, 37 bytes ``` _.maxBy(x=>if(x>0)x*2-1 else x.abs*2) ``` [Try it online!](https://scastie.scala-lang.org/ylWvG2RwRJ2SJUQJ2fi04A) Very simple, simply takes a list containing the two number, maps each to its index in the sequence, and finds the max according to that. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 bytes ``` ²+ḊỤ ``` [Try it online!](https://tio.run/##y0rNyan8///QJu2HO7oe7l7y/3D7o6Y1//9HRxvoKBjG6ihEG@ooGIBoIF8XLKALEzGEiYAYRlCGEUyJLpwFZhjpANXGAgA "Jelly – Try It Online") ~~Terrible~~ port of xnor's Python solution, also stealing from hyper-neutrino's Jelly solution ovs's output format (`[1, 2]` if `y` is greater, `[2, 1]` if `x` is greater). Takes input as a list `[x, y]`. ``` ² [x^2, y^2] + plus Ḋ [y]: ²+Ḋ [x^2 + y, y^2]. Ụ Grade up. ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes ``` I⌊Φθ⁼↔ι⌈↔θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczLzO3NFfDLTOnJLVIo1BHwbWwNDGnWMMxqTg/p7QkVSNTU0fBN7ECrAouWKgJAdb//0dH6xrrKBjHxv7XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of two (actually arbitrary many) integers (which need not be distinct). Explanation: Outputs the element with the greatest absolute value, or the less of two elements tied for absolute value. Explanation: ``` θ Input list Φ Filter where ι Current element ↔ Absolute value ⁼ Equals θ Input list ↔ Vectorised absolute value ⌈ Take the maximum ⌊ Take the minimum I Cast to string Implicitly print ``` Actually a port of @xnor's Python answer would probably be only 9 bytes but that would be boring. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 14 bytes ``` f:{x*x>-y+y*y} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qukKrwk63UrtSq7L2f5qCgbXhfwA "K (oK) – Try It Online") ]
[Question] [ > > This challenge has officially ended. Further submissions will not be competitive (but are still welcome!). View the scores [here](https://github.com/Radvylf/koths/blob/master/Simple%20Race%20KoTH/results.md) > > > In this challenge, submissions ("bots") should be Javascript functions which try to win as many races as possible. In each race, bots will have a limited amount of energy which should be used to travel as quickly as possible over a distance of 100 units. ## Mechanics Each game will consist of a number of races, which are made up of a number of turns. In each turn, bots will choose a nonnegative distance to travel forward. The amount of energy consumed is equal to the square of the distance traveled (and bots will only travel as far as their energy level allows if they return a longer distance). At the beginning of each race, bots' positions are reset to 0. Once one or more bots reach a distance of 100 units, the race will end. Note that if a bot returns a distance which would place it further than 100 units from the start, it will only move as far as it needs in order to win. At the beginning of all races, bots will receive 100 energy in addition to any remaining from the last race. They will also receive a bonus of 1 energy for every unit they traveled in the previous race. ## Points At the end of each race, all bots will receive one point for every ten units they have traveled when the game ends (including fractions of a point). At the end of a game, the bot with the most points wins. Because it's likely bots will be optimized for a certain number of races, there will be 5 categories in which all bots will compete: 250 races, 750 races, 2500 races, 7500 races, and 25000 races. A bot's overall score will be the sum of their average score **per race** in each of these categories, making the highest possible score 50. ## Input/output Bots will receive the following arguments: `dist` (the distance they have traveled in the current race), `energy` (the amount of energy they have), `bots` (an array of the distances of all other bots as of the end of the last turn, shuffled at the end of each race), and `storage`, which is by default an empty object and can be used to store information between races. ## Example bot Follower will try to keep ahead of the average bot, by the average amount moved per turn. ``` { "Follower": function(dist, energy, bots, storage) { storage.turns = storage.turns || 0; if (Math.max(...bots)) storage.avg = ((storage.avg || 0) * storage.turns++ + bots.reduce((a, b, i) => a + (b - storage.last[i]), 0) / bots.length) / storage.turns; storage.last = bots; return (bots.reduce((a, b) => a + b, 0) / bots.length + (storage.avg || 1)) - dist; } } ``` ## Controller ``` // Each bot should be placed in this object var bot_data = { "Follower": function(dist, energy, bots, storage) { storage.turns = storage.turns || 0; if (Math.max(...bots)) storage.avg = ((storage.avg || 0) * storage.turns++ + bots.reduce((a, b, i) => a + (b - storage.last[i]), 0) / bots.length) / storage.turns; storage.last = bots; return (bots.reduce((a, b) => a + b, 0) / bots.length + (storage.avg || 1)) - dist; } }; var games = 0; var records = {}; // races: Number of races // log: Array of bot names to log information about, or null for no logging // Per-turn logging will only happen in games with less than 10 races // Per-race logging will only happen in games with less than 100 races // bold: Whether to use bold text when logging information var run_game = function(races, log = [], bold = true) { var perf_now = performance.now(); var bots = []; games++; for (let bot in bot_data) bots.push({ name: bot, run: bot_data[bot] }); var uids = new Array(bots.length); for (let i = 0; i < uids.length; i++) uids[i] = i; var race = 0; var turn = 0; for (let r = 0; r < races; r++) { race++; for (let j, i = 0; i < uids.length; i++) { j = Math.random() * (i + 1) | 0; [uids[i], uids[j]][uids[j], uids[i]]; } for (let b, i = 0; i < bots.length; i++) { b = bots[i]; bots[i] = { name: b.name, run: b.run, uid: uids[i], dist: 0, energy: (b.energy || 0) + 100, points: b.points || 0, storage: b.storage || {}, next: 0, inactive: 0 }; } turn = 0; while ((bots.every(b => b.dist < 100) && bots.some(b => b.energy > 0 && b.inactive < 3))) { turn++; for (let b, i = 0; i < bots.length; i++) { b = bots[i]; try { b.next = b.run( b.dist, b.energy, bots.filter(o => o.uid != b.uid).map(o => o.dist), b.storage ); if (log && log.includes(b.name) && races < 10) console.log("[" + race + ":" + turn + "] " + b.name + "(" + (Math.round(b.dist * 1000) / 1000) + "," + (Math.round(b.energy * 1000) / 1000) + "):", b.next); } catch(e) { if (log && races < 10) console.warn("[" + race + ":" + turn + "] " + b.name + ":\n" + (e.stack || e.message)); b.next = 0; } b.next = Number(b.next); if (Number.isNaN(b.next)) b.next = 0; b.next = Math.max(Math.min(b.next, 100 - b.dist, Math.sqrt(b.energy)), 0); if (!b.next) b.inactive++; } for (let b, i = 0; i < bots.length; i++) { b = bots[i]; b.dist += b.next; b.energy = Math.max(b.energy - b.next ** 2, 0); } } for (let b, i = 0; i < bots.length; i++) { b = bots[i]; b.energy = b.energy + b.dist; b.points += b.dist / 10; } if (log && races < 100) console.log( (bold ? "%c" : "") + "Race " + race + ":\n" + (bold ? "%c" : "") + bots.map(b => b).sort((a, b) => b.dist - a.dist).map( b => b.name.slice(0, 16) + " ".repeat(20 - Math.min(b.name.length, 16)) + (Math.round(b.dist * 1000) / 10000) ).join("\n"), ...(bold ? ["font-weight: bold;", ""] : []) ); } for (let i = 0; i < bots.length; i++) records[bots[i].name] = (records[bots[i].name] || 0) + bots[i].points / races; if (log) console.log( (bold ? "%c" : "") + "Average Points/Race (" + races + " races, " + (Math.ceil((performance.now() - perf_now) * 1000) / 1000) + "ms):\n" + (bold ? "%c" : "") + bots.sort((a, b) => b.points - a.points).map( b => b.name.slice(0, 16) + " ".repeat(20 - Math.min(b.name.length, 16)) + (Math.round((b.points / races) * 10000) / 10000) ).join("\n"), ...(bold ? ["font-weight: bold;", ""] : []) ); }; // Print and clear records for average scores var print_records = function(bold = true) { console.log( (bold ? "%c" : "") + "Sum of Average Points/Game:\n" + (bold ? "%c" : "") + Object.entries(records).sort((a, b) => b[1] - a[1]).map( b => b[0].slice(0, 16) + " ".repeat(20 - Math.min(b[0].length, 16)) + (Math.round(b[1] * 10000) / 10000) ).join("\n"), ...(bold ? ["font-weight: bold;", ""] : []) ); }; var clear_records = function() { records = {}; }; // Default race categories run_game(250); run_game(750); run_game(2500); run_game(7500); run_game(25000); print_records(); ``` ## Rules * If no bots have moved for three turns in a row, a race will end (scores will still be counted) * If a bot errors, it will lose a turn (i.e., not move) * Bots may not tamper with the controller or other bots, or be otherwise malicious * Bots should run in a reasonable amount of time * Bots must be deterministic; **no randomness** unless it's seeded by the bot's arguments **Chat:** <https://chat.stackexchange.com/rooms/112222/simple-race-koth> ~~**Bots due by:** Friday, September 4th, 12:00 UTC (08:00 EDT)~~ [Answer] # Rate control ``` { "Rate control": function(distanceTravelled, energyLeft, _, s) { if (distanceTravelled === 0) { for (let i = 100; i > 0; --i) { if (10000 / i > energyLeft) { s.travelSpeed = 100 / (i + 1); break; } } } return s.travelSpeed; } } ``` Each round uses up all of its energy to reach the finish line. Strictly better than "Slow and steady" as this entry will only ever use 1 or more energy per turn while also making sure to always make it to the end. Unoptimized, but still fairly fast. [Answer] # Slow and steady ``` { "Slow and steady": function() { return 1; } } ``` Baseline bot while I try to figure out what to do with this challenge. Doesn't adapt at all so it might start consistently losing if some sort of meta develops. [Answer] # Compensator A derivative from "SubOptimal", Compensator does not explicitly cater for the "Horde/Burst" strategy, rather it naturally compensates via the knowledge that if it was not first, then it may not have used all its energy in the previous turn and so it may have more energy than expected. To capitalise on this over supply of energy, this bot will use half of the excess energy to try and force a quicker race, but keeping the other half in reserve to try and stretch out the effect of the energy surplus over multiple races. It does seem to perform slightly better than its sibling (SubOptimal), and as the time of this submission, ekes slightly ahead of all other bots. ``` { "Compensator": function(dist, energy, bots, storage) { if ( dist == 0) { if (storage.targetStartingEnergy == undefined) { storage.targetStartingEnergy = energy; storage.nominalStartingEnergy = energy + 100; } else { if (energy <= storage.nominalStartingEnergy) { storage.targetStartingEnergy = energy; } else { storage.targetStartingEnergy = ((energy - storage.nominalStartingEnergy) * 0.5) + storage.nominalStartingEnergy; } } if (storage.raceNumber == undefined) { storage.raceNumber = 1; } else { storage.raceNumber++; } storage.energyConsumptionRate = storage.targetStartingEnergy / 100; } let step = 0; if (storage.raceNumber == 1) { step = 1; } else { step = storage.energyConsumptionRate; } return step; } } ``` [Answer] # precomputed ``` { "precomputed": function(dist, energy, bots, storage) { if (dist === 0) { let movements = Array.from(new Array(100), _=>1) const totalEnergyConsumed = () => movements.reduce((a,c)=>a+c**2,0) let currentIndex = 0 while(totalEnergyConsumed() < energy) { movements[currentIndex] += movements[currentIndex + 1] movements.splice(currentIndex + 1, 1) if (++currentIndex >= movements.length - 1) { currentIndex = 0 } } currentIndex = movements.length while(totalEnergyConsumed() > energy) { if(movements[currentIndex] > 1) { movements[currentIndex]-- movements.push(1) } else { currentIndex-- } } storage.movements = {} movements.reduce((a,c)=>{storage.movements[a]=c;return a+c}, 0) } return storage.movements[dist] } } ``` starts the race by calculating the full path to the end in order to move almost the same speed for the whole race, while still using all the energy available [Answer] # Ninety ``` { "Ninety": function(dist, energy, bots, storage) { if (dist === 0) { for (let i = 90; i > 0; --i) { if (8100 / i > (energy - 10)) { storage.travelSpeed = 90 / (i + 1); break; } } } if (dist >= 89) { return 1; } return storage.travelSpeed; } } ``` Aims to get 9 points per round. I'm not sure how well it does, but it's less likely to lose points to bots finishing faster than it (as compared to Rate Control, which this is forked from). [Answer] ## I love Randomness ``` { "I love Randomness": function(dist, energy, bots, storage) { storage.rand = Math.abs(dist ^ energy ^ storage.rand) + 1; return Math.abs(dist ^ energy ^ storage.rand) + 1; } } ``` [Answer] ## Pulse ``` "Pulse": function(dist, energy, bots, storage) { storage.round = storage.round ? storage.round+1 : 1; if(storage.round%500==0) return Math.max([...bots])+50 return Math.floor(Math.sqrt(energy/100)) } ``` Each step using only 1% of the energy. Every 500 turns, takes the distance of the first place in this moment, and adds 50 pass it. [Answer] # Jack in the Box Saves up its energy until it can beat the game in 40 moves, bringing the number of average moves per game down. ``` { "Jack in the Box": function(dist, energy, bots, storage) { if (!dist) { if (energy >= 250) { storage.speed = energy / 100 } else { storage.speed = .5 } } return storage.speed } } ``` # Simpleton Simpleton just wants to win :( ``` { "Simpleton": function(dist, energy, bots, storage) { return energy / (100 - dist) } } ``` # Steady Steady tries to go the same amount every turn, but doesn't like having extra energy. ``` { "Steady": function(dist, energy, bots, storage) { storage.turns = storage.turns || 0 storage.totalTurns = storage.totalTurns || 0 storage.games = storage.games || 0 storage.totalEnergyGained = storage.totalEnergyGained || 0 storage.previousEnergy = storage.previousEnergy || 0 if (!dist) { if (storage.games == 0) { storage.speed = 1 } else { storage.totalTurns += storage.turns storage.turns = 0 storage.speed = Math.sqrt(storage.totalEnergyGained / storage.totalTurns) + storage.previousEnergy / storage.totalTurns } storage.totalEnergyGained += energy - storage.previousEnergy storage.games++ } storage.turns++; storage.previousEnergy = Math.max(energy - Math.max(Math.min(storage.speed, 100 - dist, Math.sqrt(energy)), 0) ** 2, 0) return storage.speed; } } ``` [Answer] # Suboptimal The optimal solution where there is no means to affect other racers is to use all your energy to ensure that you finish first to both gain the most energy next round and to deny energy for your opponents. To this can be achieved by, spending 1.0 energy per turn on the first race and then 2.0 per turn for subsequent races (due to the extra 100 energy given for winning at 100 distance) This can be achieved by calculating the bot's energy / the distance to travel at the start of a race, storing this value and then returning this value each turn of the race. Now, that we know the optimal solution sans opponent effects, we need to consider the actions that opponents can perform that can affect others. In this game, the only real effect is the ability to force the end of the current race by being the winner. Since bots are allowed to hoard and accumulate energy, they can decide to minimise energy consumption and maximise energy production, sacrificing the chance to gain many points for any particular race and instead spending the accumulated points in one race to dominate the other bots and win that race. While this strategy does not yield high points overall, it does impact bots that are expecting the races to finish after 100 turns. The average turn count of a race is thus reduced. So to compensate for this effect, a sub-optimal solution is derived from the optimal solution by adding a factor that emulates the effect of bots that use this "hoard-burst" strategy. This factor is not able to computed unless the bot incorporates all other bot strategies and then performing an analysis to determine the factor. This is not really in the spirit of KoTH challenges and may be not allowed. So for this bot, a simple empirical analysis was performed to determine the factor at time of submission and adding in a scalar based on number of submissions that will increase the factor as more submissions on the assumption that later bots may be more interfering. Ultimately the formula is: distance\_per\_turn = starting\_energy / (( race\_distance + hoard\_burst\_factor) \* (1.0 + (number\_of\_bots - number\_of\_bots\_at\_submission) \* 0.1)) ``` { "Suboptimal": function(dist, energy, bots, storage) { if ( dist == 0) { storage.energyConsumptionRate = energy / ((100 + 10) * ( 1.0 + (bots.length - 26) * 0.1 )); } return storage.energyConsumptionRate; }, } ``` [Answer] ## Robin Hood ``` { "Robin Hood": function(dist, energy, bots, storage) { if (!dist) storage.move = [ [100, 1], [200, Math.sqrt(192 / 49) - 0.00695], [10000 / 49, (100 / 49)] ].sort((a, b) => Math.abs(a[0] - energy) - Math.abs(b[0] - energy))[0][1]; return storage.move; } } ``` This bot will do one of three things in a race: * **Move one unit per turn:** This is done in the first race of each game to ensure it has the full 200 energy it needs * **Move slightly slower than two units per turn:** This is done every other turn and saves just enough energy to allow it to... * **Move slightly faster than two units per turn:** This lets it finish one turn faster than the current competitors, and just barely undercuts a few of the previous winners (though Rate control is ahead by a hundredth of a point as of posting) [Answer] ## Collector ``` { "Collector": function(dist, energy, bots, storage) { if (!dist) { if ("turns" in storage) { storage.avg = ((storage.avg * Math.max(storage.races++, 0)) + storage.turns) / Math.max(storage.races, 1); } else { storage.avg = 100; storage.races = -1; } storage.turns = 0; storage.move = (energy >= 10000 / (storage.avg | 0)) ? (100 / (storage.avg | 0)) : 0.5; } storage.turns++; return storage.move; } } ``` Collector will default to moving at a rate of 0.5 units/turn. This is optimal for gathering energy. If it predicts at the beginning of a race that it can tie or beat the average with the energy it has, then it will try to do so. Currently loses to Rate control, but might be able to better adapt to new strategies. [Answer] ## Greedy/Greedier ``` { "Greedy": function(dist, energy, bots, storage) { return energy > 100 ? 2 : 1; }, "Greedier": function(dist, energy, bots, storage) { return dist + energy > 100 ? 2 : 1; }, } ``` Greedy will move 2 units/turn if it has at more than 100 energy otherwise 1 unit/turn. Greedier will move 2 units/turn if it thinks it will probably have enough energy to each the end otherwise 1 unit/turn. These were the simplest ways I could think of of using any bonus energy the bot might have. [Answer] # Calculated Sprinter Calculated Sprinter tries to run the full lap as quickly as he can with his current fuel left. Not smart enough to plan for future races, is just happy to be here for the run. ``` { "Calculated Sprinter": function(dist, energy, bots, storage){ var remaining = 100-dist; var energyLeftPerUnit = energy/remaining; return Math.sqrt(energyLeftPerUnit) } } ``` [Answer] ## (New) Accelerate ``` { "Accelerate": function(dist, energy, bots, storage) { return dist * 0.21 + 0.001; }, } ``` Calm down, I'm just experimenting with extremely simple bots. This bot is very easy to understand. It initially runs at speed 0.001 and accelerates quadratically. [Answer] # Surprise/Timing ``` "Timing": function(dist, energy, bots, storage) { storage.turns = storage.turns || 0; storage.games = storage.games || 0; storage.turns++; if(dist == 0) { storage.games++; estimated_game_length = Math.ceil( storage.turns / storage.games)+2; desired_speed = 100 / estimated_game_length; max_speed = Math.sqrt( energy / estimated_game_length); storage.speed = Math.min(desired_speed, max_speed); } if(storage.games < 3) return storage.games; return storage.speed; }, "Surprise": function(dist, energy, bots, storage) { storage.turns = storage.turns || 0; storage.games = storage.games || 0; storage.turns++; if(dist == 0) { storage.games++; estimated_game_length = Math.ceil( storage.turns / storage.games); desired_speed = 100 / (estimated_game_length - 3); max_speed = Math.sqrt( energy / estimated_game_length); if(desired_speed <= max_speed) { storage.speed = desired_speed; } else { storage.speed = Math.min(2, max_speed); } } if(storage.games < 3) return storage.games; return storage.speed; } ``` Calculate a fixed speed based on how long games are generally lasting. Timing then tries to hit the mark, while Surprise tries to beat it. While running tests with both of these, it became apparent that we probably need rules about collusion in this KotH, minimal though the interactions are. Surprise could make Timing do much better by sacrificing its own score to make the race length shorter, and could help it even more by only doing so at fixed intervals that Timing knows about. I'm not pulling these shenanigans now because I assume they're not in the spirit. [Answer] ## Mimic ``` { "Mimic": function(dist, energy, bots, storage) { if (!dist) { storage.last = bots; storage.rand = energy ** 3; return energy / (100 - dist); } storage.rand = Math.abs(dist ^ dist ** 2 ^ energy ^ energy ** 3 ^ energy ** 5 ^ bots.reduce((s, b) => s + b, 0) ^ storage.rand * (2 ** 31)) / (2 ** 31); var result = bots.map((b, i) => b - storage.last[i])[storage.rand * bots.length | 0]; // Fix RNG storage.last = bots; return Math.max(Math.min(result, Math.sqrt(energy / ((100 - dist) / 4))), Math.sqrt(energy / ((100 - dist)))); } } ``` Creates a list of every other bot's (effective) move in the last turn, and picks a pseudorandom one using a better version of HighlyRadioactive's PRNG. It ensures these values are within a certain range (which happens about half the time), so it doesn't do anything stupid. [Answer] ## Fast and not steady ``` { "Fast and not steady": function() { return 99999999; } } ``` [Answer] ## Faster than Slow ``` { "Faster than Slow": function() { return 2; } } ``` If you think this is a bad bot, then no. `Faster than Slow 48.951` [Answer] **Whole** Whole doesn't like fractional distances and will always move a distance that is an integer. ``` "Whole": function(dist, energy, bots, storage) { if (dist == 0) { if (energy < 110) { storage.lambda = function(distance) {return 100 - distance - 1;} storage.step = 1 } else { storage.lambda = function(distance) {return 200 - distance - 2;} storage.step = 2 } } let expEnergyPast = storage.lambda(dist); if (expEnergyPast + (storage.step + 1) ** 2 <= energy) { return storage.step + 1; } return storage.step; } ``` ``` [Answer] **Fourty-Nine** Fourty-Nine did take a look at Winner & Winner2 and recognized that 49 turns to win is better than 48 turns to win. But Fourty-Nine wants to win according to your rules. So Fourty-Nine doesn't sacrifice its averange distance to win many races. But it will never go faster than 49 turns to win. ``` "fourty-nine": function(dist, energy, bots, storage) { if (dist == 0) { if (energy < 110) { storage.step = 1 } else if(energy < 10000.0/49){ storage.step = 2 } else { storage.step = 100.0/49 } } return storage.step; }, ``` [Answer] # Predictor ``` { "Predictor": function(dist, energy, bots, storage) { if (!dist) if (energy == 100) storage.move = 1; else storage.move = (energy >= 10000 / (50 - bots.length * 0.25 | 0)) ? (100 / (50 - bots.length * 0.25 | 0)) : 1.3; return storage.move; } } ``` Predictor assumes that the more bots are added, the faster it needs to go to win. It collects energy over time, then sprints toward the finish line in a manner similar to Collector or Jack in the box. [Answer] ## DECISION3M8 Improvement on **UWUTM8** that works kind of differently Tries to predict when someone is speeding and tries to use more energy to gain more points ``` "DECISION3M8": function(dist, energy, bots, storage) { const checkpointPer = 5; if (storage.turn == undefined) { storage.turn = 0; } else { storage.turn = storage.turn + 1; } if (dist === 0) { if (storage.round == undefined) { storage.round = 0; } storage.round = storage.round + 1; storage.turn = 0; storage.maxAtPreviouscheckpoint = 0; storage.predictedTurnsLeft = 100; storage.travelSpeed = Math.sqrt(energy / 50); if (energy == 100) { return 1; } } else if (storage.turn % checkpointPer == 0) { let maxAtCurrentTurn = Math.max( ...bots ); let speederCheck = maxAtCurrentTurn / (storage.turn / checkpointPer) - storage.maxAtPreviouscheckpoint / ((storage.turn / checkpointPer) - 1); let speedOfSpeederPerTurn = maxAtCurrentTurn / storage.turn; if ((Math.abs(speederCheck) < 0.01) && (maxAtCurrentTurn > dist)) { //console.log(speederCheck); storage.predictedTurnsLeft = Math.ceil(100 / speedOfSpeederPerTurn) - (100 - storage.turn); storage.travelSpeed = Math.sqrt(energy / (storage.turn - speedOfSpeederPerTurn)); //console.log(storage.predictedTurnsLeft); } } return storage.travelSpeed; } ``` [Answer] **Winner** Winner doesn't care about your rules. Winner plays by its own rules. Winner tries to win ( = end at distance 100) in as many races as possible. ``` "Winner": function(dist, energy, bots, storage) { if (dist == 0) { if (energy < 10000.0/49) { storage.step= 0.5; } else { storage.step = 100.0/49; } } return storage.step; }, "Winner2": function(dist, energy, bots, storage) { if (dist == 0) { if (energy < 10000.0/48) { storage.step= 0.5; } else { storage.step = 100.0/48; } } return storage.step; }, ``` ``` [Answer] ## UWUTM8 Just like many bots i tries to finish as fast as it can by using as mutch energy as it can. It also doesn't try to finish at all at specific marks but tries to reach 9 point mark ``` "UWUTM8": function(dist, energy, bots, storage) { if (dist === 0) { if (storage.round == undefined) { storage.round = 0; } storage.round = storage.round + 1; if (storage.round % 2500 == 0 || storage.round == 250 || storage.round == 750) { storage.travelSpeed = Math.sqrt(energy / 90) } else { storage.travelSpeed = Math.sqrt(energy / 100) } } return storage.travelSpeed; } ``` ]
[Question] [ # Supreme Sum String Given an input string, return the word with the highest sum of each of its unicode characters. ## Rules * The input should be seperated by whitespace * The value of each word is based on the sum of each character in the word's UTF-16 code * The output should be the first word with the highest value (in case of duplicate sums) ## Examples ``` Input: "a b c d e" Output: "e" Input: "hello world" Output: "world" Input: "this is a test" Output: "test" Input: "àà as a test" Output: "àà" Input "α ää" Output: "α" Input: "🍬 隣隣隣" Output: "隣隣隣" Input: "💀 👻 🤡 🦇 🕷️ 🍬 🎃" Output: "🕷️" ``` This is code golf, so the shortest answer wins! Good luck :) [Answer] # [Perl 6](http://perl6.org/), 34 bytes ``` *.words.max(*.encode('utf16').sum) ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfS688vyilWC83sUJDSy81Lzk/JVVDvbQkzdBMXVOvuDRX87@1QnFipYKSSryCrZ1CdZqCSnytkkJafpGCUqJCkkKyQopCqpKOglJGak5OvgLQtJwUELckI7NYAYgSFUpSi0tAIocXHF6gkIgs8mH@pAaFD/Mn7gYSSxYCiWXtQGLq9vc7@oF07xog0des9B8A "Perl 6 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~77 69 59 58 56~~ 44 bytes A group effort now. ``` '^'=mapply sort(-sum^utf8ToInt^scan(,""))[1] ``` [Try it online!](https://tio.run/##K/r/Xz1O3TY3saAgp5KrOL@oREO3uDQ3rrQkzSIk3zOvJK44OTFPQ0dJSVMz2jD2/@EFhxdwJRZzJXKVpBaX/AcA "R – Try It Online") Convert to code points, sum each word, negate, (stably) sort, return first element. Technically the return value is a "named vector" whose value is the sum and name is the winning word, but this seems to follow the rules. If you want to return the winning word as a string, you'd have to spend 7 more bytes and wrap the above in `names()`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` ð¡RΣÇO}θ ``` [Try it online!](https://tio.run/##yy9OTMpM/V9TVvn/8IZDC4POLT7c7l97bsd/nf@JCkkKyQopCqlcGak5OfkK5flFOSlcJRmZxQpAlKhQklpcwnV4weEFColw7of5kxoUPsyfuBtILFkIJJa1A4mp29/v6AfSvWuARF8zAA "05AB1E – Try It Online") **Explanation** ``` ð¡ # split input on spaces R # reverse the resulting list Σ } # sort by ÇO # sum of character codes θ # take the last ``` [Answer] # JavaScript (ES6), 81 bytes ``` s=>s.split` `.map(m=s=>m=[...s].map(c=>t+=c.charCodeAt(),t=0)&&t<=m?m:(r=s,t))&&r ``` [Try it online!](https://tio.run/##ZYzBSgMxEIbvPsWQQ0mwpp6lqYiPUYTGbNpdSZolGepV8OBJRcFzK4gn7woe@0D2DbaTLahsh@Ef@P//myu90MnEqsajeShsM1VNUqMkU@0qnMBEel1zr8jzaiylTBetY9QID5WRptTxnLgz5KKP6lj0ejhU/tSf8KhSHwUZsTFhnoKz0oUZn3Km4RIMFGCZEPA3gwEwyw465dI6F@A6RFf8r@fyzuwCWFYJaDWgTfjLZKA1uv31ar0CvdffETncIzbL5xvYLJ@@Sd5eSd7vSF4@f74e6d5/kDzcto/yi5wwipot "JavaScript (Node.js) – Try It Online") [Answer] # jq, ~~61~~ ~~43~~ ~~57~~ 37 characters (~~57~~ ~~39~~ ~~53~~ 33 characters code + 4 characters command line options) ``` ./" "|reverse|max_by(explode|add) ``` Sample run: ``` bash-4.4$ jq -Rr './" "|reverse|max_by(explode|add)' <<< 'àà as a test' àà ``` [Try it online!](https://tio.run/##yyr8/19PX0lBqaYotSy1qDi1JjexIj6pUiO1oiAnPyW1JjElRfP//8MLDi9QSCxWSFQoSS0u@a8bVAQA "jq – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~74~~ 52 bytes ``` (-split$args|sort{$r=0;$_|% t*y|%{$r+=$_};$r}-u)[-1] ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0O3uCAns0QlsSi9uKY4v6ikWqXI1sBaJb5GVaFEq7JGFcjXtlWJr7VWKarVLdWM1jWM/f//v9LhBYcXKCQWKyQqlKQWlygBAA "PowerShell – Try It Online") *Thanks to mazzy for a whopping -22 bytes.* `-split`s the input `$args` on whitespace, pipes that into `sort` with a particular sorting mechanism `{...}` and the `-u`nique flag. Here we're taking the current word `$_`, changing it `t`oCharArra`y`, then for each letter we're adding it into our `$r`esult. That turns the string into a number based on its UTF-16 representation. For once, PowerShell having all strings be UTF-16 in the background is a life-saver! We then encapsulate those results in `(...)` to transform them into an array and take the last `[-1]` one, i.e., the largest result that's the closest to the start of the sentence. This works because of the `-u`nique flag, i.e., if there's a later element that has the same value, it's discarded. That word is left on the pipeline and output is implicit. [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~8~~ 7 bytes ``` eosCMNc ``` [Test suite](https://pythtemp.herokuapp.com/?code=eosCMNc&test_suite=1&test_suite_input=%22a+b+c+d+e%22%0A%22hello+world%22%0A%22this+is+a+test%22%0A%22%C3%A0%C3%A0+as+a+test%22%0A%22%CE%B1+%C3%A4%C3%A4%22%0A%22%EF%BF%BD%EF%BF%BD+%EF%A7%B1%EF%A7%B1%EF%A7%B1%22%0A%22%EF%BF%BD%EF%BF%BD+%EF%BF%BD%EF%BF%BD+%EF%BF%BD%EF%BF%BD+%EF%BF%BD%EF%BF%BD+%EF%BF%BD%EF%BF%BD%EF%B8%8F+%EF%BF%BD%EF%BF%BD+%EF%BF%BD%EF%BF%BD%22&debug=0) I know there's already a Pyth answer but I feel like this uses a pretty different approach ~~and also it's waaaay shorter~~ Explanation: ``` eosCMNc | Full code eosCMNcQ | with implicit variables added ---------+------------------------------------ e | The last element of cQ | the input chopped at whitespace o | sorted by s | the sum of CMN | the Unicode value of each character ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ḲOS$ÐṀḢ ``` [Try it online!](https://tio.run/##ASgA1/9qZWxsef//4biyT1Mkw5DhuYDhuKL///8iw6DDoCBhcyBhIHRlc3Qi "Jelly – Try It Online") ``` ḲOS$ÐṀḢ Ḳ Split input on spaces ÐṀ Give words that have maximum of: $ Monad: O ord(each character) S sum Ḣ First word that gives the max ord-sum. ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~55~~ 52 bytes ``` lambda s:max(s.split(),key=lambda w:sum(map(ord,w))) ``` [Try it online!](https://tio.run/##PckxDoMwDADAva/wFltCXboh8ZMurhIIIsYRTkX5DX/hYSlIVcfT5a1EnR@17541sbw8g7XCH7S75TQWdOComcLW/XZt7S0onFEX36xEVPMyzgV7dDGkpOB1gBhkUkd0@9@xHzuwAUMJVuDi@fUL "Python 3 – Try It Online") * -3 bytes thanks to Gigaflop for pointing out that no argument is needed in the `split` method. [Answer] # MATLAB, 57 bytes ``` s=strsplit(input('','s'));[Y I]=max(cellfun(@sum,s));s(I) ``` In my MATLAB R2016a all tests arepassed, except that emojis are not rendered properly. But characters are returned correctly [Answer] # [Java (JDK)](http://jdk.java.net/), ~~117~~ ~~97~~ 84 bytes -13 bytes thanks @Nevay. Apparently I didn't know I can also use `var` in Java. ``` s->{var b="";for(var a:s.split(" "))b=a.chars().sum()>b.chars().sum()?a:b;return b;} ``` [Try it online!](https://tio.run/##bZCxTsMwEIb3PsXJUzI03Ru1bGxMjIjhkjiti5tUtlNUVZWQGJgAgcTC0iIqJpZOIDFm73sw0TcIdpKmDdSyTvZ/3//r7AGOsTkILjKfo5RwgiyCaQNYpKgI0adwMjlOIl@xONfhVAkW9SDUmlWepe02YNYAqVAxf98QupVqvCF0MtnsTscowOsQ4oaxsMwF29KRI86URYDYttdBx@@jkJbtyGRo2V2vfj/CtucKqhIRgefOMoDaBOOYBcDj3m7AYvSJVHToxIlyRlpXPLJCJ3@ItMsnjBKP64D9nKH@kTLo7BxQ9Mo0k08QPPAhAEpsF@qr1QJCyRbsU85juIwFD/6iBiwaW1j1mQS9ERSVqsYbOBe3bLpIF4AH2YI2QEWvV5Au0@X/aSt8vargzfz2Hb6fX4t9wGP4XX9ne7yCzfzhS5fliy5vN7o8ffx83kMeuZnfXedpxm86RLfM98@yXw "Java (JDK) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) `-h`, 8 bytes [@Emigna approach](https://codegolf.stackexchange.com/a/173427/78039) ``` ¸w ñ_¬xc ``` [Try it online!](https://tio.run/##y0osKPn//9COcoXDG@MPralI/v9f6cP8SQ0KH@ZP3A0kliwEEsvagcTU7e939APp3jVAoq9ZSUE3AwA "Japt – Try It Online") --- Another Approach # [Japt](https://github.com/ETHproductions/japt) `-g`, 8 bytes ``` ¸ñ@-X¬xc ``` [Try it online!](https://tio.run/##y0osKPn//9COwxsddCMOralI/v9f6cP8SQ0KH@ZP3A0kliwEEsvagcTU7e939APp3jVAoq9ZSUE3HQA "Japt – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` ←→kΣw ``` [Try it online!](https://tio.run/##yygtzv7//1HbhEdtk7LPLS7/////h/m9axTeL98IQQA "Husk – Try It Online") First time using `key-by`. Pretty fitting here. ## Explanation ``` ←→kΣw w split into words k key on Σ sum of codepoints → take the last(maximum) key ← return the first in the group ``` [Answer] # Ruby, 45 characters ``` ->s{s.split.max_by{|w|w.codepoints.reduce:+}} ``` Sample run: ``` irb(main):001:0> ->s{s.split.max_by{|w|w.codepoints.reduce:+}}['àà as a test'] => "àà" ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664ulivuCAns0QvN7EiPqmyuqa8plwvOT8ltSA/M6@kWK8oNaU0OdVKu7b2f0FpSbFCtHqiQpJCskKKQqq6joJ6RmpOTr5CeX5RTgqIW5KRWawARIkKJanFJSCRwwsOL1BIRBb5MH9Sg8KH@RN3A4klC4HEsnYgMXX7@x39QLp3DZDoawYpBOoqTlSPBbqsoLqmJLWipCYtGkTF1v4HAA "Ruby – Try It Online") ### Ruby 2.4, 40 characters ``` ->s{s.split.max_by{|w|w.codepoints.sum}} ``` (Untested.) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 33 bytes ``` FHmCdmcd)Kczd aYu+GHmCdH0)@KxYeSY ``` [Try it online!](https://tio.run/##K6gsyfj/380j1zklNzlF0zu5KkUhMbJU2x0k4mGg6eBdEZkaHPn/v0dqTk6@Qnl@UU4KAA "Pyth – Try It Online") There is almost certainly a better way to do this, but I spent too much on it so this will do. ``` FH #For every array of letters in mCd #the array of arrays of letters [['w', 'o', 'r', 'l', 'd'], ['h', 'e', 'l', 'l', 'o']] mcd) #wrap that in another array [[hello"], ["world"]] Kczd #split input(z) on spaces ["hello", "world"] and assign it to K for later aY #append to list Y... " " silences the prints from the for loop. u+GH #reduce the list of numbers by summing them mCdH #convert each letter in the array to its int counterpart 0) #the zero for the accumulator and close for loop @K #get by index the word from K xY #find the index in Y of that number eSY #sort Y, get the last (largest) number ``` I would have passed a reduce into another map instead of using the for loop, but I couldn't get that to work. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` ≔⪪S θ≔EθΣEι℅λη§θ⌕η⌈η ``` [Try it online!](https://tio.run/##LYtBCoMwEEX3nmJwNYH0BK7cFFxIC54gGDEDcRqTUbx9OpZ@Pp@/eG8OLs8fF2vtS6GVcUqRBAdOh0ySiVc0FlpodXfTNX9qdAl3C9Ox/S5ZeGVP7CJGo7EQlH2rLtjLwH65bvxJ7DFYGN1Fm6rhZrtaJVABrQNZijT1ccYv "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⪪S θ ``` Split the input string on spaces and assign to `q`. ``` ≔EθΣEι℅λη ``` Calculate the sum of the ordinals of the characters in each word and assign to `h`. ``` §θ⌕η⌈η ``` Find the index of the highest sum and print the word at that index. [Answer] # Powershell, 66 bytes Straightforward. See [AdmBorkBork](https://codegolf.stackexchange.com/a/173430/80745)'s answer to found a smart using of Powershell. ``` -split$args|%{$s=0 $_|% t*y|%{$s+=$_} if($s-gt$x){$w=$_;$x=$s}} $w ``` *Note!* To correct work with unicode, save your script file with `UTF-16` or `UTF8 with BOM` encoding. Test script: ``` $f = { -split$args|%{$s=0 # split argument strings by whitespaces, for each word $_|% t*y|%{$s+=$_} # let $s is sum of unicode char code if($s-gt$x){$w=$_;$x=$s}} # if $s greater then previous one, store word and sum to variables $w # return word from stored variable } @( ,("a b c d e", "e") ,("hello world", "world") ,("this is a test", "test") ,("àà as a test", "àà") ,("α ää", "α") ,("🍬 隣隣隣", "隣隣隣") ,("💀 👻 🤡 🦇 🕷️ 🍬 🎃", "🕷️") ) | % { $s,$e=$_ $r=&$f $s "$($r-eq$e): $r" } ``` Output: ``` True: e True: world True: test True: àà True: α True: 隣隣隣 True: 🕷️ ``` ]
[Question] [ # Challenge : Given a word, check whether or not it is an isogram. --- # What : An isogram is a word consisting only of letters with no duplicates (case insensitive). The empty string is an isogram. --- # Examples : ``` "Dermatoglyphics" ---> true "ab" ---> true "aba" ---> false "moOse" ---> false "abc1" ---> false "" ---> true ``` --- # Input : You may accept input in any reasonable format The input will only contain letters and/or numbers, no spaces (`[a-zA-Z0-9]`) --- # Output : * `true` or any truthy value if the input is an isogram * `false` or any falsy value otherwise This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes in each language wins. [Answer] # Python ~~2/~~3, ~~36~~ ~~52~~ 48 bytes ``` lambda s:len(s)==len({*s.lower()}-{*str(56**7)}) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYKic1T6NY09YWRFdrFevl5JenFmlo1uoCOSVFGqZmWlrmmrWa/wuKMvNKNNI01F1Si3ITS/LTcyoLMjKTi9U1NbngcolJiSj83Hz/4lQUkeLEFCOgwP//AA "Python 3 – Try It Online") I take advantage of the fact that `set` contains only unique elements. By invoking the `__len__` method of each, I can determine whether `s` also contains only unique elements (ignoring case). EDIT: Updated to satisfy the previously-overlooked requirement to return False for numeric inputs. The set of all digits is encoded as `set(str(56**7))`. EDIT 2: Following [this user suggestion](https://codegolf.stackexchange.com/a/50719/79945), I now take advantage of unpacking the arguments to set comprehension. This formally breaks compatibility with Python 2. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` lDáÙQ ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/x@XwwsMzA///d0ktyk0syU/PqSzIyEwuBgA "05AB1E – Try It Online") **Explanation** ``` l # convert input to lower-case D # duplicate á # keep only letters Ù # remove duplicates Q # compare for equality ``` [Answer] # [R](https://www.r-project.org/), 41 bytes ``` !grepl("(.).*\\1|\\d",tolower(scan(,""))) ``` [Try it online!](https://tio.run/##DccxCoAwDADAvb@wUyIi6Bvc/UCXaIMKrZGkIIJ/r8ItpzUdi5I@kLnsEg1rsylfCTz02LchDG8I0XdFktysYCud0HmPiNUo/hwt5LLMxu7f6CbWTEW29Fz7sVr9AA "R – Try It Online") Regex approach. `!grepl(regex,scan(,""),F)` didn't work so I guess capturing doesn't match case-insensitively in R? I'm bad at regex in general, though, so I won't be surprised if I'm just doing it wrong... # [R](https://www.r-project.org/), 58 bytes ``` !anyDuplicated(c(el(strsplit(tolower(scan(,"")),"")),0:9)) ``` [Try it online!](https://tio.run/##JcgxCoAwDEDRs9gpAQdXnb1IbAMWYitJRHr6WhA@b/jaJR9K2uBiP2sy7BOVtj@35EjOCSKwgLnaOA5epb6sYJEKzCEg/izbitiN0qh/ "R – Try It Online") Appends the digits `0:9` to the (lowercased) list of characters and tests if there are any duplicates. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~25 23~~ 21 bytes -2 bytes on both thanks to Giuseppe ``` ->s{/(.).*\1|\d/i!~s} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664Wl9DT1NPK8awJiZFP1Oxrrj2f4FCWrSSS2pRbmJJfnpOZUFGZnKxUqyCskJJUWkqF1g2MSkRKIIMlBXSEnOKodK5@f7FqSgKUKQTDdE0o0obJuKQ/g8A) --- -2 bytes thanks to Kirill L. # [Ruby](https://www.ruby-lang.org/) `-n`, ~~21 19 18~~ 16 bytes ``` p !/(.).*\1|\d/i ``` [Try it online!](https://tio.run/##KypNqvz/v0BBUV9DT1NPK8awJiZFP/P/f5fUotzEkvz0nMqCjMzk4n/5BSWZ@XnF/3XzAA) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes ``` ḷo⊆Ạ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompkcdy5VKikpTlfRqQMy0xJziVKXa04vK/z/csT3/UVfbw10L/v@PVnJJLcpNLMlPz6ksyMhMLlbSUUpMAhOJQDI33x@oC8RLNgRSSrEA "Brachylog – Try It Online") The predicate will succeed if the input is an isogram and fail if it is not, outputting the lowercase Latin alphabet if it does succeed. Since Brachylog's `⊆` built-in predicate doesn't exactly match the ordinary relationship between a subset and superset, I had to spend a byte on sorting the lowercased input, but saved a byte on not having to explicitly check for duplicates in it. (If it didn't need to fail with numbers, we could just use `ḷ≠`.) [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` §=f√ü_ ``` [Try it online!](https://tio.run/##yygtzv7//9By27RHHbMO74n///9/cWKKEQA "Husk – Try It Online") ### Explanation ``` §=f√ü_ -- takes a string as argument, eg: "sAad2" § -- fork the argument.. f√ -- | filter out non-letters: "sad" ü_ -- | deduplicate by lower-case: "sAd2" = -- ..and compare: 0 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 bytes ``` ;v oC ¬â eUq ``` Explanation: ``` ;v ; // Set alternative default vars, where C is the lowercase alphabet v // Make the implicit input lowercase and reassign it oC ¬â eUq oC // Remove all items from the input that are not in the alphabet ¬â // Split into chars and select unique array items eUq // Check if the result is equal to the input split into chars ``` [Try it here.](https://ethproductions.github.io/japt/?v=1.4.5&code=O3YKb0MgrOIgZVVx&input=IkRlcm1hdG9nbHlwaGljcyI=) [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` kt2Y2X&X= ``` [Try it online!](https://tio.run/##y00syfn/P7vEKNIoQi3C9v9/9cTEpBR1AA "MATL – Try It Online") ``` k % Lowercase implicit input t % Duplicate that 2Y2 % Push lowercase alphabet X& % Intersection of alphabet and duplicate lowercase input X= % Check for exact equality. ``` [Answer] # [Python 3](https://docs.python.org/3/), 46 bytes ``` lambda s:s.isalpha()*len(s)==len({*s.lower()}) ``` [Try it online!](https://tio.run/##JY2xCsMgFEX3fsVrFjUEaekWcOveD2g7vKSmEYyKTygh@O3WkDvcw13ODWuavbuVSb2KxWX4IFBP0hDaMCMXrdWOk1Bq59aStP6nIxdZlMlHIDAOnuyu44LJf@0aZjMS64DhcDTuWPyD9LHH60727k9QE6JxibNmy00PW2aySquJUwdTvYWzgosQpfwB "Python 3 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) 2.0, ~~12~~ 11 bytes *-1 byte thanks to Nit* ``` v f\l â eUq ``` [Test it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=dgpmXGwg4iBlVXE=&input=ImFiYzEi) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 29 25 bytes ``` s=>!/(.).*\1|\d/i.test(s) ``` [Try it online!](https://tio.run/##BcFBCoAgEADAr1QnjTI8h516hhex1QxzxZUg6O82c5nHkC0h1znhAc2pRmrrFya4GLX89LEEUYEqI94sJsIIIqJnjg07lNtU9PHNZ7AkBz51zkQCvrYf "JavaScript (Node.js) – Try It Online") Thanks for the update on answer to *@BMO* , *@l4m2* , *@KevinCruijssen* -4 bytes thanks to *@KevinCruijssen* [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 16 bytes ``` Ci`(.).*\1|\d ^0 ``` Returns `1` as Truthy and `0` as Falsey values. Thanks *@Neil* for discovering and fixing a bug in my initial code. [Try it online.](https://tio.run/##K0otycxLNPyvquGe8N85M0FDT1NPK8awJiaFK87g/3@X1KLcxJL89JzKgozM5GKuxCQgSuTKzfcvTgWykg25HJ1AYolJScnJhkbGAA) **Explanation:** ``` C Check if the input matches part of the following regex: i` Case insensitivity enabled Check if part of the input matches either: (.) A character `C` .* followed by zero or more characters \1 followed by the same character `C` again | Or \d A digit ^0 Invert Truthy/Falsey, basically replacing every 0 with a 1, and every other value with a 1 ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 91 bytes ``` param($b)($a=[char[]]$b.ToUpper()|group|sort c*)[0].Count-eq$a[-1].count-and$b-notmatch'\d' ``` [Try it online!](https://tio.run/##Hcc7DgIhEADQq1iQACYQtbfyClqxFMMnUuwy48DGZu8@Jr7uEX4rj1bXVYSAYTMqWaPgHnIDDjGq5J/4Iqps7PFm3OkYyPOUzzZcon/g3qerHwXBXaPP/0IvKrmOc4OZm16KFhE9oNz0Dw "PowerShell – Try It Online") Naive solution, but I can't come up with a better algorithm. Takes input `$b`, converts it `ToUpper`case, casts it as a `char`-array. Pipes that array into `Group-Object` which constructs a object that has name/count pairs for each input letter. We then `sort` that based on the `c`ount and take the `0`th one thereof. We check that its `.Count` is `-eq`ual to the `.Count` of the last `[-1]` pair. If so, then the counts are all equal, otherwise we have a different amount of letters. We then `-and` that with checking whether the input `-notmatch`es against `\d` to rule out any digits in the input. That Boolean result is left on the pipeline and output is implicit. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ŒufØA⁼QƲ ``` [Try it online!](https://tio.run/##y0rNyan8///opNK0wzMcHzXuCTy26f///y6pRbmJJfnpOZUFGZnJxQA "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~57~~ 56 bytes ``` x=input().lower() print len(set(x)-set(`763**4`))/len(x) ``` [Try it online!](https://tio.run/##LYzLCsMgFET3fsUlGzXQFtIXBLLrvp/QWHPbCEZFb6n5emugi5mzOMyElWbvuqL9hEPTNCUPxoUPCbm3/otRSBaicQQWnUhIIsvdhvF6ObbtaZTysJksSx2zl4/wAOOAA2/PPQOKa48ZNWz/DDBrDNQHlVLhN4yLIv@2a5iNTpxx9VS1F39PWJnU1P1Rw38 "Python 2 – Try It Online") First it turn then input into a set, removing the duplicates, then remove the digits (encoded in ``763**4``), then check if the length is the same as the original input [Answer] # Java 8, ~~61~~ 39 bytes ``` s->!s.matches("(?i).*((.).*\\2|\\d).*") ``` **Explanation:** [Try it online.](https://tio.run/##jY7BboMwDIbvfQqPUzKp0dYrWqdNu64XjmMHE1IICwnCoVK18ezULVynItmWLX@//Td4wm1T/kzaIRF8ovW/GwDro@mPqA0criNAEYIz6EGLLPbWV0Ay5cXIyUERo9VwAA8vMNF2/0CqxahrQyIRr1aqRyEU1zzf/eV5yV0ip3QWd0PhWLzcOAVbQss2lkdf3yhnC9mZomlVGKLqeBOdF15pkXyYnn@Fyp272mpK5M3Z/zwWKxC8y7ThicyKS/r5LvT2vsLTAoybcboA) ``` s-> // Method with String parameter and boolean return-type !s.matches("(?i).*((.).*\\2|\\d).*") // Return whether the input does not match the regex ``` Regex explanation: [`String#matches`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#matches(java.lang.String)) implicitly adds `^...$`. ``` ^(?i).*((.).*\2|\d).*$ (?i) Enable case insensitivity ^ .* Zero or more leading characters ( | ) Followed by either: (.) Any character `C` .* with zero or more characters in between \2 followed by that same character `C` again | Or: \d Any digit .*$ Followed by zero or more trailing characters ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 bytes Anonymous tacit function. ``` (∪≡~∘⎕D)819⌶ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wSNRx2rHnUurHvUMeNR31QXTQtDy0c924ByCuouqUW5iSX56TmVBRmZycXqXECxxCQolQimc/P9i1OhIsmGYIY6AA "APL (Dyalog Unicode) – Try It Online") `819⌶` lowercase `(`…`)` apply the following tacit function on that:  `~∘⎕D` remove **D**igits from the argument  `∪≡` are the unique elements of the argument identical to that? [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 22 bytes ``` {!(.uc~~/(.).*$0|\d/)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJZq@79aUUOvNLmuTl9DT1NPS8WgJiZFX7P2vzVXcSJIgYZSYmKSkiaC64jKTUxKNkTmZ2SmFuWn51QWlCYXK2n@BwA "Perl 6 – Try It Online") No matches for some character then later the same character. Implicit function as a code block, match implicitly on $\_, invert book with `!`. Added `|\d` (ta Adam) but also needed `.uc~~`, which needed parentheses... ### Alternative with Bags, 23 bytes ``` {.uc.ords.Bag⊆65..97} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJZq@79arzRZL78opVjPKTH9UVebmamenqV57X9rruJEkAoNpcTEJCVNBNcRlZuYlGyIzM/ITC3KT8@pLChNLlbS/A8A "Perl 6 – Try It Online") This one normalises case then makes a bag (set with incidence counts). Subset or equal only true if all members are members of the comparison Bag, and all incidence counts are less than or equal to those in the comparison Bag. So any repeats or digits would make the comparison false. [Answer] ## Visual Basic for Applications (32 bit), 102 bytes ``` s=LCase(InputBox(u)):j=1:For i=1To Len(s):k=Mid(s,i,1):j=j*0^Instr(i+1,s,k)*(k Like"[a-z]"):Next:?j<>0 ``` Used the fact that in VBA `0^x` yields 1 if x is zero and 0 otherwise. Run in immediate (debug) window. Edit: as pointed out by Taylor in the comments this only works in 32 bit installs of MS Office. [Answer] # [Julia 0.6](http://julialang.org/), 29 bytes ``` s->!ismatch(r"\d|(.).*\1"i,s) ``` [Try it online!](https://tio.run/##yyrNyUw0@59m@79Y104xszg3sSQ5Q6NIKSalRkNPU08rxlApU6dY839uYoFGQVFmXklO3qOOGWk6ChpKLqlFQNX56TmVBRmZycVKOsoKIKCrq2unUFJUmsqllJgEE0QBKCoSsSkBq0hLzCkGKsnN9y9OxVSErCQxKdkQizHISpRAAjiUgJ2iqcn1HwA "Julia 0.6 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) with `-n -M5.010`, 17 bytes ``` say!/\d|(.).*\1/i ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJRPyalRkNPU08rxlA/8/9/l9Si3MSS/PScyoKMzORirsQkIErkys33L04FspINubj@5ReUZObnFf/Xzfuv62uqZ2BoAAA "Perl 5 – Try It Online") Perl 5 port of my [Julia answer](https://codegolf.stackexchange.com/a/167479/8774). [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~87~~ ~~85~~ 83 bytes * Saved ~~two~~ four bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` f(s,p,b,P)char*s,*p;{for(b=s;*s;++s)for(p=b*=*s>64;b&&p<s;b=(*s^*p++)&95?b:0);s=b;} ``` [Try it online!](https://tio.run/##bY7RS8MwEMaf3V9xPVmXpBmsoAMX41D2rg97EhGarN0Kaxt6BdGxv72mnbIOFrgc3/347js73Vrbthkj6aSRb9zuklqQFE4dsqpmRpMSpKKIeCedNkILeprfKROG7pGU0UzQp3BRxMOH@6VZzLgibdSxvd2kWV6msGbU1BLqlDi4Oi@bjGHG4APH5EtYDhrGG1h2vx@VKKE3xPOp7/u07PxcwgQmEoIg@5N@31mC1t0AloAIC0BgAUeuRkWSl4wfRjdrhqu0LpKm2u6/3S635GNi3oPEIAzfACR4CWYnUFSvlOIVkBgb4zXHZcJ/Ro9m3oSDDc8D8WJX5zt/3r8G7CQ8Ora/ "C (gcc) – Try It Online") [Answer] # Powershell, 32 bytes ``` param($s)$s-notmatch'\d|(.).*\1' ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` v ¶r\L â ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=dgq2clxMIOI&input=IkFiYyI) ``` v\n¶r\L â :Implicit input of string U v :Lowercase \n :Reassign to U ¶ :Is equal to? r :Remove \L : Regex /[^a-z]/gi â :Deduplicate ``` [Answer] # [Zsh](https://www.zsh.org/), 32 bytes ``` c=${#${(uL)${(s::)1}}};((c<$#1)) ``` [Try it online!](https://tio.run/##qyrO@J@moVn9P9lWpVpZpVqj1EcTSBZbWWka1tbWWmtoJNuoKBtqav5PTc7IV1CxV1AxrOXiSlMoLE8tKqmEMECsIiDTJbUoN7EkPz2nsiAjM7kYKJKYBCYSgWRuvn9xKpiXbAiklJT@AwA "Zsh – Try It Online"). Isogram/truthy returns `1`, otherwise `0` [Answer] # [K (ngn/k)](https://github.com/ngn/k), 18 bytes ``` {(a^,/$!10)~?a:_x} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqlojMU5HX0XR0ECzzj7RKr6i9n@JVbVKdGVdkVWaQoV1Qn62tUZCWmJmjnWFdaV1kWZsLVdJtJJLalFuYkl@ek5lQUZmcrGStWEsSDgxSUkBGcCFE1HErQ3Awrn5/sWpShjCiUnJhkqYqlFNBpv9HwA "K (ngn/k) – Try It Online") [Answer] # [CJam](https://sourceforge.net/p/cjam), 11 bytes ``` qelA,s+_L|= ``` [Try it online!](https://tio.run/##NY7BSgNBDIbv@xQ/40HQUqh3BaGXgtSDQk/FZmcz25HZme5M2rKoffU1XRHCH0LC98V@UjfyDXb9DpmpKaAQkBze3perNeoBDTs6Bpljw2hSvBWcKQpkTwKXMgjCRVCTCOdhVimsJJwZJXjL8KI0B0loWfS4SPaxVdchc@Eo14HgjtGKTxEUG0VzhNU/rqw/z/9ai0@qmZzzqr9szdhzeJ6V@4@X78fRPDy5r8vP@m40S84dSWrDcNh7W0xlqJ6CNLv0Wnia7EKb@QU "CJam – Try It Online") # Explanation The basic idea is to append each digit then check for duplicates. Since the append ensures that each digit is already present once, any further presence of digits will be a duplicate, causing it to return false. ``` q e# read the input: | "MOoSE1" el e# convert to lowercase: | "moose1" A e# push 10: | "moose1" 10 , e# range [0,N): | "moose1" [0 1 2 3 4 5 6 7 8 9] s e# string representation: | "moose1" "0123456789" + e# concatenate: | "moose10123456789" _ e# duplicate: | "moose10123456789" "moose10123456789" L| e# union with the empty list: | "moose10123456789" "mose1023456789" e# (this gets rid of duplicates) = e# Equal to original: | 0 ``` [Answer] # [Red](http://www.red-lang.org), 76 bytes ``` func[s][a: charset[#"a"-#"z"#"A"-#"Z"]parse s[any[copy c a ahead not to c]]] ``` [Try it online!](https://tio.run/##VcmxDsIgEIDhvU9xOWYTXbuZ@ASOkhvO45AmFgjggC@P6WLa7f/yF3Xjrs7S5OfhP1FsJcszSOBStVmDjCeDXzR43eKBlLcD1XLsVlLuIMDAQdlBTA1aAiGikcsSG3jAm5aVW3q9ew6LVJz@h58H8E5rOlc9XLnsiOMH "Red – Try It Online") [Answer] # Smalltalk, 57 bytes Method to be defined in class String: ``` s^(self select:#isLetter)asUppercase asSet size=self size ``` This is most likely self-explanatory. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 17 bytes ``` .Am&!t/rz0d}dGrz0 ``` [**Test suite**](https://pyth.herokuapp.com/?code=.Am%26%21t%2Frz0d%7DdGrz0&test_suite=1&test_suite_input=Dermatoglyphics%0Aab%0Aaba%0AmoOse%0Aabc1%0A&debug=0) Explanation: ``` .Am&!t/rz0d}dGrz0 # Code m rz0 # Map the following over the lowercase input: /rz0d # Count occurrences of d in lowercase input t # minus 1 ! # inverted (0 -> True) & # and }dG # d is in the lowercase alphabet .A # Print whether all values are truthy ``` Python 3 translation: ``` z=input() print(all(map(lambda d:not z.lower().count(d)-1and d in "abcdefghijklmnopqrstuvwxyz",z.lower()))) ``` ]
[Question] [ You must write a program that takes an encrypted string and decrypt it according to specific rules and then print it out. Decryption will occur by performing two operations. **Sample Input Argument 1** (the encrypted string) ``` HGJILKBADCFE ``` **Operation 1:** Swap the first half of the string with the second half, which should leave you with: ``` BADCFEHGJILK ``` **Operation 2:** Swap every two characters with each other such as swapping character 1 with 2, 3 with 4, etc., which should leave you with the decrypted string: ``` ABCDEFGHIJKL ``` **Guidelines:** * Input Argument 1 will contain only uppercase letters * Input Argument 1's length will be between 2 and 100 characters * Input Argument 1's length will always be an even number * Preferably the input will be taken from the command line (like below). * Another Test Case `MPORQTSVUXWZYBADCFEHGJILKN` is the input, Output is `ABCDEFGHIJKLMNOPQRSTUVWXYZ` **My Attempt** ``` import sys _,a=sys.argv b=len(a)//2 s=a[b:]+a[:b] print(''.join(x+y for x,y in zip(s[1::2],s[::2]))) ``` [Answer] # [J](http://jsoftware.com/), 15 bytes ``` [:,_2|.\-:@#|.] ``` [Try it online!](https://tio.run/##XY5LC4JQEIX3/opDBrdIR6@a2QXBsuxJi7YZIZI9oFqUray/boa5sMXMYs7hm@@cN4glcAUYFOgQxagEf70M8o1QdkZGoSo8OaNt3pakfXy8IQGbTuaz5WI4GPnBmEnSakgI0ivucVSs9IIkih93IiojZnednt43uGUyqOIL0LlhWl275/TZj9rRwtP1CRsZQRP/Lw4uoaWJUoUXXe8lPGXHYTbfciV2qHOrW42UfwA "J – Try It Online") Straightforward implementation of the formula. --- Slightly more interesting (not helpful for J golfing, but maybe for another lang) is that the algorithm can be solved with a scan sum: 1. First take a `1` followed by `-1 3`, with `-1 3` repeated up to the length of the list. 2. Scan sum that list. 3. Rotate the numbers half the list length. 4. Sort the original according those numbers. See the TIO for a demo in J. [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, ~~48~~ 47 bytes ``` $_=$_[l= ~/$//2,l]+$_[0,l];gsub /(.)(.)/,'\2\1' ``` [Try it online!](https://tio.run/##KypNqvz/XyXeViU@OsdWoU5fRV/fSCcnVhvINwDS1unFpUkK@hp6mkCkr6MeYxRjqP7/v4e7l6ePt5Oji7Ob67/8gpLM/Lzi/7oFAA "Ruby – Try It Online") Operation 1 is handled by splitting `$_` (the predefined global variable that contains the input) into two substrings of equal length; `~/$/` gives the length of the input. Then `gsub /(.)(.)/,'\2\1'` completes Operation 2 by swapping each pair of characters. (With the `-p` flag, `gsub` without a receiver implicitly acts on `$_`.) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes ``` D2äRJ2ι`s.ιJ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fxejwkiAvo3M7E4r1zu30@v/fw93L08fbydHF2c0VAA "05AB1E – Try It Online") *-1 thanks to a golfing tip by @Kevin I saw on another answer* ## Explained ``` D2äRJ2ι`s.ιJ ``` * Duplicate the input (`D`) * Split it into 2 chunks (`2ä`) * Reverse the list and join it into a single string (`RJ`) * Uninterleave that string on every second character (`2ι`) * Push all items from the uninterleaved string onto the stack (```) * Interleave those items (`.ι`) * And join the resulting list (`J`) [Answer] # APL+WIN, ~~24~~ 22 bytes -2 bytes thanks to Jo King Prompts for input of string: ``` ,⌽n⍴⊖(⌽n←⌽2,.5×⍴s)⍴s←⎕ ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/7rPOrZm/eod8ujrmkaYGbbBCBlpKNneng6ULhYE0SABPum/gdq4HrUO1fhUdeiapC@R71bITof9e4CMXpXQARrjXSAbKgJ/9O41D3cvTx9vJ0cXZzdXNW5AA "APL (Dyalog Classic) – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~78~~ ~~80~~ 79 bytes *Edit: +2 bytes thanks to Dingus for bug-spotting, and -1 byte thanks to pajonk* ``` n=nchar(s<-scan(,''));o=1:n;cat(substring(s,p<-(o+n/2-2+2*o%%2)%%n+1,p),sep='') ``` [Try it online!](https://tio.run/##fc5LDsIgFEDROatoakjBQkyJI1sGfup/CU6QVNtYH6TQuHy0jkw0LuDmni4EkKBr1RFXcKcVEJYklOZGZjPItfLE9WfnuwauxDFbcGJSmAguUjE2GAuKMaQZs5S5yspXGrab/e54WMxXy3WJ0CjSdaVv0aPxdQQG@L1vfWPbipsLn6JhEJ8gpugfw8qf12/ehwOVA@TNCOEJ "R – Try It Online") Input given through R console (which could be considered the 'command line' for the R workspace). R can also be invoked from a (non-R) shell, using the `Rscript` helper front-end, which would allow command-line arguments to directly follow the call, in which case a modified program could be [87 bytes](https://tio.run/##K/r/P882LzkjsUij2EY3OT83NzEvxbEovVhDM9osVtM639bQKs@6wFYjXztP30jXSNtIK19V1UhTVTVP29A6ObFEo7g0qbikKDMvXaNYp0CnQFOnOLXAVl1d8z/X//8e7l6ePt5Oji7Obq4A) and called using `Rscript decrypt.r HGJILKBADCFE`. Calculates positions of decoded letters, and then outputs rearranged string. Commented: ``` n=nchar( # n = number of characters in... s<-scan(,'')); # s = the input. o=1:n; # o = sequence from 1 to n p= # p = positions of decoded characters: (o+n/2-1 # - reverse the first & second halves of o # by adding n/2-1 # (will be fixed with final modulo below) +2*o%%2-1) # - then add 2 at every odd position # and subtract 1 from all, so in effect # adding to odds & subtracting from evens %%n # - all modulo n +1 # - add 1 to get 1-based indices cat( # output: substring(s,p,p),sep='') # characters of s from positions p to p ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ŒHṚFs2U ``` [Try it online!](https://tio.run/##y0rNyan8///oJI@HO2e5FRuF/v//38Pdy9PH28nRxdnNFQA "Jelly – Try It Online") Equivalently 7 bytes, `ṙLH$s2U`. ## Explanation ``` ŒHṚFs2U Main Link ŒH Split into two halves of similar length Ṛ Reverse the order (swap the two halves) F Flatten back into a single string s2 Slice into chunks of length 2 U Reverse each chunk Output is implicitly as one string ``` The other one `ṙ`otates it by `$`(`H`alf of the string's `L`ength) and then does the same thing for the second part of the challenge. [Answer] # [Python 3](https://docs.python.org/3/), 75 bytes Exactly as asked: input from command line, output to STDOUT. ``` import sys _,s=sys.argv i=1 while s[i:]:print(end=s[i-len(s)//2]);i+=3|i%-2 ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKG4spgrXqfYFkjrJRall3Fl2hpylWdk5qQqFEdnWsVaFRRl5pVopOal2AL5ujmpeRrFmvr6RrGa1pnatsY1maq6Rv///zcwNDI2MTUzt7AEAA "Python 3 – Try It Online") --- ## [Python 2](https://docs.python.org/2/), 52 bytes If we can use a function: ``` f=lambda s,i=1:s[i:]and s[i-len(s)/2]+f(s,i+3-i%2*4) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRoVgn09bQqjg60yo2MS9FAcjQzUnN0yjW1DeK1U7TAEprG@tmqhppmWj@LyjKzCvRSNNQ93D38vTxdnJ0cXZzVdfU5IJLGBgaGZuYmplbWAKF/wMA "Python 2 – Try It Online") --- The idea of all of these is that the index of the \$i\$'th output character in a string of length \$n\$ is: $$ i - \frac{n}{2} + (-1)^i $$ Subject to the usual Python indexing semantics. If we rewrite this in an iterative fashion, then the \$i\$'th output character is: $$ a\_i - \frac{n}{2} \text{ where } a\_0 = 1 \text{ and } a\_i = a\_{i-1} + 3 - 4(i\%2) $$ Shorter with certain precedence is: $$ a\_i - \frac{n}{2} \text{ where } a\_0 = 1 \text{ and } a\_i = a\_{i-1} + 3|(i\%-2) $$ [Answer] # [Python 2](https://docs.python.org/2/), 50 bytes ``` f=lambda s,i=0:s[i:]and s[(i^1)-len(s)/2]+f(s,i+1) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRoVgn09bAqjg60yo2MS9FoThaIzPOUFM3JzVPo1hT3yhWO00DqETbUPN/QVFmXolGmoa6h7uXp4@3k6OLs5uruqYmF1zCwNDI2MTUzNzCEij8HwA "Python 2 – Try It Online") Borrowing ideas from [Sisyphus](https://codegolf.stackexchange.com/a/211375/20260), the `i`'th character of the output is the character at index `(i^1)-len(s)/2` of the input. Here, `i^1` is XOR with `1`, which flips the last bit and so swaps even/odd pairs `0<->1`, `2<->3`, `4<->5`, ... Here's a non-recursive alternative for the same length, though it outputs a list of characters which I'm not sure is allowed. ``` lambda s:[s[(i^1)-len(s)/2]for i in range(len(s))] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYKro4WiMzzlBTNyc1T6NYU98oNi2/SCFTITNPoSgxLz1VAyKuGfu/oCgzr0QjTUPdw93L08fbydHF2c1VXVOTCy5hYGhkbGJqZm5hCRT@DwA "Python 2 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~73~~ ~~72~~ 70 bytes Saved 2 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)!!! ``` i;l;f(char*s){for(i=1;(l=strlen(s))/i;)putchar(s[(i+l/2-++i%2*2)%l]);} ``` [Try it online!](https://tio.run/##TY7basMwEETf/RWLwLCya9z4VXEh9@sfJKYE12oFqhIsFUqMv91dO2oSPWl2hplTJp9l2XVKaCGx/DrVkeWNPNeo8pFAnVtX68qg5TxVgl9@XJ9Be0AV6zRL4liFWZTxUBdctJ0yDr5PyiAPmgDoDY3gKuve7aGAHBq2Xm03@910Mp8tF@wF2GQ6my@Wq/Vmu9v3ms5kPhzWiqGKoAD7AWU@ql@qehX@OwarrtVZ4m2Hp15GXgsgzD7J4Ub1ILPU4@mGRCHugUtNYxJZaCF5A@Khorsp8Vn9R4@G@WsbtN0f "C (gcc) – Try It Online") Inputs a string and outputs the decryption. ### Explanation Maps the index (starting at \$0\$ to the end), of the input string, \$s\$ of length \$l\$, to the correct place by shifting it over \$\frac{l}{2}+1\$ places and then back \$2\$ for odd indices. Using this \$\mod{l}\$ gives the correct index of \$s\$ for the next output character. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 71 65 bytes ``` s=>(s.slice(l=s.length/2)+s.slice(0,l)).replace(/(.)(.)/g,'$2$1') ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1dcopBm@7/Y1k6jWK84JzM5VSPHtlgvJzUvvSRD30hTGyZqoJOjqalXlFqQkwjk6WvoaQKRfrqOuoqRiqG6Jtio/JxUvZz8dI00DXUPdy9PH28nRxdnN1d1TU0uNGnfAP@gwJDgsNCI8KhIiCqIDj@Q4v8A "JavaScript (Node.js) – Try It Online") Saved 6 bytes thanks to @Shaggy. Original 71 byte solution: ``` s=>(l=>s.slice(l)+s.slice(0,l))(s.length/2).replace(/(\w)(\w)/g,'$2$1') ``` Pretty simple stuff here - I used an inner function because I had to surround the `slice` calls anyway - this saves 4 bytes. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` ḍ↔cġ₂↔ᵐc ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO3kdtU5KPLHzU1ARkPNw6Ifn/fyUPdy9PH28nRxdnN1el/1EA "Brachylog – Try It Online") ### How it works ``` ḍ↔cġ₂↔ᵐc ḍ split in two halves ↔ reverse c join ġ₂ group with length two ↔ᵐ reverse each c join ``` [Answer] # [Python 3](https://docs.python.org/3/), 91 bytes ``` a=input();x=len(a)//2;b=a[x:]+a[:x];c='' for i in range(0,len(b),2):c+=b[i+1]+b[i] print(c) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P9E2M6@gtERD07rCNic1TyNRU1/fyDrJNjG6wipWOzHaqiLWOtlWXZ0rLb9IIVMhM0@hKDEvPVXDQAekOklTx0jTKlnbNik6U9swVhtIxXIVFGXmlWgka/7/7@Hu5enj7eTo4uzmCgA "Python 3 – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), 21 bytes ``` RV_M(JRV(a<>#a/2)<>2) ``` [Try it online!](https://tio.run/##K8gs@P8/KCzeV8MrKEwj0cZOOVHfSNPGzkjz////BoZGxiamZuYWlgA "Pip – Try It Online") ## Explanation ``` RV_M(JRV(a<>#a/2)<>2) (a<>#a/2) split input into parts of size length/2 JRV reverse the list, and join it to string <>2 split the joined string into parts of size 2 RV_M reverse each of those parts implicit output ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~78~~ ~~76~~ ~~78~~ 74 bytes Thanks to ceilingcat for the -4! Edit: Reverted to use addition instead of OR to avoid operator precedence issues. Rather than splitting the string, the function starts at the middle of the string and wraps around the entire string has been processed. To flip every other character, the index inverts the 1s position of the counter. ``` f(s,i,j)char*s;{for(i=strlen(s),j=0;write(1,s+(i/2+j++/2*2+j%2)%i,j<i););} ``` [Try it online!](https://tio.run/##VU9Nc4JADL3vr8jg0NkVrJbrCjN@4HdP9Q/gAhoGF2eD9eDw10sX6qWX5CV5Ly9Ro7NSbZtz8tEvhLokZkjymVeGY0i1KTPNSfhFOJEPg3XGP3zyOI4Dr/C8cTC02Q2Ea7VTFFLIph2gVuU9zWBKdYrV@yVi/1olnroeQ13DNUHNvytMBTwZQOcO1p5Z3F0ggVSic@64V3J8eCMRTSTkJsvsTX8SgJuxmzoOQRiBpZGQ/cD@9EK3e03ccfqqYU27We@2h/18tlysYjabL5bxar3Z7vYHdoy/jn34jH9UXiZnakePXw "C (gcc) – Try It Online") If the program absolutely must take from the command line: 82 bytes ``` main(i,s,j)char**s;{for(i=strlen(*++s),j=0;write(1,*s+(i/2+j++/2*2+j%2)%i,j<i););} ``` [Try it online!](https://tio.run/##DcVJCsMwDADA1wRsySGtr24OXdL9E0ZkkUkTsAI5lH69aucyVPZEqq/Ik2EnLlkaYgaQ8O7mbLiWJY/tZABRrEv1JqyZl9ZsHQgarjwmxMrD/8Lbgl3asQ02fFT1ernfno/D/nQ8N1/qxtiLlusP "C (gcc) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü♠yαæ♠╟«ºñ ``` [Run and debug it](https://staxlang.xyz/#c=%3B%25h%2Fr%242%2FFrp&i=MPORQTSVUXWZYBADCFEHGJILKN) What a wonderful online interpreter. Link is to unpacked version of code. ## Explanation ``` ;%h/r$2/Frp ; copy input % get it's length h halve it / split input into parts of that size r reverse $ join to string 2/ split into parts of size 2 F for each element in the resulting array: rp reverse, and print without newline. ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 17 bytes ``` ,/|'0N 2#,/|2 0N# ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NSke/Rt3AT8FIGcgwUjDwU/6fpuTh7uXp4@3k6OLs5qrElabkG@AfFBgSHBYaER4VCRGGKPFT@g8A "K (ngn/k) – Try It Online") [Answer] # [Factor](https://factorcode.org/), 89 bytes ``` : d ( s -- s ) halves swap [ >array ] bi@ append 2 group [ reverse ] map concat >string ; ``` [Try it online!](https://tio.run/##JY67jsJADEV7vuIqFRTZgjJICFhe4RGW90sUw2AgAiazngkoXx8G0li2z5WPz0LahPPlPIx6AQSzyAwunKQ6VhfciBXdYeg/JSXJwFh2ewPNZG2m3WBRK4VRgMWV/DZJzrSNE@V3UyU/TR7ghDIMfN@VCq7i/vzceQmNPepfIQ44xg0IrUmdUC30jjI9iQ05/HBpmSgpLOrFC6jlXr83CEfDVrP92@14TvNT8sZ/k9l0MV8tN@vdtiBFKvoG8jc "Factor – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~64~~ 63 bytes ``` m=matrix;intToUtf8(m(m(utf8ToInt(scan(,"")),,2)[,2:1],2)[2:1,]) ``` [Try it online!](https://tio.run/##K/r/P9c2N7GkKLPCOjOvJCQ/tCTNQiMXCEuBjJB8z7wSjeLkxDwNHSUlTU0dHSPNaB0jK8NYEANI68Rq/nd0cnZxdfsPAA "R – Try It Online") Took a different approach than [Dominic van Essen](https://codegolf.stackexchange.com/a/211380/67312), who golfed down a byte. Uses matrix reshaping/indexing to do the reversing. Ungolfed: ``` s <- utf8ToInt(scan(,"")) # read input and convert to a list of byte values m <- matrix(s,,2) # convert to a Nx2 matrix, filling down by columns m <- m[,2:1] # reverse the columns of the matrix (flip the halves) m <- matrix(m,2) # convert to an Nx2 matrix, filling down by the columns m <- m[2:1,] # reverse the rows (swap adjacent characters) intToUtf8(m) # convert back to string ``` [Answer] # bash+sed, 57 bytes Takes input as a command line argument. ``` <<<"${1:${#1}/2}${1:0:${#1}/2}" sed 's/\(.\)\(.\)/\2\1/g' ``` [Try it online!](https://tio.run/##S0oszvivrKiflJmnnwRi29jYKKlUG1qpVCsb1uob1YLYBnCekkJxaoqCerF@jIZejCaY0I8xijHUT1f///@/b4B/UGBIcFhoRHhUpJOji7Obq4e7l6ePtx8A "Bash – Try It Online") [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 17 bytes ``` iRsa2./!!2co)<-++ ``` [Try it online!](https://tio.run/##SyotykktLixN/f8/M6g40UhPX1HRKDlf00ZXW/v/fw93L08fbydHF2c3VwA "Burlesque – Try It Online") Description: ``` iR # Generate all rotations of the input string sa # Duplicate and get length (which equals string length) 2./ # Divide by two !! # And grab the string that's been rotated that many times 2co # Split the rotated string into chunks of two <- # Reverse each chunk ++ # Join together and implicitly output ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` éUÊz)ò mw ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=6VXKeinyIG13&input=IkhHSklMS0JBRENGRSI) ``` éUÊz)ò mw :Implicit input of string U é :Rotate right by UÊ : Length of U z : Floor divided by 2 ) :End rotate ò :Partitions of length 2 m :Map w : Reverse :Implicitly join and output ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes ``` ⭆⪪⪫⮌⪪θ⊘Lθω²⮌ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaAQX5GSWaHjlZ@ZpBKWWpRYVp0KFCnUUPBJzylJTNHxS89JLMjQKNYFAR6EciI2AGKY6Eyhq/f@/h7uXp4@3k6OLs5vrf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input string L Length ⊘ Halved ⪪θ Split input string into substrings of this length ⮌ Reverse ⪫ ω Join together ⪪ ² Split into substrings of length 2 ⭆ Map over substrings and join ι Current substring ⮌ Reversed Implicitly print ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 36 bytes ``` ((.)+?)((?<-2>.)+)$ $3$1 (.)(.) $2$1 ``` [Try it online!](https://tio.run/##K0otycxL/P9fQ0NPU9teU0PD3kbXyA7I1lThUjFWMeQCigMRl4qRiuH//x7uXp4@3k6OLs5urgA "Retina 0.8.2 – Try It Online") Explanation: The first stage uses a .NET balancing group to match as few characters as possible into `$1` while still matching the same number of characters into `$3`. `$#2` increments for each character matched into `$1` and decrements for each character matched into `$3` but it cannot decrement below zero, so `$1` is forced to consume the first half of the string to allow the end of the string to be reached. The second stage then flips pairs of adjacent characters. (Also ASCII art bewbs.) [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 10 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` h½/xy2/mx~ ``` [Try it online.](https://tio.run/##y00syUjPz0n7/z/j0F79ikoj/dyKuv//lTzcvTx9vJ0cXZzdXJW4lHwD/IMCQ4LDQiPCoyIhohAVfkBJA0MjYxNTM3MLSyUA) **Explanation:** ``` h # Get the length of the (implicit) input-string (without popping) # i.e. "HGJILKBADCFE" → "HGJILKBADCFE" and 12 ½ # Halve this length # → "HGJILKBADCFE" and 6 / # Split the string into parts of that size # → ["HGJILK","BADCFE"] x # Reverse this pair # → ["BADCFE","HGJILK"] y # Join it back together to a string # → "BADCFEHGJILK" 2/ # Split it into parts of size 2 # → ["BA","DC","FE","HG","JI","LK"] m # Map over each pair: x # Reverse the pair # → ["AB","CD","EF","GH","IJ","KL"] ~ # Pop and push all strings separated to the stack # → "AB", "CD", "EF", "GH", "IJ", and "KL" # (after which the entire stack joined together is output implicitly) # → "ABCDEFGHIJKL" ``` [Answer] # [Red](http://www.red-lang.org), 89 bytes ``` func[s][move/part s tail s(length? s)/ 2 rejoin collect[foreach[b a]s[keep rejoin[a b]]]] ``` [Try it online!](https://tio.run/##PYo5DsIwEAD7vGKVCqpIlDSI@77CEWDlwnHWJGDsyDZ83yBFYsqZsVSElApkkewG@dYCHcOX@VBSc@vBgeeVAtdSpO@@7IFrJ9CJLD1MpUEYpUh4lMYSFyXmwJnDJ1ENzYEccvYj1LbSHiTEs@livloO@qPhZBxHf73ebdP98XA@XbLbtanNuYnDFw "Red – Try It Online") [Answer] # [Lua](https://www.lua.org/), 67 bytes ``` a=...b=#a//2print(((a:sub(b+1)..a:sub(1,b)):gsub('(.)(.)','%2%1'))) ``` [Try it online!](https://tio.run/##yylN/P8/0VZPTy/JVjlRX9@ooCgzr0RDQyPRqrg0SSNJ21BTTw/CNtRJ0tS0Sgcx1TX0NIFIXUdd1UjVUF1TU/P///8e7l6ePt5Oji7Obq4A "Lua – Try It Online") First, string is cut in two using `sub` functions and then concatenated back in reverse order. Then, `gsub` is used to swap pairs of characters. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~64~~ 51 bytes ``` #[[#+UnitStep@#&@Array[#+(-1)^#&,L=Tr[1^#],-L/2]]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Xzk6Wlk7NC@zJLgktcBBWc3BsagosRIopqFrqBmnrKbjYxtSFG0Ypxyro@ujbxQbG6v2P6AoM68kWlnXLs3BOSOxKDG5JLWo2EE5Vq0uODkxr66aS8nRSUmHS8nD3cvTx9vJ0cXZzRXE9w3wDwoMCQ4LjQiPioQIQ5T4KXHV/gcA "Wolfram Language (Mathematica) – Try It Online") Port of [Sisyphus's Python solution](https://codegolf.stackexchange.com/a/211375/81203) [Answer] # [CJam](https://sourceforge.net/p/cjam), 13 bytes ``` q2/::\_,2//:\ ``` [Try it online!](https://tio.run/##S85KzP3/v9BI38oqJl7HSF/fKub/fw93L08fbydHF2c3VwA "CJam – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-pF`, 40 bytes ``` for$p("."x(@F/2),"."){s/($p)($p)/$2$1/g} ``` [Try it online!](https://tio.run/##K0gtyjH9/z8tv0ilQENJT6lCw8FN30hTB8jUrC7W11Ap0ARhfRUjFUP99Nr//z3cvTx9vJ0cXZzdXLl8A/yDAkOCw0IjwqMiIWIQeb9/@QUlmfl5xf91C9wA "Perl 5 – Try It Online") [Answer] # [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/), 472 bytes ``` DECODING THINGS:A BRIEFING o,o,hello!i am agent Q nah,Q`s chosen by an infamous phoney a misprint!oh,sorry!am i sorry i am agent J.W,tech/A.I hacker i see a piece o code,i am trying at a means on how i decode it what i am doing:i am laying all A-Z clearly along a pathway midway,put in zeros(O,O)cause J.W needs it to split em i shift em in tandem,i get B,A lastly,if it leaves you a letter,it is moved o,then i am doing A-Z again,it is taken to a shift ah ha!spying is EZ ``` [Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?TVDLUsMwDLznK9QbzJhy7y19t0BDH1DoCTVRY08dKxO77YSfL0rKDFzsHWm1u9JwNEiGs8UENlN5170Y@qvZaCw4YsVKk7XcMYAFYE4uwDJyqNXyy0Oq2ZODfQ3owLgDFnzyUGp2VEcIhfFlZVzosFaeq6ruiIaBFkb/BOfdrQqU6se4OwON6ZEqaXsiQCgNpQQMKWek2plQ1cblgEG6BaHzwA40X0Q5o4YGJkQXLf2WnrGwey20eJu0FuKHHaSWsLKS3XJThRKDvmAdFSaTT5UnUXDwTRX7u0Ql9ymePDVhwRFlXmwgMPjSCqCiSazNoYHNWECXUSGJcwrQV3Fk0QdbK3No5sT5TB5qPomvpRCoUlI2Hgo@UyZ3D1oO@7dAGxhzNO6XF/AoBPHHm22EWk7X8WW7ohBGu@vLa7Jabtbvbx/b3Wc/Hg7Go@lkPnt@Wlz3mP0A) ]
[Question] [ The oldest [Polish salt mine, located in Bochnia](https://en.wikipedia.org/wiki/Bochnia_Salt_Mine)\*, was started in year 1248, which we can consider a *magical number*. We can see that it's equal to 4 digits from the sequence of exponentiations: ![2^0, 2^1, 2^2, 2^3](https://chart.googleapis.com/chart?cht=tx&chl=2%5E0%5Ctextrm%7B,+++%7D2%5E1%5Ctextrm%7B,+++%7D2%5E2%5Ctextrm%7B+++and+++%7D2%5E3). As the date is actually 4 digits from the sequence, we could make it longer. We could repeat the process until we reach infinity. The sequence would look like this, if we limit it to number `2048` ``` 124816326412825651210242048 ``` To make it look a bit better, we can separate the numbers: ``` 1|2|4|8|16|32|64|128|256|512|1024|2048 ``` Let's try a custom, longer sequence than the date. Let's say, we want it to have 5 digits - there are more than one possibility: * `24816` * `81632` * `64128` Or 3 digit ones: * `124` * `248` * `816` We could also add the 3 digit numbers to this, but let's say, that a sequence must have **at least two numbers**. \* There is no information about this on the English Wikipedia. If you enter the Polish version - then there is. If you visit the mine, the workers will also tell you, that it started in 1248. ## The challenge Create a exponentiation sequence like in examples above with 2 as the base. Given a number from range 2-27, output **all possible** parts of the sequence (The 2048 one or larger if you want) with amount of digits equal to the input. You cannot cut a number, so output like `481` is invalid, because 16 is cut in half. Rules: * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * You can assume the input is a number inside the range. * Your program can accept inputs larger than the range (28+), but that won't increase/decrease score. * Spaces in output are ignored. You can output like `124` or like `4 8 16`. * Different possibilities should be separated by any character from the list: `,./|` or a line feed. * You can output as an array. * Every possibility should include **at least 2 different numbers**. * You must output **a part** of the sequence, you cannot mix numbers that aren't next to each other, like: `14`. * Hardcoded output isn't allowed, however, you can hardcode a string/number/array containing the full sequence. * Input 27 should return the full 2048 sequence. * As already mentioned before, **do not cut numbers**. Ex. `16` must stay `16` - you can't use `481` - you must use `4816`. * **EDIT:** I might have said something wrong there; 2048 is the last number which your program should support, you can add support for larger int's. ## Test cases Input: `2` ``` 12, 24, 48 ``` Input: `3` ``` 124, 248, 816 ``` Input: `4` ``` 1248, 4816, 1632, 3264 ``` Input: `5` ``` 24816, 81632, 64128 ``` Input: `27` ``` 124816326412825651210242048 ``` And later numbers... If I made a mistake in any of the test cases, tell me or edit the question. --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ ~~11~~ 10 bytes Supports the sequence up to `2^95 = 39614081257132168796771975168` ``` ₃ÝoŒʒg≠}Jù ``` [Try it online!](https://tio.run/##AR4A4f8wNWFiMWX//@KCg8Odb8WSypJn4omgfUrDuf//NTg "05AB1E – Try It Online") **Explanation** ``` ₃Ý # push range [0 ... 95] o # raise 2 to the power of each Œ # get a list of all sublists ʒ # filter, keep elements that satisfy: g # length ≠ # false (not equal to 1) } # end filter J # join each ù # keep numbers of length matching the input ``` Saved 1 byte thanks to *Erik the Outgolfer* Saved 1 byte thanks to *Riley* [Answer] # Pyth, ~~22~~ ~~21~~ ~~20~~ 17 bytes ``` fqQlTjLkt#.:^L2yT ``` [Try it Online](https://pyth.herokuapp.com/?code=fqQlTjLkt%23.%3A%5EL2yT&input=5&debug=0) ### Explanation ``` fqQlTjLkt#.:^L2yT ^L2yT Get the powers of 2 up to 2^20 t#.: Get all consecutive sequences of at least 2 jLk Concatenate each fqQlT Get the ones whose length is the input ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~19 18~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) There may be a shorter solution now that we may use any cut-off (not just 2048), although this change to the specification has allowed a one byte save from this implementation by moving to a cut-off of 32768. --yep... -2 bytes thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) (use of `V` to allow implicit right argument of the filter and tightening) --yes it is very similar to his inefficient one now; [go upvote his](https://codegolf.stackexchange.com/a/142574/53748)! ``` ⁴Ḷ2*Ẇṫ17VDL$⁼¥Ðf ``` A monadic link taking a number and returning a list of numbers. **[Try it online!](https://tio.run/##AScA2P9qZWxsef//4oG04bi2MirhuobhuasxN1ZETCTigbzCpcOQZv///zU "Jelly – Try It Online")** ### How? ``` ⁴Ḷ2*Ẇṫ17VDL$⁼¥Ðf - Link: number, n e.g. 3 ⁴ - literal sixteen 16 Ḷ - lowered range [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] 2 - literal two 2 * - exponentiate [1,2,4,8,16,32,...,32768] Ẇ - all sublists [[1],[2],...,[1,2],[2,4],...,[1,2,4],...] 17 - literal seventeen 17 ṫ - tail from index [[1,2],[2,4],...,[1,2,4],...]] V - evaluate as Jelly code [12,24,...,124,...] Ðf - filter keep: ¥ - last two links as a dyad $ - last two links as a monad: D - decimal list (of entry) (i.e. 816 -> [8,1,6] or 24 -> [2,4]) L - length (i.e. 816 -> 3, or 24 -> 2) ⁼ - equals (n) (i.e. 816 -> 1, or 24 -> 0) - ...resulting in [816, 124, 248] ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~62~~ 59 bytes ``` {grep *.comb==$_,map {[~] 2 X**[...] $_},combinations 12,2} ``` [Try it online!](https://tio.run/##FcpBCsIwEAXQtT3Fp8xCQxhwFrqQ9BxCKSFKIwXThNRNCfHqEd/6pTm/Ly3sIA/TyivPCYqfMTyMIauDSyjjd4LgrtTIzBPIVv0Py@o@S1w3nEVLbT5mCLNcUbrD5nb0ZGEGFPJHsqfa37rafg "Perl 6 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~22~~ ~~20~~ ~~19~~ 16 bytes Supports input up to `639` but gaps start appearing in the sequence after `234` (See the full list of supported input ranges [here](https://ethproductions.github.io/japt/?v=1.4.5&code=ScZJbyGy41ggbazDpGMgbcpuIPLIxDxZw6NbWGcgWMxd4iBxLQ==&input=LVI=)). Outputs an array of strings. ``` IÆIo!²ãX m¬lUäc ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.6&code=ScZJbyGy41ggbaxsVcOkYw==&input=NjM5Ci1R) `I` (64) could be replaced with `L` (100) but we'd be getting into scientific notation and precision inaccuracies. Filtering those out would, obviously, increase the byte count and only raise the maximum input to `736`. ``` :Implicit input of integer U I :64 Æ :Map each X in [0,64) Io : Range [0,64) !² : Raise 2 to the power of each ãX : Subsections of length X m : Map ¬ : Join lU : Filter elements of length U à :End map ¤ :Slice off the first 2 elements c :Flatten ``` [Answer] # [Python 2](https://docs.python.org/2/), 105 bytes ``` lambda l,r=range:[x for x in[''.join(`2**n`for n in r(i,j+2))for i in r(13)for j in r(i,11)]if len(x)==l] ``` [Try it online!](https://tio.run/##NctBCsMgEIXhq8wumg4FDaUQ8CRGiKWxHbFjkCzs6W3TkuX7Hv/63p6ZdQtmasm/bncPCYspnh/LaCuEXKACse26c8zEYtZ9z/PO/GUogjCetJS70F/U8Fvx@JWSjgKkhUWVxiTXjtxqHPCC@urGtRBvwBgEy9Y@ "Python 2 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~18~~ 17 bytes Output is separated by newlines ``` fo=⁰LmṁsftQ↑12¡D1 ``` [Try it online!](https://tio.run/##yygtzv7/Py3f9lHjBp/chzsbi9NKAh@1TTQ0OrTQxfD///8mAA) ### How? ``` ↑12¡D1 The sequence [1,2,4...2048] ¡ Repeatedly apply function, collecting results in a list D double 1 initially applying to 1 ↑12 Take the first 12 elements Q Get all sublists ft With a length greater than 1 mṁs Convert each list into a string, e.g [4,8,16] -> "4816" fo=⁰L Keep only those whose length is equal to the input ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` ȷḶ2*ẆṫȷḊVDL$⁼¥Ðf ``` [Try it online!](https://tio.run/##y0rNyan8///E9oc7thlpPdzV9nDnahCnK8zFR@VR455DSw9PSPv//78RAA "Jelly – Try It Online") Note: very inefficient. Returns a list of numbers. [Answer] # JavaScript (ES7), ~~102~~ 100 bytes Prints all matching sub-sequences with `alert()`. ``` l=>[...1e11+''].map((_,k,a)=>a.map((_,x)=>(s=(g=n=>x<=k|n<k?'':g(n-1)+2**n)(x)).length-l||alert(s))) ``` ### Demo **NB**: This snippet is buffering the results and printing them to the console for user-friendliness. ``` let f = l=>[...1e11+''].map((_,k,a)=>a.map((_,x)=>(s=(g=n=>x<=k|n<k?'':g(n-1)+2**n)(x)).length-l||alert(s))) alert = s => res += ' ' + s; for(l = 2; l <= 27; l++) { res = ''; f(l); console.log('L = ' + l + ' -->' + res); } ``` [Answer] # [Haskell](https://www.haskell.org/), ~~72~~ 67 bytes ``` f n=[s|i<-[0..99],j<-[i+1..99],s<-[show.(2^)=<<[i..j]],length s==n] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzza6uCbTRjfaQE/P0jJWJwvIzNQ2hHCKgZzijPxyPQ2jOE1bG5voTD29rNhYnZzUvPSSDIViW9u82P@5iZl5CrYKKflcnLmJBb4KGgVFmXklemmaCtFGenpG5rH/AQ "Haskell – Try It Online") *Saved 5 bytes thanks to Laikoni* I used a limit of `99` because `2^99` has a length `> 27`. [Answer] # Mathematica, 122 bytes ``` (s=#;FromDigits@F[f/@#]&/@Select[Subsequences[Array[2^#&,99,0]],l@#>1&&(l=Length)@(F=Flatten)[(f=IntegerDigits)/@#]==s&])& ``` **Input** > > [27] > > > **Output** > > {879609302220817592186044416, 134217728268435456536870912, > 524288104857620971524194304, 163843276865536131072262144, > 204840968192163843276865536, 256512102420484096819216384, > 641282565121024204840968192, 163264128256512102420484096, > 124816326412825651210242048} > > > ``` Input [1000] Output 1441151880758558722882303761517117445764607523034234881152921504606846976230584300921369395246116860184273879049223372036854775808184467440737095516163689348814741910323273786976294838206464147573952589676412928295147905179352825856590295810358705651712118059162071741130342423611832414348226068484722366482869645213696944473296573929042739218889465931478580854784377789318629571617095687555786372591432341913615111572745182864683827230223145490365729367654460446290980731458735308812089258196146291747061762417851639229258349412352483570327845851669882470496714065569170333976494081934281311383406679529881638685626227668133590597632773712524553362671811952641547425049106725343623905283094850098213450687247810566189700196426901374495621121237940039285380274899124224247588007857076054979824844849517601571415210995964968969903520314283042199192993792198070406285660843983859875843961408125713216879677197516879228162514264337593543950336158456325028528675187087900672316912650057057350374175801344 ``` [Answer] # C, 170 bytes ``` i,j;f(n){char t[99],s[12][5]={"1"};for(i=j=1;i<12;)sprintf(s+i++,"%d",j*=2);for(i=0;i<12;++i,strlen(t)-n||j>1&&puts(t))for(j=*t=0;strlen(t)<n&&j+i<12;)strcat(t,s+i+j++);} ``` [Try it online!](https://tio.run/##PZDRbsMgDEXf8xUIaRHUVBpI09Q67EeyPERs2UCbWwF7SvPtGaRR/WRfH/le2R2/nFtXrwJOguTsvsfIcn86DSr12gz9y2BnrvmC0yUKb4PV6DttUKZr9JQnkcADKP70wVU4WCN38PmOAXiVcvz5JJHlkW638Kbb9vqXU5llRYM95EI/oI7aNsDukaMbs8iqmgQAictaTNnv6EnIZm5YqSoQbm25xwRZg4w6a16RAZDcNne01h67BD6/E1eMJD529QW4heN8l5dmWf8B) **Unrolled:** ``` i,j; f(n) { char t[99], s[12][5] = {"1"}; for (i=j=1; i<12;) sprintf(s+i++, "%d", j*=2); for (i=0; i<12; ++i, strlen(t)-n || j>1 && puts(t)) for (j=*t=0; strlen(t)<n && j+i<12;) strcat(t, s+i+j++); } ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 33 bytes ``` {(x=#:')#,/{,/'$x':|2/=12}'2+!11} ``` [Try it online!](https://ngn.bitbucket.io/k#eJxLs6rWqLBVtlLXVNbRr9bRV1epULeqMdK3NTSqVTfSVjQ0rOXiSlMwAmJjIDYBYlMQ3xwAiFgMrQ==) Generates all possible sublists, then selects those of the proper length. Returns a list of strings. * `{...}'2+!11` generate 2..12 (the valid sublist lengths for input from 2..27), and run the code in `{...}` on each of those numbers + `|2/=12` generate the sequence `1 2 4 8 16 32 64 128 256 512 1024 2048` + `,/'$x':` take `x`-length rolling windows, converting each to strings, then concatenate them (e.g., `1 2 4 8` => `(1 2;2 4;4 8)` => `((,"1";,"2");(,"2";,"4");(,"4";,"8"))` => `("12";"24";"48")`) * `(x=#:')#,/` flatten the potential strings, keeping those of the desired length [Answer] # [R](https://www.r-project.org/), 99 bytes ``` function(n)for(i in 1:11)for(j in i:11+1)if(sum(nchar(x<-2^(0:11))[i:j])==n)cat(x[i:j],"\n",sep="") ``` [Try it online!](https://tio.run/##HcpLCoAgEADQq4irGSrI2kWepA@ENDRCU1hCt7ds@eCFRKqvEkVxNx8CgnQEYMWiTGfML5/FnwqDTHDFHcRtS4Cnr5oZ6vxw4M5PaK2gW254fpZ6FF1e62m1xkTQYnoB "R – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 76 bytes 75 bytes of code + 1 for `-a` ``` for$i(0..10){$/='',(map$/.=2**$_,$i..$_)&&$F[0]-length$/||say$/for$i+1..11} ``` [Try it online!](https://tio.run/##K0gtyjH9/z8tv0glU8NAT8/QQLNaRd9WXV1HIzexQEVfz9ZIS0slXkclU09PJV5TTU3FLdogVjcnNS@9JENFv6amOLFSRR@sXdsQqN2w9v9/Yy5TLiPzf/kFJZn5ecX/dX1N9QwMDf7rJgIA "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 94 bytes ``` ->n{a=*b=1;a<<b*=2until b>3**n;(2..n).flat_map{|x|a.each_cons(x).map &:join}.grep /^.{#{n}}$/} ``` [Try it online!](https://tio.run/##LczRCoIwFADQXxkUoWNdcSJBOn9kLNlEy7DrMIXF3LevHno9D2fZzCcOIp4b9FpQI/JK17Whgm@4jhMxTUEpVgkHwBSGSa/tS1u/u11Dr7tH2834TlwKPyWn63MeMcB96S3JbuAPHkM4ZiFKzgpWsrxk/KLgP1giHRukUyrE@AU "Ruby – Try It Online") ]
[Question] [ Ok I've been on a bit of a triangle kick recently so here's another one. Clark's Triangle is a triangle where the leftmost entry of each row is 1 and the rightmost entries are made up of multiples of 6 which increase as the row number increases. Here's a visualization ``` 1 6 1 . 12 1 . . 18 1 . . . 24 1 . . . . 30 1 . . . . . 36 ``` Just like Pascal's Triangle all other entries are the sum of the numbers to their upper right and upper left. Here are the first few rows filled in ``` 1 6 1 7 12 1 8 19 18 1 9 27 37 24 1 10 36 64 61 30 1 11 46 100 125 91 36 ``` # Task Given a row number (starting from the top) and an column number (starting from the first non-zero item on that row) output the value at that particular cell. Both inputs may be either 1 or 0 indexed (you may mix and match if you desire). Out of the bounds of the triangle is undefined and you may do whatever you wish when queried for these values. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the goal is to minimize the number of bytes in your solution. [OEIS A046902](http://oeis.org/A046902) [Answer] # [MATL](https://github.com/lmendo/MATL), 15 bytes ``` [lBB]i:"TTY+]i) ``` First input is 0-based row; second is 1-based column. [**Try it online!**](https://tio.run/##y00syfn/PzrHySk200opJCRSOzZT8/9/Yy4TAA "MATL – Try It Online") ### Explanation ``` [lBB] % Push [1 6 6] i % Input: row number (0-based) :" % Repeat that many times TT % Push [1 1] Y+ % Convolution, increasing size. This computes the sum of overlapping % pairs, including the endpoints. So for example [1 6 6] becomes % [1 7 12 6], which will later become [1 8 19 18 6], ... ] % End i % Input: column number (1-based) ) % Use as index. Implicit display ``` [Answer] # [Pascal](https://en.wikipedia.org/wiki/Pascal_(programming_language)), 132 bytes ``` function f(n,k:integer):integer;begin if k=1 then f:=1 else if k>n then f:=6*n else if k<0 then f:=0 else f:=f(n-1,k-1)+f(n-1,k)end; ``` [Try it online!](https://tio.run/##RY7BcoMwDETP@Ct0CybQCZ2m05qm/0JBJgpUZhyafj4VBtM9eNZP9mrH@t7UQ2HHZp5H7zpffwO16BgrBcr@cDORY7Ap570hnrBDr6OpvrAjBrLQX0qYrigPjTgc7hjoJ@/0NeN//nHa@Wml4mRHUeZ9UerjZjVyu9R41F6BiHK4GYjLVdiuEus8EJgLSAUH79A6lSyvtzFs@vU0YXqAg0nfsnNB2Vm39IBnXakkCSG3PYSOZYgRbSmL1gSbLjW0eVk/RizBOtxD54gHjoOA5Xia5z8) 1-indexed. [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~22~~ 18 bytes *-4 bytes thanks to Martin Ender* ``` X6_]ri{0X$+.+}*ri= ``` Input is `(0-based row) (0-based column)` [Try it online!](https://tio.run/##S85KzP3/P8IsPrYos9ogQkVbT7tWqyjT9v9/AwVDAA "CJam – Try It Online") ### Explanation ``` X6_] e# Push the list [1 6 6]. This is the first row, but each row will have an extra 6 at e# the end, which is out of bounds. ri e# Push the first input as an integer. { e# The following block calculates the next row given a row on top of the stack: 0X$+ e# Copy the top list on the stack and prepend 0. .+ e# Element-wise addition with the list before prepending 0. This adds each element of e# with the one to its left, except the initial 1 gets added to 0 and the final number e# gets added to the out-of-bounds 6. The out-of-bounds 6 is unchanged since one list e# is longer. }* e# Run this block (row index) times. ri= e# Get the (column index)th item of the final list. ``` [Answer] # C#, 157 bytes ``` using System.Linq;(b,c)=>{var f=new[]{1,6};for(;c>0;c--){int s=f.Length;f=new int[s+1].Select((e,i)=>i<1?1:i==s?f[s-1]+6:f[i-1]+f[i]).ToArray();}return f[b]; ``` [Try it online](https://tio.run/##rZA9a8MwEIZ3/YobJWKbaEiGKHYIhU4pFFLoYDwo6tkVOFIqKSnB@Le7cvpBOjVD3@F0Oj08iFM@VdbhcPTaNLA9@4B7Qa5v2UabN0EIMXKP/iAVwp013ra4PhxarWTQ1nDoCMSoVnoPj842Tu7jjFymY3yIoIKT1S/wILWhbHyGq9wfjVpqExL4LgU0kA90lyiWF91JOqhzg@9l1fFk3ovaOipUMRUqTVkXefB5nW3QNOFVXMhRUvoJr7IttqgCpZjo6NJLvuILned@VZc@5dVkvqhLPTbxqFj2ZNfOyTNloncYjs5AXe4q0Q/i95@/NpE9Ox0wLgppQ6cJTBkTf3L8Ri76@I0@/p@@WQKzkfsBe/JZezJ8AA) [Answer] # [Python 2](https://docs.python.org/2/), 67 bytes ``` a,b=input() x=[1,6] exec"x=map(sum,zip([0]+x,x+[6]));"*a print x[b] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P1EnyTYzr6C0REOTq8I22lDHLJYrtSI1WanCNjexQKO4NFenKrNAI9ogVrtCp0I72ixWU9NaSSuRq6AoM69EoSI6Kfb/f1MdIwA "Python 2 – Try It Online") Brute-force approach, calculate the `a`th row, and then print the `b`th number, both inputs are 0-based [Answer] # [Python 3](https://docs.python.org/3/), ~~64~~ ~~60~~ 52 bytes ``` f=lambda r,c:c<2or c>r and r*6or f(r-1,c-1)+f(r-1,c) ``` [Try it online!](https://tio.run/##TYoxDoMwDEX3nsJj3IYhselQUe4SgqJWKgFZLJw@NJIjMfn5v7cd@2fNVEp6/8IyzQHExlcc/CoQR4GQZ5D78/8lI52zsXP4UMSyyTfvJhlnHVqoFzzirc1eZ19nBbp4Uk/NU/UKfAlZQ24ht5BrqNAjlhM "Python 3 – Try It Online") Recursive solution using 1-indexing. Outputs "True" instead of 1 for the sake of golfing. --- **Thanks to:** * @totallyhuman for saving 4 bytes! * @Rod for saving 8 bytes! [Answer] # [Haskell](https://www.haskell.org/), 41 bytes ``` n#1=1 n#m|m>n=6*n n#m=(n-1)#(m-1)+(n-1)#m ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P0/Z0NaQK085tybXLs/WTCsPxLbVyNM11FTWyAWS2hB27v/cxMw8BVuFgqLMvBKF6GiwFhvdaEM9vTxtw9jYmjwIxzQ29j8A "Haskell – Try It Online") Call using `n # m` where `n` is the row number and `m` is the column number, both 1-indexed. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~15~~ 12 bytes ``` !!¡S`JẊ+d166 ``` [Try it online!](https://tio.run/##yygtzv6fm/CoqdH44Y7FZv8VFQ8tDE7werirSzvF0Mzs/38A "Husk – Try It Online") -3 bytes from Dominic Van Essen. Same method as the MATL answer, except it uses an infinite list of rows of Clark's triangle. [Answer] # Mathematica, 32 bytes ``` b=Binomial;b[#,#2-1]6+b[#-1,#2]& ``` input > > [row,column] > > [1-indexed,0-indexed] > > > [Answer] # [Scala](http://www.scala-lang.org/), 75 bytes - Brute-force solution ``` n=>k=>2.to(n)./:(Seq(1,6))((s,i)=>1+:s.sliding(2).map(_.sum).toSeq:+6*i)(k) ``` [Try it online!](https://tio.run/##VY07D4IwFIV3fsWN071CKjAwkJTE0cHJ1cRUKFoeBWk1JoTfXouLcTrJ@c7DlKITbrg2srRwFEqDfFupKwP7cZyDl@igzuGgLfDiT8BpXrS8SJkdUBPb5XiSD0yijAjRRIp4kYS5YaZTldI3TIn1YsQLM8@efMmn8zDbKsKWXLKuJDGxepikKO@o1qM5AIhXon6gWcE4KW2x9j42BCFsznZD5NNf0OlgoWBxHw "Scala – Try It Online") # [Scala](http://www.scala-lang.org/), 88 bytes - Recursive solution ``` n=>k=>{def g(m:Int,l:Int):Int=if(m==l)m*6 else if(l<1)1 else g(m-1,l-1)+g(m-1,l) g(n,k)} ``` [Try it online!](https://tio.run/##VY3BDoIwEETvfMWGU1eB0IsHYkk8evAPvFRosVAKgcaYEL69tkhinMPszrxsdq645m54tKKycOPKgHhbYeoZLuO4RC@uQRZwNRZY@TfAGVZ2rFxqIaEhfeHbRAfHYExJ0jOmsT@cQOhZgC/0mSL9Jn@R0kSnFI/7ilFDTNLh6sCLZnYgNMdMDpPg1ZOo8HmJYFMeqPrBNsBxUsYS6XvSIhwhvtsYcb/YoDZbWjFa3Qc "Scala – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~[40](https://codegolf.stackexchange.com/revisions/213943/1)~~ 36 bytes *Thanks to Lynn for pointing out the obvious and saving me 4 bytes.* ``` n#1=1 n#m|m>n=6*n|q<-n-1=q#(m-1)+q#m ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P0/Z0NaQK085tybXLs/WTCuvptBGN0/X0LZQWSNX11BTu1A5939uYmaegq1CQVFmXolCdDRYtY1utKGeXp62YWxsTR6EYxob@x8A "Haskell – Try It Online") --- Works like [this answer](https://codegolf.stackexchange.com/a/130179) but ~~1 byte~~ 5 bytes shorter. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~28~~ 18 bytes ``` {(x{+':x,6}/1 6)y} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWqOiWlvdqkLHrFbfUMFMs7L2v5q@Rlq0ibVxbJ2ZiXVatDGIZWwOZBlYG8TWGWpy/QcA "K (oK) – Try It Online") Rows and columns are both 0-indexed. Out of bounds return null. [Answer] # Desmos, ~~118~~ ~~71~~ 55 bytes Saved a whopping 47 bytes thanks to **@ovs**! \$f(r,c)=\sum\_{k=c-2}^c(6-5\*0^{c-k})/k!\prod\_{n=r-k+1}^rn\$ ``` f(r,c)=\sum_{k=c-2}^c(6-5*0^{c-k})/k!\prod_{n=r-k+1}^rn ``` Both the row and column are 0-indexed. [Answer] # [R](https://www.r-project.org/), 77 bytes ``` Reduce(function(x,y)zoo::rollsum(c(0,x,6),2),double(scan()-1),c(1,6))[scan()] ``` Requires the `zoo` library; reads from stdin (the inputs separated by two newlines) and returns the value, with `NA` for out of bounds selections. [Try it online!](https://tio.run/##K/r/Pyg1pTQ5VSOtNC@5JDM/T6NCp1KzKj/fyqooPyenuDRXI1nDQKdCx0xTx0hTJyW/NCknVaM4OTFPQ1PXUFMnWcMQKKUZDRGJ/W/IxWX6HwA "R – Try It Online") [Answer] ## JavaScript (ES6), 38 bytes ``` f=(r,c)=>c?r>c?f(--r,c)+f(r,--c):r*6:1 ``` Crashes for negative columns, and returns multiples of six for negative rows or overlarge columns. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 44 bytes ``` f=(c,r)=>c<=1?1:c>r?6*r:f(c-1,r-1)+f(c,r-1); ``` Takes column then row, both 1-indexed. Can take row then column by swapping the inputs: `(r,c)`. Will return `row * 6` for coordinates outside the bounds on the right (i.e. `column > row + 1`), and `1` for coordinates outside the bounds on the left (i.e. `column < 1`). [Answer] # [PHP](https://php.net/), 64 bytes recursive function rows 1-indexing columns 0-indexing Output for row=0 and column=0 is 0 like in the OEIS sequence ``` function f($r,$c){return$c-$r?$c?f($r-=1,$c-1)+f($r,$c):1:$r*6;} ``` [Try it online!](https://tio.run/##K8go@G9jXwAk00rzkksy8/MU0jRUinRUkjWri1JLSovyVJJ1VYrsVZLtQeK6toZAKV1DTW2YKitDK5UiLTPr2v@pyRn5QM1mOiaa1v8B "PHP – Try It Online") # [PHP](https://php.net/), 126 bytes rows 1-indexing columns 0-indexing Output for row=0 and column=0 is 0 like in the OEIS sequence ``` for(;$r<=$argv[1];$r++)for($z++,$c=~0;++$c<$z;)$t[+$r][$c]=$c<$r?$c?$t[$r-1][$c-1]+$t[$r-1][$c]:1:$r*6;echo$t[$r-1][$argv[2]]; ``` [Try it online!](https://tio.run/##TY2xDoIwFEV3PqO@gfogEU0YKA2DYXDRxa1piGkqsNDmpXFg4NexsOhwb3LPHY4f/Fo3fvCJJXLUkfWOwjj16dJ298fzdm25SOBF/UcqlrOMlTEXpsX6dpQKoFruryp0HIh8wzAjZmDkchKIYGqYBYegEEgrMFpuiBowTYRAebHR2Pg3dVVUQMdSWDO4H99VZx31B0/jFLooC1ysXw "PHP – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ,"’U0¦c/x6,1S ``` A monadic link taking a list of `[row, entry]` (0-indexing for entries, 1-indexing for rows), returning the value. **[Try it online!](https://tio.run/##y0rNyan8/19H6VHDzFCDQ8uS9SvMdAyD////H22sYxQLAA "Jelly – Try It Online")** ### How? ``` ,"’U0¦c/x6,1S - Link: list of numbers, [row, entry] ’ - decrement -> [row-1, entry-1] " - zip with: , - pair -> [[row, row-1], [entry, entry-1]] ¦ - sparse application of: U - upend 0 - for indexes: 0 -> [[row, row-1], [entry-1, entry]] / - reduce by: c - choose -> [(row choose entry-1), (row-1 choose entry)] 6,1 - 6 paired with 1 = [6,1] x - times i.e. [a, a, a, a, a, a, a, b] S - sum -> 6*(row choose entry-1) + (row-1 choose entry) ``` ]
[Question] [ Given a sequence of integers with length \$L\$ and an integer \$1 \le N \le L\$, an "\$N\$-rich" permutation is one whose the longest **strictly** increasing **contiguous** subsequence has length exactly \$N\$. For example, let our sequence be `[0, 1, 2, 3]`. There is exactly one \$1\$-rich permutation, given by `[3, 2, 1, 0]`. By contrast, there are sixteen \$2\$-rich permutations: ``` [0, 2, 1, 3] [0, 3, 1, 2] [0, 3, 2, 1] [1, 0, 3, 2] [1, 2, 0, 3] [1, 3, 0, 2] [1, 3, 2, 0] [2, 0, 3, 1] [2, 1, 0, 3] [2, 1, 3, 0] [2, 3, 0, 1] [2, 3, 1, 0] [3, 0, 2, 1] [3, 1, 0, 2] [3, 1, 2, 0] [3, 2, 0, 1] ``` Note that `[0, 1, 3, 2]` is \$3\$-rich and NOT \$2\$-rich, because even though it contains a strictly increasing subsequence of length 2, it also contains a *longer* strictly increasing subsequence. ## The Challenge Your challenge is to write a function which takes in an integer sequence S with some length \$L\$, and an integer \$1 \le N \le L\$, and returns the number of N-rich permutations of S. This is code golf, so the shortest valid answer wins. ## Test cases Each row is a sequence along with the expected output for all possible values of L. For example, the first row says that if your function is called `f`, then `f([1, 2, 3, 4, 5], 3) = 41` ``` [1, 2, 3, 4, 5] => 1, 69, 41, 8, 1 [1, 2, 2, 3, 3, 4, 5] => 4, 2612, 2064, 336, 24, 0, 0 [1, 1, 1, 1, 1, 1, 1] => 5040, 0, 0, 0, 0, 0, 0 [1, 2, 3, 1, 2, 3, 4] => 8, 2976, 1864, 192, 0, 0, 0 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` #mȯ▲mLġ>P ``` [Try it online!](https://tio.run/##yygtzv7/Xzn3xPpH0zbl@hxZaBfw////aEMdIx1jHRMd09j/RgA "Husk – Try It Online") or [Try the test lists with N=2](https://tio.run/##yygtzv6fm/CoqfG/cu6J9Y@mbcr1ObLQLuD///9G/6OjDXWMdIx1THRMY3XAbBAPwUeCUHljHaiO2FgA) ``` #mȯ▲mLġ>P P # get all permutations of arg1 m # map over each permutation: ȯ # these 3 composed functions: ġ> # - group by pairwise greater-than mL # - get the length of each group ▲ # - maximum # # how many times is arg2 present? ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~85~~ ~~79~~ 77 bytes Misread the prompt at first and was returning the permutations themselves instead of the amount, whoops. ``` ->a,n{a.permutation.count{|r,*b|m=c=1;b.map{m=c if m<c=r<(r=_1)?c+1:1};m==n}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY9RToQwEIbfOcVk4wNot6Gwi-Bu8QSeQDdYsCgJsKQUjbKcxJdN1NN4gr2Nw5asxmaS_ul8_z_T90_Vpa_7j5zffXU6n4eHm3ksSN0L2khVdVroYlvTbNvVut8pcp7uKp5xtkppJZoeNRQ5VOuMq7WteMKc6-yCXbFhVXFeD8MUev_yVJQSHqVuLRBEAoezhLZNWWh7xuOZc0yTz6KEhA0WKARsRqmgbfEmTTenmShLWxBEHGQaUAQU59KS9YOZsz983zICHgGfwILAcgPm8BjGRhDhM94hAbaxJtTQJ8OIovICNvbcALXvByhRuFjG97-Mb-kuXEP9rdMk_8hO2xkHbuJFlxjPwnESi7xfm_nTDw) ``` ->a,n{ # Lambda definition a.permutation # Permutations .count{ # Count instances that match the given condition |r,*b| # Extract first element as r (pRevious element) m=c=1; # Initialize variables # (m = max subsequence length) # (c = current subsequence length) b.map{ # Iterate over the rest of the permutation c=r<(r=_1)?c+1:1 # If prev. element < current, add 1 to c # Otherwise, reset c to 1 # Also reset r here to save bytes m=c if m<c # Set max if needed }; # End map call m==n} # Match if max == N } # End lambda ``` [Answer] # JavaScript (ES6), 87 bytes Expects `(n)(array)`. ``` n=>g=(a,s,m,p)=>a.map((v,i)=>t+=g(a.filter(_=>i--),q=v>p?s+1:1,q<m?m:q,v),t=0)+a?t:m==n ``` [Try it online!](https://tio.run/##XVBdb4MwDHzvr/BjIgwl0LJCa3jar6hQFTHoMgHhS/x9Zsoktlkn5RzfySd/6VmPxWC6yW3tR7lUtLSUPkloHLHBTlKqvUZ3QsxouJkcegrtVaaeykE8KDWuK7GnOe2y0VGJwv7WZE3S4yxxIl86OpuShqhdrvcDwF0hBAghwgnhnCNsdTwCD6KYv/m9IKhdu8l3B2uZBZFaZ37EPAwjpkx8xo/xPzbj2T/5m@w3/uTaA@avXBwmiN94gbqsu1Qc7L784FV2eNfFp9BAKRS2HW1derVdj/Q62wPByHVWCQMOKCm05Fq@AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` n => // outer function taking n g = ( // inner recursive function g taking: a, // a[] = input array s, // s = size of the strictly increasing sequence m, // m = maximum size so far p // p = previous value from the permutation ) => // a.map((v, i) => // for each value v at index i in a[]: t += // add to t the result of ... g( // ... a recursive call to g: a.filter(_ => // remove from a[]: i-- // the i-th element ), // q = // q = new value of s, defined as follows: v > p ? // if v is greater than p: s + 1 // increment s : // else: 1, // reset to 1 q < m ? m : q, // m = max(m, q) v // pass v as the previous value ), // end of recursive call t = 0 // start with t = 0 ) // end of map() + a ? // if a[] is empty: t // return t : // else: m == n // return 1 if the maximum size is n ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `L`, 10 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` qæƑœØ^ḷG¹= ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPXElQzMlQTYlQzYlOTElQzUlOTMlQzMlOTglNUUlRTElQjglQjdHJUMyJUI5JTNEJmZvb3Rlcj0maW5wdXQ9JTVCMSUyQyUyMDIlMkMlMjAzJTJDJTIwNCUyQyUyMDUlNUQlMEEyJmZsYWdzPUw=) or [verify all test cases](https://Not-Thonnu.github.io/run#aGVhZGVyPSVDNSVCQyVDNCVCMVgmY29kZT1xJUMzJUE2JUM2JTkxJUM1JTkzJUMzJTk4JTVFJUUxJUI4JUI3R3glM0QmZm9vdGVyPSUzQmwmaW5wdXQ9JTVCMSUyQyUyMDIlMkMlMjAzJTJDJTIwNCUyQyUyMDUlNUQlMjAlM0QlM0UlMjAxJTJDJTIwNjklMkMlMjA0MSUyQyUyMDglMkMlMjAxJTBBJTVCMSUyQyUyMDIlMkMlMjAyJTJDJTIwMyUyQyUyMDMlMkMlMjA0JTJDJTIwNSU1RCUyMCUzRCUzRSUyMDQlMkMlMjAyNjEyJTJDJTIwMjA2NCUyQyUyMDMzNiUyQyUyMDI0JTJDJTIwMCUyQyUyMDAlMEElNUIxJTJDJTIwMSUyQyUyMDElMkMlMjAxJTJDJTIwMSUyQyUyMDElMkMlMjAxJTVEJTIwJTNEJTNFJTIwNTA0MCUyQyUyMDAlMkMlMjAwJTJDJTIwMCUyQyUyMDAlMkMlMjAwJTJDJTIwMCUwQSU1QjElMkMlMjAyJTJDJTIwMyUyQyUyMDElMkMlMjAyJTJDJTIwMyUyQyUyMDQlNUQlMjAlM0QlM0UlMjA4JTJDJTIwMjk3NiUyQyUyMDE4NjQlMkMlMjAxOTIlMkMlMjAwJTJDJTIwMCUyQyUyMDAmZmxhZ3M9Qw==) #### Explanation ``` qæƑœØ^ḷG¹= # Implicit input q # All permutations of the first input æ # Filtered by: Ƒ # All sublists of this list œØ^ # Only keep strictly ascending ones ḷG # Get the maximum length ¹= # Equals the second input? # Implicit output of length ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~62~~ 57 bytes Port of [@chunes's Factor code](https://codegolf.stackexchange.com/a/264172/110802) in Mathematica. Saved 5 bytes thanks to the comment of [@ZaMoC](https://codegolf.stackexchange.com/users/67961/zamoc) --- Golfed version. [Try it online!](https://tio.run/##TY/BSsRAEETv@xUFgUWXgWDU0xpYEDwpLHgMQcaxkwwknTjdswbEb4@zOeVQhy6qX3cNVjsarHpnl5sDXnxQUbxPvVd41hFCFwq2T4MLZMVzCzeykIvqLwSJn0LfkdiRGCQWo/H8BZvkxsh69TBRGKKmK2kTPx0FWu1@5JZEt@wND50V9MStdihwuN015fJ8RVbnDe6UmfkjP77ZuXpds/lp/b6aTfaUFfu6Lsui3i8TSvzeGRQG9wYPBo9/x11TTTXy/BxS1eUf) ``` Count[Permutations@#,x_/;Max[Length/@Split[x,#<#2&]]==2]& ``` Ungolfed version. [Try it online!](https://tio.run/##dZBPS8QwEMXv/RQPFkSXQNmqF9eCoCiCwoLHUpZYp20gnazNFAXxs9ck/hc85JB5L7/3MoOWngYtptHzvL/EBbWGCe3EjRjHEAe/s0ag4elxIm4IhsPUcDOS9oY7@On@U/NYHmR38cH1l15Z42Vb46REUtJdYbHCKRYF9up1loXkK2IatRC0tdjROEyiYwUP1yKU/M4PEVH3KLH54ateVgqFwqHCkcLx6wf30vADdDiNm1gS6Rf9qaeR0tg67sjLP19Drz0scSc9itjhPPKq1EQl5Bb5Grf6ubp5d@Vn@LuKaKtrlCWKGnm@GcMu5/kN) ``` (* Define function to split a sequence into increasing subsequences *) SplitIncreasing[list_] := Split[list, #1 < #2 &]; (* Generate all permutations of the sequence *) perms = Permutations[{1, 2, 3, 4, 5}]; (* Find and count the permutations where the longest increasing subsequence has length 2 *) Count[perms, perm_ /; Max[Length /@ SplitIncreasing[perm]] == 2] //Print ``` [Answer] # [Python](https://www.python.org), 126 bytes *-19 bytes thanks to @ValueInk and @TheThonnu* *+2 bytes, index was off by one* ``` lambda l,i:sum(i==1+max(sum(b)for(_,b)in groupby(a>b for(a,b)in zip(p[1:],p)))for p in permutations(l)) from itertools import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVBBasMwEKRXv2LJSWo2YNmJmwScj6ShyImdiFqWUGRoeuhHejGU9k_ta7qKCk0CC7szmtlZ9P5lT_5guuGjKR8_e99M5t9vrdTVTkKLannsNVNlKcZavrAAKt4Yx56w4qqDvTO9rU5MrioItIz0q7LMrsVyg5bzoAcLRNva6d5Lr0x3ZC3nSeOMBuVr541pj6C0Nc7fxyt-7opd3cD2UG-fWYuaLxMIGaAg7HKy29dMYFt3tGoszs9gneo8qRWOoFzBCFkTEC9LvVYTseHEjzByPEni8rVAyBByhCnCbIMBFwtC1OcI5LoWRu2_nFpWiPCQFjTneUEjDSnVlfe2yDtLp2lUXtZtYn7W_91ILroqWzxQjJiHRLHILqzx-4Yh9l8) [Answer] # [Factor](https://factorcode.org) + `math.combinatorics`, ~~83~~ 72 bytes ``` [ <permutations> [ [ < ] monotonic-split longest length = ] with count ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PU67CsJAEOzzFfMDCRgVxFerNjZiJRbnsYmHl714t0FE_BKbNOaf_BsPA7LF7MwuM_PqCqXF-fZz2u8229UUlZJzpl11MqziwejwkxBqa0QMl1nl2IljoxHo2hBrCqg9idxrb1hwIc9kMUuSHA8MkGOIEcZ4vhsp0slnfcC8Jl81osQ4Dksc4sxxxN85_aXBOi4pRCQuY4VFfLmZuGjXxJxj79dpZS2ynrRtj18) * `<permutations> [ ... ] with count` Count permutations of the input sequence using `[ ... ]` (a predicate quotation/lambda). * `[ < ] monotonic-split` Split into increasing subsequences. * `longest length` Get the length of the longest one. * `=` Is this equal to the numeric input? [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Œ!Ẇ<ƝẠ$ƇṪLƲ€ċ ``` A dyadic Link that accepts the list of elements, \$L\$, on the left and the number, \$n\$, on the right and yields the count of \$n\$-rich permutations of \$L\$. **[Try it online!](https://tio.run/##y0rNyan8///oJMWHu9psjs19uGuByrH2hztX@Rzb9KhpzZHu////RxvqKBiBkTEYmegomMb@NwUA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///oJMWHu9psjs19uGuByrH2hztX@Rzb9Khpzf/D7Ue6H21c56X5/390tKGOgpGOgrGOgomOgmmsDpcCVAQiiCaOjpDUG4NFoEYBxWMB "Jelly – Try It Online") (count, `ċ`, has been moved out to the footer to make it more efficient, and so finish within the TIO timeout). ### How? ``` Œ!Ẇ<ƝẠ$ƇṪLƲ€ċ - Link: L, n Œ! - all permutations of {L} € - for each: Ʋ - last four links as a monad: Ẇ - sublists (from shortest to longest) Ƈ - filter keep those for which: $ - last two links as a monad: Ɲ - for neighbouring pairs: < - less than? Ạ - all? Ṫ - tail L - length ċ - count occurrences of {n} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` Œ!ẆIRẠƊƇẈṀƲ€ċ ``` [Try it online!](https://tio.run/##y0rNyan8///oJMWHu9o8gx7uWnCs61j7w10dD3c2HNv0qGnNke7/h5cD6cj/XP@jDXWMdIx1THRMY3UUgBwFIzAyBiMTHQWYMDpCqDYGC0AYJrH/jQA "Jelly – Try It Online") -1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)! Footer runs each sequence test case over a provided \$N\$ # [Jelly (fork)](https://github.com/cairdcoinheringaahing/jellylanguage), 10 bytes ``` Ẇ<ɲƇẈṀƲÐ!ċ ``` [Try it online!](https://tio.run/##y0rNyan8///hrjabk5uOtT/c1fFwZ8OxTYcnKB7p/n94@aOmNZH/uf5HG@oY6RjrmOiYxuooADkKRmBkDEYmOgowYXSEUG0MFoAwTGL/GwEA "Jelly – Try It Online") (or, rather, don't as it isn't implemented on TIO) ## How they work ``` Œ!ẆIRẠƊƇẈṀƲ€ċ - Main link. Takes S on the left, N on the right Œ! - All permutations of S Ʋ€ - Over each permutation P: Ẇ - All contiguous sublists ƊƇ - Filter sublists on: I - Increments Ạ - all R - have a non-zero range Ẉ - Lengths Ṁ - Maximum ċ - Count N ``` ``` Ẇ<ɲƇẈṀƲÐ!ċ - Main link. Takes S on the left and N on the right ƲÐ! - Over the permutations of S: Ẇ - Contiguous sublists Ƈ - Keep those such that: ɲ - All neighbours are: < - In ascending order ẈṀ - Maximum length ċ - Count N ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-n`, 10 bytes ``` ↕∆±ĉᵐ∑çṀ→= ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJunlLsgqWlJWm6FjsftU191NF2aOORzodbJzzqmHh4-cOdDY_aJtkuKU5KLoaqWnCLcX-0oY6RjrGOiY5prIIhFzLPCIVnjMIzQeGZQnggPqpJSCJGGCLGGCImGCKYJpthiJiDRJAg1HYUESMMEWMMERMMEVMMETMMEXNYSEDDAykU4SJGGCLGGCImGCKmGCJmGCLmkIgEAA) ``` ↕∆±ĉᵐ∑çṀ→= ↕ Find a permutation of the first input ∆ Delta ± Sign ĉ Split into runs of equal elements ᵐ∑ Sum each run ç Prepend 0 to handle the case with no nonnegative runs Ṁ Maximum → Increment = Check if equal to the second input ``` `-n` counts the number of solutions. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` œʒü‹γOà-}g ``` [Try it online](https://tio.run/##ASgA1/9vc2FiaWX//8WTypLDvOKAuc6zT8OgLX1n//9bMSwyLDMsNCw1XQoz) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeWjlkcayQ@vslRQS81IUlOwrgaxHbZNArNBD6/4fnXxq0uE9jxp2ntvsf3hBRLFubfp/nf/R0YY6RjrGOiY6prE6YDaIh@AjQai8sQ5UR2wsAA). **Explanation:** ``` œ # Push all permutations of the first (implicit) input-list ʒ # Filter it by: ü # For each overlapping pair: ‹ # Check whether the first is smaller than the second γ # Group the 0s and 1s into adjacent equal groups O # Sum each inner group à # Pop and push the maximum - # Subtract it from the second (implicit) input-integer # (only 1 is truthy in 05AB1E) }g # After the filter: pop and push the length # (which is output implicitly as result) ``` [Answer] # [Arturo](https://arturo-lang.io), 100 bytes ``` $=>[n:&enumerate permutate&'x[i:0n=1+??max map select chunk chop x'y['i+1y<x\[i]]=>sorted?=>size 0]] ``` [Try it!](http://arturo-lang.io/playground?WvI33K) ``` $=>[ ; a function where successive inputs are assigned to & n:& ; assign first input (number) to n enumerate permutate&'x[ ; count each permutation x of input seq i:0 ; assign 0 to i n=1+ ; does n equal 1 plus ?? ... 0 ; if ... is null, evaluate to 0, else to ... max ; maximum value of map...=>size ; lengths of select...=>sorted? ; sorted blocks of chunk chop x'y[ ; split x-sans-last-elt into contiguous blocks by... '1+1 ; increment i in place y<x\[i] ; is y less than x[i]? (is it increasing?) ] ; end chunk ] ; end enumerate ] ; end function ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `l`, 71 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 8.875 bytes ``` Ṗ'ÞS~Þ⇧@G⁰= ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJsPUIiLCIiLCLhuZYnw55TfsOe4oenQEfigbA9IiwiIiwiWzEsIDEsIDEsIDEsIDEsIDEsIDFdXG4yIl0=) ## Explained ``` Ṗ'ÞS~Þ⇧@G⁰=­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁢⁢​‎‏​⁢⁠⁡‌­ Ṗ' # ‎⁡Filter permutations where: ÞS # ‎⁢ All sublists ~Þ⇧ # ‎⁣ that are strictly increasing @G # ‎⁤ has maximum sublist length ⁰= # ‎⁢⁡ equals N # ‎⁢⁢The l flag gets the length of all the permutations. 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 45 bytes ``` ⊞υ⟦⟧Fθ≔ΣEυE⁻Eθνκ⁺κ⟦μ⟧υI№EυL⌈⪪⭆Φιμ‹§θλ§θ§ιμ0⊖η ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TU9LasMwEN33FINXI1CgXyhkFVoKhQYMXhotXEexRSQ50Ugld-kmi5b2DL1JL9BzdKSkUDGS3nvz9Aa9fvZjF_qps4fDe4rr2e33T51oxCShVWJ-tp4C4E7AgsgMHpvkcNltcztfS-MTFWEnwQsJG961ZW3D750SvCQkzqmD8RHvOuJjSgxPKU_aD3FktjeOs5utNRGbyO4hOx6MjTqgkeBENhPhIj76ld7niZa1f_QPFneZXJ1XR3Cv-6Cd9lGvcMzS_I2eezr9-aOtZi-2Ul9teyHhstRVqWsJN4q5Ohp_AQ) Link is to verbose version of code. Explanation: ``` ⊞υ⟦⟧Fθ≔ΣEυE⁻Eθνκ⁺κ⟦μ⟧υ ``` Generate all of the permutations from `0` to `L-1`. This is based on my answer to [1 to N column and row sums](https://codegolf.stackexchange.com/q/254768/) but uses the indices of the input rather than an explicit range. ``` I№EυL⌈⪪⭆Φιμ‹§θλ§θ§ιμ0⊖η ``` For each permutation, create a binary string representing strictly increasing consecutive values of the input array, then split that string on `0`s and take the length of the longest resulting contiguous substring of `1`s. Count the number for which that is `N-1`. [Answer] # [Desmos](https://desmos.com/calculator), 189 bytes ``` f(L,n)=∑_{k=0}^{l^l-1}0^{(I.unique.length-l)^2+([S.length0^{0^{max(0,S[2...]-S)}.total}forb=[1...l],d=[0...l]].max-n)^2} l=L.length I=mod(floor(kl/l^{[1...l]}),l)+1 S=L[I][b...min(l,b+d)] ``` [Try It On Desmos!](https://www.desmos.com/calculator/b3vvd7mewq) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/ww0mszmxi4) Probably some of the most horrendous and inefficient Desmos code I have ever written, but at least it gets the job done (disregarding runtime lmao). It is so inefficient that I don't think it can even run a list of length 7 any time soon. I might write a longer explanation later, but the gist of it is that I iterate through all base-\$l\$ numbers of length \$l\$ where \$l\$ is the length of the input list \$L\$, then check if the resulting digits form a valid permutation of \$0,\ldots,l-1\$, then add \$1\$ to the digits because of 1-indexing. This digit list is then used to permute \$L\$. Then for each permutation I check for the "richness" by further iterating through all sublists of the permutation. Finally with that, I can count the number of permutations that are "\$n\$-rich". [Answer] # [Perl 5](https://www.perl.org/), 131 bytes ``` sub{($r,%s)=pop;$"=",";0+grep{my($l,$f,$m);$m+=($l=$_>$f?$l+1:1)>$m,$f=$_ for@_[/./g];$m==$r}grep!/(.).*\1/,glob"{@{[0..$#_]}}"x@_} ``` [Try it online!](https://tio.run/##nZHRbpswFIavx1P8c90FGo/gpGFNkFPuJzU3vUsj1LQmRQNMCdk6MZ49OyZVm/VyliWOv3O@HwsqXefTA0/VYbfftC6vxfnOU5WpIs4UEywKhttaV23x2@W54KnghRfxYqjoqHiy4Ok1z4dyLr0FL6hPDKmp42Q18kfbNY0qxevOZnweub7nX9zJkdjmZsPauF0Fvs/PknXXsZc46Q6Rw/8oGTmU4DorACspMBaYCFwKTNc4LrUA8XBGlJ5XAhL/rLU4lY/@WwTJVIxDaVtBSPVkElJJRUD7g0za@xV6mV43nn0jQ15ZWc7GR9G6p/LH3cvT4DJ4Gz/xXq@Ns19ZnqPJCm32DUyJ22wp8GCKQpd0Jna/MT818qzUaAzqfYnmKdv1wPFax@bYf5WVlYj1S@WpmCfRK0a8NY0q7it84akb90M88ez3830Ew578x3BVZ2WTsvOv4Q4gum/m6NvUozvoh0Y/EqGSAKXO@@y7kgnnE7OYQT@DWchwjYH5McAcg5vlLZbfB5HTHf4C "Perl 5 – Try It Online") [Answer] # [sclin](https://github.com/molarmanful/sclin), 48 bytes ``` perm";"map = +/ 2%`",_ <"map"="pack0"+/ |"fold1+ ``` [Try it here!](https://replit.com/@molarmanful/try-sclin) Takes number first, then sequence. For testing purposes: ``` 3 [1 2 3 4 5] ; perm";"map = +/ 2%`",_ <"map"="pack0"+/ |"fold1+ ``` ## Explanation Prettified code: ``` perm \; map = +/ 2%` ( ,_ < ) map \= pack 0 ( +/ | ) fold 1+ ``` Assuming number *n* and sequence *s*. * `perm \; map` map over each permutation of *s*... + `2%` ( ,_ < ) map` pairwise map with "less than" to get booleans indicating increases + `\= pack` group consecutive runs of booleans + `0 ( +/ | ) fold 1+` get maximum sum + 1 - sum implicitly converts true to 1 and false to 0 * `= +/` vectorized equals to *n*, sum + i.e. count occurrences of *n* ]