text
stringlengths
180
608k
[Question] [ [Boustrophedon](https://en.wikipedia.org/wiki/Boustrophedon) is a type of bi-directional text where successive lines alternate between reading left-to-right and right-to-left. Character direction was also mirrored with respect to reading direction. In reverse boustrophedon writing systems, characters were rotated 180 instead of mirrored. # Challenge Write a program/function that accepts a string of text and a number of columns, and outputs the string formatted into the specified number of columns with alternating lines flipped upside down. # Input Your program should accept two arguments: * S, the string of text to format * N, the number of columns # Output Your program should output S wrapped in N columns with alternating lines flipped 180 degrees. * The reading direction of the first line is always left-to-right. * Don't worry about where to place line breaks, lines can be split at any character, no hypenation of words required. * You may assume input string will not contain any line breaks. Here are the characters your program should support with their flipped counterparts: ``` Uppercase: ABCDEFGHIJKLMNOPQRSTUVWXYZ ∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Z Lowercase: abcdefghijklmnopqrstuvwxyz ɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz Punctuation: &_?!"'., ⅋‾¿¡„,˙' ``` # Test Cases ``` S: The quick brown fox jumps over the lazy dog. N: 30 Output: The quick brown fox jumps over ˙ƃop ʎzɐl ǝɥʇ ``` --- ``` S: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vel libero arcu. Nunc dictum elementum lectus nec aliquet. Donec dolor nunc, sodales at dolor rhoncus, hendrerit scelerisque purus. Pellentesque vel sagittis libero, et rutrum leo. Nullam vulputate enim et massa dictum, vitae venenatis augue lobortis. Fusce sollicitudin ultrices consequat. Vestibulum quis nunc non tortor eleifend facilisis. In at nunc elit. Aliquam pellentesque, lectus quis aliquam posuere, quam lectus sagittis metus, ut auctor sem quam a neque. Integer rhoncus lobortis nisl. Pellentesque mi dui, laoreet in metus quis, mollis accumsan est. Nunc dignissim tortor ac eleifend tempus. Ut ut tellus aliquam, luctus nulla quis, consectetur nunc. Suspendisse viverra molestie condimentum. Curabitur et hendrerit augue. N: 50 Output: Lorem ipsum dolor sit amet, consectetur adipiscing uǝɯǝlǝ ɯnʇɔᴉp ɔunN ˙nɔɹɐ oɹǝqᴉl lǝʌ ǝnbsᴉnQ ˙ʇᴉlǝ tum lectus nec aliquet. Donec dolor nunc, sodales lǝԀ ˙snɹnd ǝnbsᴉɹǝlǝɔs ʇᴉɹǝɹpuǝɥ 'snɔuoɥɹ ɹolop ʇɐ lentesque vel sagittis libero, et rutrum leo. Null sᴉʇɐuǝuǝʌ ǝɐʇᴉʌ 'ɯnʇɔᴉp ɐssɐɯ ʇǝ ɯᴉuǝ ǝʇɐʇndlnʌ ɯɐ augue lobortis. Fusce sollicitudin ultrices conse ɔɐɟ puǝɟᴉǝlǝ ɹoʇɹoʇ uou ɔunu sᴉnb ɯnlnqᴉʇsǝΛ ˙ʇɐnb ilisis. In at nunc elit. Aliquam pellentesque, lec ʇǝɯ sᴉʇʇᴉƃɐs snʇɔǝl ɯɐnb 'ǝɹǝnsod ɯɐnbᴉlɐ sᴉnb snʇ us, ut auctor sem quam a neque. Integer rhoncus lo snʇǝɯ uᴉ ʇǝǝɹoɐl 'ᴉnp ᴉɯ ǝnbsǝʇuǝllǝԀ ˙lsᴉu sᴉʇɹoq quis, mollis accumsan est. Nunc dignissim tortor u snʇɔnl 'ɯɐnbᴉlɐ snllǝʇ ʇn ʇ∩ ˙sndɯǝʇ puǝɟᴉǝlǝ ɔɐ ulla quis, consectetur nunc. Suspendisse viverra m ˙ǝnƃnɐ ʇᴉɹǝɹpuǝɥ ʇǝ ɹnʇᴉqɐɹnƆ ˙ɯnʇuǝɯᴉpuoɔ ǝᴉʇsǝlo ``` [Answer] # Bash + GNU utilities, 204 ``` fold -$1|sed 2~2{s/.\\+/printf\ %$1's "`echo "&"|rev`"/e y/'`printf %s {A..Z} {a..z}`"&_?!\"'.,/∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Zɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz⅋‾¿¡„,˙'/ }" ``` N is given on the command line and S is given via STDIN: ``` $ echo "The quick brown fox jumps over the lazy dog." | ./boustrophedon.sh 30 The quick brown fox jumps over ˙ƃop ʎzɐl ǝɥʇ $ ``` ### Explanation * `fold -N` splits the input into lines of length N. * The rest of the processing is done by sed, line-by-line: + `2~2` matches every other line, starting at line 2 + `s/.+/printf %'N's "`echo "&"|rev`"/e` uses GNU Sed's exec feature to call a shell to reverse the line and left-pad it with up to N spaces + `y/ABC.../∀qƆ.../` transform characters Note `ABC...` is generated using a bash expansion and printf. Also some fancy quoting for all the different characters. [Answer] # [Japt](https://github.com/ETHproductions/Japt), ~~182~~ 179 bytes **Japt** is a shortened version of **Ja**vaScri**pt**. [Interpreter](https://codegolf.stackexchange.com/a/62685/42545) ``` Ur'.+".?"pV-1 ,@A++%2?SpV-Xl)+Xw m@"„\xA1⅋,'˙¿∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Z[\\]^‾`ɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz"g(Q+"!&',.?"+65o124 m@Xd)a)bX)||X +R:X+R ``` ### How it works ``` // Implicit: U = input string, V = input number, A = 10 Ur // Take U and replace each group X of: '.+".?"pV-1 // at least one char, followed by up to V-1 other chars // literally: RegExp("." + ".?".repeat(V-1)) @ // with: (@ is compiled to (X,Y,Z)=>) A++%2? // If we're on an odd row: SpV-Xl)+ // Pad it with spaces, then concatenate it with Xw m@ // X reversed, with each character X mapped to: "..."g // The character at position N in the string, where N is: (Q+"!&',.?" // Build a string from a quote mark and these chars, 65o124 m@Xd)a) // and all chars from A..z. bX) // Return the index of X in this string. ||X // or if this number is outside the string, default to the original char. +R // Either way, add a newline. :X+R // Otherwise, return the original row text plus a newline. // Implicit: output last expression ``` There are a couple of problems, but they shouldn't affect the validity of the program: 1. User [@Vɪʜᴀɴ](https://codegolf.stackexchange.com/users/40695/v%c9%aa%ca%9c%e1%b4%80%c9%b4) has recently helped me implement Unicode Shortcuts, or single characters in the range 00A1-00FF that stand in for commonly-used several-char sequences. The problem with this is that it currently replaces inside strings, so we can't use ¡ directly in the string for now. The safe alternative, `\xA1`, is three bytes longer. 2. It's currently impossible to input a double-quote character. This will be fixed shortly. Perhaps there's a way to shorten the string. Suggestions are welcome! [Answer] # CJam, 152 ``` l~_q/\f{Se]}2/{)26,'Af+_el+"&_?!'.,"`+"∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Zɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz„⅋‾¿¡,˙'"erW%}%N* ``` [Test it here.](http://cjam.aditsu.net/#code=l~_q%2F%5Cf%7BSe%5D%7D2%2F%7B)26%2C'Af%2B_el%2B%22%26_%3F!'.%2C%22%60%2B%22%E2%88%80q%C6%86p%C6%8E%E2%84%B2%D7%A4HI%C5%BF%CA%9E%CB%A5WNO%D4%80Q%C9%B9S%E2%94%B4%E2%88%A9%CE%9BMX%E2%85%84Z%C9%90q%C9%94p%C7%9D%C9%9F%C6%83%C9%A5%E1%B4%89%C9%BE%CA%9El%C9%AFuodb%C9%B9s%CA%87n%CA%8C%CA%8Dx%CA%8Ez%E2%80%9E%E2%85%8B%E2%80%BE%C2%BF%C2%A1%2C%CB%99'%22erW%25%7D%25N*&input=50%0ALorem%20ipsum%20dolor%20sit%20amet%2C%20consectetur%20adipiscing%20elit.%20Quisque%20vel%20libero%20arcu.%20Nunc%20dictum%20elementum%20lectus%20nec%20aliquet.%20Donec%20dolor%20nunc%2C%20sodales%20at%20dolor%20rhoncus%2C%20hendrerit%20scelerisque%20purus.%20Pellentesque%20vel%20sagittis%20libero%2C%20et%20rutrum%20leo.%20Nullam%20vulputate%20enim%20et%20massa%20dictum%2C%20vitae%20venenatis%20augue%20lobortis.%20Fusce%20sollicitudin%20ultrices%20consequat.%20Vestibulum%20quis%20nunc%20non%20tortor%20eleifend%20facilisis.%20In%20at%20nunc%20elit.%20Aliquam%20pellentesque%2C%20lectus%20quis%20aliquam%20posuere%2C%20quam%20lectus%20sagittis%20metus%2C%20ut%20auctor%20sem%20quam%20a%20neque.%20Integer%20rhoncus%20lobortis%20nisl.%20Pellentesque%20mi%20dui%2C%20laoreet%20in%20metus%20quis%2C%20mollis%20accumsan%20est.%20Nunc%20dignissim%20tortor%20ac%20eleifend%20tempus.%20Ut%20ut%20tellus%20aliquam%2C%20luctus%20nulla%20quis%2C%20consectetur%20nunc.%20Suspendisse%20viverra%20molestie%20condimentum.%20Curabitur%20et%20hendrerit%20augue.) I guess I should look into compressing that Unicode string a bit... [Answer] ## Javascript (ES6), ~~407~~ ~~400~~ ~~366~~ ~~360~~ 353 bytes I'm counting only the first two "lines" in this snippet as the total count, as the rest of it is code to run it. ``` s=`ABCDEFGHIJKLMNOPQRSTUVWXYZ∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Zabcdefghijklmnopqrstuvwxyzɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz&_?!"'.,⅋‾¿¡„,˙'`,f=(i,w)=>(i=i.match(RegExp(`.{1,${w}}`,"g")),i.map((c,x)=>x%2?" ".repeat(w-c.length)+[...c].reverse().map(b=>(d=s.indexOf(b),"A"<=b&&"z">=b?s[d+26]:" "==b?b:s[d+8])).join``:c).join` `) let input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vel libero arcu. Nunc dictum elementum lectus nec aliquet. Donec dolor nunc, sodales at dolor rhoncus, hendrerit scelerisque purus. Pellentesque vel sagittis libero, et rutrum leo. Nullam vulputate enim et massa dictum, vitae venenatis augue lobortis. Fusce sollicitudin ultrices consequat. Vestibulum quis nunc non tortor eleifend facilisis. In at nunc elit. Aliquam pellentesque, lectus quis aliquam posuere, quam lectus sagittis metus, ut auctor sem quam a neque. Integer rhoncus lobortis nisl. Pellentesque mi dui, laoreet in metus quis, mollis accumsan est. Nunc dignissim tortor ac eleifend tempus. Ut ut tellus aliquam, luctus nulla quis, consectetur nunc. Suspendisse viverra molestie condimentum. Curabitur et hendrerit augue."; console.log(f(input, 50)); ``` ### Explanation ``` s=`A∀ .. ZZaɐ .. &⅋ ..`, //Character translation "map" f=(i,w)=> //Create a function named "f" that takes an (i)nput string and (w)idth ( //Implicitly return i=i.match(RegExp(`.{1,${w}}`,"g")), //Cut string into arrays every w-th match of anything i.map((c,x)=> //Loop through each element in array by (c)ut at inde(x) x%2 //If the index is odd ?" ".repeat(w-c.length) //Output spaces for padding +[...c].reverse() //Split this cut into each character, and read it backwards .map((b,d)=>( //Translate each character d=s.indexOf(b), //Save where this character appears in the mapping "A"<=b&&"z">=b //If the character is a-zA-Z ?s[d+26] //Print the flipped character by looking 26 characters ahead of where this character is found :" "==b //Else, if it's a space ?b //Output the space :s[d+8])) //Else, print the flipped punctuation character (only 8 of these) .join`` //Join everything back into a continuous string :c //Else just output the whole cut ).join` `) //Finally join each cut by a newline ``` --- * Thanks to Dendrobium for -6 bytes! * Thanks to the Closure Compiler for -34 bytes! * Thanks to ןnɟuɐɯɹɐןoɯ for -7 bytes! [Answer] # Pyth, 141 bytes ``` FNrZlKczQI%N2X.[" "Q_@KN++GrG1"&_?!\"'.,""ɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Z⅋‾¿¡„,˙'")E@KN ``` [Tested with an online Pyth Compiler.](http://goo.gl/tmX7l5) **How it Works** ``` FNrZlKczQI%N2X.[" "Q_@KN)E@KN █ █ FN █ For N in r █ ├ Range Z █ | ・Start: 0 █ | ・End: l █ | Length of K █ | └─K = c █ | Split z █ | ・String z Q █ | ・By input int Q I%N2 █ └─If divisible by 2 X █ └─Translate █ ├─Source: .[ █ | ├─Pad left " " █ | | ・With spaces Q █ | | ・Until input int Q _ █ | └──Reverse @KN █ | ・Nth line of K ++GrG1...█ ├─From: Normal (See below) "ɐqɔpǝ...█ └─To: Flipped (See below) )E@KN █ Else print Nth line of K ``` **Map** Normal ``` ++ █ Append: G █ 1) a to z rG1 █ 2) A to Z "&_?!\"'.," █ 3) Punctuation ``` Flipped (Nothing fancy) ``` "ɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Z⅋‾¿¡„,˙'" ``` [Answer] # Python, ~~453~~ 363 bytes ``` s,n=input() o="""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz&_?!"'.,""" p="""∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Zɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz⅋‾¿¡„,˙'""".decode('utf8') s=map(''.join,zip(*[iter(s+' '*(n-1))]*n)) for i in range(len(s)): if i%2:s[i]=''.join(p[o.find(c)].encode('utf8')for c in s[i][::-1]) for l in s:print l ``` ]
[Question] [ Related puzzle: Pathfinder (available on [Puzzle Picnic](http://puzzlepicnic.com)) ## Background A robot is standing on a cell of a rectangular grid, where each cell has one or more gems except for the one with the robot. The robot can move to a horizontally or vertically adjacent cell in one step, and it picks up one gem from the cell it steps on. The robot is programmed with which cell to choose for its next step, based on the number of gems each adjacent cell contains. The program is in the form of `a > b > c > ... > z`, which means that the robot prefers to move into the cell with `a` gems, followed by one with `b` gems, and so on. Any such program contains positive integers from 1 to `n` exactly once, where `n` is the length of the program. The robot will never move into any cell with no gems. If there are multiple highest-priority cells around the robot, or all the cells around it are empty, it will get stuck at that point. For example, if its program is `1 > 3 > 2` (meaning, it prefers the cell with only one gem the most, followed by the one with 3 gems, and then 2 gems) and the current state looks like this (R is the robot, the numbers are gems): ``` 0 3 2 2 R 1 1 2 3 ``` Then it will choose the cell on its right because 1 has the highest priority. Assuming the cell with R is empty, it will continue moving down, left, left, right, right, then get stuck since the cells around it have no gems left. ``` 0 3 2 0 3 2 0 3 2 0 3 2 0 3 2 0 3 2 0 3 2 2 R 1 --> 2 0 R --> 2 0 0 --> 2 0 0 --> 2 0 0 --> 2 0 0 --> 2 0 0 1 2 3 1 2 3 1 2 R 1 R 2 R 1 2 0 R 2 0 0 R R D L L R R ``` Using the `1 > 3 > 2` program, it will get stuck at any of the following cases: ``` 0 R 0 # all adjacent cells are empty 2 0 1 1 2 2 3 1 0 # there are two 1s around the robot, so it can't decide where to go 2 R 1 1 0 2 ``` ## Challenge Given the initial state of the entire grid and the robot's program, find the position (horizontal and vertical coordinates) in the grid where the robot will eventually get stuck. The initial state contains the numbers between 1 and 9 inclusive, except for a single 0 which denotes the initial position of the robot. The program is guaranteed to contain all positive numbers that appear in the grid, and the program is always valid (contains each of 1 to the maximum value on the grid exactly once). You can take the input (grid and program) in any suitable format, and output the coordinates in any sensible way. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases In the example I/O provided, the program has the highest precedence coming first, and the coordinates are 1-based. ``` Grid: 0 2 1 3 3 2 1 1 3 Program: 3 1 2 Result: 2nd row, 3rd column (Path: DRDRUUD) Grid: (one row) 0 3 2 3 1 4 4 Program: 4 2 3 1 Result: 1st row, 7th column (Path: RRLRRRRRLRLRLR) Grid: 0 1 3 3 1 3 2 1 2 Program: 3 1 2 Result: 3rd row, 3rd column (Path: DRRULRDD) Grid: 2 3 1 2 1 2 0 3 2 2 1 1 3 1 1 Program: 1 3 2 Result: 2nd row, 4th column (Path: DLUUDURRDDRRUULD) Same grid as above, Program: 3 2 1 Result: 2nd row, 2nd column (Stuck at zero moves) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~205~~ 198 bytes ``` def s(g,w,r): p=g.index(0) while 1: a=[((r+[0]).index(v),n)for n,v in enumerate(g)if(abs(n-p)in[1,w])>(p-n)%w*(p/w!=n/w)];m,n=min(a) if~-sum(k[0]==m<len(r)for k in a):return p/w,p%w p=n;g[p]-=1 ``` *-6 bytes thanks to @ovs* *-1 byte thanks to @user202729* [Try it online!](https://tio.run/##tZJRa9swFIWfo1@hGgr3btdrZGcUnKkwygaDvYU9GT@ojeyIxqqwnbrdw/56JtlJ6q3ty2AyyJJ173eOzHFP3ebeJvv9Wpe8hYp6ajBj3Mnqg7Fr/QhzZLzfmK3mImMzJXOA5n0@L/Bw/oBksbxvuKUHbizXdlfrRnUaKjQlqJsWbOzQ2FxQX@AVuNjief8O3EV/Ju1Fj8WyJitrY0Ehm5nyV9zuarjzGlLWn7baQjMI3AW8wqzR3a6x3PeTO@/ZzEm7rHJXxFLsb1WrWy55zrgfMMxh5HNKSFDqn/D2q4JOh@mryzz1ZcmkDBJKcdghvcQHcOhY0GLSI56XlxP0YiyewgVdvg0fnYuD@@QfvKdvex99D2Aa73H4RWF@XerjRGpwNSnzvEXxf6SG6/8plRykWMFCRirahAiTfnT6ttPrEJkhE9lQ5nw0jikfPzTGdqeuSF5F5Ea@KbmyT6Bjwc8kVzzQFekA/GkcOOJHDcTs5GjkRV8/f/u@PBVkEXE4bnysY/HcnAu/Hb3obav/IkG0@nF9/WW1ipDtfwM "Python 2 – Try It Online") Take the input grid as a flattened list with width also passed. Outputs 0-indexed (x,y) coordinates of the final position (I doubt index in the flattened list would be acceptable). ### Explanation: ``` # Function of flattened grid g, width w, pRiorities r def s(g,w,r): # starting position p p = g.index(0) while 1: a = [ # pair (priority rank of the cell, cell id) # priority rank is n for v=0 ((r+[0]).index(v),n) # for each adjacent cell id n with v gems for n,v in enumerate(g) if abs(n-p) in [1,w] and (p%w==n%w or p/w==n/w) ]; # min comparison is done by tuple, so it selects one with minimum priority rank # m = min priority rank; n = corresponding cell id m,n = min(a) if sum( # how many adjacent cells k[0]==m # have priority rank equal to m <len(r) # and the cell value is not 0 for k in a ) ^ 1: # If this count is not 1, then the robot is stuck; return return(p/w, p%w) # Otherwise, continue with updated position, p = n; # and take one gem g[p] -= 1 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 70 bytes ``` ≔⪪S¹θWS⊞υι≔⪫υ¶ηPη…η⌕η0≔EKV⌕θιυW⁼¹№υ⌈υ«M✳⁻χ⊗⌕υ⌈υPI⊖KK≔EKV⌕θκυ»≔⟦ⅈⅉ⟧υ⎚Iυ ``` [Try it online!](https://tio.run/##jVBLS8QwED5vf0XoaQIVmva4J2kVFCqFBVHUQ7YbNmHTpI9kVcTfXid1l6onD3lMvvkek0byobFcT9PlOKq9gU2nlYMb03m3cYMye6AJYbh6uo5epdKC/EYpqf0owSdEYcdJ5dYqE57iZxMjVyJSee1UhxwHoaznW/HeaFFI24FMyLUyu3DGaUzpolXxDmohDvfW3AnfcmNCpLm5D6ZY@CXbVe@5HoElpLAeHTBExd9U61vwqErJR7Sq7FFAqQbROGXRQBmPjDQhpfVbLXYwi/9losfqxxAFHx2UohlEK4xDUsgIp75/RT@co3@eR316CPgj0JdvoNCCD7D8VrDELOtpynIW4cpwT/MsixjLGYumi6P@Ag "Charcoal – Try It Online") Link is to verbose version of code. Takes input as the program in ascending order of priority and then the newline-terminated grid and outputs 0-indexed coordinates. Explanation: ``` ≔⪪S¹θ ``` Input the program as separate characters. ``` WS⊞υι≔⪫υ¶η ``` Input the grid. ``` Pη…η⌕η0 ``` Print the grid without moving the cursor, then print the part up to the `0` so that the cursor is now at the starting cell. ``` ≔EKV⌕θιυ ``` Get the priorities of the neighbours of the starting cell (or `-1` for directions that lie outside the grid). ``` W⁼¹№υ⌈υ« ``` Repeat while there is exactly one neighbouring cell of highest priority. ``` M✳⁻χ⊗⌕υ⌈υ ``` Move to that neighbour. ``` PI⊖KK ``` Decrement its value. ``` ≔EKV⌕θκυ ``` Get the priorities of the neighbours of the new cell (or `-1` for illegal directions). ``` »≔⟦ⅈⅉ⟧υ ``` Capture the final position. ``` ⎚Iυ ``` Clear the grid and output the position. [Answer] # JavaScript (ES7), ~~142~~ 130 bytes Expects `(program)(matrix)`, with highest precedence coming first for the program. Returns `[column, row]`, both 0-indexed. ``` p=>m=>(g=(a,X,Y)=>a.some(k=>m.map((r,y)=>r.map((v,x)=>(X-x)**2+(Y-y)**2-1|v^k||(H=x,V=y,n--)),n=1)|!n)?g(p,H,V,m[V][H]--):[X,Y])`` ``` [Try it online!](https://tio.run/##fVDRaoNAEHzPV1zf9tI96WmeAmdf/QJJOK7kSI20iXeiRRT8d7vRYivSwLHczO7MDvtpG1ufq4/ySzj/ng0XNZQqLlQMuQKLBzxyFdug9kUGV2oEhS0BKuyIribQYEsADqLl2234DEfR3T9C9s3bte8hUS2mqkMnBOfolOT9k@OvOZSYYIqFTo1ODDX3mtYZfjoNZ@9qf8uCm89hw9gFdIRMIgsNJwiaCmOavRBDPDP4Q9AUvfCXkKMsYoYwaflm7bwbTe7@K/NobiGjsd0jm/8CTuv/BFwS4SR75CynIEvnOdfyAITm3OszjFXOu4Zv "JavaScript (Node.js) – Try It Online") ### Commented ``` p => m => ( // p[] = program, m[] = matrix g = ( // g is a recursive function taking: a, // a[] = list of possible neighbor values, // from most to least preferred X, Y // (X, Y) = current position ) => // a.some(k => // for each value k in a[]: m.map((r, y) => // for each row r[] at position y in m[]: r.map((v, x) => // for each value v in r[]: (X - x) ** 2 + // compute the squared distance (Y - y) ** 2 // between (X, Y) and (x, y) - 1 | // abort if it's not equal to 1 v ^ k || // or v is not equal to k ( // otherwise: H = x, V = y, // save (x, y) in (H, V) n-- // decrement n ) // ), // end of inner map() n = 1 // start with n = 1 ) // end of outer map() | !n // yield a truthy value if n = 0 ) ? // end of some(); if truthy: g( // do a recursive call to g: p, // using a[] = p[] H, V, // using (X, Y) = (H, V) m[V][H]-- // decrement the cell at (H, V) ) // end of recursive call : // else: [ X, Y ] // we're stuck: return (X, Y) )`` // initial call to g with a[] = [''] ``` Because `g` is first called with `a = ['']` and both `X` and `Y` undefined, the test on the squared distance is disabled (because it's always NaN'ish) and `v ^ k` is equal to `0` only if `v == 0`. So the first recursive call is triggered on the `0` cell as expected. [Answer] # [J](http://jsoftware.com/), 109 bytes Takes in the program on the left, the grid on the right, and returns the 1-based end position. ``` ($-_2&u)@((](r@|.~d{.@/:])`[@.(]2=/@{./:~)[i.(d=:(,-)=i.2){::])^:_)0(]|.~u=:$@]#:(i.~,))_1(r=:-1$!.0~$)@,._,] ``` [Try it online!](https://tio.run/##lY4xa8QwDIV3/wr1anoSOErsBAoKBkOhU6euh@sbjgvpeHBTSv56arvZCoUO0vD0vaf3uR34eAUvcAQDHUiehuHl/e11Q90k93SngBjxFr54vSwcWol0PgXG6HwbFm5lpdPMePGCpiE/s6NFMvQhiTqM2Xb3okN8FJx5NUTJ4s1LY/UDd6umYDiZuNE2eRnHq1I9WHAwwYFHTg6wtiLVZdHmYw9O2Yz0ipQaslj4CdDCM@hcv9@lAQb6I6wE9HW7gpQwW72/2J@48tzt8XuBPFbVH65W@J/vGw "J – Try It Online") ### How it works Because I didn't want to handle 3 arguments (program + grid + current position) as this is awkward in tacit J definitions, this approach shifts the grid around with the upper left tile having the robot. A fix point `_2` to reconstruct the end position is in the padding. ``` _1(r=:…)@,._,] ``` Pad with `_` on the top, and `_1` on the left. ``` r=:-1$!.0~$ ``` This subtracts one from the top left tile. That makes the `_1` to a `_2`, and as we'll use this later again, assign this function to `r`. ``` 0(]|.~u=:$@]#:(i.~,)) ``` This is a bit longer than needed, but in this version we can assign `x u y` to find the position of `x` in the grid `y`. Here we use it to shift the grid so the `0` is at the top left – later we'll use it to search for the `_2`. ``` (…)^:_ ``` Until the output of `…` does not change, i.e. until the robots moves: ``` (d=:(,-)=i.2) ``` The 4 directions, saved as `d`. ``` (d=:…){::] ``` Get the numbers at the directions, e.g. `0 0 3 1`. ``` [i. ``` Find their position in the program with non-found numbers like `0 _ _1` having program length + 1, e.g. with `1 2 3`: `3 3 2 0`. ``` ](…)`[@.(]2=/@{./:~) ``` If the first 2 items of the sorted indices `0 2 3 3 -> 0 2` are equal, return the grid (stop moving), otherwise … ``` r@|.~d{.@/:] ``` Sort the directions based on the indices. Take the first one, shift the grid by it and call `r` to subtract 1 from the top left, i.e. the robots takes a gem. ``` ($-_2&u)@ ``` After the robot stopped moving, find the `_2` and subtract its position from the grid size to get the final result. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~289~~ \$\cdots\$ ~~246~~ 243 bytes Saved a whopping ~~37~~ ~~41~~ ~~43~~ 46 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` q;c;v;s;d;i;b;u;r;f(g,e,w,p,n)int*g,*p;{r=wcslen(g);for(c=d=0;c-n&&!d;!d&c<n&&--g[r=s])for(c=n,b=4;b--;d=v?q<c?c=q,s=u,0:q>c?d:1:d)for(i=~-(b&2)*(b&1?1:w),v=g[u=r+i]*(u>=0&u<e)*(r%w|~i&&r%w-w+1|i-1),q=0,i=n;i--;)q+=v-p[i]?0:i;*g=r/w;g[1]=r%w;} ``` [Try it online!](https://tio.run/##rVVdb5swFH3Pr3CRgoAYFUi6qThuHqZpr9NeaTQ1hjBHlDgmCdHa9K9nlw8DCWxPizC@@Jz7wXG4ZnbM2OWyI4wcSUZCwsmKHIgkayPGEc6xwKnJ070VY0uQN0lzliVRasQmWW@lwWhIHcLsVNfvQnIX6mwOpm3HgaTZ0qwoKV7RGVnZNgnpcbGbswWjO5zRA3b83RNbhL7rhyWX0w/bWOmeacHdXbh@buIjjYMDlRO@tIzDE3X0wzwCXI7z9w@u6zDb@cR957Zr4h11MKcp4ZDL3E3o0RYBXy4cnxMrpvI@J3HgLin4kPNFSHgvo3g3lGAEM2LVJE30NkLwg5JQQUAcUeQQmOaIETSZcMW4Ym0q1gZYsmBtTFTmWBvaOBuHGkabhYY0XwMrCbgl0QRtliZpIin2c6rVq@fReVSEfn3hqWGOqqTFwj7K9j9jJ1hCzjcHI@TBcGFM66Gey7UzuXF0W0dFntbkWTF6Dl7r0M3i3mTzeo7TyrGbwevM3QquSlZ2L@DsvwW06ohZFbGWFCuJlOEpY6qMnjx5FQEIn3GR6QGuW05ScR5LDtzdh2LcsoTThIICenKKeuNgk7wyU08f4f07QL0fbundh2eNt4cHtBJdrYTSSiithNJKKK1ET6u0yTArayiuDic6iei0j8JKh7JQbwB2axhK@DQAezXsDXtP2@BDuWctfCWBwmu4KRW3ZbWm15rT1lRysF8v0kKy0kJ7Pn31nk@PX2A8QHPoPk818LjpRmkYneqOVJpzlPHf0XZtqCzmfb1gNStl2yrY3dZVvlUModSHUDKWpEtAKFGEZBjPFZ4P4RYSChd/SZAqQjocIAK80f6WoZrmN8lDv@2cDQTnGEruc4zygU77XW5j@fLqo76bKD@gtLNeHIlJfSRevwHbShmxPZQZBw5sKZRbzLqOivOmenYHav4RZYdk76NxiGGgcQb14zIGLj0x/EPq2EPnhD38uzo@Ln8A "C (gcc) – Try It Online") Inputs the grid as a flat array, the length of that array, the grid width, the program as an array of integers and the length of the program. Returns the robot's final position (as zero-based row and column) by storing them in the first two positions of the grid. **Before golfing** ``` new_rank;current_rank;new_value;current_pos;has_doubled;i;news_bits;new_pos;robot_pos; f(grid,grid_end,grid_width,prog,prog_end)int*grid,*prog;{ for(robot_pos=0;grid[robot_pos];++robot_pos); for(current_rank=has_doubled=0; current_rank!=prog_end && has_doubled == 0;) { for(current_rank=prog_end,news_bits=0; news_bits<4; ++news_bits) { i = (news_bits&2 - 1)*(news_bits&1?1:grid_width); new_pos = robot_pos + i; new_value = new_pos >= 0 && new_pos < grid_end?grid[new_pos]:0; if((robot_pos%grid_width == 0 && i == -1) || (robot_pos%grid_width == grid_width-1 && i == 1)) new_value = 0; for(i = 0; i < prog_end; ++i) if(new_value == prog[i]) new_rank = i; if(new_value > 0 && new_rank == current_rank) { has_doubled = 1; } if(new_value > 0 && new_rank < current_rank) { current_rank = new_rank; current_pos = new_pos; has_doubled = 0; } } if (has_doubled == 0 && current_rank < prog_end) { robot_pos = current_pos; --grid[robot_pos]; } } grid[0]=robot_pos/grid_width; grid[1]=robot_pos%grid_width; } ``` ]
[Question] [ Suppose we start with the infinite list of prime numbers: ``` [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, ... ``` Then, we take the absolute differences between each pair of numbers, repeatedly: ``` [1, 2, 2, 4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, ... [1, 0, 2, 2, 2, 2, 2, 2, 4, 4, 2, 2, 2, 2, 0, 4, 4, 2, ... [1, 2, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 0, 2, 4, 0, 2, ... [1, 2, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 2, 2, 4, 2, ... ``` Notice that the leading number is 1 every time. [Gilbreath's Conjecture](https://en.wikipedia.org/wiki/Gilbreath%27s_conjecture) is the prediction that this continues to be the case forever. The only way the leading number would stop being a 1 is if the next number after it was neither a 0 nor a 2. The only way the second number wouldn't be a 0 or a 2 is if the number after that was neither a 0 nor a 2. And so on. The index of the earliest number, other than the leading 1, which is neither a 0 nor a 2, can never go down by more than 1 between a consecutive pair of sequences. This fact has been used to put a very strong lower bound on when, if ever, a sequence might not have a 1 as the first element. In this challenge, you will be given the index of a sequence, and you must output the index of the first number in that sequence which is not the leading 1, and is not a 0 or a 2. For instance, in the 4th absolute difference sequence above: ``` [1, 2, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 2, 2, 4, 2, ... ``` The first entry that's neither a zero or a two, other than the first entry, is the 15th position, 14 zero indexed. So if the input was 4, you would output 14. For inputs from 1 to 30, the outputs should be: `[3, 8, 14, 14, 25, 24, 23, 22, 25, 59, 98, 97, 98, 97, 174, 176, 176, 176, 176, 291, 290, 289, 740, 874, 873, 872, 873, 872, 871, 870]` This is [OEIS A000232](https://oeis.org/A000232). This is assuming you have 1 indexed inputs and 0 indexed outputs. You may index your inputs and outputs starting at any constant integers, as long as you can accept the range of inputs corresponding to all sequences. Requirements: Your solution must run in at most 1 minute on a input of up to 30. If it's close enough that it depends on the computer specs, it's allowed. Shortest code wins. [Answer] # Mathematica, 66 bytes ``` (For[z=1,Last@Nest[Abs@*Differences,Array[Prime,z+#],#]<3,z++];z)& ``` Pure function taking a positive integer as argument and returning a 1-indexed integer. `Nest[Abs@*Differences,Array[Prime,z+#],#]` computes the `#`th iterated absolute difference list of the list of the first `z+#` primes. `For[z=1,Last@...<3,z++]` loops this computation until the last element of the resulting list is at least `3`, and then `z` is output. (Note that the correctness of the algorithm assumes Gilbreath's conjecture!) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 32 bytes ``` -l.W>3h.WtHaVZtZ>QH+ZfP_TheZ.fP_ ``` [Try it online!](http://pyth.herokuapp.com/?code=-l.W%3E3h.WtHaVZtZ%3EQH%2BZfP_TheZ.fP_&test_suite=1&test_suite_input=2%0A3%0A4%0A5%0A6%0A31&debug=0) Uses 2-indexing. [Answer] # [MATL](https://github.com/lmendo/MATL), 18 bytes ``` `@:YqG:"d|]3<A}@G- ``` Input and output are 1-based. It takes less than 40 seconds in TIO for each of the test cases. [Try it online!](https://tio.run/nexus/matl#@5/gYBVZ6G6llFITa2zjWOvgrvv/v7EBAA "MATL – TIO Nexus") ### Explanation This keeps trying longer initial sequences of primes until the iterated absolute consecutive differences give at least one value exceeding `2`. ``` ` % Do... while loop @:Yq % Array of first k primes, where k is iteration index G:" % Do this as many times as the input d| % Absolute value of consecutive differences ] % End 3<A % Are they all less than 3? This is the loop condition } % Finally (execute before exiting loop) @G- % Push last iteration index minus input. This is the output % End (implicit). Continue with next iteration if top of stack is true % Display (implicit) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` ÆNạ2\Ḋ¿Ḣ’Ị R‘ÇпL ``` [Try it online!](https://tio.run/nexus/jelly#AS4A0f//w4ZO4bqhMlzhuIrCv@G4ouKAmeG7igpS4oCYw4fDkMK/TP8ycjMxw4figqz/ "Jelly – TIO Nexus") Input is 2-indexing. Output is 1-indexing. On TIO all testcases in total take 22.309 s. [Answer] # [Perl 6](http://perl6.org/), ~~136~~ 120 bytes ``` {->\i,\n{i??&?BLOCK(i-1,lazy n.rotor(2=>-1).map: {abs .[1]-.[0]})!!1+n.skip.first: :k,none 0,2}($_,grep &is-prime,2..*)} ``` Ungolfed: ``` { # Anonymous function with argument in $_ sub f(\i, \n) { # Recursive helper function if i != 0 { # If we're not done, # Recurse on the absolute differences between adjacent entries: f(i - 1, lazy n.rotor(2 => -1).map: { abs .[1] - .[0] }); } else { # Otherwise, return the first index after 0 # where the value is neither 0 nor 2. 1 + n.skip.first: :k, none 0, 2; } } # Call the helper function with the argument passed to the top-level # anonymous function (the recursion depth), and with the prime numbers # as the initial (infinite, lazy) list: f($_, grep &is-prime, 2 .. *); } ``` With an input of 30, the function runs in about four seconds on my modest laptop. ...which becomes 1.4 seconds after upgrading my seven-month-old Perl 6 installation (which also gives me the `skip` method that lets me shave off several bytes from my first solution). All test cases from 1 to 30 take about ten seconds. [Answer] # [Haskell](https://www.haskell.org/), 94 bytes ``` f(a:b:r)=abs(a-b):f(b:r) length.fst.span(<3).(iterate f[n|n<-[2..],all((>0).mod n)[2..n-1]]!!) ``` [Try it online!](https://tio.run/nexus/haskell#FcjBCsMgDADQ@74ihR0SWEO73krdjxQPkakraCbW4/7d0eN7PaCsbq1kxJ0oo6M14OVbNMlrbB8OZ@OziOK2EOPRfJXmIez6023cn8z2ISkhvibi/H2D0pU6ztYOA/Ush4KBUg9tcIcsBSLsM/My2f4H "Haskell – TIO Nexus") The last line is an anonymous function. Bind to e.g. `g` and call like `g 4`. All test cases combined take less than 2 seconds on TIO. ### How it works `[n|n<-[2..],all((>0).mod n)[2..n-1]]` generates an infinite list of primes. `f(a:b:r)=abs(a-b):f(b:r)` is a function yielding the absolute differences of the elements of an infinite list. Given a number `n`, `(iterate f[n|n<-[2..],all((>0).mod n)[2..n-1]]!!)` applies `f` `n` times to the list of primes. `length.fst.span(<3)` computes the length of the prefix of the resulting list where the elements are smaller 3. [Answer] # Axiom, 289 bytes ``` g(n:PI):PI==(k:=n*10;c:List NNI:=[i for i in 1..(k quo 2)|prime?(i)];repeat(a:=concat(c,[i for i in (k quo 2+1)..k|prime?(i)]);j:=0;c:=a;repeat(j=n=>break;j:=j+1;b:=a;a:=[abs(b.(i+1)-b.i)for i in 1..(#b-1)]);j:=2;repeat(j>#a=>break;a.j~=2 and a.j~=1 and a.j~=0=>return j-1;j:=j+1);k:=k*2)) ``` ungolf it and test ``` f(n:PI):PI== k:=n*10 c:List NNI:=[i for i in 1..(k quo 2)|prime?(i)] repeat a:=concat(c,[i for i in (k quo 2+1)..k|prime?(i)]) j:=0;c:=a repeat j=n=>break j:=j+1 b:=a a:=[abs(b.(i+1)-b.i) for i in 1..(#b-1)] j:=2 repeat j>#a=>break a.j~=2 and a.j~=1 and a.j~=0 => return j-1 j:=j+1 k:=k*2 (4) -> [g(i) for i in 1..30] (4) [3, 8, 14, 14, 25, 24, 23, 22, 25, 59, 98, 97, 98, 97, 174, 176, 176, 176, 176, 291, 290, 289, 740, 874, 873, 872, 873, 872, 871, 870] ``` it if not find the solution expand the prime list of 2\*x in a loop and recompute all the remain lists. 3 seconds for find g(30) ]
[Question] [ Year of 2010, an Icelandic Vulcano, concisely named [Eyjafjallajökull](https://en.wikipedia.org/wiki/File:Is-Eyjafjallaj%C3%B6kull_(3).oga) erupted, resulting in my long-planned flight being canceled. In case this ever happens again, I would really like to know in advance, so please help me build a simple visual alert system ! **Input** Take the [Icelandic Meteorological Office](http://en.vedur.is/earthquakes-and-volcanism/volcanic-eruptions/) volcanic activity alert code, as an input (string): *GREEN* - Volcano is in normal, non-eruptive state. *YELLOW* - Volcano is experiencing signs of elevated unrest above known background levels. *ORANGE* - Volcano is exhibiting heightened unrest with increased likelihood of eruption. *RED* - Eruption is forecasted to be imminent with significant emission of ash into the atmosphere likely. **Output** The graphic (ASCII art) alert, illustrating the state of Eyjafjallajökull. *GREEN* (Eyjafjallajökull is resting) ``` al la j j jaf öku y l E l ------------------- ``` *YELLOW* (some smoke appears !) ``` ~ ~ ~ al la j j jaf öku y l E l ------------------- ``` *ORANGE* (more smoke !) ``` ~ ~ ~ ~ ~ ~ al la j j jaf öku y l E l ------------------- ``` *RED* (even more smoke and some ash, too !) ``` `~ ~ ~ ~ ~ ~` ` ~ ~ ~ ` ` ~ ~ ` ` ~ ` al la j j jaf öku y l E l ------------------- ``` **Rules** * You may output to the screen (stdout), or return a string * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") ! The shortest answer (in bytes), wins * Feel free to replace **ö** with **o** * Trailing spaces are allowed, but not required * At most one trailing newline is allowed * At most 4 leading newlines are allowed (in place of smoke) [Answer] ## Batch, 284 bytes ``` @set e=echo @%e%off set s= set t= goto %1 :RED set t= ` %e% `~ ~ ~ ~ ~ ~` :ORANGE %e% %t%~ ~ ~%t% :YELLOW %e% %t%~ ~%t% %e%%s%%t%~%t% :GREEN %e%%s%al la %e% j%s% j %e% jaf %s% oku %e% y %s%%s% l %e%E%s%%s%%s%l %e%-------------------- ``` Note: Lines 1 and 7 have one trailing space, line 3 has six and line 4 has three. [Answer] # Ruby, 161 Here's my take on Iceland's famous landmark, the Eyjafjallajökull Tower. Reasonably short but I haven't come up with a good way to golf the smoke yet. ``` ->n{m=85-n[-3].ord>>2 %w{`~+~+~+~+~+~` `+~++~++~+` `+~+++~+` `+~+` al%3sla j%7sj jaf%9soku y%15sl E%17sl}.map{|i|(i%"").tr(?++?`*m," ").center(19)}[m,9]+[?-*19]} ``` **Ungolfed in test program** ``` f=->n{m=85-n[-3].ord>>2 #From ASCII code of 3rd from last letter, derive m=0 for RED up to 4 for GREEN (uppercase.) %w{`~+~+~+~+~+~` `+~++~++~+` `+~+++~+` `+~+` al%3sla j%7sj jaf%9soku y%15sl E%17sl}. map{|i| #For each line above decode as follows: (i%""). #Replace %Xs with X spaces, by inserting empty strings and padding sprintf style. tr(?++?`*m," "). #Replace + with space. If not red, replace ` with space. center(19)}[m,9]+ #Centre output to 19 characters per line. Start printing at line m and go on to the end (never more than 9 lines.) [?-*19] #Add a row of --- at the bottom. } puts f[gets.chomp] ``` [Answer] # PHP, ~~307~~ ~~288~~ 279 bytes ``` $o=" ";while($x<19)$o[$x+19*(($d=abs($x-9))>4?$d>7?$d-5:2:$d>3)]="Eyjafjal lajokull"[$x++];echo strtr((($n=ord($argv[1])/8&3)-2?"":" 1~ ~ ~ ~ ~ ~2\n").($n%3?" 1~ ~ ~2\n":"").($n?" 1~ ~2\n 1 ~ 2\n":"").chunk_split(str_pad($o,114,"-"),19),12,$n-2?" ":"`´"); ``` uglyly bulky **breakdown** ``` $o=" "; // 0.init $o to string while($x<19)$o[$x+19*( // 1.paint volcano ($d=abs($x-9))>4?$d>7?$d-5:2:$d>3 // 1a map [0..19] to row offsets )]="Eyjafjal lajokull"[$x++]; echo strtr( // 7. print (($n=ord($argv[1])/8&3) // 4.map GYOR to 0312 -2?"":" 1~ ~ ~ ~ ~ ~2\n") // 5a.add smoke & stuff for red .($n%3?" 1~ ~ ~2\n":"") // 5b for orange .($n?" 1~ ~2\n 1 ~ 2\n":"")// 5c for yellow .chunk_split( // 3.insert linebreaks str_pad($o,114,"-") // 2.add ground ,19) ,12,$n-2?" ":"`´"); // 6.replace stuff with ticks for red, with blanks else ``` [Answer] ## JavaScript (ES6), ~~235~~ ~~220~~ 218 bytes ``` c=>[344,592,160,640,192,32,28,2,1,~0].map(n=>(s='6222222661116600660').replace(/./g,(_,i)=>n&(1<<i|512>>i-9)?(s+'6allajjjafökuylEl')[p++]||'-':' '),p=0).join` `.replace(/\d/g,n=>n%4<'GYOR'.search(c[0])?n&4?'`':'~':' ') ``` ``` let f = c=>[344,592,160,640,192,32,28,2,1,~0].map(n=>(s='6222222661116600660').replace(/./g,(_,i)=>n&(1<<i|512>>i-9)?(s+'6allajjjafökuylEl')[p++]||'-':' '),p=0).join` `.replace(/\d/g,n=>n%4<'GYOR'.search(c[0])?n&4?'`':'~':' ') console.log(f('GREEN')) console.log(f('YELLOW')) console.log(f('ORANGE')) console.log(f('RED')) ``` [Answer] # JavaScript (ES6), ~~286~~ ~~262~~ ~~199~~ ~~194~~ 183 bytes Pass input to the function `f()`, e.g. `f('GREEN')`. ``` Y=`7~3~ 9~ ` f=n=>({G:'',Y,O:`5 ~2~2~ `+Y,R:'3`~ ~ ~ ~ ~ ~`\n4` ~2~2~ `\n5` ~3~ `\n7` ~ `\n'}[n[0]]+`6al3la 5j7j 2jaf9oku y15l E17l `+'-'.repeat(19)).replace(/\d+/g,n=>' '.repeat(n)) ``` *-63 bytes: Used Regex instead of function to generate spaces.* [Answer] # ><> (Fish) ~~351~~ ~~339~~ 302 bytes ``` \l?!;o00.>~00. \a"-------------------"a"l E"a"l y "a"ukö faj "a"j j "a" al la " \i:"R"-?!v " ` "a~<|.!00" `~ ~ ~ ~ ~ ~`"a" ` ~ ~ ~ ` "a" ` ~ ~ ` "a" ` ~" \ :"G"-?!v \}a"~ "a"~ ~ " \{:"Y"-?!v \~a"~ ~ ~ " ``` Fairly basic and ugly at the moment, I'm working on golfing it down lower but the 'RED' input makes it harder to re-use lines. Edit 1; Moved the initial volcano string onto 1 line to reduce line breaks, moved the 'RED' string in reverse to fill empty space. (12 bytes saved) Edit 2;Took out 'O' check and just print if the other 3 are not inputted (it doesn't specify any non 'green,red,orange,yellow' inputs. Also took out movement and used spaces in the strings to bypass extra commands. (37 bytes saved) [Online version to test!](https://fishlanguage.com/playground/3wt8ecrY8ZYqFf4Pp) [Answer] ## Python 2, 209 bytes (208 chars) ``` s=' ' y=' ~ ' v='ROY G'.index(input()[0]) a='` '[v>0] print'\n'.join([s*3+a+'~'+' ~'*5+a,s*4+a+y*3+a,s*5+a+y*2+a,s*7+a+y+a,s*6+'al la ',s*5+'j j\n jaf'+s*9+'öku\n y'+s*15+'l\nE'+s*17+'l','-'*19][v:]) ``` ]
[Question] [ I need to light some candles. In fact, I need to light an *arbitrary* amount of candles. But only the good ones. **OBJECTIVE** Given a block of text (containing lit, valid, and invalid candles) and a number `N` as input, write a program or function that lights an amount exactly equal to `N`, minus the number of already-lit candles. If `N` is greater than the number of valid candles, the program should print the number of missing, valid candles. If no candles are present, the output should be `:(`. Here are some valid candles: ``` . | . . | | . \ | | | / ``` (ending with a `.`, containing only `|` or balanced, not necessarily adjacent `\` and `/`, can be of any length.) Here are some invalid candles: ``` . . . . \ | | | | | | \ . | ! ``` (unbalanced `\`, no candle stick, disconnected, non-`|` characters, not planted on the ground.) A lit candle will replace the `.` on a valid candle with any of the following characters (your choice): ``` @ ^ & " ~ ``` You must use at least one, and you get a `-10%` bonus for each character used in your program, in such a way that each character can appear on a lit candle. If you use the `🔥` emoji, you get a `-15` byte bonus, which is applied before the percentage bonuses, if used. ***THE BYTE COUNT IS ROUNDED DOWN!*** This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. ## Example IOs ``` input: 8, . . | . ! . . |. . . . | | | | | | | | | | output: @ @ | @ ! @ @ |. @ @ @ | | | | | | | | | | input: 14, // nothing output: :( input: 15, . .. . . ". . | . || | | || ! output: 9 // more candles required; 15 - (6 unlit) = 9 (thanks to @AndersKaseorg for catching my mistakes (plural)!) input: 7, . / ~ | \ . / & " / | \ | @ | | . . . . . \ | | | | | 1 l I | output: & / ~ | \ . / & " / | \ | @ | | ^ . . . 🔥 \ | | | | | 1 l I | input: 5, . . | i Q no candl es . |3-. output: :( ``` ## 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=59664,OVERRIDE_USER=8478;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://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] # Python 2, 529 bytes with bonus, 303 * Assumes that the first line has an integer on it. * Doesn't assume consistent spacing. Doesn't assume candles' column is empty. Strategy: * Get input as list. * Reverse it and map it to a list of columns. * Test and operate. * Map it back into rows, reverse it, join the lines. ``` import re;R=raw_input;C=str.count;G=lambda x:[y if y else' 'for y in x];H=lambda x:[''.join(G(v))for v in map(None,*x)];F=re.findall;t,r,i,g,d=0,u"🔥~\"&^@",[],r'^[|/\\]+[%s](?=\s|$)',R() while d:i+=[d];d=R() c=int(F('\d+',i.pop(0))[0]);i=i[::-1];m=H(i) t+=sum(1 for x in m if F(g%r,x)) for p,n in enumerate(m): try:b=F(g%'\.',n)[0] except:continue if C(b,'/')==C(b,'\\')and t<c:t+=1;m[p]=re.sub('\.',r[0],n,1) if len(r)>1:r=r[1:] m='\n'.join(H(m)[::-1]) d=":("if t<1 else`c-t`+" more candles required"if t<c else m;print d ``` Tests: ``` 5, * * * * * * * @ @ @ @ | | . | | | | | | | ``` ``` * * * * * * * @ @ @ @ | | 🔥 | | | | | | | ``` --- ``` 3, . . . | \ | ``` ``` 1 more candles required ``` --- ``` 3, . . . . . . | | | ``` ``` . . . 🔥 ~ " | | | ``` [Answer] # Haskell, ⌊(269 bytes − 15) · 0.9⁵⌋ = 149 ``` h('.',0)(e:f,c,o)=(f,2:c,e:o) h(k,b)(f,c,o)|Just x<-lookup k$zip"\\|/"[4,0..]=(f,x+2*div b 2:c,k:o)|0<1=(f,2:c,k:o) g l(f,c,o)=foldr h(f,[],'\n':o)$zip l c d("",_,o)=o d('@':_,_,_)=":(" d(f,_,_)=show$length f f n=d.foldr g(take n$'@':cycle"🔥^&\"~",repeat 1,"").lines ``` Example run: ``` *Main> putStr s . / ~ | \ . / & " / | \ | @ | | . . . . . \ | | | | | 1 l I | *Main> putStr (f 3 s) ^ / ~ | \ . / & " / | \ | @ | | 🔥 . . . @ \ | | | | | 1 l I | ``` Assumes that each input line is at least as long as the previous line, as allowed by one of the author’s comments. [Answer] # JavaScript (ES6), 328 bytes (score: 184) I tried to beat the Haskell solution but that's actually a pretty competitive entry given all of the logic that needs to happen. Score calculated as:`Math.floor((328-15)*Math.pow(0.9,5))`, bytes counted in a file with UTF-8 encoding, tested and confirmed with `io.js --harmony_arrow_functions`. **Solution**: ``` eval("(n,s)=>{q=x=>x[0].map((_,c)=>x#[c]));h='Q';c=5;t=n;m=q(s.split('\\n')X#.match(/^ *[Q][\\\\//|]+$/)&&xR\\L==xR/L&&t-->0?xR./,c>1?h[c--]:'@'):x);return t==n?':(':t>0?1+t:q(mX.join('\\n')R@/,'🔥')}"[k='replace'](/[A-Z]/g,x=>({X:"#.split('')))#.join(''))",R:"[k](/\\",Q:'.@^&"~',L:"/g,'').length"}[x]))[k](/#/g,'.map(x=>x')) ``` **Requirements**: the array must be space-padded to be rectangular. **Explanation**: all of the eval insanity sets one variable (the variable `k` to the string `replace` to save some bytes) and shaves 11 bytes off of a 339-byte string, which I can un-golf as: ``` (num_candles_desired, string) => { transpose = array => array[0].map((_, index) => array.map(row => row[index])); candle_tips = '.@^&"~'; c = 5; // decrementing index into candle_tips when > 1. candles_left = num_candles_desired; transposed_normal_output = transpose( string.split('\n').map(line => line.split('')) ).map(col_array => col_array.join('')) // the next map does the actual logic: finds possible candles with // a regex, checks that the \ chars match the / chars in number, // then decrements the candles_left index while changing the . to a // lit flame. .map(col => col.match(/^ *[.@^&"~][\\//|]+$/) && col.replace(/\\/g,'').length == col.replace(/\//g,'').length && candles_left-- > 0 ? x.replace(/\./, c > 1 ? candle_tips[c--] : '~') : x); return candles_left == num_candles_desired ? ':(' : candles_left > 0 ? 1 + candles_left : transpose( transposed_normal_output.map(col => col.split('')) ).map(row_array => row_array.join('')).join('\n') // as promised, we include the emoji at least once if we can. // the leading backslash is unnecessary and comes from the // above metaprogramming-compression with eval(). .replace(/\@/,'🔥') } ``` Since example I/Os were requested, here was the test suite I ran, ``` Reference example #1, lighting 8 candles... Input: . . | . ! . . |. . . . | | | | | | | | | | Output: ~ 🔥 | " ! & ^ |. @ @ @ | | | | | | | | | | Reference example #2, lighting 14 candles... Input: Output: :( Reference example #3, lighting 15 candles... Input: . .. . . ". . | . || | | || ! Output: 9 Reference example #4, lighting 7 candles... Input: . / ~ | \ . / & " / | \ | @ | | . . . . . \ | | | | | 1 l I | Output: ~ / ~ | \ . / & " / | \ | 🔥 | | @ . . . @ \ | | | | | 1 l I | Reference example #5, lighting 5 candles... Input: . . | i Q no candl es . |3-. Output: :( ``` ]
[Question] [ You are a glob of slime. Naturally, being slime, you want to ooze over as much area as possible. But there are 3 other slimes who want to do the exact same thing. Who will be the superior slime? ## Description All slimes will be gathered into one arena. The judges (i.e. the control program) will go through an exhaustive list of all possible 4-slime combinations, place them on the corners of a table, and observe to see which slime oozes out over the most area. Your slimes can do one of 3 actions each turn: spread out, jump, or merge. Further description on what these mean will be provided in the **Output** section. ## Board / Arena The arena will be a square board (currently 8x8, but this may change in the future). Here is an example arena of a game in progress: ``` 11111222 11111444 11.22444 .1222.4. 333.3244 33333.44 333...44 333....4 ``` Slime is represented by the numbers 1 through 4 (players 1 to 4), and empty space is represented by a dot (`.`). Initially, the board starts out as all empty space except for a single unit of player 1's slime in the top left corner, player 2 in the top right, player 3 in the bottom left, and player 4 in the bottom right. Coordinates are represented by 0-based row and column index, for readability in the code. For example, the coordinates (3, 6) represent the 7th square in the 4th row (in the above example, a `4`). (This makes it easier to access squares: `board[coords.x][coords.y]`.) Here's a visual illustration: ``` (0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) (2, 0) (2, 1) (2, 2) ``` ## Input Your program's input will be which player you are (1, 2, 3, or 4), a comma (`,`), then the content of the board / arena (with newlines replaced with commas). For example, if you were player 3 in the above scenario, your input would be: ``` 3,11111222,11111444,11.22444,.1222.4.,333.3244,33333.44,333...44,333....4 ``` ## Output Your program must output 4 integers. The first two are the row and column index respectively of the slime you would like to move, and the next two are the row and column index of where you want to move them. There are three choices you have on each turn: Spread out, jump, or merge. * **Spread** To spread, the target coordinates must be exactly one square away from the slime being moved, and the square at the target coordinates must be empty space. When spreading, a new slime is created at the target coordinates and the old slime is *not* removed. After the new slime is created, all enemy slimes in the 8 squares around this new slime are converted to the player that moved. For example, with the board in Fig. 1, if player 1 were to output `0 1 1 2`, the result would be the board in Fig. 2. ``` 1. 2. 11.22 11.12 1..22 1.112 ..22. ..11. ..... ..... ``` * **Jump** To jump, the target coordinates must be exactly two squares away from the slime being moved, and the square at the target coordinates must be empty space. When jupming, a new slime is created at the target coordinates and the old slime is removed. After the new slime is created, all enemy slimes in the 8 squares around this new slime are converted to the player that moved. For example, with the board in Fig. 1, if player 1 were to output `0 1 2 3`, the result would be the board in Fig. 2. ``` 1. 2. 11..2 1...2 1...2 1...1 ....2 ...11 ...22 ...11 ``` * **Merge** To merge, the target coordinates must be exactly one square away from the slime being moved, and the square at the target coordinates must be the same player's slime. When merging, the old slime is removed. Then, all empty spaces in the 8 squares around the target slime are converted to the player that moved (not including the old slime being moved). For example, with the board in Fig. 1, if player 1 were to output `0 1 1 2`, the result would be the board in Fig. 2. ``` 1. 2. 11..2 1.112 1.1.2 11112 ....2 .1112 ..222 ..222 ``` You can also pass, by simply outputting invalid coordinates (ex. `0 0 0 0`). ## Rules and constraints Additional rules are: * You may read and write files within your own folder in order to persist data (submissions will be stored in `players/YourBotName/yourBotName.language`), but you may not modify or access anything else outside of it. Internet access is prohibited. * Your submission may not be coded specifically to help or hurt another submission. (You may have multiple submissions, but they must not specifically interact with each other in any way.) * Your submission must take no more than 0.1 seconds per turn. If your submission takes 0.105 seconds occasionally, that's fine, but it may not consistently take significantly longer than this time limit. (This is mainly a sanity check to avoid testing taking an overly long time.) * Your submission must not be an exact duplicate (i.e. use the exact same logic) of another, even if it's in a different language. * Your submission must be a serious submission. This is opinion-based, but if your submission is clearly not attempting to solve the challenge (ex. if you pass every turn), it will be disqualified. If your submission breaks any of these rules or doesn't follow the specification, it will be disqualified, removed from `playerlist.txt`, and the game will restart from the beginning. If your submission is disqualified, I will leave a comment on your post explaining why. Otherwise, your submission will be added to the leaderboard. (If you don't see your submission on the leaderboard, have no explanatory comment on your post, and posted your submission before the "Last updated" time below, please tell me! I may have inadvertently overlooked it.) In your entry, please include: * A name. * A shell command to run your program (for example, `java MyBot.java`, `ruby MyBot.rb`, `python3 MyBot.py`, etc.). + Note that the input (your player and map) will be appended to this as a command line argument. + Programs will be tested on Ubuntu 14.04, so make sure your code can be run (freely) on it. * A version number, if your code works differently on different versions of your language. * Your bot's code. * Instructions on how to compile the code, if necessary. ## Controller code / testing, example bot The controller code is written in C++, and [can be found on Github](https://github.com/KeyboardFire/slime-territory-war). Further instructions on how to run and test your code can be found there. `simplebot.rb`, a very simple bot that spreads or jumps a random slime to a random location each turn, [is also posted on Github](https://github.com/KeyboardFire/slime-territory-war/blob/master/players/Simplebot/simplebot.rb). ## Scoring and leaderboard When all squares on the board are filled, the game ends and scores are calculated. The final score of a player is the amount of squares that contain their slime at the end of the game. If 2000 turns have passed (500 for each player) and the game still isn't over, the game will end anyway and the scores will be reported as if the game had ended. At the end of the tournament, the scores from all games will averaged to calculate each player's final score, which will be posted on the leaderboard. There is no submission deadline; I'll continue to update the leaderboard periodically as new submissions come in. *4 submissions are required until a real leaderboard appears.* ``` +--------------------------+-----------+--------------------+ | Name | Avg Score | Last Updated (UTC) | +--------------------------+-----------+--------------------+ | GreedySlime | 47.000 | Jul 22 10:27 PM | | Jumper | 12.000 | Jul 22 10:27 PM | | ShallowBlue | 5.000 | Jul 22 10:27 PM | | Lichen | 0.000 | Jul 22 10:27 PM | +--------------------------+-----------+--------------------+ ``` Last updated: Jul 22 10:27 PM (UTC). [Answer] # GreedySlime Simply makes the move that produces the greatest net gain of slime units. Note that this is written in **Python 2.x**. ``` def gen_moves(board, pos): """Generate valid moves for a given position. Return value is a tuple of the form (type, from_x, from_y, to_x, to_y) The move 'type' is a single character with: - 's' = spread - 'j' = jump - 'm' = merge """ N = len(board) x0, y0 = pos player = board[x0][y0] for i in -2,-1,0,1,2: for j in -2,-1,0,1,2: if (i == 0 and j == 0): continue x1, y1 = x0 + i, y0 + j if not ((0 <= x1 < N) and (0 <= y1 < N)): continue c = board[x1][y1] if -1 <= i <= 1 and -1 <= j <= 1: if c == '.': yield ('s', x0, y0, x1, y1) elif c == player: yield ('m', x0, y0, x1, y1) else: if c == '.': yield ('j', x0, y0, x1, y1) def eval_move(board, move, initial_net={'s': 1, 'j': 0, 'm': -1}): """Evaluates given move in given context. - Assumes move is valid. - `move` argument is a tuple of the form (type, from_x, from_y, to_x, to_y) - The move 'type' is a single character with: - 's' = spread - 'j' = jump - 'm' = merge """ N = len(board) move_type = move[0] x0, y0, x1, y1 = move[1:] player = board[x0][y0] net = initial_net[move_type] for i in -1,0,1: for j in -1,0,1: if (i == 0 and j == 0): continue x2, y2 = x1 + i, y1 + j if not ((0 <= x2 < N) and (0 <= y2 < N)): continue c = board[x2][y2] if (move_type == 'm' and c == '.') or (move_type != 'm' and c != player and c != '.'): net += 1 return net def main(): from sys import argv data = argv[1] player, board = data.split(',', 1) board = map(list, board.split(',')) N = len(board) all_pos_gen = ((a,b) for a in range(N) for b in range(N) if board[a][b] == player) all_move_gen = (move for pos in all_pos_gen for move in gen_moves(board, pos)) move = max(all_move_gen, key=lambda move: eval_move(board, move)) print move[1], move[2], move[3], move[4] if __name__ == "__main__": main() ``` --- Example run (using the example given in the challenge description, and assuming the code is saved in a file called `slime.py`): ``` $ python slime.py 3,11111222,11111444,11.22444,.1222.4.,333.3244,33333.44,333...44,333....4 4 0 2 2 ``` [Answer] # Shallow Blue Shallow blue tries to figure out what might happen in the future by doing a~~n exhaustive~~ tree-search of possible moves, unfortunately, he doesn't get any further than his next turn. He then slaps some half-assed score on each possible boardstate after his next turn, calculates a score for each individual branch with an equally ridiculous formula and: voila the ideal move is known! EDIT: The original code ran waay too slowly so I modified it so that it only takes a random sample of all possible moves. It will try almost all moves when there are little moves possible and a smaller percentage when there are more moves possible. ``` import java.awt.Point; public class ShallowBlue { private static final int MAX_ROUNDS = 5, PLAYERS = 4; static int me = 0; public static void main(String[] args) { if (args[0] == null) { return; } me = Integer.parseInt(args[0].split(",", 2)[0]); String board = args[0].split(",", 2)[1]; System.out.println(getBestMove(board, me, MAX_ROUNDS - 1)); } private static String getBestMove(String board, int player, int rounds) { String [] boards = new String[24]; int checkedBoards = 1; char playerChar = Integer.toString(player).charAt(0); String tempMove = getMove(0, 0, 0, 0); String tempBoard = calculateMove(board, tempMove); boards[0] = tempBoard; String bestMove = tempMove; double us = numberOfUs(board, playerChar); double skip = (us*2.5/(us*2.5 + 1))/4 + 0.735; if (rounds == MAX_ROUNDS - 2) { skip = skip*skip; } float bestScore, worstScore, averageScore, tempScore; int scores; if (rounds == 0) { tempScore = calculateScore(tempBoard, MAX_ROUNDS - rounds - 1); } else { tempScore = getScore(getBestMove(tempBoard, player%PLAYERS + 1, rounds - 1)); } scores = 1; bestScore = tempScore; worstScore = tempScore; averageScore = tempScore; for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { if (getCharAt(board, x, y) == playerChar) { Point[] possibleMergers = getNeighboringMatches(board, new Point(x, y), playerChar); if (possibleMergers[0] != null) { tempMove = getMove(possibleMergers[0].x, possibleMergers[0].y, x, y); tempBoard = calculateMove(board, tempMove); if (addIfUnique(boards, tempBoard, checkedBoards)) { checkedBoards++; if ((rounds != MAX_ROUNDS - 1) && (rounds == 0 || Math.random() < skip)) { tempScore = calculateScore(tempBoard, MAX_ROUNDS - rounds - 1); } else { tempScore = getScore(getBestMove(tempBoard, player%PLAYERS + 1, rounds - 1)); } if (tempScore > bestScore) { bestMove = tempMove; } bestScore = Math.max(tempScore, bestScore); worstScore = Math.min(tempScore, worstScore); scores++; averageScore = (averageScore*(scores - 1) + tempScore)/scores; } } } else if (getCharAt(board, x, y) == '.') { Point[] possibleSpreaders = getNeighboringMatches(board, new Point(x, y), playerChar); int i = 0; while (i < possibleSpreaders.length && possibleSpreaders[i] != null) { tempMove = getMove(possibleSpreaders[i].x, possibleSpreaders[i].y, x, y); tempBoard = calculateMove(board, tempMove); if ((rounds != MAX_ROUNDS - 1) && (rounds == 0 || Math.random() < skip)) { tempScore = calculateScore(tempBoard, MAX_ROUNDS - rounds - 1); } else { tempScore = getScore(getBestMove(tempBoard, player%PLAYERS + 1, rounds - 1)); } if (tempScore > bestScore) { bestMove = tempMove; } bestScore = Math.max(tempScore, bestScore); worstScore = Math.min(tempScore, worstScore); scores++; averageScore = (averageScore*(scores - 1) + tempScore)/scores; i++; } Point[] possibleJumpers = getNextNeighboringMatches(board, new Point(x, y), playerChar); i = 0; while (i < possibleJumpers.length && possibleJumpers[i] != null) { tempMove = getMove(possibleJumpers[i].x, possibleJumpers[i].y, x, y); tempBoard = calculateMove(board, tempMove); if ((rounds != MAX_ROUNDS - 1) && (rounds == 0 || Math.random() < skip)) { tempScore = calculateScore(tempBoard, MAX_ROUNDS - rounds - 1); } else { tempScore = getScore(getBestMove(tempBoard, player%PLAYERS + 1, rounds - 1)); } if (tempScore > bestScore) { bestMove = tempMove; } bestScore = Math.max(tempScore, bestScore); worstScore = Math.min(tempScore, worstScore); scores++; averageScore = (averageScore*(scores - 1) + tempScore)/scores; i++; } } } } if (rounds == MAX_ROUNDS - 1) { return (bestMove); } else { return getScoreString(bestScore, worstScore, averageScore); } } private static int numberOfUs(String board, char playerChar) { int us = 0; for (int i = 0; i < board.length(); i++ ) { if (board.charAt(i) == playerChar) { us++; } } return us; } private static float calculateScore(String board, int roundsPassed) { int empties = 0; int us = 0; int enemy1 = 0; int enemy2 = 0; int enemy3 = 0; for (int i = 0; i < board.length(); i++ ) { if (board.charAt(i) == '.') { empties++; } else if (board.charAt(i) == Integer.toString(me).charAt(0)) { us++; } else if (board.charAt(i) == Integer.toString(me%PLAYERS + 1).charAt(0)) { enemy1++; } else if (board.charAt(i) == Integer.toString(me%PLAYERS + 2).charAt(0)) { enemy2++; } else if (board.charAt(i) == Integer.toString(me%PLAYERS + 3).charAt(0)) { enemy3++; } } if (us != 0) { us += roundsPassed; } if (enemy1 != 0) { enemy1 = enemy1 + (roundsPassed + 3)%PLAYERS; } if (enemy2 != 0) { enemy2 = enemy2 + (roundsPassed + 2)%PLAYERS; } if (enemy3 != 0) { enemy3 = enemy3 + (roundsPassed + 1)%PLAYERS; } return us*(empties + 1)/(Math.max(Math.max(enemy1, enemy2), enemy3) + 1); } private static float getScore(String scoreString) { float bestScore, worstScore, averageScore; String[] scores = new String[3]; scores = scoreString.split(","); bestScore = Float.parseFloat(scores[0]); worstScore = Float.parseFloat(scores[1]); averageScore = Float.parseFloat(scores[2]); return (float) Math.sqrt(Math.sqrt(bestScore*averageScore*worstScore*worstScore)); } private static String getScoreString(float bestScore, float worstScore, float averageScore) { return Float.toString(bestScore) + ',' + Float.toString(worstScore) + ',' + Float.toString(averageScore); } private static boolean addIfUnique(String[] boards, String board, int checkedBoards) { int i = 0; while (i < boards.length && boards[i] != null) { if (boards[i].equals(board)) { return false; } i++; } if (i < boards.length) { boards[i] = board; } else { boards[checkedBoards%boards.length] = board; } return true; } private static String calculateMove(String board, String move) { int x1 = Integer.parseInt(Character.toString(move.charAt(0))); int y1 = Integer.parseInt(Character.toString(move.charAt(2))); int x2 = Integer.parseInt(Character.toString(move.charAt(4))); int y2 = Integer.parseInt(Character.toString(move.charAt(6))); if ((Math.abs(y1 - y2) == 2 || Math.abs(x1 - x2) == 2) && getCharAt(board, x2, y2) == '.') { Point[] enemies = new Point[8]; enemies = getNeighboringEnemies(board, new Point(x1, y1), Integer.parseInt(Character.toString(getCharAt(board, x1, y1)))); board = replace(board, enemies, getCharAt(board, x1, y1)); Point[] middle = {new Point(x1, y1)}; board = replace(board, middle, '.'); } if ((Math.abs(y1 - y2) == 1 || Math.abs(x1 - x2) == 1)) { if (getCharAt(board, x2, y2) == '.' || getCharAt(board, x1, y1) == getCharAt(board, x2, y2)) { boolean merge = true; if (getCharAt(board, x2, y2) == '.') { merge = false; } Point[] spaces = new Point[8]; spaces = getNeighboringMatches(board, new Point(x1, y1), '.'); board = replace(board, spaces, getCharAt(board, x1, y1)); if (merge) { Point[] source = {new Point(x1, y1)}; board = replace(board, source, '.'); } } } return board; } private static String replace(String board, Point[] targets, char source) { int i = 0; while (i < targets.length && targets[i] != null) { if (targets[i].x == 7 && targets[i].y == 7) { board = board.substring(0, getIndexAt(targets[i].x, targets[i].y)) + source; } else if (targets[i].x == 0 && targets[i].y == 0) { board = source + board.substring(getIndexAt(targets[i].x, targets[i].y) + 1); } else { board = board.substring(0, getIndexAt(targets[i].x, targets[i].y)) + source + board.substring(getIndexAt(targets[i].x, targets[i].y) + 1); } i++; } return board; } private static Point[] getNeighboringMatches(String board, Point coord, char match) { Point[] matches = new Point[8]; int i = 0; for (int x = coord.x - 1; x <= coord.x + 1; x++) { for (int y = coord.y - 1; y <= coord.y + 1; y++) { if ((y != coord.y || x != coord.x ) && getCharAt(board, x, y) == match){ matches[i] = new Point(x, y); i++; } } } return matches; } private static Point[] getNeighboringEnemies(String board, Point coord, int player) { Point[] enemies = new Point[8]; for (int i = 1; i <= PLAYERS; i++){ enemies = mergeArr(enemies, getNeighboringMatches(board, coord, Integer.toString((player + i - 1)%PLAYERS + 1).charAt(0))); } return enemies; } private static Point[] getNextNeighboringMatches(String board, Point coord, char match) { Point[] matches = new Point[16]; int i = 0; for (int x = coord.x - 2; x <= coord.x + 2; x++) { for (int y = coord.y - 2; y <= coord.y + 2; y++) { if ((Math.abs(y - coord.y) == 2 || Math.abs(x - coord.x) == 2) && getCharAt(board, x, y) == match){ matches[i] = new Point(x, y); i++; } } } return matches; } private static char getCharAt(String board, int x, int y) { if (x >= 0 && x < 8 && y >= 0 && y < 8) { return board.charAt(9*x + y); } else { return '\0'; } } private static int getIndexAt(int x, int y) { return 9*x + y; } private static Point[] mergeArr(Point[] arr1, Point[] arr2) { int i = 0; int j = 0; while (i < arr1.length && arr1[i] != null) { i++; } while (j < arr2.length && arr2[j] != null) { arr1[i + j] = arr2[j]; j++; } return arr1; } private static String getMove(int x1, int y1, int x2, int y2) { return Integer.toString(x1) + " " + Integer.toString(y1) + " " + Integer.toString(x2) + " " + Integer.toString(y2); } } ``` [Answer] # Jumper Likes to jump, even more so towards the middle. Will pass if no slimes can jump. **C++**, Should compile simply with `g++ jumper.cpp -o jumper` ``` #include <math.h> #include <algorithm> #include <iostream> #include <string> #include <sstream> #include <vector> #define maxn(x, y) ((x) > (y) ? (x) : (y)) #define absn(x) ((x) < 0 ? -(x) : (x)) class Board { public: Board(std::string input_string); void Move(); private: void ParseBoardState(std::string console_string); int Slimes(int cell); void GetXY(int cell, int& r, int& c); bool CanJumpFromHere(int cell, int& jump_to_cell, int& rad); int CalcRadius(int cell); bool CheckJumpDist(int x, int y); int player_num_; std::size_t board_dim_; std::size_t sq_; std::vector< std::vector<int> > slimes_; }; Board::Board(std::string input_string) : player_num_(0), board_dim_(0), slimes_() { board_dim_ = std::count(input_string.begin(), input_string.end(), ','); sq_ = board_dim_ * board_dim_; std::istringstream temp(input_string.substr(0,1)); temp >> player_num_; ParseBoardState(input_string); } void Board::ParseBoardState(std::string console_string) { int place = 0; for (std::size_t row = 0; row < board_dim_; ++row ) { slimes_.push_back(std::vector<int>()); place = console_string.find(",",place+1); std::string temp2 = console_string.substr(place+1, 8); for (std::size_t col = 0; col < board_dim_; ++col ) { int sl = 0; std::istringstream bint(temp2.substr(col,1)); bint >> sl; slimes_[row].push_back(sl); } } } int Board::Slimes(int cell) { int r = 0; int c = 0; GetXY(cell, r, c); return slimes_[r][c]; } void Board::GetXY(int cell, int& r, int& c) { for (std::size_t row = 0; row < board_dim_; ++row ) { for (std::size_t col = 0; col < board_dim_ ; ++col ) { if ( (row * board_dim_ + col) == cell) { r = row; c = col; } } } } void Board::Move() { // go through each cell: int index = 0; int jump_to_cell = 0; int rad = 0; int min_rad = 1000; int best_jump_to = -1; int best_jump_from = -1; for (int c = 0; c < sq_; ++c) { if (Slimes(c) == player_num_) { if (CanJumpFromHere(c, jump_to_cell , rad)) { if (rad < min_rad) { best_jump_from = c; best_jump_to = jump_to_cell; min_rad = rad; } index += 1; } } } int ret_row = 0; int ret_col = 0; if (index == 0) { // can't jump so dont bother: std::cout << "0 0 0 0" << std::endl; } else { GetXY(best_jump_from, ret_row, ret_col); std::cout << ret_row << " " << ret_col << " "; GetXY(best_jump_to, ret_row, ret_col); std::cout << ret_row << " " << ret_col << std::endl; } } bool Board::CanJumpFromHere(int cell, int& ret_jump_to_cell, int & ret_rad) { int r = 0; int c = 0; int rad = 10000; int jump_to_cell = 0; int rad_min_for_this_cell = 10000; GetXY(cell, r, c); bool jumpable = false; for (int row_test = -2; row_test < 3; ++row_test) { for (int col_test = -2; col_test < 3; ++col_test) { if ( (r + row_test) > 0 & (r + row_test) < board_dim_ && (c + col_test) > 0 && (c + col_test) < board_dim_ && (CheckJumpDist(col_test, row_test)) && (slimes_[r+row_test][c+col_test] == 0)) { jumpable = true; jump_to_cell = (r + row_test) * board_dim_ + c + col_test; rad = CalcRadius(jump_to_cell); if (rad < rad_min_for_this_cell) { ret_rad = rad; ret_jump_to_cell = jump_to_cell; rad_min_for_this_cell = ret_rad; } } } } return jumpable; } bool Board::CheckJumpDist(int x, int y) { int maxDelta = maxn(absn(x), absn(y)); if (maxDelta <= 0 || maxDelta > 2) { return false; } else { return true; } } int Board::CalcRadius(int cell) { int r = 0; int c = 0; GetXY(cell, r, c); // unnecessary accuracy considering how bad this bot is: float mid = static_cast<float>(board_dim_) / 2; float rad = sqrt((r - mid) * (r - mid) + (c-mid)*(c-mid)); int ret = static_cast<int>(rad + 0.5); return ret; } int main(int argc, char* argv[]) { if (argc != 2) { return 0; } else { std::string input_string(argv[1]); Board board(input_string); board.Move(); } return 0; } ``` I stole your move verification sorry. Also I gave up on correct coding practices just after I started, so don't look. However, it seems to run on any size of board. [Answer] **DeathSlime**: **Description**: Tries to hunt the weakest enemy and destroy them. Repeat. **How to run**: ruby DeathSlime.rb **Ruby Version**: 2.1.2 ``` #!/usr/bin/env ruby class PlayerPosition; attr_accessor :x, :y; def initialize(x, y) @x = x; @y = y; end def distance(pos) Math.sqrt((pos.x - @x)**2 + (pos.y - @y)**2); end end class Board attr_reader :player, :empty_positions def initialize(player_id, game_state_string) @player_positions = {} @empty_positions = [] @enemies = [] @player = Player.new row = 0 col = 0 game_state_string.chars.each do |tile| row += 1 and col = 0 and next if tile == ',' @empty_positions << PlayerPosition.new(col, row) and col += 1 and next if tile == '.' @player_positions[tile] ||= [] @player_positions[tile] << PlayerPosition.new(col, row) col += 1 end @player_positions.each do |id, positions| @enemies << Player.new(id, positions) if id != player_id @player = Player.new(id, positions) if id == player_id end end def border_space(player_positions, possible_border, allowance = 1) near = [] possible_border.each do |border| is_near = false player_positions.each {|pos| is_near = true and break if pos.distance(border) <= allowance} near << border if is_near end near end def closest_to(player_positions, enemy_positions) player_closest_block = nil shortest_distance = 1000 enemy_closest_block = nil player_positions.each do |player| enemy_positions.each do |enemy| if player.distance(enemy) < shortest_distance shortest_distance = player.distance(enemy) enemy_closest_block = enemy player_closest_block = player end end end return player_closest_block, enemy_closest_block end def empty_space_near(player_positions, allowance = 1); border_space(player_positions, @empty_positions, allowance); end def weakest_enemy; @enemies.select{|enemy| !enemy.dead? }.sort {|x,y| x.strength <=> y.strength}.first; end end class Player attr_reader :positions def initialize(id = -1, positions = []); @id = id; @positions = positions; end def dead?; @positions.length == 0; end def strength; @positions.length; end def can_hurt?(enemy) is_close_enough = false self.positions.each do |my_pos| enemy.positions.each {|enemy_pos| is_close_enough = true and break if my_pos.distance(enemy_pos) <= 2 } end is_close_enough end end class DeathSlime def initialize(arg_string) game_state = arg_string[2..-1] player_id = arg_string[0] @board = Board.new(player_id, game_state) end def attack if @board.weakest_enemy try_to_spread_to_weakest || try_to_jump_to_weakest || try_to_merge_to_weakest || try_to_move_to_weakest else try_to_move if @empty_positions.length > 0 end end def try_to_spread_to_weakest mine = @board.empty_space_near(@board.player.positions, 1) theirs = @board.empty_space_near(@board.weakest_enemy.positions, 1) target_space = mine.detect{|space| theirs.include?(space) } return move(@board.closest_to(@board.player.positions, [target_space]).first, target_space) if target_space false end def try_to_jump_to_weakest mine = @board.empty_space_near(@board.player.positions, 2) theirs = @board.empty_space_near(@board.weakest_enemy.positions, 1) target_space = mine.detect{|space| theirs.include?(space) } return move(@board.closest_to(@board.player.positions, [target_space]).first, target_space) if target_space false end def try_to_merge_to_weakest definite_border = nil definite_merge = nil possible_border = @board.border_space(@board.weakest_enemy.positions, @board.player.positions) possible_border.each do |border| possible_merges = @board.border_space([ border ], @board.player.positions.select{|space| space != border }) definite_merge = possible_merges.first and definite_border = border and break if possible_merges.length > 0 end return move(definite_merge, definite_border) if definite_border && definite_merge false end def try_to_move_to_weakest player_closest, enemy_closest = @board.closest_to(@board.player.positions, @board.weakest_enemy.positions) spreading_distance = @board.empty_space_near([player_closest], 1) jumping_distance = @board.empty_space_near([player_closest], 2) theirs = @board.empty_space_near(@board.player.positions, 2) spreading_space = spreading_distance.detect{|space| theirs.include?(space) } return move(@board.closest_to(@board.player.positions, [spreading_space]).first, spreading_space) if spreading_space jumping_space = jumping_distance.detect{|space| theirs.include?(space) } return move(@board.closest_to(@board.player.positions, [jumping_space]).first, jumping_space) if jumping_space return move(@board.closest_to(@board.player.positions, [spreading_distance]).first, spreading_distance) if spreading_distance.length > 0 return move(@board.closest_to(@board.player.positions, [jumping_distance]).first, jumping_distance) if jumping_distance.length > 0 #merge randomly closest_enemy = @board.closest_to(@board.player.positions, @board.weakest_enemy.positions).first return move(@board.closest_to(@board.player.positions.select{|space| space != closest_enemy }, [closest_enemy]).first, closest_enemy) end def try_to_move spreading_distance = @board.empty_space_near(board.player.positions, 1) jumping_distance = @board.empty_space_near(board.player.positions, 2) return move(@board.closest_to(@board.player.positions, [spreading_distance]).first, spreading_distance) if spreading_distance.length > 0 return move(@board.closest_to(@board.player.positions, [jumping_distance]).first, jumping_distance) if jumping_distance.length > 0 end def move(start_block, end_block) STDOUT.write "#{start_block.x} #{start_block.y} #{end_block.x} #{end_block.y}" true end end slime_of_death = DeathSlime.new(ARGV[0]) slime_of_death.attack ``` [Answer] ## Lichen This is a bot written in R. It needs to be triggered using `Rscript Lichen.R`. ``` input <- strsplit(commandArgs(TRUE),split=",")[[1]] me <- input[1] arena <- do.call(rbind,strsplit(input[-1],"")) n <- sum(arena==me) where <- which(arena==me,arr.ind=TRUE) closest <- function(a,b){ x <- abs(outer(a[,1],b[,1],`-`)) y <- abs(outer(a[,2],b[,2],`-`)) matrix(which(x<2&y<2,arr.ind=TRUE),ncol=2) } if(n==0){ #No slime on the board out <- "0 0 0 0" }else if(n==1){ #One slime on the board x <- where[1]+c(1,-1) y <- where[2]+c(1,-1) out <- paste(where[1]-1,where[2]-1,x[x%in%2:(nrow(arena)-1)]-1,y[y%in%2:(nrow(arena)-1)]-1,sep=" ") }else{ area <- apply(which(arena==me,arr.ind=TRUE),2,range,na.rm=TRUE) empty <- matrix(which(arena==".",arr.ind=TRUE),ncol=2) opponents <- c("1","2","3","4")[c("1","2","3","4")!=me] for(i in seq_along(opponents)){ if(i==1){ other <- which(arena==opponents[i],arr.ind=TRUE) }else{other <- rbind(other,which(arena==opponents[i],arr.ind=TRUE))} } fillable <- matrix(empty[empty[,1]%in%area[1,1]:area[2,1]&empty[,2]%in%area[1,2]:area[2,2],],ncol=2) enemies <- matrix(other[other[,1]%in%area[1,1]:area[2,1]&other[,2]%in%area[1,2]:area[2,2],],ncol=2) if(length(unique(where[,2]))==1 | length(unique(where[,2]))==1){ #Slimes form a line W <- closest(where,empty) if(nrow(W)){ out <- paste(c(where[W[1,1],]-1,empty[W[1,2],]-1),collapse=" ") }else{out <- "0 0 0 0"} }else if(length(enemies)&length(fillable)){ #There are enemies and empty spaces in habitable area w <- closest(enemies, fillable) if(nrow(w)){ X <- abs(where[,1]-fillable[w[1,2],1]) Y <- abs(where[,2]-fillable[w[1,2],2]) W <- which(X<2&Y<2) out <- paste(c(where[W[1],]-1,fillable[w[1,2],]-1),collapse=" ") }else{out <- "0 0 0 0"} }else if(length(fillable)){ #There are empty spaces in habitable area w <- closest(fillable,where) out <- paste(c(where[w[1,2],]-1,fillable[w[1,1],]-1),collapse=" ") }else{ x <- area[!area[,1]%in%c(1,nrow(arena)),1] y <- area[!area[,2]%in%c(1,ncol(arena)),2] if(sum(arena[x+(-1:1),y+(-1:1)]==".")>1){ w <- where[where[,1]%in%(x+c(1,-1))&where[,2]%in%(y+c(1,-1)),] out <- paste(w[1]-1,w[2]-1,x-1,y-1,sep=" ") }else{ W <- closest(where, empty) if(nrow(W)){ out <- paste(c(where[W[1,1],]-1,empty[W[1,2],]-1),collapse=" ") }else{out <- "0 0 0 0"} } } } cat(out) ``` The intended algorithm is that it tries to cover a rectangular area (filling the blank using `spread`). When the rectangle is complete, it `merges` the two slimes at one of its corner (the one the furthest from the corner of the board) to expand the "habitable" area, then fill that newly defined rectangle, etc. It does not use `jump`. ``` ..... ..... ..... ..... ..... ..333 ..... .333. 3333. 3333. 3333. 33333 333.. 3333. 3333. 3333. 3333. 33.33 333.. 3.33. 3.33. 3333. 3333. 3333. 333.. 333.. 333.. 333.. 3333. 3333. ``` If an enemy is in the habitable area and there is an empty space as well in the area, it fills the empty space next to it. If the slime that should be merged into when expanding the habitable area is surrounded by enemies, then one slime will just `spread` instead of this one merging. [Answer] ## CornerSlime This slime has a notion of corners, or at least did when I first wrote it in C#, I'm not really sure any more. Written in C++, presumably will compile fine with gcc and next to no arguments; hopefully I've not used anything MSVC specific by accident. Tested exclusively against itself on a modified server (no fancy new C++ compiler where I am) so I have no clue how it will perform, hopefully it won't be disqualified for being too slow. There is currently no randomness in this bot, but I may add some at a later date. This is C# ported to C++ (due to speed concerns) by someone who doesn't really know C++, and is horrendous. It starts by building an array of Cells, which it then fills with all sorts of unhelpful information about the cells around it (number of my cells, number of my slimes, that sort of thing). Then it uses this information to decide if it needs to look more closely at the information it used to create that information, and then potentially uses said information to produce a meaningful output. ``` #include <iostream> #define min(a,b) a>b?b:a; #define max(a,b) a>b?a:b; #define null 0 // fun times struct Cell { public: int t; int x, y; int counts1[5]; int counts2[5]; int ecount1; int ecount2; bool safe1; bool safe2; bool canspread; bool canjump; bool canmerge; bool spreadable; bool jumpable; bool mergeable; Cell() { for (int i = 0; i < 5; i++) { counts2[i]=counts1[i]=0; } ecount1=ecount2=0; safe1=safe2=mergeable=jumpable=spreadable=canmerge=canjump=canspread=false; } Cell(int tN, int xN, int yN) // not sure why I can't call () constructor here { for (int i = 0; i < 5; i++) { counts2[i]=counts1[i]=0; } ecount1=ecount2=0; safe1=safe2=mergeable=jumpable=spreadable=canmerge=canjump=canspread=false; t = tN; x = xN; y = yN; } void findOptions(int moi) { if (t == 0) { if (counts1[moi] > 0) spreadable = true; if (counts2[moi] > 0) jumpable = true; } else if (t == moi) { if (counts1[moi] > 0) mergeable = canmerge = true; if (counts1[0] > 0) canspread = true; if (counts2[0] > 0) canjump = true; } } }; const int dim = 8; const int hdim = 4; int moi; int chezMoi; int target; int chezTarget; Cell cells[dim][dim]; int cornerCounts[4][5]; int totalCounts[5]; // ring ness - why why why // end ring ness int tlx; int tly; int thx; int thy; int alx; int aly; int ahx; int ahy; int rj; int rstate; void ring(int x, int y, int dist) { tlx=x-dist; tly=y-dist; thx=x+dist; thy=y+dist; alx=max(0, tlx); aly=max(0, tly); ahx=min(dim-1, thx); ahy=min(dim-1, thy); rstate = 0; } bool nextR(Cell** outc) { if (rstate == 1) { goto state1; } if (rstate == 2) { goto state2; } if (rstate == 3) { goto state3; } if (rstate == 4) { goto state4; } if (alx == tlx) { rj = aly - 1; rstate = 1; } state1: if (alx == tlx) { if (++rj <= ahy) { *outc = (cells[alx]+rj); return true; } alx++; } if (ahx == thx) { rj = aly - 1; rstate = 2; } state2: if (ahx == thx) { if (++rj <= ahy) { *outc = (cells[ahx]+rj); return true; } ahx--; } if (aly == tly) { rj = alx - 1; rstate = 3; } state3: if (aly == tly) { if (++rj <= ahx) { *outc = (cells[rj]+aly); return true; } } if (ahy == thy) { rj = alx - 1; rstate = 4; } state4: if (ahy == thy) { if (++rj <= ahx) { *outc = (cells[rj]+ahy); return true; } } return null; } int cox; int coy; int ci; int cj; void corner(int idx) { cox = (idx / 2) * hdim; coy = (idx % 2) * hdim; ci = 0; cj = -1; } bool nextC(Cell** outc) { for (;ci < hdim;ci++) { for (;++cj < hdim;) { *outc = (cells[ci+cox]+cj+coy); return true; } cj = -1; } return false; } void cornerCount(int idx, int* c) { int ox = (idx / 2) * hdim; int oy = (idx % 2) * hdim; for (int i = 0; i < hdim; i++) { for (int j = 0; j < hdim; j++) { c[cells[i+ox][j+oy].t]++; } } } void ringCount(int x, int y, int dist, int* c) { int tlx=x-dist; int tly=y-dist; int thx=x+dist; int thy=y+dist; int alx=max(0, tlx); int aly=max(0, tly); int ahx=min(dim-1, thx); int ahy=min(dim-1, thy); if (alx == tlx) { for (int j = aly; j <= ahy; j++) c[cells[alx][j].t]++; alx++; } if (ahx == thx) { for (int j = aly; j <= ahy; j++) c[cells[ahx][j].t]++; ahx--; } if (aly == tly) { for (int i = alx; i <= ahx; i++) c[cells[i][aly].t]++; } if (ahy == thy) { for (int i = alx; i <= ahx; i++) c[cells[i][ahy].t]++; } } int trans(char c) { return c<48?0:c-48; } std::string res(Cell* ca, Cell* cb) { char buff[100]; // shhh sprintf_s(buff, "%d %d %d %d\n", ca->x, ca->y, cb->x, cb->y); return std::string(buff); } std::string go(char* inp) { moi = trans(inp[0]); int a = 2; for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { cells[i][j] = Cell(trans(inp[a]), i, j); a++; } a++; } // count corners and totals for (int i = 0; i < 4; i++) { cornerCount(i, cornerCounts[i]); for (int j = 0; j < 5; j++) { totalCounts[j] += cornerCounts[i][j]; } } // count and find cell options for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { Cell* c = cells[i]+j; ringCount(i, j, 1, c->counts1); ringCount(i, j, 2, c->counts2); // safeness for (int r = 1; r < 5; r++) { if (r != moi) { c->ecount1 += c->counts1[r]; c->ecount2 += c->counts2[r]; } } c->safe1 = c->ecount1 == 0 && c->counts1[0] == 0; // surrounded by moi c->safe2 = c->ecount1 == 0 && c->ecount2 == 0; // no enemies in sight // that funcion which does stuff c->findOptions(moi); } } // find chezMoi chezMoi = moi-1; // might work, can't be bothered to work it out for (int i = 1; i < 4; i++) { if (cornerCounts[i][moi] > cornerCounts[chezMoi][moi]) chezMoi = i; } int best = 0; if (cornerCounts[chezMoi][moi] < hdim * hdim) { // fill our corner best = 0; Cell* ac = null; Cell* bc = null; corner(chezMoi); Cell* c; while (nextC(&c)) { if (c->spreadable && c->ecount1 + 1 > best) { ring(c->x, c->y, 1); Cell* oc; while (nextR(&oc)) { if (oc->canspread) { best = c->ecount1 + 1; ac = oc; bc = c; break; } } } if (c->mergeable && c->counts1[0] - 1 > best) { ring(c->x, c->y, 1); Cell* oc; while (nextR(&oc)) { if (oc->safe2 && oc->canmerge && c->counts1[0] > 0) { best = c->counts1[0] - 1; ac = oc; bc = c; break; } } } } if (bc != null) { return res(ac, bc); } } // pick target (why?) target = -1; best = 0; for (int i = 0; i < 4; i++) { if (i == moi) continue; int cur = totalCounts[i]; if (target == -1 || cur > best) { target = i; best = cur; } } if (target != -1) { for (int i = 0; i < 4; i++) { if (i == chezMoi) continue; int cur = cornerCounts[i][target]; if (chezTarget == -1 || cur > best) { chezTarget = i; best = cur; } } // attack chosen target (not sure it does this anymore...) best = 0; Cell* ac = null; Cell* bc = null; for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { Cell* c = cells[i]+j; if (c->spreadable && c->ecount1 + 1 > best) { ring(c->x, c->y, 1); Cell* oc; while (nextR(&oc)) { if (oc->canspread) { best = c->ecount1 + 1; ac = oc; bc = c; break; } } } if (c->jumpable && c->ecount1 - 1 > best) { ring(c->x, c->y, 2); Cell* oc; while (nextR(&oc)) { if (oc->safe2 && oc->canjump) { best = c->ecount1 - 1; ac = oc; bc = c; break; } } } } } if (bc != null) { return res(ac, bc); } } return "0 0 0 0\n"; } int main(int argc, char* args[]) { printf(go(args[1]).c_str()); return 0; } ``` ]
[Question] [ Matthew likes solving puzzles. Whenever he manages to solve one he skips around happily. Recently he really *needs* to do this as a meteor shower has opened craters and holes in the ground in which he wouldn't like to fall. You are given a part of landscape that Matthew wants to cross, hopefully arriving healthy at the end. The ground is given in meters, with each meter being either normal ground or a hole. When he is running he manages to cross one meter per step; the alternative is jumping which crosses four meters per step. Matthew starts at the far left on the first ground meter and wants to get to the last one (not beyond it, though – just imagine an endless hole beyond the last meter given in the landscape). **Input** Input is given as a single line on standard input, terminated by a line break. The line consists of either dashes (`-`) or underscores (`_`), representing a ground or hole meter, respectively. A sample input could be: ``` ----__--___--- ``` The given landscape is at least one and at most 30 meters long and always starts with ground. **Output** Output is given on standard output and represents a series of movement commands to Matthew, either *run* (`R`) or *jump* (`J`). As noted above, a *run* command causes Matthew to run one meter while jumping carries him forward exactly four meters. For the example given above the following movement is possible: ``` RRJRJRR ``` which looks approximately as follows: ![Illustration of the movement RRJRJRR](https://i.stack.imgur.com/rceVu.png) If there is no safe path through the landscape, then a single exclamation mark (`!`) should be printed. **Sample inputs** ``` -------- ----__--___--- -_______ -_-_-_-_-_- - ``` **Sample outputs** ``` JRRR RRJRJRR ! ! ``` *(the last output is blank as no movement is necessary, but I guess, Markdown cannot parse this)* **Note** Only a single possible path is necessary, so the program output does not have to conform exactly to the sample outputs. As long as a solution is given if it exists and every movement command moves to ground and the last meter is reached eventually, the output is valid. Additional output on standard error is ignored. **Winning condition** Shortest code wins, as is customary in golf. In case of a tie, the earlier solution wins. **Test cases** There are two tests scripts, containing identical test cases: * [bash](http://hypftier.de/dump/CG2896/test) (Thanks to [Ventero](https://codegolf.stackexchange.com/users/84/ventero)) * [PowerShell](http://hypftier.de/dump/CG2896/test.ps1) Invocation is in both cases: `<test script> <my program> [arguments]`, e.g. `./test ruby jumprun.rb` or `./test.ps1 ./jumprun.exe`. **Another note** This task was part of a golf contest held at my university during 2011-W24. The scores and languages of our contestants were as follows: * 104 – Haskell * 131 – Haskell * 154 – C * 170 – C * 275 – VB.NET * 286 – Common Lisp Our own solutions were * 92 – Ruby * 124 – PowerShell [Answer] ## Perl, 53 characters ``` s/-...(?=(-|-...)*-$)/J/g;y/-/R/;/_/?$_="!":s/.$// ``` Run this with `perl -p jumpnrun.pl`. I've counted 3 characters for the `-p` option, which is the length difference between `perl jumpnrun.pl` and `perl -p jumpnrun.pl`. I'm not that fluent in Perl, so I'm pretty sure this can be shortened further. This uses a regexp similar to [Howard's solution](https://codegolf.stackexchange.com/questions/2896/jumping-and-running/2899#2899). [Answer] ### Ruby, 93 90 79 70 characters I thought a regex solution would be quite fine and compact (let the matcher do the work). Unfortunately all the edge-cases and special treatments made this one such long - at least I didn't touch the 100 ;-). ``` puts gets.gsub(/-...(?=(-|-...)*-$)/,?J).tr(?-,?R)=~/^([JR]*)R$/?$1:?! ``` It passes all testcases of the provided script. Saved several characters in comparison to the previous script (now a single call to `gsub` is sufficient). *Edit 1:* Changed `puts z!=?-??!:''` to `z!=?-&&$><<?!` after the test script allowed no output for test case 1. *Edit 2:* The previous version was ``` z=gets.chop z.chars{z.sub!(/^(-|-...)((-|-...)*-)$/){$><<($1==?-??R:?J);$2}} z!=?-&&$><<?! ``` My original idea was to replace the characters by using a look-behind and look-ahead strategy like this: The pattern was `^(?<=[RJ]*)(-|-...)(?=(-|-...)*-$)` and I then would replace '-' with 'R' and otherwise with 'J'. Unfortunately Ruby does not allow variable-length look-behind and another capturing group for the first part made the code even longer. So then I did the iterative approach: if I can start with a step or jump `^(-|-...)` followed by series of other steps or jumps until the last platform `(-|-...)*-$` then I print the corresponding letter, remove the first one/four characters and start over again. On can even tune the RJ vs. JR priority by switching the choices inside the expression (currently it prefers RJ). *Edit 3:* Splitting the single subtitution ``` puts (z=gets.chop.gsub(/(-...|-)(?=(-|-...)*-$)/){$1==?-??R:?J})=~/_/??!:z.chop ``` into two ``` puts (z=gets.chop.gsub(/-...(?=(-|-...)*-$)/,?J).tr(?-,?R))=~/_/??!:z.chop ``` gave another few chars. Finally I managed to get rid of this end-of-line issue but at a cost: the fail-detection costs some more characters. [Answer] # Perl - 71 60 ``` $_=<>;y/-/R/;s/R...(?=(R(...)?)*R$)/J/g;print/_/?"!":s/.$//r ``` Now passes all of the testcases. :) Turns out I was removing the last character too soon... and half of my original regex was entirely redundant. $\_=$ARGV[0];y/-/R/;s/(R...(?=R))(R\*(?=R))/J$2/g;chop;print/*/?"!":$*,$/ Yet another regex solution, passes the 5 testcases in the post. Could be shortened by running as a one-liner with `-E` and `say` instead of `print`, but then perl tries to interpret the input as a switch... (`Unrecognized switch: -_-_-_-_-_-`) [Answer] ## Haskell, 90 characters: My first solution -- long, but works in linear time, using dynamic programming. :) **150 characters**: ``` x!y="!" q '-'=max q c=(!) s i=r where r=zipWith3 q i(0&'R')$3&'J';n&c="":replicate n"!"++map(c#)r c#"!"="!" c#s=c:s main=interact$reverse.last.s.init ``` The second solution -- much slower (exponential time), but much shorter: **90 characters** ``` s"-\n"="" s('-':t)=max('R'#s t)$'J'#s(drop 3 t) s _="!" c#"!"="!" c#s=c:s main=interact s ``` ]
[Question] [ ### Introduction From [Wikipedia](https://en.m.wikipedia.org/wiki/Tessellation): > > A **tessellation** of a flat surface is the tiling of a plane using one or more geometric shapes, called tiles, with no overlaps and no gaps. > > > A fairly well known tessellation is shown below: [![enter image description here](https://i.stack.imgur.com/IgGke.gif)](https://i.stack.imgur.com/IgGke.gif) The rhombi are tiled in a fashion that results in no overlaps or gaps, and simulates interchanging columns of cubes. ### Task Your task is to write a program that tessellates rhombi the same way the image does above. The input for the program will be dimensions of the tessellation: `height x width`, where width is the amount of columns and height is the amount of rows. A single cube that is `1 x 1` (3 tiles of rhombi) is represented exactly as so: ``` _____ /\ \ / \ \ / \ _____\ \ / / \ / / \/_____ / ``` So if the input/dimensions are `3 x 2`, this should be the output: ``` _____ /\ \ / \ \ / \ _____\ _____ \ / /\ \ \ / / \ \ \/_____ / \ _____\ /\ \ / / / \ \ / / / \ _____\/_____ / \ / /\ \ \ / / \ \ \/_____ / \ _____\ /\ \ / / / \ \ / / / \ _____\/_____ / \ / /\ \ \ / / \ \ \/_____ / \ _____\ \ / / \ / / \/_____ / ``` As you can see, there are 3 rows (height), and 2 columns (width). **The columns are interchanging up and down.** Your program should do this too and start higher. For example, `3 x 3` would be: ``` _____ _____ /\ \ /\ \ / \ \ / \ \ / \ _____\ _____ / \ _____\ \ / /\ \ / / \ / / \ \ / / \/_____ / \ _____\/_____ / /\ \ / /\ \ / \ \ / / \ \ / \ _____\/_____ / \ _____\ \ / /\ \ / / \ / / \ \ / / \/_____ / \ _____\/_____ / /\ \ / /\ \ / \ \ / / \ \ / \ _____\/_____ / \ _____\ \ / /\ \ / / \ / / \ \ / / \/_____ / \ _____\/_____ / \ / / \ / / \/_____ / ``` ### Rules * The result must be outputted, input may be taken in whatever way you like but must correspond to height and width * Trailing newlines are allowed * The tessellation columns always start from above then alternate up and down * Sides of tessellations must be shared and tessellations must be correctly placed in between the other columns with no gaps * Your submission may be a function or a full program * Your program must print *exactly* the output above given the same input; in other words the output must follow the same format for cubes/tessellations ### Assumptions * You can assume that the input will always be greater than `1 x 1`, so you don't need cases where a zero is inputted ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/56456) are prohibited as well. [Answer] ## JavaScript (ES6), 243 bytes ``` f= (h,w)=>[...Array(h*6+4)].map((_,i)=>[...Array(w*9+3)].map((_,j)=>i&&(i+j+3)%6==0&&j%9<(i>3?6:3)&&(i>3|j<w*9)&&(j>2|i<h*6)?'/':i&&(i-j+2)%6==0&&j%9<(i>h*6?j<w*9?3:0:6)?'\\':i%3==0&&j>2&&(i*3+j+14)%18%(!i|i>h*6?18:12)<4?'_':' ').join``).join` ` ``` ``` <div oninput=o.textContent=+h.value&&+w.value?f(h.value,w.value):''><input id=h type=number min=1><input id=w type=number min=1><pre id=o> ``` Directly calculates all the desired characters. For `/`: ``` i&& Not on first row of output (i+j+3)%6==0&& Backward diagonals j%9< Not on top (right) diamond of hexagons or (i>3?6:3)&& empty spaces on top half row (i>3|j<w*9)&& Not on top right corner of output (j>2|i<h*6) Not on bottom left corner of output ``` For `\`: ``` i&& Not on first row of output (i-j+2)%6==0&& Forward diagonals j%9< Not on bottom (right) diamond of hexagons or (i>h*6? empty spaces on bottom half row or j<w*9?3:0:6) bottom right corner of output ``` For `_`: ``` i%3==0&& Every third line j>2&& Not on left two columns (i*3+j+14)%18% Every 18 characters (!i|i>h*6?18:12)<4 One or two groups ``` [Answer] # Befunge, ~~277~~ 269 bytes ``` &6*4+00p&:55+*3+10p2%20pv@ 6+5:g03%*54:::<<0+55p03:<<v%*54++55:\p04:**`+3g03g00`\g01+*3!g02\-*84g+3+!\% 48*+,1+:10g`!#^_$,1+:00g-|>30g:2+6%\3-!+3+g48*-\:2`\20g3*+10g\`*30g2`**40g!*+ /\ \ / \ \ / \ _____\ \ / / \ / / \/_____ / _____ ``` [Try it online!](http://befunge.tryitonline.net/#code=JjYqNCswMHAmOjU1KyozKzEwcDIlMjBwdkAKNis1OmcwMyUqNTQ6Ojo8PDArNTVwMDM6PDx2JSo1NCsrNTU6XHAwNDoqKmArM2cwM2cwMGBcZzAxKyozIWcwMlwtKjg0ZyszKyFcJQo0OCorLDErOjEwZ2AhI15fJCwxKzowMGctfD4zMGc6Mis2JVwzLSErMytnNDgqLVw6MmBcMjBnMyorMTBnXGAqMzBnMmAqKjQwZyEqKwogIC9cICAgICAgXAogLyAgXCAgICAgIFwKLyAgICBcIF9fX19fXApcICAgIC8gICAgICAvCiBcICAvICAgICAgLwogIFwvX19fX18gLwogICAgX19fX18&input=MyAz) This question looked deceptively easy, but the edge cases turned out to be more complicated than I had originally anticipated. The best approach I could come up with was to handle the odd and even columns as separate renderings, and then just merge the results. So for each x,y coordinate that has to be output, we first need to determine what character should be rendered for an odd column, by mapping the *x*,*y* output coordinates to *u*,*v* coordinates in the cube diagram as follows: ``` u = x%20 v = (y+5)%6 + (y==0) ``` The addition of `(y==0)` is to handle the special case of the first line. But we also need to make sure we aren't rendering the last few lines at the bottom of the column, and the last few characters on the end of each row. This is achieved by multiplying output character with the expression: ``` (y > h-3) && (x > w-3*!(columns%2)) ``` The `!(columns%2)` in the width calculation is because the amount we need to trim off the end is dependent on whether the total column count is even or odd. We then do a second calculation to determine what character should be rendered for an even column, mapping the *u*,*v* coordinates as follows: ``` u = (x+10)%20 v = (y+2)%6 + (y==3) ``` This is the same basic calculation as used for the odd columns, but offset slightly. And as before, we need to make sure we don't render some of the characters on the boundaries - this time the first few lines at the top of the column, as well as some characters at the beginning and end of each row. The expression we multiply in this case is: ``` (y > 2) && (x > 2) && (x < w-3*(columns%2)) ``` Having calculated these two potential output characters, the final value used is: ``` char1 + (char2 * !char1) + 32 ``` In other words, if *char1* is zero we need to output *char2*, otherwise we output *char1*. If both are non-zero, we're just going to output *char1*, but that's fine because they'd both be the same value anyway. Also note that these character values are offset by 32 (hence the addition of 32) so that zero will always end up as a space. [Answer] ## Batch, 590 bytes ``` @echo off set c=call:c set b=\ \ set f=%b:\=/% set s= set u=_____ set w=%2 %c%" " " %u%" "%s%%s%" %c%" " "/%b%" "%s% " %c%" " "/ %b%" "%s% " %c%"" "/ \ %u%\" " %u% " for /l %%i in (1,1,%1)do %c%"\" " %f%" "%b%"&%c%" \" " %f%" " %b%"&%c%" \" "/%u% /" " \ %u%\"&if %%i lss %1 %c%" /" "%b%" " %f%"&%c%" /" " %b%" " %f%"&%c%"/" " \ %u%\" "/%u% /" %c%" " "" "%s%\ %f%" %c%" " "" " %s%\ %f%" %c%" " "" " %s%\/%u% /" exit/b :c set o=%~1 for /l %%j in (%w%,-2,1)do call set o=%%o%%%~2&if %%j gtr 1 call set o=%%o%%%~3 echo(%o% ``` The `:c` subroutine takes three parameters; `%3` is the difference between 1 and 2 columns, `%2` is the difference between 2 and 3 columns, `%1` is the extra prefix for the first column, so one column is `%1%2`, two columns is `%1%2%3`, three columns is `%1%2%3%2`, four columns is `%1%2%3%2%3` etc. [Answer] # [Python 2](https://docs.python.org/2/), ~~329~~ ~~326~~ 319 bytes ``` h,w=input() a,R=[' '*10]*3,range b=' /\ \ # / \ \ #/ \ _____\#\ / /# \ / / # \/_____ / '.split('#') c=[' _____ ']+b*h e,o=c+a,a+c k=len(e) f=e[:] o[3]=o[3][:10] for x in R(1,w): for y in R(k):f[y]+=((e[y][3:],e[y])[y in R(4)],(o[y][3:],o[y])[y in R(k-3,k)])[x%2] print'\n'.join(f) ``` [Try it online!](https://tio.run/nexus/python2#TU7LbsMgELzvV6xkRYBNQxN6QuIncsWocizcUEdgOa6SfL0LppE6hx3msWLXC79rH6afhTLo@EkbgqQ@vNta8rkLXw7OmiCKFjckqlBsXGQlCn9mtNXmixKKKtdeIu1hK7Za9sj@Nl39QklFGPT514SSJhDbnOsLOB5133S8a3oY9dUF6hgM2hllIRppdR5GpWthiDM@0Ac80QO/MwWYnWdxRqYG87SNptQlNlJZnh/M/BU@mOU0vqL4PxrfJB9Z0o/d0cI0@7CQNpD9d/SBDmxdJZe/ "Python 2 – TIO Nexus") Actually ~~21~~ ~~24~~ 31 bytes shorter than my previous incorrect post. Creates lists for the odd and even columns then concatenates them for each column in the width. ]
[Question] [ The [Laver tables](https://en.wikipedia.org/wiki/Laver_table) provide examples of programs which have not been shown to terminate in the standard axiomatic system of mathematics [ZFC](https://en.wikipedia.org/wiki/Zermelo%E2%80%93Fraenkel_set_theory) but which do terminate when one assumes very large cardinal axioms. **Introduction** The classical Laver tables `An` are the unique finite algebras with underlying set `{1,...,2n}` and an operation `*` that satisfies the identity `x * (y * z)=(x * y) * (x * z)` and where `x*1=x+1` for `x<2n` and where `2n*1=1`. More information about the classical Laver tables can be found in the book Braids and Self-Distributivity by Patrick Dehornoy. **Challenge** What is the shortest code (in bytes) that calculates `1*32` in the classical Laver tables and terminates precisely when it finds an `n` with `1*32<2n`? In other words, the program terminates if and only if it finds an `n` with `1*32<2n` but otherwise it runs forever. **Motivation** A [rank-into-rank](http://cantorsattic.info/Rank_into_rank) cardinal (also called an I3-cardinal) is an extremely large [level of infinity](http://cantorsattic.info/Upper_attic) and if one assumes the existence of a rank-into-rank cardinal, then one is able to prove more theorems than if one does not assume the existence of a rank-into-rank cardinal. If there exists a rank-into-rank cardinal, then there is some classical Laver table `An` where `1*32<2n`. However, there is no known proof that `1*32<2n` in ZFC. Furthermore, it is known that the least `n` where `1*32<2n` is greater than `Ack(9,Ack(8,Ack(8,254)))`(which is an extremely large number since the Ackermann function `Ack` is a fast growing function). Therefore, any such program will last for an extremely long amount of time. I want to see how short of a program can be written so that we do not know if the program terminates using the standard axiomatic system ZFC but where we do know that the program eventually terminates in a much stronger axiomatic system, namely ZFC+I3. This question was inspired by [Scott Aaronson's recent post](http://www.scottaaronson.com/blog/?p=2725) in which Aaronson and Adam Yedidia have constructed a Turing machine with under 8000 states such that ZFC cannot prove that the Turing machine does not terminate but is known not to terminate when one assumes large cardinal hypotheses. **How the classical Laver tables are computed** When computing Laver tables it is usually convenient to use the fact that in the algebra `An`, we have `2n * x=x` for all `x` in `An`. The following code calculates the classical Laver table `An` ``` # table(n,x,y) returns x*y in An table:=function(n,x,y) if x=2^n then return y; elif y=1 then return x+1; else return table(n,table(n,x,y-1),x+1); fi; end; ``` For example, the input `table(4,1,2)` will return `12`. The code for `table(n,x,y)` is rather inefficient and it can only compute in the Laver table `A4` in a reasonable amount of time. Fortunately, there are much faster algorithms for computing the classical Laver tables than the ones given above. [Answer] **Binary Lambda Calculus, 215 bits (27 bytes)** ``` \io. let zero = \f\x. x; one = \x. x; two = \f\x. f (f x); sixteen = (\x. x x x) two; pred = \n\f\x. n (\g\h. h (g f)) (\h. x) (\x. x); laver = \mx. let laver = \b\a. a (\_. mx (b (laver (pred a))) zero) b in laver; sweet = sixteen; dblp1 = \n\f\x. n f (n f (f x)); -- map n to 2*n+1 go2 = \mx. laver mx sweet mx (\_. mx) (go2 (dblp1 mx)); in go2 one ``` compiles to (using software at <https://github.com/tromp/AIT>) ``` 000101000110100000010101010100011010000000010110000101111110011110010111 110111100000010101111100000011001110111100011000100000101100100010110101 00000011100111010100011001011101100000010111101100101111011001110100010 ``` This solution is mostly due to <https://github.com/int-e> [Answer] ## CJam (36 32 bytes) ``` 1{2*31TW$,(+a{0X$j@(@jj}2j)W$=}g ``` In practice, this errors out quite quickly because it overflows the call stack, but on a theoretical unlimited machine it is correct, and I understand that to be the assumption of this question. > > The code for `table(n,x,y)` is rather inefficient and it can only compute in the Laver table A4 in a reasonable amount of time. > > > is not actually correct if we cache computed values to avoid recomputing them. That's the approach I've taken, using the [`j` (memoisation) operator](https://sourceforge.net/p/cjam/wiki/Basic%20operators/#j). It tests A6 in milliseconds and overflows the stack testing A7 - and I've actually *deoptimised* `table` in the interests of golfing. ### Dissection If we assume that `n` is understood from the context, instead of ``` f(x,y) = x==2^n ? y : y==1 ? x+1 : f(f(x,y-1),x+1) ``` we can remove the first special case, giving ``` f(x,y) = y==1 ? x+1 : f(f(x,y-1),x+1) ``` and it still works because ``` f(2^n, 1) = 2^n + 1 = 1 ``` and for any other `y`, ``` f(2^n, y) = f(f(2^n, y-1), 1) = f(2^n, y-1) + 1 ``` so by induction we get `f(2^n, y) = y`. For CJam it turns out to be more convenient to reverse the order of the parameters. And rather than using the range `1 .. 2^n` I'm using the range `0 .. 2^n - 1` by decrementing each value, so the recursive function I'm implementing is ``` g(y,x) = y==0 ? x+1 : g(x+1, g(y-1, x)) ``` --- ``` 1 e# Initial value of 2^n { e# do-while loop 2* e# Double 2^n (i.e. increment n) 31T e# table(n,1,32) is g(31,0) so push 31 0 W$,(+a e# Set up a lookup table for g(0,x) = x+1 % 2^n { e# Memoisation function body: stack is 2^n ... y x 0X$j e# Compute g(0,x) = x+1 % 2^n e# Stack is 2^n ... y x (x+1%2^n) @( e# Bring y to top, decrement (guaranteed not to underflow) e# Stack is 2^n ... x (x+1%2^n) (y-1%2^n) @jj e# Rotate and apply memoised function twice: g(x+1,g(y-1,x)) } 2j e# Memoise two-parameter function e# Stack: 2^n g(31,0) )W$= e# Test whether g(31,0)+1 is 2^n }g e# Loop while true ``` [Answer] # Pyth, 33 bytes ``` .N?qT^2NY?tY:N:NTtYhThT<:T1 32^2T ``` [Try it online!](http://pyth.herokuapp.com/?code=.N%3FqT%5E2NY%3FtY%3AN%3ANTtYhThT%3A.*&input=%284%2C1%2C2%29&debug=0) (Obviously the testing part is not included here.) [Answer] # Javascript, 53 bytes ``` for(M=0;!g(1,31);M-=~M)g=(x,y)=>y?g(g(x,y-1),x):x+1&M ``` Define `g(x,y)=x*(y+1)` on \$F\_{2^n}\$, aka. \$2^n\$ is written as 0 ]
[Question] [ ### The Background Imagine the English alphabet written out in a row in capital letters -- `ABCDEFGHIJKLMNOPQRSTUVWXYZ`. Suppose we have a special variable-width lens such that, when placed over the row, it shows a certain "window" of the alphabet, with letters outside the lens hidden from view. Additionally, this lens has a warping characteristic, so that the first letter inside the lens, and every second letter thereafter, is lower-cased, but the remaining letters still show capitalized. For example, we could have a lens of length 5 placed somewhere in the middle of the alphabet and we would only see `. jKlMn` (leading period here to ensure whitespace shows) -- note the `K` and `M` are still capitalized, while the `j`, `l`, and `n` are all lower-cased. As we slide this lens from left-to-right along the alphabet, different letters would be shown and different letters capitalized. The task here is to output the resultant letters as the lens slides along the alphabet. ### The Challenge Write a program or function that takes an input integer `0 < n < 27` and outputs or returns the string(s) that are visible as the lens described above slides across the alphabet. For values of `n` larger than `1`, the lens begins by "hanging" off the left side of the alphabet, so only the `A` is shown in the right-most slot of the lens. The first line of any output will thus be a single `A`, either capital or lowercase depending upon the length of the lens. Similarly, the lens finishes sliding when the `Z` is in the left-most slot of the lens (meaning that the very last line in any output will always be 25 spaces followed by a lowercase `z`). ### The Examples Input: `1` Output: ``` a b c d e f g h i j k l m n o p q r s t u v w x y z ``` Input: `4` Output: ``` A aB AbC aBcD bCdE cDeF dEfG eFgH fGhI gHiJ hIjK iJkL jKlM kLmN lMnO mNoP nOpQ oPqR pQrS qRsT rStU sTuV tUvW uVwX vWxY wXyZ xYz yZ z ``` Input: `26` Output: ``` A aB AbC aBcD AbCdE aBcDeF AbCdEfG aBcDeFgH AbCdEfGhI aBcDeFgHiJ AbCdEfGhIjK aBcDeFgHiJkL AbCdEfGhIjKlM aBcDeFgHiJkLmN AbCdEfGhIjKlMnO aBcDeFgHiJkLmNoP AbCdEfGhIjKlMnOpQ aBcDeFgHiJkLmNoPqR AbCdEfGhIjKlMnOpQrS aBcDeFgHiJkLmNoPqRsT AbCdEfGhIjKlMnOpQrStU aBcDeFgHiJkLmNoPqRsTuV AbCdEfGhIjKlMnOpQrStUvW aBcDeFgHiJkLmNoPqRsTuVwX AbCdEfGhIjKlMnOpQrStUvWxY aBcDeFgHiJkLmNoPqRsTuVwXyZ bCdEfGhIjKlMnOpQrStUvWxYz cDeFgHiJkLmNoPqRsTuVwXyZ dEfGhIjKlMnOpQrStUvWxYz eFgHiJkLmNoPqRsTuVwXyZ fGhIjKlMnOpQrStUvWxYz gHiJkLmNoPqRsTuVwXyZ hIjKlMnOpQrStUvWxYz iJkLmNoPqRsTuVwXyZ jKlMnOpQrStUvWxYz kLmNoPqRsTuVwXyZ lMnOpQrStUvWxYz mNoPqRsTuVwXyZ nOpQrStUvWxYz oPqRsTuVwXyZ pQrStUvWxYz qRsTuVwXyZ rStUvWxYz sTuVwXyZ tUvWxYz uVwXyZ vWxYz wXyZ xYz yZ z ``` ### The Rules * Standard [input/output rules](http://meta.codegolf.stackexchange.com/q/2447/42963) apply * Standard [loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) disallowed * Standard [code-golf rules](https://codegolf.stackexchange.com/tags/code-golf/info) apply * The leading whitespace as shown is required, so that we know where we're at in the alphabet. * **Each line cannot have trailing whitespace** (as shown - the output is not a rectangle). * A single trailing newline is optional. [Answer] # Pyth, 31 bytes ``` Vr_tQ26s.erb%+Nk2+*Nd:GeS,0N+NQ ``` [Try it online.](http://pyth.herokuapp.com/?code=Vr_tQ26s.erb%25%2BNk2%2B%2aNd%3AGeS%2C0N%2BNQ&input=5&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=Vr_tQ26s.erb%25%2BNk2%2B%2aNd%3AGeS%2C0N%2BNQ&test_suite=1&test_suite_input=1%0A4%0A5%0A26&debug=0) Quick and dirty. [Answer] ## JavaScript (ES6), 130 bytes ``` n=>[...Array(n+25)].map(_=>[...Array(26)].map(_=>String.fromCharCode(j++<i|i+n<j?32:j+(j-i)%2*32),++i,j=64).join``,i=64-n).join`\n` ``` Where `\n` represents the literal newline character. Works by looping over the output rectangle and outputting spaces outside the diagonal while adding 32 to the character code to lower case it in alternate squares. Using `replace` appears to be 1 byte longer: ``` n=>[...Array(n+25)].map(_=>' '.repeat(26).replace(/./g,s=>j++<i|i+n<j?s:String.fromCharCode(j+(j-i)%2*32),++i,j=64),i=64-n).join`\n` ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~160~~ 141 bytes ``` {d=-$1 for(m=25;i++<m+$1;print""){f="%"(++d<0?0:d<m?d:m)"s" c=u=65 printf f,"" for(j=++E-$1;j<E&&j<26;printf(j<0?"":"%c",c+j++))c=c==u?97:u}} ``` [Try it online!](https://tio.run/##JczRCoMgFADQd79iXCqU2yCDGlMvPvUhQxFyuI022UP07S7a@@HcvvdSVk/nSrLwXHiiftAzoklYSf1a5scHQKyBoAaO6E1nO@VNsl4lAW9gjjKNAztkOIUW4HgiIU57qqOZmiaafvxngce9AFBQO2gdRkQhHDmibK8XlbetFFl@ "AWK – Try It Online") Thanks to @ceilingcat, code rearranging helped to remove a `continue` statement and a total of 19 bytes [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes ``` ØAżØaU¡ṁ€µJR;"z⁶Ḋḣ"JY ``` [Try it online!](https://tio.run/##AS8A0P9qZWxsef//w5hBxbzDmGFVwqHhuYHigqzCtUpSOyJ64oG24biK4bijIkpZ////NA "Jelly – Try It Online") ## How it works ``` ØAżØaU¡ṁ€µJR;"z⁶Ḋḣ"JY - Main link. Takes an integer n on the left ØA - Uppercase alphabet Øa - Lowercase alphabet ż - Zip; [['A', 'a'], ['B', 'b'], ...] ¡ - Do n times: U - Reverse each pair This means we have a leading capital for even n, or a trailing capital for odd n € - Over each pair: ṁ - Mold it to length n µ - Begin a new link with this list of characters C J - Yield [1, 2, ..., 26] R - Yield [[1], [1, 2], ..., [1, 2, ..., 26]] ;" - Concatenate each of these ranges with the lists in C z⁶ - Transpose, filling with spaces Ḋ - Remove the first line ḣ"J - Remove the trailing integers from each line Y - Join with newlines ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ₂Iи2.ýžpA«RŽR‘S.Λ„ ¶: ``` [Try it online.](https://tio.run/##AS4A0f9vc2FiaWX//@KCgknQuDIuw73FvnBBwqtSxb1S4oCYUy7Om@KAniAKwrY6//80) Or alternatively: ``` ₂2‚Iи¨ARÂu«ŽR‘S.Λ„ ¶: ``` [Try it online.](https://tio.run/##ATAAz/9vc2FiaWX//@KCgjLigJpJ0LjCqEFSw4J1wqvFvVLigJhTLs6b4oCeIArCtjr//zQ) **Explanation:** This program uses the Canvas builtin `Λ` to draw the output. This builtin takes three arguments: 1. Length of the lines we'll draw: the list `[26,2,26,2,...,26]` in this case: ``` #(alternative 1) ₂ # Push 26 Iи # Repeat it the input amount of times as list 2.ý # Intersperse it with 2 #(alternative 2) ₂2‚ # Pair 26 with 2: [26,2] Iи # Repeat this list the input amount of times ¨ # And remove the trailing 2 ``` 2. Character/string to draw: the string `"zyxwvutsrqponmlkjihgfedcbaABCDEFGHIJKLMNOPQRSTUVWXYZ"` in this case: ``` #(alternative 1) žp # Push builtin string "ZYXWVUTSRQPONMLKJIHGFEDCBA" A« # Append builtin string "abcdefghijklmnopqrstuvwxyz" R # Reverse this string to "zyxwvutsrqponmlkjihgfedcbaABCDEFGHIJKLMNOPQRSTUVWXYZ" #(alternative 2) A # Push builtin "abcdefghijklmnopqrstuvwxyz" R # Reverse it: "zyxwvutsrqponmlkjihgfedcba"  # Bifurcate it (short for Duplicate & Reverse copy) u # Uppercase the reversed copy "ABCDEFGHIJKLMNOPQRSTUVWXYZ" « # Append it: "zyxwvutsrqponmlkjihgfedcbaABCDEFGHIJKLMNOPQRSTUVWXYZ" ``` 3. The direction to draw in: `[7,0,3,0]`. The digits in the range `[0,7]` each represent a certain direction: ``` 7 0 1 ↖ ↑ ↗ 6 ← X → 2 ↙ ↓ ↘ 5 4 3 ``` So the `[7,0,3,0]` in this case translates to the directions \$[↖,↑,↘,↑]\$: ``` ŽR‘ # Push compressed integer 7030 S # Convert it to a list of digits: [7,0,3,0] Λ # Use the Canvas builtin with the three pushed arguments, # after which the result is implicitly output immediately afterwards ``` Unfortunately, the Canvas builtin adds trailing spaces to make it a rectangle by default, so we'll have to remove those to comply to the challenge rules: ``` .Λ # Use the modifiable Canvas builtin instead „ \n # Push the string " \n" ¶ # Push the builtin string "\n" : # And keep repeating " \n" with "\n" until there are no longer any left # (after which the result is output implicitly) ``` Here a step-by-step explanation of the output for input \$n=3\$: Step 1: Draw 26 characters (`"zyxwvutsrqponmlkjihgfedcba"`) in direction `7↖`: ``` a b c d e f g h i j k l m n o p q r s t u v w x y z ``` Step 2: Draw 2-1 characters (`A`) in direction `0↑`: ``` A a b c d e f g h i j k l m n o p q r s t u v w x y z ``` Step 3: Draw 26-1 characters (`"BCDEFGHIJKLMNOPQRSTUVWXYZ"`) in direction `3↘`: ``` A aB bC cD dE eF fG gH hI iJ jK kL lM mN nO oP pQ qR rS sT tU uV vW wX xY yZ z ``` Step 4: Draw 2-1 characters (`"z"`) in direction `0↑`: ``` A aB bC cD dE eF fG gH hI iJ jK kL lM mN nO oP pQ qR rS sT tU uV vW wX xYz yZ z ``` Step 5: Draw 26-1 characters (`"yxwvutsrqponmlkjihgfedcba"`) in direction `7↖`: ``` a Ab aBc bCd cDe dEf eFg fGh gHi hIj iJk jKl kLm lMn mNo nOp oPq pQr qRs rSt sTu tUv uVw vWx wXy xYz yZ z ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ŽR‘` is `7030`. [See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal/wiki), 14 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page) ``` UTFN«P↘⎇﹪ι²αβ↑ ``` [Try it online (verbose)](https://tio.run/##DcyxDsIgEIDhvU9x45HAYpzqakwc6mDwAWglQEI5coU2xvjsyPgP3794wwuZ2Jom56LVHFYUl@FGjPeUa3nUdbaMQnwHgKnGEjKHVHC80pGewfkiQVtOhj840btGwiDhJCQYCbPoq85otzi@co9fa@em9tiUOnwodstmsX8) or [try it online (pure)](https://tio.run/##ATIAzf9jaGFyY29hbP//77y177y077ym77yuwqvvvLDihpjijofvuarOucKyzrHOsuKGkf//NA). **Explanation:** Toggle trim so the output won't contain any trailing spaces to comply to the challenge rules. Charcoal will make the output a rectangle by default: ``` ToggleTrim(); UT ``` Loop the input amount of times: ``` For(InputNumber()){ ... } FN« ``` Print in a down-right diagonal direction without moving the cursor: ``` Multiprint(:DownRight, ...); P↘ ``` Print the uppercase alphabet if the loop index is odd, or the lowercase alphabet if it's even (`b`/`β` is a variable that contains the lowercase alphabet by default and `a`/`α` is a variable that contains the uppercase alphabet by default): ``` Ternary(Modulo(i, 2), a, b) ⎇﹪ι²αβ ``` And then move the cursor one position up for the next iteration: ``` Move(:Up); ↑ ``` [Answer] # [Python 3](https://docs.python.org/3/), 105 bytes ``` lambda n:[(i-n)*' '+''.join(chr(97+j-(j^i^n)%2*32)[:-1<j<26]for j in range(i-n,i))for i in range(1,26+n)] ``` [Try it online!](https://tio.run/##RcvLCoMwEIXhvU8xm5KMl4KxWBrsk1gFe7FOaCcS3fTpUwcK3Z3/gzN/1slzFcfzJb6G9/U@ANtWU8GYKlCZUnvnifVtCvp0zFyhXU89486klcHWFmXjGlN3ow/ggBjCwM@H/HNCFKW/lrmpM8YuirP4RocN0SYgtoiNmqVhDsSrXjD5LYxf "Python 3 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~21~~ 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ;B¬£îXpv éU)iYçÃÕmx1 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=O0Kso%2b5YcHYg6VUpaVnnw9VteDE&input=MQ) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O0Kso%2b5YcHYg6VUpaVnnw9VteDE&footer=tw&input=WzUgMSA0IDI2XQotbVI) ``` ;B¬£îXpv éU)iYçÃÕmx1 :Implicit input of integer U ;B :Uppercase alphabet ¬ :Split £ :Map each X at 0-based index Y î : Repeat and slice to length U Xp : Append to X v : Its lowercase éU : Rotate right U times ) : End repeat i : Prepend Yç : Y spaces à :End map Õ :Transpose m :Map x1 : Trim right :Implicit output joined with newlines ``` [Answer] # [Scala](http://www.scala-lang.org/), 137 bytes Golfed version. [Try it online!](https://tio.run/##PY5BS8NAEIXv/RVDwDLTNMHEVjF2A@JJ0FPxJBbWuGl3TTbtZhGk5LfHSRM87A5v3sd70xaykn3zaVTh4VVqC@cZwJcqoWaB0u3bDB6dk7/vW@@03X9QBm9WexAXEqBsHFrYRPCiW4/JElZLSG@JJpsBtBQzpWRxwCNn@MrS5E0SR93NLo//H1lBmQE@Wy/yrTr9l3Ntb0WOCfgG0nXI0bU8njWvAggWqCNLFOIwB0JHyQgYkQ@Zhbi/C02EaHZ6Z@kqpcVN@qBLNLm4ns/Nhi8vYt88HaTjMbaCqloVBF1cf48L6gZPnfqu/wM) ``` n=>(1 to 25+n).map{i=>(" "*(i-n))+((i-n to i-1).map{j=>val c=97+j-((j^i^n)%2)*32;if(j>=0&&j<26)c.toChar.toString else""}.mkString)}.toSeq ``` Ungolfed version. [Try it online!](https://tio.run/##RZBRS8MwFIXf9ysOBceNbsVVUSzrQHwS9El8Egcxpltqmo40CjL62@vtms2Hkl7Od87JTauklX3ffFRaBTxL47CfAJ@6RM0DSb9pc9x7L3/fXoI3bvMucrw6E1AcSKBsPDks53gybaDFDNczZDdCRJkBciJlSku1pR1nBOtE1OJI49xNhi/2sy3HowvcNyQf60@9tMC3C8ZyGS7AFbXcYQ@DYhXDKUGCc5DBnHXBFI3/0WiOnurfA/xIC8Utd7dsqBgnqrDm3DWH4AyZ4Myr7MSbEgysClxiOmXDctgepEQamoet9HyMV4e2rUaSRGeX1l@jEJdncFj08AZd3/8B) ``` object Main { def main(args: Array[String]): Unit = { for(n <- List(1, 4, 26)) { f(n).foreach(println) println() } } def f(n: Int): List[String] = { (1 until 26 + n).map { i => (" " * (i - n)) + ((i - n until i).map { j => val c = 97 + j - ((j ^ i ^ n) % 2) * 32 if (j >= 0 && j < 26) (c).toChar.toString else "" }.mkString) }.toList } } ``` ]
[Question] [ Write a program that a will play a game of Misère tic-tac-toe. That is, the goal is to force your opponent to take three in a row. Accept on standard input either an 'X' or an 'O'(the letter, not zero), to determine which side the program will be playing as. Then output a single digit for your move on your turn, and read a single digit on your opponents turn until the game is over (X always goes first). Once a winner is decided, output X or O for who won, or D for a draw. For example, if O gets 3 in a row, X wins. Assume the board is numbered like so: ``` 0|1|2 ----- 3|4|5 ----- 6|7|8 ``` Ideally a solution will be optimal and never lose. Like tic-tac-toe, perfect play should always result in a draw. If the above protocol is adhered to, I can test submissions automatically against a variety of possible strategies. Winner is shortest code. bonus points if it picks randomly from equally good moves to make it a bit more unpredictable. [Answer] ## Python, 383 chars ``` M=[21,1344,86016,4161,16644,66576,65793,4368] X=lambda B,k:any(m*k==B&m*3for m in M) def S(B): if X(B,2):return 1, M=[i for i in range(0,18,2)if B>>i&3<2] return max((-S((B|3<<i)^87381)[0],i)for i in M)if M else(0,) r='D' c=ord(raw_input())&1 B=0 for i in range(9): if i&1==c:m=S(B^c*87381)[1];print m/2;B|=3-c<<m else: B|=2+c<<input()*2 if X(B,2+c):r='XO'[c];break print r ``` The board `B` is represented as an integer using two bits per square, with `00` and `01` representing empty, `10` representing O and `11` representing X. `M` is a set of bitmasks with `01` in the spots of a losing triple (`21` = `0b010101` = the top row etc.) `X` computes if any losing triple for `k` is present on a board. `S` does minimax search for an optimal move for X, returning a pair of the score (1=win, -1=lose, 0=draw) and a square index. `^87381` (=`^0b010101010101010101`) flips X and O while leaving empty squares unchanged. The computer never loses, so I didn't need to include that check :) . There is probably an easier/shorter rule-based algorithm out there, but this works. ]
[Question] [ Getting hit in the knee with arrows seems to be the [injury of choice](http://www.youtube.com/watch?v=vncIBREXCwU) right now. As such, I propose the following golf challenge. You have an adventurer that looks like this: ``` O /|\ / | \ | | / \ / \ ``` Given a text file that contains one bow (drawn as a `}` symbol), a set of walls (drawn as `#` symbols) and one adventurer, write the smallest code that calculates the angle and initial velocity at which you should fire an arrow in order to hit him in the knee. Assume the following: * Each character in the file is 0.5 x 0.5 meters. * The arrow is fired from the center of the `}`, i.e. an offset of `0.25m, 0.25m` * Gravity is `10ms^-2` * Arrow weighs `0.1kg` * Arrow is a point, i.e. collisions only occur when the arrow's coordinate enters one of the blocks. * Maximum initial velocity is `50m/s` * Angle may be between 0 (straight up) and 180 (straight down) * Hitting any part of the adventurer's leg is considered a hit to the knee. * A wall (`#` character) takes up one entire 0.5m x 0.5m block. * The arrow can travel over the "top" of the file, but there's nothing to stop the input from starting with a ceiling of `#` characters. * You can't penetrate walls with arrows. * Hitting any other part of the adventurer is not allowed! * You should display an error if hitting him in the knee is impossible. Example input: ``` # } O # /|\ / | \ # | # | / \ / \ ``` Feel free to ask questions if you need to :) [Answer] ## Python, 599 chars ``` import os,sys from math import* I=os.read(0,999) O=[] h=v=0 for i in I: if'#'==i:O+=[(h,v,h+1,v+1),(h+1,v,h,v+1)] if'O'==i:O+=[(h,v+1,h-2,v+3)];T=(h,v+5,h-2,v+7) if'}'==i:e=h+.5;c=v+.5 h+=1 if'\n'==i:v+=1;h=0 def X(K,L): A,B,C=K;p=L[0];q=L[2]-p;r=L[1];s=L[3]-r;A,B,C=A*q*q,2*A*p*q+B*q-s,A*p*p+B*p+C-r;d=B*B-4*A*C return 0 if d<0 else any(0<x<1 for x in[(sqrt(d)-B)/2/A,(-sqrt(d)-B)/2/A]) R=range(1,999) for v in R: for z in R: z*=pi/999;d=v*sin(z)/10;b=-v*cos(z)/10 K=20/d/d,b/d-40*e/d/d,c+20*e*e/d/d-b*e/d if X(K,T)and not any(X(K,x)for x in O):print v/2,z;sys.exit(0) print'ERROR' ``` The `X(K,L)` routine takes a parabola `K=(a,b,c)` representing *y=ax^2+bx+c* and a line segment `L=(a,b,c,d)` representing the segment between *(a,b)* and *(c,d)*. Both obstacles (`O`) and the target (`T`) are repesented as line segments. All distances are scaled by a factor of 2. The example input gives the following trajectory (by default, the minimum velocity one): ``` -- # -- -- - O # - /|\ - / | \ # - | # - | - / \ - \ ``` you can reverse `R` to get the maximum velocity path: ``` # ------------- O -----------# /|\ -------- / | \ # ------- | # ----- | ----- / \ ----- \ ``` ]
[Question] [ Your task: generate a Koch snowflake to the nth depth. You do not need to make a complete Koch snowflake, just one side of the starting triangle. Wikipedia on Koch flakes: <https://en.wikipedia.org/wiki/Koch_snowflake>. **Rules:** * The program must generate one side of the Koch snowflake to the nth depth. * Output must be ASCII. * You **may** generate the whole snowflake; this is not required. * Standard rules for input/output and loopholes and stuff apply. * Whitespace does not matter, as long as it all characters are in the right place relative to each other. * Shortest code wins! **Test cases:** n=0: ``` __ ``` n=1: ``` __/\__ ``` n=2: ``` __/\__ \ / __/\__/ \__/\__ ``` n=3: ``` __/\__ \ / __/\__/ \__/\__ \ / /_ _\ \ / __/\__ __/ \__ __/\__ \ / \ / \ / __/\__/ \__/\__/ \__/\__/ \__/\__ ``` I hope this makes sense. Notice that in each test case, the fractal can be divided into three parts equal in length. Also notice that the width of each snowflake is three times the width of the previous generation of the snowflake. [Answer] # [Haskell](https://www.haskell.org/), ~~308~~ ~~300~~ 299 bytes Edits: * -4 bytes: Changing `zipWith(+)` to `zipWith(-)` and adjusting encodings and offsets got rid of every negation sign. * -1 byte: Further tweaking the encoding allowed several variable names in `#` to be dropped by using `r=reverse` instead of direct pattern matching. * -2 bytes: Using an operator instead of alphanum for `zipWith(-)`. * -1 byte: Defining `o=[0,0]` to shorten list constants. * -1 byte: Merging two branches of `?`. ``` import Data.List k n=0?sort(o#(f=<<scanl1(+)(iterate(>>=(:[1,4,1]))[6]!!n))) x?l@(([_,w],c):r)|x>w='\n':0?l|0<1=([2..w-x]>>" ")++[c|w>x]++w?r _?_="" w#((c,l):m)=(l&w,c):r l&(l&w)#m _#_=[] f x=zip"_/\\_/\\"([id,r]<*>[0:1:o,[0,1,0,1],o++[1,1]])!!mod x 6<$[1,3..gcd 3x] (&)=zipWith(-) r=reverse o=[0,0] ``` [Try it online!](https://tio.run/nexus/haskell#HZA9b4MwFEV3/woDUfJecSg0VQaETYeO3TsYCyEgrRU@ImPVVpX/nkKHK12d4VzpPvR4m42l741tkg@9WHKlE0/LZYUwR3DhRbG0zTRkECNo25vG9iAEh1xm7JVlClGeVRBMiEh8ObwByJo5xVrMDd69cPxQTYc8LYd7WmQc5EuSuKNXQoQ0xDiW7d0Jr@LYlYbUZc3DkLgIoGUD5iNyGPbuX0aH/dYxGkkd1VwqcqGe/@pbWD9X1ZYQpO6YUcWTkGme5TOTKcvYGsXmdSlbi8IgGOeOenoudis5JclX29GTVwT2uOk@tf2GIxLDTf/Tm6UnM189qXqMjZ64nrYTWru7JqZvusfpDw "Haskell – TIO Nexus") (Sadly, anything bigger than n=3 gets horribly wrapped and unreadable, but you can copy it to another program to see it.) **Variations** * If you change `[6]` into `[6,4,4]`, you get a whole snowflake. [Try it online!](https://tio.run/nexus/haskell#HZA9b4MwFEV3/woDUfJecQhuogwImw4du3dwLISAtFb4iAyqUZX/npoOVzq6w7nSfZr@PtqZvldzlXyYaSY3Ooi0mHwJYwRXkedTXQ0dhxjBzK2t5hakFJApzk6Ma0R19nDSQTAgIlmK7g1AlcxpVmNm8bFIJ3aXYZelRfdIcy5AvSaJ2y9aypCGGMeqfji56Dh2hSVlUYowJC4CqFmHWY8Cuq37l9FuuzJGPSmjUihNrnQRv@YelofLZU0IyjTM6vxFqjTj2chUyjjz0Wz0S9yDxiDox4Yu9JxvfHNMkq@6ocdFE9jiqvs08zfskVhh25/WTi0Zhfek@tlXZhBmWI@o580tsW3VPI9/ "Haskell – TIO Nexus") * If you remove `,3..gcd 3x`, you get a curve in the style that this question was originally given with. [Try it online!](https://tio.run/nexus/haskell#HY9Na4QwGITv@RVRF/d9a9aatuxBTOyhx957iEHEdWlYP5YYGin73632MPAwMDPMaob7ZB39aFyTfprZkRsdRVbOmwlTBFdRFHPbjD2HBMG4zjauAykF5IqzN8Y1ojrrIBgRkSxl/w6gauY1azG3@FikF8dqPOZZ2T@yggtQL2nqT4uWMqQhJolqH14uOkl8aUld1iIMiY8AWtZjPqCAPvb/ZbSPd8ZoIHVUC6XJlS7i19zD@rmqdoWgzIVZXTxJleU8n5jKGGebNJu2Jb6BxiAYpgtd6Lk4KK4JxLiXfBn3DSckVtjup7NzRyaxpTO9Do0ZhRn366073FLbNZf19Q8 "Haskell – TIO Nexus") * Or both at once: [Try it online!](https://tio.run/nexus/haskell#HY89b4MwGIR3/woDUfK@xSG4jTIgbDp07N7BsRAColrhIzJWjar8dwodTnp00t3pFtM/RuvoR@Wq5NNMjtzpINJiWk0YI7iJPJ/qaug4xAjGtbZyLUgpIFOcnRnXiOqywlkHwYCIZC66dwBVMq9ZjZnF5yy9OFyHQ5YW3TPNuQD1miT@OGspQxpiHKv66eWs49gXlpRFKcKQ@AigZh1mPQro9v6/jHb7jTHqSRmVQmlyo7P4NY@wPF2vm0JQpmFW5y9SpRnPRqZSxtkqzcZ1ia@gMQj6saEzveQ7xTWBPW4lX8Z9wxGJFbb9ae3UklGs6VQvfWUGYYbtfu1298S2VbO8/QE "Haskell – TIO Nexus") # How it works * `k` is the main function, it takes an `Int` `n` and returns a `String`. * `iterate(>>=(:[1,4,1]))[6]` generates an infinite list containing, for each n, the *turns* between consecutive lines in that curve iteration, turtle graphics style, as numbers nominally between `0` and `5`. Each iteration is just the previous one with the turns `1,4,1` interleaved. The only reason the sublists start out with `6` instead of `0` is to make the `gcd` trick in `f` work by avoiding `f 0`. * `scanl1(+)` converts the turns into "absolute" directions, up to modulo 6. A `0` means rightwards, then each higher number is 60 degrees counterclockwise from the previous. (Well, it would be 60 degrees if this was a proper drawing rather than ASCII.) * `f` converts an absolute direction into a list of (character, offset encoding) pairs that encodes which characters to add to the curve (for horizontal directions it generates two pairs, otherwise one), and how the relative position changes. * The `#` operator iterates through the previous list of (character, offset encoding) pairs, generating actual (coordinate,character) pairs. * Encoding principles: + A character from `_/\` nominally represents a line drawn from a starting corner through a rectangular cell to a different ending corner. + Cell coordinates are of the form `[y,x]`, top to bottom, left to right, so that they sort in the order we want to print them. Columns are 1-based. Lists are used instead of tuples for shorter vector arithmetic with `(&)=zipWith(-)`. + A corner is denoted with the same coordinates `[y,x]` as the cell to its upper left. This ensures that all offsets from a corner to its neighboring cells are nonnegative, avoiding negative constants. + However, *corner* coordinates are passed around negated to allow all vector operations to be subtractions instead of additions, which avoids all other explicit signs. + An offset encoding list is `[y1,x1,x2,y2]` where `[y1,x1]` is the coordinate offset from the starting corner to the character cell and `[y2,x2]` is the offset from the end corner to the character cell. This means: - The encoding lists for the directions `3`..`5` are just the reverse of the lists for `0`..`2`, allowing them to be generated with `[id,r]<*>`. - All necessary vector arithmetic can be done by using `(&)=zipWith(-)` with either an encoding list or its reverse. * After sorting the list of (coordinate, character) pairs, they are passed to `?`, which generates the final `String` from them. + In `x?l@(([_,w],c):r)` `x` is the x-coordinate of the previous character shown on this line, or `0` if at the start of a line; `l` is the whole current list, `w` is the x-coordinate of the next character to be added, `c` is the character, and `r` is the remaining list. + At this stage the y-coordinates are no longer needed. Because every line contains characters, and every line's first character is well to the left of the end of the previous one, the start of new lines is detected by checking if the x-coordinate has decreased. + Underscore has a larger ASCII value than `\` and `/`, so it gets sorted last if it overlaps with another character in the same position. Thus a redundant underscore is detected by checking that an x-coordinate has been repeated. ]
[Question] [ This challenge is to write a **minimax function** in a language of your choice, to output the next best move in an **NxN** game of **tic-tac-toe** given the **current board state**. The board input can be accepted as a **Matrix, 2D Collection** or **anything else that makes sense to you, but adheres to the rules**. The output being **the next best move** for **whoever's turn it is currently**, where **X is considered to have started**. # Quick Background on the Minimax Algorithm The basic idea of the minimax algorithm is to enumerate all possible outcomes as a DAG then weight them by the benefit that the sequence of moves has to the player, keyed by the first move made. All possible outcomes are then 'bucketed' by the first move, and are scored based on the sum of all outcomes (-1 for a loss, 0 for a tie and a 1 for a win). In implementations that require multiple players to play, you enumerate all possible moves by the player, and all possible responses by the opponents as well. For instance, in a game of tic-tac-toe (after the first move) there are 8 possible first moves you can make, and they all may seem equal when only analyzing the next turn. But by iterating through all possible outcomes for each possible set of moves that results in a final outcome and summing them all up, we can get a score for our next move, and have a basis for our choices. For a better, more in-depth and contextual summary of the mini-max algorithm in terms of tic-tac-toe, read more here: <http://neverstopbuilding.com/minimax> # XKCD (3x3 Solution Only) [![All possible moves for a 3x3 game of tic-tac-toe.](https://i.stack.imgur.com/LHzYc.png)](https://i.stack.imgur.com/LHzYc.png) # The Rules * Any language can be used, but no external minimax libraries are allowed. * Output can be a coordinate (0-n,0-n) or a number (1-n\*n) indicative of the best next move. + In addition to this, you must be able to identify when the best case scenario is a loss or a tie instead of a win. + The way you denote a loss or a tie is, once again, up to you. * Input must use the traditional X and O, and you must assume X moves first; blank spaces can be represented by anything. * You may assume any inputs coming into your program have n O's and n+1 X's, in other words you may assume you're getting a well-formed board. * The current state of the board must be the only input to your program, if you are using recursion, helper methods must be made to facilitate the input requirements. See <https://codegolf.stackexchange.com/a/92851/59376> for clarification. * Any value of 10 >= n >= 1 must be supported; if your program "times out" for n > 10, I find this acceptable as well, as some languages have significantly lower processing power (Especially using web-facing consoles). # Judging * This is code-golf, so the lowest byte-count of the program wins and standard loopholes are universally disallowed. * In the case of a tie, the program that supports the largest 'n' will win. # Example Inputs ## 2x2 ``` [[X,O] [-,-]] ``` **Output:** 2 or [0,1] (3 or [1,1] would also be arguably correct) (Some form of indication of the location, arbitrary as long as you can easily explain the format you used) --- ## 3x3 ``` [[X,O,X] [O,X,-] [-,-,-]] ``` **Output:** -1 (Loss) --- Once again any input format you want is allowed, but X's and O's must be used, the examples provided were not meant to constrain to that format, just to inspire. [Answer] # Perl, ~~101~~ 98 bytes Includes `+4` for `-0p` Run with the input on STDIN ``` tictactoe.pl OXO --- --X ^D ``` Output is the same diagram, but with each move updated with its status, `1` represents a win, `2` represents a draw and `3` represents a loss. For this case that would be ``` OXO 223 21X ``` so 3 moves draw, 1 wins and 1 loses (I'll update the solution if this output format is unacceptable, but the basic code will remain the same) `tictactoe.pl`: ``` #!/usr/bin/perl -0p m%@{[map"O.{$_}"x"@-"."O|",1-/.( )(.)/,@-]}Z%sx||s%-%$_="$`X$'";y/XO/OX/;do$0%eg?/1/?3:1+/2/:2 ``` This is already painfully slow and uses lots of memory for the empty 3\*3 board (why actually, the recursion doesn't go that deep. Must be some memory leak). Adding memoizing costs 6 bytes but is a lot saner: ``` #!/usr/bin/perl -0p $$_||=m%@{[map"O.{$_}"x"@-"."O|",1-/.(\n)(.)/,@-]}Z%sx||s%-%$_="$`X$'";y/XO/OX/;do$0%eg?/1/?3:1+/2/:2 ``` [Answer] ## Javascript (ES6), ~~320~~ 294 bytes ``` (b,p,d,M,S=-2)=>(T=(p,q,r,s)=>b[p][q]==(n=b[r][s|0])&&n!='-',w=0,b.map((r,y)=>(l=r.length-1,m=15,r.map((c,x)=>(m&=8*T(l-x,x,l)+4*T(x,x,0)+2*T(x,y,0,y)+T(y,x,y))),w|=m)),w?-1:(b.map((r,y)=>r.map((c,x)=>S<1&&c=='-'&&(r[x]='O.X'[p+1],(s=-f(b,-p,1))>S&&(S=s,M=[x,y]),r[x]=c))),S=S+2?S:0,d?S:[M,S])) ``` ### Input 1) An array of array of characters describing the current board, such as: ``` [['X', '-'], ['-', 'O']] ``` 2) An integer describing the current turn: 1 = `X`, -1 = `O` ### Output An array made of: * an array describing the best move in `[x, y]` format * the outcome of the game as an integer: 1 = win, -1 = loss, 0 = tie ### Example In the following example, `X` is guaranteed to win by playing `[1, 2]`. ``` let f = (b,p,d,M,S=-2)=>(T=(p,q,r,s)=>b[p][q]==(n=b[r][s|0])&&n!='-',w=0,b.map((r,y)=>(l=r.length-1,m=15,r.map((c,x)=>(m&=8*T(l-x,x,l)+4*T(x,x,0)+2*T(x,y,0,y)+T(y,x,y))),w|=m)),w?-1:(b.map((r,y)=>r.map((c,x)=>S<1&&c=='-'&&(r[x]='O.X'[p+1],(s=-f(b,-p,1))>S&&(S=s,M=[x,y]),r[x]=c))),S=S+2?S:0,d?S:[M,S])) console.log(JSON.stringify(f( [['O','X','O'], ['-','-','-'], ['-','-','X']], 1 ))); ``` *A STRANGE GAME. THE ONLY WINNING MOVE IS NOT PLAY. HOW ABOUT A NICE GAME OF CHESS?* ]
[Question] [ I've always wanted to surround some text with `#`s, but I have trouble figuring out what I surrounded so in this challenge you'll be writing a program to do just that ## Examples Input / Outputs are separated by a newline. ``` ### #a# ### a ``` ``` # #a# # a ``` ``` ### # a # # b c # ####### a b c ``` ``` ABCDHIJ E####GK F# M #L # N#O P#### M N ``` ``` ###A### #C#B#o# #d###e# # go# ### C o d e go ``` ## Spec * `#`s are what "surround" a block of text * `#` will always be adjacent to one another (including diagonally) * `#` will always form a closed shape * There will only be one `#` shape * In the event of a concave shape, holes should be filled with spaces. * Whitespace **must** be preserved in the output [Answer] # Perl, ~~144~~ ~~138~~ ~~132~~ ~~129~~ ~~128~~ ~~127~~ ~~126~~ 124 bytes Includes +2 for `-p0` The code assumes `\0` is not a valid input character (at least inside the `#`). Run with the input on STDIN: ``` surround.pl < surround.txt ``` `surround.pl`: ``` #!/usr/bin/perl -p0 /^#[^#\0]/m&&s/^|[^#\n\0]\0/\0\0/mg,s%.%s/.(.*)/$+\0/g;/#/&&reverse"\n",/^./mg%seg until$?++<$$_++;y/\0/#/;s/^#*\n|#+$|^#//mg;y;#; ``` The code works as is, but replace the `\0` and `\n` by their literal versions for the claimed score. Notice there is a space at the end of the line. The code loops way too many times, so you may have to wait 30 seconds or so for output. ## Explanation I am going to do a floodfill with `\0` stopped by `#` from the outside in the orthogonal directions. After that I will slice off the `#` sides and replace all that is left by spaces. To avoid having to handle all directions in the floodfill I will repeatedly rotate the target area and only floodfill from right to left ``` /^#[^#\0]/m The rotation is written such that it slices off the first column. That is ok unless the first column contains a # that is followed by something that could be the inside. There is no newline inside the [] because short lines will get extended during the rotation and the character following the # will end up as a \0 and match in a later round &&s/^|[^#\n\0]\0/\0\0/mg In case the # could be an interior border I will add two columns of \0's in front. One will be a sacrifice for the rotation, the other column will end up at the end of the area after two rotations and function as seed for the floodfill. This regex also does one step of the floodfill from the back to the front. After a certain number of loops we are certain to get to a first column that must not be dropped so at some point the last column is guaranteed to consist of only \0. And we only need to fill backward since the rotations will make any direction backward at some point s%.% process column %seg I will replace each character (including \n) in the string by the next column in reversed order or an empty string if there are no more interesting columns. This is therefore a right rotation. There are less columns than characters so this loop is long enough s%.%s/.(.*)/$+\0/g Remove the next (now first) character from each row (so remove the column). Because the original area is not necessarily a rectangle add a \0 at the end of the row so we won't run out out of columns (this would cause shorter rows to have no entry in the new rotated row) This will not do anything for empty lines so they DO get squeezed out. But that is not a problem since the problem statement says there will be only one # shape so any empty lines are can be safely dropped (this would not be so if there could be multiple # shapes because that could create a new surrounded area /#/ Check if any of the remaining columns still has a #. If not all remaining columns are on the outside and can be dropped &&reverse"\n",/^./mg Collect the column and add a \n to its reverse until$?++<$$_++ Keep doing this until we get to a multiple of 65536 rotations when $? waraps back around to 0 (this is a multiple of 4 so the area is left unrotated) and an area we have seen before ($$_ >= 1) (so all slicing and flood filling is finished) $_ having been seen in a previous rotations is not a problem (though rather tricky to prove) ``` At this point e.g. ``` AB##J E####GK F# M #L # N#O P#### ``` will have been replaced by: ``` 0000000 0####00 0# M #0 # N#0 0####00 ``` Basically all columns and rows that are not directly bordering the inside have been sliced off. Any outside characters left has been replaced by \0. At the top and right there is an extra layer of \0. So all that is left is cleanup: ``` y/\0/#/ Replace any outside that is left by # s/^#*\n|#+$|^#//mg Removes the first two and last line (the only lines that can consist of purely #) Removes any trailing # Removes the first column of # y;#; \n; Replace any remaining # by space since they are needed to fill the concave parts The final \n; is not written since it is implicit in the -p loop ``` [Answer] # Javascript, 485 464 427 417 396 390 bytes ``` s='indexOf';k='lastIndexOf';h="#";t=b=>b[0].map((x,i)=>b.map(x=>x[i]));i=>{m=i.split` `;for(h of m){m[m[s](h)]=h.split``;}for(y=0;y<m.length;y++){for(z=x=0;x<m[y].length;x++){if(m[y][x]==h)break;if(m[y][s](h)<x&&m[y][k](h)>x)z++;q=t(m);if(q[y][s]h)<x&&m[y][k](h)>x)z++;if(z>2)m[y][x]=h}}for(p of m){v=p.join``.match(/\S/);e=v?p.join``:'';m[m[s](p)]=e;}m=m.join` `;return m.replace(#/g," ")} ``` Yes. I tried. And, although I am at 485 bytes, I am winning because no-one else felt like answering this question. So, hah! And also, I am well aware that I could golf this loads, I just am tired at the moment... **well now I'm at 396** Thanks to Conor for most of the golfing... :D ]
[Question] [ ## Introduction Suppose you and your friend are playing a game. Your friend thinks of some particular sequence of `n` bits, and your task is to deduce the sequence by asking them questions. However, the only type of question you're allowed to ask is "How long is the longest common subsequence of your sequence and `S`", where `S` is any sequence of bits. The fewer questions you need, the better. ## The task Your task is to write a program or function that takes as input a positive integer `n`, and a binary sequence `R` of length `n`. The sequence may be an array of integers, a string, or some other reasonable type of your choice. Your program shall output the sequence `R`. Your program is **not** allowed to access the sequence `R` directly. The **only** thing it's allowed to do to `R` is to give it as input to the function `len_lcs` along with another binary sequence `S`. The function `len_lcs(R, S)` returns the length of the longest common subsequence of `R` and `S`. This means the longest sequence of bits which occurs as a (not necessarily contiguous) subsequence in both `R` and `S`. The inputs of `len_lcs` which may be of different lengths. The program should call this function on `R` and other sequences some number of times, and then reconstruct the sequence `R` based on that information. ## Example Consider the inputs `n = 4` and `R = "1010"`. First, we might evaluate `len_lcs(R, "110")`, which gives `3`, since `"110"` is the longest common subsequence of `"1010"` and `"110"`. Then we know that `R` is obtained from `"110"` by inserting one bit at some position. Next, we might try `len_lcs(R, "0110")`, which returns `3` since the longest common subsequences are `"110"` and `"010"`, so `"0110"` is not correct. Then we try `len_lcs(R, "1010")`, which returns `4`. Now we know that `R == "1010"`, so we can return that sequence as the correct output. This required 3 calls to `len_lcs`. ## Rules and scoring In [this repository](https://github.com/iatorm/random-data), you'll find a file called `subsequence_data.txt` containing 100 random binary sequences of lengths between 75 and 124. They were generated by taking three random floats between 0 and 1, taking their average as `a`, and then flipping an `a`-biased coin `n` times. You score is the **average number of calls to `len_lcs`** on these sequences, lower score being better. Your submission should record the number of calls. There are no time limits, except that you should run your program on the file before submitting it. Your submission shall be deterministic. PRNGs are permitted, but they must use today's date, `200116` (or closest equivalent), as the random seed. You are not allowed to optimize your submission against these particular test cases. If I suspect this is happening, I will generate a new batch. This is not code golf, so you're encouraged to write readable code. Rosetta Code has a [page on the longest common subsequence](http://rosettacode.org/wiki/Longest_common_subsequence); you may use that to implement `len_lcs` in your language of choice. [Answer] # Java, ~~99.04~~ ~~98.46~~ 97.66 lcs() calls ### How it works Exaple: Our line that is to be reconstructed is `00101`. First we find out how many zeros there are, by comparing (here comparing = computing lcs with the original string) by a zeros only string `00000`. Then we go through each position, flip the `0` to a `1` and check if we now have a longer common substring. If yes, accept and go to next position, if no, flip the current `1` back to a `0` and go to next position: ``` For our example of "00101" we get following steps: input lcs prev.'best' 00000 3 0 //number of zeros ̲10000 3 3 //reject 0̲1000 3 3 //reject 00̲100 4 3 //accept 001̲10 4 4 //reject 0010̲1 5 4 //accept ``` ### Optimizations This is just a "naive" implementation, perhaps it would be possible to find a more sophisticated alogrithm checking multiple positions at once. But I am not sure if there really *is* a better one (e.g. based on the calculation of parity bits similar to the Hamming code), as you can always just evaluate the *length* of the common substring. For one given line of digits, this algorithm needs exactly `#ofDigitsUntilTheLastOccurenceOf1 + 1` checks. (Substract one if the last digits is an `1`.) EDIT: One small optimization: If we just checked the 2nd last digit and we still need to insert a `1`, we know for sure that it must be in the very last position, and can omit the corresponding check. EDIT2: I just noticed you can apply above idea to the last `k` ones. It might of course be possible to achieve a slightly lower score with the this optimization, by reordering the all lines first, because it could be, that you get more lines with ones at the very end but that would obviously be and optimization for the current test cases which is no longer funny. ### Runtime The upper limit is `O(#NumberOfBits)`. ### Full code Here the full code: ``` package jcodegolf; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; // http://codegolf.stackexchange.com/questions/69799/know-a-sequence-by-its-subsequences public class SequenceReconstructor { public static int counter = 0; public static int lcs(String a, String b) { //stolen from http://rosettacode.org/wiki/Longest_common_subsequence#Java int[][] lengths = new int[a.length()+1][b.length()+1]; // row 0 and column 0 are initialized to 0 already for (int i = 0; i < a.length(); i++) for (int j = 0; j < b.length(); j++) if (a.charAt(i) == b.charAt(j)) lengths[i+1][j+1] = lengths[i][j] + 1; else lengths[i+1][j+1] = Math.max(lengths[i+1][j], lengths[i][j+1]); // read the substring out from the matrix StringBuffer sb = new StringBuffer(); for (int x = a.length(), y = b.length(); x != 0 && y != 0; ) { if (lengths[x][y] == lengths[x-1][y]) x--; else if (lengths[x][y] == lengths[x][y-1]) y--; else { assert a.charAt(x-1) == b.charAt(y-1); sb.append(a.charAt(x-1)); x--; y--; } } counter ++; return sb.reverse().toString().length(); } public static String reconstruct(String secretLine, int lineLength){ int current_lcs = 0; int previous_lcs = 0; char [] myGuess = new char[lineLength]; for (int k=0; k<lineLength; k++){ myGuess[k] = '0'; } //find the number of zeros: int numberOfZeros = lcs(secretLine, String.valueOf(myGuess)); current_lcs = numberOfZeros; previous_lcs = numberOfZeros; if(current_lcs == lineLength){ //were done return String.valueOf(myGuess); } int numberOfOnes = lineLength - numberOfZeros; //try to greedily insert ones at the positions where they maximize the common substring length int onesCounter = 0; for(int n=0; n < lineLength && onesCounter < numberOfOnes; n++){ myGuess[n] = '1'; current_lcs = lcs(secretLine, String.valueOf(myGuess)); if(current_lcs > previous_lcs){ //accept previous_lcs = current_lcs; onesCounter ++; } else { // do not accept myGuess[n]='0'; } if(n == lineLength-(numberOfOnes-onesCounter)-1 && onesCounter < numberOfOnes){ //lets test if we have as many locations left as we have ones to insert // then we know that the rest are ones for(int k=n+1;k<lineLength;k++){ myGuess[k] = '1'; } break; } } return String.valueOf(myGuess); } public static void main(String[] args) { try { //read the file BufferedReader br; br = new BufferedReader(new FileReader("PATH/TO/YOUR/FILE/LOCATION/subsequence_data.txt")); String line; //iterate over each line while ( (line = br.readLine()) != null){ String r = reconstruct(line, line.length()); System.out.println(line); //print original line System.out.println(r); //print current line System.out.println(counter/100.0); //print current number of calls if (! line.equals(r)){ System.out.println("SOMETHING WENT HORRIBLY WRONG!!!"); System.exit(1); } } } catch(Exception e){ e.printStackTrace();; } } } ``` ]
[Question] [ > > For any integer \$r\$, there exists a > power of 2 each of whose last \$r\$ digits > are either 1 or 2. > > > Given \$r\$, find the smallest \$x\$ such that \$2^x\bmod{10^r}\$ consists of only 1 or 2. For \$r=2\$, \$x=9\$, since \$2^9=5\color{blue}{\textrm{12}}\$ For \$r=3\$, \$x=89\$, since \$2^{89}=618970019642690137449562\color{blue}{\textrm{112}}\$ Note: for \$r=4\$, \$x\$ is \$=89\$ (again) Input : \$r \leq 100\$ Output : \$x\$ Eg. > > Input : 2 > > Ouput : 9 > > > Input : 3 > > Ouput : 89 > > > The program should run in a reasonable amount of time. EDIT: The oeis sequence for this challenge is [A147884](http://oeis.org/A147884). [Answer] ## Python, 166 chars ``` k,f,g=1,4,16 i=j=2 n=input() m=10**n a=lambda c:c('')-1-i or c('1')+c('2')-c('')+1 while i<=n: while a(str(j)[-i:].count):j,k=j*g%m,k+f i,g,f=i+1,g**5%m,f*5 print k ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~78~~ ~~76~~ ~~57~~ 55 bytes ``` (x=0;While[Max@Abs[2IntegerDigits[2^++x,10,#]-3]>1];x)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE7876Zg@1@jwtbAOjwjMyc12jexwsExqTjayDOvJDU9tcglMz2zBMiN09au0DE00FGO1TWOtTOMta7QVPvvWFSUWBntpqNgaBD7/79uQVFmXgkA "Wolfram Language (Mathematica) – Try It Online") [`IntegerDigits[a,10,r]`](https://reference.wolfram.com/language/ref/IntegerDigits.html) generates a list of the `r` last decimal digits of `a`. Subtract 3/2 and check that they are all either -1/2 or +1/2. Timing check: 20 seconds on TIO for `r = 1 .. 10`. # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~102~~ ~~95~~ ~~91~~ 89 bytes ``` k/.FindInstance[Mod[n=0;Nest[#+10^n(2-Mod[#/2^n++,2])&,0,#]-2^k,5^#]==0,k,Integers][[1]]& ``` [Try it online!](https://tio.run/##FcjBCgIhEADQX1kQlsKxVaFTeOgS7KF@YBhBdt0S2SnUS19v9I5vD@0V99DSEvo2uJ6n0y3xOnNtgZeI9/eK7PTlEWtDIY32fLDqv2KynqUES8cRNAhS1mc4e0HOacgwc4vPWCohGqKxX0sJX9xgMJZ6V5@SuP0A "Wolfram Language (Mathematica) – Try It Online") This solution is much longer but much faster. By taking the path suggested in [OEIS A147884](http://oeis.org/A147884) to go via [OEIS A053312](http://oeis.org/A053312), as well as using [`FindInstance`](https://reference.wolfram.com/language/ref/FindInstance.html) magic, TIO manages to compute `r = 1 .. 12` in less than a minute. [Answer] # Ruby - 118 chars ``` k,f,g,m=1,4,16 i=j=2 m=10**(n=gets.to_i) ((k+=f;j=j*g%m)until j.to_s=~%r{[12]{#{i}}$};i+=1;f*=5;g=g**5%m)until n<i p k ``` [Answer] ## Haskell, 115 characters ``` import List main=readLn>>=print. \r->head$findIndices(all(`elem`"12").take r.(++cycle"0").reverse.show)$iterate(*2)1 ``` [Answer] # [Python 3](https://docs.python.org/3/), 63 bytes ``` f=lambda i,c=2:f(i,c+1)if{*str(2**c)[-i:]}-{*'12'}else c**(i>1) ``` [Try it online!](https://tio.run/##DYuxDsIgFAB3v4K4FJ5tIzUOktQfMQ6IoC8pjwZwaAjfXhkut9ytW/4Guuzo1xAzS1s6NMZkc7TmFxMGWtBj5vIMcBW7mxftX2/NsDfzpBxvPkmBrkDKkU8ARjwGVM86FOjk1FW7JMsMAMe7bH@IjBgSi5o@lsv@JtQakTI/lqpYqcexJV5nTr3jJITY/w "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞.Δo©‹®I.£2X:`P ``` [Try it online](https://tio.run/##ASIA3f9vc2FiaWX//@KIni7OlG/CqeKAucKuSS7CozJYOmBQ//8z) or [verify the first 8 test cases](https://tio.run/##ATMAzP9vc2FiaWX/OEVOPyIg4oaSICI/Tlb/4oieLs6Ub8KpWXPigLnCrlkuwqMyWDpgUP99LP8) (any more times out). **Explanation:** Uses the fact that \$2^x > r\$ for all possible results, to ensure we have enough digits to get the last \$r\$ digits of \$2^x\$. ``` ∞.Δ # Find the first positive integer x which is truthy (==1) for: o # Take 2 to the power the integer: 2^x © # Store it in variable `®` (without popping) ‹ # Check that it's larger than the (implicit) input: r < 2^x # (1 if truhy; 0 if falsey) ® # Push variable `®` again: 2^x I.£ # Only leave the last input amount of digits 2X: # Replace all 2s with 1s ` # Push all digits separated to the stack P # Take the product of all digits on the stack (including the earlier check) # (NOTE: Only 1 is truthy in 05AB1E) ``` [Answer] ### CSharp - 111 chars ``` int a(int r){int x=1;a:x++;foreach(var c in Math.Pow(2,x)%Math.Pow(10,r)+"")if(c!='1'&&c!='2')goto a;return x;} ``` [Answer] # [Perl 5](https://www.perl.org/) `-Mbigint -p`, 33 bytes ``` 1while($a=2**++$\)!~/[12]{$_}$/}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/9@wPCMzJ1VDJdHWSEtLW1slRlOxTj/a0Ci2WiW@VkW/tvr/f/N/@QUlmfl5xf91fU31DAwNgHRSZnpmXsl/3QIA "Perl 5 – Try It Online") [Answer] # [Julia](http://julialang.org/) ~~133~~ 122 (51) bytes Inspired by YOU's answer: ``` n->(k=1;f=4;g=big(16);i=j=2;m=10^n;while i<=n;while digits!(fill(0,i),j)⊈1:2;j,k=j*g%m,k+f;end;i,g,f=i+1,g^5%m,f*5end;k) ``` [Try it online!](https://tio.run/##Nc1BDoIwEEDRq@jCpAOVdFBcMI5HIdFA67SlMYrRIxiP6UUqLtz9vM339yhHfGbLOa0PKjCS5S05PolTuAMS9lzTyGi6RI@zxGEhe/5nL06m21JZiVEZLaA9fN4vbGvyOrAv3GrUobQ0pJ5EO21ZStSua2a3RfPjAPlylTTFVClbqXlcKWw3BgDyFw) The following is much shorter, but it crashes for r > 8, like some of the other answers: ``` f(r,x=big(1))=digits!(fill(0,r),x)⊈1:2&&f(r,2x)+1 ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/P02jSKfCNikzXcNQU9M2JTM9s6RYUSMtMydHw0CnSFOnQvNRV4ehlZGaGkilUYWmtuH/gqLMvJKcPD2NND0NQysLTc3/AA "Julia 1.0 – Try It Online") ]
[Question] [ We can write mathematical expressions using the standard math operators `(`,`)`,`+`,`*`,`/`,`-` available pretty much universally. We allow the symbols `a`, `b`, `c`, `d` and integers (e.g. `1`, `45`, etc.) but will restrict to just these four symbols. (Bonus points if you can handle more.) The goal is to take an expression as input and output a shorter expression that is mathematically equivalent to the input. Edit: implicit multiplication such as `2a` is not valid. It should be `2*a`. [To make this a bit easier, we will only ever divide by integers, and never the symbols. In other words, an expression is a polynomial in 4 variables with rational coefficients.] # Examples ``` input 1: 1+1/2 (5 characters) output 1: 3/2 (3 characters) input 2: a*(1-b)*(1+b) (13 characters) output 2: a-a*b*b (7 characters) input 3: a*b*2/7-a*b*b/7 (15 characters) output 3: a*b*(2-b)/7 (11 characters) input 4: b*c*c+2*a*c*d-2*a*c-2*b*c-c*c-2*a*d-2*c*d+4*c+2*d (49 characters) output 4: c*(b*c-2*a-2*b-c+4)+2*d*(1-a)*(1-c) (35 characters) input 5: a*c+b*c+a*d+b*d+3*a+3*b+c+d+4 (29 characters) output 5: (1+a+b)*(3+c+d)+1 (17 characters) ``` # Scoring Shortest (valid) output wins. As a result, whoever has the shortest *total* (valid) output from the 20 randomly generated expressions is the winner. I will also verify that the winning solution actually works by creating 20 more, similar expressions and testing those. There is a shortest solution in each case, so if multiple people come up with a solution that finds the shortest answer for every input, and not just the ones below, whoever got it first wins. # "Random" Inputs ``` (2*a*a*a-2*a*a*d+2*b*d*d+d*d*d-2*a*a+2*a*b-b*c-a*d+b*d+a+c)/2 (-d*d*d+2*c+d)/2 -b*c*c-2*a*c*d+2*a*c+2*b*c+2*a*d 2*a*a*c+2*a*c*d-2*c*d*d-2*b*b+2*a*c+2*b*c-2*c*d-2*d*d-2*a-b+2*c+d+1 -b*c*c-2*a*c*d+c*c+2*c*d+2*a+b (-2*a*a*b*b+a*a*a*c+b*c*c*d+2*c*d*d*d-d*d*d-2*a*c+2*b*c+2*c*c+d*d)/3 (-2*a*a+b*c-2*b*d+2*a-2*b-1)/2 (b*b*c+a*c*c-2*b*d*d-c*d*d-a*a-2*a*b-b*b-a*c+c*c+2*a*d-b*d-2*d*d)/4 (a*a+b*d-c*d-c-2*d)/2 -a*a+2*a*b+2*b*b+2*a*c-a*d-2 -b*c*c-2*a*c*d+2*a+b (a*b*b+2*a*b*c-b*c*c-a*d*d-b*b+a*c+b*c-c*c+2*a*d+a+2*b+d)/4 (-8*a*b*c-4*a*a*d+4*a*a+8*a*b+4*a*c+4*b*c+4*a*d-8*a-4*b+3)/3 (-2*a*a*a*a+c*c*c*c-a*b*c*d+2*b*b*c*d-a*c*c*d-2*c*c*c*d+a*a-2*b*b+2*a*c+a*d)/3 b*c*c+2*a*c*d-2*a*c-2*b*c-c*c-2*a*d-2*c*d+4*c+2*d (-2*a*b*b*b+c*c*c*c-2*a*a)/3 ``` [Answer] # [Python 3.10](https://docs.python.org/3/) ``` import copy, collections import math, itertools REDUCE_COUNT = itertools.count(1) def parse_expr(s, paren=False): expr_vars, expr_val, expr_demoninator, expr_groups = [], None, 1, [] expr_container, flag = [], True while s and (not paren or s[0] != ')'): if s[0].isdigit(): expr_val = (expr_val or 1) * int(s[0]) elif s[0].isalpha(): expr_vars.append(s[0]) elif s[0] == '*': pass elif s[0] == '/': expr_demoninator *= int(s[1]) s, flag = s[2:], False elif s[0] in {'+', '-'}: if expr_val is not None or expr_vars or expr_groups: expr_container.append({'type':'expr', 'coefficient':expr_val or 1, 'denominator':expr_demoninator, 'vars':sorted(expr_vars, key=lambda x:(isinstance(x, (dict, list)), str(x))), 'groups':sorted(expr_groups, key=str)}) expr_vars, expr_val, expr_demoninator, expr_groups = [], 1 if s[0] == '+' else -1, 1, [] elif s[0] == '(': container, s = parse_expr(s[1:], True) expr_groups.append(container) elif s[0] == ' ': pass if flag: s = s[1:] flag = True if expr_val is not None or expr_vars or expr_groups: expr_container.append({'type':'expr', 'coefficient':expr_val or 1, 'denominator':expr_demoninator, 'vars':sorted(expr_vars, key=lambda x:(isinstance(x, (dict, list)), str(x))), 'groups':sorted(expr_groups, key=str)}) return {'type':'container', 'exprs':expr_container}, s def expand_expr(expr): def update_expr_vars(expr, expr_vars): expr['coefficient'], expr['vars'], expr['denominator'] = expr['coefficient']*expr_vars['coefficient'], sorted(expr['vars']+expr_vars['vars']), expr['denominator']*expr_vars['denominator'] return expr def to_expr_var(expr): return {'coefficient':expr['coefficient'], 'vars':expr['vars'], 'denominator':expr['denominator']} def distribute(expr, expr_vars={'coefficient':1, 'vars':[], 'denominator':1}): if expr['type'] == 'container': for i in expr['exprs']: yield from distribute(i, expr_vars) else: new_expr = update_expr_vars(eval(str(expr)), expr_vars) if not new_expr['groups']: yield new_expr else: all_vars = [to_expr_var(new_expr)] for i in new_expr['groups']: all_vars = [x for y in all_vars for x in distribute(i, y)] yield from all_vars return {'type':'container', 'exprs':[*distribute(expr)]} def reduce_terms(expr): lcm, d = math.lcm(*[i['denominator'] for i in expr['exprs']]), collections.defaultdict(int) for i in expr['exprs']: d[str([i['vars'], i['groups'], i.get('reduce', 0)])] += i['coefficient']*(lcm/i['denominator']) return {'type':'container', 'exprs':[{'type':'expr', 'coefficient':int(b), 'denominator':lcm, 'vars':eval(a)[0], 'groups':eval(a)[1]} for a, b in d.items() if b]} def render_expr(expr, d=0): if expr['type'] == 'container': r_s = '' for i in expr['exprs']: if (v:=render_expr(i, 1)): if v[0] == '-' and r_s and r_s[-1] == '+': r_s = r_s[:-1]+v+'+' else: r_s += v + '+' if r_s and r_s[-1] == '+': r_s = r_s[:-1] return '' if not r_s else '('*d + r_s + ')'*d if not any([expr['vars'], expr['groups']]): return str(expr['coefficient'])+('/'+str(expr['denominator']) if expr['denominator'] != 1 else '') result = ('' if abs(expr['coefficient']) == 1 else str(expr['coefficient'])) + ('-' if expr['coefficient'] == -1 else '') if expr['vars']: result += ('*'*(bool(result) and result[-1] != '-'))+'*'.join(expr['vars']) if expr['groups']: result += ('*'*(bool(result) and result[-1] != '-'))+'*'.join(render_expr(i, 1) for i in expr['groups']) if expr['denominator'] != 1: result += '/'+str(expr['denominator']) return result def factor_combos(all_combos, c = []): if c: yield c if all_combos: for i in all_combos[0]: yield from factor_combos(all_combos[1:], c+[i]) yield from factor_combos(all_combos[1:]) def expr_factors(expr): assert expr['type'] == 'expr' yield from factor_combos([ [{'type':'coefficient', 'v':i} for i in range(2, abs(expr['coefficient'])+1) if not expr['coefficient']%i], [{'type':'vars', 'v':[*j]} for x in range(len(expr['vars'])+1) for j in itertools.combinations(expr['vars'], x)], [{'type':'groups', 'v':[*j]} for x in range(len(expr['groups'])+1) for j in itertools.combinations(expr['groups'], x)] ]) def factor_match(expr, factor): new_expr = eval(str(expr)) if 'coefficient' in factor: if expr['coefficient']%factor['coefficient']: return False new_expr['coefficient'] = int(new_expr['coefficient']/factor['coefficient']) if 'vars' in factor: c1, c2 = collections.Counter(expr['vars']), collections.Counter(factor['vars']) for a, b in c2.items(): if a not in c1 or b > c1[a]: return False c1[a] -= b new_expr['vars'] = sorted([x for a, b in c1.items() for x in ([a]*b)]) if 'groups' in factor: c1, c2 = collections.Counter(map(str, expr['groups'])), collections.Counter(map(str, factor['groups'])) for a, b in c2.items(): if a not in c1 or b > c1[a]: return False c1[a] -= b new_expr['groups'] = sorted([eval(x) for a, b in c1.items() for x in ([a]*b)], key=str) return new_expr def group_common_factor(exprs, factor): factor = {i['type']:i['v'] for i in factor} matched, non_matched = [], [] for expr in exprs: if (m:=factor_match(expr, factor)): matched.append(m) else: non_matched.append(expr) if len(matched) < 2: return [], non_matched old_denominator = matched[0]['denominator'] for i in matched: i['denominator'] = 1 new_expr_var = {'type':'expr', 'coefficient':factor.get('coefficient', 1), 'denominator':old_denominator, 'vars':sorted(factor.get('vars', []), key=str), 'groups': sorted(factor.get('groups', [])+[{'type':'container', 'exprs':matched}], key=str)} return new_expr_var, non_matched def factor_ints(d, c = []): def gen_num(n, denom): return {'type':'expr', 'coefficient':n, 'denominator':denom, 'vars':[], 'groups':[], 'reduce':next(REDUCE_COUNT)} if not d: yield c else: yield from factor_ints(d[1:], c+[d[0]]) if not any([d[0]['vars'], d[0]['groups']]): for i in range(1, d[0]['coefficient']//2): yield from factor_ints(d[1:], c+[gen_num(i, d[0]['denominator']), gen_num(d[0]['coefficient'] - i, d[0]['denominator'])]) def base_factor_combos(d, c = []): if len(c) > 1 and len(c) < len(d): yield sorted(c) for i in d: if i not in c: yield from base_factor_combos(d, c+[i]) def full_base_factors(d): return list(map(eval, set(map(str, base_factor_combos(d))))) def produce_factor_combinations(exprs, c = [], f = 0): yield {'type':'container', 'exprs':sorted(c+exprs, key=str)} if exprs: seen_factors = [] for i in exprs: for _factor_group in expr_factors(i): if (factor_group:=[*filter(lambda x:x['v'], _factor_group)]) and factor_group not in seen_factors: seen_factors.append(factor_group) matched, non_matched = group_common_factor(exprs, factor_group) if matched: yield from produce_factor_combinations(non_matched, c = c+[matched], f=f) if not f: for base_factor in full_base_factors([*range(len(non_matched))]): if len(base_factor) > 2: yield from produce_factor_combinations([a for j, a in enumerate(non_matched) if j not in base_factor], c = c+[matched]+[{'type':'expr', 'coefficient':1, 'denominator':matched['denominator'], 'vars':[], 'groups': [{'type':'container', 'exprs':[non_matched[j] for j in base_factor]}], 'base_factor':1}], f = 1) def run_transformation(expr, len_cache): queue, seen = collections.deque([(0, expr)]), [] while queue: level, expr = queue.popleft() reduced = reduce_terms(expr) s = render_expr(reduced) len_cache[len(s)]= s if s not in seen and (not len_cache or (len(s) < min(len_cache) or level < 2)): seen.append(s) for i in produce_factor_combinations(reduced['exprs']): queue.append((level+1, i)) def main(expr): full_len_cache = {} parse_result, _ = parse_expr(expr) expanded = expand_expr(parse_result) for i, _expr in enumerate(factor_ints(expanded['exprs'])): len_cache = {} run_transformation({'type': 'container', 'exprs':_expr}, len_cache) full_len_cache.update(len_cache) return full_len_cache[min(full_len_cache)] if __name__ == '__main__': print(main('1+1/2')) print(main('a*(1-b)*(1+b)')) print(main('a*b*2/7-a*b*b/7')) print(main('a*c+b*c+a*d+b*d+3*a+3*b+c+d+4')) print(main('b*c*c+2*a*c*d-2*a*c-2*b*c-c*c-2*a*d-2*c*d+4*c+2*d')) ``` This solution takes in an expression, parses it, and then repeats a process of grouping on possible factors and then combining like terms. While the code is somewhat verbose, the overall idea is very simple. It is somewhat slow on large inputs, and could be optimized further. ]
[Question] [ Assuming StackExchange doesn't decide to restore my account after deleting it due to age restrictions (even though I'm 14 already and almost 15 ಠ\_ಠ), a lot of people on this site just lost reputation from my upvotes being deleted. This happened at around 5:30 PM on June 20th, 2017, UTC. So, your challenge is to show how much PPCG reputation was lost from my deletion, given the user's PPCG ID. # Challenge ### Input A single integer will represent the user's UUID on PPCG. ### Output A single integer will represent how much reputation the user lost due to this. If the user lost reputation multiple times within the same hour all due to user removals, then it is acceptable if your program returns the number for the wrong user. In the event that the user *gained* reputation from my account being deleted, your program should return a negative number for losing negative reputation. And finally, should I have had no voting on that user (in the past 60 days), your program should return 0. # Test Cases ``` UUID -> REP-LOST (Username) # Don't output the username 40695 -> 22 (Downgoat) 12012 -> 148 (Dennis) 8578 -> 61 (Martin Ender) ``` You can check by going to `https://codegolf.stackexchange.com/users/<UUID>/?tab=reputation&sort=post` and looking for `User was removed (learn more)` [Original idea thanks to Uriel](http://chat.stackexchange.com/transcript/message/38248254#38248254) with [approval](http://chat.stackexchange.com/transcript/message/38248266#38248266) # Note Thanks to JungHwan Min for this link! `https://codegolf.stackexchange.com/ajax/users/<UUID>/rep/day/1497916800` You can fetch raw data of a user's reputation change from this link above. [Answer] ## JavaScript ES6, 132 bytes ``` n=>fetch(`/ajax/users/${n}/rep/day/1497916800`).then(v=>v.text()).then(v=>alert((v.match(/rep-down">-(\d+)[^u]+user w/)||[0,0])[1])) ``` Tested on Safari 10. This uses the new `fetch` API and alerts the output. This is a function so pass the user id as the argument. This will output `0` for no rep changes. Must be run on PPCG due to CORS (Cross-origin resource sharing), browsers do not allow JavaScript to perform a web request outside of the current domain. ]
[Question] [ In the ~~location-based AR mobile game~~ way of life [Ingress](https://www.ingress.com/) the player can hack things called portals in order to get items. (If you are interested in Ingress, you can ping me in chat for more info. Trust me, it's better than Pokémon. If you end up downloading it, remember to choose the Resistance.) A way to increase hack output significantly is the *glyph hacking* minigame, in which the player has to draw glyphs on a hexagonal grid. ![the glyph grid](https://i.stack.imgur.com/XUFhZ.png) In total, there are about 115 glyphs with about 130 names that are actually used in the game. ## Glyphs For the purposes of this challenge we will number each point of the grid like so: ![the glyph grid, numbered](https://i.stack.imgur.com/luOax.png) Here is the list of all the glyphs for the purposes of this challenge. The list is a JSON object, containing each glyph as a list of edges. ``` { "ABANDON": [[1, 6], [3, 4], [4, 8], [6, 10], [8, 10]], "ACCEPT": [[3, 7], [3, 8], [7, 8]], "ADVANCE": [[0, 9], [4, 9]], "AFTER": [[1, 2], [1, 6], [2, 7], [6, 10], [7, 10]], "AGAIN": [[4, 9], [6, 7], [6, 10], [8, 9], [8, 10]], "ALL": [[0, 1], [0, 5], [1, 2], [2, 3], [3, 4], [4, 5]], "ANSWER": [[6, 7], [6, 9], [7, 10]], "ATTACK": [[0, 6], [0, 9], [2, 6], [4, 9]], "AVOID": [[0, 5], [0, 6], [1, 6], [1, 7]], "BALANCE": [[0, 10], [2, 3], [2, 7], [3, 4], [4, 8], [7, 10], [8, 10]], "BARRIER": [[0, 10], [2, 7], [7, 10]], "BEFORE": [[4, 5], [4, 8], [5, 9], [8, 10], [9, 10]], "BEGIN": [[0, 8], [3, 7], [3, 8]], "BODY": [[6, 9], [6, 10], [9, 10]], "BREATHE": [[1, 6], [5, 9], [6, 10], [9, 10]], "CAPTURE": [[1, 7], [3, 4], [4, 8], [7, 10], [8, 10]], "CHANGE": [[3, 7], [3, 10], [8, 10]], "CHAOS": [[0, 1], [0, 5], [1, 6], [3, 8], [4, 5], [6, 10], [8, 10]], "CIVILIZATION": [[1, 6], [5, 9], [6, 7], [7, 8], [8, 9]], "CLEAR": [[0, 10], [3, 10]], "CLEAR ALL": [[0, 1], [0, 5], [0, 10], [1, 2], [2, 3], [3, 4], [3, 10], [4, 5]], "COMPLEX": [[6, 9], [8, 10], [9, 10]], "CONFLICT": [[2, 6], [4, 9], [6, 7], [7, 8], [8, 9]], "CONTEMPLATE": [[0, 1], [1, 2], [2, 3], [3, 8], [6, 10], [8, 9], [9, 10]], "COURAGE": [[4, 9], [7, 8], [8, 9]], "CREATE": [[1, 6], [4, 8], [6, 10], [8, 10]], "DANGER": [[0, 9], [3, 10], [9, 10]], "DATA": [[0, 6], [3, 8], [6, 10], [8, 10]], "DEFEND": [[1, 7], [3, 7], [3, 8], [5, 8]], "DESTINY": [[3, 8], [6, 7], [6, 10], [7, 8], [9, 10]], "DESTROY": [[2, 7], [5, 9], [7, 10], [9, 10]], "DETERIORATE": [[4, 8], [8, 10], [9, 10]], "DIE": [[2, 7], [4, 8], [7, 10], [8, 10]], "DIFFICULT": [[1, 6], [6, 7], [7, 10], [8, 10]], "DISCOVER": [[1, 2], [2, 3], [3, 4]], "DISTANCE": [[0, 5], [4, 5]], "EASY": [[3, 8], [6, 10], [8, 10]], "END": [[0, 1], [0, 10], [1, 7], [3, 7], [3, 10]], "ENLIGHTENED": [[0, 1], [0, 9], [1, 2], [2, 3], [6, 9], [6, 10], [9, 10]], "ENLIGHTENMENT": [[0, 1], [0, 9], [1, 2], [2, 3], [6, 9], [6, 10], [9, 10]], "EQUAL": [[6, 7], [6, 9], [8, 9]], "ESCAPE": [[0, 1], [1, 6], [6, 9], [8, 9]], "EVOLUTION": [[0, 10], [8, 9], [9, 10]], "FAILURE": [[0, 10], [6, 7], [6, 10]], "FEAR": [[1, 7], [6, 7], [6, 9]], "FOLLOW": [[0, 6], [1, 2], [1, 6]], "FORGET": [[4, 8]], "FUTURE": [[1, 6], [2, 7], [6, 7]], "GAIN": [[5, 8]], "GROW": [[4, 9], [8, 9]], "HARM": [[0, 6], [0, 9], [2, 7], [6, 10], [7, 10], [9, 10]], "HARMONY": [[0, 6], [0, 9], [3, 7], [3, 8], [6, 10], [7, 10], [8, 10], [9, 10]], "HAVE": [[3, 8], [7, 10], [8, 10]], "HELP": [[5, 9], [7, 8], [8, 10], [9, 10]], "HIDE": [[1, 6], [1, 7], [6, 9], [7, 8]], "HUMAN": [[3, 7], [3, 8], [6, 7], [6, 9], [8, 9]], "IDEA": [[1, 2], [1, 6], [2, 7], [4, 5], [4, 8], [5, 9], [7, 10], [9, 10]], "IGNORE": [[2, 7]], "IMPERFECT": [[6, 8], [6, 10], [8, 9], [8, 10], [9, 10]], "IMPROVE": [[1, 6], [6, 10], [7, 10]], "IMPURE": [[3, 10], [8, 9], [8, 10], [9, 10]], "INSIDE": [[6, 7], [6, 9]], "INTELLIGENCE": [[1, 6], [4, 8], [6, 10], [8, 9], [9, 10]], "INTERRUPT": [[0, 10], [3, 10], [4, 5], [4, 8], [5, 9], [8, 10], [9, 10]], "JOURNEY": [[1, 6], [2, 3], [3, 4], [4, 5], [5, 9], [6, 10], [9, 10]], "KNOWLEDGE": [[3, 6], [3, 9], [6, 10], [9, 10]], "LEAD": [[0, 5], [3, 8], [4, 5], [4, 8]], "LEGACY": [[0, 1], [0, 5], [1, 6], [2, 7], [4, 8], [5, 9], [6, 7], [8, 9]], "LESS": [[6, 10], [9, 10]], "LIBERATE": [[0, 1], [1, 6], [4, 9], [6, 10], [9, 10]], "LIE": [[6, 7], [6, 10], [7, 10], [8, 9], [9, 10]], "LOSE": [[1, 7]], "MESSAGE": [[1, 7], [4, 9], [7, 10], [9, 10]], "MIND": [[3, 8], [3, 10], [8, 9], [9, 10]], "MORE": [[7, 10], [8, 10]], "MYSTERY": [[0, 6], [0, 9], [5, 9], [6, 9], [8, 9]], "N'ZEER": [[0, 6], [0, 9], [0, 10], [3, 10], [6, 10], [9, 10]], "NATURE": [[2, 7], [4, 8], [6, 7], [6, 9], [8, 9]], "NEW": [[2, 7], [6, 7]], "NO": [[6, 7], [6, 9]], "NOT": [[6, 7], [6, 9]], "NOURISH": [[3, 4], [3, 10], [4, 8], [8, 10]], "NOW": [[6, 7], [7, 8], [8, 9]], "OLD": [[5, 9], [8, 9]], "OPEN": [[3, 7], [3, 8], [7, 8]], "OPEN ALL": [[0, 1], [0, 5], [1, 2], [2, 3], [3, 4], [3, 7], [3, 8], [4, 5], [7, 8]], "OUTSIDE": [[0, 5], [4, 5]], "PAST": [[4, 8], [5, 9], [8, 9]], "PATH": [[0, 10], [4, 8], [8, 10]], "PEACE": [[0, 6], [0, 9], [3, 7], [3, 8], [6, 10], [7, 10], [8, 10], [9, 10]], "PERFECTION": [[0, 10], [2, 3], [2, 7], [3, 4], [4, 8], [7, 10], [8, 10]], "PERSPECTIVE": [[0, 6], [0, 9], [2, 7], [4, 8], [6, 10], [7, 10], [8, 10], [9, 10]], "PORTAL": [[1, 2], [1, 6], [2, 7], [4, 5], [4, 8], [5, 9], [6, 9], [7, 8]], "POTENTIAL": [[0, 10], [1, 2], [2, 7], [7, 10]], "PRESENT": [[6, 7], [7, 8], [8, 9]], "PURE": [[0, 10], [6, 7], [6, 10], [7, 10]], "PURSUE": [[0, 6], [0, 9], [5, 9]], "QUESTION": [[0, 6], [6, 9], [8, 9]], "REACT": [[2, 7], [6, 9], [7, 10], [9, 10]], "REBEL": [[1, 2], [1, 6], [5, 8], [6, 10], [8, 10]], "RECHARGE": [[0, 5], [0, 10], [5, 9], [9, 10]], "REPAIR": [[0, 5], [0, 10], [5, 9], [9, 10]], "REPEAT": [[4, 9], [6, 7], [6, 10], [8, 9], [8, 10]], "RESISTANCE": [[0, 9], [0, 10], [3, 8], [3, 10], [6, 9]], "RESTRAINT": [[2, 3], [2, 7], [5, 9], [7, 10], [9, 10]], "RETREAT": [[0, 6], [2, 6]], "SAFETY": [[2, 6], [4, 9], [6, 9]], "SAVE": [[1, 7], [7, 10], [8, 10]], "SEARCH": [[6, 9], [6, 10], [7, 8], [8, 9]], "SEE": [[0, 9]], "SEPARATE": [[2, 7], [5, 9], [6, 7], [6, 10], [8, 9], [8, 10]], "SHAPER": [[0, 6], [0, 9], [2, 7], [4, 8], [6, 7], [8, 9]], "SIMPLE": [[7, 8]], "SOUL": [[3, 7], [3, 10], [6, 7], [6, 10]], "STABILITY": [[2, 7], [4, 8], [7, 8]], "STAY": [[2, 7], [4, 8], [7, 8]], "STRONG": [[6, 7], [6, 9], [7, 8], [8, 9]], "STRUGGLE": [[0, 9], [0, 10], [3, 8], [3, 10], [6, 9]], "SUCCESS": [[0, 10], [8, 9], [9, 10]], "TECHNOLOGY": [[1, 6], [2, 7], [6, 10], [7, 10], [8, 9], [8, 10], [9, 10]], "THOUGHT": [[1, 2], [1, 6], [2, 7], [4, 5], [4, 8], [5, 9], [7, 10], [9, 10]], "TOGETHER": [[4, 8], [6, 9], [6, 10], [8, 10], [9, 10]], "TRUTH": [[6, 7], [6, 10], [7, 10], [8, 9], [8, 10], [9, 10]], "UNBOUNDED": [[0, 1], [0, 5], [1, 7], [2, 3], [3, 4], [4, 5], [6, 9], [6, 10], [7, 8], [8, 9]], "US": [[3, 6], [6, 9]], "USE": [[1, 7], [7, 10]], "WANT": [[3, 7], [3, 8], [4, 8]], "WAR": [[0, 6], [0, 9], [2, 6], [4, 9]], "WEAK": [[5, 9], [6, 7], [6, 9]], "XM": [[6, 7], [6, 9], [7, 10], [8, 9], [8, 10]], "YOU": [[0, 7], [0, 8], [7, 8]], "YOUR": [[0, 7], [0, 8], [7, 8]] } ``` Some glyphs have multiple names (e.g. `NO, NOT, INSIDE`); you must support them all. **Disclaimer:** I couldn't find a good list of all of the glyphs, so I combined multiple sources and finally ended up drawing all of them in a hacked-together JS application to get the list of them. I may be missing some and there may be a couple of aliases not used in the game; I hope I didn't misdraw some of the glyphs, though. **Edit the next morning when it's not 4am:** I already noticed VICTORY is missing. Oh well, it's left for the best golfer then. ## Challenge Your task is to create a program or function that takes in a name of a glyph, and outputs the glyph as an image. The image must contain the grid points and the lines connecting the points in question. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. Standard rules apply. ### I/O You will take as input, in a format of your choice, a name of a glyph exactly as found in the keys of the above JSON object. Any other input is undefined behavior. You will output an image in any common format with the glyph rendered to the grid. ### Grid proportions These proportions must be accurate to five pixels (to allow for rounding etc.) * The outer points (0-5) must form a regular hexagon. * The center point (10) must be in the center of the hexagon. * The intermediate points (6-9) must be halfway between the center point and the corresponding outer points. * The grid must be oriented like the original. * The height of the outer hexagon must be at least 100 pixels. ### Other rules * The background **must** be either transparent or filled with a solid color. * The lines and points **must** be clearly distinct from the background and each other; they cannot be of the same solid color. + For example, solid blue lines and solid pink points is fine. + Solid black lines and white points with black borders is fine. + Red and white striped lines and footballs as points is fine. + Solid green lines and solid green points is **not** fine. * The radius of the points **must** be larger than the width of the lines. * You **may** draw the lines in front of or behind the points. * You **may** include any amount of padding (in the background color) in the image. * You **may** combine consecutive lines into one line, since it doesn't affect the outcome. ## Examples The colors and object widths in these images are just examples that somewhat resemble the appearance of the game. ### UNBOUNDED ![unbounded glyph](https://i.stack.imgur.com/dr8In.png) ### PEACE ![peace glyph](https://i.stack.imgur.com/16rTU.png) ### RESISTANCE ![resistance glyph](https://i.stack.imgur.com/QQfWl.png) [Answer] # Mathematica, 228 + 184 + 365 + 13 = 790 bytes ``` Graphics@{v=255#+##&~Fold~BinaryReadList@#~IntegerDigits~#2&;p=#~Partition~2&;c=p["c"~v~25-12][[#+1]]&;Array[Disk@*c,11,0],Red,Line[c/@<|Thread["a"~v~2293->First/@p@SplitBy["b"~v~12,#>10&]]|>@Mod[1##&@@ToCharacterCode@#,2293]]}& ``` The above 228-byte command defines an unnamed function that takes as input one of the glyph names above, and returns an image. For example, here is the output for `"UNBOUNDED"`: [![UNBOUNDED](https://i.stack.imgur.com/q819J.png)](https://i.stack.imgur.com/q819J.png) The command reads three binary files—`"a"`, `"b"`, and `"c"`—which have 184, 365, and 13 bytes, respectively. An easier-to-read version: ``` 1 Graphics@{ 2 v = 255#+##&~Fold~BinaryReadList@#~IntegerDigits~#2 &; 3 p = #~Partition~2 &; 4 c = p["c"~v~25-12][[#+1]] &; 5 Array[Disk@*c, 11, 0], Red, 6 Line[c /@ 7 <| Thread[ "a"~v~2293 -> First/@p@SplitBy["b"~v~12, #>10&] ] |> 8 @ Mod[1##& @@ ToCharacterCode@#, 2293]] 9 } & ``` Line 2 defines a handmade uncompression function: it reads in a stream of bytes from the file `#`, converts it into a base-256 integer, and then expands that integer into its list of digits in base `#2`. Lines 3 and 4 define a function (using the third binary file) that converts an integer from 0 to 10 into the coordinates of the corresponding grid point; all these coordinates were chosen to be integers between –12 and 12, which makes compression convenient (though not so convenient that I saw it for my initial submission). Line 5 draws the grid points (in default color black), then switches to the color red for the lines. Line 7 creates an association (using the first two binary files) that converts certain input integers between 0 and 2292 into a list of grid-point integers such as `{2, 3, 4, 5, 0, 1, 7, 8, 9, 6, 10}`, which represents a path joining point 2 to 3 to 4 to ... to 10. (This is an "Eulerian path", one that visits each edge exactly once; all the glyphs in the table have an Eulerian path, so this representation is shorter than listing the set of edges explicitly.) The command after the `->` on line 7 creates this list of Eulerian paths, by reading in a base-12 integer using `v` and then splitting it at every occurrence of the digit 11. Finally, line 8 hashes the input string by converting all its letters to their ASCII codes and taking their product modulo 2293 (the smallest modulus for which the answers are all distinct). That integer is fed into the association in the line above, resulting in the appropriate Eulerian path, and line 6 draws the resulting path over the grid points. Hex dumps of files "a", "b", and "c", in that order: ``` 09d5f27cd2246e0cb06aa243b442d761ac3a5604439f1767a202c4d3fc4fc1b24ce59acfc65a05235cc46354af8820d6733001e1f25ea01479cee027d62e8b1be10891c693ed5887942ca461c461d458a7676bfcd866a70263ad1833b3e836895ce121153c451ad327086e2bd30d6bad7097a9e71c2fc67c2c57716e5ada6907d99f42702dfb8b88c6d26799aa01f42fb89394e00b0752825f2740903276e20ec405473f309cc978aea187da24749d0a44319cd7322dd542 02d9ebf5fc94183ce50f0fc84e88a27bd21a3b3665d54949608c75c86c4507eed3072e02657822bfb83dbca8a708e07d1382c2b6c3c8fcddc88fa7244281a918b3a8aa823048d4a7e070a336c1e5ab83ec4950fc1960f34c6b89c541c9401607882418cac7f79f4edb164b775ecbb97947470016cadea4d06f93a958713b8c23d11be3c9ce8a2824a458d151ac3cafc6d7bb1557e55868434bd5c0da4bd71e66a3f7711018ae5e7f2941a949a85b6e65aebcc2fe43a89cb0479fa9474fe5102cfbf7da8a455f46ac5409dfdc79970ed8dbfc6b84df78c9c19df4d16bda298dca445ad510bf32e14ca5c91ce58e7521492f6e79e05624ab4a4c02c66c22ef670a06d5c5a3dfdf8ccc8c40c353f3aecf17bbb5cb911baefa3ce80e41551376838c166153a1038d83e171077a3f260ccd70358917eeceb5722b58ad6900a40b5b1512b292fb7a7e0d2cbe2bac2a48a4e343e8f2a338808ec9957c64778aba412bec47bcabb2a2789f01c2d5fdd993 254c40dac61bb215386b7361a8 ``` ]
[Question] [ These are ASCII dandelions: ``` \|/ \ / | /|\ | \|/ | | | | _\|/_ | | | /|\ ``` ASCII dandelions have three parameters: Length of the stem (positive number between 1 and 256, number of seeds (positive number between 0 and 7), and orientation (^ or v). The above dandelions have for length, seeds and orientation, (3,5,^), (3,2,^), (2,3,^) and (3,7,v) respectively. Seeds are filled in in the following order (flipped upside down for head-down dandelions), illustrated on a dandelion with length 2: ``` seeds: 0 1 2 3 4 5 6 7 | \ / \|/ \ / \|/ _\ /_ _\|/_ | | | | /|\ /|\ /|\ /|\ | | | | | | | | ``` ## The Challenge: Write a program/function which when given an ASCII dandelion as input, returns its length, seed count, and orientation formatted similarly to the above examples and when given parameters in that format returns an ASCII dandelion with those parameters. You can ignore the parenthesis and assume the input/output will be a number, a comma, a number, a comma, and either `^` or `v`. You may substitute other characters for `^`/`v` so long as they can still be easily interpreted as 'up'/'down' (for example, `u`/`d`). You need not distinguish between dandelions that look the same, such as (2,1,^) and (3,0,^) or (2,1,^) and (2,1,v). Given the ASCII art, either set of parameters would be an acceptable output, and both sets of parameters can give the same ASCII art. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. --- An example program in C# (not even slightly golfed): ``` string Dandelion(string s) { if (s.Contains(',')) { //got parameters as input string[] p = s.Split(','); //depth and width (number of seeds) int d = int.Parse(p[0]); int w = int.Parse(p[1]); //draw stem string art = " |"; while (d > 2) { d--; art += "\n |"; } //draw head string uhead = (w % 2 == 1 ? "|" : " "); string dhead = uhead; if (w > 1) { uhead = "\\" + uhead + "/"; dhead = "/" + dhead + "\\"; if (w > 5) { uhead = "_" + uhead + "_\n /|\\"; dhead = "_\\|/_\n " + dhead; } else if (w > 3) { uhead = " " + uhead + " \n /|\\"; dhead = " \\|/ \n " + dhead; } else { uhead = " " + uhead + " \n |"; dhead = " |\n " + dhead; } } else { uhead = " " + uhead + "\n |"; dhead = " |\n " + dhead; } //add head to body if (p[2] == "^") { return uhead + "\n" + art; } return art + "\n" + dhead; } else { //ASCII input string[] p = s.Split('\n'); int l = p.Length - 1; int offset = 0; //find first non-' ' character in art while (p[0][offset] == ' ') { offset++; } int w = 0; if (p[0][offset] == '|') { //if '|', either head-down or no head. if (offset == 0 || p[l][offset - 1] == ' ') { //if no space for a head to the left or no head at the bottom, no head. return l.ToString() + ",1,^"; } //head must have at least size 2, or else indistinguishable from no head case w = 6; if (p[l][offset] == '|') { //odd sized head w = 7; } if (offset == 1 || p[l - 1][offset - 2] == ' ') { //not size 6 or 7 w -= 2; if (p[l - 1][offset - 1] == ' ') { //not size 4 or 5 w -= 2; } } return l.ToString() + "," + w.ToString() + ",v"; } else if (p[0][offset] == '\\') { //head at least size 2 and not 6/7, or indistinguishable from no head. w = 4; if (p[0][offset + 1] == '|') { w = 5; } if (p[1][offset] == ' ') { w -= 2; } } else { w = 6; if (p[0][offset + 2] == '|') { w = 7; } } return l.ToString() + "," + w.ToString() + ",^"; } } ``` [Answer] # [Bean](https://github.com/patrickroberts/bean), 321 bytes Accepts input as single string in stdin without trailing newline. Parameters will be taken in the same manner, but formatted as ``` length (1-256) orientation (u or d) seeds (0-7) ``` The output parameters of the program when input is a dandelion will be in the same format as above. Hexdump: ``` 00000000 26 52 ca c1 20 5d d3 d0 80 d5 cd a0 5e 80 4c cc &RÊÁ ]ÓÐ.ÕÍ ^.LÌ 00000010 a0 45 86 25 3e 88 4d a0 6b 80 4c a0 5e 80 23 60  E.%>.M k.L ^.#` 00000020 cd a0 63 80 43 cd a0 5f 80 50 84 a3 81 00 20 5e Í c.CÍ _.P.£.. ^ 00000030 d0 84 a3 81 01 4d a0 60 80 4a c1 4c a0 45 86 25 Ð.£..M `.JÁL E.% 00000040 3a d0 84 a3 81 02 4c a0 45 92 25 3a d0 84 a3 81 :Ð.£..L E.%:Ð.£. 00000050 03 20 60 a0 5f a3 81 04 cd a0 61 80 50 84 a3 81 . ` _£..Í a.P.£. 00000060 05 20 5e cf 52 cc a0 45 86 25 3c a3 81 06 23 81 . ^ÏRÌ E.%<£..#. 00000070 07 a0 61 cf 53 d0 80 a3 81 08 20 80 b5 4c a0 43 . aÏSÐ.£.. .µL C 00000080 8c 25 3a 00 52 a0 6b d3 50 80 a0 63 20 80 7e 20 .%:.R kÓP. c .~ 00000090 63 20 80 7b 23 00 53 d0 80 c3 cc d0 80 a0 78 20 c .{#.SÐ.ÃÌÐ. x 000000a0 80 01 8c 25 3a d2 ce cc a0 5d 80 23 81 09 80 4c ...%:ÒÎÌ ].#...L 000000b0 d0 84 a0 5e 25 3b 81 23 81 0a ce d3 50 80 a0 78 Ð. ^%;.#..ÎÓP. x 000000c0 20 80 7e 81 23 60 23 71 cc d2 cc d0 84 d0 84 a0 .~.#`#qÌÒÌÐ.Ð.  000000d0 78 25 3a 25 3a 81 23 81 0b cc a5 3d 8b 4c cc d0 x%:%:.#..Ì¥=.LÌÐ 000000e0 84 d0 84 a0 78 25 39 25 39 81 50 84 d0 84 a0 78 .Ð. x%9%9.P.Ð. x 000000f0 25 3a 25 39 8d 25 3b 4c cc d0 84 d0 84 a0 78 25 %:%9.%;LÌÐ.Ð. x% 00000100 39 25 3c 81 23 81 0b 8d 25 3b 8b 4c d0 84 d0 84 9%<.#...%;.LÐ.Ð. 00000110 a0 78 25 39 25 3b 81 23 81 0b 00 20 80 7b 23 81  x%9%;.#... .{#. 00000120 04 a0 df 20 a0 5c a0 7c a0 2f 0a a0 a0 5f af fc . ß  \ | /.  _¯ü 00000130 5c a0 fc 20 8a a0 a0 fc a0 20 a0 a0 fc a0 20 7c \ ü .  ü    ü  | 00000140 20 00000141 ``` Equivalent JavaScript: ``` +a? // if input is parameters ( b=(C>5)<<(o=b=="d"), // encoding if seeds > 5 and if orientation is down g=[ // storing dandelion as array of characters c=" _ "[b], // "_" if seeds > 5 and orientation is up, else " " " \\"[d=+(C>1)], // "\" if seeds > 1, else " " " |"[C&1], // "|" if seeds is odd, else " " " /"[d], c, // "_" if seeds > 5 and orientation is up, else " " "\n", e=" _"[b], // "_" if seeds > 5 and orientation is down, else " " ...( // spread characters for .reverse() to be correct C>3? // if seeds > 3 "/|\" else " | " "/|\\": " | " ), e, // "_" if seeds > 5 and orientation is down, else " " ..."\n | ".repeat(A-1) // repeat stem length - 1 times ], o? // if orientation is down, reverse g.reverse(): g ).join(""): // join array of characters [ // else if input is dandelion _.length-1, // length of stem is number of rows - 1 a==" | "||b[2]!="|"? // test orientation of dandelion _.reverse()&&"d": // reverse rows if necessary and return "d" for down "u" // else return "u" for up , ( _[1][1]!=" "? // if 1,1 is not " ", seeds is 4 or more 4+(_[0][0]!=_[1][0])*2: // if 0,0 or 1,0 is "_", seeds is 6 or 7 (_[0][3]!=" ")*2 // if 0,3 is not " ", seeds is 2 or 3 )+ (_[0][2]!=" ") // if 0,2 is not " ", seeds is odd ].join("\n") // join parameters with newline to match input format ``` Implicitly takes stdin as newline separated array of unformatted strings in `_` and implicitly outputs the parameters as a triplet. Test suite below and [demo here](https://patrickroberts.github.io/bean/#h=JlLKwSBd09CA1c2gXoBMzKBFhiU+iE2ga4BMoF6AI2DNoGOAQ82gX4BQhKOBACBe0ISjgQFNoGCASsFMoEWGJTrQhKOBAkygRZIlOtCEo4EDIGCgX6OBBM2gYYBQhKOBBSBez1LMoEWGJTyjgQYjgQegYc9T0ICjgQgggLVMoEOMJToAUqBr01CAoGMggH4gYyCAeyMAU9CAw8zQgKB4IIABjCU60s7MoF2AI4EJgEzQhKBeJTuBI4EKztNQgKB4IIB+gSNgI3HM0szQhNCEoHglOiU6gSOBC8ylPYtMzNCE0ISgeCU5JTmBUITQhKB4JTolOY0lO0zM0ITQhKB4JTklPIEjgQuNJTuLTNCE0ISgeCU5JTuBI4ELACCAeyOBBKDfIKBcoHygLwqgoF+v/Fyg/CCKoKD8oCCgoPygIHwg&i=MgpkCjA=&f=0&w=1): ``` const js = String.raw` +a? // if input is parameters ( b=(C>5)<<(o=b=="d"), // encoding if seeds > 5 and if orientation is down g=[ // storing dandelion as array of characters c=" _ "[b], // "_" if seeds > 5 and orientation is up, else " " " \\"[d=+(C>1)], // "\" if seeds > 1, else " " " |"[C&1], // "|" if seeds is odd, else " " " /"[d], c, // "_" if seeds > 5 and orientation is up, else " " "\n", e=" _"[b], // "_" if seeds > 5 and orientation is down, else " " ...( // spread characters for .reverse() to be correct C>3? // if seeds > 3 "/|\" else " | " "/|\\": " | " ), e, // "_" if seeds > 5 and orientation is down, else " " ..."\n | ".repeat(A-1) // repeat stem length - 1 times ], o? // if orientation is down, reverse g.reverse(): g ).join(""): // join array of characters [ // else if input is dandelion _.length-1, // length of stem is number of rows - 1 a==" | "||b[2]!="|"? // test orientation of dandelion _.reverse()&&"d": // reverse rows if necessary and return "d" for down "u" // else return "u" for up , ( _[1][1]!=" "? // if 1,1 is not " ", seeds is 4 or more 4+(_[0][0]!=_[1][0])*2: // if 0,0 or 1,0 is "_", seeds is 6 or 7 (_[0][3]!=" ")*2 // if 0,3 is not " ", seeds is 2 or 3 )+ (_[0][2]!=" ") // if 0,2 is not " ", seeds is odd ].join("\n") // join parameters with newline to match input format`; // bean binary const bin = bean.compile(js); // program as function const prog = bean.program(bin); (document.body.onchange = function () { const parameters = stem.value + '\n' + orientation.value + '\n' + seeds.value; dandelion.textContent = prog(parameters); params.value = prog(dandelion.textContent); })(); ``` ``` textarea { resize: none; } ``` ``` <script src="https://cdn.rawgit.com/patrickroberts/bean/master/dst/bean.min.js"></script> <input id=stem type=number min=1 max=256 value=5> <select id=orientation> <option value="u">u</option> <option value="d">d</option> </select> <input id=seeds type=number min=0 max=7 value=5> <p>Dandelion (output from program given parameters)</p> <pre id=dandelion></pre> <p>Parameters (output from program given dandelion)</p> <textarea id=params rows=3></textarea> ``` [Answer] ## Javascript ~~513~~ ~~391~~ ~~379~~ 355 bytes Thanks to @Neil for helping golf off 134 bytes and @Kritixi Lithos for helping golf off 13 bytes This program assumes that any ASCII dandelions it is trying to identify have a line width of 5 for all lines of the string. ie: the stem is 2 spaces, the vertical line then another 2 spaces. (It can not classify dandelions it creates due to this issue) ``` (x,y,z)=>{a=Array(x+1).fill(1);if(x.length>1){a=x.split` `;h=a.length-1;t=b=i=0;for(;i<(h>1)+1;i++)for(j=0;j<5;a[h-i][j++]!=' '&&b++)a[i][j]!=' '&&t++;return[h,(t>b?t:b)-(h>1),t>b?'^':'v']}z<'v'?(a[0]=y&4?y-2:y,a[1]=y&4?7:1):(a[x-1]=1+(y>4)*2+(y>4)*(y&2),a[x]=y&1+(y>2)*6);return a.map(n=>', |, \\ /, \\|/,_\\ /_,_\\|/_, / \\, /|\\'.split`,`[n]).join` `} ``` ## How it Works The function checks if the first argument it is given has a length >1 (is a string). If the first argument is a string, it identifies the details of the ASCII dandelion. To get the height of the dandelion, it splits the string around newline characters and counts the number of elements - 1. To get the number of seeds, it counts the number of non space characters on the top two and bottom two lines. if there are more characters in the top, it is declared to be upright and it uses the top count-1, otherwise it is declared to be upside down and uses the bottom count-1. If the total height is only 2, it determines uprightness by checking the counts of each line individually and choosing the side with more non space characters. Otherwise, the function uses bitwise math in order to assign values from 0 to 7 according to the shape of each level of the dandelion to be drawn before converting each level into the appropriate string. ``` 0: 1: | 2: \\ / 3: \\|/ 4:_\\ /_ 5:_\\|/_ 6: / \\ 7: /|\\ ``` [Try it online](https://tio.run/#y7sRK) [Answer] # Python 3.6, ~~476~~ ~~453~~ ~~448~~ ~~413~~ 394 bytes **Solution** : ``` def h(i): l,s,o=i.split(",");s=int(s);z=[" | "];q=(int(l)-1)*z;b,d,f,h,g,c,a=[" ","\\/"][s>1]+[" ","\\/"][s>3]+["| ","||"][s%2==1]+[" ","_"][s>5] if"d"==o:b,d,h,f,c,g=f,h,d,b,g,c r=[[a+b+c+d+a]+[" "+h+g+f+" "],z][s==0];return"\n".join([q+r,r+q]["u"==o]) def j(i): if","in i:print(h(i)) else:[print(f"{m},{j},{k}")for m in range(257)for j in range(8)for k in"ud"if i==h(f"{m},{j},{k}")] ``` **Result** ``` >>> j("6,5,u") \|/ /|\ | | | | | >>> j("5,2,d") | | | | | / \ >>> j("3,2,u") \ / | | | >>> j("_\|/_\n /|\ \n | \n | \n | \n | \n | ") 6,7,u >>> j(" \|/ \n /|\ \n | \n | \n | \n | ") 5,5,u >>> j(" | \n | \n | \n | \n | ") 4,1,u 4,1,d 5,0,u 5,0,d ``` **Unfold** ``` def g(i): def h(i): # this function draw dandelion l, s, o = i.split(",") # split argument s = int(s) # Calcul the string in the flower for up case # _\|/_ --> abcdb --> when s=7 we have a=_ b=\ c=| d=/ h=/ g=| f=\ # /|\ --> hgf a = "_" if s > 5 else " " b = "\\" if s > 1 else " " d = "/" if s > 1 else " " h = "/" if s > 3 else " " f = "\\" if s > 3 else " " c = "|" if s%2 == 1 else " " g = "|" if s%2 == 1 else "|" # Shuffle a bit if the position is down if"d"==o: b,d,h,f,c,g=f,h,d,b,g,c # treate the case to remove the line with ony white space if s==0: res=[" | "] else: # assemble all piece of the flower res += [a+b+c+d+a] res += [" "+h+g+f+" "] # add stem up or down if o=="u": res = res + (int(l)-1) * [" | "] else: res = (int(l)-1) * [" | "] + res return "\n".join(res) if "," in i: print(h(i)) else: # search in all flower posibility if we can recreate the input [print(m,j,k) for m in range(1, 257) for j in range(0, 8)for k in "ud"if i == h(f"{m},{j},{k}")] ``` ]
[Question] [ **Challenge** Ever seen those movie trailer titles (namely Martian, Interstellar, etc) where they have huge gaps in between letters slowly spreading out? The challenge is to recreate this effect given a string, gap multiplier and direction, by inserting appropriate amount of spaces in between the letters. **Example** **Input**: 'INTERSTELLAR', Gap multiplier: 1.0, Direction: Increasing Inward ``` Output: I N T E R S T E L L A R ``` The spacing is: [1, 2, 3, ... , 3, 2, 1]; replacing the spaces with '.' to better demonstrate the spacing: ``` I.N..T...E....R.....S......T.....E....L...L..A.R ``` **Input**: 'INTERSTELLAR', Gap multiplier: 0.5, Direction: Increasing Inward ``` Output: IN T E R S T E L L AR ``` The spacing is multiplied by 0.5, therefore we get [0, 1, 1, 2, ... 2, 1, 1, 0] from integer division; using '.': ``` IN.T.E..R..S...T..E..L.L.AR ``` **Input**: 'CODEGOLF', Gap multiplier: 2.0, Direction: Increasing Outward ``` Output: C O D E G O L F ``` The spacing is multiplied by 2, increasing outward, therefore we get [8,6,4,2,4,6,8]; replacing with '.': ``` C........O......D....E..G....O......L........F ``` **Input**: 'CODEGOLF', Gap multiplier: 0.4, Direction: Increasing Outward ``` Output: C O DEGO L F ``` The spacing is multiplied by 0.4, increasing outward, therefore we get [1,1,0,0,0,1,1]; replacing with '.': ``` C.O.DEGO.L.F ``` **Rules** * Takes 3 input: string, gap multiplier and direction * If input string is odd in length (even in # of gaps) e.g. 'HELLO', the spacing of the inner most 2 gaps should be the same `H E L L O` * The direction and gap multiplier can be parsed however you want, e.g. you could use -2 as 'increasing inward with a multiplier of 2', 1 as 'increasing outward with a multiplier of 1', etc. * It is only required to use spaces, however it is a bonus if the character filling is customizable. **Reference Animation** ![reference gif](https://i.makeagif.com/media/10-06-2016/Sx25uj.gif) Have fun golfing! [Answer] ## JavaScript (ES6), ~~86~~ ~~82~~ ~~81~~ 80 bytes Input is expected in currying syntax `f(s)(r)`, with: * `s` = string * `r` = ratio + direction: a negative float for inward or a positive float for outward ``` let f = s=>r=>s.replace(/./g,(c,i)=>c+' '.repeat(n+=i<l?-r:r),l=s.length/2,n=r>0&&l*r+r) console.log(f("INTERSTELLAR")(-1)); console.log(f("INTERSTELLAR")(-0.5)); console.log(f("CODEGOLF")(2)); console.log(f("CODEGOLF")(0.4)); ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 33 bytes Uses [CP-1252](http://www.cp1252.com/) encoding. Gap multiplier is taken as negative when outwards increasing. ``` g;>Î.S<_²**ÄU¹vyð²¹g<;N.S*X+DUï×J ``` [Try it online!](http://05ab1e.tryitonline.net/#code=Zzs-w44uUzxfwrIqKsOEVcK5dnnDsMKywrlnPDtOLlMqWCtEVcOvw5dK&input=Q09ERUdPTEYKLTAuNA) [Answer] # APL, 40 bytes ``` {⍵\⍨0~⍨∊1,⍨1,¨-⌊⍺×(1+⌈/-+)⍣⍺⍺(⌽⌊+)⍳⍴1↓⍵} ``` This takes the string as its right argument, the ratio as its left argument and the direction as its left operand (0 for inward and 1 for outward). ``` 1 (0 {⍵\⍨0~⍨∊1,⍨1,¨-⌊⍺×(1+⌈/-+)⍣⍺⍺(⌽⌊+)⍳⍴1↓⍵}) 'INTERSTELLAR' I N T E R S T E L L A R 0.5 (0 {⍵\⍨0~⍨∊1,⍨1,¨-⌊⍺×(1+⌈/-+)⍣⍺⍺(⌽⌊+)⍳⍴1↓⍵}) 'INTERSTELLAR' IN T E R S T E L L AR 2 (1 {⍵\⍨0~⍨∊1,⍨1,¨-⌊⍺×(1+⌈/-+)⍣⍺⍺(⌽⌊+)⍳⍴1↓⍵}) 'CODEGOLF' C O D E G O L F 0.4 (1 {⍵\⍨0~⍨∊1,⍨1,¨-⌊⍺×(1+⌈/-+)⍣⍺⍺(⌽⌊+)⍳⍴1↓⍵}) 'CODEGOLF' C O DEGO L F ``` Explanation: * `⍳⍴1↓⍵`: get a list of numbers from 1 to N-1, where N is the length of the string * `(⌽⌊+)`: invert the list, and at each position, get the lowest number of both lists (this gives the sizes of the gaps if increasing inwards) * `(1+⌈/-+)⍣⍺⍺`: subtract each number in the list from the highest number in the list, and add 1. Do this `⍺⍺` times. (If `⍺⍺=0`, nothing will happen, and if `⍺⍺=1`, this will give the sizes of the gaps if increasing outwards.) * `-⌊⍺×`: multiply each gap by `⍺`, round it downwards, and negate it. * `∊1,⍨1,¨`: add a 1 in front of each gap, and a 1 at the very end of the list. * `0~⍨`: remove any zeroes. * `⍵\⍨`: use the resulting list to expand `⍵`. Expand (`\`) works in the following manner: for each positive number, the current character is replicated that many times, and for each negative number, that many spaces are inserted, with the caveat that `0` and `¯1` do the same thing, which is why all the zeroes had to be removed earlier. [Answer] # [MATL](http://github.com/lmendo/MATL), 31 bytes ``` nq:tPvX<i?tX>Qw-]*kQ1whYs''1Gb( ``` Inputs are: string; `0` or `1` for inward or outward increasing; multiplier. [Try it online!](http://matl.tryitonline.net/#code=bnE6dFB2WDxpP3RYPlF3LV0qa1Exd2hZcycnMUdiKA&input=J0lOVEVSU1RFTExBUicKMAowLjU) ### Explanation Consider inputs `'INTERSTELLAR'`, `1`, `0.5` as an example. ``` nq: % Input string implicitly. Push [1 2 ... N-1] where N is the string length % STACK: [1 2 3 4 5 6 7 8 9 10 11] tP % Duplicate, reverse % STACK: [1 2 3 4 5 6 7 8 9 10 11], [11 10 9 8 7 6 5 4 3 2 1] vX< % Vertically concatenate. Minimum of each column % STACK: [1 2 3 4 5 6 5 4 3 2 1] i % Input direction flag % STACK: [1 2 3 4 5 6 5 4 3 2 1], 1 ? % If input flag was 1 (meaning outward increasing) tX> % Duplicate. Maximum % STACK: [1 2 3 4 5 6 5 4 3 2 1], 6 Q % Add 1 % STACK: [1 2 3 4 5 6 5 4 3 2 1], 7 w- % Swap. Subtract % STACK: [6 5 4 3 2 1 2 3 4 5 6] ] % End *k % Input multiplier implicitly. Multiply. Round down % STACK: [3 2 2 1 1 0 1 1 2 2 3] Q % Add 1 % STACK: [4 3 3 2 2 1 2 2 3 3 4] 1wh % Prepend a 1 % STACK: [1 4 3 3 2 2 1 2 2 3 3 4] Ys % Cumulative sum % STACK: [1 5 8 11 13 15 16 18 20 23 26 30] '' % Push empty string % STACK: [1 5 8 11 13 15 16 18 20 23 26 30], '' 1G % Push input string again % STACK: [1 5 8 11 13 15 16 18 20 23 26 30], '', 'INTERSTELLAR' b % Bubble up % STACK: '', 'INTERSTELLAR', [1 5 8 11 13 15 16 18 20 23 26 30] ( % Assign the characters from the top string into the empty string at the % given positions. Intermediate positions are filled with character 0, % which is displayed as a space % STACK: 'I N T E R ST E L L A R' % Dispaly implicitly ``` [Answer] ## Racket 348 bytes ``` (define(f s)(let*((c #\space)(sp(λ(l)(define ol'())(for((i(length l)))(for((j i)) (set! ol(cons c ol)))(set! ol(cons(list-ref l i)ol)))(for((n(floor(/(length l)2)))) (set! ol(cons c ol)))ol))(m(floor(/(string-length s)2)))(s1(sp(string->list(substring s 0 m) )))(s2(sp(reverse(string->list(substring s m))))))(list->string(append(reverse s1)s2)))) ``` Ungolfed: ``` (define(f s) (let* ((c #\space) (sp (λ (l) ; subfn to add increasing spaces to list of characters (define ol '()) (for ((i (length l))) (for ((j i)) (set! ol (cons c ol))) (set! ol (cons (list-ref l i)ol))) (for ((n (floor(/ (length l)2)))) (set! ol (cons c ol))) ol)) (m (floor (/ (string-length s) 2))) ; find midpoint (s1 (sp (string->list (substring s 0 m)))) ; add spaces to first part (s2 (sp (reverse (string->list (substring s m)))))) ; add spaces to second part (list->string (append (reverse s1) s2)) ; re-combine 2 parts )) ``` Testing: ``` (f "INTERSTELLAR") ``` Output: ``` "I N T E R S T E L L A R" ``` [Answer] # PHP, 129 Bytes 12 Bytes saved by @Titus Thank You string = $argv[1],ratio = $argv[2], direction = $argv[3] inward = 0 ,Outward =1 ``` for($i=0;$i+1<2*$l=strlen($t=($x=$argv)[1]);)echo$i%2?str_pad("",$x[2]*abs($x[3]*(0^$l/2+1)-($i++>=$l?$l-$i/2:$i/2))):$t[$i++/2]; ``` ]
[Question] [ Y'know, we've had a lot of "alphabet" challenges recently. ([one](https://codegolf.stackexchange.com/questions/86986/print-a-tabula-recta) [two](https://codegolf.stackexchange.com/questions/87064/print-output-the-l-phabet) [three](https://codegolf.stackexchange.com/questions/87496/alphabet-triangle) [four](https://codegolf.stackexchange.com/questions/89249/slices-of-triangular-alphabets) [five](https://codegolf.stackexchange.com/questions/89283/print-an-alphabet-wave).) While I love a good challenge, and those challenges were very fun, I think it's time for a change of pace. We need to exclude such challenges in the future. It's time for [automation](http://xkcd.com/1319/)! You're going to find some alphabets for me, and for automation (and for glory!) Alphabets are tricky and like to disguise themselves.[[citation-needed]](http://bit.ly/ppcgofficialsoundtrack) You'll need to account for the following factors: 1. Alphabets can be uppercase or lowercase (but not both). So, you need to look for `ABCDEFGHIJKLMNOPQRSTUVWXYZ` and `abcdefghijklmnopqrstuvwxyz`, but not `AbCdeFGhIJkLmNOpQRsTuvwxyZ`. That is, only look for alphabets that are composed of entirely one case. 2. Alphabets can shift around. they may not always start with `A`, but instead may start with `G` or `U`. So you'll have to look for things like `OPQRSTUVWXYZABCDEFGHIJKLMN`. 3. Alphabets may not always read forwards. They can also read backwards, up, and down. E.g., `ZYXWVUTSRQPONMLKJIHGFEDCBA`is also a valid alphabet. Here's an example of a string that has an alphabet: ``` JIHGFEDCBAZYXWVUTSRQPONMLK ``` This is a backwards-oriented, shifted alphabet: ``` JIHGFEDCBAZYXWVUTSRQPONMLK <--------|<--------------- ``` This *also* contains an alphabet: ``` F G H I J K L M N O P Q R S T U V W X Y Z A B C D E ``` it's a down-oriented alphabet: ``` F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z V A=== B | C | D | E V ``` --- Your challenge is to write a program, function, etc. that, given a string, outputs/returns a truthy value if the string contains at least one alphabet, or a falsey value otherwise. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. ## Test cases ### Truthy ``` ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz ZABCDEFGHIJKLMNOPQRSTUVWXYghijklmnopqrstuvwxyzabcdef ZBCDEFGHIJghijklmnopqrstuvwxyzabcdef AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD EEEEEEEE FFFFFFFF GGGGGGGG HHHHHHHH IIIIIIII JJJJJJJJ KKKKKKKK LLLLLLLL MMMMMMMM NNNNNNNN OOOOOOOO PPPPPPPP QQQQQQQQ RRRRRRRR SSSSSSSS TTTTTTTT UUUUUUUU VVVVVVVV WWWWWWWW XXXXXXXX YYYYYYYY ZZZZZZZZ J54 Igeh H G Fzx6 E Dv Cvzxc Bs Adf Z @Yascvf Xsf W Vfas Uw Te ~S R Qasdfasdf P O N M LMNOPQR K ``` ### Falsey ``` Hello, World! KLMNOPQRSTUVWXYZABCDEF K ZYXW L V M U N T O S P R Q A BCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLmnopqrstuvwxyz ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ ~~23~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) **1 byte thanks to Dennis.** ``` 26RØAṙ;U$;Œl$ ;Zẇ@þ¢FS ``` [Try it online!](http://jelly.tryitonline.net/#code=MjZSw5hB4bmZO1UkO8WSbCQKO1rhuodAw77CokZT&input=&args=WyJBIiwiIEJDREVGR0hJSktMTU5PUFFSU1RVVldYWVoiXQ) Takes an array of strings. [Answer] # Cheddar, 148 bytes ``` (s,b=65@"90,c?)->(|>27).map(->s has(b=b.slice(1)+b[0])||s has b.lower||(1|>3).map(j->(c=s.lines.turn(j).vfuse)has b||c has b.lower?1:0).sum?1:0).sum ``` [Try it online!](http://cheddar.tryitonline.net/#code=KHMsYj02NUAiOTAsYz8pLT4ofD4yNykubWFwKC0-cyBoYXMoYj1iLnNsaWNlKDEpK2JbMF0pfHxzIGhhcyBiLmxvd2VyfHwoMXw-MykubWFwKGotPihjPXMubGluZXMudHVybihqKS52ZnVzZSloYXMgYnx8YyBoYXMgYi5sb3dlcj8xOjApLnN1bT8xOjApLnN1bQ&input=WkJDREVGR0hJSmdoaWprbG1ub3BxcnN0dXZ3eHl6YWJjZGVm) ## Non-copmeting, ~~146~~ 132 bytes This is the **exact same** as above except `map(...?1:0).sum` has become `any(...)`. ``` (s,b=65@"90,c?)->(|>27).any(->s has(b=b.slice(1)+b[0])||s has b.lower||(1|>3).any(j->(c=s.lines.turn(j).vfuse)has b||c has b.lower)) ``` Rather slow but it works ¯\\_(ツ)\_/¯ . added `any` function after challenge release date. The input **does not** need to be padded with whitespaces. But if an input doesn't work, pad it with whitespaces to make rectangle. The `turn` function is really finicky and I'm not sure when it works and when it doesn't ### Explanation Loops through all possible cycles of alphabet. On each iteration check if the current cycle of alphabet exists in the string, if not, check if any of the possible rotations of the string have the alphabet. ### Ungolfed ``` (str, a = 65@"90)-> (|>27).any(-> str has (a = a.slice(1) + a[0]) || str has a.lower || (1|>3).any(j -> (c = str.lines.turn(j).vfuse) has a || c has a.lower ) ) ``` [Answer] ## 05AB1E, 43 bytes ``` A‚Duìvy26FÀD}})U|Dø€J)˜vXDgs`rFysk>ˆ}}¯O__ ``` **Explanation in short** Get different variations of alphabet (caps, no-caps, reversed, normal) and store in X. ``` A‚Duìvy26FÀD}})U ``` Get each row and column of input as a list of strings. ``` |Dø€J)˜ ``` Check each such string if it contains a variation of the alphabet. ``` vXDgs`rFysk>ˆ}} ``` Sum and double negate, giving 1 for true and 0 for false. ``` ¯O__ ``` [Try it online](http://05ab1e.tryitonline.net/#code=QcOC4oCaRHXDrHZ5MjZGw4BEfX0pVXxEw7jigqxKKcucdlhEZ3NgckZ5c2s-y4Z9fcKvT19f&input=IEo1NCAgICAgIAogSWdlaCAgICAgCiBIICAgICAgICAKIEcgICAgICAgIAogRnp4NiAgICAgCiBFICAgICAgICAKIER2ICAgICAgIAogQ3Z6eGMgICAgCiBCcyAgICAgICAKIEFkZiAgICAgIAogWiAgICAgICAgCkBZYXNjdmYgICAKIFhzZiAgICAgIAogVyAgICAgICAgCiBWZmFzICAgICAKIFV3ICAgICAgIAogVGUgICAgICAgCn5TICAgICAgICAKIFIgICAgICAgIAogUWFzZGZhc2RmCiBQICAgICAgICAKIE8gICAgICAgIAogTiAgICAgICAgCiBNICAgICAgICAKIExNTk9QUVIgIAogSyAgICAgICAg) [Answer] # Python, 182 bytes Doesn't feel very 'golfed', but ... ``` import re a='abcdefghijklmnopqrstuvwxyz' P,N='|\n' p=P.join(a[i:]+a[:i] for i in range(26)) p+=P+p[::-1] p+=P+p.upper() lambda s:re.search(p,s+N+N.join(map(''.join,zip(*s.split(N))))) ``` Theory of operation: First, build a regex pattern combining all the possible alphabets: `p=P.join(a[i:]+a[:i] for i in range(26))` builds a string of all rotations of 'a' joined with '|'. e.g. "abc...z|bcd...za|..." `p+=P+p[::-1]` appends a reversed version of itself. `p+=P+p.upper()` appends an uppercase version. Then create a long string combining the original `s` and a version of `s` with the columns turned into rows: `N.join(map(''.join,zip(*s.split(N))))` flips the rows and columns, so 'a\nb\nc' becomes 'abc' return true if the pattern is in the long string. ]
[Question] [ **Important note**: Because this challenge only applies to square matrices, any time I use the term "matrix", it is assumed that I am referring to a square matrix. I am leaving off the "square" description for brevity's sake. ## Background Many matrix-related operations, such as computing the determinant, solving a linear system, or extending scalar-valued functions to matrices are made easier by using a diagonal matrix (one whose elements that are not on the main diagonal are 0) that is similar to the original matrix (meaning, for the input matrix `A` and the diagonal matrix `D`, there exists some invertible matrix `P` such that `D = P^(-1) * A * P`; also, `D` and `A` share some important properties, like eigenvalues, determinant, and trace). For matrices with distinct eigenvalues (the roots to the matrix's characteristic polynomial, given by solving `det(A-λI) = 0` for `λ`, where `I` is the identity matrix with the same dimensions as `A`), diagonalization is simple: `D` is a matrix with the eigenvalues on the main diagonal, and `P` is a matrix formed from eigenvectors corresponding to those eigenvalues (in the same order). This process is called [eigendecomposition](https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix). However, matrices with repeated eigenvalues cannot be diagonalized in this manner. Luckily, the [Jordan normal form](https://en.wikipedia.org/wiki/Jordan_normal_form) of any matrix can be computed rather easily, and is not much harder to work with than a regular diagonal matrix. It also has the nice property that, if the eigenvalues are unique, then Jordan decomposition is identical to eigendecomposition. ## Jordan decomposition explained For a square matrix `A` whose eigenvalues all have a geometric multiplicity of 1, the process of Jordan decomposition can be described as such: 1. Let `λ = {λ_1, λ_2, ... λ_n}` be the list of eigenvalues of `A`, with multiplicity, with repeated eigenvalues appearing consecutively. 2. Create a diagonal matrix `J` whose elements are the elements of `λ`, in the same order. 3. For each eigenvalue with multiplicity greater than 1, place a `1` to the right of each of the repetitions of the eigenvalue in the main diagonal of `J`, except the last. The resulting matrix `J` is a Jordan normal form of `A` (there can be multiple Jordan normal forms for a given matrix, depending on the order of the eigenvalues). ### A worked example Let `A` be the following matrix: [![A matrix](https://i.stack.imgur.com/tmHgd.png)](https://i.stack.imgur.com/tmHgd.png) The eigenvalues of `A`, with multiplicity, are `λ = {1, 2, 4, 4}`. By putting these into a diagonal matrix, we get this result: [![step 2](https://i.stack.imgur.com/g7oc5.png)](https://i.stack.imgur.com/g7oc5.png) Next, we place `1`s to the right of all but one of each of the repeated eigenvalues. Since `4` is the only repeated eigenvalue, we place a single `1` next to the first 4: [![jordan form](https://i.stack.imgur.com/XgS6t.png)](https://i.stack.imgur.com/XgS6t.png) This is a Jordan normal form of `A` (a single matrix can potentially have several valid Jordan normal forms, but I'm glossing over that detail for the purpose of explanation). ## The task Given a square matrix `A` as input, output a valid Jordan normal form of `A`. * The input and output may be in any reasonable format (2D array/list/whatever, list/array/whatever of column or row vectors, a builtin matrix data type, etc.). * The elements and eigenvalues of `A` will always be integers in the range `[-200, 200]`. * For the sake of simplicity, all of the eigenvalues will have a geometric multiplicity of 1 (and thus the above process holds). * `A` will at most be a 10x10 matrix and at least a 2x2 matrix. * Builtins that compute eigenvalues and/or eigenvectors or perform eigendecomposition, Jordan decomposition, or any other kind of decomposition/diagonalization are not allowed. Matrix arithmetic, matrix inversion, and other matrix builtins are allowed. ## Test cases ``` [[1, 0], [0, 1]] -> [[1, 1], [0, 1]] [[3, 0], [0, 3]] -> [[1, 1], [0, 1]] [[4, 2, 2], [1, 2, 2],[0, 3, 3]] -> [[6, 0, 0], [0, 3, 0], [0, 0, 0]] [[42, 48, 40, 64, 64], [41, 47, 31, 58, 42], [-55, -47, -27, -74, -46], [-46, -58, -46, -70, -68], [30, 20, 12, 34, 18]] -> [[10, 0, 0, 0, 0], [0, -18, 0, 0, 0], [0, 0, 6, 1, 0], [0, 0, 0, 6, 1], [0, 0, 0, 0, 6]] ``` [Answer] # Mathematica, ~~140~~ ~~139~~ 105 bytes ``` Total[DiagonalMatrix@@@{{#},{1-Sign[Differences@#^2],1}}]&@(x/.Solve[#~CharacteristicPolynomial~x==0,x])& ``` I just found the builtin `DiagonalMatrix` which allows for an easy way to place the 0s and 1s along the superdiagonal. ## Usage ![Example](https://i.stack.imgur.com/aucIS.png) [Answer] ## Sage, 79 bytes ``` lambda A:block_diagonal_matrix([jordan_block(*r)for r in A.charpoly().roots()]) ``` [Try it online](http://sagecell.sagemath.org/?z=eJw1TdEOgjAMfCfhH_q4mY3IGIOY-MB3kIUMCAoOZiYP-ve2GB-uvd712unq3dqPDppL78Pw6MbZ3cLmfLe6Pc5v1i4hjm7rDpedIp9ChAjzBk023F18Bv9hPIsh7C_GLU-TNJnYP9xqJUDXiLMAowlWQKtzVCoBBfaSXEWqLEsBknSpqFSaRnNY2iCn1R-r8Jw0NVkFUoXI8VOBiby2lvMvdPI4Eg==&lang=sage) Since nobody else is posting solutions, I might as well go ahead and post one. `A.charpoly.roots()` computes the roots (and algebraic multiplicities) of the characteristic polynomial of `A` (aka the eigenvalues and multiplicities). `jordan_block` constructs a Jordan block from the given root and multiplicity. `block_diagonal_matrix` forms a matrix with the Jordan blocks on the diagonal, which is exactly the definition of a Jordan normal form. [Answer] # [J](http://jsoftware.com/), ~~78~~ 71 bytes ``` 1(#\.|."_1#{."1],.2=/\,&_)@>@{[:p.@>[:-&.>/ .(+//.@(*/)&.>)],&.>[:-@=#\ ``` [Try it online!](https://tio.run/nexus/j#TY/daoQwEIXv8xSHFRZtbeIkExWLkvdYJRdLl95Ie799dztJhBbmJ985mSE5HpgnUF2t@kdfIlVPfaGt1XY2a3uNTVjC8zZ967DcprerXgx0/WqMDvWLaYSbrZUqXpirVam9S@siY1vhwbAgdJLxX7isFNGqnfKETRPprnhqt3@ay5pTu8uaS1ramzanKl5yObs@uxY8gjv0nIIJPMAR/Jis6L28b5DtkgPLuS8pdu5Dh9iPcB2svMXCMWhU6uP@@QX53jse0k6kgnSiLWhPdAXdiVyQj@MX) The two challenging portions of this task, getting the eigenvalues and performing the diagonalization, ending up both taking about the same number of bytes. These were disallowed by the rules but in case any are curious, J has builtins for QR decomposition (`128!:0`) as well as LAPACK addons which could be used to find eigenvalues. ## Explanation (Outdated) There are two major portions to this verb: finding the eigenvalues and performing the diagonalization. First, in order to find the eigenvalues, the roots of the characteristic polynomial for the input matrix will have to be found. Using the same input matrix from the example, ``` ] m =: _4 ]\ 5 4 2 1 0 1 _1 _1 _1 _1 3 0 1 1 _1 2 5 4 2 1 0 1 _1 _1 _1 _1 3 0 1 1 _1 2 ``` The characteristic polynomial for a matrix *M* can be found using |*M* - *λI*| = 0 where *I* is the identity matrix with the same dimensions as *M*. The expression *M* - *λI* can be modeled in J by boxing each element in *M* with a -1 if it is on the diagonal else otherwise a 0. Each box represents a polynomial in coefficient form. ``` (],&.>[:-@=#\) m ┌────┬────┬────┬────┐ │5 _1│4 0 │2 0 │1 0 │ ├────┼────┼────┼────┤ │0 0 │1 _1│_1 0│_1 0│ ├────┼────┼────┼────┤ │_1 0│_1 0│3 _1│0 0 │ ├────┼────┼────┼────┤ │1 0 │1 0 │_1 0│2 _1│ └────┴────┴────┴────┘ ``` The determinant in J is `-/ .*` however, that operates on numbers, not boxed polynomials. Instead of multiplication, the polynomial product is needed which can be found using convolution (`[:+//.*/`). Folded subtraction is still used, and both these verbs need to operate within boxes so under (`&.`) unbox (`>`) is used. ``` ([:-&.>/ .(+//.@(*/)&.>)],&.>[:-@=#\) m0 ┌───────────────┐ │32 _64 42 _11 1│ └───────────────┘ ``` These are the coefficients of the characteristic polynomial. The roots can be found using `p.` which converts the representation of a polynomial between coefficients and roots form. ``` ([:p.@>[:-&.>/ .(+//.@(*/)&.>)],&.>[:-@=#\) m0 ┌─┬───────┐ │1│4 4 2 1│ └─┴───────┘ ``` The roots are `[4, 4, 2, 1]` and those are the eigenvalues of *M*. Second, the diagonalization must be performed. Each continuous pair of values is tested for equality. ``` (2=/\]) 4 4 2 1 1 0 0 ``` A zero is appended and those values are columinized together with the eigenvalues. ``` (],.0,~2=/\]) 4 4 2 1 4 1 4 0 2 0 1 0 ``` Then each row is padded to the same length as the number of eigenvalues to form a square matrix. ``` (#{."1],.0,~2=/\]) 4 4 2 1 4 1 0 0 4 0 0 0 2 0 0 0 1 0 0 0 ``` Finally each row is shifted right with values falling off at the right and zeros being pushed in on the left. The first row is shifted zero times, the second once, the third twice, and so on. ``` (-@i.@#|.!.0"_1#{."1],.0,~2=/\]) 4 4 2 1 4 1 0 0 0 4 0 0 0 0 2 0 0 0 0 1 ``` The output is the Jordan decomposition of *M*. [Answer] # [Octave](https://www.gnu.org/software/octave/), 60 bytes ``` @(a)diag(1-sign(diff(v=round(roots(poly(a)))).^2),1)+diag(v) ``` [Try it online!](https://tio.run/nexus/octave#HYtdCoMwEITfPcU8bmhT8rMaIQi9R2lBCBGhGtFW6Ont4jLDfMzuHnfqVRr7gazexmGmNOZMe7eW75xoLeWz0VLeP7mSub2culp1OR92dWR06OctVpPAgx24BRs0LIpswQHeopbSRV3X0FJoJw4s3EQxtKzPDAa6aaM3cAbWwTNs@6wyTer4Aw) A port of my Mathematica [solution](https://codegolf.stackexchange.com/a/83429/6710). [Answer] # [MATL](https://github.com/lmendo/MATL), 29 bytes, non-competing ``` 1$Yn1$ZQYotdUZS~0hXdF1hYSwXd+ ``` [Try it online!](https://tio.run/nexus/matl#HYk9C8MwDET/yg3ZikCS5Q/w3j2EQpzSzUOmZAl06193ROEed7wbMrVDpm1u59Vf2/Ljfe1P2dvyXftjjLcprMAYyTzVBJYRBNGlVooR5ILUyeY7VQfk978zg1KpgaEMUQSDlM8N "MATL – TIO Nexus") This is my first MATL submission so there are bound to be improvements. I spent a while learning it and only at the end did I remember that this might not have worked using the MATL from May 7, 2016. Sure enough, I checked out the penultimate [commit](https://github.com/lmendo/MATL/tree/673ac40831308a27475c53e4d28bc59ebf0f453f) to that day and it did not run. I would have liked to use `diag` but it seems MATL only supports the single argument version. The second argument would be needed to place values along the superdiagonal (or any other diagonal for different problems). ]
[Question] [ You will be given two pieces of input: a string in run-length encoded format defining the running track, and a capital letter representing the lane to start from. For example, the string "3a4A6b5B" expands to "aaaAAAAbbbbbbBBBBB". You then use the expanded string to create a track, as such: ``` A) aaaAAAA B) bbbbbbBBBBB ``` This is a track with two lanes. Lowercase letters represent air. You can not run on air! Uppercase letters represent road you can run on. Your goal for this challenge is, given a capital letter, output how far a racer starting on that lane could run. Racers are allowed to switch lanes if there is a piece of road directly above or below them. **They are also allowed to run backwards!** On this particular track the output is **0** for any letter input, because neither of the tracks has runnable road at position 1. ## Examples: **Input:** "4A5B4c3C", "A" This code expands to a track that looks like this: ``` A) AAAA B) BBBBB C) ccccCCC ``` The output for this example is **7**, because a runner starting on lane A could move down to lane B, and then lane C, and end up at the 7th position. **Input:** "4A2B3D", "D" **Track:** ``` A) AAAA B) BB C) D) DDD ``` The output is **3**, because a runner starting on lane D has no way to get to lane B or A **Input:** "4A4a4A3b6B5C", "A" **Track:** ``` A) AAAAaaaaAAAA B) bbbBBBBBB C) CCCCC ``` The output is **12**, because the runner on A can switch over to B, and then come back to A at the end. The max distance for "C" is also 12. For "B" it is 0. **Input:** "12M4n10N11O", "M" **Track:** ``` M) MMMMMMMMMMMM N) nnnnNNNNNNNNNN O) OOOOOOOOOOO ``` Simple example with multi-digit run-lengths. Output is **14**. **Input:** "4A5B1b2B4c3C", "A" **Track:** ``` A) AAAA B) BBBBBbBB C) ccccCCC ``` The output is **8**, because the runner at A can go down to B, then down to C, then come back to B. (Thank you to FryAmTheEggman for this example.) **Input:** "1a2A2a2B1c1C1d3D", "B" **Track:** ``` A)aAAaa B)BB C)cC D)dDDD ``` Output is **4**. Runner has to check both paths two see which goes further. (Thanks to user81655 for this example.) **Input:** "2A1b1B2C1D3E","A" **Track:** ``` A) AA B) bB C) CC D) D E) EEE ``` Output is **3**. You have to run backwards to reach the furthest destination. (Once again, thanks to user81655 for this example.) ## Notes: * If a track does not have a letter at a certain position, that counts as air too. As such, if the input is "Q" and no road has been placed on lane "Q" the output should be **0**. * There are two pieces of input. The first is a run-length encoded string. The second is a capital letter (you can use string or char datatype for this.) For readability, there should be some reasonable separator between these inputs (space, new line, tab, comma, semi-colon). * The run-length encoded string will always list elements in alphabetical order * The very longest the entire length of a lane can be is 1000. Therefore, the greatest possible output is 1000. ## Track Generator: In honor of our first answer, here is a track generator. Try to come up with something to stump the current answers! (Note: Just because the generator doesn't show an error message doesn't mean your track code is necessarily valid. See above examples for proper form.) ``` function reset() { var t = document.getElementById("track"); t.innerHTML = ""; for(var i = 0;i<26;i++) { var c = String.fromCharCode(i+65); t.innerHTML += "<div><span>"+c+") </span><span id='"+c+"'></span></div>"; } } function rand() { var track = ""; for(var i = 0;i<26;i++) { var blocks = Math.floor(Math.random()*4); var start = Math.floor(Math.random()*2); for(var j = 0;j<blocks;j++) { var letter = String.fromCharCode(65+i+32*((start+j)%2)); var length = Math.floor(Math.random()*4)+1; track += length+letter; } } document.getElementById("code").value = track; } function gen() { var s = document.getElementById("code").value; var check = s.match(/(\d+[A-Za-z])+/); if(check == null || check[0]!=s) { alert("Invalid Track"); return false; } reset(); var n = s.match(/\d+/g); var o = s.match(/[A-Za-z]/g); for(var i = 0;i<n.length;i++) { var c = o[i].toUpperCase(); document.getElementById(c).textContent += o[i].repeat(n[i]); } return true; } ``` ``` <body onload="reset()"> Track: <input type="text" id="code" size="75%" /><input type="submit" onclick="gen()" /><input type="button" value="Random Track" onclick="rand()" /><code id="track"/> </body> ``` [Answer] # JavaScript (ES6), ~~298~~ 334 bytes ``` (t,s)=>[a=[],t.match(/\d+(.)(\d+\1)*/gi).map(l=>a[c=l.match`[A-Z]`+"",n=c.charCodeAt(),c==s?i=n:n]=l[r="replace"](/\d+./g,p=>(p.slice(-1)<"a"?"1":"0").repeat(parseInt(p))),i=o=-1),...a.join``,a[i]?a[i]=a[i][r](/^1/,2):0].map(_=>a.map((l,y)=>a[y]=l[r](/1/g,(c,x)=>((a[y-1]||s)[x]|(a[y+1]||s)[x]|l[x-1]|l[x+1])>1?(x>o?o=x:0,2):c)))&&o+1 ``` ## Explanation Basically this solution treats the track as a maze. It finds where all the tiles that are possible for the runner to reach are and returns the greatest value of the X index it found. The first thing it does is decode the input string into an array of lines. Instead of using letters though, it turns a capital letter into a `1` and a lowercase letter into a `0`. The resulting map will look something like this: ``` 11100011 0011100 100111 ``` After this it makes the first tile of the starting track a `2` (only if it is already `1`) and loops through every tile checking adjacent tiles for a `2`. If a `1` has an adjacent `2` it becomes a `2`. The above map will become this if the runner started on the first line: ``` 22200011 0022200 100222 ``` The highest X index for a `2` becomes the result. I made a very minor oversight when I did the initial version of this and it cost me 36 bytes to hack at it until it worked, so there's probably a lot of improvements that could be made to this. *\*sigh\** ### Ungolfed ``` (t,s)=> [ // Decode run-length encoded string into an array of track lanes a=[], // a = array of track line strings, 0 = air, 1 = tiles t.match(/\d+(.)(\d+\1)*/gi) // regex magic that separates pairs by their letter .map(l=> // for each line of pairs a[ // add the tiles to the array c=l.match`[A-Z]`+"", // c = pair character n=c.charCodeAt(), // n = index of line c==s?i=n:n // if this line is the starting line, set i ]=l[r="replace"](/\d+./g,p=> // match each pair, p = pair (p.slice(-1)<"a" ?"1":"0").repeat( // repeat 0 for air or 1 for ground parseInt(p) // cast of match would return NaN because of the ) // letter at the end but parseInt works fine ), i= // i = index of starting line, initialise as invalid o=-1 // o = output (max value of x) ), // Find all positions that are possible for the runner to get to ...a.join``, // add every letter of the track lines to an array a[i]?a[i]=a[i][r](/^1/,2):0 // set the starting tile to 2 if it is already 1 ].map(_=> // loop for the amount of tiles, this is usually way // more than necessary but allows for hard to reach // tiles to be parsed a.map((l,y)=> // for each line l at index y a[y]=l[r](/1/g,(c,x)=> // for each character c at index x // Replace a 1 with 2 if there is a 2 to above, below, left or right of it ((a[y-1]||s)[x]|(a[y+1]||s)[x]|l[x-1]|l[x+1])>1? (x>o?o=x:0,2):c // set o to max value of x for a 2 tile ) ) ) &&o+1 // return o + 1 ``` ## Test Bonus: Output includes the parsed map! ``` var solution = (t,s)=>[a=[],t.match(/\d+(.)(\d+\1)*/gi).map(l=>a[c=l.match`[A-Z]`+"",n=c.charCodeAt(),c==s?i=n:n]=l[r="replace"](/\d+./g,p=>(p.slice(-1)<"a"?"1":"0").repeat(parseInt(p))),i=o=-1),...a.join``,a[i]?a[i]=a[i][r](/^1/,2):0].map(_=>a.map((l,y)=>a[y]=l[r](/1/g,(c,x)=>((a[y-1]||s)[x]|(a[y+1]||s)[x]|l[x-1]|l[x+1])>1?(x>o?o=x:0,2):c)))&&o+1 function generateMap() { var start = 0; a.some((l, i) => l ? start = i : 0); var end = 0; a.map((l, i) => l && i <= 90 ? end = i : 0); for(var output = "", i = start; i < end + 1; i++) output += String.fromCharCode(i) + ") " + (a[i] || "") + "\n"; return output; } ``` ``` Track = <input type="text" id="track" value="2A1b1B2C1D3E" /><br /> Starting Letter = <input type="text" id="start" value="A" /><br /> <button onclick="result.textContent=solution(track.value,start.value)+'\n\n'+generateMap()">Go</button> <pre id="result"></pre> ``` [Answer] ## Perl, ~~231~~ ~~219~~ ~~203~~ ~~192~~ 189 bytes *includes +1 for `-p`* ``` sub f{my($l,$p,$m)=@_;map{$m=$_>$m?$_:$m}f($l,$p+1)+1,f($l-1,$p),f($l+1,$p),f($l,$p-1)-1if$L[$l][$p]&&!$V{$l}{$p}++;$m}s/(\d+)(.)\s*/push@{$L[ord$2&~32]},(0|$2lt'a')x$1;()/ge;$_=0|f(ord,0) ``` ## Less golfed: ``` sub f{ # this is a recursive function, so we need locals. my($l,$p,$m)=@_; # in: lane, position; local: max path length map{ $m = $_ > $m ? $_ : $m # update max } f( $l, $p+1 )+1, # same lane, forward f( $l-1, $p ), # left lane, same pos f( $l+1, $p ), # right lane, same pos f( $l, $p-1 )-1 # same lane, backtrack if $L[$l][$p] # check if there's road here && !$V{$l}{$p}++ # and we've not visited this point before. ; $m # return the max } s/(\d+)(.)\s*/ # Parse RLE pattern, strip starting lane separator push@{ $L[ord$2&~32] } # index @L using uppercase ascii-code, access as arrayref ,(0|$2lt'a')x$1 # unpack RLE as bitstring ;() # return empty list for replacement /gex; # (x for ungolfing) # $_ now contains trailing data: the start lane. $_ = # assign output for -p 0| # make sure we print 0 instead of undef/nothing f(ord,0) # begin calculation at start of current lane ``` ## Running Store the *code above* in a file (say `231.pl`). Input in the form of `(\d+\w)+ *\w`. Example: inputting track `4A5B4c3C` and lane `A`: ``` echo 4A5B4c3C A | perl -p 231.pl ``` ## TestSuite (not golfed) ``` printf "==== Testing %s\n", $file = shift // '231.pl'; sub t{ my($input,$expect) = @_; # $input =~ s/\s//g; printf "TEST %-20s -> %-3s: ", $input, $expect; $output = `echo $input | perl -p $file`; printf "%-3s %s\n", $output, $output == $expect ? " PASS" : " FAIL: $output != $expect"; } t("4A5B4c3C A", 7); t("4A5B4c3C C", 0); t("4A2B3D D", 3); t("4A4a4A3b6B5C A", 12); t("4A4a4A3b6B5C B", 0); t("4A4a4A3b6B5C C", 12); t("12M4n10N11O M", 14 ); t("4A5B1b2B4c3C A", 8); t("1a2A2a2B1c1C1d3D B", 4 ); t("2A1b1B2C1D3E A", 3 ); t("10A9b1B8c2C9D1E11F A", 11); ``` * *update 219* save 12 bytes by reworking array indices. * *update 203* Save 16 bytes by refactoring recursion. * *update 192* save 11 bytes by eliminating the `@L=map{[/./g]}@L` postprocessing. * *update 189* save 3 bytes by postfixing `if` using `map` instead of `for`. ]
[Question] [ ## About the Series First off, you may treat this like any other code golf challenge, and answer it without worrying about the series at all. However, there is a leaderboard across all challenges. You can find the leaderboard along with some more information about the series [in the first post](https://codegolf.stackexchange.com/q/45302/8478). Although I have a bunch of ideas lined up for the series, the future challenges are not set in stone yet. If you have any suggestions, please let me know [on the relevant sandbox post](http://meta.codegolf.stackexchange.com/a/4750/8478). ## Hole 6: Roll a d20 A very common die in table-top RPGs is the twenty-sided die (an [icosahedron](https://en.wikipedia.org/wiki/Regular_icosahedron), commonly known as **d20**). It is your task to roll such a die. However, if you were just returning a random number between 1 and 20, that would be a bit trivial. So your task is to generate a random net for a given die. We'll use the following net: [![enter image description here](https://i.stack.imgur.com/nCJeQ.png)](https://i.stack.imgur.com/nCJeQ.png) It's a triangle strip, so it can be easily represented as a list of integers. E.g. if you are given the input: ``` [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] ``` That would correspond to the following die (fun fact: this is the net used by [Magic: the Gathering](https://en.wikipedia.org/wiki/Magic:_The_Gathering) life counters/spin-down dice). [![enter image description here](https://i.stack.imgur.com/1qB3w.png)](https://i.stack.imgur.com/1qB3w.png) However, this is not the only net representing this die. Depending on how we unroll the faces, there are 60 different nets. Here are two more: ``` [1, 8, 9, 10, 2, 3, 4, 5, 6, 7, 17, 18, 19, 11, 12, 13, 14, 15, 16, 20] [10, 9, 18, 19, 11, 12, 3, 2, 1, 8, 7, 17, 16, 20, 13, 14, 4, 5, 6, 15] ``` Or graphically (I didn't rotate the face labels for simplicity): [![enter image description here](https://i.stack.imgur.com/zjmwU.png)](https://i.stack.imgur.com/zjmwU.png) [![enter image description here](https://i.stack.imgur.com/eqj4s.png)](https://i.stack.imgur.com/eqj4s.png) ## The Challenge Given an a list of integers representing a die (as described above) and an integer `N`, output `N` independently, uniformly random d20 nets corresponding to the given die. (That is, each of the 60 possible nets should have the same probability of being generated.) Of course, due to the technical limitations of PRNGs, perfect uniformity will be impossible. For the purpose of assessing uniformity of your submission, the following operations will be regarded as yielding perfectly uniform distributions: * Obtaining a number from a PRNG (over any range), which is documented to be (approximately) uniform. * Mapping a uniform distribution over a larger set of numbers onto a smaller set via modulo or multiplication (or some other operation which distributes values evenly). The larger set has to contain at least 1024 times as many possible values as the smaller set. Given these assumptions your algorithm must yield a perfectly uniform distribution. Your program should be able to generate 100 nets in less than a second (so don't try generating random nets until one corresponds to the die given above). You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. Input and output may be in any convenient, unambiguous, flat list format. You may assume that the face values of the d20 are distinct, positive integers, which fit into your language's natural integer type. This is code golf, so the shortest submission (in bytes) wins. And of course, the shortest submission per user will also enter into the overall leaderboard of the series. ## Sample Outputs For the input ``` [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] ``` The 60 possible nets (provided I didn't make a mistake), in no particular order, are: ``` [11, 10, 9, 18, 19, 20, 13, 12, 3, 2, 1, 8, 7, 17, 16, 15, 14, 4, 5, 6] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] [8, 7, 17, 18, 9, 10, 2, 1, 5, 6, 15, 16, 20, 19, 11, 12, 3, 4, 14, 13] [3, 12, 13, 14, 4, 5, 1, 2, 10, 11, 19, 20, 16, 15, 6, 7, 8, 9, 18, 17] [3, 4, 5, 1, 2, 10, 11, 12, 13, 14, 15, 6, 7, 8, 9, 18, 19, 20, 16, 17] [11, 19, 20, 13, 12, 3, 2, 10, 9, 18, 17, 16, 15, 14, 4, 5, 1, 8, 7, 6] [4, 14, 15, 6, 5, 1, 2, 3, 12, 13, 20, 16, 17, 7, 8, 9, 10, 11, 19, 18] [2, 10, 11, 12, 3, 4, 5, 1, 8, 9, 18, 19, 20, 13, 14, 15, 6, 7, 17, 16] [4, 5, 1, 2, 3, 12, 13, 14, 15, 6, 7, 8, 9, 10, 11, 19, 20, 16, 17, 18] [10, 2, 1, 8, 9, 18, 19, 11, 12, 3, 4, 5, 6, 7, 17, 16, 20, 13, 14, 15] [3, 2, 10, 11, 12, 13, 14, 4, 5, 1, 8, 9, 18, 19, 20, 16, 15, 6, 7, 17] [7, 8, 1, 5, 6, 15, 16, 17, 18, 9, 10, 2, 3, 4, 14, 13, 20, 19, 11, 12] [13, 12, 11, 19, 20, 16, 15, 14, 4, 3, 2, 10, 9, 18, 17, 7, 6, 5, 1, 8] [16, 15, 14, 13, 20, 19, 18, 17, 7, 6, 5, 4, 3, 12, 11, 10, 9, 8, 1, 2] [15, 16, 17, 7, 6, 5, 4, 14, 13, 20, 19, 18, 9, 8, 1, 2, 3, 12, 11, 10] [20, 13, 12, 11, 19, 18, 17, 16, 15, 14, 4, 3, 2, 10, 9, 8, 7, 6, 5, 1] [5, 4, 14, 15, 6, 7, 8, 1, 2, 3, 12, 13, 20, 16, 17, 18, 9, 10, 11, 19] [10, 11, 12, 3, 2, 1, 8, 9, 18, 19, 20, 13, 14, 4, 5, 6, 7, 17, 16, 15] [4, 3, 12, 13, 14, 15, 6, 5, 1, 2, 10, 11, 19, 20, 16, 17, 7, 8, 9, 18] [19, 20, 13, 12, 11, 10, 9, 18, 17, 16, 15, 14, 4, 3, 2, 1, 8, 7, 6, 5] [1, 8, 9, 10, 2, 3, 4, 5, 6, 7, 17, 18, 19, 11, 12, 13, 14, 15, 16, 20] [8, 1, 5, 6, 7, 17, 18, 9, 10, 2, 3, 4, 14, 15, 16, 20, 19, 11, 12, 13] [18, 9, 8, 7, 17, 16, 20, 19, 11, 10, 2, 1, 5, 6, 15, 14, 13, 12, 3, 4] [12, 3, 2, 10, 11, 19, 20, 13, 14, 4, 5, 1, 8, 9, 18, 17, 16, 15, 6, 7] [2, 3, 4, 5, 1, 8, 9, 10, 11, 12, 13, 14, 15, 6, 7, 17, 18, 19, 20, 16] [10, 9, 18, 19, 11, 12, 3, 2, 1, 8, 7, 17, 16, 20, 13, 14, 4, 5, 6, 15] [9, 8, 7, 17, 18, 19, 11, 10, 2, 1, 5, 6, 15, 16, 20, 13, 12, 3, 4, 14] [16, 17, 7, 6, 15, 14, 13, 20, 19, 18, 9, 8, 1, 5, 4, 3, 12, 11, 10, 2] [17, 7, 6, 15, 16, 20, 19, 18, 9, 8, 1, 5, 4, 14, 13, 12, 11, 10, 2, 3] [1, 5, 6, 7, 8, 9, 10, 2, 3, 4, 14, 15, 16, 17, 18, 19, 11, 12, 13, 20] [9, 18, 19, 11, 10, 2, 1, 8, 7, 17, 16, 20, 13, 12, 3, 4, 5, 6, 15, 14] [16, 20, 19, 18, 17, 7, 6, 15, 14, 13, 12, 11, 10, 9, 8, 1, 5, 4, 3, 2] [5, 1, 2, 3, 4, 14, 15, 6, 7, 8, 9, 10, 11, 12, 13, 20, 16, 17, 18, 19] [8, 9, 10, 2, 1, 5, 6, 7, 17, 18, 19, 11, 12, 3, 4, 14, 15, 16, 20, 13] [13, 20, 16, 15, 14, 4, 3, 12, 11, 19, 18, 17, 7, 6, 5, 1, 2, 10, 9, 8] [6, 15, 16, 17, 7, 8, 1, 5, 4, 14, 13, 20, 19, 18, 9, 10, 2, 3, 12, 11] [6, 5, 4, 14, 15, 16, 17, 7, 8, 1, 2, 3, 12, 13, 20, 19, 18, 9, 10, 11] [7, 6, 15, 16, 17, 18, 9, 8, 1, 5, 4, 14, 13, 20, 19, 11, 10, 2, 3, 12] [19, 18, 17, 16, 20, 13, 12, 11, 10, 9, 8, 7, 6, 15, 14, 4, 3, 2, 1, 5] [14, 15, 6, 5, 4, 3, 12, 13, 20, 16, 17, 7, 8, 1, 2, 10, 11, 19, 18, 9] [17, 18, 9, 8, 7, 6, 15, 16, 20, 19, 11, 10, 2, 1, 5, 4, 14, 13, 12, 3] [6, 7, 8, 1, 5, 4, 14, 15, 16, 17, 18, 9, 10, 2, 3, 12, 13, 20, 19, 11] [14, 13, 20, 16, 15, 6, 5, 4, 3, 12, 11, 19, 18, 17, 7, 8, 1, 2, 10, 9] [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] [7, 17, 18, 9, 8, 1, 5, 6, 15, 16, 20, 19, 11, 10, 2, 3, 4, 14, 13, 12] [15, 6, 5, 4, 14, 13, 20, 16, 17, 7, 8, 1, 2, 3, 12, 11, 19, 18, 9, 10] [9, 10, 2, 1, 8, 7, 17, 18, 19, 11, 12, 3, 4, 5, 6, 15, 16, 20, 13, 14] [2, 1, 8, 9, 10, 11, 12, 3, 4, 5, 6, 7, 17, 18, 19, 20, 13, 14, 15, 16] [12, 13, 14, 4, 3, 2, 10, 11, 19, 20, 16, 15, 6, 5, 1, 8, 9, 18, 17, 7] [17, 16, 20, 19, 18, 9, 8, 7, 6, 15, 14, 13, 12, 11, 10, 2, 1, 5, 4, 3] [18, 17, 16, 20, 19, 11, 10, 9, 8, 7, 6, 15, 14, 13, 12, 3, 2, 1, 5, 4] [18, 19, 11, 10, 9, 8, 7, 17, 16, 20, 13, 12, 3, 2, 1, 5, 6, 15, 14, 4] [11, 12, 3, 2, 10, 9, 18, 19, 20, 13, 14, 4, 5, 1, 8, 7, 17, 16, 15, 6] [15, 14, 13, 20, 16, 17, 7, 6, 5, 4, 3, 12, 11, 19, 18, 9, 8, 1, 2, 10] [19, 11, 10, 9, 18, 17, 16, 20, 13, 12, 3, 2, 1, 8, 7, 6, 15, 14, 4, 5] [12, 11, 19, 20, 13, 14, 4, 3, 2, 10, 9, 18, 17, 16, 15, 6, 5, 1, 8, 7] [20, 16, 15, 14, 13, 12, 11, 19, 18, 17, 7, 6, 5, 4, 3, 2, 10, 9, 8, 1] [13, 14, 4, 3, 12, 11, 19, 20, 16, 15, 6, 5, 1, 2, 10, 9, 18, 17, 7, 8] [5, 6, 7, 8, 1, 2, 3, 4, 14, 15, 16, 17, 18, 9, 10, 11, 12, 13, 20, 19] [14, 4, 3, 12, 13, 20, 16, 15, 6, 5, 1, 2, 10, 11, 19, 18, 17, 7, 8, 9] ``` For any other net, simply replace every occurrence of `i` with the `i`th number in the input (where `i` is 1-based). ## Related Challenges * [Hunt the Wumpus](https://codegolf.stackexchange.com/q/26128/8478) * [Drawing 3d nets - Platonic solids](https://codegolf.stackexchange.com/q/10662/8478) # Leaderboard **[The first post of the series generates a leaderboard.](https://codegolf.stackexchange.com/q/45302/8478)** To make sure that your answers show up, please start every 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 ``` *(The language is not currently shown, but the snippet does require and parse it, and I may add a by-language leaderboard in the future.)* [Answer] # Ruby, 160 bytes (rev B) 17 bytes saved thanks to suggestions from Martin Büttner. ``` ->a,n{n.times{k=rand 60 %w{ABCD@GHIJKLMNEFPQRSO PFENOSRQHG@DCMLKJIAB GFPQHIA@DENOSRJKBCML}.map{|b|k.times{a=b.chars.map{|i|a[i.ord-64]}}} k>29&&a.reverse! p a}} ``` # Ruby, 177 bytes (rev A) ``` ->n,a{n.times{k=rand(60) h=->b{k.times{|j|a=(0..19).map{|i|a[b[i].ord-64]}}} h['ABCD@GHIJKLMNEFPQRSO'] h['PFENOSRQHG@DCMLKJIAB'] h['GFPQHIA@DENOSRJKBCML'] k>29&&a.reverse! p a}} ``` **Explanation** It is possible to generate all possible orientations by rotations about one face (3-fold), one vertex (5-fold) and two edges (2-fold). But not just any face and edges. The axes must have the correct relationship and the rotations must be done in the correct order, or strange things can happen. This is the way I did it (though I understand Martin did it differently.) All orientations of a tetrahedron can be generated by combinations of the following three symmetry operations: a)Rotation about two 2-fold axes at right through the midpoints of the edges (these are at right angles to each other. If we multiply them together we discover a third 2-fold axis through the remaining pair of edges.) b) Rotation about a 3 fold axis diagonal to the 2-fold axes, passing through a vertex and a face. The icosahedron's symmetry is a superset of that of the tetrahedron. In the image below from <https://en.wikipedia.org/wiki/Icosahedron>, the yellow faces and red faces define two different tetrahedra (or alternatively a single octahedron), while the edges common to two blue faces are in three pairs at right angles (and lie on the faces of a cube.) All orientations of the icosahedron can be generated by those symmetry operations mentioned above plus an additional 5-fold operation. [![enter image description here](https://i.stack.imgur.com/GBjI3.png)](https://i.stack.imgur.com/GBjI3.png) The rotations about three out of the four axes mentioned above are represented by the magic strings between the `''` marks. Rotation about the second 2-fold axis is different, and can be done just by reversing the array `a[]`. Ungolfed in test program: ``` f=->a,n{ n.times{ #Iterate n times, using the result from the previous iteration to generate the next k=rand(60) #pick a random number h=->b{ #helper function taking a string representing a transformation k.times{|j| #which is performed on a using the number of times according to k a=(0..19).map{|i|a[b[i].ord-64]} } } #Rotate about axes k times (one 5-fold, one 3-fold, two 2-fold) #The first three axes have coprime rotation orders #And the rotations themselves take care of the modulus operation so no need to add it. #The second 2-fold rotation is equivalent to reversing the order #And is applied to the last 30 numbers as it is not coprime with the first 2-fold rotation. h['ABCD@GHIJKLMNEFPQRSO'] #rotate k times about 5-fold axis h['PFENOSRQHG@DCMLKJIAB'] #rotate k times about 3-fold axis h['GFPQHIA@DENOSRJKBCML'] #rotate k times about 2-fold axis k>29&&a.reverse! p a } } z=(1..20).map{|i|i} f[z,50] ``` **Alternative solution 131 bytes (Invalid due to binary random walk approach, only gives an approximately correct distribution.)** ``` ->a,n{(n*99).times{|i|s=['@DEFGHIABCMNOPQRJKLS','ABCD@GHIJKLMNEFPQRSO'][rand(2)] a=(0..19).map{|i|a[s[i].ord-64]} i%99==98&&p(a)}} ``` This is a scramble (much like the programs used to scramble rubik's cube.) The specific rotations I use are two of the most obvious ones: -A 120 degree rotation (about faces 1 and 20 per the first diagram) -A 72 degree rotation (about the vertices common to 1,2,3,4,5 and 16,17,18,19,20 per the first diagram.) we flip a coin 99 times, and each time we perform one of these two rotations depending if it is heads or tails. Note that alternating these deterministically leads to fairly short sequences. For example, with the correct rotation senses, a 180 degree rotation can be produced with a period of just 2. [Answer] # IA-32 machine code, 118 bytes Hexdump: ``` 60 33 c0 51 8b 74 24 28 8b fa 6a 05 59 f3 a5 e8 21 00 00 00 20 c4 61 cd 6a 33 00 84 80 ad a8 33 32 00 46 20 44 8e 48 61 2d 2c 33 32 4a 00 21 20 a7 a2 90 8c 00 5b b1 04 51 0f c7 f1 83 e1 1f 49 7e f7 51 8b f2 56 8d 7c 24 e0 b1 14 f3 a4 5f 8b f3 ac 8b ee d4 20 86 cc e3 0a 56 8d 74 04 e0 f3 a4 5e eb ed 59 e2 db 8b dd 59 e2 cc 59 83 c2 14 e2 91 61 c2 04 00 ``` It's a bit long, so some explanations go first. I used almost the same algorithm as the existing [answer by Level River St](https://codegolf.stackexchange.com/a/66336/25315). To make my answer different, I took other basic permutations, which don't necessarily have intuitive geometrical meaning, but are somehow more convenient. The code basically has to generate a permutation, which is a sequential application of the following: 1. A permutation of order 3, which I call `p3`, applied 0...2 times 2. A permutation of order 2, which I call `q2`, applied 0 or 1 times 3. A permutation of order 5, which I call `p5`, applied 0...4 times 4. Another permutation of order 2, which I call `p2`, applied 0 or 1 times There are many possible choices for these permutations. One of them is as follows: ``` p3 = [0 4 5 6 7 8 9 1 2 3 13 14 15 16 17 18 10 11 12 19] q2 = [4 5 6 7 0 1 2 3 13 14 15 16 17 8 9 10 11 12 19 18] p5 = [6 7 0 4 5 14 15 16 17 8 9 1 2 3 13 12 19 18 10 11] p2 = [1 0 7 8 9 10 11 2 3 4 5 6 16 17 18 19 12 13 14 15] ``` This choice is better than others because the permutations here have long runs of sequential indices, which can be compressed by run-length encoding - only 29 bytes for the 4 permutations. To simplify the generation of random numbers, I chose the powers (how many times each permutation is applied) in the range 1...30 for all of them. This leads to much extra work in the code, because e.g. `p3` becomes an identity permutation each time it's multiplied by itself 3 times. However, the code is smaller that way, and as long as the range is divisible by 30, the output will have uniform distribution. Also, powers should be positive so the run-length decoding operation is performed at least once. The code has 4 nested loops; the outline is like this: ``` void doit(int n, uint8_t* output, const uint8_t input[20]) { uint8_t temp[20]; n_loop: for i_n = 0 ... n { memcpy(output, input, 20); expr_loop: for i_expr = 0 ... 3 { power = rand(1 ... 30); power_loop: for i_power = 0 ... power { memcpy(temp, output, 20); output_index = 0; perm_loop: do while length > 0 { index = ...; // decode it length = ...; // decode it memcpy(output + output_index, temp + index, length); output_index += length; } } } output += 20; } } ``` I hope this pseudo-code is clearer than the inline-assembly code below. ``` _declspec(naked) void __fastcall doit(int n, uint8_t* output, const uint8_t* input) { _asm { pushad xor eax, eax n_loop: push ecx ; copy from input to output mov esi, [esp + 0x28] mov edi, edx push 5 pop ecx rep movsd call end_of_data #define rl(index, length) _emit(length * 32 + index) rl(0, 1) rl(4, 6) rl(1, 3) rl(13, 6) rl(10, 3) rl(19, 1) _emit(0) rl(4, 4) rl(0, 4) rl(13, 5) rl(8, 5) rl(19, 1) rl(18, 1) _emit(0) rl(6, 2) rl(0, 1) rl(4, 2) rl(14, 4) rl(8, 2) rl(1, 3) rl(13, 1) rl(12, 1) rl(19, 1) rl(18, 1) rl(10, 2) _emit(0) rl(1, 1) rl(0, 1) rl(7, 5) rl(2, 5) rl(16, 4) rl(12, 4) _emit(0) end_of_data: pop ebx ; load the address of the encoded data mov cl, 4 expr_loop: push ecx make_rand: rdrand ecx and ecx, 31 dec ecx jle make_rand ; input: ebx => encoding of permutation ; output: ebp => encoding of next permutation power_loop: push ecx ; copy from output to temp mov esi, edx push esi lea edi, [esp - 0x20] mov cl, 20 rep movsb pop edi ; ebx => encoding of permutation ; edi => output mov esi, ebx perm_loop: ; read a run-length lodsb mov ebp, esi _emit(0xd4) ; divide by 32, that is, split into _emit(32) ; index (al) and length (ah) xchg cl, ah ; set ecx = length; also makes eax = al jecxz perm_loop_done ; zero length => done decoding push esi lea esi, [esp + eax - 0x20] rep movsb pop esi jmp perm_loop perm_loop_done: pop ecx loop power_loop mov ebx, ebp pop ecx loop expr_loop pop ecx add edx, 20 loop n_loop popad ret 4 } } ``` Some fun implementation details: * I used indented assembly, like in high-level languages; otherwise the code would be an incomprehensible mess * I use `call` and subsequent `pop` to access data (encoded permutations) stored in code * The `jecxz` instruction conveniently lets me use a zero byte as termination for the run-length decoding process * By luck, the number 30 (2 \* 3 \* 5) is almost a power of 2. This lets me use short code to generate a number in the range 1...30: ``` and ecx, 31 dec ecx jle make_rand ``` * I use a "general-purpose division" instruction (`aam`) to separate a byte into bit fields (3-bit length and 5-bit index); by luck, at that position in code, `cl = 0`, so I benefit from both "sides" of `xchg` ]
[Question] [ # Finding the Deadlock When programming a multithreading application one must take good care to avoid deadlocking the various threads when accessing shared resources. A [deadlock](http://en.wikipedia.org/wiki/Deadlock) occurs when a thread attempts to access a resource that's locked in another thread at the same time that the other thread is trying to access a resource locked by the first. This is the simple case, but it can get more complex with longer resource chains. ## The challenge You should write a program or function that can detect a possible deadlock situation in a list of the resources accessed by each thread. This is code-golf, so shortest answer in bytes wins. Every thread is started at the same time, but after that they can run at any combination of interleaving. If there are 2 threads with 4 actions each, it could be run as (where each number is an action taken by the thread with that id) `1,1,1,1,2,2,2,2`, `2,2,2,2,1,1,1,1`, `1,2,1,2,1,2,1,2`, `1,1,2,2,2,2,1,1`, or any other possible combination. ## Input You will receive, via STDIN, function parameter, or closest alternative, a list of strings. Each string will be in the format `+a` `-b`. Every one of this strings represents the locking(`+`)/unlocking(`-`) of a resource by the thread. Between every thread will be a `---` separator. It is guaranteed that a thread won't try to lock a resource it already has locked, and that all threads will explicitly unlock all the resources they have locked before exiting. Following is an example to demonstrate: ``` +a # Lock resource a +b # Lock resource b -a # Unlock resource a -b # Unlock resource b --- # Thread separator +b # Lock resource b -b # Unlock resource b ``` ## Output The output shall be falsy if the input doesn't contain any deadlock possibility, and truthy if it contains a possible deadlock situation. For example: * `true` * `false` * `1` * `0` are all valid outputs, but anything clearly defined as truthy/falsy will be accepted. ## Examples ``` +a -a --- +a -a ``` Output: `false` --- ``` +a +b -b -a --- +b +a -a -b ``` Output `true` Deadlock when trying to acquire `b,a` respectively for threads `1,2` --- ``` +a +b -a -b --- +a +b -b -a ``` Output `false` --- ``` +a +b -b -a --- +b +c -c -b --- +c +a -a -c ``` Output: `true` Deadlock in threads 1,2,3 when trying to acquire `b,c,a` respectively. --- <http://pastebin.com/vMYRZxtW> Output `false` --- <http://pastebin.com/V5MVgNgS> Output `true` Deadlock in threads 1,2,3 when trying to aquire `b,d,a` respectively. --- Of course this could get a lot more complex, with more threads, more resources for each one, and so on, but I believe these tests cover the basics. ## Bonus Since it's very very sad when you find deadlock situations when writing a program, there is a -8 byte bonus to answers outputting `:(` and `:)` as truthy/falsy respectively. [Answer] # Python - ~~586~~ ~~539~~ ~~524~~ ~~501~~ 485 bytes - 8 = 477 Indentation levels: ``` 1: 1 space 2: 1 tab 3: 1 tab + 1 space 4: 2 tabs ``` -- ``` import sys V=set() t=[[[]]] for r in sys.stdin: r=r.strip() if'---'==r:t.append([[]]) else:v=r[1:];V.add(v);l=t[-1][-1];t[-1].append(l+[v]if'+'==r[0]else filter(lambda x:x!=v,l)) s=lambda l:s(l[1:])+map(lambda x:(l[0],x),l[1:])if 1<len(l)else[] E=reduce(set.union,map(lambda x:set(sum(map(s,x),[])),t),set()) for v in V: k=set();q=[v] while 0<len(q): u=q.pop(0) if u in k:continue k.add(u) for x,y in E: if u==x: if y in k:print':(';sys.exit() else:q.append(y) print':)' ``` [Answer] # Python 2 - 227 Basically makes sure there are no loops of 'precedence'. For example in the second test, the first thread has a `a(b)` precedence and the second thread has a `b(a)` precedence. I was thinking about rewriting this in Pyth as I think it would work well with all the itertools operations, but converting the regex will take some work so for now I'll post this and maybe try to convert it and post another answer later. ``` from itertools import* import re f=lambda t:any(re.search(r"(.)((.)\3)+\1",''.join(p))for i in product(*[[m.group(1)+m.group(2)for m in re.finditer(r"(\w).*(\w).*\2.*\1",e,16)]for e in t.split('---')])for p in permutations(i)) ``` ]
[Question] [ On puzzling SE there are what are called ["matchstick problems"](https://puzzling.stackexchange.com/questions/tagged/matches) in which math is written in match sticks and you are allowed to move a certain number of them to get a certain property. In this question we will be considering only integers represented in a 7-segment display format. Here are all 10 digits in that format: ``` __ __ __ __ __ __ __ __ | | | __| __| |__| |__ |__ | |__| |__| |__| | |__ __| | __| |__| | |__| __| ``` Each segment of the display is one "match-stick" which can be moved independently of the rest of the number. Matchsticks are indivisible and indestructible, the cannot be broken or removed by any means. A common puzzle is to take a number given in base 10 and try to make the largest number possible in a given number of moves. A move is considered to be one movement of a matchstick from any occupied slot to any other unoccupied slot. You are perfectly permitted to make new digits on either side of the number, for example 0 can be made into 77 give 3 moves ``` __ __ __ __ __ __ __ | | | | | | | | | |__| , __| , | , | | ``` However you may not make one slot into 2 or make new slots between existing ones, for example turning a 4 into an 11 in the middle of a number or inserting new digits in between existing ones. Each move need not make a proper number but the final result should be a proper number in the base 10 seven segment display. You need not use every move if you do not wish to. Unlike on puzzling this is a [tag:close ended question] you *may not* use any operators (multiplication, exponentiation, etc.) or mathematical constants (Pi, Graham's number, etc.) in your answers. ## Task Write a program or function that takes a number and a number of moves as input and returns the largest number that can be made with that many moves on the original number. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored in bytes, with less bytes being better. ## Test Cases ``` n, moves -> max 0, 1 -> 9 0, 3 -> 77 0, 4 -> 111 8, 3 -> 74 220, 1 -> 320 220, 2 -> 520 220, 3 -> 7227 220, 4 -> 22111 220, 5 -> 32111 747, 1 -> 747 747, 2 -> 7171 747, 3 -> 7711 ``` [Related](https://codegolf.stackexchange.com/questions/50933/matchstick-equations) [Answer] ## JavaScript (ES6), ~~297~~ ~~286~~ ~~279~~ 267 bytes Takes input in currying syntax `(s)(k)`, where ***s*** is an array of digit characters and ***k*** is the number of moves (integer). ``` s=>k=>(B=(n,b=0)=>n?B(n^n&-n,b+1):b,b=[...p='u"[k,iy#}m'].map(c=>c.charCodeAt()+2),r=[],g=(n,d='')=>n?n>0&&b.map((v,i)=>g(n-B(v),d+i)):r.push(d))(s.reduce((s,c)=>s+B(b[c]),M=0))&&b.map((_,j)=>r.map(n=>M=[...n+p].reduce((t,d,i)=>t+B(b[d]^b[s[i-j]]),0)>k*2|+n<M?M:n))|M ``` ### Test cases ``` let f= s=>k=>(B=(n,b=0)=>n?B(n^n&-n,b+1):b,b=[...p='u"[k,iy#}m'].map(c=>c.charCodeAt()+2),r=[],g=(n,d='')=>n?n>0&&b.map((v,i)=>g(n-B(v),d+i)):r.push(d))(s.reduce((s,c)=>s+B(b[c]),M=0))&&b.map((_,j)=>r.map(n=>M=[...n+p].reduce((t,d,i)=>t+B(b[d]^b[s[i-j]]),0)>k*2|+n<M?M:n))|M console.log("0 / 1 -> " + f([..."0" ])(1)) // -> 9 console.log("0 / 3 -> " + f([..."0" ])(3)) // -> 77 console.log("0 / 4 -> " + f([..."0" ])(4)) // -> 111 console.log("8 / 3 -> " + f([..."8" ])(3)) // -> 74 console.log("220 / 1 -> " + f([..."220"])(1)) // -> 320 console.log("220 / 2 -> " + f([..."220"])(2)) // -> 520 console.log("220 / 3 -> " + f([..."220"])(3)) // -> 7227 console.log("220 / 4 -> " + f([..."220"])(4)) // -> 22111 console.log("220 / 5 -> " + f([..."220"])(5)) // -> 32111 console.log("747 / 1 -> " + f([..."747"])(1)) // -> 747 console.log("747 / 2 -> " + f([..."747"])(2)) // -> 7171 console.log("747 / 3 -> " + f([..."747"])(3)) // -> 7711 ``` --- ### How? **Shape data and helper function** * The array ***b*** describes the shapes of the digits as 7-bit integers, where each bit is a segment: [![7-segment](https://i.stack.imgur.com/sorrO.png)](https://i.stack.imgur.com/sorrO.png) For instance, the shape of "7" is 0b0100101 = 37. * The helper function ***B()*** returns the number of 1's in the binary representation of a given number: ``` B = (n, b = 0) => n ? B(n ^ n & -n, b + 1) : b ``` **Step #1** We first count the number of matchsticks used in the input number: ``` s.reduce((s, c) => s + B(b[c]), 0) ``` **Step #2** We pass this value to the recursive function ***g()***, which populates a list ***r*** with all numbers that can be built with exactly this number of matchsticks: ``` g = (n, d = '') => n ? n > 0 && b.map((v, i) => g(n - B(v), d + i)) : r.push(d) ``` For instance, ***g(5)*** will load `[ '17', '2', '3', '5', '71' ]` into ***r***. **Step #3** We now have to select the highest number ***M*** in ***r*** which can actually be obtained from the input number, within the allowed number of moves ***k***. Because each number ***n*** in ***r*** uses exactly as many matchsticks as the input number ***s***, the number of moves required to transform ***s*** into ***n*** equals *half* the number of segment differences between each of their digits. The number of segment differences between two digits ***x*** and ***y*** is given by the number of 1's in the binary representation of ***b[x] XOR b[y]***. Finally, it's important to note that we need to try several possible digit alignments, because the first digit of ***s*** is not necessarily mapped to the first digit of ***n***. The shift between the digits is given by the variable ***j*** in the code. [Answer] # Mathematica, 188 ~~197~~ ~~200~~ ~~203~~ ~~170~~ ~~174~~ bytes *NOTE:* The code is still kind of buggy. I'm working on it. +30 bytes for bug ``` (p=PadLeft;q=IntegerDigits;g=Join@@(#~q~2~p~7&/@ToCharacterCode["w$]m.k{% o"][[1+q@#]])&;h=(v=g@#2~#~96-g@i~#~96;Tr@v==0&&Tr@Abs@v<=2#3)&;For[i=10^Tr@g@#,!h[p,##]&&!h[PadRight,##],--i];i)& ``` The character between `%` and `o` should be `0x7F` but SE won't allow it. You could click [pastebin link](https://pastebin.com/avNxPNPj) to copy the original code. The code takes a lot of time when there're more than 6-7 sticks. (You could modify the starting value of `i` to a smaller number to test it) ## Explanation `g` is a helper function converting digits into a list of stick representation (according to [here](https://codegolf.stackexchange.com/questions/68868/digital-clock-matches-puzzle)), such as `{1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1}` for `220`. `h` is a helper function to deal with left-padding and right-padding between two numbers. `f` iterates from `10^Tr@g@#` (upper limit) to `1` to look for a integer whose stick representation has a same quantity of `1 -> 0` and `0 -> 1` compared to the original number and the quantity is smaller or equal than second argument. ]
[Question] [ You've been given a bag of Skittles. Everybody knows that in order to appreciate the different flavors the most, you need to rotate between the flavors. ## Basics: 1. You can only eat 1 skittle at a time 2. The order that you eat your skittles *must* be periodic. 3. Each period cannot contain a particular flavor more than once. 4. Your bag only has so many skittles. You cannot eat more of a particular flavor of skittle than appears in your bag. 5. You want to eat as many skittles as you can (it may not always be possible) ## Examples: Lets say you start with 3 Red, 2 Blue, and 3 Green skittles: ``` R B G R B G R G Invalid: The last R must be followed by a B, not a G R B G R B G R Valid, but sub-optimal R R R Valid, but sub-optimal R G B R G B R G Valid and optimal G R B G R B G R Also valid and optimal (there are multiple good solutions) ``` # Input/Output * You are passed a non-empty list of positive integers for the color counts. (The above example would be `[3,2,3]`). * You need to return a list containing valid and optimal ordering. * Instead of using colors, you will use the indices from input list. (The last example output above would be `[2,0,1,2,0,1,2,0]`). * Your output may be 0-indexed or 1-indexed. My examples will be 0-indexed # Test Cases ``` 1 0 4 0 0 0 0 4 1 0 0 0 0 3 1 0 1 0 or 0 0 0 5 2 2 0 1 2 0 1 2 0 2 3 5 2 1 0 2 1 0 2 1 or 1 2 0 1 2 0 1 2 2 4 5 2 1 2 1 2 1 2 1 2 3 4 5 2 1 0 2 1 0 2 1 0 2 1 or 1 2 0 1 2 0 1 2 0 1 2 1 1 1 1 1 6 5 0 1 2 3 4 5 (lots of other solutions) 1 1 1 1 1 8 5 5 5 5 5 5 5 5 2 4 6 8 3 2 1 3 2 1 3 2 1 3 2 1 3 2 ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your solutions as short as possible in your favorite language! [Answer] ## JavaScript (ES6), ~~177~~ 175 bytes ``` a=>a.map((n,i)=>[n,l=i]).sort((a,b)=>a[0]-b[0]).reduce((P,x,i,a)=>(v=a.reduce((p,c,j)=>j<i?p:p+Math.min(c[0],x[0]+1),0))>m?[...Array(m=v)].map((_,k)=>a[l-k%(l+1-i)][1]):P,m=0) ``` ### Formatted and commented ``` a => a // given an array a: .map((n, i) => [n, l = i]) // map it to [value, index] arrays / set l = length - 1 .sort((a, b) => a[0] - b[0]) // sort it by values in ascending order .reduce((P, x, i, a) => // for each reference entry x at position i: (v = a.reduce((p, c, j) => // for each entry c at position j: j < i ? // if c is before x: p // keep the previous sum (which is 0) : // else: p + Math.min(c[0], x[0] + 1), // add minimum(value[j], value[i] + 1) 0 // initialize the sum at 0 )) > m ? // if the new sum v is better than our current best m: [...Array(m = v)].map((_, k) => // update m to v and update the result to an array a[l - k % (l + 1 - i)][1] // of length m filled with indices picked repeatedly ) // between i and l : // else: P, // keep the previous result m = 0 // start with best score m = 0 ) // the final result is returned by the outer reduce() ``` ### Used formula Below is a table showing how the formula `F(i, j) = minimum(value[j], value[i] + 1)` is working, here with `i = 0` and the input `[ 5, 2, 2 ]`. This formula can be interpreted as follows: for each Skittle type, we can select no more than the number of the least available type plus one. ``` j | Sorted | value[j] | F(0, j) | Selected | Output | input | | | Skittles | (starting from bottom left) ---+-----------+----------+---------+-----------------+----------------------------- 0 | 2 2 | 2 | 2 | [2] [2] | \ 1 | 1 1 | 2 | 2 | [1] [1] | > 0 1 2 0 1 2 0 2 | 0 0 0 0 0 | 5 | 3 | [0] [0] [0] 0 0 | / ``` ### Test cases ``` let f = a=>a.map((n,i)=>[n,l=i]).sort((a,b)=>a[0]-b[0]).reduce((P,x,i,a)=>(v=a.reduce((p,c,j)=>j<i?p:p+Math.min(c[0],x[0]+1),0))>m?[...Array(m=v)].map((_,k)=>a[l-k%(l+1-i)][1]):P,m=0) console.log(JSON.stringify(f([ 1 ]))); // 0 console.log(JSON.stringify(f([ 4 ]))); // 0 0 0 0 console.log(JSON.stringify(f([ 4, 1 ]))); // 0 0 0 0 console.log(JSON.stringify(f([ 3, 1 ]))); // 0 1 0 console.log(JSON.stringify(f([ 5, 2, 2 ]))); // 0 2 1 0 2 1 0 console.log(JSON.stringify(f([ 2, 3, 5 ]))); // 2 1 0 2 1 0 2 1 console.log(JSON.stringify(f([ 2, 4, 5 ]))); // 2 1 2 1 2 1 2 1 2 console.log(JSON.stringify(f([ 3, 4, 5 ]))); // 2 1 0 2 1 0 2 1 0 2 1 console.log(JSON.stringify(f([ 1, 1, 1, 1, 1, 6 ]))); // 5 4 3 2 1 0 5 console.log(JSON.stringify(f([ 1, 1, 1, 1, 1, 8 ]))); // 5 5 5 5 5 5 5 5 console.log(JSON.stringify(f([ 2, 4, 6, 8 ]))); // 3 2 1 3 2 1 3 2 1 3 2 1 3 2 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ċЀṢN ỤṚ;\Ṛẋ"‘Ṣ$ḣ"ÇLÞṪ ``` 1-based indexing. **[Try it online!](https://tio.run/nexus/jelly#@3@k@/CER01rHu5c5Mf1cPeShztnWccAiYe7upUeNcwACqs83LFY6XC7z@F5D3eu@v//f7SZjomOkY5FLAA)** ### How? Repeats each prefix of the indexes sorted by value descending one more time than would be achievable with the given bag of skittles, then removes the final skittle or skittles from each of these as necessary to make them achievable, and returns the one with the most skittles. The number that should be removed from one extra periodic repetition is just the number with the minimum count across that prefix. ``` ỤṚ;\Ṛẋ"‘Ṣ$ḣ"ÇLÞṪ - Main link e.g. [6,4,2,8] Ụ - grade up: sort indices by value [3,2,1,4] Ṛ - reverse [4,1,2,3] \ - cumulative reduce with ; - concatenation (get prefixes) [[4],[4,1],[4,1,2],[4,1,2,3]] Ṛ - reverse [[4,1,2,3],[4,1,2],[4,1],[4]] $ - last two links as a monad ‘ - increment [7,5,3,9] Ṣ - sort [3,5,7,9] " - zip with ẋ - list repetition [[4,1,2,3,4,1,2,3,4,1,2,3],[4,1,2,4,1,2,4,1,2,4,1,2,4,1,2],[4,1,4,1,4,1,4,1,4,1,4,1,4,1],[4,4,4,4,4,4,4,4,4]] Ç - call last link (1) as a monad [-1,-1,-1,-1] " - zip with ḣ - head list to (remove excess) [[4,1,2,3,4,1,2,3,4,1,2],[4,1,2,4,1,2,4,1,2,4,1,2,4,1],[4,1,4,1,4,1,4,1,4,1,4,1,4],[4,4,4,4,4,4,4,4]] Þ - sort by L - length [[4,4,4,4,4,4,4,4],[4,1,2,3,4,1,2,3,4,1,2],[4,1,4,1,4,1,4,1,4,1,4,1,4],[4,1,2,4,1,2,4,1,2,4,1,2,4,1]] Ṫ - tail [4,1,2,4,1,2,4,1,2,4,1,2,4,1] ċЀṢN - Link 1: head amounts (negative of skittle excess of each N+1 repeated period) Ṣ - sort [2,4,6,8] Ѐ - for each mapped over right argument ċ - count [1,1,1,1] N - negate [-1,-1,-1,-1] ``` [Answer] # Python3, ~~174~~ ~~172~~ 167 Bytes ## Idea Given e.g. 3 Red, 2 Blue, and 3 Green skittles one can arrange them in a grid, sorted by color and amount: ``` r g r g b r g b ``` If one tries to eat exactly i skittles, one can at least eat i\*c skittles in total, where c is the number of skittles in the r-th column, e.g. for i=2 one can at least eat 6 skittles. ``` r g # # # # # # ``` The only thing left to do is count how many additional skittles can be eaten by an incomplete period. ## Golfed ``` def f(a): r=range;f=m=0;s=r(len(a));b=sorted(zip(a,s))[::-1] for i in s: c=b[i][0];n=-~i*c+sum(c<e[0]for e in b) if n>m:f,m=i+1,n return[b[j%f][1]for j in r(m)] ``` ## Commented ``` def f(a): r = range; f = m = 0; - Some variables we need later on s = r(len(a)); - Integers from 0 to (num_skittles - 1) b = sorted(zip(a,s))[::-1] - Zip with s to remember initial order, then sort and reverse for i in s: c = b[i][0] n = (i+1)*c - If we attempt to eat i different skittles, we can surely eat (i+1)*c skittles. + sum(1 for e in b if e[0]>c) - The additional sum corresponds to an incomplete period. if n>m: - If a better way of eating skittles is found: f,m = i+1,n - update variables return [b[j%f][1] for j in r(m)] ``` [Try it online!](https://tio.run/nexus/python3#VU7bisMgEH3PVwyFpbqx0KQXlgTzIyJiUl0sqy2avuzPZ2fS7sKO6JnLOc5ZLs6DZ5Z3FWSZbfp0vZdR7vsiM/tyCUe8H2W55dld2He4MysK56rrdo2uwN8yBAgJCn4AkxxV0Gqv@yRZqBv@PtXlEVlDNEe0EYIHh4xh4ijAIg2x8yJKpIuEJtz8yEmN6vrmtWo0Ka@kzCxyXVWoMCbZ6IwBKWFjTLQhGbOh/QCzK/NkiysgQaFcqCNdQdlhfU@iFS1iKw7itOJxxcMLG/F7zv@qjxf3jJled5E12kXu/vY@bVDcc0gzK3NmNOBQwxa7uzUGzLbYoal/zjlflh8 "Python 3 – TIO Nexus") Edit: Replaced `(i+1)` with `-~i` to save 2 bytes. Edit: -5 bytes thanks to Dead Possum ]
[Question] [ In a twist on finding a needle in a haystack, you need to find the largest contiguous haystack containing **exactly** **one** **needle**. Note that you cannot connect cells on diagonals, only left/right/up/down. ## Input An array (or a number of user input lines, your pick) of `'N'` (needles) and `'#'` (hay) characters. Input only contains those two characters, and must contain at least one of each. For example: ``` N#N#N #NN## ###N# N##N# ``` ## Output The size of the largest possible valid haystack. For our example, we would output 11 (there are 11 pieces of hay, and one needle). ``` # # ## ###N# ## # ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. Standard loophole restrictions apply. ## Test Cases *Input on left, possible maximal haystack on right* **Case 1: 4** ``` N## ## NN# # #NN N #N# # ``` **Case 2: 7** ``` ### ### N#N # NNN N ### ### ``` **Case 3: 10** ``` N###N ### #N#N# #N# #N#N# # # N###N ### ``` **Case 4: 10** ``` N#N#N #N#N# # # # ##N## ##N## #N#N# # # # N#N#N ``` **Case 5: 1** ``` NN#NN NNNNN #NNN# #N NN#NN ``` [Answer] # JavaScript (ES6), 152 bytes ``` s=>[...s].map((n,i)=>n>'M'&&(a=[...s],a[i]=r=1,a.map(_=>a.map((c,j)=>c=='#'&&a[j+1]|a[j-1]|a[j+l]|a[j-l]?a[j]=++r:0)),o=r>o?r:o),o=0,l=~s.search` `)|o-1 ``` ## Explanation For each needle in the input, sets the needle to a part of the haystack (represented by setting it to a non-zero number) and continuously checks hay cells. If hay contains an adjacent part of the hay stack, also sets it part of the haystack and increments the size of the hay stack. Outputs the highest result. ``` var solution = s=> [...s].map((n,i)=>n>'M'&&( // for each needle in s at index i a=[...s], // a = array of each character in s a[i]=1, // set the starting needle to 1 (haystack) r=0, // r = haystack size starting from this needle a.map(_=> // loop to ensure the complete haystack is found a.map((c,j)=> // for each cell c at index j c=='#'&& // if the current cell is hay a[j+1]|a[j-1]|a[j+l]|a[j-l] // and any adjacent cells are part of the haystack ?a[j]=++r:0 // add the current cell to the haystack, increment r ) ), o=r>o?r:o // o = max of o and r ), o=0, // o = final output, initialise to 0 l=~s.search` ` // l = line length of s ) |o // return o ``` ``` <textarea id="input" rows="6" cols="40">N#N#N #N#N# ##N## #N#N# N#N#N</textarea><br /> <button onclick="result.textContent=solution(input.value)">Go</button> <pre id="result"></pre> ``` [Answer] ## Ruby, 207 ``` ->a{d=->b{0...b.size} f=c=s=->y,x{(d[a]===y&&d[a[0]]===x&&!f[y][x]&&a[y][x]==c)?(c,f[y][x]=?#,1 1+s[y,x-1]+s[y,x+1]+s[y-1,x]+s[y+1,x]):0} d[a].map{|y|d[y].map{|x|f,c=a.map{|b|b.map{p}},?N s[y,x]}.max}.max-1} ``` This is an anonymous function that takes in the input as an array of arrays. Usage: ``` f=->a{......} f[" N## NN# #NN #N# ".strip.split.map(&:chars)] # => 4 ``` The proc named `s` recursively finds the size of the haystack with needle at specific coordinates and is called on each needle in the haystack. ]
[Question] [ This challenge is about writing code to solve the following problem. Given two strings A and B, your code should output the start and end indices of a substring of A with the following properties. * The substring of A should also match some substring of B with up to one substitution of a single character in the string. * There should be no longer substring of A that satisfies the first property. For example: ``` A = xxxappleyyyyyyy B = zapllezzz ``` The substring `apple` with indices `4 8` (indexing from 1) would be a valid output. **Score** The score of your answer will be the sum of length of your code in bytes + the time in seconds it takes on my computer when run on strings A and B of length 1 million each. **Testing and input** I will run your code on two strings of length 1 million taken from the strings in <http://hgdownload.cse.ucsc.edu/goldenPath/hg38/chromosomes/> The input will be on standard in and will simply be two strings, separated by a new line. **Languages and libraries** You can use any language which has a freely available compiler/interpreter/etc. for Linux and any libraries which are also open source and freely available for Linux. **My machine** The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code. As a consequence, only use easily available free software and please include full instructions how to compile and run your code. [Answer] # C++ time: O(n^2), extra space: O(1) It takes 0.2s to complete the 15K data on my machine. To compile it, use: ``` g++ -std=c++11 -O3 code.cpp -o code ``` To run it, use: ``` ./code < INPUT_FILE_THAT_CONTAINS_TWO_LINES_SPERATED_BY_A_LINE_BREAK ``` ## Explaination The idea is simple, for string `s1` and `s2`, we try to offset `s2` by `i`: ``` s1: abcabcabc s2: bcabcab ``` When offset is 3: ``` s1: abcabcabc s2: bcabcab ``` Then, for each offset `i`, we perform a dynamic programing scan on `s1[i:]` and `s2`. For each `j`, let `f[j, 0]` be the maximum length `d` such that `s1[j - d:j] == s2[j - i - d: j - i]`. Similarly, let `f[j, 1]` be the maximum length `d` such that strings `s1[j - d:j]` and `s2[j - i - d:j - i]` differ by at most 1 character. So for `s1[j] == s2[j - i]`, we have: ``` f[j, 0] = f[j - 1, 0] + 1 // concat solution in f[j - 1, 0] and s1[j] f[j, 1] = f[j - 1, 1] + 1 // concat solution in f[j - 1, 1] and s1[j] ``` Otherwise: ``` f[j, 0] = 0 // the only choice is empty string f[j, 1] = f[j - 1, 0] + 1 // concat solution in f[j - 1, 0] and s1[j] (or s2[j - i]) ``` And: ``` f[-1, 0] = f[-1, 1] = 0 ``` Since we only need f[j - 1, :] to calculate f[j, :], only O(1) extra space is used. Finally, the max length will be: ``` max(f[j, 1] for all valid j and all i) ``` ## Code ``` #include <string> #include <cassert> #include <iostream> using namespace std; int main() { string s1, s2; getline(cin, s1); getline(cin, s2); int n1, n2; n1 = s1.size(); n2 = s2.size(); int max_len = 0; int max_end = -1; for(int i = 1 - n2; i < n1; i++) { int f0, f1; int max_len2 = 0; int max_end2 = -1; f0 = f1 = 0; for(int j = max(i, 0), j_end = min(n1, i + n2); j < j_end; j++) { if(s1[j] == s2[j - i]) { f0 += 1; f1 += 1; } else { f1 = f0 + 1; f0 = 0; } if(f1 > max_len2) { max_len2 = f1; max_end2 = j + 1; } } if(max_len2 > max_len) { max_len = max_len2; max_end = max_end2; } } assert(max_end != -1); // cout << max_len << endl; cout << max_end - max_len + 1 << " " << max_end << endl; } ``` [Answer] ## C++ I tried thinking of a good algorithm to do this, but I'm a bit distracted today and couldn't think of anything that would work well. This runs at O(n^3) time, so it's veeeery slow. The other option I thought of could have been theoretically faster but would have taken O(n^2) space, and with inputs of 1M, it would have been worse even. It's shameful, it takes 190 seconds for inputs of 15K. I'll try to improve it. **Edit:** Added multiprocessing. Now takes 37 seconds for 15K input on 8 threads. ``` #include <string> #include <vector> #include <sstream> #include <chrono> #include <thread> #include <atomic> #undef cin #undef cout #include <iostream> using namespace std; typedef pair<int, int> range; int main(int argc, char ** argv) { string a = "xxxappleyyyyyyy"; string b = "zapllezzz"; getline(cin, a); getline(cin, b); range longestA; range longestB; using namespace std::chrono; high_resolution_clock::time_point t1 = high_resolution_clock::now(); unsigned cores = thread::hardware_concurrency(); cores = cores > 0 ? cores : 1; cout << "Processing on " << cores << " cores." << endl; atomic<int> processedCount(0); vector<thread> threads; range* longestAs = new range[cores]; range* longestBs = new range[cores]; for (int t = 0; t < cores; ++t) { threads.push_back(thread([&processedCount, cores, t, &a, &b, &longestBs, &longestAs]() { int la = a.length(); int l = la / cores + (t==cores-1? la % cores : 0); int lb = b.length(); int aS = t*(la/cores); for (int i = aS; i < aS + l; ++i) { int count = processedCount.fetch_add(1); if ((count+1) * 100 / la > count * 100 / la) { cout << (count+1) * 100 / la << "%" << endl; } for (int j = 0; j < lb; ++j) { range currentB = make_pair(j, j); bool letterChanged = false; for (int k = 0; k + j < lb && k + i < la; ++k) { if (a[i + k] == b[j + k]) { currentB = make_pair(j, j + k); } else if (!letterChanged) { letterChanged = true; currentB = make_pair(j, j + k); } else { break; } } if (currentB.second - currentB.first > longestBs[t].second - longestBs[t].first) { longestBs[t] = currentB; longestAs[t] = make_pair(i, i + currentB.second - currentB.first); } } } })); } longestA = make_pair(0,0); for(int t = 0; t < cores; ++t) { threads[t].join(); if (longestAs[t].second - longestAs[t].first > longestA.second - longestA.first) { longestA = longestAs[t]; longestB = longestBs[t]; } } high_resolution_clock::time_point t2 = high_resolution_clock::now(); duration<double> time_span = duration_cast<duration<double>>(t2 - t1); cout << "First substring at range (" << longestA.first << ", " << longestA.second << "):" << endl; cout << a.substr(longestA.first, longestA.second - longestA.first + 1) << endl; cout << "Second substring at range (" << longestB.first << ", " << longestB.second << "):" << endl; cout << b.substr(longestB.first, longestB.second - longestB.first + 1) << endl; cout << "It took me " << time_span.count() << " seconds for input lengths " << a.length() << " and " << b.length() <<"." << endl; char c; cin >> c; return 0; } ``` [Answer] # [R](http://www.r-project.org/) Seems I was over complicating the problem with the previous solution. This is about 50% quicker (23 secs on 15k strings) than the previous one and pretty simple. ``` rm(list=ls(all=TRUE)) a="xxxappleyyyyyyy" b="zapllezzz" s=proc.time() matchLen=1 matchIndex=1 indexA = 1 repeat { i = 0 repeat { srch = substring(a,indexA,indexA+matchLen+i) if (agrepl(srch,b,max.distance=list(insertions=0,deletions=0,substitutions=1))) i = i + 1 else { if (i > 0) { matchLen = matchLen + i - 1 matchIndex = indexA } break } } indexA=indexA+1 if (indexA + matchLen > nchar(a)) break } c(matchIndex, matchLen + matchIndex) print (substring(a,matchIndex, matchLen + matchIndex)) print(proc.time()-s) ``` This will never be a contender due to the language, but I did have a bit of fun doing it. Not sure of the complexity of it, but over a couple of ~15k strings it takes 43 secs using a single thread. The largest portion of that was the sorting of the arrays. I tried some other libraries, but without significant improvement. ``` a="xxxappleyyyyyyy" b="zapllezzz" s=proc.time() N=nchar S=substring U=unlist V=strsplit A=N(a) B=N(b) a=S(a,1:A) b=S(b,1:B) a=sort(a,method="quick") b=sort(b,method="quick") print(proc.time()-s) C=D=1 E=X=Y=I=0 repeat{ if(N(a[C])>E && N(b[D])>E){ for(i in E:min(N(a[C]),N(b[D]))){ if (sum(U(V(S(a[C],1,i),''))==U(V(S(b[D],1,i),'')))>i-2){ F=i } else break } if (F>E) { X=A-N(a[C])+1 Y=X+F-1 E=F } if (a[C]<b[D]) C=C+1 else D=D+1 } else if(S(a[C],1,1)<S(b[D],1,1))C=C+1 else D=D+1 if(C>A||D>B)break } c(X,Y) print(proc.time()-s) ``` **Method:** * Create a suffix array for each string * Order the suffix arrays * Step through each of the arrays in a staggered sort of way comparing the beginning of each ]
[Question] [ # Let's have a tank war! Partially inspired by [Destroy Them With Lazers](https://codegolf.stackexchange.com/questions/28345/destroy-them-with-lazers) ## Objective Your task is to control a tank. Move around and shoot other tanks and obstacles in the 2D battlefield. The last tank standing will be the winner! ## Map format Your tank will be on a 2D field based on an `n` by `n` grid of unit squares. I will decide what `n` is based on the number of submissions. Each square can contain only one of: * A tank * A tree * A rock * A wall * Nothing All obstacles and tanks completely fill their spaces, and they block all shots that hit them from damaging things further down. Here is an example of a field with `#`=tank; `T`=tree; `R`=rock; `W`=wall; `.`=nothing with `n`=10 ``` .....#.... ..T....R.. WWW...WWWW W......T.. T...R...Ww W...W..... W....W...T WWWWWW...R W......... WWWWWWRT.. ``` Coordinates are in the format `x, y` where `x` increases left to right and `y` increases bottom to top. The bottom left space has the coordinate `0, 0`. Each tank may move to any empty space and shoot in any direction. ## Map Dynamics Your tank doesn't just have to shoot other tanks! If it shoots something on the map, things can happen. * If a wall is shot at, it will be destroyed after some number of shots, ranging from 1 to 4 * If a tree is shot at, it will be destroyed immediately * If a rock is shot at, the shot will pass over it and damage the next thing it hits Once something is destroyed, it is no longer on the map (it will be replaced with nothing). If a shot destroys an obstacle, it will be blocked and will not damage anything further along its path. ## Tank dynamics Each tank starts with `life`=100. Each shot at a tank will reduce 20-30 `life` based on distance. This can be calculated with `delta_life=-30+(shot_distance*10/diagonal_map_length)` (where `diagonal_map_length` is `(n-1)*sqrt(2)`). Additionally, each tank regenerates 1 `life` per turn. ## Turns Some number of rounds will be run (I will decide once I have submissions). At the beginning of every round, a map will be generated randomly, and tanks will be placed on it in random empty locations. During every round, each tank will be given a turn, in any arbitrary order. After every tank has been given a turn, they will be given turns again in the same order. The round continues until there is only one tank left. That tank will be the winner, and they will receive 1 point. The game will then go on to the next round. Once all the rounds have been run, I will post the scores on this question. During a tank's turn, it may do one of the following * Move up to 3 spaces in a single direction, either horizontally or vertically. If the tank is blocked by an obstacle or another tank, it will be moved as far as possible without going through the obstacle or tank. * Shoot in some direction, represented by a floating point angle in degrees. The x-axis of your tank's local space (horizontally left to right, aka east or `TurnAction.Direction.EAST`) is 0deg, and angles increase counterclockwise. Shots are inaccurate, and the actual angle of the shot may be 5 degrees greater or less than the angle you choose. * Do nothing. Turns are not limited in time, but this doesn't mean you can intentionally waste time to hang everything up. ## Submissions/Protocol Each program submitted will control one tank on the field. The control program is in Java, so your programs need to be in Java for now (I will probably write a wrapper for other languages at some point, or you could write your own). Your programs will implement the `Tank` interface, which has the following methods: ``` public interface Tank { // Called when the tank is placed on the battlefield. public void onSpawn(Battlefield field, MapPoint position); // Called to get an action for the tank on each turn. public TurnAction onTurn(Battlefield field, MapPoint position, float health); // Called with feedback after a turn is executed. // newPosition and hit will be populated if applicable. public void turnFeedback(MapPoint newPosition, FieldObjectType hit); // Called when the tank is destroyed, either by another tank, // or because the tank won. The won parameter indicates this. public void onDestroyed(Battlefield field, boolean won); // Return a unique name for your tank here. public String getName(); } ``` The `Battlefield` class contains a 2D array of objects (`Battlefield.FIELD_SIZE` by `Battlefield.FIELD_SIZE`) which represents things on the battlefield. `Battlefield.getObjectTypeAt(...)` will give a `FieldObjectType` for the object at the specified coordinates (one of `FieldObjectType.ROCK`, `FieldObjectType.TREE`, `FieldObjectType.TANK`, `FieldObjectType.WALL`, or `FieldObjectType.NOTHING`). If you try to get an object out of range of the map (coordinates <0 or >=`Battlefield.FIELD_SIZE`) then an `IllegalArgumentException` will be thrown. `MapPoint` is a class for specifying points on the map. Use `MapPoint.getX()` and `MapPoint.getY()` to access the coordinates. **EDIT:** Some utility methods have been added: `MapPoint.distanceTo(MapPoint)`, `MapPoint.angleBetween(MapPoint)`, `Battlefield.find(FieldObjectType)`, and `TurnAction.createShootActionRadians(double)` as suggested by [Wasmoo](https://codegolf.stackexchange.com/a/34574/20666). More info can be found in the javadocs, see section below. All (public API) classes are under the package `zove.ppcg.tankwar`. ## Control Program The full source and javadocs of the control program and tank API can be found on my GitHub repo: <https://github.com/Hungary-Dude/TankWarControl> Feel free to send pull requests and/or comment if you see a bug or want an improvement. I have written two sample tank programs, `RandomMoveTank` and `RandomShootTank` (the name says it all). To run your tank, add your fully qualified (package name + class name) tank class to `tanks.list` (one class per line), edit settings as necessary in `zove.ppcg.tankwar.Control` (turn delay, whether or not to show a GUI representation of the field, etc), and run `zove.ppcg.tankwar.Control`. Make sure there are at least 2 tanks on the list, or results are undefined. (Use the sample tanks if necessary). Your programs will be run on my machine under this control program. I'll include a link to the source once I write it. Feel free to suggest edits to the source. ## Rules * Your submissions must follow the guidelines above * Your programs may not access the filesystem, network, or attempt to attack my machine in any way * Your programs may not attempt to exploit my control program to cheat * No trolling (such as intentionally making your program waste time to hang everything up) * You may have more than one submission * Try to be creative with submissions! * I reserve the right to allow or not allow programs arbitrarily Good luck! **UPDATE:** After fixing the wall teleportation bug and implementing regeneration, I ran the current submissions for 100 rounds with `Battlefield.FIELD_SIZE = 30` **UPDATE 2:** I added the new submission, RunTank, after fooling with Groovy for a bit... Updated results: ``` +-----------------+----+ | RandomMoveTank | 0 | | RandomShootTank | 0 | | Bouncing Tank | 4 | | Richard-A Tank | 9 | | Shoot Closest | 19 | | HunterKiller 2 | 22 | | RunTank | 23 | | Dodge Tank | 24 | +-----------------+----+ ``` Currently tanks regenerate 1 life per turn. Should that be increased? [Answer] **HunterKiller** This intelligent hunter will attempt to find a safe position where it can cleanly shoot at exactly one target. (And thus, only one target can shoot it) Works best when there is lots of cover. ``` import zove.ppcg.tankwar.*; import java.util.*; public final class HunterKiller implements Tank { private final int MAX_DEPTH = 2; private Battlefield field; private List<MapPoint> enemies; private MapPoint me; private HashMap<MapPoint, MoveNode> nodeMap = new HashMap(); //A description of how safe the position is from each tank in enemies private class Safety extends java.util.ArrayList<Double> { public int threats; public Safety(MapPoint position) { for (MapPoint p : enemies) { int obstacles = countObstacles(position, p, false); if (obstacles > 0) { add((double) obstacles); } else { add(missChance(position.distanceTo(p))); threats++; } } } }; //A description of a move private class Move { public TurnAction.Direction direction; public int distance; public MapPoint point; public Move(TurnAction.Direction direction, int distance, MapPoint point) { this.direction = direction; this.distance = distance; this.point = point; } public TurnAction action() { return TurnAction.createMoveAction(direction, distance); } @Override public String toString() { return direction + " " + distance; } } /** * A MoveNode holds a point and all the moves available from that point. * The relative safety of the node can be calculated as a function * of its depth; ie. this position is safe because we can can move to safety */ private class MoveNode { MapPoint point; ArrayList<Move> moves; ArrayList<Safety> safetyArray = new ArrayList(); public MoveNode(MapPoint point) { this.point = point; this.moves = getMoves(point); } public Safety getSafety(int depth) { if (safetyArray.size() <= depth) { Safety value; if (depth == 0 || this.moves.isEmpty()) { value = new Safety(point); } else { ArrayList<Safety> values = new ArrayList(); for (Move m : moves) { MoveNode n = nodeMap.get(m.point); if (n == null) { n = new MoveNode(m.point); nodeMap.put(n.point, n); } values.add(n.getSafety(depth - 1)); } Collections.sort(values, cmp); value = values.get(0); } safetyArray.add(depth, value); } return safetyArray.get(depth); } } /** * Find all the points between here and there, excluding those points */ private java.util.ArrayList<MapPoint> path(final MapPoint p1, MapPoint p2) { java.util.ArrayList<MapPoint> ret = new ArrayList(); float tankX = p1.getX(); float tankY = p1.getY(); double angle = p1.angleBetweenRadians(p2); double maxDistance = p1.distanceTo(p2); for (int x = 0; x < Battlefield.FIELD_SIZE; x++) { for (int y = 0; y < Battlefield.FIELD_SIZE; y++) { float x2 = (float) (((x - tankX) * Math.cos(-angle)) - ((y - tankY) * Math.sin(-angle))); float y2 = (float) (((x - tankX) * Math.sin(-angle)) + ((y - tankY) * Math.cos(-angle))); if (x2 > 0 && y2 >= -0.5 && y2 <= 0.5) { MapPoint p = new MapPoint(x, y); if (maxDistance > p1.distanceTo(p)) { ret.add(p); } } } } Collections.sort(ret, new Comparator<MapPoint>() { @Override public int compare(MapPoint o1, MapPoint o2) { return (int) Math.signum(p1.distanceTo(o2) - p1.distanceTo(o1)); } }); return ret; } /** * Find the number of obstacles between here and there, excluding those * points */ private int countObstacles(MapPoint p1, MapPoint p2, boolean countRocks) { java.util.ArrayList<MapPoint> points = path(p1, p2); int count = 0; for (MapPoint p : points) { Object obj = field.getObjectTypeAt(p); if (FieldObjectType.NOTHING.equals(obj) || (!countRocks && FieldObjectType.ROCK.equals(obj)) || (!countRocks && FieldObjectType.TANK.equals(obj)) || p.equals(me)) { count += 0; } else { count += 1; } } return count; } /** * Returns a value between 1.0 and 0.0, where 1.0 is far and 0.0 is close */ private double missChance(double distance) { return distance / Battlefield.DIAGONAL_FIELD_SIZE; } //Returns a list of valid moves from the given position private ArrayList<Move> getMoves(MapPoint position) { ArrayList<Move> ret = new ArrayList(); for (TurnAction.Direction d : TurnAction.Direction.values()) { for (int i = 1; i <= 3; i++) { MapPoint p = d.translate(position, i); try { FieldObjectType t = field.getObjectTypeAt(p); if (t != FieldObjectType.NOTHING && !p.equals(me)) { break; } ret.add(new Move(d, i, p)); } catch (IllegalArgumentException ex) { //Can't move off the map... break; } } } return ret; } //Compares two safeties with a preference for exactly 1 threat private Comparator<Safety> cmp = new Comparator<Safety>() { @Override public int compare(Safety o1, Safety o2) { int tc1 = o1.threats; int tc2 = o2.threats; //Prefer 1 threat if (tc2 == 1 && tc1 != 1) { return 1; } if (tc2 != 1 && tc1 == 1) { return -1; } //Prefer fewer threats if (tc2 != tc1) { return tc1 - tc2; } //We're splitting hairs here //Determine the least safe option int ret = -1; double s = Double.MAX_VALUE; for (Double d : o1) { if (d < s) { s = d; } } for (Double d : o2) { if (d < s) { ret = 1; break; } if (d == s) { ret = 0; } } if (tc1 > 1) { //Prefer the safest return -ret; } else { //Prefer the least safest return ret; } } }; @Override public TurnAction onTurn(Battlefield field, MapPoint position, float health) { //Find all the tanks List<MapPoint> enemies = field.find(FieldObjectType.TANK); enemies.remove(position); if (enemies.isEmpty()) { return TurnAction.createNothingAction(); } //Set the constants needed for this turn this.enemies = enemies; this.field = field; this.me = position; //Create a new NodeMap MoveNode n = new MoveNode(position); this.nodeMap.clear(); this.nodeMap.put(position, n); //Find the "best" safety within MAX_DEPTH moves int depth = 0; Safety safety = n.getSafety(0); for (depth = 0; depth < MAX_DEPTH; depth++) { int lastThreat = safety.threats; safety = n.getSafety(depth); int newThreat = safety.threats; if (newThreat == 1) { //Always prefer 1 threat break; } if (depth != 0 && lastThreat - newThreat >= depth) { //Prefer fewer threats only if we are much safer; // Specifically, don't move twice for only 1 less threat break; } } //Depth == 0 : Only 1 threat; best position //Depth == MAX_DEPTH : Many or no threats, but no good moves available if (depth > 0 && depth < MAX_DEPTH) { //Move towards the better spot for (Move m : n.moves) { if (nodeMap.get(m.point).getSafety(depth - 1) == safety) { return m.action(); } } } //We're in a good position, shoot now //Calculate tank with most threat MapPoint threat = null; double biggestThreat = Double.MAX_VALUE; for (MapPoint p : enemies) { double t = missChance(position.distanceTo(p)) + countObstacles(position, p, false); if (t < biggestThreat) { biggestThreat = t; threat = p; } } return TurnAction.createShootActionRadians(position.angleBetweenRadians(threat)); } public void onDestroyed(Battlefield field, boolean won) {} public void onSpawn(Battlefield field, MapPoint position) {} public void turnFeedback(MapPoint newPosition, FieldObjectType hit) {} public String getName() { return "HunterKiller " + MAX_DEPTH; } } ``` And that's it. I'm spent. [Answer] This straight-forward tank finds the closest enemy tank and shoots at it. Would be nice if `find`, `distance`, and `angle` were built in, and if `createShootAction` accepted a double in radians (i.e. the result of `angle`) **Edit:** Class rewritten to include new utility methods ``` public final class ShootClosestTank implements Tank { @Override public TurnAction onTurn(Battlefield field, MapPoint position, float health) { //Find all the tanks List<MapPoint> tanks = field.find(FieldObjectType.TANK); tanks.remove(position); if (tanks.isEmpty()) return TurnAction.createNothingAction(); //Calculate closest tank MapPoint cPoint = null; double cDist = Double.POSITIVE_INFINITY; for (MapPoint p : tanks) { double dist = position.distanceTo(p); if (dist < cDist) { cDist = dist; cPoint = p; } } //Shoot at closest tank return TurnAction.createShootActionRadians(position.angleBetweenRadians(cPoint)); } @Override public void onDestroyed(Battlefield field, boolean won) { //Sucks to be me } @Override public void onSpawn(Battlefield field, MapPoint position) { //No setup } @Override public void turnFeedback(MapPoint newPosition, FieldObjectType hit) { //Nothing to update } @Override public String getName() { return "Shoot Closest"; } } ``` [Answer] I'm not very good at this but I thought I'd still give it a shot, you know, practice and stuff. My tank will randomly decide to move or shoot. When it decides to shoot, it'll try to shoot at the nearest available target. ``` package com.richarda.tankwar; import zove.ppcg.tankwar.*; import java.util.Random; import java.util.ArrayList; public class RichardATank implements Tank { private String name; public RichardATank() { this.name = "Richard-A Tank"; } /** * * @param field * The current battlefield, complete with all obstacle and tank * positions * @param position */ @Override public void onSpawn(Battlefield field, MapPoint position) { } /** * The tank will randomly move around and occasionally shoot at the nearest available target. * * @param field * The current battlefield, complete with all obstacle and tank * positions * @param position * The tank's current position * @param health * The tank's current health * @return */ @Override public TurnAction onTurn(Battlefield field, MapPoint position, float health) { Random r = new Random(); int n = r.nextInt(2); if(n == 1) { return this.tryShootAtNearestTank(field, position); } return TurnAction.createMoveAction(TurnAction.Direction.getRandom(), r.nextInt(2) + 1); } /** * * @param newPosition * The tank's new position (may not be changed) * @param hit * What the tank hit, if it decided to shoot */ @Override public void turnFeedback(MapPoint newPosition, FieldObjectType hit) { } /** * * @param field * The battlefield * @param won */ @Override public void onDestroyed(Battlefield field, boolean won) { } @Override public String getName() { return this.name; } /** * Try and shoot at the nearest tank * * @param bf The battlefield * @param curTankLocation The current tank's location * @return TurnAction the shoot action to the nearest tank */ private TurnAction tryShootAtNearestTank(Battlefield bf, MapPoint curTankLocation) { MapPoint nearestTankLoc = this.getNearestTankLocation(bf, curTankLocation); double firingAngle = curTankLocation.angleBetween(nearestTankLoc); return TurnAction.createShootAction((float) firingAngle); } /** * Try to find the nearest tank's location * * @param bf The battlefield * @param curTankLocation The current tank's location * @return MapPoint The location of the nearest tank */ private MapPoint getNearestTankLocation(Battlefield bf, MapPoint curTankLocation) { ArrayList<MapPoint> enemyTankLocations = this.getEnemyTanksOnField(bf, curTankLocation); MapPoint nearestTankLoc = null; for(MapPoint enemyTankLoc : enemyTankLocations) { if(nearestTankLoc == null || curTankLocation.distanceTo(enemyTankLoc) < curTankLocation.distanceTo(nearestTankLoc)) { nearestTankLoc = enemyTankLoc; } } return nearestTankLoc; } /** * Get all enemy tanks on the field * * @param bf The battlefield * @param curTankLocation The current tank's location * @return ArrayList<MapPoint> A list with all enemy tanks in it */ private ArrayList<MapPoint> getEnemyTanksOnField(Battlefield bf, MapPoint curTankLocation) { int maxSize = Battlefield.FIELD_SIZE; ArrayList<MapPoint> tanks = new ArrayList<MapPoint>(); for(int i = 0; i < maxSize; i++) { for(int j = 0; j < maxSize; j++) { FieldObjectType objType = bf.getObjectTypeAt(i, j); if(objType == FieldObjectType.TANK) { MapPoint tankLocation = new MapPoint(i, j); if(!tankLocation.equals(curTankLocation)) { tanks.add(tankLocation); } } } } return tanks; } } ``` The full code including the control program can be found [here](https://bitbucket.org/Richard-A/koth-tank-war/src). [Answer] ## Dodge Tank This tank will shoot at the closest tank. Every so often, depending on its health and the last time it moved, it will try to move perpendicular to the closest tank in an attempt to dodge its lasers. ``` public class DodgeTank implements Tank { private int lastMove; @Override public void onSpawn(Battlefield field, MapPoint position){ //nada } @Override public TurnAction onTurn(Battlefield field, MapPoint position, float health){ List<MapPoint> tanks = field.find(FieldObjectType.TANK); tanks.remove(position); MapPoint nearest= new MapPoint(0,0); double dis=Double.POSITIVE_INFINITY; for (MapPoint tank: tanks){ double distance=tank.distanceTo(position); if (distance<dis){ nearest=tank; dis=distance; } } if (lastMove*Math.random()+(4-health/25)<5){//Attack lastMove++; return TurnAction.createShootActionRadians(position.angleBetweenRadians(nearest)); } else { lastMove=0; double cumulativeAngle=position.angleBetweenRadians(nearest); for (MapPoint tank : tanks){ cumulativeAngle+=position.angleBetweenRadians(tank); } cumulativeAngle/=tanks.size(); cumulativeAngle/=(Math.PI/2); int dir=(int)Math.floor(cumulativeAngle); TurnAction move; switch (dir){ case 0: if (position.getX()>2&&field.getObjectTypeAt(position.cloneAndTranslate(-3, 0)).equals(FieldObjectType.NOTHING)){ return TurnAction.createMoveAction(TurnAction.Direction.WEST, 3); } return TurnAction.createMoveAction(TurnAction.Direction.EAST, 3); case 1: if (position.getY()>2&&field.getObjectTypeAt(position.cloneAndTranslate(0, -3)).equals(FieldObjectType.NOTHING)){ return TurnAction.createMoveAction(TurnAction.Direction.SOUTH, 3); } return TurnAction.createMoveAction(TurnAction.Direction.NORTH, 3); case -1: if ((position.getY()<(Battlefield.FIELD_SIZE-4))&&field.getObjectTypeAt(position.cloneAndTranslate(0,3)).equals(FieldObjectType.NOTHING)){ return TurnAction.createMoveAction(TurnAction.Direction.NORTH, 3); } return TurnAction.createMoveAction(TurnAction.Direction.SOUTH, 3); default: if ((position.getX()<(Battlefield.FIELD_SIZE-4))&&field.getObjectTypeAt(position.cloneAndTranslate(3,0)).equals(FieldObjectType.NOTHING)){ return TurnAction.createMoveAction(TurnAction.Direction.EAST, 3); } return TurnAction.createMoveAction(TurnAction.Direction.WEST, 3); } } } @Override public void turnFeedback(MapPoint newPosition, FieldObjectType hit){ //Nada } @Override public void onDestroyed(Battlefield field, boolean won){ //if (won) this.taunt(); //else this.selfDestruct(); } @Override public String getName(){ return "Dodge Tank"; } } ``` [Answer] This was way more complicated than I thought.. This is my entry in groovy, you need groovy installed and compile it with ``` groovyc zove\ppcg\tankwar\felsspat\RunTank.groovy ``` To call it you need to add $GROOVY\_HOME/Groovy/Groovy-2.3.4/lib/groovy-2.3.4.jar (or whatever version) to the classpath. I could send you a compiled .class file and the library if you don't want to install it. There seems to be a situation where tanks can't see it other, I don't know if that is intended. That caused deadlocks while testing. Anyway here is RunTank: RunTank boldy advances in the opposite direction of the closest tank if it is the closest tank to the closest tank or more than one tank is within FIELD\_SIZE / 3. I hope that makes sense, I'm drunk :) ``` package zove.ppcg.tankwar.felsspat import zove.ppcg.tankwar.Battlefield import zove.ppcg.tankwar.FieldObjectType import zove.ppcg.tankwar.MapPoint import zove.ppcg.tankwar.Tank import zove.ppcg.tankwar.TurnAction import zove.ppcg.tankwar.TurnAction.Direction public class RunTank implements Tank { @Override public TurnAction onTurn(Battlefield field, MapPoint position, float health) { def targets = (field.find(FieldObjectType.TANK) - position).sort{ position.distanceTo(it) } if (targets) { def runDistance = (Battlefield.FIELD_SIZE / 3).toInteger() def closeTargets = targets.grep { position.distanceTo(it) < runDistance } if (position.distanceTo(closestEnemy(position, field)) < targets.first().distanceTo(closestEnemy(targets.first(), field))) { return run(field, position, targets) } if (closeTargets.size() > 1) { return run(field, position, targets) } else { return shootEnemy(position, targets) } } else { println "WTF! Targets: ${field.find(FieldObjectType.TANK)} + Position ${position}" return TurnAction.createMoveAction(Direction.getRandom(), 1); } } def shootEnemy(position, targets) { return TurnAction.createShootActionRadians(position.angleBetweenRadians(targets.first())) } def run(field, position, targets) { def freePositions = (field.find(FieldObjectType.NOTHING) - position).grep { position.distanceTo(it) <= 3.0 && [0d, 90d, 180d, 270d].contains(position.angleBetween(it))}.sort{position.distanceTo(it)} def availablePositions = [] freePositions.each { targetPosition -> def positions = getPositionsBetween(position,targetPosition) if (! positions || positions.every { it.equals(FieldObjectType.NOTHING) }) { availablePositions.add(targetPosition) } } availablePositions = availablePositions.sort{closestEnemy(it, field)}.reverse() if (availablePositions) { def targetPosition = availablePositions.first() if (targetPosition.distanceTo(closestEnemy(targetPosition, field)) > position.distanceTo(closestEnemy(position, field))) { // Don't move closer to an enemy return moveTo(position, targetPosition) } else { return shootEnemy(position, targets) } } else { return shootEnemy(position, targets) } } def moveTo(position, targetPosition) { def distance = position.distanceTo(targetPosition).toInteger() switch (position.angleBetween(targetPosition)) { case 0d: return TurnAction.createMoveAction(TurnAction.Direction.NORTH, distance) break case 90d: return TurnAction.createMoveAction(TurnAction.Direction.EAST, distance) break case 180d: return TurnAction.createMoveAction(TurnAction.Direction.SOUTH, distance) break case 270d: return TurnAction.createMoveAction(TurnAction.Direction.West, distance) break default: println "I'm stupid :(" } } def closestEnemy(position, field) { return field.find(FieldObjectType.TANK).sort { position.distanceTo(it) }.first() } def getPositionsBetween(self, target) { def positions = [] if(self.x == target.x) { for (y in self.y..target.y) { positions.add(new MapPoint(self.x, y)) } } else { for (x in self.x..target.x) { positions.add(new MapPoint(x, self.y)) } } return positions - self - target } @Override public void turnFeedback(MapPoint newPosition, FieldObjectType hit) { } @Override public void onDestroyed(Battlefield field, boolean won) { println ":(" } @Override public void onSpawn(Battlefield field, MapPoint position) { println "Go!" } @Override public String getName() { return "RunTank"; } } ``` I have one suggestion: Add colors to the tank, and a method to implement it. Also labels would be nice in the GUI :) [Answer] This one is a variant on the Shoot-Closest in that, every other turn, it moves in a direction until it can no longer. It shoots every other turn. It has a handy utility, `path`, which can be used to identify all points (and thus objects) between two points. ``` public final class BouncingTank implements Tank { /** * Find all the points between here and there, excluding those points * @param p1 Here * @param p2 There * @return */ private java.util.ArrayList<MapPoint> path(MapPoint p1, MapPoint p2) { double dist = p1.distanceTo(p2); double dx = (p2.getX() - p1.getX()) / dist; double dy = (p2.getY() - p1.getY()) / dist; java.util.ArrayList<MapPoint> ret = new java.util.ArrayList(); MapPoint lastP = null; for (int i = 0; i < dist; i++) { MapPoint p = p1.cloneAndTranslate((int)(i*dx), (int)(i*dy)); if (p.equals(p1) || p.equals(lastP)) continue; if (p.equals(p2)) break; ret.add(p); lastP = p; } return ret; } /** * Find the number of legal moves in the given direction * @param field * @param position * @param dir * @return */ private int findMoves(Battlefield field, MapPoint position, TurnAction.Direction dir) { if (dir == null) return -1; int count = 0; MapPoint dest = dir.translate(position, Battlefield.FIELD_SIZE); java.util.ArrayList<MapPoint> obs = path(position, dest); for (MapPoint oMP : obs) { try { if (FieldObjectType.NOTHING.equals(field.getObjectTypeAt(oMP))) { count++; } else { break; } } catch (IllegalArgumentException ex) { break; } } return count; } /** * Finds the direction towards which there are the fewest obstacles * @param field * @param position * @return */ private TurnAction.Direction findDirection(Battlefield field, MapPoint position) { TurnAction.Direction ret = null; int mostMoves = 0; for (TurnAction.Direction d : TurnAction.Direction.values()) { int count = findMoves(field, position, d); if (count > mostMoves) { ret = d; mostMoves = count; } } return ret; //Maybe null } private TurnAction shootClosest(Battlefield field, MapPoint position) { //Find all the tanks List<MapPoint> tanks = field.find(FieldObjectType.TANK); tanks.remove(position); if (tanks.isEmpty()) return TurnAction.createNothingAction(); //Calculate closest tank MapPoint cPoint = null; double cDist = Double.POSITIVE_INFINITY; for (MapPoint p : tanks) { double dist = position.distanceTo(p); if (dist < cDist) { cDist = dist; cPoint = p; } } //Shoot at closest tank return TurnAction.createShootActionRadians(position.angleBetweenRadians(cPoint)); } private int turnsUntilShoot = 1; private TurnAction.Direction moveToward = null; @Override public TurnAction onTurn(Battlefield field, MapPoint position, float health) { //Determine if current direction is valid int moves = findMoves(field, position, moveToward); if (moves <= 0) { moveToward = findDirection(field, position); //Determine if we're stuck if (moveToward == null) { return shootClosest(field, position); } } //Shoot if it's time if (turnsUntilShoot == 0) { turnsUntilShoot = 1; return shootClosest(field, position); } else { turnsUntilShoot--; return TurnAction.createMoveAction(moveToward, Math.min(3, moves)); } } public void onDestroyed(Battlefield field, boolean won) {} public void onSpawn(Battlefield field, MapPoint position) {} public void turnFeedback(MapPoint newPosition, FieldObjectType hit) {} public String getName() { return "Bouncing Tank"; } } ``` ]
[Question] [ From [Quine central](http://blog.sigfpe.com/2011/01/quine-central.html): Write a quine that takes as input the name of a language and outputs the same thing implemented in the input language. The source article has something you can work from, but as the author says this is much harder. Obviously you only need to support a limited set of languages. The choice is yours though, as well as the base language. As a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), your score will be the number of languages your program supports; higher is better. [Answer] ## Ruby ``` require 'json';s=%q[{"ruby":[" %q[","require 'json';s=##;j=JSON.load s;puts j[l=gets.chomp][1].sub('##',j[l][0].delete(' ')+s+j[l][2].delete(' '))"," ]"],"python":["' ''","import json,re;s=##;j=json.loads(s);l=raw_input();print(re.sub('##',j[l][0].replace(' ','')+s+j[l][2].replace(' ',''),j[l][1],1))","' ''"]}];j=JSON.load s;puts j[l=gets.chomp][1].sub('##',j[l][0].delete(' ')+s+j[l][2].delete(' ')) ``` ## Python ``` import json,re;s='''{"ruby":[" %q[","require 'json';s=##;j=JSON.load s;puts j[l=gets.chomp][1].sub('##',j[l][0].delete(' ')+s+j[l][2].delete(' '))"," ]"],"python":["' ''","import json,re;s=##;j=json.loads(s);l=raw_input();print(re.sub('##',j[l][0].replace(' ','')+s+j[l][2].replace(' ',''),j[l][1],1))","' ''"]}''';j=json.loads(s);l=raw_input();print(re.sub('##',j[l][0].replace(' ','')+s+j[l][2].replace(' ',''),j[l][1],1)) ``` Both versions take input on stdin (`ruby` or `python` currently) and generate the output to stdout in either language. [Answer] # [Turtlèd](https://github.com/Destructible-Watermelon/turtl-d/), Python 2, and Python 3, 3 languages, only competing for bounty all oneliners follwed by newline ## Turtlèd ``` @##'@r,r,r-{ +.r_}r{ +.r_}!!-.(3"';m=ord(input()[-1]);_='x=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))';print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"367>;++[ d( d)('.)]d<"x='"))(2"';m=ord(raw_input()[-1]);_='x=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))';print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"371>;++[ d( d)('.)]d<"x='"))(d' )#'@r,r,r-{ +.r_}r{ +.r_}!!-.(3"';m=ord(input()[-1]);_='x=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))';print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"367>;++[ d( d)('.)]d<"x='"))(2"';m=ord(raw_input()[-1]);_='x=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))';print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"371>;++[ d( d)('.)]d<"x='"))(d' ) ``` [Try it online!](https://tio.run/nexus/turtled#7ZNNa8JAEIbv/RVjJOwM@SCbqCGkW/wJ3kUWcSMGNIYx0oj0t6fW2EJFD6XoKexhhmcP88LD24z7fTFm9/S8Izg@6w@@zF7P8zGyRLpRWzaYF@W@Qpp6ckapVqJWNt/@OvGS86JC7XNWrueLDBcrRhkE5Hwtg4Dca3CeUg7aJYm/QXIBQyLbxtrVBPkSNkoNA8jWuwz0FZYtrn@fDmV7MkqISDwm3u10fw1nRaP4LXWcKRgEQyh8mplXq1bCIsLwRwfP33Wn5ElKYnlfiRFAXYW6CnVK/lWhl6aZHKrVtoDwEw "Turtlèd – TIO Nexus") ## Python 2 ``` x='@##y@r,r,r-{ +.r_}r{ +.r_}!!-.(3"y;m=ord(input()[-1]);_=yx=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))y;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"367>;++[ d( d)(y.)]d<"x=y"))(2"y;m=ord(raw_input()[-1]);_=yx=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))y;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"371>;++[ d( d)(y.)]d<"x=y"))(dy )#y@r,r,r-{ +.r_}r{ +.r_}!!-.(3"y;m=ord(input()[-1]);_=yx=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))y;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"367>;++[ d( d)(y.)]d<"x=y"))(2"y;m=ord(raw_input()[-1]);_=yx=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))y;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"371>;++[ d( d)(y.)]d<"x=y"))(dy )';m=ord(raw_input()[-1]);_='x=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))';print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39))) ``` [Try it online!](https://tio.run/nexus/python2#7ZPdSsNAEEbvfYppSsgM@SGbtIYQV/oI3peylG6kgTYNY8RdxGeP1VTB0l4UURTCXsxw9mI@OHydkd5sPLYzDvYvfAY/YvXChzkahRGmji22cscaq7p5bJHmoVhQoaQ10uXTX3vecFW3qCIum81yVeJqzSjimPy3ZRJTcAzepxCTfsmzD5AfwJTIddEEiqC6h62U0xjKzUMJ6giLHpuvpxPRn0xzIrI/E@90ukvDOel1dlv4/hw0gia0ES30jWOkdYgw@dTByyc1KPklJZk4r0RboKFCQ4UGJd@qkHdeivd/pXh/WcpV193Zdr2rIXkF "Python 2 – TIO Nexus") ## Python 3 ``` x='@##y@r,r,r-{ +.r_}r{ +.r_}!!-.(3"y;m=ord(input()[-1]);_=yx=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))y;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"367>;++[ d( d)(y.)]d<"x=y"))(2"y;m=ord(raw_input()[-1]);_=yx=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))y;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"371>;++[ d( d)(y.)]d<"x=y"))(dy )#y@r,r,r-{ +.r_}r{ +.r_}!!-.(3"y;m=ord(input()[-1]);_=yx=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))y;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"367>;++[ d( d)(y.)]d<"x=y"))(2"y;m=ord(raw_input()[-1]);_=yx=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))y;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"371>;++[ d( d)(y.)]d<"x=y"))(dy )';m=ord(input()[-1]);_='x=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))';print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39))) ``` [Try it online!](https://tio.run/nexus/python3#7ZPPSsNAEIfvPsU0JWSG/CHbtA0hrvQRvJeylG5KA20axoi7iM8eq6mCJR5EFIWwhxm@PcwwH7/WSG8xHtsFB6cXPoIfsXricx2NwggTx@YHeWSNZVXfN0jLUKwoV9Ia6XL/14nXXFYNqoiLer/eFLjZMYo4Jv@lmcYUXILXKsS0a7L0DWRnMCNyXTSBIii3cJByFkOxvytAXWDRYfNx9ER0I5OMiOzPrNe/3VeXc5J5epP7/hI0gia0Ea30tWOkdYhw8q6D1w9qUPJLSlLxuRJtgYYIDREalHwrQl7/1b3/K8T7y0Ku2vbWNrtjBckz "Python 3 – TIO Nexus") ## Explanation: For each language, I took already written quines and modified them a bit. ### Turtlèd first: Turtlèd includes the standard quine structure. however, should the input end with a 2 or a 3, it appends the end of the python code, either 2 or 3, it includes them both separately, to the quine output, and then goes back to the start and adds `x='`. Otherwise the sourcecode is left and output like a regular quine Also note it takes input twice `!!.`, because the source contains a newline which feeds to input an empty line. however, along the way to the start of string, in order to avoid the fact that the string cannot have `'` in it, it changes all the `'` in the main source along the way to `y`. if it did, quote escaping could be annoying, if even possible this relies on a trick; I could not have written `(''y)`, `(pseudocode:if cell is ', write y)`, because then that y would have been indistinguishable from a '. so, I use the y from the input "Python"! this was a real eureka moment for me. then, there are the python quinelike things. ### How the python quinelike thing works: it works like a regular quine, except it also includes the variable x if it has input Python 3, it works like a regular quine, and uses % formatting to also include the source for Turtlèd. if it has input Python 2, it replaces `input` in the string with `raw_input`, and does otherwise the exact same thing. if input is Turtlèd, it replaces the `y`s in the Turtlèd source and prints it. The two python programs function the same, and take input the same way ]
[Question] [ The Rubik's Snake (or Rubik's Twist) is a toy consisting of several triangular prisms strung together in a line in such a way that the pieces can be rotated about one another in 90 degree turns. [![unfolded](https://i.stack.imgur.com/KQmL8s.png)](https://i.stack.imgur.com/KQmL8.png) [![triplepeaks](https://i.stack.imgur.com/0jquts.png)](https://i.stack.imgur.com/0jqut.png) Any snake can be described by an ordered sequence of rotations (format described below). Some sequences do not describe physically possible, "valid", snakes because they would cause the pieces to self-intersect. Some sequences describe "cyclic" snakes, which happens when the open square faces of the first and last piece of the snake meet. Given a sequence of rotations, your task is to output whether the snake is "valid" and output whether the snake is "cyclic". # Input A sequence of length *n-1* describes a snake with *n* pieces. The index of the sequence describes the state of the interface between two pieces at that index, i.e., how those two pieces are rotated. Any alphabet with 4 letters can be used to describe the possible rotations. Here we will use: * `0` - No rotation * `1` - 90 degree rotation * `2` - 180 degree rotation * `3` - 270 degree rotation Note that this implies some chirality. For the demos below I use a left-hand rule but the choice is arbitrary as long as you are consistent. Here are some basic examples: `00000000000` - A straight, unfolded Rubik's Mini Snake (12 pieces) [![](https://i.stack.imgur.com/P8eag.gif?comment=00000000000)](https://i.stack.imgur.com/P8eag.gif) `0220` - A simple 5 piece snake    [![](https://i.stack.imgur.com/qywRn.gif?comment=0220)](https://i.stack.imgur.com/qywRn.gif) `11111111111111111111111` - A Rubik's Snake (24 pieces) consisting only of 90 degree clockwise turns [![](https://i.stack.imgur.com/cdua3.gif?comment=11111111111111111111111)](https://i.stack.imgur.com/cdua3.gif) `13131` - A "cyclic" snake that mixes clockwise and counterclockwise turns [![](https://i.stack.imgur.com/PeESk.gif?comment=13131)](https://i.stack.imgur.com/PeESk.gif) `20220200022020020220002` - A classic Rubik's Snake dog design without symmetry [![](https://i.stack.imgur.com/REiUq.gif?comment=20220200022020020220002)](https://i.stack.imgur.com/REiUq.gif) `222` - The shortest "cyclic" snake [![](https://i.stack.imgur.com/f744l.gif?comment=222)](https://i.stack.imgur.com/f744l.gif) `13133311131333111313331` - A more elaborate "cyclic" design on the Rubik's Snake [![](https://i.stack.imgur.com/jllMs.gif?comment=13133311131333111313331)](https://i.stack.imgur.com/jllMs.gif) `0022200` - Not a "valid" snake because it self-intersects [![](https://i.stack.imgur.com/YUmAo.gif?comment=0022200)](https://i.stack.imgur.com/YUmAo.gif) `00031310000` - A more elaborate invalid snake    [![](https://i.stack.imgur.com/oPevJ.gif?comment=00031310000)](https://i.stack.imgur.com/oPevJ.gif) `0003131000313` - Snakes which are not "valid" may still be "cyclic"    [![](https://i.stack.imgur.com/ykzSs.gif?comment=0003131000313)](https://i.stack.imgur.com/ykzSs.gif) `2222222` - Another invalid snake which is still "cyclic" (deceptively similar to `222`, which is valid) [![](https://i.stack.imgur.com/aXDAR.gif?comment=2222222)](https://i.stack.imgur.com/aXDAR.gif) The first image is the "Twin Peaks" pattern as found on Wikipedia (the pattern was found there, the images here are my original work). It is described by `10012321211233232123003` and is both "valid" and "cyclic". Finally, a bonus 240 piece Rubik's Snake (yes, they actually sell these) `01113133131131331311313330020013000000310000003100000013000000130022031000013211001302020031002203100001300001300003121102022011001300130031001300310031001121300003323100000013211000031000031000220000130000003100000031002022022031233213002` [![](https://i.imgur.com/TrbQ70d.gif?comment=big_kahuna)](https://i.imgur.com/TrbQ70d.gif) **Caveats** * By default, the input is a string consisting of `0`s, `1`s, `2`s, and `3`s * Must be able to handle all sequences of length 3 or greater (*n* >= 4) * If it is more practical or golf-able to handle a list of characters or a list of integers 0 thru 3, you may do so as long as it is consistent. Just be sure to specify in your answer. # Output Given a sequence as described above, your program should ouput whether the sequence describes a snake that is: * "valid" and "cyclic" (`[true, true]`) * "valid" but not "cyclic" (`[true, false]`) * not "valid" but "cylcic" (`[false, true]`) * not "valid" and not "cyclic" (`[false, false]`) **Caveats** The format of your output need not be exactly `[bool, bool]`, as long as: * There are exactly 4 possible outputs * Each possible output uniquely corresponds exactly 1-to-1 with `[true, true]`, `[true, false]`, `[false, true]`, `[false, false]` for `[valid, cyclic]` * Your chosen format is consistent for each input * Standard loopholes. Ask for clarification in comments For example, if you want your outputs to be `"alice"`, `bob`, `37`, `[]`, you may do so as long as you specify what that means in your answer. # Examples ``` INPUT=====================+=OUTPUT========== Sequence | Valid | Cyclic ==========================+========+======== 00000000000 | true | false 0220 | true | false 11111111111111111111111 | true | false 13131 | true | true 20220200022020020220002 | true | false 222 | true | true 13133311131333111313331 | true | true 0022200 | false | false 00031310000 | false | false 0003131000313 | false | true 2222222 | false | true 10012321211233232123003 | true | true | | 0111313313113133131131333 | | 00200130000003100000031 | | 00000013000000130022031 | | 00001321100130202003100 | | 22031000013000013000031 | true | true 21102022011001300130031 | | 00130031003100112130000 | | 33231000000132110000310 | | 00031000220000130000003 | | 10000003100202202203123 | | 3213002 | | ==========================+========+======== ``` --- This is `code-golf`, so shortest answer wins! [Answer] # [Python 2](https://docs.python.org/2/), ~~217 212 198~~ 194 bytes ``` from numpy import* A=any d,t,_=eye(3) p=b=t v=0 S=[] for m in input():S+=(p,d,t),;exec"t=cross(t,d);"*m;p,d,t=p+d,t,d;v|=A([all(p==P)*A([d+D,t+T])*A([d-T,t-D])for P,D,T in S]) print v,A([p,d-b]) ``` [Try it online!](https://tio.run/##pVLBioMwEL3nK0JPiUbQeFuZQ8EPKOhNQmmrZYWqwaZSYf/djRVLzK7dwsIgmZeZ954zkb36bGo@DOe2qXB9q2SPy0o2rXLQFg51j3Km2B6KviAhRRKOoFAHPkogE@jctLjCZa1D3hShH4kLRDLdQllU3IvTRsGpba5XolhOo41TRY9bkO5Im0fdF2xJdrhciATYUUcnuRsz5aZiSryUKS8WdFTasZilo1oitJO2rBXumC7SlN5R0GHIfIaDOcL5Gxrpm7gO/xF8PgQGaMbU9T6@xhMsRfkKyVTGZ89WL196Ntv/5HyNTF2mLl/S/urHOocrNSZu1TxFf/qZ5vB6ztag1lZjIdyY4f@3bw3KWgQ3/mXxBsQ3) or [Verify all test cases!](https://tio.run/##hVJNj9owEL37V4zcS7yYVT5ui3xYaS@9IFToCUWrkJjdqIljOYYWqf@dju1AFpptjfDYM89v3sxEn@x7p9Jz2VUSBFBKz3vTtaAOrT5B3erO2AfyLAp1IhW3/FXIk4wyRrTYCUuOIiZrsc3JvjPQQq3g63L1fROxp/VMRJrjE8YX8pcsqRWl6fo@srxiC/rQLnxU6JmjrRbH3@I52hZNE2khVuwBL9XshdvZJg@X@Ybb@UvOXKYVf@Ebl22dM7L6ttxER44YZJzvcsbOWMZjb02tI0ZIrY5FU1ccVGdfy1PZ1CVWuuyU5H4nldyDJyk47NgTgbem2xUNTDwkMM3mXmIm3y7oT73vR1Mr6UTiHdVUtULqL6CN1IVxAX2wBNruKHsOhepfB2J3vBK3hY6wklAN95SPvW5qGzE2PEbUtlY2ahlcp@ADOfmU9uoXglpzkPRj/OIjYZgIb4p2VxVPgZaAK8McFJbSvZmiJeAGDO4TCrHyXZY/HOFPaQj6jZGlDfkA2SJs3aWPDHCJD4JG/FWsx4/tZhf8ZSTaYPmwpUMCrIUO7DTfDqecI2BghIBRnZoHD8JGekTSLZ1hw6Nb5YWq7rSxGc3pOR4X3CzXRDT7ouklidP0LjyFSqbXPSrD3z@4nCGpy5iiqGD8Fc0dVZqmAP@jcvmyDHXc2luQS5TGEzX6RNc2xLET/3ezPkGhmUCFAsP6NGGQHsdJmqVJmqDJ/ClD1jvpQ0m43djMtS1OsjDcoHq0F7@zWHlwJ5gh8T7fdef8EBv3zCkKQxnw/p8lo/VnhAU8ar/m9SkuQvzuZzupNHwGToKr32sNtbvtDw) *-6 bytes thanks to @dingledooper!* **Input**: A list of integers from `STDIN` **Output**: A number and a boolean, printed to `STDOUT`. The number is `0` if the snake is valid, `1` otherwise. The boolean is `False` if the snake is cyclic, `True` otherwise. ### Big idea: Each snake piece fits exactly into half of a unit cube in a 3D grid. There are 12 possible orientations of a piece, corresponding to 6 ways of slicing a cube in half diagonally. Thus, each snake piece can be characterized by the `x, y, z` coordinates of the cube containing it, and the orientation of the piece within the cube. Now that we have a way to store each piece's info, we can build the snake, then detect self-intersection and cycle. If 2 pieces occupy the same cube, they intersect unless the 2 pieces are exactly opposite of each other in the cube: ![](https://i.stack.imgur.com/hT0frl.png) Example orientations that can coexists within the same cube. Image taken from [here](https://www.researchgate.net/figure/Diagonal-planes-that-are-formed-by-cutting-the-cube-diagonally-starting-at-one-of-the_fig1_220490601) ### Details **Snake building** A simple way to characterize the orientation of a piece is with 2 directions: the "in" direction \$t\$, and "out" direction \$d\$. \$d\$ and \$t\$ are always axis-aligned (since they are always perpendicular to a face of a cube). ![](https://i.stack.imgur.com/yZ7i1.png) For each piece, we store the cube position \$p\$ and the 2 directions \$d, t\$. This makes it easy to figure out the position and orientation of the next piece. Consider the piece \$(A)\$ in the figure above. If the move is \$0\$ (no turn), then the next piece will be \$(B)\$. If the move is \$(1)\$ (90 degree turn), then the next piece will be \$(C)\$. We can see that if the current piece is \$(p\_1, d\_1, t\_1)\$ and the number of turns is \$m\$, then the next piece is: $$ p\_2 = p\_1 + d\_1 $$ $$ t\_2 = d\_1 $$ $$ d\_2 = t\_1 \text{ rotated } m \text{ times around } d\_1 $$ **Cycle detection** If the snake is cyclic, then the last and first piece must be connected. This means that the "out" direction of the last piece must be the same as the "in" direction of the first piece, and their coordinates must be adjacent in that direction. If the first piece has the default value: \$p=(0,0,0), t=(0,1,0)\$, then the last piece must have the value: \$p=(0,-1,0), d=(0,1,0)\$. **Self-intersection detection** If 2 pieces intersect each other, then the following must be true: * They are in the same cube: \$p\_1 = p\_2\$ * Their orientations are not opposite of each other. The orientations of 2 pieces are opposite of each other when one of the following happens: * \$d\_1 = -d\_2\$ and \$t\_1 = -t\_2\$ * or \$d\_1 = t\_2\$ and \$t\_1 = d\_2\$ ]
[Question] [ Your task is to implement a Tetris strategy balanced in terms of score vs code size. In this version of the game tetrominoes are rotated and dropped from above into a grid of 20 rows and 10 columns. While falling, they cannot be rotated or moved horizontally. As usual, a dropped piece stops when it reaches the bottom of the grid or when further downwards motion would cause collision with an already occupied square. When `n` horizontal lines get filled completely, they collapse simultaneously, the grid is replenished with `n` empty lines at the top, and the score is incremented by 2n-1 points. For `n`=1,2,3,4 that's 1,3,7,15 points respectively. After the lines disappear, some blocks may remain floating in the air (there's no "[gravity chain reaction](https://en.wikipedia.org/wiki/Tetris#Gravity)"). When no room is available for the current piece to appear where desired, the grid is cleared, the current piece ignored, and the game continues with the next piece as current. There's no penalty for that. You should read a stream of piece types and decide how to rotate them and where to drop them. Look-ahead for the next piece (just one) is allowed: you can look at piece `i+1` before responding to `i`, but you must have decided the fate of `i` before looking at `i+2`. No look-ahead is available beyond the last piece of the input. Tetromino types and their rotations are encoded per the following table: ``` type 0 1 2 3 4 5 6 O I Z J L S T ┌────┬────┬────┬────┬────┬────┬────┐ rotation 0 │## │# │## │ # │# │ ## │### │ │## │# │ ## │ # │# │## │ # │ │ │# │ │## │## │ │ │ │ │# │ │ │ │ │ │ ├────┼────┼────┼────┼────┼────┼────┤ 1 │## │####│ # │### │ # │# │# │ │## │ │## │ # │### │## │## │ │ │ │# │ │ │ # │# │ │ │ │ │ │ │ │ │ ├────┼────┼────┼────┼────┼────┼────┤ 2 │## │# │## │## │## │ ## │ # │ │## │# │ ## │# │ # │## │### │ │ │# │ │# │ # │ │ │ │ │# │ │ │ │ │ │ ├────┼────┼────┼────┼────┼────┼────┤ 3 │## │####│ # │# │### │# │ # │ │## │ │## │### │# │## │## │ │ │ │# │ │ │ # │ # │ │ │ │ │ │ │ │ │ └────┴────┴────┴────┴────┴────┴────┘ ``` Input is binary - a sequence of bytes whose remainders when divided by 7 should be interpreted as the `OIZJLST` tetrominoes. They will occur with roughly the same probability (except that the first few types may appear slightly more often due to 256 not being a multiple of 7, but that should be negligible). Input can be from stdin or from a file named "i" or passed as an argument. You can read all of the input at once, provided you make sure to abide by the look-ahead restriction. Output is binary too - a sequence of bytes of the same length as the input. It can be stdout or a file named "o" or the result from a function. Each byte encodes `r*16 + x`, where `r` is the desired rotation and `x` is the 0-based index of the column where the leftmost square of the rotated tetromino should go. Those `r` and `x` must be valid, i.e. `0 ≤ r ≤ 3` and `0 ≤ x ≤ 10-w`, where `w` is the width of the corresponding piece. You program must be deterministic - given the same input, it has to produce exactly the same output. Using a PRNG is ok as long as it's const-seeded. The total score is the score from the game minus the size of your code in bytes. Please use the following file (64kiB of pseudo-random noise) as input: <https://gist.github.com/ngn/857bf2c99bfafc649b8eaa1e489e75e4/raw/880f29bd790638aa17f51229c105e726bce60235/i> The following python2/python3 script reads files "i" and "o" from the current directory, replays the game and prints the score (please remember to subtract your code size from the score): ``` a = [0] * 23 # grid (1square=1bit, 1row=1int, LSB is left, 3 empty rows on top) # O I Z J L S T tetrominoes t = [[[3,3],[1,1,1,1],[3,6], [2,2,3],[1,1,3],[6,3], [7,2] ], [[3,3],[15], [2,3,1],[7,4], [4,7], [1,3,2],[1,3,1]], [[3,3],[1,1,1,1],[3,6], [3,1,1],[3,2,2],[6,3], [2,7] ], [[3,3],[15], [2,3,1],[1,7], [7,1], [1,3,2],[2,3,2]]] tw = [[2,1,3,2,2,3,3],[2,4,2,3,3,2,2],[2,1,3,2,2,3,3],[2,4,2,3,3,2,2]] # widths th = [[2,4,2,3,3,2,2],[2,1,3,2,2,3,3],[2,4,2,3,3,2,2],[2,1,3,2,2,3,3]] # heights score = 0 for p, rx in zip(bytearray(open('i', 'rb').read()), bytearray(open('o', 'rb').read())): p %= 7; r = rx >> 4; x = rx & 15 # p:piece type, r:rotation, x:offset b = [u << x for u in t[r][p]] # as a bit-matrix (list of ints) bw = tw[r][p]; bh = th[r][p] # width and height y = 0 # drop it while y <= 23 - bh and all((a[y + i] & b[i]) == 0 for i in range(bh)): y += 1 y -= 1 if y < 3: # no room? a = [0] * len(a) # clear the grid and carry on else: for i in range(bh): # add the piece to the grid a[y + i] |= b[i] n = 0 for i in reversed(range(bh)): # collapse full lines if a[y + i] == (1 << 10) - 1: n += 1; del a[y + i]; a = [0] + a score += (1 << n) - 1 print(score) ``` So does the following much faster C program but it's guaranteed to work only on Linux: ``` #include<stdio.h> #include<fcntl.h> #include<sys/mman.h> #include<sys/stat.h> #define F(i,n,b...)for(i=0;i<n;i++){b;} typedef int I;typedef char C; I a[23],t[]={ 51,4369,99,802,785,54,39,51,15,306,71,116,561,305, 51,4369,99,275,547,54,114,51,15,306,113,23,561,562}; C*th="2423322213223324233222132233"; I main(){ struct stat h;stat("i",&h);I i,j,k,l=h.st_size,z=0; C*mi=mmap(0,l,1,1,open("i",0,0),0),*mo=mmap(0,l,1,1,open("o",0,0),0); F(k,l, I p=(mi[k]&255)%7,r=3&mo[k]>>4,q=r*7+p,x=mo[k]&15,y=0,h=th[q]-'0',b[4]; F(i,h,b[i]=(t[q]>>(4*i)&15)<<x) while(y<=23-h){I u=0;F(i,h,u|=a[y+i]&b[i])if(u)break;y++;} if(--y<3){F(i,23,a[i]=0)continue;} F(i,h,a[y+i]|=b[i]) I n=0;F(i,23,n+=a[i]==1023) if(n){j=23;F(i,20,a[j]=a[22-i];j-=a[j]!=1023)F(i,j,a[i]=0);z+=(1<<n)-1;}) printf("%d\n",z);return 0;} ``` The highest total score wins. Standard loopholes are forbidden. [Answer] # C, score: 4136 (4290 - 154 bytes) ``` #include <stdio.h> main(){int c,p=0,t[]={7,9,21,0,0,51,1,32,16,48,0,33,0,32,16,49};for(;(c=getchar())>=0;putchar(c)){c%=7;c=t[!c||!(10%c)?c:2*c+p++%4];}} ``` The idea is that blocks S,Z,O,I use fixed locations and rotations: ``` | s z | s s z z # # | s z # # | 0 1 2 3 4 5 6 7 8 9 ``` The rest - J,L,T - are packed into first three columns with some cyclic rotation. Ungolfed version: ``` #include <stdio.h> int main() { int c,p=0,t[] = {7,9,21,51, 1,32,16,48, 16,48,0,33, 0,32,16,49 }; while ((c=getchar())!=EOF) { switch(c%7) { case 0: c = t[0]; break; case 1: c = t[1]; break; case 2: c = t[2]; break; case 3: c = t[4+p++%4]; break; case 4: c = t[8+p++%4]; break; case 5: c = t[3]; break; case 6: c = t[12+p++%4]; break; } putchar(c); } return 0; } ``` ]
[Question] [ (This might be quite classic but this is my first post here, so I'm not ready for the fancy stuff yet) The [Goodstein sequence](http://mathworld.wolfram.com/GoodsteinSequence.html) is defined for an input number as follows: *Pick a starting number **n**, let **b**=2 and repeat:* * *write **n** in heriditary base **b** notation* * *substitute all the (**b**)s to (**b**+1)s in **n** and substract 1* * *output the new decimal evaluation of **n*** * *increment **b*** Hereditary Base notation is a decomposition of a number where the basis is the bigger number to appear. Examples: * `83` in HB3: `3^(3+1)+2` * `226` in HB2: `2^(2^(2+1))+2^(2+1)+2` Goodstein sequences [always end up at 0](https://www.wikiwand.com/en/Goodstein%27s_theorem), but they tend to first get quite big quite fast so it is not asked to output the complete sequence. --- **Task:** Given an input number in any reasonable format, your job is to output the Goodstein sequence for this number at least until it reaches 10^25 or 0 **Examples:** ``` Input: 3 Output: 3, 3, 3, 2, 1, 0 Input: 13 Output: 13, 108, 1279, 16092, 280711, 5765998, 134219479, 3486786855, 100000003325, 3138428381103, 106993205384715, 3937376385706415, 155568095557821073, 6568408355712901455, 295147905179352838943, 14063084452067725006646, 708235345355337676376131, 37589973457545958193377292 Input: 38 Output: 38, 22876792454990 ``` --- **Details:** * Input number can be an array, a string, an integer, as long as it is in decimal base * Output follows the same rule * Separation of the terms in the output can be spaces, new-lines, or any reasonable separation * As soon as the sequence becomes larger than 10^25, your program may exit normally, throw an error/exception, or continue (no restriction) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins * Of course, [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden * Python ungolfed working example [here](https://tio.run/##jVRNj5swEL3zK6ZaRUCaZje7t0hZqVV7bS@9pZHlwJC1CjYxZrf59enYOGBCWi0ne/zmzdcb6pN5UfLpfM5K3jTwhTe4joC@HAtgTEhhGEsaLIsF7Okx7V7tZ43LPWycPeqdeHuoUBrnM0V/3MAqCgJorLUPEIA1mlZLaIxOOr80iiLrkGOmqlo1mMj9KKEj5SH3njijSykak6TOgHR9cKe3F1EiYT@QYYh2XIAmyPH@3hIuifg46049JGu1hSR6AZj2VlGQ45jLmxGeoaMYP11xDeWgryYdwbF0XJvNe8ic/whA9Ete1yjzxOKGR@zmELSaoL7F@MrLlptJhykTc6qtOQXRgJBmMi8/gCvkoKkR1HfXlRjCTVuXt/Dbh92868J8HuS4Xe3C0id0VgdTYbVVsu1JhCeAQmkQVBlF210Ud0CJ2qIaw7XxvZDUcnd3N@tMBltn8pgGQpPwPBLHHdSa@pbEFgqzPIaZH2w6xfwy3vK9rfao1x4vB2gHDAxGn8YKySmtYGVuaSSI99UjhRFKUrzGxrM7mF/J0uV82fN/0tnr5w6E@f/obDf7YeSXYXzyAnVT/ZNhbeDHK@qiVG/ftFZ6fTvuT6Wg5PqAVqF4QFqMjEupDGRKGiFbjK@K0ch/07CF/R1JXiFjduFixiouJGNxF6jXweopjc7nvw "Python 3 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 77 bytes `(&2)` is an anonymous function taking an `Integer` and returning a (potentially very long) list of `Integer`s, use as `(&2) 13`. ``` (&2) n&b|n<0=[]|let _?0=0;e?n=(e+1)?div n b+mod n b*(b+1)^0?e=n:(0?n-1)&(b+1) ``` [Try it online!](https://tio.run/##LYtLCsIwFAD3PUUWUl7UltQiiBqz8ALdKfgjta82mL5KU@3Gsxs/OJuBgam0u6K1vtaGpKEOW33uBneyhtDFtb5BwP7AnqKVq5oeaNzpK24qYxGWMhHHyZRDyYhzHreoi9/C475pCxeUcu8hnPCAwvxJSyF3h6fFjp2UkGKBiiTgKOGqMA9GLB/VTfH1EPJPPQqFkuYgFEUJD3/N@5QlKUtnr3Np9cX5aLvOsjc "Haskell – Try It Online") (cuts off at `10^25`.) # How it works * `(&2)` starts the sequence with base `2`. * `n&b` calculates the subsequence starting with the number `n` and base `b`. + It halts with an empty list if `n<0`, which generally happens the step after `n==0`. + Otherwise, it prepends `n` to the list returned recursively by the expression `(0?n-1)&(b+1)`. * `?` is a local function operator. `0?n` gives the result of converting `n` to hereditary base `b`, then incrementing the base everywhere. + The conversion recurses with the variable `e` keeping track of the current exponent. `e?n` converts the number `n*b^e`. + The recursion halts with `0` when `n==0`. + Otherwise, it divides `n` by the base `b`. - `(e+1)?div n b` handles the recursion for the quotient and next higher exponent. - `mod n b*(b+1)^0?e` handles the remainder (which is the digit corresponding to the current exponent `e`), the increment of base, and converting the current exponent hereditarily with `0?e`. [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~28~~ 26 bytes ``` .V2JbL&bs.e*^hJykb_jbJ=ty ``` The trailing newline is significant. [Try it online!](https://tio.run/##K6gsyfj/Xy/MyCvJRy2pWC9VKy7DqzI7KT4rycu2pJIr8P9/Q2MA "Pyth – Try It Online") (This link includes an extra `Q` not needed by the current version of Pyth.) ### How it works ``` .V2JbL&bs.e*^hJykb_jbJ=ty .V2 for b in [2, 3, 4, ...]: Jb assign J = b L def y(b): &b b and jbJ convert b to base J _ reverse .e enumerated map for values b and indices k: hJ J + 1 ^ yk to the power y(k) * b times b (newline) print Q (autoinitialized to the input) y y(Q) t subtract 1 = assign back to Q ``` It’s important that `y` is redefined in each loop iteration to prevent memoization across changes to the global variable `J`. ]
[Question] [ I'm at position **(0, 0)** of an infinite two-dimensional city, which is perfectly divided into blocks centered at each lattice point, some of which contain buildings. A building at a certain point **(x, y)** takes up the entire square with opposite corners at **(x-.5, y-.5)** and **(x+.5, y+.5)**, including its border. A building is visible iff there is some line segment from **(0, 0)** to a point in the building which does not intersect any other building. For example, I (the `@`) can see 6 buildings (`*`) in the following city: ``` * * * *@ x** * y ``` I can't see the building marked with an `x`, at **(-1, -1)** because it's obstructed by the two adjacent to it; or the one marked with a `y` at **(3, -2)** because it's obstructed by the edge of the **(1, -1)** building. ### Input A multiline string, or list of lines, optionally padded with spaces into a rectangle. It will contain only: * a single `@` (my position) * Spaces * `*`, which represent buildings. There will always be at least one building, and therefore at least one visible building. ### Output The number of visible buildings. ### Test cases ``` *@ 1 * ******* @ * 7 ***** **@** ***** 4 * ** @ ** 2 * * * * @ 4 @ * *** 1 ``` *Thanks to @Geobits for the [title](https://en.wikipedia.org/wiki/Cities%3a_Skylines).* [Answer] # Unity + C#, 589 bytes This is probably the worst language to do a code golf in (read: worse than Java), but Unity comes with a lot a helpful features for this challenge. EDIT: missed a couple of spaces, returns list length, not counter Golfed: ``` using UnityEngine;using System.Collections;public class c:MonoBehaviour{public int h(string[]i){ArrayList k=new ArrayList();for(int y=0;y<i.Length;y++){char[]l=i[y].ToCharArray();int x=0;foreach(char c in l){if(c=='*'){GameObject b=GameObject.CreatePrimitive(PrimitiveType.Cube);b.transform.position=new Vector3(x,y);}if(c=='@')transform.position=new Vector3(x,y);x++;}}for(int n=0;n<3600;n++){RaycastHit h;Physics.Raycast(transform.position,Quaternion.Euler(0,0,n/10)*Vector3.up,out h);if(h.collider!=null){GameObject o=h.collider.gameObject;if(!k.Contains(o))k.Add(o);}}return k.Count;}} ``` Ungolfed: ``` using UnityEngine; using System.Collections; public class citiessightlines : MonoBehaviour { public ArrayList todelete; // Anything concerning this array just has to do with cleanup of //objects for testing, and doesn't contribute to the byte count. void Start() { todelete = new ArrayList(); } public int calcSight(string[]input) { todelete = new ArrayList(); int total = 0; ArrayList check = new ArrayList(); for (int y=0;y < input.Length; y++) { char[] line = input[y].ToCharArray(); for (int x = 0; x < line.Length; x++) { char c = line[x]; if (c == '*') { GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube); cube.transform.position = new Vector3(x, y); todelete.Add(cube); } if (c == '@') { transform.position = new Vector3(x, y); } } } for (int angle=0; angle < 3600; angle++) { RaycastHit hit; Physics.Raycast(transform.position, Quaternion.Euler(0, 0, angle/10) * Vector3.up, out hit); if (hit.collider!=null) { GameObject hitObject = hit.collider.gameObject; if (!check.Contains(hitObject)&&hitObject!=this) { total += 1; check.Add(hitObject); } } } return total; } } ``` I used 3600 raycasts because it fails the 5th test case with lower. It still might fail for even larger/more precise test cases. Unfortunately, both webgl and desktop builds seem to break, so all I have is the source code to test with [on github](https://github.com/jediguy13/citiessightlines). [Answer] ## Java 8 lambda, ~~1506~~ ~~1002~~ ~~972~~ 942 characters I wanted to beat this challenge, as it is very interesting. The result ~~(not very golfy)~~ can be seen here: ``` import java.util.*;f->{Set<double[]>B=new HashSet(),r,n;double a,M,m,P=Math.PI*2,z=.5;int x=0,y,v=0,i,j,c[],p,q,l=g.length;for(;x<l;x++)for(y=0;y<g[x].length;y++)if(g[x][y]>63)for(;;){c=new int[]{-1};M=2e31-1;for(i=0;i<l;i++)for(j=0;j<g[i].length;j++)if(g[i][j]==42)if((m=(p=x-i)*p+(q=y-j)*q)<M){M=m;c=new int[]{i,j};}if(c[0]<0)break;g[c[0]][c[1]]=0;double[]A={(a=Math.atan2((c[1]-=y)-z,(c[0]-=x)-z))<0?a+P:a,(a=Math.atan2(c[1]+z,c[0]-z))<0?a+P:a,(a=Math.atan2(c[1]+z,c[0]+z))<0?a+P:a,(a=Math.atan2(c[1]-z,c[0]+z))<0?a+P:a};r=new HashSet();M=-P;m=P;for(double d:A){M=d>M?d:M;m=d<m?d:m;}r.add(new double[]{m,M});for(double[]t:B){n=new HashSet();for(double[]h:r)for(double[]u:t[0]<h[0]?t[1]<h[0]?new double[][]{h}:t[1]<h[1]?new double[][]{{t[1],h[1]}}:new double[0][]:t[0]>h[1]?new double[][]{h}:t[1]>h[1]?new double[][]{{h[0],t[0]}}:new double[][]{{h[0],t[0]},{t[1],h[1]}})if(u[0]<u[1])n.add(u);r=n;}B.addAll(r);if(!r.isEmpty())v++;}return v;} ``` Of course this also exists in the ungolfed version: ``` import java.util.*; public class AngleCheck { static int getViewableBuildingsC(char[][] grid) { Set<double[]> blocked = new HashSet(), ranges, newRanges; double angle, max, min, PI2 = Math.PI * 2, half = 0.5; int x = 0, y, viewable = 0, i, j, building[], dX, dY, length = grid.length; for (; x < length; x++) { for (y = 0; y < grid[x].length; y++) { if (grid[x][y] > 63) { for (;;) { building = new int[]{-1}; max = 2e31-1; for (i = 0; i < length; i++) { for (j = 0; j < grid[i].length; j++) { if (grid[i][j] == 42) { if ((min = (dX = x - i) * dX + (dY = y - j) * dY) < max) { max = min; building = new int[]{i, j}; } } } } if (building[0] < 0) break; grid[building[0]][building[1]] = 0; double[] angles = { (angle = Math.atan2((building[1] -= y) - half, (building[0] -= x) - half)) < 0 ? angle + PI2 : angle, (angle = Math.atan2(building[1] + half, building[0] - half)) < 0 ? angle + PI2 : angle, (angle = Math.atan2(building[1] + half, building[0] + half)) < 0 ? angle + PI2 : angle, (angle = Math.atan2(building[1] - half, building[0] + half)) < 0 ? angle + PI2 : angle}; ranges = new HashSet(); max = -PI2; min = PI2; for (double d : angles) { max = d > max ? d : max; min = d < min ? d : min; } ranges.add(new double[]{min, max}); for (double[] reference : blocked) { newRanges = new HashSet(); for (double[] currentRange : ranges) { for (double[] subRange : reference[0] < currentRange[0] ? reference[1] < currentRange[0] ? // whole range after referencerange new double[][]{currentRange} : reference[1] < currentRange[1] ? // lower bound inside referencerange, but upper bound outside new double[][]{{reference[1], currentRange[1]}} : // whole range inside referencerange -> nothing free new double[0][] : // greater or equal lower bound reference[0] > currentRange[1] ? // whole range before referencerange new double[][]{currentRange} : // ranges overlap reference[1] > currentRange[1] ? // range starts before and ends in reference range new double[][]{{currentRange[0], reference[0]}} : // referencerange is in the range -> two free parts, one before, one after this new double[][]{{currentRange[0], reference[0]}, {reference[1], currentRange[1]}}) { if (subRange[0] < subRange[1]) newRanges.add(subRange); } } ranges = newRanges; } blocked.addAll(ranges); if (!ranges.isEmpty()) { viewable++; } } } } } return viewable; } } ``` So it looks very difficult but it's way easier than one might think. My first idea was to use some intersection algorithm to check whether a line from my position to the building can be made without any intersections. To do this I decided to use the Cohen-Sutherland algorithm and draw lines to all four corners of the building. This worked pretty well for the first tests, but the last one failed. I soon found out, that it's a case where you can't see the corners but a part of an edge. So I thought about some sort of ray casting like @Blue did it. I put that challenge away, as I didn't got some progress. Then I saw Blue's answer and the following simple idea came to my mind: Each building blocks some angle in which nothing else can be seen. I just need to keep track of what can be seen and what is already hidden by other buildings. That's it! The algorithm works as follows: It determines the building with the smallest distance to the person. Then we imagine four lines drawn from the person to the corners of the building. Two of these have an extreme value: The minimum and maximum angle in which the building can be seen. We take them as a range and compare them with other buildings of which we know that they can be seen (none at the beginning). The ranges may overlap, include each other or don't touch at all. I compare the ranges and get some new ranges of the building which aren't hidden by the viewable buildings. If there is something remaining after comparing it with the buildings in-sight the building is also viewable. We add the remaining angle range to the list of ranges to compare to and start off with the next building with the next longer distance. Sometimes the ranges may overlap in a way that I end up with a range of 0 degrees. These ranges will be filtered to don't mistakenly add a building that isn't even viewable. I hope someone understood this explanation :) ~~I know this code isn't golfed very much, I'll do this asap.~~ That was a really challenging task. You thought you found a solution that works but instead you are far away still. I think this solution works pretty good. It isn't very fast but at least it works ;) Thanks for that puzzle! --- **Update** I found the time to golf the whole thing down into a single function, which thus can be turned into a lambda. All functions were only called once and thus can be put into one method. I switched from lists to sets as this saves some additional characters. The declarations have been put together. The comparisons have been put together and characters were replaced by there ascii value. The range comparing can be expressed as many ternaries. Some tricks here and there to prevent long expressions like Double.NEGATIVE\_INFINITY got done. Where possible inline assigments are done. To save a bit more I switched from comparing the angles in degrees to comparing the radians. The whole change saved over 500 characters, I hope to get it all under 1000 though ;) I removed the generics where possible and shortened the return comparison by creating an one element array and check it's value instead. I also replaced the Double.NEGATIVE\_INFINITY with PI2 and -PI2 as these are the upper and lower bounds of the angles. Now it's finally under 1000 chars long! I merged the loops for finding the persons location and the building iterator to save some characters. Unfortunately this requires us to move the return out of the loop and still use a break but this time without a label. I merged `max` and `distanceSquared` and `min` and `newDistanceSquared` as they aren't required at the same time. I changed `Integer.MAX_VALUE` to `2e31-1`. Also I created a constant `half = 0.5` which is used to calculate the corners of the building. This is shorter in the golfed version. Overall we saved another 30 characters! ]
[Question] [ # Challenge You will be making a program/function that takes a string input of length `n`, and: 1. Puts the `kth` char at the center of the space, where `k = (n+1)/2`. This will be the location of your ground zero. 2. Puts the rest of the non-whitespace chars randomly arranged around ground zero. The Pythagorean distance from the char must not exceed `n`. 3. Outputs the result. **If you need clarifications, see the example below.** --- ## Rules * Standard loopholes apply! * I/O must be in the form of a string. * Input will always be odd to ensure that you have a central char to put at ground zero. * Every valid output should occur with a non-zero probability. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest code in bytes wins! --- ## Example Input: `qwert` The boundaries of the explosion emanating from ground zero (x's mark valid places for the rest of the chars to be): ``` x xxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxexxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxx x ``` Example output: ``` t r q e w ``` [Answer] # JavaScript (ES6), 211 ~~216 220~~ **Edit** 1 byte saved thx @usandfriends ``` s=>[...s].map((c,i)=>{for(R=_=>Math.random()*h-l|0;x=R(y=R()),!(i-(l/2|0)?x|y&&x*x+y*y<=l*l&g[y+=l][x+=l]<'!':x=y=l););z=[...g[y]],z[x]=c,g[y]=z.join``},l=s.length,g=Array(h=l-~l).fill(' '.repeat(h)))&&g.join` ` ``` **Test** ``` f=s=>[...s].map((c,i)=>{for(R=_=>Math.random()*h-l|0;x=R(y=R()),!(i-(l/2|0)?x|y&&x*x+y*y<=l*l&g[y+=l][x+=l]<'!':x=y=l););z=[...g[y]],z[x]=c,g[y]=z.join``},l=s.length,g=Array(h=l-~l).fill(' '.repeat(h)))&&g.join` ` // Less golfed U=s=>( l=s.length, h=l-~l, // l+l+1 g=Array(h).fill(' '.repeat(h)), [...s].map((c,i)=>{ for(R=_=>Math.random()*h-l|0; x=R(y=R()), // set x,y to a random value in range -l ... l !(i - (l/2|0) // check if at mid point of input string ? x|y && // if not, check x and y must not be both 0 x*x + y*y <= l*l & // then check position inside the circle of ray L g[y+=l][x+=l] < '!' // then add offset L and check if position is not already used : x=y=l // if at midpoint in input string, x and y have fixed value L ); ); // loop until valid position found z = [...g[y]]; // modify string at current position: convert to array ... z[x] = c; // ... set element ... g[y] = z.join`` // ... back to string }), g.join`\n` ) setInterval(_=>O.textContent=(f(I.value)),1000) ``` ``` Word <input id=I value='qwert'><pre id=O></pre> ``` [Answer] # Ruby, ~~211~~ ~~207~~ ~~203~~ 196 characters Thanks to edc65 for 4 characters ``` ->(x){x=x.chars o,b,c=x.size l=o*2+1 a=Array.new(l){Array.new l,' '} a[o][o]=x.delete_at o/2 a[b][c]=x.pop if a[b=rand(l)][c=rand(l)]==' '&&(b-o)**2+(c-o)**2<=o*o while x[0] a.map(&:join).join $/} ``` Explanation: `->(x){...}` define an anonymous function that takes in an argument `x` `x=x.chars` transform `x` from a string into an array of one-character strings `o,b,c=x.size` store the length of the input in `o` for later use. `b` and `c` simply need to be initialized to *something*, so save 2 characters by attaching to a previous assignment. `l=o*2+1` this is the length/width of the field where all characters could possibly go, also the diameter of the explosion circle. `Array.new(l){Array.new l,' '}` make an `l`x`l` sized 2D array of space characters. `a[o][o]=x.delete_at o/2` sets the center of the array to the center of the values of `x` (the input), while deleting that value from `x` `... while x[0]` run the block (in this case, the code before `while` because it is inline) over and over until `x` is empty. In ruby, accessing an index that does not exist returns `nil`, which is a falsey value. `a[b=rand(l)][c=rand(l)]==' '` Assign `b` and `c` to random values where 0 <= *n* < `l`. Then check if the spot at `b`,`c` is empty (aka is set to space character) `(b-o)**2+(c-o)**2<=o*o` Pythagorean distance check. `o` is the length of the input. `**` is ruby's exponentiation operator, and `val<=o*o` is shorter than `val**0.5<=o`. `a[b][c]=x.pop` delete the last value from `x`. Set the position `a`,`b` to that value in array `a` `a[b][c]=x.pop if a[b=rand(l)][c=rand(l)]==' '&&(b-o)**2+(c-o)**2<=o*o while x[0]` Set a random position to the last value if that position is free and is within the explosion radius; keep doing this until we run out of characters to place. `$/` is set to the operating system's newline. It's also shorter than `"\n"` `a.map(&:join).join $/` Map all the arrays in `a` to a single-string version of themselves (eg `['a','b','c']` -> `'abc'`). Take that new array and join it with newlines. Implicit return. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~68~~ ~~66~~ ~~65~~ ~~63~~ 62 bytes ``` {⍵@(n⊣¨¨@(⊢≡¨⌽)i[n?≢i←⍸(××n≥*∘.5)+.ר⍨n-⍳s])⊢''⍴⍨s←2⍴1+2×n←≢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Bk9aPerQ4aeY@6Fh9acWiFg8ajrkWPOhceWvGoZ69mZnSe/aPORZlAZY96d2gcnn54et6jzqVajzpm6Jlqausdng5U17siT/dR7@biWE2gVnX1R71bgELFQC1GQKahthFID1B/5yKgRbX//6epF5anFpWoAwA "APL (Dyalog Classic) – Try It Online") `{ }` anonymous function with argument `⍵` `n←≢⍵` variable `n` is the length `s←2⍴1+2×n` variable `s` is the shape of the result: 2n+1 by 2n+1 `''⍴⍨s` create a square of spaces with that shape `A@I⊢B` puts elements `A` at (pairs of) indices `I` in matrix `B` `+.ר⍨n-⍳s` squared distances from the centre of the matrix `(××n≥*∘.5)` boolean matrix indicating where those distances are non-zero and `≤n` `⍸` coordinate pairs for the 1s in the boolean matrix `i[n?≢i← ... ]` choose n of them randomly (no duplicates) `n⊣¨¨@(⊢≡¨⌽)` change the central one to `n n` `⍵@( ... )⊢ ...` put the chars from the argument at the given indices in the matrix of spaces [Answer] # [Python 3](https://docs.python.org/3/), 286 bytes ``` import random as r i=input() l=len(i) a=range(-l,l+1) g=[(y,x)for y in a for x in a] p=[(y,x)for y,x in g if abs(x+y*1j)<=l and x|y] m=i[l//2] d=[*i.replace(m,"",1).center(len(p))] r.shuffle(d) o="" for c in g: o+=m if c==(0,0)else d.pop()if c in p else" " if c[1]==l:o+="\n" print(o) ``` [Trying it online is an option.](https://tio.run/##TY5BboQwDEXX41NYWcVDygztblSfhLKgEJhUJokCI4HUu1PCqruv5//1HLflGfzHvrsphrRgan0fJmxnTODY@fhaNIGwWK8dQctHYbT6TYwUFcHItd7MSkNIuKHz2GKO6xkbiP/P5qQjugHb71mvxXatfuiTBQ8nrr9bAxO7Wm639wZ6rq@uTDZK21k9GaVMRWVn/WKTzs9EogZSOT9fwyBW9wSBlYJs6k7PAy6h4CnrOmZ9N3eyMlvsyxiipoxzL2KmChVcMqqrhlkex1J9eQUxOb/oQPv@tCLhDw "Python 3 – Try It Online") Whoops, stumbled onto this due to recent activity, didn't notice it was over two years old somehow until I spent a good while on this. Well, two answers is kind of sad, so this is probably a good idea to post anyway. I'm sure there are dozens of ways to improve on this—didn't notice until just now that input is always odd, which would've been helpful to know. ## Explanation `i=input()` is input, of course, `l=len(i)` is saving the length of the string because it's used quite a few times. `a=range(-l,l+1)` — a quick tool to create an iterator ranging the available distances away from the origin both ways along one dimension. `g=[(y,x)for y in a for x in a]` builds a list of tuple coordinates that makes up the entire final grid. `p=[(y,x)for y,x in g if abs(x+y*1j)<=l and x|y]` creates a subset of the list containing only the coordinates that non-center letters can possibly land on. `m=i[l//2]` establishes the center character. `d=[*i.replace(m,"",1).center(len(p))]` — the center character's taken out, leaving us with the other debris. The `center()` function is very nice here, because it allows us to pad out the line (with by default a space) until it's a certain number of characters long. Here, that's the number of spaces the letters can land on, thus mirroring the distribution we need. `r.shuffle(d)` naturally shuffles said distribution to be actually... distributed. The loop, `for c in g: o+=m if c==(0,0)else d.pop()if c in p else" "`, looks over the entire square of feasible tiles, regardless of anything possibly landing on it or not, and as necessary, adds a character to our output string `o`. Characters are popped out of our sample of debris so that they only appear once. `if c[1]==l:o+="\n"` — Adds line breaks as well. Returns. ]
[Question] [ Shocking news: Dr. Mad J Scientist has released a proof of P = NP to the world. But the proof is nonconstructive, and she's keeping the algorithm to herself. Worry not. Without even looking at her proof, we can still (almost) write a computer program that solves NP-complete problems in polynomial time. # The Problem Input a list of integers, such as `[-10, -4, 1, 1, 2, 6, 8]`. Output a nonempty sublist that sums to 0, such as `[-10, 1, 1, 2, 6]`. The output list can be in any order. Ignore any integer overflow issues in your language. **If P = NP, your program must provably run in polynomial time on solvable inputs.** Your program may act arbitrarily on inputs with no solution. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest code wins. **Yes, this challenge is possible.** One approach is as follows: > > Enumerate all possible computer programs \$P\_0, P\_1, P\_2, \dots\$ > > Repeat as \$i\$ goes from 0 to \$\infty\$: > > ----- Run the first \$i\$ programs on the input list, for \$i\$ steps each. > > ----- For each output you get, check whether it's a valid subset sum solution. If so, return it. > > > This works because, if P = NP, then some program \$P\_m\$ solves subset-sum in some polynomial time \$O(n^k)\$. Therefore, the above algorithm will output a solution on the \$\max(m, O(n^k))\$th iteration of the loop, if not before. Therefore, the above algorithm runs in polynomial time on solvable inputs. Note: A proof that P ≠ NP would allow a 0-byte solution to this problem. Good luck with that :) **Notes** Before you start `eval`ing all strings in a language like Python, let me point out that [some of those strings will reformat your hard drive](https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html). This challenge does not run afoul of [the no famous open questions rule](https://codegolf.meta.stackexchange.com/questions/11033/are-challenges-that-may-not-be-solvable-on-topic-for-ppcg), because although it is related to P vs NP, this challenge is solvable. [Answer] # [Python 3.8](https://docs.python.org/3/) (on Unix), 429 bytes Since nobody else has posted an answer yet, I thought I'd have a go, though I not 100% certain I haven't missed something important (and I *am* 100% certain the code could be shrunk down significantly). As noted in the question, evaluating arbitrary Python strings is dangerous. Fortunately, it's easy to come up with a safe subset of strings whose evaluation is still Turing complete, by embedding the Turing complete [While Programming Language](http://profs.sci.univr.it/~merro/files/WhileExtra_l.pdf), summarised below: [![enter image description here](https://i.stack.imgur.com/x2RpN.png)](https://i.stack.imgur.com/x2RpN.png) This can be embedded into Python using only strings that match the following regex: ``` ^([0-9 \n():_=+-]|while)+$ ``` To reduce the number of necessary characters, we use a few embedding hacks: * variable names are built only of underscores * `if B then C1 else C2` is emulated using while loops (and temporary variables x and y, which hang around afterwards but that's ok): ``` x=B;y=not x while x:C1;x=False while y:C2;y=False ``` * skip is emulated using any constant expression, e.g. `0` * true is emulated using e.g. `0==0` * false is emulated using e.g. `0==1` * `B & C` is emulated using a pre-evaluated if-then-else (and another temporary variable x): ``` if B then x=C else x=False ``` * `¬ B` is emulated using `1-B` To make our life easier, we also allow `[` and `]`, as this permits direct operations on lists (including slicing and concatenation) which avoids having to translate the problem from one on lists into one on integers. *Update*: as noted by @ØrjanJohansen, it's also necessary to include `<` to ensure basic arithmetic remains polynomial. **I claim that any program with just those characters will either execute, or (far more likely) fail to execute, or raise an exception, but will *not* crash the interpreter or change any global state. Please correct me if I'm wrong.** The rest of the solution is now similar to the prototype presented in the question. We generate all strings of increasing lengths *n* and execute them, prepopulating the input in variable `_` and checking and validating any output from the same variable. We catch any raised exceptions and continue. The main tricky bit is ensuring polynomial complexity (and termination). We do this by breaking out of each execution after `n` seconds, using Unix signals and a handler that raises an exception (which the string executions themselves have no way of catching). Since every program will appear repeatedly (eg with trailing whitespace), we don't need to worry about breaking out too soon from a correct program. One tricky bit here is to make sure that the program doesn't crash if the signal is received *after* the execution completed (successfully or not) but *before* the signal has been reset; this explains the nested try-catch. ``` from itertools import* from re import* from signal import* I=eval(input()) signal(SIGALRM,0) for n in count(): for p in product(*[set(map(chr,range(128)))]*n): if match("([0-9 \n()[\]:_=<+-]|while)+$",(s:="".join(p))): try: try: g={'_':I[::]};alarm(n);exec(s,g);h=g['_'] if h and all(h.count(x)<=I.count(x)for x in h)and sum(h)==0: print(h);n=-1;break except:0 alarm(0) except:0 if n<0:break ``` [Try it online!](https://tio.run/##VVDPT4MwFL7zVzTEZK8bW5i7zLIePBkSveiRkaWyjlahbUpRFvVvxwJmZqe@9/3I976asxNabbbG9v3J6hpJx63TumqQrI22bh6MsOXXeyNLxaoLllL@wSqQyrQOMA4mGl7Sh/vH56coxsFJW6SQVKjQrfIaEqABMgNkrD62hYN51nAHNTNQCBtZpkoO69stxjifq8GB5AnVzBUCQsji5R3aK8DZPicHuljm359CVhwvbsIIGkLDcPWmpQLj/YMXOXse3/8BlfRrdpiRNCMk/0lYxWwNCie84wU0UYkTQcvMK/JJ7uMFYuqIWFWBWE1VOryj6WUeSnVDKYEHYdPWIDCl8V@g7yq9TuBE0eU6ebWcvY8M7wpuHInHZTrE/9oV4dPVLiajp@@zOFpHt9Em/wU "Python 3.8 (pre-release) – Try It Online") (though don't expect an actual result; it may be P but it's obscenely slow) ]
[Question] [ In Dungeons & Dragons 5th edition (as well as most other editions), there exists a magic item called the [*Deck of Many Things*](http://www.5esrd.com/gamemastering/magic-items/wondrous-items/#Deck_of_Many_Things). It is an incredibly powerful item, as the cards all have very strong positive or negative effects. To use the deck, a character declares a number, and then draws up to that number of cards, with the effects applying in sequence. If the character does not draw all of the cards that they declared, and it has been at least 1 hour since the last card has been drawn, the rest of the cards are automatically drawn for them and the effects applied. After each card is drawn, it is returned to the deck, and the deck is shuffled. The following is a list of the effects of drawing each of the cards1: * **Balance**: Your mind suffers a wrenching alteration, causing your alignment to change. Lawful becomes chaotic, good becomes evil, and vice versa. If you are true neutral or unaligned, this card has no effect on you. * **Comet**: If you single-handedly defeat the next hostile monster or group of monsters you encounter, you gain experience points enough to gain one level. Otherwise, this card has no effect. * **Donjon**: You disappear and become entombed in a state of suspended animation in an extradimensional sphere. Everything you were wearing and carrying stays behind in the space you occupied when you disappeared. You remain imprisoned until you are found and removed from the sphere. You can’t be located by any divination magic, but a wish spell can reveal the location of your prison. You draw no more cards. * **Euryale**. The card’s medusa-like visage curses you. You take a -2 penalty on saving throws while cursed in this way. Only a god or the magic of The Fates card can end this curse. * **The Fates**: Reality’s fabric unravels and spins anew, allowing you to avoid or erase one event as if it never happened. You can use the card’s magic as soon as you draw the card or at any other time before you die. * **Flames**: A powerful devil becomes your enemy. The devil seeks your ruin and plagues your life, savoring your suffering before attempting to slay you. This enmity lasts until either you or the devil dies. * **Fool**: You lose 10,000 XP, discard this card, and draw from the deck again, counting both draws as one of your declared draws. If losing that much XP would cause you to lose a level, you instead lose an amount that leaves you with just enough XP to keep your level. * **Gem**: Twenty-five pieces of jewelry worth 2,000 gp each or fifty gems worth 1,000 gp each appear at your feet. * **Idiot**: Permanently reduce your Intelligence by 1d4 + 1 (to a minimum score of 1). You can draw one additional card beyond your declared draws. * **Jester**: You gain 10,000 XP, or you can draw two additional cards beyond your declared draws. Discard this card after drawing it. * **Key**: A rare or rarer magic weapon with which you are proficient appears in your hands. The GM chooses the weapon. * **Knight**: You gain the service of a 4th-level fighter who appears in a space you choose within 30 feet of you. The fighter is of the same race as you and serves you loyally until death, believing the fates have drawn him or her to you. You control this character. * **Moon**: You are granted the ability to cast the wish spell 1d3 times. * **Rogue**: A nonplayer character of the GM’s choice becomes hostile toward you. The identity of your new enemy isn’t known until the NPC or someone else reveals it. Nothing less than a wish spell or divine intervention can end the NPC’s hostility toward you. * **Ruin**: All forms of wealth that you carry or own, other than magic items, are lost to you. Portable property vanishes. Businesses, buildings, and land you own are lost in a way that alters reality the least. Any documentation that proves you should own something lost to this card also disappears. * **Skull**. You summon an avatar of death - a ghostly humanoid skeleton clad in a tattered black robe and carrying a spectral scythe. It appears in a space of the GM’s choice within 10 feet of you and attacks you, warning all others that you must win the battle alone. The avatar fights until you die or it drops to 0 hit points, whereupon it disappears. If anyone tries to help you, the helper summons its own avatar of death. A creature slain by an avatar of death can’t be restored to life. * **Star**: Increase one of your ability scores by 2. The score can exceed 20 but can’t exceed 24. * **Sun**: You gain 50,000 XP, and a wondrous item (which the GM determines randomly) appears in your hands. * **Talons**: Every magic item you wear or carry disintegrates. Artifacts in your possession aren’t destroyed but do vanish. * **Throne**: You gain proficiency in the Persuasion skill, and you double your proficiency bonus on checks made with that skill. In addition, you gain rightful ownership of a small keep somewhere in the world. However, the keep is currently in the hands of monsters, which you must clear out before you can claim the keep as yours. * **Vizier**: At any time you choose within one year of drawing this card, you can ask a question in meditation and mentally receive a truthful answer to that question. Besides information, the answer helps you solve a puzzling problem or other dilemma. In other words, the knowledge comes with wisdom on how to apply it. * **The Void**: This black card spells disaster. Your soul is drawn from your body and contained in an object in a place of the GM’s choice. One or more powerful beings guard the place. While your soul is trapped in this way, your body is incapacitated. A wish spell can’t restore your soul, but the spell reveals the location of the object that holds it. You draw no more cards. (card descriptions copied from the [D&D 5th edition SRD](http://dnd.wizards.com/articles/features/systems-reference-document-srd)) Some especially foolish players will draw a large number of cards at once, hoping to get at least one powerful boon to balance out the detrimental cards. As one might expect, this often results in the character's death or inability to continue to draw cards. ## The Challenge Simulate repeated drawing from a 22-card *Deck of Many Things*, outputting each card drawn, stopping only when one of the following conditions is met: * The character dies (via drawing **Skull**, or drawing 5 cards after drawing **Flames** or **Rogue**, without the benefit of **The Fates** or **Moon** active2). * The character is incapable of drawing more cards (via the effects of **Donjon**, **Talons**, **The Void**3, or the character's Intelligence score dropping to 3 or lower via **Idiot**4). ## Rules * The character's alignment, level, XP, and possessions other than the deck do not matter. * The character's Intelligence score starts at 10. * There is no maximum limit to the character's Intelligence or their stockpiled uses of *wish*. * Uses of **The Fates** do not stack. * The *wish* spell has a 1-in-3 chance of causing the character to never be able to use the *wish* spell again, in addition to its regular effect. If this occurs, the character can no longer use the spell to negate **Flames**, **Rogue**, or **Skull** - the power of **The Fates** is their only recourse. * The character always makes the following choices: + **The Fates** and **Moon** are solely used to get the character out of trouble from **Skull**, **Flames**, and **Rogue**. The character will never use them to reverse the effect of **Talons** or the *wish* spell being unable to be cast again, and cannot use them to reverse the effects of **Donjon** and **The Void**. The character will immediately use one *wish* spell to negate the effects of **Skull**, **Flames**, or **Rogue** upon drawing one of them, and it will always succeed. The character will always use **The Fates** before using *wish*. + The character always chooses to draw more cards with the effects of **Idiot** and **Jester** (appropriately). + The effect of **Star** is always used to increase Intelligence by 2, to avoid having to stop drawing cards via the effect of **Idiot**. * The NPC ally summoned by **Knight** is not powerful enough to save the character from their untimely demise. * Any increases or decreases to Intelligence (via **Star** or **Idiot**, respectively) must be reflected in the output (either by noting the change (`+2` or `-(1d4+1)`), or by outputting the current Intelligence score after the effect takes place). * Any changes to the number of *wish* uses the character has stockpiled must similarly be reflected in the output, including a *wish* causing the character to not be able to use *wish* anymore. * All random selections are from uniform discrete distributions. * You may choose any set of 22 distinct outputs to output for the cards drawn - the cards' names do not have to be used. * You may output changes in Intelligence, *wish* uses, and *wish* becoming unusable in any consistent, unambiguous manner of your choosing. * The character may use *wish* or the power of **The Fates** to avoid death if the appropriate card is drawn as the fifth card after drawing **Rogue** or **Flames**. Only if *wish* is unusable or all of the uses have been used, as well as **The Fates** is not drawn in time or has already been used, will the character die. * **Fool** and **Jester** are discarded after they are drawn. All other cards are immediately returned to the deck, and the deck is then shuffled. * If there are multiple stacks of **Rogue** and/or **Flame** active, only one use of **The Fates** or *wish* is necessary to dispel all of them. * Drawing multiple cards at once via **Jester** or **Fool** does not advance the turn counter on **Flames** and/or **Rogue**. ## Examples Each line represents a sequence of draws. Changes to Intelligence and *wish* uses are shown by the current value in parentheses. A `C` next to a *wish* use denotes that *wish* cannot be used anymore. A `F` denotes that the power of **The Fates** was used to avoid death. Additional comments are provided for explanatory purposes, in the form of Python-style comments. ``` Void # Can't draw with your soul ripped out of your body. Throne, Euryale, Rogue, Star (12), Donjon # Can't draw while in suspended animation. Moon (3), Throne, Sun, Flames (2), Fool, Idiot (6), Flames (1 C), The Fates, Skull (F), Skull # Two uses of wish were used on the two Flames draws. The second use rendered the character unable to use wish again. The Fates was used on the first Skull. When the second Skull came up, there was no way for the character to save himself, so he died. Idiot (5), Star (7), Idiot (3) # Too dumb to draw. Sun, Star (12), Talons # Talons destroys the deck. Fates, Throne, Moon (2), Fates, Skull (F), Skull # Fates doesn't stack Fates, Flames, Euryale, Fates, Skull, Void Flames, Comet, Euryale, Gem, Knight, Key # 5 draws after Flames, the hero dies Rogue, Balance, Throne, Gem, Idiot (8), Vizier, Sun # 5 draws plus one extra from Idiot ``` ## Reference Implementation ``` #!/usr/bin/env python3 import random deck="""Sun Moon Star Throne Key Knight Void Flames Skull Ruin Euryale Rogue Jester Vizier Comet Fates Gem Talons Idiot Donjon Balance Fool""".split() random.shuffle(deck) int_stat = 10 wish_uses = 0 wish_expired = False fates = False turn_count = None while True: card = deck.pop() if card == "Fates": if turn_count is None: fates = True print(card) else: turn_count = None fates = False print("{} (F)".format(card)) elif card == "Moon": wish_uses += random.randint(1, 3) if turn_count is None: print("{} ({})".format(card, wish_uses)) else: turn_count = None wish_uses -= 1 print("{} ({}) ({})".format(card, wish_uses+1, wish_uses)) elif card in ["Flames", "Rogue"]: if turn_count is None: turn_count = 5 if fates: fates = False turn_count = None print("{} (F)".format(card)) elif wish_uses > 0 and not wish_expired: wish_uses -= 1 turn_count = None wish_now_expired = random.choice([False, False, True]) print("{} ({}{})".format(card, wish_uses, " C" if wish_expired else "")) wish_expired = wish_now_expired else: print("{}".format(card)) elif card == "Idiot": int_stat -= random.randint(2, 5) print("{} ({})".format(card, int_stat)) if turn_count is not None: turn_count += 1 if int_stat <= 3: break elif card == "Star": int_stat += 2 print("{} ({})".format(card, int_stat)) elif card == "Skull": if fates: fates = False turn_count = None print("{} (F)".format(card)) elif wish_uses > 0 and not wish_expired: wish_uses -= 1 turn_count = None wish_now_expired = random.choice([False, False, True]) print("{} ({}{})".format(card, wish_uses, " C" if wish_expired else "")) wish_expired = wish_now_expired else: print(card) break elif card in ["Donjon", "Void", "Talons"]: print(card) break elif card == "Fool": print(card) if turn_count is not None: turn_count += 1 elif card == "Jester": print(card) if turn_count is not None: turn_count += 2 else: print(card) if card not in ["Fool", "Jester"]: deck.append(card) random.shuffle(deck) if turn_count is not None: turn_count -= 1 if turn_count == 0: break ``` --- [1]: Technically, there are two variants: one with 13 cards, and one with 22 cards. We're only concerned about the full 22-card version here. [2]: **Flame** and **Rogue** don't normally outright kill the character, but the hostile NPC is assumed to have found and killed the foolish character after they have time to draw 5 more cards. The spectre summoned by **Skull** is extremely difficult to fight, and it's assumed that the character doesn't win. Only divine/magical intervention via **The Fates** or **Moon** can save the foolish character from their death by these 3 cards. [3]: We assume the character's friends are smart enough to not try to rescue the character and allow them to draw more cards. [4]: An Intelligence score of 3 is roughly equivalent to a wild animal, which wouldn't be able to actively make the choice to draw cards. [Answer] # JavaScript (ES6), 379 bytes ``` for(D=[...Array(21)].map((a,b)=>b),d={},i=10,w=e=f=t=0,F=_=>f=t=o=0,W=_=>{w--,t=0,o=w+(e?' C':''),e=1>r(2)},r=a=>0|Math.random()*a,$=1;$;){for(;d[c=r(22)];);o='',c?3>c?(t&&(t+=c),d[c]=1):4>c?f?F():0<w&&!e?W():$=0:7>c?$=0:9>c?(!t&&(t=5),f?F():0<w&&!e&&W()):10>c?(w+=1+r(2),t?(t=0,o=[w,--w]):o=w):11>c?(i-=2+r(3),o=i,$=3<i):12>c&&(i+=2,o=i):t?F():f=1,console.log(c,o),t&&(t--,$=t)} ``` ### Ungolfed ``` let print = (...x) => console.log(card, ...x), // Uncomment for more human-friendly output: // print = (...x) => console.log(`Fates Fool Jester Skull Donjon Void Talons Flames Rogue Moon Idiot Star Sun Throne Key Knight Ruin Euryale Vizier Comet Gem Balance`.split` `[card] + x.map(x => ` (${x})`).join``), deck = [...Array(21)].map((_,i)=>i), discard = {}, intelligence = 10, wishUses = 0, wishExpired = false, fates = false, turns = 0, useFates = () => { fates = false turns = 0 print('F') }, useWish = () => { wishUses-- turns = 0 print(wishUses + (wishExpired ? ' C' : '')) wishExpired = random(2) < 1 }, random = n => Math.random() * n | 0, canDraw = true while(canDraw){ // card = deck.splice(random(deck.length), 1)[0] while(discard[card = random(22)]); if(card){ if(card < 3){ // 1: Fool // 2: Jester if(turns){ turns += card } print() discard[card] = 1 }else if(card < 4){ // 3: Skull if(fates){ useFates() }else if(wishUses > 0 && !wishExpired){ useWish() }else{ print() canDraw = false } }else if(card < 7){ // 4: Donjon // 5: Void // 6: Talons print() canDraw = false }else if(card < 9){ // 7: Flames // 8: Rogue if(!turns){ turns = 5 } if(fates){ useFates() }else if(wishUses > 0 && !wishExpired){ useWish() }else{ print() } }else if(card < 10){ // 9: Moon wishUses += 1 + random(2) if(!turns){ print(wishUses) }else{ turns = 0 wishUses-- print(wishUses + 1, wishUses) } }else if(card < 11){ // 10: Idiot intelligence -= 2 + random(3) print(intelligence) if(intelligence <= 3){ canDraw = false } }else if(card < 12){ // 11: Star intelligence += 2 print(intelligence) }else{ print() } }else{ // 0: Fates if(!turns){ fates = true print() }else{ useFates() } } if(turns){ turns-- if(!turns){ canDraw = false } } } ``` ### Explanation of Output Cards range from 0-21 as follows: * 0: Fates * 1: Fool * 2: Jester * 3: Skull * 4: Donjon * 5: Void * 6: Talons * 7: Flames * 8: Rogue * 9: Moon * 10: Idiot * 11: Star * 12 though 21: Sun, Throne, Key, Knight, Ruin, Euryale, Vizier, Comet, Gem, Balance A reversal of Skull, Flames, or Rogue via The Fates is denoted with a `0`. --- # JavaScript (ES6), 792 bytes Previous version using card names, before I found out that any 22 distinct outputs are allowed. ``` d=`Sun Moon Star Throne Key Knight Void Flames Skull Ruin Euryale Rogue Jester Vizier Comet Fates Gem Talons Idiot Donjon Balance Fool`.split` `,i=10,w=0,W=!1,f=!1,t=null,F=()=>{f=!1,t=null,_('F')},U=()=>{w--,t=null,_(w+(W?' C':'')),W=1>r(2)},_=(...a)=>console.log(c+a.map(b=>` (${b})`).join``),r=a=>0|Math.random()*a,$=!0;for(;$;)c=d.splice(r(d.length),1)[0],'Fates'==c?null==t?(f=!0,_()):F():'Moon'==c?(w+=1+r(2),null==t?_(w):(t=null,w--,_(w+1,w))):'Idiot'==c?(i-=2+r(3),_(i),3>=i&&($=!1)):'Star'==c?(i+=2,_(i)):'Flames'==c||'Rogue'==c?(null==t&&(t=5),f?F():0<w&&!W?U():_()):'Skull'==c?f?F():0<w&&!W?U():(_(),$=!1):'Donjon'==c||'Void'==c||'Talons'==c?(_(),$=!1):'Fool'==c?null!==t&&(t+=1):'Jester'==c?null!==t&&(t+=2):_(),['Fool','Jester'].includes(c)||d.push(c),null!==t&&t--,0===t&&($=!1) ``` ### Ungolfed ``` let deck = `Sun Moon Star Throne Key Knight Void Flames Skull Ruin Euryale Rogue Jester Vizier Comet Fates Gem Talons Idiot Donjon Balance Fool`.split` `, intelligence = 10, wishUses = 0, wishExpired = false, fates = false, turns = null, useFates = () => { fates = false turns = null print('F') }, useWish = () => { wishUses-- turns = null print(wishUses + (wishExpired ? ' C' : '')) wishExpired = random(2) < 1 }, print = (...x) => console.log(card + x.map(x => ` (${x})`).join``), random = n => Math.random() * n | 0, canDraw = true while(canDraw){ card = deck.splice(random(deck.length), 1)[0] switch(card){ case 'Fates': if(turns === null){ fates = true print() }else{ useFates() } break case 'Moon': wishUses += 1 + random(2) if(turns === null){ print(wishUses) }else{ turns = null wishUses-- print(wishUses + 1, wishUses) } break case 'Idiot': intelligence -= 2 + random(3) print(intelligence) if(intelligence <= 3){ canDraw = false } break case 'Star': intelligence += 2 print(intelligence) break case 'Flames': case 'Rogue': // Changed Condition if(turns === null){ turns = 5 } if(fates){ useFates() }else if(wishUses > 0 && !wishExpired){ useWish() }else{ // Added print() } break case 'Skull': if(fates){ useFates() }else if(wishUses > 0 && !wishExpired){ useWish() }else{ print() canDraw = false } break case 'Donjon': case 'Void': case 'Talons': print() canDraw = false break case 'Fool': if(turns !== null){ turns += 1 } break case 'Jester': if(turns !== null){ turns += 2 } break default: print() } if(!['Fool', 'Jester'].includes(card)){ deck.push(card) } if(turns !== null){ turns-- } if(turns === 0){ canDraw = false } } ``` [Answer] # Java 10, ~~481~~ ~~480~~ ~~476~~ ~~470~~ ~~453~~ ~~439~~ ~~437~~ 436 bytes ``` v->{var r="";Math M=null;int i=10,d=22,c,F=0,t=0,w=0,W=0,j=2;for(j*=M.random();;){c=d;c*=M.random();r+=" "+c;t=c<1?(r+=t<(F=1)?"":"F"+(F=0))==""?-1:-1:c<2?0*(w+=M.random()*3-(t>0?0:1)):c<4?F>0?-1:t<1?6:t:c<5?F*w*W>(F=0)?-1:1:c>19?t+(t>0*d--*j++?j%2+1:0):t;W=c>1&c<5&w*W>0?(int)(M.random()*3)%2+0*w--:W;i-=c==5?M.random()*3+2:c==6?-2:0;r+=c>1&c<5&F>0?"F"+(F=0):c>0&c<5?"w"+w+"W"+W:c>4&c<7?"i"+i:"";if(--t==0|c==5&i<4|c>6&c<10)return r;}} ``` Ported the Python3 reference implementation in Java, and then golfed it down. -46 bytes thanks to *@ceilingcat*. **Card outputs:** > > `0`: Fates > > `1`: Moon > > `2`: Flames > > `3`: Rogue > > `4`: Skull > > `5`: Idiot > > `6`: Star > > `7`/`8`/`9`: Donjon/Void/Talons > > `20`/`21`: Fool/Jester > > > `10-19`: everything else (Sun/Throne/Key/Knight/Ruin/Euryale/Vizier/Comet/Gem/Balance) > > > Output format for wishes left, wishes used, intelligence left, and flag used: ``` 4w1W0 4 // Card drawn w1 // New amount of wishes left W0 // Whether the wishes used flag is active (1) or inactive (0) 5i6 5 // Card drawn i6 // New intelligence 0F0 0 // Card drawn F0 // Fates used ``` **Explanation:** [Try it here](https://tio.run/##VVJRa9swEH7XrxCCFcuKYtlN0lWKopcR6CAdbGN5GHvQZCeV69jFkRNKm9@endpudGDZ3Hd33538fbU9WF6X9@csRULipQ3VHuUSr7quRQUAjd0Bcinx1247VBJNJP52PzQNmkp8U/ouoBkgwfboKvuYXUv8qWvrrs1@dL7Mvtuma4FP8Bwy1aHqH8Odb7e4avYVKuLArmtQAQM/V/tQ9SjNEHKN3e/xyvr2CWHsW8A31lX4NoYYhvWRwiVxBD5QBegJwWsfbPAO3@IW6/OBL54Otse9JkStbLjDK93C3gr4sNe5GJW6KEZutNRiFOAc4azh1LpQm65P6lSvxr1ty26XUKXok9Olcv@BPdMEE@ZU0G6emwTiME@WOqeGEEmWhEEgKNWwg@G5hMfNCyPS5Mje8aSXPAkLYYTMKYWKiVlCBMUBSGcyADQ1y/SYrhcvfDEFTIv82gQWO9OS87RmzNQfCpZLQWVQaw0FF9B5EfuESeDeNHk/lEKxSI@cy7XyXDutp@Z9nhUSsJnhhRTxqn/54nL/7gZriIgaciTsyMiasDVgE8CuDPGEeQn/328SzoPW4jlOufDzybNbzKAmF7SvwtC3uFen01lFGR@G3w3I@KbmIYq8Ay8kr7r//GXpqw@yDH8ZwsMQcDHFr2vjbXSrfElHDd@0VtjPdTGFD2P0JQkuegS/7cbdEMYPwBuaNmnHLokWoW@WOp3/AA) or [**Try it here with pretty-printed output**](https://tio.run/##fZVdb9MwFIbv9yssa0x23ZQkawtL6kZ8BQEqIIboBePCJF7nkjqV4zQa2377OE4G2yRSqWnk48fv@UyyFjvhrfNft1khqgothNJXBwgpbaU5F5lEH90SoVNrlF6hjHwrVY52NAbrzQH8VVZYlaGPSCOObnfe/GonDDIc43gh7AVacF0XRQyCSPHAH@Y8DIfZMOX@0MLVwLWEa83D@Lw0ZD3gi5EROi83hMYxvcp4HmePjIZxjDDLYsuzWZAQWNsZSXlAE4wjnGIGC59SDjEkXhDBL5uFiT8gDXugMzj2iJ37iR8FlAIxTlJYAWxBdBpZME2SdNAMlvNWz22B0jw4SSxzJwe55w3WjCXrJyELIp9GNl5yAI7g5JE75ycE8qbkoVMKsD9oPC9axsrjGeeT5OE@CyOwTRMvjHyX6l89F9y/3CAM31kT3GDWMLzEbAm2MdieJVhhpiKovzonnmc596@dlyM1G19n8ykwgU@NtLXRyMQ3N7ex6@O2/llAH@/auXNd3sAwkK7x338gQbtJePoUfarttrYonKAubrQSG1lF7bZr4l2zY6RmPJzAjTHaboIbcGwvP4OmJfdDtDVqJ6x85P0R@WgIDUyaHmXEDVargVqTGRm5LWBmXxQFwcgnKTQNDxFGKWhXh0GM/0cDGjQttihL3eB@xZA01yntFAuX8WGwhz6@p7@Uq1ruhcf38OkvSKsHBnKiWupdrkqr@qBpB51aYXqZZy3yutTrUvdW5nkLuWe@Fzlpka@iKHXVX2G/C6judxUEndCFKbXsp8KW@iAv@5HjDtFqdWH7qXHXmlrtCWnSMm9qcymKPTFNuyqp30qafqor@KtyI/dE1RX8rdz0I13BX4pC6Kw/qLCreFqWRT/Tlfy9rGxf4O14NuTsLGd02d3cGdKo6kJWqJDnNkLwaKE7Q13JHAwh3SOnHui4D01RqJWEXP6p7TsMZxtG0za7w4C0j3brlf49c3oJ6WxGZW1HW/f2KDR8IvCZxnfvm5vbPw). ``` v->{ // Method with empty unused parameter and String return-type var r=""; // Result-String, starting empty Math M=null; // Static Math to save bytes int i=10, // Intelligence, starting at 10 d=22, // Amount of cards in the deck, starting at 22 c, // Current card drawn F=0, // Fates flag, starting at inactive t=0, // Turn-counter, starting at 0 w=0, // Wishes left, starting at 0 W=0, // Wishes used flag, starting at 0 j=2;for(j*=M.random() // Whether Jester/Fool is drawn first of the two, random 0/1 ;;){ // Loop indefinitely: c=d;c*=M.random(); // Draw a random 0-21 card (or less if Fool/Jester is gone) r+=" "+c; // Append the result with a space and this card t=c<1? // If the card was Fates: (r+=t<(F=1) // Set the Fates-flag to active ? // And if the turn-counter is 0: "" // Append nothing : // Else (the turn-counter is larger than 0): "F"+(F=0)) // Append that Fates was used (and make Fates inactive) ==""?-1:-1 // Then set the turn-counter to -1 (none) :c<2? // If the card was Moon instead: 0*(w+=M.random()*3 // Increase the wishes by 0-2 randomly -(t>0? // Then, if the turn-counter is larger than 0 0 // Leave the (0-based random) wishes the same : // Else: 1)) // Subtract 1 from the (0-based random) wishes -1 // Set the turn-counter to -1 (none) :c<4? // If the card was Flames or Rogue instead: F>0? // If the Fates-flag is active: -1 // Set the turn-counter to -1 (none) :t<1? // Else-if the turn-counter is 0 or -1 (none): 6 // Set the turn-counter to 6 : // Else: t // Leave the turn-counter the same :c<5? // If the card was Skull instead: F // If the Fates-flag is inactive *w // or the amount of wishes is smaller than 1 *W<1 // or the wishes used flag is inactive +0*(F=0)? // (And set the Fates-flag to inactive) 1 // Set the turn-counter to 1 : // Else: -1 // Set the turn-counter to -1 (none) :c>19? // If the card was Fool or Jester instead: t+(t>0*d-- // Remove the Fool/Jester from the Deck *j++ // And increase `j` (Fool/Jester) by 1 ? // If the turn-counter was not 0 or -1 (none): j%2+1 // Increase either by 1 (Fool) or 2 (Jester) : // Else: 0) // Leave the turn-counter the same by increasing with 0 : // Else: t; // Leave the turn-counter unchanged W=c>1&c<5 // If the card drawn was Flames, Rogue or Skull, &w // and the amount of wishes is at least 1, *W>0? // and the wishes used flag is active (int)(M.random()*3)%2// Randomly set the wishes used flag to one of (0,0,1) +0*w-- // And decrease the wishes left by 1 : // Else: W; // Keep the wishes used flag the same i-=c==5? // If the card drawn was Idiot: M.random()*3+2 // Decrease the intelligence by 2-5 randomly :c==6? // Else-if the card drawn was Star: -2 // Increase the intelligence by 2 : // Else: 0; // Leave the intelligence the same r+=c>1&c<5 // If the card drawn was Flames, Rogue or Skull, &F>0? // and Fates is active "F"+(F=0) // Append that Fates was used (and make Fates inactive) :c>0&c<5? // Else-if the card drawn was Moon, Flames, Rogue or Skull: "w"+w+"W"+W // Append the amount of wishes left and wishes used flag :c>4&c<7? // Else-if the card drawn was Idiot or Star: "i"+i // Append the amount of intelligence left : // Else: ""; // Append nothing if(--t // Decrease the turn-counter by 1 ==0 // And if the turn-counter is now 0, |c==5 // or the card drawn was Idiot, &i<4 // and the intelligence dropped below 4, |c>6&c<10) // or the card drawn was Donjon, Void or Talons: return r;}} // Return the result of the game ``` [Answer] # [Kotlin](https://kotlinlang.org), 1173 bytes ``` fun main(args:Array<String>){val d="Sun Moon Star Throne Key Knight Void Flames Skull Ruin Euryale Rogue Jester Vizier Comet Fates Gem Talons Idiot Donjon Balance Fool".split(" ");var c=(Math.random()*22).toInt();var i=10;var u=0;var e=false;var f=false;var t=1;r@while(true){when(c){15->{if(t>=1){f=true;println(c)}else{t = 1;f = false;println("${d[c]} (F)")}}1->{u+=(Math.random()*3).toInt()+1;if(t>=1){println("${d[c]} ($u)")}else{t=1;u-=1;println("${d[c]} (${u + 1}) ($u)")}}in arrayOf(7,11)->{if(t>=1){t=5};if(f){f=false;t=1;println("${d[c]} (F)")}else if(u>0&&!e){u-=1;t=1;val n=(Math.random()*3).toInt();println("${d[c]} ($u$e)");e=n==0}else{println(d[c])}}18->{i-=(Math.random()*4).toInt()+2;println("${d[c]} ($i)");if (t!=0){t+=1};if(i<=3){break@r}}2->{i+=2;println("${d[c]} ($i)")}8->{if(f){f=false;t=1;println("${d[c]} (F)")}else if(u>0&&!e){u-=1;t=1;val n=(Math.random()*3).toInt();println("${d[c]} ($u$e)");e=n==0}else{println(c);break@r}}in arrayOf(6,17,19)->{println(d[c]);break@r}21->{println(d[c]);if(t!=0){t += 1}}12->{println(d[c]);if(t!=0){t+=2}}else->{println(d[c])}};if((c !in arrayOf(12,21))){c=(Math.random()*23).toInt()};if(t!=0){t-=1}else{break}}} ``` It's runnable, too. - [Try it online!](https://tio.run/##zVPRbtMwFP2V26iabNJWdcZgkLkaMIrGNCGt014QDyZ1WjPXnhx7U4n87cVO1K60Hc@82Jbu8bnnnGvfayuFWq1Kp2DBhELMzKr3H4xhy7OJNULNRrh@ZBKmNJkEzLXWCiaWGbidG604XPElXCkxm1u402IKY8kWvILJvZMSbpxQ8NmZJZMcbvTMcfjKK8sN3InfImyf9IJbGDMbrnzhC7hlUqsKLqdCW7jQ6lfo9pFJpgoOY61lMqgepLAogQTnj0FFQdE1s/OBYWqqFwi/yjI8sPpSWdQCBCXD5uBou3NaMlnx5lxunS0luTl/mgvJkTWO4/ppzhUqcE1O@qNalMiOKMF1SWM1fwjZWBnrngeK2gIFkpdhbSnX9aRbT78XPzygMU6w9yRwuXRX9fFGdEryTat9jq6LJG3DoNf1w3IAVTtIgXi8vuDDGFic6bcSve0RgrcNWXriY88yemvF24O043VvCGg3Gh4ddUJKjYZ4Ib4S9bKxQzpdlwfOnFNF6bC1tUZFSIzrNErt79K@fs4rO0QsIq0oAdkOHQaLKSWNR3FGj3H903B2f268zyJ5Sl@k8KdtUP9XNAXONw62BvumR8Js38XZ/hXiBpyRvVJ8BG1CkIb3G/LO/oEJSflGyi7GN@GiAjpbekjWywjGuN7/o8/W/RZ9SKs12gj23q9WfwA) There's probably lots of bugs... let me know in the comments! ]
[Question] [ Dropbox recently released [Lepton](https://blogs.dropbox.com/tech/2016/07/lepton-image-compression-saving-22-losslessly-from-images-at-15mbs/) ([GitHub](https://github.com/dropbox/lepton)), a method that **losslessly** compresses JPEG images round-trip, saving an average of 22%. ![](https://i.stack.imgur.com/0qCK6.png) Because of the [pigeonhole principle](http://matt.might.net/articles/why-infinite-or-guaranteed-file-compression-is-impossible/), any *general* compression algorithm cannot be *guaranteed* to result in a smaller file (*general* because it doesn't apply to inputs constrained to a specific format). Lepton exploits common characteristics about JPEGs, which if subverted, might pigeonhole it to produce a file larger than the source. # Requirements Write a program that generates: * A valid JPEG/JFIF image, * with a size between 0.5 MB and 1 MB, * no smaller than 256 × 256 px, * no larger than 4096 × 4096 px, * recognizable by Lepton (it can successfully "compress" to a `.lep` image), and * decompresses to an *identical* `.jpg` (as the input). * `APPx`, `COM`, and other metadata, non-graphical marker sections are restricted in the JPEG (injecting arbitrary amounts of random bytes into the image to asymptotically approach 1:1 compression is lame.) + an [`APP0` JFIF marker](https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format#JFIF_APP0_marker_segment) is permitted but no thumbnail is allowed (should be exactly 16 bytes) + **tl;dr** If you're not intentionally shoving metadata into an EXIF segment and you disable any sort of thumbnail your language library of choice wants to put into the image, that should be OK. Post the code and image. If you want to write a program that produces a *Lepton* image that when converted yields a JPEG meeting the criteria, that's fine. It must remain identical across arbitrarily many JPEG → Lepton → JPEG → ... cycles. # Scoring The byte size of the Lepton image divided by the source JPEG image. Higher (worse Lepton compression) is better. Run Lepton with default flags and switches. --- # Getting Lepton A 5-second crash-course to build Lepton: ``` git clone https://github.com/dropbox/lepton.git cd lepton ./autogen.sh && ./configure && make # fish shell: ./autogen.sh ;and ./configure ;and make ``` Then `./lepton --help` should tell you things. [Answer] # Python 3 + mozjpeg + /dev/urandom, 720×720: avg. score 102% Depends on the `mozjpeg` package, the code assumes it's installed into `/usr/local/opt/mozjpeg`. (on OS X it's trivial to install, just run `brew install mozjpeg`) Also it depends on `/dev/urandom` special file, it's used for generating random data. The code simply feeds random data to `mozjpeg` compressor (in TGA format, because cjpeg understands it and it has very simple header), and lets it create an optimized jpeg file. Quality is set to the maximum because it makes DCT coefficients the least compressable, and it doesn't matter much what algorithm is used to compress uncompressable data. I checked that the jpeg->lepton->jpeg cycle is lossless — it is true. ``` import subprocess from subprocess import PIPE c_mozjpeg_path = '/usr/local/opt/mozjpeg/bin/cjpeg' cjpeg_params = '-quality 100 -dc-scan-opt 2 -dct float -targa' image_size = 720 def write_random_tga_image(w, h, of, rf): def wb(value, size): of.write(int.to_bytes(value, size, 'little')) wb(0, 2) wb(3, 1) wb(0, 9) wb(w, 2) wb(h, 2) wb(8, 1) wb(0, 1) data_size = w * h while data_size > 0: data_size -= of.write(rf.read(data_size)) def main(): with open('/dev/urandom', 'rb') as rf: with open('oops.jpg', 'wb') as f: p = subprocess.Popen((c_mozjpeg_path,) + tuple(cjpeg_params.split(' ')), stdin=PIPE, stdout=f) write_random_tga_image(image_size, image_size, p.stdin, rf) p.communicate() if __name__ == '__main__': main() ``` Code is not golfed, obviously. Example image: ![](https://cloud.githubusercontent.com/assets/1442206/17919118/005ee04c-69dc-11e6-83e0-4d027edfb399.jpg) Fun fact: generated JPEG file is larger than the source uncompressed TGA image, even though JPEG uses lossy compression. Fun fact 2: Imgur (the default image hosting for SO) does very bad job at this file — for some reason it recompresses it to lower quality, even though it's less than 1MB. So I used Github to upload the example image. Fun fact 3: In general, mozjpeg indeed does better JPEG compression while staying compatible with existing JPEG decoders. And it also has tool to losslessly optimize JPEG files, too — `jpegtran`. [Answer] # Naive Noise, 1024 × 1024: score 85.55% A compliant example in Python to get the ball rolling. Not optimized in any way; probable shortcomings: * No idea what the default quality setting is. * Each 8x8 block has practically the exact same average value (~50%) to the one adjacent to it: Lepton says that they use that information to save space. * Totally default quantization and Huffman tables (whatever the library decides to use). --- ``` import numpy as np from PIL import Image np.random.seed(0) # make sure it's repeatable. size = 1024 imgr = np.random.randint(0, 0xFF, (size, size, 3)).astype('uint8') pimg = Image.fromarray(imgr) pimg.save('noise.jpg') ``` [![noise](https://i.stack.imgur.com/8blg6.jpg)](https://i.stack.imgur.com/8blg6.jpg) Then some bash to do the thing: ``` ./lepton noise.jpg noise.lep 2>\dev\null # vomits out a lot of technobabble ./lepton noise.lep noise-out.jpg 2>\dev\null diff -qs noise.jpg noise-out.jpg SIZE1=$(stat -f "%z" noise.jpg) # http://superuser.com/a/570920/18931 SIZE2=$(stat -f "%z" noise.lep) RATIO=$(bc <<< "scale=4; $SIZE2/$SIZE1") echo "$SIZE2/$SIZE1 = $RATIO" # Files noise.jpg and noise-out.jpg are identical # 538817/629769 = .8555 ``` ]
[Question] [ Polygons are named after the number of sides that they have. A pentagon has 5 sides, an octagon has 8 sides. But how are they named? What's the name for a 248-sided polygon? All polygons are suffixed with `-gon`. There are specific prefixes for each polygon depending on the number of sides. Here are the prefixes for the lower numbers: ``` 3 - tri 4 - tetra 5 - penta 6 - hexa 7 - hepta 8 - octa 9 - nona 10 - deca 11 - undeca 12 - dodeca 13 - triskaideca 14 - tetradeca 15 - pentadeca 16 - hexadeca 17 - heptadeca 18 - octadeca 19 - nonadeca 20 - icosa ``` Polygons with 21 to 99 sides have a different system. Take the prefix for the tens digit (found on the left column), the ones digit (right column below), and then stick a "kai" between them to get `(tens)kai(ones)gon`. ``` 10 - deca | 1 - hena 20 - icosi | 2 - di 30 - triaconta | 3 - tri 40 - tetraconta | 4 - tetra 50 - pentaconta | 5 - penta 60 - hexaconta | 6 - hexa 70 - heptaconta | 7 - hepta 80 - octaconta | 8 - octa 90 - nonaconta | 9 - nona ``` The 3-digit sided polygons are named in a similar fashion. A 100-sided polygon is called a hectogon. Take the hundreds digit, find it on the column for ones digits, then stick a "hecta" to its right. Now number off the tens and ones like above: `(hundreds)hecta(tens)kai(ones)gon`. If the hundreds place digit is a 1, don't put the prefix behind "hecta"; if the ones place is 0, then omit the (ones) section. So, given an integer (3 <= n <= 999), return the name of an n-sided polygon. `n-gon` is not a valid answer :P As with all code golf, shortest code wins. [Answer] ## C, 401, 391 Lets put something out there so there is at least one answer for reference :-) ``` char*s[]={"","hena","di","tri","tetra","penta","hexa","hepta","octa","nona","un","do","triskai","deca","icosi","tria","conta","kai","icosa","hecto","hecta","gon\n"}; p(i){printf(s[i]);} t;n(i){ if(i<10) p(i); // ones else if(i<20){ i-=10; p(i+(i&&i<4)*9); // teens p(13); // "deca" }else if(i==20) p(18); // "icosa" else if(i==100) p(19); // "hecto" else{ t=i/100; p(t>1?t:0); // hundreds p(t?20:0); // "hecta" i%=100; t=i/10; p(t+(t&&t<4)*12); // tens p(t>2?16:0); // "conta" i%=10; p(i?17:0); // "kai" p(i); // ones } p(21); // "gon\n" } ``` Test with: ``` main(){ for(int i=3;i<=999;i++){ printf("%3d: ",i);n(i); } } ``` Subset of output: ``` 3: trigon 4: tetragon 5: pentagon 6: hexagon 7: heptagon 8: octagon 9: nonagon 10: decagon 11: undecagon 12: dodecagon 13: triskaidecagon 14: tetradecagon 15: pentadecagon 16: hexadecagon 17: heptadecagon 18: octadecagon 19: nonadecagon 20: icosagon 21: icosikaihenagon 22: icosikaidigon 23: icosikaitrigon ... 99: nonacontakainonagon 100: hectogon 101: hectakaihenagon 102: hectakaidigon 103: hectakaitrigon 104: hectakaitetragon 105: hectakaipentagon 106: hectakaihexagon 107: hectakaiheptagon 108: hectakaioctagon 109: hectakainonagon 110: hectadecagon 111: hectadecakaihenagon ... 997: nonahectanonacontakaiheptagon 998: nonahectanonacontakaioctagon 999: nonahectanonacontakainonagon ``` [Answer] ## JavaScript - 405 386 Version 1: (405 chars) ``` i=prompt(),o='0hena0di0tri0tetra0penta0hexa0hepta0octa0nona'.split(0),d='0W0icosi0triaQ0tetraQ0pentaQ0hexaQ0heptaQ0octaQ0nonaQ'.split(0),t='W0unW0doW0triskaiW0tetraW0pentaW0hexaW0heptaW0octaW0nonaW0icosa'.split(0),x=('000'+i).substr(-3).split('');alert((i<10?o[i]:i<21?t[i-10]:i==100?'hecto':(i<100?'':i<200?'hecta':o[x[0]]+'hecta')+d[x[1]]+'kai'+o[x[2]]).replace(/Q/g,'conta').replace(/W/g,'deca')+'gon') ``` Version 2: (386 chars) ``` i=prompt(),p='0tetra0penta0hexa0hepta0octa0nona',o='0hena0di0tri'+p,t=('W0unW0doW0triskai'+p.replace(/0/g,'W0')+'W0icosa').split(0),x=('000'+i).substr(-3).split(''),o=o.split(0);alert((i<10?o[i]:i<21?t[i-10]:i==100?'hecto':(i<100?'':i<200?'hecta':o[x[0]]+'hecta')+('0W0icosi0tria'+p.replace(/0/g,'Q0')+'Q').split(0)[x[1]]+'kai'+o[x[2]]).replace(/Q/g,'conta').replace(/W/g,'deca')+'gon') ``` Output example: ``` 3: trigon 4: tetragon 5: pentagon 6: hexagon 7: heptagon 8: octagon 9: nonagon 10: decagon 11: undecagon 12: dodecagon 13: triskaidecagon 14: tetradecagon 15: pentadecagon 16: hexadecagon 17: heptadecagon 18: octadecagon 19: nonadecagon 20: icosagon 21: icosikaihenagon 22: icosikaidigon 23: icosikaitrigon 99: nonacontakainonagon ... 100: hectogon 101: hectakaihenagon 102: hectakaidigon 103: hectakaitrigon 104: hectakaitetragon 105: hectakaipentagon 106: hectakaihexagon 107: hectakaiheptagon 108: hectakaioctagon 109: hectakainonagon 110: hectadecakaigon 111: hectadecakaihenagon ... 997: nonahectanonacontakaiheptagon 998: nonahectanonacontakaioctagon 999: nonahectanonacontakainonagon ``` [Answer] # Cobra - 370 bytes This is currently a function, but if that isn't allowed then I'll change it. ``` def f(x) as String o='. hena di tri tetra penta hexa hepta octa nona'.split o[0],t,h,d='',['','deca','icosci','triconta'],['','hecta','dihecta','trihecta'],['undeca','dodeca','triskaideca'] for z in 4:10,t,h,d=t+[o[z]+'conta'],h+[o[z]+'hecta'],d+[o[z]+'deca'] for z in 10,t[z]+='kai' return if(x-100,h[x//100]+if(10<x<20,d[x-11],t[x%100//10]+o[x%10]),'hecto')+'gon' ``` And for some reason the cobra highlighter has `//` set as a comment, which is wrong. ]
[Question] [ My teacher was more than unhappy with my [Martian Homework](https://codegolf.stackexchange.com/questions/101727/please-do-my-martian-homework). I followed all the rules, but she says that what I output was gibberish... when she first looked at it, she was highly suspicious. "All languages should follow Zipf's law blah blah blah"... I didn't even know what Zipf's law was! It turns out [Zipf's law](https://en.wikipedia.org/wiki/Zipf's_law) states that if you plot the logarithm of the frequency of each word on the y axis, and the logarithm of the "place" of each word on the x axis (most common = 1, second most common = 2, third most commmon = 3, and so on), then the plot will show a line with a slope of about -1, give or take about 10%. For example, here's a plot for Moby Dick: [![enter image description here](https://i.stack.imgur.com/BqwQg.png)](https://i.stack.imgur.com/BqwQg.png) The x axis is the *n*th most common word, the y-axis is the number of occurences of the *n*th most common word. The slope of the line is about -1.07. Now we're covering Venutian. Thankfully, Venutians use the latin alphabet. The rules are as follows: * Each word must contain at least one vowel (a, e, i, o, u) * In each word there can be up to three vowels in a row, but no more than two consonants in a row (a consonant is any letter that's not a vowel). * No words longer than 15 letters * Optional: group words into sentences 3-30 words long, delimited by periods Because the teacher feels that I cheated on my Martian homework, I've been assigned to write an essay at least 30,000 words long (in Venutian). She's going to check my work using Zipf's law, so when a line is fitted (as described above) the slope has to be at most -0.9 but no less than -1.1, and she wants a vocabulary of at least 200 words. The same word should not be repeated more than 5 times in a row. This is CodeGolf, so shortest code in bytes wins. Please paste the output to Pastebin or another tool where I can download it as a text file. [Answer] # Mathematica, 102 bytes ``` ""<>RandomChoice[1/Range@215->Rest@Flatten@Outer[StringJoin,a={"v","a","e","i","o","u"},a,a,{" "}],8!] ``` Unnamed function taking no input and returning a string consisting of 40,320 three-letter Venusian words with trailing spaces. `Outer[StringJoin,a={"v","a","e","i","o","u"},a,a,{" "}]` produces the 216 three-letter words possible using only the letters "vaeiou", each with its own trailing space. The first of these words, "vvv", is not valid Venusian, but `Rest` throws it away. Then `RandomChoice[1/Range@215->...,8!]` makes 8! = 40,320 random choices from the resulting 215-word list, with frequency weights determined by the reciprocals of the first 215 integers (`1/Range@215`). Finally, `<>""...` concatenates the strings in the resulting list. The output is far from deterministic; one run yielded [this Venusian essay](http://pastebin.com/gvUkSRgC). # Mathematica, 129 bytes ``` #2&@@@Sort[Join@@Table[{i,Rest@Flatten@Outer[StringJoin,a={"v","a","e","i","o","u"},a,a,{" "}]~Part~j},{j,215},{i,0,1,j/7!}]]<>"" ``` This one is deterministic. The base set of 215 words is the same, but now each word is repeated an exact number of times (word #j is repeated roughly 7!/j times) to force zipf's law to hold. Then the words are interleaved equally to avoid repetitions. (Imagine each word is laid out on a ruler, with all the copies of that word equally spaced; when all the words are read in order, no particular word will repeat much, perhaps not at all.) The result is a [30,117-word Venusian essay](http://pastebin.com/ETcPW5JQ). [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~34~~ ~~33~~ 32 bytes ``` 525DL/9*vNy<FD}})žMDâžNâJè3ô.rðý 525DL Yield [1, ..., 525] / Yield [525/1, ..., 525/525] 9* Yield [4725/1, ..., 4725/525]. It's the number of occurences of each word. The sum of this array is greater than 30000 v For each value (y = value, N = iteration counter starting from 0) N Push iteration counter y<FD} Push an array of "int(value)" times the iteration counter } End for ) Wrap everything in an array. At this point the array countains the sorted indices of all words that matches the frequency specs žM Push "aeiou" Dâ Cartesian product with itself (["aa", "ae", ...]) žN Push the consonants âJ Cartesian product and join the values to make valid venutian words è Compute a big string with all words that correspond to the formerly computed indices 3ô Since all words are concatenated, separate them into blocks of 3 letters .r Shuffle ðý Join with whitespaces and implicitly display ``` [Try it online!](http://05ab1e.tryitonline.net/#code=NTI1REwvOSp2Tnk8RkR9fSnFvk1Ew6LFvk7DokrDqDPDtC5yw7DDvQ&input=) I think it is still pretty golfable! For instance the numeric constants and `vNy<FD}` might be golfable. [Output example](http://pastebin.com/EQsyVUBE) ## How does it work? It generates all combinations of words following the rule "vowel+vowel+consonant", which makes 525 unique valid words (more than 200). It then associates to each of them a frequency that satisfies the law `f(x) = 4725/x` where `x` is the rank of the current word, starting at 1 and ending at 525. Then the frequencies are normalized and multiplied so there are at least 30000 words. This code always yields 32074 words to make the involved constants golfable (please see the code explanation). So each word is repeated the amount of times corresponding to the frequency of the same word. Finally the words are shuffled. However it does not guarantee that a word is never repeated five times in a row. Hence the programs generates more than the needed 200 unique words in order to decrease the probability of having a word repeated five times in a row. Please note that this code always generates the same word sequence. The only thing that differs between two runs is the result of the shuffling operation. ## How to evaluate frequency? I made a simple Python3 code that takes the text in the file named "output" (from the algorithm point of view, it makes sense!) and outputs to "stats.csv". ``` from collections import Counter from math import log10 with open("output", "r") as f: with open("stats.csv", "w") as stats: words = f.read().split() freqs = Counter(words) freqs = sorted([(i,freqs[i]) for i in freqs],key=lambda x:-x[1]) print(len(words), "words") stats.write("logX;logF\n") for i, (key, f) in enumerate(freqs): stats.write(str(log10(i+1))+";"+str(log10(f))+"\n") ``` Which always yields the following distribution for my code: [![Frequency law](https://i.stack.imgur.com/3L4QW.png)](https://i.stack.imgur.com/3L4QW.png) So the slope is -1.0138. This value is now less close to -1 than the slope of the previous code, but it still satisfies the slope constraints. [Answer] # Bash/Core Utils, ~~122~~ 110 bytes ``` for w in {b,c,d}{a,e,i}{f,g,h}{o,u,a}{j,k,l};{ let ++x;yes $w|head -$[5575/x];}|shuf --random-source=<(yes ae) ``` Unrolled: ``` for w in {b,c,d}{a,e,i}{f,g,h}{o,u,a}{j,k,l};{ let ++x yes $w|head -$[5575/x] }|shuf --random-source=<(yes ae) ``` The `for w` loop generates 243 distinct words. `let ++x;` increments initially unset x (per arithmetic expression rules during that first execution, `x` is treated as 0 and thus its increment sets it to 1). The next line thus generates succeeding words at frequency 5575/x to approximate zipf frequency. The next step is to permute this deterministically to fit the repetition requirement; despite `--random-source` being a terribly large flag name, using it with shuf beats the char count of hand rolling a mul-mod selector. `yes ae` is actually the shortest fixed "random" device I found to comply. This generates [this 33729 word essay [pastebin]](http://pastebin.com/22wzBrs4). ## Bash/Core Utils, ~~96~~ 84 bytes (non-competing) For a non-deterministic approach, just chop off shuf flags: ``` for w in {b,c,d}{a,e,i}{f,g,h}{o,u,a}{j,k,l};{ let ++x;yes $w|head -$[5575/x];}|shuf ``` ## Analysis The zipf slope is tuned to be straight. Using Excel to plot on logarithmic scales: [![](https://i.stack.imgur.com/IC1jd.png)](https://i.stack.imgur.com/IC1jd.png) The teacher should notice a zipf slope of =-1.000764. ]
[Question] [ Write a program or function that prints an input string around the discrete circle that has the minimum possible radius. For example, for input `This is an example`, your program should output: ``` a si n s i e h x T a m p le ``` ### Circle generation You shall use the **Midpoint circle algorithm** to compute the coordinates of each point of the discrete circle. You can find examples on how to implement this algorithm [on this Wikipedia page](https://en.wikipedia.org/wiki/Midpoint_circle_algorithm). Here is the pseudo code of the algorithm (based on Wikipedia's C example): ``` integer x = radius integer y = 0 int decisionCriterion = 1 - x while y <= x point at coordinates (x,y) belongs to the circle // Octant 1 point at coordinates (y,x) belongs to the circle // Octant 2 point at coordinates (-x,y) belongs to the circle // Octant 4 point at coordinates (-y,x) belongs to the circle // Octant 3 point at coordinates (-x,-y) belongs to the circle // Octant 5 point at coordinates (-y,-x) belongs to the circle // Octant 6 point at coordinates (x,-y) belongs to the circle // Octant 7 point at coordinates (y,-x) belongs to the circle // Octant 8 y++ if decisionCriterion <= 0 decisionCriterion += 2 * y + 1 else x-- decisionCriterion += 2 * (y - x) + 1 end while ``` You may use a different algorithm **if and only if it produces the exact same circles that the Midpoint circle algorithm produces, for all radiuses**. The circle must have the **smallest possible radius** that still allows to write all letters of the input. If the circle ends up with more points than the number of characters in the string, then the last filling characters will be spaces . The first character of the input must be printed on the point with coordinates `(Radius,0)`. The subsequent characters are printed in an anticlockwise fashion. ### Inputs The input is a string of any ASCII characters between the space (32) and the tilde `~` (126). You may assume the input will always be valid, shorter than 256 characters and at least 5 characters long. The input may be taken from STDIN, or as a function parameter, or anything similar. ### Outputs You may output the result either to STDOUT, or return it as string from a function. You may have trailing spaces, provided that it does not cause the line to exceed the longest line (the middle one) (as such, the middle line cannot have trailing spaces). A trailing new line is permitted. ### Test cases ``` Input: Hello, World! Output: ,ol l W e o H r l d! Input: 4 8 15 16 23 42 Output: 51 8 1 6 4 2 2 3 4 Input: Programming Puzzles & Code golf Output: gnim uP ma z r z g l o e r s P & C od f e Gol Input: Ash nazg durbatuluk, ash nazg gimbatul, ash nazg thrakatuluk agh burzum-ishi krimpatul. Output: zan hsa , g ku ig lu bm ta a b t r u u l d , g a z s a h n n h a s z A g t h r a . k l a u t t u a l p u m k ri ag k h hi burzum-is ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] ## C, 367 Bytes ``` #include<math.h> main(){char*m="12345678",b[9999];int p,i,n,q,c,l=strlen(m),r=1,d,f=0;float o,s;for(;!f;r++){f=0;q=r*r;c=r/4;o=6.3,s=o/99.;memset(b,0,q);for(i=0;i<l;i++){p=1;f=0;while(p&&o>0){d=(c-1+(int)(sin(o)*c))*r+c-1+(int)(cos(o)*c);f+=p=b[d];if(!p)b[d]=m[i];o-=s;}}if(f){for(n=p=0;n<q;n++){p+=c=b[n];putchar(c?c:32);if(n%r==r-1){if(!p)n=q;putchar(10);p=0;}}}}} ``` [Test Here](https://ideone.com/5hzDQR) I'm sure it can be golfed much further but it’s starting to give me a headache. ## C, 324 Bytes Smaller code but the results are not the same as OP's ``` #include<math.h> main(){char*m="12345678",b[9999];int q,c,l=strlen(m),r=1,d,i=0;float o;for(;i<l;r++){i=0;c=r/2;q=r*r;memset(b,0,q);for(o=6.28;o>=0&&i<l;o-=0.001){d=(c-1+(int)(sin(o)*c))*r+c-1+(int)(cos(o)*c);if(!b[d]){b[d]=m[i++];}}}for(d=i=0,--r;d<q;d++){i+=c=b[d];putchar(c?c:32);if(d%r==r-1){putchar(10);d=i?d:q;i=0;}}} an hsa ,k gz ulu ig ta bm br ta ud lu g , z a an s h h s n A a z g l t tu h a ra mp ka ri tu k lu hi k a -is gh burzum ``` [Answer] ## Mathematica, ~~359 357~~ 354 ``` (L=Length;T=Tuples;c=Characters@#;For[r=1,L[p=RotateRight[SortBy[#,ArcTan@@N@#&]+r+1,L@#/4+1]&@(f=1-r;X=1;Y=-2r;x=0;y=r;q={{0,r},{0,-r},{r,0},{-r,0}};While[x<y,If[f>0,y--;f+=Y+=2];x++;f+=X+=2;q=Join[q,T@{{x,-x},{y,-y}},T@{{y,-y},{x,-x}}]];Union@q)]<L@c,r++];R=2r+1;s="";Do[s=s<>({u,v}/.Thread[p~Take~L@c->c]/.{_,_}->" ")<>If[v==R,"\n",""],{u,R},{v,R}];s)& ``` Ungolfed: ``` ( L = Length; T = Tuples; c = Characters@#; For[r = 1, L[ p = RotateRight[ SortBy[#, ArcTan @@ N@# &] + r + 1, L@#/4 + 1 ] &@( f = 1 - r; X = 1; Y = -2 r; x = 0; y = r; q = {{0, r}, {0, -r}, {r, 0}, {-r, 0}}; While[x < y, If[f > 0, y--; f += Y += 2 ]; x++; f += X += 2; q = Join[q, T@{{x, -x}, {y, -y}}, T@{{y, -y}, {x, -x}}] ]; Union@q )] < L@c, r++]; R = 2 r + 1; s = ""; Do[s = s <> ({u, v} /. Thread[p ~ Take ~ L@c -> c] /. {_, _} -> " ") <> If[v == R, "\n", ""], {u, R}, {v, R}]; s ) & ``` [Answer] # C, 494 Bytes This one uses the actual Midpoint circle algorithm: ``` void main(){char s[]="12345678";int a[9999],b[9999],f=0,c,h,x,y,e,q,t,u,v,g,i,d,l,r=0,k=strlen(s);for(;f<k;r++){c=r;e=r*2+1;q=e*e;memset(b,0,q*4);f=0;l=0;for(i=0;i<8;i++){x=r;y=0;d=1-x;for(x=r,y=0,d=1-x;y<=x;y++,d+=2*d>0?y- --x:y+1){t=(i+1)%4>1;u=t?y:x;v=t?x:y;h=(c+v*(i>3?1:-1))*e+(c+u*(i>1&&i<6?-1:1));if(!b[h])b[h]=f<k?s[f]:0,a[f]=h,f++;}if(i%2){for(g=0;g<(f-l)/2;g++)t=b[a[l+g]],b[a[l+g]]=b[a[f-1-g]],b[a[f-1-g]]=t;}l=f;}}for(i=0;i<q;i++){c=b[i];putchar(c?c:32);if(i%e==e-1)putchar(10);}} ``` ### De-golfed Code: ``` void main() { char text[]="Ash nazg durbatuluk, ash nazg gimbatul, ash nazg thrakatuluk agh burzum-ishi krimpatul."; char points[9999]; int pos[9999]; int sl = strlen(text); int r = 0; int pc = 0; // point count int lc = 0; // last count int c, h, x, y, e, q, t, u, v, g, i, d; // increase radius until number of points => strlen(text) for(; pc<sl; r++) { c = r; e = r * 2 + 1; q = e * e; memset(points,0,q); pc = 0; lc = 0; // loop through the octants for(i=0; i<8; i++) { // midpoint loop x = r; y = 0; d = 1 - x; while (y <= x) { // calc index of point t = (i + 1) % 4 > 1; u = t ? y : x; v = t ? x : y; h = (c + v * (i > 3 ? 1 : -1)) * e + (c + u * (i > 1 && i < 6 ? -1 : 1)); // add point if space is empty if(!points[h]) { points[h] = pc < sl ? text[pc] : 0; pos[pc] = h; pc++; } y++; d += 2 * d > 0 ? y- --x : y + 1; } if(i % 2) { // reverse point order for odd octants for(g=0; g<(pc-lc)/2; g++) { t = points[pos[lc + g]]; points[pos[lc + g]] = points[pos[pc - 1 - g]]; points[pos[pc - 1 - g]] = t; } } lc = pc; } } // write output for(i=0;i<q;i++) { c = points[i]; putchar(c ? c : 32); if(i % e == e - 1) putchar(10); } } ``` ]
[Question] [ I define four box styles: ``` +-----+ ooooooo ^^^^^ ******* | 1 | o 2 o < 3 > * 4 * | | o o < > * * +-----+ ooooooo vvvvv ******* ``` Write a program or function that given an integer and a string will find one of the above boxes inside the string and change its style into the box style requested by the user. For example: ``` 1 This is a test document. It ********* has no *purpose* other than dem*onstrat*ion. ********* ``` Becomes: ``` This is a test document. It +-------+ has no |purpose| other than dem|onstrat|ion. +-------+ ``` You may assume that the input contains exactly one valid box that's at least 3x3. Your code must ignore incomplete/incorrect boxes: ``` ooooooooooooooooooooooooooooooooo o This is not a box. o This is. o ooooooooooo ooooo ooooooooooooooo ^^^^ ###### <NOPE> #NOPE# vVVv ###### ``` --- Shortest code in bytes wins. [Answer] # Julia, ~~995~~ ~~818~~ ~~713~~ 613 bytes ``` g=(s,n)->(w=map;f=t->(t[z=end];for i=1:z-2,j=eachmatch(r"([*o]|(\+)|(\ ))(?(2)-|(?(3)\^|\1))+\1",t[i],1>0),k=i+2:z N=j.match;N[M=end];p=N[1];J=j.offset;u=w(i->i[[J:J+M-1]∩[1:end]],t);try p%3<1?for l=matchall(r"^([*o])\1+\1",u[k]),q=3:endof(l) w(r->r[[1,q]],u[i:k])⊆["$p$p"]&&return(i,k,J,J+q-1)end:u[k]==replace(N,"^","v")&&w(r->r[[1,M]],u[i+1:k-1])⊆[p<33?"<>":"||"]&&return(i,k,J,M+J-1)end;end);o=ones(5)';T=split(s,'\n');(i,j,k,l)=f(T);u=w(collect,T);(a,u[i][r=k+1:l-1],u[j][r],b,c)=41+[2 4 4 83 83;70o;-9 53 77 19 21;o][n,:];u[i][I]=u[j][I=[k,l]]=a;w(e->(e[k]=b;e[l]=c),u[i+1:j-1]);join(w(join,u),'\n')); ``` Ungolfed with explanation: ``` function g(s,n) # First, we define function f(t), which finds the box function f(t) # determine the number of rows of text z=length(t) # Get an iterator of all of the matches to iterate over # Regex handles all four box styles temp=i->eachmatch(r"([*o]|(\+)|(\ ))(?(2)-|(?(3)\^|\1))+\1",t[i],1>0) # Iterate over rows up to third-last one (i)... # and over any possible box-tops on each of those rows (j)... # and all possible box-bottom rows for each possible box-top (k) for i=1:z-2,j=temp(i),k=i+2:z # N holds the matched box-top N=j.match # M stores the length of the match M=length(N) # p holds the first letter of the match, the corner character. p=N[1] # J holds the position of the first character of the match in row i J=j.offset # The intersection here allows truncation of each row to only those # parts that lie within the valid range of the box-top u=map(i->i[[J:J+M-1]∩[1:end]],t) # A try block is being used to skip if a BoundsError is encountered # this BoundsError will occur if a box cannot be formed due to # a row not being long enough to form both sides or to form bottom try # This distinguishes between simple boxes (types 2 and 4) # from fancy boxes (types 1 and 3), as code differs between them if p%3<1 # "then" for simple boxes # loop over l either doesn't run (if bottom won't form a match # from position 1 within u) or holds the unique match # then loop over q looks at all possible bottom-lengths for l=matchall(r"^([*o])\1+\1",u[k]),q=3:endof(l) # If box sides are found to match top and bottom... if map(r->r[[1,q]],u[i:k])⊆["$p$p"] # return the coordinates of the box return(i,k,J,J+q-1) end end else # "else" for fancy boxes # If the bottom matches the top (replace fixes for type 3)... if u[k]==replace(N,"^","v") # ... and the edges are also there... if map(r->r[[1,M]],u[i+1:k-1])⊆[p<33?"<>":"||"] # return the coordinates return(i,k,J,M+J-1) end end end end end end # That defines function f(t), now for the replacement part of the code # Input s is a single string with newlines, split into separate strings T=split(s,'\n') # Find the coordinates of the box using f(T) (i,j,k,l)=f(T) # u holds the same strings, but stored as char arrays u=map(collect,T) # Here, we have the appropriate replacement characters for each type # with n determining which character from each array is taken # Variable names are used here to make it clearer corners = ['+';'o';' ';'*'][n] topedge = ['-';'o';'^';'*'][n] bottomedge=['-';'o';'v';'*'][n] leftedge = ['|';'o';'<';'*'][n] rightedge= ['|';'o';'>';'*'][n] # Assign the appropriate characters in the appropriate places u[i][[k,l]]=corners u[j][[k,l]]=corners u[i][k+1:l-1]=topedge u[j][k+1:l-1]=bottomedge # Iteration is required here because it's an array of arrays for e=i+1:j-1 u[e][k]=leftedge u[e][l]=rightedge end # All that's left to do is recombine to form a single string again # we join each internal char array into single-line strings... # then join the strings together with a newline delimiter, and return return join(map(join,u),'\n') end ``` Contrary to how I first approached it, this code will only work correctly for "valid" type numbers - 1, 2, 3, or 4. It is split into two parts - a box-finder, and a box-replacer. The box-finder code, function `f(t)`, uses regex to locate tops and, for the simpler boxes (types 2 and 4), bottoms. The first regex is the simplest way I could find to find the box-tops. Here's the logic of it: ``` r"([*o]|(\+)|(\ ))(?(2)-|(?(3)\^|\1))+\1" ([*o]|(\+)|(\ )) < This finds the first corner ( 2) ( 3) . if a + or space, conditionals ( 1 ) . kick in, so they're captured . separately (?(2)-| ) < If a +, top edge must be . at least one - (?(3)\^|\1) < Otherwise, if a space, top . edge must be at least one ^, . otherwise, repeat the corner + < Allows more than one top-edge . character \1 < finish with the same corner . char found at the start ``` The code is used like this: ``` julia> s="""This is a test document. It************* has no *purpose* other than dem*onstrat*ion. ************o"""; julia> print(s) This is a test document. It************* has no *purpose* other than dem*onstrat*ion. ************o julia> print(g(s,1)) This is a test document. It*+-------+*** has no |purpose| other than dem|onstrat|ion. **+-------+*o ``` Printing is not included in the function, as the output format isn't specified - I just return the string, you can print it afterwards as seen above. ]
[Question] [ There's a type of *n*×*n* matrix *W* called the basic [Weyr canonical form](https://en.wikipedia.org/wiki/Weyr_canonical_form). Such a matrix is described by its [blocks](https://en.wikipedia.org/wiki/Block_matrix) and has the following properties, using the following reference diagram: [![enter image description here](https://i.stack.imgur.com/Sht6F.png)](https://i.stack.imgur.com/Sht6F.png) * the main diagonal blocks *Wii* are *ni×ni* matrices of the form λ***Ini*** where ***Ini*** is the *ni×ni* identity matrix. * *n1 ≥ n2 ≥ ... ≥ nr* * the first superdiagonal blocks *Wk-1,k* for *k ∈ 2..r* are *nk-1×nk* matrices that are *full column rank in row-reduced echelon form*, or more simply put, ***Ink*** sitting on top of *nk-1 - nk* rows of zeros. * all other blocks are **0** matrices. For example: [![Weyr form](https://i.stack.imgur.com/HI5O5.jpg)](https://i.stack.imgur.com/HI5O5.jpg) * The main diagonal blocks (yellow) are such that the ni are 4, 2, 2, and 1. * The first superdiagonal blocks are in green. * The grey zone consists of all the other blocks, which are all **0**. For this challenge we will assume λ=1. ## Input A square matrix with 0s and 1s in any convenient format. ## Output Output one of two distinct values for whether the input matrix is Weyr or not Weyr. ## Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Fewest bytes in each language wins. Standard rules/loopholes apply. ## Test cases Presented as arrays of rows. Weyr: ``` [[1]] [[1,1],[0,1]] [[1,0,1,0,0],[0,1,0,1,0],[0,0,1,0,1],[0,0,0,1,0],[0,0,0,0,1]] [[1,0,0,1,0,0,0,0,0],[0,1,0,0,1,0,0,0,0],[0,0,1,0,0,1,0,0,0],[0,0,0,1,0,0,1,0,0],[0,0,0,0,1,0,0,1,0],[0,0,0,0,0,1,0,0,1],[0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,0],[0,0,0,0,0,0,0,0,1]] [[1,0,0,0,1,0,0,0,0],[0,1,0,0,0,1,0,0,0],[0,0,1,0,0,0,0,0,0],[0,0,0,1,0,0,0,0,0],[0,0,0,0,1,0,1,0,0],[0,0,0,0,0,1,0,1,0],[0,0,0,0,0,0,1,0,1],[0,0,0,0,0,0,0,1,0],[0,0,0,0,0,0,0,0,1]] ``` Non-Weyr: ``` [[0]] [[1,0],[1,1]] [[1,0,0,1,0,0],[0,1,0,0,0,0],[0,0,1,0,0,1],[0,0,0,1,0,0],[0,0,0,0,1,0],[0,0,0,0,0,1]] [[1,0,1,0,0],[0,1,0,0,0],[0,0,1,0,0],[0,0,0,1,0],[0,0,0,0,1]] [[1,0,0,1,0,0,0,0,0],[0,1,0,0,1,0,0,0,0],[0,0,1,0,0,1,0,0,0],[0,0,0,1,0,0,0,0,0],[0,0,0,0,1,0,1,0,0],[0,0,0,0,0,1,0,1,0],[0,0,0,0,0,0,1,0,1],[0,0,0,0,0,0,0,1,0],[0,0,0,0,0,0,0,0,1]] ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~91~~ ~~88~~ ~~84~~ ~~80~~ 81 bytes ``` {x~e|(-n)#'(0*x),'(!n)=\:,/(-1_b)+1_0{x#!y}':|-n-':|b:|\@[-1++/|\|+x|e:=n:#x;]\0} ``` [Try it online!](https://tio.run/##fZFfy4IwFIfv@xSGgVtudM7tDkHfQ6U/kBG97AXpYuHsq9uyMl0rRP2dR872eHaS@qDbtlS1ue4tk5rHCYO54SJhU82XuRILJnG94ymuoTbx9NIkykot3XOnbL7KJKbpwuY2NXavllrFhoocmvas6ll2uVaqjAxt/k/ENuX2@EeGKsJVxYtmcs6EQMLCBYYREkTI@9IV7gZ6vLFLz9ylN@vysPHZ@rjoVeGAeOy94GBbj/WkZwPid0GgKyg61vIYeb/iicKHqC@BAQn8UP8tKoT79jImvHPwJ01fpksQniiNtoHgiY@WCp84FO0N "K (ngn/k) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 270 bytes ``` lambda m,w=0:{w}&{0,len(m)}and I(m)or any(I([l[:i]for l in m[:i]])*I([l[i:j+i]for l in m[:j]])*(sum(sum(m[:i]+[l[:i]for l in m],[]))==2*i+j)and f([l[i:]for l in m[i:]],j)for i in range(w,len(m))for j in range(1,i+1)) I=lambda m:all(sum(l)==l[i]>0for i,l in enumerate(m)) ``` [Try it online!](https://tio.run/##1ZLBboQgFEX3fgWrRkYWMEsTu/cbLAuawRYDzMQ6MZPJfLsFtBaQ2N0kjSHh3SeXc8O73IbPsz5ObfU2SabeTwwoNFa4vI@PlztGkutcwQfTJ1CbzbkHTN/yOm9kUwramloCoYGyFYUH1xBlV4S9zvbyr6tyy/1cxA4UNRTCqjoeRNFBe2E7m/lOpqKog1YRVumZ/uD5uGA6vfvVCRIFgTCrq59oJZPSMUhzkzGnr9h5IefP9VXxng3cek2XXujBQjTE4GdeiYiBxWgjG8ksPDfnyu2Xatn7uqu2NovR/K12nurZrqpvH6BEqqetaqBtz@Lk2R38GDVSA3ycxMcJ/C0WSWKRRKRd/Jk/82LgTSpzlqDkJJCdJwzSR88WJg6zhin/GrTI@rmD9tSX@j@DRhL40zc "Python 2 – Try It Online") Explanation: Recursively checks blocks for identity and their superdiagonal blocks. `I` checks if a matrix is an identity matrix ``` I=lambda m:all(sum(l)==l[i]>0for i,l in enumerate(m)) ``` For each block of the input matrix, the function checks that it is an identity, and that there is another identity matrix block, to it's right. The next iteration then looks at a block of that size. ``` {w}&{0,len(m)}and I(m) # if the while matrix is an identity matrix, # return true (but only the first time or last block) or any( I([l[:i]for l in m[:i]]) # the current block is identity *I([l[i:j+i]for l in m[:j]]) # and, the smaller block to the right is identity *(sum(sum(m[:i]+[l[:i]for l in m],[]))==2*i+j) # and everything below and to the right (not the # smaller block), are 0 and f([l[i:]for l in m[i:]],j) # and the remaining matrix is alse Weyr(recursively) for i in range(w,len(m)) # for each block size i for j in range(1,i+1) # for each smaller right block of size j ) ``` ]
[Question] [ A riffle shuffle is a type of shuffle where the deck is split into two partitions and the partitions are then spliced back together to create a new shuffled deck. The cards are spliced together in such a way that cards maintain their relative order *within the partition they are a member of*. For example, if card **A** is before card **B** in the deck and cards **A** and **B** are in the same partition, card **A** must be before card **B** in the final result, even if the number of cards between them has increased. If **A** and **B** are in different partitions, they can be in any order, regardless of their starting order, in the final result. Each riffle shuffle can then be viewed as a permutation of the original deck of cards. For example the permutation ``` 1,2,3 -> 1,3,2 ``` is a riffle shuffle. If you split the deck like so ``` 1, 2 | 3 ``` we see that every card in `1,3,2` has the same relative order to every other card in it's partition. `2` is still after `1`. On the other hand the following permutation is *not* a riffle shuffle. ``` 1,2,3 -> 3,2,1 ``` We can see this because for all the two (non-trivial) partitions ``` 1, 2 | 3 1 | 2, 3 ``` there is a pair of cards that do not maintain their relative orderings. In the first partition `1` and `2` change their ordering, while in the second partition `2` and `3` change their ordering. However we do see that `3, 2, 1` can be made by composing two riffle shuffles, ``` 1, 3, 2 + 2, 3, 1 = 3, 2, 1 ``` In fact a pretty simple fact to be proven is that *any* permutation can be made my combining some number of riffle shuffle permutations. # Task Your task is to make a program or function that takes a permutation (of size **N**) as input and outputs the smallest number of riffle shuffle permutations (of size **N**) that can be combined to form the input permutation. You do not need to output the riffle shuffles themselves just how many there are. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better. You may output either 1 or 0 for an identity permutation. # Test Cases ``` 1,3,2 -> 1 3,2,1 -> 2 3,1,2,4 -> 1 2,3,4,1 -> 1 4,3,2,1 -> 2 ``` [Answer] # [Python 3](https://docs.python.org/3/), 255 bytes Checks all possible riffles up to the length of the list (maximum number required), so it is very slow for larger input. Could also probably be golfed quite a bit. ``` lambda x:f(range(1,len(x)+1),x) f=lambda x,y,i=0:x==y and i or i<len(x)and min(f(q,y,i+1)for a in range(1,len(x))for q in g(x[:a],x[a:]))or i g=lambda x,y:(x or y)and[[v]+q for v in x[:1]for q in g(x[1:],y)]+[[v]+q for v in y[:1]for q in g(x,y[1:])]or[[]] ``` [Try it online!](https://tio.run/##XY7NbsMgEITP4Sk4gryH4viEypOQVUUbO0ZK8B@J4OldNq3bJCd2dr@ZYcyxH8J@7c1hPbvL59HxpDsxu3BqhYJzG0SSlZKQJOvMRkAGb950MiZzF47c82Hm/v2HpsXFB9GJibhi7srVcR/4c@x9P9H@JJLVDiFZp1FKCmOnhzYtEjVkyrb2htXEyXsjb3EqfEpSGiFLrF7J/EpCJlbiMFuLuMZ2iR9fbmkXbrhlO2sV7KFGUAikykxjvSlVdPN3rQvbkPjVDTzwyBgV@zBeI/DhGstLn/iv1Gw3zj5E0Ys7JTdMrt8 "Python 3 – Try It Online") [Answer] # [Clean](https://clean.cs.ru.nl), ~~206~~ ... 185 bytes ``` import StdEnv f=flatten $a b#[c:d]=b |a>[]#[u:v]=a =[a++b,b++a:f[[[u,c:e],[c,u:e]]\\e<- $v d]]=[b] @l#i=length l =hd[n\\n<-[0..],e<-iter n(f o map(uncurry$o splitAt(i/2)))[[1..i]]|l==e] ``` [Try it online!](https://tio.run/##DY89b4MwFAB3/4onwQDC0Cb9GFBcpVI7VOqW8fEGY0xiyRgENlKk/Pa6nm654U5ZLV2c5iFYDZM0LpppmVcPFz98u52NYrTSe@1YLqHPULUDiZ495AdShqHdSUgmUFZVz/uqku2IiIGrVhNHxUMidZ0@1ZDvMBAJ7ImdbWaE1e7qb2CZuA3ous6danxuGuJJNl6v4IoR5tS0FMGpsK73fIZtscZ/@sI8HcuyRDw0jSF6WCE0xYuXKVzAGfDIX/g7P/BX/kbxT6WH6xbrn9/4dXdyMmr7Bw "Clean – Try It Online") Generates every possible outcome of shuffling `n` times, and checks if the list is a member. While this is a horribly inefficient way to solve the problem, this code is *particularly slow* due to its use of list comprehensions instead of composition, which heavily limits any elementary graph reduction, and results in a spectacular showcase of Clean's garbage collector. **Ungolfed:** ``` import StdEnv shuffle [] l = [l] shuffle [a: b] [c: d] = [[a: b]++[c: d], [c: d]++[a: b]: flatten [ [[a, c: e], [c, a: e]] \\ e <- shuffle b d ]] numReq l = until cond ((+)1) 0 where cond n = let mapper = map (uncurry shuffle o splitAt (length l/2)) options = iter n (removeDup o flatten o mapper) [[1..length l]] in isMember l options ``` [Try it online!](https://tio.run/##bVHLbsIwELzzFXNMhKGFPg5ROVSih0rtpRxDDiZZwJIfqWNT8fNNl0DSInVP3pmd2dW41CRta1wVNcFIZVtlaucDVqF6sYdRs4/bLVN5AT0C1wK5Ln5hmWFTIC8zVEXPn8Hx@IyKC8t9h2fYahkCWeSd4FQsEeAp6qYF5OlZDPR6DcLTBP3WDaqB4zEbzQd9DvdFG5RG6WyFJBmnsxS3o689eer4DrcY9AtoCkN3KiPrmvwVdB5kAkm0ZfT@ONzi0NRaheeARJPdhT30zTxNr@SuDsrZ5h9LFcjzNYkn4w60jDX79fG4yyUpxzObTnv3P7koC9W8k9mwie63tKsg@f8WuMSSz8WdeBQzcS8eiva7ZPtd005e39rl0UqjyuYH "Clean – Try It Online") ]
[Question] [ Today is Purim on which one custom is to give out triangle-shaped cookies with filling called *hamantaschen* (singular: *hamantasch*). Another custom is to drink heavily. I'm not the most perfect baker.... I have so many irregularly-sized hamantaschen to give out and so many friends to give them to! If I sent you a picture of my cookies, can you tell me how many I have of which size and filling? But because it's Purim and I'm too drunk to read much code, it needs to be as small code as you can make. ## Definitions ### Size A hamantasch can be any **size**. The smallest hamantasch is size 1 and looks like these: ``` /\ -- -- \/ ``` Sometimes, multiple hamantaschen can **overlap**. The shape below counts as two hamantaschen (one size 1, one size 2): ``` /\ /\ \ ---- ``` Some hamantaschen have **filling**. This will be indicated by filling all whitespace inside with a character. Note that size 1 hamantaschen cannot have filling. We will **name** hamantaschen based on filling and size. Let's use the format `<filling> <size>` and if unfilled, `- <size>` (you can use a space instead of a `-`, but markdown doesn't like that). Here are a `. 2`, a `. 4`, and a `- 3`: ``` /\ /./\ ---- /./ \ \../ /./ \ \/ -------- ``` These are a `@ 3`, a `. 2` and a `- 4`: ``` /\ / /\ /\ / /@@\ /..\ / /@@@@\ ---- -------- ``` Here's something more difficult. See how the `& 2` has less filling than you've come to expect due to the slant from the overlapping `- 3`? It has a `- 1`, a `& 2` a `- 3` and a `& 4`: ``` -------- \ \/&/ \ /\/ \/&/ \/ ``` ## Input You will be given a text file or single string of hamantaschen (optional trailing newline and optionally padded trailing whitespace to be even). ### Limits * You can expect the string to be **valid** - that is, every non-whitespace character contributes to a deliciously sweet hamantasch (why waste dough?). * You can also expect it to be **properly filled** or not - that is, each hamantasch it will be entirely filled with a consistent ASCII character - ASCII 32 for unfilled, or anything 32..127 for filled (excluding `/`, `\` and `-`). * These hamantaschen are **not stacked** in 3-space. All `/` and `\` will be visible. All `-` that are not blocked by `/` and `\` will be visible. Filling comes very last. * All hamantaschen will have at least **half of their horizontal line** (rounding up) visible. * Any contiguous block of **filling only fills the smallest hamantasch** that surrounds it. ## Output Return a list of "names" of all the hamantaschen that can be found meeting the above criteria. The output can be in whatever form you'd like (a string, a hash, stdout, etc). ## Test cases ### Test case #1 Input #1: ``` /\ / /\ /\ / /@@\ /..\ / /@@@@\ ---- -------- /\ /**\ /*/\*\ /*/..\*\ -------- ``` Output #1: ``` . 2 . 2 - 4 @ 3 * 4 ``` ### Test Case #2 Input #2: ``` /\---- /\/\*\/ / /\d\/ ------ ``` Output #2: ``` - 3 - 2 d 2 - 1 * 2 - 1 ``` ### Test #3 Input #3: ``` ---- \/\/ /\/\ /\ ---- /::\ ---- ``` Output #3: ``` - 1 - 1 - 2 - 1 - 1 - 2 : 2 ``` ### Test #4 Input #4: ``` /\/\ / /\$\ -/--/\\ --/--\ /xxx/\ /xxx/##\ ---/----\ / \ -------- ``` Output #4: ``` $ 2 x 4 - 3 - 2 - 4 - 1 - 1 # 2 ``` ### Invalid Test Case #5 Input: ``` /\ \/ ``` Output: You do not need to handle this. [Answer] # C#, ~~496~~ 452 bytes ***Edit:*** found a bug with bounds checking... but also striped a load of bytes having been forced to understand my own code. Unrolling the local function helped a bit, and removed the C# 7 specific code. This question has been a lot of fun. ``` using C=System.Console;class P{static void Main(){string D="",L;int W=0,H=0,z=0,d,q,c,j,b;for(;(L=C.ReadLine())!=null;H+=W=L.Length)D+=L;var B=new int[H];for(d=W;(d=-d)>0||++z<H*H;)for(c=1,q=z%H;c<=z/H&q%W+c<W&q>=d&q<H+d&&D[q]==(d>0?92:47)&D[j=q+c]==(d<0?92:47);q-=d+1,c+=2){for(b=0;j>q;)b+=D[--j-d]==45?2:0;for(char h='-',e;c==z/H&b>c;C.WriteLine(h+" "+c/2))for(b=c++;b>1;j=q+=d+1,b-=2)for(;j<q+b;)B[j]=h=B[j]<1&h==45&(e=D[j++])!=47&e!=92&e>32?e:h;}}} ``` [Try it Online](https://tio.run/nexus/cs-core#NVDBbtswDL3nK9R0da1Jih0vQ9HIdIAmBx88YNgOPsQ52JJW28gcKHa7LG2@PZPkjgAlPoqPfOL1pW@6Z7SGn3/7Qf2erQ9df9grLvZl36Pvb/1QDo1Ar4dGom9l0/nYpI6WsoHplGa86QaUQ0hT42fjkmoqaEsr/utw9LmfwXr2Q5UyazrlY3wD3ct@z1MCOWSzTHXPQ403BDL@Wh7RE3TqDzItt@nO8SXk3BxM4iR8fyfkHKefU47tk4A51XC@S7mI4Ryknr7LiYhzTycgPR2nRHreZqt3AL5MwtVjtFw8YJNpQRPhsvH/LNcMJJlTQSDCb7Z7BSFvE81xRWCzZaxl0lAWX1fRMnTKRG301nDP7qnZFjgFVSL4epYfm0G579ZkiqZEBBHGY09BCK@SObcS3MCKmYFuUW2sScXx07bdQQ32iudebUd6vjISWkJ2ZnuLB0/dwGPkqeRLtFLLml8ul@sVBUVQIGeTwIBPI5iwgLGgcGCCmEUfMQpOp5OjTMbw9rYYa2yRLTM1KBhbFjZmH/YP) Complete program, expects space-padded input to standard in, outputs to standard out. The output is one entry per line, with trailing line feed. Cookies are outputted in increasing size order, upper-left most first. It took me a good while to understand the rules, but I think it passes all the examples provided. It works by repeatedly searching the entire grid for valid Hamantaschen, incrementing the 'allowed' size. For each cell, it checks up and down, following the `\` and `/` on either side as far as it can. If it notices that the next row has lots of `-`, and the current size is the 'allowed' size, then it determines the filling and prints out the entry. The filling is found by exploring the entire space of the cookie, looking for an 'unused' cell. When an unused cell is found, it is marked as used (since we increase the allowed size, we know we are the smallest cookie that contains it), and we record the filling. Formatted and commented code: ``` using C=System.Console; class P { static void Main() { // 32 // - 45 // / 47 // \ 92 // range 32..127 (no mod for you) string D="", // the whole map L; // initally each line of the map, later each line of output int W=0, // width H=0, // length (width * height) z=0, // search tracker d, // check direction (this is backwards (1 byte saving!)) q, // check tracker c, // counter (truely, this is the distance from the right to the left) //M, // c max (now inlined as z/H) j, // horiontal tracker b; // - count, and reverse counter // read map and width for(;(L=C.ReadLine())!=null; // read a line, while we can H+=W=L.Length) // record the width, and increment height D+=L; // add the line to the map var B=new int[H]; // whether this filling has been used already (0 -> false, >0 -> true) for(d=W; // init direction (d=-d)>0|| // swap direction, else increment z (this allows us to run the check for the same z twice with opposite direction) ++z<H*H; // for all M, for all q (z<H -> M=z/H=0 -> no valid cookies, so we can safetly skip them) ) for(//M=z/H, // c allow (now inlined) c=1, // reset counter q=z%H; // note position c<=z/H& // counter check // no need for a left check: if we run off the left end, then the right check will necessarily fail q%W+c<W& // right check q>=d& // high check q<H+d&& // low check (short-circuit lookups) D[q]==(d>0?92:47)&D[j=q+c]==(d<0?92:47); // /\ or \/ check, and set j=q+c q-=d+1, // move left tracker c+=2) // increase counter (move right tracker) { // count the number of '-' into b for(b=0; // zero b j>q; // for each element in the row below ) // empty b+=D[--j-d]==45?2:0; // add 2 to b if we tap a '-' // j = q // check valid before looking up cHaracter (so we don't mark unused stuff as taken) // if we are at the current max count, and we have enough -, then we are valid and should be commited for( // this runs either one or zero times, we only have a for here (rather than an if) so we can ditch a pair of braces char h='-', // default filling e; // filling we are considering c==z/H&b>c; C.WriteLine(h+" "+c/2)) // print filling and count // continuously compute character for(b=c++; // count b backwards, starting from c (add 1 to c so we can /2 in print) b>1;j=q+=d+1,b-=2) // count q backwards toward z%H (where q came from), and b backwards toward 1 (for each row) for(;j<q+b;) // for each cell in row B[j]= // mark cell as taken (h,e > 0) h= // record filling B[j]<1& // check cell not already used h==45& // '-' (e=D[j++])!=47& // '/' e!=92& // '\' e>32 // ' ' ?e:h; // take first filling we can // c runs out after this (exists both loops), so no need to action } } } ``` Outputs for the 4 test cases: ``` testcase #1 . 2 . 2 @ 3 - 4 * 4 testcase #2 - 1 - 1 - 2 d 2 * 2 - 3 testcase #3 - 1 - 1 - 1 - 1 - 2 - 2 : 2 testcase #4 - 1 - 1 - 2 $ 2 # 2 - 3 x 4 - 4 ``` ]
[Question] [ This is a mini golf hole: ![](https://i.stack.imgur.com/EwORE.png) The outer boundary is a circle with radius 10 and center (0,0). The inner boundary is a circle with radius 3 and center (0,5). The tee is at (0,-8). Assume the ball is just a point with radius 0. The dynamics of the ball are governed by the following rules: * The ball is initially hit with energy 50, and with a given angle. + The angle is in degress in the Cartesian coordinate system, so 0° means directly to the right, 90° is directly up, and so on. * When the ball hits the edge of the inner or outer circle, it bounces off the circle using the law of reflection. + The angle of collision with the circle at that point is equal to the angle of reflection. (Here angles are relative to the tangent line of the circle at the point of collision.) + For clarification, see [this](https://math.stackexchange.com/questions/81269/angle-of-reflection-off-of-a-circle) or [this](https://stackoverflow.com/questions/5532891/angle-that-a-moving-ball-will-bounce-off-of-an-inert-ball) (in the notation of the second link, R\_0 = 0 in this challenge.) * The ball loses energy as it moves. + For every unit of ground it covers, it loses 1 unit of energy. + Every time it bounces off a wall it loses 5 units of energy. * The ball stops either when it runs out of energy or when it falls into the hole. + If the ball hits a wall with <= 5 units of energy, it stops. + It falls into the hole if it has energy < 10 when it is within distance 1 of the hole, otherwise it keeps moving. ### Challenge Given the x-y coordinates of a hole, return an angle at which that you can hit the ball in order for the ball to fall into the hole (if such an angle exists). ### Input Take as input the x- and y-coordinates of the center of the hole in any convenient form. Input may be taken from STDIN (or closest alternative), command line parameters, or function arguments. ### Output Print or return an angle in degrees at which the ball can be hit from the tee such that the ball will fall into the hole. If such an angle exists, the output should be in the range [0, 360), otherwise the output should be -1. [Answer] **C, 415 430** EDIT: Like @Winny mentioned, exit values above 255 aren't possible, so I had to increase this code size in order to print values up to 360. Assumes 2 (and only 2) command-line inputs (x y) as ints. Answer in degrees is printed or -1 if no degree exists. ``` #include <math.h> #define E(z) {if((e-=5)<0)break;q=n/sqrt(n*n+pow(m-z,2));w=(m-z)/sqrt(n*n+pow(m-z,2));d=(t=d)*(1-2*q*q)-2*f*q*w;f=f*(1-2*w*w)-2*t*q*w;} main(a,v)char**v;{float D=.01,e,d,f,n,m,p=.0174,q,t,w;a-=4;while(++a<360){n=0,m=-8,d=D*cos(a*p),f=D*sin(a*p),e=50;while(e>0){if((pow(n-atoi(v[1]),2)+pow(m-atoi(v[2]),2)<1)&(e<10)&&printf("%d",a))return;n+=d,m+=f,e-=D;if(n*n+m*m>100)E(0)if(n*n+pow(m-5,2)<9)E(5)}}puts("-1");} ``` Ex. ``` >./golfed 0 2; echo $? 90 >./golfed 0 10; echo $? 0 >./golfed -2 -7; echo $? 12 ``` First time golfer; could probably be improved quite a bit. If we need to have more precision, I have a version that takes in x y and returns the angle with doubles working with .01 degree precision at 449 chars. Readable version: ``` #include <math.h> int main(int argc, char** argv) { // p is roughly pi/180 and q, t, and w are temp vars float Delta=.01, energy, delta_x, f(delta_y), n(cur_x), m(cur_y), p=.0174, q, t, w; argc -= 4; /*using argc as int for angle*/ // iterate through each degree while (++argc < 360) { n=0, m=-8, d=D*cos(a*p), f=D*sin(a*p), e=50; // then move in discrete .01 steps while (e > 0) { // check to see if we're inside the hole if ((pow(n-atoi(v[1]),2) + pow(m-atoi(v[2]),2) < 1) & (e<10) && printf("%d",a)) return; // move forward n += d, m += f, e -= D; // check if we've hit the outer wall if (n * n + m * m > 100) { // if too slow, finish this iteration // if not, find reflection vector if ((e -= 5) < 0) break; q = n / sqrt(n * n + pow(m,2)); w = (m) / sqrt(n * n + pow(m,2)); d = (t = d) * (1 - 2 * q * q) - 2 * f * q * w; f = f * (1 - 2 * w * w) - 2 * t * q * w; } // check inner wall collision if (n * n + pow(m - 5,2) < 9) { // if too slow, finish this iteration // if not, find reflection vector if ((e -= 5) < 0) break; q = n / sqrt(n * n + pow(m - 5,2)); w = (m - 5) / sqrt(n * n + pow(m - 5,2)); d = (t = d) * (1 - 2 * q * q) - 2 * f * q * w; f = f * (1 - 2 * w * w) - 2 * t * q * w; } } } // if an angle not found, return -1 puts("-1"); } ``` ]
[Question] [ Your friend invited you to a high-stakes poker game at the last minute and, as a computer scientist, you've decided to use your skills to gain an edge on the game. Your task will be, given `2 cards` (your hand) and `0, 3, 4 or 5 cards` (the dealt cards), you must decide what the best possible hand you can get will be. If all 7 cards are given as arguments, the answer is pretty clear. If given less, the problem becomes more complex. However, this isn't quite enough to give you the edge you're looking for, you must also calculate the best possible hand from the remaining cards to understand what your opponents could have as well. --- **Hold'em Refresher** If you don't know about hold'em, each player in the game starts with 2 cards as their 'hand'. Over the course of 3 'turns', additional cards are revealed to be shared between all players. The first turn, 3 cards are revealed. The second, 1 more, and the third time a final card is revealed. The two cards given first represent your hand, while the latter represents 0, 3, 4, or 5 cards given by the successive turns. --- **Possible Numbers:** ``` [2,3,4,5,6,7,8,9,T(10),J,Q,K,A] ``` **Possible Suits:** ``` [S,C,H,D] ``` **Full Deck:** ``` [2S,3S,4S,5S,6S,7S,8S,9S,TS,JS,QS,KS,AS, # Spades. 2C,3C,4C,5C,6C,7C,8C,9C,TC,JC,QC,KC,AC, # Clubs. 2H,3H,4H,5H,6H,7H,8H,9H,TH,JH,QH,KH,AH, # Hearts. 2D,3D,4D,5D,6D,7D,8D,9D,TD,JD,QD,KD,AD] # Diamonds. ``` **Hand Rankings:** ``` 1:Royal Flush (A-K-Q-J-10, all from the same suit). 2:Straight Flush (Sequential cards, all from the same suit). 3:Four-of-a-Kind (Self explanatory). 4:Full House (3-of-a-kind and a 2-of-a-kind). 5:Flush (All cards are from the same suit). 6:Straight (Sequential Cards, any suits). 7:3-of-a-Kind (Self explanatory). 8:2-Pair (Double 2-of-a-Kind). 9:Pair (2-of-a-Kind). 10:High Card (You have absolutely nothing except a single card). ``` --- **Lets take an example or two and walk through them:** The simple example: `[AS, AC],[AH,AD,9S,9C,9H]` -> `3` (Four-of-a-Kind), `3` (Four-of-a-Kind) The best possible hand you'll have in this setup is the four of a kind hand. The best possible hand your opponents could have is also a 4-of-a-Kind, as you cannot have a KQJ10 in their 2-card hands. --- `[5C,2C],[6C,4C,JH,JD]` -> `2` (Straight Flush), `3` (4-of-a-Kind) You're at risk for a straight flush, but because you have the 2/5C in your hand, nobody else is due to you holding both middle cards. The best they can hope for is having 2 pocket Jacks and getting a Jack on the flop. --- `[JS,JC],[]` -> `1` (Royal Flush), `1` (Royal Flush) No information you can use against them has been given, all you can tell at the moment is that they can only have a royal flush in diamonds/hearts, but it's just as possible that you get the royal flush as they do. In fact, all inputs where the flop has yet to happen should result in a 1-1 answer. --- `[2C,4S],[3C,7S,9D,AH,JD]` -> `10` (High Card), `7` (3-of-a-Kind) This is an example of where you're absolutely screwed, and there's no possibility of a straight or a flush given the river. Meaning the best hand here is pocket aces resulting in a 3-of-a-Kind. --- # I/O Requirements * Input must be separated between what is in your hand and what is public knowledge; it'll likely be easier this way regardless of implementation. + Cards can be tuples or strings, up to you. + The Hand and the Playing Field can be arrays or delimited strings. * Output must be two indexes from the list of hands I've provided (E.G. [2,1]). + It may be returned as part of a function, printed to console or output in a suitable manner. + There must be two distinct values, one for your best hand, another for the best possible. * 10 may be represented as a `T` or as `10`, whichever makes sense for you. * Standard loopholes are disallowed. # Winning Criteria * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count with a tie-breaker of post date. [Answer] # [Haskell](https://www.haskell.org/), ~~433 430~~ 425 bytes -5 bytes thanks to @Laikoni ``` import Data.List q="23456789TJQKA" e=elem l=length b=map r p|z,elem 'A'u,elem 'K'u=1|z=2|e 4t=3|v<3=4|w=5|y=6|e 3t=7|v<4=8|v<5=9|1>0=10where u=[n!!0|n<-p];v=l$nub u;t=b(\n->l[x |x<-u,x==n])q;w=all(==(last$p!!0))[last s|s<-p];y=elem""[u\\s|s<-b(take 5.flip drop('A':q))[0..10]];z=y&&w 0%_=[[]] n%(x:y)=b(x:)((n-1)%y)++n%y _%_=[] h#t|let p=h++t;c i=minimum$b r$concat$b(5%)$b(++i)((7-l i)%([n:[s]|n<-q,s<-"SCHD"]\\p))=(c p,c t) ``` [Try it online!](https://tio.run/##LU/RbuIwEHzPV2zdpNgKoARIaYGthOChau@l4t6CVSW53BHVMSZxCkH@d86J@jKand0dzRyS@isX4nYrSnWsNGwTnYx/FbV2Tkgm01n0OH96/v328b4mTo65yEtHoMjlP31wUiwT5VSgzHXYbWCwHjQ/7H3QYGiuODE5zDROzfdqijNzxsi0@GjFqca5FWf4ZDHCZxO@BBgG50Ne5dBgLO/uAiNXI8WX3yhc2aTQLDWmdC9HLyK@gLmsRs3wgig5Oy3PmAhBEalIau0q@8xY3HGoTd27tH16QuJmv@@1lOrkK4do/FcUCv5UR0VtgcXJPgbjcRhwvrxi@/BwdgLvE@OYc0d69LJomU1xWTBK5ShkXst8X3qt89kdcedwr43INSg8@L5eZlBgWciibEo3hcrNjjJLtJvSyGMWfb@wPvORgIJ5NJaLuOZd69PQBiS7zeuW8P1eMYY0AzXMQLNbmRQSEFRVSA0uxGT9SoZA1jvC7@2w7YdNh5Ndh9NeiTaE3/4D "Haskell – Try It Online") Ungolfed (same idea, slightly different structure): ``` import Data.List -- for (\\) numbers = "23456789TJQKA" e=elem rank_hand hand |royal_flush=1 |straight_flush=2 |four_of_a_kind=3 |full_house=4 |flush=5 |straight=6 |three_kind=7 |two_pair=8 |pair=9 |1>0=10 where nums = [head n | n<-hand] unique = length $ nub nums counts = map (\n->length [x | x<-nums, x==n]) numbers pair = unique < 5 two_pair = unique < 4 -- could also be 3 of a kind, but that's ok three_kind = e 3 counts flush = all (==(last$hand!!0)) [last s|s<-hand] straight = elem "" [nums\\s | s <- map (take 5.flip drop ('A':numbers))[0..10]] full_house = unique < 3 four_of_a_kind = e 4 counts straight_flush = straight && flush royal_flush = straight_flush && elem 'A' nums && elem 'K' nums -- taken from https://codegolf.stackexchange.com/a/34496/66460 -- k%l finds combinations of size k from a list l 0%_=[[]] n%(x:y)=map(x:)((n-1)%y)++n%y _%_=[] -- find every combination available to each player, and rank each one. -- could be golfed a lot more. h#t=let p=h++t a=[n:[s]|n<-numbers,s<-"SCHD"]\\p c i=minimum $ map rank_hand $ concat $ map (5%) $ map (++i) ((7-length i)%a) in(c p,c t) ``` Very slow, since there's no special casing at all (e.g. if no cards have been shown, a royal flush is always possible.) Most of my golfing effort went into the `rank_hand` function; `#` can be golfed a lot more by combining maps and such. `hand#table` calculates the optimal scores for you and your opponent. Does no error checking. ]
[Question] [ **The challenge below requires you to be familiar with formal parser theory.** If you don't know what the question is asking because you don't know what the terms mean, context-free grammars and first/follow sets are covered in a lot of university courses. I can recommend [this Stanford course](http://web.stanford.edu/class/archive/cs/cs143/cs143.1128/), in particular handouts 08 and 09 (from page 7). I've extracted also extracted a [cheat sheet](https://i.stack.imgur.com/lPuvy.png) from these handouts - *I recommend anyone attempting this challenge to read it*. --- Write a program or function that given a context-free grammar finds the follow set of every nonterminal. Informally, the follow set of a nonterminal is a set of terminals and `$` (meaning end-of-input) that you can possibly find after that terminal in a valid sentence. The input is given as a single printable ASCII string or array of printable ASCII lines. You may output the sets in any reasonable format, using `$` (either as literal output, or string inside a set, etc) to indicate the end of input. **You may assume that the input is always valid according to the format below.** The context free grammar is given in a very simplified manner. Every line contains a single production. Every production is a space separated list of symbols. A terminal is a string of characters surrounded by apostrophes (e.g. `'**'`). For simplicity you may assume that terminals do not contain spaces, but it would be nice if your program allows it. A nonterminal may be any string not containing spaces or `$`. The empty production (normally indicated with ε) is simply a line containing only the left hand side nonterminal. The first line is the production defining the start symbol. As an example, the following grammar: S → aSa | bSb | ε Will be given as: ``` S 'a' S 'a' S 'b' S 'b' S ``` --- Example input / outputs: ``` In: S 'a' S 'a' S 'b' S 'b' S Out: S {'a', 'b', $} In: S A B C A 'a' A C 'b' A B C B 'd' A B C 'e' C 'f' Out: S {$} A {'d', 'e', 'f'} B {'e', 'f'} C {'b', 'e', 'f', $} In: Start Alice Bob Alice Charlie 'a' Alice Bob Bob 'a' Alice Charlie Bob '!!!' Charlie 'b' Charlie Out: Start {$} Alice {'a', '!!!', 'b', $} Bob {'a', $} Charlie {'a', $} ``` --- Shortest code in bytes wins. [Answer] # Perl, 257 bytes Includes +4 for `-0p` Give grammar on STDIN (without trailing spaces. Make sure to remove the extra space in the second example). Assumes non-terminal names only contain letters, digits and `_`. Uses `#` instead of `$` to indicate end of input. Can handle literals containing spaces ``` perl -M5.010 follow.pl E T e e '+' T e e T F t t '*' F t t F '(' E ')' F 'id' ^D ``` Outputs the follow sets as a list of `non-terminal literal` in no particular order. For the example above it outputs: ``` F ')' F # t ')' t # T ')' T # F '+' t '+' T '+' F '*' e ')' e # E ')' E # ``` `follow.pl`: ``` #!/usr/bin/perl -0n s/'.*?'/~$&/eg;s% (?=(\w.*\n))%$_.=">$1"%reg;/\s/;$_.=">$` #\n";s%^((\w+)\K ?\S*).*%$s{$1}++||"\$a.=s/ $2\\b/$&/rg"%eemgr,s%^(\w+ ).*?(\w+)$%"\$a.=s/>$1/>$2 /rg"%eermg,$_.=$a,s%>.*\xd8\K .*%%g,s%.+\n%$&x!/\n$&/g%eg until$$_++;s/\xd8.*?\xd8/~$&/eg;say/>(\w+ \W\S*\n)/g ``` Works as shown, but replace `\xd8` and `\n` by their literal versions to get the claimed score. It should be possible to improve this since converting the `first` sets to the `follow` sets is currently very awkward. [Answer] # Python3, 271 bytes ``` def f(g): d={g[0][0]:{''}} q=[(i[1:],[])for i in g] for a,S in q: for i,A in enumerate(a): if A and"'"!=A[0]: if a[i+1:]and"'"==a[i+1][0]:d[A]={*d.get(A,[]),a[i+1],''} for j,*k in g: if j==A and(j,k)not in S:q+=[(a[:i]+k+a[i+1:],S+[(j,k)])] return d ``` [Try it online!](https://tio.run/##dVJNT@MwED2vf8U0l3EaC20pBxQpB7eCA0hcyi0brVziGPfDab3mgCp@e9fjBHaRQLKsN/Nm3htbc3gNz72bXx/8@dzqDjpu8pJBW51M/bOJpzwhvr0xOFY1t/WsbETd5F3vwYJ1YBoGFCixovAYW1NshaRYu5e99iporkgVwHYgQbk2w2xSSZKnLKVVbYuoPnBVlcLk39ayqU7T9sLowCW5i4EUcbDUTYYbMd2mgQZBUtxUVfLiG7HNXR@IXpXHIj5E1aVtim0xmopVUaeqJo/v8Tq8eAft2cyggizL2ApQIaSb8DrhNWFGtLn8qJOwgCWTqVLCMlVJRrkFYIsQMYtZjXR3OPQzM38XCMoHkDv7pGHRr9mAls/K76weRCnDIkd8GutTTWJwMplEg/eu9Qce3a5Gtxt4hDt2B1jggNgj3MI9uwec4oDYLSBHuAHMkbBtcRChXQn9b@PVfq98Wpof48fV9uLPYWcD/7cmnd0F7flD77QAM9L4y2EeP5wdvHWBd/x/vVme518Sl98R8@@Iq0ic/wI) ]
[Question] [ Censors are a common tool used on the interwebs. But they often censor too much of the word, and thus make the cursing ambiguous to the reader. And sometimes they don't censor enough, so the words still remain offending. Your task is to fix that. ## Your task Write a program/function/whatever that takes two lists and a string. The first list will be the dictionary of all words in your language like: `["hello", "goodbye", "belgium", "offensive", "jumping", "hypercool"]`. The next will be subset of the first list containing all of the *offensive* words in the language: `["belgium", "offensive"]`. The words in these lists are guaranteed to contain only lowercase letters of the alphabet. The string is the phrase you will have to censor. It will be made of words from the dictionary, separated by spaces: `"Goodbye offensive belgium"` The return value will be that phrase censored. However, you have to censor in a certain way. Specifically, for each word in the offensive list, you have to *censor as many letters as possible while remaining completely unambiguous in the main dictionary.* So here it would be: `Goodbye o******** b******`. ## Clarifications * Your code has to interpret the words case-insensitively, but return with the initial capitalization. * If there are multiple optimal answers, pick any of them. * If unambiguous censoring is impossible, censor a single letter that has the least number of other possible interpretations (If multiple are possible, again, its your choice). ## Test Cases ``` ["hello", "goodbye", "belgium", "offensive", "jumping", "hypercool"] ["belgium", "offensive"] "Goodbye offensive belgium" -> "Goodbye o******** b******" ["word"] ["word"] "word" -> "****" ["hot", "hat", "bat", "had"] ["hat"] "hat" -> "*at" or "h*t" or "ha*" https://gist.github.com/deekayen/4148741 ["quart"] "I am a quart" -> "I am a q**r*" ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest d\*mn code in bytes wins! P.S. Anyone caught the reference with belgium? ;P [Answer] # JavaScript ES7, 194 bytes ``` (d,c,s,g=(a,b)=>[...b].reduce((z,l,i)=>z+(a[i]==l?1:0),0))=>[for(s of s.split` `)~d.indexOf(s)?[...c[(x=[for(i of c)g(i,s)]).indexOf(Math.max(...x))]].map((l,i)=>l!=s[i]?`*`:l).join``:s].join` ` ``` A very large function. I'm guessing a few bytes can be golfed off but not much unless I completely change the way it works. ]
[Question] [ # Paper Folding for the win --- "How many times can you fold a paper?" - This well known question led to many arguments, competition, myths and theories. Well, the answer to that question depends on many properties of the paper (length, strength, thickness, etc...). In this challenge we will try to fold a piece of paper as much as we can, however, there will be some constraints and assumptions. --- ### Assumptions: * The paper will be represented in pixel-sized cells. The length and width of the paper is `N x M` respectively (which means you can not fold a pixel/cell in the middle). * Unlike real paper, each spot (pixel) of the paper has its own thickness. --- ### A paper: A paper will be represented as a 2D `M x N` Matrix as the top-view of the paper. Each cell of the matrix will contain a number that will represent the thickness of the paper's pixel. Area with no paper is the cell with the number 0. Paper representation example: ``` Option 1 Option 2 2 1 1 1 1 1 1 1 2 [[2,1,1,1,1,1,1,1,2], 1 1 1 1 2 1 1 1 1 [1,1,1,1,2,1,1,1,1], 1 1 1 2 3 2 1 1 1 [1,1,1,2,3,2,1,1,1], 1 1 1 1 2 1 1 1 1 [1,1,1,1,2,1,1,1,1], 2 1 1 1 1 1 1 1 2 [2,1,1,1,1,1,1,1,2]] ``` --- ### A fold: A fold is a manipulation on the matrix defined as follows: Assuming there is a 2 pixels fold from the right side of the paper in the example above, the size of the paper will now be `N-2 x M` and the new thickness of the pixels will be the summation of the previous thickness of the cell + the thickness of the mirrored cell relative to the fold cut: ``` ___ / \ \/<-- | 2 1 1 1 1 1 1|1 2 2 1 1 1 1 3 2 1 1 1 1 2 1 1|1 1 1 1 1 1 2 2 2 1 1 1 2 3 2 1|1 1 ===> 1 1 1 2 3 3 2 1 1 1 1 2 1 1|1 1 1 1 1 1 2 2 2 2 1 1 1 1 1 1|1 2 2 1 1 1 1 3 2 ``` --- ### Constraints: * You can fold a paper from 4 directions only: Top, Left, Right, Bottom. * The fold will be symmetric, which means, if you fold 2 pixels of the paper from the left, all of the cells in the first and second columns will be folded 2 pixels "mirrorly". * A thickness threshold of a paper cell will be given in each case, a cell can not exceed that threshold at any time, which means, you will not be able to fold the paper, if that specific fold will result exceeding the thickness threshold. * Number of pixels being fold must be between 0 and the length/width of the paper. * Do not exceed with your folding the initial dimensions and position of the paper. ( there is no pixel -1 ) --- ### Input: * A paper (represented as described before) * Thickness threshold --- ### Output: * A list of folds that yields a valid paper (with no pixels exceeding the thickness threshold) folded in any way you want (using any heuristic or algorithm you've implemented). --- ### Scoring: The goal is writing a program that will output a set of folds that result in the minimum possible number of remaining pixels for any input. Since this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code wins. --- ### Examples: **Example:** ``` Threshold: 9 1 1 1 1 1 1 1 1 1 1 1 1 fold 2 pixels from top 2 2 2 2 2 2 fold 3 pixels from right 4 4 4 fold 1 pixel from top 1 1 1 1 1 1 ======================> 2 2 2 2 2 2 =======================> 4 4 4 =====================> 8 8 8 No more fold possible 1 1 1 1 1 1 Optional outputs: [2T,3R,1T] ------------or---------- [[2,top],[3,right],[1,top]] ------------or---------- Top 2 Right 3 Top 1 ------or any other sensible readable way------ --------notice the order is inportant--------- ``` --- ### Some Test cases: **Case 1:** ``` N = 17 , M = 11 , Threshold = 16 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 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 2 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 2 3 2 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 2 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ``` **Case 2:** ``` N = 20 , M = 9 , Threshold = 32 1 1 1 1 1 1 1 1 1 8 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 8 1 1 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 8 1 1 1 1 8 1 1 1 1 1 1 1 1 1 1 1 1 1 8 1 1 1 1 1 1 8 1 1 1 1 1 1 1 1 1 1 1 8 1 1 1 1 1 1 1 1 8 1 1 1 1 1 1 1 1 1 1 1 8 1 1 1 1 1 1 8 1 1 1 1 1 1 1 1 1 1 1 1 1 8 1 1 1 1 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 8 1 1 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 8 8 1 1 1 1 1 1 1 1 1 ``` **Case 3:** ``` N = 10 , M = 10 , Threshold = 29 1 1 1 1 1 1 1 1 1 1 1 1 9 1 1 1 1 9 1 1 1 9 9 9 1 1 9 9 9 1 1 1 9 1 1 1 1 9 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 9 1 1 1 1 9 1 1 1 9 9 9 1 1 9 9 9 1 1 1 9 1 1 1 1 9 1 1 1 1 1 1 1 1 1 1 1 1 ``` **Case 4:** ``` N = 20 , M = 12 , Threshold = 23 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 3 4 4 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 3 4 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 3 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 3 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 2 3 4 1 1 1 3 4 3 1 1 1 1 1 1 1 1 1 1 2 3 4 4 1 1 1 1 3 1 1 1 1 1 1 1 1 1 2 2 3 4 4 4 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 3 4 4 4 3 1 1 1 1 1 1 1 1 2 2 2 2 2 3 4 4 4 3 3 2 2 2 1 1 1 1 1 1 1 1 2 2 2 2 2 3 3 2 1 1 4 3 2 1 1 1 1 1 2 2 3 3 2 2 1 1 1 1 1 1 5 4 3 2 1 1 1 3 3 2 2 1 1 1 1 1 1 1 1 1 ``` --- ## Check validity [This nodejs program](https://tio.run/##3Vhtc9o4EP7uX7HnL7XBEF56MwkcdHIpvWOGBiahnZvh/MEBUZwQ27VN6Mvkt@ck2ZZl@QU7Q9q5WgkR0rOr3We1WsW3xoPhLV3T8RuWvUJPT8sNWt59NLbmyvS/wkBxDAe5GvgbF3kbe7tSYTCE7xLgZ227oGyRDyYMoNXHf/4ACm9ukfXJ3@CRel2l0AT8NoDfRvCFqTOJW17CXCsRYHGrDzkbXOTvXAvWxtZDfYoPR3x3hwceJUlam9Zqul57eMEBRG6sTBctfdO2QjeoKLGJzr/dORi7aDab9KveD@a9vekvN6Bwwt@ZjUvDQ/BqPp296rEx8nAKo27z3nAUgyxsNF202i2RonzT4Au15RvUcU/tJ5Q8GC6YySHKokg4Uc5zztkXcxmSgLGYTxhCS02ByHPjIuMuueajJGoy4beBuDSLimAxDpu9B/nSDgTkvsDdn9P5fPr@R9MnGA8NaBNChwGxjcaP4JAsxljjM4dYg38rEjkZvZsLNJbdQIuWfmgDkSzxdvdUMDWZm9uJxKby9ZB7nNGYw34myQR3xA0ae/fcPXo1/uvvKtwKpJbaXf83gtO7N@kwNEqTvEJrY7f1e1nwD9adZe@t@OgO5R7JKf9ACpXhY3LwGc/qgwbhcb81PV886Vc7Z0ZmhZOemhFPRV166KDBENHO58Hw85t2rxUdNLT4WaY/CZzOEotOKkO7UQdDo36jqhljYaWhUXaCCDs4wsR@FmAnmZe0aplf0NbDeAJcODoOQD8BYKRxmHZU1yKQHVXJuGSm66Ugs8Y0j6zVzCarB2bUOvVAEwctLJ1F5TMs//EyQ363q9HmGFt0B1BzQK6HLhakD3/wUatzz7tKV5YceVbJFiHH9ShkNehEhzy528RJy4B0vF9WbaAl8@hI52/2SEbaFxToXy1AilB/Q2YbXMBUxjOLVp4QC@yhACYUZGp4oaBmXBZyQspXz58c1WohxfWvKO0ShZJLpH4FteZLhSfrwvELxkcRkrUo8RLxKpALolsiigd1HD22mfecA3cdKV6BdU9OYGlbnr1Fza39KSBR7ZPh8Rq@2jvYG5YPPr5ouSbpbFDgNRhrH38iA9dkz0eOJHGKj30xstD@WPci3ln5X@sS7UN/TK8nh0tmEMJMCbJhAImXG@lXGyk9VO6NXKvVYHY@G13B@Bo@nk/GbwEPyT1u4sNlPJ5hUKhojO@KEOy2Hs7L@OpYlzUgXsVzjD0yNQtSwUX39gNa4ev70naRSmBKrKPBRFToyZdTuL6YXo2gpxCDyBsR6aTUg2Fw8BFh89H1HC7Or0fXhbAibaVsk0J9i0VLS7a28L2laxFWBLZFcDaUwDoiOAsaALsiOA1th63DejnQdmYToJ0cGGvloZ2Xhx5oui6xzbJYpHWd4lbgYBoef5YQOM3oFQicarnfsgROtWzzjrfCM3x4Bkv5cTgQPEHjGZs4EyfPaAumaK@0ZLuKFz/HoEMs8amDj5PXuHULNWYJlRcI16iyAhVKC3SrmUSW7VYzqZsJjlg66EN0zITwIlo7aTA52pNHWZFQWAdigdesNPB2dzVBUSzwu8aLZEDZfnrRmn5xPpnA6J/z97MJX9aPXtOxNvYeT4l0n0Vs0FSBxI8ezx1pSo@muFW7Gsj03zBZ10jUQQ5ehNCv7XiSypKbqvTEuRE5ke9CnpHVxnUpMLuy0djkp/8A) will: 1. Check if your folded papers are valid 2. Check if your steps are valid # How to use: Call the desired function in the footer. Call **validator** with threshold, initial paper, and a list of steps with the format `[x,d]` for folding `x` pixels from `d` direction. `d` is one of the following strings: "RIGHT","LEFT","TOP","BOTTOM". This function will print if the final paper as a matrix and the amount of pixels reduced. Output will look like this: ``` *** PAPER IS VALID *** Init length: 240, New length: 180, Pixels removed (score): 60 ``` Or, if the paper isn't valid: ``` *** PAPER UNVALID *** NO SCORE :( ``` **You can see call examples commented in the code.** You can also remove the comment in the line `// console.log(paper); // If you want to print the paper after each step` to "debug" and print the folded paper after each fold. [Answer] # [R](https://www.r-project.org/), 425 bytes ``` p=function(m,t){ d=dim(m);r=d[1];c=d[2] l=apply(matrix(c(seq(l=r-1),rep(0,r+c-2),seq(l=c-1)),,2),1,function(f){n=array(0,pmax(g<-(f-1)%%d+1,h<-(d-f-1)%%d+1)) `if`(f,n[1:g[1],]<-m[g[1]:1,],n[,1:g[2]]<-m[,g[2]:1]) n[1:h[1],1:h[2]]=n[1:h[1],1:h[2]]+m[(i=g%%d+1)[1]:r,i[2]:c] if(max(n)<=t)cbind(c(T=f[1],L=f[2]),p(n,t))}) if(!is.null(l))l[[order(sapply(l,function(f){for(x in seq(ncol(f))){d=pmax(f[,x],d-f[,x])};prod(d)}))[1]]]} ``` [Try it online!](https://tio.run/##nVLbitswEH2uvkJlWaohcqlDyEMS/UEf982YrqNLLCpLqqx0E0K@PR3FZZds2D4UgWfm6MzljJwuJjj1I3ZRJ3GJwuy9zDZ4NvAMJ6KEsgMbYJ2Eaup2LdHMW@JEF6M7sqHLyR6YZKP@xZxIVQ086ci@8TST1Rz4hEvEgXOMa/7awMDJiy6l7oj0OHQHtttUzCD18VHNat5jpKrXGIA8W/PMDPdNvdrhMLzdVENTvFXNW4R5weftFebFW9UtkELvC70YvBXvgdnQMCt2U5dSLXFbkmVLrGFlMA8bkUFurVeo9UmYkv0dzbwFHpnHVcEZCvuzHb/6vXPMAbimCUnpxMZpWe5GuwmJHaj1tKzIy@AQBDgpcV2Fafih5Si/WDivYwqKKWxSBmzb8@WBjnaITtOx1zrTYOj1CYuz9xaLDzT3Vv70ehxXtLwx4tk6ajNNupO9Ht8IdEGmH@Dve9Z8yZdAyduvwa5fvgBCHt63fLG5p91UjcqQvE5Tx2ofEdVUqx122@4zVcF/wczfOrluupv4t@0lIzUvZ4Hn3p3jeXMJ4M32mMKLeIJP/zEyhtMQnHZeIdrbXY9g7pMeeyy3ojGMo93isnO4Eea0yVd1mDVqGTA920F/oAZ3yu/df6i5F7MEcvkD "R – Try It Online") This came out *much* longer than I expected, and also slows-down a lot for big sheets of paper with large thresholds (which could be foreseen from the approach). Recursively tries each possible fold, keeping only results that don't exceed the threshold at any pixel, and choosing the series of folds that gives the smallest folded size. Output is 2d list of folds, with 'T' row indicating position of horizontal folds from top, and 'L' row indicating position of vertical folds from left. Ungolfed version: ``` fold_paper=p=function(m,t){ # m=matrix of paper thicknesses; t=threshold thickness; d=dim(m);r=d[1];c=d[2] # get paper dimensions; fold_list=apply( # iterate over list of possible folds to this paper... matrix(c(seq(l=r-1),rep(0,r+c-2),seq(l=c-1)),,2),1, # as a matrix: each row is a possible fold, and the 2 # columns represent positions vertical & horizontal folds; function(f){ new_m=array(0,pmax(g<-(f-1)%%d+1,h<-(d-f-1)%%d+1)) # make a new matrix for each trial fold, then... if(f) # if it's a horizontal fold... new_m[1:g[1],]<-m[g[1]:1,] # add the relevant rows of m, reversed, else new_m[,1:g[2]]<-m[,g[2]:1]) # otherwise add the relevant cols of m, reversed; new_m[1:h[1],1:h[2]]=new_m[1:h[1],1:h[2]]+m[(i=g%%d+1)[1]:r,i[2]:c] # and now add all the unfolded elements of m if(max(new_m)<=t) # now, if we didn't exceed the paper thickness threshold... cbind(c(T=f[1],L=f[2]),p(new_m,t)) # add this fold to the list (labelled with 'T' and 'L', # and recursively call function with newly_folded paper; } ) if(!is.null(fold_list)) # if we ended-up with a list containing any valid folds, fold_list[[ # return the element containing the set of folds with... which.min( # the lowest value of... sapply(fold_list,function(folds){ for(x in seq(ncol(folds))){d=max(folds[,x],d-folds[,x])};prod(d)}))]] # the number of remaining pixels, calculated from the product # of the remaining cols & rows after applying all the folds } ``` ]
[Question] [ > > *This question is the first of several Brain-flak Birthday challenges designed to celebrate Brain-Flak's first Birthday! You can find more information about Brain-Flak's Birthday [here](https://hackmd.io/KwRgnARiAcCGAsBaaEBMAGR8DG8Cmis0AZsVhPLOtsWAOzQAmIQA?view)* > > > Last summer we had the [Brain-flak Integer Metagolf](https://codegolf.stackexchange.com/questions/89726/golf-a-brain-flak-integer), and the answers it generated have been very useful to the Brain-Flak community since. The main thing that makes the Integer Metagolf so efficient is a technique called Multiplication hardcoding. In Brain-Flak runtime multiplication is extremely expensive. The shortest known multiplication snippet is: ``` ({}<>)({<({}[()])><>({})<>}{}<><{}>) ``` *Discovered by [Megatom](https://codegolf.stackexchange.com/users/31203/megatom)* However there is a very simple way to create compile time multiplication. For example the following code will multiply by 5: ``` (({})({})({})({}){}) ``` [Try it online!](https://tio.run/nexus/brain-flak#@6@hUV2riYyB6P9/C0MA) This works because consecutive expressions are added together. Each `({})` does nothing to the stack (`{}` pops and `(..)` pushes it right back) and evaluates to whatever is on top of the stack. All these expressions together sum up to five times whatever was on the top of the stack. For any `n` the following string expression will make a snippet that will multiply the top of the stack by `n`: ``` "("+"({})"*(n-1)+"{})" ``` This works by making `n` expressions that all evaluate to the top of the stack. The first `n-1` don't actually change anything and the last one removes the top of the stack before the push. For composite numbers you can chain multiple smaller expressions together to save bytes. For example you can multiply by 25 by multiplying by 5 twice: ``` (({})({})({})({}){})(({})({})({})({}){}) ``` This is pretty simple, and for some numbers it works pretty well however there are better ways to do this. For example one method I came up with uses the binary representation of the number. ([Here is a python implementation](https://tio.run/nexus/python2#q7A1NLKw/J@UmZdYVKlgq5CbWKCRmVeiAxTQqNCMNraK1eQqKAKKKChpKGlpFJfmakDUamrnpObB2Yaa2kpKeln5QF1K1bWaStpKmkpaFQpp@UUKFQqZeQoQddFWVrqGsUCl1bVoZoH0ayr9/w8A)) This new method is much more effective than the simple string expression shown earlier, but its not the end, there are all sorts of interesting ways to hardcode multiplication and probably a ton that no one has yet discovered. So I think it is time to see how good we can get. ## Brief Overview of Brain-Flak Here is a description of everything you will need to know about Brain-Flak for this challenge. Brain-Flak has "nilads" and "monads". Nilads are parentheses that have nothing inside of them. Each nilad does a thing and returns a value. For this challenge the two nilads we are concerned with are `{}` and `<>`. `{}` pops the top of the active stack and returns its value. `<>` switches the active stack and the in active stack, so that the active stack becomes inactive and the inactive stack becomes active, it returns zero. Monads are parentheses with stuff inside them. They take a single argument, the sum of everything inside them, sometimes perform an action, and then return a value. The three of these we are concerned with are `(...)`, `<...>` and `[...]`. The most important monad for this challenge `(...)` takes the value of the inside and pushes it to the active stack. It then returns the argument. `<...>` and `[...]` are both "inert" monads, that is they do not perform any action but rather modify the value they are passed. `<...>` always returns zero regardless of the argument passed. Meanwhile `[...]` always returns the argument times `-1`. --- ### Sample programs with explanation If you have never programmed in Brain-Flak it might be a good idea to look at some example programs using the operations described ``` ({}{}) ``` This adds the top two numbers on the stack. Each `{}` pops a value off of the stack and `(...)` pushes their sum back. ``` ({}[{}]) ``` Similarly this subtracts the second item on the stack from the first. Like before each `{}` pops a value but the `[..]` around the second one causes it to be added. Once again the `(...)` pushes the sum. ``` ({}<{}>) ``` This removes the second value on the stack keeping the top value intact. It works just like the last two except the second value is silenced by the `<...>` so the push only pushes the first value back. ``` (({})) ``` This makes a second copy of the value on the top of the stack. It does this by popping the top of the stack with `{}` getting its value, the first `(..)` then pushes it back evaluating to its value. The second `(...)` takes the value returned by the first and pushes that to the stack as well. creating a second copy. ## Task Given an integer `n` create a stack-clean Brain-Flak snippet that multiplies the top of the current stack by `n`. You are permitted to use the following Brain-Flak operations ``` (...) -> Push Monad, Pushes the result of its contents <...> -> Zero Monad, Returns zero [...] -> Negative Monad, Returns the opposite of its contents result {} -> Pop nilad, Pops the TOS and returns its value <> -> Switch nilad, Switches the active and inactive stack ``` The other operations are banned for the purpose of the challenge. ## Scoring Your score will be the cumulative lengths of all the programs from `n=2` to `n=10000`. Be sure to include a link to the output of your program for verification. [Answer] # Ruby, 669856 ``` $answers = Hash.new{|hash,n| valid = [] 2.upto(n**0.5){|i| valid.push("("+hash[n/i]+")"+"({})"*(i-2)+"{}") if n%i == 0 } valid.push("({})"+hash[n-1]) (hash[n] = valid.min_by{|s| s.length}) } $answers[1] = "{}" def full_answer n "("+$answers[n]+")" end ``` This is a quick baseline answer. First 1000 min-programs found [here](https://pastebin.com/fk12ysaE). (I tried posting all of them, but that overloaded the max pastebin size.) I may add a code explanation later. Examples: ``` 360: ((((((({})(({}){}){})({}){})({}){}){}){}){}) 4608: (((((((((((({})({}){})({}){}){}){}){}){}){}){}){}){}){}) 9991: (({})((({})(((((((({})((({})({}){}){}){}){}){}){}){}){}){}){})({}){}){}) ``` ]
[Question] [ # The Challenge You are the owner of an amazing service called *Coyote Beta*, which magically answers math questions its users send to it over the internet. But it turns out, bandwidth is expensive. You have two choices, either create a "*Coyote Beta* Pro" or find some way to solve this. Just recently, someone queried `(x + 2)`. Couldn't the client send `x+2`, and the user would see no difference? # The Task Your task is to "minify" math expressions. Given an input expression, you must get rid of whitespace and parentheses until it gives a minimal representation of the same input. The parentheses around associative operations need not be preserved. The only operators given here are `+`, `-`, `*`, `/`, and `^` (exponentiation), with standard mathematical associativity and precedence. The only whitespace given in the input will be actual space characters. # Sample Input/Output ``` Input | Output ------------|-------------- (2+x) + 3 | 2+x+3 ((4+5))*x | (4+5)*x z^(x+42) | z^(x+42) x - ((y)+2) | x-(y+2) (z - y) - x | z-y-x x^(y^2) | x^y^2 x^2 / z | x^2/z - (x + 5)+3 | -(x+5)+3 ``` # Scoring Input/output can use any preferred method. The smallest program in bytes wins. **Exact bits** Exponentiation is right associative and also follows standard math precedence (being the highest). A valid numeric literal is `/[0-9]+/`, and a valid variable literal is `/[a-z]+/`. A single variable literal represents a single value even when its character length is longer than 1. What is meant by "the parentheses around associative operations need not be preserved" is that the output should consist of an expression that results in an identical parse tree, with the exception that associative operations can be rearranged. [Answer] # C#, ~~523~~ ~~519~~ 504 bytes Check the in-code comments to see how it works! --- ## Golfed ``` using System;using System.Collections.Generic;namespace n{class p{static void Main(string[]a){foreach(String s in a){String r=s.Replace(" ","");List<int>l=new List<int>();for(int i=0;i<r.Length;i++){if(r[i]=='('){l.Add(i);continue;}if(r[i]==')'){switch(r[Math.Max(l[l.Count-1]-1,0)]){case'+':case'(':switch(r[Math.Min(i+1,r.Length-1)]){case'+':case'-':case')':r=r.Remove(Math.Max(l[l.Count-1],0),1);r=r.Remove(Math.Min(i,r.Length)-1,1);i-=2;break;}break;}l.RemoveAt(l.Count-1);}}Console.WriteLine(r);}}}} ``` --- ## Ungolfed ``` using System; using System.Collections.Generic; namespace n { class p { static void Main( string[] a ) { // Loop every String given for the program foreach (String s in a) { // Get rid of the spaces String r = s.Replace( " ", "" ); // A little helper that will have the indexes of the '(' List<int> l = new List<int>(); // Begin the optimizatio process for (int i = 0; i < r.Length; i++) { // If char is an '(', add the index to the helper list and continue if (r[ i ] == '(') { l.Add( i ); continue; } // If the char is an ')', validate the group if (r[ i ] == ')') { // If the char before the last '(' is an '+' or '(' ... switch (r[ Math.Max( l[ l.Count - 1 ] - 1, 0 ) ]) { case '+': case '(': // ... and the char after the ')' we're checking now is an '+', '-' or ')' ... switch (r[ Math.Min( i + 1, r.Length - 1 ) ]) { case '+': case '-': case ')': // Remove the '()' since they're most likely desnecessary. r = r.Remove( Math.Max( l[ l.Count - 1 ], 0 ), 1 ); r = r.Remove( Math.Min( i, r.Length ) - 1, 1 ); // Go two steps back in the loop since we removed 2 chars from the String, // otherwise we would miss some invalid inputs i -= 2; break; } break; } // Remove the last inserted index of '(' from the list, // since we matched an ')' for it. l.RemoveAt( l.Count - 1 ); } } // Print the result Console.WriteLine( r ); } } } } ``` --- ## Side notes 1. Fixed some typos and renamed some vars. 2. Nested an switch to get rid of an unnecessary variable. Also, fixed a bug that would render some solutions invalid, reported by [Anders Kaseorg](https://codegolf.stackexchange.com/questions/61079/minifying-math-statements/77844?noredirect=1#comment190070_77844). --- ***P.S.:*** If you have a tip or found a bug, please let me know in the comments and I'll try to fix it ( I'll then add a note about the bug fix with your name ;) ) [Answer] ## C++, 284 bytes **Golfed** ``` #include<iostream> #include<algorithm> int main(){std::string e;std::getline(std::cin,e);e.erase(std::remove_if(e.begin(),e.end(),isspace),e.end());for(int x=0;x<e.length();x++){if(e[x]=='('&&e[x+1]=='('){e.erase(x,1);}if(e[x]==')'&&e[x+1]==')'){e.erase(x,1);}}std::cout<<e;return 0;} ``` **Ungolfed** ``` #include<iostream> #include<algorithm> int main() { std::string e; std::getline(std::cin, e); e.erase(std::remove_if(e.begin(), e.end(), isspace), e.end()); for(int x = 0; x < e.length(); x++) { if (e[x] == '(' && e[x+1] == '('){ e.erase(x, 1); } if (e[x] == ')' && e[x+1] == ')'){ e.erase(x, 1); } } std::cout<<e; return 0; } ``` ]
[Question] [ Key links: * [Troll question](https://codegolf.stackexchange.com/questions/230966/play-thud-troll-edition) * [Chat room](https://chat.stackexchange.com/rooms/127179/thud-challenge) * [Game](https://ajfaraday.github.io/Thud/dist/index.html) * [Controller Interface](https://github.com/AJFaraday/Thud/blob/main/docs/controller_interface.md) Dwarf league table ``` <script src="https://ajfaraday.github.io/Thud/dist/data/tables.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><table> <thead> <tr> <th>Client</th> <th>Wins</th><th>Loses</th> <th>Score</th> </tr></thead> <tbody id="clients"> </tbody></table><script type='text/javascript'> league_table.dwarf.forEach( function(data_row){var row=$('<tr>'); var cell=$('<td>'); cell.html(data_row.name.substring(6)); row.append(cell); cell=$('<td>'); cell.html(data_row.win); row.append(cell); cell=$('<td>'); cell.html(data_row.lose); row.append(cell);row.append(cell);cell=$('<td>'); cell.html(data_row.score); row.append(cell); $('tbody#clients').append(row);});</script> ``` *Thud* is a game described by Terry Pratchett in his novel, *Thud!* The game simulates a battle between the Dwarfs (in blue) and the Trolls (in green) on an octagonal board with the Thudstone (an impassable space) in the centre of the board. [![Thud board in starting positions](https://i.stack.imgur.com/L1m6A.png)](https://i.stack.imgur.com/L1m6A.png) I have created an environment to play the game and create your automated player at: <https://ajfaraday.github.io/Thud/dist/index.html> The challenge is to write the most successful dwarf player of this game (these will be two separate challenges). # Rules Starting with the dwarf player, players take it in turns to move. ## Dwarf Movement On the dwarf player's turn, they can move one dwarf piece either as a walk or a hurl. *Walk*: Dwarfs can move as far as they like in any direction until they hit an obstacle (another dwarf, the edge of the board, or a troll). They can only kill a troll by walking if they are only one space away. *Hurl*: If two or more dwarfs are in a line (horizontal, vertical or diagonal), they can hurl the dwarf on the end of the line, by the length of the line (e.g. in a line of 3, the dwarf on the end can be hurled 3 spaces). If a dwarf is hurled into a troll, the troll is killed, reducing the troll player's score by 4 points. ## Troll Movement On the Troll player's turn they can move one troll piece, either as a walk or a shove. *Walk*: Trolls can move one space in any direction, unless a troll, dwarf or the edge of the board is in the way. Whenever a troll moves, it kills all dwarfs adjacent to its destination space. *Shove*: If two or more trolls are in a line (horizontal, vertical or diagonal) they can shove the troll at the end of the line that number of spaces away, but *only* if any of the target space's immediate neighbours contain a dwarf. When a troll is shoved, it kills all dwarfs on or adjacent to it's destination space. A troll may not land directly on a dwarf by either walk or shove moves. Each dwarf killed reduces the dwarf player's score by 1 point. ## Scores The score is calculated thus: * The dwarf player has one point for every dwarf remaining on the board. * The troll player has four points for every troll remaining on the board. * The key figure is the difference between these two. This will be used to calculate players' scores in the tournament. ## Ending the game The game ends when any of these conditions is met: * There are no dwarfs on the board. * There are no trolls on the board. * Both players have declared the game over. * The game has reached its cut-off length of 500 moves. # How to manually play a game * Go to <https://ajfaraday.github.io/Thud/dist/index.html> * Hover the mouse over a piece to see it's available moves. * Click on a piece to select it for the current move. * Click on one of the available moves to move the piece. * (You can click the relevant 'Make Peace' button to declare the game over according to that player, during their turn) # How to set up a local instance of the game You don't have to clone the repository and use it locally to make the game work, or to create an entry, but it helps. * `git clone https://github.com/AJFaraday/Thud.git` * `cd Thud` * `npm install` * You can then call `node script/get_clients.js` to get the latest entries from Stack Exchange If you prefer, you can use the github pages instance at <https://ajfaraday.github.io/Thud/dist/index.html> # How to customize a game * Open /dist/index.html in your browser * Click 'Customize' * Select troll and dwarf clients (manual allows direct control) * Select a turn time in milliseconds (only relevant to non-manual players) * Click 'Run Game' to see or play the game. * (Clicking 'Close' will not enact any changes) # Clients The game is played by clients, which represent either a troll or a dwarf player. Each is a JavaScript class which must have these three functions: * `constructor(controller)` - controller is an object which acts as your interface with the game (see below). * `turn()` - This is called whenever it is your players turn to move. * `end_turn()` - This is called after your player's turn is over. It can not move pieces, but can make decisions on whether or not to declare the game over. ## Controller The `controller` object is your client's interface with the game itself. You can find full documentation for the controller class here: <https://github.com/AJFaraday/Thud/blob/main/docs/controller_interface.md> It provides these functions to interrogate the state of the game: * `turn()` - Current turn of the game * `scores()` - The current score * `spaces()` - Every space, and what's in it * `space_info(x, y)` - Detailed information on any space on the board. * `dwarfs()` - The location of every dwarf * `trolls()` - The location of every troll * `pieces()` - All pieces belonging to the current player (equivalent of `dwarfs()` or `trolls()`) * `indexed_dwarfs()` - The location of every dwarf with a fixed index * `indexed_trolls()` - The location of every troll with a fixed index * `previous_move()` - What got moved to where last turn * `killing_moves()` - All moves which can kill one or more opponent * `current_space` - Currently selected space (not a function) * `clear_space()` - Empties currently selected space These functions are used to actually make your move: * `check_space(x, y)`- Find out what moves are available from a given space * `select_space(x, y)` - The player decides to move a piece at space. * `check_move(x, y)` - Find out what will happen if you move to a place * `move(x, y)` - The player moves the current piece to the selected space. These are concerned with ending the game: * `declare(game_over)` - Say whether or not your player thinks the game is over. * `opponent_declared()` - Has the opponent declared the game over? Your client will also have a `utils` object which will provide these helpful geometry functions: * `utils.distance_between(source, target)` - The square distance between two objects which respond to x and y * `utils.farthest_from(spaces, target)` - From an array of spaces (with x and y), choose the farthest from target (with x and y) * `utils.closest_to(spaces, target)` - From an array of spaces (with x and y), choose the closest to target (with x and y) # How to write a client Warning: There is an issue with the project on Firefox (<https://github.com/AJFaraday/Thud/issues/3>) which prevents editing the code in the browser. This has been confirmed to work in Chrome. * Open 'dist/index.html' in your browser. * Click 'Customize'. * Select 'dwarf/template' as the Dwarf player (or use another client as a starting point). * Click 'Edit' beside the Dwarf player select. * Write your client code in the text box provided. * The Validate button will change colour based on whether or not the client is passes validations (see below). * When you're happy with it, click 'Apply' (This can be done before it passes validation, but it may not actually work). * Select a worthy opponent and click 'Run Game' to see the game. ## Validations In order for a client to work, and therefore be enterable in the challenge, it has to pass these validations: * It must evaluate as Javascript code. * The code must return a class with a constructor which accepts one argument. * Instances of this class should have functions named `turn()` and `end_turn()` * The client must play a game until it is over (i.e. it must call a valid `move` during every `turn` call). The validator will run games against default opponents to determine if this happens. * Does not have any forbidden terms + `game.` - Only interact with the game via controller + `Math.random` - Please keep it deterministic + `setTimeout` or `setInterval` - Keep it sequential + `eval`, `require` or `import` - Just don't You can open the developer console (F12) to see more detailed information on your client's validation process. ## How to save a client If you have cloned the git repository, you can save your entry for future tinkering. This step is not required for entry in the challenge, but it may be helpful. * Edit a client, as above. * When you're happy with it (preferably if it's passing validation, too), click 'Copy' from the edit interface. * Create a .js file in `/src/clients/dwarf/entry` with the name of your entry e.g. `/src/clients/dwarf/entrygreat_dwarf_player.js`. (This folder will not be wiped by `get_clients.js`) * Run `node script/get_clients.js` from the Thud directory to make your entry available from the Dwarf player select. You only need to do this once to make it avilable. * `npm run build` - this will keep watching for changes in your entry and updating the package. ## How to enter your client in the competition * Decide on the name of your client, your client\_name must only have alpha characters and underscores. * Answer this question with your entry + The first line of your answer should be your client's name as a title (with = characters under it on the second line) + There should be a code block containing the class for your entry (with or without the preceeding `module.exports =`) + After that please include a brief explanation of your client's behaviour, and any other information you'd like to include. Once this is in place, anyone running `./get_answers.sh` will see your client available under your username. The GitHub Pages instance will also be updated periodically, so by making an entry, your code will be added to the repo. # Tournament rules The tournament will pit every available dwarf client (in `/src/clients/dwarf/`) against every available troll client (in `/src/clients/troll/`), and each pairing will play exactly one game. The *difference* between the two players' scores will then update a running total for each client. The winner will gain the difference, and the loser will lose the difference. There are two winners in the tournament: the most successful troll player and the most successful dwarf player. # Seeing the result of the tournament You can use the 'League Table' button to see the overall results of the clients. If you click on a client, you will see all the matches for that client. You can use the 'Matches' button to see the result of all matches. If you click on a match, the game will replay the match for you. You can change the select at the bottom of the screen to highlight specific clients. To rerun the tournament (including changes on Stack Exchange and your own entries in /src/clients/dwarf/entry) you can run `.get_answers.sh`. This will update the 'League Table' and 'Matches' screens. --- According to the rules, after playing a game, the players swap sides, so please also write an entry on the [Troll challenge](https://codegolf.stackexchange.com/questions/230966/play-thud-troll-edition). ]
[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/22009/edit). Closed 7 years ago. [Improve this question](/posts/22009/edit) ## **The Challenge** You must calculate pi in the shortest length you can. Any language is welcome to join and you can use any formula to calculate pi. It must be able to calculate pi to at least 5 decimal places. Shortest, would be measured in characters. Competition lasts for 48 hours. Begin. --- **Note**: [This similar question](https://codegolf.stackexchange.com/questions/7112/calculate-pi-to-5-decimals?lq=1) states that PI must be calculated using the series 4 \* (1 – 1/3 + 1/5 – 1/7 + …). This question does **not** have this restriction, and in fact a lot of answers here (including the most likely to win) would be invalid in that other question. So, this is not a duplicate. [Answer] ## Python3, 7 Runs in the interactive shell ``` 355/113 ``` Output: `3.1415929203539825`, correct to 6 decimal places And finally I have a solution that beats APL! Oh, and in case you are wondering, this ratio is called the 密率 (literally "precise ratio"), and is proposed by the Chinese mathematician Zu Chongzhi (429-500 AD). A related wikipedia article can be found [here](https://en.wikipedia.org/wiki/Mil%C3%BC). Zu also gave the ratio 22/7 as the "rough ratio", and he is known to be the first mathematician to propose that 3.1415926 <= pi <=3.1415927 [Answer] # PHP — ~~132~~ ~~127~~ ~~125~~ 124 bytes Basic Monte-Carlo simulation. Every 10M iterations, it prints the current status: ``` for($i=1,$j=$k=0;;$i++){$x=mt_rand(0,1e7)/1e7;$y=mt_rand(0,1e7)/1e7;$j+=$x*$x+$y*$y<=1;$k++;if(!($i%1e7))echo 4*$j/$k."\n";} ``` Thanks to cloudfeet and zamnuts for suggestions! Sample output: ``` $ php pi.php 3.1410564 3.1414008 3.1413388 3.1412641 3.14132568 3.1413496666667 3.1414522857143 3.1414817 3.1415271111111 3.14155092 ... 3.1415901754386 3.1415890482759 3.1415925423731 ``` [Answer] ## J 6 ``` {:*._1 ``` Explanation: `*.` gives length and angle of a complex number. The angle of -1 is pi. `{:` takes the tail of the list [length, angle] Just for the slowly-converging-series-fettishists, for 21 bytes, a Leibniz series: ``` +/(4*_1&^%>:@+:)i.1e6 3.14159 ``` [Answer] ## Perl, 42 bytes ``` map{$a+=(-1)**$_/(2*$_+1)}0..9x6;print$a*4 ``` It's calculates π using the [Leibniz formula](https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80): ![Leipniz formula](https://i.stack.imgur.com/oakSa.png) 999999 is used as largest *n* to get the precision of five decimal digits. Result: `**3.14159**165358977` [Answer] # TECHNICALLY I'M CALCULATING, 9 ``` 0+3.14159 ``` # TECHNICALLY I'M STILL CALCULATING, 10 ``` PI-acos(1) ``` # I'M CALCULATING SO HARD, 8 ``` acos(-1) ``` # I ACCIDENTALLY PI, 12 ``` "3.14"+"159" ``` And technically, this answer stinks. [Answer] ## Piet, many codels Not my answer, but this is the best solution I've seen to this problem: ![Pi approximation in Piet](https://i.stack.imgur.com/qvRiF.png) My understanding is that it adds up the pixels in the circle and divides by the radius, and then once again. That is: ``` A = πr² # solve for π π = A/r² π = (A/r)/r ``` A better approach in my mind is a program that generates this image at an arbitrary size and then runs it through a Piet interpreter. Source: <http://www.dangermouse.net/esoteric/piet/samples.html> [Answer] # APL - 6 ``` 2ׯ1○1 ``` Outputs `3.141592654`. It computes twice the arcsine of 1. A 13-char solution would be: ``` --/4÷1-2×⍳1e6 ``` This outputs `3.141591654` for me, which fits the requested precision. It uses the simple `+ 4/1 - 4/3 + 4/5 - 4/7 ...` series to calculate though. [Answer] # J - 5 bytes ``` |^._1 ``` This means `|log(-1)|`. [Answer] # Octave, 31 ``` quad(inline("sqrt(4-x^2)"),0,2) ``` Calculates the area of one quarter of a circle with radius 2, through numerical integration. ``` octave:1> quad(inline("sqrt(4-x^2)"),0,2) ans = 3.14159265358979 ``` [Answer] # Mathematica 6 ``` 180N@° -->3.14159 ``` [Answer] # Python, 88 Solution : ``` l=q=d=0;t,s,n,r=3.,3,1,24 while s!=l:l,n,q,d,r=s,n+q,q+8,d+r,r+32;t=(t*n)/d;s+=t print s ``` Sample output in Python shell : ``` >>> print s 3.14159265359 ``` Manages to avoid any imports. Can easily be swapped to use the arbitrary precision Decimal library; just replace `3.` with `Decimal('3')`, set the precision before and after, then unary plus the result to convert precision. And unlike a whole lot of the answers here, actually *computes* π instead of relying on built-in constants or math fakery, i.e. `math.acos(-1)`, `math.radians(180)`, etc. [Answer] ### x86 assembly language (5 characters) ``` fldpi ``` Whether this loads a constant from ROM or actually calculates the answer depends on the processor though (but on at least some, it actually does a calculation, not just loading the number from ROM). To put things in perspective, it's listed as taking 40 clock cycles on a 387, which is rather more than seems to make sense if it were just loading the value from ROM. If you really want to ensure a calculation you could do something like: ``` fld1 fld1 fpatan fimul f f dd 4 ``` [for 27 characters] [Answer] # bc -l, 37 bytes ``` for(p=n=2;n<7^7;n+=2)p*=n*n/(n*n-1);p ``` I don't see any other answers using the [Wallis product](http://en.wikipedia.org/wiki/Wallis_product), so since its named after [my namesake](http://en.wikipedia.org/wiki/John_Wallis) (my *History of Mathematics* lecturer got a big kick out of that), I couldn't resist. Turns out its a fairly nice algorithm from the golfing perspective, but its rate of convergence is abysmal - approaching 1 million iterations just to get 5 decimal places: ``` $ time bc -l<<<'for(p=n=2;n<7^7;n+=2)p*=n*n/(n*n-1);p' 3.14159074622629555058 real 0m3.145s user 0m1.548s sys 0m0.000s $ ``` --- # bc -l, 15 bytes Alternatively, we can use Newton-Raphson to solve `sin(x)=0`, with a starting approximation of 3. Because this converges in so few iterations, we simply hard-code 2 iterations, which gives 10 decimal places: ``` x=3+s(3);x+s(x) ``` The iterative formula according to Newton-Raphson is: ``` x[n+1] = x[n] - ( sin(x[n]) / sin'(x[n]) ) ``` `sin'` === `cos` and `cos(pi)` === `-1`, so we simply approximate the `cos` term to get: ``` x[n+1] = x[n] + sin(x[n]) ``` Output: ``` $ bc -l<<<'x=3+s(3);x+s(x)' 3.14159265357219555873 $ ``` [Answer] ## Perl - 35 bytes ``` $\=$\/(2*$_-1)*$_+2for-46..-1;print ``` Produces full floating point precision. A derivation of the formula used can be seen [elsewhere](https://codegolf.stackexchange.com/a/18988). Sample usage: ``` $ perl pi.pl 3.14159265358979 ``` --- **Arbitrary Precision Version** ``` use bignum a,99;$\=$\/(2*$_-1)*$_+2for-329..-1;print ``` Extend as needed. The length of the iteration (e.g. `-329..-1`) should be adjusted to be approximately *log2(10)* ≈ *3.322* times the number of digits. ``` 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211707 ``` Or, using `bigint` instead: ``` use bigint;$\=$\/(2*$_-1)*$_+2e99for-329..-1;print ``` This runs noticably faster, but doesn't include a decimal point. ``` 3141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067 ``` [Answer] # python - ~~47~~ 45 pi is actually being calculated without trig functions or constants. ``` a=4 for i in range(9**6):a-=(-1)**i*4/(2*i+3) ``` result: ``` >>> a 3.1415907719167966 ``` [Answer] # C, 99 Directly computes area / r^2 of a circle. ``` double p(n,x,y,r){r=10000;for(n=x=0;x<r;++x)for(y=1;y<r;++y)n+=x*x+y*y<=r*r;return(double)n*4/r/r;} ``` This function will calculate pi by counting the number of pixels in a circle of radius `r` then dividing by `r*r` (actually it just calculates one quadrant). With `r` as 10000, it is accurate to 5 decimal places (3.1415904800). The parameters to the function are ignored, I just declared them there to save space. [Answer] # Javascript, 43 36 ``` x=0;for(i=1;i<1e6;i++){x+=1/i/i};Math.sqrt(6*x) ``` `x` becomes `zeta(2)=pi^2/6` so `sqrt(6*x)=pi`. (47 characters) After using the distributive property and deleting the curly brackets from the `for` loop you get: ``` x=0;for(i=1;i<1e6;i++)x+=6/i/i;Math.sqrt(x) ``` (43 characters) It returns: ``` 3.14159169865946 ``` Edit: I found an even shorter way using the Wallis product: ``` x=i=2;for(;i<1e6;i+=2)x*=i*i/(i*i-1) ``` (36 characters) It returns: ``` 3.141591082792245 ``` [Answer] ## Python, Riemann zeta (~~58~~ 41 char) ``` (6*sum(n**-2for n in range(1,9**9)))**0.5 ``` Or spare two characters, but use scipy ``` import scipy.special as s (6*s.zeta(2,1))**0.5 ``` **Edit**: Saved 16 (!) characters thanks to [amcgregor](https://codegolf.stackexchange.com/questions/22009/pi-calculation-code-golf/22259?noredirect=1#comment448396_22259) [Answer] ## Javascript: 99 characters Using the formula given by Simon Plouffe in 1996, this works with 6 digits of precision after the decimal point: ``` function f(k){return k<2?1:f(k-1)*k}for(y=-3,n=1;n<91;n++)y+=n*(2<<(n-1))*f(n)*f(n)/f(2*n);alert(y) ``` This longer variant (130 characters) has a better precision, 15 digits after the decimal point: ``` function e(x){return x<1?1:2*e(x-1)}function f(k){return k<2?1:f(k-1)*k}for(y=-3,n=1;n<91;n++)y+=n*e(n)*f(n)*f(n)/f(2*n);alert(y) ``` I made this based in my [two](https://codegolf.stackexchange.com/a/18883/3755) [answers](https://codegolf.stackexchange.com/a/18880/3755) to [this question](https://codegolf.stackexchange.com/questions/18865/stupid-restrictions-and-deser). [Answer] ### Ruby, ~~54~~ ~~50~~ 49 ``` p (0..9**6).map{|e|(-1.0)**e/(2*e+1)*4}.reduce :+ ``` [Online Version](http://ideone.com/eiqini) for testing. Another version without creating an array (50 chars): ``` x=0;(0..9**6).each{|e|x+=(-1.0)**e/(2*e+1)*4}; p x ``` [Online Version](http://ideone.com/h0gZ7m) for testing. [Answer] ## TI CAS, 35 ``` lim(x*(1/(tan((180-360/x)/2))),x,∞) ``` [Answer] **C# 192** ``` class P{static void Main(){var s=(new System.Net.WebClient()).DownloadString("http://www.ctan.org/pkg/tex");System.Console.WriteLine(s.Substring(s.IndexOf("Ver&shy;sion")+21).Split(' ')[0]);}} ``` Outputs: ``` 3.14159265 ``` No math involved. Just looks up the [current version of TeX](http://www.ctan.org/pkg/tex) and does some primitive parsing of the resulting html. Eventually it will become π according to [Wikipedia](http://en.wikipedia.org/wiki/Software_versioning). [Answer] ## Python 3 Monte Carlo (103 char) ``` from random import random as r sum(1 for x,y in ((r(),r()) for i in range(2**99)) if x**2+y**2<1)/2**97 ``` [Answer] ## Game Maker Language, 34 Assumes all uninitialized variables as 0. This is default in some versions of Game Maker. ``` for(i=1;i<1e8;i++)x+=6/i/i;sqrt(x) ``` Result: ``` 3.14159169865946 ``` [Answer] **Java - ~~83~~ 55** Shorter version thanks to Navin. ``` class P{static{System.out.print(Math.toRadians(180));}} ``` Old version: ``` class P{public static void main(String[]a){System.out.print(Math.toRadians(180));}} ``` [Answer] ## **R**: 33 characters ``` sqrt(8*sum(1/seq(1,1000001,2)^2)) [1] 3.141592 ``` Hopefully this follows the rules. [Answer] # Ruby, 82 ``` q=1.0 i=0 (0.0..72).step(8){|k|i+=1/q*(4/(k+1)-2/(k+4)-1/(k+5)-1/(k+6)) q*=16} p i ``` Uses some formula I don't really understand and just copied down. :P Output: `3.1415926535897913` [Answer] # Ruby, 12 ``` p 1.570796*2 ``` I *am* technically "calculating" ~~pi~~ an approximation of pi. [Answer] ## JavaScript - 19 bytes ``` Math.pow(29809,1/9) ``` Calculates the *9*th root of *29809*. ``` 3.1415914903890925 ``` [Answer] ## R A few years back I was taking a math course and the instructor asked the class how we might compute pi from scratch. A guy at the back of the class suggested drawing a circle of diameter 1 and then laying a piece of string around it. I couldn't figure out how to do that in R. I decided the second most primitive approach would be to approximate the circle with a regular polygons. A 4096-gon gets us 5 digits. The polygons are approximated with a simple binary search using only the midpoint and distance formulae (i.e. no trigonometric functions are used). ``` a <- c(0,1); b <- c(0,0); c <-c(1,0) eps <- 0.000000001 mid <- function(a,b) { c(mean(c(a[1],b[1])), mean(c(a[2],b[2])))} dist <- function(a,b) { sqrt((a[1]-b[1])^2 + (a[2]-b[2])^2)} for (i in 1:10) { ab1 <- mid(a,b) ab2 <- mid(b, ab1) bc1 <- mid(b,c) bc2 <- mid(b, bc1) repeat { newab <- mid(ab1,ab2) newbc <- mid(bc1, bc2) corner <- dist(newab,newbc) side <- dist(a,b) - 2*dist(newab,b) dif <- side - corner if (abs(dif) < eps) { a <- c(0,newab[2]+dist(newab,newbc)) b <- newab c <- newbc break } if (dif > 0){ab2 <- newab;bc2 <- newbc} if (dif < 0){ab1 <- newab;bc1 <- newbc} } } print((2^(i+2))*dist(newab,newbc)) ``` ]
[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/150870/edit). Closed 6 years ago. [Improve this question](/posts/150870/edit) # **Challenge:** Your task is to use any language to output that language's name times the number of character's in its name. * Use the common name or acronym of the language. * If there are multiple versions of a language, you need not include the version number. * The capitalization matters. **Examples:** ``` PHP -> PHPPHPPHP Java -> JavaJavaJavaJava C++ -> C++C++C++ Python 3 -> PythonPythonPythonPythonPythonPython JavaScript -> JavaScriptJavaScriptJavaScriptJavaScriptJavaScriptJavaScriptJavaScriptJavaScriptJavaScriptJavaScript ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 2 bytes ``` iV ``` [Try it online!](https://tio.run/##K/v/PzPs/38A "V – Try It Online") Citing *Arnauld*, with Levenshtein distance of 1: > > I now have 15 seconds of experience in V programming. So, this may actually be golfable. > > > [Answer] # [Haskell](https://www.haskell.org/), 16 bytes ``` h>>h h="Haskell" ``` [Try it online!](https://tio.run/##y0gszk7NyflfbBvzP8POLoMrw1bJAyKm9D83MTNPwVahoLQkuKRIofj/v@S0nMT04v@6yQUFAA "Haskell – Try It Online") Applied on two lists, [`(>>)`](http://hackage.haskell.org/package/base-4.10.1.0/docs/Prelude.html#v:-62--62-) concatenates the second list with itself as often as the first list has elements. --- ### Point-free (19 bytes) ``` id=<<(>>)$"Haskell" ``` [Try it online!](https://tio.run/##y0gszk7NyflfbBvzPzPF1sZGw85OU0XJAyKs9D83MTNPwVahoLQkuKRIofj/v@S0nMT04v@6yQUFAA "Haskell – Try It Online") `(id=<<)` is the same as [`join`](http://hackage.haskell.org/package/base-4.10.1.0/docs/Control-Monad.html#v:join), but without the need for `import Control.Monad`. [Answer] # [J](http://jsoftware.com/), 7 bytes I now have 15 seconds of experience in J programming. So, this may actually be golfable(1). ``` echo'J' ``` [Try it online!](https://tio.run/##y/r/PzU5I1/dS/3/fwA "J – Try It Online") *(1) Edit: And of course it was. Thanks to @ConorO'Brien for saving 2 bytes! Using a verb:* ## 5 bytes ``` 'J'"_ ``` [Answer] # [4](https://github.com/urielieli/py-four), 11 bytes ``` 3.600525004 ``` Explanation: ``` 3. Required prefix for all 4 programs. 6 Set 00 The cell at index 0 52 To 52 (ASCII value for '4'). 5 Print 00 The cell at index 0. 4 Required suffix for all 4 programs. ``` [Try it online!](https://tio.run/##M/n/31jPzMDA1MjUwMDk/38A "4 – Try It Online") [Answer] # [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, 64 bytes ``` f={s="%1%1%1%1";format[s+"%1",format[s,"Operation Flashpoint"]]} ``` Since there is no official name for the scripting language, I'm using `Operation Flashpoint` as the name of the language. **Call with:** ``` hint call f ``` **Output:** [![](https://i.stack.imgur.com/FrRt3.jpg)](https://i.stack.imgur.com/FrRt3.jpg) [Answer] # [R](https://www.r-project.org/), 8 bytes ``` cat("R") ``` [Try it online!](https://tio.run/##K/r/PzmxREMpSEnz/38A "R – Try It Online") [Answer] # [M](https://github.com/DennisMitchell/m), 2 bytes ``` ”M ``` Single-letter languages have a clear advantage. [Try it online!](https://tio.run/##y/3//1HDXN///wE "M – Try It Online") [Answer] ## [Retina](https://github.com/m-ender/retina), 12 bytes ``` Retina . $_ ``` [Try it online!](https://tio.run/##K0otycxL/P@fKwjM4NLjUon//x8A "Retina – Try It Online") ### Explanation ``` Retina ``` Initialise the string to `Retina`. ``` . $_ ``` Replace each character with the full string. [Answer] # [///](https://esolangs.org/wiki////), 17 bytes ``` /i/\\\//iiiiiiiii ``` [Try it online!](https://tio.run/##K85JLM5ILf7/Xz9TPyYmRl8/Ewb@/wcA "/// – Try It Online") (this prints `/////////`) --- Naive solution is (only) 1 byte longer. ``` \/\/\/\/\/\/\/\/\/ ``` Trying to remove the duplicated `i`s actually increases byte count. ``` /#/iii//i/\\\//### ``` [Answer] # [C](https://gcc.gnu.org/), 12 bytes ``` f(x){x="C";} ``` [Try it online! (GCC)](https://tio.run/##S9ZNT07@/z9No0KzusJWyVnJuva/cmZeck5pSqqCTXFJSma@XoYdV2ZeiUJuYmaehqZCNRdnQRGQn6aRpqGpac3FWZRaUlqUp2BgzVX7HwA "C (gcc) – Try It Online") Saved 3 bytes with help from [user202729](https://codegolf.stackexchange.com/users/69850/user202729). C has been chosen strategically, but this is pretty much GCC-specific. [Answer] # [Verbosity](https://github.com/cairdcoinheringaahing/Verbosity), ~~458~~ 454 bytes ``` Include<Integer> Include<MetaFunctions> Include<Output> Include<String> Integer:DefineVariable<o; 1> Output:DefineVariable<P; 0> String:DefineVariable<s; "VerbosityVerbosityVerbosityVerbosityVerbosityVerbosityVerbosityVerbosityVerbosity"> String:DefineVariable<q; String:RemoveCharactersFromStart<s; o>> String:DefineVariable<r; String:TakeFirstCharacters<q; o>> Output:DisplayAsText<P; r> DefineMain<> [ MetaFunctions:ExecuteScript<MetaFunctions@FILE> ] ``` [Try it online!](https://tio.run/##rZHBbsIwDIbveYqIJxhXWkWgjUqVhphWxGXawWSGWZSkcxwET1@WdV0FErfdbP/6P1u/j8gbH0jObVs6W8cPzEsnuEM2qh8sUKCIzgp5F4bxMkoTZegrYXK71P/4J0@4JYdrYIJNjbnP9NioznSrvWT6wagOcKuFTI/W/ZX/VYzubfvK9K/wigd/xMdPYLCCHAr2h0qAJV3kzT0A/wFWsMeCOMjASPhk7VOg0NRwnoUVniSF8B16h1sAudzoN3WV/WR@QhsFK8vUyPVfpkX5PDfqvW0v "Verbosity – Try It Online") Saved 4 bytes thanks to NieDzejkob! You know your language is verbose when it's shorter to create an 81 character long string that it is to multiply a 9 character long string by 9. [Answer] # [Chef](http://search.cpan.org/~smueller/Acme-Chef/), 268 bytes ``` C. Ingredients. 102 l f 101 l e 104 l h 67 l c 4 g i Method. Put f into the mixing bowl. Put e into the mixing bowl. Put h into the mixing bowl. Put c into the mixing bowl. V the i. Pour contents of the mixing bowl into the baking dish. V the i until ved. Serves 1. ``` [Try it online!](https://tio.run/##fY9BCsIwEEX3c4p/gmCl6AFcuRAEwb1NJs1gTaBNq7ePUwUFwa4e/Pc/zNjAvpSdIdrHtmcnHPNgqFqt0cErKyUra2WgzVZhqUYLITpwDskZOo4ZHhJzQg6MmzwktmjSvXs7XnBhwdk/7vyKREtp7GFTzPPVSP63@t03l@scOhnCZ48xZukwsb5AJ@4nHlCZUp4 "Chef – Try It Online") ### More idiomatic (565 bytes): ``` PPCG Holiday Punch. Ingredients. 408 ml apple cider 404 ml ginger beer 416 ml champagne 67 ml unsweetened cranberry juice 4 pinches mixed spice Method. Put apple cider into the mixing bowl. Divide mixed spice into the mixing bowl. Put ginger beer into the mixing bowl. Divide mixed spice into the mixing bowl. Put champagne into the mixing bowl. Divide mixed spice into the mixing bowl. Put unsweetened cranberry juice into the mixing bowl. Sift the mixed spice. Pour contents of the mixing bowl into the baking dish. Sift the mixed spice until sifted. Serves 5. ``` [Try it online!](https://tio.run/##rZFNTsQwDEb3OYVPUIFUBvYgAQukSnOCNHEbQ@pE@ZlhTl@cxUCFGFazzLPzPic2Dqd1HYbHZ3gJnqw@wVDZuE6pV54TWkIuuVP9zQMsHnSMHsGQxSSob2gmnjHBiA3d7hoyTi9Rz4xqd9/OlfMRsSCjBZM0j5jSCd4rGVQ9RJI8zLDQp9RzbFS9YXHBdmqoZRsKxCVAcdi6JRjGcPSdeqKDVLeGC41Ntxn4Grrvx15D9s9PXbi1p6mc6TlAXKEmMIFL2x6E6fe9H9moPxq0lN3fMpmpkIcsJZSFqD2mg2zrrlvXLw "Chef – Try It Online") [Answer] # [ArnoldC](https://lhartikk.github.io/ArnoldC/), 107 bytes ``` IT'S SHOWTIME TALK TO THE HAND "ArnoldCArnoldCArnoldCArnoldCArnoldCArnoldCArnoldC" YOU HAVE BEEN TERMINATED ``` [Try it online!](https://tio.run/##SyzKy89JSf7/3zNEPVgh2MM/PMTT15UrxNHHWyHEXyHEw1XBw9HPRUHJEazQmXhKiSvSPxSoOcxVwcnV1U8hxDXI19PPMcTV5f9/AA "ArnoldC – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 17 bytes ``` print("Python"*6) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQykAzFfSMtP8/x8A "Python 3 – Try It Online") Of course, Python 2 is 2 bytes shorter with ``` print"Python"*6 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EKQDMVdIy@/8fAA "Python 2 – Try It Online") But I prefer Python 3 [Answer] # [Whispers](https://github.com/cairdcoinheringaahing/Whispers), 36 bytes ``` > "Whispers" > 8 >> 1×2 >> Output 3 ``` [Try it online!](https://tio.run/##K8/ILC5ILSr@/99OQSkcylHislOw4LKzUzA8PN0IRPuXlhSUligY//8PAA "Whispers – Try It Online") Trivial question, trivial answers. [Answer] # [,,,](https://github.com/totallyhuman/commata), 6 bytes ``` ',9i× ``` [Try it online!](https://tio.run/##S87PzU0sSfz/X13HMvPw9P//AQ ",,, – Try It Online") Hehe... [Answer] # [7](https://esolangs.org/wiki/7), 3 bytes ``` 31317403 ``` [Try it online!](https://tio.run/##M///39jQ2NDcxMD4/38A "7 – Try It Online") Format similar to Hello World program, except output mode is `3` (Byte-per-three-commands). The three commands `131` encodes value `131` base 6 = `37` base 16 = character 7. Then `3` prints the character. [Answer] # [Starry](https://esolangs.org/wiki/Starry), 146 bytes ``` + +*` + + * + * +* . + + * + + * + . + * + + +* + * + * . . . . + * +' ``` [Try it online!](https://tio.run/##Ky5JLCqq/P9fAQq0FbS1EpA4CgpaEAIqoqWgp4AGEKoQIiCuHgoPWTmKkWB5PShEaFD//x8A "Starry – Try It Online") It looks prettier with decoration, though (180 bytes): ``` + +*` + + /| * + * + * .| \__ + \__/+ * +__ + * + . / \ + * + ======== + +* + * \__/ + * . . . . + * +' ``` [Try it online!](https://tio.run/##TY5LCsAwCET3nmJ2hQjJCXqTQNorpN0UcnerYVI6guLv6XWfvT9moBSajpWIZygDyYM7TkhCHqit4S@JXS@WOarsCqFByChAJXciQztFgq5bgfq4fpFGnv@gm9kL "Starry – Try It Online") [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~23 19 15 13~~ 12 bytes ``` "><>" |o<.0l ``` [Try it online!](https://tio.run/##S8sszvj/X8nOxk5JoSbfRs8g5/9/AA "><> – Try It Online") [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) saved 4 bytes. [Not a tree](https://codegolf.stackexchange.com/users/66104/not-a-tree) saved another 3. [Teal pelican](https://codegolf.stackexchange.com/users/62009/teal-pelican) managed to save 1 more byte. Thanks to all who have helped golfing! Citing Arnauld, with slight modifications: *I now have 15 seconds of experience in ><> programming. So, this may actually be golfable*. [Answer] # [Commentator](https://github.com/cairdcoinheringaahing/Commentator), 316 bytes ``` {- {- -}! {-{- e#-}//{-#-}-}! {- ;{- {- -}!! -}////{-#{-#-} {- -}!-}//-}//e# e#-}// -}//-}//{-e# e#-}-}//e# e#-}//-}//-}//-}//e# e#{-e# e#{-e# e#{-e# e#-}-}-}-}-} ;{-/*{-/*{-/*{-/*{-/*{-/*{-/*{-/*{-/*{-/*{-/*-}-}-}-}-}-}-}-}-}-}-} ``` [Try it online!](https://tio.run/##jU4xDoAwCNz7ijbdTAgP8DXGMKqJ6UZ8ewXaWHQScqVw3LXrsW20l6UcZ61xBIMrcCW9SkMZLkQGKTrsWzGGmSEMhXBJT0Rbtn3nKrRyCsrSN9dOtTmDMd8ge7jLHqWHk1E2l3d5O7XU3@P0F0Pns9Yb "Commentator – Try It Online") Not quite as long as my Verbosity answer, but getting there [Answer] ## [MSM](https://esolangs.org/wiki/MSM), 9 bytes ``` ..;;..MSM ``` Stack trace: ``` . . ; ; . . M S M -- concat . ; ; . . M MS -- concat ; ; . . MSM -- dup ; . . MSM MSM -- dup . . MSM MSM MSM -- concat . MSM MSMMSM -- concat MSMMSMMSM ``` [Answer] # D, 20 bytes ``` auto f(){return"D";} ``` [Try it online!](https://tio.run/##S/mfmVuQX1SiUFySogfEmfnW/xNLS/IV0jQ0q4tSS0qL8pRclKxr/5flZ6Yo5CZm5mloclVzKQBBeVFmSaoGUJ2mNVftfwA) [Answer] # [I](https://github.com/mlochbaum/ILanguage), 3 bytes ``` "I" ``` [Try it online!](https://tio.run/##y/z/X8lT6f9/AA "I – Try It Online") [Answer] # [Emoji](https://esolangs.org/wiki/Emoji), 33 bytes ``` 💬Emoji💬💬6💬📥👪➡ ``` Abuses the type system. A lot. May not work on other interpreters than the Python one. It probably won't. [Try it online!](https://tio.run/##S83Nz8r8///D/ElrXEFMEAOEzSCMyUs/zJ@46tG8hf//AwA "Emoji – Try It Online") [Answer] # [Aceto](https://github.com/aceto/aceto), 16 bytes ``` o"pp tkpp ecp "A ``` [Try it online!](https://tio.run/##S0xOLcn//z9fqaCAqyQbSKQmF3ApOf7/DwA "Aceto – Try It Online") [Answer] # [Funky](https://github.com/TehFlaminTaco/Funky), 16 bytes ``` print("Funky"*5) ``` [Try it online!](https://tio.run/##SyvNy678/7@gKDOvREPJDcRT0jLV/P8fAA "Funky – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` •äƵí•h6×R ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcOiw0uObT28FsjIMDs8Pej/fwA "05AB1E – Try It Online") --- 0xE1BA50, encoded in base 255, decoded into hexadecimal, repeated 6 times, reversed. [Answer] # Japt, ~~8~~ 7 bytes ``` 4ç"Japt ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=NOciSmFwdA==&input=) [Answer] # [K](https://github.com/kevinlawler/kona), 9 bytes ``` \echo "K" ``` [Try it online!](https://tio.run/##y9bNzs9L/P8/JjU5I19ByVvp/38A "K (Kona) – Try It Online") [Answer] # [uBASIC](https://github.com/EtchedPixels/ubasic), 27 bytes ``` 1FORI=1TO6:?"uBASIC";:NEXTI ``` This answer is pretty small, thanks to uBASIC's tokenizer being powered with a solution of magic in unicorn blood. [Try it online!](https://tio.run/##K01KLM5M/v/f0M0/yNPWMMTfzMpeqdTJMdjTWcnays81IsTz/38A "uBASIC – Try It Online") ]
[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/139824/edit). Closed 3 years ago. [Improve this question](/posts/139824/edit) Given an integer `n` as input, return a list containing `n`, repeated `n` times. For example, the program would take `5` and turn it into `[5,5,5,5,5]`. The elements need to be integers, not strings. No built-in functions that accomplish the task are allowed. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so standard rules apply. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 byte ``` x ``` [Try it online!](https://tio.run/##y0rNyan8/7/i////pgA "Jelly – Try It Online") Note that this is **not** the “repeat `n` `n` times” built-in — its function is more general than that. For example `4,5,6x1,2,3` equals `[4, 5, 5, 6, 6, 6]`. Given only one argument, Jelly just happens to use it as both the left and right argument for the supplied link, but this functionality is not *inherent* to `x`. If this doesn’t count, there are various fun 2-byte alternatives: ``` x` ṁ` Ra Rị R» a€ oR oḶ oṬ oẊ Ḷị Ḷ» Ṭị Ṭ» Ẋị Ẋ» ị€ ṛ€ ȧ€ »€ ``` etc. [Answer] # [Python 3](https://docs.python.org/3/), 14 bytes ``` lambda k:[k]*k ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHbKjo7Viv7f1p@kUKmQmaeQlFiXnqqhoGOoaGmFZdCQVFmXolGpo66rp26TppGpqbmfwA "Python 3 – Try It Online") [Answer] # [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, ~~50~~ 46 bytes ``` f={a=[];t=_this;while{count a<t}do{a=a+[t]};a} ``` **Call with:** ``` hint format["%1", 5 call f] ``` **Output:** [![](https://i.stack.imgur.com/oyafl.jpg)](https://i.stack.imgur.com/oyafl.jpg) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 2 bytes Five equally short solutions. Last two are courtesy of [Zacharý](https://codegolf.stackexchange.com/users/55550/zachar%c3%bd). --- ``` ⍴⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v@JR24RHvVse9a4AshVMAQ "APL (Dyalog Unicode) – Try It Online") `⍴` cyclically **r**eshape `⍨` self --- ``` /⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v@JR2wT9R70rgCwFUwA "APL (Dyalog Unicode) – Try It Online") `/` replicate `⍨` self --- ``` \⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v@JR24SYR70rgCwFUwA "APL (Dyalog Unicode) – Try It Online") `\` expand `⍨` self --- ``` ⌿⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v@JR24RHPfsf9a4AshVMAQ "APL (Dyalog Unicode) – Try It Online") `⌿` replicate along first (and only) axis `⍨` self --- ``` ⍀⍨ ``` `⍀` expand along first (and only) axis `⍨` self [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v@JR24RHvQ2PelcA2QqmAA "APL (Dyalog Unicode) – Try It Online") [Answer] # Mathematica, 10 bytes ``` #~Table~#& ``` [Answer] # [Proton](https://github.com/alexander-liao/proton), 8 bytes ``` n=>[n]*n ``` [Try it online!](https://tio.run/##KyjKL8nP@59m@z/P1i46L1Yr739BUWZeiUaahqmm5n8A "Proton – Try It Online") [Answer] # Octave, 12 bytes ``` @(n)~(1:n)+n ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQSNPs07D0CpPUzvvf2JesYap5n8A "Octave – Try It Online") [Answer] # JavaScript (ES6), 19 bytes ``` n=>Array(n).fill(n) ``` --- ## Try it ``` o.innerText=(f= n=>Array(n).fill(n) )(i.value=8);oninput=_=>o.innerText=f(+i.value) ``` ``` <input id=i type=number><pre id=o> ``` [Answer] # [Pyth](https://pyth.readthedocs.io), 2 bytes ``` *] ``` **[Test suite](http://pyth.herokuapp.com/?code=%2a%5D&input=5&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5&debug=0).** --- ``` *]QQ - Full program with implicit input ] - Turn the input into a list. * - Repeat it a number of times equal to the input. ``` [Answer] # [Haskell](https://www.haskell.org/), 13 bytes ``` f n=n<$[1..n] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzbPRiXaUE8vL/Z/bmJmnoKtQkFRZl6JgopCmoLpfwA "Haskell – Try It Online") Usage: `f 5` yields `[5,5,5,5,5]`. For `n=5`, `[1..n]` yields the list `[1,2,3,4,5]`. `n<$` replaces each element of this list with `n`. [Answer] # [R](https://www.r-project.org/), 18 bytes ``` array(n<-scan(),n) ``` [Try it online!](https://tio.run/##K/r/P7GoKLFSI89Gtzg5MU9DUydP87/pfwA "R – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` Fˆ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f7XTb//@mAA "05AB1E – Try It Online") [Answer] # [Dodos](https://github.com/DennisMitchell/dodos), 76 bytes ``` f f r 2 2 r r d f s t f d dip f s t f t dot f dot s s dip f dab ``` [Try it online!](https://tio.run/##HYlLCoBADEPXzSlyhll4H6UUXFVa718zEsjnxdOzZywYLC4smFSwokO0@TKg6vfDf4pC5rmPHWhYUz/2Pq@ZOT4 "Dodos – Try It Online") # Explanation: `f` is an alias for `dab` (tail). `s` is subtraction, as explained on the wiki: **(x, y) → (0, y−x)** when **x ≤ y**. `t` maps **(a, b, c…)** to **(b+c+…, a+b+c+…)**. `f s t` maps **(a, b, c…)** to **a**. This is our “head” function. `d` dips only the head of its argument: **(a, b, c…) → (|a−1|, b, c…)** `r` is the main repetition logic. We map **(a, b)** to **(\*r(|a−1|, b), b)**. For example, **r(4, 7)** will evaluate as ``` r(4, 7) = r(3, 7), 7 = r(2, 7), 7, 7 = r(1, 7), 7, 7, 7 = r(0, 7), 7, 7, 7, 7 → This would call r(1, 7), but (1, 7) ≥ (0, 7), so surrender! = 0, 7, 7, 7, 7, 7. ``` Finally, we define `2`, which maps **n → (n, n)**, and define `main` as `f f r 2`, computing **r(n, n)** and chopping off the first two elements. [Answer] # [Japt](https://github.com/ETHproductions/japt/), 2 bytes ``` ÆU ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=xlU=&input=OA==) --- ## Explanation Implicit input of integer `U`. Generate an array of integers from `0` to `U-1`. Fill it with `U`. Implicit output of resulting array. [Answer] # TeX, 81 bytes ``` \newcommand{\f}[1]{#1\count0=2\loop,#1\advance\count0 by1\ifnum\count0<#1\repeat} ``` ## Usage ``` \documentclass[12pt,a4paper]{article} \begin{document} \newcommand{\f}[1]{#1\count0=2\loop,#1\advance\count0 by1\ifnum\count0<#1\repeat} \f{5} \f{10} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/8xkEq.png)](https://i.stack.imgur.com/8xkEq.png) [Answer] # [Husk](https://github.com/barbuz/Husk), 2 bytes ``` ´R ``` [Try it online!](https://tio.run/##yygtzv7//9CWoP///5sCAA "Husk – Try It Online") ``` ´ -- Apply next function twice to same argument R -- given an integer n and some element, replicate the element n-times ``` --- ### Polite alternative (3 bytes) ``` ṠIR ``` [Try it online!](https://tio.run/##yygtzv7//@HOBZ5B////NwUA "Husk – Try It Online") [Answer] # Haskell (14 bytes) ``` replicate>>=id ``` Thanks to @nimi, I don't need any import anymore. Yay! It's a function that takes an integer argument; for example, the following returns `[5,5,5,5,5]`: ``` (replicate>>=id) 5 ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~50~~ 48 bytes ``` n->java.util.Arrays.stream(new int[n]).map(i->n) ``` [Try it online!](https://tio.run/##bVDBasMwDD3HX6GjTVezndMVehnssO3QY@nBS53gLpGNrXQNI9@eKWnWQTcQPCG993jS0ZzM0geLx8PH4JrgI8GRZ7olV@tNjKZLufizKFssyHnUT3PzDydRtKbRz0jbqcuFCO177QooapMSvBiH4ktk8zCRIYaTdwdoeCVZ5bDa7cHEKimRMTUrfQTpkMDBI9znDCt4GHGxYMZEybZdItto35IO7EA1yssdmvzFU9Yu0Vv5Kp3i2bSUSqmc1b3gus10PQGuQo5wnjP9vGDFNFvZePfLX0PFOUU24HJ9@9X5PxLtJ7DdDvdKNyZIt1yjGsYs0VIbESptQqg7eR4D9qIfvgE "Java (OpenJDK 8) – Try It Online") *-2 bytes thanks to @Jakob* Inspired by the comments in @OlivierGrégoire's post, and optimized a little further. Takes an integer input, creates an IntStream of `n` elements, then maps each element to `n` and returns it. [Answer] # [Perl 5](https://www.perl.org/), ~~18~~ 14 bytes -4 bytes thanks to @DomHastings ``` sub{(@_)x"@_"} ``` [Try it online!](https://tio.run/##K0gtyjH9n1upoJKmYPu/uDSpWsMhXrNCySFeqfa/NVdBUWZeiUJWfmaehpKOkg5Qla6dhqmmpo6CUkyekvV/AA "Perl 5 – Try It Online") Is `x` a builtin that does the entire task? Sort of? Not really? Rules unclear? Edit: Yeah, probably it's fine. [Answer] # J, 2 bytes ``` $~ ``` Same as the APL answer: reflexively shape the input. In other words: ``` $~ y y $ y NB. y copies of y ``` [Answer] # [Brainbash](https://github.com/ConorOBrien-Foxx/Brainbash), 39 bytes ``` >-[-[-<]>>+<]>->#[->+>+<<]>>[-<;<<.>>>] ``` [Try it online!](https://tio.run/##SypKzMxLSizO@P/fTjcaCG1i7ey0gYSunXK0rp02kA0SAYpb29jo2dnZxf7/bwoA "Brainbash – Try It Online") Prints `N` `N` times. Works by generating 32, taking input, then duplicating the input twice, then output the first for each 1 in the second. [Answer] # [C (gcc)](https://gcc.gnu.org/), 55 bytes ``` int*f(k){int*r=malloc(k*4),a=k;for(;a-->0;)r[a]=k;k=r;} ``` [Try it online!](https://tio.run/##TU7bioMwEH3vVxwChUxrwEL7sqnth4gswa1LUGNJbGFX/HZ3ksLWvOScmXOZWn3X9bJYN@4a2dIUgS9603VDLdvdkTJTtLoZvNRGqUuuyZem4lFbeD0vz8F@wXhvfj7vnr0y@tHZMGZgiGB/b4QJMSByiwK55u@cVoz2e0KyNlJs7TaILNlLW2X/MigccAWvBD4gBGnMm1Q93kLqhIst7xyoC0rWO5auz2uko9f0/hiDFNUrKyb0xjpJ0wb8UmxO@k0Oa3JckxOTeTn9AQ "C (gcc) – Try It Online") Returns a list of `k` integers. [Answer] # [Röda](https://github.com/fergusq/roda), 10 bytes ``` {[[_]*_1]} ``` [Try it online!](https://tio.run/##K8pPSfxfzcWZpmBlqxDzvzo6Oj5WK94wtvZ/LRdXbmJmngJQsqAoM69EoaC0OEPDVFOhRiFNQ5Or9j8A "Röda – Try It Online") Explanation: ``` {[[_]*_1]} { } /* Anonymous function */ _ /* The input (_1) */ [ ] /* As a list */ *_1 /* Repeated _1 times */ [ ] /* Pushed to the stream */ ``` [Answer] # [Groovy](http://groovy-lang.org/), 9 bytes ``` {[it]*it} ``` [Try it online!](https://tio.run/##Sy/Kzy@r/F9QlJlXkpOnofG/OjqzJFYrs6T2v6aGmaGm5n8A "Groovy – Try It Online") --- Perhaps the most competitive groovy answer I've done to date. [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 16 bytes ``` [->+>+<<]>[->.<] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/q/zP1rXTttO28Ym1g7I0rOJ/f9fEQA "brainfuck – Try It Online") ## The breakdown: ``` [->+>+<<] Duplicate 'n' into the next 2 cells to the right > Move to the first duplicate [->.<] Print 'n', 'n' times ``` As I'm sure you're aware, brainfuck takes input and output values as ASCII characters. So a `!` is represented as the value 33. [Answer] # Coreutils, sed, 14 bytes ``` yes $1|sed $1q ``` As a zsh function, 20 19 bytes: ``` f(){yes $1|sed $1q} ``` [Try it online!](https://tio.run/##qyrO@P8/TUOzujK1WEHFsKY4NQVIFdb@T1Mw@w8A) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~4~~ 3 bytes ``` tY" ``` [Try it online!](https://tio.run/##y00syfn/vyRS6f9/UwA "MATL – Try It Online") **Explanation:** ``` t % duplicate elements Y" % replicate elements of array % (implicit) convert to string and display ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~58~~ 56 bytes ``` n->{int a[]=new int[n],i=n;for(;i-->0;)a[i]=n;return a;} ``` [Try it online!](https://tio.run/##RU9Na8MwDL33V@gY08WUXV0HdinssFOPIQctTYqyVA623BFKfntmN4UJhD7e4@lpwDuWbup4uPysU/weqYV2xBDgC4nhsQN4bYOgpHJ3dIFbwoqzeOJr3QD6a1CZCTAkOR2FRt1HboUc60@W06s/EkvdVNDblcvqkSbAurHc/UJGuHkjy6Z3vjBUltXBKKwp4cZ3Ej0DmmWFZ5jntczMIgQWDiaVo4X33Oz3CjZDAOc5SHfTLoqekmEZufh3@eE9zkGL254peo3TNM4FKaW2G8su57L@AQ "Java (OpenJDK 8) – Try It Online") -2 bytes thanks to @KevinCruijssen [Answer] # [cQuents](https://github.com/stestoltz/cQuents) v0, 3 bytes ``` ::n ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/38oq7/9/UwA "cQuents – Try It Online") ## Explanation ``` :: Mode: sequence 2. Given input n, output the sequence n times n Each item in the sequence is n ``` [Answer] # [Swift 3](https://www.swift.org), 29 bytes ``` {n in(0..<n).map{_ in n}} ``` **[Try it here!](http://swift.sandbox.bluemix.net/#/repl/599ad86ca5f97c4ee18da7ff)** # [Swift 3](https://www.swift.org), 30 bytes ``` {Array(repeating:$0,count:$0)} ``` **[Try it here!](http://swift.sandbox.bluemix.net/#/repl/599abf047a55b2295b134530)** ]
[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/141213/edit). Closed 6 years ago. [Improve this question](/posts/141213/edit) Does your language have a maximum recursion depth (MRD)? Let's say your language has **MRD=500** Write a code that finds the recursion depth and outputs the **exact value** For the case above your program (or function) should output **500** **Code-Golf** Shortest answer wins! [Answer] # Mathematica, 15 bytes ``` $RecursionLimit ``` ¯\\_(ツ)\_/¯ [Try it online!](https://tio.run/##y00sychMLv6fZvtfJSg1ubSoODM/zyczN7Pkf0BRZl6JgkMa1///AA "Mathics – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 40 bytes ``` def f(x=2): try:f(x+1) except:print(x) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNo8LWSNOKS6GkqNIKyNE21ORSSK1ITi0osSooyswr0ajQ/J@mofkfAA "Python 3 – Try It Online") Without just reading it from the builtin. We start at 2 instead of 1 because the except clause is run one level before it errors. This is a byte shorter in python 2, of course. [Answer] # [JavaScript (Babel)](https://babeljs.io/), ~~35~~ ~~33~~ 29 bytes ``` f=_=>do{try{-~f()}catch(e){}} ``` * 2 bytes saved thanks to Neil. [Try it here](https://babeljs.io/repl/#?babili=false&browsers=&build=&builtIns=false&code_lz=MYewdgziA2CmB0w4EMBOAKAlAbjgFwCgAzAXgH0SA-AExAG89UBPOgWgD8isBfYZPYAAt0sTHW7cCoSDATQQAc3RdMmIA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=true&fileSize=false&lineWrap=false&presets=es2015%2Cstage-0&prettier=false&targets=&version=6.26.0&envVersion=), or use the Snippet below to test it with `eval` instead of `do`. ``` console.log((f=_=>eval(`try{-~f()}catch(e){}`))()) ``` --- ## [Japt](https://github.com/ETHproductions/japt/) port, 24 bytes It's not really worth posting this as a separate solution as it's, essentially, identical. ``` Ox`try\{-~rp()}¯t®(e)\{} ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=T3hgdHJ5XHstfnJwKCl9r3SuKGUpXHt9&input=) --- ## Explanation JavaScript itself doesn't have a recursion limit per se, rather the limit is imposed by the interpreter (i.e., the browser) - good thing we define languages by their interpreter 'round here! Among other factors, the limit can vary by browser and available memory, which is impacted by the operations being performed. The following Snippet illustrates that last point, using the 5 different versions of this solution I went through. As you can see from the last 2 tests, in Chrome, at least, even the order of operations can make a difference. ``` console.log((f=(i=0)=>eval(`try{f(i+1)}catch(e){i}`))()) console.log((f=i=>eval(`try{f(-~i)}catch(e){i}`))()) console.log((f=(i=0)=>eval(`try{f(++i)}catch(e){i}`))()) console.log((f=_=>eval(`try{-~f()}catch(e){}`))()) console.log((f=_=>eval(`try{f()+1}catch(e){0}`))()) console.log((f=_=>eval(`try{1+f()}catch(e){0}`))()) ``` Given that, we therefore don't have the convenience of a constant or method to work with. Instead, we're going to create a function that calls itself continuously before, eventually, crapping out. In it's simplest form that is: ``` f=_=>f() ``` But that's not much use to us for this challenge as it only throws an overflow error with no indication of how many times `f` called itself. We can avoid the error by *`try`ing* to call `f` continuously and `catch`ing when it fails: ``` f=_=>{try{f()}catch(e){}} ``` No error, but still no return value of how many times the function managed to call itself before failing, because the `catch` isn't actually doing anything. Let's try evaluating the `try / catch` statement: ``` f=_=>eval(`try{f()}catch(e){}`) ``` Now we've got a value being returned (and, because this is code golf, saved ourselves a few bytes over using an actual `return`). The value being returned, though, is `undefined`, again because the `catch` isn't doing anything. Luckily for us `-~undefined==1` and `-~n==n+1` so, by popping a `-~` in front of the call to `f`, we've essentially got `-~-~ ... -~-~undefined`, with another `-~` prepended with each call, giving us the number of times `f` was called. ``` f=_=>eval(`try{-~f()}catch(e){}`) ``` [Answer] # Mathematica (no built-in), 20 bytes ``` #0[#+1];&@1 %[[1,1]] ``` Omitting the `;` will calculate `1+$IterationLimit` (probably because Mathematica tail-optimize the function). Alternatively `0 //. x_ -> x + 1` calculate `ReplaceRepeated`'s default `MaxIteration`, that is, `65536` (which is larger than both value above). (This is a code snippet which evaluates to the result. However the other Mathematica solution is also) [Answer] # J, 8 bytes ``` 1+$: ::] ``` [Try it online!](https://tio.run/##y/r/P03BVk/BUFvFSsHKKpaLKzU5I18hTcHg/38A) So, I don't actually know how to execute a verb without any input and some brief searching (as well as personal intuition) makes it seem like that isn't possible. If it is, please let me know how to do it and I'll either delete or update my answer. It doesn't really make sense for a verb to be given no input, though. In light of this, the function given expects `0`, the default "empty" input for integers. I can probably change it to use the empty array (`0$0`) if you think that's more befitting. Edit: the OP has allowed the function to take 0. # Explanation ``` 1+$: ::] ::] Assign adverse: if an error occurs, call ] (the identify function) 1+ Add one to $: Recursive call to self ``` This calls itself recursively, adding 1 to the input (0 expected) until it hits a stack error. When it errors, it calls the adverse (`]`-right identity) on the input, which is just 0. By the way, [the space is necessary](http://code.jsoftware.com/wiki/Vocabulary/coco). [Answer] # [Python 3](https://docs.python.org/3/), ~~41~~ 32 bytes ``` import sys sys.getrecursionlimit ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKG4spgrzRZI6qWnlhSlJpcWFWfm5@Vk5maW/C8oyswr0UjT0NT8DwA) Saved 9 bytes thanks to @FryAmTheEggman! ### 34 bytes ``` from sys import* getrecursionlimit ``` ### 35 bytes ``` __import__('sys').getrecursionlimit ``` The last 2 are thanks to @totallyhuman [Answer] # Java 8, ~~131~~ ~~51~~ ~~48~~ ~~47~~ 43 bytes ``` int d;int c(){try{c();}finally{return++d;}} ``` -80 bytes thanks to *@Nevay*. I tried a method instead of program as well, but made a mistake so ended up with a full program.. Now it's a method. -3 bytes thanks to *@Neil* by making use of `finally` instead of `catch(Error e)`. -5 byte thanks to *@Nevay* again. **Explanation:** [Try it here.](https://tio.run/##HY2xDsMgEEP3fMWNoKj5Ab6hU8aqwxVoRUouERypIsS302s92IOt5wUPvGy7p8W9u42YM1wxUO2BGJz5uVW6cjqrpGnPQBjjWZPnkmgcnWmtA@zlEYOFzMgSxxYcrIJRM6dAr9sddR1ANJ@Z/TpthaddGlbkP/9DpSfhayOrNrT@BQ) ``` int d; // Depth-integer `d` on class-level (implicit 0) int c(){ // Method without parameter and integer return-type try{c();} // Recursive call finally{return++d;} // Increase depth-integer `d` and always return it, // whether a StackOverflowError occurs or not } // End of method ``` [Answer] # C (gcc, Linux x64), ~~180~~ 133 bytes *-4 bytes thanks to @scottinet* ``` c;f(){f(++c);}h(){exit(printf("%d",c));}main(){int b[512];f(sigaction(11,(int*[]){h,[17]=1<<27},sigaltstack((int*[]){b,0,2048},0)));} ``` [Try it online!](https://tio.run/##PYzBCsIwEER/RQrCxq6QBKVC2y8JOaSraYM1SpuDUPLtcXvxNsx7M3QeiUqh1oPYPNQ1iTZPnB/fkOCzhJg8VMd7hSSYvFyIDLk9DOaqtOXdGkZHKbwjKIXA6GSs2CY0qrG96jrdZNydOa3J0RP@yoAStbzcMkqxn5fyAw "C (gcc) – Try It Online") Installs a SIGSEGV (signal 11) handler with an alternate signal stack (minimum size `MINSIGSTKSZ` is 2 KB, flag `SA_ONSTACK` is 0x08000000), then calls a function without arguments and no local variables recursively until the stack overflows. It's interesting that the maximum recursion depth varies across runs, probably due to ASLR. The maximum recursion depth in C depends on a lot of factors, of course. On a typical 64-bit Linux system the default stack size is 8 MB, and the stack alignment is 16 bytes, so you get a recursion depth of about 512K for simple functions. Also note that the program above doesn't work with `-O2` because of tail call optimization. [Answer] # **Octave, 19 bytes** ``` max_recursion_depth ``` Usage: ``` octave:1> max_recursion_depth ans = 256 ``` [Answer] # [R](https://www.r-project.org/), ~~32~~ ~~26~~ 18 bytes *-8 bytes thanks to Sven Hohenstein* : `$` will do partial matching, so we can just use `exp` instead of the full `expressions`. ``` cat(options()$exp) ``` The `options` command can also be used to set the recursion depth, i.e., `options(expressions=500)` for 500. [Try it online!](https://tio.run/##K/r/PzmxRCO/oCQzP69YQ1MltaJA8/9/AA) [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~25~~ ~~22~~ 20 bytes *2 bytes removed thanks to a suggestion by Sanchises* ``` @max_recursion_depth ``` Anonymous function that outputs the value. [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en998hN7Eivig1ubSoODM/Lz4ltaAk43@ahuZ/AA) [Answer] # zsh, 24 bytes ``` f(){f $[++i];f};set -x;f ``` [Try it online!](https://tio.run/##qyrO@P8/TUOzOk1BJVpbOzPWOq3Wuji1REG3wjrt////AA "Zsh – Try It Online") (See under debug) Or 12 bytes if hardcoded values are allowed (From *GammaFunction*): ``` <<<$FUNCNEST ``` # bash, 24 bytes ``` f(){ f $[++i];};set -x;f ``` [Try it online!](https://tio.run/##S0oszvj/P01Ds1ohTUElWls7M9a61ro4tURBt8I67f9/AA "Bash – Try It Online") (See under debug) # ksh93, 27 bytes ``` f(){ f $(($1+1));};set -x;f ``` [Try it online!](https://tio.run/##yy7O@P8/TUOzWiFNQUVDQ8VQ21BT07rWuji1REG3wjrt/38A "ksh – Try It Online") (See under debug) # dash, 27 bytes ``` f(){ f $(($1+1));};set -x;f ``` [Try it online!](https://tio.run/##S0kszvj/P01Ds1ohTUFFQ0PFUNtQU9O61ro4tURBt8I67f9/AA "Dash – Try It Online") (Exceeds tio debug output, run it in your own shell) [Answer] # [Lua](https://www.lua.org), 52 bytes ``` f=load"b,e=pcall(f,(...or 3)+1)return b and e or..." ``` [Try it online!](https://tio.run/##DckxCsAgDADAub4iOCVUhNLZx8SqUAgqQd@f9taTzWYtyeDic6hpPiyCLWCMcSjcdF6kdW3tkIF7gQpD//M29e0L3dGQHNkH "Lua – Try It Online") [Answer] # q/kdb+, 16 bytes **Solution:** ``` {@[.z.s;x+1;x]}0 ``` **Example:** ``` / solution q){@[.z.s;x+1;x]}0 2000 / without apply (try/catch) q){.z.s x+1}0 'stack @ {.z.s x+1} 2001 ``` **Explanation:** Try to recurse, increase x by one each time, if error, return x. ``` {@[.z.s;x+1;x]}0 / the solution { }0 / call lambda function with 0 @[ ; ; ] / @[function;argument;catch] .z.s / call self (ie recurse) x+1 / increment x x / return x if function returns error ``` [Answer] # Excel-VBA, 26 Bytes ``` ?Application.MaxIterations ``` Not recursion depth per-se, this actually outputs the maximum number of iterations for a cell in an Excel worksheet. Given that the output pertains to a language other than the language in which this is written, perhaps this is more appropriate: # Excel + Excel-Vba, 3 + 38 = 41 Bytes ``` Function f:f=Application.MaxIterations ``` As that can be called from a cell with ``` =f( ``` For VBA with no built in: # Excel-VBA, ~~53~~ ~~44~~ 40 bytes -9 as variable no longer needs to be initialised or printed -4 as code execution no longer has to be ended to avoid multiple prints ``` Sub s:[A1]=[A1]+1:On Error Resume Next:s ``` Call with s in the immediate window, outputs to cell A1 of the worksheet *(warning takes a while to run now, add `Application.ScreenUpdating = False` first)* [Answer] # [Lua](https://www.lua.org), ~~45~~ 37 bytes ``` x=2 f=load"x=x+1;f()"pcall(f)print(x) ``` [Try it online!](https://tio.run/##yylN/P@/wtaIK802Jz8xRanCtkLb0DpNQ1OpIDkxJ0cjTbOgKDOvRKNC8/9/AA "Lua – Try It Online") I don't know which value to initialize `x` with as I don't know the number of intermediary calls there are... [Answer] # Clojure, ~~72~~ ~~55~~ 48 bytes -23 bytes by getting rid of the atom -7 bytes thanks to @madstap. Switched to using `fn` over `def` and `#()`, and `pr` over `println`. ``` ((fn f[i](try(f(inc i))(catch Error e(pr i))))0) ``` Wrote and tested on my phone. The Clojure REPL app gave me a depth of 13087. Basic solution. Recurse until a SO is thrown, incrementing a counter each recurse. When it's thrown, the value of the counter is printed. [Answer] # VBA, any type, ~~41~~ 39 bytes ``` Function A:On Error Resume Next:A=A()+1 ``` Call using `?A()` in the Immediate window, or as worksheet function. **Note:** Returns 4613 in Excel-VBA, while the answer by @Greedo returns 3666 on my system (highest should be the max). Apparently also varies between Office programs (Access-VBA returns 4622, Word-VBA 4615) Edit: Guess VBA auto-adds parantheses, so removed them. [Answer] # Pyth - 9 bytes ``` L.xyhbbyZ ``` If I can run it like the J answer above, this is 7 bytes because you can take out the last `yZ`. [Try it online here](http://pyth.herokuapp.com/?code=L.xyhbbyZ&debug=0). [Answer] # Forth, 48 bytes Loops until it hits the limit. ``` : m 1+ recurse ; : f 0 ['] m catch drop ; f . ``` [**Try it online**](https://tio.run/##S8svKsnQTU8DUf//WynkKhhqKxSlJpcWFacqWHNZKaQpGChEq8cCJZITS5IzFFKK8gsUrIHCev//AwA) [Answer] # [Tcl](http://tcl.tk/), 18 bytes ``` puts [interp r {}] ``` [Try it online!](https://tio.run/##K0nO@f@/oLSkWCE6M68ktahAoUihujb2/38A "Tcl – Try It Online") `recursionlimit` can be abbreviated to `r` # [Tcl](http://tcl.tk/), 31 bytes ``` puts [interp recursionlimit {}] ``` [Try it online!](https://tio.run/##K0nO@f@/oLSkWCE6M68ktahAoSg1ubSoODM/LyczN7NEobo29v9/AA "Tcl – Try It Online") [Answer] # [Tcl](http://tcl.tk/), 49 bytes ``` proc R {i\ 1} {if [catch {R [incr i]}] {puts $i}} ``` [Try it online!](https://tio.run/##K0nO@f@/oCg/WSFIoTozRsGwFkilKUQnJ5YkZyhUBylEZ@YlFylkxtbGKlQXlJYUK6hk1tb@D/oPAA "Tcl – Try It Online") [Answer] # Ruby, 39 bytes ``` END{p$.} $stderr=$< f=->{$.+=1;f[]} f[] ``` Suppressing the error message is a little shorter than rescuing it, since by default `rescue` doesn't catch `SystemStackError`. There's a cheesier answer if I can output in unary, representing `n` with n consecutive newline characters: # Ruby, 35 bytes ``` $stderr=$< f=->{puts;$.+=1;f[]} f[] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) :( \* ``` “¡żuẋ×HẒpƙ7"8!ƭ»ŒV ``` **[Try it online!](https://tio.run/##ASgA1/9qZWxsef//4oCcwqHFvHXhuovDl0jhupJwxpk3Ijghxq3Cu8WSVv// "Jelly – Try It Online")** ### How? \* Since Jelly as far as I am aware: (1) sets the Python recursion limit prior to setting up much of its own interpreter and parsing the code to be run; and (2) has no way of catching Python errors I'm not sure if there is a way to either reliably evaluate the recursion limit or to print it out as it is discovered other than to actually ask Python what the value was set to (I'd love to see if it can be done though!) so that's what the code here does: ``` “¡żuẋ×HẒpƙ7"8!ƭ»ŒV - Link: no arguments “¡żuẋ×HẒpƙ7"8!ƭ» - compression of "sys."+"get"+"recursion"+"limit"+"()" ŒV - evaluate as Python code ``` ]
[Question] [ # Introduction My gnome friends are writing a programming language and have asked for my help. Due to their size, the gnomes can only handle small superscript numbers instead of big numbers. However, the language they're writing the interpreter in only accepts big numbers! # Your Challenge Given an input of a superscript number (a series of characters that can be any of ⁰¹²³⁴⁵⁶⁷⁸⁹), convert it to normal ASCII numbers and print the result. This is code golf, so shortest answer wins! ## Test Cases ``` ¹ -> 1 ⁵ -> 5 ¹²³ -> 123 ⁶⁵⁵³⁵ -> 65535 ⁰¹²³ -> 123 ``` [Answer] # JavaScript, 20 bytes ``` s=>s.normalize`NFKD` ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvu/2NauWC8vvyg3MSezKjXBz83bJeF/QVFmXolGmob6oZ3qmppccO6jxq0o/EM7D206tBlNyTagKiA6tBmi@j8A) [Answer] # JavaScript (ES6), 43 bytes Edit: +1 to support `0123` -> `123` ... ``` s=>+s.replace(/./g,c=>c.charCodeAt()%92%12) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1k67WK8otSAnMTlVQ19PP10n2dYuWS85I7HIGajGsURDU9XSSNXQSPN/cn5ecX5Oql5OfrpGmobSoZ1KmppcaIKPGrdiET2089CmQ5uxKt8G1AFEhzZj1/mocQNOzRCJR41bwEYADdr@qHHHo8adQD1A1f8B "JavaScript (Node.js) – Try It Online") ### Conversion table ``` char. | code | mod 92 | mod 12 -------+------+--------+-------- '⁰' | 8304 | 24 | 0 '¹' | 185 | 1 | 1 '²' | 178 | 86 | 2 '³' | 179 | 87 | 3 '⁴' | 8308 | 28 | 4 '⁵' | 8309 | 29 | 5 '⁶' | 8310 | 30 | 6 '⁷' | 8311 | 31 | 7 '⁸' | 8312 | 32 | 8 '⁹' | 8313 | 33 | 9 ``` [Answer] # [Hexagony](https://github.com/m-ender/hexagony), side length 4, 37 bytes ``` 92},/%=\_@=..}{<.{\<.>".2//{%.1!}>'/_ ``` ## Unwrapped code: ``` 9 2 } , / % = \ _ @ = . . } { < . { \ < . > " . 2 / / { % . 1 ! } > ' / _ ``` [Try it on hexagony.net](https://hexagony.net/#lzN4Igxg9gJgpiBcICcAmAvgGgPQFIC8AOgQPoACeAdBWsADwXBH0B8BIFKWWwOFAjAEI0zAORZiIDCACWAOwAOAVwAuCEIAcCAJ0AmgM2AXAkCuBIDcCQO4EgDwJAngSSZClQFlocRAEMATgHMQaIA===) This is my first post on Code Golf, and first time using Hexagony. It's as painful as the name implies, but so satisfying to get a result! I ended up with more mirrors than I expected, but I'm pretty proud of what I achieved. Credit to the previous users who worked out the modulo trick. My hexagon would have been a lot bigger without `%92%12`! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` O%12&ƊḌ ``` [Try it online!](https://tio.run/##y0rNyan8/99f1dBI7VjXwx09////f9S47VHjViA6tBlMbzi089AmEHsLmAuU3P6occejxp0A "Jelly – Try It Online") ``` O Get ordinal values %12&Ɗ Apply x ↦ x%12&x Ḍ Digits to number ``` I found the `x%12&x` formula by computer search. If I/O were super duper lenient, I guess `%12&` would be a valid 4-byte answer. [Answer] # [R](https://www.r-project.org/), ~~45~~ ~~53~~ 51 bytes *Edit +8 bytes to comply with the updated rules (`0123` -> `123`), but then -2 bytes thanks to pajonk* ``` function(s)el(chartr("⁰¹²³⁴-⁹","0-9",s):1) ``` [Try it online!](https://tio.run/##K/pfkp@UmW77P600L7kkMz9Po1gzNUcjOSOxqKRIQ@lR44ZDOw9tOrT5UeMW3UeNO5V0lAx0LZV0ijWtDDUhWlEVPWrc@qhx26PG7Y8ad4DUa/4HAA "R – Try It Online") --- # [R](https://www.r-project.org/), ~~53~~ ~~51~~ 57 bytes / ~~[25 bytes](https://tio.run/##K/pfkp@UmW77P600L7kkMz9PI1kzWVXVzETXQksxWdfQwvR/Zl5JSH5oSZqFBlipRimQGZLvmVeiofSoccOhnYc2Hdr8qHHLo8atjxq3PWrc/qhxx6PGnUqampr/AQ) with IO as character codes~~ *Edit: -4 bytes thanks to pajonk, but then +6 bytes (again thanks to pajonk) to comply with the updated rules* ``` function(s,x=utf8ToInt(s))el(intToUtf8(x%%64-8*!x-185):1) ``` [Try it online!](https://tio.run/##K/pfkp@UmW77P600L7kkMz9Po1inwra0JM0iJN8zr0SjWFMzNUcjM68kJD8UKKhRoapqZqJroaVYoWtoYappZagJMUBD6VHjhkM7D206tPlR45ZHjVsfNW571Lj9UeOOR407lTT/AwA "R – Try It Online") Function without multi-byte character codes, but sadly the verbose `utf8ToInt` and `intToUtf8` function names make it quite long if we want to accept input directly as a string... The new rule that `⁰¹²³` should output `123` invalidates the second version with IO as character codes. It could be fixed for [+17 bytes](https://tio.run/##K/pfkp@UmW77P600L7kkMz9PI1kzNUcjM68kJD@0JM1CI1lV1cxE10JLMVnX0MJU08pQE6JDoxQoG5LvmVeiofSoccOhnYc2Hdr8qHHLo8atjxq3PWrc/qhxx6PGnUqamv8B), but it's shorter to completely change approach (below), porting [Arnauld's charcode-to-digit](https://codegolf.stackexchange.com/a/238482/95126) method. --- # [R](https://www.r-project.org/), 40 bytes with IO as character codes ``` function(c)c%%92%%12%*%10^rev(seq(!c)-1) ``` [Try it online!](https://tio.run/##K/pfkp@UmW77P600L7kkMz9PI1kzWVXV0khV1dBIVUvV0CCuKLVMozi1UEMxWVPXUBOiXqO0JM0iJN8zr0RD6VHjhkM7D206tPlR45ZHjVsfNW571Lj9UeOOR407lTQ1/wMA "R – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 2 bytes ``` IV ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9npXv92z7//9R47ZHjVuB6NBmIAEA "Charcoal – Try It Online") Explanation: ``` V Eval as a Charcoal integer literal I Cast to string Implicitly print ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~46~~ 50 bytes -1 thanks to ovs! ``` lambda x:int(x.translate('%7d 45678923'%10*999)) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUaHCKjOvRKNCr6QoMa84J7EkVUNd1TxFQUHBxNTM3MLSyFhd1dBAy9LSUlPzf1p@kUKmQmaeQrT6oZ3qOgrqjxq3gqhDOw9tOrQZIrANKAZEhzZD5R41boBKx1opFBSBLEvTyNTUVFbQtVMwNDL@DwA "Python 3.8 (pre-release) – Try It Online") Helper program to generate this: [helper](https://tio.run/##XY9NbsJADIX3nMK7GQOKQrtpkHISxCIUU1xgEnkG1C7nRqj/bHOUuUjqQWLD0tL3vffcvYdt6x6fOhmGTSvAwA6kcS9kqyk8lGWJ8xF4qMGY4rVlZ5@3YhnhDlbyik8YcQSS@RTP/aX/6D9T/ErxO8WfFH9T/EvxYoqgmt83gawfV1WlDm9gT856ClYQoa5hVmo1tMegaQsDZjlmva/FUzjlbnLHA0lOEZxncuELdmt6sydcquVD3qpSJ@w0lzqxtz@UxrwVVkLNbhj@AQ) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~83~~ \$\cdots\$ ~~60~~ 46 bytes ``` n;f(int*s){for(n=0;*s;)n+=9*n+*s++%92%12;n=n;} ``` [Try it online!](https://tio.run/##dVBJTsMwFN33FF@RImVwRZO0QGTCBrHjBrSLyHVKBbhVHImIKgvfCDF326P4IITfOA1tJSx5@m@w32f9GWN1LWjmzEXhSXeVLXJHJAPqSeoKP4k94XvS9@04tIOQikTQqkYqPKZz4biw6gGOrRYKLosAErixNmutXix6CIUGet28afWu1ccxHjW4Vp9afWn1rdX6mDFszdHjXxd5O0HWqvkLMe@aLTLbsOoEwMslZwWfGkkwIBBGwxGB07PzmEAQbm8tnS2ELIDdpbmHK2f3PDcqa1xeh@MyvsI5sgjs3yOrVWNPYdtffHXKS5QNaHu8ADl/5ovM2f3FPWkLXleh4PsNe9ftv8BoZUI3@ITuwyARzZzCPaxyrHbBj2XLHCmZY9lT6F8CrrYcC0zV8AhI0oWXScInrXXVq@oflj2kM1n3n34B "C (gcc) – Try It Online") Inputs a pointer to a `wchar_t` string of superscript numbers. Returns the normal number. Discovered the `n % 92 % 12` formula independently. [Answer] # [Raku](https://raku.org), ~~14~~ ~~10~~ ~~11~~ 8 bytes +1 and +4 to remove leading 0's. -3 bytes thanks to [Moonchild](https://codegolf.stackexchange.com/users/51682/moonchild)! ``` +~*.NFKD ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPtfu05Lz8/N2@W/NReXnkqaXnFipUJafpFCTmZeavH/Qzu5HjVu5Tq089CmQ5uBzG1AHhAd2gwSfdS4ASLxqHELWBwou/1R445HjTsB "Perl 6 – Try It Online") --- # [Raku](https://raku.org) `-p`, ~~15~~ ~~19~~ bytes -1 byte and -1 flag thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)! ``` $_=+S:g{.}=$/.EVAL ``` [Try it online!](https://tio.run/##K0gtyjH7/18l3lY72Cq9Wq/WVkVfzzXM0ef//0M7uR41buU6tPPQpkObgcxtQB4QHdoMEn3UuAEi8ahxC1gcKLv9UeOOR407/@UXlGTm5xX/1y0AAA "Perl 6 – Try It Online") Raku uses superscript digits as exponents, but single digits on their own evaluate to their numeric value. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` C:12%⋏ṅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJDOjEyJeKLj+G5hSIsIiIsIifigbbigbXigbXCs+KBtSciXQ==) Port of Lynn's answer thanks to steffan. [Answer] # [Python 3](https://docs.python.org/3/), 53 bytes ``` from unicodedata import* lambda s:normalize("NFKC",s) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehNC8zOT8lNSWxJFEhM7cgv6hEiysnMTcpJVGh2Covvyg3MSezKlVDyc/N21lJp1jz/38A "Python 3 – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~9~~ 12 bytes *+3 bytes to handle more stringent rules* ``` +:A_%E#A_MJa ``` [Replit!](https://replit.com/@dloscutoff/pip) (Note: the Unicode input seems not to play well with Pip's interactive mode, or maybe it's a Replit issue. For best results, Ctrl-C out of the default interactive mode and enter `./pip.py -e A_%E#A_Ma ⁶⁵⁵³⁵` at the command prompt.) Or, here's a 14-byte equivalent in Pip Classic: [Try it online!](https://tio.run/##ATEAzv9waXD//ys6QV8lMioqI0FfTUph////4oGwwrnCssKz4oG04oG14oG24oG34oG44oG5 "Pip – Try It Online") ### Explanation After some trial and error, I found a really nice property of these numbers' codepoints: * ¹, ², and ³ have codepoints 185, 178, and 179. Mod 8 (or 4), these become 1, 2, and 3. * The other superscript numbers have codepoints equal to the corresponding digit plus 8304. Mod 16 (or 12, or many other options), these become their respective digits. So all we need to do is take the codepoint of each digit mod 8 if it's 3 digits and mod 16 if it's 4 digits... ``` a First command-line argument MJ Map this function to each character, joining the results together: A_ Codepoint of the character % Mod E 2 to the power of # Length of A_ Codepoint of the character +: Treat the resulting string as a number (removing leading 0s) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ç92%12%J ``` -3 bytes porting [*@Arnauld*'s JavaScript method](https://codegolf.stackexchange.com/a/238482/52210) (thanks *@Neil* for the heads up). Add a trailing `ï` (+1 byte) if you want to remove leading 0s.. [Try it online](https://tio.run/##AS4A0f9vc2FiaWX//8OHOTIlMTIlSv//4oGwwrnCssKz4oG04oG14oG24oG34oG44oG5) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w@2WRqqGRqpe/3X@Rysd2qmko/SocSuQPLTz0KZDm8HcbUARIDq0GSLzqHEDRPJR4xawDFB@@6PGHY8adyrFAgA). **Explanation:** ``` Ç # Convert the (implicit) input to a list of its codepoint-integers # e.g. "⁰¹²³⁴⁵⁶⁷⁸⁹" → [8304,185,178,179,8308,8309,8310,8311,8312,8313] 92% # Modulo-92 # → [24,1,86,87,28,29,30,31,32,33] 12% # Modulo-12 # → [0,1,2,3,4,5,6,7,8,9] J # Join the list together # → 0123456789 ï # (Optionally) Remove leading 0s by casting to an integer # → 123456789 # (after which the result is output implicitly) ``` [Answer] # JavaScript, ~~65~~ ~~62~~ ~~61~~ 60 bytes ``` s=>s.replace(/./g,x=>-~'¹²³⁴⁵⁶⁷⁸⁹'.search(x)) ``` *Saved 3 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602).* *Saved 1 byte thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974).* *Saved 1 byte thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563).* [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvu/2NauWK8otSAnMTlVQ19PP12nwtZOt0790M5Dmw5tftS45VHj1keN2x41bn/UuONR4051veLUxKLkDI0KTc3/BUWZeSUaaRpA1eqamlxwLlAPCh9iGJqSbWCTt4IsAan@DwA) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 19 bytes ``` T`⁰-⁹_¹²³`dd ``` [Try it online!](https://tio.run/##K0otycxL/P8/JOFR4wbdR4074w/tPLTp0OaElJT//w/t5HrUuJULIgJkbgPygOjQZiABAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: `d` is a shorthand for `0123456789`. As `⁰-⁹` expands to `⁰ⁱ⁲⁳⁴⁵⁶⁷⁸⁹`, and assuming none of `ⁱ⁲⁳` will appear in the input, those supserscript digits will get mapped to ASCII digits, while the `_¹²³` gets mapped to `0123` (the remaining digits in `d` get ignored). `_` is actually a placeholder on the LHS and does nothing except to skip `0` on the RHS (on the RHS it causes the character on the LHS to be deleted). [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Use Arnauld's formula so be sure to upvote him. ``` c %#\%C ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=YyAlI1wlQw&input=Ilx1MjA3MLmys1x1MjA3NFx1MjA3NVx1MjA3Nlx1MjA3N1x1MjA3OFx1MjA3OSI) [Answer] # [C (gcc)](https://gcc.gnu.org/) with `-funsigned-char`, 63 bytes This version takes a string of UTF-8 characters. If the leading byte is `E2` then I mask the third byte with 15; otherwise I mask the second byte with 3. It's useful that `B9` (the trailing byte of ¹) is odd! ``` i;f(char*s){for(i=0;*s;s++)i=(*s++-226?*s&3:*++s&15)+i*10;i=i;} ``` [Try it online!](https://tio.run/##RZDNSsNAFIX38xSHSMvMJLFNamvrmAoVd8WdK3VRkqYdqIl0piKULvJGYv3LNo@SBzHOWEG4cH@@cy@HG/uLOG4aKVIaL2drrtg2zddURl3BlVCuy2REucl@GA4uuGr3zrjrqnbQZ67kQVfISIpdcySzeLVJ5jhXOpH58XJMSKeDqxDDAJNn0C5O0McApxhixCy7DDEZdSwLEKLHCJGZxsNMZvQplwnDlgDWE7i6vY9sBzhV6Xhw6uLdpqqsXqv9YfBhZiaq/R@ri5d/fKjq4u1XZKSfdfFVF6URGXx9M52a6zsPnGtBTGlfoCMlYHpo8wQ8ro27lDothWiMVnKXmUWuPaSUa8YE2TXfcbqaLVTjp5tMyUU2T3xr/wc "C (gcc) – Try It Online") [Answer] # [APL (dzaima/APL)](https://github.com/dzaima/APL), ~~16~~ 15 bytes −1 byte thanks to rak1509 Anonymous tacit prefix function. Requires 0-based indexing. ``` 10⊥'⁰¹²³⁴⁵⁶⁷⁸'⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pSszMTfz/qG@qp/@jtgkGXGlAUuO/ocGjrqXqjxo3HNp5aNOhzY8atzxq3Pqocdujxu2PGnc8atyp/qh3839NLqA@oPo0pUM7leBsoEolJAmQfmTJbWCTtoIM3YosDrVK6T8A "APL (dzaima/APL) – Try It Online") `10⊥` evaluate in base 10 `'⁰¹²³⁴⁵⁶⁷⁸'⍳` the respective *i*ndices of the argument characters in this string (any character not in the string gets the first index beyond the end, i.e. 9) [Answer] # [APOL](https://esolangs.org/wiki/APOL), ~~46~~ 27 bytes `I(j(ƒ(i %(%(↶(∋) 92) 12))))` Uses Arnauld's 92/12 solution. *Note: 3 bytes can be saved by removing the `I` instruction, however this version is not case 5-compliant.* ## Explanation ``` I( Cast to integer j( Join string (default is no seperator) ƒ( List-builder for loop (returns a list of every returned value of the passed instruction) i Get input %( Modulo 2 (12) %( Modulo 1 (92) ↶( Get codepoint ∋ The current item in the for loop ) 92 ) 12 ) ) ) ) Implicit print ``` Old code (uses lookup table instead): `v(0 []);f(i a(0 t(⌕("⁰¹²³⁴⁵⁶⁷⁸⁹" ∋))));I(j(⁰))` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), ~~6.5~~ 6 bytes (12 nibbles) ``` `@~.$`&%$12 ``` A port of [Lynn's Jelly answer](https://codegolf.stackexchange.com/a/238491/95126) comes out ~~half-a-byte~~ a byte shorter in [Nibbles](http://golfscript.com/nibbles/index.html). ``` . # Map over $ # the input string: `& # bitwise-and of $ # each element % # modulo 12 # twelve # and itself `@~ # Finally, convert from base-10 digits ``` [![enter image description here](https://i.stack.imgur.com/n5peI.png)](https://i.stack.imgur.com/n5peI.png) [Answer] # Python 3, ~~63~~ 62 bytes `lambda n: int("".join([str("⁰¹²³⁴⁵⁶⁷⁸⁹".index(c))for c in n]))` Thanks @Fmbalbuena! [Answer] # [Husk](https://github.com/barbuz/Husk), ~~10~~ 9 bytes ``` dm(Sn%12c ``` [Try it online!](https://tio.run/##AS8A0P9odXNr//9kbShTbiUxMmP///8i4oGwwrnCssKz4oG04oG14oG24oG34oG44oG5Ig "Husk – Try It Online") Port of ~~[Arnauld's Javascript answer](https://codegolf.stackexchange.com/a/238482/95126)~~ [Lynn's Jelly answer](https://codegolf.stackexchange.com/a/238491/95126). The 'charcode-to-charcode' [modulo-except-when-it's-185](https://codegolf.stackexchange.com/a/238472/95126) approach is discouragingly long in [Husk](https://github.com/barbuz/Husk), but Lynn's 'charcode-to-digit' modulo-AND approach is very well-suited to [Husk](https://github.com/barbuz/Husk)'s `d` (digits to decimal number) function. [Answer] # [PHP](https://php.net/), 35 bytes ``` <?=+iconv('','US//TRANSLIT',$argn); ``` [Try it online!](https://tio.run/##K8go@P/fxt5WOzM5P69MQ11dRz00WF8/JMjRL9jHM0RdRyWxKD1P0/r//0eNGw7tPLTp0OZ/@QUlmfl5xf913QA "PHP – Try It Online") Some nice PHP builtin [Answer] # [Nim](http://nim-lang.org/), 63 bytes ``` import strutils,unidecode stdin.readAll.unidecode.parseInt.echo ``` [Try it online!](https://tio.run/##y8vM/f8/M7cgv6hEobikqLQkM6dYpzQvMyU1OT8llau4JCUzT68oNTHFMSdHDy6uV5BYVJzqmVeil5qckf///6PGDYd2Htp0aPOjxm2PGrcCEYi5FQA "Nim – Try It Online") If removing leading zeros is not required: ## [Nim](http://nim-lang.org/), 45 bytes ``` import unidecode stdin.readAll.unidecode.echo ``` [Try it online!](https://tio.run/##y8vM/f8/M7cgv6hEoTQvMyU1OT8llau4JCUzT68oNTHFMSdHDy6ul5qckf///6PGDYd2Htp0aPOjxm2PGrcCEYi5FQA "Nim – Try It Online") [Answer] # [Turing Machine Code](http://morphett.info/turing/#SyntaxInfo), 99 bytes ``` * ⁰ 0 r * * ¹ 1 r * * ² 2 r * * ³ 3 r * * ⁴ 4 r * * ⁵ 5 r * * ⁶ 6 r * * ⁷ 7 r * * ⁸ 8 r * * ⁹ 9 r * ``` [Try it online!](http://morphett.info/turing/?86ef941bf68261e77f4e6e876cfe6ae7) [Answer] # [Ruby](https://www.ruby-lang.org/), 40 bytes ``` ->s{s.tr("⁰-⁹¹²³","0-9123").to_i} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664ulivpEhD6VHjBt1HjTsP7Ty06dBmJR0lA11LQyNjJU29kvz4zNr/BQpp0SA1EPlHjVseNW591LjtUeP2R407gPqUYrnASg7tBCnaBCKAqjaAFW4Aq90AVr4BrGMDWBOQBKlWiv0PAA "Ruby – Try It Online") [Answer] # [Factor](https://factorcode.org/), 13 bytes ``` [ nfkd dec> ] ``` `nfkd` postdates the build TIO uses, so have a screenshot: [![enter image description here](https://i.stack.imgur.com/HH70b.png)](https://i.stack.imgur.com/HH70b.png) [Answer] # [Lua](https://www.lua.org/), 94 bytes ``` r=0 t={[185]=1,[178]=2,[179]=3}for _,c in utf8.codes(...)do r=r*10+(t[c]or c-8304)end print(r) ``` [Try it online!](https://tio.run/##yylN/P@/yNZAocS2OtrQwjTW1lAn2tDcItbWCERbxtoa16blFynE6yQrZOYplJakWegl56ekFmvo6elppuQrFNkWaRkaaGuURCfHAtUl61oYG5hopualKBQUZeaVaBRp/v///1HjhkM7QcSmQ5sB "Lua – Try It Online") [Answer] # Excel, ~~72~~ 63 bytes Saved 9 bytes thanks to [JvdV](https://codegolf.stackexchange.com/questions/238462/convert-superscript-numbers-to-normal-numbers/238512?noredirect=1#comment560546_238512) ``` =--CONCAT(MOD(MOD(UNICODE(MID(A1,SEQUENCE(LEN(A1)),1)),92),12)) ``` Not very exciting, really. It's the Excel version of [Arnauld's answer.](https://codegolf.stackexchange.com/a/238482/38183) * `MID(A1,SEQUENCE(LEN(A1)),1)` pulls each character from the input one at a time. * `MOD(MOD(UNICODE(MID(~)),92),12))` converts that character to unicode and then takes the mod 92 and mod 12. * `--CONCAT(MOD(~))` combines all those code values into a string and then coerces that string into a number by making it negative twice (so back to positive again) which also will drop any leading zeros. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 40 bytes ``` A+O:-unicode_nfkd(A,C),atom_number(C,O). ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/31Hb30q3NC8zOT8lNT4vLTtFw1HHWVMnsSQ/Nz6vNDcptUjDWcdfU@@/la5CbmJBTmZxiUZ0RKydnUaEtr9OeVFmSWpOnoa/pqZOtNKhnUo6So8atwLJQzsPbTq0GczdBhQBokObITKPGjdAJWOBpgIA "Prolog (SWI) – Try It Online") Builtins ]
[Question] [ Based on this: [Make me a square!](https://codegolf.stackexchange.com/questions/120052/try-to-make-a-square) You need to output this: ``` #### # # # ### # # # # #### ``` Where "#" is replaced with the input. If you input "A", you should get ``` AAAA A A A AAA A A A A AAAA ``` If you input "&", you should get ``` &&&& & & & &&& & & & & &&&& ``` ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. ``` /* Configuration */ var QUESTION_ID = 121651; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; if (/<a/.test(lang)) lang = jQuery(lang).text(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang > b.lang) return 1; if (a.lang < b.lang) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # [Carrot](http://kritixilithos.github.io/Carrot/), 31 bytes ``` #### # # # ### # # # # #### ``` `#`s are replaced by the input. Basically a port of [this answer](https://codegolf.stackexchange.com/a/120079/65836), to this problem. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 15 bytes ``` ð‚•nxвΛ•2вèJ6ô» ``` [Try it online!](https://tio.run/nexus/05ab1e#@394w6OGWY8aFuVVXNh0bjaQYXRh0@EVXmaHtxza/f@/FgA "05AB1E – TIO Nexus") **Explanation** ``` ð‚ # push the list [<input>,<space>] •nxвΛ• # push the number 816342339 2в # convert to list of base 2 digits è # index into the the 2-char string with this list J # join to string 6ô # split into pieces of length 6 » # join on newlines ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 62 bytes ``` ./v<.o;.@?/;w.w;i:::::NrSs::SrSuUS::sN::rS:r:srNr:SrSsNs:::SSv ``` [Try it online!](https://tio.run/nexus/cubix#FcmxDYAwDETRYeid/owEE7g5MQQV0lkk4zvJL98va/20z@2@mg8b/mIXYgIU/4dABiBCSIW2ZqwLslcdEw) and [Watch the interpreter!](http://ethproductions.github.io/cubix/?code=Li92PC5vOy5APy87Li53O2k6Ojo6Ok5yU3M6OlNyU3VVUzo6c046OnJTOnI6c3JOcjpTclNzTnM6OjpTU3Y=&input=Qg==&speed=5) This fits onto a 4-cube: ``` . / v < . o ; . @ ? / ; . . w ; i : : : : : N r S s : : S r S u U S : : s N : : r S : r : s r N r : S r S s N s : : : S S v . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ``` I'm not very good at manipulating the direction of the instruction pointer, so I will continue to try and golf this. Both this and my answer [here](https://codegolf.stackexchange.com/a/121693/67312) are based on the "Hello, World!' example program using `./v.o;@?/` (on a 3-cube) to recursively print and pop the characters on the stack, so the rest of the code is just pushing the characters onto the stack in the right order. I have now made a cube on a cube, so I can rest easy (and do my actual work). [Answer] # [SOGL](https://github.com/dzaima/SOGL), ~~13~~ 10 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` Βū&⁵'r⁹‘6n ``` Explanation: ``` Βū&⁵'r⁹‘ push " ŗŗŗŗ ŗ ŗ ŗŗŗŗ ŗŗ ŗ ŗ ŗŗŗŗ", where "ŗ" is replaced with input 6n split into lines of length 6 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~13~~ 10 bytes *Thanks to Conor O'Brien for removing 3 bytes, and for showing me that unprintables can be used in Octave.* The code contains unprintable characters. [Try it online!](https://tio.run/nexus/matl#@6/OL2qpZaPupJX8/7@6ozoA "MATL – TIO Nexus") ### Explanation ``` '....' % Push 5-char string (contains unprintables). Each char encodes a row % of the desired pattern B % Convert to binary. Gives a 5×6 binary matrix with the pattern * % Implicit input. Multiply element-wise (converts input to ASCII code) c % Convert to char. Implicitly display. Char 0 is shown as space ``` [Answer] # PHP, 52 Bytes ``` <?=strtr(" 0000 0 0 0 000 0 0 0 0 0000",0,$argn); ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVVJWsuayt/tvY29bXFJUUqShpKBgAARcCgYgyAVkKoAoGMdAScdAB6xV0/r/fwA "PHP – TIO Nexus") [Answer] ## [Japt](https://github.com/ETHproductions/japt), 20 bytes ``` "OUyj|"®c ¤Åd0S1U +R ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=Ik9VeWp8Iq5jIKTFZDBTMVUgK1I=&input=IkEi) Not too bad for a language with no built-in compression (well, except compressing strings of lowercase letters)... ### Explanation In binary, the five characters in the string are: ``` O 1001111 U 1010101 y 1111001 j 1101010 | 1111100 ``` Slice off the initial `1` from each, and you get the pattern for the cube. ``` "OUyj|"® c ¤ Å d0S1U +R "OUyj|"mZ{Zc s2 s1 d0S1U +R} // Expanded // Implicit: U = input string "OUyj|"mZ{ } // Replace each character Z in this string with this function: Zc // Take the char-code of Z. s2 // Convert to a binary string. s1 // Slice off the first character (always a "1"). d0S1U // Replace "0"s with spaces and "1"s with the input. +R // Append a newline. // Implicit: output result of last expression ``` [Answer] # LOLCODE, ~~202~~ 170 bytes ``` I HAS A c GIMMEH c VISIBLE" "AN c AN c AN c AN c AN":) "AN c AN" "AN c AN" "AN c AN":)"AN c AN c AN c AN" "AN c AN":)"AN c AN" "AN c AN" "AN c AN":)"AN c AN c AN c AN c ``` In LOLCODE, not much to golf... This sets the variable `c` into the input, and creates a giant concatenated string including `:)` newlines. That's about it. [Answer] # Sed, 40 characters ``` s/./ &&&&\ & & &\ &&& &\ & & &\ &&&&/ ``` Almost cheating as the challenge description contained it almost literally. Sample run: ``` bash-4.4$ sed 's/./ &&&&\ & & &\ &&& &\ & & &\ &&&&/' <<< 'C' CCCC C C C CCC C C C C CCCC ``` [Try it online!](https://tio.run/nexus/sed#@1@sr6evoKAGBDFcCmogGMMF5CiAaThXTf//f2cA "sed – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), 61 bytes ``` lambda c:""" #### # # # ### # # # # ####""".replace('#',c) ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQbKWkpKSgoAwEXArKIMgFZCqAKBhHGahCryi1ICcxOVVDXVldJ1nzf0FRZl6JQpqGuqO6JheYwwUXUlPX/A8A "Python 2 – TIO Nexus") [Answer] # Z80 Assembly, 37 bytes machine code Assume a memory mapped I/O device: ``` ; DO NOT INPUT A SPACE or it will go into infinite loop printing spaces & newlines! 3A xx xx ld a, (input) ; get input character 11 0A 20 ld de, 200ah ; space & newline 21 yy yy ld hl, output ; get output address 4F ld c, a ; put character in c loop: 72 ld (hl), d ; output space * 2 | output character * 2 72 ld (hl), d 77 ld (hl), a ; output character | output character 71 ld (hl), c ; output character * 2 | output space * 2 71 ld (hl), c 77 ld (hl), a ; output character | output character 73 ld (hl), e ; output newline | output newline 72 ld (hl), d ; output space | output character 71 ld (hl), c ; output character | output space 72 ld (hl), d ; output space | output character 71 ld (hl), c ; output character | output space 72 ld (hl), d ; output space | output character B9 cp c ; set zero flag 1st time | clear 2nd time 20 06 jr nz, end ; skip to end 77 ld (hl), a ; output character 73 ld (hl), e ; output newline 4A ld c, d ; put space in c 57 ld d, a ; put character in d 28 FB jr z, loop ; loop to 2nd time end: 73 ld (hl), e ; output newline 77 ld (hl), a ; output character * 4 77 ld (hl), a 77 ld (hl), a 77 ld (hl), a 76 halt ; or C9 ret ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 27 bytes ``` 4äl2>>Äyvho3pÄÙ3älWx<<3Îd^ ``` [Try it online!](https://tio.run/##K/v/3@TwkhwjO7vDLZVlGfnSxgWHWw7PNAaKhVfY2Bgf7kuJ@//fEQA "V – Try It Online") Hexdump: ``` 00000000: 34e4 6c32 3e3e c479 7668 6f1b 3370 c4d9 4.l2>>.yvho.3p.. 00000010: 33e4 6c57 783c 3c33 ce64 5e 3.lWx<<3.d^ ``` [Answer] # PHP, 72 bytes I made this one just for the fun of it, since there's already a better PHP answer. ``` for($i=0;$i<27;)echo('00'.decbin(64349871))[$i]?$argn:' ',++$i%6?'':' '; ``` --- The cube is drawn by getting the binary value of `64349871`, concatenated by `'00'`. This returns the following: ``` 0011110101011110011010101111 ``` Every 6th character, I'm outputting a newline, resulting in this: ``` 001111 010101 111001 101010 1111 ``` And, instead of displaying `0`, it displays a space, which will look like: ``` 1111 1 1 1 111 1 1 1 1 1111 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~17~~ 16 bytes ``` SβGH7+↗→³β→G↓↙³β ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0JLikKDMvXSNJkysgP6cyPT/PIz8nJ79cw8pcwUpbwSq0ICgzPaNEwQpM6SgY6ygkaVpz@eaXpWpAxIA8qE4NK5f88jwFMOmTmgZX/f9/xH/dsv@6xTkA "Charcoal – Try It Online") Link is to verbose version of code. Longer than I wanted it to be, because the "cube" is slightly wider than it is tall or deep. Fortunately some of the multidirectional characters work with PolygonHollow, which saves me 3 bytes. Edit: Saved a further byte by using + instead of T↑. Explanation: ``` Sβ Input the character GH7+↗→³β Draw the left half. 7 becomes ←↙ and + becomes →↓←↑. → Move right one character. G↓↙³β Draw the right half. ``` At the time of the challenge, the `q` variable didn't work in verbose mode, otherwise I could have created this 14-byte version: ``` GH7+↗→³θ→G↓↙³θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8gP6cyPT/PIz8nJ79cw8pcwUpbwSq0ICgzPaNEwQpM6SgY6ygUalpz@eaXpWpAxIA8qE4NK5f88jwFMOmTmgZX/f9/xH/dsv@6xTkA "Charcoal – Try It Online") [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 31 bytes ``` ' '\+$'9*<'#.2 tb[6 dpad]map# ``` [Try it online!](https://tio.run/nexus/stacked#U3dU/6@uoB6jraLOL2qpZaOurGekUJIUbaaQUpCYEpubWKD8P7@05D8A "Stacked – TIO Nexus") Here's a hexdump: ``` λ xxd try-to-make-a-cube.stk 00000000: 2720 275c 2b24 270f 1539 2a3c 2723 2e32 ' '\+$'..9*<'#.2 00000010: 2074 625b 3620 6470 6164 5d6d 6170 23 tb[6 dpad]map# ``` This converts a character array to binary, pads each row to length `6`, and indexes it according to the string `' ' input +` [Answer] # Pyth, ~~25~~ ~~22~~ ~~21~~ 20 bytes ``` jcsm?d\ zjC"0¨eC"2 6 ``` [Try it!](https://pyth.herokuapp.com/?code=jcsm%3Fd%5C+zjC%220%C2%A8eC%222+6&input=B&debug=1) 21 bytes ``` t::." \"o½MËñ"\!bNw ``` [Try this!](https://pyth.herokuapp.com/?code=t%3A%3A.%22+%5C%22%02o%C2%BD%C2%82M%C3%8B%C3%B1%22%5C%21bNw&input=A&debug=0) Also 21 bytes: ``` :jbct." \" ±¢î "6Nw ``` [Try that!](https://pyth.herokuapp.com/?code=%3Ajbct.%22+%5C%22%01%C2%8B+%C2%B1%C2%A2%C3%AE%0A%226Nw&input=B&debug=0) [Answer] # JS (ES6), ~~64~~ ~~60~~ 52 bytes ``` i=>` #### # # # ### # # # # ####`.replace(/#/g,i) ``` Can this be improved: ``` i=>` ${y=i+i+i+i} # # # ### # # # # ${y}`.replace(/#/g,i) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~90~~ 84 bytes ``` i;v;f(g){for(i=32;i--;)putchar((v="####*@#@#@#*#@@###*#@#@#@*####@@"[i])&1?g:v-32);} ``` [Try it online!](https://tio.run/nexus/c-gcc#@59pXWadppGuWZ2WX6SRaWtsZJ2pq2utWVBakpyRWKShUWarpAwEWg7KIKil7OAA4oE5DlogGQcHpejMWE01Q/t0qzJdYyNN69r/mXklCrmJmXkamtVcCgVFQG6aBtCSVIiZmpqa1ly1/5UB "C (gcc) – TIO Nexus") Defines a function `f` that takes a character `g`. Too bad encoding the table directly is shorter... ## Old version, 90 bytes (Still trying to golf this one) Trying to have only a single `putchar`, but idk. There are unprintables, so here is the hexdump: ``` λ xxd try-to-make-a-cube.c 00000000: 693b 6a3b 6628 6729 7b63 6861 722a 6b3d i;j;f(g){char*k= 00000010: 220f 1539 2a3c 223b 666f 7228 693d 303b "..9*<";for(i=0; 00000020: 693c 353b 7075 7463 6861 7228 3130 292c i<5;putchar(10), 00000030: 692b 2b29 666f 7228 6a3d 3332 3b6a 3b6a i++)for(j=32;j;j 00000040: 2f3d 3229 7075 7463 6861 7228 6b5b 695d /=2)putchar(k[i] 00000050: 266a 3f67 3a33 3229 3b7d &j?g:32);} ``` This encodes the cube into a binary lookup table, where a `1` bit represents the input and a `0` bit represents a space. [Try it online!](https://tio.run/nexus/c-gcc#@59pnWWdppGuWZ2ckViklW2rxC9qqWWjZJ2WX6SRaWtgnWljal1QWgKS1TA00NTJ1NbWBMll2RobAbVm6dsaacLks6MzY9Wy7NOtjI00rWv/Z@aVKOQmZuZpaFZzKRQUAblpGkCrUiGKNTU1rblq/ysDAA "C (gcc) – TIO Nexus") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 217 bytes ``` (((((((((((((((((({}))))<([][]()())>)<(([][])[]{}())>)<(([][]){})>)<([])>)<(((() ())[][]{}()()))>)))<((()()()()()){})>)<(((()()()){}){}()[])>)<(((()()())()){}{}[ ])>)<(((()()())){}{}[])((()()()()()){})>))))(([]()()())) ``` [Try it online!](https://tio.run/##ZY4xDoAgDEUP49I/cAPDRQgDmpgYDYMr4ey1remAlIX//qNhe8pZw3GXi5mmaR0yK6WcMoGAKMESUm59AOJGUz9G5mujnlwFwwr48SfONKs8rBBsTet/7HBeKaOfco954bC/ "Brain-Flak – Try It Online") Waaaaay too long. [Answer] # Swift - 82 bytes + Foundation (18 bytes)? ``` var f={" ####\n # # #\n### #\n# # #\n####".replacingOccurrences(of:"#",with:$0)} ``` By default, Xcode-Swift projects have `Whole-Module Optimization`, so that `import Foundation` is not required for this simple lambda-like function. However, running it in online environments requires it, which may add 18 bytes. **[Check it out!](http://swift.sandbox.bluemix.net/#/repl/5920707315c0ca24e9dbb84e)** [Answer] # Java 8, 55 bytes ``` c->" ####\n # # #\n### #\n# # #\n####".replace('#',c) ``` [Try it here.](https://tio.run/nexus/java-openjdk#hY5BCsIwEEX3PcXHgG1Ac4Gi4AHsxqV1EceogTQtSSqI9Ow1qcWdmIEMf@bz5pOR3mMvtX1lgLZBuaskhSpJ4BCctjdQQXfpQLyM0yGLnw8yaEIFiw1GWm8XAIuvtmCpahsFpv6VbCGc6kzEFznLV8THMqG6/mwiaiY@Wn1BE/MUn9vHEySfwzx9UI1o@yC6uArGFlZQYvEp2G/H7q9jOTuGbBjf) # Java 7, 77 bytes ``` String c(char c){return" ####\n # # #\n### #\n# # #\n####".replace('#',c);} ``` [Try it here.](https://tio.run/nexus/java-openjdk#hY1BCsIwEEX3PcWnAZuA9AJdeQBXXVoXcQwaSNOSTAQpPXtNtbjU@Yvh8@B9cjpGHKcCiKzZEpaWg/U3kKS7DiA1BcMp@BIQ@ToPsabzueD9v1WUdTCj02RkJao9qWZegDFdXPZu@sdgr@i19fKzczpDq3UeaJ@RTV8PiesxI3Ze0ipSqvnBD3/4buNzMS8v) [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `jr`, 12 bytes ``` ðp»2<I∵»τ5$/ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=jr&code=%C3%B0p%C2%BB2%3CI%E2%88%B5%C2%BB%CF%845%24%2F&inputs=%27%26%27&header=&footer=) ``` »2<I∵»τ # Decompress the pattern using... ðp # Space + input 5$/ # Split into 5 # (j flag) Join by newlines ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 79 bytes ``` +++++[->++++++<<++>],>++..<....<.>>.<.>.<.>.<.>.<<.>...>..<.<.>.>.<.>.<.<.>.... ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwSide3AtLaNjba2XawOkKenZ6OnByLs7EAEAoMIPRC2AfNhMhBhvf//lQE "brainfuck – Try It Online") Not sure why this doesn't exist [Answer] ## CJam, 23 bytes ``` "pjFUC"{i2b(;}%rS+ff=N* ``` I feel like I can still golf this. ``` "pjFUC" e# String literal: │ "pjFUC" { e# For each: │ 'p i e# Get code point: │ 112 2b e# To binary: │ [1 1 1 0 0 0 0] (; e# Delete first: │ [1 1 0 0 0 0] }% e# End │ [[1 1 0 0 0 0] [1 0 1 0 1 0] [0 0 0 1 1 0] [0 1 0 1 0 1] [0 0 0 0 1 1]] r e# Read token: │ [[1 1 0 0 0 0] [1 0 1 0 1 0] [0 0 0 1 1 0] [0 1 0 1 0 1] [0 0 0 0 1 1]] "&" S e# Push space: │ [[1 1 0 0 0 0] [1 0 1 0 1 0] [0 0 0 1 1 0] [0 1 0 1 0 1] [0 0 0 0 1 1]] "&" " " + e# Concatenate: │ [[1 1 0 0 0 0] [1 0 1 0 1 0] [0 0 0 1 1 0] [0 1 0 1 0 1] [0 0 0 0 1 1]] "& " ff= e# Vectorized array lookup: │ [" &&&&" " & & &" "&&& &" "& & & " "&&&& "] N* e# Join with newlines │ " &&&& e# │ & & & e# │ &&& & e# │ & & & e# │ &&&& " e# Implicit output ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 70 bytes Encodes the sequence rather directly, with minor optimization: ``` 8224PdPdPdPdP10Pd8192+ddPPP10PdPdPdP8224PdP10Pd256*32+ddPPP10PdPdPdPdP ``` [Try it online!](https://tio.run/nexus/dc#Mzb9b2FkZBKQAoWGBgEpFoaWRtopKQEBYB4YQtWA@EamZlrG6PIpAf//AwA "dc – TIO Nexus") --- Taken to a (not very golfy) extreme, 145 bytes: ``` 27065671941896667324298575455432398417474802390765222440949482848513*56759961956005660143530475805610581704254588701249011343446231795984498688+P ``` [Try it online!](https://tio.run/nexus/dc#DY2xAQMwCMP@aRcMNpgv@v8zKZu0SKWXE60eLOHt7qlkrjWixMpaE8Oh4zimlZlkLJdO00J9LqDdxqoj1B1gqYIjnyJkTDAvaU8guQEUi@wszOomXLf9/b33Bw "dc – TIO Nexus") This computes `A*x+B`, where `A` encodes the positions of the input character and `B` encodes all the rest: > > A = 2560 + 2561 + 2562 + 2563 + 2565 + 2567 + 2569 + 25611 + 25614 + 25615 + 25616 + 25618 + 25620 + 25622 + 25625 + 25626 + 25627 + 25628 > > > B = 10×2564 + 32×2566 + 32×2568 + 10×25610 + 32×25612 + 32×25613 + 10×25617 + 32×25619 + 32×25621 + 32×25623 + 10×25624 + 32×25629 + 32×25630 > > > `P` command prints the resulting number as a byte stream. [Answer] ## C#, 53 bytes ``` c=>@" #### # # # ### # # # # ####".Replace('#',c); ``` [Answer] # Windows batch, 79 bytes ``` @echo %1%1%1%1 @echo %1 %1 %1 @echo %1%1%1 %1 @echo %1 %1 %1 @echo %1%1%1%1 ``` Special char. safe, 97 bytes: ``` @echo ^%1^%1^%1^%1 @echo ^%1 ^%1 ^%1 @echo ^%1^%1^%1 ^%1 @echo ^%1 ^%1 ^%1 @echo ^%1^%1^%1^%1 ``` [Answer] # Tcl, 60 bytes ``` proc c x {regsub . $x " &&&&\n & & &\n&&& &\n& & &\n&&&&"} ``` ]
[Question] [ Your task is to input a sequence of integers and chunk sort it. You may assume the input list can always be chunked into groups of 1, 2, and 3. # Definition *Chunk sorting* (a term I made up for the purpose of this challenge) is the action of first chunking a sequence into groups of 1, 2, and 3 in a cycle and then sorting each group. # Test cases ``` [1, 2, 3, 4, 5, 6, 7, 8, 9] => [[1], [2, 3], [4, 5, 6], [7], [8, 9]] [5, 9, -2, 8, -6, 4, 5, 9, 1] => [[5], [-2, 9], [-6, 4, 8], [5], [1, 9]] [8, 3, -1, 6, -8, 7, -1] => [[8], [-1, 3], [-8, 6, 7], [-1]] ``` # Scoring The shortest code wins! # Rules No standard loopholes, please. [Answer] # [Ruby](https://www.ruby-lang.org/), 49 bytes ``` ->l{x=5;l.chunk{441[(x+=1)%12]}.map{|a,b|b.sort}} ``` [Try it online!](https://tio.run/##NcpLCsIwGATgvaf4N4LiJJA06QOJFwlZNEIRrLVUC5U0Z49RcTXMfDPN/pU6k9ipD4vRx56fL/NwDUoJu1sORuy3QrrIb@0Y1hZ@9fxxn54xppE6awUkCiholKhQo3Fu8wUNakBMguocJUiBfpv4XzIU2QQoM8ut@jTn0hs "Ruby – Try It Online") Literally: chunk, then sort. The magic number 441 is a bitmask with 1,2,3 binary digits alternatively seto to 1 or 0: ``` 000 11 0 111 00 1 ``` Since there are only 2 binary digits, I can't make it 3 chunks, so I make it 6 and so I use mod 12 to rotate. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 8 bytes ``` 3Rṁx@JṢƙ ``` [Try it online!](https://tio.run/##y0rNyan8/9846OHOxgoHr4c7Fx2b@f9w@9FJD3fO0Iz8/z/aUEfBSEfBWEfBREfBVEfBTEfBXEfBQkfBMlZHIRooYKmjoGsEFtE1gykCihmCpC3AGnUNwdp0LcBadQ1jAQ "Jelly – Try It Online") ## How it works ``` 3Rṁx@JṢƙ - Main link. Takes L on the left 3R - [1,2,3] ṁ - Mold to length L, repeating J - Yield [1,2,...,len(L)] x@ - Repeat 1 once, 2 twice, 3 thrice, 4 once, 5 twice, etc. Ṣƙ - Sort chunks of L, grouped by the elements of [1,2,2,3,3,3,4,...] ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` mOC¢ḣ3 ``` [Try it online!](https://tio.run/##yygtzv7/P9ff@dCihzsWG////z/aVMdSR9dIx0JH10zHRAfEM4wFAA "Husk – Try It Online") **How?** ``` ḣ3 # 1..3 ¢ # repeated infinitely; C # now split the input into sublists # of these lengths (discarding any # extra, unused lengths); m # finally, for each sublist: O # sort it. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 3LI∍£€{ʒgĀ ``` [Try it online](https://tio.run/##yy9OTMpM/f/f2MfzUUfvocWPmtZUn5qUfqTh//9oUx1LHV0jHQsdXTMdEx0QzzAWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRf@d/Yp/JRR@@hxY@a1lSfmpR@pOF/rc7/6GhDHSMdYx0THVMdMx1zHQsdy1gdhWhTHUsdXSMgT9cMLGWpYwgStgCq1DUEKtS1AKrVBYsZAhUAxQyNYmMB). Or alternatively (thanks to *@ovs* for `N6%tò`): ``` .yN6%tò}€{ ``` [Try it online](https://tio.run/##yy9OTMpM/f9fr9LPTLXk8KbaR01rqv//jzbVsdTRNdKx0NE10zHRAfEMYwE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRf@V@v0s9MteTwptpHTWuq/@v8j4421DHSMdYx0THVMdMx17HQsYzVUYg21bHU0TUC8nTNwFKWOoYgYQugSl1DoEJdC6BaXbCYIVABUMzQKDYWAA). **Explanation:** ``` 3L # Push list [1,2,3] I∍ # Extend the [1,2,3] list to the same size as the input-list £ # Split the (implicit) input-list into those parts, # which includes trailing empty lists at the end €{ # Sort each inner list ʒgĀ # Remove the empty lists: ʒ # Filter the list of lists: gĀ # Check if the list-length is not 0 # (after which the result is output implicitly) .y # Adjacent group the (implicit) input-list by: N # Push the 0-based group-by index 6% # Modulo-6 t # Take the square-root of that ò # Round it to the nearest integer }€{ # After the group-by: sort each inner list # (after which the result is output implicitly) ``` The `N6%tò` results in the sequence `[0,1,1,2,2,2,0,1,1,2,2,2,...]`, causing the adjacent group-by to split the input-list into parts of sizes `[1,2,3,1,2,3,...]`, which is what we want. --- The first program could be 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) if the input-length is guaranteed to be \$n>1\$: ``` 3LI∍£€{Ô¨ ``` [See all test cases](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRf@d/Yp/JRR@@hxY@a1lQfnnJoxX@d/9HRhjpGOsY6JjqmOmY65joWOpaxOgrRpjqWOrpGQJ6uGVjKUscQJGwBVKlrCFSoawFUqwsWMwbqBzPARGwsAA), and how it unfortunately fails for `[1]`. (Adding `Ć` after `I` would fix that edge-case, but unfortunately we'll then have another 10-bytes alternative.) [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 10 bytes ``` J%6B§=1ÄṢƙ ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJKJTZCwqc9McOE4bmixpkiLCIiLCIiLFsiWzUsIDksIC0yLCA4LCAtNiwgNCwgNSwgOSwgMV0iXV0=) ``` J%6B§=1ÄṢƙ Main Link J [1, 2, 3, ..., len(input)] %6 [1, 2, 3, 4, 5, 0, 1, 2, 3, ...] B Binary; [[1], [1, 0], [1, 1], [1, 0, 0], [1, 0, 1], [0], ...] § Sum each; [1, 1, 2, 1, 2, 0, ...] =1 Equal to 1?; [1, 1, 0, 1, 0, 0, ...] Ä Cumulative sum; [1, 2, 2, 3, 3, 3, 4, 5, 5, 6, 6, 6, ...] Ṣƙ Sort chunks of the input grouped based on equal elements on the left side ``` [Answer] # [Python](https://www.python.org), ~~86~~ ~~65~~ 63 bytes ``` def f(a,i=0): for x in a:a[i:i%3-~i]=sorted(a[i:i%3-~i]),;i+=1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY37VNS0xTSNBJ1Mm0NNK24FNLyixQqFDLzFBKtEqMzrTJVjXXrMmNti_OLSlJTNJCENHWsM7VtDaHG6CbaRpvqKFjqKOga6ShYACkzHQUTHQWImGEsF9AKTa6Cosy8EiADognmBgA) Modifies the list in-place; kinda cursed. [Answer] # [Python 2](https://docs.python.org/2/), 50 bytes ``` f=lambda a,i=1:a and[sorted(a[:i])]+f(a[i:],i%3+1) ``` [Try it online!](https://tio.run/##NY7BasMwEETv/oq5lEhkXZDTJLZB/REhioptInBs4SgJ/XpXqziX3WHn7TDhL17mqVrXQY/u@ts5OPJatWlPnbnNS@w74UzrrbT7ISnfWvIfh72S6/Pixx6qLeCnQJjvMUDj6oLoH24kLO75k5x7FPLzFkYfxQ76GzspC4TFTxGDSL6E1vl5NYpQEQ6EL8KRcCKcCTWhsfxojLIEwwTvjWF55pE5W5h0bAhllT/L0zss3dQWc2ScgSaLF1Kzzo7agupcpVS5SFnnMuU7I@Ps5S7sctvX0dp/ "Python 2 – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip) `-xp`, ~~24~~ ~~23~~ 18 bytes ``` $AL:SN*_^@^13Ma<>6 ``` [Replit!](https://replit.com/@dloscutoff/pip) Or, here's a 20-byte equivalent in Pip classic (with a header to simulate the -x flag): [Try it online!](https://tio.run/##K8gs@B9mlWj9X8XRx6o62E8rMc4hztC41jfRxs7s////ugX/o02tLa11jawtrHXNrE2sQTzDWAA "Pip – Try It Online") ### Explanation ``` $AL:SN*_^@^13Ma<>6 a First command-line arg <>6 Group into length-6 chunks M Map this function to each chunk: ^13 Split 13 into a list of digits [1;3] _^@ Split the argument at those indices SN* Sort each sublist using numeric comparison $AL: Fold the result on append-list (flattening by one level) ``` [Answer] # [R](https://www.r-project.org/), ~~70~~ ~~63~~ 59 bytes ``` function(a)Map(sort,split(a,rep(l<-seq(!a)-1,l%%3+1)[l+1])) ``` [Try it online!](https://tio.run/##Jco9CoAwDEDh3VPEQUgwHeIfKl7BE4hDEQtC0drW81fB6cHH88nApJJ5zi0e14maZu0wXD5ycPaIqNnvDu2kwn5jrkkJ26KoS6HFlrISJYMyDpQZ3LBlGBhUxdB/6Rgaht/kG18 "R – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 53 bytes ``` Sort/@TakeList[#,i=0;UpTo@Mod[++i,4]&/@#]/.{}->Set@$& ``` [Try it online!](https://tio.run/##NctBC4IwGMbx@z7FC4YX37VmZpMw9gEKAu0kHkYNG2GG7Tb22ZcNuv6f5zcq@9CjsuamwlCHZpotk6166pP52C5BU28O13c7yfN077LMYNGnTCY9WztPj422cpWGy2xeFpgcmHTEcYQcYYtQIOwQSoQ9gkCoPBK3hAqB5rHQ8n9aGv/NIkLKI6MiUso98SF8AQ "Wolfram Language (Mathematica) – Try It Online") -6 bytes thanks to @alephalpha -3 bytes thanks to @theorist -2 bytes thanks to @att [Answer] # JavaScript (ES6), 61 bytes *-4 and -1 thanks to Arnauld* ``` x=>(f=n=>x+x&&[x.splice(0,++n).sort((w,z)=>w-z),...f(n%3)])`` ``` [Answer] # [R](https://www.r-project.org/), 59 bytes ``` function(x,`*`=`[<-`)Map(sort,split(x,x*rep(seq(x),x*1:3))) ``` [Try it online!](https://tio.run/##K/qfnFGal12cX1Ri@z@tNC@5JDM/T6NCJ0ErwTYh2kY3QdM3sUADJK1TXJCTWQKUqtAqSgUKpRZqVGgCOYZWxpqamghjNAytLDW5ENxkDVMdBUsdBV0jHQULIGWmo2CiowARM9REVQmUNwYqMdRRAKrSBfLMQTyg6QA "R – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 24 bytes ``` 5,6,S`, %,,2S`, %N`[^,]+ ``` [Try it online!](https://tio.run/##K0otycxLNPz/31THTCc4QYdLVUfHCEz7JUTH6cRqg2QsdXSNdCx0dM10THRAPEMA "Retina – Try It Online") Explanation: ``` 5,6,S`, ``` Split the input into groups of up to six values. Limits are 0-indexed in Retina 1, so the first six values are numbered `0` to `5` and therefore the comma after the sixth value is also numbered `5`, however subsequent splits are every six commas as expected, until the end of the input. ``` %,,2S`, ``` Split each group into groups of 1, 2 and 3 values (if possible). The syntax `,,2` is short for `,2,2` so it only splits on the first and third comma; `,2` would be a range and so would also split on the second comma. ``` %N`[^,]+ ``` Sort the values in each group. [Answer] # [Bash 4.4.23](https://www.gnu.org/software/bash/), 142 bytes ``` f()( i=1 a=("$@") while [ ${#a[@]} -gt 0 ] do r=$r"["$(printf "%s\n" "${a[@]:0:$i}" |sort -n)"]" a=("${a[@]:${i}}") ((i=i==3?1:i+1)) done echo $r ) ``` [Try it here!](https://tio.run/##fc7PioMwEMfx@zzFjzSFhBJo@m9VCNv3cD3YVuvAEkt02YPrs7ux7bH0PN/5zJzKrpmmWmlF7CyVTgl5FJp@G/6ukEMOizI/FiPMtccaBV1aCk6GXKpbYN/XEMvuywsIOcxhts4kj@Kva0MP43XxIB8zOfA4Rlwpduzc9tNmvLJaR9RXVJ2bFjKQntjffnqnLDbYYoc9DvhAglQT1fOh@3z@ShA92z1SmE2MzOG@kcK@qZPoGhtZk0TZvEinfw) ## Explanation ``` i=1 > used to keep track of chunk size a=("$@") > transforms the parameters as an array while [ ${#a[@]} -gt 0 ] > while there is still some elements to "chuck sort" do r=$r[$(printf "%s\n" "${a[@]:0:$i}"|sort -n)] > construct the final result by picking only the required chunk from the array and sorts it. Store sort result in r and ad some delimiters a=("${a[@]:${i}}") > remove processed chunk from the array ((i=i==3?1:i+1)) > set size of next chunk done echo $r ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), ~~24~~ ~~23~~ ~~22~~ ~~21~~ 20 bytes *-1 thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)* ``` ∧¨⊢⊔˜¯1+`(0=∾↑↕3)⥊˜≠ ``` Anonymous tacit function that takes an array of numbers as its right argument. [Run it online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oinwqjiiqLiipTLnMKvMStgKDA94oi+4oaR4oaVMynipYrLnOKJoAoKRiA14oC/OeKAv8KvMuKAvzjigL/CrzbigL804oC/NeKAvznigL8x) ### Explanation The explanation uses an example argument of `⟨ 8 3 ¯1 6 ¯8 7 ¯1 ⟩`: ``` ∧¨⊢⊔˜¯1+`(0=∾↑↕3)⥊˜≠ ( ) Generate the array ⟨ 1 1 0 1 0 0 ⟩: ↕3 Range(3): ⟨ 0 1 2 ⟩ ↑ Prefixes: ⟨ ⟨⟩ ⟨ 0 ⟩ ⟨ 0 1 ⟩ ⟨ 0 1 2 ⟩ ⟩ ∾ Join: ⟨ 0 0 1 0 1 2 ⟩ 0= Equal 0: ⟨ 1 1 0 1 0 0 ⟩ ⥊˜ Reshape it to ≠ the length of the argument: ⟨ 1 1 0 1 0 0 1 ⟩ +` Cumulative sum ¯1 starting at -1: ⟨ 0 1 1 2 2 2 3 ⟩ ⊔˜ Using that list as a categorizer, group ⊢ the argument: ⟨ ⟨ 8 ⟩ ⟨ 3 ¯1 ⟩ ⟨ 6 ¯8 7 ⟩ ⟨ ¯1 ⟩ ⟩ ∧¨ Sort each: ⟨ ⟨ 8 ⟩ ⟨ ¯1 3 ⟩ ⟨ ¯8 6 7 ⟩ ⟨ ¯1 ⟩ ⟩ ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ẏǒʀÞṁvs ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuo/HksqAw57huYF2cyIsIiIsIls1LCA5LCAtMiwgOCwgLTYsIDQsIDUsIDksIDFdIl0=) I'm way late to the party, but who cares when the program looks like it spells something with heavy skamtebord vibes. ## Explained ``` ẏǒʀÞṁvs ẏ # The range [0...len(input)] ǒ # modulo each by 3 to get the chunk sizes ʀ # cast each to range [0...n] for shape Þṁ # mold the input to that, without repeating elements vs # sort each sublist ``` [Answer] # [J](http://jsoftware.com/), 24 15 bytes ``` <@/:~/.~#$#\##\ ``` [Try it online!](https://tio.run/##VY/BCsIwEETvfsVghCJsUlNtmxYFUfAkHry2IQexiBf/oL8eu5t6MJDssjvzmLzj0mQDDi0yEDZop6sNzvfrJe6PeTvmZlQr1SvVx/Xi@Xh9MMASCsKWsCOUhIpQExyhAXA7GXSd9YSONVxnFbc1P6z0/gebVg0hFEII1Q86zewMK9mkC3ZxkySOe9nYP5yTYMFKrOAkWrCQk3Di1HYOp136QBp6H78 "J – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~48~~ 40 bytes ``` ≔⮌AθWθ⊞υE⊕﹪Lυ³⊟θIEυ✂⟦⌊ι⁻Σι⁺⌊ι⌈ι⌈ι⟧⁰χ⁻⁴Lι ``` [Try it online!](https://tio.run/##VY5PC8IwDMXvfoocU4jgfxRP4klwMPQ4digzuELXzbVVv33NcB48JS/5vZdUte6rVtuUDt6bu8MLP7n3jCfXxYBKETzUfvKqjWXAh4I8@hojQaY7YaqeG3aBb5i1t2hbPLO7BwHEtxzMeduJS0lE3hsX8Kh9wMErEVdrKsYiM840sUEjuPTR43VUuRXxt9bvsVd/qiSYEcxnv4AVwfjIQA7nUyqKNcGOYLog2ErZEAj2nc3LMk2f9gM "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Charcoal really struggles here as it has no variable length split, flatten or sort primitive (at least not on TIO). ``` ≔⮌Aθ ``` Reverse the input array. ``` Wθ ``` Repeat until the input array has been chunked. ``` ⊞υE⊕﹪Lυ³⊟θ ``` Create a chunk of size depending on the number of chunks so far. ``` IEυ✂⟦⌊ι⁻Σι⁺⌊ι⌈ι⌈ι⟧⁰χ⁻⁴Lι ``` For each chunk, get the minimum, middle and maximum elements, but skip the middle if the chunk's size is less than `3` and skip the maximum if its size is less than `2`. Previous 48-byte version didn't require the input to be completely chunkable: ``` WθF³«⊞υ✂θ⁰⊕κ≔✂θ⊕κLθ¹θ»IEΦυι✂⟦⌊ι⁻Σι⁺⌊ι⌈ι⌈ι⟧⁰χ⁻⁴Lι ``` [Try it online!](https://tio.run/##VU7LCsIwEDzbr9jjBlawvlA8iSAICgWPpYdQYxtMo01SFcRvj6kv6GHZmd3ZnclLbvIzV97fSqkEYM3geDaAIwaPqJc0tsSGYK9kLrAmGBBsdG5EJbQTBzwxxhZRb2mtLDT@VV0JwVbowpXhN0Ecqg43zygxUjtccetwxy@4lsoJ05pJ9jNMd1LLqqmwHQXcWNx/WaIC6az5/YtZh2Xv0PHg92D8j9Mq2/zep@mEYE7QHxLMQpsSBNlnFmeZ71/VCw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Wθ ``` Repeat until the input is empty. ``` F³« ``` Take three chunks. ``` ⊞υ✂θ⁰⊕κ ``` Save the chunk. ``` ≔✂θ⊕κLθ¹θ ``` Remove the chunk from the input. ``` »IEΦυι✂⟦⌊ι⁻Σι⁺⌊ι⌈ι⌈ι⟧⁰χ⁻⁴Lι ``` For each non-empty chunk, get the minimum, middle and maximum elements, but skip the middle if the chunk's size is less than `3` and skip the maximum if its size is less than `2`. [Answer] # [HBL](https://github.com/dloscutoff/hbl), 17 [bytes](https://github.com/dloscutoff/hbl/blob/main/docs/codepage.md) ``` ?.(1(%(0,.))('?(2,.)(+(?(<,<), ).1 ``` [Try it!](https://dloscutoff.github.io/hbl/?f=0&p=Py4oMSglKDAsLikpKCc/KDIsLikoKyg/KDwsPCksCikuMQ__&a=KDUgOSAtMiA4IC02IDQgNSA5IDEp) ### Explanation The first line is a recursive function that does most of the work. It takes two arguments, a list and an integer, where the integer represents the current chunk size (1, 2, or 3). ``` ?.(1(%(0,.))('?(2,.)(+(?(<,<), ? If . Argument 1 is truthy (non-empty): (1 Construct a list from , Argument 2 (0 ) Take that many elements of . Arg1 (% ) Sorted prepended to ('? Recursive call with two arguments: (2,.) Drop (arg2) elements of arg1 and (+ Increment (? If , Arg2 (< ) is less than < 3: , Arg2 Else, 0 Else, empty list ``` Then the main function on the second line is simply: ``` ) Call the previous function with these arguments: . Argument 1 of the main function and 1 1 ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` £ñ+Ü5▬ ``` [Run and debug it](https://staxlang.xyz/#p=9ca42b9a3516&i=%5B1,+2,+3,+4,+5,+6,+7,+8,+9%5D+%0A%5B5,+9,+-2,+8,+-6,+4,+5,+9,+1%5D+%0A%5B8,+3,+-1,+6,+-8,+7,+-1%5D+&a=1&m=2) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~73~~ 70 bytes ``` l;f(a,n)int*a;{for(l=0;n;n-=l,a+=l,l%=3)qsort(a,++l,4,L"\x62b078bǃ");} ``` [Try it online!](https://tio.run/##tVJNj5swEL3vrxghpeLDVgPsZkld2kPVW/9BElWsY3bRsk6KkYo24tQf139VOtiAQdlDL0XCYL83M2@eh9NHzruuZLmbEekVsvYzdslPlVumayaZpGlJsgCXcpXG3g91qmpkBkFJbsk3Z99soof1ffLw@5fjsbbDeHjJCul6cLkBfPqDWqg63B0ghUtIICIQE7glcEdgQ@CeQEJg27KJGhkqwlsCNNI43YwheBbOyLEhJzopDXVKmui0FHkLDd@lIaviVZxyV8vy3g8732wJzNBoiUZLNF6isWfL@bqeMuV0YmJaM594Jkw0Z8FrcfxHg0a6Nal3aDs5lOiw8DrAGtW7FBuXNldG@VOA4U/yiC1tf8dG@EmqGvhTVvm4Cv4sKhOOA/I12jfbL/jeOQTm@9gZonHawO21FvIoGgxbs@H34@j3WNBaPp0wCALNHkdudFZipuHaNX5gcxivaMDVFXyukJC7zg5nejq0KgeFqE7q4vPC8/CVWh2x5@Jz3/gHB9d6VxxmKVub3K0JSO9awgHoJ1joMJeEGqaLeqM7OGdKISf8r/o1uS/0LtUQpKgKv291aBtaqb3EXOOc9AnGpO1N2/3heZk9qo7@7OiraARXdcaf/wI "C (gcc) – Try It Online") Inputs a pointer to an array of integers and its length (because pointers in C carry no length info). Chunk sorts the array in place. [Answer] # Haskell, ~~76~~ 71 bytes ``` import Data.List f=(%)1 n%[]=[] n%x=sort(take n x):(mod n 3+1)%drop n x ``` [Try it Online!](https://tio.run/##FYq9CsMgGEX3PMVdBKVpQQJtKbhl7NZRHIQkRBJ/0K80b2/NdO453NWWbd73Wp1PMRNGS/b2doW6RXEmZBeYNkqbxkOV9uBktxkBh3hxH6e2hosUbMoxnbV66wIU0pc@lMHLGn/gC/Szx9DjKnvcG5o9TjNC1D8) -5 bytes thanks to xnor Calling f on a list chunk sorts it. [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), ~~194~~ ~~170~~ 146 bytes ``` (load library (d C(q((L P)(i L(c(map head(zip L(1to P)))(i(e P 3)(C(t(t(t L)))1)(i(e P 2)(C(t(t L))3)(C(t L)2))))( (d S(q((L)(map merge-sort(C L 1 ``` [Try it online!](https://tio.run/##RY6xDoMwEEN3vsLj3dAh0FKYWTMg8QVpiWgkKDRkoT9PL6FVlcV69tkJ7rmNbl32ncbZ9BjdzRu/ZdSjoReRRsvkoOlOk1nwsKant1sEqDCLx@KSRYuCqaEQH7RQ9eP5l0d6ZETlHA/jSJdGOJVP1g/2tM4@UAMNtVMHsRVyFDjjghJXVKizyOXTQVANetpBVsRIquQUraH@sUruk6lYOpKqWLoOtn8A "tinylisp – Try It Online") -24 thanks to DLosc suggesting implementing `take` instead of the hodge-podge mess of `c`s I was using before. -24 again by implementing `take` more golfily. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 53 bytes ``` a->i=0;c=2;[vecsort(a[i+1..i=j+1])|b<-a,#a>j=i+c++%3] ``` [Try it online!](https://tio.run/##NYtRCsIwEAWvslSEhuwW02pNqelFQj7WYiVFNFQRBO8e04Cfb@ZN4MXTNcQJTGQavNn1o6l7@76Mz8fyKtl6qarKm1kqJ77nEzFueJiNl6OU28ZFDuH2KRlogLD4e0qgWEcBU8lCIFirEGqEBmGPcEBoEY4IGqFzySbQIVCdCbX/U2Jq1TqHpHJGOqeknBPxBw "Pari/GP – Try It Online") [Answer] # [PHP](https://php.net/), 131 bytes ``` function(&$a){for($a=array_chunk($a,3),$i=-1;$a[++$i];sort($a[$i]))!$a[$i][1]|$i%3?:array_splice($a,$i,0,[[array_shift($a[$i])]]);} ``` [Try it online!](https://tio.run/##jY7disIwEIXv@xQjjEuDEzDWn2osPkgIErpbGtQ2RCuIu89es3FXL/XuzDnzHY6rXb/euNolWBV91TXlybZN@oGGXavWp2gK4725bMu6a3bhpIwR2oILiUaNRmi1PLb@FBIVNGODu1BCf6MdZpvVHT@6vS2/fnm0NCal/uzaVg9WayZ/epkkGEIoQAmCCUFGMCWYEcwJFgQ5wVLLMDeF@MdkcjZ@@9kd3NN5VARsScAnkePz/6rgifdL8jiCiziB53EGf8n3Nw "PHP – Try It Online") This is a first take, it feels awfully long, there has to be a better way.. damn these "array\_" prefixes! ]
[Question] [ Ah, yet another of [my selfish uses of this Stack](https://codegolf.stackexchange.com/questions/115863/create-a-codeblock-tool). Being a Chromebook owner, I'm a frequent user of the Ace IDE, the editor used by Cloud9. It has lots of tools for dealing with excess whitespace, but it notably lacks one: clearing empty lines. Your mission today is, given an input from a place I can copy-paste to [`;)`], output something identical, save all spaces and tabulators on otherwise empty lines. I'll give some examples, with `#`s representing whitespace characters to be removed. --- ## INPUT 1: ``` if (this.Color !== 'blue') { ## this.Color = 'blue'; } ``` ## OUTPUT: ``` if (this.Color !== 'blue') { [empty line] this.Color = 'blue'; } ``` --- ## INPUT 2: ``` function outputSomething(times) { for (var iter = 0; iter < times; iter++) { console.log('"# # " represents a tabulator'); // This is a comment # # }} ``` ## OUTPUT: ``` function outputSomething(times) { for (var iter = 0; iter < times; iter++) { console.log('"# # " represents a tabulator'); // This is a comment [empty line] }} ``` --- ## INPUT 3: ``` var x = 'Do you prefer spaces or tabs?'; var y = 'I\'m using both here. Sue me.'; # # #### console.log(x + ' ' + y); ``` ## OUTPUT: ``` var x = 'Do you prefer spaces or tabs?'; var y = 'I\'m using both here. Sue me.'; [empty line] console.log(x + ' ' + y); ``` --- You may process the input however you like. Output wherever, so long as I can copy-paste from it [`;)`]. Standard loopholes apply, shortest answer in bytes wins! [Answer] # [Retina](https://github.com/m-ender/retina), 5 bytes ``` %G`\S ``` [Try it online!](https://tio.run/nexus/retina#FcoxCoNAEEbhWk/xN2ENwl5AxCYgqW0tsspEA@rIjCvu6Tfre@0XH@2n72I8neBCDfNiBPbYhb4k0N2NpGDB4QZtTJXfMNzw3ZsVXn/bhIGPGTMJWXSesJJNMMuQykfelBeyC0/FhRImXSI8qz8 "Retina – TIO Nexus") A not so obvious approach rewards us with a better score :) ### Explanation `G` indicates this as a Grep stage, keeping only those lines where a match to the regex given (`\S`, matches non-space characters) can be found. If it wasn't for the starting `%` this would completely remove lines instead of just "emptying" them. The `%` is a modifier which applies the stage once to each line and then joins the results with newlines: in our case this means that the empty string returned by Grep for whitespace-only lines will become an empty line in the result. [Answer] # [sed](https://www.gnu.org/software/sed/), 6 bytes ``` /\S/!g ``` [Try it online!](https://tio.run/nexus/sed#JcuxDoJAEATQWr5ihAIIiWePfgWWNidZYBPultzt2Ri@HRW6mcybzTw7cx63bUi@VxYPSbok7cSRTuzHStlRrPHJgEECqrcNYKWAO67tkW7Y0dGa5sBALz7KTJdZxqrMCxTIEWgJFMlrhIXaV5qtSijrdn8Yg8fEEfxfe3HuB7NTtq6Y@As "sed – TIO Nexus") ``` / /! # If the line doesn't contain... \S # anything non-whitespace (i.e. the entire line is whitespace) g # replace the pattern space with the hold space which is empty ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 8 6 5 4 bytes ``` mx1R ``` [Try it online!](https://tio.run/nexus/japt#@59bYRj0/79SZpqCRklGZrGec35OfpGCoq2tgnpSTmmquqZCNZeCAhAhycLkrEEytUoA "Japt – TIO Nexus") **Explanation** ``` (from the Japt docs) .m(f,s=""): Splits this with s, maps each item by f, then rejoins with s. ``` So `mx1R` splits the string by `R` which is a newline, trims the right hand side of each line using `x1` and joins the strings again with a newline. Saved 2 bytes thanks to ETHproductions. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~5~~, 4 bytes ``` ÇÓ/D ``` [Try it online!](https://tio.run/nexus/v#@3@4/fBkfZf//zPTFDRKMjKL9Zzzc/KLFBRtbRXUk3JKU9U1Faq5FBSACEkWJmfNVQsA "V – TIO Nexus") Explanation: ``` Ç " On every line not matching the following regex: Ó/ " a non-whitespace character... D " Delete the whole line ``` Hexdump: ``` 00000000: c7d3 2f44 ../D ``` [Answer] # JavaScript (ES6), 26 bytes I don't understand why this is getting so many upvotes! ``` s=>s.replace(/^\s+$/gm,``) ``` --- ## Try It ``` f= s=>s.replace(/^\s+$/gm,``) i.addEventListener("input",_=>o.innerText=f(i.value)) ``` ``` <textarea id=i></textarea><pre id=o> ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~63~~ ~~55~~ 36 bytes ``` lambda s:[x.strip()and x for x in s] ``` Input and output are arrays of strings. Join on `'\n'`. For the original program that I/O's strings: ``` lambda s:'\n'.join(x.strip()and x for x in s.split('\n')) ``` [Try it online!](https://tio.run/nexus/python3#HcrNCoMwEATgs28xeEmCJQ9QKb300nOP1kPU9Qc0CdlY9OltdAeWGfh8mGyU8pjN0nQGfK82zTFMXipjO2zoXUh/suD6ULLKf@bcD4iXw@5W@EA9BbA3LTESjqbhpyjz20X3k76/YsHKkx3QuDhipEAan5WwkL5oliFdKq2z7GbSsxvkhgIipcCuyrxW6vgD "Python 3 – TIO Nexus") *Saved 8 bytes thanks to @Rod!* *Saved 19 bytes thanks to @LeakyNun!* [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~18~~ 16 bytes ``` qN/{_" "-\e&N}% ``` Note that the string contains 1 space and 1 tab. [Try it online!](https://tio.run/nexus/cjam#JctBDoIwFATQtZxiUqJAiOIevQIbXZqYSj7QhPZj@3FDODsq7GYyb5Z3VUxPhZ06PuhQzftlaUZXi2EHHmUY5caWpDOuTcVYChmmCGjYI/1oDyPkccW53NIFK9panm8YqNkF7unUc5smKkYMBU@Dp0BOAjREv8ZeC/skK9dHUeDemQDzX2u29gejXTTPXw "CJam – TIO Nexus") **Explanation** ``` q e# Read the input N/ e# Split it on newlines { e# Apply this block to each line: _ e# Copy the line " "- e# Remove all spaces and tabs from the copy \ e# Bring the original to the top of the stack e& e# Logical AND; returns the original line if the copy is truthy e# (non-empty), otherwise returns the copy line N e# Push a newline after the line }% e# (end of block) ``` [Answer] # [Retina](https://github.com/m-ender/retina), 8 bytes ``` m`^\s+$ ``` A really pointless challenge. `m` makes it multiline (ignores newline). `\s` matches both space and tab. [Try it online!](https://tio.run/nexus/retina#FcpBCsIwEEbhdXOKfyFECeQCRdy4ce22iGkZW6HplJlGmtPH9L3tV@L71ak7mVJ@QbDjCntnZE5YhT4k0DUMpGDBFnq92dYcMB/w0dmIpN9lRM/bhImEPJ6JEMlX2DSomYEX5Zn8zON5h4OtO@RL@wc "Retina – TIO Nexus") [Answer] # Vim, ~~20~~ ~~18~~ ~~16~~ ~~13~~ 10 bytes I am by no means a Vim expert, but this question needs a Vim answer. `:%s/^\s*$<cr>` `<cr>` is a carriage return. Changelog: * `:norm` instead of `:normal` (-2 bytes) * Switching to `*` instead of `+` means we will match already empty lines, but that doesn't matter. And now we can get rid of `\v` (*very magic* option) (-2 bytes) * New approach: Instead of replacing every line that matches with an empty line, we replace every line that doesn't have a no non-whitespace characters with an empty line. (-3 bytes) * Actually, a normal replacement is shorter (thanks, @DJMcMayhem) (-3 bytes) [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~12~~ 11 bytes ``` !NF{$0=""}1 ``` [Try it online!](https://tio.run/nexus/awk#@6/o51atYmCrpFRr@P9/ZpqCRklGZrGec35OfpGCoq2tgnpSTmmquqZCNZeCAhAhycLkrLlqAQ "AWK – TIO Nexus") I was just feeling like AWK should have an answer too It works by: 1. Checking if there are no fields in the input. AWK by default uses all whitespace as separator between fields 2. If there are no fields, change the input line to an empty string 3. Print the line. As 1 is a truthy value, it runs the default command which is printing the line [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~11~~ 10 bytes ``` '\s+$'⎕R'' ``` `⎕R` is an operator which derives a function which replaces stuff. In this case, anything matched by the RegEx is replaced with an empty string. [Answer] # Ruby, 22 bytes ``` ->s{s.gsub /^\s+$/,''} ``` Straightforward regex solution [Answer] # Java 7, 57 bytes ``` String c(String s){return s.replaceAll("(?m)^\\s+$","");} ``` **Explanation:** ``` String c(String s){ // Method with String parameter and String return-type return s.replaceAll( // Return the input String after we've replaced "(?m)^\\s+$", // all lines only containing whitespaces ""); // with empty Strings // (NOTE: `(?m)` enables multiline regex) } // End of method ``` **Test code:** [Try it here.](https://tio.run/nexus/java-openjdk#nVFNSywxELz7K8pRmISR8d1HEdGLB0/r7UUhO2Z3A/kYko64LPPb93XceeDFizSEJFXpquqMTueM58MZkEmTHXFcUbJhi1EsmywPyVBJAblPZnJ6NPfOiUbcefmmVO4um6umkcN8BKaydtxjafUR7Tu8tmFp9fcVWlYpYLXPZHwfC/UTQ@SCGEVjNxC0s7l/iC4mnN/eol27YlqJgwpQxAu@Ef7DgwpzI@XwU@ufERbdlDCSjQF8PxVaRW9YImwFWW/ySRkbVhMfOsGSqbp/htPuBl@s06nrFjYwxpCjM72LW9Gq5gIXUA14fMlkEyhDg/S6OE0xtXI4Pbq@xguHg63wGL1nZkVq7vn3Aavtzzqrx4h9LGAPG7aeJ/7JDA7GTvJdHWJl7ivzSbUeJdfvX0faYWeS6bEqBt707WKXbXFBhe9hP9Gh5eqwl8NieT6bj/8A) ``` class M{ static String c(String s){return s.replaceAll("(?m)^\\s+$","");} public static void main(String[]a){ System.out.println(c("if (this.Color !== 'blue') {\n \t\n this.Color = 'blue';\n}")); System.out.println(); System.out.println(c("function outputSomething(times) {\n for (var iter = 0; iter < times; iter++) {\n console.log('\"# # \" represents a tabulator');\n // This is a comment\n \t\n}}")); System.out.println(); System.out.println(c("var x = 'Do you prefer spaces or tabs?';\nvar y = 'I\'m using both here. Sue me.';\n \t\t\t \nconsole.log(x + ' ' + y);")); } } ``` [Answer] # Groovy, 31 bytes ``` {it.replaceAll(/\n\s+\n/,"\n")} ``` [Answer] # [Perl 6](https://perl6.org), ~~15~~ 12 bytes ## 15 ``` {S:g/^^\h+$$//} ``` [Try it](https://tio.run/nexus/perl6#zVNBb5swGL37V7yGaIaQma6TdiBLE2m79NJOanoq7USIkzABRtiuGqX0r3efYcvSw7bLDuMA2H7f83vvs62WePggsgkrd3iTqZXE9GV/HW@i@/tkGw6HUdS@eMhU9SAbAyO1QZZqqZFXRkE@1jIzckWj2ppIWUMfRzXvkFPowja1HwhdF7nxIyTVDLcXl09XN4u7LzcLJHqEZDUCj3kUiE0ja382CkSZ1jHeniPpeMdIembsGeB3c3h@xg@d8Dk8/sQ9HoQIzsHBRyDle8xPHZO/h8i2aaOn0zPMZhgkZoCTE4dDG4hvKq/QRm0wduT9RkLbpTZ@vBljcCvL2uxQ5JW8S6oBzdA7CFjLmIeVXNoNzFb2CcQ01VnvHexFLZtC6HSHtWowH36lIkuRLwgyYXWRVgg7/ISxDtHFRsb9X9YPGQed/VzDtalPIRgfWsDal4tLF@m7mOVr@Gaba/FJFcR6Mp2CLwsruaPwPGI5Wv25NnGOqC/E8ReG40T@wNXLOYvZ2laZyVWFPtxrVUqqqTa@yUupe1vOvf@QNsiNdDynk/7vIzpQPwrDHgx3ILUqpCjUxucDDx4GoMPTSC0ro5HCpEtbpEY1PJh0FVGEBQl1@aVUXpYEZK6QtUe@/1@pr0JvD/G@j5mT8uii/6ywUxZEvSY5uk4zuqckljbQM@qJA@4c8CLhJawmX1gqs8VWNlLg2kqUUhDQifToYcfaHxF2VybEjnQeEvv3u79y@nsF3wE "Perl 6 – TIO Nexus") ``` { # bare block lambda with implicit parameter 「$_」 S # string replace (implicitly against 「$_」) :global # globally / ^^ # match beginning of line \h+ # match at least one horizontal whitespace $$ # match end of line // # replace with nothing } ``` --- ## 11+1 ``` perl6 -pe 's/^^\h+$$//' ``` Largely the same as above. * `-p` runs the code for every line of input, putting the line into `$_` and printing whatever is left in `$_`. * `s` replaces in-place, whereas `S` returns the result. * No need for `:g`/`:global` as `-p` takes care of that. [Answer] # [Python 2](https://docs.python.org/2/), 26 bytes ``` lambda l:map(str.rstrip,l) ``` [Try it online!](https://tio.run/nexus/python2#Hcq9CoMwHATwuW9xuCRB8QEq0qVL5461Q7RRA/nin6To09vUOzhu@M39cBhpx4@EuVoZeEzUUhkdGiOOQNolzFy7kBMX4nhVX0nY0IPdPXafEUjNihCDnFSEJyQ5xhvrquak@58@BmaRo3YLRp9WrIpUi2dWsKo96eWCknIm76I3qjV@4RtqsNIau@iq9w8 "Python 2 – TIO Nexus") Inputs and outputs a list of strings. This takes advantage of the ruling in the comments that trailing whitespace may be removed on non-empty lines. [Answer] # C, 168 bytes ``` #define P putchar(*t++) s;e(char*t){s=0;while(*t>10)if(*t!=32|*t!=9)return 0;else t++,s++;return s;} r(char*t){while(*t==10)P;if(!*t)return;if(!e(t))while(*t)P;t+=e(t);} ``` **Detailed** ``` #include <stdio.h> int e (char * t) { int s = 0; // till the end of the line while (*t!='\0' && *t!='\n') // if it's not a space if (*t!=' ' || *t!=' ') // ignore the line return 0; else // count the space t++, s++; // return number of spaces return s; } void r (char * t) { // skip to empty lines while (*t != '\0' && *t == '\n') putchar('\n'), t++; // stop at end of string if (*t == '\0') return; // if there is contnet print it if (!e(t)) while(*t != '\0') putchar(*t), t++; // skip to the end of line t += e(t); } int main (int argc, char**argv) { if (argc > 1) r(argv[1]); putchar('\n'); return 0; } ``` [Answer] ## C, 100 bytes ``` c,i,j;f(char*s){for(i=j=c=0;s[i];s[++j]^10?c=s[j]^32:(printf(!c?"\n":"%.*s",j-i+1,s+i),c=0,i=j+1));} ``` See it [work online](https://tio.run/nexus/c-gcc#bZBRa8IwEMefzac4C6OJ6Yq6N0Pow/ay5z2qg5qlNqU2JZeKUvzsLsW5OWgCyeX@9/tzl6tKTFKJgqoydzNkfWEdNbKSSs4Frs02HJxX28/FPFMS1yF6Wa5o60zjCzpVWbRpolX0lM4wSqpnwxcJcsOSgCfBhi8YE5frYA5eo19vQUJkCqC@NJi@2to6mEoJ8a7udMygD3YE/q0IYDT54HDnxUjhJeRAEEJ@m1jeujiG52lA3yycbQet04V2gG2uNEJw9fkOszHPG3se2PdNfIAOTbOHnfUllNrpFD46DQedjrM/95ikbIO21mlt9/QEHOKwOZyZuM8Qfh0OuWkoHK35AkZ6Mmk7j3SYiwkyKe4ReRCWf8oQksv1Gw). [Answer] # Vim, 13 9 bytes `:v/\S/le↵` **Edits:** * Original answer: `:v/\S/d↵` (based on this [vim question on SO](https://stackoverflow.com/questions/706076/vim-delete-blank-lines)). It deletes empty lines, which isn't the expected behavior. * Valid answer using [vglobal](http://vimdoc.sourceforge.net/htmldoc/repeat.html#:vglobal): `:v/\S/norm D↵` * Now using the [left-align](http://vimdoc.sourceforge.net/htmldoc/change.html#:left) ex command instead of `normal D` [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 5 bytes ``` \s+$ ``` [Try it online!](https://tio.run/##FcqxDoIwFEbh2T7FP5hU06QvQIyLi7MrS4ELmAAX76WEPn0t56zfL4ZOcq7VXU3OexAceMC@GIkjVqGeBLqGlhQs2EKjT1uZE6YTvms7I@p3GdDwNmIkIY9PJMzkC7ygXDItL8oT@YmH2wEHW3ZI9@oP "QuadR – Try It Online") `\s+` replace one or more whitespace chars followed by `$` end of line  with nothing ]
[Question] [ [Related](https://codegolf.stackexchange.com/questions/126172/create-a-binary-ruler), [related](https://codegolf.stackexchange.com/questions/71833/how-even-is-a-number) # Introduction The [ruler sequence](https://oeis.org/A001511) is the sequence of the largest possible numbers \$a\_n\$ such that \$2^{a\_n}\mid n\$. It is so-called because its pin plot looks similar to a ruler's markings: ![Pin plot of ruler sequence](https://oeis.org/A001511/graph?png=1) However, with a slight modification, we can also get a similar sequence. This sequence is \$\{a\_1,a\_2,a\_3,…\}\$ where \$a\_n\$ is the largest **power of 2** such that \$a\_n\mid n\$ ([relevant OEIS](http://oeis.org/A006519)). The first 100 terms of this sequence are: ``` 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 16, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 32, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 16, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 64, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 16, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 32, 1, 2, 1, 4 ``` # Challenge Your challenge is to do one of these three things: * Take a positive integer \$n\$ as input and return the \$n\$th term of this sequence. * Take a positive integer \$n\$ as input and return the first \$n\$ terms of this sequence. * Output the sequence infinitely. # Test Cases ``` 12 -> 4 64 -> 64 93 -> 1 8 -> 8 0 -> (undefined behavior) ``` # Rules * You may output the sequence in any convenient format - e.g. as a list or some other iterable or separated by any non-digit separator, as long as it is constant between all terms. * You may output the term(s) in any convenient format - e.g. as an integer, as an integer string, as a float with the decimal part consisting of only zeros, ditto but as a string, or as a Boolean (`True`) if and only if the term is `1`. * You may choose to use either zero- or one-indexing. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Trailing whitespace is allowed. * If possible, please link to an online interpreter (e.g. [TIO](https://tio.run)) to run your program on. * Please explain your answer. This is not necessary, but it makes it easier for others to understand. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] # [Python 2](https://docs.python.org/2/), 13 bytes Takes a positive integer \$ n \$ as input and returns the \$ n \$th term of the sequence. ``` lambda n:n&-n ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKk9NN@9/ooKtQrShjoKRjgKQNAGTELYFEhtZ3NAMhwQuDcZGJGog2QYzE1rbgOqHWC6utPwihUwdhQqFzDyF1LzS3NSixJJUjURNKy6FgqLMvBKFNI1MBW0FQ00FW1uFiv8A "Python 2 – Try It Online") The largest power of \$ 2 \$ that divides \$ n \$ is also the lowest set bit. The bitwise magic is a bit difficult to explain, but it uses the fact that `~n + 1` in its binary representation produces the same lowest set bit as `n`. ### [Python 2](https://docs.python.org/2/), 26 bytes Outputs the sequence infinitely. ``` n=1 while 1:print-n&n;n+=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8/WkKs8IzMnVcHQqqAoM69EN08tzzpP29bw/38A "Python 2 – Try It Online") ### [Python 2](https://docs.python.org/2/), 33 bytes Takes a positive integer \$ n \$ as input and returns the first \$ n \$ terms of the sequence. ``` f=lambda n:n*[0]and f(n-1)+[n&-n] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIc8qTyvaIDYxL0UhTSNP11BTOzpPTTcv9n@igq1CtKGOgpGOApA0AZMQtgUSG1nc0AyHBC4NxkYkaiDZBjMTWtuA6odYLq6Cosy8EmBYGhoYaCrY2iok/gcA "Python 2 – Try It Online") [Answer] # Regex (ECMAScript), 13 bytes ``` (x+?)(\1\1)*$ ``` [Try it online!](https://tio.run/##Tc@9UsJAFIbhW4kZh5xDTCCMWLAuVBY0FFoCxQ4ckqObzc7u8iM/rRfgJXojEQtmrJ/i@953tVN@5diGzFtek6sb80GfrZOG9tErlS8HC3CU4163hUM6QVgUiwK79223d8Q8NG/BsSkBc695RfD0kD0iCi/7Yl@xJgAtHam1ZkOAeCfNVms8lVLn3moOkGQJCt4AGFnmmkwZKhwPzmf2MzUDllY5T1MToJz3l4g3oP9gxsWkGP0xhso1@3hqdkrzOnLKlDSK4lSLTeNA8LMkwWmK18Faxoc4d2RJBWDMaxVWFTjEk@907DUqwF9HIew2@OCA0yT6@fqOkrSeF8vbVXG5tP1sMBz@Ag "JavaScript (SpiderMonkey) – Try It Online") Works by finding the smallest positive natural number that divides the input yielding an odd quotient. As such, this algorithm is generally applicable to any power of \$p\$, where \$p\$ is prime: find the smallest number that divides the input yielding a quotient that is not divisible by \$p\$. Takes its input in unary, as a sequence of `x` characters in which the length represents the number. The output is returned in capture group 1. ``` # No anchor needed, since every input N>=1 returns an output (x+?) # \1 = the smallest number >= 1 for which: (\1\1)*$ # \1 divides N and N / \1 is odd ``` Below is a demonstration showing how the algorithm above generalizes to other prime powers: Largest power of \$3\$ that divides \$n\$ (17 bytes): `(x+?)\1?(\1{3})*$` - [Try it online!](https://tio.run/##Tc@9UsJAFIbhW4kZh5xDTCDIWLAuVBY0FFoCxQ4ckqObzc7u8iM/rRfgJXojEQtmrJ/i@953tVN@5diGzFtek6sb80GfrZOG9tErlS8HC3CU4163hUM6wUUxgUVxerxg977t9o6Yh@YtODYlYO41rwieHrIhovCyL/YVawLQ0pFaazYEiHfSbLXGUyl17q3mAEmWoOANgJFlrsmUocLx4HxmP1MzYGmV8zQ1Acp5f4l4A/oPZlxMitEfY6hcs4@nZqc0ryOnTEmjKE612DQOBD9LEpymeB2sZXyIc0eWVADGvFZhVYFDPPlOx16jAvx1FMJugw8OOE2in6/vKEnrebG8XRWXS9vPBsPBLw "JavaScript (SpiderMonkey) – Try It Online") Largest power of \$5\$ that divides \$n\$ (21 bytes): `(x+?)\1{0,3}(\1{5})*$` - [Try it online!](https://tio.run/##TY87csIwFEW34ngy@D2MjU0IBYqgSkFDkZSEQgPCfoksayTxCeA2C2CJ2YgDBTOpbnGKe86n2Am3smR84gytpa1q/SW/W8u13Advsng9GIAjn/S7LRziKX7kp6z31MB1nxvsPrbd/hFTX797S7oATJ2ilYRRLxkiMsczti9JSQDFrRRrRVoC4gPXW6XwVHCVOqPIQ5REyGgDoHmRKqkLX@JkcD6Tm4s5EDfCOjnTHopFtkS8A/kf6Ek@zcc3jL609T6c6Z1QtA6s0IUcB2Gs2Ka2wOiFS0ZxjNfDioeHMLXSSOGBMK2EX5VgEU@u0zHXKA@3jpyZrXfeAsVR8PtzCaK4WuTLuyprmjZLRoPhHw "JavaScript (SpiderMonkey) – Try It Online") Largest power of \$17\$ that divides \$n\$ (23 bytes): `(x+?)\1{0,15}(\1{17})*$` - [Try it online!](https://tio.run/##TY@9bsIwFEZfJY0qci8hIalaqHANUwcWhnakDBaY5LaOY9nmp0BWHqCP2BdJYUDq9kln@M75FFvhlpaMT5yhlbRVrb/kd2u5lrvgTRavewNw4ON@t4V9PMGP/Jj18qcGLiMfNti9b7v9A6a@fveWdAGYOkVLCYNe8ojIHM/YriQlARS3UqwUaQmId1xvlMJjwVXqjCIPURIhozWA5kWqpC58ieOH04ncTMyAuBHWyan2UMyzBeINyP9Aj/NJPrpi9KWtd@FUb4WiVWCFLuQoCGPF1rUFRi9cMopjvBxWPNyHqZVGCg@EaSX8sgSLeHSdjrlEebh25MxsvPMWKI6C3/NPEMXVPF/cVFnTtFnyPBj@AQ "JavaScript (SpiderMonkey) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 19 bytes ``` l=1:do x<-l;[2*x,1] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P8fW0ColX6HCRjfHOtpIq0LHMPZ/bmJmnoKtQkFRZl6JgopCSWJ2qoKRAZCV8/9fclpOYnrxf93kggIA "Haskell – Try It Online") Generates an infinite list. This list is defined recursively using the property that the list is unchanged if we double each value and intersperse 1's at every other position including at the start. So, we start the list with a `1`, then iterate through the list itself, each time producing the doubled number followed by a `1`. Haskell's laziness allows this kind of self-reference. ``` 1 <- initial value 2 \ 1 doubled 1 / 4 \ 2 doubled 1 / 2 \ 1 doubled 1 / 8 \ 4 doubled 1 / 2 \ 1 doubled 1 / ... ``` --- # [Haskell](https://www.haskell.org/), 10 bytes ``` gcd=<<(2^) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPz05xdbGRsMoTvN/bmJmnoKtQkFRZl6JgopCbmKBQppCtKGenpFB7P9/yWk5ienF/3WTCwoA "Haskell – Try It Online") Outputs the n'th term. Equivalent to `f n=gcd n(2^n)`. We take the greatest common divisor of `n` and a large power of 2. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` LoÖOo ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fJ//wNP/8//8tzQA "05AB1E – Try It Online") Takes \$n\$ as input, outputs the \$n\$th term ## How it works ``` LoÖOo - Full program. Input n L - Range from 1 to n o - Raise 2 to the power of each Ö - Yield 1 if divisible by n, for each O - Sum, counting the 1s o - Raise 2 to the power ``` --- # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` (& ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fQ@3/f0szAA "05AB1E – Try It Online") Boring bitwise solution. Calculates the bitwise AND of \$n\$ and \$-n\$ [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` N& ``` [Try it online!](https://tio.run/##y0rNyan8/99P7b@hgYH14XaVR01r3P8DAA "Jelly – Try It Online") Takes \$n\$ as input, outputs the \$n\$th term ## How it works Uses [dinglelooper’s observation](https://codegolf.stackexchange.com/a/220527/66833) [Answer] # [JavaScript (V8)](https://v8.dev/), 18 bytes ``` f=n=>n&1||2*f(n/2) ``` [Try it online!](https://tio.run/##NYrLCoMwEADvfsWe6qb2pSAU0vRHSg8ihq7IJmRXT/57moungZmZh22QMVHU6/bM2Tt2bz61@96dPfK9M3kMLAppknVRAQefr618SIDLpEBFtLbgBf2jsGnMsd7iKj/0SMbYKiZixaPMgRjrC9Ql5T8 "JavaScript (V8) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/) x86, 14 bytes Takes a positive integer \$n\$ as input and returns the \$n\$th term of the sequence. ``` f(n){n&=-*&n;} ``` [Try it online!](https://tio.run/##xZCxDoIwEIZ3nuJCAilyxBSJMWLjg6iDwdZ0sBBgMBJWH0Dj5tP5IngqYFxcHOzQP/16@XP5kmCbJE2jmPEq44pg4Jq4bnZrbZgHlQV0tClB7jOZlHKzWIGAimOIHCN85QQ/33yM3wdGIf7YMI7w3zvU8VOOSnNgD0OaxPCYYiag0AeZKtZJ84YtGPSEBn2/E9xJLqhCMe3FH1QS7fXrgK/e31lOA4rZTgHOBm7HE8XS2AiFEHJu365ne0r3hYgm2BbXVt3cAQ "C (gcc) – Try It Online") ``` f(n){*&n&=-n;} ``` [Try it online!](https://tio.run/##xZCxDoIwEIZ3nuJCAilyxBSJMWLjg6iDwdZ0sBBgMBJWH0Dj5tP5IngqYFxcHOzQP/16@XP5kmCbJE2jmPGqgWtcEZi4bnZrbZgHlQV0tClB7jOZlHKzWIGAimOIHCN85QQ/33yM3wdGIf7YMI7w3zvU8VOOSnNgD0OaxPCYYiag0AeZKtZJ84YtGPSEBn2/E9xJLqhCMe3FH1QS7fXrgK/e31lOA4rZTgHOBm7HE8XS2AiFEHJu365ne0r3hYgm2BbXVt3cAQ "C (gcc) – Try It Online") Same bitwise formula as used [ChartZ Belatedly](https://codegolf.stackexchange.com/a/220522/17216), [dingledooper](https://codegolf.stackexchange.com/a/220527/17216), and many more. Thanks to [Noodle9](https://codegolf.stackexchange.com/a/220550/17216) for the nice idea of showing ✓ or ✕ in the TIO code depending on correctness; I haven't done that before, but might use it some more in the future. Uses the very common code golf hack of avoiding the non-golfy `return` keyword (by taking advantage of the fact that results to most calculations get stored in the accumulator, the same register that is used for return values), but without resorting to use of global variables or fake function parameters. This is done by taking the address of `n` and then dereferencing that address. This of course requires the default optimization level `-O0`. Using `-O1` will break gcc `return` avoidance hacks (and in clang, they don't even work at `-O0`). In 32-bit x86, this compiles to the following (`[ebp+0x8]` is the `n` parameter): ``` mov eax,DWORD PTR [ebp+0x8] neg eax mov edx,eax mov eax,DWORD PTR [ebp+0x8] and eax,edx mov DWORD PTR [ebp+0x8],eax ``` Whereas `f(n){n&=-n;}` doesn't work because it compiles to the following, which acts like `f(n){return-n;}`: ``` mov eax,DWORD PTR [ebp+0x8] neg eax and DWORD PTR [ebp+0x8],eax ``` An essentially equivalent result occurs in x86-64 and MSP430. # [C (gcc)](https://gcc.gnu.org/) - many other platforms, 12 bytes ``` f(n){n&=-n;} ``` On many architectures other than x86, this actually works: [ARM64 gcc 10.2](https://godbolt.org/z/8xdcav) [ARM gcc 10.2.1](https://godbolt.org/z/KahGEK) [KVX gcc 7.5 (ACB 4.1.0-cd1)](https://godbolt.org/z/6P441M) [MIPS64 gcc 5.4](https://godbolt.org/z/z57arq) [MIPS gcc 5.4](https://godbolt.org/z/ebY7n6) [PowerPC64 AT13.0 (gcc9)](https://godbolt.org/z/x3jrEz) [RISC-V rv64gc gcc 10.2.0](https://godbolt.org/z/EKzGEG) [AVR gcc 5.4.0](https://godbolt.org/z/joGo8x) This is case in point for why I hate the gcc `return` avoidance hack so much. It's not merely reliant on `-O0`, and not only uses undefined behavior in general, but it's not even portable within different architecture targets of `gcc` itself. Here it is failing to work as desired on x86 and MSP430, contrasted with the `*&` forcing it to work: [x86-64 gcc 10.2](https://godbolt.org/z/v6zrWb) [x86-32 gcc 10.2](https://godbolt.org/z/asYenx) [x86-32 gcc 5.4](https://godbolt.org/z/W5WWe4) [MSP430 gcc 6.2.1](https://godbolt.org/z/o3b5d5) There is no guarantee that the same undefined behaviors will still behave the same way in future versions of gcc (and/or the toolset) even on the same architecture. This is why I prefer to post "C (clang)" or "C (gcc `-O1`)" answers instead of "C (gcc)". If the fragile undefined behavior hacks work, you have to use them in "C (gcc)" answers to stay competitive with other "C (gcc)" answers. In any case, people posting answers that use this hack should probably call the language "C (gcc) x86" instead of "C (gcc)". # [C (gcc)](https://gcc.gnu.org/), 37 bytes Outputs the sequence infinitely. ``` main(n){for(;;)printf("%d ",-n&n++);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI0@zOi2/SMPaWrOgKDOvJE1DSTWFU0lHN08tT1tb07r2/38A "C (gcc) – Try It Online") Saves 1 byte by using tab (which can be used literally) instead of newline (which would require `\n`). Takes another shortcut by using the first parameter of `main()`, the command line argument count, which is 1 when there are no command line arguments (because the pathname of the executable is treated as the first argument, at index 0). # [C (gcc)](https://gcc.gnu.org/), 52 bytes Takes a positive integer \$n\$ as input and outputs the first \$n\$ terms of the sequence. ``` main(n){for(scanf("%d",&n);n;)printf("%d ",-n&n--);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI0@zOi2/SKM4OTEvTUNJNUVJRy1P0zrPWrOgKDOvBCzEqaSjm6eWp6uraV37/7@hgQEA "C (gcc) – Try It Online") Abuses a loophole by printing the first \$n\$ terms in descending instead of ascending order. Without this, it would be **~~57~~ 56 bytes**: ``` main(i,n){for(scanf("%d",&n);n--;)printf("%d ",-i&i++);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1MnT7M6Lb9Iozg5MS9NQ0k1RUlHLU/TOk9X11qzoCgzrwQsyKmko5uplqmtrWld@/@/oYEBAA "C (gcc) – Try It Online") # [C (gcc)](https://gcc.gnu.org/), 53 bytes Takes a positive integer \$n\$ as input and returns the first \$n\$ terms of the sequence. ``` f(n){int*m=malloc(n*4);for(;n;)m[n]=-n&n--;n=(int)m;} ``` [Try it online!](https://tio.run/##rZDBSsQwEIbvPsVQWEm6KdK1LGIMPkjtYckmEthMlqaCWHr1ARRvPt2@SB3bbaEXL2sOM8mXf4aZX2fPWve9Zchbh03qld8dDkEzTAsubaiZRMl9iZXK8BqzTKJiJORedr3fOWQc2iugQxDM69HoxuzLChS0udiIXBRizHdi@c634m/B7UZc2GFbiH@boZPDljpgbIZddXihqCC6NxMsm1bncDOhdGZydij1VGLZUHzGZDL8WgqOvnJJ6UGN3em@Xk/@Th0iqXzpsrySC26Iz/4vv481CSxLVhFWezi9f1B6wkRAVMo8Jqfvz@Se4hcRR/A8VzdOVxvDPKGu/wE "C (gcc) – Try It Online") `4` is `sizeof(int)`. `m[n]=-n&n--;` works because by the time `m[n]` evaluates, `n` has already been decremented; it's equivalent to `m[n-1]=-n&n;--n;`. The array returned is allocated by this function, and must be `free()`ed after use. [Answer] # [Octave](https://www.gnu.org/software/octave/) / MATLAB, ~~28~~ 23 bytes *5 bytes off thanks to [@Giuseppe!](https://codegolf.stackexchange.com/users/67312/giuseppe)* ``` @(n)2^sum(factor(n)==2) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI0/TKK64NFcjLTG5JL8IyLW1NdL8X5JaXKJgq2BoZWhgYM2VWFSUWJlWmqeRpqMAktHUU/8PAA "Octave – Try It Online") ### Explanation ``` @(n) % Define anonymous function of n factor(n) % Vector of prime factors of n, possibly repeated ==2 % Compare each element with 2. Gives 1 (true) or 0 (false) sum( ) % Sum 2^ % 2 raised to that ``` [Answer] # [J](http://jsoftware.com/), 6 4 bytes ``` AND- ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Hf1cdP9rcvk56SkY6igY6YBIEx0E2wKJbcLFlZqcka@QpqStYKidqWdo8B8A "J – Try It Online") -2 thanks to FrownyFrog Just because expressing [dingledooper's idea](https://codegolf.stackexchange.com/a/220527/15469) in J is nice.... * `...-` The whole thing is a J hook, so that the verb `...` will receive the input and its negative as the left and right argument. * `AND` Elementwise "and" on the bits. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 19 bytes ``` param($n)$n-band-$n ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPUyVPNykxL0VXJe/////GAA "PowerShell – Try It Online") It does: * Take a positive integer \$n\$ as input and return the \$n\$th term of this sequence. Thanks to @xnor [Answer] # [Scala](http://www.scala-lang.org/), 8 bytes ``` n=>n& -n ``` [Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFBQzVWWmKOQZqXgmVeiYGsHof7n2drlqSno5v0vKMrMK9EwVCjJVzAyUMhNLFBI0@Sq/Q8A "Scala – Try It Online") dingledooper's idea works also in Scala [Answer] # [R](https://www.r-project.org/), ~~34~~ ~~33~~ 32 bytes *Edit: -1 byte thanks to Giuseppe* ``` function(n,t=2^(n:0))t[!n%%t][1] ``` [Try it online!](https://tio.run/##K/qfU5BfUpKSZ/s/rTQvuSQzP08jT6fE1ihOI8/KQFOzJFoxT1W1JDbaMPa/skJaZlFxiYKhgYFCSWpRbrEVV3FiQUFOpYahFVBMB2qS5n8A "R – Try It Online") Constructs a series `t` of powers of 2 in reverse (`t=2^(n:0)`), then gets the first element (`[1]`) for which n MOD t is zero (`[!n%%t]`). This works *in principle* for any `n`, but is limited by floating-point accuracy and - more obviously - calculation time and memory. A faster and less memory-hungry (but 7 byte longer) version using the same approach would be: `function(n,t=2^(0:log2(n)))max(t[!n%%t])` ([try it](https://tio.run/##NYxBCoMwEADvecUWEXaph5jeAr6kVAg1akA3IVmhfX1air0OM5PrlqLIxEOdD35KiIzcyWBG1HaLi0Emot29UO4Xblt5UG1gDrkI9FqD@LwXq4pLaXtjb7@sO4@kVAOyekAz3szVkKw/HTAeUsLkIbD4xWfIjhdPVp3h368f)). --- # [R](https://www.r-project.org/), 34 bytes ``` f=function(n)`if`(n%%2,1,2*f(n/2)) ``` [Try it online!](https://tio.run/##NYxBCsMgEADvvmIhBHZbodHehHwlJDSaCukqujn09baU9DrMTGl7TiIrjy2M4eCHxMTINMcwI/e91UbbS0C@WaLWQYilCphhAPHlVZ2qS877G437Mn2@SKkO0E53e7Ukz58KmA6pcfUQWfzmC5SFN09OndHfbx8 "R – Try It Online") An alternative recursive approach (ported from [user81655's answer](https://codegolf.stackexchange.com/a/220525/95126)) is 1 byte longer, but runs significantly faster and so can actually be tested for very large numbers. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 11 bytes ``` GCD[2^#,#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277393ZJdooTllHOVbtf0BRZl6Jgr5Dur5DUGJeemq0oYFB7P//AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 6 bytes ``` ÝoʒÖ}θ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8Nz8U5MOT6s9t@P/fzMA "05AB1E – Try It Online") Turns out I'm way too used to Vyxal. -2 thanks to Makonede ## Explained ``` ÝoʒÖ}θ Ýo # 2 ** range(0, input) // vectorised ʒÖ} # filter(lambda x: x % input == 0, ^) θ # ^[-1] ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 2 bytes ``` N⍲ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=N%E2%8D%B2&inputs=5&header=&footer=) Just a port of the bitwise stuff. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 7 bytes ``` n=>n&-n ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i5PTTfvf6KCrUK0oY6CkY4CkDQBkxC2BRIbWdzQDIcELg3GRiRqINkGMxNa24Dqh1gurrT8IgWNTFsDa4VMm0S9nNS89JIMIFtbW5NLITk/rzg/J1UvJz9dI00jU0FbwVBTwdZWITE6M1bzPwA "JavaScript (Node.js) – Try It Online") dingledooper's solution (for Python) adapted to JavaScript. [Answer] # [Java (JDK)](http://jdk.java.net/), 7 bytes ``` n->n&-n ``` [Try it online!](https://tio.run/##tVGxasNADN3vKzQVG8dHnYZQcF3o2KlDKBRCBtWxXbln@biTU0Lwt7vXtENayJChi3hPepKQXos7TNvt@0Sd7Z1AG7gehIyuBy6FetaPLM@Mbv9kK4fSu1yVBr2HFzgoAC8oVMJfEdTFxOk9X6U85UrZ4dUE1Y9419MWOiSOVuKIm/UG0DU@DgOJ5YtBAVx9wJEdshnMZxDi4hi/8e0JPs1nyzOFcw038wsbLt6wXPz3ht83jOHhdbAgCu8DKq5zoDvUpuJG3gJOkljBau@l6nQ/iLbBAjEc1RqtNfsHH7yMCBLIYigKwDVt4lyNapw@AQ "Java (JDK) – Try It Online") dingledooper's solution (for Python) adapted to Java [Answer] # [R](https://www.r-project.org/), 24 bytes ``` function(n)bitwAnd(n,-n) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jTzMps6TcMS9FI09HN0/zv7JCWmZRcYmCoZG5QklqUW6xFVdxYkFBTqWGoRVQTCdN8z8A "R – Try It Online") While it's good to have a variety of answers using different techniques, the actual shortest in each language should be represented too. As is the case in most languages, I think the bitwise hack is the shortest here. [Answer] # [Groovy](http://groovy-lang.org/), 8 bytes ``` {it&-it} ``` [Try it online!](https://tio.run/##Sy/Kzy@r/J@SmqaQZvu/OrNETTezpBbMT1SwVYg21FEw0lEAkiZgEsK2QGIjixua4ZDApcHYiEQNJNtgZkJrG1D9EMvFlZZfpKCRmVeikGlrYK2QaZOoV5xZlaqhCWRra2tyKRQUASVz8jTSNDIVtBUMNRVsbRUSozNjNf8DAA "Groovy – Try It Online") dingledooper's Python solution, translated to Groovy [Answer] # [Julia](http://julialang.org/), 18 bytes (recursive approach) ``` !n=n%2>0||2*!(n/2) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/XzHPNk/VyM6gpsZIS1EjT99I839BUWZeSU6enoahlaGBgYKerZ2CniKEo6n5HwA "Julia 1.0 – Try It Online") # [Julia](http://julialang.org/), 7 bytes (bitwise approach) ``` n->n&-n ``` [Try it online!](https://tio.run/##yyrNyUw0rPifZvs/T9cuT003739BUWZeSU6enoahlaGBgYKerZ1CGpSjqfkfAA "Julia 1.0 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 15 bytes ``` a;f(n){a=n&-n;} ``` [Try it online!](https://tio.run/##tVFNj4IwEL3zKyYkGpCSCH7ETZe9GH@FcGhKccm6s4aaSEL461tHQIWDBw426WQ@3ut05kn/IKUxgmcOupWIcOojr82vyNFxrcoCOjmeQZUnJc8q3ScQQRUwCBmQXTa29Tc9v58P1i8KrwiLcCRhdIf18t0dhjPUvFmk/BbFjKySP6poN2nH5S6My48t3ZXNoB8v7I6X/RXg3FTIMVUl0ea8cz8hmFPgeU3oQivYXTQkaIvzIOCDkqbSTfJhVlH2oXTDTJ6AU0GQzLEnKfhfQHaiY6QvIwPNHlPpKFJJ92xt1eZfZkdx0Ma/XAE "C (gcc) – Try It Online") Inputs a positive integer \$n\$ and returns \$2^a\$ which is the largest power of \$2\$ such that \$2^a\mid n\$. [Answer] # [Japt](https://github.com/ETHproductions/japt), 3 bytes `U` is the first input, same bitwise approach as many other answers already covered. ``` &-U ``` [Try it out here.](https://ethproductions.github.io/japt/?v=1.4.6&code=Ji1V&input=MjA=) [Answer] # [Perl 5](https://www.perl.org/), 15 bytes ``` sub($n){$n&-$n} ``` [Try it online!](https://tio.run/##tY9BDoIwEEX3nGKCE2gDJKJIjNjoBTyBusCkNY2mJS2sCFe3Im5wwYKFmz8vM/PnZypunhuHgjnb3Agq2qIKElSdK7xjCQxIGsMqhl6zQb@8HfG4n@YTgynDejXTMDshz/6d8PsDLTxPaAMEJVsWgHKPi/JTo4hC60FlpKpJgKJfgAhSCowBlmeUVzhAqB8h7CDkxmgTxv5F@f3Bzr10VUutrEtOgpd1Y3hk5V0NZN8 "Perl 5 – Try It Online") dingledooper's Python solution, translated to Perl 5 [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 72 bytes ``` N =INPUT X =1 I J =N / X X =X * 2 EQ(REMDR(J,2)) :S(I) OUTPUT =X END ``` [Try it online!](https://tio.run/##K87LT8rPMfn/n9NPwdbTLyA0hIszQsHWkMuT00vB1k9BXyECLBChoKVgxOkaqBHk6usSpOGlY6SpyWkVrOGpycXpHxoC1AdUw@Xq5/L/v6ERAA "SNOBOL4 (CSNOBOL4) – Try It Online") ``` N =INPUT ;* read input X =1 ;* set X =1 I J =N / X ;* set J to N / X X =X * 2 EQ(REMDR(J,2)) :S(I) ;* If J is divisible by 2, double X and goto I, else OUTPUT =X ;* print X and exit END ``` [Answer] # [Factor](https://factorcode.org/), 14 bytes ``` [ dup 2^ gcd ] ``` [Try it online!](https://tio.run/##Hci9CsIwFAbQ3af43GOhP0hVcBWXLuIkCiG91dL2Nt7cDCI@exSXM5zOOp0lnU/H5rDFQMI0wgupvrz0rAj0jMSOAiarjz9ZF9lpP3PAbvFGXmBdYVOixgdLrPaozG8McoM6XdBGj@KGu2txTZP1yOBGspK@ "Factor – Try It Online") [J42161217's](https://codegolf.stackexchange.com/a/220573/78410) and [xnor's](https://codegolf.stackexchange.com/a/220539/78410) approach: GCD with a large power of 2. # [Factor](https://factorcode.org/), 18 bytes ``` [ dup neg bitand ] ``` [Try it online!](https://tio.run/##HcixCsIwEAbg3af43WOhWqQquEoXF3ESh5heNdhe08tlEPHZo7h8w9dZp6Pk86k5HrZ4kjD1CEKqryCeFZGmROwoYrD6@FN0iZ36kSN2szfKJdYVNivU@GCOxR6V@Y1BaVDnC9oUwHTHzavlFtc82IACricr@Qs "Factor – Try It Online") Bitwise approach already done by many different answers. # [Factor](https://factorcode.org/), 18 bytes ``` [ factor-2s . 2^ ] ``` [Try it online!](https://tio.run/##HY0xC8IwFAZ3f8XnnhYai1SFruLiIk6iEMILFtvX@PI6iPjbY@lyHLdccF5HydfL6Xzc40XC1CMKqX6idKxI9J6IPSUMTp8LyjCx127khMPqi8piW2O3QYMf1iha1GYuBpVBk28Iy6KwCSXsA/c8uDir78lJ/gM "Factor – Try It Online") There's a built-in that is supposed to do most of the job: `factor-2s`, which takes a positive integer `n` and returns `[ exponent-of-2 odd-part ]` on the stack. Unfortunately the power of 2 is the secondary return value (so you need to discard the top with `.`) and it is the exponent (not the power of 2 itself) so `2^` is needed. [Answer] # [Factor](https://factorcode.org/), ~~56~~ ~~50~~ 46 bytes * Saved 6 bytes thanks to @Bubbler! * Saved 4 bytes thanks to @chunes! ``` [ 2 over [0,b] n^v [ 2 * mod 0 > ] with find ] ``` [Try it online!](https://tio.run/##LY07C8IwGEV3f8WdRULq@wGu4uIiTqVCbL9o0H6paVoR8bfHVLpcOGc4V6vcWxdOx/1ht8adHNMDlSPv35Uz7FHTsyHOqUap/O0/wim@9kLohnNvLPfYUtersRl8kGCMCaaYYY4FllghkfgipNHblhxSObpk4HOLTg1R2gISW2R4mfilDRfIQgxXEOEH "Factor – Try It Online") # [Factor](https://factorcode.org/), 53 bytes ``` [ 0.5 [ [ 2 / ] [ 2 * ] bi* over dup floor = ] loop ] ``` [Try it online!](https://tio.run/##HYixCgIxEAV7v@LVV0QRtFCsxcbmsDquiHGDwZiNm43g18dwDLx5jLdOWdptvFzPB7xIEkVkIdVflpAUhT6VkqOCt9XnMsbX5DRwKjiu9m3CxuwwdbZYY148dN/DAP6S4FEzfGQWnHruJ2NucDZGmPYH "Factor – Try It Online") [Answer] # Excel, ~~29~~ 24 bytes *-5 bytes thanks to @TaylorScott* A port of [Dingledooper's answer](https://codegolf.stackexchange.com/a/220527/101349) to Excel. ``` =BITAND(2^47+A1,2^47-A1) ``` ## Original much worse answers, 29 bytes ``` [A2]=2^47+A1*{1;-1} [A4]=BITAND(A2,A3) ``` Had to use 2 cells because `BITAND` requires 2 arguments. The formula in A2 spills to A3. Works up to 2^47 - 1. Can save a byte changing 2^47 to 8^9. This lowers the range to 2^27-1. ## Excel (one cell), 35 bytes ``` =2^SUM(1*(MOD(A1,2^(ROW(1:47)))=0)) ``` This is what I came up with on my own. Works up to 2^41. [Try them online](https://1drv.ms/x/s!AkqhtBc2XEHJm32SpsepsFNWTPjw?e=ai5tmg) [Answer] # Scala, 43 bytes ``` n=>Stream.iterate(1)(_*2).find(n%_>0).get/2 ``` [Try it in Scastie!](https://scastie.scala-lang.org/d5Bu24wuSeCvmvdyIJqN8g) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` o¿ ``` [Try it online!](https://tio.run/##ASoA1f9vc2FiaWX/fHZ5w5A/4oCm4oaSw7Auw7g//2/Cv/8s/zEyCjY0CjkzCjg "05AB1E – Try It Online") ``` o¿ # full program ¿ # greatest common divisor of... # implicit input... ¿ # and... o # 2 to the power of... # implicit input # implicit output ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 bytes Nth Term ``` {2*(⊥⍨~)2⊥⍣¯1⊢⍵} 2* ⍝ exponentiation ⊥⍨~ ⍝ number of trailing zeros 2⊥⍣¯1⊢ ⍝ bit vector conversion ⍵ ⍝ argument ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqIy2NR11LH/WuqNM0AjMWH1pv@Khr0aPerbVAJQqGRlxpCmYmQMLSGEhYALEBAA "APL (Dyalog Unicode) – Try It Online") --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), 21 bytes First N Terms ``` {2*(⊥⍨~)∘(2⊥⍣¯1⊢)¨⍳⍵} 2* ⍝ exponentiation ⊥⍨~ ⍝ number of trailing zeros ∘ ⍝ curry 2⊥⍣¯1⊢ ⍝ bit vector conversion ¨ ⍝ each ⍳⍵ ⍝ range of 1–n ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqIy2NR11LH/WuqNN81DFDwwjMWXxoveGjrkWah1Y86t38qHdrLVCxgqERV5qCmQmQsDQGEhZAbAAA "APL (Dyalog Unicode) – Try It Online") ]
[Question] [ ### Task Given two lists of characters, output their Cartesian product, i.e. the list of pairings of each letter from the first list with each letter from the second list. ### Example `"123456"` and `"abcd"` give: ``` [["1","a"],["1","b"],["1","c"],["1","d"],["2","a"],["2","b"],["2","c"],["2","d"],["3","a"],["3","b"],["3","c"],["3","d"],["4","a"],["4","b"],["4","c"],["4","d"],["5","a"],["5","b"],["5","c"],["5","d"],["6","a"],["6","b"],["6","c"],["6","d"]] ``` ### Input Two lists of characters or strings. The characters used will be alphanumeric `a-z, A-Z, 0-9` and a character can occur both multiple times and in both inputs at the same time. ### Output The Cartesian product of the input lists. That is, a list of each possible ordered pair of a character from the first list and a character from the second list. Each pair is a list or string or similar of two characters, or of two length-one strings. The output's length will be equal to the product of the lengths of the inputs. The pairs must be listed in order; first listing the first character of the first list with the first of the second list, followed by all the pairings of the first character of the first list. The last pair consists of the last character of the first list together with the last character of the second list. The output must be a flat list of pairs; not a 2D matrix where pairs are grouped by their first or second element. ### Test cases ``` inputs output "123456", "abcd" [["1","a"],["1","b"],["1","c"],["1","d"],["2","a"],["2","b"],["2","c"],["2","d"],["3","a"],["3","b"],["3","c"],["3","d"],["4","a"],["4","b"],["4","c"],["4","d"],["5","a"],["5","b"],["5","c"],["5","d"],["6","a"],["6","b"],["6","c"],["6","d"]] "abc", "123" [["a","1"],["a","2"],["a","3"],["b","1"],["b","2"],["b","3"],["c","1"],["c","2"],["c","3"]] "aa", "aba" [["a","a"],["a","b"],["a","a"],["a","a"],["a","b"],["a","a"]] ``` [Answer] # [Haskell](https://www.haskell.org/), 12 bytes ``` (<*>).map(,) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P81Ww0bLTlMvN7FAQ0fzf25iZp5tQVFmXomCRpqCUmJSspKCkqGRsZLmfwA "Haskell – Try It Online") [Answer] # Mathematica, 12 bytes ``` Tuples@{##}& ``` Takes two lists of characters as input. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte ``` â ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8KL//6MNdRSMdBSMdRRMdBRMY7milRKVdBSUkkBEMohIARGpSrEA "05AB1E – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 4 bytes ``` ,∘., ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wSdRx0z9HT@ZxXn5wF55oZmBo96toG5CuqGRsYmpmbqCmkK6olJySnqXBBhIBssBpSGCyVCVSWqAwA "APL (Dyalog Unicode) – Try It Online") `,` flatten `∘.` the Cartesian `,` concatenation [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 byte ``` p ``` [Try it online!](https://tio.run/##y0rNyan8/7/g/6OGOYZGxiamZo8a5h5eDuQlJiWnANmR/wE "Jelly – Try It Online") [Answer] # Octave, 32 bytes ``` @(a,b)[(a+~b')(:) (b'+~a)(:) ''] ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQSNRJ0kzWiNRuy5JXVPDSlNBI0lduy4RzFRXj/2fmFesoWRoZGxiaqako6CUmJScoqT5HwA "Octave – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~30~~ 18 bytes -12 bytes from Jordan reminding me of a way to use the spec to my advantage! Takes lists of characters as input. ``` ->a,b{a.product b} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9cuUSepOlGvoCg/pTS5RCGp9n@BQppecmJOjoKWY5B7mF5uYoGGmlVyRmJRseb//xmpOTn5/8vzi3JSAA "Ruby – Try It Online") [Answer] # [Perl 6](http://perl6.org/), 4 bytes ``` &[X] ``` This is just a reference to the built-in cross product operator `X`. It works on lists of any sort, not just characters. [Answer] # J, 3 bytes ``` ,@{ ``` This is the [Catalogue verb](http://code.jsoftware.com/wiki/Vocabulary/curlylf) in J. We need to Ravel (`,`) the result to make it 1 dimensional. [Try it online!](https://tio.run/##y/r/PzU5I19Bx6FaQT0xKVndWt3QyFj9/38A "J – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` {∋ᵐ}ᶠ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/pRR/fDrRNqH25b8P9/tJKhkbGJqZmSjlJiUnKKUuz/KAA "Brachylog – Try It Online") ### Explanation Pretty self-explanatory ``` { }ᶠ Find all: ᵐ Map: ∋ In ``` [Answer] # [Tcl](https://www.tcl.tk), 60 bytes ``` proc p x\ y {lmap X $x {lmap Y $y {lappend l $X\ $Y}};set l} ``` Use: ``` % p {1 2 3} {a 2 2} {1 a} {1 2} {1 2} {2 a} {2 2} {2 2} {3 a} {3 2} {3 2} ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 3 bytes ``` *ww ``` Multiplying two strings just acts as the cartesian product. [Test it online!](https://pyth.herokuapp.com/?code=%2Aww&input=aa%0Aaba&debug=0) [Answer] # JavaScript (ES6), ~~45~~ ~~36~~ ~~34~~ 33 bytes Requires Firefox. Takes both inputs as strings or as arrays of individual characters. ``` a=>b=>[for(x of a)for(y of b)x+y] ``` * -1 byte thanks to [CalculatorFeline](https://codegolf.stackexchange.com/users/51443/calculatorfeline) spotting an errant `<space>`. --- ## Try It ``` f= a=>b=>[for(x of a)for(y of b)x+y] oninput=_=>console.clear()&console.log(f(i.value)(j.value)) console.log(f(i.value="123456")(j.value="abcd")) ``` ``` <input id=i><input id=j> ``` [Answer] # Bash, 18 This can be done with brace expansions: ``` eval echo {$1}{$2} ``` [Try it online](https://tio.run/##S0oszvhfnFqiYKhjpGOskKiTpJP8P7UsMUchNTkjX6FaxbC2WsWo9v9/AA). [Answer] # Common Lisp, 63 bytes ``` (lambda(a b)(mapcan(lambda(x)(mapcar(lambda(y)(list x y))b))a)) ``` [Try it online!](https://tio.run/##Ncu7CoAwDIXhVwk4mDN6fRqXtF0KVYo62KevR7DDB@FP4lO8ctV8xsOLVk22u2Bq4qC7ZW9HS88fzhYKlM@3PFIABxhQe@22QbptpIlmWmiFfCvj6MhTAO9f) [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 29 bytes ``` [_l;||[_l;||?_sA,a,1|+_sB,b,1 ``` This prints 2-char strings with all combinations on one line each. ## Explanation ``` ; Read in string A$ _l | Get its length as b [ | and kick off a FOR-loop from 1 to that [_l;|| Do the same for B$ Note that, while the FOR-loop may pass this code several times, the 'read-from cmd line' is done only once. ?_sA,a,1| PRINT the character from A$ at the position of the 'a' loop counter +_sB,a,1 concatenated with the char from B$ at the pos of the 'b' loop counter ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 2 bytes ``` Z* ``` `*` is the general operator for products and the prefix `Z` makes it the *cartesian* product and can take two strings as arguments. [Try it online!](https://tio.run/##y00syfn/P0rr/3/1xOKUNHUu9YrKKnUA "MATL – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 39 bytes ``` lambda x,y:[[i,j]for i in x for j in y] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFCp9IqOjpTJys2Lb9IIVMhM0@hQgHEzAIxK2P/FxRl5pUopGmoGxoZm5iaqesoqCcmJaeoa3KBZbjg8kBRkCRQGRa5RIi@RHXN/wA "Python 2 – Try It Online") ## Alternate solution, ~~34~~ 30 bytes *-4 bytes thanks to Anders Kaseorg.* There is a built-in for this... ``` from itertools import* product ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 1 byte ``` ∙ ``` [Try it online!](https://tio.run/##S0wuKU3Myan8//9Rx8z//5USk5JTlLiUDI2MTUzNlAA "Actually – Try It Online") `∙` is the Cartesian product command. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` v²NFÀ}¹ø)˜ ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/7NAmP7fDDbWHdh7eoXl6zv//KUWpXFWJBQA "05AB1E – Try It Online") This is without the built-in, and undoubtedly won't be competitive. [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), 1 byte ``` ╒ ``` [Try it online!](https://tio.run/##y8/I/f//0dRJ//8bGhmbmJpxJSYlpwAA "Ohm – Try It Online") Literally only the built-in [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~5~~ 2 bytes Japt now has a method for the Cartesian product. Takes input as 2 arrays of character strings. ``` ïV ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=71Y=&input=WyJhIiwiYSJdLFsiYSIsImIiLCJhIl0KLVE=) [Answer] # C# 7, ~~78~~ 63 bytes ``` (a,b)=>$"({string.Join(",",a.SelectMany(x=>b,(x,y)=>(x,y)))})"; ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 1 byte ``` * ``` [Try it online!](https://tio.run/##yygtzv6fm18enHpiffGh5Y@aGh@1TXjUNqn80Lb/Wv///zc0MjYxNVNITEpO4QISCkA@V2IikJ8IAA "Husk – Try It Online") `*` does Cartesian products when given two lists. [Answer] # [Rockstar](https://codewithrockstar.com/), 81 bytes ``` listen to X listen to Y cut X while X roll X in C cut Y in Z while Z say C+roll Z ``` [Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in) [Answer] ## Clojure, 21 bytes ``` #(for[i % j %2][i j]) ``` [Answer] # [PHP](https://php.net/), 69 bytes ``` <?foreach($_GET[0]as$x)foreach($_GET[1]as$y)$r[]=[$x,$y];print_r($r); ``` [Try it online!](https://tio.run/##Vcy9CsIwFAXgvY8RMiQQwfq3xOIgQVx06RZCiG00XZJw7dAuvrVzvLo5fHA4cE4OuewPOeTKAySw4HOCcYgP9lL2cm3PR8VlRe1JtY3WpCaCrNAabdAW7YgRmjhMN9ShHnlijCz3BN51gf0O9NK4J534f1l/y5lT0KbRdBJ0NjLDEEcLjAKXpbxjWnQ48B8 "PHP – Try It Online") [Answer] # [Cheddar](http://cheddar.vihan.org/), 52 bytes ``` a->b->a.chars.map(i->b.chars.map(i&(+))).reduce((+)) ``` [Try it online!](https://tio.run/##S85ITUlJLPpfUJSZV6LxP1HXLknXLlEvOSOxqFgvN7FAIxMogsxV09DW1NTUK0pNKU1O1QBx/mtqKBkaGZuYmikBWYlJySlKmv8B "Cheddar – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), 49 bytes ``` .(?=.*¶(.+)) $1$&¶ ¶¶.+ ¶ .(?=.*(.)¶) $1$&¶ ¶.¶ ¶ ``` [Try it online!](https://tio.run/##K0otycxL/P9fT8PeVk/r0DYNPW1NTS4VQxW1Q9u4Dm07tE1PG0hxQaQ19DQPbUOS1QOT//8bGhmbmJpxJSYlpwAA "Retina – Try It Online") Takes input on separate lines. Explanation: ``` .(?=.*¶(.+)) $1$&¶ ``` Each character in the first string generates a separate line prefixed by the second string. ``` ¶¶.+ ¶ ``` The original second string is deleted. ``` .(?=.*(.)¶) $1$&¶ ``` For each character in the first string, each character in the second string generates a separate line prefixed with the first character. ``` ¶.¶ ¶ ``` The left-over characters from the first string are deleted. [Answer] # q/kdb+, 5 bytes **Solution:** ``` cross / yup, there's a built-in to do exactly this ``` **Example:** ``` q)"123456"cross"abcd" "1a" "1b" "1c" "1d" "2a" "2b" "2c" "2d" "3a" "3b" "3c" "3d" "4a" "4b" ...etc ``` ]
[Question] [ Given a string containing decimal numbers: `teststring134this 123test string54 100` increment every number in this string by one to give the new string `teststring135this 124test string55 101`. The string can be provided as: * a command line argument * STDIN * a hard-coded variable or function argument Cover all possible positions for a number: * as a prefix for a word; `123test` ► `124test` * as a suffix for a word; `test123` ► `test124` * inside a word; `te123st` ► `te124st` * alone `test 123 test` ► `test 124 test` Here's a non-golfed solution in Python: ``` NUMBERS = '0123456789' def increment(s): out = '' number = '' for c in s: if c in NUMBERS: number += c else: if number != '': out += str(int(number) + 1) number = '' out += c if number != '': out += str(int(number) + 1) number = '' return out print "\"%s\"" % (increment('teststring134this 123test string54 100')) ``` This is a `code-golf` question, shortest code wins. [Answer] # Perl, 14 bytes ``` s/\d+/$&+1/ge ``` Requires the `-p` switch, which I have counted as one byte. ### Example run ``` $ perl -p <(echo 's/\d+/$&+1/ge') <<< 'teststring134this 123test string54 100' teststring135this 124test string55 101 ``` [Answer] ## Ruby, ~~30~~ 24 bytes ``` $><<s.gsub(/\d+/,&:next) ``` Expects the input to be stored in `s`. [Answer] # JavaScript (ES6) - 28 ``` H=k=>k.replace(/\d+/g,k=>++k) ``` Run by using `H("test 123 234t")`. [Answer] # Vim - 13 keystrokes ``` 0qqqqq^Al@qq@q ``` Expects the input to be the current line. Or for finitely many numbers (e.g. 999) in 8 + ceil(log(n)) keystrokes: ``` 0qq^Alq999@q ``` [Answer] ## Perl, 23 Assumes the input string is assigned to `$_` ``` s/\d+/@{[$&+1]}/g;print ``` [Answer] # Python 2 - 59 Supply the string as the variable `n` ``` import re;print re.sub('\d+',lambda x:`int(x.group())+1`,n) ``` [Answer] # C99 - 86 (GCC 4.9.0 and Visual C++ 2013) **Edit: Both GCC 4.9.0 (with -std=c99) and Visual C++ 2013 successfully build (with warnings) the same code without the includes. I didn't know you could do that! Thanks for the hint.** **Edit: It didn't even occur to me that I should write it to the screen on the fly instead of creating the string and then printing it. That makes a huge difference. Thanks Dennis!** This is using a hard coded string but the contents of the string are not counted towards the total (the ="" is counted). ``` main(i){for(char*q,*s="test123test999test-1test";i=strtol(s,&q,0),*s;q>s?printf("%d",i+1,s=q):putchar(*s++));} ``` Basically it runs through the string one character at a time checking each to see if it is an integer. If it is then it increments the integer and writes it to the output otherwise it copies the current character to the output. This leaks the hardcoded string because it increments s. [Answer] ## J (20) Expects the input to be stored in the variable `a`. ``` '\d+'>:&.".rxapply a ``` Test: ``` a=:'teststring134this 123test string54 100' '\d+'>:&.".rxapply a teststring135this 124test string55 101 ``` [Answer] # (f?)lex (39) File `inc.l`: ``` %% [0-9]+ printf("%d",atoi(yytext)+1); ``` Compile: ``` $ flex inc.l $ gcc lex.yy.c -o inc -lfl ``` Run: ``` $ echo 'teststring134this 123test string54 100' | ./inc teststring135this 124test string55 101 $ i='(-: 2 empty bottles of beer :-)' $ tty=$(tty) $ for n in {2..5} ; do i=$(./inc<<<$i|tee $tty) ; done (-: 3 empty bottles of beer :-) (-: 4 empty bottles of beer :-) (-: 5 empty bottles of beer :-) (-: 6 empty bottles of beer :-) ``` I did not test this with the original `lex`. Comments are welcome. [Answer] # Emacs - 20 characters ``` C-M-% [0-9]+ RET \,(1+ \#0) RET ! ``` Requires text to be processed to be present in the current buffer. I counted C-M-% as one character here since it can be entered with one keystroke when holding down three modifiers. [Answer] # GNU sed, 304 (including 1 for -r flag) I close-voted this question as a possible duplicate, but this is perhaps contrary to that because this answer can't be trivially changed to work there. By far the longest answer though. Inspired by [this example from the sed documentation](http://www.gnu.org/software/sed/manual/sed.html#Increment-a-number), though it needed some work to handle multiple numbers in a string: ``` :d s/9([^0-9]+|$)/_\1/g td s/8(_*)([^0-9]+|$)/9\1\2/g s/7(_*)([^0-9]+|$)/8\1\2/g s/6(_*)([^0-9]+|$)/7\1\2/g s/5(_*)([^0-9]+|$)/6\1\2/g s/4(_*)([^0-9]+|$)/5\1\2/g s/3(_*)([^0-9]+|$)/4\1\2/g s/2(_*)([^0-9]+|$)/3\1\2/g s/1(_*)([^0-9]+|$)/2\1\2/g s/0(_*)([^0-9]+|$)/1\1\2/g s/(^|[^0-9_]+)(_+)/\11\2/g y/_/0/ ``` ### Output: ``` $ for s in "teststring134this 123test string54 100" "123test" "test123" "te123st" "test 123 test" ; do echo "$s" | sed -rf incr.sed ; done teststring135this 124test string55 101 124test test124 te124st test 124 test $ ``` Note this temporarily inserts `_` characters, so could lead to incorrect results if there are `_` in the input stream. As a mitigation to this, we can replace the `_` in the sed script with some non-printable character (e.g. ASCII 0x07 BEL), and assume the input stream contains only printable ASCII. This seems to work fine when I test it. [Answer] # Racket 74 ``` (define(f x)(regexp-replace* #px"\\d+"x(λ(m)(~a(+ 1(string->number m)))))) ``` [Answer] ## Lua - 68 characters ``` d='(%D-)'for k,i,j in s:gmatch(d..'(%d+)'..d)do io.write(k,i+1,j)end ``` Expects the input to be stored in s. [Answer] ## CJam, ~~67 58 53~~ ~~48~~ 31 characters This question is like the worst question for CJam. No regex, no pattern matching, no exception catching. But here we go *(#YOLO)* ``` Sl+_A,sNerN%\[_A,s-Ner~]:)]zs1> ``` This one splits the string in group of just alphabets and just digits. The increments each digit and stitches back the two array taking one element of each at a time. --- Previous solution: ``` L_l{:Ci57-zA<:RC*+:N\R!N*NNW?i):NL?+RLC?@R*}/NL? ``` [Try it online here](http://cjam.aditsu.net/) How it works: Basic idea is to keep storing the character separately in a string if it is a digit and dump the incremented value to the final string once we get a non digit character. ``` L_ "Push two empty strings to stack," "first representing the final string" "and second, the current ongoing number"; l{ }/ "Run this block for each character of input string"; :Ci "Store the character to C and convert to" "its ASCII equivalent integer"; 57-zA<:R "Subtract 57 from the integer and compare" "its absolute value with 10. Numeric character" "would result to true here. Store the result in R"; C*+:N "Take either 0 or 1 characters from C based" "on value of R, add it to the second string" "from first step. Also store the value in N"; \ "Switch the strings. Now the string containing" "the final result string is at top of stack"; R!N* "If the character was not a digit and N contains a number in it"; NNW?i):NL?+ "Convert N to number and increment it." "If N is blank, take 0 instead. Put the final" "value back in N and add it to the final result string"; RLC? "If the character was not a digit, push it to stack"; @R* "Put the ongoing numeric string back to top of stack"; NL? "This is to handle the case when the last number" "is not followed by a string, so stack will" "have a string at top. Push the value of N to stack in that case"; ``` [Answer] # Cobra - 88 ``` do(s='')=RegularExpressions.Regex.replace(s,'\d+',do(m as Match)='[int.parse("[m]")+1]') ``` [Answer] # C# - 178 169 157 characters This assumes that numbers like 999 are allowed to overflow to 000 and that -+,.E are not part of a number. ``` class T{static void Main(){var a="".ToCharArray();for(int b=1,c,i=a.Length;i-->0;b=48>c|c>57?7:b>0?c>56?a[i]='0':++a[i]*0:b)c=a[i];System.Console.Write(a);}} ``` Better readable form: ``` class T { static void Main() { var a="7teststring134this 123test string59 100".ToCharArray(); for (int b=3, c, i=a.Length; i-->0; b=48>c|c>57 ?7 :b>2 ?c>56?a[i]='0':++a[i]*0 :b ) c=a[i]; System.Console.Write(a); System.Console.ReadKey(); } } ``` I'm new here, never tried code golf before, just gave it a try :) I wonder if anyone has ideas to get it even shorter... To participate with C# it would be nice if we could omit all the necessary framework around the actual code - then this would only have 82 chars, and that without calling any powerful system functions. --- The same with pointers (182 chars): ``` class T { unsafe static void Main() { char[] a="7teststring134this 123test string59 100".ToCharArray(); int b=3; fixed (char* s=&a[0]) for (var p=s+a.Length; p-->s; ) b=*p<48|*p>57 ?7 :b>2 ?*p>56?*p='0':++*p*0 :b; System.Console.Write(a); System.Console.ReadKey(); } } ``` --- Now without overflowing, this correctly handles the 999 case (223 chars): ``` class T { static void Main() { var s=new System.Text.StringBuilder("9999teststring134this 123test string99 100"); for (int b=3, c, i=s.Length; i-->0; ) { c=s[i]; b=48>c|c>57 ?b>8?8:7 :b>2 ?c>56?c-(s[i]='0'):++s[i]*0 :b; if (b>8&i<1|b==8) s.Insert(i+9-b, '1'); } System.Console.Write(s); System.Console.ReadKey(); } } ``` --- Another different older one, it reads from standard input and uses recursion: ``` namespace System { using C=Console; class T { class t { byte b=1; string s=""; void R() { var c=C.Read(); if (c>31) { R(); if (48>c|c>57) b=1; else if (b==1) c=c==57?48:++c*b--; s=(char)c+s; } } public t() { R(); C.Write(s); } } static void Main() { new t(); C.ReadKey(); } } } ``` Note: `Console.ReadKey();` and the string itself should not be counted. I improved this already multiple times, see comments. There is still room for more improvements, I would say :) And sorry for the length, but I think the different versions are interesting enough to keep them... [Answer] # Groovy, 38 bytes ``` {it.replaceAll(/\d+/,{(it as int)+1})} ``` Uggghhh... I absolutely hate the words `replace` and `all`, they ruin all regex golfs for me. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 40 bytes ``` BEGIN{RS="[0-9]+";ORS=e}$0=$0(RT?RT+1:e) ``` [Try it online!](https://tio.run/##SyzP/v/fydXd0686KNhWKdpA1zJWW8naH8hJrVUxsFUx0AgKsQ8K0Ta0StX8/78ktbikuKQoMy/d0NikJCOzWMHQyBgkqAARNTVRMDQw4IIKcoEIIBtIA0koH6RDAcQAAA "AWK – Try It Online") Parses each substring of numbers as a record separator (default is a newline, "\n"). Adds one to the record text (RT), that is the number that previously matched to the regex. Except for the last RT, which is null. That's what the last condition is about. Otherwise, there would be a `1` appended to the end of the output. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 13 bytes ``` {S:g{\d+}+=1} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzrYKr06JkW7VtvWsPZ/cWKlgh5QIi2/SCEnMy@1@H9JanFJcUlRZl66obFJSUZmsYKhkTFIUAEiamqiYGhgAAA "Perl 6 – Try It Online") Very simple regex substitution that just increments each instance of a series of digits [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes ``` ~c{ịᵐc+₁ṫ|ịˢĖ&}ᵐc ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy65@uHu7odbJyRrP2pqfLhzdQ2Qe3rRkWlqtSDB//@VdE2MFBKTTPUslf5HAAA "Brachylog – Try It Online") ### Explanation ``` ~c{ịᵐc+₁ṫ|ịˢĖ&}ᵐc ~c Partition the input string such that { }ᵐ this predicate can be applied to each substring: Either: ịᵐ Convert each character to a number (i.e. they are all digits) c Concatenate the digits into a single number +₁ Add 1 ṫ Convert back to a string | Or: ịˢ Find all characters that can be converted to a number Ė Assert that that list is empty (i.e. none of them are digits) & Return the substring unchanged c Concatenate the results back into a single string ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 8 bytes ``` ⁽±Ḋƛ±[⌊› ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwi4oG9wrHhuIrGm8KxW+KMiuKAuiIsIiIsIjEzNHRoaXMgMTIzdGVzdCBzdHJpbmc1NCAxMDAiXQ==) Who needs regex amiright? ## Explained ``` ⁽±Ḋƛ±[⌊› ⁽±Ḋ # Group the input by whether each item is numeric ƛ # To each group: ±[ # If it's numeric: ⌊› # Cast to int and increment # -s flag sums into a single string. ``` [Answer] ## **PHP - 91 Bytes** ``` <?$i=fgets(STDIN);for($n=0;$n<strlen($i);$n++)if(is_numeric($i[$n]))$i[$n]=$i[$n]+1;echo$i; ``` I don't wanted to use regular expressions. PHP isn't capable to directly increment a string offset, so, I needed to add some bytes on the increment step. This one line script remembers me a very dark age of the PHP scripting... [Answer] # K, 56 ``` {" "/:{,/$(`$a)^`$$1+"I"$a:_[;x]@&~~':x in .Q.n}'" "\:x} ``` [Answer] sed and bash - 40 (including invocation and pipes) ``` $ cat << EOF |sed 's/[0-9]\+/$((\0+1))/g;s/^/echo /'|bash teststring134this 123test string54 100 123test test123 te123st test 123 test EOF ``` Outputs: ``` teststring135this 124test string55 101 124test test124 te124st test 124 test ``` [Answer] # Java 7, 119 bytes ``` void c(String s){for(String x:s.split("(?=[^\\d]+)|(?<=[^\\d]+)"))System.out.print(x.matches("\\d+")?new Long(x)+1:x);} ``` If the requirement is a program instead of just a function, then it's **149 bytes:** ``` class M{public static void main(String[]a){for(String x:a[0].split("(?=[^\\d]+)|(?<=[^\\d]+)"))System.out.print(x.matches("\\d+")?new Long(x)+1:x);}} ``` **Ungolfed & test code:** [Try it here.](https://ideone.com/13ZpSs) ``` class M{ static void c(String s){ for(String x : s.split("(?=[^\\d]+)|(?<=[^\\d]+)")){ System.out.print(x.matches("\\d+") ? new Long(x) + 1 : x); } } public static void main(String[] a){ c("123test"); System.out.println(); c("test123"); System.out.println(); c("te123st"); System.out.println(); c("test 123 test"); System.out.println(); c("7teststring134this 123test string59 100"); } } ``` **Output:** ``` 124test test124 te124st test 124 test 8teststring135this 124test string60 101 ``` [Answer] # Gema, 14 characters ``` <D>=@add{$1;1} ``` Sample run: ``` bash-4.3$ gema '<D>=@add{$1;1}' <<< 'teststring134this 123test string54 100' teststring135this 124test string55 101 ``` [Answer] # CJam, 18 bytes ``` q_A,s-_:(:`ers~]:) ``` Try it here. ### Explanation ``` q e# Read input. _A,s- e# Duplicate and remove digits. _ e# Duplicate. :(:` e# Decrement and get the string representation of each character. er e# Map the characters to the decremented string representation. s~ e# Flatten to string and evaluate. ]:) e# Wrap in an array and increment each element. ``` [Answer] ## R, 83 bytes Late to the party. Assumes input is stored in variable `x`. It's probably not needed to use `regmatches` to solve this but I couldn't figure out vectorized replacements without any external packages. ``` paste0(el(r(x,m<-gregexpr("\\d+",x),T)),c(as.numeric(el(r(x,m)))+1,""),collapse="") ``` **Ungolfed and explained** ``` r=regmatches # Alias for regmatch y=r(x<-scan(,""),m<-gregexpr("\\d+",x)) # return match digits i=r(x,m,T) # return inverted match (non-digits) paste0(el(i),c(as.numeric(el(y))+1,""),collapse="") # join digits+1 and non-digits, element-wise ``` **Example output** ``` input: "teststring135this 124test string55 101" output: [1] "teststring136this 125test string56 102" ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc) with command-line option `/u:System.Text.RegularExpressions.Regex;System.Int32`, 40 bytes ``` Replace(n,"\\d+",m=>Parse(m.Value)+1+"") ``` Expects input to be in a variable named n. [Try it online!](https://tio.run/##LY3NCoJAFEb3PsXgStEM/wgT20SLoEVY1MbNpLdxYLzKzEj28k0afcuPczi1WtWKG6UlR0aw2PeoegFBCbQ5cQTHzS0sTAmDoDU46NtV1Xi23xW7M5UKnC64UTGC64Webbsmt@6Sa/ip6OYmSuKUPGlN2etBkjBNSdu00G5IlmVs3qcfNJ@bZj1uL2@loQuuMOm5z0ZB5WEaJCi1EMsFU/6Hjqjj6As "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü╜≥NÇNX╪ÿ ``` [Run and debug it](https://staxlang.xyz/#p=81bdf24e804e58d898&i=teststring134this+123test+string54+100%0A123test%0Atest123%0Ate123st%0Atest+123+test&m=2) regex ]
[Question] [ **Challenge** Given an integer **n ≥ 4**, output a permutation of the integers **[0, n-1]** with the property that no two consecutive integers (integers with absolute difference 1) are next to each other. **Examples** * **4** → **[1, 3, 0, 2]** * **5** → **[0, 2, 4, 1, 3]** * **6** → **[0, 2, 4, 1, 3, 5]** * **7** → **[0, 2, 4, 1, 5, 3, 6]** You may use 1-indexing instead (using integers **[1, n]** instead of **[0, n-1]**). Your code must run in polynomial time in **n**, so you can't try all permutations and test each one. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~3~~ 2 bytes ``` ḂÞ ``` Sorts the integers in **[1, ..., n]** by their LSB. [Try it online!](https://tio.run/##y0rNyan8///hjqbD8/4fbn/UtMb9/38THQVTHQUzHQVzAA "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 32 bytes ``` lambda n:(range(n|1)*2)[1:n*2:2] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPSqMoMS89VSOvxlBTy0gz2tAqT8vIyij2f1p@kUKeQmaeAkTeRMfQQNOKi7OgKDOvRCFPRyFNI0/zPwA "Python 2 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~40~~, 38 bytes ``` lambda n:[*range(1,n,2),*range(0,n,2)] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKlqrKDEvPVXDUCdPx0hTB8ozAPNi/6flFylkKmTmKUCETXSMDDStuBSAoKAoM69EI00jU1Pz//9oQx0FIx0Fk1gA "Python 3 – Try It Online") This runs in `O(n)` time. Thanks to Dennis for saving 2 bytes! [Answer] # [Python 2](https://docs.python.org/2/), 34 bytes ``` lambda n:range(1,n,2)+range(0,n,2) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPqigxLz1Vw1AnT8dIUxvCMQBz/qflFynkKWTmKUBETXQMDTStuDgLijLzShTydBTSNPI0/wMA "Python 2 – Try It Online") **[Python 2](https://docs.python.org/2/), 40 bytes** ``` lambda n:[(k-~k)%(n|1)for k in range(n)] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKlojW7cuW1NVI6/GUDMtv0ghWyEzT6EoMS89VSNPM/Y/SCgPIWSiY2igacXFWVCUmVeikKeTBlT0HwA "Python 2 – Try It Online") [Answer] ## Haskell, 22 bytes f is a function of n that returns an appropriately ordered list. I am using the 1-indexing option. ``` f n=[2,4..n]++[1,3..n] ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 17 bytes ``` @(x)[2:2:x,1:2:x] ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0Iz2sjKyKpCxxBExv5Pyy9SyLQ1sTLnStPI1ORKzUv5DwA "Octave – Try It Online") This uses the same approach as many others. Concatenate two vectors, one with all the even number in the inclusive range **2 ... x**, and all the odd numbers in the inclusive range **1 ... x**. The syntax should be fairly obvious, so I won't explain that. [Answer] # [Gaia](https://github.com/splcurran/Gaia), 2 bytes ``` r∫ ``` [Try it online!](https://tio.run/##S0/MTPz/v@hRx@r//00B "Gaia – Try It Online") This simply (stable) **∫**​orts the integers in the range **[1, input]** by their pa**r**ity. [Answer] # [R](https://www.r-project.org/), ~~39~~ ~~36~~ 35 bytes ``` function(x)c(seq(2,x,2),seq(1,x,2)) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQjNZozi1UMNIp0LHSFMHxDQEMzX/FycWFORUaphYGRropGn@BwA "R – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) Port of [DJMcMayhem's Python answer](https://codegolf.stackexchange.com/a/164702/53748) and [Dennis's Jelly answer](https://codegolf.stackexchange.com/a/164704/53748) ``` ÝΣÉ ``` **[Try it online!](https://tio.run/##MzBNTDJM/f//8Nxziw93/v9vaAQA "05AB1E – Try It Online")** ### How? ``` ÝΣÉ - implicitly take input onto stack e.g. 7 Ý - pop a and push range(a) [0,1,2,3,4,5,6] Σ - sort by (stable): É - is even? (x%2==0 ?) [1,3,5,0,2,4,6] - implicit print of top of stack ``` [Answer] ## JavaScript (ES6), 40 bytes ``` f= n=>[...Array(i=n)].map(_=>(i+--i)%(n|1)) ``` ``` <input type=number min=4 oninput=o.textContent=f(+this.value).join`\n`><pre id=o> ``` Edit: Saved 1 byte thanks to @Arnauld. [Answer] # Japt, 4 bytes You could also replace `u` with `v` to get a different order. ``` õ ñu ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=9SDxdQ==&input=OAotUQ==) Or, if we can ouput an array of 2 arrays: ``` õ ó ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=9SDz&input=OAotUQ==) [Answer] # Mathematica, 50 -> 47 -> 42 bytes ``` p = Join[Range[2, #, 2], Range[1, #, 2]] & ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/79AwVbBKz8zLzooMS89NdpIR0FZR8EoVkcBwjeE8mMV1P4HFGXmlUQX6DtApEx0zGNj/wMA "Wolfram Language (Mathematica) – Try It Online") Thanks to user202729 for pointing out the twofold optimization potential Join[] insteaed of Flatten[] and using pure functions. I'd like to add two remarks. 1) It is fairly straightforward to construct a specific permutation with no falling or rising succession for n>=4 as requested n the OP. It consists of two consecutive list. For even n these are: list1 = (2,4,...,n/2) list2 = (1,3,...,n/2-1) For odd n we have: list1 = (2,4,...,Floor[n/2]) list2 = (1,3,...,Floor[n/2]) For this "algorithm" just one decision must be made (n even or odd), the rest is just writing down n numbers. A possible Mathematica solution is provided at the top. 2) A related question is how many such permuations exist as a function of n. # Mathematica, 124 Bytes ``` a[0] = a[1] = 1; a[2] = a[3] = 0; a[n_] := a[n] = (n + 1)*a[n - 1] - (n - 2)*a[n - 2] - (n - 5)*a[n - 3] + (n - 3)*a[n - 4] ``` [Try it online!](https://tio.run/##fY7NasMwEITvfoqJAyE/NbKV5NLQEii5hpKrEEV15VTFkowiQ97elWLsJpdedlefdmZWC/8ttfCqFF0nWM7xAsGK2IpdmGgP1rHlu0Qw88HxHJGJaG6wQrFYhicyBFkWUQY6IDqi7YCC16pH6wFteNK9O2U8S4@t/pQOtsKlkaWqVIlGOt36cKM1l5Qn/aJgU44ZyB4nYc6SbZ5Acz78pqe4Dnc78X/HBQjmoq4f4UMOmU4wI/shKOQQchyjDlehm1rGAIfKOtTCnSXMnQXNgySUyb3uzZofWfrWyS/USiv/52CyV2tH/eHasIzeMrtf "Wolfram Language (Mathematica) – Try It Online") Example: ``` a[#] & /@ Range[4, 12] ``` > > {2, 14, 90, 646, 5242, 47622, 479306, 5296790, 63779034} > > > To count the number of such permutations is a standard problem. For n = 4 there are 2: {{2,4,1,3},{3,1,4,2}} For n = 5 there are 14: {{1,3,5,2,4},{1,4,2,5,3},{2,4,1,3,5},{2,4,1,5,3},{2,5,3,1,4},{3,1,4,2,5},{3,1,5,2,4},{3,5,1,4,2},{3,5,2,4,1},{4,1,3,5,2},{4,2,5,1,3},{4,2,5,3,1},{5,2,4,1,3},{5,3,1,4,2}} The number a(n) of these permutations rises quickly: 2, 14, 90, 646, 5242, 47622, 479306, 5296790, 63779034, ... For large n the ratio a(n)/n! seems to approach the limit 1/e^2 = 0.135335... I have no strict proof but it is just a conjecture from numerical evidence. You can test this by trying to run the program online. The program above (based on the reference given below) calculates these numbers. You can find more information in the relevant sequence on OEIS: [A002464](https://oeis.org/A002464). Hertzsprung's problem: ways to arrange n non-attacking kings on an n X n board, with 1 in each row and column. Also number of permutations of length n without rising or falling successions. [Answer] # [Ruby](https://www.ruby-lang.org/), 27 bytes ``` ->n{[*2.step(n,2)]|[*1..n]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOlrLSK@4JLVAI0/HSDO2JlrLUE8vL7b2f4FCWrRJLBeIMoVQhoYQ2sg09j8A "Ruby – Try It Online") Using 1-indexing [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 161 bytes Here is the official, uncommented submission: [Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgYuTi5MTTIMoTiBPAcRT4AQjEAsoqAATBavlgksDIRdEAmGAArIJYLUQJWASq3koBiKUcgHB//@WAA "Whitespace – Try It Online") ``` push_0 read_n push_0 retreive_n push_1 subtract dup_and_out[ ]label_s' 'push_2 subtract dup[ ]jump_next_if_neg: :dup_and_out[ ]else_jump_back: :label_ss' 'push_0 retreive_n push_2 subtract dup_and_out[ ]dup[ ]jump_next: :label_ssss' 'push_2 subtract dup[ ]jump_end_if_neg: :dup_and_out[ ]else_jump_back: :label_sss' 'end ``` [Try it online!](https://tio.run/##jY/BDoIwEETP3a/YG1f1Zn/FkE2BVVBEQlv17@sWwaBgQtKkyWRn3syjrBzb1uQcQuttSRtEhI5NQY0Cpaaa67i6s@iDvEVUCqzPXGdyp@So8C2ZpqCbdwcEVPLS2mRck00ghiS9cReN@OuMjvTsry01/HRUHeU/aekgPr2UzLVl6g2ZyS8aRAc94N68EfhnwHKPGWfWrUfFyA9t5K2eyMKYLlw/8Zs7YCGRQAAIYf8C "Whitespace – Try It Online") I sacrificed a few bytes so that the program would execute without any errors, I believe that I could lose around 7-8 bytes, and it would still output correctly, but it would also output error messages, and nobody wants that. ### Full Byte Explanation: ``` [Space][Space][Space][N] Push a 0 on the stack [Tab][Tab][N][Tab][Tab][Tab][Tab] Read input value and store in heap [Space][Space][Space][N] Push a 0 on the stack again [Tab][Tab][Tab] Retrieve the value from the heap [Space][Space][Tab][Tab][N] Push a -1 on the stack [Tab][Space][Space][Space] Add -1 to value [Space][N][Space] Duplicate [Tab][N][Space][Tab] Output [N][Space][Space][Space][N] Set First Label [Space][Space][Tab][Tab][Space][N] Push a -2 on the stack [Tab][Space][Space][Space] Subtract 2 from value [Space][N][Space] Duplicate [N][Tab][Tab][Space][Space][N] If negative, jump to second label [Space][N][Space] Duplicate [Tab][N][Space][Tab] Output [N][Space][N][Space][N] Jump back to first label [N][Space][Space][Space][Space][N] Set Second Label [Space][Space][Space][N] Push a 0 on the stack [Tab][Tab][Tab] Retrieve input value from heap again [Space][Space][Tab][Tab][Space][N] Push a -2 on the stack [Tab][Space][Space][Space] This time, Add a -2 to the value [Space][N][Space] Duplicate [Tab][N][Space][Tab] Output [Space][N][Space] Duplicate [N][Space][N][Space][Tab][N] Jump to third label [N][Space][Space][Space][Tab][N] Set third label [Space][Space][Tab][Tab][Space][N] Push a -2 on the stack [Tab][Space][Space][Space] Subtract 2 from value [Space][N][Space] Duplicate [N][Tab][Tab][Space][Space][Space][N] Jump to end if negative [Space][N][Space] Duplicate [Tab][N][Space][Tab] Output [N][Space][N][Space][Tab][N] Jump back to third label [N][Space][Space][Space][Space][Space][N] Set fourth label/end [N][N][N] Terminate ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 42 bytes ``` n=>(f=i=>i<n?[i,...f(i+2)]:i&1?[]:f(1))(0) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/e9m@z/P1k4jzTbT1i7TJs8@OlNHT08vTSNT20gz1ipTzdA@OtYqTcNQU1PDQPN/cn5ecX5Oql5OfrqGm4aJpiYXqogphogZhog5hogFUOQ/AA "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 47 bytes ``` n=>(f=i=>i--?[n--*2%(N|1)+N%2,...f(i)]:[])(N=n) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/e9m@z/P1k4jzTbT1i5TV9c@Ok9XV8tIVcOvxlBT20/VSEdPTy9NI1Mz1io6VlPDzzZP839yfl5xfk6qXk5@uoabhommJheqiCmGiBmGiDmGiAVQ5D8A "JavaScript (Node.js) – Try It Online") [Answer] # [F# (Mono)](http://www.mono-project.com/), 27 bytes ``` let f n=[2..2..n]@[1..2..n] ``` [Try it online!](https://tio.run/##SyvWzc3Py///Pye1RCFNIc822khPD4jyYh2iDaGs/wVFmXklaXkKSqqOSgoaaQommlzoQqaYQmaYQuaa//8DAA "F# (Mono) – Try It Online") [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 14 bytes ``` FL:2%Z}:3=?$|B ``` [Try it online!](https://tio.run/##S8/PScsszvhv6Oju6Wrt7pITVPffzcfKSDWq1srY1l6lxun/fxMuUy4zLnMuCwA "Gol><> – Try It Online") ### Example full program & How it works ``` 1AGIE;GDlR~ FL:2%Z}:3=?$|B 1AG Register row 1 as function G IE; Take number input; halt on EOF GD Call G and print the stack lR~ Empty the stack Repeat indefinitely F | Repeat n times... L Push loop counter (0..n-1) :2%Z} If even, move to bottom of the stack :3=?$ If top == 3, swap top two This is activated only once to make [2 0 3 1] B Return ``` [Answer] # [J](http://jsoftware.com/), 10 bytes ``` i./:2|1+i. ``` [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8D9TT9/KqMZQO1PvvyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKaggmMYQpjmMEY5v8B "J – Try It Online") ## Explanation: ``` /: sort i. the numbers in the range 0..n-1 2| according the remainder mod 2 of 1+i. the numbers in the range 1..n ``` [Answer] # Java 8, 56 bytes ``` n->{for(int i=n;i>0;)System.out.println((i+--i)%(n|1));} ``` Port of [*@Neil*'s JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/164711/52210). [Try it online.](https://tio.run/##LY4xDoMwDEX3nsJLpURVEMwR3KAsjKhDGqAyBYNIQKooZ09dQLIHf9vv/9YsRrXVO9jOOAd3g7ReAJB8PTXG1pD/R4BlwAqsYB1IapY2bi7njUcLORCkEEhlazNM@xmmpDGLtSw@ztd9NMw@GifedCQE3pRCeRX0TaTUW9AHbZyfHdNO6O7ZcyJReH58lQ8w8ohDkRVJfAbZwg8) --- **Old 66 bytes answer:** ``` n->{String[]r={"",""};for(;n-->0;)r[n%2]+=n+" ";return r[0]+r[1];} ``` [Try it online.](https://tio.run/##hZDPCoJAEIfvPcWwEOxiikV/Dou9QV06iodttVjTUcY1CPHZbUs7hjBzmPmGjx@Tq6fy8/Qx6EI1DZyUwW4BYNBmdFM6g/NnBLhYMngHzR0BFNIte9euGqus0XAGhAgG9I/deBsnFHWMrRjr5a0iLtH3j6EUFONyk3gRegyYpMy2hEBxmHgUrxPZD3L01u21cN5J/6xMCqVLx392UGKK9mpsVgZVa4PaIVsgx0Dzrfim/Mt3M3w/ww8zfB2K6U398AY) **Explanation:** ``` n->{ // Method with integer parameter and String return-type String[]r={"",""}; // Result-Strings, both starting empty for(;n-->0;) // Loop in the range (n, 0] r[i%2]+=i+" "; // Append `i` and a space to one of the two result-Strings, // depending on if it is even (first) or odd (second) return r[0]+r[1];} // Return the two result-Strings appended to each other ``` [Answer] # Ruby, 27 bytes ``` ->n{(1..n).sort_by{|i|i&1}} ``` As in this [answer](https://codegolf.stackexchange.com/a/164704/65905), `n` first integers are sorted by their least significant bit. [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNQTy9PU684v6gkPqmyuiazJlPNsLb2f4FCWrRJLBeIMoVQhoYQ2sg09j8A "Ruby – Try It Online") ]
[Question] [ Output ``` # # # # # ##### ## # ## #### ####### # # ## #### ## ## # ### ####### # # # # ##### ### # # # # ### ##### ##### # # # ####### ### # ### # ## #### ## # # ### # ####### ## # ## ##### ##### # # # ## # # # # ##### # ## ## ####### # ####### #### ## # ### ### # # # # # ##### # # # # ### ##### # #### ####### ### # ## ## ## # # ####### # # ## ##### # # # # ##### ## # # ####### # # ## ## ## # ### ####### #### # ##### ### # # # # ##### # # # # # ### ### # ## #### ####### # ####### ## ## # ##### # # # # ## # # # ##### ##### ## # ## ####### # ### # # ## #### ## # ### # ### ####### # # # ##### ##### ### # # # # ### ##### # # # # ####### ### # ## ## #### ## # # ####### #### ## # ## ##### # # # # # # ## #### # # # # ### ####### ## # # ## ##### ## # ### # # ## # ### ####### ##### ### # # # # # ## #### #### ## # # # # # # # # ##### ## #### ####### # #### ## ## # ### # # # # ##### # # ### ##### ##### # ####### ### # ### # ## ## # # ### # ####### # ## ##### ##### # # ## # # # ## ## ####### #### ### # # # # # # # # ### #### ####### ## ## # # # ## ``` Trailing spaces allowed. Shortest solution wins. [hint0](https://codegolf.stackexchange.com/questions/143220/simple-complexity/143249#comment350883_143220) hint1: > > [![hint1](https://i.stack.imgur.com/Plsqf.png)](https://i.stack.imgur.com/Plsqf.png) > > > --- thanks @Tahg for correcting hint1 [Answer] ## JavaScript (ES6), ~~233~~ ~~217~~ ~~213~~ ~~198~~ ~~182~~ ~~170~~ ~~163~~ 122 bytes ``` f=_=>[...Array(64)].map((_,x,a)=>a.map(g=(i=(n=64,x),j)=>(n>>=1)?i&n?j&n?g(j,i):` `:j&n?g(i,~j):g(~i,j):`#`).join``).join` ` document.write(`<pre>${f()}</pre>`) ``` Edit: Saved ~~14~~ 18 bytes thanks to @Shaggy. Saved 3 bytes thanks to @ngn. Saved a further 12 bytes thanks to the two working together. Saved 41 bytes by stealing @user202729's observations that the quarters use reflections rather than rotations. Ungolfed: ``` function f() { var s = ''; for (var i = 0; i < 64; i++) { for (var j = 0; j < 64; j++) { var x = i, y = j, c = '#'; // Default to # // Each non-blank quadrant maps to to the original // image by doubling and a reflection. Repeat // this six times unless we hit the blank quadrant. for (var n = 0; n < 6; n++) { if (x >= 32) { if (y >= 32) { // Bottom right quarter is a diagonal reflection var t = x - 32; x = y - 32; y = t; } else { // Bottom left quarter is blank c = ' '; break; } } else { if (y >= 32) { // Top right corner is a horizontal reflection y = 63 - y; } else { // Top left corner is a vertical reflection x = 31 - x; } } x *= 2; y *= 2; } s += c; } s += '\n'; } return s; } ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~17~~ ~~16~~ 14 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` #6{³IIč▓┼;I+§ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIwJTIzNiU3QiVCM0lJJXUwMTBEJXUyNTkzJXUyNTNDJTNCSSslQTc_) At a later update `č▓` could be removed for 12 bytes - that converts ToS from an array of arrays of characters a multiline string to an array of strings - `[["#","#"],[" ","#"]] -> ["##"," #"]` - , because `┼` - horizontal append - doesn't deal well with arrays of arrays of characters - which `I` creates, because it's used for array rotation too. In SOGL an array of arrays of characters should be = array of strings, but many things don't support that yet.. Explanation: ``` # push "#" 6{ 6 times do ³ create 3 total copies of ToS II rotate clockwise twice č▓ normalize as explained above ┼ append horizontally ; get the 3rd copy ontop I rotate clockwise + append vertically § reverse horizontally ``` [Answer] # LOGO, ~~375~~ ~~341~~ ~~297~~ ~~295~~ 278 + 3 bytes Add 3 bytes because of `-p` flag, which enable perspective mode by default, thus don't need to run `perspective` command, saves 9 bytes overall. Use FMSLogo on Windows with Unix (LF) newline format (FMSLogo have problem with parsing CR newline format) ``` to R rt 90 end to g :w :l R fd 2*:l R bk :l up 180 run :w R run :w fd 2*:l R bk :l run :w fd 2*:l up 180 end to h pu ask -1[setxyz 0 0 870]g[g[g[g[g[g[rt 45 fd .7 pd fd 0 pu bk .7 lt 45]1]2]4]8]16]32 repeat 64[sety 64-# repeat 64[setx #-1 type if pixel=[0 0 0]""#["\ ]](pr)] end ``` Unfortunately, no "Try it online!" link because I can't find any online interpreter support perspective mode. Idea: Draw a picture of the image, then retrieve the pixels from the picture and print as output. Picture breakdown to simple repeated parts: [![](https://i.stack.imgur.com/435YM.png)](https://i.stack.imgur.com/435YM.png). Make use of the hint above. However, since LOGO does not support reflection, we can only simulate that by enter 3D (`perspective`) mode and turn the turtle 180 degree around an axis parallel to the computer screen. This defines a helper function `g`, which given 2 parameters `l` (image side length) and `w` (procedure used to draw the image), draw 3 copies of its reflected image. (see hint in the question) The procedure `h` perform the main procedure. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~30~~ 26 bytes ``` '#)6F©R®í®'#ð:®ζ)2䀸€J˜}» ``` [Try it online!](https://tio.run/##ATMAzP8wNWFiMWX//ycjKTZGwqlSwq7DrcKuJyPDsDrCrs62KTLDpOKCrMO44oKsSsucfcK7//8 "05AB1E – Try It Online") [Answer] ## [CJam](https://sourceforge.net/p/cjam), 30 bytes ``` "#"]{_W%_32ff&+\_Wf%\z+.+}6*N* ``` [Try it online!](https://tio.run/##S85KzP3/X0lZKbY6Plw13tgoLU1NOyY@PE01pkpbT7vWTMtP6/9/AA "CJam – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~205~~ ~~195 ... 145~~ ~~144~~ ~~142~~ 144 bytes ``` g=lambda n,i,j,*_:g(n/2,*[~i,j,i,~j][2*(j&n>0)-(i&n>0):])if n*(i&n<=j&n)else'# '[i&n>0] r=range(64) for j in r:print''.join(g(32,j,i)for i in r) ``` [Try it online!](https://tio.run/##HY3LCgIhGEb38xRCkBfsgkULyV5EJIwc@2X6HWw2bebVLV19HL4DZ/4ur4yq1mgm/348PUEJMklx15HhQUlh18Yg1@SsEixt8XbkOwZ9teMwEhQNr@b/8TB9At0QarvghmKKxxjY5cyHMReSCCApei6AC6X7lAFZZCfVGrwJ0AVe6w8 "Python 2 – Try It Online") Inspired by Neil's [JS answer](https://codegolf.stackexchange.com/a/143253/38592). [Answer] ## Haskell, ~~126~~ ~~125~~ ~~113~~ ~~106~~ 103 bytes ``` e=[]:e z=zipWith r=reverse m s=z(++)(r s++map(' '<$)s)$map r s++foldr(z(:))e s unlines$m$m$m$m$m$m["#"] ``` A direct implementation of hint1 in the spoiler. Function `m` generates the next iteration. The main functions applies `m` 6 times. Details to `m`: ``` m s= -- s is the current pattern zipWith(++) -- concatenate pairwise the lines of (r s)++ -- the lines of s in reverse order, followed by map(' '<$)s -- each char in s replaced by a space -- and map r s++ -- each line of s reversed, followed by foldr ... s -- the transposition of s e=[]:e;foldr(zipWith(:))e -- this right fold transposes a matrix ``` Edit: @ngn saved a byte and @Laikoni another 3. Thanks! [Answer] # Java 7, ~~259 238 237~~ 200 bytes ``` void f(){char[][]o={{35}},n;for(int s=1,x,y;s<64;s*=2,o=n)for(n=new char[64][64],x=s;x-->0;)for(y=0;y<s;n[s+y++][x]=32)n[s+~y][x]=n[y][2*s+~x]=n[s+x][s+y]=o[y][x];for(char[]b:o)System.out.println(b);} ``` Saved 2 bytes by removing the {} on the x loop, thanks ngn Saved 19 bytes from various assignment changes, thanks Jonathan Saved 24 bytes for print vs return (didn't know this was allowed), and Saved 13 bytes for loop changes, thanks Nevay [Try it online!](https://tio.run/##JY/BbsMgDIZfJcfQJKhNux5G2Rv01CPiQNJ0o0tNFNMOhLJXz4AdLPu3P1u/7@qlGjMNcL9@r/2oEIuz0hCmZzfqvkCrbEwvo6/FI/bLi501fFJKFQkw/GS4JPRWErasGYtl6L/ULKSQhoewf1uWGtjNzKUGWyDf1a72DE/HA8MNb2vDgaQp8HQwrx4PMkXtODLXNB9blgnPt8yfkIHAyleVFE7yfUuS/PVZgYi53USdBVZOJlZyIzKQbfy7694NuXi0w4Oap6VT/MuOUHbpkWX9Aw "Java (OpenJDK 8) – Try It Online") My first challenge, and I think respectable for Java. Uses hint 1, (which is wrong btw, but I can't write comments). It can probably be golfed further, this pass was basically as is, without pretty printing. [Answer] # [J](http://jsoftware.com/), ~~30~~ 27 bytes ``` |:@(|:@|.,|.@|:,.])^:6,.'#' ``` [Try it online!](https://tio.run/##y/qfmpyRr6CgpKdQa6WQl1@ap5CSmpaZl/q/xspBA4hr9HRq9BxqrHT0YjXjrMx09NSV1f9r/gcA) ### Original version. ``` ((|.,.|."1),' '"0,.|:)^:6,.'#' ``` [Try it online!](https://tio.run/##y/qfmpyRr6CgpGetkFxa4uOmkJdfmqeQkpqWmZf6X0FDo0ZPR49LQaFGD6iGy1BTR11BHchVMgCLAsWtFEC0ZpwViDKDiKorq//X/A8A) [Answer] ## Python 2, 586 bytes ``` import zlib,base64 as b print zlib.decompress(b.b64decode('eJyVVlsOwzAI++8pJuX+d1zXDGLAUKi0pUp52ATcfj7+Wni3dF2/677ZO1dw+z/Zd3+rJU4SdkVHMcYQS9OuJVGio4N61p31+TGoQkco6eqoU6gSWdBJRrQhjhIdvLQ6YhNrqrEtUsu8yEbjmRqUWXlgYbl5EHfLC7cDQl4sxxAhO4wUv7fFPTx22sUWqOeEJ544Z3vn9FPU+ZmdHtCak6Fk3hfCx0FkOC8DF4YvmgoFMnCEwW2cDBkzftoiGy4GZaNhM8VYSl3YMEV7ctxsjLQKRCHZ3IB6+ATZpKSKmEyGrqZvEHY8lEQBWf8zbuAg0eypWG6nRqTLIzM+NPQa2faN89FlxhMY2vcTKDP7579fl0rmIpJ+grTvSyis798ghb4vM0CuVgbM1SFdvukjnFnfR1Gt3vAEngd6lGrIDdfkDU/ARwl+ecMHf5SzIzct8KhsqHANZ0FqFbpXdad5qH2DzOHJIHGM2pz26oug9i2+EBpX+cXQCpBA7/tne01lLb4wviHjtJE=')) ``` [Try it online.](https://tio.run/##Jci3kptAAADQ3l9x3d3Nek4kASpcIDISQohMByxJpCULfl4ej8v30DYVXUu832WDumH62Osy/h1HY0pTH9H4Ef9CQ9n@7x@YJl2DhnQcv@KfmKb@GaZfn6m2uW49GuvOqQCwSJt9APHdF@Qr51xKDDnoSHB2kj0Z4LUlCSXiQDNMaOBwBfshhCQYNIeyYOUqehKY1smYNVcuO@pG44jEgS13ZpV0dNp3Dp1bHjxrj8EsnoUKl6tJB8Vt6AdxcsaZ3cT42Tx6x/PrPIjro6hkV55JBLOmxteLKwxqdRYmk@72iyBGx@uNVNSOFBWSS3uS7g4IG6hMfFTRUkUWGf/CpMrgWUGigqXJO0lveXH1iEQ4V3s2daW8UXIY3QqddQOrJgNddJlkeo3Pq3l58EpIqmcacHaILtalETd56MNFVAK2Fs2zl7F7PHM5lm7Ik@n20dtXddfB7W5GRBbd2JNUvwo9IJbEvgh35sicshobGhVpIB/sxdrKkTmxeRFTi47xs5vHOm5JcJmrZyu12QOXJ3LhxDaHdC0PqgCzSnAO3GOtQZroSna0dnVPJvZSjL3C3UJM6qUY@TCCx14hhN1QNFWRdQLtBN3N@akkgHhGPkh8k0dnjjlMbYrh9TWm1qVUnpMm/vn8/n6//wI) --- ## Python 2, ~~1032~~ 1025 bytes I like this one more. But it is much longer. It could be golfed down but there is no need for that. officialaimm's approach is much shorter. -7 thanks to Jonathan Frech ``` print''.join(' '*int(x)if'/'<x<'@'else("#"*(ord(x)-64),"\n")[x<"#"]for x in'99A9A2A4A2A1E2B4A9!99B8D4G2A3A4B8!88D8B6B4A2C1G8!88A2A9A7A4E1C1A2A8!88A2A1C1E3E4A9A2A8!88G1C2A2C2A4B8D8!88B4A3A2C2A2G8B55!98A4B2E3E1A2A9A55!88B4A559A9A2A1E2!98A4B99B8G2A2!98G88D8B4A2C!88C1A2A88A2A9A4E1!992A2A88A2A1C1E4A5!992D88G1C2A4B4!992B99B4A3A2G4!777A559A4B2E1A2A4!4A2A1E2B4A559A777!4G2A3A4B99B992!4B4A2C1G88D992!5A4E1C1A2A88A2A569!1E4A9A2A88A2A1C88!C2A4B8D88G98!2A2G8B99B4A89!2E1A2A9A559A4B88!55A9A2A1E3E2B4A98!55B8G2A2C2A3A4B88!8D8B4A2C2A2C1G88!8A2A9A4E3E1C1A2A88!8A2A1C1E4A7A9A2A88!8G1C2A4B6B8D88!8B4A3A2G4D8B99!9A4B2E1A2A4A2A9A99!99996A777!99996B992!99994D299!99994A2A992!99994A2A1C88!99994G98!99994B4A98!99995A4B88!9996E2B4A89!9995C2A3A4B88!9997A2C1G88!9997E1C1A2A88!9997A9A2A88!9997B8D88!9995D8B99!9995A2A9A99!9997A9A2A4A2A1E2!9997B8D4G2A2!9995D8B6B4A2C!9995A2A9A7A4E1!9995A2A1C1E3E4A5!9995G1C2A2C2A4B4!9995B4A3A2C2A2G4!9996A4B2E3E1A2A4!9995B4A559A5!9996A4B99B4!9996G88D4!9995C1A2A88A2A4!9999A2A88A2A1C!9999D88G1!9999B99B4A1!99991A559A4B') ``` [Try it online.](https://tio.run/##TVLJboMwEP2VOD0Yoi7C2GBLOdQs4iPa3pqoVBVEaQ706@ksdkykSDNvFt48v8vf7Wue1LperuN0k/L5ex6nTO7kAdJsycezfJHH5Shf5enn95TtH/aHbL5@Qump0vnj/n3a52/LEfCP83zdLbtxks5555XX8C961WjvhHON7fSgfOl1Y4W1nW0qqKi2GDCFVudrr/uiLSAOECR92WvahtBQtApGFO7oEIANJQFqsI0xwlkoKZgpaCEg1GMMMwI23IJ0gAxmA3FBJtDLH2c2wAVoqwggF9iEUBeY6EZjituIx6BFXdf0NWSBu7RIKiAOdRFlgDGYFjrKYDtMTRIBP2sqJ4ooAfOwVkQJ7OCs4OuJhHVC3W9HFtBrTLi95LdAhK9vw3OAkkECFZiIKEF55yKSCHVgI6IMFXERNsrQIR2xUYG2IQS/ikSgiO7HSHcqVKk1ovFcSvBUCvgIDA2zx1V0m6UdJt0FWR1PwjhdQxWXYr4ApwN53J5Y11tHxwHNFuIZdnOaq4OBKI1GNgRsbKwJ2NiYgGrj4nsHPqiJVXxtitE23JI8Q/nGMJSSaSliq3BcBJ/IfF3/AQ) [Answer] # Mathematica, ~~112~~ 90 bytes Thanks to Jonathan Frech for help saving 2 bytes! ``` ""<>Nest[{{(r=Reverse)@#,r/@#},{" "+0#,#}}~Flatten~{{1,3},{2,4}}&,{{"#"}},6]~Riffle~" " ``` [Try it online!](https://tio.run/##Dcq9CsIwEADg3aeQC4jSA39xqtLJUaS41Q5BrhioUS6Hy3F59dj143t7eYVnKjcOUTp4RMACUJ@vlKRTXfKppR9xolXjkNeNM1SYQ7VxeGcf0/eTaELLl9GLUMyqW9xPaYcHswWqggMzPPa5DcMwUoYZlL78AQ "Mathics – Try It Online") (Mathics) For some reasons, Mathics prints leading spaces in all lines except the first one when print multiline string. Also Mathics doesn't support operator``. Explanation: * `{{Reverse@#,Reverse/@#},{" "+0#,#}}` : Represent the reverse-horizontally, reverse-vertically, replace-all-by-`" "`, and transpose (`` is transpose operator in Mathematica), corresponding to different ways to reflect or rotate the image. * `~Flatten~{{1,3},{2,4}}` : Flatten in particular dimensions. * `Nest[ ... ,{{"#"}},6]` : Apply the function inside to `{{"#"}}` 6 times. * `~Riffle~"<literal newline character>"` : Riffle a newline character between each line. * `""<>` : Join all strings together. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~1016~~ ~~1002~~ ~~980~~ 955 bytes Saved 14 bytes thanks to Kevin Cruijssen! Saved 47 bytes thanks to Jonathan Frech! ``` o=>{foreach(var l in new[]{35223185965568,52841249260288,0xf00c0c277f00,0x9004043ee900,0x977c7c200900,0xfee4e4300f00,0xc22727f00c00,73934616658944,0xc2000020097c,73667282210788,0x7f0000f00c27,0xe9000090043e,9895614577696,0xf0000fee430,0xc0000c227f0,4398050918032,325982355457<<21,1092065689603<<20,835235872783<<20,291765223433<<20,0x7c20090000970000,-15289957744513<<17,21955973480545<<17,68788263321667<<16,68799053409<<17,206425089091<<16,0xf00c27277f0000,618546478825<<16,650622541833<<16,0xfee430300f0000,208473439235<<18,72203117569<<18,1<<21,3<<20,15<<20,9<<20,9895936,127<<17,97<<17,67<<16,15969<<17,3829596160,662634496,16105<<16,8201<<16,806289408,4027318272,9217L<<18,537463164,806293476,4027321383,2416182334,2541517856,4276413488,3257346032,1128152720,3254779936,1124073520,2130706672,3909091472,150995095,251658494,201326786,67108931})System.Console.WriteLine(System.Convert.ToString(l,2).PadLeft(64,'0').Replace('0',' ').Replace('1','#'));} ``` [Try it online!](https://tio.run/##TVNNa9tAED3Hv0KkB9uwMTOzs1/kA0qvKZSm0EPIQSjrVODIwRJpQshvd99qA6mFpZ3Z2Zn33sx241m3P@Tj0D7m8antcvOyeFt0u3Ycm1esxqmd@q553vf3zfe2H1bjdOiHh9u7pj08jGtEnNy8jlN@3Hztpn4/XNT9q2bbXB73l1dvW2Rvuz@r5/bQ7Jp@aIb89/buzToRy9El75yPxklUFk3iSWI09LIl6qiTELCAmYiU1OacqhlCFzohquY2Z81qiWpwJxIkzBnIBJusevbexaQ67xJ@5WzosOt9kCjCFOa65dicB7VhlnpzFdQ2KSbnWV0IPvmKEaG5VC55i1VKb8moTZEcJY5kxVhxKYp1DkcvLoQNUxLy4J08WXjIROhhXQTsWB2SOPiikdrqALQPwgV5eZszhmwpAY@qY4RxMMLJuRSsor662eUjqIm3VqACALAvrpTIWaVUT5FXcRQTIM8BtQFFxiqI8eiVei2ZXE3hyIs45VgA1iOzFLUNOCIUFUBsAjNERBNEyDIH59Ns8yxGpcdu/qT6htDJesMSZnipfj7AM4amwrZREIjmAp8HQ1X0hT1ThRiFKpsIqOg@RaMkAWMHYiYJh@sZh7NBvWWvcyDGJfgaKGyjNaJIif5ZNYWv4xAdAiR4ZegcS3/B05dWM0tEVwJIwKsBMhceGG0KaDFEYUuBytAZC7Wht2LJmJWEv0MFxqRqQi1iKz5ESB0YrbH8vv64at/2w7jf5c3vQz/l637Iq8@N53yYNr/2N/M1XO2MrDc/2vvrvJ1WILik5XrzMz/tcNNXMMyy@d/BcHxZrtfn78fzxcl2dXq6Pl@8l@f4Dw "C# (.NET Core) – Try It Online") --- # Explanation The format of the output is stored inside an array of signed 64-bit numbers, which fits perfectly since each line is 64 characters long. Empty spaces are represented by `0` and `#` is represented by `1`. The numbers are then converted to their binary string, zeros are padded left until the string is 64 characters wide and then the `0` and `1` characters are replaced with and `#`. The code is stored inside a lamba function, more specifically a `System.Func<string>`. Some constants in the `long[]` are shortened by performing some bit-shifting. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes ``` #↓##FE⁵X²ι«‖↑J⁻×³ι¹±⁰ψ⟲OO⁴ײι⟲CJ⁰±φT×⁴ι×⁴ι ``` [Try it online!](https://tio.run/##hZPRToMwFIav16c4oTclYcnUeaOXemUyXRZ8AELKJAFKCtuyGJ@9thSwHDokY4PDx/n//6xNvxKZiqRQai/zqmUBDcJnYq@fXsWliiCgXS0TEtguqdljBHtx4ZLdR5CHYQjfZHXgWcFT/cpnrdHV26msY8F2eXVqWJyXvGEPBo7gTp/v/Ji0nG1Cg1qpq7k8iFbXP85cFknd/7BtBLaBVRuxF1FfmaO1GftmHRXLvOylt1baudHAj1IwHLT7oubUh7ntKmR8TgdqYCgG@jcpdbq5gPn0xF83DCA/hpxIzPzo2ggMZdePYVwAsB9qgWluxHbAJPdUTAM4NzZMcG4cmeDc2A/BubEfgnNjPwTnxn6cQQHcmIPn@f8A8uBRuA145zDrvyjhm8M8wdIc0P5Y6DBbk/79QbwzcPYHWRqSvwNam2Tpr6I@k3htqvVZrZviFw "Charcoal – Try It Online") Link is to verbose version of code. Would be 25 bytes if this worked: ``` #FE⁷X²ι«‖↑⟲C→⁴⟲CJ⁰±φTιι ``` Explanation: ``` #↓## ``` Manually generate the first recursion, since it's not possible to rotate around (1, 0.5). (Such a rotation would only make sense if it was 180°.) ``` FE⁵X²ι« ``` Loop over the first five powers of 2 (1, 2, 4, 8, 16). ``` ‖↑ ``` Reflect the canvas vertically. This completes the top left quarter of the result. ``` J⁻×³ι¹±⁰ψ⟲OO⁴ײι ``` Rotate the canvas 180° around a point half-way up the right-hand side. The copy ends up in the correct position for the top right quarter of the result. ``` ⟲C ``` Rotate the canvas 90° around the bottom right corner. The copy of the top right corner ends up in the correct position for the bottom right corner of the result. The copy of the top left corner is extraneous. ``` J⁰±φT×⁴ι×⁴ι ``` Trim the canvas to the size we want. The trim starts at the cursor or the top left of the canvas, whichever is bottom rightmost. The cursor is therefore sent to (0, -1000) to ensure that it doesn't interfere with the trim. [Answer] # [Dyalog APL](https://www.dyalog.com/), 29 bytes ``` ⎕←(((⊖,⌽)⍪⊢∘' '¨,⍉)⍣6)1 1⍴'#' ``` [Try it online!](https://tio.run/##AUgAt/9hcGwtZHlhbG9nLWNsYXNzaWP//@KOleKGkCgoKOKKlizijL0p4o2q4oqi4oiYJyAnwqgs4o2JKeKNozYpMSAx4o20JyMn//8 "APL (Dyalog Classic) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~715~~ 711 bytes * -4 bytes thanks to @Jonathan Frech ``` for k in range(64):print"".join(ord(i)*" #"[j%2]for j,i in enumerate('            <?<<<89:11222 202 4 $"  !%$%$&%$($%&'))[k<<6:][:64] ``` [Try it online!](https://tio.run/##VZFBa4NAEIWZdeyam0QCmlys1URLKY2E0IrQHxJyCNS2JlSDpIf@ejs7Wbf2IKy7M@/NfO/8c/lsm7zv39suPIV1E3aH5qNKt5usOHd1c4mix2NbN2nbvaV1dh@Fd9HumOR7VX98qFVH1Xx/Vd3hUqWrKUxAANIHthAIC@EgSgEWoPDRETd0JyyQPlVMQALa9ERn9U8n27KRFXwJlqBK0iIFn7os/hPSEQu6E1QJrDGnN497wPboZSoc8vOkS27Ky2V9l2vRnumz8kII0GUfmo362EMG4LG@6nLMHh4Eeoup8PUOLgZmfqU507Nf9V09uys9nlrpe3pm5TDXM1sDJ3nddyCF130NK1Qb/2OFxO@PFRJbQ0oiDpxA5zGBEl5FiSWdS1Z4li9UXVDVmmdYa/ecXXPtlrNHTtpPpJmz0maUcqwTjky6ocn2dpRqMko0HuWZjNKMmfSSKSfENzZsU8M1JqIJ01wyx1WW7U5luS32u2K72ff9Lw "Python 2 – Try It Online") [Answer] ## [Perl 5](https://www.perl.org/), 452 bytes **451 bytes code + 1 for `-p`.** Packs all the data into the string, rather than stealing @[Neil](https://codegolf.stackexchange.com/users/17602/neil)'s [correct answer](https://codegolf.stackexchange.com/a/143253/9365). ``` $_=unpack"B*","\x00\x00\x20\x09\x09\x7c\xc2\x33\x00\x30\x0f\x0f\xe4\x43\x33\x00\xf0\x0c\x0c\x27\x7f\x33\x00\x90\x04\x04\x3e\xe9\x33\x00\x97\x7c\x7c\x20\x09\x33\x00\xfe\xe4\xe4\x30\x0f\x33\x00\xc2\x27\x27\xf0\x0c\x33\x00\x43\x3e\x3e\x90\x04\x33\x00\xc2\x00\x00\x20\x09\x7c\x00\x00\x43\x00\x00\x30\x0f\xe4\x00\x00\x7f\x00\x00\xf0\x0c\x27\x00\x00\xe9\x00\x00\x90\x04\x3e\x00\x00\x09\x00\x00\x97\x7c\x20\x00\x00\x0f\x00\x00\xfe\xe4\x30\x00\x00\x0c\x00\x00\xc2\x27\xf0\x00\x00\x04\x00\x00\x43\x3e\x90\x09\x7c\xc2\x00\x00\x20\x00\x00\x0f\xe4\x43\x00\x00\x30\x00\x00\x0c\x27\x7f\x00\x00\xf0\x00\x00\x04\x3e\xe9\x00\x00\x90\x00\x00\x7c\x20\x09\x00\x00\x97\x00\x00\xe4\x30\x0f\x00\x00\xfe\x00\x00\x27\xf0\x0c\x00\x00\xc2\x00\x00\x3e\x90\x04\x00\x00\x43\x33\x00\x20\x09\x7c\x7c\xc2\x33\x00\x30\x0f\xe4\xe4\x43\x33\x00\xf0\x0c\x27\x27\x7f\x33\x00\x90\x04\x3e\x3e\xe9\x33\x00\x97\x7c\x20\x20\x09\x33\x00\xfe\xe4\x30\x30\x0f\x33\x00\xc2\x27\xf0\xf0\x0c\x33\x00\x43\x3e\x90\x90\x04\x37\x00\x20\x37\x00\x30\x37\x00\xf0\x37\x00\x90\x37\x00\x97\x37\x00\xfe\x37\x00\xc2\x37\x00\x43\x36\x00\x7c\xc2\x36\x00\xe4\x43\x36\x00\x27\x7f\x36\x00\x3e\xe9\x36\x00\x20\x09\x36\x00\x30\x0f\x36\x00\xf0\x0c\x36\x00\x90\x04\x36\x00\x20\x09\x09\x7c\x34\x00\x30\x0f\x0f\xe4\x34\x00\xf0\x0c\x0c\x27\x34\x00\x90\x04\x04\x3e\x34\x00\x97\x7c\x7c\x20\x34\x00\xfe\xe4\xe4\x30\x34\x00\xc2\x27\x27\xf0\x34\x00\x43\x3e\x3e\x90\x34\x00\xc2\x00\x00\x20\x34\x00\x43\x00\x00\x30\x34\x00\x7f\x00\x00\xf0\x34\x00\xe9\x00\x00\x90\x34\x00\x09\x00\x00\x97\x34\x00\x0f\x00\x00\xfe\x34\x00\x0c\x00\x00\xc2\x34\x00\x04\x00\x00\x43"=~s/[3-9](.)/$1x$&/ger;y/01/ #/;s/.{64}/$& /g ``` Reversible output from `xxd` for 451 byte file: ``` 00000000: 245f 3d75 6e70 6163 6b22 422a 222c 2200 $_=unpack"B*",". 00000010: 0020 0909 7cc2 3300 300f 0fe4 4333 00f0 . ..|.3.0...C3.. 00000020: 0c0c 277f 3300 9004 043e e933 0097 7c7c ..'.3....>.3..|| 00000030: 2009 3300 fee4 e430 0f33 00c2 2727 f00c .3....0.3..''.. 00000040: 3300 433e 3e90 0433 00c2 0000 2009 7c00 3.C>>..3.... .|. 00000050: 0043 0000 300f e400 007f 0000 f00c 2700 .C..0.........'. 00000060: 00e9 0000 9004 3e00 0009 0000 977c 2000 ......>......| . 00000070: 000f 0000 fee4 3000 000c 0000 c227 f000 ......0......'.. 00000080: 0004 0000 433e 9009 7cc2 0000 2000 000f ....C>..|... ... 00000090: e443 0000 3000 000c 277f 0000 f000 0004 .C..0...'....... 000000a0: 3ee9 0000 9000 007c 2009 0000 9700 00e4 >......| ....... 000000b0: 300f 0000 fe00 0027 f00c 0000 c200 003e 0......'.......> 000000c0: 9004 0000 4333 0020 097c 7cc2 3300 300f ....C3. .||.3.0. 000000d0: e4e4 4333 00f0 0c27 277f 3300 9004 3e3e ..C3...''.3...>> 000000e0: e933 0097 7c20 2009 3300 fee4 3030 0f33 .3..| .3...00.3 000000f0: 00c2 27f0 f00c 3300 433e 9090 0437 0020 ..'...3.C>...7. 00000100: 3700 3037 00f0 3700 9037 0097 3700 fe37 7.07..7..7..7..7 00000110: 00c2 3700 4336 007c c236 00e4 4336 0027 ..7.C6.|.6..C6.' 00000120: 7f36 003e e936 0020 0936 0030 0f36 00f0 .6.>.6. .6.0.6.. 00000130: 0c36 0090 0436 0020 0909 7c34 0030 0f0f .6...6. ..|4.0.. 00000140: e434 00f0 0c0c 2734 0090 0404 3e34 0097 .4....'4....>4.. 00000150: 7c7c 2034 00fe e4e4 3034 00c2 2727 f034 || 4....04..''.4 00000160: 0043 3e3e 9034 00c2 0000 2034 0043 0000 .C>>.4.... 4.C.. 00000170: 3034 007f 0000 f034 00e9 0000 9034 0009 04.....4.....4.. 00000180: 0000 9734 000f 0000 fe34 000c 0000 c234 ...4.....4.....4 00000190: 0004 0000 4322 3d7e 732f 5b33 2d39 5d28 ....C"=~s/[3-9]( 000001a0: 2e29 2f24 3178 2426 2f67 6572 3b79 2f30 .)/$1x$&/ger;y/0 000001b0: 312f 2023 2f3b 732f 2e7b 3634 7d2f 2426 1/ #/;s/.{64}/$& 000001c0: 0a2f 67 ./g ``` [Try it online!](https://tio.run/##hVXbbhs3EH3XVxCuETVFQ41IijQbRECqfELf6sKwVlyjaJEYcQu4qNpPrzsXDpe7sZGFqCWH5JmZM5e9L59/3z09Xd68@/Pj/e3w28WP3118f3H9CCDD0TvLSMP14@CuH72XPU97o4wSrh@Dn/ZG2htkuIR3x2kv016Q4Qvezd1eEj00VHfDLKKHhurWPbKL9NBQ3brHdhUZqru/t/SVdKss@GmuOkm/ysgvnateskFl5JvOm@4yyaDfT53fOnr80vmuo7NVORj7/TD3pXHQxXPmf6dXYzrzv9OrcZ353@nV2M78V966@Pb@N966GPf@N1u7OPf@N1u7WM/891/G@qW81lx7Lq81157La8215/Lawct57eHlvB7h5bzOve40@adz383Hbp77eerOlGnOvKROX5zix3txile/37iJUzyYjzjnv@2r33HOs66bf/H5vuTD8z1J5ct@pPJlL2ryRR9qOIsepPJl/1H5svf05/u668/39abyZZ2pfFlfKl/WVZMv6qnJF3XU5LP6uXj378PmZ/8m//Ktfb253D5evtrclc9v/9rAdmO@2bx92Ni/Y/hnc/lqtblbrW5uPrz/6f3NzQrq84NxYTcaf0o7E0sCE7fRm3h0zgTnbo1zbsA/AGMWnyRbMbaIAeDAQIZs0jA44z2exzEaGEswwXuPR0bEsMbas/UWrLUHbxXDEcYAqCmlUa5ngGAg@GJK5us5IXgaEMOuEQGfPb3O54rhyRc8JtfHgopL8GjWyNfRLJdcMiNODYIwAtBrvW52BMTg62hyMb5kIBPqdTogGtJAfHh72O@tABn0qmLsmI/g5TyzUALOANA1lrEJLhGGPVjmQp61YkTGKFnOMxW@MAaoLCEVDhjDChn8nI1iJMYA1Ul8eBCMQWSDEz4aBqgZinElGEHOMykZNMrKB4gaxjjsKb7ER8PIiFFCx0c1gUOtfICoaXysKyMV45biUjo@mM5BolH5YBk6aSYmZhhHwuj44POaEJUPlqGTZmJCyK0YA2Lkng@vqY/GLFJf@PCUGpLxFePEfMzKArMrLVPfF7JDqoRSlF57taMQRlcWDpap70FTn1P9XDMeMOMrxsix5bIYa05OqY@lzKmfxD8jVHiOr03WrGrpE6eJPeajCMTLLEu0jZdjwaVJFhJd1l/F2KodfBS1R4nt4HgmREWJlaGbh4gpFi291xWD@kca@ZQ0jKhxERlTEbUHRSyWaOkNhFMxPPcgPiW@x1lb80GBOLZ4jzHsOVDCVozAseWjHFZOc14ypIQ1CDPGBk4x/t@HhkH9gxudAwEqki5ellMfw6U5nw3fh8BJEipG1B7EWZTbzVqyvNSKNNzGGAWxDs2OxPXCR6dC5eVUh7xEegzwfdv@K0btH1SecrRVnyxb4ZEv/X36rxh50YPwy4Rfq2KSd6PZHTHD3clnszu5q1pz3UexYlD/cMVl40aHTG7TFX72XMRlTCbuEkIeE@164mPxIa0Y3D@2qNOB83T0KCa4ko7GR/QgnWhJuOaLj69gUP@AWzyFar/62M3d09Pqv0/3f/z66ePD05v7/wE "Perl 5 – Try It Online") [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), ~~538~~ ~~535~~ ~~488~~ 476 bytes This is a straightforward representation. ~~I haven't attempted any fancy encodings yet.~~ Replaced 0,0 pairs with Z function. Thanks again to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech) for helping eliminate 3 bytes! ``` def B:recurse(if.>0then./2|floor else empty end)|.%2;def S:256+.|[B]|reverse[2:]|map(if.>0then"#"else" "end)|join("");def Z:0,0;[[Z,3,1,1,4,5,2],[1,4,5,2,2,3,Z],[Z,Z,2,3,Z],[Z,Z,3,1,1,4]]as$m|[[],[9,15,12,4,124,228,39,62],[Z,Z,Z,Z,124,228,39,62,32,48,240,144],[32,48,240,144,151,254,194,67,194,67,127,233,9,15,12,4],[124,228,39,62,32,48,240,144,32,48,240,144,151,254,194,67],[194,67,127,233,9,15,12,4,9,15,12,4,124,228,39,62]]as$c|$m[]|range(16)as$l|map($c[.][$l]|S)|join("") ``` Character count ``` $ wc -c picture.jq 476 picture.jq ``` Sample run ``` $ jq -Mnr -f picture.jq # # # # # ##### ## # ## #### ####### # # ## #### ## ## # ### ####### # # # # ##### ### # # # # ### ##### ##### # # # ####### ### # ### # ## #### ## # # ### # ####### ## # ## ##### ##### # # # ## # # # # ##### # ## ## ####### # ####### #### ## # ### ### # # # # # ##### # # # # ### ##### # #### ####### ### # ## ## ## # # ####### # # ## ##### # # # # ##### ## # # ####### # # ## ## ## # ### ####### #### # ##### ### # # # # ##### # # # # # ### ### # ## #### ####### # ####### ## ## # ##### # # # # ## # # # ##### ##### ## # ## ####### # ### # # ## #### ## # ### # ### ####### # # # ##### ##### ### # # # # ### ##### # # # # ####### ### # ## ## #### ## # # ####### #### ## # ## ##### # # # # # # ## #### # # # # ### ####### ## # # ## ##### ## # ### # # ## # ### ####### ##### ### # # # # # ## #### #### ## # # # # # # # # ##### ## #### ####### # #### ## ## # ### # # # # ##### # # ### ##### ##### # ####### ### # ### # ## ## # # ### # ####### # ## ##### ##### # # ## # # # ## ## ####### #### ### # # # # # # # # ### #### ####### ## ## # # # ## ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~174~~ ~~164~~ 154 bytes (based on matrix operations) * -10 bytes thanks to ngn. * -10 bytes thanks to Jonathan Frech. ``` from numpy import* s=[['#']] exec'b=fliplr(s);s=vstack((hstack((flipud(s),b)),hstack((eye(len(s)),rot90(b)))));'*6 s[s>'#']=' ' for l in s:print''.join(l) ``` [Try it online!](https://tio.run/##NYzRCsIgGEbvfQqhi1@HRHQR1HAvIrtoS5nlVPxd5NObg/puDpwDXyx5Cf5cq0lhpX5bY6F2jSHljqBUCg4wjkR/9AyTNM5GlxjyHuUb831@Mbb8uLft0ZqYOBd/q4tmTvumuUghX0@s1bYeugtBhcP@L4ECMSFRR62neIvJ@gxwfAbrmeO1fgE "Python 2 – Try It Online") [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), ~~32~~ ~~31~~ 27 bytes ``` 6{,[|x;""x],'(+|+x),+x}/"#" ``` [Try it online!](https://tio.run/##y9bNS8/7/9@sWie6psJaSakiVkddQ7tGu0JTR7uiVl9JWen/fwA "K (ngn/k) – Try It Online") `6{` `}/` 6 times do `+x` transpose `|x` reverse vertically `+|+x` reverse horizontally `,` concatenate vertically `,'` concatenate horizontally `,[A;B]` is the same as `A,B`. it helps avoid parentheses around `A` and around the whole expression `""x` use the elements of `x` as indices in the empty string. out-of-bounds indexing produces spaces, so this expression will return an all-spaces matrix, same size as `x` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 10 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` #6[↔ω⤢∔ω↶× ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JTIzJXVGRjE2JXVGRjNCJXUyMTk0JXUwM0M5JXUyOTIyJXUyMjE0JXUwM0M5JXUyMUI2JUQ3,v=8) [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~976~~ 969 bytes ``` o=>{foreach(var l in new[]{35223185965568,52841249260288,0xf00c0c277f00,0x9004043ee900,0x977c7c200900,0xfee4e4300f00,0xc22727f00c00,73934616658944,0xc2000020097c,73667282210788,0x7f0000f00c27,0xe9000090043e,9895614577696,0xf0000fee430,0xc0000c227f0,4398050918032,0x97cc20000200000,0xfe44300003<<20,0xc277f0000f<<20,0x43ee900009<<20,0x7c20090000970000,-0x1bcff0ffff020000,0x27f00c0000c20000,0x3e90040000430000,9017629528424448,0x300fe4e4430000,0xf00c27277f0000,0x90043e3ee90000,0x977c2020090000,0xfee430300f0000,0xc227f0f00c0000,0x433e9090040000,2097152,3145728,15728640,9437184,9895936,16646144,12713984,4390912,2093088768,3829596160,662634496,1055457280,537460736,806289408,4027318272,2416181248,537463164,806293476,4027321383,2416182334,2541517856,4276413488,3257346032,1128152720,3254779936,1124073520,2130706672,3909091472,150995095,251658494,201326786,67108931})System.Console.WriteLine(System.Convert.ToString(l,2).PadLeft(64).Replace('0',' ').Replace('1','#'));} ``` [Try it online!](https://tio.run/##TVPBbtswDD03X2F0hySAGlAUJUpIW2DYtQOGdcAORQ@uKnceUruIja5F0W/PKNnp5iCGRNF87/FRcTiL/T4duvoxDU91TNXL4m0Rd/UwVK@yGsZ6bGP13Lf31de67VbDuG@7h5vbqt4/DGvJOLl@Hcb0uPkcx7bvzvu73ymOl1VTXRz6i8u3RqrX8dfqud5Xu6rtqi79ubl9MxbRaG@Ds9Z5ZdGTRgroAL1X8NIARIjILAvZBgACMimFacscOSLAtG1SokQGYEqOiIxcKoBiEww57Zz1gaicgjz5W45y6hyjR9TABTd/VuoItmwzXkERbBV8sE6TZXbBTRwlNWXkXDfvMnQDikzwYCFoDwYL3/gBCzNlyoQBzPk5TqR5xp4Ds1pBnwNHwZl5qXIGL/ouNg008kylJe2oPJOZQyaV/kGWUUIBNDsMuetIRFl47l7u4pwxOZD7OLGaPTDpyGp2AeFIavbBwOTDhxMNHPkUUZnLkY1CkaItKpO7il7p/HYkBMmw9lRaHoxT4p@YKP5pZC3Npdxi6S/mEga8Zxki40VSEK9BOYfOEIlNGqwtxUFZw@RALFceHMo4gFcEyDKHIlQhaae9TKGfMo12VDJlgNhNmaiNN3MmGkMKLWmr2VtJQHakDckcGbQsU5fN1xq9SGSxUKLEHIoegREmVqJSEhjyGKosSUSRLLVMT5C/FQQts0tBsEAbdOydcqzBB6Pf1/Pl@9J3Q79Lm5/7dkxXbZdW/w6e037c/Oivy8Vd7RSuN9/q@6vUjCtH68339LSTe79awlItq@V/AS2BT8v1evt@2C5OmtXp6Xq7eM@/w18 "C# (.NET Core) – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 739 bytes ``` _=>{var r="";for(int i=0,j,k=0;i<626;i++)for(j=0;j++<@"4#+#$#&#$##'$$&#=$*&&)$#%#&$:&*$($&#$%#):#$#+#)#&'#%##$#:#$##%#'%'&#+#$#:)#%$#$%$#&$*&:$&#%#$%$#$)*$=#&$$'%'##$#+#<$&#5#+#$##'5#&$4$*)$#5)2&*$&#$%2%##$#2#$#+#&'7#$#2#$##%#'&#;&2)#%$#&$:$4$&#%#$);#5#&$$'##$#*#$##'$$&#5#;)$#%#&$4$:$&#$%#)2&;#&'#%##$#2#$#7'&#+#$#2#$##%2%$#&$*&2)5#$)*$4$&#5'##$#+#5#&$<#+#$##'%'$$&#=$*)$#$%$#%#&$:&*$&#$%$#$%#):#$#+#&'%'#%##$#:#$##%#'&#)#+#$#:)#%$#&$($*&:$&#%#$)&&*$=#&$$'##$#&#$#+#^#a$^&^#$#^#$##%Z)[$&#\#&$S'$$&#S%$#%#&$T#$%#)T'#%##$#T#+#$#T$*&R&*$T#$#+#V#+#$#&#$##'F$*&&)$#D&*$($&#$%B#$#+#)#&'C#$##%#'%'&#G)#%$#$%$#&$F$&#%#$%$#$)G#&$$'%'##$#F$&#5#H#&$4$G)2&F%##$#2#$#J#$#2#$##%F&2)G$4$&#H#5#&$"[i]-34;){r+=i%2<1?' ':'#';if(++k%64<1)r+='\n';}return r;} ``` [Try it online!](https://tio.run/##bVNha9swEP3eXyEsWbLitLRenIJld2MdThkMxmI2WNoMkyVBaWuD7BZGyG/PTmfF9WACO2fd3Xt375FVc76qzfq4eiqbhnw19daUz2cEzh7f9jRt2eoVea31b/Kl1FXQtEZX28UDKc22kX3dW4c98z9Nu36@yF@qVdo1jLufG7Ih2fFXdrN/LQ0xmeepTW0CXbVEZ5fj3fgxu1Q6nUZTpcNQ2twObnZhmH7wJjSkjHJ4qGCM04yNOJeM@pSzhI9YAHfMpzKBipBKygWkILbfEAlfcERIJPUZVAIWICTQ5eMXkyOWwR2DSooYKeRi7KEihsyEjYAvlhGwWa4I8SOs5eLaxZaLU8Uj5IHZoA85pKIx4tuuUb9HTJXbYsISt0PEVT@/xbx2s3f4kZs9kjFObfFjN7NlSN3M/kkn2e17Uop3@/ZacbvxP1px0O9NKw7a9kpJzk86UedHSJe0ZEu@hHiJCD/lAqrvoWqOM8wde4GshWMrkKMA7G@AWSDS94HLuXP4U@/ux97b24Grs4Gj@cDP2cDNHJW@Q5VnoG/ea/u51zUHRWeo5h3q6C30w/m7iZJ7E2baj9Kr94KIRFCh9CYIw0d/OkmvJCTFfSXUwazbF1MRow5Hdfa/f8RtXTX10/rih9HtOtgEniel6gsPGB2OfwE "C# (.NET Core) – Try It Online") Uses the same approach is [this other answer](https://codegolf.stackexchange.com/a/126301/70347). [Answer] # [JavaScript (Node.js)](https://nodejs.org), 1233 bytes ``` _=>` 18# 9# 2# 4# 2# #5 2#2 4# 18#2 8#4 4#7 2# 3# 4#2 16#4 8#2 6#2 4# 2#3 #7 16# 2# 9# 7# 4#5 #3 # 2# 16# 2# #3 #5 3#5 4# 9# 2# 16#7 #3 2# 2#3 2# 4#2 8#4 16#2 4# 3# 2#3 2# 2#7 8#2 17# 4#2 2#5 3#5 # 2# 9# 16#2 4# 19# 9# 2# #5 17# 4#2 18#2 8#7 2# 17#7 16#4 8#2 4# 2#3 16#3 # 2# 16# 2# 9# 4#5 20# 2# 16# 2# #3 #5 4# 20#4 16#7 #3 2# 4#2 20#2 18#2 4# 3# 2#7 21# 19# 4#2 2#5 # 2# 4# 2# #5 2#2 4# 19# 4#7 2# 3# 4#2 18#2 4#2 4# 2#3 #7 16#4 5# 4#5 #3 # 2# 16# 2# #5 4# 9# 2# 16# 2# #3 #3 2# 4#2 8#4 16#7 2# 2#7 8#2 18#2 4# 2#5 # 2# 9# 19# 4#2 10# 9# 2# #5 3#5 2#2 4# 10#2 8#7 2# 2#3 2# 3# 4#2 8#4 8#2 4# 2#3 2# 2#3 #7 8# 2# 9# 4#5 3#5 #3 # 2# 8# 2# #3 #5 4# 7# 9# 2# 8#7 #3 2# 4#2 6#2 8#4 8#2 4# 3# 2#7 4#4 8#2 9# 4#2 2#5 # 2# 4# 2# 9# 42# 42#2 40#4 40# 2# 40# 2# #3 40#7 40#2 4# 41# 4#2 33#5 2#2 4# 32#3 2# 3# 4#2 34# 2#3 #7 34#5 #3 # 2# 34# 9# 2# 34#2 8#4 32#4 8#2 32# 2# 9# 34# 9# 2# 4# 2# #5 34#2 8#4 4#7 2# 32#4 8#2 6#2 4# 2#3 32# 2# 9# 7# 4#5 32# 2# #3 #5 3#5 4# 32#7 #3 2# 2#3 2# 4#2 32#2 4# 3# 2#3 2# 2#7 33# 4#2 2#5 3#5 # 2# 32#2 4# 19# 33# 4#2 18#2 33#7 16#4 32#3 # 2# 16# 2# 36# 2# 16# 2# #3 36#4 16#7 36#2 18#2 4# 37# 19# 4#2`.replace(/(.)(\d+)/g,(_,c,n)=>c.repeat(n)) ``` [Try it online!](https://tio.run/##ZVPLbsIwELz7Kyz54qgUEjuJkwN8SSWIQqhaoQQB6u/T3fU7XCx7dr2eHc/@Dn/DY7z/3J6f83KeXpf967g/nHjVCd4LrgSvaRUNrAoODEOKd6KGg8GQxhwFeAsYxlpKhJDmwhCOaVDNYGbDEQckRPDcQJkGb/UhZDCgbB3iQa9SiOrrEFKQ2xEFY/OUq@cejneq3rclmpjuOjL2ZQOb0IvtgwpY1kk7NdZQZYraVlAlwOu0C5IIQPea5w/6qMry8sStACvZMYPlilMhRrugNhFnvMmEduQYTxSOhFkmL1FmiaieLgvcsIDjC7qUUVCSPLikDJr6b/JG6TJtfQI@2yXS2g/0VukyedFJvQ8kCpP1yCSZxrCrrUFWMjuVSVplF1S0xAp16T6i9ELh1tBqW6wr15BOG9erbnUyCjqzv45218HdcN1x1SqQC5nBFvGKM0W8mcxfUsQNX0DSoSPwfdwIfh816vdtzGIyOVVnHoWTtybJk7lStytDIuKNqNvUgtoE65229@l2HcZJ7uS2kF/nj2L3vZHHzbiZi/1hxPA0POVcFK9xmR/Lddpel295kQD8Aw "JavaScript (Node.js) – Try It Online") ]
[Question] [ Write a program that, given any 'n' number of strings of 'm' length, returns 'm' number of 'n'-length strings, with this condition: **Every new string should contains the letters at the same index of the others strings** For example, the first output string must contain the first letter of all the input strings, the second output string must contain the second letter of all the input strings, and so on. Examples (the numbers under the letters are the indexes of the strings): ``` input: "car", "dog", "man", "yay" 012 012 012 012 output: "cdmy", "aoaa", "rgny" 0000 1111 2222 input: "money", "taken", "trust" 01234 01234 01234 output: "mtt", "oar", "nku", "ees", "ynt" 000 111 222 333 444 ``` Assume that the input is correct everytime Shortest bytes' code wins! **Edit:** Since there are many programming languages, and there could be many possible solutions for each of them, I will post the shortest solution for each programming language and the user who provided it. Keep coding! **Re-Edit:** Thanks to user [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) I inserted a snippet for the leaderboards. ``` var QUESTION_ID=85255,OVERRIDE_USER=56179;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, 1 byte ``` C ``` [Try it here](http://pyth.herokuapp.com/?code=C&input=%22car%22%2C+%22dog%22%2C+%22man%22%2C+%22yay%22&debug=0) Another transpose builtin [Answer] # Python, ~~36~~ 29 bytes `zip(*s)` returns a list of tuples of each character, transposed. ``` lambda s:map(''.join,zip(*s)) ``` [**Try it online**](https://repl.it/CbMM/1) [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 1 byte ``` Z ``` [Try it online!](http://jelly.tryitonline.net/#code=WgrDh-KCrEc&input=&args=WyJjYXIiLCAiZG9nIiwgIm1hbiIsICJ5YXkiXSwgWyJtb25leSIsICJ0YWtlbiIsICJ0cnVzdCJd) [Answer] # Vim, ~~37~~ 36 keystrokes All the other answers are boring, and using boring single-byte builtins. Here's a hacky answer that does the entire thing manually, in something that isn't even a programming language: ``` Gmaqqgg:s/./&<cr>d<C-v>`aGo<esc>pvGgJ@qq@q`adgg ``` Explanation: ``` G "move to the end of this line ma "And leave mark 'a' here qq "Start recording in register 'q' gg "Move to the beginning :s/./&<cr> "Assert that there is atleast one character on this line d "Delete <C-v> "Blockwise `a "Until mark 'a' G "Move to the end of the buffer o<esc> "Open a newline below us p "And paste what we deleted vG "Visually select everything until the end gJ "And join these without spaces @q "Call macro 'q'. The first time, this will do nothing, "The second time, it will cause recursion. q "Stop recording @q "Call macro 'q' to start it all ``` Now, everything is good, but the buffer has some extra text left over. So we must: ``` `a "Move to mark 'a' dgg "And delete everything until the first line ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 1 byte ``` ! ``` [**Try it online!**](http://matl.tryitonline.net/#code=IQ&input=WydjYXInOyAnZG9nJzsgJ21hbic7ICd5YXknXQ) Takes input implicitly, transposes, displays output implicitly. [Answer] ## PowerShell v2+, ~~66~~ 54 bytes ``` param($n)for($x=0;$n[0][$x];$x++){-join($n|%{$_[$x]})} ``` Yo ... no `map`, no `zip`, no `transpose`, etc., so we get to roll our own. Big props to [@DarthTwon](https://codegolf.stackexchange.com/users/56063/darth-twon) for the 12-byte golf. Takes input `$n`, sets up a `for` loop. Initialization sets `$x` to `0`, the test is whether we still have letters in our word `$n[0][$x]`, and we increment `$x++` each iteration. Inside the loop, we take our array of strings, pipe it to an inner loop that spits out the appropriate character from each word. That is encapsulated in a `-join` to form a string, and that string is left on the pipeline. At end of execution, the strings on the pipeline are implicitly printed. ``` PS C:\Tools\Scripts\golfing> .\convert-n-strings.ps1 "Darth","-Twon","Rocks" D-R aTo rwc tok hns ``` [Answer] ## CJam, ~~6~~ 5 bytes *Saved 1 byte thanks to Luis Mendo.* ``` qS%zp ``` [Try it online!](http://cjam.aditsu.net/#code=q%20%20%20%20%20%20e%23%20Get%20all%20input%0A%20S%25%20%20%20%20e%23%20Split%20it%20on%20spaces%0A%20%20%20z%20%20%20e%23%20Take%20the%20transpose%0A%20%20%20%20p%20%20e%23%20Print%20it%20as%20an%20array&input=car%20man%20dog%20yay) ``` q e# Get all input S% e# Split it on spaces z e# Take the transpose p e# Print it as an array ``` [Answer] ## [Retina](https://github.com/m-ender/retina), ~~45~~ 43 bytes Byte count assumes ISO 8859-1 encoding. ``` O$#`.(?<=(.+))|¶ $.1 !`(?<=(¶)+.*)(?<-1>.)+ ``` The leading linefeed is significant. Input and output are linefeed-terminated lists of printable ASCII strings (note that both have a single trailing linefeed). [Try it online!](http://retina.tryitonline.net/#code=TyQjYC4oPzw9KC4rKSl8wrYKJC4xCiFgKD88PSjCtikrLiopKD88LTE-Likr&input=YWJjZGUKZmdoaWoKa2xtbm8K) I knew for a while that transposing rectangular blocks would be a pain in Retina (whereas transposing squares isn't too bad), but never actually tried. The first solution was indeed a whopping 110 bytes long, but after several substantial changes in the approach, the resulting 45 bytes are by far not as bad as I suspected (but still...). Explanation will follow tomorrow. ### Explanation **Stage 1: Sort** ``` O$#`.(?<=(.+))|¶ $.1 ``` This does the main work of reordering the characters in the input, but it ends up messing up the separation into lines. Interestingly, if we remove the `|¶`, we get the code required to transpose a square input. Sort stages (denoted by the `O`) work like this: they find all matches of the given regex (the thing after the ```), and then sort those matches and reinsert them into the places where the matches were found. As it happens, this regex matches every single character: non-linefeeds via the `.(?<=(.*))` alternative and linefeeds via the `¶`. Hence, it sorts all characters in the input. The more interesting part is what they are sorted *by*. The `$` option activates a "sort-by" mode, where each match is replaced with the substitution pattern on the second line, which is then used for comparing the matches. Furthermore, the `#` tells Retina to convert the result of the substitution to an integer, and compare those integers (instead of treating them as strings). So finally, we need to look at the regex and the substitution. If the first alternative matches (i.e. we have matched any character within one of the lines), then the `(?<=(.*))` captures everything up to that character on that line into group `1`. The `$.1` in the substitution pattern replaces this with the *length* of group `1`. Hence, the first character in each string becomes `1`, the second becomes `2`, the third becomes `3` and so on. It should be clear now how this transposes a square input: all the first characters of the lines come first and all end up in the top-most line, then all the second characters end up in the second line and so on. But for these rectangular inputs, we're also matching the linefeeds. Since group `1` is unused in this case, the substitution is empty, but for the purposes of the `#` option, this is considered `0`. That means, all the linefeeds are sorted to the front. So now we do have the characters in the first order (first character of each string, second character of each string, etc.) and all the linefeeds at the start. **Stage 2: Match** ``` !`(?<=(¶)+.*)(?<-1>.)+ ``` We now need to split up the characters into lines of the correct length. This length corresponds to the number of lines in the original input, which is corresponds to the number of linefeeds we have at the beginning of the string. The splitting is done here with the help of a match stage, which simply finds all matches of the given regex and uses the `!` option to print those matches (the default would be to count them instead). So the goal of the regex is to match one line at a time. We start by "counting" the number with the lookbehind `(?<=(¶)*.*)`. It generates one capture in group `1` for every linefeed at the front. Then, for each of those captures, we match a single character with `(?<-1>.)+`. [Answer] ## Pyke, 1 byte ``` , ``` [Try it here!](http://pyke.catbus.co.uk/?code=%2C&input=%22money%22%2C+%22taken%22%2C+%22trust%22) Transpose. [Answer] # x86 machine code, 19 bytes In hex: ``` fc89d35651a401dee2fb91aa595e464a75f1c3 ``` Input: `ECX`: # of strings (n), `EDX`: individual string length (m), `ESI`: array of input strings, `EDI`: output buffer receiving array of strings. Array is presumed to be defined as `char src[n][m+1]` for input and `char dst[m][n+1]` for output, and all strings are NULL-terminated. ``` 0: fc cld 1: 89 d3 mov ebx,edx ;EDX is the counter for the outer loop _outer: 3: 56 push esi 4: 51 push ecx _inner: 5: a4 movsb ;[EDI++]=[ESI++] 6: 01 de add esi,ebx ;Same char, next string 8: e2 fb loop _inner ;--ECX==0 => break a: 91 xchg eax,ecx ;EAX=0 b: aa stosb ;NULL-terminate just completed string c: 59 pop ecx d: 5e pop esi ;First string, e: 46 inc esi ;...next char f: 4a dec edx 10: 75 f1 jnz _outer 12: c3 ret ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` z:ca. ``` Expects a list of strings as input, e.g. `run_from_atom('z:ca.',["money":"taken":"trust"],Output).` ### Explanation ``` z Zip the strings in the Input list :ca. output is the application of concatenation to each element of the zip ``` [Answer] ## 05AB1E, 3 bytes ``` ø€J ``` **Explained** ``` # implicit input, eg: ['car', 'dog', 'man', 'yay'] ø # zip, producing [['c', 'd', 'm', 'y'], ['a', 'o', 'a', 'a'], ['r', 'g', 'n', 'y']] €J # map join, resulting in ['cdmy', 'aoaa', 'rgny'] ``` [Try it online](http://05ab1e.tryitonline.net/#code=w7jigqxK&input=WydjYXInLCAnZG9nJywgJ21hbicsICd5YXknXQ) [Answer] # [CJam](https://sourceforge.net/projects/cjam/), 3 bytes ``` {z} ``` This is a code block (equivalent to a function; [allowed by default](https://codegolf.meta.stackexchange.com/q/2419/36398)) that expects the input on the stack and leaves the output on the stack. [**Try it online!**](http://cjam.tryitonline.net/#code=cX4gICAgZSMgcmVhZCBpbnB1dCBhcyBhbiBhcnJheQp7en0gICBlIyBhY3R1YWwgY29kZSBibG9jawp-ICAgICBlIyBldmFsdWF0ZSBjb2RlIGJsb2NrCnAgICAgIGUjIGRpc3BsYXkgYXMgYXJyYXk&input=WyJjYXIiICJkb2ciICJtYW4iICJ5YXkiXQ) [Answer] # JavaScript ES6, ~~48~~ 46 bytes ``` a=>[...a[0]].map((n,x)=>a.map(a=>a[x]).join``) ``` I feel left out, we have no built in zip function. Thanks nicael for pointing out my type error. Usage ``` (a=>[...a[0]].map((n,x)=>a.map(a=>a[x])))(["asd","dsa"]); //or whatever is above, might change due to edits ``` returns ``` ["ad","ss","da"] ``` [Answer] # Bash + BSD utilities, 27 ``` sed s/./\&:/g|rs -c: -g0 -T ``` I/O via STDIN/STDOUT newline-separated strings. You may need to install `rs` with `sudo apt install rs` or similar. Works out of the box on OS X. The `-T` option to `rs` does the heavy lifting of the transposition. The rest is just formatting: * The `sed` command simply inserts `:` after every character * `-c:` specifies input columns are `:` separated * `-g0` specifies output columns have zero width separation If my reading of the `rs` manpage is correct, then the following **ought** to work for a score of 12, but unfortunately it doesn't work - see note below: ``` rs -E -g0 -T ``` ### Example output: ``` $ printf "%s\n" car dog man yay |sed s/./\&:/g|rs -c: -g0 -T cdmy aoaa rgny $ ``` If input is expected to be all printable ASCII, then the `:` may be replaced with some unprintable character, e.g. 0x7 `BEL`. --- ### Note I wanted to understand why I couldn't get the `-E` option to work and get rid of the `sed` preprocessing. I found the [`rs` source code here](https://github.com/denghuancong/4.4BSD-Lite/blob/master/usr/src/usr.bin/rs/rs.c). As you can see, giving this option sets the `ONEPERCHAR` flag. However, there is nothing in the code that actually checks the state of this flag. So I think we can say that despite the fact that is option is documented, it is not implemented. In fact, this option is documented in the Linux `rs` manpage: > > -E Consider each character of input as an array entry. > > > but not the OS X version. [Answer] # PHP, 82 bytes ``` function f($a){foreach($a as$s)foreach(str_split($s)as$i=>$c)$y[$i].=$c;return$y;} ``` takes and returns an array of strings **break down** ``` function f($a) { foreach($a as$s) // loop through array $a foreach(str_split($s)as$i=>$c) // split string to array, loop through characters $y[$i].=$c; // append character to $i-th result string return$y; } ``` **examples** ``` $samples=[ ["asd","dsa"], ["ad","ss","da"], ["car", "dog", "man", "yay"], ["cdmy", "aoaa", "rgny"], ["money", "taken", "trust"], ["mtt", "oar", "nku", "ees", "ynt"] ]; echo '<pre>'; while ($samples) { echo '<b>in:</b> '; print_r($x=array_shift($samples)); echo '<b>out:</b> '; print_r(f($x)); echo '<b>expected:</b> '; print_r(array_shift($samples)); echo '<hr>'; } ``` [Answer] ## APL, 3 bytes ``` ↓⍉↑ ``` `↑` takes the input strings and turns them into a char matrix. `⍉` transposes the matrix. `↓` splits back the rows of the resulting matrix into strings. [Answer] # K, 1 [byte](https://codegolf.meta.stackexchange.com/a/9429/43319) ``` + ``` [Try it here!](http://johnearnest.github.io/ok/index.html?run=%2B(%22car%22%3B%22dog%22%3B%22man%22%3B%22yay%22)) Transpose [Answer] # Mathematica, 26 bytes ``` ""<>#&/@(Characters@#)& ``` Anonymous function. Takes a string list as input and returns a string list as output. The Unicode character is U+F3C7, representing `\[Transpose]`. Works by converting to a character matrix, transposing, and converting back to a string list. If the input/output format was stretched, then a simple 5-byte transpose would work: ``` #& ``` [Answer] # MATLAB / Octave, 4 bytes ``` @(x)x' ``` This defines an anonymous function. Input format is `['car'; 'dog'; 'man'; 'yay']`. [**Try it here**](http://ideone.com/7g6VaE). [Answer] # Haskell, 41 bytes ``` f l=zipWith($)[map(!!n)|n<-[0..]]$l<$l!!0 ``` Or with a bit more air: ``` f l = zipWith ($) [map (!! n) | n <- [0..]] $ l <$ (l !! 0) ``` The second list is the list of words repeated “the length of a word” time. On each list of words, we select the n-th letter of each word, giving the result. [Answer] ## Common Lisp, 62 bytes ``` (lambda(s)(apply'map'list(lambda(&rest x)(coerce x'string))s)) ``` The `map` function takes a result type (here `list`), a function *f* to apply and one or more sequences *s1*, ..., *sn*. All sequences are iterated in parallel. For each tuple of elements *(e1,...,en)* taken from those sequences, we call *(f e1 ... en)* and the result is accumulated in a sequence of the desired type. We take a list of strings, say `("car" "dog" "man" "yay")`, and use `apply` to call `map`. We have to do this so that the input list is used as more arguments to `map`. More precisely, this: ``` (apply #'map 'list fn '("car" "dog" "man" "yay")) ``` ... is equivalent to: ``` (map 'list f "car" "dog" "man" "yay") ``` And since strings are sequences, we iterate in parallel over all first characters, then all second characters, etc... For example, the first iteration calls *f* as follows: ``` (f #\c #\d #\m #\y) ``` The anonymous lambda takes the list of arguments given to it and coerces it back to a string. [Answer] ## Perl, 91 bytes So lengthy one.. ``` $l=<>;$p=index($l," ")+1;@i=split//,$l;for$a(0..$p-1){print$i[$a+$_*$p]for(0..$p);print" "} ``` [Try it here!](https://ideone.com/srDzwg) [Answer] # [Ruby](https://www.ruby-lang.org/), 40 bytes ``` ->a{a.map(&:chars).transpose.map &:join} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3NXTtEqsT9XITCzTUrJIzEouKNfVKihLzigvyi1NBwgpqVln5mXm1UPWKBQpu0dFKyYlFSjoKSin56SAqNzEPRFUmVirFxkIULlgAoQE) [Answer] # [J-uby](https://github.com/cyoce/J-uby), 24 bytes Port of [my Ruby answer](https://codegolf.stackexchange.com/a/254848/11261). ``` :*&A|:transpose|:*&:join ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWO6y01BxrrEqKEvOKC_KLU2uAfKus_Mw8iPRNxQIFt-hopeTEIiUdBaWU_HQQlZuYB6IqEyuVYmMhChcsgNAA) ## Explanation ``` :* & A | :transpose | :* & :join :* & A | # Map converting to character arrays, then :transpose | # Transpose, then :* & :join # Map with join ``` [Answer] # [Go](https://go.dev), 111 bytes ``` type S=[]string func f(I S)S{O:=make(S,len(I[0])) for _,s:=range I{for j,r:=range s{O[j]+=string(r)}} return O} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVBLasMwFKRbneLhlU3VULoqAR8gqxS8DKE8FNkoiSQjyQsjdJJuQqGH6FHa0_TJauhn4zFvRvPmzcvrYC_vI4oTDhI0KsOUHq0Lq6rXoXqbQn_3-GHDPEro2t3eB6fMwPrJCOjrDXRNF7frVuNJ1h0_S1Nvdvf7pmG9dfDM_bp1aMh5E_PgyN114ON2d9zftsWwdk1KzMkwOQPbVNZ-3jwse0dUDkg3iQBRcQvXGImVIDl23UBkAr30sG5JkR_F5XNVx0qgqzhUBztk0GgyzDhXif8SHfSc52gRM7rBkCDxf17aGrnoAp2-GFFAH_5Y6RAyYctac5oySOmXtYa0dHPpSeTQpZhyQ2RP5BHOphYrxUGsLKe-6Z-q_WFsZlRhLDGJfVd3uRT8Ag) [Answer] # [Japt](https://github.com/ETHproductions/japt), 1 [byte](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Simply transposes the input. ``` Õ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1Q&input=WyJtb25leSIsICJ0YWtlbiIsICJ0cnVzdCJd) [Answer] # Ruby, 46 bytes Probably the first time that "Ruby strings aren't Enumerables" is actually biting me hard since I had to map the strings into arrays before processing. (Normally having to use `String#chars` isn't enough of a byte loss to matter, but since I need to map them, it stings a lot more) ``` ->s{s.map!(&:chars).shift.zip(*s).map &:join} ``` [Answer] # Clojure, 68 bytes ``` #(map(fn[g](reduce(fn[a b](str a(nth b g)))""%))(range(count(% 0)))) ``` Maps a function which is just `reduce` (goes on elements of the list one by one and joins nth character of the string) on the range from 0 to length of the first string. See it online: <https://ideone.com/pwhZ8e> [Answer] # C#, 53 bytes ``` t=>t[0].Select((_,i)=>t.Aggregate("",(a,b)=>a+b[i])); ``` C# lambda (`Func`) where the output is `IList<string>` and the output is `IEnumerable<string>`. I dont know how work `zip` in other language but I can't find a way to use the [C#'s one](https://msdn.microsoft.com/en-us/library/dd267698(v=vs.110).aspx) here. `Aggregate` fit the need well. No transpose in C#, there is [one](https://stackoverflow.com/a/12839486/1248177) in Excel but I wont use it. [Try it online!](https://dotnetfiddle.net/sDajpJ) ]
[Question] [ The [Jaccard index / similarity coefficient](https://en.wikipedia.org/wiki/Jaccard_index), also known as the Tanimoto index / coefficient, is a statistic used for gauging the similarity and diversity of finite sample sets. It was developed by Grove Karl Gilbert in 1884 for the field of weather forecasting [[1]](https://journals.ametsoc.org/view/journals/wefo/11/1/1520-0434_1996_011_0003_tfaase_2_0_co_2.xml) and later independently developed by Paul Jaccard [[2]](https://doi.org/10.1111/j.1469-8137.1912.tb05611.x) who was studying species of alpine plants. Finally, it was also formulated again by T. Tanimoto [[3]](https://agris.fao.org/agris-search/search.do?recordID=US201300372414). Overall, it is widely used in various fields where binary or binarized data are used. These include computer science, ecology, genomics, etc. Mathematically speaking, it is defined as the size of the [intersection](https://en.wikipedia.org/wiki/Intersection_(set_theory)) divided by the size of the [union](https://en.wikipedia.org/wiki/Union_(set_theory)) of finite sample sets. Specifically, for two sets \$A\$ and \$B\$ it is defined as: \$J(A, B) = \frac{|A \bigcap B|}{|A\bigcup B|}\$ It ranges from \$0<= J(A, B) <=1\$, where `0` is the case of the intersection between \$A\$ and \$B\$ being equal to the empty set. # Challenge Given two finite sets, containing positive or negative integers, calculate their Jaccard index. You may assume that at least one of the sets will be non-empty. This index is applied on mathematical sets, meaning that if your language of choice does not support sets, use any other data collection containing *unique* elements. ## Test cases ``` {1, 2}, {} -> 0.0 {-7, 3, -9}, {9, 2, 3, 4} -> ~0.167 {1, 2, 3}, {2, 4, 6} -> 0.2 {0, 64}, {0, 64, 89, 93} -> 0.5 {6, 42, 7, 1}, {42, 7, 6} -> 0.75 {3, 6, 9}, {3, 6, 9} -> 1.0 ``` ## Rules * You may use [any standard I/O method](https://codegolf.meta.stackexchange.com/q/2447), including taking as input a list of other data collections. * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 5 bytes [SBCS](https://github.com/abrudz/SBCS) ``` ∩÷⍥≢∪ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9Sx8vD2R71LH3UuetSxCgA&f=HYxBEcAwDMP@QSEIa5NLF0JlMya7K4dCKZJl@ViWH250Jud5Za@BslekR66KSSvOTMPlwi2lcAeh4lhn0HKt4qI4/0PxAw&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f) Input `A f B` [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` h8#uqYm ``` Try it at [MATL online](https://matl.io/?code=h8%23uqYm&inputs=%5B1%2C+2%5D%0A%5B%5D&version=22.7.4)! Or [verify all test cases](https://tio.run/##y00syfmf8D/DQrm0MDL3v0vI/2hDHQWjWK5oINI111Ew1lHQtQSyLYGiYJ4JkGMI4QBZQMpER8EMyDIAUiYwWkfBAqjBEqTCDKgCqApolCGQB2WCNADNAspZIrEA). ### How it works ``` h % Implicit inputs. Concatenate 8#u % Number of occurrences of each unique value (will be 1 or 2) q % Subtract 1, element-wise Ym % Mean. Implicit display ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~8 7~~ 6 bytes ``` ₍↔∪@÷/ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigo3ihpTiiKpAw7cvIiwiIiwiey03LCAzLCAtOX1cbns5LCAyLCAzLCA0fSJd) -1 thanks to TheThonnu, -1 thanks to Lyxal ``` ₍↔∪@÷/ # implicit input of two lists ₍ # apply each to the stack, and wrap: ↔ # intersection ∪ # union @ # map each set to its size ÷ # dump list onto stack / # divide ``` [Answer] # [Python 3](https://docs.python.org/3/), 28 bytes ``` lambda a,b:len(a&b)/len(a|b) ``` [Try it online!](https://tio.run/##NY/BjoJAEETv8xWVmKxM0uAgLCwm@iPIASJkTVw0MpcN4q9jzaBzmeru113dt3/7e@2Tudsf50v915xq1NLsLm0f1F@N3njxaPRs28EO2KMsx1iwnQRDawNdCfhWMJFR5RjmgkQQFiyPBTEfphOpFZ4mirNcLf0sOIZ/KsimZcwyaEvEMJk6wAvBD4cViccc8k0kYyvb6Rg78K2zxctEuWNoTsxv85FV9XGKubLqrndYnHv4@3bKXc8rrcLtfu5twFDWCA9YS@cCrecX "Python 3 – Try It Online") Simply uses the built-in python set operations [Answer] # [J](https://www.jsoftware.com), ~~15~~ 12 bytes ``` +/@e.%#@~.@, ``` Uses formal definition. -3 thanks to [att](https://codegolf.stackexchange.com/users/81203/att). [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxRlvfIVVPVdmhTs9BByJ0M0OTKzU5I1_BUMFIIU3BQMUAwo03VzBWiLcEClkCJYwVTCDCBgpmJiBlIMrCUsHSGCJspmBipGAONCMNwjCDCBsDJUBGgGmIfQsWQGgA) ``` +/@e.%#@~.@, , NB. concat ~.@ NB. then uniquify #@ NB. then get size e. NB. vectorized "is x in y" +/@ NB. then sum the resulting boolean list to get size % NB. division ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~16~~ 13 bytes -3 from @ovs's improvement ``` +/%/#:\2=#'=, ``` [Try it online!](https://ngn.codeberg.page/k#eJxdkMFuwjAMhu95Ck9sGtXSpklD2jRiT8GNIVGVljIY3WgnFVXh2ecENk3k4Nj+P9uJ6/yFPbFJ/ibmk+c5JWSRj4/L8+WU1xDBYNbt3kzXdbE7mMGczSlYWbJYTjkI8xAHJo7ilYvDFBIItdEg0JFO4OrurG6FkBgBEpSDhE/GoKRxBjINOnHCzAsKpIAUuPGXr0ivSgIKtPE2MNy9ghBGmr7/7HLGynZTbdtDHXV9Ue6roWyK47aKyvaDfX1XXb9rjx0TM51lnPVNFb4XZVmcNuHuuKmGiRN0RsjIKQhLYbRwd8JXwJ+TMUwpJBQ/7iiNtA+ldcDFrSC9NsG0I/CWFJT910SQMcaUdLJ3KO6A4hLsDZiRUWEZluIs7rCbr+wVSJHAoQj5V/y6fzNwOT/6u3BZ) * `=,` group the concatenated inputs * `2=` determine which elements in each input are present in both (1 if so, 0 otherwise) * `+/%/#:\` calculate the average [Answer] # [Arturo](https://arturo-lang.io), ~~40~~ 35 bytes ``` $[a b]->//size a--a--b size b++a--b ``` [Try it](http://arturo-lang.io/playground?rcdY1B) Port of Neil's [Charcoal answer](https://codegolf.stackexchange.com/a/259906/97916). `--` is set difference, `++` is concatenation, `size` is length, and `//` is float division. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~50~~ 30 bytes ``` Tr[1^(#⋂#2)]/Tr[1^(#⋃#2)]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6Qo2jBOQ/lRd5OykWasPpzbDOKq/Q8oyswrcUiLrjbUUTDSUTCu1VGoBtImOgpmtbH/AQ "Wolfram Language (Mathematica) – Try It Online") -20 thanks to *@att* [Answer] # [R](https://www.r-project.org), 27 bytes ``` \(x,y)mean(table(c(x,y))-1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGKrMTk5MSiFNulpSVpuha7YzQqdCo1c1MT8zRKEpNyUjWSwQKauoaaEBW3GMWhWoBShjoKRpo6CskampoKaEBZQddOwUDPgAuhWtdcR8FYR0HXEqzFEqgXzDcBagarrjPQMzQz50I1HqgErBzIMNFRMINZBDXeCEm1AVDaBKwWzNJRsABaYWkM0gFVbYqk2gxoHtBMoJMMwXqgHDOYYwz0zJGVA90J1AFxOYyN7BRDPQNI-CxYAKEB) [Answer] # Julia, 26 characters, 30 bytes Correction from Ashlin Harris much appreciated. ``` n=length A\B=n(A∩B)/n(A∪B) ``` Doesn't actually require A and B to be `Set` objects, as if they aren't it converts them anyway. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ãg¹²«Ùg/ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cHP6oZ2HNh1afXhmuv7//9GGOkY6xrFc0UY6JjpmsQA "05AB1E – Try It Online") #### Explanation ``` Ãg¹²«Ùg/ # Implicit input g # Length of... à # ...intersection of inputs... / # ...divided by... g # ...length of... ¹² # ...both inputs... « # ...merged... Ù # ...without duplicates # Implicit output ``` [Answer] # JavaScript (ES6), 74 bytes Expects two sets as `(a)(b)`. There's unfortunately not any union nor intersection built-in in the current ECMAScript specification. :-/ ``` a=>b=>new Set([...a,...b]).forEach(v=>k+=a.has(v)&b.has(v,n++),n=k=0)||k/n ``` [Try it online!](https://tio.run/##fdC9DoIwEAfw3afoZNpQjqIIMpTNJ3A0DgVBFNMaMbgYXx0v9YPUBDs07T/N7@56VJ1qi8vhfPW12ZV9JXsls1xmuryRdXmlGwBQHLd8y6Ayl5UqatrJrPGkglq1tGPT/HXg2vMY17KRgt3vTaD7wujWnEo4mT2t6JcMOZltGRsCvDDys4KACBCTEcJPOJlz4qeOkyJs88iKSDwEhHEy@dMIvncMDCJO4qEl28hsjBD4NnIAm3CyxGbS@YuxxGKMiLEiVsWJQgd6h/FnFgHJqIEzI@P@xpANk4Qg@ic "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` I∕L⁻θ⁻θηL⁺η⁻θη ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwyWzLDMlVcMnNS@9JEPDNzOvtFijUEcBzsjQ1NTUUYBKB@QABTPQZIHA@v//6GhDHQUjHQXjWB2FaCBtoqNgFhv7X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as lists which the program assumes are unique. Explanation: Charcoal doesn't have set union or intersection but it can do set difference of two set-type lists, so I have to simulate intersection with double set difference and union by concatenation of set difference. ``` θ First input ⁻ Set difference with θ First input ⁻ Set difference with η Second input L Take the length ∕ Divided by θ First input ⁻ Set difference with η Second input ⁺ Concatenated with η Second input L Take the length I Cast to string Implicitly print ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 6.5 bytes (13 nibbles) ``` ,`&$_"/",`|$_ ``` Outputs as a non-reduced fraction (one of the [standard I/O methods](https://codegolf.meta.stackexchange.com/a/19024/95126), following the [consensus](https://codegolf.meta.stackexchange.com/a/9267/95126) that reducing fractions is optional unless specified). ``` , # length of `& # set intersection of $ # arg1 and _ # arg2; "/" # the character "/"; , # length of `| # set union of $ # arg1 and _ # arg2; # concatenated into output ``` [![enter image description here](https://i.stack.imgur.com/8sWPc.png)](https://i.stack.imgur.com/8sWPc.png) --- # [Nibbles](http://golfscript.com/nibbles/index.html), 8 bytes (16 nibbles) ``` /*,`&$_100,`|$_ ``` Outputs the Jaccard index truncated at two decimal places; the decimal point is omitted (so, equivalently, an integer representing 100x the Jaccard index). ``` / # divide: , # length of `& # set intersection of $ # arg1 and _ # arg2 * 100 # multiplied by 100 # by: , # length of `| # set union of $ # arg1 and _ # arg2 ``` [![enter image description here](https://i.stack.imgur.com/rJmkU.png)](https://i.stack.imgur.com/rJmkU.png) The choice of two decimal places (costing +2.5 bytes) here is arbitrary: if zero decimal places is acceptable (meaning that output can only be `1` or `0`), then the same approach could be only 5.5 bytes: `/,`&$_,`|$_`. [Answer] # [Lua](https://www.lua.org/), 106 bytes ``` load"i=0u=0g,h=...for k in next,g do i=h[k]and i+1or i h[k]=1 end for k in next,h do u=u+1 end return i/u" ``` [Try it online!](https://tio.run/##ZY/NCoMwEITvfYrFk8FojYqthzxJ8CD4F5RYgoGC@Ow2MWprvSTsfDOzSa@KpaZLPxSlw2moaNjglgZBUA8SOuACRPUecQPlAJy2rMsLUQL3iMYczEwJVFo6@1vjV1R5FspqVFIAvytneUkuRrd2J0Z0FrMop9GMpxmh2xf5j5XF6@ln@tIWlu2BAyWGnJLkz2Ny0eHFLL0kQqsnm/lnxOxpV2bxJZXaTlttX0u2hpN43RcfOmb7zy4aQssH "Lua – Try It Online") Takes in tables that represent sets- [This page](https://www.lua.org/pil/11.5.html) should describe how they are formatted. Ungolfed version below. ``` function f(g,h) i=0 u=0 -- Represents size of intersection and union for k in next,g do -- For each element in set g i=h[k]and i+1or i -- Increment i if k is in h h[k]=1 -- Add k to set h end for k in next,h do -- Counts elements in h (now union set) u=u+1 end return i/u end ``` [Answer] # Raku, 19 characters/23 bytes ``` {($^a∩$^b)/($a∪$b)} ``` Straight out of the definition. [Try it online!](https://tio.run/##XY49DoJAEIV7TzHFFjvJQ2Uhi1voJSxFkt0EC6LRoA0h9F5Fj@VFVhawwFe9ny@TuZX1WftLQ3m19a0Uhf08X6JwvJKit2/huPOna00HuS8fMoZiBMOMBQUNdZQhQWQYFJKB6mM6R@JQToBCCj2f19DptAaLjYFJ5ohGqpAhnrAh/F1JoPH7YvR8pGhHMreg3DG1I9zrbhuqltLC8aLzXw) [Answer] # JavaScript, 65 bytes ``` a=>b=>a.filter(i=>b.includes(i)).length/new Set(a.concat(b)).size ``` [Try it online!](https://tio.run/##bY7BDoIwEETvfkWPbVKqCEE5wE94JBxKWbWkaQ2tmvjzdYvGg@G0MzsvszvJh/Rq1reQWTdCnJoom3ZoWinO2gSYqUYrtFXmPoKnmjFhwF7CdWvhSU4QqBTKWSUDHTDz@gURvXcGhHEXOtEu52TfM9r1jG3@ouzAScFJVqe8Rm6x5QqZf8LE4Sw5qVagHa7LhCyCkyNW1sUKWGEF1uD1POFfvVaJ7yC8/PeTLL4B "JavaScript (Node.js) – Try It Online") [Answer] # [Scala](https://www.scala-lang.org/), 33 bytes ``` (a,b)=>((a&b).size+.0)/(a|b).size ``` [Try it online!](https://tio.run/##TY3LbsIwEEX3/oq7QmNhpQ8qFpFSiaqbLrop6gqxmAQHGRkb2aZSH3x7cEIq2M2Zc@dObNhyZ/YHHxJiD0XjrdVNMt4VS52E8PUuI97ZOPwKYKNb7DMQh20ssQiBv1fLFIzbrmWJT2cSqiEJfLFF1GmRF7mLHhQeFWby1r2MLosnhfnVtR86Hm3f1VLfoYb0xR/yt2QdjZl@eRJiuCpBuW715tJa/Q@yen71x9pqVB2xqjMT8aSWRTQ/elrcyzvivxG7k@jO) [Answer] # [Pyt](https://github.com/mudkip201/pyt), 15 bytes ``` Á←ÁáĐỤ⇹ɔĐŁ⅟⇹⁻Ʃ* ``` [Try it online!](https://tio.run/##AToAxf9weXT//8OB4oaQw4HDocSQ4buk4oe5yZTEkMWB4oWf4oe54oG7xqkq//9bMywyXQpbNSwyLDksNTZd "Pyt – Try It Online") ``` Á implicit input; push contents of Árray to stack ←Á get input; push contents of Árray to stack á push contents of stack to árray Đ Đuplicate Ụ get Ụnique elements ⇹ swap ɔ get ɔount how many times each unique element occurs in the combined list Đ Đuplicate Ł get Łength (size of union) ⅟ multiplicative inverse ⇹ swap ⁻ decrement each element Ʃ sum (size of intersection) * multiply ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` f,œ|Ẉ÷/ ``` [Try it online!](https://tio.run/##y0rNyan8/z9N5@jkmoe7Og5v1/9/eLnS0UkPd8541LQm8v//akMdBaNaHYVqXXMdBWMdBV1LEAckCOSCmAY6CmYmIIaZjoIJUBCozBDEBaoFiljW/q8G8SwhGoBKQDwg0wQoDdeuo2ABVGAJNg9qhhmyGQA "Jelly – Try It Online") ## How it works ``` f,œ|Ẉ÷/ - Main link. Takes A on the left, B on the right f - Intersection of A and B œ| - Set union of A and Q , - Pair Ẉ - Lengths of each / - Reduce the length pair by: ÷ - Division ``` [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 37 bytes ``` [ 2dup ∩ length -rot ∪ length / ] ``` [Try it online!](https://tio.run/##VZBNDoIwEIX3nOJdAJSfgGji1rhxY1wZFwSKEqFgWxaGdO9V9FheBIcSTOgs@t77pp20eZKqWvSn4/6wWyORsk4l7kxwVqJK1M1peZHWGYNkj5bxlEkToxFMqWcjCq6wsazOAq2OyoUHTbuG/md2BB92bPKYuI9gxl2TDdQjEs7YEmFgkBGrGLE/4yECDxFdMfQYOT/vkx8nT0pbuj/Dy9oG39cbJeNXepAtakX@M/kFLn0@fsi2Sho4/Q8 "Factor – Try It Online") ``` ! { 1 2 3 } { 2 4 6 } 2dup ! { 1 2 3 } { 2 4 6 } { 1 2 3 } { 2 4 6 } ∩ ! { 1 2 3 } { 2 4 6 } { 2 } length ! { 1 2 3 } { 2 4 6 } 1 -rot ! 1 { 1 2 3 } { 2 4 6 } ∪ ! 1 { 1 2 3 4 6 } length ! 1 5 / ! 1/5 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` cl@FQls ``` [Try it online!](https://tio.run/##K6gsyfj/PznHwS0wp/j//@hqQx0jHeNaHYVqIx1THbPaWAA "Pyth – Try It Online") ### Explanation ``` cl@FQlsQ # implicitly add Q # implicitly assign Q = eval(input()) c # float division of l # length of @FQ # intersection of the two elements of Q l # and the length of sQ # union of the two elements of Q ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 10 bytes ``` (+´⊒÷·≠⍷)∾ ``` [Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=SmFjY2FyZCDihpAgKCvCtOKKksO3wrfiiaDijbcp4oi+Cgrin6gx4oC/MiBKYWNjYXJkIOKfqOKfqSwgCsKvN+KAvzPigL/CrzkgSmFjY2FyZCA54oC/MuKAvzPigL80LAox4oC/MuKAvzMgSmFjY2FyZCAy4oC/NOKAvzYsCjDigL82NCBKYWNjYXJkIDDigL82NOKAvzg54oC/OTMsCjbigL80MuKAvzfigL8xIEphY2NhcmQgNDLigL834oC/NiwKM+KAvzbigL85IEphY2NhcmQgM+KAvzbigL854p+p) ``` ∾ # join L & R args together ( ) # and apply this: +´ # sum of ⊒ # occurrence counts of each element # (zero if one instance, one if two instances) ÷· # divided by ≠ # length of ⍷ # deduplicated elements ``` [Answer] # [Haskell](https://www.haskell.org/), 43 bytes ``` a%b=1/(sum(1<$a++b)/sum[1|x<-a,elem x b]-1) ``` [Try it online!](https://tio.run/##Dcc5CoAwEADA3ldsoZDgiqx3YV4SUmwgopiIeICFf482AzPzuTrvY@TMKirFeQdBY8p5bmX5R9P7jAWj8y7AA9YUJOOkRCaTwMsGCvZj2S5IYQJNWGFtQP9igy122ONg4gc "Haskell – Try It Online") Haskell makes an interesting language for this challenge because it lacks sets or set operations like union barring a costly import. Also, it won't take the ratio of two lengths to make a real number without a costly type conversion. The answer uses the formula \$1/\left(\frac{\left| A \right| + \left| B \right|}{\left| A\cap B \right|} - 1 \right)\$. The inputs are lists. Lengths are computed as `sum(1<$l)` which converts each element to 1 then takes the sum -- unlike `length`, this can produce a float because Haskell typechecks the literal `1` as a float here. The `sum(1<$a++b)` takes the length of the concatenation of the two inputs lists, which is the sum of their lengths. The intersection uses a list comprehension to extract all elements of `a` that are also in `b`. Two more symmetric version of this are 1 byte longer: ``` a%b=1/(sum(1<$a++b)/sum[1|x<-a,y<-b,x==y]-1) a%b=1/(sum(1<$a++b)/sum[1|0<-(-)<$>a<*>b]-1) ``` Importing `Data.List` comes out longer: **53 bytes** ``` import Data.List a%b=sum(1<$a++b)/sum(1<$nub(a++b))-1 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrUTXJtrg0V8PQRiVRWztJUx/KyStN0gALaOoa/k@z1VDV5MpNzMxTsFUoKMrMK1FQUUhTiDbUMdIxjlWIBpI6JjqmOmY65joWsf8B "Haskell – Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 49 bytes ``` param($a,$b)($c=$a+$b).Count/($c|sort|gu).Count-1 ``` [Try it online!](https://tio.run/##XVDRaoNAEHz3K5ZwFKV3qSZWa0AwDe1baWkeQyinvVSKqeIpLajfbtc7k9guqHMzs7PrFfm3KGUqsowleSl6cgibvuAlP5qEUxJbJklCwq8RzTd5/VXdINHKvKzaj3qkmNN3hhGZBmBRiMzIdCgsrAHiy57b1kRiPoUlBRYoPUCjOrvK6XjT8q1/kehUXQhcCp5qWUxNNrKusihE4Q4HBEtlvJ0aPUzAFNzFUfbxoCP9P1ZcDt163Qt2hr@yoIXHvHzgScqe40@RVNCoTrw7IDE@4qdAVrxDCORNS6WQdVYhcUUOaESf4ncv200tq/yog/aRThpqWyeJkBJbdk@8Sver1TqW5imIXaZYwJDACz@Vc85Yj98QZg3h3ews3E@FeCK86vhhcz1JKZ3RGf0v "PowerShell Core – Try It Online") Takes two lists as parameters, returns a `double` or an `int32`. Knowing that A and B are sets, I'm calculating the Jaccard index this way: ``` U = Size of the union of A and B with duplicates D = Size of the union of A and B without duplicates Jaccard Index = (U - D) / D = U / D - 1 ``` ## Explanation ``` param($a,$b)($c=$a+$b).Count/($c|sort|gu).Count-1 # Function body param($a,$b) # Declares the two parameters $a and $b ($c=$a+$b) # Concatenates the two input lists and keep the result in $c .Count # Gets the size of the two set's union $c|sort|gu # Finds only the unique elements in the union ( ).Count # Calculates the size of the intersection / -1 # Divides the size of the union by the size of the unique items and subtracts one ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 6 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` çȯċḷẸ/ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWaw8vP7H-SPfDHdsf7tqhv6Q4KbkYKrNgR7WZjoKJkY6CuY6CYS1XNZRpVguRBwA) #### Explanation ``` çȯċḷẸ/ # Implicit input ç # Apply two functions in parallel: ȯ # Set intersection ċ # Set union ḷ # Length of each list Ẹ # Dump onto stack / # Divide # Implicit output ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 4 bytes ``` ,Ţ←µ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6Fit0ji561Dbh0NYlxUnJxVDBBTdTog11jGIVomO5onXNdYx1dC2BHEsdIyDTBChmCGIBRYx0THTMgHwDHTMTIBdE6VhY6lgaA8XMdEyMdMx1DIHiYAZInbGOmQ7IJAgNsQwA) A port of [@Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/259898/9288). ``` , Join Ţ Tally (count occurrences of each unique element) ← Decrement µ Mean ``` [Answer] # Excel, 72 bytes ``` =LET(x,VSTACK(A1#,B1#),(COUNT(x)-COUNT(UNIQUE(x,,1)))/ROWS(UNIQUE(x))/2) ``` where `A1#` and `B1#` are vertical spilled ranges containing the elements of each set. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 11 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` +h\▀£_@-²√╠ ``` [Try it online.](https://tio.run/##y00syUjPz0n7/187I@bRtIZDi@MddA9tetQx69HUBf//RxvqGMUqRMdyReua6xjr6FoCOZY6RkCmCVDMEMQCihjpmOiYAfkGOmYmQC6I0rGw1LE0BoqZ6ZgY6ZjrGALFwQyQOmMdMx2QSRAaAA) **Explanation:** ``` + # Merge the two (implicit) input-lists together h # Push the total length (without popping the list) \ # Swap so the list is at the top of the stack again ▀ # Uniquify it £ # Pop and push the length _ # Duplicate this union-length @ # Triple-swap the stack - # Subtract the union-length from the total length to get the amount of # items that are in both input-lists ²√ # Convert it to a float, by taking the square-root of its square # (otherwise division builtins would be integer-division) ╠ # Divide this top float by the duplicated union-length # (after which the entire stack is output implicitly as result) ``` [Answer] # [Go](https://go.dev) (using `golang.org/x/exp/slices`), ~~170~~ 168 bytes ``` import."golang.org/x/exp/slices" func f(a[]int,b[]int)float64{i,j:=0.,0. for _,x:=range a{if Contains(b,x){i++} j++} for _,y:=range b{if!Contains(a,y){j++}} return i/j} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RY9BSsQwFIb3OcWzq4SJ6ajDIIUuZrzA7EUkLUlIbZOSptAh9CRuiiB4BY_ibUzbcdy8Bx8f7_3_-4ey03fLyzeuBDRcG6Sb1joPiWx88tl7efv487Uylihbc6OYdSodUjG0aVfrUnQJkr0pQWL-_KKNp8WyiKwt9_td0LTK8i2jW4akdfBKhyx38Y4AHrSEJ2t8fNzhgg4k6M1mRNU8Vvf85xbRvbm6nJ5JmLUROeF7Z0Cn1XjJe1rizG0wgYAADpDlsIQKdxTuKTyMkR7_aUQ7CvuZxt7s5CLEEh8oHAlBl7vTtO5f) Go has *literally* no built-ins (including `Contains`) so we have to implement set union and intersection ourselves. *-2 thanks to @code* #### Commented ``` import ."golang.org/x/exp/slices" // Import the module we need to get Contains func f(a []int, b []int) float64 { // Define a function, f, taking two lists of ints, // a and b, and returning a float i, j := 0., 0. // Initialise i (Intersection length) and j (Union length) to 0.0 for _, x := range a { // Loop through each x in a: if Contains(b, x) { // If x is in b: i++ } // Increment i j++ } // Increment j for _, y := range b { // Loop through each y in b: if ! Contains (a, y) { // If y is not in b: j++ } } // Increment j return i / j } // Return the Jacard index ``` ]
[Question] [ Given a string `s` and a non-negative number `n` less than the length of `s`, output the character at the `n`-th position of `s`. 0-indexing and 1-indexing are allowed. For 1-indexing, `n` will be positive and less than or equal to the length of `s`. `s` will consist of printable characters only. Any reasonable input/output is permitted. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. Testcases (0-indexing): ``` n s output 0 "abcde" a 1 "abcde" b 2 "a != b" ! 3 "+-*/" / 4 "314159" 5 ``` Testcases (1-indexing): ``` n s output 1 "abcde" a 2 "abcde" b 3 "a != b" ! 4 "+-*/" / 5 "314159" 5 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] # [MATL](https://github.com/lmendo/MATL), 1 byte ``` ) ``` [Try it online!](https://tio.run/nexus/matl#@6/5/796SEZmsQIQJSoUlxRl5qWrcxkDAA "MATL – TIO Nexus") Well, hard to make it much simpler. `)` indexes the first input, using the second input value. This is 1-indexed. [Answer] ## [Alice](https://github.com/m-ender/alice), 5 bytes ``` I&IO@ ``` [Try it online!](https://tio.run/nexus/alice#JcshEsNQDAPRs5QE25ZsSyw0qPc/zW9mSvahPc/1fO9zPkhm@9@aRstrFMSpISDUuqMkpjfHsLGd0arw0uQ7IlY5jClNhewXBahqsDI3Zn8 "Alice – TIO Nexus") As usual it's much shorter if we avoid Ordinal mode and use an abysmal input format. Here, the first [character's code point is used as the integer input](http://meta.codegolf.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values). The remainder of the input is the string. The index is 1-based. ### Explanation ``` I Read a character and push its code point. &I Read that many more characters and push them. O Output the last one we read. @ Terminate the program. ``` [Answer] # Python, 15 bytes ``` str.__getitem__ ``` or ``` lambda s,i:s[i] ``` Both take 2 arguments: the string and the index. 0-indexed. [Answer] ## Haskell, 4 bytes ``` (!!) ``` 0-based indexing. Usage example: `(!!) "Hello" 1`-> `'e'`. [Answer] # Octave, 10 bytes ``` @(s,n)s(n) ``` Takes a string `s`, and a number `n` as input, and returns the `n`th character of `s`. [Answer] # [Retina](https://github.com/m-ender/retina), ~~28~~ ~~20~~ 19 bytes *Saved 8 bytes thanks to @MartinEnder by not using balancing groups* *Saved 1 byte thanks to @mbomb007 by using `^.+` instead of `^\d+`* ``` ^.+ $* +`1¶. ¶ !1`. ``` [Try it online!](https://tio.run/nexus/retina#U9UITrD@H6enzaWixaWdYHhomx7XoW1cioYJev//G1gnJiWnpHIZQmkj60QFRVuFJC5ja21dLX0uE2tjQxNDU0sA "Retina – TIO Nexus") The program is 0-indexed. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte 0-indexed. ``` è ``` [Try it online!](https://tio.run/nexus/05ab1e#@394xf//JlzGhiaGppYA "05AB1E – TIO Nexus") [Answer] ## [Alice](https://github.com/m-ender/alice), 10 bytes ``` /@!O?]& I ``` [Try it online!](https://tio.run/nexus/alice#@6/voOhvH6vGpeD5/7@xoYmhqSWXCQA "Alice – TIO Nexus") Expects the string on the first line and the 0-based index on the second line. ### Explanation Despite its wealth of built-ins, string indexing doesn't exist in Alice. The reason is that it requires both an integer and a string parameter, and all commands in Alice are strictly integers to integers or strings to strings. In general, the main way to perform any operations on strings that require or result in integers is to store the string on the tape in Ordinal mode, which you can then manipulate with integers in Cardinal mode. ``` / Reflect to SE. Switch to Ordinal. While in Ordinal mode, the IP bounces diagonally up and down through the program. I Read one line from STDIN and push it. ! Store the string on the tape. This writes the character codes into consecutive tape cells starting at the tape head. (It also writes a -1 at the end as a terminator, but the tape is initialised to -1s anyway). The next few commands are junk that luckily doesn't affect the program: ? Load the string from the tape and push it to the stack again. & Fold the next command over this string. That is, for each character in the string, push that character, then execute the command. ? So we're folding "load" over the string itself. So if the string is "abc" we'll end up with "a" "abc" "b" "abc" "c" "abc" on the stack. ! Store the top copy of "abc" on the tape (does nothing, because it's already there). Now the relevant part of the program continues. I Read another line from STDIN, i.e. the string representation of the index. / Reflect to W. Switch to Cardinal. The IP wraps to the last column. & Implicitly convert the string to the integer value it represents and repeat the next command that many times. ] Move the tape head right that many cells. Note that Ordinal and Cardinal mode have separate tape heads, but they are initialised to the same cell. ? Load the value from that cell, which is the code point of the character at the given index. O Print the corresponding character. ! This discards or converts some of the strings on the stack and writes some value back to the tape, but it's irrelevant. @ Terminate the program. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 byte ``` ị ``` [Try it online!](https://tio.run/nexus/jelly#@/9wd/f///9N/itp62rpKwEA "Jelly – TIO Nexus") [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), ~~40~~ 37 bytes ``` q(L,N,A):-nth0(N,L,X),char_code(A,X). ``` [Try it online!](https://tio.run/nexus/prolog-swi#@1@o4aPjp@OoaaWbV5JhoOGn46MToamTnJFYFJ@cn5Kq4Qjk6v3/X6iRYGxoYmhqmaBjAhIBAA "Prolog (SWI) – TIO Nexus") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes ``` ∋₎ ``` [Try it online!](https://tio.run/nexus/brachylog2#@/@oo/tRU9///9FKxoYmhqaWSjomsf@jAA "Brachylog – TIO Nexus") ### Explanation `∋` unifies its output with an element of the Input. With `₎` as subscript, it will unify its output with the `I`th element of `S`, with `[S,I]` as input. [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 8 bytes ``` t@poIA// ``` This solution is 1-indexed. The input should consist of a number first, then a separator (that is not a digit or a `.`) and then the string. [Try it online!](https://tio.run/nexus/cubix#@1/iUJDv6aiv//@/iUJiUnJKahoA "Cubix – TIO Nexus") [Answer] ## [CJam](https://sourceforge.net/p/cjam), 3 bytes ``` {=} ``` [Try it online!](https://tio.run/nexus/cjam#M1BQSkxKTklV4jKEs4yALAVFW4UkJS5jBSVtXS19JS4TBSVjQxNDU0slrlgj/eq6/9W2tf/rCmr1/wMA "CJam – TIO Nexus") `=` is the built-in for list/string indexing. [Answer] # [Japt](https://github.com/ETHproductions/japt), 2 bytes ``` gV ``` This solution is 0-indexed. [Try it online!](https://tio.run/nexus/japt#@58e9v@/UmJSckpqmpKOggkA "Japt – TIO Nexus") [Answer] # [S.I.L.O.S](https://github.com/rjhunjhunwala/S.I.L.O.S), 43 bytes ``` loadLine readIO a=256+i a=get a printChar a ``` [Try it online!](https://tio.run/nexus/silos#@5@Tn5jik5mXylWUmpji6c@VaGtkaqadCaTTU0sUErkKijLzSpwzEosUEv///1@QX5JYkv/fCAA "S.I.L.O.S – TIO Nexus") Simple enough. [Answer] # [BF](https://esolangs.org/wiki/brainfuck), 9 bytes ``` ,[->,<]>. ``` The index is taken via the character code of a char (like the Alice submission). Following that, we have the string. [Try it online!](https://tio.run/nexus/bash#LcxLCoAgFEDRuat4ONYMmoYbqQZ@XiTFU0yh3Rt9xudy0W0RJCHw@eoHY53HlYOGLlCqhTF8nDcxSS3GRXftRRc9MhVTUSVEWbKhM4UD86lsNoHW6vYvgvE/tRs "Bash – TIO Nexus") The TIO link uses a Bash wrapper and the input can be changed in the header file (the reason for the wrapper is so that we can see the bytes). [Answer] # JavaScript, ~~11~~ 10 bytes ``` s=>n=>s[n] ``` Uses 0-based indexing. *-1 byte thanks to @Leaky Nun* ``` f= s=>n=>s[n] console.log(f("abcde")(0)); console.log(f("abcde")(1)); console.log(f("a != b")(2)); console.log(f("+-*/")(3)); console.log(f("314159")(4)); ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 13 + 1 = 14 bytes +1 for `-v` flag to take input ``` :?!\i~1- io;\ ``` *Thanks to [@steenbergh](https://codegolf.stackexchange.com/users/44874) for notifying me about the `-v` flag and saving me 3 bytes!* Input the index with the command line argument `-v [index]` (0-indexed) and input the string through stdin. [Try it online!](https://tio.run/nexus/fish#@29lrxiTWWeoy5WZbx3z/7@BoZGxiamZuUUFiPVft0zBEgA "><> – TIO Nexus") ### Explanation The stack starts with the index on top. `:` duplicates it. `?` ignores the next character if the index is 0. (Popping it off the stack) If it is zero, `\` reflects the direction to go down. Then, it is reflected to the right with the next `\`. It wraps around and executes `i`nput a character, `o`utput it and `;` halts execution. If not, `!` skips the next instruction, so it doesn't go down. `i~` inputs a character and then immediately discards it. `1` pushes 1. `-` subtractes `1` from the index, so one character in the input is consumed and the index is decremented. The program loops around back to the `:`. [Answer] # [Carrot](https://github.com/kritixilithos/Carrot/), 16 bytes ``` $^//.{#}/S1//.$/ ``` [Try it online!](http://kritixilithos.github.io/Carrot/) The input format is as such: ``` string index ``` And the program is 1-indexed. ### Explanation Carrot has several global variables, one for each type: string, float and array (others to be implemented soon). The program starts in string-mode, where all the operators will affect the global string variable. And I call these variables the "stack". (Example input: `abcdef\n3`) ``` $ Get the first line of the input and set the stack-string to this value ^ Exit caret-mode stack-string = "abcdef" / Operator (behaves differently depending on the argument) /.{#}/ And the argument to this operator is a regex, so this program gets the matches of this regex into the stack-array . Any character {#} Pops a line from the input. So now this evaluates to # of any character where # is the second line of the input (in this case, 3) stack-array = ["abc"] And now we just need to get the last character in this string, but first S1 Join the array on the number 1 and set this to the stack-string. Because the array only contains one element, the number 1 does not appear in the stack-string. stack-string = "abc" / Operator; because the argument is a regex, this retrieves the matches of the regex: /.$/ Get the last character in the string stack-array = ["c"] ``` Now this returns a one element array containing a string of length one, but it is shown as a string in the website. If we really wanted to give the result as a string, we could easily do `S","` at the end, but it doesn't matter because the output still looks the same on the interpreter. [Answer] ## Batch, 32 bytes ``` @set/ps= @call echo(%%s:~%1,1%% ``` Reads `s` from STDIN and takes `n` as a command-line parameter. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), ~~7~~ 4 bytes ``` ~1/= ``` [Try it online!](https://tio.run/nexus/golfscript#@19nqG/7/7@xgpK2rpa@EgA "GolfScript – TIO Nexus") I suck in GolfScript, so I value [Martin Ender](/u/8478)'s help. [Answer] # [Turtlèd](https://github.com/Destructible-Watermelon/Turtl-d), 9 bytes ``` !?:[*l+]. ``` [**Try it online!**](https://tio.run/nexus/turtled#@69obxWtlaMdq/f/P5zJZQAA "Turtlèd – TIO Nexus") ## explanation: First off, Turtlèd is grid based, with a turtle thing. There are grid cells the turtle can move left, up, down, and right on, and can write things on the grid cells. ``` [the first grid cell the turtle starts on is marked with a *] ! input the string into the string variable ? input the number into the number variable : this command takes the number variable and moves right that many. hence this moves right by the amount inputted [* ] this is an `until` loop. the * there means that `until` the turtle ends the loop on a grid cell with * written on it (that is, the first cell), it will execute the code inside again and again l+ the code inside the while loop. the `l` moves the turtle left, and the + increments the string pointer. the string pointer is used with the string var; when you want to write something from the string, you use `.`, which writes the pointed char. the pointed char is the n-th character of the string, n being the value of the string pointer. this code will execute until the l moves the turtle back on to the origin cell. since we moved right by the number inputted, this will increase the string pointer (which starts at 1) by the amount inputted. . write the pointed char, which was dealt with in the previous comment. if 0 is inputted, turtle stayed on the origin square, and executed none of the loop, and turtle writes the first char of string input. if 1 is inputted, turtle moved one right, moved one left and incremented string pointer once, which means the second char is written. and so on. [the char of input has been written over the origin square] [implicitly the grid is outputted, which has spaces and blank lines taken out] [this is the requested char outputted, plus an unavoidable trailing newline due to how I made the interpreter. sue me] ``` [Answer] ## Clojure, 3 ``` nth ``` :P What can you do when there is a [built-in](https://clojuredocs.org/clojure.core/nth) for this? This works on lists, vectors, strings and sequences. It is either O(1) or O(n), depending on the used datatype. [Answer] # [sed](https://www.gnu.org/software/sed/), 31 bytes ``` : /^1/{s:1 .: :;b} s: (.).*:\1: ``` [Try it online!](https://tio.run/nexus/sed#@2/FpR9nqF9dbGWooGelYGWdVMtVbKWgoaepp2UVY2j1/79CYlJySiqXIYwGMhQUbRWSgCxDBW1dLX0Qw1DB2NDE0NTyX35BSWZ@XvF/3SIA "sed – TIO Nexus") Input: index and the string, separated by one space. Index in unary, but zero-based. [Answer] # [Dyvil](https://github.com/dyvil/dyvil), 4 Bytes ``` _[_] ``` Creates an anonymous function that takes a `String` and an `int` and returns a `char`. Usage: ``` let f: (String, int) -> char = _[_] print f("abc", 1) // b ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 3 bytes ``` a@b ``` This is 0-based. [Try it online!](https://tio.run/nexus/pip#@5/okPT///@Kyqr/hgA "Pip – TIO Nexus") [Answer] ## QBasic 4.5, 24 bytes ``` INPUT a$,b:?MID$(a$,b,1) ``` Pretty straightforward. [Answer] # Vim, 8 bytes ``` DJ@"|xVp ``` Since V is backwards compatible, you can [Try it online!](https://tio.run/nexus/v#@@/i5aBUUxFW8P@/IZejk7OLoxMA "V – TIO Nexus") [Answer] # Mathematica, 18 bytes ``` #~StringTake~{#2}& ``` Basic solution, but unfortunately the function name is quite long. [Answer] ## C#, 11 bytes ``` s=>n=>s[n]; ``` ]
[Question] [ # Intro: --- You accidentally corrupted the flow of time with a device you made for fun, that turned out to be a time machine. As a result, you got pushed to the far future. You realized that computing, processing power, and computers in general have been evolved by a huge amount, *an infinite amount to be precise*. So you grab yourself a computer with infinite memory and processing power. You have no idea how it can have infinite memory and infinite processing power, but you just accept it and return to the present. ## Challenge: --- You heard that the person who discovered the currently largest prime `2^74,207,281 − 1` got paid $100.000. You decide to make a program that finds the next prime, since you want to get back the money you spent for the computer. You make one that takes input of a number, and finds the next prime number, either by bruteforcing or any other method. **Clarifications:** You have a hypothetical machine with infinite memory and processing power. Your program MUST NOT be limited (e.g.: C#'s int's can store from `-2,147,483,648` to `2,147,483,647`), well your program must be able to store, and work with any number of any size. You have infinite resources, so you shouldnt care if you would run out of memory if you allowed that. **Example I/O:** Input: [The currently largest discovered prime with 22,338,618 digits.](https://en.wikipedia.org/wiki/Largest_known_prime_number) Output: Exactly the next prime Obviously, you dont have to prove that it works, as it would take a ton of time to compute in a physical machine. But if you moved your program to a hypothetical machine with infinite processing power / memory, it should compute instantly. --- Finding the next prime and checking if a number is a prime, are two completely different things [Answer] # Mathematica, 9 bytes ``` NextPrime ``` [Answer] # [Python 3](https://docs.python.org/3/), 45 bytes ``` f=lambda n,k=1,m=1:m%k*k>n or-~f(n,k+1,m*k*k) ``` [Try it online!](https://tio.run/nexus/python3#JYxNCoMwFITX9RSzERP7LElr/wS9i60KQZNIki666dXtKx2YGfgYxtjVh4T4jhn7EMcUxucrROPdYqxJQiuW3KZ26e1j6OFobjXZVjc2n8u5c/Ch@kyC@Z55yYzXPsDBOGjCkXAi1IQz4UK4Em6EO0Grn/@hmmy3BuOSKPJ6QNWBq0AOvgV/Sym3Lw "Python 3 – TIO Nexus") [Answer] ## Python 2, ~~78~~ ~~77~~ ~~76~~ 74 bytes ``` def f(n): while 1: n+=1 if[i for i in range(1,n)if n%i<1]==[1]:return n ``` --- -1 byte thanks to @KritixiLithos -1 byte thanks to @FlipTack -2 bytes thanks to @ElPedro [Answer] # Regex `🐇` (PCRE2 v10.35 or later), ~~80~~ 77 bytes ``` ^(?=(?*(x+?)(x*$))(?!(?*(xx+)(x+$))(?=\3*(x+))(?=\4\5(x*))\6\2\3*$))\2x+|\B|$ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hVbNbttGED4W0FOsmcTeJalUkmvDEE0Lji3ABmI7UGQ0jaUSNLmUFqGWBLmMZTe-9gF67aWXHPNA6bGv0UtnfyTRloAStrQ7O_PNz34z1J_fojytSvkfTKLo243VTPOooJ3mgTX-PngR04Rxit6dDPqd4OTqtB9cX54Pg5_PT4dn6KDxgvEorWKKDpXR6-lRI5qGBQrymzHy0cB6c3f36Xa3-uX-_sNwun83xV8rkTQPvl_8ins-7tl47vQIntsvCcG9LSWYOyBwlMAf7UoNvfxptAeKhIz2Rx2Qg8KoM3e-jN58ealB__7hX_Lcn-UiO_eD3Gl7tWBLUTA-kdGuZCwDKQ1nR2t6Rw3GBcphKQJaFFmBo4yXAqlM7Rkty3BCCfqtFHG3G4EGOjxERiyXSk55nHqooKIqOGp7j2uYch9lMXXRbZalKPOTMC0lrHJj4G46e_tjr4HgYQnCqujBhBqMwGhhjYP1rV2fnB0PDmxiDl1UsgeaJXgZ-I8LSU2fEKK8yAdnqKeTiLJKoC5aJkpkepYyQyqCLrKeJa-MLQusrBG3yLIeCTBuqjNZFqXx2Kh4ySacxijN-ER_hLy8o4WnCja7D6IwTSEMk7vZBbdpFn1CduSizxmLkR2HIoTaySLJJfJ9hOWJTbZXGMRgO87yZlrmZmYh4xgAVID5DRAhpRznpNke-y1Pp6DZgfLIt3Cva3mwcvxcf1lA2RNJaQLyChB3O4GASwVbCT-BhYKuAzGeV0Kaq8TgCpFd0MV-FopoGqhc7NVaoxW0rFLh6ivwTLO-P__YV5IkKSkcQr6QwkRMnyjY2WcaCbAyNwFNu_A_y1lKsSHF-3fDAcmj11EAwWLiGoyP_cFVMOwPLs4vj4f904W4_2HYvzyV-20Vk_k2kbTIisFbBRDQ1L7eDerT6NVS99eqEcA-FDRIimwW5KEQtOC4AJZfXr99awDqNtC6gs4FFHGx8jedG1i8hgIZLCm4gHBrvHQ38ew5gHaVshmrgzTbxKspxTQX_6tU0KgqSpbxjYrKbZIVSE2XhyVzYWKkMNaxbmTGXc094i0Yr64HTHgLyhOKjGGlsLh-uH_edlGelXCsT-A1EeOd5o5xKh_elrUFnS2_zvNul0thbwMucpS-g9oEBgZvrbD0rJXuOL3TuxvedtpjD4bNDCqBSxftzHdkYFCgEg7Hfs1-WQTmc9mDhz5ve8hxWD3jBSkfCIKgpBO8M-KQEpQOtBU_E2y9itE_v_-B4NXC4EiPEAis5k33kmzKp-xSxKx3FATNoCHU34rTsDbXSLy14DTuYQttbxsfW77pusHgahBcXl0cD0_OyBNDRb9aey0mhigq-swHhbfOmu1q-sP8NhlvmOTyeWysPjc1VlJQilf5rTe0VljuSX0i6kOYGcuBrTOBV4f-DfDX11Zzr9XSm_8A "C++ (GCC) - Attempt This Online") 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.) This is the first `🐇`-regex I've written that can be really said to compute its result before turning it into a number of possible matches. This output method allows actually directly returning the result; before adopting this output method, it was impossible for a regex to return a value greater than the input. The regex computes \$p-n\$, where \$n\$ is the input and \$p\$ is the next prime. To do this it takes advantage of the fact that there will always be a prime in the interval \$(n,2n]\$. Once that is complete, it outputs \$p-n+n=p\$ in the form of a number of possible matches. ``` ^ # tail = N = input number (?= (?* # Non-atomic lookahead (try all options until matching) (x+?)(x*$) # \1 = conjectured P - N; \2 = N - \1 ) (?! # Negative lookahead - assert that this cannot match (?* # Non-atomic lookahead (try all options until matching) (xx+) # \3 = try all numbers from 2 through N-1 (x+$) # \4 = N - \3; assert \3 < N ) (?= # Atomic lookahead (locks onto the first match) \3*(x+) # \5 = N % \3, giving \3 instead of 0 ) (?= # Atomic lookahead (locks onto the first match) \4 # head = \4 \5 # head += \5 (x*) # \6 = tail == N - head == tool to make tail = \4 + \5 ) \6 # tail = tail-\6 == \4 + \5 \2 # tail -= \2 \3*$ # Assert tail is divisible by \3 ) ) \2 # tail = \1 x+ # add tail to the number of possible matches | \B # add abs(N-1) to the number of possible matches | $ # add 1 to the number of the possible matches; this gets # us a return value of 2 for N==0, instead of 0 which we # would have if simply adding N instead of abs(N-1)+1 ``` Molecular lookahead `(?*`...`)` is used for convenience. It would be possible to port to flavors that don't have it, but the regex would be much longer – it would still need to emulate arithmetic in the range \$[0,2n]\$, but would need to do so within just \$[0,n/4]\$ or perhaps \$[0,n/3]\$, instead of \$[0,n]\$ as this version does. Without returning the correct value for \$0\$, this would be **72 bytes**. # Regex `🐘` (.NET), 79 bytes ``` (?=(x)*)((?<1>x)+?)(x*$)(?<!(?=(?=\6*(x+))\5\4(?<=^\3\6*))(^x+)(x+x))|(?<1>){2} ``` [Try it online!](https://tio.run/##RZBBboMwEEWv4qKR8EBBJGm7CHWJ1HVPEBIJUSdYcmxkjGKFsu0BesRehJpEUZfv/5k/X9PqMzddw6WcwLCt4Ufuduu14me6CSdaMOowQkqL18Wbw7hA6iJAjw@zV7DyJaIuRiyfyyevsn258hIi3XvVOw7x67qMw3Kcws1j8K5PrZD8M8AcLizLD9rwqm4oSCIUAaHa3uIAFQOZdK0UNkiCXBwoVGmte2UTaclyHogZVNtsN/oACopthbK7q5KDSiS/82LmOMZhzjgxMOlHZeuGdzR0YQQKb84Fh7MRlieN7uzomy3yfyaJ0v4lUihOAlDk9/uHgE9Lj0b3bedvpHXV2t7w7lYSg3EcpyxZZdkf "PowerShell – Try It Online") Returns its output as the capture count of group `\1`. ``` # tail = N = input number (?=(x)*) # \1.captureCount = N ((?<1>x)+?)(x*$) # Assert N > 0; \2 = P - N; # \1.captureCount += \2; \3 = N - \2 (?<! # Right-to-left negative lookbehind (?= # Atomic lookahead (?= # Atomic lookahead \6*(x+) # \4 = N % \6, giving \6 instead of 0 ) \5 # head = \5 \4 # head += \4 (?<= # Right-to-left atomic lookbehind ^\3\6* # Assert head-\3, that is, \5+\4-\3, is divisible by \6 ) ) (^x+) # \5 = N - \6; assert \6 < N (x+x) # \6 = try all numbers from 2 through N-1 ) | (?<1>){2} # if N == 0, \1.captureCount = 2 ``` Without returning a value for \$0\$, this would be **69 bytes**. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` Æn ``` [Try it online!](https://tio.run/nexus/jelly#@3@4Le////9mAA "Jelly – TIO Nexus") This implicitly takes input z and, according to the manual, generate the closest prime strictly greater than z. [Answer] # [Oasis](https://github.com/Adriandmen/Oasis), 2 bytes Run with the **`-n`** flag. Code: ``` p ``` [Try it online!](https://tio.run/nexus/oasis#@1/w//9/3bz/5gA "Oasis – TIO Nexus") [Answer] # [Bash](https://www.gnu.org/software/bash/) + coreutils, 52 bytes ``` for((n=$1,n++;`factor $n|wc -w`-2;n++)){ :;};echo $n ``` [Try it online!](https://tio.run/nexus/bash#@5@WX6ShkWerYqiTp61tnZCWmFySX6SgkldTnqygW56ga2QNFNfUrFawsq61Tk3OyAfK/f//39wYAA "Bash – TIO Nexus") The documentation for bash and factor do not specify a maximum integer value they can handle (although, in practice, each implementation does have a maximum integer value). Presumably, in the GNU of the future on your infinitely large machines, bash and factor will have unlimited size integers. [Answer] # Maxima, 10 bytes ``` next_prime ``` A function returns the smallest prime bigger than its argument. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes ``` <ṗ ``` [Try it online!](https://tio.run/nexus/brachylog2#@2/zcOf0///N/0cBAA "Brachylog – TIO Nexus") ### Explanation ``` (?) < (.) Input < Output ṗ (.) Output is prime (Implicit labelization of the Output at the end of the predicate) ``` [Answer] # Python with sympy, 28 bytes ``` import sympy sympy.nextprime ``` `sympy.nextprime` is a function which does what it says on the tin. Works for all floats. [**repl.it**](https://repl.it/FYgk) --- # Python, ~~66~~ 59 bytes -4 bytes thanks to Lynn (use `-~`) -3 bytes thanks to FlipTack (use `and` and `or`, allowing `...==1` to be switched to a `...-1` condition.) ``` f=lambda n:sum(-~n%-~i<1for i in range(n))-1and f(n+1)or-~n ``` [**repl.it**](https://repl.it/FYgm/1) A recursive function that counts up from `n` until a prime is found by testing that only one number exists up to `n-1` that divides it (i.e. 1). Works for all integers, raises an error for floats. Works on 2.7.8 and 3.5.2, does not work on 3.3.3 (syntax error due to lack of space between `==1` and `else`) [Answer] # Python, ~~114~~ 83 bytes ``` def g(b): while 1: b+=1 for i in range(2,b): if b%i<1:break else:return b ``` Without builtins, if there are any. -30 by removing whitespace and -1 by changing `b%i==0` to `b%i<1` [Answer] # [Perl 6](http://perl6.org/), 25 bytes ``` {first *.is-prime,$_^..*} ``` ### How it works ``` { } # A lambda. $_ ..* # Range from the lambda argument to infinity, ^ # not including the start point. first , # Iterate the range and return the first number which *.is-prime # is prime. ``` --- # [Perl 6](http://perl6.org/), 32 bytes ``` {first {all $_ X%2..^$_},$_^..*} ``` With inefficient custom primality testing. ### How it works Outer structure is the same as above, but the predicate passed to `first` (to decide if a given number is prime), is now: ``` { } # A lambda. $_ # Lambda argument (number to be tested). 2..^$_ # Range from 2 to the argument, excluding the end-point. X # Cartesian product of the two, % # with the modulo operator applied to each pair. all # Return True if all the modulo results are truthy (i.e. non-0). ``` [Answer] ## Pyke, ~~8~~ 7 bytes ``` ~p#Q>)h ``` [Try it here!](http://pyke.catbus.co.uk/?code=%7Ep%23Q%3E%29h&input=5) ### 4 bytes, noncompeting (Interpreter updated since challenge posted) ``` ~p<h ``` [Try it here!](http://pyke.catbus.co.uk/?code=%7Ep%3Ch&input=5) ``` ~p - primes_iterator() < - filter(^, input() < i) h - ^[0] ``` [Answer] # Lua, 876 Bytes ``` function I(a)a.s=a.s:gsub("(%d)(9*)$",function(n,k)return tostring(tonumber(n)+1)..("0"):rep(#k)end)end function D(a)a.s=a.s:gsub("(%d)(0*)$",function(n,k)return tostring(tonumber(n)-1)..("9"):rep(#k)end):gsub("^0+(%d)","%1")end function m(a,b)local A=K(a)local B=K(b)while V(0,B)do D(A)D(B)end return A end function M(a,b)local A=K(a)local B=K(b)while V(m(B,1),A)do A=m(A,B)end return A end function l(n)return#n.s end function p(a)local A=K(a)local i=K(2)while V(i,A)do if V(M(A,i),1)then return false end I(i)end return true end function V(b,a)A=K(a)B=K(b)if l(A)>l(B)then return true end if l(B)>l(A)then return false end for i=1,l(A)do c=A.s:sub(i,i)j=B.s:sub(i,i)if c>j then return true elseif c<j then return false end end return false end function K(n)if(type(n)=='table')then return{s=n.s}end return{s=tostring(n)}end P=K(io.read("*n"))repeat I(P)until p(P)print(P.s) ``` Lua, unlike some other languages, does have a Maximum Integer Size. Once a number gets larger than 232, things stop working correctly, and Lua starts trying to make estimates instead of exact values. As such, I had to implement a new method of storing numbers, in particular, I've stored them as Base10 strings, because Lua doesn't have a size limit on Strings, other than the size of the memory. I feel this answer is much more to the Spirit of the question, as it has to itself implement arbitrary precision integers, as well as a prime test. ## Explained ``` -- String Math _num = {} _num.__index = _num -- Increase a by one. -- This works by grabbing ([0-9])999...$ from the string. -- Then, increases the first digit in that match, and changes all the nines to zero. -- "13", only the "3" is matched, and it increases to 1. -- "19", firstly the 1 is turned to a 2, and then the 9 is changed to a 0. -- "9" however, the 9 is the last digit matched, so it changes to "10" function _num.inc(a) a.str = a.str:gsub("(%d)(9*)$",function(num,nines) return tostring(tonumber(num)+1)..("0"):rep(#nines) end) end -- Decrease a by one -- Much like inc, however, uses ([0-9])0...$ instead. -- Decrements ([0-9]) by one and sets 0... to 9... -- "13" only the "3" is matched, and it decreases by one. -- "10", the "1" is matched by the ([0-9]), and the 0 is matched by the 0..., which gives 09, which is clipped to 9. function _num.dec(a) a.str = a.str:gsub("(%d)(0*)$",function(num,zeros) return tostring(tonumber(num)-1)..("9"):rep(#zeros) end) :gsub("^0+(%d)","%1") end -- Adds a and b -- Makes A and B, so that the original values aren't modified. -- B is then decremented until it hits 0, and A is incremented. -- A is then returned. function _num.__add(a,b) local A = str_num(a) local B = str_num(b) while B > 0 do A:inc() B:dec() end return A end -- Subs b from a -- Works just like Addition, yet Dec's A instead of Incs. function _num.__sub(a,b) local A = str_num(a) local B = str_num(b) while B > 0 do A:dec() B:dec() end return A end -- A % B -- Makes A and B from a and b -- Constantly subtracts B from A until A is less than B function _num.__mod(a,b) local A = str_num(a) local B = str_num(b) while A >= B do A = A - B end return A end -- #a -- Useful for golfiness function _num.__len(n) return #n.str end -- Primacy Testing -- Generates A from a and i from 2. -- Whilst i is less than A, i is incremented by one, and if A % i == 0, then it's not a prime, and we return false. -- Once that finishes, we return true. function _num.isprime(a) local A = str_num(a) local i = str_num(2) while i < A do if A%i < 1 then return false end i:inc() end return true end -- b < a -- A and B are generated from a and b -- Fristly, if the length of A and B aren't equal, then that result is output. -- Otherwise, each character is searched from left to right, the moment they are unequal, the difference is output. -- If all the characters match, then it's equal. Return false. function _num.__lt(b,a) A=str_num(a) B=str_num(b) if #A > #B then return true end if #B > #A then return false end for i=1, #A.str do As = A.str:sub(i,i) Bs = B.str:sub(i,i) if As > Bs then return true elseif As < Bs then return false end end return false end -- b <= a -- Same as b < a, but returns true on equality. function _num.__le(b,a) A=str_num(a) B=str_num(b) if #A > #B then return true end if #B > #A then return false end for i=1, #A.str do As = A.str:sub(i,i) Bs = B.str:sub(i,i) if As > Bs then return true elseif As < Bs then return false end end return true end -- Just straight up returns it's string component. Endlessly faster than the int equivalent, mostly because it never is anything _but_ the string form. function _num.__tostring(a) return a.str end -- Just set up the metatable... function str_num(n) if(type(n)=='table')then return setmetatable({str = n.str}, _num) end return setmetatable({str = tostring(n)}, _num) end -- Generate a new str_num from STDIN Prime = str_num(io.read("*n")) -- This is handy, because it will call Prime:inc() atleast once, and stop at the next prime number it finds. -- Basically, if it weren't for all that overhead of making the math possible, that's all this would be. repeat Prime:inc() until Prime:isprime() print(Prime) ``` Although the above uses Metatables, instead of just regular functions like the actual answer, which worked out smaller. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes ``` ∆Ṗ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyIiLCIiLCLiiIbhuZYiLCIiLCI1Il0=) Here for completeness. Like answers in many other golfing langs, `∆Ṗ` is simply a builtin for "next prime greater than n". It uses `sympy.nextprime` from Python's `sympy` library to do this [Answer] # J, 4 bytes ``` 4&p: ``` Simple built in for next prime. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 13 bytes (Emigna @ -3 bytes) ``` 2•7£?ÿ•o[>Dp# ``` [Try it online!](https://tio.run/nexus/05ab1e#@2/0qGGR@aHF9of3Axn5h1ZGH1pnd2hlgfKhdf//R1ta6uga6Zga65jomJnrmJrqGAGZxrEA "05AB1E – TIO Nexus") ``` 2•7£?ÿ•o # Push current largest prime. [ # # Until true.. >Dp # Increment by 1, store, check primality. # After infinite loop, implicitly return next prime. ``` [Answer] ## Perl, 30 bytes (29 +1 for `-p`): ``` (1x++$_)=~/^(11+?)\1+$/&&redo ``` **Usage** Input the number after pressing return (input 12345 in example below, outputs 12347): ``` $ perl -pe '(1x++$_)=~/^(11+?)\1+$/&&redo' 12345 12347 ``` **How it works** * Define a string of `1`'s that has length `++$_`, where `$_` is initially the input value * The regex checks to see if the string of `1`s is non-prime length (explained [here](https://stackoverflow.com/q/3329766/133939)). * If the string length is non-prime, the check is re-evaluated for the next integer (`++$_`) * If the string length is prime, the implicit `while` loop exits and `-p` prints the value of `$_` * Note: there is no need to handle the edge case `"1"` of length 1 because it will never be used for values less than `1`, per the specification. [Answer] # Java 7, ~~373~~ ~~343~~ ~~334~~ ~~303~~ 268 bytes ``` import java.math.*;class M{public static void main(String[]a){BigInteger n,i,o,r=new BigInteger(a[0]);for(r=r.add(o=r.ONE);;r=r.add(o)){for(n=r,i=o.add(o);i.compareTo(n)<0;n=n.mod(i).compareTo(o)<0?r.ZERO:n,i=i.add(o));if(n.compareTo(o)>0)break;}System.out.print(r);}} ``` -75 bytes thanks *@Poke* **Ungolfed:** ``` import java.math.*; class M{ public static void main(String[] a){ BigInteger n, i, o, r = new BigInteger(a[0]); for(r = r.add(o = r.ONE); ; r = r.add(o)){ for(n = r, i = o.add(o); i.compareTo(n) < 0; n = n.mod(i).compareTo(o)< 0 ? r.ZERO : n, i = i.add(o)); if(n.compareTo(o) > 0){ break; } } System.out.print(r); } } ``` [Try it here.](https://ideone.com/mhrhxP) **Some example input/outputs:** ``` 7 -> 11 1609 -> 1613 104723 -> 104729 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` ÅN ``` [Try it online!](https://tio.run/##yy9OTMpM/f@oY97/w61@//8DAA "05AB1E – Try It Online") ``` ÅN # full program ÅN # push smallest prime greater than... # implicit input # implicit output ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` fP_Th ``` [Try it online!](https://tio.run/##K6gsyfj/Py0gPgRIGZoCAA "Pyth – Try It Online") --- Explanation: ``` f # first integer greater than or equal to hQ # input + 1 P_T # which is prime ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~4~~ 3 bytes *Edit: -1 byte thanks to Leo* ``` ḟṗ→ ``` [Try it online!](https://tio.run/##yygtzv7//@GO@Q93Tn/UNun///@GBgaWAA "Husk – Try It Online") ``` ḟ # first element that ṗ # is a prime, → # counting up beginning at one greater than the input ``` [Answer] ## Java, 176 Bytes ``` import java.math.*;import java.util.*;class a{public static void main(String[] args){System.out.print(new BigInteger(new Scanner(System.in).nextLine()).nextProbablePrime());}} ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 40 bits1, 5 [bytes](https://github.com/Vyxal/Vyncode/blob/main/README.md) ``` {›:æ¬| ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyI9IiwiIiwie+KAujrDpsKsfCIsIiIsIjQ1Il0=) Non-built-in answer, but does use a prime check built-in ## Explained ``` {›:æ¬| { | # While › # incrementing the top of the stack :æ¬ # gives a non prime number: # do nothing. just run the condition actually. ``` ## [Vyxal](https://github.com/Vyxal/Vyxal), 52 bits1, 6.5 [bytes](https://github.com/Vyxal/Vyncode/blob/main/README.md) ``` {›:KḢ₃¬| ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyI9IiwiIiwie+KAujpL4bii4oKDwqx8IiwiIiwiNDUiXQ==) Uses `KḢ₃` as a prime check (`len(factors(x)[1:] == 1`) [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) `-1`, 3 bytes ``` Ƥ$> ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJKuoVLsgqWlJWm6FkuOLVGxW1KclFwMFViwyMgYwgIA) #### Explanation ``` Ƥ$> # Implicit input Ƥ # Find the first prime > # which is greater than $ # the input integer # Implicit output ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 3 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` µƘP ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMiVCNSVDNiU5OFAmZm9vdGVyPSZpbnB1dD0yMyZmbGFncz0lMkI=) #### Explanation ``` µƘP # Implicit input µƘ # Find the next number after the input P # which is a prime number # Implicit output ``` [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 34 bytes ``` :{a=a+1[2,a/2|~a%b=0|b=a]]~a<b|_Xa ``` Based off this [QBIC primality tester](https://codegolf.stackexchange.com/a/105049/44874). Explanation: ``` :{a=a+1 Read 'a' from the command line, start an infinite loop and at the start of each iteration increment 'a' [2,a/2| FOR b = 2, b <= a/2, b++ ~a%b=0| IF b cleanly divides a, we're no prime b=a]] so, break out of the FOR loop ( ]] = End if, NEXT ) ~a<b| If the FOR loop completed without breaking _Xa then quit, printing the currently tested (prime) number The second IF and the DO-loop are implicitly closed by QBIC. ``` [Answer] # JavaScript (ES7), 61 bytes ``` a=>{for(;a++;){for(c=0,b=2;b<a;b++)a%b||c++;if(!c)return a;}} ``` ## Usage ``` f=a=>{for(;a++;){for(c=0,b=2;b<a;b++)a%b||c++;if(!c)return a;}} f(2) ``` ## Output ``` 3 ``` [Answer] # MATL, 3 bytes ``` _Yq ``` The function `Yq` returns the next prime of the absolute value of the input if the input is negative so we implicitly grab the input, negate it (`_`) and find the next prime using `Yq`. [**Try it Online!**](https://tio.run/nexus/matl#@x8fWfj/vzEA) [Answer] # Haskell, ~~42~~ ~~46~~ 43 bytes ``` f n=[i|i<-[n..],all((>0).rem i)[2..i-1]]!!1 ``` the usual code for brute force. Of course this finds the next *smallest* prime number after `n`. There is no biggest prime. Works for *n* > *0*. *edit:* Assumes `n` is prime. Thanks to [@Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni)'s advice in [the comments](https://codegolf.stackexchange.com/questions/108512/the-program-that-will-find-the-next-prime-number/108555?noredirect=1#comment264188_108555). ]
[Question] [ I'm surprised that this challenge isn't already here, as it's so obvious. (Or I'm surprised I couldn't find it and anybody will mark it as a duplicate.) ## Task Given a non-negative integer \$n\$, calculate the sum of the first \$n\$ primes and output it. ## Example #1 For \$n = 5\$, the first five primes are: * 2 * 3 * 5 * 7 * 11 The sum of these numbers is \$2 + 3 + 5 + 7 + 11 = 28\$, so the program has to output \$28\$. ## Example #2 For \$n = 0\$, the "first zero" primes are none. And the sum of no numbers is - of course - \$0\$. ## Rules * You may use built-ins, e.g., to check if a number is prime. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest number of bytes in each language wins! [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) routine, 75 bytes ``` A0 01 84 FD 88 84 FE C4 02 F0 32 E6 FD A0 00 A5 FD C9 04 90 1F 85 64 B1 FB 85 65 A9 00 A2 08 06 64 2A C5 65 90 02 E5 65 CA D0 F4 C9 00 F0 DC C8 C4 FE D0 DB A5 FD A4 FE 91 FB C8 D0 C8 A9 00 18 A8 C4 FE F0 05 71 FB C8 D0 F7 60 ``` Expects a pointer to some temporary storage in `$fb`/`$fc` and the number of primes to sum up in `$2`. Returns the sum in `A` (the accu register). Never did some prime checks in 6502 machine code, so here it finally comes ;) Note this starts giving wrong results for inputs >= 14. This is because of overflow, the code works with the "natural" number range of the 8bit platform which is `0 - 255` for *unsigned*. ### Commented disassembly ``` ; function to sum the first n primes ; ; input: ; $fb/$fc: pointer to a buffer for temporary storage of primes ; $2: number of primes to sum (n) ; output: ; A: sum of the first n primes ; clobbers: ; $fd: current number under primality test ; $fe: number of primes currently found ; $64: temporary numerator for modulo check ; $65: temporary divisor for modulo check ; X, Y .primesum: A0 01 LDY #$01 ; init variable for ... 84 FD STY $FD ; next prime number to test 88 DEY ; init number of found primes .mainloop: 84 FE STY $FE ; store current number of found primes C4 02 CPY $02 ; compare with requested number F0 32 BEQ .sum ; enough primes -> calculate their sum .mainnext: E6 FD INC $FD ; check next prime number A0 00 LDY #$00 ; start check against first prime number .primecheckloop: A5 FD LDA $FD ; load current number to check C9 04 CMP #$04 ; smaller than 4? 90 1F BCC .isprime ; is a prime (shortcut to get list started) 85 64 STA $64 ; store to temp as numerator B1 FB LDA ($FB),Y ; load from prime number table 85 65 STA $65 ; store to temp as divisor A9 00 LDA #$00 ; init modulo to 0 A2 08 LDX #$08 ; iterate over 8 bits .bitloop: 06 64 ASL $64 ; shift left numerator 2A ROL A ; shift carry into modulo C5 65 CMP $65 ; compare with divisor 90 02 BCC .bitnext ; smaller -> to next bit E5 65 SBC $65 ; otherwise subtract divisor .bitnext: CA DEX ; next bit D0 F4 BNE .bitloop C9 00 CMP #$00 ; compare modulo with 0 F0 DC BEQ .mainnext ; equal? -> no prime number C8 INY ; next index in prime number table C4 FE CPY $FE ; checked against all prime numbers? D0 DB BNE .primecheckloop ; no -> check next .isprime: A5 FD LDA $FD ; prime found A4 FE LDY $FE ; then store in table 91 FB STA ($FB),Y C8 INY ; increment number of primes found D0 C8 BNE .mainloop ; and repeat whole process .sum: A9 00 LDA #$00 ; initialize sum to 0 18 CLC A8 TAY ; start adding table from position 0 .sumloop: C4 FE CPY $FE ; whole table added? F0 05 BEQ .done ; yes -> we're done 71 FB ADC ($FB),Y ; add current entry C8 INY ; increment index D0 F7 BNE .sumloop ; and repeat .done: 60 RTS ``` --- ### Example C64 assembler program using the routine: **[Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22primesum.prg%22:%22data:;base64,AQgLCOIHnjIwNjEAAACpF40Y0KmVoAkgHqupuqAJogQgTAitugnw66m6oAkgvwiQCamYoAkgHquw2YUCqcGF+6kJhfwgSgmqqQBMzb3KhvuF/IT9oACEzIT+IELx8PuFAil/ySCwDskN8BDJFNDrpf7w59AGpf7F+/DfeKTTsdEpf5HRpQIgFuemz/AKpNOx0QmAkdGlAljJFPAgyQ3wCaT+kfzIhP7QsakApP6R/Hik07HRKX+R0ebMWGDG/rCahfuE/KAAjL4JjL8JjMAJsfvwEcjJIPD3yTCQBsk6sAKQ7ThgiDD7ogKx+8kwkAvJOrAHOOkwnb4JyogQ7KkAhfuiCE6+Ca2/CZACCRBKjb8JrcAJkAIJEEqNwAlm+8rwJq2+CckIMAXpA42+Ca2/CckIMAXpA42/Ca3ACckIMMPpA43ACbC8pfsYYKABhP2IhP7EAvAy5v2gAKX9yQSQH4VksfuFZakAoggGZCrFZZAC5WXK0PTJAPDcyMT+0Nul/aT+kfvI0MipABioxP7wBXH7yND3YD4gAMVSUk9SIFBBUlNJTkcgTlVNQkVSLCBUUlkgQUdBSU4uDQA=%22%7D,%22vice%22:%7B%22-autostart%22:%22primesum.prg%22%7D%7D)** **Code in [ca65](http://cc65.github.io/doc/ca65.html) syntax:** ``` .import primesum ; link with routine above .segment "BHDR" ; BASIC header .word $0801 ; load address .word $080b ; pointer next BASIC line .word 2018 ; line number .byte $9e ; BASIC token "SYS" .byte "2061",$0,$0,$0 ; 2061 ($080d) and terminating 0 bytes .bss linebuf: .res 4 ; maximum length of a valid unsigned ; 8-bit number input convbuf: .res 3 ; 3 BCD digits for unsigned 8-bit ; number conversion primebuf: .res $100 ; buffer for primesum function .data prompt: .byte "> ", $0 errmsg: .byte "Error parsing number, try again.", $d, $0 .code lda #$17 ; set upper/lower mode sta $d018 input: lda #<prompt ; display prompt ldy #>prompt jsr $ab1e lda #<linebuf ; read string into buffer ldy #>linebuf ldx #4 jsr readline lda linebuf ; empty line? beq input ; try again lda #<linebuf ; convert input to int8 ldy #>linebuf jsr touint8 bcc numok ; successful -> start processing lda #<errmsg ; else show error message and repeat ldy #>errmsg jsr $ab1e bcs input numok: sta $2 lda #<primebuf sta $fb lda #>primebuf sta $fc jsr primesum ; call function to sum primes tax ; and ... lda #$0 ; jmp $bdcd ; .. print result ; read a line of input from keyboard, terminate it with 0 ; expects pointer to input buffer in A/Y, buffer length in X .proc readline dex stx $fb sta $fc sty $fd ldy #$0 sty $cc ; enable cursor blinking sty $fe ; temporary for loop variable getkey: jsr $f142 ; get character from keyboard beq getkey sta $2 ; save to temporary and #$7f cmp #$20 ; check for control character bcs checkout ; no -> check buffer size cmp #$d ; was it enter/return? beq prepout ; -> normal flow cmp #$14 ; was it backspace/delete? bne getkey ; if not, get next char lda $fe ; check current index beq getkey ; zero -> backspace not possible bne prepout ; skip checking buffer size for bs checkout: lda $fe ; buffer index cmp $fb ; check against buffer size beq getkey ; if it would overflow, loop again prepout: sei ; no interrupts ldy $d3 ; get current screen column lda ($d1),y ; and clear and #$7f ; cursor in sta ($d1),y ; current row output: lda $2 ; load character jsr $e716 ; and output ldx $cf ; check cursor phase beq store ; invisible -> to store ldy $d3 ; get current screen column lda ($d1),y ; and show ora #$80 ; cursor in sta ($d1),y ; current row lda $2 ; load character store: cli ; enable interrupts cmp #$14 ; was it backspace/delete? beq backspace ; to backspace handling code cmp #$d ; was it enter/return? beq done ; then we're done. ldy $fe ; load buffer index sta ($fc),y ; store character in buffer iny ; advance buffer index sty $fe bne getkey ; not zero -> ok done: lda #$0 ; terminate string in buffer with zero ldy $fe ; get buffer index sta ($fc),y ; store terminator in buffer sei ; no interrupts ldy $d3 ; get current screen column lda ($d1),y ; and clear and #$7f ; cursor in sta ($d1),y ; current row inc $cc ; disable cursor blinking cli ; enable interrupts rts ; return backspace: dec $fe ; decrement buffer index bcs getkey ; and get next key .endproc ; parse / convert uint8 number using a BCD representation and double-dabble .proc touint8 sta $fb sty $fc ldy #$0 sty convbuf sty convbuf+1 sty convbuf+2 scanloop: lda ($fb),y beq copy iny cmp #$20 beq scanloop cmp #$30 bcc error cmp #$3a bcs error bcc scanloop error: sec rts copy: dey bmi error ldx #$2 copyloop: lda ($fb),y cmp #$30 bcc copynext cmp #$3a bcs copynext sec sbc #$30 sta convbuf,x dex copynext: dey bpl copyloop lda #$0 sta $fb ldx #$8 loop: lsr convbuf lda convbuf+1 bcc skipbit1 ora #$10 skipbit1: lsr a sta convbuf+1 lda convbuf+2 bcc skipbit2 ora #$10 skipbit2: lsr a sta convbuf+2 ror $fb dex beq done lda convbuf cmp #$8 bmi nosub1 sbc #$3 sta convbuf nosub1: lda convbuf+1 cmp #$8 bmi nosub2 sbc #$3 sta convbuf+1 nosub2: lda convbuf+2 cmp #$8 bmi loop sbc #$3 sta convbuf+2 bcs loop done: lda $fb clc rts .endproc ``` [Answer] # [Python 2](https://docs.python.org/2/), 49 bytes ``` f=lambda n,t=1,p=1:n and p%t*t+f(n-p%t,t+1,p*t*t) ``` Uses [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem), (as introduced to the site by xnor, I believe [here](https://codegolf.stackexchange.com/a/27022/53748)) **[Try it online!](https://tio.run/##K6gsycjPM/qfZhsDxDmJuUkpiQp5OiW2hjoFtoZWeQqJeSkKBaolWiXaaRp5ukCWTok2UE4LKKL5v6AoM69EIU3DWPM/AA "Python 2 – Try It Online")** The function `f` is recursive, with an initial input of `n` and a tail when `n` reaches zero, yielding that zero (due to the logical `and`); `n` is decremented whenever `t`, a test number which increments with every call to `f`, is prime. The prime test is then whether \$(n-1)!\ \equiv\ -1 \pmod n\$ for which we keep a track of a square of the factorial in `p`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes My first Jelly program ``` RÆNS ``` [Try it online!](https://tio.run/##y0rNyan8/z/ocJtf8P///00B "Jelly – Try It Online") [Answer] # Java 8, ~~89~~ 78 bytes ``` n->{int r=0,i=2,t,p;for(;n>0;r+=t<2?p+0*n--:0)for(p=t=i++;p%--t>0;);return r;} ``` [Try it online.](https://tio.run/##LU/LbsIwELzzFSskpLi2I4PUS4zpF5QLR@BggqlMw8ZyNlRVlG8PNnAZaWdH87jau5VtcHg9/051Y7sOvq3HYQbgkVy82NrBNp9PAuoiIzKdmHGWoCNLvoYtIBiYUG6GLIhGCW9WgkTQlzYWGjdKR25ovfoKXH2glJVi@RMMGc@5DgspKYmYjo76iBD1OOmcEPpTkxLeQffWn@GWKhY7ih5/9kew7NUv2@VwDxWg@8t998dBiaX4FEs1sqcIYPffkbuVbU9lSA7UYOH5vDrQnGOZ9rH3uHF6AA) **Explanation:** ``` n->{ // Method with integer as both parameter and return-type int r=0, // Result-sum, starting at 0 i=2, // Iteration-integer, starting at 2 t,p; // Temp integers for(;n>0 // Loop as long as `n` is still larger than 0: ; // After every iteration: r+=t<2? // If `t` is 1 (which means `p` is a prime): p // Increase `r` by `p` +0*n-- // And decrease `n` by 1 : // Else: 0) // Both `r` and `n` remain the same for(p=t=i++; // Set both `p` and `t` to the current `i`, // and increase `i` by 1 afterwards with `i++` p%--t>0;); // Decrease `t` by 1 before every iteration with `--t`, // and continue looping as long as `p` is NOT divisible by `t` return r;} // Return the result-sum ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÅpO ``` [Try it online.](https://tio.run/##MzBNTDJM/f//cGuB////pgA) **Explanation:** ``` Åp # List of the first N primes (N being the implicit input) # i.e. 5 → [2,3,5,7,11] O # Sum of that list # i.e. [2,3,5,7,11] → 28 ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 31 bytes ``` {sum grep(&is-prime,2..*)[^$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/urg0VyG9KLVAQy2zWLegKDM3VcdIT09LMzpOJT629n9xYqVCmoappjUXhGWg@R8A "Perl 6 – Try It Online") The `is-prime` built-in is unfortunately long. [Answer] # [J](http://jsoftware.com/), 8 bytes ``` 1#.p:@i. ``` [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N9QWa/AyiFT778ml5KegnqarZ66go5CrZVCWjEXV2pyRr5CmoIpjGFs8B8A "J – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~8~~ 7 bytes ``` ~lṗᵐ≠≜+ ``` [Try it online!](https://tio.run/##ASAA3/9icmFjaHlsb2cy//9@bOG5l@G1kOKJoOKJnCv//zX/Wg "Brachylog – Try It Online") Saved 1 byte thanks to @sundar. ### Explanation ``` ~l Create a list of length input ṗᵐ Each element of the list must be prime ≠ All elements must be distinct ≜ Find values that match those constraints + Sum ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` Σ↑İp ``` [Try it online!](https://tio.run/##yygtzv7//9ziR20Tj2wo@P//vykA "Husk – Try It Online") Generates the **İ**nfinite list of **p**rime numbers, and computes the sum of the first \$N\$ (`Σ↑`) [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 10 bytes ``` Sum@Primes ``` [Try it online!](https://tio.run/##SywpSUzOSP2fpmBlq/A/uDTXIaAoMze1@L9fampKcbRKQUFyeiwXF1AwryQktbjEObE4tTg6TUfBwMrQIPY/AA "Attache – Try It Online") ho hum [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 41 bytes ``` K`_ "$+"{`$ $%"_ )/¶(__+)\1+$/+`$ _ ^_ _ ``` [Try it online!](https://tio.run/##K0otycxLNPz/3zshnktJRVupOkGFS0VVKZ5LU//QNo34eG3NGENtFX1toHA8V1w8F1f8//@mAA "Retina – Try It Online") I wanted to keep adding 1 until I had found `n` primes but I couldn't work out how to do that in Retina so I resorted to a nested loop. Explanation: ``` K`_ ``` Start with 1. ``` "$+"{` ``` Loop `n` times. ``` $ $%"_ ``` Make a copy of the previous value, and increment it. ``` )/¶(__+)\1+$/+`$ _ ``` Keep incrementing it while it's composite. (The `)` closes the outer loop.) ``` ^_ ``` Delete the original `1`. ``` _ ``` Sum and convert to decimal. [Answer] # [MATL](https://github.com/lmendo/MATL), 4 bytes ``` :Yqs ``` [Try it online!](https://tio.run/##y00syfn/3yqysPj/f1MA "MATL – Try It Online") ### Explanation: ``` % Implicit input: 5 : % Range: [1, 2, 3, 4, 5] Yq % The n'th primes: [2, 3, 5, 7, 11] s % Sum: 28 ``` [Answer] # Ruby, 22 + 7 = 29 bytes Run with `ruby -rprime` (+7) ``` ->n{Prime.take(n).sum} ``` [Answer] # PHP, 66 bytes using [my own prime function](https://stackoverflow.com/a/39743570/6442316) again ... ``` for(;$k<$argn;$i-1||$s+=$n+!++$k)for($i=++$n;--$i&&$n%$i;);echo$s; ``` Run as pipe with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/39a2a6b4385ddbd12da15939193b35580a1b4f85). **breakdown** ``` for(;$k<$argn; # while counter < argument $i-1|| # 3. if divisor is 1 (e.g. $n is prime) $s+=$n # add $n to sum +!++$k # and increment counter ) for($i=++$n; # 1. increment $n --$i&&$n%$i;); # 2. find largest divisor of $n smaller than $n: echo$s; # print sum ``` [Answer] # [Haskell](https://www.haskell.org/), 48 bytes ``` sum.(`take`[p|p<-[2..],all((>0).mod p)[2..p-1]]) ``` [Try it online!](https://tio.run/##FcuxCsIwEIDhV7kxARNUcEtd@gIdCzXQwya19JIezbn57MY6/MsH/wvLGohqhAYetbyTVaPgGsaBP@zMcLXWn5BIqftZ27RNwPqPbC7e65pwycfJ@5IFLMSjPeAEjXMwB2m3LCFLqbfvMxLOpZq@7bof "Haskell – Try It Online") **Note:** `\p-> all((>0).mod p)[2..p-1]` is not a valid prime check, since it is `True` for \$0,1\$ as well. But we can work around that by beginning with \$2\$, so in this case it suffices. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 20 bytes ``` n->vecsum(primes(n)) ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P0/Xriw1ubg0V6OgKDM3tVgjT1Pzf1p@kUaegq2CgY6CIRADZfJKgAJKCrp2QCINpEbzPwA "Pari/GP – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 70 bytes ``` f(n,i,j,s){s=0;for(i=2;n;i++)for(j=2;j/i?s+=i,n--,0:i%j++;);return s;} ``` [Try it online!](https://tio.run/##FYzBCsIwEETv/YqhEEjIBkuPrtEf8SLFyAZcJamn0m@P6Wl485hZwmtZWktWSShTdVuNE6dPsRJnVhbv3UG5Uz7JrfoopCHQdBaTvWfH5bn@iqLy3kRXvB@i1mEbgD6EPTpBxMQ9LpiP7Kdd41u6THY0gnCFkbuOBCEkK87xsLc/ "C (gcc) – Try It Online") [Answer] ## C, C++, D : ~~147~~ 142 bytes ``` int p(int a){if(a<4)return 1;for(int i=2;i<a;++i)if(!(a%i))return 0;return 1;}int f(int n){int c=0,v=1;while(n)if(p(++v)){c+=v;--n;}return c;} ``` ### 5 bytes optimization for C and C++ : -2 bytes thanks to Zacharý ``` #define R return int p(int a){if(a<4)R 1;for(int i=2;i<a;++i)if(!(a%i))R 0;R 1;}int f(int n){int c=0,v=1;while(n)if(p(++v))c+=v,--n;R c;} ``` `p` tests if a number is a prime, `f` sums the `n` first numbers Code used to test : C/C++ : ``` for (int i = 0; i < 10; ++i) printf("%d => %d\n", i, f(i)); ``` ## [D Optimized answer by Zacharý](https://tio.run/##PU5LCsMgEN33FNNAwUFTaunO2FN4AcmHDiQarE0WwbOnpiF9MAzM@8xr1tXAyAwyAxYX6pitHhja@AkOpOp8yATpu6LKKsz0mdkLcY6H5qb@4mSg25McLgZqMWmp5hf1LXObdWScT4g115MoS3cYa5XWyVMDgyXHEJYTZNAw@hDhHZtrHvLqd936kItAoPPnvCqQUgHndPg2zIFi2ztGAgrQTyhELkaIe0Y6pfUL), ~~133~~ 131 bytes D has a golfy template system ``` T p(T)(T a){if(a<4)return 1;for(T i=2;i<a;)if(!(a%i++))return 0;return 1;}T f(T)(T n){T c,v=1;while(n)if(p(++v))c+=v,--n;return c;} ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) `-x`, 11 bytes ``` ;@_j}a°X}hA ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=O0Bfan1hsFh9aEE=&input=NQoteA==) Saved several bytes thanks to a new language feature. Explanation: ``` ;@ }hA :Get the first n numbers in the sequence: a : Get the smallest number °X : Which is greater than the previous result _j} : And is prime :Implicitly output the sum ``` [Answer] # [Factor](https://factorcode.org/) + `math.primes math.unicode`, 14 bytes ``` [ nprimes Σ ] ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQm1iSoVdQlJmbWgxhl@ZlJuenpCoUFKWWlFQCZfJKFIpTC0tT85KBSqy5qhUMFAwVjBSMFUwUTBVq/0cr5EG1n1usEPs/N7FAQe8/AA "Factor – Try It Online") ## Explanation: It's a quotation (anonymous function) that takes an integer as input and leaves an integer as output. * `nprimes` Obtain a list of the first n primes. * `Σ` Sum the list. [Answer] # [D](https://dlang.org/), 106 bytes ``` T f(T)(T n){T p(T a){T b=1;for(T i=2;i<a;)b*=a%i++;return b;}T c,v=1;while(n)if(p(++v))c+=v,--n;return c;} ``` [Try it online!](https://tio.run/##NU9bCoNADPzvKYZCYdPVUvsbt6fYC/ikAV1lu9UP8ex2bXFgyEyYJKTeNotWWVIWjhaLMYpiF6XJuB18tGIeLHnBVF5NcRGt2Tfh4x1KXi2qZIrJ@SVdoxxJq0al9URUaTMlaeqOcMXrNg1Soy/EKcJyQoT04@AD3qG@RcrAv@5@V1yAwODOseTIMobWcsztmL2EpnNKEpxhnjgn8RMh@u9YT@v2BQ "D – Try It Online") Based on my previous revisions to HatsuPointerKun's C++ answer. [Answer] # JavaScript (ES6), 55 bytes ``` f=(k,n=2)=>k&&(g=d=>n%--d?g(d):d<2&&k--&&n)(n)+f(k,n+1) ``` [Try it online!](https://tio.run/##FcpRDkAwDADQ02jaUAmJH9E5i6gtTDoxcf2J9/2O5V3yeu/Xw5Z0K8ULxsakJ3ERAIOoOKuYdQ6oNOrUA0RmACM0qv2/647Kmiync2vPFNDjQFQ@ "JavaScript (Node.js) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ê☺Γ☼èY ``` [Run and debug it](https://staxlang.xyz/#p=8801e20f8a59&i=5%0A0&a=1&m=2) Explanation: ``` r{|6m|+ Unpacked program, implicit input r 0-based range { m Map: |6 n-th prime (0-based) |+ Sum Implicit output ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 + 9 = 16 bytes ``` +/pco∘⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVOdI9ZS0vGJ1rrRHbRO09QuS8x91zHjUuxksCRTSUA8uzVXX1FBXVshPUwgoysxNLVbX5Kp@1LtLR10BCNR1TLQf9W6tfdSzI@3QChB7s6EBAA "APL (Dyalog Unicode) – Try It Online") 9 additional bytes to import the `pco` (and every other) Dfn: `⎕CY'dfns'` ### How: ``` +/pco∘⍳ ⍳ ⍝ Generate the range from 1 to the argument ∘ ⍝ Compose pco ⍝ P-colon (p:); without a left argument, it generates the first <right_arg> primes. +/ ⍝ Sum ``` [Answer] # [JAEL](https://github.com/eduardoHoefel/JAEL), 5 bytes ``` #&kȦ ``` ### Explanation (generated automatically): ``` ./jael --explain '#&kȦ' ORIGINAL CODE: #&kȦ EXPANDING EXPLANATION: Ȧ => .a! EXPANDED CODE: #&k.a!, # , repeat (p1) times: & push number of iterations of this loop k push nth prime . push the value under the tape head a push p1 + p2 ! write p1 to the tape head ␄ print machine state ``` [Answer] # [Reticular](https://github.com/ConorOBrien-Foxx/reticular), ~~52~~ 40 bytes ``` indQ2j;o_1-2~d:^=[d@P~1-]:^`*[+]:^`1+*o; ``` [Try it online!](https://tio.run/##K0otyUwuzUks@v8/My8l0CjLOj/eUNeoLsUqzjY6xSGgzlA31iouQStaG0QZamvlW///bwoA "Reticular – Try It Online") ## Explanation Fun fact: Reticular does not count 2 as a prime number, so the instruction `@P` which gives the \$n\$-th prime in reality gives the \$(n+1)\$-th prime and due to this we have to add the first prime 2 manually. ``` in # Read input and convert to int dQ2j;o_ # Check if input is 0. If so, output and exit 1-2~d:^= # Subtract 1 from input and save it as `^` [d@P~1-] # Duplicate the top of the stack (call it k) and push the k-th prime. Finally swap the two top items in the stack and subtract 1. Stack before: [k] Stack after: [k-1, k-th prime] :^`* # Repeat the above a `^` number of times. Stack before: [n] Stack after: [0, 3, 5, ..., n-th prime, 2] [+]:^`1+* # Add the two top items in the stack a total of (`^`+1) number of times o; # Output the sum and exit. ``` [Answer] # Vyxal, 2 bytes, `s` ``` ʁǎ ``` [Try it!](http://lyxal.pythonanywhere.com?flags=s&code=%CA%81%C7%8E&inputs=5&header=&footer=) **Explanation** ``` ʁ # Range from 0 to input ǎ # Map to a_th prime ``` At last, sum with `s` flag *Disclaimer: my first Vyxal answer* [Answer] # [Pyt](https://github.com/mudkip201/pyt), 3 bytes ``` řᵽƩ ``` [Try it online!](https://tio.run/##K6gs@f//6MyHW/ceW/n/vykA "Pyt – Try It Online") ``` ř implicit input (n); creates array of [1,2,...,n] ᵽ gets the kth prime for each item k in the array Ʃ sums the array; implicit print ``` [Answer] # [Arturo](https://arturo-lang.io), 38 bytes ``` $[n][sum take select 2..n*n=>prime? n] ``` [Try it](http://arturo-lang.io/playground?BNjv0Z) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~8~~ 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Èj}jU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=yGp9alU&input=OA) ``` Èj}jU :Implicit input of integer U È :Function taking an integer as argument j : Is prime? } :End function jU :First U integers >=0 that return true :Implicit output of sum of resulting array ``` ]
[Question] [ Actually *not* inspired neither by [Atbash Self Palindromes](https://codegolf.stackexchange.com/questions/68757/atbash-self-palindromes) nor by [Generalized Gematria Calculator](https://codegolf.stackexchange.com/questions/41760/generalized-gematria-calculator). Given a string *s* of length *n*, output the [Revu'a sequence](https://en.wikipedia.org/wiki/Gematria#Methods), which is the first character of *s*, the first two characters of *s*, ... the first *n*–2 characters of *s*, the first *n*–1 characters of *s*, the entire *s*. The string will only consist of Unicode (any encoding you want) characters that have [strong directionality](https://en.wikipedia.org/wiki/Bi-directional_text#strong_characters) and are found in the range 0x0000 through 0xFFFF. However, no directionality control characters will occur. All characters in any given string will have the same directionality. You may return in array notation `["t","te","tes","test"]`, as a space-separated string `"t te tes test"`, as multi-line text `t` `te` `tes` `test` , a pre-formatted array ``` t te tes test ``` , or anything similar. Amounts of leading, separating, and trailing spacing is not important, and neither are trailing newline. Ask if in doubt. Right-to-Left input must result in Right-to-Left output in proper order: Input: `"נחמן"` Output: `"נ נח נחמ נחמן"` or ``` נ נח נחמ נחמן ``` , or `["נ","נח","נחמ","נחמן"]`. Among invalid results are `"נחמן נחמ נח נ"` ,`"ן מן חמן נחמן"`, and `"נחמן חמן מן ן"`. [Answer] ## Dyalog APL, 2 bytes ``` ,\ ``` Cumulative reduce by concatenate. Try it [here](http://tryapl.org/?a=%2C%5C%27%u05E0%u05D7%u05DE%u05DF%27&run). The formatting of the output is nicer [when you prefix a `⍕`](http://tryapl.org/?a=%u2355%2C%5C%27%u05E0%u05D7%u05DE%u05DF%27&run), but it clearly shows the correct order without. [Answer] # JavaScript (ES6), ~~27~~ ~~26~~ 25 bytes *Saved one byte thanks to @nicael and @MartinBüttner, one thanks to @Neil* ``` x=>x.replace(/.?/g,"$` ") ``` Takes advantage of some [built-in features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter) of JS's `.replace` function. Specifically, in the replacement, `$`` becomes everything preceding the matched character. Using the regex `/.?/g` rather than `/./g` means it also matches the empty string at the end. [Answer] ## Retina, ~~11~~ 7 bytes ``` . $`$0 ``` Output is space-separated, with a leading space and a trailing linefeed. [Try it online!](http://retina.tryitonline.net/#code=LgogJGAkMA&input=16DXl9ee158) [Answer] # Japt, ~~10~~ 4 bytes I didn't realize that a cumulative reduce would be so useful in this case. :-) ``` U¬å+ ``` Outputs as an array, comma-separated by default. If this is not allowed, use this 6-byte code instead: ``` U¬å+ · ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=VazlKw==&input=Ilx1MDVlMFx1MDVkN1x1MDVkZVx1MDVkZiI=) ### How it works ``` // Implicit: U = input string U¬ // Split U into chars. å+ // Cumulative reduce: loop through each item in the array, concatenating it to the total. // ["t","e","s","t"] => ["t","te","tes","test"]. // Implicit: output last expression ``` [Answer] # Brainfuck, 40 bytes My console doesn't support Right-to-Left characters, but I don't think it will work :c ``` ++++++++++>,[>,]<[<]>[[<+>-]<[<]>[.>]>] ``` Ungolfed: ``` ++++++++++> # Store 10 (Newline) ,[>,] # Store input <[<]> # Goto first character [ # While next character [<+>-] # Copy character to the left <[<]> # Goto first character [.>] # Print all charaters > # Go to next character ] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` η ``` Builtins ftw ¯\\_(ツ)\_/¯ Outputs as a list of prefixes. [Try it online](https://tio.run/##yy9OTMpM/f//3Pb//68vuD79@rzr8wE) or [verify all test cases.](https://tio.run/##yy9OTMpM/V9TVvn/3Pb/Ov9LUotLuK4vuD79@rzr87kS81LiE/PySzJSi@JBMgA) **Explanation:** ``` η # Push a list of prefixes of the (implicit) input-string # (and output this list implicitly as result) ``` [Answer] # Python, 35 ``` f=lambda s:f(s[:-1])+[s]if s else[] ``` Couldn't find a way to use `and/or` to simplify the recursion because `[]` is falsy. Recursive solution, returns a list of strings. [Try it online](https://ideone.com/d1wDve) [Answer] # Prolog (SWI), ~~60~~ 49 bytes **Code:** ``` p(X):-findall(S,atom_prefix(X,S),[_|R]),write(R). ``` **Explained:** **atom\_prefix** with **X** set to input and **S** as a variable gives 1 prefix of the atom **X** starting with the empty atom. **findall** gets all solutions and puts them in a list. **[\_|R]** throws away the head (the empty atom) and stores the tail in **R** **Examples:** ``` p('נחמן'). [נ, נח, נחמ, נחמן] p('test'). [t, te, tes, test] ``` Try it online [here](http://swish.swi-prolog.org/p/HdptFMQA.pl) **Edit:** saved 11 bytes by only storing the tail in **R**. [Answer] # Pyth, 3 ``` ._z ``` Prefix builtin does the trick. [Test Suite](http://pyth.herokuapp.com/?code=._z&input=%D7%A0%D7%97%D7%9E%D7%9F&test_suite=1&test_suite_input=%D7%A0%D7%97%D7%9E%D7%9F%0Aa%0Aabcd&debug=0) [Answer] # GNU Sed, 21 Score includes +1 for `-E` option to sed: ``` : s/^(\S+)\S/\1 &/ t ``` Works for LTR, but not RTL - I missed that bit.. Actually it *does* work, the RTL was just not rendering correctly in my terminal. It works fine with IO viewed in a sensible text editor (e.g. emacs). It also works in Ideone: [Try it online.](https://ideone.com/fk4Qo1) [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 5 bytes ``` @[@w\ ``` [Try it online!](http://brachylog.tryitonline.net/#code=QFtAd1w&input=Iteg15fXntefIg) ### Explanation ``` @[ Take a prefix of the input @w Write this prefix to STDOUT followed by a linebreak \ False: try another prefix ``` Right-to-left strings seem to work properly, even though I never even considered them. [Answer] ## CJam, 9 bytes ``` l{N2$@+}* ``` Output is linefeed-separated. [Test it here.](http://cjam.aditsu.net/#code=l%7BN2%24%40%2B%7D*&input=%D7%A0%D7%97%D7%9E%D7%9F) ### Explanation ``` l e# Read input. { e# Fold this block over the input, which is effectively a foreach-loop which skips e# the first character... N e# Push a linefeed. 2$ e# Copy the previous string. @ e# Pull up the current character. + e# Concatenate. }* ``` [Answer] ## JavaScript, 36 bytes ``` x=>[...x].map((c,i)=>x.slice(0,i+1)) ``` Demo: ``` a=x=>[...x].map((c,i)=>x.slice(0,i+1)); document.write( a("test")+"<br>"+ a("נחמן") ) ``` The principle is to map and output the slice of string from the first char to the every char in the word. Surprisingly, this works perfectly for the RTL strings too, no optimization needed. [Answer] My console doesn't support Right-to-Left characters, but I don't think it will work :c **C, 74 bytes (2nd entry)** ``` char m[2<<9];i;main(){do{m[i]=getchar();printf("%s ",m);}while(m[i++]>0);} ``` Ungolfed: ``` #include <stdio.h> // char, because `printf("%s", str);` expects a array of characters. char str[2<<9]; int str_len = 0; int main(void) { do { str[str_len]=getchar(); printf("%s ", str); } while(m[i++]>0); return 0; } ``` [Answer] My console doesn't support Right-to-Left characters, but I don't think it will work :c **C, 105 bytes (3th entry)** ``` m[2<<9];i;j;k;main(){while((m[i++]=getchar())<0);for(;j<i;j++,putchar(10))for(k=0;k<j;k++)putchar(m[k]);} ``` Ungolfed: ``` #include <stdio.h> int str[2<<9]; int str_len = 0; int main(void) { do { str[str_len] = getchar(); } while(str[str_len++] != EOF); int i; for(i=0; i<str_len; i++) { int j; for(j=0; j<i; j++) { putchar(str[j]); } putchar(10); } } ``` [Answer] ## TI-BASIC, 18 bytes ``` For(X,1,10^(9 Disp sub(Ans,1,X End ``` Not technically valid: TI-BASIC doesn't support Unicode. Name this `prgmA`, and input using `Ans`. Program recursion would be shorter, but there would be no way to initialize the variables. Therefore, we display a substring of the input at each iteration. The input is never overwritten, since Disp doesn't return a value. Eventually, the program terminates with an error after printing the whole string. [Answer] # Python, 54 Bytes ``` b='';y=input() for a in range(len(y)):b+=y[a];print(b) ``` [Answer] # Java 8, ~~95~~ ~~92~~ 58 bytes ``` s->{for(int i=0;;)System.out.println(s.substring(0,++i));} ``` [Try it online.](https://tio.run/##dY@xbsIwEIZ3nuLkyVZKxFyLbh0YSgfGqoMxpjUEJ8qdUVHk52Cjfas8Tuo4oUthOcmn///u804d1XS32Xe6UIjwoqxrJgDWkam3ShtY9k@AY2k3oPmKaus@AIWM2zCJA0mR1bAEB/MOp0/Ntqx5rIOdz6QUqxOSOeSlp7yKVSocxxz9GhOIzx6yzAohQyd7WOXXRYSNzHTzEI3Gs2/voMSgQwaJs36ypHLdtD/tub203@yfYIKl0N8fBtQNQ7ZwladHYBmO9FuhV09D6mpQnxqXax47QSvSn/z5S5uKbOnAiCbcA42qofsF) **Explanation:** ``` s->{ // Method with String parameter and no return-type for(int i=0; // Index-integer, starting at 0 ;) // Loop indefinitely: System.out.println( // Print with trailing newline: s.substring(0,++i // Increase the index by 1 first with `++i` ));} // And print an input-substring in the range [0,i) ``` Stops the infinite loop with a `StringIndexOutOfBoundsException` after everything has been printed to STDOUT already, which is [allowed according to the meta](https://codegolf.meta.stackexchange.com/a/4781/52210). [Answer] # [MATL](https://esolangs.org/wiki/MATL), 8 bytes Uses [current version (8.0.0)](https://github.com/lmendo/MATL/releases/tag/8.0.0) of language/compiler ``` jtn1X"YR ``` ### Example ``` >> matl > jtn1X"YR > > test t te tes test ``` ### Explanation ``` j % input string tn % duplicate and get length, say "N" 1X" % repeat string N times vertically. Gives a char matrix YR % lower triangular part of matrix. Implicitly print ``` [Answer] # Mathematica, 29 bytes ``` #<>#2&~FoldList~Characters@#& ``` TODO: explanation [Answer] # 𝔼𝕊𝕄𝕚𝕟, 7 chars / 16 bytes ``` ᴉⓜᵖ ᵴ˖$ ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=false&input=%D7%A0%D7%97%D7%9E%D7%9F&code=%E1%B4%89%E2%93%9C%E1%B5%96%20%E1%B5%B4%CB%96%24)` There's probably a builtin for this somewhere - I just haven't found it. # Explanation ``` ᴉⓜᵖ ᵴ˖$ // implicit: ᴉ=split input, ᵴ=empty string ᴉⓜ // map over ᴉ ᵖ ᵴ˖$ // push ᵴ+=(mapped item char) // implicit stack output, separated by newlines ``` [Answer] # Javascript ES6, 29 bytes ``` (a,b='')=>[...a].map(x=>b+=x) ``` This ain't winning anything, but it's a simple solution. [Answer] # Pyth, 11 Bytes ``` Vlz=k+k@zNk ``` [Try It Out](https://pyth.herokuapp.com/?code=Vlz%3Dk%2Bk%40zNk&input=test&debug=1) ***Explanation*** ``` (z=input) (k="") V for N in Range( lz length of z): =k+k@zN k=k+z[N] k print(k) ``` [Answer] ## Python, 32 bytes ``` f=lambda s:s and f(s[:-1])+" "+s ``` Recursive function that outputs a space-separated string with a leading space. A 34-byte program (Python 2): ``` s="" for c in input():s+=c;print s ``` [Answer] ## PowerShell v2+, 28 bytes ``` [char[]]$args[0]|%{($o+=$_)} ``` Takes input `$args[0]`, casts it as a `char`-array, pipes the characters into a loop `|%{...}`. Each iteration, we accumulate onto `$o` via `+=` the current character `$_`. That expression is encapsulated in parens so a copy is placed on the pipeline. At end of execution, the pipeline is flushed via `Write-Output` which puts a newline between elements. ``` PS C:\Tools\Scripts\golfing> .\spell-out-the-revua "נחמן" נ נח נחמ נחמן PS C:\Tools\Scripts\golfing> .\spell-out-the-revua "PPCG" P PP PPC PPCG ``` [Answer] # [V](http://github.com/DJMcMayhem/V), 5 bytes ``` òÄ$xh ``` [Try it online!](http://v.tryitonline.net/#code=w7LDhCR4aA&input=SGVsbG8gV29ybGQh) Explanation: ``` ò " Recursively: Ä " Duplicate this line $ " Move to the end of this line x " Delete one character h " Move one character to the right, which will throw an error when the line is one character long ``` [Answer] # [jq](https://stedolan.github.io/jq/), 17 bytes ``` .[:range(length)] ``` [Try it online!](https://tio.run/##yyr8/18v2qooMS89VSMnNS@9JEMz9v9/pYzUnJx8pX/5BSWZ@XnF/3WLAA "jq – Try It Online") -10 from ovs. [Answer] # PHP, 59 Bytes ``` for(;$i++<mb_strlen($argn);)echo"\n".mb_substr($argn,0,$i); ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/34c6bf3768ceea746ad250f2d99745189a1bbe19) [Answer] # [Unwanted, Unnecessary, Opportunistic](https://github.com/faso/Unwanted-Unnecessary-Opportunistic), 9 bytes ``` E<+S0;*P ``` [Answer] # [.+?](https://github.com/EdgyNerd/DotPlusQuestion/blob/master/README.md), 18 bytes ``` ^((.+).) \2\n\1 $ ``` # Explanation ``` ^((.+).) Replace the first line with \2 The first line missing the last character \n A newline \1 The first line $ Repeat until the regex doesn't match (when first line has 1 character) ``` [Try it online!](https://tio.run/##TY5BTsMwEEX3c4qRKKrdFKsOO4RP0gQpRW5jkToj24B6EnbArXIc46FR1N3Mn/efhi6pH/1jzu5MY0gYL3GLwQKF8YSGV9WF08detyrS4JJYN34tAdwRB@sFY/K@NkY/ATpPhgNFIwkJdoj2mt6K6raUOdnBZ@8Gi4429fPi4sKxPKDOXXrt/7M9E@2WRXyehQWJ74dbYBkrPdMME1YGNeD8DdsdGbPjGQ/Bdm9X6oGpO6TgfBKlXAxFsKwy5/wihKqkktDUjW80rCBPv9PX9D39/AE ".+? - Try it Online!") (The second command line argument is input) ]
[Question] [ # Intro Two numbers are a *reversed multiple pair* if they satisfy the following property: $$ a\cdot b = \operatorname{reversed}( (a-1)\cdot b ) $$ Here, \$\operatorname{reversed}()\$ means to reverse the digits of a number (e. g `123` becomes `321`.) # Example $$ a=6,\quad b=9,\quad 6\cdot 9=54,\quad 5\cdot 9=45 $$ As you can see, \$45\$ is the reversed version of \$54\$. # Task Given two integers, \$a\$ and \$b\$, output if these two numbers is a reversed multiple pair. # Test Cases ``` 6 9 => True 4 5 => False 3 2178 => True 34 2079 => True 7 8 => False 600 100 => False 46 1089 => True 817 503 => False 6 9009 => True 321 81 => False 10 1089 => False ``` Shortest code wins! [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 76 bytes ``` (load library (d f(q((a b)(e(to-base 10(*(- a 1)b))(reverse(to-base 10(* a b ``` [Try it online!](https://tio.run/##VYtBCoMwFET3nmKWPwXhx2iix0kwQiDUNkrB06fB301X85g3c6bnldPxqpXy7lfkFIovV0crNnoTeQRFkc69D/6I0EwP6uGhVVCKSvzEcvzrJkOlDRaL6lqOmO40GLSbBUcM7EQ7SGeZ253lYhvO4mftMLGRDRZmqc2gm7pR829dvw "tinylisp – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` -₁ʰ×↔~×? ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X/dRU@OpDYenP2qbUnd4uv3//9EmZjqGBhaWsf8B "Brachylog – Try It Online") ### Explanation ``` Input = [A, B] -₁ʰ Compute [A-1, B] × Compute (A-1) × B ↔ Reverse digits ~×? It can be unmultiplied into [A,B] ``` [Answer] # [Python 3](https://docs.python.org/3/), 37 bytes ``` lambda a,b:str(a*b)==str(~-a*b)[::-1] ``` [Try it online!](https://tio.run/##TYzNCsIwEITveYrFUyKxpP@1kB59Am/qIaUtBtImJFHoxVevDUjrYZeZnW/WzP6pp3QZ@H1RYmw7AYK2tfMWi2NLOA/qcwr6Vten@LHI0Wjrwc0ODdqCAjkFEznfyalGIKnmKnJGSY8PvDkQFD7y4ygM7t9CUfkLCaEIjJWTxytAh7AJDQjWhCwFnIE3cLWvHmWQB30RyvUohSQuqy1LM0hYubMlVDtbMAbxOtshK1Zf7XQVl5Cz9K8BZ8a2/As "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ’×ṚḌ⁼× ``` A dyadic Link accepting \$a\$ and \$b\$ that yields `1` if \$a\times b = \text{reversed}( (a - 1)\times b )\$, `0` if not. **[Try it online!](https://tio.run/##ASAA3/9qZWxsef//4oCZw5fhuZrhuIzigbzDl////zb/OTAwOQ "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8//9Rw8zD0x/unPVwR8@jxj2Hp/8/vFz/UdOa//@jo810FCxjdRSiTXQUTEG0sY6CkaG5BZgJFDMyMAdLm@sogMXMDAx0FAwNDMBazEBMC7C8hSFQhamBMVgN0EgDA7CwsZEhUKNhbCwA "Jelly – Try It Online"). ### How? ``` ’×ṚḌ⁼× - Link: a, b ’ - a-1 × - (a-1) times b Ṛ - reverse the digits of (a-1)×b Ḍ - convert back to an integer × - a×b ⁼ - equal? ``` [Answer] # [APL (Dyalog Unicode)](https://dyalog.com), 9 bytes Anonymous tacit infix function, taking \$a\$ as left argument and \$b\$ as right argument. ``` ×≡∘⌽⍥⍕×-⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn///D0R50LH3XMeNSz91Hv0ke9Uw9P133Uteh/2qO2CY96@x51NT/qXfOod8uh9caP2iY@6psaHOQMJEM8PIP/mymkKVgqPOqdqxBSVJrKZQLkmoK5bok5xalcxkC@kaG5BUKFMUiJkYE5kiZzoIgFkiYzAwOgiCGQRIiZmIGFLJC0WRiCNJoaGCNrBTnHwABJlbGRIch4Q4QiAA "APL (Dyalog Extended) – Try It Online") (Uses Extended because TIO hasn't updated to 18.0) `×` [Does] the product `≡∘` match the…  `⌽⍥` reversed, when both are…   `⍕` stringified `×` product `-` minus `⊢` the right argument[?] [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 9 bytes ``` ,’$×DU⁼¥/ ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCIs4oCZJMOXRFXigbzCpS8iLCIiLCIiLFsiMzQiLCIyMDc5Il1d) ``` ,’$×DU⁼¥/ Main Link; dyad accepting a, b ,’$ pair: [a, a - 1] × multiply: [ab, (a - 1)b] D to digit list / reduce between the two: U is the reverse of the former ⁼ equal to the latter? ``` [Answer] # [Factor](https://factorcode.org/), ~~47~~ 39 bytes ``` [ over * dup present reverse dec> - = ] ``` [Try it online!](https://tio.run/##TU9NC4JAEL3vr3jnIFk/0rXIa3TpEp2iw6ITRanb7hqE@Ntt@0AdGHgfw8y8s8xtrfvDfrvbLCGNqXODG@mK7iilvUBpMlRZGHo0VOVkvrKnpDakP661L6WvbmLFWMvgqkWKGN0fLxANOPATgXCkPEkRjrZAMmCfc8SuRy5SRJO1PITwx/mU8@nVMPCd7WjH@iPqp/t1hqJRQx5NTjOEgvIMc6xx6s@//FkpFbz@DQ "Factor – Try It Online") Saved 8 bytes thanks to @ovs' [observations](https://codegolf.stackexchange.com/a/242000/97916). ## Explanation Takes input as `b a`. ``` ! 9 6 over ! 9 6 9 * ! 9 54 dup ! 9 54 54 present ! 9 54 "54" reverse ! 9 54 "45" dec> ! 9 54 45 - ! 9 9 = ! t ``` [Answer] # Python 2, 31 bytes ``` lambda a,b:`a*b`==`a*b-b`[::-1] ``` Using the logic that $$ ab = \operatorname{rev}( (a-1)b ) \iff ab = \operatorname{rev}(ab-b) $$ -2 thx to @dingledooper [Try it online!](https://tio.run/##TUxLDoIwEN33FBNWYAop/09Sl57AnZrQBohNCiW0Ljh9pUbBxcyb95k3r@appsQO9G4lG3nHgGHetOzEW0odhLy9NU0YP6wYZ7UY0KtGg1pAgpgcibTpxNQgEFhRGelZCuN7QM/gBci1UfEVf3QyPguwA75J8/IRMMeD2wFWgS2gdgXX5dWjDHJ3X5jUPUohictq99IMElIe2RKqI1sQAvE2u5AVG6@OdBWXkJP07wNqQnb/DQ) ## Other solutions: ### Python 2, 31 bytes ``` lambda a,b:`a*b`[::-1]==`a*b-b` ``` Using the logic that $$ \operatorname{rev}(ab) = (a-1)b \iff \operatorname{rev}(ab) = ab-b $$ -2 thx to @dingledooper [Try it online!](https://tio.run/##TYzLDoIwEEX3/YoJKzCFlPcjqUu/wJ2a0AaITQoltC74@kqNgot5nDt37ryap5oSO9C7lWzkHQOGedOyE29vTRPGD0odhLy1YpzVYkCvGg1qAQlichBp04mpQSCwojLSsxTG94CewQuQS6PiK/5wMj4LsBt8k@blI2COB9cDrAJbQO0CrsurRxnkbr8wqXuUQhKX1X5LM0hIeXhLqA5vQQjEW@1CVmxcHe4qLiEn6d8H1ITs9zc) ### Python 2, 34 bytes ``` lambda a,b:a*b-int(`a*b`[::-1])==b ``` Using the logic that $$ ab - \operatorname{rev}(ab) =b $$ [Try it online!](https://tio.run/##TUxLDsIgEN1ziokrMdjQj/0luPQE7tREiG0koaUBXPT0CEZbFzPzfvOm2T31mPmeXb3ig3hw4ES0fCf2cnTbewD3S9vu0xtmTHg5TNo4sLNFvTagQI6RJNY95NgikEQzldhJSbfdADvCBqNYyORX/NHQzTGJRwRpMh@BCNLHjYnGvoQmFpzNq0MFHCI@cWU7lEOWVvXi5QVktFqzFdRrtqQU0jCLUJSB12u6Tis40PzvAxpKF/8N) ^Credits to @ovs for the equations! [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` :‹"*÷Ṙ= ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI64oC5XCIqw7fhuZg9IiwiIiwiNlxuOSJd) ``` " # Pair the first input with :‹ # Itself decremented * # Multiply both by the second input ÷ # Push both to the stack Ṙ= # Is one reversed equal to the other? ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes ``` NθNη⁼×θη⮌×⊖θη ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oLmZ8B5AcUZeaVaLgWlibmFGuEZOamFmsU6ihkaOooBKWWpRYVp0IFXVKTi1JzU/NKUlOA5oBUAIH1///GJgpGBuaW/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a reversed pair, nothing if not. Explanation: ``` Nθ First input as a number Nη Second input as a number θ First input × Multiplied by η Second input ⁼ Equals θ First input ⊖ Decremented × Multiplied by η Second input ⮌ Reversed Implicitly print ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 40 bytes ``` f(a,b)=d=digits;d(a*b)==Vecrev(d(a--*b)) ``` [Try it online!](https://tio.run/##HYzbCoMwDIZfJXjVjhRSndox3GPsRrzIPFGQUZwM9vRdzFW@/5TEe3RrynkxjC/bTd0U13h87pPhi@juOY/7/DUinRPDZk5p@xkG94C0x/chWJyigJG3zSwIbC1C3zcIt0HgilCft0IofRsUxSup1bhFUK8hQvBEOmlODJoHL42aKu3ISyK1q9LL0A@DzX8 "Pari/GP – Try It Online") [Answer] # JavaScript (ES6), 41 bytes Expects `(a)(b)`. Returns a Boolean value. ``` a=>b=>[...a*b+''].reverse().join``==a*b-b ``` [Try it online!](https://tio.run/##fZBNDoIwEEb3noIdHQ2l5bcsytITuDMmFCwGQqhpletja0yMBpjFbOblfTPTi0mYRnf3RzCqq5xbPgte1rw8Y4zFvj74/gVrOUltJALcq26sKs7tJKjnRo1GDRIP6oZalAEqADxXYeid9FPufoEEUPoFjmIw/0QMKKI5c9CyIraOiOQuZxnIAbHtjIwQQNQ2WCOSzAFsPYRRG5OSeF3hfkFIsXFIRO2m9AO8FfML "JavaScript (Node.js) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 55 bytes ``` c;r;f(a,b){for(r=0,c=~-a*b;c;c/=10)r+=9*r+c%10;r-=a*b;} ``` [Try it online!](https://tio.run/##bVHZboMwEHzPV2yRkDiMYifNgVz3pepXNFEFxqSoLYlspKJG9NNL11xKoiKzeGd2BhjL6CBl20quee4lJPXP@VF7WlAixU@UBCmXXM4Fo74ORRzoULqMch0JSzVtUVbwmRSl58N5BnhZoFKmMq/Jyx4EnNcE7gksceFjQ2BNKSKIbpntEF@wht9o014bE1gRWLDNFivdYIsbZg0Y3VqSom9MqSUuTVR9UrJSWe/CCFhFt@i4H@ogksfSVCDfEh1gVfJd6V7r7Ornxa6On/BeOQQu@6UzqDEx8Ox7izJTNcooH7YPYIpvdcy98Yv8@QAEE8IhDLtpvzPrYxz/JEG3Mc5uaM@v@HTi0395g/ydPVhI/WtGITPldCs9aRzJPcfNCLgZRI@2umZXYgTWi4AhU1BGCLUf3JtZ0/7K/CM5mDb6@gM "C (gcc) – Try It Online") Inputs two integers \$a\$ and \$b\$. Returns a falsy value if these two numbers are a reversed multiple pair or a truthy value otherwise. [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 14 bytes ``` Jpdjp^-..*<-== ``` [Try it online!](https://tio.run/##JYoxCoAwEAT7vGJrQblLYhLBfMDOD1iINmIRlWAhvj0eWCzDzu6cz329jryWZ0hXGdKypalumqqvYyw5be@9j8Whg7JooQw0@yC00OTFekhzRGCJsk4YRAf2aMnIhI5IhNGMwFBM/@MD "Burlesque – Try It Online") Takes input as array of pairs {a b} ``` J # Duplicate pd # Product of array j # Swap p^ # Push elements to stack (b, a) -. # Decrement .* # Product <- # Reverse digits == # Equal ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 33 bytes ``` ->a,b{"#{a*=b}"==(a-b).digits*''} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6laSbk6Ucs2qVbJ1lYjUTdJUy8lMz2zpFhLXb32f4FCWrSZjmUsF4hhrmMBYZgZGOgYGhhAOCZmQLaFZex/AA "Ruby – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~43~~ 33 bytes ``` a?b=a*b==read(reverse$show$a*b-b) ``` [Try it online!](https://tio.run/##XY7NCsIwEITvfYo95KCCsNu/pIfQZ9nQQIu1laTo48dEPKwev4@ZYWaON7@uKfHoLF@ctcHzdAr@6UP0Ks77S2V9ded052UDC9NewSMs2wEKoIcRBsFN5pq0kaotDrWMtaVHaIb/KcSfWFadYJ1ZTveInx0UzlBJddjICzWVJglF@H0AVXoD "Haskell – Try It Online") * I haven't thought `reverse` was available in prelude, no reason to use foldl(flip(:))""String [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 55 bytes ``` \d+ $* 1, , 1(?=.*,(1+)) $1 , ,$` 1+ $.& +`(.),\1 , ^,$ ``` [Try it online!](https://tio.run/##FYu7CgIxFAX78x1Rks0h3Jvs5lGIpT@xSAQtbCwW/z/GamCYOV7f9@cxTvbWx/70MAuUINReL2GhVe8cjE5D06EzCGf4boPj/rd3mjEyG1ZuSIxaKtLKKKWhsCKLUEWw5onaULVwk4S5iDSkqKz6Aw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \d+ $* ``` Convert to unary. ``` 1, , ``` Decrement `a`. ``` 1(?=.*,(1+)) $1 ``` Multiply `a-1` by `b`. ``` , ,$` ``` Add that to `b` giving `(a-1)b,ab`. ``` 1+ $.& ``` Convert to decimal. ``` +`(.),\1 , ^,$ ``` Test whether the results are mirror images of each other. [Answer] # [Red](http://www.red-lang.org), ~~47~~ 45 bytes ``` func[a b][(to""a * b)= reverse to""a - 1 * b] ``` [Try it online!](https://tio.run/##JYxLCsIwAET3PcWjKxWEpGmbRPASbkMW/STopi2xev0YdWAYePAmhTnfwux8FS85vpbJDYzeHfa1rgdOjMcrKbxDegb@7Iz8cp/jmsIw3fkZuB5LS4eikdqgWhqhLRpDLwSytO3LGIuRmk4oiiKERTWyIO8qSrb0WHYi5bTy@QM "Red – Try It Online") [Answer] # BQN, ~~33~~ 22 Bytes ~~This seems too long.~~ A little better. ``` {(𝕨×𝕩)=•BQN⌽•Fmt𝕩×𝕨-1} ``` [Try it!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkHso8J2VqMOX8J2VqSk94oCiQlFO4oy94oCiRm108J2VqcOX8J2VqC0xfQo2IEYgOQ==) *¯11 bytes thanks to @Razetime* [Answer] # APL+WIN, ~~22~~ 20 bytes Prompts for a then b. Minus 2 bytes using rearrangement logic ``` (⍎⌽⍕n-b)=n←(b←⎕)×a←⎕ ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##JYuxDcIwEEX7m8JlUlg628R2CgZAAjGDE2SEZAWkVCwAFCSiiZiGik28iLkTje/pv@dwSfJwDel8lH0K43jqS56X3TbfXgaINnsiBflxj6XK05yfnzwtg@zq9UCm6uihrP6@w58KpVAiWGghwkpAQ8cI0Mp5Jlo0OnZOAC8WUYBC5NoyeZZekW7QcCCgReTRaEV/1A8 "APL (Dyalog Classic) – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 41 bytes ``` L$`.+, *$'*_,$($^$.(*$'*))*_$'* ^(_+),\1$ ``` [Try it online!](https://tio.run/##FcsxDgIhEEbh/j/HGIGdbGaAheEENh7BLGthYWNh9v6I1ZdXvO/rfH@eOi7udow7HevCCHQNncnRTqv7h/ehT7C7vnh@KI1RuCHzhsRRqyFljlIbKhuKCKsIcplYg2nlTRLmItKQorLpDw "Retina – Try It Online") Link includes test cases. Explanation: Based on @ovs' 05AB1E answer. ``` L$`.+, ``` Match `a` as `$&` (Retina ignores the trailing comma when performing arithmetic) and `b` as `$'` and replace the whole input with the result. ``` *$'*_,$($^$.(*$'*))*_$'* ``` Calculate `a*b` and also `rev(a*b)+b` in unary. ``` ^(_+),\1$ ``` See whether they are the same. [Answer] # [GeoGebra](https://geogebra.org), ~~86~~ ~~77~~ 70 bytes ``` a=6 b=9 s=Text(ab-b) o=Sum(Zip(Take(s,c,c),c,Length(s)…1))==Text(ab) ``` [Try It On GeoGebra!](https://www.geogebra.org/calculator/m3g8bgb6) Input is `a` and `b`, output is `o` as `true` if `a` and `b` are a reversed multiple pair, `false` otherwise. The example input shown in the code is `a=6` and `b=9`, but you can change these values to whatever you want. [Answer] # [J](http://jsoftware.com/), ~~20~~ 14 bytes ``` *=|.&.":@(*<:) ``` -6 bytes, thanks @Jonah [Try it online!](https://tio.run/##XY7NCsIwEITveYqhB2uLht30JzEYEARPnnwFsS1efAHx1eNGhQQPu/DNzgx7j5WuZwSPGhsQvMxW43g5n2IbnnqlK39Yt3vfxEZNQc8vpW7X5QFGwIgJuy@SYC84IJ87YcPWFUqyGLJFyIrikHkkEoVl51g/fiRXxByn4EAd/t4hKlyd4VTPRT/TrwvxDQ "J – Try It Online") [Answer] # [PHP](https://php.net/), 79 bytes ``` $a=trim(fgets(STDIN));$b=trim(fgets(STDIN));echo $a*$b==(int)strrev($b*($a-1)); ``` [Try it online!](https://tio.run/##K8go@G9jXwAkVRJtS4oyczXS0lNLijWCQ1w8/TQ1rVWSsImmJmfkK6gkagFlbTUy80o0i0uKilLLNFSStDRUEnUNgUr@/zfjsgQA "PHP – Try It Online") With the help of Github Copilot [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` `(*x¬*= ``` [Try it online.](https://tio.run/##HYqpEYAwEEX9r2IlE/U350bQCxhAwGAQFEUVNBYyyHcc87Wt5760Ng3ufh83tpalIojXYghRPEtFzKK0ip7IjpJQxJDJ7gnTIokBwauYQvnfHw) **Explanation:** ``` ` # Duplicate the top two items, using the implicit inputs # STACK: b,a,b,a ( # Decrease the top item # STACK: b,a,b,a-1 * # Multiply the top two together # STACK: b,a,b*(a-1) x # Reverse the top integer # STACK: b,a,reverse(b*(a-1)) ¬ # Reverse rotate the stack: # STACK: reverse(b*a(-1)),b,a * # Multiply the top two again # STACK: reverse(b*a(-1)),b*a = # Check if the two are equal # STACK: reverse(b*a(-1))==b*a # (after which the entire stack joined together is output implicitly) ``` [Answer] # T-SQL, 31 bytes Using bitwise operators ``` PRINT-1/~(@*@b^reverse(@b*~-@)) ``` **[Try it online](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=9fc7f0105c4dda09629b30cabc563aba)** [Answer] # [Julia 1.0](http://julialang.org/), 56 bytes ``` (a,b,d=digits,s=string)->s(d(a*b))==s(reverse(d(a*b-b))) ``` [Try it online!](https://tio.run/##Tc5JCsMwDAXQfU@hpV0UkDJn4dKrJGSoS2nASofbuy6lQUs9/v/o@rj5nt9xdtH0OODoRr/4TVCcbMHfF5udxIymPw7WOicmTM8pyPSjLKGNZ7msL5hNjdDZw/8qESoL@1kg5Ny0WlIip6ZT1CDoRE2EwESKyvorrS61nGoVFbqYPiHSoSLntM1KmPal@AE "Julia 1.0 – Try It Online") Pretty straightforward answer, with nothing particularly clever to it (unfortunately). [Answer] # [Ly](https://github.com/LyricLy/Ly), 15 bytes ``` nn&s*SrJlf,*=u; ``` [Try it online!](https://tio.run/##y6n8/z8vT61YK7jIKydNR8u21Pr/f2MuI0NzCwA "Ly – Try It Online") ``` nn - read two numbers from STDIN &s - save the entries to the backup cell * - multiple the two numbers passed in S - convert integer to individual digits on stack r - reverse stack J - re-compose digits on stack into a integer l - restore saved numbers f - flip top two entries , - decrement the top of stack * - multiple top two entries = - compare the two entries on the stack u - print "1|0" from comparison ; - exit the program ``` ]
[Question] [ In a now deleted stackoverflow question, someone posted the following: Write a program or function to print alternating patterns in `*` and `#` based on a given integer `n`. Some examples: Input: `n=1` Output: ``` * ``` Input `n=5` Output: ``` *#### ###** ***## ###** *#### ``` Input: `n=8` Output: ``` *####### ######** ***##### ####**** ****#### #####*** **###### #######* ``` Since it looked like a pretty cool code-golfing challenge, here it is. **How are these patterns build?** The first line starts with a single `*`, followed by `n-1` amount of trailing `#`. The second line then contains two `*`, with `n-2` amount of leading `#`. The third line starts with three `*`, followed by `n-3` amount of trailing `#`. etc. Once we've reached the middle (`n/2`), we count back again with the amount of `*`, which can be seen in the examples above. NOTE that for odd input numbers the inversed pair of lines (so first and last; second and next to last; etc.) are exactly the same. In the `n=5` example the first and last lines are `*####`; the second and next to last lines are `###**`. For even input numbers however the inversed pair of lines are reversed. In the `n=8` example the first and last lines are `*#######` and `#######*`; the second and next to last lines are `######**` and `**######`; etc. ## Challenge rules: * You can use any two distinct *printable* characters instead of `*` and `#`. You can use `A` and `B`; `3` and `7`; `<` and `>`; etc. Please state in your answers what you've used. * You can assume `n` will be a positive integer (`>= 1`) * You are allowed to output a list/array of strings for each line or a 2D matrix of characters, instead of printing them to STDOUT. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code. * Also, adding an explanation for your answer is highly recommended. ## Test cases (first `n=1` through `n=10`) ``` * *# #* *## #** *## *### ##** **## ###* *#### ###** ***## ###** *#### *##### ####** ***### ###*** **#### #####* *###### #####** ***#### ###**** ***#### #####** *###### *####### ######** ***##### ####**** ****#### #####*** **###### #######* *######## #######** ***###### #####**** *****#### #####**** ***###### #######** *######## *######### ########** ***####### ######**** *****##### #####***** ****###### #######*** **######## #########* ``` [Answer] # [Python 2](https://docs.python.org/2/), 62 bytes ``` lambda n:["%*s"%(i%2*2*n-n,"x"*min(i+1,n-i))for i in range(n)] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKlpJVatYSVUjU9VIy0grTzdPR6lCSSs3M08jU9tQJ083U1MzLb9IIVMhM0@hKDEvPVUjTzP2f0FRZl6JgnpMnrpeVj5QbZqGoaYmF1RUFwjUuTCVmBJWYqGp@R8A "Python 2 – Try It Online") Uses `x` and space. The rows are computed like this: ``` "%-5s" % "x" == "x " "%5s" % "xx" == " xx" "%-5s" % "xxx" == "xxx " "%5s" % "xx" == " xx" "%-5s" % "x" == "x " ``` Using the `%*s` specifier to choose between `n` and `-n`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` >þµoṚUÐeY ``` [Try it online!](https://tio.run/##y0rNyan8/9/u8L5DW/Mf7pwVenhCauT///8tAA "Jelly – Try It Online") # Explanation ``` >þ Create a table of (x>y) over [1…n]×[1…n]: [0 1 1 1 1] [0 0 1 1 1] [0 0 0 1 1] [0 0 0 0 1] [0 0 0 0 0] µ Take this array, and... oṚ OR it with its reverse: [0 1 1 1 1] [0 0 1 1 1] [0 0 0 1 1] [0 0 1 1 1] [0 1 1 1 1] UÐe Apply U (reverse) to even-indexed rows. Y Join by newlines. ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 18 bytes ``` ⎕a[↑⊢∘⌽\(⊂>⊢⌊⌽)⍳⎕] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra00DcxOhHbRMfdS161DHjUc/eGI1HXU12IG5PF5Cr@ah3M1BN7H@g6v9pXBYA "APL (Dyalog Classic) – Try It Online") outputs `AB` instead of `*#` `⎕` evaluated input n `⍳⎕` the vector `0 1 ... n-1` `⊢⌊⌽` min (`⌊`) between themselves (`⊢`) and their reverse (`⌽`) - see [*trains*](https://codegolf.stackexchange.com/questions/17665/tips-for-golfing-in-apl/43084#43084) `⊂>⊢⌊⌽` where is the `⍳` vector as a whole (`⊂`) less than each of its `⊢⌊⌽` - return a vector of boolean (0/1) vectors `⊢∘⌽\` [reverse every other vector](https://codegolf.stackexchange.com/questions/150117/boustrophedonise/) `↑` mix into a matrix `⎕a` the uppercase English alphabet, `'AB`...`Z'` `⎕a[` `]` replace `0` `1` with `'A'` `'B'` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 57 bytes ``` {map ^$^a: {fmt -$a*(-1)**$_=>\*x($_+1 min$a-$_): "%*s"}} ``` [Try it online!](https://tio.run/##JcuxCoMwFEbh3af4kVs1tyQ0i4PFPIkY7tBAoWlFO1RCnj0VnA7fcJbH@upL3NEEjCgpyoKZZhmQQvxCk3CnrWImP7qJfx35q0V8vkk0eTWgvvBW51zCZ4U1xt6QKsA0wTmzyX4/cAStbs9XVbn8AQ "Perl 6 – Try It Online") Uses the same method as [Lynn's Python answer](https://codegolf.stackexchange.com/a/169216/76162). Outputs using `*` and space. [Answer] # MATL, ~~34~~ ~~31~~ 18 bytes ``` :t!>tPY|!"@X@oQ&P! ``` [Try it on MATL Online](https://matl.io/?code=%3At%21%3EtPY%7C%21%22%40X%40oQ%26P%21&inputs=5&version=20.9.2) Uses 0 for \* and 1 for #. Based on [Lynn's Jelly answer](https://codegolf.stackexchange.com/a/169240/8774). --- Older answer, 31 bytes: ``` 2/tk:wXk:Ph"X@ot~XHh@Gy-hHQ&PY" ``` [Try it on MATL Online](https://matl.io/?code=2%2Ftk%3AwXk%3APh%22X%40ot%7EXHh%40Gy-hHQ%26PY%22&inputs=8&version=20.9.2) Uses 1 for \* and 0 for #. ``` % implicit input, say 5 2/ % divide input number by 2 [2.5] tk % make a copy and floor that [2.5, 2] : % create range 1 to the floored value [2.5, [1, 2]] wXk % bring out the division result and this time ceil it % [[1, 2], 3] : % create range 1 to that [[1, 2], [1, 2, 3]] Ph % flip the last array and concatenate horizontally % [[1, 2, 3, 2, 1]] " % loop through the array X@o % Is the current loop index odd? 1 for odd, 0 for even t~ % duplicate and logical negate that XH % copy that value to clipboard H h % and concatenate the values ([1 0] on odd iterations, [0 1] on even) @ % push current value from array (say 2, then stack is [[0 1], 2) G % push input again y- % subtract current array value from input [[0 1], 2, 3] h % concatenate those two [[0 1], [2, 3]] H % get the stored value from clipboard H (1 for even iterations, 0 for odd) Q % increment that &P % flip the array in that dimension: in even iterations, this flips % across columns and hence inverts the two values. [[0 1], [3, 2]] % in odd iterations, it's a no-op Y" % run-length decoding - repeat the element from first array the number of times % specified in the second array % implicit loop end, implicit output ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` ≔⮌…⁰NθEθ⭆θ›§⟦μλ⟧κ⌊⟦κι ``` [Try it online!](https://tio.run/##NYyxDoIwFEV3v@IFl1fzTFycmJgMA8bgSBgqvtSGtkBpiX9fG6NnOye5d3hJP0zSpFStq1YOW97Yr4ytdIrxRFC7OYZrtA/2KIQgWES5u3ntAjZyxoXgHrKpn1Shdk9@Y3HYFwQXzzLk4b92lsD0BGP@abTTNlrsRgLdiy9lSud03MwH "Charcoal – Try It Online") Uses `0` and `1`. Link is to verbose version of code and includes `§*#` which translates the output to the `*` and `#` in the question. Explanation: ``` N Input number …⁰ Range from 0 ⮌ Reversed ≔ θ Assign to `q` Eθ Map over reversed range ⭆θ Map over reversed range and join §⟦μλ⟧κ Alternate between range and reversed range column ⌊⟦κι Minimum of range and reversed range row › Greater Implicitly print each row on its own line ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) +3 fixing `n=1` edge-case bug :( ``` R«Ṛ$‘r⁸ṬUÐe0YE? ``` A full program accepting an integer which prints the output as defined in the OP using `0` and `1` for `*` and `#` respectively. **[Try it online!](https://tio.run/##ASQA2/9qZWxsef//UsKr4bmaJOKAmHLigbjhuaxVw5BlMFlFP////zU "Jelly – Try It Online")** ### How? ``` R«Ṛ$‘r⁸ṬUÐe0YE? - Main Link: integer, n R - range -> [1,2,3,4,...,n] $ - last two links as a monad: Ṛ - reverse -> [n,...,4,3,2,1] « - minimum (vectorises) -> [1,2,3,4,...,4,3,2,1] ‘ - increment (vectorises) -> [2,3,4,5,...,5,4,3,2] ⁸ - chain's left argument, n r - inclusive range (vectorises) -> [[2,3,...,n],[3,4,...n],[4,5,...n],[5,...n],...,[5,...n],[4,5,...n],[3,4,...n],[2,3,...,n]] Ṭ - untruth (vectorises) -> [[0,1,1,...,1],[0,0,1,1,...,1],[0,0,0,1,...,1],[0,0,0,0,1,...,1],...,[0,0,0,0,1,...,1],[0,0,0,1,...,1],[0,0,1,1,...,1],[0,1,1,...,1]] Ðe - apply to entries with even indices: U - upend -> [[0,1,1,...,1],[1,1,...,1],[0,0,0,1,...,1],[1,...,1,0,0,0,0],...] ? - if... E - ...condition: all equal? (only true when n=1, where we have [1,1]) 0 - ...then: zero Y - ...else: join with newline characters - implicit print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` r1«RR;ṬṖɗ€‘UÐeY ``` [Try it online!](https://tio.run/##ASYA2f9qZWxsef//cjHCq1JSO@G5rOG5lsmX4oKs4oCYVcOQZVn///8xMA "Jelly – Try It Online") Full program. `*` = `1` `#` = `0` [Answer] # Java 10, 145 bytes ``` n->{var r=new char[n][n];for(int j=0,k;j<n;++j)for(k=0;k<n;)r[j][k]=k++<(j<n/2?j%2<1?j+1:n+~j:j%2>0?j:n-j)?j%2<1?'*':'#':j%2>0?'*':'#';return r;} ``` All the ternary makes it a bit messy, but it works fine. I tried flattening the nested loop, and various other things, but they only increased the byte count. Try it online [here](https://tio.run/##bVDLboMwEDw7X7FSVWHXJYUcMSTnHHrKEXFwgaQ2yQYZQ1VF9NepeaRVpUqWVrOzntkdLTvp66Ia6vbtrHLIz7Jp4FUqhNuKKLSlOcq8hP0ISf4uTZqlGdTUUYBMrEi/IsvfxkrrSndVBVycAj1Yo/DkxqU5NWxS2IOCBAb0t7dOGjAJlh8wyWLmnjhezSStk@C5EjpGwblmY7dKAlE5zEyqs7TKkorzmLqJl81OP27icKd5GCH/0pGD22CnI/Q1WzjvyYu8B2@hFiRMaVuDYEQ/EOJuIXd7dEuGwpXY1UAA5zjvT2p3kqVqXVNk4/mEHD4bW17W19auJ/KMdCL6ORujOmnLP@HMGj9h5rP06D33oIDo3v1PfsxszpYW7NerH74B). Ungolfed: ``` n -> { // lambda taking an integer as output and returning a char[][] var r = new char[n][n]; // the output array; we make use of Java 10's var here (replace with char[][] for another 4 bytes to make this work in Java 8) for(int j = 0, k; j < n; ++j) // iterate over the lines for(k = 0; k < n; ) // iterate over the j'th line r[j][k] = // set the current character k++ < // determine if we're in the first or second portion of the line: (j < n/2 ? // for the first half of the output: j%2 < 1 // on even lines ... ? j + 1 // ... print the first symbol j+1 times ... : n + ~j // ... on odd lines, print it n-j-1 times. : j%2 > 0 ? // for the second half of the output, on odd lines ... j : // ... print the first symbol j times ... n - j) // ... on even lines, print it n-j times. ? j%2 < 1 ? '*' : '#' // for the first part of the line, use '*' on even lines, '#' otherwise : j%2 > 0 ? '*' : '#'; // for the second part of the line, use '*' on odd lines, '#' otherwise return r; // return the completed array } ``` # Java ~~8~~ 11, ~~179~~ 127 bytes ``` n->{String r="",a,b;for(int j=0;j<n;b="#".repeat(j<n/2?n+~j:j),r+=(j++%2<1?a+b:b+a)+"\n")a="*".repeat(j<n/2?j+1:n-j);return r;} ``` Try it online [here](https://tio.run/##TVLLTsMwELzzFasghI3TR3qsGzgXCXEoN@jBSQ21STaR7YCqqvx62SQu4pKNPbOz47Gt@lKTptVod5/nslLew5MyeLwCMBi0e1elhnW/BNgEZ/ADWkYIIJe0ebqiT9sVlSnBBxWofDVmBzVpsJH/ugXlPjwfNdZgIIczTu6PUc7lSZKqtJDvjRuUbT6XdoWyyJ1utQosuU5S2pgtHlD82KXlqRM5s0LcLFbZgxLFshCKi@QNE67@mu4uTVZkS5xYLp0OnUNw8nTurcjB0GUqkq1MUllRnUsQAqNlOvjBB11Pmy5MW/IcKmRm2jLkfNQ4XZKYzWBjkBJ7pFghy8B4vA3QILysn@GgQwphbzzUOuybHUSrYxApCXPQdVepoD3xdAx8GmkDzsjvgHlVaygOQU/KpiOEpscLuOT6X5ww1w8AVQ/s8WQxENTfsYn1v@VeudeRt@X98IreAEve5klKKvHaT@df) (TIO does not have Java 11 yet, so this uses a custom method that results in the same byte count as [`String#repeat()`](https://bugs.openjdk.java.net/browse/JDK-8197594)). Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for golfing a whopping 52 bytes! Ungolfed: ``` n -> { // lambda taking an int argument and returning a String String r = "", // the output String a, // temporary String containing the '*'s b; // temporary String containing the '#'s for(int j = 0; j < n; // loop over the lines b = "#".repeat( // repeat the '#' character ... j < n/2 ? n + ~j // ... n-j-1 times in the first half of the output ... : j), // ... j times in the second half r += (j++ % 2 < 1 ? a + b : b + a) + "\n") // assemble the j'th line and append it to the output: on even lines, the '*'s go first; on odd lines, the '#'s go first a = "*".repeat( // repeat the '*' character ... j < n/2 ? j + 1 // ... j+1 times in the first half of the output ... : n - j); // n-j times in the second half return r; // return the completed output } ``` [Answer] # [Lua](https://www.lua.org/about.html "About Lua"), ~~148~~ 133 Bytes ``` function(n)t,a,b={},".","#"for i=1,n do r=i<n/2+1 and i or-~n-i s=a:rep(r)..b:rep(n-r)t[i]=i%2<1 and s:reverse()or s end return t end ``` [Try it online!](https://tio.run/##HY7NCoMwEITP@hRLSiHBnzYem@6TlFJijbBQVlmjl9Jnt4m3nfl2mPmsfh8BYR9XfkeaWLOJ@P05j6pVrkd1Um6cBAhtzTBMIEh31FxZc@nA8wAECXNDlXVLFPQ3CbMW07b9cXEjxsUHPZHOHeL1yKTHBLcgS9Am55MBIQEJcRWGmIXbj@K0ztZgr7m8LLL1qjcgBpo9yaJHTcZkOAtx1JvJ2bI4FChVJrX/AQ "Try it online!") -15 bytes thanks to @KevinCruijssen and @JoKing. ``` function(n) t = {}; a = "."; b = "#" -- initialize variables, output is in table -- strings are needed in variables for -- the str:rep and str:reverse syntax for i = 1, n do -- build the rows of the table r = i<=(n+1)/2 and i or n-i+1 -- logic used to count up then down str = a:rep(r)..b:rep(n-r) -- append correct number of '.'s, fill -- in the rest with '#'s t[i]=i%2==0 and str:reverse() or str -- logic used to control reversing end return t -- return table end ``` [Answer] # [Kotlin](https://kotlinlang.org), 86 bytes ``` {n:Int->for(i in 0..n)println("%${i%2*2*n-n}s".format("x".repeat(Math.min(i+1,n-i))))} ``` [Try it online!](https://tio.run/##fY1BCsIwFETX5hSfYCGpJtgKIkULLl248gRZNPVj@1vSKErp2WNEcNm3GmaGmXvnG6RgHwStQRLG1UMBJ@fM@3D1DqkuJYxs8TQNWDiGkYozeVXazgkEJNhoTbKPRd@Q4MlyxCRP85QUTQPXsdYaL/iLa1f1VZQX42@6jU@4ytakUEamABErMsm@4r@mIvznWbGbC7dz4V6yKXwA "Kotlin – Try It Online") Uses `x` and space as output symbols. Derivates from [Lynn Answer](https://codegolf.stackexchange.com/a/169216/81779) [Answer] ## [Perl 5](https://www.perl.org/) + `-pa -MPOSIX -M5.010`, 58 bytes ``` say+sort{$|--}1x abs,2x("@F"-abs)for(1..ceil$_/=2),-$_..-1 ``` [Try it online!](https://tio.run/##Dcy9CsIwFEDh/T5FiBkqNjG3tf5QCk6Cgyi4uJVYqhRCU5IIFeurG7Od5TtDa3UR2FTJkszIw1hiX33f9U@itCa@dZ40yrUuOPVeOGP9h02cf3Ek6u7SbEzo/kB57Hm0CQrRtJ1m9bLK5ilntRAcQxktpXHvBtXEdUDIIIcVFLCGDWxhBygBETADzOFnBt@Z3gV@KoREGbiKeTlfj7c/ "Perl 5 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 104 99 bytes ``` h,j,k;f(i){char s[h=i++];for(j=0;k=++j>i/2?i-j:j,j<i;memset(memset(s,42,h)+j%2*k,35,h-k),puts(s));} ``` [Try it online!](https://tio.run/##LY7LCsIwEEX3fkVAhKSZ@qgWxDT1Q8RFjW0zSR/SpG7Eb49GXN1z5wzMqLRVKixxUN18r0nh/L3D21qXQYMBKxqK7KV0NRF30RI5v4pmnKiRW2El56bETXbG1JwMmAJFX/eu9vQfDg4ZaMbNKkss7HPQqWXwmL2jjjHxDjh40lc40AjV1Cr4nUqSLz8ZeS0IiQZlLiI2NO6UO/adVH7EWJ@X3ZVFGz8Vi3cIxw8 "C (gcc) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 118 108 bytes This one isn't going to win, but it's a different approach (or at least, I think so!) Instead of doing string manipulations, I make use of the fact that \$10^x-1\$ over \$[1..n] = \{9, 99, 999, ...\}\$, which then can be multiplied to get the appropriate pattern; `printf()` then does the zero-padding for right-justification. Sadly, `int` only has sufficient range to do up to 9 digits (on 32-bit platforms), so you need to go to `long` for larger patterns; a language that natively does MP arithmetic might be able to use this for something. Thanks to ceilingcat for the suggestion. ``` h,j,k;p(h){h=h?10*p(--h):1;}f(i){for(j=0,h=i++;k=++j>i/2?i-j:j,j<i;printf("%0*d\n",h,~-p(k)*p(j%2*(h-k))));} ``` [Try it online!](https://tio.run/##FY7BDoIwEETvfkWjMdmWVsHExFiKH6IesIi7RYEgeiH467Xd09uZyWSseljrV9Ta56e6s/w9Vk@6bbDwKJ1sdA/IJzR4ylLRg1LIj5meayA@1d0AzqQSDSWJbkySuIK2uxMpd3TS5aT7gdqxhuU6FdWlXUqUP9VDw0OTW@8EoGp4OD37kGOvklqIUA4PKy2WAxMi8JezacFYdMjsdcQaYqbIeFDKsaP4fs/ZlUc3jtOL2fvDHw "C (gcc) – Try It Online") --- ### Proof of concept that this works with MP arithmetic: ### [C# (Mono C# compiler)](http://www.mono-project.com/docs/about-mono/languages/csharp/), 187 165 bytes (143 bytes + 22 bytes for the `using System.Numerics;` in the header) ``` q=>{var r="";for(int j=0,h=q+1,k;j<q;r+=((BigInteger.Pow(10,k)-1)*BigInteger.Pow(10,j%2*(q-k))).ToString("D"+q)+"\n")k=++j>h/2?h-j:j;return r;} ``` [Try it online!](https://tio.run/##ZY9fS8MwFMXf@ykuBSFZ/9jVN7NUcCIIU4QJPugeas3atNuNTdKJjH32mnQvgk8nN@eX3HMqk@wVqnEwEmtY/xgr9iz4O6VPw15oWRkWBNWuNAYeS4nL6XQMAL6Gj52swNjSOjko@TkBxFjtPnnbQKlrQz0JcD9gtZBo47NZgORjz4vjodSgeRiyrdLE@dDyLG54H83jjrWLnumIE3Ir6we0ohY6fVbfZJ7FHU3mdPb/vr3IZ6RPOkpp@qLW0zIS3oVRT6PwHUPa8Shqi@Yyv2mS9rplWthBI2h2Gn1OV9WLT4LAIc/Yed4SXyZdCaxtAwVkdPKXCg9CW7fK5bjKJ@gt29DzK9@JOc7hTpKEet6onUhftbRiJVEQSZBO@Ck4jb8 "C# (Mono C# compiler) – Try It Online") [Answer] # Vim, 99 keystrokes It's always interesting to try to do vim with input arguments. It's very unnatural, so it's not going to be amazingly short. There probably are other good approaches to this. Input is assumed to be by itself in a buffer. Registers are assumed to be empty. Editor is assumed to be tall enough to contain the result without scrolling (this could technically be avoided at the cost of some keystrokes). ``` "nD@ni<cr><esc>MmaGddM <c-v>'aI*<esc>qwgvjokoI*<esc>@wq@w<esc> :set ve=all<cr>@nlh<c-v>@nkr# :%s/ /#/g<cr>o<esc> 2Gqqdt#$p2j0@qq@q ``` Explanation ``` | Buffer state (odd and even case): | 5 6 "nD read input into register n @ni<cr><esc> add n newlines MmaGddM<c-v>'a visual block select center row(s) I*<esc> prepend a column of * qw record macro w gvjoko expand selection up and down I*<esc> @w recurse q @w<esc> run macro w and exit visual block select | Buffer state: | * * | ** ** | *** *** | ** *** | * ** | * :set ve=all<cr> move anywhere! @nlh<c-v>@nkr# add last column of #s | Buffer state: | * # * # | ** # ** # | *** # *** # | ** # *** # | * # ** # | * # :%s/ /#/g<cr> replace spaces with # | Buffer state: | *#### *##### | **### **#### | ***## ***### | **### ***### | *#### **#### | *##### o<esc>2G prep and jump to line 2 qqdt#$p2j0@qq@q (effectively) flip every other onward | Buffer state: | *#### *##### | ###** ####** | ***## ***### | ###** ###*** | *#### **#### | #####* ``` And in base64, with actual characters (put input in `input` and keystrokes in `keys` and run using `vim -u NONE -s keys input`) ``` Im5EQG5pDRtNbWFHZGRNFidhSSobcXdndmpva29JKhtAd3FAdxs6c2V0IHZlPWFsbA1AbmxoFkBua3IjOiVzLyAvIy9nDW8bMkdxcWR0IyRwMmowQHFxQHE= ``` [Answer] # [R](https://www.r-project.org/), 75 bytes ``` function(n)outer(1:n,1:n,function(x,y,a=x<y|x>n-y+1)+ifelse(x%%2,a,rev(a))) ``` [Try it online!](https://tio.run/##TYzNasMwEITvfQpBCbtbbyDq0UR9kTQHoUpFYK@EpASbNM/u1P0JOQwM881MWYJZwklci0lQKJ2aL6h74VV3MPHM1kz7@Wt6k@3caepi8EP1OG02r2y5@DNaIlpCKhhVFKV7vaPLk1LONgQxwJHhXYC@o9EEjKvJJUrD8Sc7HNV@qxzCCzA8Ax3GTh//9y6V4mtO8hHlU7XU/z2t0OY8zDiy5mxr8zt2aRhsrt4AEFefDTy0f/11uQE "R – Try It Online") * Inspired by @Lynn answer * function getting `n` as parameter and returning a matrix of `0/1` where `0` corresponds to `'*'` and `1` corresponds to `'#'` [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 22 bytes ``` {"*#"i|:/'i>/:i&|i:!x} ``` [Try it online!](https://tio.run/##hZBLDoIwEIb3nkKLUWw0iG/bxIsQEtxgGo0mxAVG8OrVVgvTKQirZuZ/fMN5dj1dpUzZk1CPiIIFY3EImBgVgg3yUt7Zcxg9XhlL@zlPbmfuJ@lRXHjOHzybxGXvHoV8OiWUxJ/ngvsqptdXH/EomajpUk/BmJqnmmrJ6iupNVAEvZ4JXf8c1gp4aNtGe3TExkRAJQ6xUywo22fAtlUqWqNcFPxn6@CbA3Z1la13y9CJ1r6pDx2K882xe0DgSBwGp8SioF2KrpaKQ6OFc8hmbJWvNoJsrAIAgBGpqKNqbrRVrVz618o3 "K (ngn/k) – Try It Online") `{` `}` function with argument `x` `!x` the list `(0;1;`...`;x-1)` `i:` assign to `i` `i&|i` minima (`&`) of `i` and its reverse (`|`) `i>/:` compare with greater than (`>`) `i` against each element from the list on the right (`/:`) - return a boolean matrix (list of lists) `i|:/'` for each (`'`) j in `i`, reverse (`|:` - we need the `:` to force `|` to be unary) the corresponding element j times (`n f/ x` applies `f` `n` times on `x`). Effectively, reverse every other row. `"*#"` use matrix elements as indices in the string `"*#"` [Answer] # [Python 3](https://docs.python.org/3/), 251 bytes ``` n = int(input()) for i in range(1,n+1): if i%2 != 0: for j in range(1,n-i+2): print("*",end=" ") for j in range(1,i+1): print("#",end=" ") if i%2 == 0: for j in range(1,n-i+2): print("*",end=" ") print() ``` [Try it online!](https://tio.run/##pY3BCoMwEETv@YppSiFbLVRLL0I@pqC228MaQjz061OjQRC8edydefPcL3wGecQosGAJhsWNwRAp1Q8ePP3gX/LuTFVKUVGjAO7Blxoni3s6gdT8bpo3LmpaQsD5NKyvuuyktRqapkDtYJwFK3LeIDOU5faQPG8tGcX4/AM "Python 3 – Try It Online") ]
[Question] [ A positive integer \$x\$ is an \$n\$-perfect number if \$\sigma(x) = nx\$, where [\$\sigma(x)\$](https://en.wikipedia.org/wiki/Divisor_function) is the divisor sum function. For example, \$120\$ is a \$3\$-perfect number because its divisors sum to \$360\$: $$360 = 3\times120 = 1+2+3+4+5+6+8+10+12+15+20+24+30+40+60+120$$ and $$926073336514623897600 = 6\times154345556085770649600 = 1+2+3+4+5+6+7+8+9+10+11+12+\dots+51448518695256883200+77172778042885324800+154345556085770649600$$ so \$154345556085770649600\$ is a \$6\$-perfect number. You are to take an integer \$x\$ as input and output a value \$n\$, such that \$x\$ is an \$n\$-perfect number. If no such \$n\$ exists, you may output any consistent value that isn't a positive integer. You will never receive an input outside the bounds of your language, but your algorithm must work for arbitrarily large \$x\$. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. Mini challenge: Beat 5 bytes in Jelly ## Test cases ``` x -> n 1 -> 1 2 -> 0 3 -> 0 4 -> 0 5 -> 0 6 -> 2 28 -> 2 120 -> 3 496 -> 2 500 -> 0 672 -> 3 30240 -> 4 154345556085770649600 -> 6 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` R×iÆs ``` [Try it online!](https://tio.run/##y0rNyan8/z/o8PTMw23F////NzM3AgA "Jelly – Try It Online") ### Explanation: ``` - Explanation (sample for input 6) R - Range ([1, 2, 3, 4, 5, 6]) × - Multiply by input ([6, 12, 18, 24, 30, 36]) Æs - Divisor sum (12) i - Index of divisor sum in list, else 0 (2) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` ¦¹ΣḊ ``` [Try it online!](https://tio.run/##yygtzv6vkPuoqfH/oWWHdp5b/HBH1////6MNdYx0jHVMdEx1zHSMLHQMjQx0TCzNdEwNDHTMzIFSBkYmBrEA "Husk – Try It Online") The last test case times out. ## Explanation ``` ¦¹ΣḊ Input is a number x. Ḋ List of divisors. Σ Sum. ¦ Division if divisible, 0 if not ¹ by x. ``` `¦` is usually just a divisibility test, but here its return value is useful. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` f+;?/ℕ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSu9qhtw6Ompoe7Oh91rFBKS8wpTtVTAvJqH26d8D9N29pe/1HL1P//ow11jHSMdUx0THXMdIwsdAyNDHRMLM10TA0MdMzMgVIGRiYGsQA "Brachylog – Try It Online") ### How it works ``` f+;?/ℕ f+ the sum of the factors ;?/ℕ divided by the input ℕ is a natural number ``` Alternative version, I think is cooler, but longer: ``` f+~×[?,.]∧ f+ the sum of the factors ~× unifies with the multiplication of [?,.] the input and the output ∧ return the output ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 6 bytes ``` Ý*IÑOk ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8Fwtz8MT/bP//zc2MDIxAAA "05AB1E – Try It Online") Explanation: ``` Ý*IÑOk> Ý 0-Index inclusive range of input (6 -> [1, 2, 3, 4, 5, 6]) * Multiply by input ([6, 12, 18, 24, 30, 36]) IÑO Get input -> divisors -> sum (6 -> [1, 2, 3, 6] -> 12) k 0-Index of divisor-sum in array or -1 if not found. ([6, >12<, 18, 24, 30, 36] -> 1) ``` I just used Sisyphus' method. This could probably be golfed down or even made more efficient, but I lack the 05AB1E knowledge to do so. Just thought I'd give it a shot to pass the time. *-1 Byte thanks to ovs* [Answer] # [C (gcc)](https://gcc.gnu.org/), 47 bytes ``` s,i;f(x){for(i=s=x;--i;)s+=x%i?0:i;s/=s%x*s+x;} ``` [Try it online!](https://tio.run/##LU/basMwDH33VxxaAvbirI6b7ua6@5AtDyW3Cbp01BkYQr49k7c9nCPp6EhCTTE0zboGTa6XUc399SbJBx9dUZBTIfcxo1fzQi7sfMjiXcijW9Ytjc3lu@1wDFNL1/uPkxCDjLpTs8DXjcaph9xkLYoTmHdM7@NGs0GnM8qJRQh24fNMo1SYf4upC1N4q@Exl7rUVhu9Z1SMA@OBFfvEVNrUqJ6TcDAmtR4tK3tjK7YvTkCAP4FEWku80MBxPMJWKcm9hRIABvl3k2r9n@RlrdL8sv4A "C (gcc) – Try It Online") Returns `n` or `0`. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~16 15~~ 13 [bytes](https://github.com/abrudz/SBCS) *Thanks to Bubbler for pointing out I can change the output format to save a couple of bytes* ``` ⍸×∘⍳⍨=1⊥∘∪⊢∨⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HvjsPTH3XMeNS7@VHvClvDR11LQbyOVY@6Fj3qWAEU/p/2qG3Co96@R13Nh9YbP2qb@KhvanCQswKQCvHwDP6fpmDIlaZgBMTGQGwCxKZAbAYSswAShkYGIGFLkICpAYhtZg5WbGBkYsD1qHcuUImpibGJqampmYGFqbm5gRlQsYEBAA "APL (Dyalog Unicode) – Try It Online") Outputs a singleton list of `n` when `n` exists, and an empty array otherwise. Finds the index of (`⍸`) where the sum of (`1⊥`) the divisors (`∪⊢∨⍳`) equals (`=`) a multiple of the input (`×∘⍳⍨`). I use `⍸` and `=` instead of just `⍳` to find the index because it returns an empty list when the element isn't there rather than the length of the list. [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 153 bytes ``` [S S S N _Push_0][S N S _Duplicate_0][T N T T _Read_STDIN_as_integer][T T T _Retrieve_input][S N S _Duplicate_input][S N S _Duplicate_input][N S S N _Create_Label_LOOP][S S S T N _Push_1][T S S T _Subtract][S N S _Duplicate][N T S S N _If_0_Jump_to_Label_REACHED_ZERO][S T S S T S N _Copy_0-based_2nd_input][S T S S T N _Copy_0-based_1st_integer][T S T T _Modulo][N T S T N _If_0_Jump_to_Label_ADD_TO_SUM][N S N N _Jump_to_Label_LOOP][N S S T N _Create_Label_ADD_TO_SUM][S N T _Swap_top_two][S T S S T N _Copy_0-based_1st_integer][T S S S _Add_top_two][S N T _Swap_top_two][N S N N _Jump_to_Label_LOOP][N S S S N _Create_Label_REACHED_ZERO][S N N _Discard_top][S N S _Duplicate_top][S T S S T S N _Copy_0-based_2nd_input][T S T T _Modulo][N T S S S N _If_0_Jump_to_Label_DIVISIBLE][S S S N _Push_0][N S N S T _Jump_to_Label_OUTPUT][N S S S S N _Create_Label_DIVISIBLE][S N T _Swap_top_two][T S T S _Integer_divide_top_two][N S S S T N _Create_Label_OUTPUT][T N S T _Output_as_integer] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online](https://tio.run/##LU1BDoAwCDuXV/CERf2QMUv0ZqKJz8cW2AahLe2@83rnc@/HjHB344VBh1NCPXFswhDRACUgm1FkcdBSS4pEC3JnYLnbV/lWH5vXGpD5mUE@Yh3LNn4) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** ``` Integer input = STDIN as input Integer sum = input Integer i = input Start LOOP: i = i - 1 If(i == 0): Jump to Label REACHED_ZERO If(input % i == 0): sum = sum + i Go to next iteration of LOOP Label REACHED_ZERO: Integer output If(sum % input == 0): output = sum integer-divided by input Else: output = 0 Print output as integer to STDOUT ``` **Example run: [`input = 6`](https://tio.run/##LU1BDoAwDDrDK/oK/2PMEr2ZaOLzK7Td1qZAYd95veu592NlRgR1QfhoKuhnTs0YJgagBVSjRJUGL43kSIxgdwW2e3ydz/6Y0WtA5VeG@MztBw)** ``` Command Explanation Stack Heap STDIN STDOUT STDERR SSSN Push 0 [0] SNS Duplicate top (0) [0,0] TNTT Read STDIN as integer [0] {0:6} 6 TTT Retrieve at address (0) [6] {0:6} SNS Duplicate top (6) [6,6] {0:6} SNS Duplicate top (6) [6,6,6] {0:6} NSSN Create Label LOOP [6,6,6] {0:6} SSSTN Push 1 [6,6,6,1] {0:6} TSST Subtract top two (6-1) [6,6,5] {0:6} SNS Duplicate top (5) [6,6,5,5] {0:6} NTSSN If 0: Jump to Label REACHED_ZERO [6,6,5] {0:6} STSSTSN Copy 0-based 2nd (6) [6,6,5,6] {0:6} STSSTN Copy 0-based 1st (5) [6,6,5,6,5] {0:6} TSTT Modulo top two (6%5) [6,6,5,1] {0:6} NTSTN If 0: Jump to Label ADD_TO_SUM [6,6,5] {0:6} NSNN Jump to Label LOOP [6,6,5] {0:6} SSSTN Push 1 [6,6,5,1] {0:6} TSST Subtract top two (5-1) [6,6,4] {0:6} SNS Duplicate top (4) [6,6,4,4] {0:6} NTSSN If 0: Jump to Label REACHED_ZERO [6,6,4] {0:6} STSSTSN Copy 0-based 2nd (6) [6,6,4,6] {0:6} STSSTN Copy 0-based 1st (4) [6,6,4,6,4] {0:6} TSTT Modulo top two (6%4) [6,6,4,2] {0:6} NTSTN If 0: Jump to Label ADD_TO_SUM [6,6,4] {0:6} NSNN Jump to Label LOOP [6,6,4] {0:6} SSSTN Push 1 [6,6,4,1] {0:6} TSST Subtract top two (4-1) [6,6,3] {0:6} SNS Duplicate top (3) [6,6,3,3] {0:6} NTSSN If 0: Jump to Label REACHED_ZERO [6,6,3] {0:6} STSSTSN Copy 0-based 2nd (6) [6,6,3,6] {0:6} STSSTN Copy 0-based 1st (3) [6,6,3,6,3] {0:6} TSTT Modulo top two (6%3) [6,6,3,0] {0:6} NTSTN If 0: Jump to Label ADD_TO_SUM [6,6,3] {0:6} NSSTN Create Label ADD_TO_SUM [6,6,3] {0:6} SNT Swap top two [6,3,6] {0:6} STSSTN Copy 0-based 1st (3) [6,3,6,3] {0:6} TSSS Add top two (6+3) [6,3,9] {0:6} SNT Swap top two [6,9,3] {0:6} NSNN Jump to Label LOOP [6,9,3] {0:6} SSSTN Push 1 [6,9,3,1] {0:6} TSST Subtract top two (3-1) [6,9,2] {0:6} SNS Duplicate top (2) [6,9,2,2] {0:6} NTSSN If 0: Jump to Label REACHED_ZERO [6,9,2] {0:6} STSSTSN Copy 0-based 2nd (6) [6,9,2,6] {0:6} STSSTN Copy 0-based 1st (5) [6,9,2,6,2] {0:6} TSTT Modulo top two (6%5) [6,9,2,0] {0:6} NTSTN If 0: Jump to Label ADD_TO_SUM [6,9,2] {0:6} SNT Swap top two [6,2,9] {0:6} STSSTN Copy 0-based 1st (2) [6,2,9,2] {0:6} TSSS Add top two (9+2) [6,2,11] {0:6} SNT Swap top two [6,11,2] {0:6} NSNN Jump to Label LOOP [6,11,2] {0:6} SSSTN Push 1 [6,11,2,1] {0:6} TSST Subtract top two (2-1) [6,11,1] {0:6} SNS Duplicate top (1) [6,11,1,1] {0:6} NTSSN If 0: Jump to Label REACHED_ZERO [6,11,1] {0:6} STSSTSN Copy 0-based 2nd (6) [6,11,1,6] {0:6} STSSTN Copy 0-based 1st (1) [6,11,1,6,1] {0:6} TSTT Modulo top two (6%1) [6,11,1,0] {0:6} NTSTN If 0: Jump to Label ADD_TO_SUM [6,11,1] {0:6} SNT Swap top two [6,1,11] {0:6} STSSTN Copy 0-based 1st (1) [6,1,11,1] {0:6} TSSS Add top two (11+1) [6,1,12] {0:6} SNT Swap top two [6,12,1] {0:6} NSNN Jump to Label LOOP [6,12,1] {0:6} SSSTN Push 1 [6,12,1,1] {0:6} TSST Subtract top two (1-1) [6,12,0] {0:6} SNS Duplicate top (1) [6,12,0,0] {0:6} NTSSN If 0: Jump to Label REACHED_ZERO [6,12,0] {0:6} NSSSN Create Label REACHED_ZERO [6,12,0] {0:6} SNN Discard top (0) [6,12] {0:6} SNS Duplicate top (12) [6,12,12] {0:6} STSSTSN Copy 0-based 2nd (6) [6,12,12,6] {0:6} TSTT Modulo top two (12%6) [6,12,0] {0:6} NTSSSN If 0: Jump to Label DIVISIBLE [6,12] {0:6} NSSSSN Create Label DIVISIBLE [6,12] {0:6} SNT Swap top two [12,6] {0:6} TSTS Integer-divide top two (12/6) [2] {0:6} NSSSTN Create Label OUTPUT [2] {0:6} TNST Output top as integer (2) [] {0:6} 2 error ``` Stops with an error after printing the result, because no exit is defined. [Answer] # [R](https://www.r-project.org/), ~~42~~ ~~41~~ 39 bytes *Edit: -1 byte (and, inspired by this, -2 more bytes) thanks to Robin Ryder* ``` function(x)(d=sum(1:x*!x%%1:x))/x*!d%%x ``` [Try it online!](https://tio.run/##PY3NCoMwEAafxUNgt3zgJo3RCj6LSFQotGnwB9Knjzl5moE5zJbjsq2LP8Yw5PUM/nj/AiWmedjPL@k@PaqkVCFzXXxWKuV9ivHzJ08aBk9YNHAwHbQR2JdDIwLXliTGCuM@cL4A "R – Try It Online") Commented: ``` perfect_n= function(x) (d= # d is the divisor sum, calculated as... sum( # sum of... 1:x* # the values of 1..x that have... ! # zero values for... x%%1:x) # x MOD 1..x ) )/x # output d/x... *!d%%x # but only if it's an integer # (so d MOD x == 0) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 15 bytes ``` &!%Jsf!%QTSQQ/J ``` [Try it online!](https://tio.run/##K6gsyfj/X01R1as4TVE1MCQ4MFDf6/9/o3/5BSWZ@XnF/3VTAA "Pyth – Try It Online") ## Explanation ``` &!%Jsf!%QTSQQ/J J # set J to s # sum of f SQ # filtering the range [1, input] with !%QT # lambda T: not (input % T) (divisibility test) # implicit print the & # short-circuiting and of !%J Q # not (J % input) /J # and J / input ``` [Answer] # JavaScript (ES6), 41 bytes Returns **0** if there's no solution. ``` x=>(g=k=>x=k&&k*!(x%k)/x+g(k-1))(x)%1?0:x ``` [Try it online!](https://tio.run/##dc9LDoIwFIXhuauoA8itBvsCfCTFtRCEBkuoEWPu7qtJHVU6/pL/5Nzbd7t0z/HxKmZ36/2gPeoGjLa6QW3z3O62gJmlDPcGbCEoBaSZuPIL@s7Ni5v6w@QMDEDIFwljRGxikAH4H6gUlCmoUlAHkDHI0zoIyQOoCMpzIlVxvj5eH38Hlf8A "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Æs0:%? ``` A monadic Link accepting a positive integer which yields a non-negative integer. **[Try it online!](https://tio.run/##y0rNyan8//9wW7GBlar9////DU1NjE1MTU3NDCxMzc0NzEwszQwMAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8//9wW7GBlar9/6N7Drc/alqTBcSPGuYo6NopPGqYG/n/f7ShjoKRjoKxjoKJjoKpjoIZkGuho2BoZAAUsQTyTA2ALDNzkBoDIxMg29DUxNjE1NTUzMDC1NzcwAyoysAgFgA "Jelly – Try It Online"). ### How? ``` Æs0:%? - Link: x Æs - divisor sum ? - if... % - ...condition: has a remainder when divided 0 - ...then: zero : - ...else: integeger divide ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~19~~ 18 bytes ``` ⊢(÷⍨×0=|)1⊥∘⍸0=⍳|⊢ ``` [Try it online!](https://tio.run/##VdDNCkFREAfwvae4SxZqzue9FmyU2AkvoMRGWFJ2Srp1xEJsbJSyUBYUa95kXuSauT7vWZz6NXOm@Z/moJttjZrdfidCt/X4DL1sweulPhRM8aVkwpcqSZ2kSdIy5Ycy@KeQwFRv6lyi2QD8j7K@/DUrkDqu6pjCaKWNMRYC4/tgadLrsU3hfFWq4XQhZOAzqlWC0hGGu/Tjiu7wWEN@nBEY7nG2QXeDPLrzmMpRmzrRzTGcoDuiu9xPCqdLmlGvFelulCv1qH0/pAV9kKJvMBSWAnIqjsL789LxrhnvCQ "APL (Dyalog Unicode) – Try It Online") Conversion to train by Jo King.(-3 bytes) -1 more byte from Jo King after changing the check condition. # Older answer, 22 bytes ``` {(⊢×⌊=⊢)⍵÷⍨+/⍸0=⍵|⍨⍳⍵} ``` ## Explanation ``` {(⊢×⌊=⊢)⍵÷⍨+/⍸0=⍵|⍨⍳⍵} ⍵ → input ⍳⍵ range 1-⍵ ⍵|⍨ mod ⍵ 0= check which ones are divisors ⍸ get the indices (factors) +/ sum the factors ⍵÷⍨ divide by ⍵ (⊢×⌊=⊢) Inner tacit fn: ⌊=⊢ Floor equals right? (integer test, returns 0 or 1) ⊢× times right ``` [Answer] # [Haskell](https://www.haskell.org/), ~~51~~ 46 bytes ``` a!b=0^mod a b*div a b f n=sum(map(n!)[1..n])!n ``` [Try it online!](https://tio.run/##FclBDsIgEEDRvacYdmAmZECKuuAInqCpZpraSFrGxqrXx7r6yfsPXqf7PNfKqk90Lc8BGPr9kL//7kaQtH6KLrxoUaZ11kpnlNTCWSDB5pcb6OWV5Q0WRgOtQ48HDNhgRH9C5wnDOWJDhPG4LfKBuvoD "Haskell – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes ``` Tr@Divisors@#/#/._Rational->0& ``` [Try it online!](https://tio.run/##DcpBCsIwEAXQqwgFV18zSTOTulCy8AAi7iWI1IBtIQ1uxLOPWb83pfp6TqnmR9LxqLcSz/mT16WssTOd2d@vzZY5vXcn2uql5LluTBxN/Fo49PBgCNwA6wj@IGAiSGhEzhMs@94zs9DAIZC0QfRT/QM "Wolfram Language (Mathematica) – Try It Online") -6 bytes from @att [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~23~~ 20 bytes ``` NθI⌕E⊕θ×θιΣΦ⊕θ∧ι¬﹪θι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMMtMy9FwzexQMMzL7koNTc1ryQ1BahGRyEkMze1WKNQRyFTE8gLLs0FKs0pARqArtARaECmjoJffomGb35KaU4@VBMEWP//b2TxX7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Port of @Sisyphus's algorithm but using @ovs's comment to deal with 0-indexing. Outputs `-1` for nonexistence. Explanation: ``` Nθ Input `x` as a number θ `x` ⊕ Incremented Φ Filter over implicit range ι Current index ∧ Logical AND θ `x` ﹪ Modulo ι Current index ¬ Logical NOT Σ Take the sum θ `x` ⊕ Incremented E Map over implicit range θ `x` × Multiplied by ι Current index ⌕ Find the index I Cast to string Implicitly print ``` Unfortunately for Charcoal the sum of `[]` is not zero, which means that I can't save a byte by removing the two increments of `x` and incrementing the result instead. Previous 23-byte solution: ``` Nθ≔ΣΦ⊕θ∧ι¬﹪θιη¿¬﹪ηθI÷ηθ ``` [Try it online!](https://tio.run/##TYwxCgIxEEV7TzHlLMTGSthqUYQtXARPEJNoBrITk0z2@jEWgr/87/GM19lEHVqb@V1lqevDZUzDuJtKoRfjva54oSD9ndlktzoWZ7uhYGKLpGCJgtdoa4iYFNDwnQLfE/QE/KNeQeoMbplY8KSL9KScaSPrfnBs7XBs@y18AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `x`. ``` ≔ΣΦ⊕θ∧ι¬﹪θιη ``` Create a list from `1..x`, filter out numbers that don't divide `x`, and take the sum. ``` ¿¬﹪ηθI÷ηθ ``` If `x` divides the sum then print the quotient. [Answer] # Scala, ~~54~~ 53 bytes ``` x=>{val s=1 to x filter(x%_<1)sum;s/x*(1-(s%x).sign)} ``` [Try it in Scastie](https://scastie.scala-lang.org/3ACs1NnWSY6bdgzZMlqMFA) Sums every divisor of `x` from 1 to x, inclusive. If that sum is divisible by x, it returns that divided by x, otherwise it returns 0. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 51 bytes ``` .+ * |""Lw`^(.+)(?=\1*$) ^ $-1; L$`^(.+);(\1)+$ $#2 ``` [Try it online!](https://tio.run/##JcixDkAwFAXQ/X4GT9JqNH0PRRoxWnyCCIPBYhCJxb/X4Izn2u/j3DhmalyjNcjxJsn0rIuyRquhnzknjQVUcMBE/wc1szYESiVGhqBEhRoe0oLFoeo8aufgG/kA "Retina – Try It Online") Link includes less slower test cases. Explanation: ``` .+ * ``` Convert the input to unary. ``` |""Lw`^(.+)(?=\1*$) ``` List all of the factors without delimiting them, thus summing them. ``` ^ $-1; ``` Retrieve the original unary value. ``` L$`^(.+);(\1)+$ $#2 ``` Count how many times it divides the sum. (Or output nothing if it does not.) [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~36~~ 34 bytes ``` @(x)~mod(s=~mod(x,r=1:x)*r',x)*s/x ``` Anonymous function that takes a floating-point or integer number as input. The last test case fails due to memory limitations. [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzLjc/RaPYFkxV6BTZGlpVaGoVqesAyWL9iv9pGsYGRiYGmv8B) Or [verify test cases](https://tio.run/##HYm9DsIgAAb3PsW3NIBBBGzxJ8H4HsbBSEkYShtoDJOvjsQb7oZb3tvrM1VvhRD1Tgv7zouj2f5TeLLqWtguEd6cD6X6JSHC4qGgccSAEQb6DKUlhovBKCXMqS2pB/ns0HAhrzSvKcTNU9IH7G/oA@GIHJ5Gxlg3RVd/). ### Explanation ``` @(x)~mod(s=~mod(x,r=1:x)*r',x)*s/x @(x) % anonymous function with input x 1:x % row vector [1 2 ... x] r= % call that r mod(x, ) % x modulo [1 2 ... x]. Gives a row vector ~ % negate each element. Gives 1 for divisors r' % column vector [1; 2; ... ; x] * % matrix-multiply. Gives the sum of divisors s= % call that s mod( ,x) % sum of divisors modulo x ~ % negate. Gives 1 if x divides sum of divisors s/x % sum of divisors divided by x * % multiply ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 62 bytes ``` lambda x:(a:=sum(x/i*(x%i<1)for i in range(1,x+1)))%x<1and a/x ``` [Try it online!](https://tio.run/##RY7LboMwEEX3fMVsosy0hNiGPIpCvqQbV0BqCYxlO5L5eoodpczq6N5zpTGz/510eTV26aGB72WQ408rIdQo68Y9RwxH9YFhp26c@smCAqXBSv3okOfhkxPRLty41C3IY1jUaCbrwc0uy6I@KN3FxRoUzrdKF7aTLVLhzKB8bB1SncF6IYd5fWGUBpX2eZq@NNwf7nuiZBm7lthjIGgamGmJIYfDHXjqRUSWsNyw2vC04TmiiCiub@SCRSxXrL7@hRNj79n5Il5CyUSV0uoP "Python 3.8 (pre-release) – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ─Σk‼÷/* ``` [Try it online.](https://tio.run/##y00syUjPz0n7///RlIZzi7MfNew5vF1f6/9/Qy4jLmMuEy5TLjMuIwsuQyMDLhNLMy5TAwMuM3OglIGRiQEA) **Explanation:** ``` ─ # Get the divisors of the (implicit) input-integer Σ # Sum those divisors k # Push the input-integer again ‼ # Apply the following two commands separately to the stack: ÷ # Check if the divisor-sum is divisible by the input (1 if truthy; 0 if falsey) / # Integer-divide the divisor-sum by the input * # Multiply the two together # (after which the entire stack joined together is output implicitly as result) ``` [Answer] # [Rockstar](https://codewithrockstar.com/), ~~141~~ ~~135~~ 131 bytes Outputs nothing if no `n` exists. ``` listen to N X's0 T's0 while N-X let X be+1 let D be N/X turn up D let T be+D is N/X and X let D be T/N turn up D if D is T/N say D ``` [Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 71 bytes ``` param($x)(1..$x|?{!($x%$_)})|%{$s+=$_};((1..$x)|%{$_*$x}).indexof($s)+1 ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQ6VCU8NQT0@losa@WhHIU1WJ16zVrFGtVinWtlWJr7XWgEiDheK1VCpqNfUy81JSK/LTNFSKNbUN////b2xgZGIAAA "PowerShell – Try It Online") * Get the parameter `x` * Brute force and calculate divisors * Sum up the divisors to variable `s` * Multiply range of `1..x` with `x` * Return index of `s` in the multiplied range and add 1 to it [Answer] # [Icon](https://github.com/gtownsend/icon), 67 bytes ``` procedure f(n) s:=0 n%(i:=1to n)=0&s+:=i&\z return(0=s%n&s/n)|0 end ``` [Try it online!](https://tio.run/##TY7BCsIwEETv@Yq10JLgitvaVg3EH1EP0kbIwY0kraL47zX25G3eMMyM6zxP0z34zvZjsHCVrETUhgTn0mlTDh5YGSriUhtXnN4i2GEMLMnEnIu4ZvUhYbn/67hdHEslAMA@bHgBa7M4lggVwgahRmgQ2oQ7hLKi5OwTNZRUu/1lqKrpDL0H@QxusJIxg9UBMpzfKTXPfQE "Icon – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-æ`](https://codegolf.meta.stackexchange.com/a/14339/), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs `undefined` if no `n` is found. ``` *N¶Îâ x ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LeY&code=Kk62zuIgeA&input=MTIw) [Answer] # [Factor](https://factorcode.org/), 84 bytes ``` : f ( n -- n ) dup [1,b] [ dupd mod 0 = ] filter sum swap /mod 0 > [ drop 0 ] when ; ``` [Try it online!](https://tio.run/##JYwxT8MwGER3fsUbQSKtE9K0pKJr1aULYqoypMlnWlE7xnZUIcRvDy4spye9u9NtFwc/vb3u9tuaD/FWLpg2nv5i5lv7LoEgn6PYLpHzEuOX82cbWd/t9jU2c@K1dDGzozmKD1ON5h5LlqV4oB8dh/zx2HC4cY8ZehQvNOjzJYonjIZwbR3zf7W5Nf3gEjZcT2JZT9/kFDxRsqCiWJEXivK5YqEU1TIpVZSKnzTVaWXS22z6BQ "Factor – Try It Online") [Answer] # Prolog, 117 bytes ``` s(X,D,S):-D<1,!,S is 0;E is D-1,(0 is X mod D,!,s(X,E,T),S is T+D;s(X,E,S)). f(X,N):-s(X,X,S),0 is S mod X,N is S//X. ``` [Try it online!](https://swish.swi-prolog.org/p/foobar2.swinb) (Please don't modify it directly, it would change my version too) --- If anyone could figure out why this shorter version (96 bytes) isn't working, I'd be really grateful. ``` s(X,D,S):-D<1,!,S is 0;E is D-1,(0 is X mod D,!,s(X,E,T),S is T+D;s(X,E,S)). f(X,N):-s(X,X,N*X). ``` [Version with print debugging](https://swish.swi-prolog.org/p/foobar3.swinb) [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 22 bytes ``` ~:x),{.x\%!*+}*.x%!*x/ ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v86qQlOnWq8iRlVRS7tWS68CSFfo//9vbGBkYgAA "GolfScript – Try It Online") ``` ~:x # Store the input in x ), # Make an array from 0 to x { }* # For each number in the array, execute this block . # Copy current number x\%! # The copy becomes 1 if it is a divisor of x and 0 if it isn't *+ # Multiply and add . # Copy the sum of the divisors x%! # The copy becomes 1 if it is a divisor of x and 0 if it isn't * # Multiply x/ # Divide by x ``` ]
[Question] [ Provided that the input is a **monotone** sequence of three or more integers: * Output -2 if the sequence strictly decreases. Example: `[7,4,3,2]` * Output -1 if the sequence monotone decreases but is neither strict nor constant. Example: `[6,5,5]` * Output 0 if the sequence is constant. Example: `[0,0,0]` * Output +1 if the sequence monotone increases but is neither strict nor constant. Example: `[-1,2,2,2,4]` * Output +2 if the sequence strictly increases. Example: `[0,1,2]` I/O format is flexible. Standard loopholes apply. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8 7~~ 6 bytes ``` ¥.±Z+W ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m73MwDQxyTB1weqySnslBV07BSX7yqWlJWm6FisOLdU7tDFKO3xJcVJy8UIdiOiCm5rR0YY6RjrGsTpg2ghIGyHRhkDaGEzHQnQAAA) ``` ¥ deltas .± sign Z maximum without popping + add (vectorized) W minimum ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` IṠQ.ịS ``` [Try it online!](https://tio.run/##y0rNyan8/9/z4c4FgXoPd3cH/3@4c5/1o4Y5Crp2Co8a5lofbuc63P6oaU3k///R0YY6RjrGsTpg2ghIGyHRhkDaGEzHAgA "Jelly – Try It Online") Port of Command Master's [05AB1E answer](https://codegolf.stackexchange.com/a/266708/97916). A monadic link taking a list of integers and returning an integer. ## Explanation ``` I | Increments Ṡ | Signs Q | Uniquify .ị | Last and first S | Sum ``` [Answer] # [Uiua](https://uiua.org), 11 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` ⊢+⇌.⊝±≡/-◫2 ``` [Try it!](https://uiua.org/pad?src=0_2_0__ZiDihpAg4oqiK-KHjC7iip3CseKJoS8t4perMgoKZiBbMSAyIDNdCmYgWzEgMiAyXQpmIFsyIDIgMl0KZiBbMiAyIDFdCmYgWzMgMiAxXQo=) Port of Command Master's [05AB1E answer](https://codegolf.stackexchange.com/a/266708/97916). ``` ⊢+⇌.⊝±≡/-◫2 ≡/-◫2 # deltas ± # sign ⊝ # deduplicate . # duplicate ⇌ # reverse + # add ⊢ # first ``` [Answer] # JavaScript (ES6), 47 bytes ``` a=>(a.reduce((p,v)=>(a|=p<v?5:p>v?-2:3,v)),a%3) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1k4jUa8oNaU0OVVDo0CnTBMkUGNbYFNmb2pVYFdmr2tkZQwU1tRJVDXW/J@cn1ecn5Oql5OfrpGmEW2uo2Cio2Cso2AUq6nJhSZppqNgCkRYZAx0FEAIi4yuIdAsGDLBrtUQYt1/AA "JavaScript (Node.js) – Try It Online") ### Method Because the input array `a` contains at least 3 elements, it is guaranteed to be evaluated to \$0\$ when coerced to an integer. So we can safely re-use it as a signed 32-bit mask. For each pair of consecutive elements \$(p,\:v)\$ in the input array, we apply to `a` a bitwise OR with: * \$5\$ if \$p<v\$ * \$-2\$ if \$p>v\$ * \$3\$ if \$p=v\$ These values were chosen such that the expected output in \$[-2\dots2]\$ is obtained by reducing the final bitmask modulo \$3\$. ### List of cases Because the sequence is monotone, there are only 5 possible cases: | \$p<v\$ | \$p>v\$ | \$p=v\$ | operations | final bitmask | modulo 3 | | --- | --- | --- | --- | --- | --- | | no | no | yes | 0 | 3 | 3 | **0** | | no | yes | no | 0 | -2 | -2 | **-2** | | no | yes | yes | 0 | -2 | 3 | -1 | **-1** | | yes | no | no | 0 | 5 | 5 | **2** | | yes | no | yes | 0 | 5 | 3 | 7 | **1** | [Answer] # [Scala 3](https://www.scala-lang.org/), ~~71~~ 63 bytes Saved 8 bytes thanks to the comment of @corvus\_192 --- ``` x=>x zip x.tail map{case(a,b)=>b compare a}pipe(x=>x.min+x.max) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fY7BSgMxFEX38xWXrhJMArYUVJgRl4KuXJYib2JGI5lMmEk1WPolbrrRjUu_pn9j2gqCaOFxH9x3uPe9vg-aHE0-ZiPpu2fq_Wi-ubFt6PqI3UktonVKP5D11t-r26KrH42OuM4GTIrG3w24CAHLosATOTRnYFd2iLNLH-dllZWjxNsiNvJkc57KKuHFBiQVyTq0FJaaBsNI1LysauiuDdQb0CrYYNiWV631R1kp8e-YTyD01kfnWbMrY8cCY4GJwFTglHNeHCSm_xE_c4CQOUTmFPl3kdwi49_Yav_6er3fXw) [Answer] # [Python](https://www.python.org), 55 bytes ``` lambda S,*s:min(x:={(S<t)-(S>(S:=t))for t in s})+max(x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3zXMSc5NSEhWCdbSKrXIz8zQqrGyrNYJtSjR1NYLtNIKtbEs0NdPyixRKFDLzFIprNbVzEys0KjSh2rMLijLzSjTSNAx1jHSMdUx1LDU1udDFTFHEoBBNTNdYR9dURxdZuy5Q1AhJAmLlggUQGgA) # [Python 2](https://docs.python.org/2/), 53 bytes ``` def f(s):t=map(cmp,s[1:],s[:-1]);return min(t)+max(t) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWN01TUtMU0jSKNa1KbHMTCzSScwt0iqMNrWKBpJWuYaymdVFqSWlRnkJuZp5GiaZ2bmIFkIJqLi0oyswr0UjTiDbUMdIx1jHVsYzV1OTCEDVFE4VCDFFdYx1dUx1dVEN0geJGyFIQy2E-AAA) [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 5 bytes ``` ∆±uĵ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FqsedbQd2lh6uOXQ1iXFScnFUOEFN_WizXVMdIx1jGK5os10THVMgbSBDhACaV1DHSMwNAELAnmxEG0A) ``` ∆±uĵ ∆ Delta ± Sign u Uniquify Ä Multiply by 2 µ Mean ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 14 bytes ``` +/2#?0 1'1_-': ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs9LWN1K2N1AwVDeM11W34uJKU9cwVDBSMLYGkUbWRnDS0NoYRGpyAQAGowlp) A slight variation on [Nick Kennedy's Jelly answer](https://codegolf.stackexchange.com/a/266711/78410). `0 1'` is from coltim's comment on another K answer. ``` +/2#?0 1'1_-': 1_-': differences 0 1' binary search into 0 1; negative -> -1, 0 -> 0, positive -> 1 ? keep unique elements 2# cycle the elements to length 2 +/ sum ``` [Answer] # [Python 2](https://docs.python.org/2/), 43 bytes ``` lambda s:cmp(s[::-1],s)<<len(set(s))/len(s) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMHiNNuYpaUlaboWN7VzEnOTUhIViq2Scws0iqOtrHQNY3WKNW1sclLzNIpTSzSKNTX1wWxNqJaagqLMvBKNNI1oQx0jHWMdEx3TWE1NLjRRbOJQiCKqa6ija6SjawxGJjq6pjhkoVIQNyxYAKEB) Logs: * My original answer (49 bytes): ``` lambda s:cmp(s[-1],s[0])*(2-(len(set(s))<len(s))) ``` * Neil's suggestion: `*(2-(len(set(s))<len(s)))` -> `-~(len(set(s))==len(s))` * xnor's suggestion: `*(2-(len(set(s))<len(s)))` -> `<<(len(set(s))==len(s))` ; `cmp(s[-1],s[0])` -> `cmp(s[::-1],s)` * Albert.Lang's suggestion: `*(2-(len(set(s))<len(s)))` -> `<<len(set(s))/len(s)` Thank for amazing suggestions! [Answer] # [R](https://www.r-project.org), ~~32~~ 29 bytes ``` \(x)sum(range(sign(diff(x)))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhZ7YzQqNItLczWKEvPSUzWKM9PzNFIy09KAokAAUXPTME3D0MpYkytNI1nDUMdQx0gTwjbSMUJiA2XAbGMrQ6jGBQsgNAA) A function taking a vector and returning the relevant result. Based on [Command Master's 05AB1E answer](https://codegolf.stackexchange.com/a/266708/97916). *Thanks to @pajonk for saving three bytes!* [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~21~~ 16 bytes Port of 05AB1E answer -5 thanks to @coltim ``` &/+/|/\0 1'1_-': ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs1LT19av0Y8xUDBUN4zXVbfi4kpT1zBUMFIwtgaRRtZGcNLQ2hhEanIBAC5ECjE=) ``` 1_-': deltas 0 1' sign +/|/\ add maximum &/ minimum ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 50 bytes ``` a=>~!a.some(p=x=>p==(p=x))*Math.sign(a[0]-a.pop()) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1q5OMVGvOD83VaPAtsLWrsDWFsTQ1NTyTSzJ0CvOTM/TSIw2iNVN1CvIL9DQ1PyfnJ9XnJ@TqpeTn66RphFtqGOkYxyrqcmFRdwIqzgQYhE3xqEeJA5S/x8A "JavaScript (Node.js) – Try It Online") Use begin and end to detect direction [Answer] # [sclin](https://github.com/molarmanful/sclin), 23 bytes ``` _"-"2%map0<=>"|/"Q + &/ ``` [Try it on scline!](https://scline.fly.dev/#H4sIAKvoUmUCA4uONlQwUjBWMFWwjNXjUoDzTKE8KITzjOMVTOMVLOMVICLxCkbxSGJAwRhrhdzEAgA7e7IoVwAAAA#H4sIAKvoUmUCA4tX0lUyUs1NLDCwsbVTqtFXClTQVlDTBwBmzrqDFwAAAA#) Port of [Command Master's answer](https://codegolf.stackexchange.com/a/266708/41247). ## Explanation Prettified: ``` _ \- 2%map 0<=> \|/ Q + &/ ``` * `_ \- 2%map` negated delta (via pairwise difference) * `0<=>` sign (i.e. compare to 0) * `\|/ Q` dup and get max * `+ &/` vectorized-add and get min [Answer] # [Desmos](https://desmos.com/calculator), 33 bytes ``` f(L)=D.max+D.min D=sgn(L[2...]-L) ``` Port of 05AB1E. [Try It On Desmos!](https://www.desmos.com/calculator/vv4pgpmhg1) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/rxbl6uy6cw) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~57~~ 51 bytes ``` \d+ * Lv`\b_+,_+ +`_,_ , O^` ,,G` ^_ -_ /[^-]+/_`_+ ``` [Try it online!](https://tio.run/##PcmxCoNAEIThft5DkOyInN6Bb2Aj@AAxt6uYIk2KIL7@uTZhmo/5f@/j811DqerRyrILHphOWzYVqkBMqSDmbCBHQ1Y0ivaZm5e0aiqlBHaMHBB4q2dyD/zPnfztvAZ3vHUB "Retina – Try It Online") Link includes test cases. Only accepts positive integer lists, but will output `-2` to `2` as required. Explanation: ``` \d+ * ``` Convert to unary. ``` Lv`\b_+,_+ +`_,_ , ``` For each overlapping pair of integers, get a substring representing the delta: `_+,` for negative, `,` for `0` and `,_+` for positive. ``` O^` ``` Group identical substrings together and sort `_,` first. ``` ,,G` ``` Keep only one of each group, but if there is only one group, keep two of it. ``` ^_ -_ ``` If there was a `_,` then prefix a `-` sign. ``` /[^-]+/_`_+ ``` Count the runs of `_`s. Edit: Saved 6 bytes by porting my answer to [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d) for 61 bytes and then backporting the golfs: ``` \d+ $* M!&`\b1+,1+ +`1,1 , O^` +`¶.+¶ ¶ ^1 -1 ((1+)|,|¶)+ $#2 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFm0tFi8tXUS0hJslQW8dQm0s7wVDHkEuHyz8uAcg@tE1P@9A2LiCKM@TSNeTS0DDU1qzRqTm0TROoU9no/39DHSMdEx0LLqAuIMtYxxTIttCBQyDbFChqpAMy1QKoEsgCAA "Retina 0.8.2 – Try It Online") Link includes test cases. Only accepts positive integer lists, but will output `-2` to `2` as required. Explanation: Retina 0.8.2 uses `$*` (which produces `1`s) instead of `*` (which produces `_`s) for unary, needs to use `M!&` instead of `Lv`, and doesn't have an equivalent of `,,G` or `_` (as a command), so I had to emulate those. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `g`, 29 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 3.625 bytes ``` ¯±:G+ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJnPSIsIiIsIsKvwrE6RysiLCIiLCJbMyw0LDUsNV0iXQ==) Bitstring: ``` 11001100111100010001111111001 ``` Port of the 05ab1e answer [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes ``` ≔EΦθκ⁻›ι§θκ‹ι§θκθI⁺⌊θ⌈θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DN7FAwy0zpyS1SKNQRyFbU0fBNzOvtFjDvSg1ESSYqaPgWOKZl5JaAZEHKvBJLS7GFAfJFGpacwUUZeaVaDgnFpdoBOQADQIal5lbmqtRCDI6sQLKBgLr//@jow11FIx0FEx0FCxiY//rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @Albert.Lang's Python answer. ``` ≔EΦθκ⁻›ι§θκ‹ι§θκθ ``` Get the signs of the deltas. ``` I⁺⌊θ⌈θ ``` Add the minimum and maximum of them. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 54 bytes ``` a=>a.map(n=p=o=v=>[n|=a>v,p|=a<v,o|=a==v,a=v])|p-n<<!o ``` [Try it online!](https://tio.run/##dcrBCoMwEIThe9@itwRWoXrN5EXEw2JVLDa71LIn3z2N95Q5/PAxLzY@ps@m3ybJc84LMiNy@2Z1CQqBIQ7pBEcjLQlGUgIYMWz0pzYphLvkSdIh@9zusrrFDQ/qqB@9v1W8q3pZxfs//8uvf/4B "JavaScript (Node.js) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 63 bytes Port of [my JS answer](https://codegolf.stackexchange.com/a/266729/58563). ``` m,p;f(a,n)int*a;{for(m=0;p=*a++,--n;)m|=p<*a?5:p>*a?-2:3;m%=3;} ``` [Try it online!](https://tio.run/##dc9LCsIwEAbgvacYBKGpE@hToTF6EHWRpq0UTAxVdFF7dWOUSDcWfpjFx7wkPUlprULDmkCgJq2@hYL1zaULFI@Y4aFYLpFSzYh6crMJxS4vzNYVmhQpUwuessHeL20FSrQ6INDPANwUEPsjcOhhjZAhpAgJDMxb6W2FkLuMID1E@M0IlQcau0G/ZKPXY2PsVzkxnbMmmC@qg54jfF6EjBD2j0p35ATJaarc@RNU@67BvmRzFqerpY83 "C (gcc) – Try It Online") [Answer] # APL+WIN, 52 bytes Prompts for vector: ``` +/2 1 0×(×n)×(s=⍴v),((s<⍴v)^s>0),0=s←1+|n←+/×-2-/v←⎕ ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv7a@kYKhgsHh6RqHp@dpAqli20e9W8o0dTQ0im3ArLhiOwNNHQPbYpAm7Zo8IKWtf3i6rpGufhmQDTTvP9Akrv9pXOYKJgrGCkZcaVxmCqYKpkDaQAEIgfSh9YYKRmBoAhYF8gA "APL (Dyalog Classic) – Try It Online") [Answer] # [Go](https://go.dev), ~~193~~ 183 bytes --- Saved 10 bytes thanks to the comment of @corvus\_192 --- Golfed version. [Attempt this online!](https://ato.pxeger.com/run?1=hU_LSsQwFF1PvuLSjQlNhunoiPYxexeC60qFTGnG4DQdQgrS0C9xUwS_wS9xMX9jUusIgg7k5l4O59xz7svrthkOZ3tePvFtBTWXCiFZ7xttAKNZIGoTuFZz8xgg8tYawa4O76JVJZSY0w1IZYgrKwXwdGN1ZVqtIOoTD6yPAHPINC56NOoFVvfFt7yLM-8xv-XPN8pcXiR5nD10iWg0yDhbJDLdVQorwqJEhqHVcVY6uSyo-8KoIN5Op53tMj1a63VuczcfXbsw76f4H6O9PxUTsGjmbpzfaZdip7DAYyYbUVhSOKewonDdE3KatfqP9fNOsJhbxtw29rcp87Tlb-p03DB89U8) ``` func c(a,b int)int{if a<b{return 1};if a>b{return -1};return 0} func f(n[]int)int{z:=math.MaxInt64;Z:=^z;for i:=0;i<len(n)-1;i++{r:=c(n[i],n[i+1]);if r<z{z=r};if r>Z{Z=r}};return z+Z} ``` Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=hZJLasMwEIahO-sUg1cWlkKcNqUPJ_suCl10F7xQjZWKWrJxZAgEn6SbUOilepqObCWpC23AWPP4NPpnmPePdbXff7ZW8puvi-da5G9iXYAWyhCidF01FiIShFLbEA8t7GtIKCGyNTnkla5FU0SCwQsoY6n7wY4ESoKAFINoB01h28ZAQoLOZ5bjDB9S3puSzpeXkWn1BlbZz9JaGYbytnC3AKdm8ii2D8ZeXzHvKtO7JJBVA8ph03s8UygL0xekPMFAHHsJm7a0jjo045CVyhgMRpxkFDnU7dEUUEJ_12mBhY-j3424Za9y4NAYc6d2XY3Yoce23ewj6m7i0CdPDTZemkhG_Rx2CYMZg0sGcwa3HaXnqfl_1Ok7Q3EsxrEa__tR7rDZb7Qblsvv2GHXvgE) ``` package main import ( "fmt" "math" ) func compare(a, b int) int { if a < b { return 1 } if a > b { return -1 } return 0 } func f(nums []int) int { min, max := math.MaxInt64, math.MinInt64 for i := 0; i < len(nums)-1; i++ { result := compare(nums[i], nums[i+1]) if result < min { min = result } if result > max { max = result } } return min + max } func main() { fmt.Println(f([]int{1, 2, 3, 5, 9})) fmt.Println(f([]int{1, 2, 3, 5, 5})) fmt.Println(f([]int{1, 1, 1, 1, 1})) fmt.Println(f([]int{1, 1, -3, -5, -9})) fmt.Println(f([]int{-1, -2, -3, -5, -9})) } ``` [Answer] # Swift, 175 bytes Short version: ``` func m(_ n:[Int])->Int{var r=0,s=0>1;for i in 0..<n.count-1{let(y,x)=(n[i+1],n[i]);if y>x{r=r>0 && !s ?2:1}else if y<x{r=r<0 && !s ? -2:-1}else{r=r.signum();s=0<1}};return r} ``` Verbose version: Basically update the return value to be 2 or -2 as long as the elements differ from each other and "clamp" it to -1,0,+1 as soon as two same elements are found. ``` func m(_ n:[Int])->Int{ var r=0, s=0>1 for i in 0..<n.count-1{ let(y,x)=(n[i+1],n[i]); if y>x{ r=r>0 && !s ?2:1 }else if y<x{ r=r<0 && !s ? -2:-1 }else{ r=r.signum(); s=0<1 } }; return r } ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 53 bytes ``` s/\S+/$'&&$'-$&/ge;$_=2*(/^(\S+ )\1+$/?$1<=>0:.5-/-/) ``` [Try it online!](https://tio.run/##K0gtyjH9/79YPyZYW19FXU1NRV1XRU0/PdVaJd7WSEtDP04DKKOgGWOoraJvr2JoY2tnYKVnqquvq6/5/7@xgpGCIReINOIyArONwGxDBUMwaQQljf/lF5Rk5ucV/9f1NdUzMDT4r1uQAwA "Perl 5 – Try It Online") ]
[Question] [ This is not the same as [m-ss-ng-lette-s](https://codegolf.stackexchange.com/questions/164809/m-ss-ng-lette-s) **Challenge:** Given a string with masked characters, generate all possible words, inclusive of non-meaningfull words. **Rules:** * The sequence of the characters in the string does not change. * The masked character (\*) will be one of an English alphabets [a-z]. * There are no line breaks, space, numbers, special characters or punctuations. * The output can be a list of non-meaningfull words too. * Any characters in a string can be masked. Not necessarily alternating characters. * For memory constraint, lets keep the maximum length of input as 10. **Example 1:** Input: ``` *o* ``` Output: ``` aoa aob aoc ... ... ... boa bob boc ... ... ... zoa zob zoc ... ... ... zoz ``` **Example 2:** Input: ``` *e*c*m* ``` Output: ``` aeacama aeacamb ... ... ... welcome ... ... zezczmz ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! [Answer] # [Haskell](https://www.haskell.org/), 31 bytes ``` mapM q q '*'=['a'..'z'] q c=[c] ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPzexwFehkKtQQV1L3TZaPVFdT0@9Sj0WKJBsG50cC5TPzLMtKMrMK1FQUUhTUNJK1UrWytVS@v8vOS0nMb34v25yQQEA "Haskell – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 25 bytes ``` eval echo ${1//\*/{a..z}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY7U8sScxRSkzPyFVSqDfX1Y7T0qxP19KpqayHyUGXLo5W08rWUYqFcAA) [Answer] # [Ruby](https://www.ruby-lang.org/), 39 bytes ``` ->s{(?a..?z*10).grep /^#{s.tr'*',?.}$/} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664WsM@UU/PvkrLWFMvvSi1QEE/Trm6WK@kSF1LXcder1ZFv/Z/gUJatLpWvpZ67H8A "Ruby – Try It Online") The range is set to terminate after 10 `z`s, to fit the constraint. Realistically this takes forever to run unless a smaller number is used. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 5 bytes ``` ×kaVΠ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwiw5drYVbOoCIsIiIsIltcIipcIixcInlcIixcInhcIixcIipcIixcImxcIl0iXQ==) Input as char lists. ``` V # Replace × # Asterisks ka # With the lowercase alphabet Π # Take cartesian product ``` [Answer] # [Perl 5](https://www.perl.org/) + `-n -M5.10.0`, 37 bytes 1 byte saved thanks to [@Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus)! ``` $"=",";s/\*/{@{[a..z]}}/g;say<"$_\n"> ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJFwiPVwiLFwiO3MvXFwqL3tAe1thLi56XX19L2c7c2F5PFwiJF9cXG5cIj4iLCJhcmdzIjoiLW5cbi1NNS4xMC4wIiwiaW5wdXQiOiIqbXkifQ==) ## Explanation Turns the input into a `glob` (`<"$_\n">`) which is then evaluated as a list and printed (`say`) with newline separators. **Note:** This does struggle to produce all the output for multiple `*`s when running on my phone! [Answer] # Python 3, ~~88~~ 86 bytes ``` def A(x):p=x.find("*");~p and[A(x[:p]+chr(i+97)+x[p+1:])for i in range(26)]or print(x) ``` Removed 2 bytes thanks to [@Adam](https://codegolf.stackexchange.com/users/113573/adam) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, ~~14~~ 13 bytes ``` ×Oka↔ƛ?×\%V$% ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwiw5dPa2HihpTGmz/Dl1xcJVYkJSIsIiIsIipvKiJd) [Could be 8 bytes by using `%` instead of `*`](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwiXFwlT2th4oaUdiUiLCIiLCIlbyUiXQ==) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 9 bytes ``` ×Ẇ⌈yvkaYΠ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwiw5fhuobijIh5dmthWc6gIiwiIiwiKnl4KmwiXQ==) Based on emanresu A's answer, but shaves off another byte. [Answer] # [R](https://www.r-project.org), 65 bytes ``` f=\(s)`if`(grepl("[*]",s[1]),f(sapply(letters,sub,pa="[*]",s)),s) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWNx3TbGM0ijUTMtMSNNKLUgtyNJSitWKVdIqjDWM1ddI0ihMLCnIqNXJSS0pSi4p1ikuTdAoSbaFqNDWBGGLQ3jQNJa18LSVNrpzUvPSSDI00DXWtVK1krVwtdU2oGpilAA) Basically the same recursive idea as in [Cong Chen's answer](https://codegolf.stackexchange.com/a/250540/55372). [Answer] # [Julia](https://julialang.org), 61 bytes ``` !s=join.(Iterators.product((x>'*' ? x : 'a':'z' for x=s)...)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FjdtFYtts_Iz8_Q0PEtSixJL8ouK9QqK8lNKk0s0NCrs1LXUFewVKhSsFNQT1a3Uq9QV0vKLFCpsizX19PQ0NaGGuOek5qWXZGgoKmnlaylpKtTYKRQUZeaV5ORxKSrla-UrIYsg1KZqJWvlAtXX2EHlIMbB3AYA) (This returns a matrix of all possible words, rather than a list/vector.) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 30 bytes ``` /\*/{%`$ 25*$(¶$` ,Y0`*`l`\*.* ``` [Try it online!](https://tio.run/##K0otycxLNPz/Xz9GS79aNUGFy8hUS0Xj0DaVBC6dSIMErYSchBgtPa3//7XytQA "Retina – Try It Online") Explanation: ``` /\*/{ ``` Repeat while there are still any `*`s to process. ``` %`$ 25*$(¶$` ``` Add 25 copies of each line. ``` ,Y0`*`l`\*.* ``` Cyclically transliterate the first `*` on each line to the lowercase alphabet. The `,` tells Retina to process all matches and the `0` tells Retina to process the first character of each match. [Answer] # [lin](https://github.com/molarmanful/lin), 49 bytes ``` "\*".?g.+_.+_"%s"?s.#t ?i len $a.~ `/\".t.~ sf"`' ``` [Try it here!](https://replit.com/@molarmanful/try-lin) Returns an iterator of strings. For testing purposes: ``` "*e*c*m*" ; \outln `' `_ "\*".?g.+_.+_"%s"?s.#t ?i len $a.~ `/\".t.~ sf"`' ``` ## Explanation Prettified code: ``` "\*".?g.+_.+_ "%s"?s.#t ?i len $a.~ `/\ (.t.~ sf ) `' ``` Not very short, but surprisingly straightforward. * `"\*".?g` regex `/\*/g` * `.+_.+_ "%s"?s.#t` replace `*` with `%s` and store as *t* * `?i len` get number of `*`s as *n* * `$a.~ `/\` create length-*n* "digit" sequences from alphabet * `(.t.~ sf ) `'` use *t* to `sprintf` each sequence [Answer] # sh + coreutils + [hashcat](https://hashcat.net/hashcat/), 31 bytes ``` sed s/*/?l/g|xargs hashcat -a 3 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '*A:.»â€S ``` Input as a list of characters. [Try it online](https://tio.run/##yy9OTMpM/f9fXcvRSu/Q7sOLHjWtCf7/P1pJS0lHKR@ItZRiAQ) or [verify both test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXwf3UtRyu9Q7sPL3rUtCb4v5fO/2glrXwtJR0FJa1UrWStXC2lWAA). **Explanation:** ``` '*A: '# Replace all "*" in the (implicit) input-list with the lowercase alphabet .» # Left-reduce the list of strings by: â # Taking the cartesian product €S # Then convert each inner list to a flattened list of characters # (after which the result is output implicitly) ``` Minor note: `'*` could be `W` in the legacy version of 05AB1E if the input is guaranteed to always contain a `"*"`, but unfortunately the `€S` should be `€˜J` in that case, not saving any bytes. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` ⊞υSFυ¿№ι*Fβ⊞υ⭆ι⎇⁻μ⌕ι*λκ⟦ι ``` [Try it online!](https://tio.run/##Pc1BCsIwEIXhvacYupoJ8QRdCoKLQkF34iLW1A7GSUkygqePVtH1@z/eMLk0RBdq7TVPqBZ2MmvZl8RyRaJ2NcYEqAQ8Am6iSkG20JiGCD7TmeBHv6pz85IcfBKXntixaMa7hS3L5W8tBAs3Wg58yB76tyx45BO1tZpo6voRXg "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υS ``` Start with the input string. ``` Fυ ``` Check each string. ``` ¿№ι* ``` If it contains a `*`, then: ``` Fβ ``` Loop over the lowercase alphabet. ``` ⊞υ⭆ι⎇⁻μ⌕ι*λκ ``` Replace the first `*` in the string with the current letter and push it to the search list. ``` ⟦ι ``` Otherwise output the string on its own line. 23 bytes using the newer version of Charcoal on ATO: ``` ⊞υωFS≡ι*≔ΣEυEβ⁺κμυ≧⁺ιυυ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY6xDoIwEIZ3nuLS6UrKbnBydDAhMhqHUoE2ViBcK4PxKRxdGDTxAXwZ30YauOG_S-77_7vnR2nZq1bacXx7VyWr3yPzpNELGPg6qtoecNt03uWuN02NnAMNxikNaDjcIiWpBBazFDZEpm4w9xfcyS4EhFYIyKwnPAu48KkE-Cn2VFbSW5cGZPbtTa0dBlSAmaF7lE0nHU7ziwpFy4PfA0uulglgiQkatzE7Lrs_ "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation: ``` ⊞υω ``` Start with the empty string. ``` FS ``` Loop over the characters of the input string. ``` ≡ι* ``` If the current character is a `*`, then... ``` ≔ΣEυEβ⁺κμυ ``` ... append each lowercase letter to each of the strings so far and join the resulting lists, otherwise... ``` ≧⁺ιυ ``` ... append the current character to each of the strings so far. ``` υ ``` Output the final list of strings. [Answer] # [R](https://www.r-project.org), 91 bytes ``` \(a,j=Vectorize(\(x,y)sub('*',y,x,,,T),'y'))`if`(grepl('*',a,,,T),sapply(j(a,letters),f),a) ``` Recursive solution. [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3o2M0EnWybMNSk0vyizKrUjViNCp0KjWLS5M01LXUdSp1KnR0dEI0ddQr1TU1EzLTEjTSi1ILcsCSiRCp4sSCgpxKjSygQTmpJSWpRcWaOmmaOomaUCtUc1Lz0ksyNNKAmvK1gMZwIQmkaiVr5YIEIYoXLIDQAA) [Answer] # [Factor](https://factorcode.org) + `spelling`, ~~60~~ 56 bytes ``` [ 1 group { "*"} ${ ALPHABET } replace [ ] product-map ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TYyxCsIwFEX3fsWjOBUquBWdKogKIoK6WDqE-KzBZxLTZCr9Epcu-gN-Tf_GlDg43Qv3nPt8Xxi3ynT96bhfb5dTuKGRSFAZ5bSQFdQaiYZCwqJhVEOND4eS418ba6POjlsQyguetIMxi6I4UUn8cvaSZn1WwCT8QgNxErcwaiDf7Fb5fHGAFgxqYhyhgBJ-f-mdaSiD_-GMyI_aCGk9goxfw9J1Ib8) ``` ! "*o*" 1 group ! { "*" "o" "*" } { "*"} ${ ALPHABET } replace ! { "abcdefghijklmnopqrstuvwxyz" "o" "abcdefghijklmnopqrstuvwxyz" } [ ] product-map ! { "aoa" "boa" ... "zoz" } ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes ``` ẹ{"*"∧!Ạ∋|}ᵐc ``` [Try it online!](https://tio.run/##ATQAy/9icmFjaHlsb2cy/@KGsOKCgeG2oP/hurl7Iioi4oinIeG6oOKIi3x94bWQY///IipvIv9a "Brachylog – Try It Online") This is a generator predicate that will unify its output with each possible combination. The TIO example uses `ᶠ - findall` to generate all answers, but in a Prolog REPL you could just press `;` repeatedly to get each answer. ### Explanation ``` ẹ Split the string into a list of characters { }ᵐ Map for each char: "*" If the char is "*" ∧! Cut (i.e. discard the "else" possibility) Ạ∋ The output is an element of the alphabet | Else don’t modify the char c Concatenate back to a string ``` The cut `!` is necessary, otherwise the predicate would also generate answers with the asterisk unchanged. [Answer] ## JavaScript, 111 bytes I feel like it's way too long and I'm missing something big. ``` s=>(r=s=>s[1]?.at?[...'abcdefghijklmnopqrstuvwxyz'].flatMap(c=>r(s.slice(1)).map(p=>s[0]+c+p)):s)(s.split('*')) ``` [Answer] # Also **Python 3, 86 Bytes**: ``` def f(x): for i in range(26):y=x.replace('*',chr(i+97),1);f(y)if'*'in y else print(y) ``` [Answer] # [Julia](https://julialang.org), 61 bytes ``` !s=foldl((x,y)->[x.*y...],[x<'a' ? 'a'.+(0:25)' : x for x=s]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FjdtFYtt0_JzUnI0NCp0KjV17aIr9LQq9fT0YnWiK2zUE9UV7BWApJ62hoGVkammuoKVQoVCWn6RQoVtcawm1BDjnNS89JIMDUUlrXwtJc0au4KizLySnDwuhHiqVrJWLrIcRCvMHQA) ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 7 years ago. [Improve this question](/posts/22352/edit) I would like to see who can make Python have a fatal crash with the most creative code. This means that when the program runs, Windows for example, will take over and pop up with something like “IDLE has stopped working”, or Linux will do whatever Linux does when a program crashes. Rules: 1. This must be made in Python 2.7 or above (So old bugs aren't exploited that have been fixed in future versions of Python). 2. The definition of "crash" is "make IDLE or Python exit in an unintended way." This does not mean "make IDLE or Python halt and give a traceback". This also means exit, sys.quit, abort etc are not valid answers. For example, this will not be accepted: ``` import sys try: print c # Crashes Here, as c is not defined. except NameError, SyntaxError: print "Oh No!" sys.exit() ``` 3. Making Python stop responding is not accepted. 4. The code must be explained on what it does to crash. A link to a bug report is fine. The most upvoted answer after 10 days wins! Begin!! **EDIT:** May I make it clear that the objective is **not to make Python just halt executing the program** with a traceback. The objective is to make Python completely crash or stop working. This means that if this task is successfully accomplished, Windows would give this (I'm not crashing Word here, it's just an example of what should happen for a different program): ![error dialogue](https://i.stack.imgur.com/RjbuS.jpg) or this: ![error dialogue 2](https://i.stack.imgur.com/dikW4.png/wordhasstoppedworking.png) [Answer] Should have been a code-golfing contest ;) - I guess the creativity is the statement the code makes: "I just don't know what's happening here..." **Copy and paste** the following character in IDLE running on Windows: ``` 𐒢 ``` The crash has something to do with the character being encoded as UTF-16 by Windows and the unsuccessful conversion to a UTF-8 character by IDLE... Edit: [python bug #13153](http://bugs.python.org/issue13153) [Answer] `ctypes` abuse: ``` import ctypes;ctypes.string_at(1) ``` This casts 1 to an address and dereferences it. On any sane system (i.e. one on which 0x00000001 is not a mapped address), this will segfault instantly. [Answer] ## 60 ``` import sys sys.setrecursionlimit(1<<30) f=lambda f:f(f) f(f) ``` Not my own idea. Copied from the Python Wiki [here](//wiki.python.org/moin/CrashingPython). This causes an infinite recursion, and is not stopped by the interpreter because we changed the recursion limit. [Answer] `signal` abuse (non-Windows only): ``` import os;os.kill(0,4) ``` On most systems (on which SIGILL = 4) this will kill Python with an "illegal instruction" error. Or you can kill the program using the *killer alarm clock*: ``` import signal;signal.alarm(1) ``` After one second, Python dies with the cryptic message "Alarm clock". [Answer] In Python 3.3: ``` exec(type((lambda:0).__code__)(0,1,0,0,0,b'',(),(),(),'','',1,b'')) ``` In Python 2.7 code objects are slightly different: ``` exec type((lambda:0).func_code)(0,1,0,0,'Q',(),(),(),'','',0,'') ``` Yes, you can pass any old rubbish to the byte code interpreter and it executes it ([Python issue #17187](http://bugs.python.org/issue17187)). [Answer] Recursive iterators use the C stack, not the Python stack ([issue #14010](http://bugs.python.org/issue14010) and [issue #14507](http://bugs.python.org/issue14507)): ``` i='' for _ in range(9**6):i=filter(int,i) del i ``` [Answer] One easy way to crash the interpreter is to trick it into deallocating None: ``` import ctypes, sys (ctypes.c_char*4).from_address(id(None))[:] = '\0'*4 ``` As a bonus, here's a clever way to segfault Python 2: ``` import ctypes, struct, sys inner = () outer = (inner,) c_outer = (ctypes.c_char * sys.getsizeof(outer)).from_address(id(outer)) inner_index = c_outer[:].find(struct.pack('P', id(inner))) c_outer[inner_index:inner_index+struct.calcsize('P')] = struct.pack('P', id(outer)) print outer ``` What exactly this does is left as an exercise to the reader. [Answer] Someone thought they could prevent new `FlagsType` objects from being created by setting `FlagsType.tp_new = NULL`, but they forgot to remove the method ([issue #13204](http://bugs.python.org/issue13204)): ``` import sys t=type(sys.flags) t.__new__(t) ``` (`sys.version_info` has the same bug.) [Answer] Use of `alloca` in `ctypes` module ([issue #13096](http://bugs.python.org/issue13096)): ``` from ctypes import * POINTER('a'*9**8) ``` [Answer] One possible way which crashes my Python with `MemoryError`: ``` x=[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] ``` ]
[Question] [ [This blog post](http://www.paulirish.com/2009/random-hex-color-code-snippets/) about generating random CSS color codes in JavaScript have multiple solutions for generating a random color in JavaScript. The shortest I can find is this: ``` '#'+(Math.random()*0xffffff).toString(16).slice(-6) ``` If you are not familiar with CSS color code [read documentations here.](http://www.w3.org/TR/css3-color/) Can we do better? What about other languages? [Answer] ## PHP 23 bytes ``` #<?=md5(rand())&ÿÿÿÿÿÿ; ``` Where `ÿ` is character 255. Bitwise and will truncate the string returned from `md5`, which is already in hexadecimal format. [Answer] Three character codes are valid too, so I can save some chars (`4095 == 0xfff`): ## Ruby, ~~24~~ ~~23~~ ~~22~~ 18 ``` '#%03x'%rand(4095) ``` If I *have* to use a 6-char one, then: ## Ruby, ~~28~~ ~~27~~ ~~26~~ ~~24~~ 20 Shaved one character off because `8**8-1 == 0xffffff` ``` '#%06x'%rand(8**8-1) ``` Thanks to chron for the format string, saving 4 chars! --- Cheating (with [this xkcd strip](http://xkcd.com/221/) in mind): ## Ruby/JS/Python/Perl/lots more, 6 (or 5) ``` "#a83" ``` I assure you, I generated it randomly! An even cheatier version: ``` "red" ``` [Answer] # Javascript ``` '#'+Math.random().toString(16).substr(2,6) ``` Just a little shorter at 42. ``` function randomColor() { return '#' + Math.random().toString(16).substr(2, 6); } for (var n = 0; n < 16*9; n++) { var el = document.createElement('SPAN'); el.style.backgroundColor = randomColor(); document.getElementById('demo').appendChild(el); } ``` ``` span { width: calc(100%/16); height: calc(100vh/9); margin-top: -7px; display: inline-block; } ``` ``` <div id='demo'></div> ``` [Answer] # Fish 79 ``` vnnnnnnnn 601234567; >xxxxxxxx< 89""""""? nnABCDEF: vv""""""- vvoooooo1 >>>>>>>>^ ``` Not the shortest solution in the world, but it was fun to code :) It's also not a uniform distribution, but all outputs have a non-zero probability 7 and F are most likely digits. Outputs: ``` python fish.py randomColor.fish 07FFF7 python fish.py randomColor.fish 07EFD7 python fish.py randomColor.fish 366F67 python fish.py randomColor.fish 977FD7 python fish.py randomColor.fish 97F7F7 python fish.py randomColor.fish 87F6FF ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~28~~ 24 bytes *-4 bytes thanks to @Julian!* ``` "#{0:X6}"-f(random 16MB) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0m52sAqwqxWSTdNoygxLyU/V8HQzNdJ8/9/AA "PowerShell – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `Ṫ`, ~~8~~ 7 bytes ``` \#k66ƈṅ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=%E1%B9%AA&code=%5C%23k66%C6%88%E1%B9%85&inputs=&header=&footer=) ``` \# # Push a # 6ƈ # Choose six... k6 # Hex digits ṅ # Appended to the # ``` [Answer] ## APL (17) ``` '#',(⎕D,⎕A)[6?16] ``` Explanation: * `6?16`: 6 random numbers from 1 to 16 * `⎕D,⎕A`: the digits (`0..9`) followed by the alphabet (`A..Z`) (but only the first 16 values are ever used, i.e. `0..F`) * `'#',`: add a `#` to the front [Answer] # [Zsh](https://www.zsh.org/), 37 bytes ``` <<<\#`tr -dc 0-9a-f</*/ur*m|head -c6` ``` [Try it online!](https://tio.run/##qyrO@P/fxsYmRjmhpEhBNyVZwUDXMlE3zUZfS7@0SCu3JiM1MUVBN9ks4f9/AA "Zsh – Try It Online") * `</*/ur*m`: input from `/dev/urandom` (shortened with wildcards) * `tr -dc 0-9a-f`: keep only characters in the range `0-9a-f` * `head -c6`: take the first 6 characters * `<<<#```: prepend `#` and print [Answer] # [Python 3](https://docs.python.org/3/), 44 bytes ``` from secrets import* print("#"+token_hex(3)) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehODW5KLWkWCEztyC/qESLq6AoM69EQ0lZSbskPzs1Lz4jtULDWFPz/38A "Python 3 – Try It Online") Did you know this built-in python module? It was added in python 3.6 to include some random function for paswords (more informations [here](https://docs.python.org/3/library/secrets.html)). ## How it works ? Basicaly, I generate a random 3-bytes long hexadecimal string ... Yeah, that's it. # [Python 2](https://docs.python.org/2/), ~~32~~ 31 bytes I also have the slightly less elegant : (also works in Python3 in ~~34~~ 33 bytes by adding parenthesis for the `print` function) ``` print"#%06x"%((id(0)>>16)%8**8) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69ESVnVwKxCSVVDIzNFw0DTzs7QTFPVQkvLQvP/fwA "Python 2 – Try It Online") This one uses the fact that at each execution of the code, python uses an indivdual memory address for each object. This memeory address change at each execution of the program. As the last 16 bits of this id are not random, I shifted the result before using a modulo to have the right number of bits Thanks to pxeger for -1 bytes [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `Ṫ`, 7 bytes ``` \#6(k6℅ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=%E1%B9%AA&code=%5C%236%28k6%E2%84%85&inputs=&header=&footer=) ## Explanation ``` \#6(k6℅ \# Push "#" ( For _ 6 in range(6): k6 "0123456789abcdef" ℅ Random item Ṫ Concatenate the stack ``` [Answer] ## Python 3, 32 bytes ``` print(f"{hash('a'):x}#"[:-8:-1]) ``` [Answer] ## Bash (51) ``` od -N4 -An -tx /dev/urandom | cut -c2-7 | sed s/^/#/ ``` [Answer] # [Python 3](https://docs.python.org/3/), 53 bytes ``` from random import*;print(f"#{randint(0,16**6):06x}") ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehKDEvBUhl5hbkF5VoWRcUZeaVaKQpKVeDJEBsAx1DMy0tM00rA7OKWiXN//8B "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 50 bytes ``` import time print(f"#{int(time.time()%16**6):6x}") ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEkMzeVq6AoM69EI01JuRpEg4T0QISGpqqhmZaWmaaVWUWtkub//wA "Python 3 – Try It Online") Random generation by modulo of current time saves two precious bytes Also 0 before 06x can be omitted [Answer] # [Nim](http://nim-lang.org/), 57 bytes ``` import colors,random randomize() echo 0xffffff.rand.Color ``` [Try it online!](https://tio.run/##y8vM/f8/M7cgv6hEITk/J7@oWKcoMS8lP5cLQmVWpWpocqUmZ@QrGFSkgYEeSEbPGaT4/38A "Nim – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` 6ØhX¤€”#; ``` [Try it online!](https://tio.run/##y0rNyan8/9/s8IyMiENLHjWtedQwV9n6/38A "Jelly – Try It Online") ## Explanation ``` 6ØhX¤€”#; Main niladic link 6 6 € Map ¤ ( Øh "0123456789abcdef" X Choose random ¤ ) ; Prepend ”# "#" ``` [Answer] # [Julia 1.0](http://julialang.org/), 24 bytes ``` '#'repr(rand(UInt))[3:8] ``` [Try it online!](https://tio.run/##yyrNyUw0rPhfUJSZV5KTp/FfXVm9KLWgSKMoMS9FI9Qzr0RTM9rYyiL2v@Z/AA "Julia 1.0 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Gö6 msG i'# ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=R/Y2IG1zRyBpJyM) [Answer] # [Java (JDK)](http://jdk.java.net/), 54 bytes ``` n->"#"+Long.toHexString((int)(Math.random()*0xffffff)) ``` [Try it online!](https://tio.run/##RY9Pb8IwDMXvfAqLXZKhhu2MxnlIcOI47WASN4SlSdW4iGnis3fpH8q7WHZ@znu@4BWLi/nptMeU4IAuwN9iAVnrNegzBkt48gQuMDUlahre5g52GYdJR25csMCUGERGwNkQG5KbgbiP39btyTsNiZFzuUZnoOpdxbj99Q3Y2CQfKaYkibit58EOUvQtuxjgYx4@aRt9SQZ0NNSFYrt8Wa72MVjF8ZNuo43o80lxQD6rBoOJlZCvb7dykJTd5ul@/E1MlYotqzqvsg/i4a76U0XxLuXE5xvv3T8 "Java (JDK) – Try It Online") [Answer] # [Mathematica](https://www.wolfram.com/wolframscript/), 30 bytes `0xfff == 4095`, so we can just take a random integer from 0-4095 and convert it to hexadecimal form. We save a few characters using prefix and infix notation. ``` RandomInteger@4095~BaseForm~16 ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z8oMS8lP9czryQ1PbXIwcTA0rTOKbE41S2/KLfO0Oz/fwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Ly](https://github.com/LyricLy/Ly), ~~29~~ 26 bytes ``` '#o6['0'??'9G[p'(+,0]po,]p ``` [Try it online!](https://tio.run/##y6n8/19dOd8sWt1A3d5e3dI9ukBdQ1vHILYgXye24P9/AA "Ly – Try It Online") At a high level, here's how this one works... 1. write out `#` 2. loop 6 times... 3. each iteration, write out a random digit in `0-f` range And for people who like gory details about stacks. :) ``` '#o6['0'??'9G[p'(+,0]po,]p '#o - push "#" on stack, print it as char 6[ ,] - loop 6 times '0'? - push "0" and "?" codepoints on stack ? - pick a random number between them '9G - is it greater then "9" codepoint? [p 0]p - if/then, called if pick is > "9" '( - push 28 on stack (Note 1) + - add 28 to random pick (Note 1) , - decrement (Note 1) o - print top of stack as a char p - clear the loop artifact from the stack ``` Note 1: Mapping the codepoints `:-?` to `a-f` means adding 27 to the codepoint. The shortest way to do that would be to push `'` onto the stack, but the code for that (at least on TIO) `''` doesn't work. So this code loads 28 (which is `(` then decrements the result with `,` instead. [Answer] # [C (tcc)](http://savannah.nongnu.org/projects/tinycc), ~~46~~ 43 bytes *-3 bytes, thanks @ceilingcat* ``` main(){srand(main);printf("#%08X",rand());} ``` [Try it online!](https://tio.run/##S9YtSU7@/z83MTNPQ7O6uCgxL0WjJDM3VcNAU9O6oCgzryRNQ0lZ1cAiQkkHLAkUrv3/HwA "C (tcc) – Try It Online") 4 byte color codes are valid, the last byte is used as alpha. C is weird with random numbers because of how old it is. While the code above is *technically* a valid answer, it does a really bad job because different compilers treat `rand()` differently and often use a suboptimal generator, in addition to not actually guaranteeing every possible color. Importing a better library for generation isn't exactly a good idea for Code Golf though. [Answer] # Zsh (coreutils), 26 bytes Using `jot`, [originally](https://github.com/freebsd/freebsd-src/blob/9b50d9027575220cb6dd09b3e62f03f511e908b8/usr.bin/jot/jot.c) in BSD Unix. [Try it Online](https://tio.run/##qyrO@P8/K79EQbc8Rlm1QkG3SMFQwUDB0Mzc3NzI0Oz/fwA). ``` jot -w\#%x -r 1 0 16777216 ``` [Answer] #### Red, 18 bytes ``` random 255.255.255 ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 43 bytes ``` from os import* print("#"+urandom(3).hex()) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P60oP1chv1ghM7cgv6hEi6ugKDOvRENJWUm7tCgxLyU/V8NYUy8jtUJDU/P/fwA "Python 3.8 (pre-release) – Try It Online") 1 byte less than current top Python 3 sol by @Jakque, as I don't think that one by @Ivar Matstoms is fair ]
[Question] [ A mad scientist has just created a new species of bacterium! He has decided to name it *Noblus Gentlemanus*, after observing its behaviour. However, his bacteria have ran out of food, and have declared war, as they are able to harvest other bacterium's corpses for enough food to create copies of themselves. There are a number of different subspecies of this bacterium, who have different strategies in playing Prisoner's Dilemma, their favourite game. There are five bacteria from each different subspecies. In Prisoner's Dilemma, each of the two players simultaneously chooses either defect or cooperate. If one player chooses cooperate and the other chooses default, the defaulter gets 2 points, and the cooperator loses 3 points. If both player choose cooperate, both players get one 1 point. If both players choose default, both players lose 1 point. Being Noble Gentlemen, the bacteria have decided to fight this war by playing 200 round long games of Iterated Prisoner's Dilemma. The loser of each duel will commit suicide, allowing the victor to clone itself. In the event of a tie, both bacteria will remain alive, but neither will be able to clone itself. In addition, all bacteria from a match carry over 10% of their points to the next match. A clone carries over the points of the bacterium it was cloned by. Also, there is a one in ten chance each turn that one bacterium will mutate into another subspecies, with 0 bonus points (if I receive complaints about the randomness of this, I can remove it). After the bacteria have played a number of these duels equal to the number of subspecies of bacteria times ten, the mad scientist accidentally drops the petri dish the bacteria reside in, and all of the bacteria acquire new sources of food, ending their duels. This is different from an ordinary iterated prisoner's dilemma contest, as it involves 1v1 duels with carryover points, rather than simply attempting to get the most points overall. This makes a big difference in how effective a given strategy is. Each bacterium will receive input at the beginning of its turn in the format: (turn number, current points, enemies points, your previous moves [in a string, using the character "c" for cooperate, and the character "d" for defect], enemies previous moves [in the same format]). Here are four sample strategies that will be entered. I actually think that Defector might win, even though it is extremely simple. ### Tit for Tat ``` def titfortatfunc(counter, mypoints, enpoints, mylist, enlist): if counter==0 or enlist[counter-1] == "c": return "c" else: return "d" ``` ### RandomPick ``` from random import choice def randompickfunc(counter, mypoints, enpoints, mylist, enlist): if counter == 199: return "d" else: return choice(["d", "c"]) ``` ### Cooperator ``` def cooperatorfunc(counter, mypoints, enpoints, mylist, enlist): return "c" ``` ### Defector ``` def defectorfunc(counter, mypoints, enpoints, mylist, enlist): return "d" ``` All submissions must be in the form of a Python 2.7 function, with the name being the name of the submission with no spaces, with `func` on the end. If someone would like to submit an answer in a different language, please enter it in pseudo-code, for me to convert to Python in an edit to your answer once I have time, or give me instructions on interfacing your language with my controller which is found below set up for all submissions as of June 4. ``` from titfortat import titfortatfunc from randompick import randompickfunc from cooperator import cooperatorfunc from defector import defectorfunc from luckytitfortat import luckytitfortatfunc from randomtitfortat import randomtitfortatfunc from remorsefulaggressor import remorsefulaggressorfunc from everyother import everyotherfunc from niceguy import niceguyfunc from titfortatbackstab import titfortatbackstabfunc from gentleDefector import gentleDefectorfunc from anticapitalist import anticapitalistfunc from grimtrigger import grimtriggerfunc from bizzaro import bizzarofunc from neoanticapitalist import neoanticapitalistfunc from bittertat import bittertatfunc from teamer import teamerfunc from copyfirst import copyfirstfunc from exploitivetat import exploitativetatfunc from defectorv2 import defectorv2func from crazytat import crazytatfunc from randomchoicev2 import randomchoicev2func from twotitsforatat import twotitsforatatfunc from threetitsforatat import threetitsforatatfunc from fourtitsforatat import fourtitsforatatfunc from fivetitsforatat import fivetitsforatatfunc from sixtitsforatat import sixtitsforatatfunc from tentitsforatat import tentitsforatatfunc from theelephant import theelephantfunc from xbittertat import xbittertatfunc from fifteentitsforatat import fifteentitsfortatfunc from twentytitsforatat import twentytitsforatatfunc from fox import foxfunc from onehundredfortysixtitsforatat import onehundredfourtysixtitsforatatfunc from gameofthrones import gameofthronesfunc from boy import boyfunc from grimace import grimacefunc from fiftytitsforatat import fiftytitsfortatfunc from soreloser import soreloserfunc from everyotherd import everyotherdfunc from fiftythreetitsfortat import fiftythreetitsfortatfunc from twentyfivetitsfortat import twentyfivetitsfortatfunc from handshake import handshakefunc from anty import antyfunc from fiftyfourtitsforatat import fiftyfourtitsfortatfunc from kindatitsfortat import kindatitsfortatfunc import random players = 38 rounds = players*10 def runcode(num, points1, points2, history1, history2, cell): ans = "" if cell == 0: ans = titfortatfunc(num, points1, points2, history1, history2) elif cell == 1: ans = randompickfunc(num, points1, points2, history1, history2) elif cell == 2: ans = cooperatorfunc(num, points1, points2, history1, history2) elif cell == 3: ans = defectorfunc(num, points1, points2, history1, history2) elif cell == 4: ans = luckytitfortatfunc(num, points1, points2, history1, history2) elif cell == 5: ans = randomtitfortatfunc(num, points1, points2, history1, history2) elif cell == 6: ans = remorsefulaggressorfunc(num, points1, points2, history1, history2) elif cell == 7: ans = everyotherfunc(num, points1, points2, history1, history2) elif cell == 8: ans = niceguyfunc(num, points1, points2, history1, history2) elif cell == 9: ans = titfortatbackstabfunc(num, points1, points2, history1, history2) elif cell == 10: ans = gentleDefectorfunc(num, points1, points2, history1, history2) elif cell == 11: ans = anticapitalistfunc(num, points1, points2, history1, history2) elif cell == 12: ans = grimtriggerfunc(num, points1, points2, history1, history2) elif cell == 13: ans = bizzarofunc(num, points1, points2, history1, history2) elif cell == 14: ans = neoanticapitalistfunc(num, points1, points2, history1, history2) elif cell == 15: ans = tentitsforatatfunc(num, points1, points2, history1, history2) elif cell == 16: ans = bittertatfunc(num, points1, points2, history1, history2) elif cell == 17: ans = copyfirstfunc(num, points1, points2, history1, history2) elif cell == 18: ans = exploitativetatfunc(num, points1, points2, history1, history2) elif cell == 19: ans = sixtitsforatatfunc(num, points1, points2, history1, history2) elif cell == 20: ans = fifteentitsfortatfunc(num, points1, points2, history1, history2) elif cell == 21: ans = fivetitsforatatfunc(num, points1, points2, history1, history2) elif cell == 22: ans = twentytitsforatatfunc(num, points1, points2, history1, history2) elif cell == 23: ans = threetitsforatatfunc(num, points1, points2, history1, history2) elif cell == 24: ans = fiftyfourtitsfortatfunc(num, points1, points2, history1, history2) elif cell == 25: ans = theelephantfunc(num, points1, points2, history1, history2) elif cell == 26: ans = xbittertatfunc(num, points1, points2, history1, history2) elif cell == 27: ans = foxfunc(num, points1, points2, history1, history2) elif cell == 28: ans = gameofthronesfunc(num, points1, points2, history1, history2) elif cell == 29: ans = boyfunc(num, points1, points2, history1, history2) elif cell == 30: ans = grimacefunc(num, points1, points2, history1, history2) elif cell == 31: ans = soreloserfunc(num, points1, points2, history1, history2) elif cell == 32: ans = everyotherdfunc(num, points1, points2, history1, history2) elif cell == 33: ans = twentyfivetitsfortatfunc(num, points1, points2, history1, history2) elif cell == 34: ans = fiftythreetitsfortatfunc(num, points1, points2, history1, history2) elif cell == 35: ans = handshakefunc(num, points1, points2, history1, history2) elif cell == 36: ans = antyfunc(num, points1, points2, history1, history2) elif cell == 37: ans = kindatitsfortatfunc(num, points1, points2, history1, history2) return ans def fight(l1,l2): num1,num2=l1[0],l2[0] points1,points2=l1[1],l2[1] history1 = "" history2 = "" for num in range(200): p1 = runcode(num, points1, points2, history1, history2, num1) p2 = runcode(num, points2, points1, history2, history1, num2) history1+=p1 history2+=p2 if p1 == "c" and p2 == "c": points1 += 1 points2 += 1 elif p1 == "c" and p2 == "d": points1 -= 3 points2 += 2 elif p1 == "d" and p2 == "c": points1 += 2 points2 -= 3 elif p1 == "d" and p2 == "d": points1 -= 1 points2 -= 1 if points1 > points2: return [l1[0], points1/10], [l1[0], points1/10] elif points1 < points2: return [l2[0], points2/10], [l2[0], points2/10] else: return [l1[0], points1/10], [l2[0], points2/10] def rounddoer(bots): bots2=[] for x in range(len(bots)): if x%2==0: out1, out2 = fight(bots[x], bots[x-1]) bots2.append(out1) bots2.append(out2) return bots2 def gamedoer(): bots=[[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0],[12,0],[13,0],[14,0],[15,0],[16,0],[17,0],[18,0],[19,0],[20,0],[21,0],[22,0],[23,0],[24,0],[25,0],[26,0],[27,0],[28,0],[29,0],[30,0],[31,0],[32,0],[33,0],[34,0],[35,0],[36,0],[37,0],[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0],[12,0],[13,0],[14,0],[15,0],[16,0],[17,0],[18,0],[19,0],[20,0],[21,0],[22,0],[23,0],[24,0],[25,0],[26,0],[27,0],[28,0],[29,0],[30,0],[31,0],[32,0],[33,0],[34,0],[35,0],[36,0],[37,0],[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0],[12,0],[13,0],[14,0],[15,0],[16,0],[17,0],[18,0],[19,0],[20,0],[21,0],[22,0],[23,0],[24,0],[25,0],[26,0],[27,0],[28,0],[29,0],[30,0],[31,0],[32,0],[33,0],[34,0],[35,0],[36,0],[37,0],[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0],[12,0],[13,0],[14,0],[15,0],[16,0],[17,0],[18,0],[19,0],[20,0],[21,0],[22,0],[23,0],[24,0],[25,0],[26,0],[27,0],[28,0],[29,0],[30,0],[31,0],[32,0],[33,0],[34,0],[35,0],[36,0],[37,0],[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0],[12,0],[13,0],[14,0],[15,0],[16,0],[17,0],[18,0],[19,0],[20,0],[21,0],[22,0],[23,0],[24,0],[25,0],[26,0],[27,0],[28,0],[29,0],[30,0],[31,0],[32,0],[33,0],[34,0],[35,0],[36,0],[37,0]] random.shuffle(bots) counter=0 while counter < rounds: counter += 1 bots = rounddoer(bots) if random.randint(0,10) == 9: bots[random.randint(0, players*5)-1] = [random.randint(0, players-1), 0] random.shuffle(bots) ## for item in bots: ## print str(item[0]) + " with " + str(item[1]) + " bonus points." return bots a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21,a22,a23,a24,a25,a26,a27,a28,a29,a30,a31,a32,a33,a34,a35,a36,a37,mycounter=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 while mycounter < 1000: mycounter += 1 bots = gamedoer() print "Game: " + str(mycounter) for item in bots: if item[0]==0: a0 += 1 if item[0]==1: a1 += 1 if item[0]==2: a2 += 1 if item[0]==3: a3 += 1 if item[0]==4: a4 += 1 if item[0]==5: a5 += 1 if item[0]==6: a6 += 1 if item[0]==7: a7 += 1 if item[0]==8: a8 += 1 if item[0]==9: a9 += 1 if item[0]==10: a10 += 1 if item[0]==11: a11 += 1 if item[0]==12: a12 += 1 if item[0]==13: a13 += 1 if item[0]==14: a14+=1 if item[0]==15: a15+=1 if item[0]==16: a16+=1 if item[0]==17: a17+=1 if item[0]==18: a18 += 1 if item[0]==19: a19+=1 if item[0]==20: a20+=1 if item[0]==21: a21+=1 if item[0]==22: a22+=1 if item[0]==23: a23+=1 if item[0]==24: a24+=1 if item[0]==25: a25+=1 if item[0]==26: a26+=1 if item[0]==27: a27+=1 if item[0]==28: a28+=1 if item[0]==29: a29+=1 if item[0]==30: a30+=1 if item[0]==31: a31+=1 if item[0]==32: a32+=1 if item[0]==33: a33+=1 if item[0]==34: ``` ## This Contest is now Finished If you would like to add an answer, I'll see if I can get around to adding a post-challenge scoreboard under the one for the original contestants. I'll be adding that one as soon as the testing program finishes (probably 2-3 more days). ## FINAL SCORES!!!!! ``` Tit for Tat: 18 Random Pick: 28 Cooperator: 19 Defector: 24 Lucky Tit for Tat: 23 Random Tit for Tat: 23 Remorseful Aggressor: 22 Every Other C: 23 Nice Guy: 18 Tit for Tat Backstab: 15 Gentle Defector: 22 Anticapitalist: 27 Grim Trigger: 19 Bizzaro: 21 NeoAnticapitalist: 24 Ten Tits for a Tat: 240 Bitter Tat: 12 Copy First: 30 Exploitative Tat: 19 Six Tits for a Tat: 16 Thirty Tits for Tat: 4129 Five Tits for a Tat: 22 Forty Tits for a Tat: 1972 Three Tits for a Tat: 22 Fifty Four Tits for a Tat: 25805 The Elephant: 31 Extra Bitter Tat: 28 Fox: 35 Game of Thrones: 11297 The Boy: 31 Grimace: 26 Sore Loser: 39 Every Other D: 18 Twenty Five Tits for a Tat: 2399 Fifty Three Tits for a Tat: 5487 Handshake: 28 Anty: 26 Kinda Tits for Tat: 20 Prudent Defector: 154539 Bizzarro Trigger: 25 Young Mathematician: 21 Older Mathematician: 16 Perfect Gentleman: 1953341 ``` So, it appears that Perfect Gentleman is the winner. Congratulations to Draco18, who definitely deserves his green checkmark. [Answer] # The Perfect Gentleman I don't have a good description for this bot. I stumbled into a couple of potential optimizations, tested them, fine tuned, and ended up with a bacteria that *utterly destroys* the competition. Instead, I've commented the code itself to explain what it does. ``` import random def perfectgentlemanfunc(num, i, d, c, en): if num>0 and i < 0 and d > 0 and -i%3 == 0 and d%2 == 0 and en[0] == "d": #probably very first iteration, probably facing a defector: feed it free points # defector cannot be beaten by *any* bot unless that bot # entered with a point lead. defector does some of our work for us if num >= 140: #140 threshold restricts how much we feed return "d" return "c" turn_to_betray = 130 if num > turn_to_betray and en[turn_to_betray -2] == "c" and en[turn_to_betray -1] == "c" and en[turn_to_betray] == "d": #if self, then sacrifice the lower point bot to raise the points of the higher #(better net outcome than "c/c" cooperation) # Handshake independently arrived at this same optimization if i == d: #max 50% probability of choosing different possible. May as well take it # "ccd" has a 55% chance of choosing the same # better outcomes for splitting early return "cd"[random.randint(0,1)] if i > d: return "d" return "c" #betray after betray point, or if behind by >200 #performs 6 percentage points better than not having the condition if num >= turn_to_betray or i + 200 < d return "d" else: #be nice the first turn if num == 0: return "c"; #finally, be tit-for-tat return en[-1] ``` Several values were arbitrarily chosen with alternatives tested and the values here are near-optimal at this point. Against the current spread of opposing factions, The Perfect Gentleman achieves complete dominance (100% of bacteria population) about 90% of the time (plus or minus 3 percentage points). I have not added in the Mathematicians to my tests yet, however those two should only serve to feed existing strategies and not alter the outcome greatly. It does manage a good portion of its control via propping up Defector, but that was allowed per the rules (the example strategies were fair game for targeting). It has a side effect of *also* propping up Game of Thrones, but that was unintentional as the two are indistinguishable based on the criteria I chose. Those "defector types" then have a point-advantage in round 2 and take out several troublesome neighbors as a result (the N-T4T types) and when they reface The Perfect Gentleman, they've expended their point advantage and are swiftly consumed. There is an approximate 5% chance that all Perfect Gentlemen end up paired with Defector-types in the first round and end up committing mass suicide. In which case, one of the n-T4t types achieves total domination (196 cells of 196). Very rarely one of the other types (Game of Thrones, Boy, Grimace, Sore Loser...) manage to not go completely extinct and score a point or two. Current simulation (still in progress towards 200 total games). All entries scoring 0 removed. Looks like Game of Thrones and 54-T4T split a round (195 points between them) after PG was eliminated. ``` Game: 90 Cooperator: 1 Remorseful Aggressor: 1 Copy First: 1 Six Tits for a Tat: 1 Thirty Tits for Tat: 393 Five Tits for a Tat: 1 Fifty Four Tits for a Tat: 538 Game of Thrones: 248 Perfect Gentleman: 16456 (93.2)% ##Simulation Terminated: Adding new bots ``` # Backstabbing Tit for Tat (with Forgiveness) This is basically Lucky Tit for Tat (aka Tit for Tat with Forgiveness) which is the "solved" optimal solution (for some value of "lucky"), with a twist. As we *know exactly how many rounds* the game will last, this bacteria backstabs on the final round thus ensuring a net-beneficial outcome against any other Tit for Tat and Cooperator bacteria (against itself it ends with a net zero, same as if it had cooperated). Due to the 10% carryover, this results in a long-term advantage. ``` from random import randint def titfortatbackstabfunc(num, i, d, c, enlist): if num == 199: return "d"; lucky = randint(0, 200) if lucky == 0: return "c" if num == 0 or enlist[-1] == "c": return "c" else: return "d" ``` # Bitter Tat Bitter Tat takes advantage of *any* attempts of cooperation given by the enemy when the enemy is ahead in points. Most bacteria offer an olive branch at least once during the 200 rounds, and as Bitter Tat is behind overall, it will milk those 5 points in a desperate bid for recovery. Otherwise, it tit-for-tats per the usual dominant strategy. Also, it's a little bit more of a jerk than its cousin and backstabs a round earlier and offers no forgiveness. ``` def bittertatfunc(num, i, d, c, enlist): if i < d: return "d"; if num >= 198: return "d"; if num == 0 or enlist[-1] == "c": return "c" else: return "d" ``` Bitter Tat was designed via looking at the behaviors of other bots against Tit for Tat and the patterns expressed in those results, but is not designed to explicitly counter those strategies: it is still a general purpose formula. # Extra Bitter Tat ``` def xbittertatfunc(num, i, d, c, enlist): if i < d: return "d"; if num >= 188: return "d"; if num == 0 or enlist[-1] == "c": return "c" else: return "d" ``` Extra bitter by defecting extra early. [Answer] # Anticapitalist Another simple one. For even matches (starting at the same score) behaves pretty much like TitForTat, but the main idea is trying to survive the match. ``` def anticapitalistfunc(counter, mypoints, enpoints, mylist, enlist): if mypoints >= enpoints: return "c" else: return "d" ``` --- # Gentle Defector My idea here is to defect except if my enemy is usually cooperating. Though, it begins cooperating. ``` def gentleDefectorfunc(counter, mypoints, enpoints, mylist, enlist): if enlist.count("d") * 4 > len(enlist): return "d" else: return "c" ``` --- # NeoAnticapitalist An improvement of the Anticapitalist (or so I think). I see no reason to collaborate on last turn. I also see no reason to collaborate when I am pretty sure my opponent won't. ``` def neoanticapitalistfunc(counter, mypoints, enpoints, mylist, enlist): if mypoints >= enpoints: if counter > 1: if counter == 199 or (enlist[-1] != "c" and enlist[-2] != "c"): return "d" return "c" else: return "d" ``` [Answer] # Remorseful Aggressor ``` from random import randint def remorsefulaggressorfunc(counter, mypoints, enpoints, mylist, enlist): if counter == 0: return "d" if (counter > 195 and mylist[-1] == "d"): return "d" if ((counter == 1 or counter > 2) and enlist[-1] == "d"): return "d" if (counter == 2 and enlist[-1] == "d" and enlist[-2] == "d"): return "d" if (counter >= 195 and randint(0, 200 - counter) == 0): return "d" else: return "c" ``` This is designed to "keep up" with Defector, by defecting every time against it, and also to beat tit-for-tat-based strategies. The basic idea is that we start by defecting, but if the opponent cooperated turn 1, we then cooperate twice to avoid a mutual recrimination cycle, thus avoiding too large a point penalty. (If, however, the opponent defects later on, we don't break the cycle ourself; we'll make them do it and likely lose the game as a result.) Then at the end of the game, we pick a random time within the last 5 turns to backstab the enemy, giving us one more defection than them and thus meaning that as long as we weren't too far behind on carryover points, we end up winning, without sacrificing much in terms of carryover in the process. (Randomizing the time period means that we're very likely to get in first with the backstab, also that this strategy can't be "tuned against" by aiming to backstab it one turn earlier.) [Answer] # Grim Trigger Simplistic bot, to try and fill out the competition It will cooperate, unless the enemy defects, in which case it defects unforgivingly ``` def grimtriggerfunc(I, Do, Not, Care, enlist): return "d" if "d" in enlist else "c" ``` well, seems like this doesn't work because of the ntitsfortat meta of defecting early [Answer] # Game of Thrones ``` def gameofthronesfunc(counter, mypoints, enpoints, mylist, enlist): turn_to_betray = 140 if counter >= turn_to_betray or mypoints > enpoints or "d" in enlist: return "d" else: return "c" ``` Idea here is that you can never lose by betraying, so the only reason to cooperate is if you're behind. It also has the general framework of the other T4T answers (without any forgiveness, because I'm not sure if there's much point with the other contenders here). The turn to betray might need to be changed to win, since in an even race, the T4Ter who betrays first will win, but against a very cooperative bot, you will miss out on some lifetime points. I'm not sure the right apex for this hill, so I'm just going for 140. I wouldn't be surprised if it were much earlier, though. If this ends up in a petri dish with a T4Ter who betrays earlier or a defector (ie 146 T4T), then it depends entirely on if the GoT is already ahead (it will stay ahead) or if they're even/GoT is behind, in which case the early betrayer will win. [Answer] # Lucky Tit For Tat ``` import os def luckytitfortatfunc(num, i, d, c, enlist): lucky = ord(os.urandom(1)) lucky = int(round(200 * float(lucky - 0) / 255.0)) if lucky == 0: return "c" if num == 0 or enlist[-1] == "c": return "c" else: return "d" ``` I'm pretty sure I read somewhere that tit for tat was the best strategy. I decided to make it a possibility for other programs to redeem themselves just to add some variety. Now with a proper random number generator (it gives me an advantage right?). [Answer] # The Elephant The Elephant never forgets! ``` import re def theelephantfunc(counter, mypoints, enpoints, mylist, enlist): interwoven = "".join(i for j in zip(mylist, enlist) for i in j) backwoven = interwoven[::-1] predict = re.match("^((?:..)*).*?(.).\\1(?:..)*$",backwoven) if(predict is None): return "c" predict = predict.groups()[1] if(predict == "d"): return "d" if(mypoints - enpoints >= 6): return "c" return "d" ``` The Elephant looks at the history of the fight, and tries to figure out what the enemy has planned. He looks at both his moves and his enemies! He tries to find the longest concurrent group that matches what's just happened, and takes what the enemy did just after that. If he can't work it out, the Elephant will just Cooperate, as friendship is always the answer. If he thinks his opponent will defect, he too will defect, not wanting to lose his hard earned points. If he thinks his opponent will cooperate, but his less than or exactly 6 points lead, then he will defect, to gain some foothold. And lastly, if he thinks his opponent will cooperate, and he has a strong lead, he will cooperate. [Answer] # 54 Tits for a Tat ``` def fiftyfourtitsfortatfunc(num, more, fun, me, en): tits = 54 if "d" in en[-tits:] or num >= (200-tits): return "d" return "c" ``` [Answer] # Nice Guy ``` def niceguyfunc(counter, mypoints, enpoints, mylist, enlist): if counter < 2: return "c" mylast = mylist[-1] enlast = enlist[-1] last_found_index = -1 for i, item in enumerate(mylist): if i == counter - 1: break if mylist[i] == mylast and enlist[i] == enlast: last_found_index = i if last_found_index == -1: return "c" else: if enlist[last_found_index + 1] == "c": return "c" else: return "d" ``` Tries to predict the opponents output by looking at the history. For example, if the last moves were (`c`, enemy `d`), it tries to find the last occurrence of the exact same moves. [Answer] # ~~Hackman~~ [disqualified as expected] Ok, this one will probably be ruled out of the contest, but I really feel like trying it out: ``` def hackmanfunc(counter, mypoints, enpoints, mylist, enlist): if enlist.count("#") > 0: return "c" elif counter >= 2 and enpoints > mypoints: return "d" elif counter == 198: return "d" elif counter == 199: return "#" elif counter == 0 or enlist[-1] == "c": return "c" elif counter >= 2 and enlist[-2] != "c": return "#" else: return "d" ``` Here I'm taking as base the BackstabbingTitForTat that proved to be the best in my simulations. Also, it's heavily based in using a non-used symbol `"#"`(that's why I say it will be probably ruled out). Now let me explain the conditions here: 1st: Ensure two Hackman cooperate if something went wrong. 2nd: If I'm going to lose against a different bot, at least make him lose as many points as possible, so it's not a huge enemy afterwards. 3rd: Betray one turn before, so wins vs Backstabbing using "#" instead of "d" makes me get 0 points instead of -1 and also communicate with other Hackman who has less points, so he stops defecting. [Answer] # Bizzaro Does the exact opposite of tit for tat. When someone is kind to him he shows his love by being evil, and when someone is mean he shows revenge by being good. Heavily based on tit for tat. ``` def bizzarofunc(counter, mypoints, enpoints, mylist, enlist): if counter==0 or enlist[counter-1] == "c": return "d" else: return "c" ``` [Answer] # 6 Tits for a Tat ``` def sixtitsforatatfunc(num, more, fun, me, en): if "d" in en[-6:] or num >= 194: return "d" return "c" ``` Tit for Tat arms race is happening :) [Answer] ## Ten Tits for a Tat ``` def tentitsforatatfunc(num, more, fun, me, en): if "d" in en[-10:] or num >= 190: return "d" return "c" ``` Defects earlier, and also defects if its opponent has defected in the last ten turns. ## CopyFirst ``` def copyfirstfunc(num, mypoints, enpoints, myhistory, enhistory): if num == 0 or num >= 197: return "d" else: return enhistory[0] ``` This defects the first round, then does whatever the opponent did the first round, until the 197th round, when it backstabs. ## Forty Tits for a Tat ``` def fourtytitsforatatfunc(num, mypoints, enpoints, myhistory, enhistory): if "d" in en[-40:] or num >= 150: return "d" return "c" ``` If the opponent defected in the last 40 turns, defect, otherwise cooperate. Backstab on the last 50 turns. ## Three Tits for a Tat If the opponent defected in the last 3 turns, defect, otherwise cooperate. Backstab on the last 5 turns. This program has stolen the lead from Tit for Two Tats by a narrow margin. ``` def threetitsforatatfunc(num, mypoints, enpoints, myhistory, enhistory): if num == 0 or num==1 and enhistory[-1]=="c" or num==2 and enhistory[-1]=="c" and enhistory[-2]=="c": return "c" if enhistory[-1] == "d" or enhistory[-2] == "d" or enhistory[-3] == "d" or num >= 195: return "d" else: return "c" ``` ## Five Tits for a Tat ``` def fivetitsforatatfunc(num, more, fun, me, en): if "d" in en[-5:] or num >= 194: return "d" return "c" ``` If you can't figure out what this one does, you're an idiot. Also backstabs one round earlier. [Answer] # Grimace ``` def grimacefunc(I, Do, Not, Care, enlist): if round < 123: return "d" if "d" in enlist else "c" return "d" ``` [Answer] # Every Other D ``` def everyotherdfunc(counter, mypoints, enpoints, mylist, enlist): if counter % 2 == 0: return "d" else: return "c" ``` # Every Other C ``` def everyotherdfunc(counter, mypoints, enpoints, mylist, enlist): if counter % 2 == 0: return "c" else: return "d" ``` [Answer] # Predictable Mathematicians: ## Young Mathematician New to the harshness of the world ``` import math def ymathfunc(num, mpoints, enpoints, mlist, enlist): if(math.sin(num) + 0.8 > 0): return 'c' else: return 'd' ``` ## Older Mathematitian More experienced in these matters ``` import math def omathfunc(num, mpoints, enpoints, mlist, enlist): if(math.cos(num) + 0.8 > 0): return 'd' else: return 'c' ``` I doubt either of these will do well, but at least they'll add ways for others to get points! [Answer] # Randomized Tit For Tat ``` import os def randomtitfortatfunc(forgot, ten, var, iables, enlist): luck = enlist.count("d") + 1 choice = ord(os.urandom(1)) choice = int(round(luck * float(choice - 0) / 255.0)) if choice == 0: return "c" return "d" ``` Tit For Tat, but randomized. This is not going to win any prizes (unless I'm really lucky). Now with random numbers generated from a proper source. [Answer] # Exploitative Tat Exploitative Tat tries to play the following strategies: * Defect when behind. It's the only way to catch up. * Cooperate against tit-for-tat and similar strategies. It's the only way to get a good long-term score. * Defect against always-cooperators and other chumps. * Defect 5 rounds early. Here's the code: ``` def exploitativetatfunc(num, mypoints, enpoints, mylist, enlist): if mypoints < enpoints: return "d" if num >= 195: return "d" if num == 0: return "c" # Test defect, and keep defecting as long as they'll allow if (num == 5 or num >= 8) and all(choice == "c" for choice in enlist): return "d" # Recover if that goes wrong, and they were nice. if (num == 6 or num == 7) and all(choice == "c" for choice in enlist[:4]): return "c" # Otherwise, tit for tat. return enlist[-1] ``` [Answer] # 30 Tits for a Tat ``` def thirtytitsfortatfunc(num, more, fun, me, en): tits = 30 if "d" in en[-tits:] or num >= (200-tits): return "d" return "c" ``` [Answer] but what if... the next answer was not grim trigger or something for tat I present # Anty ``` def antyfunc(counter, mypoints, enpoints, mylist, enlist): if counter > 150: return "d" if not "c" in enlist[-2:]: return "d" if enpoints >= mypoints: return "d" else: return "c" ``` [Answer] ## Fox ``` def foxfunc(counter, mypoints, enpoints, mylist, enlist): if counter > enpoints: return "d" return "c" ``` Defects if the round number is greater than the enemies points, cooperates otherwise. ## The Boy ``` def boyfunc(counter, mypoints, enpoints, mylist, enlist): if counter!=0 and enlist[-1]=="c" and counter <= 194 or enpoints+10<mypoints: return "c" return "d" ``` Cooperates first round, then acts for tit for tat but backstabs on the last five rounds, and defects if it isn't ten points ahead. ## 53 tits for a tat ``` def fiftythreetitsfortatfunc(num, more, fun, me, en): tits = 53 if "d" in en[-tits:] or num >= (200-tits): return "d" return "c" ``` You all know what this is :) [Answer] # Twentyfivetitsforatat ``` def twentyfivetitsfortatfunc(num, more, fun, me, en): tits = 25 if "d" in en[-tits:] or num >= (200-tits): return "d" return "c" ``` # Kinda titsforatat ``` def kindatitsfortatfunc(num, more, fun, me, en): tits = 54 if "c" in en[-tits:] or num >= (200-tits): return "c" return "d" ``` [Answer] # Prudent Betrayer ``` def PrudentBetrayer(counter, mypoints, enpoints, mylist, enlist): # Am I ahead, even if he betrays first? if mypoints > enpoints + 5: if counter == 0: return "c" else: return enlist[-1] # Can I catch up if I betray first? elif mypoints + 5 > enpoints: if counter == 0: return "c" elif counter > 130: return "d" else: return "d" if "d" in enlist else "c" # can't win -> kill his score else: return "d" ``` Assumes it is fighting an `n-tits-for-a-tat` bot. If it has the score to be betrayed and still win, it will let the other bot hit it first (playing as tit for tat.) If it can win only when it betrays first, It will betray on round 130, well before any current bot. If it is many points behind its opponent, it will just play defector in an attempt to lower the unsuspecting bots score. --- # Handshake ``` import random def handshakefunc(num, me, him, m, en): handshake = "cdccd" # For the first few rounds, give the handshake. if num < len(handshake): if m == en: return handshake[num] return "d" if en[:len(handshake)] == handshake: if me > him: return "d" if me == him: return "ccd"[random.randint(0,2)] return "c" return "d" ``` Uses the pattern `cdccd` on the first five rounds, to find out if it is with itself. If so, it will try to max its points by having the bot with more points always defect, while the other always cooperates. If it finds it is fighting an enemy, it will play the defector. In my tests, I find it dose well if it makes up a significant portion of the population. When it dose not have a chance to fight itself, it will basically be reduced to a defector. EDIT: Clearly from the scores, their are to many bots for this to work well. It will still win if fighting just the top few... --- # Bizzaro Trigger ``` def bizzaroTriggerfunc(round,ms,ts,mm,tm): if round==1:return 'c' if 'c' in tm:return'd' return 'c' ``` Always cooperate, unless your opponent ever cooperates with you, in which case you defect. Always. [Answer] # FakeShake takes advantage of handshake- does a handshake then just defects while handshake trusts it. When it meets itself, however, it does the 'real' handshake. If it meets a different bot it plays tit for tat, with a betrayal at the end. This feels kinda mean... ``` import random def fakeshakefunc(num, i, d, m, enlist): secret_handshake="cdccdd" handshake= "cdccd" #checks if it is meeting itself if enlist[:len(secret_handshake)] == secret_handshake: if me > him: return "d" if me == him: return "ccd"[random.randint(0,2)] return "c" #does handshake's handshake,if the bot is not handshake or fakeshake it plays T4T if num < len(handshake): if m == enlist: return handshake[num] if i < d or num>= 198: return "d"; if num == 0 or enlist[-1] == "c": return "c" else: return "d" if enlist[:len(handshake)] == handshake: return "d" if i < d or num>= 198: return "d"; if num == 0 or enlist[-1] == "c": return "c" else: return "d" ``` One problem with this is that if it meets handshake and it has more points, it thinks its playing itself. I'm a newbie to python and this site (in fact this is my first answer) so make sure to tell me if I've made any stupid mistakes! ]
[Question] [ Obviously, code golfing is all about making the most of the least code. Who really cares what the actual output is? While [we have had](https://codegolf.stackexchange.com/questions/13074/shortest-code-for-longest-output) a challenge for highest input-to-output *ratio*, this is a call for **most finite and deterministic** output with given code lengths. Ironically, this challenge is then not [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). **Rules:** 1. Write three independent snippets (not full programs/functions). 2. The snippets must be in the same language. 3. Score is total number of outputted bytes. 4. Outputs may be in the form of a result, STDOUT, etc. 5. The snippets may not cause any error. 6. The snippets may cause different forms of output. 7. Trailing newline characters are not counted. 8. The first snippet must be 1 byte or the minimum length that produces at least 1 byte of output. 9. The second snippet must be one byte longer than that. 10. The third snippet must be two bytes longer than the first. [Answer] # gs2, 412 + 5.37 \* 10902 + 1010903.1 bytes 1. `f` pushes `1\n2\nFizz\n4\nBuzz\n...\nFizzBuzz` as a `412`-byte string. 2. `fô` prints all of its permutations, so `412! * 412` characters. 3. `fôô` prints all permutations of that 412!-element list, where each element is 412 characters long, so `412 * (412!)!` bytes. EDIT: To put things into perspective, this is at least > > 101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 > > > bytes, dwarfing all of the other answers here so far. [Answer] # Pyth, 26 + 1140850688 + (>4.37 × 1020201781) I have no idea if it is possible to calculate the exact length of the output for the third program. I can only give boundaries. It'll print something between `4.37 × 10^20201781` and `1.25 × 10^20201790` characters. ``` G yG yyG ``` This prints: ``` abcdefghijklmnopqrstuvwxyz ['', 'a', 'b', ..., 'abcdefghijklmnopqrstuvwxyz'] [[], [''], ['a'], ['b'], ['c'], ..., ['', 'a', 'b', ..., 'abcdefghijklmnopqrstuvwxyz']] ``` The first one prints the alphabet, the second one all subsets of the alphabet, and the third one the subsets of the subsets of the alphabet, which is a list of length `2^(2^26) ~= 1.09 × 10^20201781`. Obviously no computer ever will be able to compute this large list and output it. [Answer] ## CJam, 17 + 34 + 72987060245299200000 = 72987060245299200051 bytes of output For easier comparison, this is approximately 7.3 \* 1019. ``` P PP Ke! ``` Prints: ``` 3.141592653589793 3.1415926535897933.141592653589793 012345678910111213141516171819012345678910111213141516171918012... ``` Well, the last one consists of all permutations of `[0 1 2 ... 19]` with the numbers squished together. I wouldn't recommend trying it out... (Try it as `4e!` though to get a taste.) Test it here: [Program 1](http://cjam.aditsu.net/#code=P), [Program 2](http://cjam.aditsu.net/#code=PP), [Sane version of program 3](http://cjam.aditsu.net/#code=4e!). [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 1.2 × 102568 bytes of output ``` ȷ ȷ* ȷ*! ``` Calculates **1000**, **10001000** and **10001000!**. Try it online: [first program](http://jelly.tryitonline.net/#code=yLc&input=) | [second program](http://jelly.tryitonline.net/#code=yLcq&input=) | [third program (modified)](http://jelly.tryitonline.net/#code=OCoh&input=) For byte counting purposes, `ȷ` can be encoded as the byte 0xa0 in [the current version of Jelly](https://github.com/DennisMitchell/jelly/tree/e27683dee67e6a23f0651e839a4a4bf96322fe91). ### How it works In Jelly, `ȷ` can be used inside number literals as Python's `e` (scientific notation). For example, `3ȷ4` returns **30000**. In Jelly's scientific notation, the coefficient defaults to **1** and the exponent defaults to **3**, so `ȷ`, `1ȷ3` and `1000` all return the same number. ``` ȷ Return 1000. ``` ``` ȷ Return 1000. Parse the remaining code as a program with input 1000. * Hook; compute 1000 ** 1000. ``` ``` ȷ Return 1000. Parse the remaining code as a program with input 1000. ! Return 1000!. * Fork; compute 1000 ** 1000!. ``` [Answer] ## [Hexagony](https://github.com/mbuettner/hexagony), 1 + 3 + 6 = 10 bytes of output Well... not a very impressive score, but at least I can assert that it's optimal. With a single bytes it's impossible to print something *and* terminate, so we start with two bytes: ``` !@ ``` The unfolded code is ``` ! @ . . . . . ``` This prints a byte and terminates. For three bytes of code, we can print three bytes of output. For instance: ``` o!@ ``` or unfolded: ``` o ! @ . . . . ``` prints `111`. Any lower-case letter from `d` to `z` works and prints its character code. Those are the only 23 ways to print 3 bytes with 3 bytes of code. Finally, for four bytes, there are 169 ways to print 6 bytes. Since none of them do anything more interesting (except for odd control flow) than the straight-forward solution, I'll present that: ``` o!!@ ``` Unfolded: ``` o ! ! @ . . . ``` You guessed it. It prints `111111`. How do I know these are optimal? I adapted the brute forcer [I wrote for the truth machine catalogue](https://codegolf.stackexchange.com/a/62812/8478) to look for maximum finite output in 7000 cycles (I don't think you can write a busy beaver with 4 bytes, that runs for 7000 cycles but still terminates later.) [Answer] # Python 3, 1 + 22 + 23 = 56 ``` 9 id abs ``` Output ``` 9 <built-in function id> <built-in function abs> ``` Print 9 and then the definition for `id` and `abs`. [Answer] ## [Labyrinth](https://github.com/mbuettner/labyrinth), 1 + 2 + 4 = 7 bytes Another low score, which I'm mainly posting because I've proven it to be optimal for the language. Like Hexagony, Labyrinth can't print and terminate with a single byte, so we start with two bytes: ``` !@ ``` Prints a zero and terminates. For three bytes, we can't beat the naive solution: ``` !!@ ``` This prints two bytes before terminating. There are a few other options, like printing `-1` with `(!@` or `~!@` or `,!@`. There is one pretty cool solution though which uses source code rotation: ``` !>@ ``` This prints a zero, then shifts the source to become `@!>`. At that point it hits a dead end, turns around, and executes the `!` again on the way back, before terminating. For four bytes, it's a bit more fun, because the *only* way to print 4 characters is to use the above trick: ``` !!>@ ``` Print two zeroes, shift to `@!!>`, print another two zeroes. In all of these cases I'm ignoring that you can also print a byte with `\` or `.`, because those will always print exactly one byte, whereas `!` will print at least one and potentially several. [Answer] ## Seriously, 2025409 bytes 1 byte: ``` N ``` (produces 11,756 bytes of output) 2 bytes: ``` Nñ ``` Produces 153,717 bytes of output 3 bytes: ``` 9!! ``` Produces 1,859,936 bytes of output Seriously does not yet feature things like "all subsets" or "all combinations", so scores relatively low on this. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 313 The current version of the language ([3.1.0](https://github.com/lmendo/MATL/releases/tag/3.1.0)) is used, which is earlier than this challenge. 1. Code (predefined literal: produces number 2, which is implicitly printed): ``` H ``` Output (1 byte): ``` 2 ``` 2. Code (produces number pi, which is implicitly printed with 15 decimals): ``` YP ``` Output (17 bytes): ``` 3.141592653589793 ``` 3. Code (numbers from 1 to 99, which are printed by default with spaces in between): ``` 99: ``` Output (295 bytes): ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 ``` [Answer] # Processing, 39 bytes ### Deterministic **1 byte**: ``` print(X); ``` Outputs `0`. **9 bytes**: ``` print(PI); ``` Outputs `3.1415927` **29 bytes**: ``` print(P3D); ``` Outputs `processing.opengl.PGraphics3D` ## Non-deterministic, >= 129 bytes **>= 32 bytes:** ``` print(g); ``` Outputs `processing.awt.PGraphicsJava2D@ + [mem-address]` **>= 32 bytes:** ``` print( g); ``` Outputs `processing.awt.PGraphicsJava2D@ + [mem-address]` **>= 65 bytes:** (Thank you to @anOKsquirrel for this suggestion.) ``` print(g,g); ``` Outputs ``` processing.awt.PGraphicsJava2D@ + [mem-address] processing.awt.PGraphicsJava2D@ + [mem-address] ``` [Answer] # JavaScript, 1 + 3 + 18 = ~~18~~ 22 Not a very interesting answer but probably the best JavaScript is capable of. ``` alert(1) alert(.1) alert(1/9) ``` *Added 4 score thanks to [@UndefinedFunction](https://codegolf.stackexchange.com/users/42844/undefinedfunction)!* Outputs as text: ``` 1 0.1 0.1111111111111111 ``` [Answer] # Bash, 1726 bytes (I fixed it now. Please consider upvoting.) **1 byte**: `"` Outputs: ``` > ``` **307 bytes:** `id` Outputs: ``` uid=501(geokavel) gid=20(staff) groups=20(staff),701(com.apple.sharepoint.group.1),12(everyone),61(localaccounts),79(_appserverusr),80(admin),81(_appserveradm),98(_lpadmin),33(_appstore),100(_lpoperator),204(_developer),395(com.apple.access_ftp),398(com.apple.access_screensharing),399(com.apple.access_ssh) ``` **1418 bytes:** `zip` (Prints to STDOUT) ``` Copyright (c) 1990-2008 Info-ZIP - Type 'zip "-L"' for software license. Zip 3.0 (July 5th 2008). Usage: zip [-options] [-b path] [-t mmddyyyy] [-n suffixes] [zipfile list] [-xi list] The default action is to add or replace zipfile entries from list, which can include the special name - to compress standard input. If zipfile and list are omitted, zip compresses stdin to stdout. -f freshen: only changed files -u update: only changed or new files -d delete entries in zipfile -m move into zipfile (delete OS files) -r recurse into directories -j junk (don't record) directory names -0 store only -l convert LF to CR LF (-ll CR LF to LF) -1 compress faster -9 compress better -q quiet operation -v verbose operation/print version info -c add one-line comments -z add zipfile comment -@ read names from stdin -o make zipfile as old as latest entry -x exclude the following names -i include only the following names -F fix zipfile (-FF try harder) -D do not add directory entries -A adjust self-extracting exe -J junk zipfile prefix (unzipsfx) -T test zipfile integrity -X eXclude eXtra file attributes -y store symbolic links as the link instead of the referenced file -e encrypt -n don't compress these suffixes -h2 show more help ``` [Answer] # Befunge, 2 + 4 + 6 = 12 ``` .@ ..@ ...@ ``` Any snippet shorter than length 2 either cannot output, or cannot terminate its output. In Befunge, `.` outputs the top value of the stack as an integer, followed by a space. A space is not a newline, so it is included in the count. Additionally, the stack is "infinitely" filled up with 0's, so the programs output (respectively): ``` 0 0 0 0 0 0 ``` [Answer] # SmileBASIC, 1+4+10= 15 bytes ### Program 1: The shortest way to print something is with ? (PRINT) and a single character. This can be either a number or a variable name, and it doesn't matter since they're all the same length. ``` ?1 1 ``` ### Program 2: Now we have access to a few more things. The longest expression which can be made would be one of the constants #Y, #L, or #R, which have values 128, 256, and 512, respectively. However, instead of that, I use a comma so that (in this case) 3 extra spaces are printed. ``` ?1, 1 ``` ### Program 3: With 3 characters, you can write E-notation numbers: ``` ?1E9 1000000000 ``` [Answer] # HQ9+, 71304 ``` 9 ``` Prints the 11,884-character lyrics of "99 bottles of beer" ``` 99 ``` Prints "99 bottles of beer" twice ``` 999 ``` Prints "99 bottles of beer" three times [Answer] # Japt `-Q`, Outputs `1.0123378918474279e+150` bytes The full number is ``` 1,012,337,891,847,427,807,734,770,805,740,683,255,348,979,141,331,502,541,182,800,555,980,960,810,784,280,906,237,433,006,787,771,597,919,201,659,212,694,207,520,340,705,280,000,000,000,000,000,000,568 ``` bytes. ## # 1 ``` M ``` Outputs ``` {"P":3.141592653589793,"Q":1.618033988749895,"T":6.283185307179586} ``` For 67 bytes. (Credit to Shaggy) ## # 2 ``` LÆ ``` Outputs ``` [null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null] ``` which is 501 bytes. (Credit to @Shaggy) ## # 3 ``` ;Eá ``` Outputs all permutations of the 95 printable ASCII characters in the format `["...","...","..."...]`, which is \$1,012,337,891,847,427,807,734,770,805,740,683,255,348,979,141,331,502,541,182,800,555,980,960,810,784,280,906,237,433,006,787,771,597,919,201,659,212,694,207,520,340,705,280,000,000,000,000,000,000,001\$ bytes of output. --- You can get an infinite amount of output bytes if you use the `-F` flag in Japt. What it does is that if the last expression of the program evaluates to false, it outputs the value specified in the flag instead. So I guess the score for Japt`-F"Insert Super Long String Here"` is infinity. [Answer] # [Malbolge](https://www.lscheffer.com/malbolge.shtml), 1 + 2 + 3 = 6 bytes ``` (=aN (&a`M (=a`_L ``` Try it online: [first](https://tio.run/##y03MScrPSU/9/1/DNtHv/38A), [second](https://tio.run/##y03MScrPSU/9/19DLTHB9/9/AA), [third](https://tio.run/##y03MScrPSU/9/1/DNjEh3uf/fwA) Outputs: ``` r ll xxx ``` Brute forced. Assumes `\0` is not a valid output character With `\0`: ``` cP cbO cbaN ``` Outputs: ``` \0 \0\0 \0\0\0 ``` [Answer] # [scg](http://github.com/an-OK-squirrel/scg), 1 + 27 + 188 = 216 First one: ``` 1 ``` Just prints 1, as the stack is outputted at the end of program. Second: ``` .d ``` Prints debug info, which should look like this: ``` Stack: [] Array Markers: [] ``` Third: ``` 99r ``` adds 99 to stack, then uses range function. Outputs 01234567891011.... (this is one of those times I wish I implemented the factorial function. I haven't) [Answer] ## Marbelous 1 + 1 + 2 = 4 bytes of output Marbelous is hamstrung here by having two-byte instructions. Pointless comments or unnecessary whitespace are the only ways to get an odd byte count. print "A" and terminate: ``` `A ``` print "B" and terminate, with an empty EOL comment ``` `B# ``` print "CD" and terminate: ``` `C`D ``` [Answer] ## Mathematica, 6 + 461 + 763 = 1230 ~~1225~~ ~~618~~ ~~163~~ bytes of output ``` % (* -> Out[0] *) ?D (* -> D[f, x] gives the partial derivative ∂ f/∂ x. n n D[f, {x, n}] gives the multiple derivative ∂ f/∂ x . D[f, x, y, …] differentiates f successively with respect to x, y, …. D[f, {{x , x , …}}] for a scalar f 1 2 gives the vector derivative (∂ f/∂ x , ∂ f/∂ x , …). 1 2 D[f, {array}] gives a tensor derivative. *) ?Do (* -> Do[expr, {i }] evaluates expr i times. max max Do[expr, {i, i }] evaluates expr with the variable i successively taking on the values 1 through i (in steps of 1). max max Do[expr, {i, i , i }] starts with i = i . min max min Do[expr, {i, i , i , di}] uses steps di. min max Do[expr, {i, {i , i , …}}] uses the successive values i , i , …. 1 2 1 2 Do[expr, {i, i , i }, {j, j , j }, …] evaluates expr looping over different values of j, etc. for each i. min max min max *) ``` Currently, the last two use `Information` to get documentation about the symbols, which can output many bytes. Note that this was run on the 10.1 command-line `MathKernel`. [Answer] # Javascript, 72 bytes This works in the [Mozilla JSShell](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Introduction_to_the_JavaScript_shell) Javascript command line interpreter. **1 byte:** `1` Outputs `1` **35 bytes:** `gc` Outputs ``` function gc() { [native code] } ``` **36 bytes:** `run` Outputs ``` function run() { [native code] } ``` [Answer] # Octave, 2818417 bytes ``` e ``` 14 bytes for `ans = 2.7183\n` ``` pi ``` 14 bytes for `ans = 3.1416\n` ``` doc ``` Display the entire documentation. 2818389 bytes, counted with `dd` [Try it online!](https://tio.run/##S0oszvj/Pz@5JLEsVUFXN7UsMUchJT9ZoUYhJUXBTkE/JbVMP680J@f/fwA "Bash – Try It Online") because `evalc` didn't work. [Answer] # SmileBASIC 4, 1 + 13 + 15 = 29 bytes This is going to be similar to 12Me21's SmileBASIC 3 answer, with a couple adjustments. ## 1 As before, the shortest amount of code to produce some output is 2 bytes: `?` (`PRINT`) and some single-byte expression. The consensus is that `PRINT` does *not* produce a newline when it advances to the next line, due to the way the text screen works. So this results in one byte of output. ``` ?1 1 ``` ## 2 With 3 bytes, we can do something different. SB4 introduces `INSPECT`, aliased as `??`, which prints info about a single value. If we give it an empty string, for example, this can produce much more output than SB3 could. This gets us 13 bytes. ``` ??" STRING: (0)"" ``` ## 3 We have 4 bytes to work with, so we have to decide what we should do to maximize our output. Going with `??` is a safe bet; we only have 2 bytes to use on our expression, but the additional output of `INSPECT` is basically free. So I use it to print a label string. This is 15 bytes. ``` ??@A STRING: (2)"@A" ``` The total is 29 bytes. [Answer] # [Julia 0.6] REPL, 94354 bytes ``` 9[enter] # output 9, 1 byte [tab][tab] # output all possible auto completes for the empty string, 31451 bytes [tab][tab][tab] # output all possible auto completes for the empty string twice, 62902 bytes ``` There is nothing special about 0.6 here, I just don't have 1.0 installed locally. Not counting command prompts as output, or `[enter]` as input, and requiring each to be independent of the previous. # [Julia 1.0](http://julialang.org/) program, 562 bytes ``` dump(!) dump(!!) dump(!!!) ``` Optimizing output to `STDOUT` here. I'm not sure how to even calculate the byte size for results, eg `!` returns a function with 3 methods... there are multiple reasonable interpretations for how many bytes that represents, and most of them aren't easy to count. I'm not sure if this is optimal, it just builds up an anonymous function with a long name and prints the name. [Try it online!](https://tio.run/##yyrNyUw0rPj/P6U0t0BDUZMLQiMYipr//wMA "Julia 1.0 – Try It Online") [Answer] # Microscript II, 23+47+71=141 bytes 1: `C` The stringification of continuations is not strictly defined by the specs, but in the reference implementation this, run on its own, yields a 23 byte string. `<Continuation @t=\d\d\dus>` (`\d` represents a digit, which digits varies). On my computer, at least, this does, in fact, always take between about 180 and about 400 microseconds to run. The first use I've ever actually had for this instruction. 2: `CP` 47 bytes of output- the output from the first one twice with a newline in between. 3: `CPP` Fairly straightforward. 71 bytes of output- the output from the first one three times with newlines in between. [Answer] ## PowerShell, ~4300 bytes Approximate output length, given the system that it's run on. All the snippets below are deterministic, in that if given the same initial state of the computer will output the same text, just that in practice the output could change from execution to execution. ### Length 1, 107 bytes ``` ? ``` This is an alias for `Where-Object`. It will output a user prompt asking for additional information: ``` cmdlet Where-Object at command pipeline position 1 Supply values for the following parameters: Property: ``` ### Length 2, 113 bytes ``` rp ``` This is an alias for `Remove-ItemProperty`. It will output a user prompt asking for additional information: ``` cmdlet Remove-ItemProperty at command pipeline position 1 Supply values for the following parameters: Path[0]: ``` Just barely longer than the length 1 snippet. ### Length 3, ~4100 bytes ``` gps ``` This is an alias for `Get-Process` which will output a formatted table of all running processes on the system: ``` Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 85 8 1232 4452 46 0.14 544 armsvc 151 10 6800 9888 39 0.58 5116 audiodg 480 25 6060 17200 124 0.84 4536 AuthManSvr ... ``` [Answer] ## Javascript, 312 + 318 + 624 = 1254 bytes of output ``` $ $$ $+$ ``` The two functions `$` and `$$` are available in all major browsers' consoles, as shortcuts for `document.querySelector` and `document.querySelectorAll` respectively. Different browsers have native code coerced to strings somewhat differently from each other, and IE uses plain JS in each function resulting in much longer representation. For the byte count, I'm taking the length of the string representation of each rather than the sometimes-modified console display, so the total bytes are, for each of the following browsers: * Chrome: 56 + 57 + 112 = 225 bytes * IE: 312 + 318 + 624 = 1254 * Firefox: 33 + 33 + 66 = 132 (I'm considering the IE result to be the "official" count because it's the longest.) For non-console browser environments, the largest outputs come from the following: ``` 1 !1 // Or '{}' if being fed to a function instead of beginning a statement Map ``` Results length by browser: * Chrome: 1 + 5 (or 15 if `{}` is usable) + 32 = 38 (or 48) bytes * IE: 1 + 5 (or 15 if `{}` is usable) + 38 = 44 (or 54) * Firefox: 1 + 5 (or 15 if `{}` is usable) + 36 = 42 (or 52) These two sets of input produce the largest output possible in all of these browsers and consoles. To prove this, let's check all alternatives: * Existing variables: We can find all native available variables with maximum three characters with `Object.getOwnPropertyNames(window).filter(x=>x.length<=3)`, and then `map` them to their string outputs to determine the larger ones. (Note that in some browsers such as Firefox, certain special console variables cannot be accessed this way as they're not a property of the window.) * JS has a limited number of types of literals that can be created with so few characters: + Per the spec, decimal numbers must be a decimal digit (`1234567890`) optionally followed by `.` and more decimal digits and/or an exponent part, or be a `.` followed by one or more decimal digits and optionally an exponent part. Other kinds of numbers must be either `0o`, `0x`, or `0b` (or uppercase forms), followed by one or more digits. For our purposes, we can deduce the following: - There are only ten single-character numbers, which are the integers 0 through 9. The only two-character numbers are integers 0-99 (0-9 by adding a decimal after), and the numbers 0.1 through 0.9 by omitting the initial zero. The only three-character numbers are 0-999, including 0x0-0xf, 0o0-0o7, 0b0, and 0b1, the exponential 1e1 through 9e9 (10 characters), and the numbers 0.1-9.9 and .01 through .99. While not technically a number literal, NaN can also be referenced in three characters. + Strings, arrays, and regexps, each of which can take at max only a single character of content. An array could be filled with `$`, a comma, or a single-digit number. Arrays with only one element are coerced to strings as the element itself. Empty arrays become empty strings. + Depending on environment, it may or may not be possible to create simple objects with three characters. Normally, `{}` alone at the beginning of a script would be treated as an enclosure rather than creating an object. `eval({})` returns undefined, `eval({$})` returns the `$` function. There are insufficient characters to surround the `{}` in `()`. * There are no keywords that are short enough to use. The keywords `if`, `in`, `do`, `new`, `for`, `try`, `var`, and `let` would all require a minimum of two other characters to use, exceeding the limit. * Available unary operators include `~`, `+`, `-`, `!`, `++`, and `--`. The two-character operators can only be used with a single character variable, of which there is only one (`$`), which yields `NaN`. The other four operators can be used with any one- or two- character value, of which there are: + Several variables. (On some consoles `$`, `$_`, `$0`, `$1`, `$2`, `$3`, `$4`, `$`, `$$`, `$x` ). When used with these operators, the results are limited to `-1`, `true`, `false`, and `NaN`. + 109 numbers. Results: Integers -100 through 99, -0.9 through -0.1, `true`, `false`. + Empty strings. Results: `-1`, `0` (`-0` becomes `0` on toString), `true`. + The results of any of the one-character values above associated with a one-character unary operator. New results: None. * Usable binary operators (which must be a single character to have room left for both operands) are `+`, `-`, `*`, `/`, `%`, `<`, `>`, `&`, `|`, `^`. They can only be used with a single-character value on each side. Options for values include `$` and integers 0-9. Results of all combinations of these include `Infinity`, some numbers and binary values mentioned above, and numerous fractions which are coerced to strings of 19 characters or less (`1/7` is 19 characters, unlike `1/9` suggested above which is only 18), and the text representation of `$` preceded or followed by a single-digit integer or itself. * Finally, all remaining operators and expressions: The member operator `.` requires an existing variable and a identifier referring to a property. All uses of this here result in `undefined`. Surrounding a value in `(` `)` returns the value, as does assigning it with `=`. Using `()` or `` to call a value as a function results in undefined or errors with all available values. Adding all this up, there are a grand total of 1651 possible outputs when using a Chrome console. The longest outputs for one, two, and three characters are from `$`, `$$`, and `$+$` respectively. [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 2+5+18=25 bytes 1: `Ff` yields ([Try it online!](https://tio.run/##S0n@/98t7f9/AA "dc – Try It Online")): ``` 15 ``` 2: `Fdf` yields ([Try it online!](https://tio.run/##S0n@/98tJe3/fwA "dc – Try It Online")): ``` 15 15 ``` 3: `Fd^f` yields ([Try it online!](https://tio.run/##S0n@/98tJS7t/38A "dc – Try It Online")) ``` 437893890380859375 ``` None of which are particularly interesting, but `dc` isn't really great for spitting out piles of output. I do like that each answer builds on the previous. Anyway, `F` is just the number 15; `f` prints the entire stack; `d` duplicates top-of-stack; `^` raises next-to-top-of-stack to the power of top-of-stack (in this case, 15^15). I don't believe this can be topped in `dc`. [Answer] # Ruby, 3+14+28 = 45 bytes Why did I do this. ``` p ``` Prints `nil`. ``` $> ``` Prints `#<IO:<STDOUT>>`. ``` dup ``` Prints something along the lines of `#<Object:0x0000000003610988>`. ``` irb ``` Launches an instance of Interactive Ruby. Upon exiting, the returned object is `#<IRB::Irb: @context=#<IRB::Context:0x0000000003643040>, @signal_status=:IN_EVAL, @scanner=#<RubyLex:0x00000000038900a0>>` for 121, but since it requires you to press `^D` or something to actually exit the irb instance, I wasn't sure if it'd actually count as a solution in "3 bytes" so I'm not actually including it in the score unless it gets an OK. [Answer] # Perl 6, 53 (17 + 18 + 18) bytes ``` e -e e*e ``` 1. `e` outputs \$e\$ to 15 decimal places 2. `-e` outputs \$-e\$ to 15 decimal places 3. `e*e` outputs \$e^2\$, but oddly, it gives one more decimal place ]
[Question] [ Given two strings of digits, determine which string, if any, has the earliest digit which is lower than the other string's digit at the same index. Do note that this differs from alphabetization, as shown in the following examples: ### Examples Given inputs `12345000` and `1233999999`, the second string would have the earliest lower digit. ``` 12345000 1233999999 ^ same value ^ same value ^ same value ^ second is lower ^^^^^^ irrelevant ``` Given strings `99` and `998`, neither has the earliest lowest digit, since `99` equals `99`, and the `8` has no digit to compare against. ``` 99 998 ^ same value ^ same value ^ irrelevant ``` ### Additional specification * Input/output can be taken/given in any reasonable format. * You can output any three consistent values to represent choosing the first input, the second input, or neither. (similar to [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'")) * Alternatively, you may use the standard output method of three-way comparison of your language of choice (if one exists) * You may assume that there will be no leading 0s in input. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. ### Test cases Output is in the form `<` for first input, `>` for second input, and `=` for equal. ``` 999 999 = 115 116 < 116 115 > 870 789 > 33 3333 = 3333 33 = 20 2100 < 19 1200 > 2100 20 > 1200 19 < 1234 1234 = 4321 5432 < 5678 5432 > 99 998 = 12345000 1233999999 > ``` [Answer] # [Python 2](https://docs.python.org/2/), 28 bytes ``` lambda*l:cmp(*zip(*zip(*l))) ``` [Try it online!](https://tio.run/##NY7dCoMwDIXv8xShV1bCaFqdreCTzF04N5lQf1Bvtpd3rcMDOQnkkHzzZ3tPo967qt59MzyeTerLdpiT9Nuf5qWUe9usrxUrvLWXdfb9lggSErtpwRb7EYUQzjkKBcw5MV/BFooK68AYMkGgFWlWCtgR69i1ySgaZEYz5cEhvxb2Px3H7BHKlVIxaNyh8OpEqEch7wiRYqUtchyYJSDivPTjlnRJWAT8Hw "Python 2 – Try It Online") Uses `zip`'s truncating the to the shorter list. Test harness from @SuperStormer. Python 2 is needed for `cmp`. [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` ±ḟIz- ``` [Try it online!](https://tio.run/##yygtzv7//9DGhzvme1bp/v//P9pQx0jHWMdUx0zHAARjYSLmOpYIGAsA "Husk – Try It Online") Input as lists of digits, output as `-1` (first wins), `0` (neither wins) or `1` second wins. Would be 1-byte shorter to output negative, zero or positive, but [Husk](https://github.com/barbuz/Husk) doesn't have a 3-way comparison operator so it seems this is ruled-out... ``` z # zip digits from each pair of inputs together - # by subtraction, ḟ # get the first element that is I # itself truthy (non-zero), ± # output the sign of that (-1 or 1) or zero if it's empty ``` [Answer] # [Factor](https://factorcode.org/), 17 bytes ``` [ zip unzip <=> ] ``` [Try it online!](https://tio.run/##LY@7DoJAEEX7/Yr7BWRnl6cPWmNjY6yMBUFQCmBZlhA1fjsO4CRz52QyzzLLXWuny/l4OmyQ9X2b96gz9/Raey8sjC2cexlbNQ7diIdtB1M1D2yF6MaPSJIEAKsAUcBIFArEkWSMYs5C69m1ZlScVSQlI3EbKUZS2p9R@8LXioCAgwjCKP7jPH1ZES@1gZRyqdfJYuILtV41XfGuDIZm1t0@xW0q14fSOjPwph8 "Factor – Try It Online") Outputs `+lt+` for first input, `+gt+` for second input, or `+eq+` for neither. * `zip unzip` Truncate the longer input to the same length as the shorter one. * `<=>` Compare. [Answer] # JavaScript (ES6), 34 bytes Expects two arrays of characters as `(a)(b)`. Returns `-2`, `-1` or `0` for `<`, `>` or `=` respectively. ``` a=>b=>-a.some((c,i)=>d=c-b[i])^d<0 ``` [Try it online!](https://tio.run/##hZLLDoIwEEX3fkXTFU2ktJRnQvkRgkl5aDBIjRh/HwsL0GrLLE96MnduehUvMdaP7v50B9m005lPgucVz12BR3lrHac@dojnDa/dquhKdGoyMtVyGGXf4l5enLNTYIzBPDBNU1iiDawIAc8DgB9MIqWhLlIarWJmFJOY6GKcbBtzkwggY9@iAgvaiQqgr22EPiVkP6q6SCsHUv9DNEVVr1jwIy7IHhUGzKeaGCq2GxWGUZzYREur/z5AYo26HBMSsrY6A5Yus22c3g "JavaScript (Node.js) – Try It Online") Or **31 bytes** if we output negative / zero / positive: ``` a=>b=>a.some((c,i)=>d=c-b[i])*d ``` [Try it online!](https://tio.run/##hZLLDoMgEEX3/QrCSpuKIOIjKfyIcYGvxsZKU5v@vlUX2tKCszzhZO7ccJUvOZSP9v70elXVY8NHyUXBhUSDutWOU55al4uKl16Rtbl7rMZS9YPqatSpi9M4GUIIzAPTNIW5u4EVucD3AeAHk0gI00VColU8G8UkxroYJ9tGYRIBpPRbnMCCdqICGGgbYUAw3o86XaSVA0nwIZqiTq9o@CMuyB4VhjQgmsgmthsVsihObKKl1X8fILFGXY5hGK@tzoCmy2wbxzc "JavaScript (Node.js) – Try It Online") [Answer] # [R](https://www.r-project.org), 44 bytes ``` \(x,n=nchar(x))sign(diff(x%/%10^(n-min(n)))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZZBNCsIwEEZx6ykGpJBAi5mkPylYVx5DBKlEuzBCVehd3FTBQ-lp7DQtWDKLzOLxvZnJ41m3L1O87zcT6U-4ZU1oC1ue9jVrOL9WR8sOlTGsCZYBih2z0bmyzPKuXOY72xhWMsjzPASgBpzDAgq41CDmPUNMiCGmjq2IoWM6E8QyPeTWxKIBglIhPUr5UpAUlCiELwWkZVCO7F-KUsU9VLEnjZXEjiVd96RJmukJm246nq89KU1KhBBuqMr7mii6oPvMtnX9Bw) [Answer] # [Python 2](https://docs.python.org/2/), 37 bytes ``` lambda s,t:cmp(s[:len(t)],t[:len(s)]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NU9bisMwDPzXKYShYINa_GgaO9CTtPnIZhs2kLqhdj96lv4ElmVvsffobWon3QGNBBqkmcfveI9fF6-n725__LnFbm2fq6E5f3w2GChW7Xnk4VANJ8-jqCkuYxC1eIv_2iacAu7x0G7COPSRM2ICu8sVW-w9Msacc5QKlCpIqR3YUlJpHRhDJgG0JK2kBOVI6dy12VIm2BqtqEgMxa60yzQfs7OokFJmoXEz0qt_C0fPRI2QXaQU2cdsswJEHK-9j7zjaSHeKaZp6S8) [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 4.5 bytes (9 nibbles) ``` `$/|!$_-* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWKxNU9GsUVeJ1tSB8qPBNw2ilaEMdIx1jHRMdUx0DEIxV0oGJGQPFLJFhrFIsVCcA) Input as lists of digits, output as `1` (first wins), `0` (neither wins) or `-1` second wins. Would be 1-byte (2 nibbles) shorter to output negative, zero or positive. ``` `$/|!$_-* # full program `$/|!$_-*$$$ # with implicit args (I think*): ! # zip together $_ # arg1 & arg2 - # by subtraction, | # filter the resulting list *$$ # by each element multiplied by itself # (zero and negatives are falsy in nibbles), / # now fold over this list $ # returning the left-hand element each time # (so returning the first element), `$ # and return the sign of this # (or zero if empty) ``` \*I'm not quite sure why `$$$` is chosen for implicit args ([here](http://golfscript.com/nibbles/tutorial_minutiae.html) for the documentation), but happily it is and it works here... [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` ≔✂θ⁰Lη¹θ≔✂η⁰Lθ¹ηI⁻›θη›ηθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU8jOCczOVWjUEfBQEfBJzUvvSRDI0NTR8EQiAs1rblQVGUgqyqEqsoAqgooyswr0XBOLC7R8M3MKy3WcC9KTSxJLQKZCzINxs0AGQoE1v//m5qZWyiYmhgb/dctywEA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Charcoal doesn't have any relevant builtins, so it struggles even to port @SuperStormer's Python 2 answer. ``` ≔✂θ⁰Lη¹θ ``` Truncate the first string to the length of the second. ``` ≔✂η⁰Lθ¹η ``` Truncate the second string of the length of the first. ``` I⁻›θη›ηθ ``` Compare the strings. [Answer] # [C (clang)](http://clang.llvm.org/), ~~64~~ ~~63~~ 62 bytes ``` c;f(*a,*b){for(c=1;(*a&&*b)&c;c+=*a++>*b++)c-=*a<*b;return c;} ``` [Try it online!](https://tio.run/##bVHbboJAEH33KyYkGlgg5SLKZtWXpm/9g2qaZV0sqUUDNCU1/HrpuCxUrZuwc2bOmTlkVrhiz/Nd2wqWmoQ7JLFO6aEwxdJnmE8mWJgIJuwl4ba9IoltW8LFZEESVsjqs8hBsKbN8go@eJabFpxGgAcLBCpZVq/8ZQNLOD0blFLDgWfD9yMV47mnYhiqEHSZr0VBOFVgGga@AtFsHitA/xSR53lGw24ck/@OMxXnMdWOvafvaddgANo3QuNrQGncS0KqzoU1yPooRSW3nbfvgOdA4MBdEOg@ccjLCsQbLwjeUrzLoms31vVTsK7pI37nZV3mYe@K7wTm2TrLt7LGNo9puIAy@5aH1Ox/ynrQBTJUGNi2UltqWPdqwx45jtOvp0Qbds0nPZ/c46FEOjW5A4l1TUgkhk3ddh4LlKSmMd6XDuAF7grGWxiX6xx3cJ7mADL9ptAEh220QzNq2h@R7vmubN2vXw "C (clang) – Try It Online") *Saved a bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* Inputs the digits as two wide-character strings. Returns \$0\$ for `<`, \$2\$ for `>`, or \$1\$ for `=`. [Answer] # [Pip](https://github.com/dloscutoff/pip), 20 17 12 bytes *-5 bytes by Dlosc* Returns -1 for first element, 1 for second and nothing if equal. ``` SG@FI_-BMZab ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZrgt0d3DzjdZ18oxKTIEJQmW3RhkbGxpZgoKMAZJuYGhgYxEJlAQ) ``` SG@FI_-BMZab­⁡​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌­ MZab # ‎⁡For each pair of digits in a, b _-B # ‎⁢Return difference of digits SG # ‎⁣Push sign of @FI # ‎⁤First truthy element 💎 ``` [Answer] # `sed -E`, 92 bytes ``` s/^(.*)(.).* \1(.).*/\2\30123456789/;s/^(.)(.).*\1.*\2.*/</;s/^(.)(.).*\2.*\1.*/>/;s/...*/=/ ``` Assuming, that both numbers are in one line, space separated. Unfortunately, `sed` doesn't know how compare numbers, so we need to add the digit list and do some regexp backreferencing stuff. Option `-E` used for extended regular expressions to avoid twelve more bytes for escaping: * `^(.*)(.).* \1(.).*/\2\30123456789/` removes everything but the first differing digit and adds the ordered digits, so `42 43000` would turn into `230123456789` * `s/^(.)(.).*\1.*\2.*/</` turn the whole line into `<`, if the first digit appears in the digit list before the second one * `s/^(.)(.).*\2.*\1.*/>/` does the opposite with `>` * `s/...*/=/` cares for the rest (all legal lines that have not been replaced by `<` or `>` contain at least two characters (`..*` is one byte shorter than `.{2,}`) [Answer] # [Julia](http://julialang.org/), ~~93~~ ~~77~~ 54 bytes Port of [@Dominic van Essen' R answer](https://codegolf.stackexchange.com/a/264919/110802) in Julia. Saved 39 bytes thanks to the comment of [@MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush) --- Golfed version. [Try it online!](https://tio.run/##dZBBCsIwEEX3nmLATQJtyCSNbdEW71EUBKlEahSt0Jt5AA9WO9WKAZNFZpHHf39yvDd2h11fF30Xl8wVbm8Ptr0J1vHlzR4c29u6ZmvRPR8ot8zFJ@uYE0JwzqsN5/3lal3bOFazCvI8jwBowPAEcyjgfAU5@2UQDTGIiw@zIgY9JkslMWk25ZTExD4EWkd0aR2WgaIghVKGZYBUGtWX@SNDpZMR0klQlmiFA2OGGZSZRZr5zN/Npm/MgjJqYqSU71I6H48f2b8A) ``` x->(n=ndigits.(x);sign(diff(@.x÷10^(n-min(n...)))[])) ``` Ungolfed version. [Try it online!](https://tio.run/##ddBRSsQwEAbg5@0pBnxJYDdkknbbovXdM4iCuE2NtLOSptCbeQAPVpPqioVNHjIQvsw/yfvU2xecl8U0ZqJXb8/EZp7tqOlb6vybYCfbWT@KcMpvs51r/eQIHsiz0XbEjHWjD8YYNouvT5QgnhmJw2DJDtPAiK8ra@m0fDhLvg932CPUdb0HiAWeOIcbaODsQGb/DWIRDeLx19xFgxtTlTKasrr0uY/msEWg9T5uWqfDQMVGCqVMhwHGoVH9mSthqHS@Ip0nw3KtMJgi1GRYcSyrrbn6sss3VsmwOEkhpfwZStfr2rZcvgE) ``` f=function(x) n=length.(digits.(x)); return Int(sign(first(diff(x.÷10 .^(n.-minimum(n)))))) end ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 9 bytes ``` $CM Z:aZb ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhYrVZx9FaKsEqOSIHyo8NpoQyNjE1MdBRAVCxUEAA) Outputs -1 for `<`, 1 for `>`, and 0 for `=`. ### Explanation ``` aZb ; Zip the input numbers together, giving a list of pairs of digits Z: ; Transpose into a pair of (equal-length) lists of digits $CM ; Fold on numeric comparison ``` The `CM` operator, when given two lists of digits, does almost what we want, but not if the lists are of unequal lengths. (If the shorter list is a prefix of the longer list, the longer list is considered to be greater.) So we zip the numbers together to clip to the length of the shorter one, then zip back again and compare. [Answer] # Excel, 70 bytes ``` =@IFERROR(SIGN(TOCOL(1/(MID(A1,ROW(1:99),1)-MID(B1,ROW(1:99),1)),2)),) ``` Inputs in cells `A1` and `B1`. Outputs `1` for first input, `-1` for second input and `0` for equal. Assumes maximum string length of `99` characters. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 56 bytes ``` ^(.+)(.*¶)\1 $2 ^(¶.*|.*¶)$ (.).* $1$* (1*)¶\1 - 1+-? 1 ``` [Try it online!](https://tio.run/##JYw9DgIhEIX7d4opMAE2S2ZgWaDyELZmo4WFjYWx9Fx7gL0YAr7k/WTyZd6Pz/N1ryd9uVHdtJuMdvbYzVWgPDZ97M5@x0UB2hlnoURZaLHm2Bs1Q6b5DKm1lELNEIkksiInppQLQqDQBM/khRlSSHxvHxbqgSV4odgScU35v8azPKDIzB0MZegH "Retina 0.8.2 – Try It Online") Takes input on separate lines but link is to test suite that splits on spaces for convenience. Outputs `-1` for the first input and `1` for the second input having the earliest lower digit. Explanation: ``` ^(.+)(.*¶)\1 $2 ``` Remove any matching leading digits. ``` ^(¶.*|.*¶)$ ``` If at least one string is empty, then the there is no earliest lower digit. The rest of the program has no effect now that the output is empty. ``` (.).* $1$* ``` Convert the first remaining digit of each number to unary, discarding the rest. ``` (1*)¶\1 - ``` Subtract the two unary numbers. ``` 1+-? 1 ``` Take the sign. [Answer] # [Julia 1.0](http://julialang.org/), 23 bytes port of [l4m2's answser](https://codegolf.stackexchange.com/a/265431) ``` a+b=(a>"$b:")-(b>"$a:") ``` [Try it online!](https://tio.run/##PU7tboMwDPyfp7hlVZVoTCJQCkxN/u1Bwke1bAwQsK1vzxyvmqXYvvP5nPevIXhz23f/1FjlnTw0L1I/q4Y6T90urtOCgDBi6X03hLFflRag8EmTtLBY5yFsKvyRkWg/Z9Um0kqNR1odpu8e25vfKIUVP9PysbK2Iy2d5X5ewrgNo1LkqmEdOn3XPJAhjsd/hXy9zX279R0OrdSiH7sddV2TNmYrYExBwJgzLoILmHICVZkSKKs6AuR5fJSt4AKmyAAZyTKTptEAhqxNRsAJ5sBzJ5gDzy8E8lOUUbbilGcGKKjQpDiX1R3Eo/ePVvFOLIwIxNUijY7U5TUHHPAL "Julia 1.0 – Try It Online") ### nice solution but longer, 28 bytes the same as [xnor's answer](https://codegolf.stackexchange.com/a/264907) *i swear i found it on my own* ``` a+b=cmp(zip(zip(a,b)...)...) ``` [Try it online!](https://tio.run/##PY7hToQwEIT/9ylGNBeIhFA4Dkiu/PNBOKixikAA9eLL43TvYpPd7cx@THn/Glyrr/vePl9M9zmHv@5WbXyJkiSR2tXrtMDBjVhs2w9utGsYKfAQizsYrPPgttDdTG/4rC4OTBDhkZ8O07fF9tZubG7Fz7R8rML2ZPm23OfFjdswhvI4TIM@ujMPDMTh8E8EL9fZdpvt8dQFkbJjv6Oua7K@GwWtCwqtTzgrGRCrUajKlKKsai@Q577YjZIBsRiAjFim09QHQDNaZxSNEg@yb5R4kP2ZIj96jN2oY55poODgpjiV1V34R@8/WhHzdJH6EN7yWg4a4A8 "Julia 1.0 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 21 bytes ``` f=a=>b=>[a>b+f,b>a+f] ``` [Try it online!](https://tio.run/##fZFdC4IwFIbv@xVjV4qV@/Bjg7Y/El1M0yjERUZ/f22GTmJ6rt4XHg7P2R7qo4b6dX@@D72@Nsa0QglZCXlWskrafSVV0l5MrftBd82x07eojYAbyDmH8S9PLQZpCoDYhXCM8wWOcTHhpyDOSrTASzZvlyEcQEpn3GbXNmQAJH47JBihTRmr60@FmHg8JGMBmi1x19ZlYEYJ9nhu65YMzIuShfGVl/n7JrYmM5rmyB03ZsrHmbebLw "JavaScript (Node.js) – Try It Online") <!-- Before IO tweak: --> # [JavaScript (Node.js)](https://nodejs.org), 22 bytes ``` f=a=>b=>a>b+f|-(b>a+f) ``` [Try it online!](https://tio.run/##fZFdC4MgFIbv9yvEqyK2/MhSmP4Xazk2Iscau9p/b9ooY1jn6n3h4fAcveu3Hprn7fE69vbSjqORWqpaKq3qzHyOSa10ZtKxsf1gu/bU2WtiEuAHCiFg@stzS0GeAyAPMRxjtsIxLmf8HMV5hVZ4xZftKoYDSOmCu@zbjgyAJGyHBCO0K@N0w6kQk4DHZBxAizXu27YMLCjBAWeu7slAVlY8jm@8zN838S2ZyZQhf9yUqZhm2T5@AQ "JavaScript (Node.js) – Try It Online") Same length as `a=>b=>a>b+{}|-(b>a+!0)` [Answer] # [Haskell](https://www.haskell.org) + [hgl](https://www.gitlab.com/wheatwizard/haskell-golfing-library), 9 bytes ``` fo<<zW cp ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FN68zcgvyiEoUALiijsDQxJzMtMzVFIaAoNac0JZUrzcoq2jOvJFbXDkr5F6WkFmXmpS8tLUnTtVidZpuWb2NTFa6QXAARuVmVm5iZp2CrkJLPpaBQUKSgopCmEG2pY6ljEQumY9GFdQwgEjrm2CQt4ZIG6JJmOkZwSTMds1guiAsWLIDQAA) Outputs as a native comparison value. This zips the lists together comparing their values pairwise, then folds the results to get the answer. ## Reflection This is rather short, however I have found myself desiring to zip and fold at once before, and so I might actually make a way to combine `fo` and `zW`. [Answer] # [Haskell](https://www.haskell.org), 49 bytes ``` ((head.(++[EQ]).snd.span(EQ==)).).zipWith compare ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZDBaoNAEIbp1af4j7tkI67GREM9SikUilDoQTxsolZpYsS1FErfpBcplD5T-zTdVRPtwM4MHzP_7v4f34WQz9nh0H3mwddLmy-9HxuEFJlITbJYxGGUUFNWqSlrUZEwCgJKTWq-lfVj2RbYn461aLJh8_eqbjPZ7oXMJLZbxOS2ahn6dN-kWVNWTzQxppkAsQEVBL7vMww5jCgbKeeuopyvGe4eLtTbWIpuPDV7M1E4DlNH55kCbDVrc8v6pwCudrmt6aTAbWelqc6TwsqxOYOrylzBXW-8M52_YfyFN1fQiq6l71Kd4_fRbyWGcRRlpVyolTMt4hxEFqdXCDo2O4ogQIN3EMGwY2gorpe4GJgYg_FdN9Q_) [Answer] # [Ruby](https://www.ruby-lang.org/), 32 bytes ``` ->a,b{a[0,b.size]<=>b[0,a.size]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY5daoNAFIXfZxUHqdCCkfnxF6IbESlKNBFCEUcJaelK-hJK-9r9ZDc9oxmYO98598zM_fqZlvZ6--6L32Xud9kdu7IJ2o-mkkEb2uG9q_dF2VI1m_p85E6X03DucOxmKwBeQYGn19DO0zCGdjwPM-2JZl-xWVOMy2zh9ZUf2QAsNZu-PuDZty8efDCHNsAUwCvKvVdNdS26t8P23-3-hzzPAVcFlIqJSiUOkxVjgSyVxDRjAMa4bYxwhS4FXc2AVlISFR9Tmui0C2gpnHaocqKJXMBEIjJaATEPESdp9kA3yTpOtmZj6a6STL6ubex_) [Answer] # [TypeScript](https://www.typescriptlang.org/)'s Type System, 128 bytes ``` type F<A>=A extends[[infer G,...infer N],[infer H extends 1[],...infer M]]?G extends[...H,...infer R]?R extends[]?F<[N,M]>:2:1:0 ``` [Try it at the TypeScript Playground!](https://www.typescriptlang.org/play?#code/PTAEHkCcBMFNNAIwJ6gKIENIBsCWsBnAF1ABkB7Ad3lABFcBzXEgWlAEYAmADiWSMIAoQUWQAHWKABiAHgCCAPgC8c0LAAeAgHbQCAbT24tAMxoBxADQA6G0dMIAcgF0LhkzQASazbB0EOei42VnY0ALJOTgD8Zt7aunrBHta27ggAStHpcb4J0bJ6DhYRCgBcnKXspQAMwoIgoMbk5AKQwg0AykYAxpJEABa4-kQYANaEoEZiAK4kGP4YoHjEoOTGoNNaWKha0wC2iPAEFqAAkgDke6BwxkZGDPVgBOR7kv2w2BIIohLD5KB7MZ9d6gATEFjdeYTWDzfDff6QGHQKzCH6SACqW0gyBkDhyflAuwO8BOqg08X87ECoCUoECChpoDkegARNhfAwBiynPjdKAHIJQKAokzBaBSqBMdtcSdEjY5Cd2E4FABuETiSQdIiQe4AFXIUuxpCGRAIMjFHV5-mIOq0DwZtMt5Ny-gABgASADeoUcVsJ+0OkAAvl6faB0kHXWKRXpDTiHAoTsEtbaGPq48biGb0gonGKJYE1WjQLrCER5H6bfcTgAhSva+4OulilloACO0ww2BZFhbUlwkBWQyWVHgPZbHVg3XIOkm-mwo8g46cegKKb1BqxyEzpvkidA67t6a3O7NNdzubVjxLZdAkIIQnVEhvxHYjNLxBkLK4AGYACwAKzVMBPagN+nA-j+ACcMGwSyCjXkKAB6URPpIH5EJw75ll+MGgSyMHcPBiGgChaEvkQP7YZ+37sAB+HsOwABsxENMhqHFhhf7UeWtEsSctH0QhbGkRxGoUQBPFftwADs1T4TJ3BQaxYDseRGFMVJLKQfhkE6cJqmiepZYyVpf4-pw7D4QB5mcCpQpGYIQA) Generic type `F` takes type `A` which is a tuple of two lists of unary digits. Output is 0 for equal, 1 for first is lower, 2 for second is lower. ## Explanation ``` type F<A>= // match the first item (G or H) and rest (N or M) of each list in A A extends[[infer G,...infer N],[infer H extends 1[],...infer M]] ?G extends[...H, // if H fits in G, ...infer R] // let R be the difference. ?R extends[] // if R is empty, ?F<[N,M]> // recurse with N and M. :2 // otherwise, 2 is smaller :1 // if H doesn't fit in G, 1 is smaller :0 // if neither has been chosen yet, they're equal ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 74 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 9.25 bytes ``` Z~AEv¯fꜝh± ``` Returns -1 for first element, 1 for second and 0 for equal. [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiWn5BRXbCr2bqnJ1owrEiLCIiLCJcIjEyMzM5OTk5OTlcIlxuXCIxMjM0NTAwMFwiIl0=) ``` Z~AEv¯fꜝh± ­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌­ Z~A # ‎⁡Zip and filter out falsy elements (trim numbers) E # ‎⁢Covert string input to integers v¯f # ‎⁣Calculate differences and flatten ꜝh± # ‎⁤Output sign of first truthy element 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [BQN](https://github.com/mlochbaum/BQN), 12 bytes ``` (⊑⍋-⍒)⌊○≠↑¨⋈ ``` `¯1`:`<`, `0`:`≡`, `1`:`>` [Answer] # [Arturo](https://arturo-lang.io), 43 bytes ``` $[a b]->compare take a size b take b size a ``` [Try it!](http://arturo-lang.io/playground?x6oogQ) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .S0Ûн ``` I/O as two lists of digits. Outputs `-1` if the second is lower; `1` if the first is lower; and nothing if they're 'the same'. [Try it online](https://tio.run/##yy9OTMpM/f9fL9jg8OwLe///jzbUMdIx1jHRMdUxAMFYLqiIsY4lAsYCAA) or [verify all test cases](https://tio.run/##Nc6xCsIwEAbgVymZFA65S5o2AbWTT9CxFFRwcHIoCN3EwVlc3cWhryAOeQGfoS8SL4ce5Pj4kzty6Dbb/S4e@0pl4@WWqaofz0O97uKsxnD/vGK4VhiG2Wo8PRbzZReeKpuE91RBbBrvPfBpoSGyQFSICpZluRKhdOnWGDBcIjFLI2hCTBMeSItSAFoyDoBkszY5pMbOjSaw3Nm2KN3f8g33e2wxjWpjvFTbfgE). **Explanation:** ``` .S # Compare the digits at the same positions in the two (implicit) input-lists, # ignoring any trailing digits if the lists are of unequal lengths # -1 if a<b; 0 if a==b; 1 if a>b 0Û # Trim all leading 0s н # Pop and push the first item, or an empty string if the list is now empty # (which is output implicitly as result) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` Z~A∩÷₌><- ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJ+IiwiIiwiWn5B4oipw7figow+PC0iLCIiLCJcIjk5OVwiLCBcIjk5OVwiID0+IDBcblwiMTE1XCIsIFwiMTE2XCIgPT4gMVxuXCIxMTZcIiwgXCIxMTVcIiA9PiAtMVxuXCI4NzBcIiwgXCI3ODlcIiA9PiAtMVxuXCIzM1wiLCBcIjMzMzNcIiA9PiAwXG5cIjMzMzNcIiwgXCIzM1wiID0+IDBcblwiMjBcIiwgXCIyMTAwXCIgPT4gMVxuXCIxOVwiLCBcIjEyMDBcIiA9PiAtMVxuXCIyMTAwXCIsIFwiMjBcIiA9PiAtMVxuXCIxMjAwXCIsIFwiMTlcIiA9PiAxXG5cIjEyMzRcIiwgXCIxMjM0XCIgPT4gMFxuXCI0MzIxXCIsIFwiNTQzMlwiID0+IDFcblwiNTY3OFwiLCBcIjU0MzJcIiA9PiAtMVxuXCI5OVwiLCBcIjk5OFwiID0+IDBcblwiMTIzNDUwMDBcIiwgXCIxMjMzOTk5OTk5XCIgPT4gLTEiXQ==) [Answer] # JavaScript, 62 bytes (but outputting the actual comparison characters instead of numbers, because... (that's the challenge spec??)) ~~More like I was stupid and didn't read the comments and thought that that was necessary and didn't want to rewrite the code~~ ``` a=>b=>a.split``.find((u,i)=>u>b[i]?b=">":b[i]>u?b="<":0)?b:"=" ``` [Try it online!](https://tio.run/##dc7RCoIwFAbg@54iztUGJpvLaOLmg0TgpiYLcdK0119t5E3lufnPgY/Df1dP5ZqHmebDaNvOO@GVkFpIlbppMHNdpzcztggticFCLlJfzLXSAiQUYZVLOEooCK50AQJ8Y0dnhy4dbI8cAs454E8k@zfAuy9BaR4Epacoyl/BWAAsxP8XbBVbYC1x3iyRsWNOCIlNMsZ4nKglYP8C "JavaScript (Node.js) – Try It Online") ]
[Question] [ Tonight is card game night! You are the dealer and your task is to write a program to deal the cards to the players. Given an array of cards and the number of players, you need to split the array of cards into a hand for each player. [![example for 4 players with a deck of 10 cards](https://i.stack.imgur.com/dVfIO.png)](https://i.stack.imgur.com/dVfIO.png) ## Rules Your program will receive an non-empty array `A` , as well as a non-zero positive integer `n`. The array should then be split into `n` hands. If the length of the string isn't divisible by `n` any leftover cards at the end should be distributed as evenly as possible. * If `n==1`, you will need to return an array of array with `A` as it's only element * If `n` is greater than the length of `A`, you will need to return every hand and an empty hand. if `n = 4` and `array A = [1,2,3]`, you should return `[[1],[2],[3]]` or `[[1],[2],[3],[]]`. You are free to handle the empty hand with empty, undefined or null. * The array can contain any type rather than a number. * You should not change the order of the array while dealing. For example `if n = 2` and `A= [1,2,3]`, any result rather than `[[1,3],[2]]` will be invalid. ## Test Cases ``` n A Output 1 [1,2,3,4,5,6] [[1,2,3,4,5,6]] 2 [1,2,3,4,5,6] [[1,3,5],[2,4,6]] 3 [1,2,3,4,5,6] [[1,4],[2,5],[3,6]] 4 [1,2,3,4,5,6] [[1,5],[2,6],[3],[4]] 7 [1,2,3,4,5,6] [[1],[2],[3],[4],[5],[6]] // or [[1],[2],[3],[4],[5],[6],[]] ``` ## Demo Program ``` def deal(cards, n): i = 0 players = [[] for _ in range(n)] for card in cards: players[i % n].append(card) i += 1 return players hands = deal([1,2,3,4,5,6], 2) print(hands) ``` [Try it online!](https://tio.run/##NY5NCsIwEIXXmVPMRmhwENuqC6EnCUGCSW1ApmFaFz19bIIu38/3ZtK2TjP3Ofswog/u3Tyd@IWQ9R1UxAHPoNLbbUGWXRhjcZwFHxgZxfErNKwtqOIVsNh1YIf/mIl4QLYnl1JgX/f1nkY8DtiCkrB@hPFXBpgc@3KqPmNa6qinC13pZgk7DZAk8trUls75Cw "Python 3 – Try It Online") This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so you the shortest bytes of each language will be the winner. Inspired from [Create chunks from array](https://codegolf.stackexchange.com/q/180970/67312) by [chau giang](https://codegolf.stackexchange.com/users/84378/chau-giang) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~3~~ 1 byte Saved 2 bytes thanks to *Adnan* ``` ι ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3M7//024og11jHSMdUx0THXMYgE "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##yy9OTMpM/W/h7udir6Sga6egZP//3M7/h9fr/I821DHSMdYx0THVMYsFAA) **Explanation** ``` ι # uninterleave ``` Does exactly what the challenge asks for [Answer] # [R](https://www.r-project.org/), ~~46~~ 25 bytes ``` function(A,n)split(A,1:n) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NRJ0@zuCAnswTIMrTK0/yfnFiioaSLDEpSi0sUDJFFYvKUNLnSNAytzHQMNa1x6DDCocMIpw5jHDqMceowwaHDXJPrPwA "R – Try It Online") `split`s `A` into groups defined by `1:n`, recycling `1:n` until it matches length with `A`. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~33~~ 24 bytes ``` ->\b{*.classify:{$++%b}} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX9cuJqlaSy85J7G4ODOt0qpaRVtbNam29n9afpGCoZ6eiUI1F2dxYqVCmoZKvKYGUMRMk6uWiwsiZKKpEW2oY6RjHKv5HwA "Perl 6 – Try It Online") Anonymous curried code block that takes a number and returns a Whatever lambda that takes a list and returns a list of lists. This takes the second option when given a number larger than the length of lists, e.g. `f(4)([1,2,3])` returns `[[1],[2],[3]]` ### Explanation: ``` ->\b{ } # Anonymous code block that takes a number * # And returns a Whatever lambda .classify # That groups by :{$++%b} # The index modulo the number ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes ``` (s=#;GatherBy[#2,#~Mod~s&])& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X6PYVtnaHSRW5FQZrWyko1znm59SV6wWq6n2P6AoM69EwSE92lCn2lDHSMdYx0THVMesNpYLLmOEU8YYp4wJThlzNJn//wE "Wolfram Language (Mathematica) – Try It Online") [Answer] # Japt, 2 bytes Takes the array as the first input. ``` óV ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=81Y=&input=WzEsMiwzLDQsNSw2XQo0Ci1R) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 2 bytes ``` sZ ``` [Try it online!](https://tio.run/##y0rNyan8/7846v/h5UcnPdw54///aEMdIx1jHRMdUx2z2P8mAA "Jelly – Try It Online") Thanks to @JonathanAllan for saving 4 bytes [Answer] # [Python 2](https://docs.python.org/2/), 37 bytes ### Code: ``` lambda x,n:[x[i::n]for i in range(n)] ``` [Try it online!](https://tio.run/##fclLCoAgFAXQeau4w4Q30X4gtBJzYJQl1CvEga3eduCZnvdL58OqeMxYyuXudXPIxNpkE7Rm65@IgMCIjo@9ZWHLGwMn@NZIgiJ0hJ4wEEZLkKKptap3V@@@3pMoPw "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 39 bytes ``` import Data.Lists (transpose.).chunksOf ``` Note: `Data.Lists` is from the third-party library [lists](https://hackage.haskell.org/package/lists), which is not on Stackage and hence will not appear on Hoogle. [Answer] # [J](http://jsoftware.com/), ~~13~~, ~~11~~, ~~10~~, 9 bytes ``` (|#\)</.] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NWqUYzRt9PVi/2typSZn5CsYKqQBsZGCsYKJgqmCGURQXR1CG@GTNMYnaYJP0hxV8j8A "J – Try It Online") ## how (previous explanation, fundamentally the same) ``` ] </.~ (| #\) </.~ NB. box results of grouping ] NB. the right arg by... | NB. the remainders of dividing... [ NB. the left arg into... #\ NB. the length of each prefix of... ] NB. the right arg, NB. aka, the integers 1 thru NB. the length of the right arg ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes ``` IEθ✂ηιLηθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQKNQRyE4JzM5VSNDRyFTR8EnNS@9JEMjQ1NHoVATCKz//4820Yk21DHSMdYx0THVMYuN/a9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order `[n, A]` and outputs each value on its own line and each hand double-spaced from the previous. Explanation: ``` θ First input `n` E Map over implicit range η Second input `A` ✂ Sliced ι Starting at current index Lη Ending at length of `A` θ Taking every `n`th element I Cast to string Implicitly print ``` [Answer] # [Kotlin](https://kotlinlang.org), ~~53~~ ~~51~~ 49 bytes ``` {a,n->(0..n-1).map{a.slice(it..a.size-1 step n)}} ``` The old, incorrect solution only worked for divisors of the array length. I'm certain this can be golfed down. [Try it online!](https://tio.run/##XY/NCsIwEITvfYrR0wbaYP0DxRY8Cr5EqBEW07U0UdDSZ6@pigfnsMxhZj72cg2OZbgbh/NNqi3oyD7sDhLKFPEqZCX28kAxdCaVrKSZ1pLlStem6Yz2jitLHLSOnp82y@GDbSCq74e4iNqwkEKXIGrECAq01pyOLJbUZKLDNXJI/QKVaU/@P@Qbx4GmmH7AEfit9cm72LQswQmNT9B7IRWlkn7YJDnmWGCJFdYv) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes ``` #2[[i;;;;#]]~Table~{i,#}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9koOjrTGgiUY2PrQhKTclLrqjN1lGvV/gcUZeaVRFcrK9fq2qU5KCvHqjk4OChUc1Ub6gCRkY6xjomOqY5Zba0OV7URppAxppAJppA5Vo2OOk46zjouOq46brW1XLX/AQ "Wolfram Language (Mathematica) – Try It Online") [Answer] # TSQL, 44 bytes ``` -- @ : table containing the input -- column c: value of the card, -- column a: position on the card in the deck -- @n : number of players DECLARE @ table(a int identity(0,1), c varchar(9)) DECLARE @n int = 4 INSERT @ values('1a'),('2c'),('3e'),('4g'),('5i'),('6k') SELECT string_agg(c,',')FROM @ GROUP BY a%@n ``` **[Try it out](https://data.stackexchange.com/stackoverflow/query/1000657/deal-the-cards-to-the-players)** [Answer] # [JavaScript (Node.js)](https://nodejs.org), 51 bytes ``` A=>n=>A.map((x,i)=>e[i%=n]=[...e[i]||[],x],e=[])&&e ``` [Try it online!](https://tio.run/##DcZLCoNADADQ01QSSAPaz0Yy4DlCFoONZYqdkVrEhXef9q3eK25xHT9p@Z5zeXidpA4SsoSB33EB2CmhBNd0kmyizPy/HYca7UYuatg0Xvux5LXMznN5wgTaUkcXutKN7obQIfb1Bw "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 53 bytes ``` A=>n=>g=(i=n)=>i?[...g(--i),A.filter(_=>i--%n==0)]:[] ``` [Try it online!](https://tio.run/##DclRCsIwDADQ0wgJJEGd@uFIZecoRcZsS6Wksg2vX32/7z1/521Zy2dna6/Yk/ZJnanLCkUN1ZWHF5EMzAVpklTqHld4/oP5YKpHDHcf@rg021qNUluGBP5EZxroQle6BYQBAXHsPw "JavaScript (Node.js) – Try It Online") [Answer] # Ruby, 81 bytes ``` def s a,n;a.each_with_index.inject(([[]]*n).map(&:dup)){|b,(c,d)|b[d%n]<<c;b};end ``` [Try It Online](https://repl.it/repls/HoneydewOilyPlots) [Answer] # APL+WIN 26 or 31 bytes If individual hands can be represented as columns of a 2D matrix then 26 bytes if an array of arrays then add 5 bytes. ``` (l,n)⍴((l←⌈(⍴a)÷n)×n←⎕)↑a←⎕ ``` [Try it online! ourtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5r5OjkaT7q3aKhkQMUfNTToQHkJGoe3p6neXh6Hkiob6rmo7aJiRDmf6Cm/2lchgpGCsYKJgqmCmZcJgA "APL (Dyalog Classic) – Try It Online") or ``` ⊂[1](l,n)⍴((l←⌈(⍴a)÷n)×n←⎕)↑a←⎕ ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4/6mqKNozVyNHJ03zUu0VDIwco9ainQwPISdQ8vD1P8/D0PJBQ31TNR20TEyHM/0Ct/9O4DBWMFIwVTBRMFcy4TAA "APL (Dyalog Classic) – Try It Online") Explanation: a←⎕ prompt for array of cards ((l←⌈(⍴a)÷n)×n←⎕)↑ prompt for integer, pad a with zeros to given even hands (l,n)⍴ create 2D matrix with each column representing each hand ⊂[1] if required convert to nested vector - APL array of arrays [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 9 bytes ``` \ô_í\%q╞; ``` [Try it online!](https://tio.run/##y00syUjPz0n7/z/m8Jb4w2tjVAsfTZ1n/f9/tKGOkY6xjomOqY5ZrIIhFyrfCI1vjMY3QeObovHN0fiGqAbomOtY6FjqGBroGBrqGBoB9f8HAA "MathGolf – Try It Online") ## Explanation ``` \ swap top elements (pops both input onto stack) ô start block of length 6 _ duplicate TOS (will duplicate the list) í get total number of iterations of for loop (the other input) \ swap top elements % modulo (picks every n:th item of the list q print without newline ╞ discard from left of string/array (makes the next player pick cards starting with the next in the deck) ; discard TOS (removes some junk in the end) ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 90 bytes ``` A->n->{var o="";for(int h=0,i;h<n;o+="\n")for(i=h++;i<A.length;i+=n)o+=" "+A[i];return o;} ``` [Try it online!](https://tio.run/##bZE9b8IwEIb3/IqTp6Q2VvloK9U4UpZKHToxUgYDgRw1duQ4SAjlt6dJsBBDbrIfv6d7bJ/URU1O@78Wz6V1Hk7dntceNT/UZufRGv4iorLeatzBTquqgh@FBm4RdFV55Tv@FaJLNH69Yd/GP8jKOzTHNIV9rjTINpukZpLeLsqBlYSIg3Vx1wWFfGUoiqURlkrya0gynMiCUoHLjOvcHH0hkEqT9AkgNFvjRrjc186AFU0rosEpuAa1i8U9nDvj@G6y3oByxyoJF@hrkIYMJNxgymDGYM5gweCNwTs04pEru34fZwymyQicjcH5GFyMwY8Am@j5YQf7eyZYsl4X8Nl/da18fua29nyIahMTIwlFSj6BPA0bCfa/wlVZ6mucJWGBycOlaf8B "Java (JDK) – Try It Online") Thanks [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%C3%A9goire) for the lambda and better incrementing while iterating. [Answer] # [PHP](https://php.net/), ~~85~~ ~~83~~ 82 bytes ``` function($a,$n){while($x<$n)$c[]=array_column(array_chunk($a,$n),+$x++);return$c;} ``` [Try it online!](https://tio.run/##bY5BS8NAEIXv@RVDWciGzMGmTaWkUaQKPQi26C2GsKxbN1p3w2aDldLfHndDjrk85n0z83iNbPrNfSMbEMZoUxnRaGNr9UlvoiwgIu@PneK21ooShkRFl19ZnwQl540zhBdlzoxhfxXXp@5H0dHITn2PDxiTcxxHmRG2M4rw7NpnQUCsaG0LORQBwBzyOyjmmOACl5jiqkRHk0m6mKTLSXo7SdOBhuttiOHh0Uny6mS5c7Ly9sHbtZ/ePEu3oXsrXeejNoJxSWEsz1ogyocRBhFcXLTgUjuGMHu3M4SvVqtKKK4/BB2OphfDEn1W5E/2u3319PKcBdf@Hw "PHP – Try It Online") This will not be the shortest entry, but I thought it'd be fun to try and do it using PHP array function built-ins. Result: long. ***Output*** ``` 1 [1,2,3,4,5,6] [[1,2,3,4,5,6]] 2 [1,2,3,4,5,6] [[1,3,5],[2,4,6]] 3 [1,2,3,4,5,6] [[1,4],[2,5],[3,6]] 4 [1,2,3,4,5,6] [[1,5],[2,6],[3],[4]] 7 [1,2,3,4,5,6] [[1],[2],[3],[4],[5],[6],[]] 5 ["9C","QD","2S","4H","6D","AS","9D","TH","5C"] [["9C","AS"],["QD","9D"],["2S","TH"],["4H","5C"],["6D"]] ``` [Answer] # [Perl 5](https://www.perl.org/) `-la`, ~~66~~ 56 bytes ``` $,=<>;map{push@$_,shift@F}1..$,while@F;say"@$_"for 1..$, ``` [Try it online!](https://tio.run/##K0gtyjH9/19Fx9bGzjo3saC6oLQ4w0ElXqc4IzOtxMGt1lBPT0WnPCMzJ9XBzbo4sVIJKKmUll@kAJb4/99QwUjBWMFEwVTBjMvQ4F9@QUlmfl7xf11fUz0DQ4P/ujmJAA "Perl 5 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 43 bytes ``` a=>b=>{int i=0;return a.GroupBy(_=>i++%b);} ``` [Try it online!](https://tio.run/##Xc7fS8MwEAfw9/4Vx0BI6Fm6@ePBNAEVFWGPgg9jSBpSG9wSSVtlhPztNQsTxHtI4Huf3EUN52ow8@NkVfP8YKe99rLd6cbYUWA68G/4HwgBHfCZSGwpFyFFYHjNvB4nb0FWT95Nn3cH8saFKcuzlrI4s6L4kh7MqPcDcLD6e7MNS1zhBV7iFV5Hlvuqn@zHEXQkU1zR6sXdei8PhKYZnfNA8sJkapau5vSmWmv7PvYpKktahAJSJa2l6oH8rgZjT3xjtjSbY907O7idrl59QmtjNVlkdRPqCGEZFwgG84D0hzj/AA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # C (gcc), 5 bytes The compiler flag `-Df=` (req. leading space) fulfills specification. `f(n_cards,n_hands,card_ptr)` evaluates to a pointer to a list of hands. # Explanation In C, it is common practice to implement lists of lists as a single interleaved array, when the number of lists remains constant but all lists can be extended. For example, in this case of dealing cards, it is more common for more cards to get added to each hand than more hands to be added, so it would be reasonable to implement a list of hands as an interleaved list. Coincidentally, the "deck" is such a list, and thus we return the parameter unmodified. This challenge probably should've been sandboxed. ]
[Question] [ Given `n=m^2`, return a list of integers that do not border the `m x m` grid of integers from `1 to n`. ## Examples ### n=1 (m=1) Grid: ``` [1] ``` Return: ``` [] ``` ### n=4 (m=2) Grid: ``` [1,2] [3,4] ``` Return: ``` [] ``` ### n=9 (m=3) Grid: ``` [1,2,3] [4,5,6] [7,8,9] ``` Return: ``` [5] ``` ### n=16 (m=4) Grid: ``` [ 1, 2, 3, 4] [ 5, 6, 7, 8] [ 9,10,11,12] [13,14,15,16] ``` Return: ``` [6,7,10,11] ``` --- For higher values of `m`, [this](https://codegolf.stackexchange.com/a/154691/59376) answer does a great visualization. --- Rules: * You may take in either `m` or `n` (where `n = m*m`). + If taking in `n` you are allowed to have undefined behavior where there exists no `m` for `n` (E.G. 15). + `n > 0`, `m > 0`: Both must be integer values. * The output may be as a 1D/2D array, matrix or whitespace delimited * The output must be in order from least to greatest. + If outputting as a matrix this means it must be as it would be in the grid. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins. [Answer] # C, 50 bytes ``` i;f(m){for(i=m;++i<m*m-m;)i%m>1&&printf("%d ",i);} ``` [Try it online!](https://tio.run/##PY3NCsIwEITveYol0LJr7KFH2dZ3kUhkD1NLraeSZ48hinP75oeJwyPGUkwTQ4703NhmaAg24YQBKtbhOvb9utmyJ/bdnfzZRHOpTLjZwuIOR1V1TNzceVTCdFEKAdKyb6O16o/@aX3vL/b@52SXywc) [Answer] # [Octave](https://www.gnu.org/software/octave/), 31 bytes ``` @(m)vec2mat(1:m*m,m--)(2:m,2:m) ``` Returns a matrix. [Try it online!](https://tio.run/##y08uSSxL/f/fQSNXsyw12Sg3sUTD0CpXK1cnV1dXU8PIKlcHiDX/pynYKiTmFVtzcaXlFynkAnmGVoZGXApAkAbUypWal/IfAA) [Answer] # [Octave](https://www.gnu.org/software/octave/), 26 bytes ``` @(m)find((t=[0:m-2 0])'*t) ``` The code defines an anonymous function that inputs `m` and outputs a (possibly empty) column vector. [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI1czLTMvRUOjxDbawCpX10jBIFZTXatE83@ahqEmV5qGEYgwBhEmmv8B "Octave – Try It Online") ### Explanation ``` @(m) % Define anonymous function of m t=[0:m-2 0] % Build row vector [0 1 2 ... m-2 0] and assign it % to variable t ( )' % Complex-conjugate transpose into a column vector *t % Matrix-multiply that column vector times the row % vector t. This gives an m×m matrix with zeros in % the border and nonzeros in the other entries. find( ) % Linear indices of nonzero entries. The result is % in increasing order ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ’Ṗ×+€ṖḊ€ ``` A monadic link taking `m` and returning a list of lists (the inner rows). **[Try it online!](https://tio.run/##y0rNyan8//9Rw8yHO6cdnq79qGkNkPFwRxeQ8f//f0MDAA "Jelly – Try It Online")** ### How? ``` ’Ṗ×+€ṖḊ€ - Link m e.g. 5 ’ - decrement 4 Ṗ - pop (implicit range of input) [1,2,3] × - multiply by m [5,10,15] Ṗ - pop m [1,2,3,4] +€ - add €ach [[6,7,8,9],[11,12,13,14],[16,17,18,19]] Ḋ€ - dequeue €ach [[7,8,9],[12,13,14],[17,18,19]] ``` [Answer] # Pure Bash, 49 The boring answer: ``` for((i=$1;i++<$1*$1-$1;));{ ((i%$1>1))&&echo $i;} ``` [Try it online](https://tio.run/##HYs7DoAgEAV7TrHFSkCDyRY2It7FD0YKIFE7wtkR7d5k5q3LfZYjXuDBBUjU90PWsEdmtzOCN@hHdtsHlAL0XyiEM0jadd2E1CKpClLqBFU0SDNJyfl/Rqdz@RbbY7DlBQ). --- Or the interesting answer for 52: ``` (($1>2))&&eval echo \$[$1*{1..$[$1-2]}+{2..$[$1-1]}] ``` [Try it online](https://tio.run/##S0oszvifll@kkKuQmadQbainZ1prrZCSz5WanJGvkGurkmvFVZxaoqCrq6CS@19DQ8XQzkhTU00ttSwxRwGsJkYlWsVQC6QTxNA1iq3VrjaCcgxja2P/g1RxpeTnpf4HAA). [Answer] # [Haskell](https://www.haskell.org/), 31 bytes ``` f m=[i|i<-[m..m*m-m],mod i m>1] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00h1zY6sybTRjc6V08vVytXNzdWJzc/RSFTIdfOMPZ/bmJmnoKtQkFRZl6JgopCmoLJfwA "Haskell – Try It Online") Math version: ``` f(m) = {i : i ∈ (m, m² - m), i mod m < 1} ``` :P [Answer] # [R](https://www.r-project.org/), ~~44~~ ~~43~~ 32 bytes ``` function(n)(x=n:(n^2-n))[x%%n>1] ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPU6PCNs9KIy/OSDdPUzO6QlU1z84w9n@ahonmfwA "R – Try It Online") Returns a vector. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` sƽḊṖ$⁺€ ``` [Try it online!](https://tio.run/##AR4A4f9qZWxsef//c8OGwr3huIrhuZYk4oG64oKs////MTY "Jelly – Try It Online") [Answer] # [Proton](https://github.com/alexander-liao/proton), 28 bytes ``` k=>filter(u=>1<u%k,k..k*~-k) ``` [Try it online!](https://tio.run/##KyjKL8nP@59m@z/b1i4tM6cktUij1NbO0KZUNVsnW08vW6tON1vzf0FRZl6JRpqGiabmfwA "Proton – Try It Online") Takes **m** as input. ### How? Filters the integers in **[k, k2-k)** that, when divided by **k**, yield a remainder higher than **1**. This ensures that both ends are trimmed, because the first one yields **0** and the last one yields **1**. It is also guaranteed to return a higher value for any valid integer, because they are consecutive. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes ``` Table[# i+j+1,{i,#-2},{j,#-2}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyQxKSc1WlkhUztL21CnOlNHWdeoVqc6C0zHqv0PKMrMK4lOi1aOjVXTdwhKzEtPjTaN/Q8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # Bash + GNU utilities, 35 ``` seq $1 $[$1*$1-$1]|sed 1~$1d\;2~$1d ``` [Try it online](https://tio.run/##Fcs7DoAgEAXAnlO8YisTSNbERuJJ1EJlDRZAFDs/V8dYTTXzlH1Z04GALeJiY5rHwiUli08IHYVWZTmhNSiULDuIQT1xRayJxzuLA7/EbrD1T/mjcilK@QA). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` LItä¦¨ε¦¨ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fx7Pk8JJDyw6tOLcVRP7/b2gGAA "05AB1E – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 44 bytes ``` lambda t:[k for k in range(t,~-t*t)if k%t>1] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHEKjpbIS2/SCFbITNPoSgxLz1Vo0SnTrdEq0QzM00hW7XEzjD2f0FRZl6JQpqGieZ/AA "Python 2 – Try It Online") I promise this is my last answer (to this challenge) today. Takes **m** as input. [Answer] # [Ruby](https://www.ruby-lang.org/), 32 bytes ``` ->m{(m..m*m-m).reject{|e|e%m<2}} ``` Takes `m`, returns a one-dimensional array. [Try it online!](https://tio.run/##KypNqvyfZvtf1y63WiNXTy9XK1c3V1OvKDUrNbmkuia1JlU118aotvZ/gUJatGEsF4gyglDGEMok9j8A "Ruby – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` :G\1>&*f ``` Input is `m`. Output is the numbers in increasing order. [**Try it online!**](https://tio.run/##y00syfn/38o9xtBOTSvt/38TAA "MATL – Try It Online") ### Explanation Consider input `4` as an example. ``` : % Implicit input: m. Push range [1 2 ... m-1 m] % STACK: [1 2 3 4] G\ % Modulo m, element-wise % STACK: [1 2 3 0] 1> % Greater than 1, element-wise. % STACK: [0 1 1 0] &* % Matrix of pair-wise products % STACK: [0 0 0 0; 0 1 1 0; 0 1 1 0; 0 0 0 0] f % Column vector of linear indices of nonzeros. Implicit display % STACK: [ 6; 7; 10; 11] ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 14 bytes ``` 1+⊢⊥¨∘⍳2⍴0⌈-∘2 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CYb/00Ck9qOuRY@6lh5a8ahjxqPezUaPercYPOrp0AVyjf7/LwEqqX7Uu/VR56IiIFMn7VHvLiv1tMTMHHUgCyhR9Ki7RT0/W72Wy7DkUe8aLiMwaVyiY8plUqJgpmCuYGigYGgIAA "APL (Dyalog Classic) – Try It Online") [Answer] ## Batch, 85 bytes ``` @for /l %%i in (3,1,%1)do @for /l %%j in (3,1,%1)do @cmd/cset/a(%%i-2)*%1+%%j-1&echo( ``` I can't easily loop from `2` to `m-1` so I loop from `3` to `m` and adjust in the calculation. [Answer] # [Julia 0.6](http://julialang.org/), 36 bytes ``` m->reshape(1:m*m,(m,m))[2:m-1,2:m-1] ``` [Try it online!](https://tio.run/##yyrNyUw0@59mm5Sanpn3P1fXrii1OCOxIFXD0CpXK1dHI1cnV1Mz2sgqV9dQB0zG/k/NS@FKyy9SyLU1tLJU4FIAgoKizLySnDyNXE0wNyWzuCAnsVIjDSigiaJAkwuo@z8A "Julia 0.6 – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 26 bytes ``` n->[x|x<-[n..n^2-n],x%n>1] ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1y66oqbCRjc6T08vL85INy9Wp0I1z84w9n9afpFGHlCNoY6CiY5CQVFmXgmQr6Sgawck0jTyNDU1/wMA "Pari/GP – Try It Online") [Answer] # Japt, 12 bytes I spent so long golfing the extraction of elements that I ran out of time to golf the array generation. I'm also only now noticing that we can take `n` as input instead so I may be able to save something there. To be revisited ... ``` òUnU²)òU m¤c ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=8lVuVbIp8lUgbaRj&input=OAotUQo=) --- ## Explanation ``` :Implicit input of integer U=m :e.g., 4 U² :U squared :16 Un :Minus U :12 ò :Range [U,U**2-U] :[4,5,6,7,8,9,10,11,12] òU :Partitions of length U :[[4,5,6,7],[8,9,10,11],[12]] m :Map ¤ : Remove first 2 elements :[[6,7],[10,11],[]] c :Flatten :[6,7,10,11] ``` [Answer] # [J](http://jsoftware.com/), 23 19 bytes -4 bytes thanks to FrownyFrog! ``` 1 1}:@}.-@%:}:\1+i. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRUMa60cavV0HVStaq1iDLUz9f5rcilwpSZn5CukKZhAGOrqMAFLdAFDM3QRYzOu/wA "J – Try It Online") My original olution: # [J](http://jsoftware.com/), 23 bytes ``` [:|:@}:@}.^:2-@%:]\1+i. ``` Takes n as input, returns a matrix ## How it works `1+i.` - generates a list 1..n `-@%:` - finds the square root of n and negates it (m) `]\` - makes a table (matrix) m x m from the list `^:2` - do the following twice: `|:@}:@}.` - drop the first row, then drop the last row, then transpose `[:` - cap the fork [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o61qrBxqgUgvzspI10HVKjbGUDtT778mlwJXanJGvkKaggmEoa4OE7BEFzA0QxcxNuP6DwA "J – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` ‼ȯTthS↑CN ``` [Try it online!](https://tio.run/##yygtzv7//1HDnhPrQ0oygh@1TXT2@///vykA "Husk – Try It Online") ## Explanation ``` ‼ȯTthS↑CN Implicit input, say m=4. CN Cut the natural numbers by m: [[1,2,3,4],[5,6,7,8],[9,10,11,12],.. S↑ Take first m lists: [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] ‼ȯ Do this twice: h Remove last row, t remove first row, T transpose. Result is [[6,7],[10,11]]; print it implicitly. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 bytes ``` ²õ òU ÅkJ ®ÅkJ ``` Takes `m` as input ## Explanation ``` ²õ òU ÅkJ ®ÅkJ // U = input | 3 U² // U squared | 9 õ // Range [1...U²] | [1,2,3,4,5,6,7,8,9] òU // Cut into slices of U | [[1,2,3],[4,5,6],[7,8,9]] Å // Remove the first item | [[4,5,6],[7,8,9]] kJ // Remove the last item | [[4,5,6]] ® // Map: | ÅkJ // Remove the first and last items | 5 ``` [Try it online!](https://tio.run/##y0osKPn//9Cmw1sVDm8KVTjcmu2lcGgdiPr/3wQA) --- The solution that takes `n` is also 14 bytes: ``` õ òU¬ ÅkJ ®ÅkJ ``` [Try it online!](https://tio.run/##y0osKPn///BWhcObQg@tUTjcmu2lcGgdiPr/39AMAA) [Answer] ## TI-BASIC, ~~44~~ 43 bytes (tokenized) ``` DC 4D 3F CE 4D 6D 32 3F CF 3F DE 2A 08 09 3F D0 3F 4D 71 32 3F 23 4D 70 32 70 58 70 32 B1 58 83 72 11 2B 58 2B 30 2B 72 0D 71 31 ``` Readable version: ``` :Input M :If M≤2 :Then :Disp "{} :Else :M-2 :seq(M+2+X+2int(X/Ans),X,0,Ans²-1 ``` --- It was unfortunately necessary to print empty lists manually since TI-BASIC does not normally allow that. If `m` were given greater than two, the code could be reduced to just **29 bytes**. [Answer] # [Pyth](https://pyth.readthedocs.io), 10 bytes ``` mtPdtPcQS* ``` **[Try it here!](https://pyth.herokuapp.com/?code=mtPdtPcQS%2a&input=4&debug=0)** Takes **m** as input. [Answer] # [Red](http://www.red-lang.org), 63 62 bytes ``` f: func[n][repeat i(n - 2 * n)[if(a: n + i)// n > 1[print a]]] ``` [Try it online!](https://tio.run/##Rcg7CoAwEAXA3lM8rBJFxF9j4SFsly2CZiHNIkHPHyWCdsNEv6fV7yBOMkMu3UiZoj@8OxGMokGPCmopiHEzFDWCbdsHCzo6YtATjpnTy1LMYMtCMBRfjDnGP6YcU7oB "Red – Try It Online") This is a Red port of totallyhuman's Haskell / Mr. Xcoder's Python 2 solution [Answer] # [Clean](https://clean.cs.ru.nl), 45 bytes ``` import StdEnv $m=[i\\i<-[m..m*m-m]|i rem m>1] ``` [Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4xLJdc2OjMmJtNGNzpXTy9XK1c3N7YmU6EoNVch184w9n9wSSJQsa2CivH/f8lpOYnpxf91PX3@u1TmJeZmJhcDAA "Clean – Try It Online") This is just [totallyhuman's Haskell answer](https://codegolf.stackexchange.com/a/154687/18730) but in Clean. [Answer] # [Pyt](https://github.com/mudkip201/pyt), 13 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage) ``` ĐĐ⁻⁻ř*⇹⁻⁻ř⁺ɐ+ ``` Port of [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/154708/77078) Explanation: ``` Implicit input (takes m) ĐĐ Triplicate the input (push it on the stack two more times) ⁻⁻ Decrement top of stack twice ř Push [1,2,...,m-2] * Multiplies by m ⇹ Swaps top two items on stack ⁻⁻ Decrement (m-2 is now on top) ř Push [1,2,...,m-2] ⁺ Increment each element by 1 ɐ+ Add [2,3,...,m-1] to each element of [m,2m,...,m(m-2)] Implicit print ``` [Try it online!](https://tio.run/##K6gs@f//yIQjEx417gaiozO1HrXvhLEfNe46OUH7/39TAA) [Answer] # Python, 111 bytes ``` def f(s): r=[] for i in[i[1:-1]for i in[[(j*s)+i+1 for i in range(s)]for j in range(s)][1:-1]]:r+=i return r ``` [Answer] # [Java 8](http://www.oracle.com/technetwork/java/javase/overview/java8-2100321.html), ~~241~~ ~~183~~ ~~170~~ ~~162~~ ~~160~~ ~~132~~ 122 bytes ``` j->{if(j<3)return new int[1];int e[]=new int[j*j-4*j+4],x=0,i=0;for(;++i<=j*j;)if(!(i<j|i>j*j-j|i%j<2))e[x++]=i;return e;} ``` [Try it online!](https://tio.run/##nZPfboIwFMbveYozkiXFCoHp/qVg4gPsykvCRafVtYNiSnUax7OzImwhxpilvTnJ1/6@06/pEXRP/XLLpFh9Ntvde86XsMxpVcEb5fLkOGAWl5qpNV0ymMPprPRqmgFFpgL3yFmvnY6oNNXGaQ4UEmiEPzvxNRLxxFNM75QEyb7OfJSRFmdplvxKYiT86UjgaTY@JOGYJyFZlwoRjHmcmE3iGas7xGPxzWftYVPvRfzgeSw9YJwlnPRNGKkbYu7Tx@rvtC/5CgoTDi204nLTZlCbyhsk2xpdz5WiR0QDiiKvT9euxbHSrAjKnQ7Ox3KJBrsX5IM1ObEmp9bkozX5ZE0@W5Mv1uSrNRmF/0PrbgqufLyBYTc/xfDjXToiN3UHDc0cQDduZqpCYkoMRZAzudEf4ENkFIyHflc9i5RngMEdw9C7dm4AwybZ7RdwM/fvEermBw "Java (OpenJDK 8) – Try It Online") Java makes it very tough(lots of bytes) when you have to create an array of somewhat "unknown" size. * -8 bytes thanks to Magic Octopus Urn * -28 bytes thanks to Mr. Xcoder * -10 bytes thanks to Kevin Cruijssen ]
[Question] [ Another easy challenge for you. ## Your task Write a program or function that takes the input, which contains 3 pairs of x- and y-coordinates and calculates the area of the triangle formed inside them. For those who can't remember how to calculate it, you can find it [here](https://en.wikipedia.org/wiki/Triangle#Computing_the_area_of_a_triangle). ### Example: ``` 1,2,4,2,3,7 # input as x1,y1,x2,y2,x3,y3 7.5 # output ``` See it at [Wolfram Alpha](http://www.wolframalpha.com/input/?i=%5B1%2C2%5D%5B4%2C2%5D%5B3%2C7%5D+Triangle) Some considerations: * The input will be six base 10 positive integers. * You may assume the input is **in any reasonable format**. * The points will always form a valid triangle. * You can assume the input is already stored in a variable such as `t`. * The shortest code in bytes wins! **Edit: To avoid any confusion I've simplificated how the input should be dealt without jeopardizing any of the current codes.** **Remember that the your program/function must output a valid area, so it can't give a negative number as output** [Answer] # CJam, ~~18~~ 16 bytes ``` T(f.-~(+.*:-z.5* ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%3AT%3B%20e%23%20Store%20input%20in%20T.%0A%0AT(f.-~(%2B.*%3A-z.5*&input=%5B%5B1%202%5D%20%5B4%202%5D%20%5B3%207%5D%5D). ### Idea As mentioned on [Wikipedia](https://en.wikipedia.org/wiki/Triangle#Using_coordinates "Triangle - Wikipedia, the free encyclopedia"), the area of the triangle `[[0 0] [x y] [z w]]` can be calculated as `|det([[x y] [z w]])| / 2 = |xw-yz| / 2`. For a generic triangle `[[a b] [c d] [e f]]`, we can translate its first vertex to the origin, thus obtaining the triangle `[[0 0] [c-a d-b] [e-a f-b]]`, whose area can be calculated by the above formula. ### Code ``` T e# Push T. e# [[a b] [c d] [e f]] ( e# Shift out the first pair. e# [[c d] [e f]] [a b] f.- e# For [c d] and [e f], perform vectorized e# subtraction with [a b]. e# [[c-a d-b] [e-a f-b]] ~ e# Dump the array on the stack. e# [c-a d-b] [e-a f-b] (+ e# Shift and append. Rotates the second array. e# [c-a d-b] [f-b e-a] .* e# Vectorized product. e# [(c-a)(f-b) (d-b)(e-a)] :- e# Reduce by subtraction. e# (c-a)(f-b) - (d-b)(e-a) z e# Apply absolute value. e# |(c-a)(f-b) - (d-b)(e-a)| .5* e# Multiply by 0.5. e# |(c-a)(f-b) - (d-b)(e-a)| / 2 ``` [Answer] # Mathematica, 27 bytes ``` Area@Polygon@Partition[t,2] ``` [Answer] # JavaScript (ES6) 42 ~~.44.~~ **Edit** Input format changed, I can save 2 bytes An anonymous function that take the array as a parameter and returns the calculated value. ``` (a,b,c,d,e,f)=>(a*(d-f)+c*(f-b)+e*(b-d))/2 ``` Test running the snippet below in an EcmaScript 6 compliant browser. ``` f=(a,b,c,d,e,f)=>(a*(d-f)+c*(f-b)+e*(b-d))/2 function test() { var v=I.value.match(/\d+/g) I.value = v R.innerHTML=f(...v) } ``` ``` <input id=I onchange="test()"><button onclick="test()">-></button><span id=R></span> ``` [Answer] # Julia, 32 bytes ``` abs(det(t[1:2].-t[[3 5;4 6]]))/2 ``` Constructs a matrix of the appropriate terms of a cross product, uses `det` to get the resulting value, takes absolute value to deal with negatives, and then divides by 2 because it's a triangle and not a parallelogram. [Answer] # Matlab/Octave, 26 bytes I did not know about this built in so far=) ``` polyarea(t(1:2:5),t(2:2:6)) ``` [Answer] # Java, ~~79~~ 88 bytes ``` float f(int[]a){return Math.abs(a[0]*(a[3]-a[5])+a[2]*(a[5]-a[1])+a[4]*(a[1]-a[3]))/2f;} ``` Just uses the basic formula, nothing special. Edit: Forgot to take the absolute value :( [Answer] ## [Minkolang 0.8](http://esolangs.org/wiki/Minkolang), 34 bytes ``` ndndn0g-n1g-n0g-n0g-1R*1R*-$~2$:N. ``` Anyone want some egg-`n0g`? ### Explanation Very straightforward. Uses the formula `|(x2-x1)(y3-y1) - (x3-x1)(y2-y1)|/2`. ``` nd x1, x1 nd x1, x1, y1, y1 n0g- x1, y1, y1, x2-x1 n1g- x1, y1, x2-x1, y2-y1 n0g- y1, x2-x1, y2-y1, x3-x1 n0g- x2-x1, y2-y1, x3-x1, y3-y1 1R* y3-y1, x2-x1, (y2-y1)(x3-x1) 1R* (y2-y1)(x3-x1), (y3-y1)(x2-x1) - (y2-y1)(x3-x1) - (y3-y1)(x2-x1) $~ |(y2-y1)(x3-x1) - (y3-y1)(x2-x1)| 2$: |(y2-y1)(x3-x1) - (y3-y1)(x2-x1)|/2 (float division) N. Output as integer and quit. ``` [Answer] # [JayScript](https://github.com/minxomat/JayScript), 58 bytes Declares an anonymous function: ``` function(a,b,c,d,e,f){return (a*(d-f)+c*(f-b)+e*(b-d))/2}; ``` Example: ``` var nFunct = function(a,b,c,d,e,f){return (a*(d-f)+c*(f-b)+e*(b-d))/2}; print(nFunct(1,2,4,2,3,7)); ``` [Answer] # Ruby, 45 ``` ->a,b,p,q,x,y{((a-x)*(q-y)-(p-x)*(b-y)).abs/2} ``` [Answer] # PHP – 68 ~~88~~ ~~89~~ bytes Thanks to Martjin for some great pointers! ``` <?=.5*abs(($t[1]-$t[5])*($t[4]-$t[2])-($t[1]-$t[3])*($t[6]-$t[2]))?> ``` To use it, create a file `area.php` with this content, the extra line meets the *assume the data is saved in a variable `t`* part of the specs, and the ␍ at the end adds a carriage return so the output is nice and separated: ``` <?php $t = $argv; ?> <?=.5*abs(($t[1]-$t[5])*($t[4]-$t[2])-($t[1]-$t[3])*($t[6]-$t[2]))?> ␍ ``` Then provide the coordinates on the command line as `x₁ y₁ x₂ y₂ x₃ y₃`, e.g. ``` $ php area.php 1 2 4 2 3 7 7.5 ``` [Answer] # Pyth, ~~34~~ 30 bytes ``` KCcQ2c.asm*@hKd-@eKhd@eKtdU3 2 ``` [Try it online.](http://pyth.herokuapp.com/?code=KCcQ2c.asm%2a%40hKd-%40eKhd%40eKtdU3+2&input=1%2C2%2C3%2C7%2C4%2C2&debug=0) Works by calculating abs(a\*(d-f) + c\*(f-b) + e\*(b-d))/2 from input a,b,c,d,e,f. [Answer] # R, 37 bytes ``` cat(abs(det(rbind(matrix(t,2),1))/2)) ``` Converts the vector of coordinates into a matrix and tacks on a row of 1's. Calculates the determinant and divides by 2. Returns the absolute result. If the order was always clockwise the `abs` would not be required. ``` > t = c(1,2,4,2,3,7) > cat(det(rbind(matrix(t,2),1))/2) 7.5 ``` [Answer] # Python 2, ~~48~~ ~~47~~ 50 bytes Very simple; follows the standard equation: ``` lambda a,b,c,d,e,f:abs(a*(d-f)+c*(f-b)+e*(b-d))/2. ``` The other, similarly simple approaches are longer: ``` def a(a,b,c,d,e,f):return abs(a*(d-f)+c*(f-b)+e*(b-d))/2. # 57 lambda t:abs(t[0]*(t[3]-t[5])+t[2]*(t[5]-t[1])+t[4]*(t[1]-t[3]))/2. # 67 def a(t):return abs(t[0]*(t[3]-t[5])+t[2]*(t[5]-t[1])+t[4]*(t[1]-t[3]))/2. # 74 ``` Python's access to a determinate function is through [numpy](https://stackoverflow.com/a/462514/2676531). Thanks to [muddyfish](https://codegolf.stackexchange.com/users/32686/muddyfish) for 1 byte and [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for catching an error. [Answer] ## PHP, 77 Based on @Yimin Rong's answer, I felt I could improve upon it by a few bytes by using `list()` rather than straight `$argv` to abbreviate some variables. Also `echo` doesn't need a space if there is delimiter between echo and the thing being echoed. `echo$variable;`, `echo(4+2);`, and `echo'some string';` are equally valid whereas `echofunction($variable)` confuses PHP. On the other hand, I also added `abs()` to be mathematically accurate, since some combinations of vertices yielded "negative area" ``` list($t,$a,$b,$c,$d,$e,$f)=$argv;echo.5*abs(($a-$e)*($d-$b)-($a-$c)*($f-$b)); ``` You can run it via CLI ``` php -r "list($t,$a,$b,$c,$d,$e,$f)=$argv;echo.5*abs(($a-$e)*($d-$b)-($a-$c)*($f-$b));" 1 2 4 2 3 7 7.5 ``` [Answer] # AWK – 51 ~~42~~ bytes AWK has no built-in `abs` so using `sqrt(x^2)` to substitute. ``` {print sqrt((($1-$5)*($4-$2)-($1-$3)*($6-$2))^2)/2} ``` Save as `area.awk` and use as `echo x₁ y₁ x₂ y₂ x₃ y₃ | awk -f area.awk`, e.g. ``` $ echo 1 2 4 2 3 7 | awk -f area.awk 7.5 ``` [Answer] # PowerShell, 70 Bytes ``` [math]::Abs(($t[0]-$t[4])*($t[3]-$t[1])-($t[0]-$t[2])*($t[5]-$t[1]))/2 ``` Uses the same standard formula as other solutions. Per the question, assumes the array is pre-populated, e.g. `$t=(1,2,4,2,3,7)`. But *ooof*, does the `$` and `[]` syntax kill this one... [Answer] ## [dc](https://en.wikipedia.org/wiki/Dc_(computer_program)), 52 bytes Assumes the input is in register `t` as: `x1 y1 x2 y2 x3 y3` with `x1` at the top of `t`'s stack. ``` 1kLtLtsaLtsbLtdscLtltrlalclbltla-*sd-*se-*leld++2/p ``` `1 2 4 2 3 7stStStStStSt #puts coordinates into register t (closest thing dc has to variables) 1kLtLtsaLtsbLtdscLtltrlalclbltla-*sd-*se-*leld++2/p 7.5` This uses the following formula for area: `(x1(y2-y3) + x2(y3-y1) + x3(y1 - y2))/2` And for a quick breakdown of the process: * `1k Lt Lt sa Lt sb Lt d sc Lt lt r`: set decimal precision to 1 place, move parts of the stack in `t` to the main stack and move various parts of the main stack to other registers for storage (`d` duplicates the top of main stack, `r` reverses the top two elements of main stack, `L/l` move/copy from the given register to main, `s` moves top of main stack to the given register) Main: `y3 x3 y2 x1` a: `y1`, b: `x2`, c: `y2`, t: `y3` * `la lc lb lt la`: copy the top of the stacks in registers `a`, `c`, `b`, `t`, and `a` to the main stack in that order Main: `y1 y3 x2 y2 y1 y3 x3 y2 x1` a: `y1`, b: `x2`, c: `y2`, t: `y3` * `- * sd`: calculate `((y3-y1)*x2)` and put result in `d` (registers `a`, `b`, `c`, and `t` are no longer used so I'll drop them from the list of stacks now) Main: `y2 y1 y3 x3 y2 x1` d:`((y3-y1)*x2)` * `- * se - *`: compute `((y1-y2)*y3)` and `((y2-x3)*x1)`; store the former in `e` and leave the latter on the main stack Main: `((y2-x3)*x1)` d:`((y3-y1)*x2)`, e:`((y1-y2)*y3)` * `le ld + +`: copy top of register `e` and `d` to the main stack, calculate sum of top 2 stack values (pushing result back to main stack) twice Main: `(((y3-y1)*x2)+((y1-y2)*y3)+((y2-x3)*x1))` d:`((y3-y1)*x2)`, e:`((y1-y2)*y3)` * `2 /`: push 2 onto main stack, divide 2nd values on stack by the 1st (`d` and `e` are no longer used, dropping them from list of stacks) Main: `(((y3-y1)*x2)+((y1-y2)*y3)+((y2-x3)*x1))/2` Rearranging the value on the stack we can see it's equivalent to the formula at the top of this explanation: `(x1(y2-y3) + x2(y3-y1) + x3(y1 - y2))/2` * `p`: Print top of main stack to output. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` _ḢÆḊHA ``` [Try it online!](https://tio.run/##y0rNyan8/z/@4Y5Fh9se7ujycPz//3@0oY5RrE60CZg01jGPBQA "Jelly – Try It Online") Takes input as 3 pairs `[a,b],[c,d],[e,f]` as Jelly has no concept of variables ## How it works This implements the method outlined on [Wikipedia](https://en.wikipedia.org/wiki/Triangle#Using_coordinates) that [Dennis' answer](https://codegolf.stackexchange.com/a/60803/66833) uses, in that, the area of a triangle \$(0,0), (x,y), (v,w)\$ is $$\frac12\left|\det\left[\begin{matrix} x & y \\ v & w \end{matrix}\right]\right|$$ and that, for an arbitrary triple of points \$(a,b),(c,d),(e,f)\$, we can translate them to form a triangle with a corner on the origin: \$(0,0),(c-a,d-b),(e-a,f-b)\$, so the area is $$\frac12\left|\det\left[\begin{matrix} c-a & d-b \\ e-a & f-b \end{matrix}\right]\right|$$ ``` _ḢÆḊHA - Main link. Takes [[a, b], [c, d], [e, f]] on the left Ḣ - Remove [a,b] and yield it _ - Vectorised subtraction from each of [[c, d], [e, f]] which yields [[c-a, d-b], [e-a, f-b]] ÆḊ - Determinant H - Halve A - Absolute value ``` ]
[Question] [ You host the Olympic Games, and need to build a fantastic pool for the sake of the occasion, but the supervisors often change their mind regarding the dimensions, and need a quick way to rebuild it with the requested size! --- Given two integers, `L` and `x`, your task is to build a swimming pool of length `L` and `x` lanes. # How is a pool built? * It contains an inner square, whose horizontal walls are made of `L` consecutive dashes(`-`) , and whose vertical walls are made out of `3x - 1` bars (`|`). Additionally, 4 `+` signs lie in each corner. Let's have an example (`L = 10, x = 2`): ``` +----------+ | | | | | | | | | | +----------+ ``` * *Each lane* has a width of 2 vertical units. The inner square is filled with `x-1` lane separators, consisting of `L` horizontally consecutive `:` symbols. After putting the lane separators, our pool should look like this: ``` +----------+ | | | | |::::::::::| | | | | +----------+ ``` * A pool also contains a *padding* (an outer square), whose horizontal walls are (L+4) `-`s and whose vertical walls are (3x + 1) `|`s, that surrounds the inner square: ``` +--------------+ | +----------+ | | | | | | | | | | |::::::::::| | | | | | | | | | | +----------+ | +--------------+ ``` And that's our olympic-sized\*\* swimming pool! --- # Specs: * For design and functionality purposes, you are guaranteed that `100 ≥ L ≥ 10` and `15 ≥ x ≥ 2`. * The output must be exactly as shown. Outputting a "vertically-built"\* pool is disallowed. * Trailing and leading spaces are allowed. * You may take input and provide output through [any standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. --- # Examples / Test cases: ``` L = 20, x = 3 +------------------------+ | +--------------------+ | | | | | | | | | | |::::::::::::::::::::| | | | | | | | | | | |::::::::::::::::::::| | | | | | | | | | | +--------------------+ | +------------------------+ L = 50, x = 5: +------------------------------------------------------+ | +--------------------------------------------------+ | | | | | | | | | | |::::::::::::::::::::::::::::::::::::::::::::::::::| | | | | | | | | | | |::::::::::::::::::::::::::::::::::::::::::::::::::| | | | | | | | | | | |::::::::::::::::::::::::::::::::::::::::::::::::::| | | | | | | | | | | |::::::::::::::::::::::::::::::::::::::::::::::::::| | | | | | | | | | | +--------------------------------------------------+ | +------------------------------------------------------+ L = 10, x =15 +--------------+ | +----------+ | | | | | | | | | | |::::::::::| | | | | | | | | | | |::::::::::| | | | | | | | | | | |::::::::::| | | | | | | | | | | |::::::::::| | | | | | | | | | | |::::::::::| | | | | | | | | | | |::::::::::| | | | | | | | | | | |::::::::::| | | | | | | | | | | |::::::::::| | | | | | | | | | | |::::::::::| | | | | | | | | | | |::::::::::| | | | | | | | | | | |::::::::::| | | | | | | | | | | |::::::::::| | | | | | | | | | | |::::::::::| | | | | | | | | | | |::::::::::| | | | | | | | | | | +----------+ | +--------------+ ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code *in bytes* wins! \*The water could flow out if it is built vertically :P \*\*Yes, I am aware that the more the lanes are and the shorter the pool is, the less the drawing looks like a pool! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` NθNη↓Eθ×η: B⁺θ²⁺׳η¹↖←B⁺θ⁶⁺×³η³ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9nnXndoCI7Y/aJr/fs/TcjsPTz223UlB4v2fRo8Zd53Yc2gSkDk8/tPnc9kM7H7VNe9Q2ASb1qHEbQm7z//@mBlymAA "Charcoal – Try It Online") -4 thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil). AST: ``` Program ├N: Input Number │└θ: Identifier θ ├N: Input Number │└η: Identifier η ├Print │├↓: Down │└E: Map │ ├θ: Identifier θ │ └×: Product │ ├η: Identifier η │ └': ': String ': ' ├B: Box │├⁺: Sum ││├θ: Identifier θ ││└2: Number 2 │└⁺: Sum │ ├×: Product │ │├3: Number 3 │ │└η: Identifier η │ └1: Number 1 ├Move │└↖: Up Left ├Move │└←: Left └B: Box ├⁺: Sum │├θ: Identifier θ │└6: Number 6 └⁺: Sum ├×: Product │├3: Number 3 │└η: Identifier η └3: Number 3 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 40 39 37 bytes ``` NθNηB⁺θ⁶⁺׳η³↘→B⁺θ²⁺׳η¹→F⁻η¹«M³↓P×:θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9nnXndoCI7e/3LHrUuOvcjkeN24D04emHNp/bfmjzo7YZj9omweQObUJI7QSLL3vUuBvEObT6/Z61IOWT3@/ZcHi61bkd//9HmxroKJjGAgA "Charcoal – Try It Online") I know [Neil](https://codegolf.stackexchange.com/users/17602/neil) already has a Charcoal answer of around the same length, but I took a bit of a different approach so I figured I may as well also post mine. ## Explanation ``` NθNηB⁺θ⁶⁺׳η³↘→B⁺θ²⁺׳η¹→F⁻η¹«M³↓P×:θ NθNη take the two inputs as numbers in θ and η B⁺θ⁶⁺×³η³ draw a rectangle θ + 6 by 3η + 3 (characters default to |, - and +) ↘→ move the cursor down one and right two B⁺θ²⁺×³η¹ draw a rectangle θ + 2 by 3η + 1 F⁻η¹« for ι (unused) from 0 up until η - 1: M³↓ move the cursor down by 3 P×:θ print θ :s without moving the cursor [implicit end of for] ``` [Answer] # Charcoal, ~~40~~ ~~38~~ ~~36~~ 31 bytes ``` A⁺²NθA⁺¹×³NηUOθη:¶¶Bθη↖←B⁺⁴θ⁺²η ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU8jIKe0WMNIR8Ezr6C0xK80Nym1SENTU0ehUNOaC1mJoY5CSGZuarGGMbpaoOIMoGL/pJz8vHSNQiBPR0HJKiYvJk8JKOyUXwEWAzJ988tSNaxCC3xS00rgXCgHpAxsjwnIah0FmLMyNDWt//83NeAy/a9b9l@3OAcA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` A⁺²Nθ Assign(Plus(2, InputNumber()), q); ``` Charcoal's drawing primitives use the overall character count including `+`s, however the input is just the number of `-`s, so we need to add 2 to obtain the width of the inner wall. ``` A⁺¹×³Nη Assign(Plus(1, Times(3, InputNumber())), h); ``` Calculate the height of the inner wall, again, inclusive of the bottom row, so three per lane plus one. ``` UOθη:¶¶ Oblong(q, h, ":\n\n"); ``` Draw the lanes. This is simply a rectangle filled with `:`s vertically separated by two blank lines (the pilcrows represent newline characters). ``` Bθη Box(q, h); ``` The `Rectangle` command is exactly what we need to draw the inner wall. Edit: `Box` allows you to omit its third parameter, saving me 2 bytes. ``` ↖ Move(:UpLeft); ← Move(:Left); B⁺⁴θ⁺²η Box(Plus(4, q), Plus(2, h)); ``` And again to draw the outer wall, except slightly wider and taller, and centred on the inner wall. [Answer] # T-SQL, ~~284~~ 281 bytes ``` DECLARE @ INT,@x INT,@S VARCHAR(MAX)='+--d--+b| +d+ |b'SELECT @=L,@x=x FROM t P:SET @S+='| |s| |b| |s| |b| |c| |b'SET @x-=1IF @x>0GOTO P PRINT REPLACE(REPLACE(REPLACE(REPLACE(LEFT(@S,LEN(@S)-6)+'+d+ |b+--d--+','d',REPLICATE('-',@)),'b',CHAR(13)),'s',SPACE(@)),'c',REPLICATE(':',@)) ``` Input is taken from INT columns **L** and **x** in preexisting table **t**, [per our allowed input methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). Basically I'm creating a long string with letters representing the repeated characters (d=dashes, s=spaces, c=colons, b=line break), then REPLACE them all at the end with the appropriate fillers. Formatted: ``` DECLARE @ INT,@x INT,@S VARCHAR(MAX)='+--d--+b| +d+ |b' SELECT @=L,@x=x FROM t P: SET @S+='| |s| |b| |s| |b| |c| |b' SET @x-=1 IF @x>0 GOTO P PRINT REPLACE(REPLACE(REPLACE(REPLACE( LEFT(@S,LEN(@S)-6)+'+d+ |b+--d--+' ,'d',REPLICATE('-',@)) ,'b',CHAR(13)) ,'s',SPACE(@)) ,'c',REPLICATE(':',@)) ``` Inside the loop I append 2 rows of blanks and 1 row of colons, then at the end I chop off that divider row and append the pool border before performing the replaces. **EDIT**: Saved 3 bytes by switching `@` to the most-often used variable, and swapping initialization order. [Answer] # JavaScript (ES6), ~~137~~ 124 bytes Golfed it down a bit on my phone, more to follow. ``` x=>y=>`+--0--+ | +0+ | ${((a=`| |1| | `)+a+`| |2| | `).repeat(y-1)+a+a}| +0+ | +--0--+`.replace(/\d/g,n=>"- :"[n].repeat(x)) ``` --- ## Try it ``` f= x=>y=>`+--0--+ | +0+ | ${((a=`| |1| | `)+a+`| |2| | `).repeat(y-1)+a+a}| +0+ | +--0--+`.replace(/\d/g,n=>"- :"[n].repeat(x)) oninput=_=>o.innerText=f(+i.value)(+j.value);o.innerText=f(i.value=50)(j.value=5) ``` ``` input{font-family:sans-serif;margin:0 5px 0 0;width:50px;} ``` ``` <label for=i>L: </label><input id=i type=number><label for=j>x: </label><input id=j type=number><pre id=o> ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~124~~ ~~120~~ 117 bytes -2 bytes thanks to Hyper Neutrino ``` l,x=input() o='+--%s--+\n| +%s+ |\n'%(('-'*l,)*2) print o+'| |%s| |\n'*(x*3-1)%((' '*l,' '*l,':'*l)*x)[:-1]+o[-2::-1] ``` [Try it online!](https://tio.run/##LcpBCsMgEEDRfU4xGxnHcaCx7UbISZLuGwgq1YIB725r6ebzFy@d5RmD6/2wddlDehdNU1yQRVQW4S00YJUZ2hZQaY2C5rBkHE3ptYcCkbFBU7n9hNHVXGWmIWHIf/23ZCqtXuYHx1WcH9f7/WJvHw "Python 2 – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~52~~ 51 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` :┌* +1Ο;@*┐1ΟG∙⁴++⁰ b3*Ie4+⁰b3*He⁰32žbH∫3*2+4;e :*ž ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=YjMqSGUlM0EldTI1MEMqJTIwKzEldTAzOUYlM0JAKiV1MjUxMDEldTAzOUZHJXUyMjE5JXUyMDc0KytiMypJZTQrJTNBJXUyNTBDKiUyMCsxJXUwMzlGJTNCQColdTI1MTAxJXUwMzlGRyV1MjIxOSV1MjA3NCsrJXUyMjA2MCV1MjU2QzViSCV1MjIyQjMqMis0JTNCZSUyMCUzQSoldTAxN0U_,inputs=NSUwQTUw) Not bad considering that 20 bytes of this is a rectangle function, which charcoal has a built-in for. Explanation: ``` Rectangle function: (example: on stack 4, 2) : duplicate the top of stack (X pos) [4, 2, 2] ┌* get that many "-"es [4, 2, "--"] + push "+" [4, 2, "--", "+"] 1Ο wrap the dashes in pluses [4, 2, "+--+"] ; get the duplicated X position [4, "+--+", 2] @* get that many spaces [4, "+--+", " "] ┐ push "|" [4, "+--+", " ", "|"] 1Ο wrap the spaces with "|" [4, "+--+", "| |"] G get the Y value ontop ["+--+", "| |", 4] ∙ get an array with that many strings ["+--+", ["| |", "| |", "| |", "| |"]] ⁴ duplicate the dashes wrapped in pluses ["+--+", ["| |", "| |", "| |", "| |"], "+--+"] ++ add everything to one array [["+--+", "| |", "| |", "| |", "| |", "+--+"]] Main function: (example input: 2, 5) b3* push variable B (input 1, Y length) multiplied by 3 [6] I increase it [7] e4+ push variable E (input 2, X length) + 4 [7, 9] ⁰ execute the rectangle function [in X: E+4, Y: b*3+1] [["+---------+","| |","| |","| |","| |","| |","| |","| |","+---------+"]] b3* push variable B * 3 [["+---------+",..,"+---------+"], 6] H decrease it [["+---------+",..,"+---------+"], 5] e push variable E [["+---------+",..,"+---------+"], 5, 5] ⁰ execute the rectangle function [on X: E, Y: B*3-1] [["+---------+",..,"+---------+"], ["+-----+","| |","| |","| |","| |","| |","+-----+"]] 32ž at coordinates [3;2] (1-indexed) in the first rectangle put in the 2nd [["+---------+", "| +-----+ |", "| | | |", "| | | |", "| | | |", "| | | |", "| | | |", "| +-----+ |", "+---------+"] bH∫ iterate over the numbers from 1 to B-1: [[...], 1] 3*2+ push pop()*3+2 [[...], 5] 4; push 4 one below the stack [[...], 4, 5] e push the variable E (X length) [[...], 4, 5, 5] :* get that many colons [[...], 4, 5, ":::::"] ž insert [at coordinates [4; cIter*3+2] the colons] ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 202 bytes ``` (L,x)=>{char p='+',n='\n',e=' ';string v="|",r="",s=p+new string('-',L+4)+p+n,q=v+e+p+new string('-',L)+p+e+v+n;r+=s+q;for(int i=0;i<3*x-1;)r+=v+e+v+new string(i++%3<2?e:':',L)+v+e+v+n;r+=q+s;return r;} ``` [Try it online!](https://tio.run/##jY9BS8NAEIXv/RVDQDbrbEpqLUI3Ww@CpwiCh168hLipC@1us7tdKzW/PSapGEEPvsMwzPvmMVO6pDRWttCp3BbOwaM1G1vsJv3kNNRezhdelRCMeoGHQumYflsj1Ovp3Xm5m94fdJkp7RkMxXmr9GYFFYhJG@fsSMXqVL4WFvaCIGFakGdNmBQECD/DEET0ETEroog5sUct375iYpIQluM1xW7KahFQ4m@/dyUG1NyicFjzyti4OwaUSLnK5pfHZMZp54UzNq4rxIt5dnUrl2Q5BIUxqEbHrfQHq8HypuWTv56/M9qZrZyurfIyV1rGVbxIGSwo5f/lbzp@lv5caIauaT8B "C# (.NET Core) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~128~~ 126 bytes ``` L,x=input() k='+'+'-'*(L+4)+'+\n| +'+'-'*L+'+ |\n' f=lambda k:'| |'+k*L+'| |\n' print k+f(':').join([f(' ')*2]*x)[:-1]+k[::-1] ``` [Try it online!](https://tio.run/##LYlNCoMwFIT3nuLtXn5UVNpNIDfIDaILS5GmaZ9BUrCQu8dIyyy@mfnCNz5WGnI29a4dhU9kvPIaZUmDghl54aWPlOB/mUJII2G16Nf8vt1n8AoTJJT@lOknw@YogpcLQ4W8fa6OmC0DkIthEju3qukn6a06mXPfdfX1AA "Python 2 – Try It Online") -2 bytes thanks to @Mr.Xcoder [Answer] # [PHP](https://php.net/), 153 bytes ``` for(;$i-2<$z=3*$argv[2]+1;$i++)echo str_pad(strrev($r=["--+","+ |","| |"][!($b=$i>1&$i<$z)?$i&&$i<$z+1?1:0:2]),$argv[1]+3,"- :"[$b?$i%3!=1?1:2:0])."$r "; ``` [Try it online!](https://tio.run/##JYxBDoMgEEX3nkInUwNFGsEdSj0IIY22trKS0MZF490p1s2byc/L87OPXe9nn@EQXqs2wKGCpt4Bto3PJZAWHZcdfnVz/ktGWibSyBid7vOSvz/h5ocHSTdMK8GwVzhLCZZviVuiNQXBUaO7ihJditEeXXm8TPRC1UpaWh19YVlTAc8VGByTd2oKvTtS1ZZeAEMGbYw/ "PHP – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 97 bytes ``` L,x=input() for i in'01'+'223'*~-x+'2210':r=('+|||- -+||'+L*'-- :')[int(i)::4];print r+r[2::-1] ``` [Try it online!](https://tio.run/##FcdBCoQwDADAu6/ILa01YKsgZPEH/kC8LptLLaGCQtmvV73NpCv/9hhqXbpzlpiObGzz3RUEJGLv0WEIA7Z/Ol/5Hllng66UQgBAD9AtLRIBo10lZiOWedw@SZ@AOl0DM/mt1qkbbw "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), 98 bytes ``` L,x=input() s='+---| +-%s+-+---'%'|:'.join(['| '*5]*x) while s:print s[:3]+s[3]*L+s[2::-1];s=s[4:] ``` [Try it online!](https://tio.run/##FcZLCoMwEADQvafIRkYTR6gfClNyA28QZlkwpcTgRGohd0/r6r34TesWhlKW7rQ@xCM1bSUWDCJmZbAWg9ehhkzQvzYfGgdZgZ5Zn231Wf37qYTi7kNS4mhkI25kvfwZiPDGD7HiJuJS7t30Aw "Python 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` NθNηFη«M³↑P×θ:»←B⁺θ²⁺׳η¹↖←B⁺θ⁶⁺×³η³ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9nnXndoCI7e/3LDu3/dDq93vWHtr8qG3i@z0bDk8/t8Pq0O5HbRPe71n0qHHXuR2HNgGpw9MPbQaq3PmobRqS1KPGbQi5zf//mxpwmQIA "Charcoal – Try It Online") This is a more Charcoal-y algorithm than my other answer. [Answer] # [C (gcc)](https://gcc.gnu.org/), 195 bytes ``` #define P printf y;f(L,l){char s[L+1],t[L+1];memset(s,45,L);memset(t,58,L);t[L]=s[L]=0;P("+-%s-+\n|+%s+|\n",s,s);for(y=3*l;y-->1;y%3?P("||%*c||\n",L,32):P("||%s||\n",t));P("|+%s+|\n+-%s-+",s,s);} ``` [Try it online!](https://tio.run/##fY/LasMwEEX3/grhYNBjBLIdQ6lI@wNeZF9nERSpNcRKkNSCifLtrmw3y2YzjzuXMzOKfyo1TZuTNr3VaI@urrfBZKM0uIUzuamvo0P@o2XlAcKS5KAHrwP2sG2gJY82QPMyt8l02Pk5CLnHOeOF56yzkRWexc7m4METaS4Oj7uanuXI@Vspx6J@T@4YC6riYmuhrsjrqvlVCoTMyAdqRf8B71O6Gw3H3uKfS38i6JYhZHApAFVEpnp9DOedpZQm2iIaXAmon80bAc2zeVpQ/mtIqtPh21kkZHaffgE "C (gcc) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 124 + 1 (-a) = 125 bytes ``` say$o='+'.'-'x($l=pop@F),$t="----+ ",$i="| $o+ | ",$e=($d="| |").$"x$l.$d,$/,$e;say$d.':'x$l."$d $e $e"for 2..$_;say$i,$o,$t ``` [Try it online!](https://tio.run/##HU1LCoMwFNx7ivAYiGLyakU3LYGuuusZihALgvQFdWHBszdNOsxmPsyEcZn7GNfhA3G61qyt3kvMLki43SuDzZFNqAsymBwdClKrI6vRlfDZOahi0I6Z4Q1OKbnmPc/6orNL8AXGRHrJolpmPP@FyUDSQYydapuvhG2S9xrto@fm3EQ7/AA "Perl 5 – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 72 bytes ``` {g' '∘,∘⌽∘⍉⍣4(g←{'+'@(⊂1 1)∘⌽∘⍉⍣4⊃(⍪∘⌽∘⍉)/'-|-|',⊂⍵})↑(¯1+3×⍵)⍺⍴⍺/' :'} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///vzpdXUH9UccMHSB@1LMXRPZ2PupdbKKR/qhtQrW6trqDxqOuJkMFQ010FY@6mjUe9a5CFtbUV9et0a1R1wFqedS7tVbzUdtEjUPrDbWND08H8jUf9e561LsFSOqrKyhYqdf@TwNa8qi3D2jUo941QKlD642BWh71TQ0OcgaSIR6ewf/BDgFygJS6@qPuFqD2NJDhXIYGCukKRlxGIMqYyxREmUIEDU0B "APL (Dyalog Unicode) – Try It Online") A function that takes L on the left and x on the right. [Answer] # [Haskell](https://www.haskell.org/), 111 bytes ``` r=replicate a?b=a++b++reverse a l!x=unlines$map(?r l '-')["+--","| +"]?map("| |"?)(tail$concat$r x$r l<$>": ") ``` [Try it online!](https://tio.run/##FYzBCoJAEEDvfsU4LKhsQhBdwm1/oFvH6DDKQEvjJuMaHvz3zQ4PHjx4L5rfLJKzOuVJwkCJC/K9I2t7a5W/rDMDFVKubokSIs9mpKn2CgJVWzUPtG2LB9zA4tP/064b@qZOFMQMn7g/jcK6I5254gUAmzxSiOBgWtI96S2CgfOxPOUf "Haskell – Try It Online") ]
[Question] [ [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal%27s_triangle) is a triangular diagram where the values of two numbers added together produce the one below them. This is the start of it: ``` 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 ``` You can see that the outside is all 1s, and each number is the sum of the two above it. This continues forever. Your challenge is to count the number of times a value \$> 1\$ appears in Pascal's triangle. For example, with the value 6: ``` 1 1 1 1 2 1 1 3 3 1 1 4 **6** 4 1 1 5 10 10 5 1 1 **6** 15 20 15 **6** 1 ``` It occurs three times. It will never occur more because after this, all numbers other than 1s will be greater than it. As pointed out by tsh, this is [A003016](https://oeis.org/A003016). # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! # Testcases ``` 2 => 1 4 => 2 6 => 3 10 => 4 28 => 4 20 => 3 120 => 6 ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), 4 bytes Full program. Doesn't work as a function because of the way it reuses the input. ``` K‡_C ``` [Try it online!](https://tio.run/##S0/MTPz/3/tRw8J45///DY0MAA "Gaia – Try It Online") `K‡` Table of binomial coefficients, `‡` casts integer arguments to the range `[1 .. x]`. `_` Flatten the table. `C` count the number of occurences of the input in this list. `C` doesn't care about the order of arguments as long as one is a list and the other is not. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` c€ŻFċ ``` [Try it online!](https://tio.run/##ATUAyv9qZWxsef//Y@KCrMW7RsSL/yzDh2rigJwgLT4g4oCdKVn//zIsNCw2LDEwLDI4LDIwLDEyMA "Jelly – Try It Online") ## How it works ``` c€ŻFċ - Main link. Takes n on the left Ż - Range from zero; [0, 1, ..., n] € - Over each integer 1 ≤ i ≤ n: c - Calculate iCr for each r in [0, 1, ..., n] F - Flatten ċ - Count occurrences of n ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~54~~ 53 bytes ``` ->n,*a{(0..n).sum{y=0;a.map!{|x|y+y=x}<<1;a.count n}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5PRyuxWsNATy9PU6@4NLe60tbAOlEvN7FAsbqmoqZSu9K2otbGxhAolpxfmleikFdb@79AIdpIx0THTMfQQMfIQsfIQMfQyCAWpElDLU3zPwA "Ruby – Try It Online") Thanks Dingus for -1 byte [Answer] # [R](https://www.r-project.org/), ~~41~~ 40 bytes Or **[R](https://www.r-project.org/)>=4.1, 33 bytes** by replacing the word `function` with `\`. *Edit: -1 byte thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).* ``` function(n)sum(outer(0:n,0:n,choose)==n) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT7O4NFcjv7QktUjDwCpPB4STM/Lzi1M1bW3zNP@naRhpKivY2ikYcqVpmECYRkCmGYRpDGQaGkDYJkC2kQUS2wBJDYxj9h8A "R – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ƛɾƈ;f?O ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C6%9B%C9%BE%C6%88%3Bf%3FO&inputs=6&header=&footer=) Basically, just generate Pascal's triangle (sans the first row of just `1`) and get the count. Flagless just for Redwolf. ## Explained ``` ƛɾƈ;f?O ƛ ; # for each n in the range [1, input]: ɾƈ # n c x for x in range [1, n] - ʀƈ also works if you want the full row for some reason. f # flatten that ?O # and get the count of the input in that ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` ṁ#¹↑¡Sż+Θ;1→ ``` [Try it online!](https://tio.run/##ASAA3/9odXNr///huYEjwrnihpHCoVPFvCvOmDsx4oaS////Ng "Husk – Try It Online") The last part of this answer (`Sż+Θ;1`) was copied verbatim from DLosc's [clever answer](https://codegolf.stackexchange.com/a/212042) to [Generate Pascal's triangle](https://codegolf.stackexchange.com/questions/3815/generate-pascals-triangle/). Go upvote that! ``` ṁ#¹↑¡Sż+Θ;1→ ¡Sż+Θ;1 Generate Pascal's triangle (an infinite list) ;1 Start with the list [1] ¡ Repeatedly Θ prepend 0 to the list, ż+ then add that to the original list, ż keeping the last element of the new, longer list ↑ Take the first → n + 1 rows ṁ For each, # find how many occurrences of ¹ the input they contain, ṁ then sum those counts ``` [Answer] # [Python 3](https://docs.python.org/3/), 67 bytes ``` f=lambda n,*r:r.count(n)+(r<(n,)and f(n,*map(sum,zip(r,(1,*r))),1)) ``` [Try it online!](https://tio.run/##DcxBCsIwEEbhq8xypv5IEkWk6GHSlmDATMLYLvTyMbu3@Hjtu7@qXnpPz3csyxZJMdls57UeurPKie3BCom6URoxldj4cxT8cmMD@8FFBF6kp2qklJUCrrjBO4Q7goMPbqZmeQzHYsA/ "Python 3 – Try It Online") [Answer] # JavaScript (ES6), 61 bytes ``` n=>eval("for(i=t=0;i++<=n;)for(q=j=1;q*=i-j,q/=j++;)t+=q==n") ``` [Try it online!](https://tio.run/##dcvRCsIgAEbh@55CdqXZ2uZGBPb3LrJcKKK5yV7fCLsyuj0fx6pdbfNqXqn14aHzguxx17tytFnCSg0Semk4v8FL9ikRFoOMR5jWnmIHy7lkiSMCvmF5Dn4LTp9deNKFEiIYI11HhkMNUwHxA5cCYw1DX2CqQVz/wfcY8xs "JavaScript (Node.js) – Try It Online") Or **65 bytes** for a BigInt version: ``` n=>eval("for(i=t=0n;i++<=n;)for(q=j=1n;q*=i-j,q/=j++;)q-n?t:++t") ``` [Try it online!](https://tio.run/##dczRCsIgFIDh@55CdqW5pa4xIjv1LLK2UOSYm@z1jWB0Yez2/@B3ZjXLMNt3ajA8xzxBRriPq/G0msJMLSSQqC3nN0DNvimCA4U6HsE2ro4CHOeaxQYf6cp5qlgeAi7BjycfXnSihLTIGBGCqEMp3Sbtn/SbnEtRcpOulPayK3Lnpn7S5w8 "JavaScript (Node.js) – Try It Online") [Answer] # [Dyalog APL](https://dyalog.com), ~~11~~ 10 bytes *Thanks to ovs for -1 byte* ``` ≢∘⍸⊢=⍳∘.!⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/P@1R24RHnYsedcx41LvjUdci20e9m4EcPUUg/f9R31SgdJqCEReMZQJnmcFZhgZwppEFgokQNTQy@A8A "APL (Dyalog Extended) – Try It Online") How it works: ``` ⍳ Range [1, n] ∘.! Outer product binomial with ⍳ Range [1, n] = Equals ⊢ Right argument ⍸ Generate list of indices from truthy values ≢ Tally, get length ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 19 bytes ``` {+/,/x=x(+':|0,)\1} ``` [Try it online!](https://ngn.bitbucket.io/k#eJwtyEEKgzAQQNH9nGIWhSoKmYwhSAZ7ERuwm0BpoSAuImrPXodm9T4/ha0xrclDrppr2Kmt7/YAWMJ2GdfvHBIiZpk+L6mm9Hi+Jcsqcx0PWEYWG0+csOKlUyyJU7kvUvln+AhggHG4oQWnMHilA0uqA+6LVP4//A/uLiiI) * `x(+':|0,)\1` generate the first x+1 rows of Pascal's Triangle + `x(...)\1` run the code in `(...)` `x` times, seeded with `1`, returning a list containing the original input and the results from each iteration + `(+':|0,)` prepend a 0, then reverse the sequence. add each value to its predecessor * `x=` check where the original input appears in these rows * `+/,/` flatten the rows into a single list, then take the sum [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 15 bytes ``` {+//x=x+\\1+!x} ``` [Try it online!](https://ngn.bitbucket.io/k#eJwtyEEKgzAQRuH9f4oUurBkkWQMQTLYi2hAN4HSQkFcRETPXodm9T1ejrs2pvRFj6PTt3IAa9zvw3YuMSulCk/fNzdTnl8fLrzx8kgH1oHYpQvPJARuBWfZi9RVbf1XhAQYkOqfysELhCC0cFb0oK5q6/9HAH7WSygG) Different approach from @coltim, uses Pascal matrix. Explanation: ``` {+//x=x+\\1+!x} / construct the pascal matrix: x \ / do x times saving intermediate results +\ / cumulative sum 1+!x / starting at the range [1,x] x= / equals x? +// / sum all elements in the binary matrix, giving the count ``` [Answer] # Excel (Insider Beta), ~~59~~ 55 bytes *-4 using COMBIN(x+y,y) instead of COMBIN(x,y) eliminates need for IF* ``` =SUM(MAKEARRAY(A1,A1,LAMBDA(x,y,(COMBIN(x+y,y)=A1)*1))) ``` `LAMBDA` and `MAKEARRAY` are not in the current release of Excel Office 365. ## Excel Office 365, ~~67~~ 63 bytes ``` =LET(x,SEQUENCE(A1),y,TRANSPOSE(x),SUM((COMBIN(x+y,y)=A1)*1))) ``` [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnHmTdYYX0UODsCQm?e=k6kTAf) [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes (using Pascal matrix) ``` t2YL=z ``` [Try it online!](https://tio.run/##y00syfn/v8Qo0se26v9/MwA) Or [verify all test cases](https://tio.run/##y00syfmf8L/EKNLHtuq/S8h/Iy4TLjMuQwMuIwsuIwMuQyMDAA). How it works, using input `6` as an example: ``` t % Implicit input. Duplicate % STACK: 6, 6 2YL % Pascal matrix of that size % STACK: 6, [1 1 1 1 1 1 1 2 3 4 5 6 1 3 6 10 15 21 1 4 10 20 35 56 1 5 15 35 70 126 1 6 21 56 126 252] = % Test for equality, element-wise % STACK: [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 0 1 0 0 0 0] z % Number of nonzeros. Implicit display % STACK: 3 ``` # [MATL](https://github.com/lmendo/MATL), 8 bytes (using binomial coefficients) ``` t:t!Xn=z ``` [Try it online!](https://tio.run/##y00syfn/v8SqRDEiz7bq/38zAA) Or [verify all test cases](https://tio.run/##y00syfmf8L/EqkQxIs@26r9LyH8jLhMuMy5DAy4jCy4jAy5DIwMA). How it works, using input `6` as an example: ``` t % Implicit input. Duplicate % STACK: 6, 6 : % Range. Gives a row vector % STACK: 6, [1 2 3 4 5 6] t! % Duplicate, transpose. Gives a column vector % STACK: 6, [1 2 3 4 5 6], [1 2 3 4 5 6] Xn % Binomial coefficient, element-wise with broadcast. Gives a matrix % 6, [1 2 3 4 5 6 0 1 3 6 10 15 0 0 1 4 10 20 0 0 0 1 5 15 0 0 0 0 1 6 0 0 0 0 0 1] = % Test for equality, element-wise % STACK: [0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0] z % Number of nonzeros. Implicit display % STACK: 3 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 32 bytes ``` Count[Binomial~Array~{#,#},#,2]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zm/NK8k2ikzLz83MzGnzrGoKLGyrlpZR7lWR1nHKFbtf0BRJlCBsq5dmoNyrFpdcHJiXl01l5EOl4kOl5kOl6GBDpeRBRADaUMjA67a/wA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ŻcŻ$€Fċ ``` [Try it online!](https://tio.run/##y0rNyan8///o7uSju1UeNa1xO9L9//9/MwA "Jelly – Try It Online") A port of my Vyxal answer, and contains part of my [Jelly answer](https://codegolf.stackexchange.com/a/235665/78850) to the "vanilla" pascal triangle generation. (yes, this is the exact same as caird's answer but with an extra atom and quick because fgitw reasons) ## Explained ``` ŻcŻ$€Fċ # A monadic chain with argument n. Let the current value be λ Ż # λ = [0, n] € # over each item in λ: cŻ$ # yield item choose [0, item] (vectorising) F # flatten that ċ # and get the count of n ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 67 bytes ``` ->n{a=[1] n.times{|x|a=[1]+(1..x).map{|y|a[y]+a[y-1]}+a} a.count n} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtE22jCWK0@vJDM3tbi6pqIGLKCtYainV6Gpl5tYUF1TWZMYXRmrDSR0DWNrtRNruRL1kvNL80oU8mr/F5SWFCuk6SUn5uQoKBgpKCvY2ikYcqGImkBEjVBFzSCixqiihgYQYRNUYSML7MIG2A2BiZv9BwA "Ruby – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 80 bytes ``` lambda n:sum(math.comb(x,z)==n for x in range(n+1)for z in range(x)) import math ``` [Try it online!](https://tio.run/##Rcs7CoQwEADQ3lNMOYPL4qcRITfZJn6iAWcSZrOQ9fIRK9sHL/7THqQfohZnPuWwPC0WZPz@GNmm/T0HnjC/TjJGwAWFDF5ArWwrSt3STedDmajyHIMmuHuJ6iWhw7ZriMoF "Python 3.8 (pre-release) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 91 bytes ``` sub{($i,$c)=@_;for$r(1..$i+1){$n=1;map$c+=$i-~~($n*=$r/$_-1)?0:$_>$r/2-1?1:2,1..$r/2-.5}$c} ``` [Try it online!](https://tio.run/##XZBNa4NAEIbv/oohDPUjat1NTIvLxt4LzaW3tkgqWqR1XYyFBjF/3e6qxODenvdjZhmZ1T9hjznvT7@frYWFi6nNnxKWVzXWFvF9LNbEblFwwsqjxHTNsfAuFwuFw7G@x8QjdhxEmOwVUY/EJKKu7mnyww7TrmeGGgflGbDJTg1YBqj3BhT4Hgh8uBNvNdOZd5o3M5NAC9tZoI9LIVhWRmV3o4SLDnm4rrWNdhDLs7qEkC5mf1JdY/g1mxzAr6oBDneYDyF7NGRdiGbwONc1iMGsvk2IwHQc5@XwCodn8za6ApgGgIqPHd3WI97Fihmd0f8D "Perl 5 – Try It Online") [Answer] # TI-Basic, 27 bytes ``` Input N For(I,2,N Ans+sum(N=I nCr seq(J,J,0,I End ``` Output is stored in `Ans`. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 38 bytes ``` n->sum(i=0,n,#[1|j<-binomial(i),j==n]) ``` [Try it online!](https://tio.run/##FcsxCoQwEEbhqwxuk8AfSIKIxcaLiEUslBGdHdzdQvDuUbv3FU/zzm7WMlEq4rrvfzOcPASvPpzL240sn43zathiSUkGW7Lqehgh15HuLL87qwcVTUasBfURNRoEj9gieoTo7@0C "Pari/GP – Try It Online") When `binomial` takes only one argument, it returns the `n`'th row of the Pascal's triangle. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` δc˜I¢ ``` [Try it online](https://tio.run/##yy9OTMpM/f//3Jbk03M8Dy36/98MAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/3Nbkk/PqTy06L/O/2gjHRMdMx1DAx0jILLQMTQyiAUA). **Explanation:** ``` δc # Create a binomial coefficients table: δ # Apply double-vectorized: # (which implicitly converts the implicit input-integer to the range # [1,input] first, used twice) c # Binomial coefficient ˜I¢ # Count the amount of times the input occurs in this matrix: ˜ # Flatten the matrix to a single list I¢ # Count how many times the input is in this list # (after which the result is output implicitly) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` Nθ⊞υ¹≔⁰ηFθ«⊞υ⁰UMυ⁺κ§υ⊖λ≧⁺№υθη»Iη ``` [Try it online!](https://tio.run/##NY3LCsIwEEXX7VdkOYEIrVtXpW66UIp/EJvYFPNo8xBB/PY4oTirmcM9cyfF/eS4znmwa4rXZO7Sw0ZP9ZiCgsRIi3sXwjJbaBhReD2cJxghn7r6hxrE1YWvvTOGW1HQqFOAJyNdHKyQ74LOcvLSSBulAE1xdmn/fltmFaFYjPQu2ViMje6V33r0C6KehwgKxZzbY5MPL/0D "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input the target `n`. ``` ⊞υ¹ ``` Start with the `0`th row of Pascal's triangle. ``` ≔⁰η ``` Start with `0` occurrences of `n`. ``` Fθ« ``` Loop `n` times. ``` ⊞υ⁰ ``` Append a `0` to the row. ``` UMυ⁺κ§υ⊖λ ``` For each element, add the original previous element to it. (Due to cyclic indexing, the `0` at the end gets added to the first element.) ``` ≧⁺№υθη ``` Keep a running total of the number of occurrences of `n`. ``` »Iη ``` Output the final total. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~96~~ \$\cdots\$ ~~81~~ 77 bytes ``` c;i;f(n){for(int p[n],r=c=0;p[i=r++]=r<=n;)for(;i;)c+=(p[i--]+=p[i])==n;i=c;} ``` [Try it online!](https://tio.run/##XU/baoQwEH3frxiEhWSNVN0LLdn0pfQrNA8S4za0zUoiVCr@eu14Wek2JJnJuQw5KrooNQyKG14RS7vq6oixDdSZlcwJJWJeZ0a4MJTCnYXldFSgmqpQEKSiSIYCq6QCWSMU74dxwGdhLKHQbQDXCDTaNz6TIKBLGewZHBgcGZwYJDGD9BEP1iSNe756dFtr1ehytiUoue3Zf5ia0@JQb4Xb4a3Vu3azJcjb1zRvn17wHAMGf9/7YPFhIphCG1vqFm0xX9ozePOtrxW5fYQ@LMBuRTiE4aS@hV0D46Q59ERLfsd6ZCvS0HtUI7qG/m@rHUoqEmz3JUTPsC1h63OLqRoGnq3BtRBeLnP7TT/8qOqjuPgh@voF "C (gcc) – Try It Online") Inputs integer \$n > 1\$ and returns the number of times \$n\$ appears in Pascal's triangle. *Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* #### Commented code ``` c;i; // declare counter (c) and // index (i). f(n){ // declare function f taking an // int parm (n). for( // outer loop over rows of Pascal's // triangle. int p[n], // declare int array (p) that will // store successive rows of // Pascal's triangle. r=c=0; // declare int row (r) and // init r and c to 0. p[ // set the rth element in p to 1: // the first time through this // sets p[0] = 1, and every // time after that sets // p[current last position] = 1. i=r++ // init i to r and post bump r. ]=r<=n;) // loop until r is greater than n. for(;i;) // inner loop over current row's // elements backwards but // stops before touching p[0]. c+=( // bump c... p[i--] // update current ith element by +=p[i] // adding previous values: // p[i] = p[i] + p[i-1]. )==n; // ...if this new value of // Pascal's triangle is // equal to n. i=c; // return counter c. } ``` Aside: This method golfed the best but also calculating rows of Pascal's triangle through repeated summation works well with \$32\$-bit integers, calculating \$\binom{n}{m}\$ as \$\frac{(n-m)!}{m!}\$ quickly overflows, even for \$64\$-bit integers. This method might also be faster, especially for \$n<=16\$ where rows of Pascal's triangle will fit on a single cache line. [Answer] # [Python 3](https://docs.python.org/3/), 117 109 94 bytes *-23 bytes thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)* ``` f=lambda n,k=0:(k:=k or n)-1and[math.comb(k,i)for i in range(k)].count(n)+f(n,k-1) import math ``` [Try it online!](https://tio.run/##FYzBCsMgEETv@xV7XGlS1JYSAvmS0oNpYiPGVcRQ@vXWzGEu782kX9ki34aUa7XTbsK8GOTOT3IkP04eY0YWvTK8PIMp2/Udw0y@c8I24tAxZsOflbx4NXZwIRYXS@2iVwJcSDEXPJf1u7l9RTWm7Jpl6WzH6SgkWqqGOzxASdADaAlKyz8 "Python 3 – Try It Online") Generates each line of Pascal's triangle recursively and counts times `n` appeared. Sorry for causing so much trouble with this solution. Much thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) and [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler) for helping me out. [Answer] ## Clojure, 94 bytes ``` #((frequencies(apply concat(take(inc %)(iterate(fn[i](concat[1](map +'(rest i)i)[1]))[1]))))%) ``` Actually `frequencies` calculates the frequencies of all numbers, and it is used in a function context of that S-expression, thus returning the frequency of the queried number. One must use `+'` for summation to handle integer overflows properly. A `loop` implementation should be shorter than this `iterate` - `take` - `frequencies` combination. [TIO](https://tio.run/##JY1BCsIwFET3PcWAFP/HTRNLETxK6CLEH4jWGNNU8PQx0s1bvHkwbnndtyy10k08PA5EPst7k@iCrGRTWr5wr@hsoWIfQiE69EyhSLZFyEcTZtoDo2Z62oTTkbKsBYEDN8c7mHvmrqOUQyxLxD/9tEejMWKCGqAv0AOUHlrdXWEUNM5tHBunudYf). [Answer] # Swift, 129 bytes Short version: ``` func c(_ n:Int)->Int{var l=[0,1,0];var c=0;while l[2]<=n{for i in 0..<l.count-1{l[i]+=l[i+1];c+=l[i]==n ?1:0};l=[0]+l};return c} ``` Verbose version: ``` func c2(number: Int) -> Int { var line: [Int] = [0, 1, 0] var count = 0 while line[2] <= number { for i in line { if i == number { count += 1 } } for i in 0 ..< line.count - 1 { line[i] += line[i + 1] } line.insert(0, at: 0) } return count } ``` [Answer] # [Perl 5](https://www.perl.org/) `-ap`, 59 bytes ``` $i=0,$\+=grep"@F"==$_,@a=(1,map$_+$a[++$i],@a)while@a<=$_}{ ``` [Try it online!](https://tio.run/##K0gtyjH9r1Joa2D9XyXT1kBHJUbbNr0otUDJwU3J1lYlXsch0VbDUCc3sUAlXlslMVpbWyUzFiioWZ6RmZPqkGgDVFNb/f@/oZHBv/yCksz8vOL/ur6megaGBv91EwtyAA "Perl 5 – Try It Online") [Answer] # APL(NARS), 43 chars ``` r←P w;a a←⍬⋄r←0 r+←+/w=a←2+/1,a,1⋄→2×⍳w≥↑a ``` 7+7+26+3=43. Use & test ``` P¨2 4 6 10 28 20 120 1 2 3 4 4 3 6 P 1002 2 ``` ]
[Question] [ **Definition**: a *prime power* is a natural number that can be expressed in the form pn where p is a prime and n is a natural number. **Task**: Given a prime power pn > 1, return the prime p. **Testcases**: ``` input output 9 3 16 2 343 7 2687 2687 59049 3 ``` **Scoring**: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte ``` f ``` [Try it online!](https://tio.run/##MzBNTDJM/V9TVvk/7X@l0uH9Crp2Cof3K@n8t@QyNOMyNjHmMjKzMOcytTQwsQQA "05AB1E – Try It Online") [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), ~~209~~ 207 bytes ``` T.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:Listen tothy!Page:You cat!Scene V:.Page:You be the sum ofyou a cat!Be the product ofthe quotient betweenI you you worse I?If soLet usScene V.Open heart ``` [Try it online!](https://tio.run/##PY7BCsIwEER/ZXuX4EEPzUUqeCgUFBRBxENst7ai2ZpsqP36mrXiYWHnMcOM7x7jeFDZ3bxnamduOFNZyZBrtS/RojznjWV0IBYwtgJxXUTpovWMFpi4GRLB@kQBSsPJFD5q9adXBG4QfHgC1UME5mtcT7hzVIXYS7WoVyBu0XIMcY9oc5CAXE/Ox1GrvAZPBTIE/6tS2y5OadA4HsdlOl@kHw "Shakespeare Programming Language – Try It Online") `(I/you)*you<I` is shorter than `I%you>0` in SPL. [Answer] # Java 8, ~~46~~ ~~39~~ 37 bytes ``` n->{int r=1;for(;n%++r>0;);return r;} ``` -7 bytes indirectly thanks to *@Tsathoggua*. -2 bytes thanks to *JoKing* [Try it online.](https://tio.run/##hU7NCsIwDL77FLkILeLY/B9F30AvHsVDrZ1kbtnouoFIn71206sMkkC@n3zJZSfn@f3pVSGbBo4S6T0BQLLaZFJpOPXrAIBi/SQuAuJCh2qstKjgBAR78DQ/vHsJ7hORVYYJms5meIgFF0bb1hCgcF58rXV7K4L1d6Gr8A5lSGdna5AelytI/o0@vxqry6hqbVQHyhbEKFIs5cMjf/lkMyJYrpYjisVmtx2RrNN49fvETZz/AA) **Explanation:** ``` n->{ // Method with integer as both parameter and return-type int r=1; // Start the result-integer `r` at 1 for(;n%++r>0;); // Increase `r` by 1 before every iteration with `++r` // and loop until `n` is divisible by `r` return r;} // After the loop, return `r` as result ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~36~~ 35 bytes *-1 byte thanks to mathmandan* ``` f=lambda n,x=2:n%x and f(n,x+1)or x ``` [Try it online!](https://tio.run/##DYdBCoMwFAX3nuJtCgkNxajVKniS0kVaDQ3ojyS/EE@fZmAG5jj566nNbj98YMQzVsVbXDmsn1@IztPmdsdC1wWZ7byZ/b0YkEpzM9ElwdACK8pftfQBKdtShiM8RwXdK7Rdq9D0j0HhPnb1@Joq4AiOWFjBUuY/ "Python 3 – Try It Online") Recursive function that finds the first factor larger than 1 [Answer] # [MATL](https://github.com/lmendo/MATL), ~~4~~ 3 bytes ``` Yfu ``` [Try it online!](https://tio.run/##y00syfn/PzKt9P9/U0sDE0sA "MATL – Try It Online") ### Explanation: ``` % Implicit input: [59049] Yf % Prime factorization: [3 3 3 3 3 3 3 3 3 3] u % Unique elements: [3] % Implicit output ``` [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~80~~ ~~61~~ 60 bytes ``` [S S T T N _Push_-1][S S S N _Push_0][T N T T _Read_STDIN_as_number][N S S N _Create_Label_LOOP][S S S T N _Push_1][T S S T _Subtract][S N S _Duplicate][S S S N _Push_0][T T T _Retrieve][S N T _Swap][T S T T _Modulo][N T T N _If_0_Jump_to_Label_LOOP][S S T T N _Push_-1][T S S N _Multiply][T N S T _Print_as_number] ``` -20 bytes thanks to *@JoKing*. Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0GBk5NLQUGBi5MLzACxgUwgAWYCxTk5QQRIGVgBJ1gWqFyB8/9/YxNjAA) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** ``` Integer n = STDIN as integer Integer i = -1 Start LOOP: i = i - 1 if(n modulo-i is negative) Go to next iteration of LOOP else i = i * -1 Print i Exit with error: No exit defined ``` **Example run: [`input = 9`](https://tio.run/##K8/ILEktLkhMTv3/X0GBk5NLQUGBi5MLzACxgUwgAWYCxTk5QQRIGVgBJ1gWqFyB8/9/SwA)** ``` Command Explanation Stack Heap STDIN STDOUT STDERR SSTTN Push -1 [-1] SSSN Push 0 [-1,0] TNTT Read STDIN as integer [-1] {0:9} 9 NSSN Create Label_LOOP [-1] {0:9} SSSTN Push 1 [-1,1] {0:9} TSST Subtract top two (-1-1) [-2] {0:9} SNS Duplicate top (-2) [-2,-2] {0:9} SSSN Push 0 [-2,-2,0] {0:9} TTT Retrieve [-2,-2,9] {0:9} SNT Swap top two [-2,9,-2] {0:9} TSTT Modulo top two (9%-2) [-2,-1] {0:9} NTSN If neg.: Jump to Label_LOOP [-2] {0:9} SSTTN Push -1 [-2,-1] {0:9} TSST Subtract top two (-2-1) [-3] {0:9} SNS Duplicate top (-2) [-3,-3] {0:9} SSSN Push 0 [-3,-3,0] {0:9} TTT Retrieve [-3,-3,9] {0:9} SNT Swap top two [-3,9,-3] {0:9} TSTT Modulo top two (9%-3) [-3,0] {0:9} NTSN If neg.: Jump to Label_LOOP [-3] {0:9} SSTTN Push -1 [-3,-1] {0:9} TSSN Multiply top two (-3*-1) [3] {0:9} TNST Print as integer [] {0:9} 3 error ``` Program stops with an error: No exit found. [Answer] # [Octave](https://www.gnu.org/software/octave/), 16 bytes ``` @(x)factor(x)(1) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzLTG5JL8IyNAw1PyfpmFsYqz5HwA "Octave – Try It Online") ### Explanation: ``` @(x) % Anonymous function taking x as input factor(x) % Prime factorization (1) % Get the first element ``` Or: ``` @(x)max(factor(x)) % the makeup of makeup artists ``` [Answer] # JavaScript (ES6), 25 bytes ``` f=(n,k=2)=>n%k?f(n,k+1):k ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjTyfb1kjT1i5PNds@DcTTNtS0yv6fnJ9XnJ@TqpeTn66RpmGpAASamgr6@grGXKhShmZwKSM0KWMTY5iUOZqUkZmFOUwXkIkma2ppYGIJte4/AA "JavaScript (Node.js) – Try It Online") [Answer] # [Funky](https://github.com/TehFlaminTaco/Funky), 30 bytes ``` n=>fori=2n>i i++if1>n%i breaki ``` [Try it online!](https://tio.run/##SyvNy678n2b7P8/WLi2/KNPWKM8uUyFTWzszzdAuTzVTIakoNTE7839BUWZeiUaahrGJsabmfwA "Funky – Try It Online") [Answer] # [Pyth](https://pyth.readthedocs.io), 2 bytes ``` hP ``` [Try it here!](https://pyth.herokuapp.com/?code=hP&input=343&debug=0) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ÆfḢ ``` [Try it online!](https://tio.run/##y0rNyan8//9wW9rDHYv@//9vamlgYgkA "Jelly – Try It Online") `ÆfṪ`, `ÆfX` could also be seriously competing functions. `ÆfQ` could be a seriously competing full program. [Answer] # [C (gcc)](https://gcc.gnu.org/), 28 bytes ``` f(k,p){for(p=1;k%++p;);k=p;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI1unQLM6Lb9Io8DW0DpbVVu7wFrTOtu2wLr2f25iZp6GZnVBUWZeSZqGkmqKgq2tgrGOAoRhBGOYw0XMLOBsYyUdhTQNS00QaWgGpoxNjME0SBmYYWppYGKpqQm0CQA "C (gcc) – Try It Online") [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 34 bytes ``` : f 1 begin 1+ 2dup mod 0= until ; ``` [Try it online!](https://tio.run/##FYtHCoAwFAX3nmJwKwZjL@hhLFHBEoKeP343M/CKud2zxav55X2LQTMu636hI9L5tZz3TNLzXs9@0MnE8scFyqFCiAdCuSkmRxc02ECXgizPhGlZV6KiSXJp/Ac "Forth (gforth) – Try It Online") ### Explanation 1. Iterate integers starting from 2 2. Stop and return when you find one that divides n with no remainder ### Code Explanation ``` : f \ Define a new word 1 \ place a 1 on the stack (to use as a counter/index) begin \ start indefinite loop 1+ 2dup \ increment counter and duplicate counter and prime power mod \ calculate power % index 0= until \ end the loop if modulus is 0 (no remainder) ; \ end word definition ``` [Answer] # [R](https://www.r-project.org/), ~~32~~ 26 bytes @Giuseppe with different logic and a shorter solution: ``` (x=2:(n=scan()))[!n%%x][1] ``` [Try it online!](https://tio.run/##K/r/X6PC1shKI8@2ODkxT0NTUzNaMU9VtSI22jD2v6mlgYnlfwA "R – Try It Online") Original: ``` numbers::primeFactors(scan())[1] ``` [Try it online!](https://tio.run/##K/r/P680Nym1qNjKqqAoMzfVLTG5JL@oWKM4OTFPQ1Mz2jD2v6mlgYnlfwA "R – Try It Online") This is obviously a much superior port of the [05AB1E](https://codegolf.stackexchange.com/a/167107/79980) solution. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~7~~ 2 bytes ``` ⊃⍭ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/P@1R24RHXc2PetcC2QqWXGkKhmZAwtjEGEgamVmYAylTSwMTSwA "APL (Dyalog Extended) – Try It Online") `⍭` gives a list of factors, `⊃` gets the first of them. [Answer] # Regex (ECMAScript), 10 bytes ``` (xx+?)\1*$ ``` [Try it online!](https://tio.run/##Tc@9UsJAFIbhnquIGYecQyQQQBTWhcqChkJLpdiBQ7K62ezsLhD5ab0AL9EbiVAwY/0U3/d@iK1wSyuNbzsjV2SLUn/SV225pl3wQtlzZQD2fNJp1VBV8RTf09Zt3ersMfHlq7dSZ4CJU3JJMLxrDxCZ4122y6UiAMUtiZWSmgDxhuuNUnjIuEqcUdJD1I6QyTWA5lmiSGc@x0nveJRuLuYguRHW0Ux7yN66C8Qr0H/Qk3Saji@MPrflLpzprVByFVihMxoHYazYurTA5BMnJuMYz4MFD6swsWRIeJCYFMIvc7CIB9dsmnOUh0tHyszGO29BxlHw@/0TRHHxli6uV9npVI8a6bDRH/QbveHjQ@N@1B2M/gA "JavaScript (SpiderMonkey) – Try It Online") Works by finding the smallest prime factor. Takes its input in bijective unary, as a sequence of `x` characters in which the length represents the number. The output is returned in capture group 1. ``` # No anchor needed, since every input N>=2 returns an output (xx+?) # \1 = the smallest number >=2 for which: \1*$ # N-\1 is divisible by \1 ``` [Answer] # Vyxal 1, 1 byte ``` ′ ``` There was a builtin just for this. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes ``` ḋh ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO7oz//41NjP9HAQA "Brachylog – Try It Online") ### Explanation ``` ḋ Prime decomposition h Head ``` [Answer] # [J](http://jsoftware.com/), 4 bytes ``` 0{q: ``` Select `{` the first `0` of the prime factors `q:` [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N@gutDqvyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKagiWMYWgGYxmbGMOYRmYW5jC2qaWBieV/AA "J – Try It Online") [Answer] # [Neim](https://github.com/okx-code/Neim), 1 byte ``` 𝐔 ``` [Try it online!](https://tio.run/##y0vNzP3//8PcCVP@/ze1NDCxBAA "Neim – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 26 bytes ``` f n=until((<1).mod n)(+1)2 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz7Y0ryQzR0PDxlBTLzc/RSFPU0PbUNPof25iZp5tQVFmXomCikJuYoFCmkK0iY6FjqGZjpG5jqmOsYlx7H8A "Haskell – Try It Online") [Answer] # Mathematica, 17 bytes ``` Divisors[#][[2]]& ``` The second smallest divisor. [Answer] # [Husk](https://github.com/barbuz/Husk), 2 bytes ``` ←p ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8f@jtgkF////j7bUMTTTMTYx1jEyszDXMbU0MLGMBQA "Husk – Try It Online") [Answer] # [ARBLE](https://github.com/TehFlaminTaco/ARBLE), 19 bytes ``` index(factors(a),1) ``` [Try it online!](https://tio.run/##SyxKykn9/z8zLyW1QiMtMbkkv6hYI1FTx1Dz////xibGAA "ARBLE – Try It Online") [Answer] # Japt `-g`, 1 byte ``` k ``` [Try it here](https://ethproductions.github.io/japt/?v=1.4.5&code=aw==&input=MTYKLWc=) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 31 bytes ``` param($a)(2..$a|?{!($a%$_)})[0] ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRU8NIT08lsca@WhHIU1WJ16zVjDaI/f//v5GZhTkA "PowerShell – Try It Online") Constructs a range from `2` to input `$a`, pulls out those elements `where` (`?`) the modulo operation `%` results in a zero `!(...)` (i.e., those that are divisors of `$a`), and then takes the smallest `[0]` one thereof. That's left on the pipeline, output is implicit. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 22 bytes ``` {grep($_%%*,2..$_)[0]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Or0otUBDJV5VVUvHSE9PJV4z2iC29n@ahqWmXnFipTVXmoahGZxpbGIMZxuZWZjDOaaWBiZQHf8B "Perl 6 – Try It Online") Anonymous code block that filters the factors of the range of 2 to the input and returns the first one. I tried using `^$` to save 2 bytes, but that didn't work in the case that the input was prime. [Answer] # Visual Basic .NET (.NET Framework v4.5), ~~123~~ 71 bytes *-52 bytes thanks to @Jo King* ``` Function A(n) For i=n To 2 Step-1 A=If(n Mod i=0,i,A) Next End Function ``` [Try it online!](https://tio.run/##dZC5CsJAEIb7fYopdyGRHF4pUgQPEIyNgnWOUUbirGR3xbeP8epMN8zH/8/H3Mm4ovHLwlDlM1r/XlZdrmvXIORiSVcgDy5QGNiwxTO23dpxZUkzZJKVWOsWKGU4aIhgb/HmhyJLNyfJ0Lf0KPDIy5TY4cOKFdfwi3d7V0JeEEslxEKz0Q2Oji1Z3BKjzGSi1N99OB0A8TgeINF0PhtAkyQYvy693Xqlz/B9QPcE "Visual Basic .NET (VBC) – Try It Online") Ungolfed: ``` Function A(input As Long) As Long For i = input To 2 Step -1 A = If (input Mod i = 0, i, A) Next End Function ``` Explanation: The `i` loop searches backwards from the first number, and finds all numbers that divide it evenly. Because we are going backwards, the smallest is stored in the vairable `A`. VB gives you a free variable that matches your function name (in my case, `A`). At the end of the function execution, the value in that variable is returned (barring an explicit `Return` statement. [Answer] # [Haskell](https://www.haskell.org/), 29 bytes ``` f y=[x|x<-[2..],mod y x<1]!!0 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02h0ja6oqbCRjfaSE8vVic3P0WhUqHCxjBWUdHgf25iZp5tQVFmXolKmoKR@X8A "Haskell – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~47~~ ~~45~~ 44 bytes *Inspired by [Kevin Cruijssen's answer in Java](https://codegolf.stackexchange.com/a/167115/36398)*. *~~2~~ 3 bytes removed thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)*. ``` lambda n:[i+1for i in range(n)if n%-~i<1][1] ``` [Try it online!](https://tio.run/##FcmxDsIgFAXQvV9xlyYQaVIEqTT6JciAUfQl9bUhLC7@OqZnPdu3vlc2LV9vbUmf@yOB50AHndcCAjFK4tdTsKQM7ocfXXQMOrb96/7BK2inYKxROLrzpHDydvRx7oCtEFeRRZWy/QE) ]
[Question] [ *Note: This is #3 in a series of [array-manipulation](/questions/tagged/array-manipulation "show questions tagged 'array-manipulation'") challenges. For the previous challenge, [click here](https://codegolf.stackexchange.com/questions/103973/an-array-of-challenges-2-separate-a-nested-array).* # Moving Average of a List > > The [**moving average**](https://en.wikipedia.org/wiki/Moving_average) of a list is a calculation resulting in a new, smoothed out list, created by averaging small overlapping sublists of the original. > > > When creating a moving average, we first generate the list of overlapping sublists using a certain 'window size', shifting this window to the right once each time. For example, given the list `[8, 4, 6, 2, 2, 4]` and the window size `3`, the sublists would be: ``` [8, 4, 6, 2, 2, 4] Sublists: ( ) <- [8, 4, 6] ( ) <- [4, 6, 2] ( ) <- [6, 2, 2] ( ) <- [2, 2, 4] ``` We then calculate the [**mean average**](https://en.wikipedia.org/wiki/Arithmetic_mean) of each sublist to obtain the result: `[6.0, 4.0, 3.3, 2.7]` (each value rounded to one decimal place). --- # The Challenge Your task is to write a program or function which, given a list **L**, and an integer **1 ≤ n ≤ length(L)**, calculate the moving average for **L** using the window size **n**. **Rules:** * Your program may use integer division *or* float division. In the case of float division, small inaccuracies due to the data type's limitations are permitted, as long as the value is otherwise correct. * You may submit a full program, or a function (but not a snippet). * You may assume that the list will only contain **positive integers**. * [Standard loopholes are forbidden.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins!** --- # Test Cases Note that, for ease of readability, all values are rounded to one decimal place. ``` n=5, [1, 2, 3, 4, 5, 6, 7, 8] -> [3, 4, 5, 6] n=3, [100, 502, 350, 223, 195] -> [317.3, 358.3, 256] n=1, [10, 10, 10] -> [10, 10, 10] n=3, [10, 20, 30] -> [20] n=2, [90, 40, 45, 100, 101] -> [65, 42.5, 72.5, 100.5] ``` [Answer] # Dyalog APL, 4 bytes *1 byte saved thanks to @Graham* *2 bytes saved thanks to @jimmy23013* Did I mention APL is **not** a golfing language? ``` ⊢+/÷ ``` with `n` on the right, or ``` +/÷⊣ ``` with `L` on the right. [Try it online!](http://tryapl.org/?a=100%20502%20350%20223%20195%28%u22A2+/%F7%293&run) **How?** `÷` - divide `L` by `n` `⊢+/` - reduce `+` on windows of `n` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ṡÆm ``` [Try it online!](https://tio.run/##y0rNyan8///hzoWH23L///8fbaGjYKKjYKajYARGJrH/jQE "Jelly – Try It Online") Pretty simple thanks to `ṡ` ## How it works ``` ṡÆm - Main dyadic link. Arguments: l (list) and n (integer) ṡ - Split l into sublists of length n Æm - Mean of each ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 13 bytes Mathematica has a built-in for everything ``` MovingAverage ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8d83vywzL92xLLUoMT31v6Y1V0BRZl6JQ1p0taWBjoIJCJvqKBgaGIAIw1odBaPY/wA "Wolfram Language (Mathematica) – Try It Online") Takes a list and then a radius... [Answer] # [Haskell](https://www.haskell.org/), 47 bytes ``` n!a|length a<n=[]|_:t<-a=div(sum$take n a)n:n!t ``` [Try it online!](https://tio.run/##DcZBCoMwEAXQfU/xAy4UIsSELCrmJCJlwFCDcSo67cq7x77VW@hcY86lsKIrR37LAho4jNP16mVoKczpV5/frRJaIxjUcM9KykaJETB/HsB@JBbUDgpjZ4yGN1bD@f@sdRrd009NuQE "Haskell – Try It Online") Saved two bytes thanks to xnor! [Answer] # [Python](https://docs.python.org/2/), 48 bytes ``` f=lambda n,l:l[n-1:]and[sum(l[:n])/n]+f(n,l[1:]) ``` [Try it online!](https://tio.run/##DclNCoAgEEDhq8xSy8gfXCR0ksGFEZJgk5QtOr25e7yvfPW4SLcW1xzObQ9AIruMNCnnA@34vCfL6MjzmfwYWWfsxFu5E1WIbEhU3so4b0YAKikFWKkFGNtL6z7VYv0P "Python 2 – Try It Online") A recursive function. Shorter than the program (50 bytes) ``` n,l=input() while l[-n]:print sum(l[:n])/n;l=l[1:] ``` [Try it online!](https://tio.run/##DchLCoAgEADQfaeYZYKRH1xkeBJxGShMk5QSnX5y93j1a/kiw0wSQ6Ha2yymNxc8AONCyde7UIOnnzNGT0mstGPAqH1ithKiVkqCU0aCdUPGjNSbSz8 "Python 2 – Try It Online") This saves 2 bytes by terminating with error on the `while` condition. [Answer] # [Enlist](https://github.com/alexander-liao/enlist), 3 bytes ``` ṡÆm ``` [Try it online!](https://tio.run/##S83LySwu@f//4c6Fh9ty////H21oYKCjYGpgpKNgbApkGRkZ6ygYWprG/jcGAA "Enlist – Try It Online") [Answer] # [Perl 6](https://perl6.org), 33 bytes ``` {@^a.rotor($^b=>1-$b)».sum X/$b} ``` [Test it](https://tio.run/##fVHbbptAEH3nK84D7UJZrw02vhTj8gF9qvIQCeMKm21lCS@IxVGiKP2hfELf8mPu7Ma5tVVGmtlh5py50cqunp6OWuJqKnaJc7jBx11TSaSn22xTiq7pm85zN9t0FQ7crf/wW@jjAZdDd3t3InDWS90jRb1XUnu@OJTt51sHGGIDplJGLuAu1Yow3roKfDCOxyjLGX6BFQzZsn7KI2eC0Vt88QN8eAGv9SewwYoZ5y07W3bvk4cJGQ@BmYIjeLg37cTXve59bsi00reytwHufnfuHHONC1orcdq6VAjsjonzo@nO6w5W8DxX8az2OTJ53cpdLysOt5J658PsT6dZd1Ifa3Mcc1Avq7mrfNvGDFTty594RIiWfoKJ7fWgkrKtb84JmqxrjqryRiL8T6eEZj2pNObIQ46IY8wx4aDvKceMY17ACo1rJX/JF45Kx4Y3GlFgZLgxeVFEwXARF3/xwpkYG8jcPFFs6aGlE9zqudVreaa/Qj23pTKk43d5kcXTbPmCsBOjsaliS4XFP/gpZSeRIDuzlpAiLv4A "Perl 6 – Try It Online") ## Expanded: ``` { # bare block with placeholder parameters 「@a」, 「$b」 @^a # declare and use first param .rotor( # split it into chunks $^b # declare and use second param => # pair it with 1 - $b # one less than that, negated )».sum # sum each of the sub lists X/ # cross that using &infix:«/» $b # with the second param } ``` [Answer] # C, ~~86~~ ~~84~~ 83 bytes ``` i,j,s;f(a,l,n)int*a;{for(i=-1;i+++n<l;s=!printf("%d ",s/n))for(j=n;j--;)s+=a[i+j];} ``` [Try it online!](https://tio.run/##dY/BasQgEIbveYppoKB1QqPGtov1SZY9hLRZDFu7rOkp5NnT0bYUDxEGZPy/b8ahOQ/DtnmcMNqR9XjBwH2YH3q7jJ835l0jrRdChNeLje7ueqPHkdX3b1BjfAycp9Tkgp2axvIoXH/0YjrZdaMgfPQ@MF4tFdBJjfk9zvJ4AgeLRFAIGqFDMAhPCM8IL6vN2ZHlJDXokdvr1xxZXXNbFSb1a2pbSrXJZuimFEnlwRQqlYfoXZX@UxGaq6B1XlTu0t0/rah0SXeZ3p9tfugDkV0qk@bnJWThMfkPivB1@wY) **Unrolled:** ``` i, j, s; f(a, l, n)int*a; { for(i=-1; i+++n<l; s=!printf("%d ", s/n)) for(j=n; j--;) s += a[i+j]; } ``` [Answer] # J, ~~7~~ 5 bytes ``` ]+/\% ``` [Try it online!](https://tio.run/##VYw7DoAgEER7TzGNFQnuLqzBwptoZSRq4w28OoJYaGaqN58jpThazKab2mZdthMO8UKARw/J8pVqoWx2Gz4tJoKSwClBxIEHrSnXtPo3gBDci6SggeCz9Tlj4pRu "J – Try It Online") Takes `n` as the right argument and the list as the left. Credit to Uriel's solution for the idea of doing only the summation in the infix. ### Explanation ``` ]+/\% % Divide list by n ]+/\ Sum on overlapping intervals of size n ``` ### Previous solution (7 bytes) ``` (+/%#)\ \ Apply to overlapping intervals of size n (+/%#) Mean +/ Sum % Divided by # Length ``` [Answer] # [Ohm v2](https://github.com/MiningPotatoes/Ohm), 3 bytes ``` ÇÆm ``` [Try it online!](https://tio.run/##y8/INfr//3D74bbc//@jLQ10FExA2FRHwdDAAEQYxnIZAQA "Ohm v2 – Try It Online") Explanation: ``` ÇÆm Main wire, arguments l (list) and n (integer) Ç All consecutive sublists of l with length n Æm Arithmetic mean of each sublist ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` .O.:F ``` **[Try it here!](https://pyth.herokuapp.com/?code=.O.%3AF&input=%5B%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8%5D%2C+5%5D&debug=0)** ## How this works ``` .O.:F - Full program. F - Reduce the input (nested list) with... .: - ... Sublists. .O - Average of each. ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~33~~ 31 bytes ``` @(x,n)conv(x,~~(1:n)/n,'valid') ``` [**Try it online!**](https://tio.run/##PYrBCsIwEETvfsXemoUlZpNGrSD0P8RDqRYESS8SPPXX46SUHgZm5r15/A75Vaabtbb05ieJxzlllGUxek18TNLk4fN@Nlwmc1chLxSEWqEodBI6C10eGHyo2DlUV5WI5j1M7SJ42Dj2Gly6Xx4Jbrc6zLYmVnPVFdBz@QM "Octave – Try It Online") ### Explanation Convolution (`conv`) is essentially a moving weighted sum. If the weights are chosen as `[1/n, ..., 1/n]` (obtained as `~~(1:n)/n`) the result is a moving average, of which only the `'valid'` part is kept. [Answer] # [Python 3](https://docs.python.org/3/), 55 bytes ``` lambda n,A:[sum(A[j:n+j])/n for j in range(-n-~len(A))] ``` [Try it online!](https://tio.run/##dZDNbsIwEITP5SlGOdnqksZOTCBSDnmFXoMPqUooESwopYde@urp2hyIimpp/TOz39jy5fv6ceZ86uvtdOxOb@8dmJqq/fw6qaYdKn4evH5h9OcRAw6MseP9Ti15@XPcsWq09lPwmNAQXkOHWjwpR2gNwRJyQkGQ84pQEtYeYt1Fj/vQJGQeyCwTNwu0k521IpqN84E0ZZoHfR0W624BkTSRlM5Y82DgX2t2p8RJ5Y@k/SPNSHliuxGqCOVCeLzB@Bu5EqmwqcxlnMVJndeLh6wKl/HAV9Wr8JGakGy5rhP50bhN9PQL "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` ŒsùÅA ``` Explanation: ``` Œ All substrings sù Keep those only where the length is equal to <the second input> ÅA Arithmetic mean of each element in the resulting array. ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6KTiwzsPtzr@/x9tqKNgpKNgrKNgoqNgqqNgpqNgrqNgEctlCgA "05AB1E – Try It Online") [Answer] # [R](https://www.r-project.org/), 72 bytes ``` function(l,n)(k=sapply(0:sum(l|1),function(x)mean(l[x+1:n])))[!is.na(k)] ``` [Try it online!](https://tio.run/##PcrNCkBAFAbQVxm7@2XIX5J4EllMMiXjkqEo7z5mIYuzO7vToomcPnk4ppXJSAbNrVXbZm5KansuZJ4U8h8XllH52F1hWnMPoAsmG7OiGb3TNFAlhSi80ss@BWQO9wI "R – Try It Online") Computes the `mean` of all the size `n` windows; when the window goes past the edge of `l`, the results are `NA` so we filter them out. # R + zoo package, 13 bytes ``` zoo::rollmean ``` The [`zoo`](https://cran.r-project.org/web/packages/zoo/) package (S3 infrastructure for Regular and Irregular Time Series) has a lot of handy functions. You may [try it here (R-fiddle)](http://www.r-fiddle.org/#/fiddle?id=YkjMGlQL&version=1). [Answer] # [Japt](https://github.com/ETHproductions/japt/) v2.0a0, 7 bytes ``` ãV ®x÷V ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=41Ygrnj3Vg==&input=WzgsNCw2LDIsMiw0XSwz) --- ## Explanation Implicit input of array `U` and integer `V`. ``` ãV ``` Get subsections of `U` with length `V` ``` ® ``` Map over the subsections. ``` ÷V ``` Divide each element by `V`. ``` x ``` Sum all elements. [Answer] # [Factor](https://factorcode.org/) + `math.extras`, 14 bytes ``` moving-average ``` [Try it online!](https://tio.run/##VY7NCsIwEITveYp5Acs2bdRa8CpevIgn8RBKWnvoD0koSsmzx8UfVHYOy37DzNa68oONp@P@sNtAOzdUDp3218TcvNUOozXe30fb9h6lELMAZp4UEhlyKCyxwhqBt/BhRFDEXBGkzJAWzNj95W8Fjvk5SkJGf86CkLPUMzIldnNtEAHn2A1T2zcLPRmrGxMvqF/fbzs9IokP "Factor – Try It Online") Built-in. --- # [Factor](https://factorcode.org/), 22 bytes ``` [ clump [ mean ] map ] ``` [Try it online!](https://tio.run/##VY@9DsIwDIT3PsU9QeX@BChIrIiFBTFVHaIqLZVoGpJ0QFWevZg/AfINtr/TWW5k7Qc7n477w24N6dxQO7R2GE2nW/TSn2Pnpe@c7xgYq7y/GdtpD6euo9K1cthE0RQBE1eCFBlyCCywxAqBu/BhRBDEXBDSNENSMGP3l78VOOZnmRIy@nMWhJwlnpEJsZvPhijMJerL2BuU6JXUqPgBg2puXo9tH1M83wE "Factor – Try It Online") ## Explanation: A non-trivial answer. It's a quotation (anonymous function) that takes a sequence and an integer from the data stack as input and leaves a sequence on the data stack as output. * `clump` Split a sequence into groups of `n` with overlapping. This creates the moving window. * `[ mean ] map` Map each window to its mean. [Answer] # [Python 3](https://docs.python.org/3/), 61 bytes ``` lambda l,n:[sum(e)/n for e in zip(*[l[i:]for i in range(n)])] ``` [Try it online!](https://tio.run/##PY5BDoIwEEXXeopZtmYSSxEVEk9Su8AI2qQMBHGhl68zqCx@Mu//t5jhNd17ylN7OqdYd5drDRGpco9npxq9JWj7ERoIBO8wqI2LLlReuiDdWNOtUaS99knKiEDSO@cyBIuQI@wQCoQ9wgHh6Bk4PBvDpxGl4MtaNrNStvy3M89hzJbKcnKzWCXjTlKIOeviWu@r9WoYA01KXtJ/aL@4sE4f "Python 3 – Try It Online") [Answer] # Mathematica, 21 bytes ``` Mean/@##~Partition~1& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfNzUxT99BWbkuILGoJLMkMz@vzlDtf0BRZl6JgkNadLWlgY4JEJnqGBoYALFhrY5R7H8A "Wolfram Language (Mathematica) – Try It Online") -3 bytes JungHwan Min [Answer] # [Proton](https://github.com/alexander-liao/proton), 46 bytes ``` n=>l=>[sum(l[h to h+n])/n for h:0..len(l)-n+1] ``` [Try it online!](https://tio.run/##DcZLCoAgEADQq8xyBq384KLALiIuEwMbw@z81lu9u9VeeSQ/2O/F7@F5LywhQ6@QBUdaGFJtkDc1z@VgLDSx0HHc7eSOCS1h0EpJcMpIsO6fMVaCXl0kGh8 "Proton – Try It Online") Note that this takes input via currying functions syntax, and returns a list of fractions. [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), 61 bytes ``` def f(N;L):[L|range(0;1+length-N)as$i|.[$i:$i+N]|add/length]; ``` Expanded ``` def f(N;L): [ L | range(0;1+length-N) as $i # generate | .[$i:$i+N] # sublists | add/length # compute mean ]; ``` [Try it online!](https://tio.run/##fY3NasMwDIDvfQrBckioncVO3LQ17AlKXiD4EMhPPYLTJQ675NnnyS5jgcEEki30fdL7h3Nt10MfV/KWXOvbNjdm6OJMsuPYmcHeaZU0S6S3tI70NdLHSm1N274@h0q6PhayZgQ4gZxAQUAQOBEoCZxVQgDgBegbhKh/AXXo4xy9LMM@867AH@dIsIsI4t5jZZp75uwfLoLOvI54yOepfez0HfZzFrdg5v97PPBc1hdkC5/CLwmbmEr@8CccFzzFWoaKaCrUYbPTYmdtBvc1PayezOIoNes4Um0eq8Vmbj7ptFpsvgE "jq – Try It Online") [Answer] # CJam, ~~14~~ 12 bytes -2 bytes thanks to @aditsu ``` {_@ew::+\f/} ``` [Answer] # x86 Machine Code, 20 bytes ``` 86 89 D9 31 C0 03 44 8F FC E2 FA 31 D2 F7 F3 AB 39 F7 72 ED C3 ``` The above bytes define a function that calculates the moving average of a list, modifying the elements of the list in-place. It assumes that the list is a contiguous array of integer elements. The function takes the following inputs in registers * `edi`: the address of the first element in the list (*i.e.*, a pointer to the beginning of the array) * `esi`: the address of the element following the last element in the list (*i.e.*, a pointer to one past the end of the array) * `ebx`: the size of the window (*i.e.*, number of elements to consider in each window) This is a custom calling convention, which is common when writing machine/assembly language functions. All averaging operations are done internally in integer mode, as provided for by the challenge. The input array, bounded by the addresses specified as `edi` and `esi`, is modified in-place by the function: the first *n* elements are replaced with the corresponding moving average. Thus, the caller just discards all but the first *n* elements. **[Try it online!](https://tio.run/##rZRfb9owEMDf8ylOmbYm1G0JhG0FitSKPlTaaNVO6ySKkIkN8pTYUWwYDPWrjzl/m5TQly2RE/ty9zvf5c5eGJ4sPG@3WwlG4KtYMb64XNEIL6i15JItOCUNCL9jf0nlFV0wjmBPfs3JixS8R8aJ@GUbWwP0NZ1iGUynlnnKuKL@VG64wmvgIozonK1NI9HKL/OJ3y4Vjb4IEb6/6JqvPz6pQKziOfXWCOhsXaOxFlGigWMNXOPhhvO3PGBCCvvh4@39EO6@3cOYEgbHsV9ogAsn4E5qbH1N1fOSh333Lzsk8Q5JXQyEpVHWBiiVkKRG7gVhimUaK1mNxs9ZMi@leH97p1ip/C@l/@iJV1BdqK7MoQlglWvETj@dNYDxcKkgxBEOqPap13A9vIHGWRmBwHwoIXQ5AbyNeKhBzGJEVnyJ7G3E1Y9XCB1IQAMRbSrB2j3jefeOcc9fEgp9ps2xEtHAKMmEVBHFwcAwFA1CHystlOw3nSoYDYyks@4i4VEpL6MIb4rGAusDjiJ7PJrst09Z8rCc@UwqmbWUVKTb9YSOqN@Ho/FRLxbOdUlZmVMGF9Ds6VcfRj04PmZ2rLHNwqqa61u/9DbGbNLLNNgcrNjYGukyd2w7E29f8lJloKPc8tnIHxUNEyavaigrNpXeFwMYmwkjHtVTKAHN4qqy4mShlEw5yZb5cVOYH8hEkcV/ykhB@a@Z0TVmGPp4hADrMPOTsygARaVyxhMdyxYcBC0EbQQugg6Cjwg@IfgMz6mfSpklZomWq7Ozj2zlyGZTazVjbEfPWi1Nd847B5mp/3Yts10wUTYOYmIvhzBuCdPSo30Y4ya7cWoxnQxzrhFuPDoojdZpOgeBnSTDbtL4f7y5jxdydxK0W38B "C++ (gcc) – Try It Online")** Here are the ungolfed assembly mnemonics: ``` MovingAverage: ; Inputs: ; edi = &array[0] ; esi = &array[N] ; ebx = cWindow ; Outputs: ; array is modified in-place, starting from the beginning ; Clobbers: ; eax, ecx, edx, edi, flags OuterLoop: 89 D9 mov ecx, ebx 31 C0 xor eax, eax InnerLoop: 03 44 8F FC add eax, DWORD PTR [edi + ecx * 4 - 4] E2 FA loop InnerLoop 31 D2 xor edx, edx F7 F3 div ebx AB stos ; DWORD PTR [edi], eax; sub edi, 4 39 F7 cmp edi, esi 72 ED jb OuterLoop C3 ret ``` The assembly code should be pretty self-explanatory, although I hope sufficiently clever! The code basically just runs two loops. The outer loop iterates through the entire array, one element at a time. The inner loop starts at the current element, iterates through the length of the window, and computes the sum. After the inner loop, the sum is used to compute the average (simple division by the window size), and then the resulting moving average for that "sublist" is written back into the original array at the current index. Very few notable "tricks" here. Of mention: * Cleverly choosing the calling convention allows significant savings with the elision of unnecessary `MOV` instructions. (Of course, that burden is transferred onto the caller, but they're not playing code golf!) * The string instruction, `STOSD`, is used to save a large number of bytes; encoded with only 1 byte, it writes the contents of the `eax` register back to the memory location contained in `edi`, while simultaneously incrementing `edi` by 4 bytes to contain the location of the next element. * The `LOOP` instruction (which does a combined decrement of `ecx` and loop if its new value is not equal to 0) is used to save a couple of bytes. [Answer] ## JavaScript (ES6), 53 bytes ``` (l,n)=>l.map(e=>(s+=e-=a[i-n]||0)/n,s=i=0).slice(n-1) ``` [Answer] # PHP, 94 bytes ``` function f($l,$n){while($i<=count($l)-$n)$r[]=array_sum(array_slice($l,$i++,$n))/$n;return$r;} ``` [Try it online!](https://tio.run/##bU/dCoIwFL7vKXaxiw0XufmTotKDRIiI0sCWLCUienb7ZgVRwr5x9v2cc9Yf@ynf9bjb0dSDPhvSMtoJavj9etRdw6jOi/o8mgE0X4Ondn8oKmurW3kZT@xddbpu5qD2PJfmG2oy2wyjNdRmj6m32gylZS3bS0GUIIEgoSCRILEgW0GSAx6cZ6tvo@@D9J05QqUUMjKN4Az@nFBmQJQLogICfyGZQggdIpeeW0jY1G8PCK/jLLFbBr2wd5jiB@AT9cnL5D1megI) [Answer] # [Clojure](https://clojure.org/), 48 bytes ``` (fn[n a](map #(/(apply + %)n)(partition n 1 a))) ``` [Try it online!](https://tio.run/##TcnBCsIwEATQe79iQIRdPJi0idZvCT0s2kClbkOoB78@7klkZi7z7uv2fNe50WPOyI2yJoVM9JKCA51JSlk/OOHIylSk7su@bAqFhzBz466jUhWUMSCNCLigt4SJ@ScRyds3mEbzK8Z/7ZFuDsEa4Z2zeeP2BQ "Clojure – Try It Online") [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 22 bytes ``` [infixes[:sum\#'/]map] ``` [Try it online!](https://tio.run/##JY7LCoMwFET39yumuNAsam8S01Ypxf9Is5CqIMUSjEL/PvUBZzNzGJgwN@9P18Zoh28//Lpgq7CMryS9uLHxLtZVT5QRMgkFjQIGV9xwFzBbyQzDqzAMpTRkaQT0LrAjII@kGJoPVzKKFYNtLVkKKBKkkgcsAWk9dX7C@Yn0BL/MyPO8RzsETw7rpfgH "Stacked – Try It Online") ## Explanation `infixes` generates all the windows of the given length. Then, we map our own average function over each infix. [Answer] # [Common Lisp](http://www.clisp.org/), 77 bytes ``` (defun f(x y)(if(>=(length x)y)(cons(/(apply'+(subseq x 0 y))y)(f(cdr x)y)))) ``` [Try it online!](https://tio.run/##bY6xDsIwDER3vuI2bDHgJAToAP8CbQOVqhCaVmq/vpiyoVo33T37XLZNTvNMVR2GiEAjJqYm0PVCbR0f/RMjq1O@YqY93VJqp@2O8nDP9RsjRPFvHqisugXVmSl1TezV1OM9DCwcDvA44oQze@bNHyECL0p5gbUOpvDsVqif2KxFVuBkZasQHFR@KTFi2OqDHw "Common Lisp – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~13~~ 11 bytes **Solution:** ``` {+/+x':y%x} ``` [Try it online!](https://tio.run/##y9bNz/7/v1pbX7tC3apStaI22tja0MBAwdTASMHY1EDByMhYwdDSNPb/fwA "K (oK) – Try It Online") **Examples:** ``` {+/+x':y%x}[3;8 4 6 2 2 4] 6 4 3.3333 2.6667 {+/+x':y%x}[5;1 2 3 4 5 6 7 8] 3 4 5 6 ``` **Explanation:** `oK` has a built-in for creating a sliding window, then sum up resulting arrays and divide by sliding window size to get mean: ``` {+/+x':y%x} / the solution { } / lambda function taking x and y as implicit parameters y%x / y (list) by x (sliding array size) x': / sliding window of size x over list y + / flip array (rotate by 90 degrees) +/ / sum up array ``` [Answer] # [DataWeave](https://blogs.mulesoft.com/dev/mule-dev/dataweave-mule-4-beta-syntax-changes-part-2), 50 bytes ``` fun s(l,w)=0 to(sizeOf(l)-w)map avg(l[$ to $+w-1]) ``` ``` %dw 2.0 output application/json fun sma(list: Array<Number>, window: Number) = 0 to (sizeOf(list) - window) // generate starting indices of sublists map list[$ to $ + window - 1] // generate sublists map avg($) // calculate averages --- sma([90, 40, 45, 100, 101], 2) ``` ]
[Question] [ Write a program or function that takes input and outputs/returns a full program (in the same language) that outputs said input. Note that the input may contain any printable ASCII character or newline (AKA 0x20-0x7f and 0x0a). However, the input will not have trailing whitespace nor preceding whitespace, nor will it be empty. ## Test cases (Javascript): ``` cat => console.log("cat") fish => console.log("fish") m(newline)ta-c t => console.log("m\neta-c t") m"'`\c => console.log("m\"'`\\c") ``` ## Example program ``` function metaCat(text){ return "console.log(\"" + text.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n") + "\")" } ``` ## Scoring Score is the sum of your code size and the size of the output for each test case [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 78 + 2109 = 2187 bytes ``` +++++[>+++++++++<-]>[->+>>+>++>+>++<<<<<<]>-->>+>+>>+++<<<<,[[-<.>]>[.>]<[<],] ``` [Try it online!](https://tio.run/##NYpBCoAgEEX3niLctBinEwxzkVHIBElCF2XnNxV6fP7i8Y7bpxLfcLUGA2H4IXQsyMB9APNo4hhxSh7xMEYEaePe9yMhZ1xrwVcV03MqnW2pHsOiVdbrbsMH "brainfuck – Try It Online") [Answer] # [Python](https://www.python.org), 19 (program) + 60 (output) = 79 bytes *-3 bytes thanks to loopy walt* ``` "print(%r)".__mod__ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RU5BCsIwELznFcuCmKIVjyL0Ja3EEBNaaLelWQWPvsNLQPQDvsbfmJiDp5nZnRnm_pqu3I4UHq5qnmd25e6N09wRy8Vc4EapYTwplT-fG1vPymhvPVRQo9GMa0DX-Tbh0BDr0sDviDjg8tiYSA6Con0r3DhDCkNH8G_aC0htTiZVCLAX3UsfCcGqgt5SEnkSFXlICBm_) [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 1 + 32 = 33 bytes ``` ` ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/P@H//@TEEgA "GolfScript – Try It Online") The outputs are: ``` "cat" "fish" "m\nta-c t" "m\"'`\\c" ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes + 23 character sum = 26 score ``` øDṪ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBIiwiIiwiw7hE4bmqIiwiIiwiY2F0XG5maXNoXG5cIm1cXG50YS1jIFwiXG5tXCInYFxcYyJd) So funny story, my previous answer wasn't actually valid because `øD` already wraps in quotes, making the `q` useless. ## Explained ``` øDṪ øD # dictionary compress the input, quoting it at the same time Ṫ # Remove the trailing backtick ``` [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), 71 + 46 bytes = 117 ``` !["](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")![<](https://$ "Change Cursor Direction")![o](https://$ "output a character")![>](https://$ "Change Cursor Direction")!['](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")!["](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")![i](https://$ "read a character")![:](https://$ "Duplicate the top item on the stack")![0](https://$ "Push the number (0-9)")![(](https://$ "Greater than, less than. Push 1 or 0 to the stack.")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![v](https://$ "Change Cursor Direction")![:](https://$ "Duplicate the top item on the stack")![\](https://$ "Reflect the cursor direction") ![<](https://$ "Change Cursor Direction") ![\](https://$ "Reflect the cursor direction") ![>](https://$ "Change Cursor Direction")![o](https://$ "output a character")![<](https://$ "Change Cursor Direction")!["](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")!['](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")!["](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")![~](https://$ "Delete the top element of the stack")![<](https://$ "Change Cursor Direction") ![|](https://$ "Reflect the cursor direction")![.](https://$ "Pop 2 values of the stack then move to that position.")![!](https://$ "Skip the next instruction, moving 2 spaces instead of 1")![0](https://$ "Push the number (0-9)")![5](https://$ "Push the number (0-9)") ![^](https://$ "Change Cursor Direction")![v](https://$ "Change Cursor Direction")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![=](https://$ "Pop 2 values of the stack, push 1 if they are equal and 0 otherwise") !["](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")!['](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")!["](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")![:](https://$ "Duplicate the top item on the stack")![v](https://$ "Change Cursor Direction")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![=](https://$ "Pop 2 values of the stack, push 1 if they are equal and 0 otherwise")![a](https://$ "Push the hexadecimal (10-15)")![/](https://$ "Reflect the cursor direction") ![^](https://$ "Change Cursor Direction") !["](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")!['](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")![a](https://$ "Push the hexadecimal (10-15)")!['](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")!["](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")![~](https://$ "Delete the top element of the stack")![/](https://$ "Reflect the cursor direction") ![~](https://$ "Delete the top element of the stack")![/](https://$ "Reflect the cursor direction")![^](https://$ "Change Cursor Direction")![1](https://$ "Push the number (0-9)")!["](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")!['](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")![d](https://$ "Push the hexadecimal (10-15)")![3](https://$ "Push the number (0-9)")![*](https://$ "Pop 2 values of the stack then perform the given operation.")!['](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")!["](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.") ``` Hover over any symbol to see what it does [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiXCI8bz4nXCJpOjAoP3Y6XFxcbjwgXFwgPm88XCInXCJ+PCB8LiEwNVxuXnY/PSBcIidcIjp2Pz1hL1xuXiAgXCInYSdcIn4vXG5+L14xXCInZDMqJ1wiIiwiaW5wdXQiOiInYWJjICdcIiBkZWYiLCJzdGFjayI6IiIsInN0YWNrX2Zvcm1hdCI6Im51bWJlcnMiLCJpbnB1dF9mb3JtYXQiOiJjaGFycyJ9) Unformatted version if the code above appears glitched: ``` "<o>'"i:0(?v:\ < \ >o<"'"~< |.!05 ^v?= "'":v?=a/ ^ "'a'"~/ ~/^1"'d3*'" ``` Only characters that need escaping are the single quote and line break [Answer] # [Haskell](https://www.haskell.org), 24 + 76 = 100 bytes ``` f=("main=putStr"++).show ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWO9JsNZRyEzPzbAtKS4JLipS0tTX1ijPyyyHSN7tLUotLkhOLU4sVbBWilZITS5R0FJTSMoszQHRuTF5Jom6yQgmEo6SeEBOTrBTLxQUyEaghJZ9LQQFisE-egopCmoJSBtDyfCVUYZB9IKo0F0jmJhYoaOSk5qWXZCjoKaRpKsBdAHESzOUA) [Answer] # [Rust](https://www.rust-lang.org/), 51 bytes + 110 bytes = 161 bytes ``` fn f(x:&str){print!("fn main(){{print!({:?})}}",x)} ``` [Try it online!](https://tio.run/##PY7RCsIwDEXf9xUxA21g@gHzwQ9xomVYLNhM2giD0m@vXcHm5ZITODf@GyRnw2DUOu6DeIofb1l2Cgt02rKi@EdxvCRKCYeVUm5niB2UMYuHAJbhirMWHACNDa8tnZqYRB9n2LDv0eFhmh/Y305Fu9ytPH3TVJUKdG5bLX9z@QipwtSl/AM "Rust – Try It Online") We take the input as a string, but print the output, saving having to specify `f`'s return type. `Debug` does the escaping for us. [Answer] ### Common Lisp, 21 + 52 = 73 ``` (lambda(s)`(print,s)) ``` For example: ``` (funcall (lambda(s)`(print,s)) "cat")) => (print "cat") ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 23+49 = 72 bytes ``` printf 'echo %q\n' "$1" ``` [Try it online!](https://tio.run/##S0oszvifpqFZ/b@gKDOvJE1BPTU5I19BtTAmT11BScVQ6X8tV1p@kUKFQmaeQnJiiUJaZnGGgop6bkxeSaJuskKJOoijFGNgYp4Qk6xuXa2QBtRWoWSdWpaYA2RpQLiaSta1XP8B "Bash – Try It Online") [Answer] # [JavaScript (V8)](https://v8.dev/), 32 + 60 = 92 bytes ``` s=>`print(${JSON.stringify(s)})` ``` [Try it online!](https://tio.run/##TY3NCsIwEITvfYolCKZoi0ehpDcvHvTQoxUaYtJGYlOapaClz14TxZ/DsszM7jdXPnAnet1hMmxnxWbH8qrrdYt0Me6L4yF16FWt1Z26eIqr2UgEtMhNoR8SGGyy6AREcCRrIEq7Juxb2SJPBOBbkGVVloLAOUqV7XdcNNQBy2GMAAJP2EtAKV@ReeuHX7FXlhrZ1tiETNjWWeMdW9MQvR7kwM1HTX7@j76wOJuf "JavaScript (V8) – Try It Online") [Answer] # [Lua](https://www.lua.org/), 30 bytes, score 82 ``` print(('print%q'):format(...)) ``` [Try it online!](https://tio.run/##yylN/P@/oCgzr0RDQx1Mqxaqa1ql5RflJpZo6OnpaWr@//8/V0k9ISYZAA "Lua – Try It Online") No need for parentheses in resulting program since we're printing a string literal. [Answer] # [C (gcc)](https://gcc.gnu.org/), 108 + 84 = 192 bytes Lots of bytes less thanks to @c--. ``` f(int*s){for(printf("main(){puts(\"");*s;s++)printf(*s-34?*s-92?*s-10?s:"\\n":"\\\\":"\\\"");puts("\");}");} ``` [Try it online!](https://tio.run/##PYw/D4IwEMVn@ynwprakjf8WZWAzDo4mLhcTAtSQYEs4dCF89tqCcbh3d@/u/Ur1LEvvDW/sIEmMxvW868NiOLyKxnIxdu@BOAKITFJGaSp@d0lqf8iDHndRt5ucToBoISri0mJsBgCGaYrlQzqZ2R/XVIKNbGX4FW41DYnWOrwsxqVuW4f27vq2Wv9dbZSmqpDnB0Yim/wX "C (gcc) – Try It Online") [Answer] # [ForWhile](https://esolangs.org/wiki/ForWhile), 42 (Program) + (9+10+14+14) (Output) = 89 bytes `34#::`[_~:[~;;=[92#):92=[:#)#])#"(,#)"(,#)` [online interpreter](https://bsoelch.github.io/OneChar.js/?lang=forwhile&src=MzQjOjpgW19-Olt-Ozs9WzkyIyk6OTI9WzojKSNdKSMiKCwjKSIoLCMp&in=IjEyM1w0CjU2NyI=) # Explanation: ForWhile allows multi-line strings, so the only characters that need to be escaped are `"` and `\` ``` 34# \ print a " ::`[ \ loop up to 34^34 times (for-while has no infinite loops) _ \ read a character ~:[~ \ character is not end-of file ;;=[92#) \ print a backslash if character is " :92=[:#) \ print a backslash if character is \ # \ print the character ]) \ break loop if character was end of file #"(,#)"(,#) \ print "(,#) to print the string produced by the program ``` The printed programs are just a (multi-line) string literal containing the Input-string, followed by `(,#)` which will print the string. Output for Test-cases: ``` "cat"(,#) "fish"(,#) "m ta-c t"(,#) "m\"'`\\c"(,#) ``` # ForWhile, 35 (Program) + (4\*17+3+4+8+6) (Output) = 124 bytes Shorter program but slightly longer output. `"17-9:`[1-:@:[#])?"(,#)9:`[_~:[~#])` Prints a program (of length 17) that prints all its source code except the first 17 characters and then terminates, followed by the input string. [Answer] # [owl lisp](https://haltp.org/posts/owl.html), 51 + 176 = 227 this is a very *quick and dirty* solution ``` (λ (s) `(print (list->string ',(string->list s)))) ``` example: ``` > (eval ((λ (s) `(print (list->string ',(string->list s)))) "cat") *toplevel*) cat ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 2 + 28 = 30 ``` Ṙṫ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVFMSVCOSU5OCVFMSVCOSVBQiZmb290ZXI9JmlucHV0PWNhdCUwQWZpc2glMEElMjJtJTVDbnRhLWMlMjB0JTIyJTBBbSUyMiclNjAlNUNjJmZsYWdzPVY=) Take the string `Ṙ`epresentation, then remove the `ṫ`ail (last character, the end quote). [Answer] # [C++14](https://gcc.gnu.org), 132 + 176 = 308 bytes ``` [](auto&s){auto t=s;s="#include<cstdio>\nint main(){puts(\"";for(auto c:t)s+=c-34?c-92?c-10?s+=c,"":"\\n":"\\\\":"\\\"";s+="\");}";} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVDLTsMwEBQ36q9YGYkmCkEt9ABx3H5IXbWRmxRLjVNl1xeq3vgLLr0gcYH_ga_BToR4HrxrzezsjP34ondbh-EsN1q_znmKtJY6ScYTvnguHDVQgXxyVKU3bw_zRRSgc4z3HUUSBUp-ZqzeunWZay82zVRZYwnqwtgo3u8cYaQ4F1XTdmrQGcWYSJ1eT2Y6vb3yZTyaBeSC84wrZbuqVN-81HNc8VgcuDj0Wd5PTgX79IXcNEhtWdRTxnyELENzXy6JUYkU9QC1xm4AY7ZngyrCWLBBR-jGEeQ5YChDZYeCsUFbkmst4GXYE_nZA2NfTworvrnAtrQgYRSE4ZpI6Hy5LogHnx9gZfDuL1orS0Wq4R9BrfhwpZQOzK_Mfs5H6z_keOz7Bw) [Answer] # [Go](https://go.dev), 91 + 216 = 307 bytes ``` import."fmt" func f(s string){Printf(`package main import."fmt" func main(){Print(%q)}`,s)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70oPX_BmoLE5OzE9FSF3MTMvKWlJWm6FjejM3ML8otK9JTSckuUuNJK85IV0jSKFYpLijLz0jWrA4BUSZpGArJOLkwtIGENqGoN1ULN2gSdYs1aqBVZSEoUqrk40zSUkhNLlDS5OMHqc_I0lEAcoHBaZnEGNvHcmLySRN1kBayacmOU1BNiYpKBXKiNCxZAaAA) [Answer] # [Nim](https://nim-lang.org/), 49 + 55 = 104 bytes ``` import strutils proc m[S](s:S):S="echo "&s.escape ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY9BCsIwEEX3OcUQQdtFRXdScOEZurSCIaRt0GlKZorexU1B3Hofb2Noo4Kbz-cxf_7M7d5aHIZHz1W2ea0tds4zEPue7ZlE550G3BeHhPIizYutNLpxIOe0NKRVZ2LwOWJMpJRacdBU_EhlqflDKFhlGv4nUS6OpR6hmAEbYtvWwI3iIAbCNbVXSHBx_iSm3NgX7VgUPZbX1S6WfJEsw_5QMF39efsN) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 9 bytes, score 39 ``` ¶ $¶ ^ K` ``` [Try it online!](https://tio.run/##K0otycxLNPz//9A2LhUgjuPyTvj/P5crtSRRN1mhBAA "Retina – Try It Online") Explanation: ``` ¶ $¶ ``` Change newlines into pilcrows. ``` ^ K` ``` Prepend the `K` instruction (replace buffer with literal string). The test cases encode as follows: ``` K`cat K`fish K`m¶eta-c t K`m"'`\c ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 19 bytes +10+11+16+15 = 71 Chose to count the trailing newline in the score because it's possible to print without it, as per the other answer. ``` $><<"$><<" p$<.read ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWm1XsbGyUwARXgYqNXlFqYgpEBqpgwbJcJfWEmGQIDwA) # [Ruby](https://www.ruby-lang.org/), 23 bytes +9+10+15+14 = 71 Output doesn't include a trailing newline, but the score turned out to be the same anyways because the solution required 4 more bytes. ``` $><<"$><<"+$<.read.dump ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboW21XsbGyUwIS2io1eUWpiil5KaW4BRBaqaMGyXCX1hJhkCA8A) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes, score 33 ``` SUT¿ⅉ´U´T ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMzr6C0JLgEyE7X0NS05grJT0/PSQ0pyszVAPIy0xQ0IoHiChDFSu/3bH2/Z4uSpvX//9FKuTF5qSWJuskKJUqx/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` S ``` Write the input string to the canvas. This is sufficient to generate a program that prints only printable ASCII; the rest is newline handling. ``` UT ``` Turn off right-padding. (Has no effect if there was no newline in the input.) ``` ¿ⅉ ``` If the input contained at least one newline... ``` ´U´T ``` ... output the command to turn off right-padding. The test cases encode as follows: ``` cat fish m eta-c tUT m"'`\c ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@XK7UkUTdZoeT9nq3v92z5/x8A "Charcoal – Try It Online") (Third test case only; the others are trivial.) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 24 + 30 = 54 bytes ``` % *ce "'" "''"|%{"'$_'"} ``` [Try it online!](https://tio.run/##TU7BasMwDD3XXyGEOzXdMnYO5FTWU6GH7raNxPW8ppsTB0dlh6bfnikUmj4Q4uk9PakNfy52lfN@0G0Mh2jqDnIga5iegL6PXSUd67Jhk1pglGGNROWHJeiHOSytAySUIuznZyRdEF4GbcOX27jmwJXEvagpvId1iK/GVul2/@Msw1nN7t2POeji@UrUjFaiZCSWQkg6Qghe5Qz04uZN8M5A2xO3Jx4XH2DxvrPx2PLeB/v7mWWr6Aw72UwSicpvKBtUF4VvgY2H8SPw05npwwSHfw "PowerShell – Try It Online") Input comes through the pipeline. `% *ce "'" "''"` - `%` is an alias for the `ForEach-Object` cmdlet, which takes the input string, and runs the string's method "Replace()" (the only one matching "\*ce") against it, replacing all single quotes with a double single quote. This is then piped further to `%{"'$_'"}`; again ForEach-Object, but this time invoking the scriptblock, which simply takes the input string, and wraps it in single quotes; output is implicit. In PowerShell, anything inside a string enclosed in single quotes is taken verbatim, so no need to worry about escaping anything, except for the single quotes. As an alternative, a Here-String `@'<LF>...<LF>'@` could be used, which would remove the need to escape even the single quotes: ``` %{"@'`n$_`n'@"} ``` This is only 15 bytes instead of 24, but the output has 6 additional characters per test case instead of 2, and would come to a total of 60 bytes. In the TIO above, the code can just be replaced. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: 28 (3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) + 25 output sum) ``` "“ÿ ``` [Try it online.](https://tio.run/##yy9OTMpM/f9f6VHDnMP7///PVVJPiEkGAA) The outputs for the four test cases are: ``` Input: cat Output (4): “cat Input: fish Output (5): “fish Input: """m ta-c t""" (multiline input) Output (9): “m ta-c t Input: m"'`\c Output (7): “m"'`\c ``` **Explanation:** ``` " "# Push the following string: “ # Regular dictionary quote for the output program ÿ # String interpolation, which is automatically replaced with the (implicit) input # (after which the result is output implicitly - with trailing newline) ``` If there is no trailing `"` or `“`, 05AB1E outputs everything after it as a string. [Answer] # [Trilangle](https://github.com/bbrk24/Trilangle), 104 (program) + 48 + 82 + 175 + 175 (outputs) = score 584 ``` '0.<_.<.>i,S)#..\_//222*3'/."-S:2'*)<.L-3',o\.><#.(,o.""<._.......j)2<>(<#,,o@o+0"@#.,#,o'"........^oo", ``` [Try it in the online interpreter!](https://bbrk24.github.io/Trilangle/?i=m%0Ata-c#%270.%3C_.%3C.%3Ei%2CS)%23..%5C_%2F%2F222*3%27%2F.%22-S%3A2%27*)%3C.L-3%27%2Co%5C.%3E%3C%23.(%2Co.%22%22%3C._.......j)2%3C%3E(%3C%23%2C%2Co%40o%2B0%22%40%23.%2C%23%2Co%27%22........%5Eoo%22%2C) The score is kinda terrible because the output is quadratic in the size of the input. This program: 1. Collects the input and keeps track of length ``` ' 0 < _ < . > i , S ) # . \ _ / ``` 2. Computes `triangular(3n) - 3n - 2`, the amount of NOPs needed to put the work all on the bottom row of the output program ``` / 2 2 2 * 3 ' / - S : 2 ' * ) ``` 3. Outputs a leading `\` to redirect the IP to the bottom row, all the filler NOPs, and the "end program" instruction ``` " < L - 3 ' , o \ > < # . ( , o . " " < _ , o @ ``` 4. Repeats the input in a format that Trilangle can understand it. This relies on implementation-defined behavior; it works in my reference interpreter as of v1.6.2. ``` j ) 2 < > ( < # , o + 0 " @ # . , # , o ' " ^ o o " , . ``` ]
[Question] [ # Background I am currently in an AP Comp Sci A: Java class, and I want to start some of my friends on code golfing. I have a challenge from the course, and I would like to see how many bytes the community can do this challenge in. # Challenge details: Given two input strings, the main string and the pivot string, do the following: If the pivot string is exactly once as a substring of the main string, the part of the main string that comes before the pivot string shall be swapped with the part that comes after, while *preserving the order within said subtrings being swapped*. For example: If the pivot string is empty or the pivot string is *not* found within the main string, the program does not have to have defined behavior. If there is more than one instance of the pivot string, the split should occur at the first and *only* the first instance of the pivot. Examples: Given the main string `OneTwoThreeTwoOne` and the pivot string `Two`, the output should be `ThreeTwoOneTwoOne`. Given the main string `1Two2Two3Two4` and pivot `Two`, the output should be `2Two3Two4Two1`. Given the main string `OneTwoThree` and the pivot string "Two", the output should be `ThreeTwoOne`. Given the main string `the rabbit is faster than the turtle` and the pivot string ``` is faster than ``` (note the single space trailing and preceding), the output should be `the turtle is faster than the rabbit`. Given the main string `1-2-3-4-5-6` and the pivot `-`, the output should be `2-3-4-5-6-1`. ## Afterword: This is my first ever question on code golf, so if you have suggestions or constructive criticism, then feel free to say so. Additionally, my code for this project (written in Java because the course focuses on that) can be found below. If you have any tips, I'd love to see them. Its currently 363 bytes, but I bet you guys can come up with much better and smaller solutions. ``` import java.util.Scanner;interface Main{static<T>void D(T f){System.out.println(f);}static void main(String[]A){Scanner s=new Scanner(System.in);D("Enter the first String:");String a=s.nextLine();D("Enter the pivot String:");String p=s.nextLine();if(p.isEmpty()|!a.contains(p)){D("Error: Pivot String not found.");return;}String w[]=a.split(p,2);D(w[1]+p+w[0]);}} ``` Note: The text for the inputs and for the case that the pivot string is not found is mandatory for the original assignment, but not for this challenge. [Answer] # Mathematica, 42 bytes ``` Reverse@StringSplit[##,2]~StringRiffle~#2& ``` [Try it online!](https://tio.run/##XY3BCsJADETvfkXYBU899S70D5S2t9JDKlk3sF0ljXrrr68RoRRPk8ljZmbUSDMqX7GEU2npRbJQ06lwvnWPxDp4X9Xj@vu0HEKi1dfHcjGvTRjcOVP/vvdRiFwFzm43HjZq9SA4TazACwRclAQ0YoYv0adospj7h/uK3YCpuW2mfAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` œṣṙ1j⁴ ``` [Try it online!](https://tio.run/##y0rNyan8///o5Ic7Fz/cOdMw61Hjlv///yv556WGlOeHZBSlgmggT@m/EpChBAA "Jelly – Try It Online") # Explanation ``` œṣṙ1j⁴ Main Link œṣ Split around sublists equal to the pivot ṙ1 Rotate left by one j⁴ Rejoin on the pivot ``` [Answer] # [Python 2](https://docs.python.org/2/), 37 ~~39~~ bytes ``` lambda a,b:b.join(a.split(b,1)[::-1]) ``` Where `a` is the main string and `b` is the pivot string. [Try it online!](https://tio.run/##XY6xDsIwDET3foWVKUGhUhkjdeIDWLpVHRzhKEElqRIjxNeHdEHALb675@G2F/sUT7W6ccW7vSKgtsb2txSixL5sa2Bp9aBmY47DoipT4TMWKjDC3ElxiTQ90@QzkdCiWaH0b91uS9@QPUFGawNDKOCwMGVgjxF2wo/Ma/sH8U@FWjqXWmgbIET4bDEdNG05RAYnD3uv6hs "Python 2 – Try It Online") [Answer] ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes ``` p#2<>p<>#&@@StringSplit[#,p,2]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v@D9pIXKRjZ2BTZ2ymoODsElRZl56cEFOZkl0co6BTpGsWr/A4BCJQ5p0Uoh5flKsdFK/nmpQFZIRlFqqlIsF1xWIbNYIS2xuCS1SKEkIzFPAaQUaJVCUWJSUmYJuixIpqS0qCQHxQxMG4A0kIesRhekwlDXSNdY10TXVNdMKfY/AA "Wolfram Language (Mathematica) – Try It Online") An unnamed, curried function which should be called with the pivot first and the main string second. E.g., if you assigned the function to a name `f`: ``` f["-"]["1-2-3-4-5-6"] ``` [Answer] # [Ohm v2](https://github.com/nickbclifford/Ohm), 4 bytes ``` ïλ⁴j ``` [Try it online!](https://tio.run/##y8/INfr///D6c7sfNW7J@v/fPy81pDw/JKMoFUQDeVxACgA "Ohm v2 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 20 + 2 (`-pl`) = 22 bytes ``` <>=~/$_/;$_="$'$_$`" ``` [Try it online!](https://tio.run/##K0gtyjH9/9/GzrZOXyVe31ol3lZJRV0lXiVB6f//kPJ8Lv@8VCAVklGUCqKBvH/5BSWZ@XnF/3ULcgA "Perl 5 – Try It Online") Takes the pivot string on the first line, then the full string on the second. [Answer] # [Python 2](https://docs.python.org/2/), ~~53~~ 44 bytes thanks to [ThePlasmaRailgun](https://codegolf.stackexchange.com/users/75773/theplasmarailgun) for some bytes ``` p,m=input() k=m.split(p,1) print k[1]+p+k[0] ``` [Try it online!](https://tio.run/##DcWxCoAgEADQ3a9oO6UStCbBv2gT98zUoy6ir78cHg8/2lu1zDgVnyo@JJXIvugbz0QSlcArVRpQHy1VmYNxbjZxzMG6qJhhextMYHq2W7oVfg "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 37 bytes ``` lambda a,b:b.join(a.split(b,1)[::-1]) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFRJ8kqSS8rPzNPI1GvuCAns0QjScdQM9rKStcwVvN/QVFmXolGmoaSf15qSHl@SEZRKogG8pR0FJSALCVNzf8A "Python 2 – Try It Online") [Answer] # [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 56 bytes ``` (m,p)=>(m+p+m).Substring(m.IndexOf(p)+p.Length,m.Length) ``` [Try it online!](https://tio.run/##VYy9CoMwGABfJWRKMA30b2p1EQoFSweHzjEmNmBi8ItFKz57Cq1Lpzs4OAkbCTLKVgCgfIYggpHo1Zka3YRxhM7lBEFZfhmcPEPojWvYHzKk00gs8zTNiE18Yikvh@oXieVXV6vxromnieeFck14MrsKjad1n3cOulbxR2@CKoxTRBMsKlkr3Wx3@8NxnN6Y4a9iSk/LEj8 "C# (Visual C# Compiler) – Try It Online") [Answer] ## [Alice](https://github.com/m-ender/alice), 18 bytes ``` /?.?.Qz \IoI%!oo@/ ``` [Try it online!](https://tio.run/##S8zJTE79/1/fXs9eL7CKK8Yz31NVMT/fQf//f/@81JDy/JCMolQQDeRxASkA "Alice – Try It Online") ### Explanation ``` /... \...@/ ``` This is just a framework for linear Ordinal mode (string-processing) code. Unfolding the zigzag control flow, we get: ``` I.I.!zo?o?%Qo I. Read the first string, duplicate it. I Read the second string (the pivot). .! Store a copy of the pivot on the tape. z Drop. Removes everything up to and including the pivot from the first string, so we get only the stuff after the pivot. o Output that. ?o Retrieve the pivot from the tape and output it. ?% Retrieve the pivot again and split the input around (all occurrences of) the pivot. Q Reverse the stack. o Output the top of the stack (i.e. the chunk in front of the first pivot). ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), ~~9~~ 5 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ΘK+,∑ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMzk4SyslMkMldTIyMTE_,inputs=VHdvJTBBT25lVHdvVGhyZWVUd29PbmU_,v=0.12) Explanation: ``` Θ split the 2nd input on the 1st one K get the 1st element + and add it to the end ,∑ join on the 1st input ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~24~~ 23 bytes tanks to Martin Ender for -1 byte ``` (.*)¶(.*?)\1(.*) $3$1$2 ``` [Try it online!](https://tio.run/##K0otycxL/P9fQ09L89A2IGmvGWMI4nCpGKsYqhj9/5@oy2Woa6RrrGuia6prBgA "Retina – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 48 bytes ``` lambda s,p:p.join(s.split(p)[1:]+s.split(p)[:1]) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFYp8CqQC8rPzNPo1ivuCAns0SjQDPa0CpWG4lrZRir@b@gKDOvRCFNQ90/LzWkPD8koygVRAN56joK6kCWuuZ/AA "Python 2 – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 8 bytes ``` jQ.<cEQ1 ``` **[Try it here!](https://pyth.herokuapp.com/?code=jQ.%3CcEQ1&input=%22Two%22%0A%22OneTwoThreeTwoOne%22&debug=0)** ### Explanation ``` jQ.<cEQ1 - Full program. cEQ - Split the second input by the first input. .< 1 - Cyclically rotate by 1 place to the left. jQ - Join on the first input. ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes ``` ≔⪪θηθ⪫Eθ§θ⊕κη ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU8juCAns0SjUEchQ1NHoVDTmiugKDOvRMMrPzNPwzexACTjWOKZl5JaAWJ65iUXpeam5pWkpmhka2pqgrRpWv//b6hrpGusa6JrqmvGpftftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ First input η Second input ⪪ Split ≔ θ Assign result Eθ Map over result κ Current index ⊕ Incremented §θ Circularly index into result ⪫ η Join Implicitly print ``` [Answer] # [R](https://www.r-project.org/), ~~63~~ ~~58~~ 57 bytes ``` function(M,P)sub(sub("_",P,"(.+?)(_)(.+)"),"\\3\\2\\1",M) ``` [Try it online!](https://tio.run/##XYzBCsIwEETvfkXY0y5GQb0KfkFpDz0GSqIJCdQUNlvEr4/J1cPwZphhuK7JseUvvr3E7VXoENT9VMOen5K2jIOeqOwOu2ABPWnA8/FBuFAjAWkw5mbM1ZgL6IFqQBiznz/bHNl3tgQamoH2jSDRK7bOJVGpqGCLeFYSbVa9kZ1l7fv/Eqj@AA "R – Try It Online") `M` is the main string, `P` is the pivot. [ovs' Retina answer](https://codegolf.stackexchange.com/a/150176/67312) indicated that I could repair my earlier attempt at a regex approach ``` (.+)(Pivot string)(.+) ``` by adding `?` to the first capture group. [Answer] # Java 8, 47 bytes ``` x->y->x.replaceAll("(.*?)("+y+")(.*)","$3$2$1") ``` [Try it online](https://tio.run/##pYwxb8IwEIX3/IqTlcEGYol2hAaxsFUdYKs6uMEBpxfbcs5AVPHbU0cghnbs9O597/Q16qQK57Vt9l@Dab0LBE1iMpJBOVlkf1gdbUXG2XHMfPxEU0GFquvgVRkL3w/YkaIUtbEK4eTMHtr0wLcUjD28fygx/m7utuUNz373W5Ql1C/DpSj7orzIoD2qSq8ROeNyshKcTfspE@kWbMby5/wpnzMxLLJt35FupYskffIQWg5QS@U99hzYm9W7s9sdgx4zNQbiMSaSKoj/WTYuhrvmml2HHw) [Answer] # JavaScript (ES6), ~~41~~ 40 bytes ``` (s,p,[a,...r]=s.split(p))=>r.join(p)+p+a ``` ### Test cases ``` let f = (s,p,[a,...r]=s.split(p))=>r.join(p)+p+a console.log(f('the rabbit is faster than the turtle', ' is faster than ')) console.log(f('1-2-3-4-5-6', '-')) ``` [Answer] # [J](http://jsoftware.com/), 14 bytes ``` #@[}.{.@ss|.,~ ``` # How it works: The left argument is the pivot, the right one - the string to be reversed ``` ,~ appends the pivot to the string {.@ss finds the positions of the pivot in the string and takes the first one |. rotates the appended string to the left, so that the pivot is at the start #@[ finds the length of the pivot string (n) }. drops n characters from the begining of the rotated string ``` [Try it online!](https://tio.run/##dY2xCsJAEET7fMWgxSLkDk2iRUDIH9iks0rkjotIAncrFhp//dwopAhYDDvDm2Wu0YZjiS1EcV2dR/3UVQgvnb7jJllpkBVMSDGWsCExFzeA6sdAsKBTb8TWzpvpSqJFYScmE@WigvD/fWboAmwT2Hiwa3p8i@wMfNO2HS/xRPju@TZPq9@wylSuCrVXB0L8AA "J – Try It Online") [Answer] # C, ~~106~~ 100 bytes ``` i,l;f(s,p)char*s,*p;{l=strlen(p);for(i=0;strncmp(s+i,p,l);++i);printf("%s%s",s+i+l,p);write(1,s,i);} ``` [Try it online!](https://tio.run/##XY/BCsIwEETv/YqlICR2BXte@iXiIYa0XYgxZFc9FL@9RiwI7nHnzQzjD5P368oYaTSC2frZlb3gPtMSB9ESQzLZ0ngrhocj1U/y12ykY8wYLXUdW8qFk46m3clOWqxaF2sUPQtrMD0KVua1VgaujpOxzdJAvU8X1EROU386wwCtzgGKu1xYgQVGJxoK6OwSfBS9F42hpZ858@Omm/ffsXF11rcBN9pS81rf) [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 53 bytes ``` P =INPUT INPUT ARB . R P REM . L OUTPUT =L P R END ``` [Try it online!](https://tio.run/##K87LT8rPMfn/nzNAwdbTLyA0hIsTTCk4Bjkp6CkEKQQoBLn6Alk@XJz@oSEgGVsfkCCXq5/L//8KmcUKaYnFJalFCiUZiXkKXCUZqQpFiUlJmSXoUiCZktKikpxUAA "SNOBOL4 (CSNOBOL4) – Try It Online") Takes input as Pivot, then Main, separated by a newline. This is basically the SNOBOL equivalent of [my R answer](https://codegolf.stackexchange.com/a/150174/67312). [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 31 bytes ``` ->$_,$b {S/(.*?)$b(.*)/$1$b$0/} ``` [Test it](https://tio.run/##fVBLUoNAEN3PKXoxJaAMSBLZYNAbuJC9xUBHqCJADZNoKpXL6DEsN17II2AT@VjRctHV093vve43NarCbzcNwtZ3koCtd3CWVCnCshUhf7C5hP29azrnNxaXlCyXe1zyS/fQEvRWY6NhCUVeYmNaH29OUq2l6Rqf7y8GXB9pIVD1arhWwLo1ETECVhdxCRdHesBWleqVRAgmb7TKy0eb1/m20jbH5xoTjakFewaQNyJFrIsddFeegC0bRrg9KUE/dWoyG7BDS9fdlRg9VVGmsMtU0Y1AfSqG1zQbEYz6HlUzijnF4hdrnFB4PePHrv@29GidIahYylyTWVjFjUYFOqP/6iZ6o3QxyJwC@vaE@0vhW3swI2ZiLhbiSvg9WQxGhr7obHwB "Perl 6 – Try It Online") [Answer] # PHP, 62 bytes ``` <?=![,$s,$p]=$argv,preg_filter("(^(.*)$p(.*)$)U","$2$p$1",$s); ``` requires PHP 7.1; may fail if the pivot contains regex special chars (`\+*?[^]$(){}=!<>|:-`). no changes if Pivot is empty, empty output if Pivot is not in input. Run with `-n`. **safe version, 77 bytes:** ``` <?=preg_filter("(^(.*)".preg_quote($p=$argv[1])."(.*)$)U","$2$p$1",$argv[2]); ``` no changes if Pivot is empty, empty output if Pivot is not in input. Run with `-n`. **non-regex version, 71 bytes:** ``` $a=explode($p=$argv[2],$argv[1]);$a[]=array_shift($a);echo join($p,$a); ``` yields warnings if the Pivot is empty; no change if Pivot is not in input. Run with `-nr`. [Try them online](http://sandbox.onlinephpfunctions.com/code/794ba74a30e6afbdd585a0467e6afd555f316edf). [Answer] # [Red](http://www.red-lang.org), 63 bytes ``` f: func[p s][rejoin[copy find/tail s p p copy/part s find s p]] ``` [Try it online!](https://tio.run/##dU1BCoMwELz7imXvQaq2h36iULyFHKImmCIxrCvS16ebmwhlGWZnZtkhN@W3m0Cb7J/g9zjqBJvR5D5riHpc0xd8iFPNNiywQZIpZp0sseiSFduYnChEBg/YHysCvqKTpZ/JFRaF1eXiJtQIWkGHUP1/cA4hSKvd2BHwbKMYyLMDssMQ@BqWhHfi5dyuSrdqVKs6dVcPhPwD "Red – Try It Online") [Answer] # [Swift](https://swift.org), 131 bytes ``` import Foundation func f(s:String,d:String){var c=s.components(separatedBy:d);print((c+[c[0]]).suffix(from:1).joined(separator:d))} ``` ## Explanation (ungolfed) ``` import Foundation // Import String.components func f(s:String,d:String){ var c=s.components(separatedBy:d) // Split the input string by the separator print((c+[c[0]]) // Add the last element of c ([A,B,C] -> [A,B,C,A]) .suffix(from:1) // Remove the first element ([A,B,C,A] -> [B,C,A]) .joined(separator:d)) // Join with the separator } ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 76 bytes ``` f(s,t)char*s,*t;{char*p=strstr(s,t);printf("%s%s%.*s",p+strlen(t),t,p-s,s);} ``` [Try it online!](https://tio.run/##dYzBCsIwDIbP7ilKQWhnK2xOL8Nn8LIX6EpnB7OWJsPD2LPPbDcVSX4S8n9/rL5buyydAIXSepNyUDnW07bGK2Ci3sw6pj5gJ/geqI45cBUPZA4uCJQKVdSgQNbzQhh7mD4ImU3ZjhJF83qWpBOp4opxmlzWLI4IgtO2Ubfg6N745NxfBr1jybRtj6wH1hlAlxh6E9jq4Jhw2MLf7u@nQpf6pCt91pc1oD@JeXkD "C (gcc) – Try It Online") [Answer] **C++11, 64 bytes** ``` [s,p,&a]{int f=s.find(p);a=s.substr(f+p.size())+p+s.substr(0,f);} ``` A lambda, which captures the strings s, p and a, with a as a reference (in-out). Test code ``` #include <iostream> #include <string> std::string Test(std::string s, std::string p) { std::string a; [s,p,&a]{int f=s.find(p);a=s.substr(f+p.size())+p+s.substr(0,f);}(); return a; } int main() { std::string s = "OneTwoThreeTwoOne", p = "Two", r = "ThreeTwoOneTwoOne"; auto a = Test(s,p); std::cout << ((a==r)?"OK":"Failed") << ": " << a << std::endl; return 0; } ``` [Answer] # [Clean](https://clean.cs.ru.nl), 83 bytes ``` import StdEnv;f s c=(\p=p takeWhile++[hd s,c:p dropWhile])\g=reverse(tl(g((<>)c)s)) ``` A `String` in Clean is normally `{#Char}` - an unboxed (`#`) `Char` array (`{}`). This function takes `[Char]` instead of `String`, which is a second, valid version of `String`. The full function signature is `f :: [.t] .t -> [.t] | [.t <= Char]`. [Try it online!](https://tio.run/##Hcy7DsIgFADQX7npUkjtD6g46WDi1sHBOlzhQom8AtjEnxeN6xmOdISh@ahejsCjDc36FHOFqapTWHcaCkjB5iQSVHzSdbGOhuG2KCgbuU2gckx/vPPZiEwr5UKsOmYY2x@45IXzNlX8lQI0MJ2jn2q2wUCHD6lG0mbpOPRj3z5SOzSljedLO74DeivLFw "Clean – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~8~~ 7 bytes ``` £Zg°Y}V ``` [Try it here](https://ethproductions.github.io/japt/?v=1.4.5&code=o1pnsFl9Vg==&input=IjEtMi0zLTQtNS02IgoiLSI=) ]
[Question] [ # The Problem You must write a program that, when the Konami Code is typed in during runtime, prints the string "`+30 lives`" and sounds a noise of your choice from the computer's speaker. ### Definition The "Konami Code" is defined as `UUDDLRLRBA` followed by pressing the enter key. ### The Rules * You may choose to use the up arrow for `U`, down for `D`, left for `L`, and right for `R`, as long as your code is consistent with either arrows or letters. * Your input may be accepted from a controller or a keyboard, but does not need to support both. * Existing answers may continue to use `BABA` instead of `BA`, but may also shorten it if they wish to do so. Future answers should all use `BA` for consistency. * Empty input doesn't need to be supported. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 33 bytes (Fine on Empty Input) ``` Dg0Qiq}•ï“뙵yê!•36BQi7ç“+30™‹“J, ``` [Try it online!](http://05ab1e.tryitonline.net/#code=RGcwUWlxfeKAosOv4oCcw6vihKLCtXnDqiHigKIzNkJRaTfDp-KAnCszMOKEouKAueKAnEos&input=) # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~30~~ 26 bytes (Fails on Empty Input) -4 thanks to Adnan ``` •ï“뙵yê!•36BQi7ç,“+30™‹“, ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oCiw6_igJzDq-KEosK1ecOqIeKAojM2QlFpN8OnLOKAnCszMOKEouKAueKAnCw&input=VVVERExSTFJCQUJB) ``` •ï“뙵yê!•36B # UUDDLRLRBABA in base-214, converted back to base-36. Qi # If implicit input is equal to... 7ç, # Print 7 converted to a character to the console (bell sound)... “+30™‹“, # Print +30 lives. ``` Disclaimer: Bell sound does not play on TryItOnline, maybe ask Dennis if one of his servers somewhere is pinging when you run it. [Answer] ## JavaScript (ES6), ~~202~~ ~~200~~ 198 bytes Tested only on Chrome and Firefox. Uses `UDLR` rather than the arrow keys. Please make sure that CapsLock is off. ``` (o=(A=new AudioContext()).createOscillator()).connect(A.destination);s='';document.onkeyup=e=>{(s+=e.key[0]).slice(-11)=='uuddlrlrbaE'&&setTimeout('o.stop()',500,console.log('+30 lives'),o.start())} ``` ``` Please click inside this area to make sure it gets focus. ``` [Answer] # Python 3, ~~55~~ 53 bytes -1 byte thanks to isaacg (use bitwise not to replace `-10` with `~9`). -1 byte thanks to CalculatorFeline (it is possible to use a literal `BEL` byte). ``` while'UUDDLRLRBA'!=input()[~9:]:1 print('+30 lives7') ``` where the `7` shown above is a literal byte `0x07` (an unprintable in a code block). Once enter is pressed the `while` loop condition is checked. If the last `~9` = 10 characters (at most) do not match the Contra command code then the no-op `1` is executed (replacement of `pass` for brevity); if they *do* match then the while loop ends and the `print` statement is executed, which writes the required text along with an ASCII bell character ("alarm"), `0x07`, which produces a sound unless it has been explicitly disabled (or the terminal has no speaker!). [Answer] ## Jelly, ~~33~~ ~~30~~ ~~29~~ 27 bytes ``` ɠ⁻“UUDDLRLRBA”$¿ṛ7Ọ“¡}ʠƈ[ỵ» ``` Turns out, the append (`ṭ`) is not needed, strings are automatically ~~joined together~~ both printed. ``` ɠ⁻“UUDDLRLRBABA”$¿ṛ7Ọṭ“¡}ʠƈ[ỵ» ``` --- **Uncompressed** ``` ɠ⁻“UUDDLRLRBABA”$¿ṛ7Ọṭ“+30 lives” ``` [Try it online](http://jelly.tryitonline.net/#code=yaDigbvigJxVVURETFJMUkJBQkHigJ0kwr_huZs34buM4bmt4oCcKzMwIGxpdmVz4oCd&input=VVVERExSTFJCQUJjCmFzZGYKYnJ0ClVVRERMUkxSQkFCClVVRERMUkxSQkFCQQphc2RmCmtqaGc) If you remove everything after `¿`, you can mess with the input and see that it only returns when the input string is correct. ``` ɠ⁻“UUDDLRLRBABA”$¿ṛ7Ọṭ“+30 lives” - main link ɠ - takes a line of input ⁻“UUDDLRLRBABA”$ - $ groups it into a monadic !="UUDDLRLRLRBABA" ¿ - while (the inequality, which takes from the getline) ṛ - take the right argument (to ignore the input string) 7Ọ - chr(7), the bell character ṭ“+30 lives” - append that bell character to the output ``` Thanks @JonathanAllan for helping me figure out string compression :) [Answer] # Processing, ~~161~~ ~~157~~ 155 bytes ``` String k="";void keyTyped(){if(match(k+=key,"uuddlrlrba\\n$")!=null){print("+30 lives");new processing.sound.SoundFile(this,"a.mp3").play();}}void draw(){} ``` The audio file must be saved as `sketchName/data/a.mp3`. Note: I have only tested this program without the audio file because I am too lazy to download an `mp3` file (since only limited extensions are supported from `processing.sound.SoundFile`). The `draw()` function is needed to be there in order for `keyTyped` to work. The reason we are using `keyTyped` is because Processing does not have STDIN, it can only listen for keys being pressed via the sketch being run. ### Explanation ``` String k=""; void keyTyped(){ if(match(k+=key,"uuddlrlrba\\n$")!=null){ print("+30 lives"); new processing.sound.SoundFile(this,"a.mp3").play(); } } void draw(){ } ``` All of the user's keystrokes are stored as chars inside the String `k`. The `keyTyped` is an inbuilt function that is called whenever the user types a key. Simultaneously, we are checking if this String ends with the keystrokes. Then we print `+30 lives` and play the sound file. And the `draw` function is there to continuously update `keyTyped`. After the Konami code is entered, then nothing else will be outputted and no audio will be played. [Answer] ## ><>, ~~132~~ ~~69~~ ~~64~~ 62 bytes ~~[\*><>](https://esolangs.org/wiki/Starfish), 84 bytes~~ ``` i:1+?\0[ :1+?!\i BA"a~/"UUDDLRLR {v!?l/!?= 7/"+30 lives" o<;!?l ``` [Try it here!](https://starfish.000webhostapp.com/?script=JYLgjA1A-AOgDAbQFDmgQhsJAhAggIgEMA-AenwFUKARagGQCVGkBvANzSgBtTOBeJAHZyEAMxwABF2BsApgGd8SAPYAeANycuQA) This relys on the bell chime (ascii `7`) for the noise at the end (not heard on the online interpreter). Thanks to @TealPelican for saving another 15 bytes! Saved two bytes checking for `BA` instead of `BABA`. [Answer] # C 119 -1 - 2 = 116 bytes ### Golfed ``` i;f(){char a[14];a[13]=0;while(strcmp(a,"UUDDLRLRBA"))for(i=0;i<12;a[i]=a[i+++1]);a[i]=getch();puts("+30 Lives\a");} ``` ### Ungolfed ``` #include<stdlib.h> #include<conio.h> i; f() { char a[14]; a[13]=0; while(strcmp(a,"UUDDLRLRBA")) { for(i=0;i<12;a[i]=a[i+++1]); a[i]=getch(); puts(a); //This is to print every step in the runtime } puts("+30 Lives\a"); // '\a' is the acsii char that makes sound when passed to STDOUT } main() { f(); } ``` [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked/), 41 bytes ``` ['+30 lives'BEL+out]prompt'UUDDLRLRBA'=if ``` Reads input from keyboard. ``` ['+30 lives'BEL+out]prompt'UUDDLRLRBA'=if [ ]prompt'UUDDLRLRBA'=if if the input is the desired string, '+30 lives'BEL+out output '+30 lives' and the BEL character. ``` [Answer] ## AutoHotkey, 63 bytes ``` Input,K,L10 if(K="UUDDLRLRBA"){ MsgBox,"+30 lives" SoundBeep } ``` After running this script, it will check if the next 10 keys are the Konami code and if it is, it will show a message box saying "+30 lives" and it *should* play a beep (I don't have speakers now to test). [Answer] # GNU sed, ~~32~~ 25 + 1 = ~~33~~ 26 bytes +1 byte for `-n` flag. ``` /UUDDLRLRBA$/a+30 Lives\a ``` [Try it online!](https://tio.run/##K05N@f9fPzTUxcUnyCfIyVFFP1Hb2EDBJ7MstTgm8f//tPx8LrgsV1JiEUIpF5BbxfUvv6AkMz@v@L9uHgA) # Explanation Every time enter is pressed (`$`), the program checks if the preceding 10 keystrokes were the code. If they were, the `a` command queues the text `+30 Lives` and the bell sound (`\a`) to be printed at the end of the current cycle (which, in this case, is immediately). [Answer] ## Mathematica, 50 bytes ``` While[x=!=UUDDLRLRBA,x=Input[]];Beep[];"+30 lives" ``` Initially, `x` is just a symbol and is thus not identical ([`=!=`](http://reference.wolfram.com/language/ref/UnsameQ.html)) to the symbol `UUDDLRLRBA`, so `x=Input[]` is evaluated. This will open a dialog box with the cursor already in the input field, so the user can immediately start typing on the keyboard. If `Enter` is pressed or `OK` is clicked without typing anything, then `InputField[]` will return `Null`, which is not identical to `UUDDLRLRBA`, so the loop continues and another dialog box will be opened. If the user clicks `Cancel` or otherwise exits the dialog box, then `InputField` will return `$Canceled`, which is also not identical to `UUDDLRLRBA`, so the loop will continue. The user can type in the dialog box to their heart's desire. When they hit `Enter`, their input is interpreted as a Wolfram language expression (possibly just boxes). If that expression is anything other than the symbol `UUDDLRLRBA`, the loop will continue. "Must loop until the Konami code is entered" is a little vague, but I believe this satisfies it. Once the `While` loop is completed, [`Beep[]`](http://reference.wolfram.com/language/ref/Beep.html)`;"+30 lives"`. [Answer] # Petit Computer BASIC, 91 bytes ``` @L WAIT 1S$=S$+CHR$(B)*!!B B=BTRIG()IF B<1024GOTO@L IF"xxxxxxxxxx"==S$THEN BEEP?"+30 lives ``` Finally a solution that actually uses controller input! I used Petit Computer rather than the newer version (SmileBASIC) because it has access to the Start button, and `BTRIG()` is shorter than `BUTTON()`. I've replaced the data string with `x`'s, it should contain characters with ascii codes 1,1,2,2,4,8,4,8,32,16 ### Boring version, 46 bytes ``` INPUT S$IF"UUDDLRLRBA"==S$THEN BEEP?"+30 lives ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 21 bytes ``` «_sa}]∷«⇧=`+30 æ§\7`* ``` Based on [@Makonede's 05AB1E answer](https://codegolf.stackexchange.com/a/225302/80050). [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%AB_sa%7D%5D%E2%88%B7%C2%AB%E2%87%A7%3D%60%2B30%20%C3%A6%C2%A7%5C7%60*&inputs=UUDDLRLRBA&header=&footer=) Explained: ``` «_sa}]∷«⇧=`+30 æ§\7`* * # Repeat... `+30 æ§\7` # the string '+30 lives␇'... (escape code \7 is BEL) # once if ... = # the (implicit) input equals... «_sa}]∷« # the compressed code... ⇧ # in uppercase... # otherwise repeat zero times ``` [Answer] ## Powershell, ~~89~~ 86 Bytes ``` if((Read-Host)-eq"UUDDLRLRBABA"){"+30 Lives";[System.Media.SystemSounds]::Beep.Play()} ``` enter submits the string to the `Read-Host`, so it should.. work? [Answer] # C# (the boring version), 80 bytes ``` void n(){while(Console.ReadLine()!="UUDDLRLRBA"){}Console.Write("+30 Lives\a");} ``` # C# (The interesting one), 202 bytes ``` void n(){t();Console.Write("+30 Lives\a");}void t(){var k="UUDDLRLRBA";var s="";while(s!=k){s+=Console.ReadKey().Key.ToString();s=k.StartsWith(s)?s:"";}if(Console.ReadKey().Key!=ConsoleKey.Enter){t();}} ``` I **think** this works, sadly online testers do not support the existence of a console input, as such I will have to go on the tests I have done Can most likely be golfed hugely - I'm not great at this! :) Ungolfed: ``` void n() { t(); Console.WriteLine("+30 Lives\a"); } void t() { var k = "UUDDLRLRBA"; var s = ""; while(s != k) { s += Console.ReadKey().Key.ToString(); s = k.StartsWith(s) ? s : ""; } if(Console.ReadKey().Key != ConsoleKey.Enter) { t(); } } ``` [Answer] # [Wonder](https://github.com/wonderlang/wonder), 50 bytes ``` ol"•";f\@[="UUDDLRLRBA"rl0?ol"+30 lives•"?f0];f0 ``` Replace `•` with the character of code `\x07` (the BEL control char). Takes input through STDIN. [Answer] ## flex, 37 + 5 = 42 bytes ``` %% UUDDLRLRBA puts("+30 lives\a"); ``` The code itself is 37 bytes, compile it with the "-main" option which adds 5 bytes. Naturally, you have to compile the resulting C file with your favorite C compiler, but I don't think that step should count toward the byte count. I could save a byte by using a literal BEL character instead of `\a`, but I'd rather be able to read my own code. [Answer] # C, ~~87~~ ~~85~~ 81 bytes ``` s[13];f(){for(;strcmp(s,"UUDDLRLRBA\n");fgets(s,12,stdin));puts("+30 Lives!\a");} ``` [Answer] # shortC, 52 bytes ``` s[13];AO;Ms,"UUDDLRLRBA\n");Ys,12,N));J"+30 Lives!\a ``` Explanation: ``` s[13]; // declare array with 13 members A // main function O;Ms,"UUDDLRLRBA\n"); // for loop while input is not equal to the Konami Code Ys,12,N)); // read 12 characters of input into array J"+30 Lives!\a // print the string ``` [Try it online!](https://tio.run/##K87ILypJ/v@/ONrQONba0d/at1hHKTTUxcUnyCfIyTEmT0nTOrJYx9BIx09T09pLSdvYQMEnsyy1WDEm8f9/AA) [Answer] # C, 114 bytes ``` #define X "UUDDLRLRBA" main(i,j){for(i=j=0;!j;)(getchar()==X[i++])&&((j=1?!X[i]|puts("+30 lives\a"):0)|1)||(i=0);} ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 21 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` é>Δ┼3Σöîc9qz╔°→cz╣╖↑└ ``` [Run and debug it](https://staxlang.xyz/#p=823effc533e4948c6339717ac9f81a637ab9b718c0&i=UUDDLRLRBA%0A) ## Explanation ``` `!j.o6F>"`=D"+30 lives"7+ `!j.o6F>"`= input equals sequence? D if so, "+30 lives" push +30 lives 7+ add a bell to it ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes ``` .•›Gβ…Ýò•uQ7ç“+30™‹ÿ“× ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f71HDokcNu9zPbXrUsOzw3MNAalFpoPnh5Y8a5mgbGzxqAcruPLwfyDs8/f//0FAXF58gnyAnRwA "05AB1E – Try It Online") ``` .•...•uQ7ç“...“× # trimmed program “...“ # push "+30 livesÿ"... # (implicit) with ÿ replaced by... ç # unicode character with codepoint... 7 # literal... × # repeated... Q # is... # implicit input... Q # equal to... .•...• # "uuddlrlrba"... u # in uppercase... × # times # implicit output ``` ]
[Question] [ # The Symbols vs. The Letters The [ASCII characters](http://www.asciitable.com/) have been divided once [again](https://codegolf.stackexchange.com/questions/35310/write-the-whole-of-the-holed-using-the-unholed)! Your sets are **The Letters** and **The Symbols**. ## The Letters ``` ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ``` ## The Symbols ``` !"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~ ``` The task is to write two programs: 1. Print each of **The Letters** exactly once without using any of them in your program. 2. Print each of **The Symbols** exactly once without using any of them in your program. # Rules * Whitespace may appear in your program or the output. * Non-ASCII characters are not allowed. * Output goes to standard out or to a file as either the contents or name of the file. * No input. * Output must only contain ASCII characters from one set or the other. * The programs can be written in different languages or the same language with one exception: * The [Whitespace language](http://en.wikipedia.org/wiki/Whitespace_(programming_language)) may only be used for one of the programs. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply. # Scoring `# of characters in program 1` **+**`# of characters in program 2` = `Score` Lowest score wins! ## Note: To encourage more submissions, you may still post an answer with a solution for only one of the programs. You won't be able to win, but you would still be able to show off something cool. Thanks to [Calvin's Hobbies](https://codegolf.stackexchange.com/users/26997/calvins-hobbies) for inspiring the idea with his [previous question](https://codegolf.stackexchange.com/questions/35310/write-the-whole-of-the-holed-using-the-unholed). [Answer] # Python (Symbols, ~~87~~ 82) ``` from string import punctuation from string import digits print digits print punctuation ``` I just love Python's string module... Edit: ``` from string import punctuation as p from string import digits as d print d print p ``` Output: ``` 0123456789 !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ ``` # ~~[FALSE](http://esolangs.org/wiki/False) (Letters, 21)~~ [DUP](http://www.quirkster.com/iano/js/dup.html) (Letters, 20): FALSE solution: ``` 65[$91\>][$,$32+,1+]# ``` DUP sollution (1 char shorter) ``` 65[$91<][$,$32+,1+]# ``` Output (for both): ``` AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz ``` [Interpreter for FALSE.](http://www.quirkster.com/iano/js/false-js.html) --- ## Total: 102 [Answer] ## GolfScript (14 chars) + [Deadfish x](http://esolangs.org/wiki/Deadfish_x) (116 chars) = 130 chars ``` 91,65>{.32+}%+ ``` and ``` xxcxxcdddKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKxKDxxxccxxxxxxxxxxKxKxKxKxKxKDxxxcxxcxxKxKxKxK ``` [Answer] # Parts 1 and 2 in Ruby 2, 56 + 484 = 540 Part 1: ``` __=->_{(91..96)===_||$><<(''<<_);_>121||__[-~_]} __[65] ``` For more on this style of Ruby, check out [narfnme](https://github.com/threeifbywhiskey/narfnme). Part 2 (this bit is Ruby 2.0+ only, works perfectly with ruby-2.1.0 but may give warnings in earlier versions): ``` class Fixnum def c String def a end end def b String def A end end def x String def z end end def y String def Z end end def inspect case chr when c when b when y p succ else print chr p succ end p rescue p end end def x String def z end end def y String def Z end end class String def inspect p size p end end p String p class String def inspect p ord p end end p y class Fixnum def inspect case chr when x p succ else send chr print chr p end p rescue print chr p succ p end end p x ``` That one was hard. Calling built-in Fixnum methods like `chr` and `succ` requires opening up the Fixnum class and redefining `inspect`, since I can trigger a call to `x.inspect` with `p x`. I need inspect to return `nil` so that `p` will only print a newline, any string will be framed in double quotes. But as a side effect, it loops. I can terminate the first loop and second loops using a string comparison to see when I've reached a letter range, but since I can't write a string literal I need to get one by calling `String()` on the symbol returned (in Ruby 2) by the `def` keyword. Since that's a multiline syntax and I can only do string comparison via `case`, which can't take multiline expressions, I need to wrap the literal in a method (since I obviously can't do assignment). The last loop is harder to terminate. I need it to stop at `~`. Luckily, of the ascii characters in that range, `~` is the only one that can be called on a Fixnum with no arguments without raising an error, so I can use `send chr` to detect when I'm at the end and stop looping. Not the best score in this thread, but thus far the only one that uses the same language for both parts. Yay Ruby. [Answer] # Part 2 in Applescript, 654 *wait... where's the "**tips for golfing in Applescript**" page?* ``` global a global b global c global s on f at n set end of b to a end on g at n f at a f at a end on h at n g at a g at a end on i at n h at a h at a end on j at n repeat with t in system info f at a end end on m at n set end of b to a set c to count of b set end of s to ASCII character c end on n at n m at a m at a m at a end on o at n repeat with t in system info m at a end end set a to random number set b to a as list j at a j at a set c to count of b set s to ASCII character c set s to s as list o at a n at a n at a n at a n at a n at a j at a i at a g at a f at a n at a m at a m at a j at a i at a g at a n at a m at a display dialog s as text ``` ### Output: ![enter image description here](https://i.stack.imgur.com/08jpG.png) [Answer] # Total: 53 characters # Total in a single language: 230 characters, Pyth # Part 1: Golfscript, 15 ``` 91,65>123,97>++ ``` Outputs: ``` ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ``` Explanation: ``` 91, Make the list, [0 1 .. 90] 65> Take elements after the 65th, [65 66 .. 90] 123,97> Same, but [97 98 .. 122] + Add the list above to the newline character that is automatically pushed to the stack. List + str coerces to string by ascii encoding. + Same, for the other list. ``` # Part 2: [Pyth](https://github.com/isaacg1/pyth), 38 ``` JhCeGLjkmCdbsrCdCPhGsrhCPeGChGsrJhhhhJ ``` Outputs: ``` !"#$%&'()*+,-./0123456789:;<=>?@ [\]^_` {|}~ ``` Explanation: ``` G = "abcdefghijklmnopqrstuvwxyz" Implicit. k = "" Implicit. d = " " Implicit. JhCeG J = 1 + chr(end(G)) # J = 123 L def d(b): return jk k.join( m map(lambda d: Cd chr(d), b b)) s print(s( #print is implicit. rCd range(chr(d), # chr(d) = 32 CPhG chr(upper(head(G)))) # chr("A") = 65 srhCPeGChG print(s(range(1+chr(upper(end(G))),chr(head(G))) srJhhhhJ print(s(range(J, 1+1+1+1+J))) ``` --- # Bonus solution: # Part 1: Pyth, 192 ``` %*$"%\143"$52(65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 ``` Explanation: `$"%\143"$` => "%c". `$` switches to and from Python parsing style, and in Python string parsing, `\143` is the octal escape sequence for `c`. This answer is thus equivalent to the following Python-style code: ``` ("%c" * 52) % (65, 66, 67, ...) ``` Of course, this doesn't work in Python, because printing in Python uses `print`, but printing in Pyth is implicit, so it works. --- Pyth solutions do not use any of the features added since the question was asked. [Answer] # [CJam](https://sourceforge.net/p/cjam) + [AlphaBeta](https://github.com/TryItOnline/alphabeta), 62 bytes --- ## Letters, [CJam](https://sourceforge.net/p/cjam), 12 bytes ``` "[{"{,-26>}/ ``` [Try it online!](https://tio.run/##S85KzP3/Xym6WqlaR9fIzK5W//9/AA "CJam – Try It Online") ### Output ``` ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ``` ### How it works ``` "[{"{ }/ For each of the characters "[" and "{", , push an array of all ASCII characters before it -26> and discard all but the last 26 characters. ``` --- ## Symbols, [AlphaBeta](https://github.com/TryItOnline/alphabeta), 50 bytes ``` ZaaAccctFUaCLOrEbbCLbCLbCLbCLdddACLbCLbCLgDLgDLgDL ``` [Try it online!](https://tio.run/##S8wpyEhMSi1J/P8/KjHRMTk5ucQtNNHZx7/INSnJ2QeOUlJSHGHsdBco@v8fAA "AlphaBeta – Try It Online") The official C++ interpreter has a bug that makes loops impossible and I can't figure out how to use the Lua interpreter. [I fixed that bug.](http://pastebin.com/zEJkABZV "ab.cpp - Pastebin.com") You can verify that it works as intended by running the example programs from the EsoLang page. ### Output ``` !"#$%&'()*+,-./0123456789:;<=>?@~}|{]\[^_` ``` ### How it works ``` Z Switch register 4 to the position register. aa Set registers 1 to 2. A Copy the value from register 1 to register 2. ccc Add 30 to register 1 (result: 31). tF Set register 2 to the product of registers 1 and 2 (result: 64). U Add 10 to the position register (result: 10, i.e., the position of the next byte). aCL Add 1 to register 1 and print the corresponding ASCII character. O If register 1 != register 2, go to the position in the position register. rEb Set register 1 to the sum of registers 1 and 2 minus 1 (result: 127). bCL Subtract 1 from register 1 and print the corresponding ASCII character. bCL Subtract 1 from register 1 and print the corresponding ASCII character. bCL Subtract 1 from register 1 and print the corresponding ASCII character. bCL Subtract 1 from register 1 and print the corresponding ASCII character. ddd Subtract 30 from register 1 (result: 93). A Copy the value from register 1 to register 2. CL Print the ASCII character corresponding to register 1. bCL Subtract 1 from register 1 and print the corresponding ASCII character. bCL Subtract 1 from register 1 and print the corresponding ASCII character. gDL Add 1 to register 2 and print the corresponding ASCII character. gDL Add 1 to register 2 and print the corresponding ASCII character. gDL Add 1 to register 2 and print the corresponding ASCII character. ``` [Answer] # Part 1 in BrainFuck: ~~80~~ 74 bytes ``` >-[+>+<[+<]>]>+.<<+++++[>+++++[>+.<-]<-]>>+++++++.<<+++++[>+++++[>+.<-]<-] ``` [Answer] # Total 318 bytes I was really hoping to figure out an answer with both programs in the same language, but so far nothing. Here's this instead: # Part 1: Pure bash, 129 bytes ``` _0=`$ 2>&1` _0=${_0##*:} _1=${_0:5:1} _5=${_0:1:1}$_1${_0:11:1} . <($_5<<<_2=\({${_1^}..$_1}\)) _3=${_2[@]:0:26} $_5<<<$_3${_3,,} ``` ### Output: ``` $ ./letsym.sh A B C D E F G H I J K L M N O P Q R S T U V W X Y Za b c d e f g h i j k l m n o p q r s t u v w x y z $ ``` # Part 2: GNU dc, 189 bytes ``` zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzPzzzzzzzzzzzzzzzzzzzzzzzzzzzzPzzPzzPzzPzzPzzPzzBDPBEdPBFPdkvZP ``` ### Output: ``` $ dc symlet.dc !"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~$ ``` [Answer] Well, you know, someone should get it going. ## Part 1 in BrainFuck: 174 bytes ``` +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+++++++ .+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+. ``` [Answer] ## Part 1: Ruby, 45 bytes ``` _=[*?@...?[,*?`...?{] _[0],_[27]=*$_ $><<_*'' ``` ### Explanation * A Range containing a-z (`?@...?[`) and a Range containing A-Z (`?`...?{`) become the elements of the array `_` using the splat operator (`*`). * The 0th element (`"@"`) and 27th element (`"`"`) of the array `_` are set to `nil`. * The array `_` is joined together using `Array#*` and printed to stdout (`$>`) ]
[Question] [ The [Polygamma](https://en.wikipedia.org/wiki/Polygamma_function) function of order \$m\$, \$\psi^{(m)}(z)\$, is the \$(m + 1)\$th derivative of the logarithm of the [gamma](https://en.wikipedia.org/wiki/Gamma_function) function, which is also the \$m\$th derivative of the [digamma](https://en.wikipedia.org/wiki/Digamma_function) function. Your task is to take an integer \$m\$ and a positive real number \$z\$ and output \$\psi^{(m)}(z)\$ ## Definitions For those unfamiliar with the functions above (Gamma, Digamma and Polygamma), here are a few different definitions for each: ### \$\Gamma(z)\$ * The gamma function is an extension of the factorial (\$x! = 1\cdot2\cdot3\cdots(x-1)\cdot(x)\$) to real numbers * \$\Gamma(z) = \int\_{0}^{\infty}x^{z-1}e^{-x}dx\$ * \$\Gamma(n) = (n - 1)! \:,\:\: n \in \mathbb{N}\$ * \$\Gamma(n+1) = n\Gamma(n) \:,\:\: n \in \mathbb{N}\$ ### \$\psi(z)\$ * The digamma function is the logarithmic derivative of the gamma function * \$\psi(z) = \frac{d}{dz}\ln(\Gamma(z))\$ * \$\psi(z) = \frac{\Gamma'(z)}{\Gamma(z)}\$ * \$\psi(z + 1) = \psi(z) + \frac{1}{z}\$ ### \$\psi^{(m)}(z)\$ * The polygamma function of order \$m\$ is the \$m\$th derivative of the digamma function * \$\psi^{(m)}(z) = \frac{d^m}{dz^m}\psi(z)\$ * \$\psi^{(m)}(z) = \frac{d^{m+1}}{dz^{m+1}}\ln(\Gamma(z))\$ * \$\psi^{(m)}(z+1)= \psi^{(m)}(z) + (-1)^m\frac{m!}{z^{m+1}}\$ ## Task You are to take two inputs, a natural number \$m\$ and a positive real number \$z\$, and output \$\psi^{(m)}(z)\$. The inputs and outputs will always fit within the number bounds of your language, but [your algorithm must work *theoretically* for any and all inputs](https://codegolf.meta.stackexchange.com/q/18196/66833). As the output is usually going to be a real number, rather than an integer, the output should be correct to at least 10 significant figures. Trailing zeros may be omitted for exact values. For example, if the output is an integer, trailing decimal `0`s are not required, but are allowed if you want. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. ## Test cases Results may differ due to floating point inaccuracies, Python's [scipy](https://www.scipy.org/) library was used to generate the values. Values are rounded to 15d.p., unless otherwise stated. ``` m, z -> ψ⁽ᵐ⁾(z) 17, 2 -> 1357763223.715975761413574 5, 40 -> 0.0000002493894351 9, 53.59375 -> 0.00000000001201026493 35, 9 -> 469354.958166260155849 46, 5 -> -7745723758939047727202304.000000000000000 7, 1.2222222222222222 -> 1021.084176496877490 28, 6.25 -> -2567975.924144014250487 2, 7.85 -> -0.018426049840992 ``` This table has the values of \$\psi^{(m)}(z)\$ for \$0 \le m \le 9\$ and \$1 \le z \le 20\$: ``` +---+------------------------+---------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+ | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | +---+------------------------+---------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+ | 0 | -0.577215664901533 | 0.422784335098467 | 0.922784335098467 | 1.256117668431800 | 1.506117668431800 | 1.706117668431800 | 1.872784335098467 | 2.015641477955610 | 2.140641477955610 | 2.251752589066721 | 2.351752589066721 | 2.442661679975812 | 2.525995013309145 | 2.602918090232222 | 2.674346661660794 | 2.741013328327460 | 2.803513328327460 | 2.862336857739225 | 2.917892413294781 | 2.970523992242149 | | 1 | 1.644934066848227 | 0.644934066848227 | 0.394934066848226 | 0.283822955737115 | 0.221322955737115 | 0.181322955737115 | 0.153545177959338 | 0.133137014694031 | 0.117512014694031 | 0.105166335681686 | 0.095166335681686 | 0.086901872871768 | 0.079957428427324 | 0.074040268664010 | 0.068938227847684 | 0.064493783403239 | 0.060587533403239 | 0.057127325790783 | 0.054040906037696 | 0.051270822935203 | | 2 | -2.404113806319188 | -0.404113806319189 | -0.154113806319189 | -0.080039732245115 | -0.048789732245114 | -0.032789732245115 | -0.023530472985855 | -0.017699569195768 | -0.013793319195768 | -0.011049834970802 | -0.009049834970802 | -0.007547205368999 | -0.006389797961592 | -0.005479465690312 | -0.004750602716552 | -0.004158010123959 | -0.003669728873959 | -0.003262645625435 | -0.002919710097314 | -0.002628122402315 | | 3 | 6.493939402266829 | 0.493939402266829 | 0.118939402266829 | 0.044865328192755 | 0.021427828192755 | 0.011827828192755 | 0.007198198563125 | 0.004699239795945 | 0.003234396045945 | 0.002319901304290 | 0.001719901304290 | 0.001310093231071 | 0.001020741379219 | 0.000810664701232 | 0.000654479778283 | 0.000535961259764 | 0.000444408525389 | 0.000372570305061 | 0.000315414383708 | 0.000269374221340 | | 4 | -24.886266123440890 | -0.886266123440879 | -0.136266123440878 | -0.037500691342113 | -0.014063191342113 | -0.006383191342113 | -0.003296771589026 | -0.001868795150638 | -0.001136373275638 | -0.000729931168235 | -0.000489931168235 | -0.000340910050701 | -0.000244459433417 | -0.000179820455575 | -0.000135196191875 | -0.000103591253604 | -0.000080703070010 | -0.000063799959344 | -0.000051098643488 | -0.000041405977726 | | 5 | 122.081167438133861 | 2.081167438133896 | 0.206167438133897 | 0.041558384635954 | 0.012261509635954 | 0.004581509635954 | 0.002009493175049 | 0.000989510004771 | 0.000531746332896 | 0.000305945162117 | 0.000185945162117 | 0.000118208290511 | 0.000078020533309 | 0.000053159387985 | 0.000037222150950 | 0.000026687171526 | 0.000019534614153 | 0.000014563111016 | 0.000011034967722 | 0.000008484266206 | | 6 | -726.011479714984489 | -6.011479714984437 | -0.386479714984435 | -0.057261607988551 | -0.013316295488551 | -0.004100295488551 | -0.001528279027645 | -0.000654007738836 | -0.000310684984930 | -0.000160150871077 | -0.000088150871077 | -0.000051203486564 | -0.000031109607963 | -0.000019635233198 | -0.000012804988755 | -0.000008590996985 | -0.000005908787970 | -0.000004154139804 | -0.000002978092040 | -0.000002172607350 | | 7 | 5060.549875237640663 | 20.549875237639476 | 0.862375237639470 | 0.094199654649073 | 0.017295357774073 | 0.004392957774073 | 0.001392271903016 | 0.000518000614207 | 0.000217593204539 | 0.000100511115987 | 0.000050111115987 | 0.000026599144024 | 0.000014877714841 | 0.000008699205352 | 0.000005284083130 | 0.000003317553637 | 0.000002144087193 | 0.000001421585007 | 0.000000964233099 | 0.000000667475582 | | 8 | -40400.978398747647589 | -80.978398747634884 | -2.228398747634885 | -0.179930526327158 | -0.026121932577158 | -0.005478092577158 | -0.001477178082416 | -0.000478010895205 | -0.000177603485537 | -0.000073530517936 | -0.000033210517936 | -0.000016110901963 | -0.000008296615840 | -0.000004494456155 | -0.000002542957742 | -0.000001494142013 | -0.000000907408791 | -0.000000567407762 | -0.000000364140247 | -0.000000239189714 | | 9 | 363240.911422382690944 | 360.911422382626938 | 6.536422382626807 | 0.391017718703625 | 0.044948382766125 | 0.007789470766125 | 0.001788099024012 | 0.000503455497598 | 0.000165497161722 | 0.000061424194120 | 0.000025136194120 | 0.000011145599233 | 0.000005284884641 | 0.000002652620244 | 0.000001398085550 | 0.000000768796112 | 0.000000438758675 | 0.000000258758130 | 0.000000157124373 | 0.000000097937278 | +---+------------------------+---------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+ ``` [Answer] # JavaScript (ES7), ~~68 66 61~~ 59 bytes Expects `(m)(z)`. ``` (m,n=m)=>g=z=>n?-n--*g(z):eval("for(k=5e6;k--;)n-=z++**~m") ``` [Try it online!](https://tio.run/##bZHBbgIxDETv/YoVpyw0IXbsOC5a@i2ILqgFdiuoOHDor28DBQnSztHSPI/HH4vj4rDcv39@2a5/a4dVM5jdc9fs6ma@bk7NvHu1nbXjtTnVL@1xsTWjVb83m4bbONtYO6s725wmk/H4ezeqh2XfHfpt67b92qwMSG2qUljX1XRaQWCRGBCDE2AVlgh0HtLTI6TivxDyvxDv/EVIGpJSYCjNem/m4FiD8KP5LEAPHmPGFIDwz/YMvQAoamByyglixOiBOZEWAIr/AK4JrAixYE6UNKgnERT0GDzdRbuoPCsXCw4LXYv1CM4nAsnnxJRXaGnHVGaKDm@ZkKPkdzhFAiIPhOwpSZkAS4S4dEPkZiFRboQ0kVfF4Qc "JavaScript (Node.js) – Try It Online") This is based on the following series representation ([from Wikipedia](https://en.wikipedia.org/wiki/Polygamma_function#Series_representation)): $$\psi^{(m)}(z)=(-1)^{m+1}m!\sum\_{k=0}^{\infty}\dfrac{1}{(z+k)^{m+1}}$$ ### Commented ``` (m, n = m) => // outer function taking m and saving a copy in n g = z => // inner recursive function taking z n ? // if n is not equal to 0: -n-- // yield -n to invert the sign; decrement n afterwards * g(z) // multiply by the result of a recursive call : // else: eval( // evaluate as JS code: "for(k = 5e6; k--;)" + // repeat 5 million times: "n -= z++ ** ~m" // subtract z ** -(m+1) from n; increment z ) // end of eval(), which returns the final value of n ``` [Answer] # Mathematica, 9 bytes ``` PolyGamma ``` Of course Mathematica has a [builtin](https://reference.wolfram.com/language/ref/PolyGamma.html) for this [Answer] # Mathematica, 32 bytes (30 characters) Without any `Gamma` related builtin, uses [Bubbler's](https://codegolf.stackexchange.com/a/210462/90265) formula ``` Sum[#!/(-#2-x)^(#+1),{x,0,∞}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7g0N1pZUV9DV9lIt0IzTkNZ21BTp7pCx0DnUce82li1/wFFmXklCg5p0YbmOgpGsVxQfkB@TqV7Ym5uIlT8PwA "Wolfram Language (Mathematica) – Try It Online") # Mathematica, 29 bytes Without `PolyGamma[z]` or `PolyGamma[n, z]` ``` Log@Gamma@x~D~{x,#+1}/.x->#2& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yc/3cE9MTc30aGizqWuukJHWduwVl@vQtdO2Ujtf0BRZl6JQ1q0obmOglEsFxeEH5CfUwnWAxX/DwA "Wolfram Language (Mathematica) – Try It Online") # Mathematica, 27 bytes With `PolyGamma[z]` (this is the equivalent of the digamma function, or \$\large\psi^0(z)\$) ``` PolyGamma@x~D~{x,#}/.x->#2& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyA/p9I9MTc30aGizqWuukJHuVZfr0LXTtlI7X9AUWZeiUNatKG5joJRLBcXhA/XARX/DwA "Wolfram Language (Mathematica) – Try It Online") A few Mathematica programs that don't use the builtin `PolyGamma[n, z]`. [Answer] # [R](https://www.r-project.org/), 8 bytes ``` psigamma ``` [Try it online!](https://tio.run/##XYtLCoAwEEP3nqSFUHTqWLvwMCIoglXxs7CXryKI1ezeS7KEeRqOrnaurtp9bLZ@GoWDl/Pa31Z4OBkeetciMyCZvMzI05gtWCu22nBsNcPGnBf49AaZol/inkoUij4XglHlZcIJ "R – Try It Online") Takes inputs `z,m` (test harness stolen from [Dominic's answer](https://codegolf.stackexchange.com/a/210432/67312)). R has a builtin as part of its [Special Functions of Mathematics](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Special.html) including various forms of the gamma function. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ₄nÝ+I±mOI!IÉ·<P ``` -1 byte thanks to *@ovs*. First input is \$z\$, second input is \$m\$. [Try it online](https://tio.run/##yy9OTMpM/f//UVNL3uG52p6HNub6eyp6Hu48tN0m4P9/EwMuUwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmaCUa3t4v0JiXopCFYjxqG2SgpJ9ZULo/0dNLXmH52pHHNqY6x@hGHG489B2m4D/Ov@jo410DM1jdaJNDHRMgZSpsZ6ppbG5qY4lkGOpYwwW0zExA1KGekZoQAek0UzPyFTHyALIMtezALJiYwE). **Explanation:** Uses the same algorithm as in [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/210426/52210), so make sure to upvote him. Or to be more precise, it uses the algorithm: $$\psi^{(m)}(z)=(m\text{%}2\times2-1)\times m!\times\sum\_{k=0}^{1000^2}{(z+k)^{\sim m}}$$ ``` ₄ # Push 1000 n # Square it to 1000000 Ý # Pop and push a list in the range [0,1000000] + # Add the first (implicit) input-integer `z` to each value I # Push the second input `m` ± # Take it's bitwise-NOT: -m-1 m # Take each value to the power this `-m-1` O # Sum all values in the list together I! # Push the second input `m` again, and take its factorial IÉ # Push the second input `m` again, and check if it's odd # (1 if truthy; 0 if falsey) · # Double that < # And decrease it by 1 P # And finally take the product of all three values on the stack # (after which it is output implicitly as result) ``` NOTE: If there are any very minor inaccuracies in the decimals, the `₄n` (\$1\text{,}000\text{,}000\$) could be replaced with `žm` (\$9\text{,}876\text{,}543\text{,}210\$), although it would be too slow to run on TIO in that case. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/) 18.0, 20 bytes ``` +/!⍤⊣÷(-(⍳!9)+⊢)*1+⊣ ``` [Try it online!](https://tio.run/##bVExa1RBEO73V@x175m8dWd2Znen0MbGVAZjLQTunkhyiaCCXheEIAcXYiFWNsbeQkKqWHg/wN/g/pFz9oFwXO4rdofh@@bb@fbw1XE3fn94fPqim7x7MzkZT8arcvF570k5v/RGq/19rYBNWXy105FdfrGv306bowfg3MuTftc23aw7ap833bSDtl3t3B@Vxfcyv1reNF1TFj9H0u6U@bf2Huh1tep1WllclPmH3z9COf@kDgdPH@n57PHewQqS7S0a1pO8Eb04OJaQ2ITaFEOxNk3lASxvxGDWMjpkg1okl9mY9rTvjbHTXXsHM9s9tH8@lrPbv9eX5exXM2sNpC1ErEQInFIMiMElYEmcIlBtkrF8V0S@irzzA5AkZKHAYKysk//vtE6uAPTgMapMt93yJKkCihKYnHCGGDF6YM5Uc9kiGBy6lIgTql@WIJ5SwoQeg6c16wHGahDgcANDEB7B@UyQ9Hkx60jxGv2mZ/2HwRM5Jo3LCRIQeSBkTzkZi5uS@mODRJOATLoRSSYvgv8A "APL (Dyalog Extended) – Try It Online") -2 bytes thanks to Adám and ngn. --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), 22 [bytes](https://github.com/abrudz/SBCS) ``` {+/(!⍺)÷(-⍵+⍳1e6)*1+⍺} ``` [Try it online!](https://tio.run/##bVHBSl0xEN3nK@Lu3uqNmclMklnUjZu6qtSuC0J7S9FXC8WFT7oQQaRwxS5KV/2GLkQEoV30fYDfYH7kdXKh8Hi@s0gOw5w5mZP9T4fd25P9w6P383L1fedlubj2RtnurjJgU4afdrJmZz/s5@NJc/AcnPvwsd@wTTftDto3TTfpoG3np@ubzVoZ7tvZXdOV4Xa9DDfwLrbPQNn9l3mv08pwVb6e//0VysU3ddh7ta3n6xc7e3NItrdoWE/yRvTi4FhCYhNqUQzFWjS1D2B2Jwaz0uiQDSpJLrMx7VHfG2MnG/YJprbbsg@X5ez34@11OfvTTFsDaUUj1kYInFIMiMElYEmcIlAtkrH8VES@irzzI5AkZKHAYKwsNv/fabG5AtCDx6gy3XbFk6QKKEpgcsIZYsTogTlTzWWFYHToUiJOqH5ZgnhKCRN6DJ4WrEcYq0GAwyWMQXgE5zNB0ufFrCPFa/TLnvUfRk/kmDQuJ0hA5IGQPeVkLC5L6o@NEk0CMulGJJm8CP4D "APL (Dyalog Unicode) – Try It Online") Left argument is \$m\$, right arg is \$z\$. Uses a slight modification of the formula used by other answers: $$ \begin{aligned} \psi^{(m)}(z)&=(-1)^{m+1}m!\sum\_{k=0}^{\infty}\dfrac{1}{(z+k)^{m+1}} \\ &\approx\sum\_{k=0}^{10^6-1}\dfrac{m!}{(-z-k)^{m+1}} \end{aligned} $$ ### How it works ``` {+/(!⍺)÷(-⍵+⍳1e6)*1+⍺} ⍝ ⍺←m, ⍵←z -⍵+⍳1e6 ⍝ vector of -(z+0..999999) ( )*1+⍺ ⍝ raise each to the power of 1+m +/(!⍺)÷ ⍝ divide m! by each of above and sum them ``` [Answer] # [Octave](https://www.gnu.org/software/octave/) / MATLAB, 4 bytes ``` @psi ``` [Try it online!](https://tio.run/##XYvBDkAwEETvvmKPJJsNW6t6kPgVERUJKojfr66jOb3JmwnjPTxT9B0Rxf64lujDuQ03rGGfM59XFoGLBIJQlwoOQQyJM1a0miScQt0koZAeFfEvKrhFaIi/ESNYaqWILw) [Answer] # [R](https://www.r-project.org/), ~~52~~ ~~51~~ ~~45~~ 44 bytes *Edit: -1+1 bytes thanks to Giuseppe, who also pointed out that there is already a built-in [R](https://www.r-project.org/) function, `psigamma`, that solves the task for only 8 bytes* *Edit2: ...and -6 more bytes thanks to Robin Ryder* ``` function(m,z)gamma(M<-m+1)*sum((-z:-1e4)^-M) ``` [Try it online!](https://tio.run/##XYtBCsIwEEX3nmRGJ8FMMk0jeoReQSiiIjhtUbuwl4/ipql/997jP/LQ39/XVrU95MvYnV63vgOlCX8Omr3RjcP1c1QAM@2MOwc8mgbnH7hIjKuZhcK25ETirSQfpbReKJUcKlr0SM7y38rONVWWFxemaOuvyR8 "R – Try It Online") Uses the same formula as Arnauld's answer. Series representations like this are very well-suited to [R](https://www.r-project.org/) as a natively-vectorized language. Change the `1e4` to higher values (up to `9e9` without increasing the byte count) for progressively higher-accuracy and slower runtime. [Answer] # [Python 3](https://docs.python.org/3/), 38 bytes ``` from scipy.special import* f=polygamma ``` [Try it online!](https://tio.run/##XZHPbsIwDMbvfQrf2qIQxY4TJ2jsRRgHhuhWCWjVdgeE@uwsrbYy7Ts50c@f/7W34bO52sej6poL9Me6vem@PR3rwxnqS9t0wyqrtm1zvn0cLpfDYzj1Qw9bKDJIKgoUBVQqQOtEvCWyWtBFceKRp08u1Q/qFLBJqNFmFnG0IbJ1uCBRgbPaRSvuDzgJyaAhn1IW2CbDmDD20TrW0QX0nrxB5wLHBWOfTBO2FmEnlKxDtNGwCAkZsob/lJm1pKbZUNM/TcMaQm0Co6SGfEjG8ZlEQYHXNJck5yXtQkdiZDbI5AwHebIKRIcZTcNi4NQ@x8AmxlQnK7NuWnX@9kXCx1zBHKHNy6xqOhjUCeorzCfZzI7TZapiNZTzq@3q61BU@X3Ymf2GRgUpwv0GZYT1K9z7DdEI9253eO@Lfn0qX343jvsxLx/f "Python 3 – Try It Online") [Answer] # Java, ~~168~~ ~~148~~ 102 bytes ``` (m,z)->{double p=1-m%2*2,f=0;long i=m;for(;i>0;)p*=i--;for(;i<1e7;)f-=p*Math.pow(z+i++,~m);return f;}; ``` ## Explanation I used the same algorithm as in [@Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/210426/91267). Please vote his answer up. For convenience, here the auto-formatted version: ``` (m, z) -> { double p = 1 - m % 2 * 2, f = 0; long i = m; for (; i > 0; ) p *= i--; for (; i < 1e7; ) f -= p * Math.pow(z + i++, ~m); return f; }; ``` So typical Java code: quite verbose. At least my version. Edit: could save 20 bytes thanks to @user Edit: saved even more bytes thanks to @ceilingcat [Try it online](https://ideone.com/d7FVJX) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 24 bytes ``` **^_1JhhQ*FhQsm^+deQ_JCG ``` [Try it online!](https://tio.run/##K6gsyfj/X0srLt7QKyMjUMstI7A4N047JTUw3isuxPT//2hDcx0Fo9h/@QUlmfl5xf91UwA "Pyth – Try It Online") (link points to slightly different code that sums `1e5` terms instead of `1.56e62` terms to make code runnable and avoid overflow errors) ## Explanation Uses the same algorithm as in [@Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/210426/91267), so make sure to upvote him. ``` **^_1JhhQ*FhQsm^+deQ_JCG JhhQ : Set J to first input + 1 ^_1J : -1 ^ J * *FhQ : times factorial of first input * s : times sum of m : mapping ^+deQ_J : F(d): (d + (second input)) ^ -J CG : on range(1.56e62) ``` [Answer] # [Scala](http://www.scala-lang.org/), 68 bytes *Saved 3 bytes and fixed my answer thanks to Arnauld* Uses the algorithm from Arnauld's [answer](https://codegolf.stackexchange.com/a/210426/95792) ``` m=>z=>(0 to 1<<20 map(z+_ pow ~m)sum)*(m%2*2-1)*(1.0/:(1 to m))(_*_) ``` [Try it online!](https://tio.run/##ZVJbbtswEPznKRZCCkiOzZLL5SuIDKTITz96gwCG4iitClMSRKUPG@3VXdIo2sQeggS5HM5yH3Hb7Jrj8Pi13c7wqel6aH/Mbf8U4W4c4cC@NTt4voGP/Qz1Gj50n@/bbReS8ex0DPV6X69LAfMA8vYWBYRmLPfXGxiH7/A7VPElVIsyvMMFrmTaSS7e35Qy80NVlZvFpjoWRSEtXAABpNLWGoWouJXaW22NpGwkpi/4JAAEFycgeeU8KS0Z@Fccrbj2yur/zAyJQgo06Q1Tl7pZgIxXmrjXThqDRkitHXlG5pKdBFbWkraY/DivvCBr0aJAJeiV0xMYWJAcz5ACF5gy5Uja9Cvjkp4XDN2ZK8Mxe0NtbMoN90iSSEhCLchZljP4Bpa7zE@hS0cpCvKOhPeYCsB4HHfdXBYPfVExnqp4iPWaAUQ@T134d/sQr4sqFXnefjmwrLltYgt309T8LMNyv5yq06uM3ERTG@vnMvB5SL1Ulfu0uR9eHndt9Zc0Tl0/7/oyFldhCVf7NCdYrdPaxiKTfrE0jn8A "Scala – Try It Online") ]
[Question] [ Fairly obviously, you have to print the Greek alphabet. But I thought I'd make it slightly more interesting, so there's a twist: when your program is ran with an argument (anything), it should output the Greek alphabet in lowercase. **Information** 1. Greek alphabet (Capitals): `ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ` 2. Greek alphabet (Lowercase): `αβγδεζηθικλμνξοπρστυφχψω` --- ## Rules/Requirements * Each submission must be a full program. * Builtins to print the Greek alphabet are not permitted * Standard loopholes apply * You must print exactly what is shown. ## Scoring Programs are scored according to bytes. If you are using a character set different to UTF-8 please specify. Try to get the least bytes out of everyone, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")! ## Test cases ``` ./program ==> ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ ./program 1 ==> αβγδεζηθικλμνξοπρστυφχψω ./program 'lower' ==> αβγδεζηθικλμνξοπρστυφχψω ./program 123897883421 ==> αβγδεζηθικλμνξοπρστυφχψω ./program "" ==> αβγδεζηθικλμνξοπρστυφχψω greek(); ==> ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ greek("blah"); ==> αβγδεζηθικλμνξοπρστυφχψω greek(123); ==> αβγδεζηθικλμνξοπρστυφχψω ``` ## Submissions To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. ``` /* Configuration */ var QUESTION_ID = 97049; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; if (/<a/.test(lang)) lang = jQuery(lang).text(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang > b.lang) return 1; if (a.lang < b.lang) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # Ruby, 56 bytes Full program. I don't think a function/lambda answer will be shorter than this for this language. Dangit, sigma `ς`. This is why we can't have nice things. And you too, (unrenderable character that serves as a placeholder for "uppercase" `ς`) ``` print *($*[0]?([*?α..?ω]-[?ς]):[*?Α..?Ρ,*?Σ..?Ω]) ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 16 bytes Uses [CP-1252](http://www.cp1252.com) encoding. ``` 24Ý17K913+çJDl¹s ``` [Try it online!](http://05ab1e.tryitonline.net/#code=MjTDnTE3SzkxMyvDp0pEbMK5cw&input=) **Explanation** ``` 24Ý # push range [0 ... 24] 17K # remove 17 913+ # add 913 to each ç # convert from code point J # join to string Dl # push a lowercase copy ¹ # push the input s # swap the top 2 elements of the stack # implicitly display the top of the stack ``` [Answer] ## JavaScript (ES6), ~~89~~ ~~83~~ 81 bytes ``` (...a)=>String.fromCharCode(...[...Array(24)].map((_,i)=>i*1.06+913+32*a.length)) ``` If a character array is acceptable, then for ~~82~~ ~~80~~ 78 bytes: ``` (...a)=>[...Array(24)].map((_,i)=>String.fromCharCode(i*1.06+913+32*a.length)) ``` Edit: Saved a bunch of bytes thanks to @ETHproductions. [Answer] # Haskell, ~~114~~ 108 bytes ``` import System.Environment q[a,b]=[a..b] f[]=q"ΑΡ"++q"ΣΩ" f _=q"αρ"++q"σω" main=f<$>getArgs>>=putStr ``` Thanks to @xnor for saving 6 bytes This might win in the category of longest imports if nothing else… [Answer] # [CJam](http://sourceforge.net/projects/cjam/), 16 bytes ``` 25,H-ea'α'Α?f+ ``` [Try it online!](http://cjam.tryitonline.net/#code=MjUsSC1lYSfOsSfOkT9mKw&input=) ``` 25,H- e# 0 to 24 excluding 17. ea'α'Α? e# If the argument list is truthy (non-empty), alpha, otherwise Alpha. f+ e# Return characters with each number added to the character code. ``` [Answer] # R, ~~104~~ ~~99~~ 92 bytes ``` g=function(x)for(i in sprintf("'\\u%04X'",913:937+32*!missing(x))[-18])cat(eval(parse(t=i))) ``` Golfing down on the second version I had previously. Work the same way as previous version. Thanks to @JDL for shaving off 7 bytes! **Old versions at 104 bytes:** I have two different solutions with the same byte count: ``` f=function(x){a="ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ";cat(if(missing(x))a else tolower(a))} ``` Or: ``` g=function(x)for(i in sprintf("'\\u%04X'",if(missing(x))913:937 else 945:969)[-18])cat(eval(parse(t=i))) ``` Explanations: ``` #First one is trivial f=function(x){ a="ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ" #String to print #If argument missing, print uppercase else lowercase cat(if(missing(x))a else tolower(a)) } #Second one more interesting: g=function(x) #Create escaped unicode strings (i. e. "'\\u03B1'" etc.), loop over them... for(i in sprintf("'\\u%04X'",if(missing(x))913:937 else 945:969)[-18]) #...eval the strings cat(eval(parse(t=i))) ``` Usage: ``` > f() ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ > g() ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ > f(1) αβγδεζηθικλμνξοπρστυφχψω > g(1) αβγδεζηθικλμνξοπρστυφχψω > f("a") αβγδεζηθικλμνξοπρστυφχψω > g("a") αβγδεζηθικλμνξοπρστυφχψω ``` For some reasons, it doesn't work on R-Fiddle (it changes `"` to `'` by default which makes the code throw an error) but you can try it out on [Ideone](http://ideone.com/sbQqNV). [Answer] ## Pyke, ~~55~~ ~~21~~ 20 bytes ``` 24Fi16>913s.C)sz!hAl ``` [Try it here!](http://pyke.catbus.co.uk/?code=24Fi16%3E913s.C%29sz%21hAl&input=h) ``` 24F ) - for i in range(24): i16> - i > 16 913s - sum(i, ^, 913) .C - chr(^) s - sum(^) - created uppercase alphabet Al - [len, lower, upper][V](^) h - V + 1 z! - not input() ``` [Answer] # [Python 3](https://docs.python.org/3/), 73 bytes ``` import sys x=25 while x:print(end=chr(906-x+32*len(sys.argv))[:x^8]);x-=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKG4spirwtbIlKs8IzMnVaHCqqAoM69EIzUvxTY5o0jD0sBMt0Lb2EgrJzVPA6hWL7EovUxTM9qqIs4iVtO6QtfW8P9/AA "Python 3 – Try It Online") This still may not be as low as it can go! [Answer] # [Actually](http://github.com/Mego/Seriously), 62 bytes ``` "$ù"E"ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"@ƒ.X ``` [Try it online!](http://actually.tryitonline.net/#code=ICIkw7kiRSLOkc6SzpPOlM6VzpbOl86YzpnOms6bzpzOnc6ezp_OoM6hzqPOpM6lzqbOp86ozqkiQMaSLlg&input=) Because some of the uppercase Greek alphabet is not present in CP437, this solution is encoded in UTF-8 and scored accordingly. Here is a hexdump (reversible with `xxd -r`): ``` 00000000: 2022 24c3 b922 4522 ce91 ce92 ce93 ce94 "$.."E"........ 00000010: ce95 ce96 ce97 ce98 ce99 ce9a ce9b ce9c ................ 00000020: ce9d ce9e ce9f cea0 cea1 cea3 cea4 cea5 ................ 00000030: cea6 cea7 cea8 cea9 2240 c692 2e58 0a ........"@...X. ``` Explanation: ``` "$ù"E"ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"@ƒ.X <space> push the number of items present on the stack `$ù`E select `ù` (lowercase) if the number of items is not 0, else `$` (stringify - does nothing to a string) "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ" push the uppercase Greek alphabet @ƒ call the selected function . print X discard ``` [Answer] # Python 3, ~~80~~ ~~77~~ 76 bytes ``` import sys;a='ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ';print([a,a.lower()][-len(sys.argv)]) ``` Old version: ``` import sys;a='ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ';print([a,a.lower()][len(sys.argv)-1]) ``` Older version: ``` import sys;a='ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ';print(a.lower()if len(sys.argv)>1else a) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 81 bytes ``` 'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ'|%('*wer','*per')[!$args.Count] ``` [Try it online!](https://tio.run/##pZLZSsNAFIbv8xRjmTpJaYW0glEQBB9DRKROVBiTtGlQaAuK@6X7vuF@6b7rG/zzSHEaNYrghWQuZuCc///OcM7x3FFe9oe4ECG1SSephgwLWMQSlrGCVaxhHRvYxBa2sYNd7GEfBzjEEY5xglOc4ZzV0jrLKAzLsoynHqOnifaXB/2WbjdwKr1hXdO6dI2ok9X/T88S5rhE8YIR7lR8ZsSkC1ziCte4wS3ucI8HPOIJz3jBK97kuJyQk3JKTssZOSvn5LwimUnMTDR6lag@M/MFq73NsgqteTMZKZGbOoEQhmaQGkmTagSifMzjxQofUNmvZqt9oH1alB629Tic46VfI/lARJgy9wPRcDZTO4rWo5sLn/@h@q73Q5@i@qcoV@Sl@HNGR@yNXSmtHr4D "PowerShell – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 68 bytes ``` j=24;main(i){for(setlocale(6,"");j--;)putwchar(968-1/i*32-j+(j<7));} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/L1sjEOjcxM08jU7M6Lb9Iozi1JCc/OTEnVcNMR0lJ0zpLV9das6C0pDw5I7FIw9LMQtdQP1PL2Eg3S1sjy8ZcU9O69v///4YA "C (gcc) – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~96 53 51~~ 58 bytes ``` cat(intToUtf8((913:937)[-18]+32*!!length(commandArgs(T)))) ``` [Try it online!](https://tio.run/##K/r/PzmxRCMzryQkP7QkzUJDw9LQ2MrS2FwzWtfQIlbb2EhLUTEnNS@9JEMjOT83NzEvxbEovVgjRBMI/v//DwA "R – Try It Online") I tried to make an R answer with command line args, but it's a bit longer(now a lot, lot shorter) than the loop based approach by plannapus. I used some of the tricks in their answer. A crazy -43 bytes from Dominic Van Essen. -2 more bytes from Dominic Van Essen. +7 bytes after removing `ς` [Answer] # [Julia 1.0](http://julialang.org/), 42 bytes ``` print.(['Α':'Ρ';'Σ':'Ω'].+32(ARGS>[])) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/v6AoM69ETyNa/dxEdSv1cwvVrdXPLQaxVqrH6mkbG2k4BrkH20XHamr@V1YIKapUSExJycxLV0jMU0gsSi/NTc0rUUhKzckvV/wPAA "Julia 1.0 – Try It Online") -1 byte thanks to MarcMush: use `ARGS>[]` instead of `ARGS==[]` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~21~~ ~~19~~ 18 bytes ``` ;Ckzir)c+816+32*NÊ ``` [Test it (no input)](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O0NremlyKWMrODE2KzMyKk7K) [Test it (empty string input)](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O0NremlyKWMrODE2KzMyKk7K&input=IiI) ``` ;Ckzir)c+816+32*NÊ :Implicit input (or not) ;C :Lowercase alphabet. k :Remove zir : "z" prepended with "r" ) :End remove c+ :Map charcodes and add 816+32* : 816 plus 32 multiplied by N : Array of all inputs Ê : Length (0 if no input, 1 if a single input) ``` [Answer] # Scala, 82 bytes ``` print((('Α'to'Ρ')++('Σ'to'Ω')).mkString.map(& =>if(args.size<1)&else&toLower)) ``` Ungolfed: ``` print((('Α'to'Ρ')++('Σ'to'Ω')).mkString.map(s=>if(args.size==0)s else s.toLower)) ``` Sadly, `(('Α'to'Ρ')++('Σ'to'Ω'))` is a `Vector[Char]`, which would be printed as `Vector('Α', 'Β', ...`, so it has to be converted to a string with `mkString`.The argument to `map` is called `&` to save spaces between `&else`, `else&` and `& toLower`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ,⁸Ea32µ24R%18T+912+µỌ ``` A full program **[TryItOnline!](http://jelly.tryitonline.net/#code=LOKBuEVhMzLCtTI1UiUxOFQrOTEyK8K14buM&input=)** - note once run with an argument a refresh will be required to run with no argument. ### How? ``` ,⁸Ea32µ24R%18T+912+µỌ - Main link ,⁸ - pair (,) with left argument (defaults: left=0, ⁸=[]) no argument: [0,[]] argument: [argument,argument] E - all items equal? -> no argument: 0; argument: 1 a32 - and 32 -> no argument: 0; argument: 32 µ - monadic chain separation 24R - range(25) -> [ 1, 2, 3,..., 17, 18, 19,..., 25] %18 - mod 18 -> [ 1, 1, 1,..., 1, 0, 1,..., 1] T - truthy indices -> [ 1, 2, 3,..., 17, 19,..., 25] +912 - add 912 -> [913,914,915,...,929, 931,...,937] + - add the 0 or 32 (lowercase letters are 32 code points higher) µ - monadic chain separation Ọ - cast to ordinals ``` [Answer] ## PowerShell v2+, 68 bytes ``` (($a=-join([char[]](913..929+931..937))).toLower(),$a)[!$args.count] ``` ASCII-only, but outputs in UTF-16. Constructs a `char`-array of the appropriate characters, `-join`s it together into a string, stores it into `$a`. Then, uses `!$args.count` as an index into the tuple, to output either `$a` if no arguments are present, or `$a.ToLower()` if there is at least one argument. ``` PS C:\Tools\Scripts\golfing> .\print-the-greek-alphabet.ps1 ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ PS C:\Tools\Scripts\golfing> .\print-the-greek-alphabet.ps1 '' αβγδεζηθικλμνξοπρστυφχψω ``` [Answer] # Python 3, 80 bytes ``` import sys;print(''.join(chr(x+881+len(sys.argv)*32)for x in range(25)if x!=17)) ``` [Answer] ## C#, 174 bytes Lazy implementation, can probably golf it a lot ``` class P{static void main(string[] a){System.Console.Write(a.Length>0?"αβγδεζηθικλμνξοπρστυφχψω":"ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ");}} ``` [Answer] # tcl, 73 ``` puts [expr $argc>0?"αβγδεζηθικλμνξοπρστυφχψω":"ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"] ``` [demo](http://www.tutorialspoint.com/execute_tcl_online.php?PID=0Bw_CjBb95KQMT2N4TEkxRGpZb1E) [Answer] # PHP, 84 Bytes [Online Version](http://sandbox.onlinephpfunctions.com/code/4170b41daca83e8496a985157cd8952062004dc7) ``` <?=($argc<2?trim:mb_strtolower)("ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"); ``` # PHP, 87 Bytes ``` $s="ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ";echo$argc>1?mb_strtolower($s):$s; ``` [Answer] # [Retina](https://github.com/m-ender/retina), 55 bytes ``` .+ αβγδεζηθικλμνξοπρστυφχψω ^$ ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ ``` [**Try it online**](https://tio.run/##BcE5EsFgAIbh/j9HOjOOlBmFQqMwDsAQpLTEmljGEkpZxO4G73ek3/M0qs1avWJtuWS4kpCSkXOj4M6DJy/efPjyU0ttddSVp576Gsg3rmMYMmLMhIApM@YsWLIiJGLNhi079hw4ciLmzMXaPw) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 26 bytes The normal way to pass multiple arguments to APL programs is through a lists. So this program prompts for such a list, which may have 0 or 1 arguments. ``` 'ς΢'~⍨⍳'Ω'×~≢⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94L/6@aZzi9TrHvWueNS7Wf3cSvXD0@sedS561DcVJP9fAQwKuIB8r2B/P/XoWHUuDDGlpJzEDCVsMoZGxrHqAA "APL (Dyalog Extended) – Try It Online") `⎕` prompt for argument list `≢` tally the number of arguments (0 or 1) `~` negate that (1 or 0) `'Ω'×` "multiply" Omega by that (1 keeps uppercase, 0 folds to lowercase) `⍳` All characters from `Α`–`Ω` or `α`–`ω` respectively `'ς΢'~⍨` remove lowercase and "uppercase" final sigmas [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf), 24 bytes ``` l?#α:#Α|# 9->[.!@ 1+]; ``` [Try it online!](https://tio.run/##SypKzMxLz89J@/8/x1753EYr5XMTa5QVLHXtovUUHRQMtWOt////bwgA "Braingolf – Try It Online") ### Explanation: ``` l?#α:#Α|# 9->[.!@ 1+]; Implicit input of args to stack l Push length of stack ? If last item (length) is != 0.. #α ..Push lowercase alpha : else #Α ..Push uppercase alpha | endif #<space> Push 32 (ordinal of a space) 9- Subtract 9 (23) > Move last item to start of stack [......] Do-While loop, will run 24 times . Duplicate last item !@ Print without popping 1 Push 1 + Pop last 2 items (1 and duplicate) and push sum ; Suppress implicit output ``` [Answer] # Python 3, 78 bytes ``` import sys;a=(len(sys.argv)-1)<<5;print(''.join(map(chr,range(a+913,a+938)))) ``` ## Explanation `a` is an offset, 32 when an argument is given to use the lowercase range. 913 to 937 is the range of unicode values for the uppercase greek alphabet. [Answer] # [Python 3](https://tio.run/##FcdBCoMwEAXQfU7xdyZUCql1oeBJigtpow60kzATBE8/0rd75ax75s6MfiVLhZ7qdBqePWj9577IdrziOCN9NWGInVuzgEAMWXhLXlu9PfowOqAIcfXvXTyFNvFnappgZvEC), 88 bytes ``` import sys s=945 if sys.argv[1:] else 913 for i in range(s,s+25): print(chr(i),end='') ``` [Answer] # Python 3, 74 bytes This an improvement to @HackerBoss es' answer (I don't have enough reputation to comment). ``` import sys;a=len(sys.argv)-1<<5;print(*map(chr,range(a+913,a+938)),sep='') ``` Subtraction has higher precedence than bit shift, so no need for parentheses, we save 2 bytes. Also instead of using `''.join()` we unpack the `map()` and set `print()`'s default seperator to an empty string to omit the spaces, that saves 1 byte. [Answer] # [Zsh](https://www.zsh.org/), 45 bytes ``` A=({Α..Ω}) ((#))&&A=${(L)A} tr -d \ -z<<<$A ``` [Try it online!](https://tio.run/##qyrO@P/f0Vaj@txEPb1zK2s1uTQ0lDU11dQcbVWqNXw0HWu5SooUdFMUYhR0q2xsbFQc//8HAA "Zsh – Try It Online") [Answer] # [Rust](https://www.rust-lang.org/), 134 bytes ``` fn main(){let mut s:String=('α'..'ϊ').collect();s.remove(34);print!("{}",if std::env::args().nth(1)==None{s.to_uppercase()}else{s})} ``` [Try it on the Rust Playground!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&code=fn%20main()%7Blet%20mut%20s%3AString%3D(%27%CE%B1%27..%27%CF%8A%27).collect()%3Bs.remove(34)%3Bprint!(%22%7B%7D%22%2Cif%20std%3A%3Aenv%3A%3Aargs().nth(1)%3D%3DNone%7Bs.to_uppercase()%7Delse%7Bs%7D)%7D) ungolfed: ``` fn main() { //full program let mut s: String = ('α'..'ϊ').collect(); //create a range of chars from 'α'(inclusive) to 'ϊ' (exclusive) and collect into string s.remove(34); //remove 'ς' print!( //print "{}", //with default formatting if std::env::args().nth(1) == None { //if the 2nd arg doesn't exist (first is filename) s.to_uppercase() // uppercase string then return } else { // else s // return unmodified string } ) } ``` This doesn't work on tio for some reason so this is on the playground, where you can't add input- turn the `==` to a `!=` to test lowercase version. ]
[Question] [ Given a list of positive integers such as `[69, 420]`, your challenge is to generate the sequence of numbers that can be formed by concatenating numbers from the above set, in ascending numerical order. For example, with `[69, 420]` the sequence begins: ``` 69 420 6969 42069 69420 420420 ``` Note that elements of the sequence should be unique. The list will be nonempty and will not contain duplicates. Standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply. ## Testcases In `list, 0-indexed number` format. ``` [69, 420], 4 -> 69420 [32, 33, 34], 8 -> 3334 [109, 5], 7 -> 10955 [2, 22, 222], 4 -> 22222 ``` [Answer] # [Python](https://www.python.org), 71 bytes (-3 thanks to @pxeger) ``` def f(A): o=A while o:=o-{x:=min(o,key=int)}|{x+i for i in A}:yield x ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY1BCsIwEEX3PcWQVYIt6EKwgQpdiceodEKH1qSEVFNiTuKmG914Im9jtf7le_D-_dmPrjF6mh6DU9nufahRgeKlkAmYokzg2lCHYGRhsuBlcSbNTdriWJB2It6CXxEoY4GANJRRjoRdDf6fO_5U6r8S9XBGWznkiuOl6jjpfnBczJvPSAHtc3myWLUJ9HbOc8UCRQnBRyaW4PQKbLPOWcq2LC7oAw) This takes a set of strings as its input. ### Old [Python](https://www.python.org), 77 bytes ``` def f(A): o=A while o:O,*o=sorted({*o},key=int);yield O;o+=map(O.__add__,A) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LYwxCsIwFED3niJ0-qlR2kHQlgw9gPQAIiGQRD_WJMRUqeJJXLro4om8jQX7xgfvPd--jwdnh-HVRTNffTdKG2KgpmVCHK8Tcj1gq4krG5Y5fnYhagX3zD3YUfccbaRVj7pVpKncjJ-kh2YhhFRKCFbTaVoYFwgStOSGHoK0ew1FTpkBfZEtoPVdBDpS-jAuAadw-GzTIl-nLF2mu7_6AQ) A generator that walks through the sequence. How does it work? It maintains a list/set which always contains (or has yielded) all the concatenations of all numbers output so far with all numbers in the input list. At each iteration it yields the smallest element and adds its concatenations with the input list. [Answer] # [JavaScript (V8)](https://v8.dev/), 60 bytes Prints the sequence forever. ``` a=>{for(k=0;;)(++k+'').match(`^(${a.join`|`})+$`)&&print(k)} ``` [Try it online!](https://tio.run/##BcHRCkAwFADQX/Egu7chSSLNj4h2U8sspll7wbfPOTsFulenL1@ELioRSYyPsg6MqIYBgXPDGcPyIL9uIBdIHyp3q0/5yg95KjHLLqdPDwa/qGBq@zxp6mrG@AM "JavaScript (V8) – Try It Online") ### How? We turn the list of integers into a regular expression: ``` [69, 420] ~~> /^(69|420)+$/ ``` And we use it to identify the positive integers that belong to the sequence. [Answer] # [Zsh](https://www.zsh.org/) `-F`, 30 bytes ``` seq inf|grep -xP (${(j"|")@})+ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjWbSSrptS7IKlpSVpuhb7ilMLFTLz0mrSi1ILFHQrAhQ0VKo1spRqlDQdajW1IYqgaldGm1nqKJgYGcA0AwA) Slow. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` иæJïê¹£ ``` Given \$n\$ and the list, it outputs the first \$n\$ results. [Try it online](https://tio.run/##ASIA3f9vc2FiaWX//9C4w6ZKw6/DqsK5wqP//zEwCls2OSw0MjBd) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXCoZX/L@w4vMzr8PrDqw6tO7T4v87/6OhoM0sdEyODWB2TWB2F6GhjIx1jYx1jIMcMzDc0sNQxjdUxB3OMdIxAyAikOBYA). **Explanation:** ``` и # Repeat the (implicit) second input-list the first (implicit) # input-integer amount of times as list æ # Get the powerset of this list J # Join each inner list together ï # Cast each string to an integer ê # Uniquify and sort the list ¹£ # Only leave the first first input amount of values # (after which this is output implicitly as result) ``` Too bad sorting builtins don't work on infinite lists, otherwise `ÞæJïê` would have been enough to output the infinite sequence given just an input-list. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes ``` tT&j₎⊇ᵘcᵐoh↙T ``` [Try it online!](https://tio.run/##ATMAzP9icmFjaHlsb2cy//90VCZq4oKO4oqH4bWYY@G1kG9o4oaZVP//W1s2OSw0MjBdLDVd/1o "Brachylog – Try It Online") Extremely inefficient. This returns the first N elements, 1-indexed. ### Explanation ``` tT Input = [List, T] &j₎ Concatenate List T times to itself ⊇ᵘ Find all unique subsets of this new list cᵐ Map concatenate o Sort h↙T Return the first T elements ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~109~~ ~~108~~ 104 bytes ``` a=input();i=0 m=lambda n:n*all(n.find(p)or m(n[len(p):])for p in a) while 1: if""==m(`i`):print i i+=1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=Lc1NCsIwEEDhfU4xZJX4R1tENJKTlEIjbchAMg0lRTyLm2zElQfyNgbq8n2b93zHR3ITNTm_lmT3568zGikuScgr6ooF7U24DQZI0cZ4L-hgkQYR5TRDENT6kUqoTtoCEZDASHZ36EeoFQO0nGsdRI-9VHFGSoBFt7pef_9t_rT8dOE74Mem4t2KPw) -1 byte thanks to Jonathan Allan --- # [Python](https://www.python.org), 81 bytes ``` import re def f(a,i=0):re.match(f'({"|".join(a)})+$',str(i))and print(i);f(a,i+1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwU31zNyC_KISheLKYi4g1itOLSlKTS4tKs7Mz8vJzM0s0TA0AALNpaUlaboWNwOhyotSuVJS0xTSNBJ1Mm0NNK2KUvVyE0uSMzTS1DWqlWqU9LLyM_M0EjVrNbVV1HWKS4o0MjU1E_NSFAqKMvNKgBxrsFZtQ6jBG9I0opXMLJV0FJRMjAyUYqHCCxZAaAA) Dies with the recursion limit, but works theoretically (or if you use a Python interpreter with TCO) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` xŒPḊVQṢḣ ``` A dyadic Link that accepts the list of positive integers on the left and the number of elements to get, `N`, on the right and yields a list of the first `N` concatenated integers. **[Try it online!](https://tio.run/##AScA2P9qZWxsef//eMWSUOG4ilZR4bmi4bij////WzEsIDIzLCAxMDFd/zU "Jelly – Try It Online")** - extremely inefficient! ### How? ``` xŒPḊVQṢḣ - Link: list of positive integers, L; positive integer, N x - repeat the elements of L N times each ŒP - powerset Ḋ - dequeue (remove the empty list) V - evaluate as Jelly code (concatenates each and gives back the integer) Q - deduplicate Ṣ - sort ḣ - head -> the first N elements ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` ≔θζFη«⊞υ⌊⁻ζυ≔⁺ζI⁺I⌈υIθζ»Iυ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU@jUEehStOaKy2/SEEjQ1OhmoszoLQ4Q6NUR8E3My8ztzRXA0iXFmtU6SiUamoCVXJCNQbkQESdE4tLIBwwyzexAqwLqBgqVwjUpgmxpZYroCgzrwSiEqjC@v//6GgzSx0FEyODWB0Fs9j/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` terms. Explanation: Based on @Albert.Lang's Python answer. ``` ≔θζ ``` Start with the input list. ``` Fη« ``` Repeat `n` times. ``` ⊞υ⌊⁻ζυ ``` Save the minimum value not collected so far. ``` ≔⁺ζI⁺I⌈υIθζ ``` Append all the concatenations of that value with the input list to the current list. ``` »Iυ ``` Output the collected terms. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 62 bytes ``` ~(T`,`| (\d+).(.+) K`0¶$1{`.+¶$$.($\*\_\_¶/^($2)+$/^+`.+¶$$.($*__ ``` [Try it online!](https://tio.run/##K0otycxLNPz/v04jJEEnoYZLIyZFW1NPQ09bk8s7weDQNhXD6gQ9bSCtoqehohUff2ibfpyGipGmtop@nDaKzP//pjpmljomRgYA "Retina – Try It Online") Takes `n` as the first input in the list and outputs the 1-indexed `n`th term. Explanation: Similar approach to @Arnauld's JavaScript answer. ``` T`,`| ``` Change the commas into `|`s. ``` (\d+).(.+) ``` Match the first number and the remaining numbers separately. ``` K`0¶$1{`.+¶$$.($\*\_\_¶/^($2)+$/^+`.+¶$$.($*__ ``` Create a Retina program with them substituted in. ``` ~(` ``` Evaluate that program. For example, with the inputs `5,69,420` the following Retina program is created: ``` K`0 ``` Set the current value to `0`. ``` 5{` ``` Repeat `5` times. ``` .+ $.(*__ ``` Increment the current value. ``` /^(69|420)+$/^+` ``` Repeat while the current value isn't a concatenation of `69`s and `420`s... ``` .+ $.(*__ ``` ... increment the current value. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` ẋfṗvṅ⌊sUi ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuotm4bmXduG5heKMinNVaSIsIiIsIjRcblsyLCAyMiwgMjIyXSJd) Port of the Jelly answer. Yields a list of the first N concatenated integers. ## Explained (outdated - will fix soon) ``` ẋfṗvṅ⌊sUi ẋf # Repeat the input list N times ṗ # take the powerset of that list vṅ⌊ # Concatenate each sublist into a single integer sUi # and get the Nth item in the sorted uniquified list ``` [Answer] # [R](https://www.r-project.org/), 82 bytes ``` function(n)repeat grepl(sprintf("^(%s)+$",paste(n,collapse="|")),F<-F+1)&&print(F) ``` [Try it online!](https://tio.run/##HctBCoAgEADAr4hU7KJBRQRBXX1GIKIRyCpqt/5u0WlOk6rbq7vJlCsQECYbrS7s/PSQY7qoOOAHtBlFw2XUuVggaYL3Oma784cjSrX1SozYdX8AhdWBgWWVbJ4GxPoC "R – Try It Online") Port of [@Arnauld's answer](https://codegolf.stackexchange.com/a/248332/55372). [Answer] # [Pip](https://github.com/dloscutoff/pip), 12 bytes ``` W1Ui~=+Xg&Pi ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLG51bGwsIkxtVWl+PStYZyZQaSIsIiIsIjIgMyIsIi1wIl0=) (link is to a safe version that only runs 1000 times) -2 thanks to DLosc. ``` W1 # Forever ~= # Check a regex match of... Xg # Input regex'd + # With a `+` Ui # In (incrementing) i &Pi # If so, print i ``` [Answer] # [Factor](https://factorcode.org/) + `lists.lazy`, ~~95~~ 82 bytes ``` [ 0 lfrom swap "|"join "^(%s)+$"sprintf <regexp> '[ present _ matches? ] lfilter ] ``` [Try it online!](https://tio.run/##PY1Na8JAFEX3/opLqFQRJC0iaKUuxY2b0lWwMgxv4tRxkrz3JE0/fnsaDbi8l3vuccZqwe3723a3WSJ4UZkG893gRBwpQKi6ULQkcAWfjaqPOZhy@irhuEHJJBS1J69JtSnZd01V42UwqOofzBeYPaf4azOkCI6LM6Q2JZLf5LPwEcnHaCjjyUMiN9Jh1Qte8ZjdBQd0dnskWWPfnfigxNi31oSAp7Q/DGpOhAzT64SMPbb/ "Factor – Try It Online") -13 bytes from using [@Arnauld's method](https://codegolf.stackexchange.com/a/248332/97916). Takes input as a sequence of strings representing integers and returns an infinite lazy list of the sequence. [Answer] # BQN, 37 bytes ``` {𝕨⊑∧⍷•Bqn¨∾¨•Fmt¨¨1↓(⥊(↕2˘)/¨<)∾𝕨/⋈𝕩} ``` [Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge/CdlajiipHiiKfijbco4oCiQnFu4oiY4oi+4oCiRm10wqgpwqgx4oaTKOKliijihpUyy5gpL8KoPCniiL7in5zwnZWp4o2f8J2VqPCdlal9CjQgRiA2OeKAvzQyMA==) Slow enough that you'll probably need a local interpreter to run most of the cases. 2 bytes saved thanks to @Razetime! # Explanation *w* is index, *x* is list of numbers. * `∾𝕨/⋈𝕩` *x* repeated *w* times * `(⥊(↕2˘)/¨<)` powerset * `1↓` remove empty set * `•Bqn¨∾¨•Fmt¨¨` for each element in powerset, concatenate numbers + Super-slow since we're "eval"ing each string to get the number (BQN doesn't have an easy way to convert strings to numbers) * `∧⍷` Deduplicate and sort * `𝕨⊑` Get *w*th number [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 16 bytes ``` Jx/jcb)imNB><j!! ``` [Try it online!](https://tio.run/##SyotykktLixN/Z@TV62ka6dkba0bW5D636tCPys5STMz18/JziZLUfF/bW70/2ozSwUTI4NaBRMFXTsFM0sgm6va2EjB2FjB2KRWwQIkamxsbMJVbWhgqWBaq2AOEgGyTU25qo0UjEDICKrbCAQA "Burlesque – Try It Online") Takes block (L) and int (N) ``` J # Duplicate N x/j # Make stack N,L,N cb # Combinations of L of length [1..N] )im # Concat each result NB # Remove duplicates >< # Sort j!! # Select Nth ``` ]
[Question] [ Three positive integers A, B, C are ABC-triple if they are coprime, with A < B and satisfying the relation : A + B = C Examples : * `1, 8, 9` is an ABC-triple since they are coprime, 1 < 8 and 1 + 8 = 9 * `6, 8, 14` is not because they are not coprime * `7, 5, 12` is not because 7 > 5 You can see this [Frits Beukers 2005 presentation](https://web.archive.org/web/20181227041615/http://www.staff.science.uu.nl/%7Ebeuke106/ABCpresentation.pdf) for more details about ABC-triples. # Input/Output Three integers, decimal written. May be separated values or list. Output had to be a truthy/falsy value whether the three integers are an ABC-triple. Note: It is important to respect integers order in the list, for example: `1, 8, 9` is not considered as the same list as `9, 1, 8` or any other combination. So first is an ABC-triple and second is not. Thus A is the first element of the list, B the second and C the third. # Test cases Each of the following lists should output a truthy value ``` [1, 8, 9] [2, 3, 5] [2, 6436341, 6436343] [4, 121, 125] [121, 48234375, 48234496] ``` Each of the following lists should output a falsey value ``` [1, 1, 2] [1, 2, 5] [1, 9, 8] [4, 12872682, 12872686] [6, 8, 14] [7, 5, 12] ``` [Answer] # [Haskell](https://www.haskell.org/), ~~48 38~~ 29 bytes -10 bytes due to [TFeld](https://codegolf.stackexchange.com/users/38592/tfeld)'s `gcd` trick! -7 bytes thanks to [HPWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz) for improving the co-primality test and spotting a superfluous space! -2 bytes thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi) for suggesting an infix-operator! ``` (a!b)c=a<b&&a+b==c&&gcd a b<2 ``` [Try it online!](https://tio.run/##VVDJboMwEL3zFS8RQrZwDhiHpYJcem1PPbY9GEMWNTERi0q/ntooBXoZvU3zRnOW7Vd1vY4jkZuCqlxmhedJv8hz5XknVUKiyPh4kxeNHGXtABd97ztkOzSVLJG5B5yq7rnWXaW71vg3eX8F@Rh2B5jgW9e8aLhoz/U3Bvg@tjDO1qJJI71WfdP8hCAbioFSuGbJo@XJwneABAwJQ0otZ4ZzhpBhv@aRCKNQBH8gnD3BEPDAjiU/CSLhJhfvH0ik0eKbOANfc77uMzw1J/3vSGIeJXxGy7Zouj4QsxCbXTY3CZ@OM//gCCJZwRQ13z7a50ONpoyzkP4C "Haskell – Try It Online") ## Explanation The first two conditions `a < b` and `a + b == c` are fairly obvious, the third one uses that \$\gcd(a,b) = \gcd(a,c) = \gcd(b,c)\$: Writing \$\gcd(a,c) = U \cdot a + V \cdot c\$ using [Bézout's identity](https://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity) and substituting \$c = a + b\$ gives: $$ U \cdot a + V \cdot (a + b) = (U + V) \cdot a + V \cdot b $$ Since *the* \$\gcd\$ is the minimal positive solution to that identity it follows that \$\gcd(a,b) = \gcd(a,c)\$. The other case is symmetric. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes ``` Ṫ=S×</=g/ ``` [Try it online!](https://tio.run/##y0rNyan8///hzlW2wYen2@jbpuv/P9z@qGkNECm4//@voRFtqKNgoaNgGculoBNtpKNgrKNgCmObmRibGZsYwhjGYHETHQVDI0MQAVEH5phYGAHlzU2hLBNLM6CcJpcO2HggMoIoBTJgxgPZlkCbEUZamBuZWRjBWWZgGTOw4wxNwBxzoF6QfCyXpiYA "Jelly – Try It Online") ### How it works ``` Ṫ=S×</=g/ Main link. Argument: [a, b, c] (positive integers) Ṫ Tail; pop and yield c. S Take the sum of [a, b], yielding (a + b). = Yield t := (c == a + b). </ Reduce by less than, yielding (a < b). × Multiply, yielding t(a < b). g/ Reduce by GCD, yielding gcd(a, b). = Check if t(a < b) == gcd(a, b). ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~33~~ 32 bytes *-1 byte thanks to nwellnhof* ``` {(.sum/.[2]/2*[<] $_)==[gcd] $_} ``` [Try it online!](https://tio.run/##Pc6xCoMwEAbg3ae4oYhKiOQSo0KldOjWuUuQUlqVgraidBCxr26TkLocH/ffXdJXQyvXbgK/hmKdAzp@upgqLGOM1L6E3TUsCtXcH4bLWr8HCNrnqxpD2gxVH3yjEGYPYLxNcKCny/FM/dpbVsUIZATy0vMUEuAEEkcpuOSC/cFNWxBgyEyxU9YiQ52miZPIpY30EAF0RHdWM9fvbaeyFGWGm@ymtB9iwjjVeyYtfw "Perl 6 – Try It Online") Anonymous code block that takes a list of three numbers and returns True or False. ### Explanation ``` { } # Anonymous code block [gcd] $_ # Is the gcd of all the numbers ( )== # Equal to .sum # Whether the sum of numbes / # Is equal to .[2]/2 # The last element doubled *[<] $_ # And elements are in ascending order ``` [Answer] # Excel, 33 bytes ``` =AND(A1+B1=C1,GCD(A1:C1)=1,A1<B1) ``` [Answer] ## bash, 61 bytes ``` factor $@|grep -vzP '( .+\b).*\n.*\1\b'&&(($1<$2&&$1+$2==$3)) ``` [Try it online!](https://tio.run/##NY5NboMwEEb3nOJbWAYaJdHYxhiVRD1CD8AGqJ0sUIgIyaKlZ6d2nSxG8@bvabr2dl77dsbRoa5Tl66u7edxAvtYTpO9Yvv4/kSaYbdpunz31lx8UNOlnGcZo5oJzhltmDgcmMzz1SXJacxy/KDzZjjvwXH/ZR/7y30YwDlsfx4xT3eLZYmFa4ebfcdvOAXBoAogIFFE0EpqqeiZZWgqkCAf/xsBlRF@VBYRVKWTJMifToKIIKKTUMG8PKYU2ogX6NDW/gtSgUoUfrL@AQ) Input as command line arguments, output in the exit code (also produces output on stdout as a side effect, but this can be ignored). The second part (starting from `&&((`) is pretty standard, but the interesting bit is the coprime test: ``` factor $@ # produces output of the form "6: 2 3\n8: 2 2 2\n14: 2 7\n" |grep - # regex search on the result v # invert the match (return truthy for strings that don't match) z # zero-terminated, allowing us to match newlines P # perl (extended) regex '( .+\b)' # match one or more full factors '.*\n.*' # and somewhere on the next line... '\1\b' # find the same full factors ``` [Answer] # Java 10, ~~65~~ 64 bytes ``` (a,b,c)->{var r=a<b&a+b==c;for(;b>0;a=b,b=c)c=a%b;return r&a<2;} ``` -1 byte thank to *@Shaggy*. [Try it online.](https://tio.run/##jVLBcoIwEL37FXupE6YRm4CIRTz2Vi/21ulhE2OLheCEYMdx/HYaEI8tHrLZnX3v5WWTPR5xst9@NzLHqoJXzPR5BJBpq8wOpYJ1WwKIsswVapDEtQBpG0UXpZc4xGXkwho0pNAQpIJKb7I6H9GASXEpxvgo0lQmu9KQRKyeEkwFFan0ZIoPIjHK1kaDGeOSJ5cmacUOtcgzCZVF67ZjmW2hcO7IxppMf75/AHpXa61nKNzBWv10BekcAUyn8GZq@3V67srNqbKq8Mva@gcnYXNNCl/7kjAa04XXk/5EcRrQ2R2oKAyiIGT9HgwyQso4c2tYu8WFMXei89k1CRfRP6y@c5vFC@aVGp4Fo3zYCeV3zILRBY3vun8851HMb0k0yInci7FwEDanM6fp9R/00vwC) **Explanation:** ``` (a,b,c)->{ // Method with three integer parameters and boolean return-type var r= // Result-boolean, starting at: a<b // Check if `a` is smaller than `b` &a+b==c; // And if `a+b` is equal to `c` for(;b>0 // Then loop as long as `b` is not 0 yet ; // After every iteration: a=b, // Set `a` to the current `b` b=c) // And set `b` to the temp value `c` c=a%b; // Set the temp value `c` to `a` modulo-`b` // (we no longer need `c` at this point) return r // Return if the boolean-result is true &a<2;} // And `a` is now smaller than 2 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ ~~11~~ 10 bytes Saved 1 byte thanks to *Kevin Cruijssen* ``` ÂÆ_*`\‹*¿Θ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cNPhtnithJhHDTu1Du0/N@P//2gTHQVDI0MQYRoLAA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##yy9OTMpM/W9o6HZ4gr2Sgq6dgpL9/8NNh9vitRJiHjXs1Dq0/9yM/zr/ow11FCx0FCxjuaKNdBSMdRRMISwzE2MzYxNDGMMYKGqio2BoZAgiQGrATBMLI6CcuSmUZWJpBpIBKtFRMIKwjCAmAlmWQItgpliYG5lZGMFZIF1mYHcYmgCZ5kA9ILlYAA) **Explanation** ``` ÂÆ # reduce a reversed copy of the input by subtraction _ # logically negate * # multiply with input ` # push the values of the resulting list separately to stack \ # remove the top (last) value ‹ # is a < b ? * # multiply by the input list ¿ # calculate the gcd of the result Θ # is it true ? ``` [Answer] # Wolfram Language ~~24 30 28~~ 26 bytes With 2 bytes shaved by Doorknob. A further 2 bytes shaved off by @jaeyong sung ``` #<#2&&GCD@##==1&&#+#2==#3& ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~69~~ ~~67~~ ~~63~~ ~~62~~ 55 bytes ``` lambda a,b,c:(c-b==a<b)/gcd(a,b) from fractions import* ``` [Try it online!](https://tio.run/##XY/LDoMgFET3fsVN3EhD0/AQsal/0g1iaU18BemiX0/RWB9NCJmcGe4dho979R31prj7RrVlpUDhEutros9lUahbiS5PXSUBosjYvgVjlXZ1341Qt0Nv3cnHzr4f0WDrzoFJCAaJIUcroBgYhvQABGeCcfITbDM5BkLJdO1ezIRLGpJZuiieiyUQxUY146FBOBTtAT00CCAPNf@2yowKSVclNlvMfyJ8I1mYNyWR/wI "Python 2 – Try It Online") --- # [Python 3](https://docs.python.org/3/), ~~58~~ 51 bytes ``` lambda a,b,c:(c-b==a<b)==gcd(a,b) from math import* ``` [Try it online!](https://tio.run/##XY9NDoMgEIX3noLEDTR0wY@ITblJN6ClmogaShc9PUXTGmxCJo9vHjOP5R36eWLRqlsctTOdBhob3F5gezZK6atBSj3aDiaKCutnB5wOPRjcMvtwimXwr3ux@GEK0EKCgcSgQWgnFAOGQXUkgjPBOPkJlnU5BoSSteRvNsQlTd66@ireiN2BitLq8XkIkg7NR6TrMUgiTcr7v1zWVEi6K5H1xfY9wjNUp5mrN6H4AQ "Python 3 – Try It Online") --- -7 bytes, thanks to H.PWiz [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~16~~ ~~14~~ ~~13~~ 11 bytes ``` <V¥yU «NÔr- ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=PFaleVUgq07Uci0=&input=MQo4Cjk=) ``` :Implicit input of integers U=A, V=B & W=C <V :Is U less than V? ¥ :Test that for equality with yU :The GCD of V & U « :Logical AND with the negation of N :The array of inputs Ô :Reversed r- :Reduced by subtraction ``` [Answer] # JavaScript (ES6), ~~54 43 42~~ 40 bytes *Thanks to @Shaggy for pointing out that we don't need to compute \$\gcd(a,c)\$. Saved 11 bytes by rewriting the code accordingly.* Takes input as 3 separate integers. Returns \$true\$ for an ABC-triple, or either \$0\$ or \$false\$ otherwise. ``` f=(a,b,c)=>c&&a/b|a+b-c?0:b?f(b,a%b):a<2 ``` [Try it online!](https://tio.run/##bVDdCoIwGL33KXaTbPRZ7cc5JfNZtqVSiIuMrnr3NaWCmDDG4fx839mu@qkne7/cHtnozq33XY01GLCkPtk01Xvz0luT2eZQmabDBvTGkEofmbdunNzQ7gbX4w5TQApQSUjyzzNAHFC@xkvBJRf0C3jkEYAoo/MV5xdBKBZyRf5BopTBl0TFwmHxgECuFQt8Gd6yXkYVTCr2QzJyyeUbqIiEIuyac4T4Nw "JavaScript (Node.js) – Try It Online") [Answer] # Regex (ECMAScript), 34 bytes Input is in unary, in the domain `^x*,x*,x*$` (repeated `x`s delimited by `,`). `^(?!(xx+)\1*,\1+,)(x*)(,\2x+)\3\2$` [Try it online! - SpiderMonkey (Mozilla Firefox) regex engine](https://tio.run/##ZY9Rb9owFIXf8ytCNcn3EpPWTgiByOtTJ/WlD1vfyia5wUm9mSRyTBVK@e3MMLoh7cHX1@fzsc/9KV9lX1rduUnf6ZWy67b5pbYHK76q@m7oAN7E5@vx4QfcjmAYIlyyMV2yiCIMYwS65EctWfJPh/H1G8au/easbmrAuDe6VJDRSYpYVK2FSrACjLBKroxuFCCORLMxpqjEDe50BaMKO292gEXgj1ALE/ed0Q4IJYixUU3tXkYieX/X/YN8ACk6aXt17y310813xA/wfAnYBSgvAfcAd93G9c7C1X3zKo1ehbrxyuIKizMwWJRt43SzUcU@cHa7WwsgA4mt6pR0IDHy8aIL5fk/pfTp19KVL2D9bOeH1@I0/i35Ik2vFiFZkEe78U1IsNiXp@vbv/nInbWtXRyZiQQJJyGJtsX@X8j9gdGczgNOEzr1NUuTLEnZeU@ClDLO/JoGxz3NuRdn0z9NOs8Czyj3lXs3o3Oanxz5jGc5/2iyIPN/sDSY0anXfgM) [Try it online! - .NET regex engine with ECMAScript emulation enabled](https://tio.run/##bVBta9swEP7uX@GYQaRYMZHtOC/C64bpoNCwsQT2oclAcZREoMiuZKcuTv76MtluB2MTSHe65@6e5y7VwzRT7CbpiemcpsxevuqCnepSc3mwkzjJpM4EI91/xarC@84OpaDqvsoV05qbBJIKqrV9qnVBC57a54zv7AXl0gawPlNl6/iTc/sJ7nqgqly4xgO0xi6CoBpAgNZ@EwvW/oebQ5psFUv2YhsaVgHtLcutLpRhBxhp75HJQ3Ec@hC1@Ne8aAR4SXbKuWC7y1/R@2TxeZkqnheQdD1sQfaZAlwWtoxHBIg4MfPQ3SOXDEDYi2UpBJExhjXfA/lxBBPvh@IF6xJaeXksvGUueAH6qA9J04uiLUqJZUryN4W9OLhcegbzVur1G1WagfxptEFZabLhvxDuoO1/IL@DUviuBTgP8kyF2bGi8sDmdj26OkhAwoRm7b6rdoPLbm39qo@ou3VT14eklJruWb3nFduB9EjV4DmuYP38RF3sbjexcTaxmYtcr3/YTHu7xoZCeQ96QYv0CCp456xUabidufOFGt55q@DanBtGUzSzfBSgsXmjMIiCEL/ZwAoR9rG5Y6ux4dQ3wcm4c8JZZBkM@eb1TTVGMzRtK6YTP5r6705kRYYDh9YEjU3sV7oX9KBvw2683w "C# (.NET Core) – Try It Online") ``` # see https://codegolf.stackexchange.com/questions/178303/find-if-a-list-is-an-abc-triple ^ (?! # Verify that A and B are coprime. We don't need to include C in the # test, because the requirement that A+B=C implies that A,B,C are # mutually comprime if and only if A and B are coprime. (xx+)\1*,\1+, # If this matches, A and B have a common factor \1 and aren't coprime. ) (x*)(,\2x+)\3\2$ # Verify that A<B and A+B=C. The first comma is captured in \3 and # reused to match the second comma, saving one byte. ``` The question does say "Three integers, *decimal* written", so this might not qualify (as it takes input in unary), but it makes for such an elegant pure regex that I hope it will at least be appreciated. However, note that if the phrasing is to be literally interpreted, lambda and function submissions that take integer arguments are to be disqualified too, as to strictly adhere to the question's specification they would need to take the input in the form of a string. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 90 bytes ``` n=>new int[(int)1e8].Where((_,b)=>n[0]%++b<1&n[1]%b<1).Count()<2&n[0]+n[1]==n[2]&n[0]<n[1] ``` Runs for numbers up to 1e8, takes about 35 seconds on my machine. Instead of calculating the gcd like others, the function just instantiate a huge array and filter the indexes that aren't divisors of a or b, and check how many elements are left. Next it check if element one plus element two equals element three. Lastly, it checks if the first element is less than the second. [Try it online!](https://tio.run/##bVFBa8MgGL3nV3hpUeLKNNYYorkMduq9hxBGk1oqHQaSdCuU/PZMwxYY5vLxvve@5/vUpn9pejO9320jD6YfpLFDgeu2/SwearKqsPobOK6EriCiRbU7XnWnIfzANXJy@Vpt4riWZGtLUm0cQLu39m4HiCTdejn2glK2pNXcS99PefR16sBN@fPn4CW9eC6cb58EA4FBNuLoP08xSDDYr/GcJTxh5A8kwQzDgFDiS@ifBSao86X7X8QyHs45OwZ0jadrezk@c1dZ30WklAu6oDCNz69AWCCkLsv7xjGPLm2nT80V@qc9u28DNxQdOzPog7EaPuAZoXz6AQ "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 59 bytes ``` (a,b,c)=>Enumerable.Range(2,a).All(i=>a%i+b%i>0)&a<b&a+b==c ``` [Try it online!](https://tio.run/##VY9BDsIgEEX3nqIbG4hjlSmlNEoTF7o23gBIa0iwTVp7/opGTVkAkzf/z3zsuLWjmy9TZ4@ue8LvmL73ddImaiYaDFiq6nM3PZpBG99kN93dG4KgaXbynjhV67XbmLWr9zTVR5PqjVHKzofVbpc8h6lZXYcwlbSEgYSK0sMfIORQxEDwXOScfd982eSQMGTvK/J8GJcY1GXxrXgl3pIQoNV@XCZggJEZME7AoAIZb2UoSxQSf4VYtkX4E@NLUkIRlIHMLw "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [J](http://jsoftware.com/), 27 bytes ``` (+/=2*{:)*({.<1{])*1=+./ .* ``` [Try it online!](https://tio.run/##TY69DsIwDIT3PsWJpW2K0tr5aVqRR2FCRIiFoWPUZw9BkIbB8n3y6c7PFDYvMWHFlLph9Czi2osuygvFay/ID3KEFKlvThJt8LLFGfuKsDXN/fZ4IYDgsBRgKJgKViurNP22KgcNYspzOD@oHWfLbL5CL7YWELgC1wLCAvcf6ma2jos4Emx@kXShGSY70hs "J – Try It Online") Inspired by Jo King's Perl solution [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 68 bytes Without Linq. ``` (a,b,c)=>{var t=a<b&a+b==c;while(b>0){c=b;b=a%b;a=c;}return t&a<2;}; ``` [Try it online!](https://tio.run/##jZBNS8QwEIbv/RXDgkvLxsWm36TpRfAmCB68eEnSUgvdRJJ0Rcr@9pquq@5F2iRMXpiH4WGEuRVKN9NgOtnC86exzYF4omfGwJNWrWaH0QN4H3jfCTCWWfcdVVfDI@ukH8xNgIdBinLolWzRdeVK9RXUQCefIY5EQKvxyDRYykq@ZTtOqSAfb13f@Ly6C0ZBOeGU3XDCXOOkGztoCXbLSkxOZPq2298raVTf7F90Zxu/9mMEIQ7nkgSwg82r3ATE@wd2XI6gWAYxgghBsgpM4yiN4vAnRCs0ZuE4xw7OkkuKi3SVv3t4FYhX@TuwcEtZBs97zjOc5vg3rTBOzxsP42Uyc77z5D8SLsc7uTt9AQ "C# (.NET Core) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü╡v╕7+Pü°╔|g ``` [Run and debug it](https://staxlang.xyz/#p=81b576b8372b5081f8c97c67&i=[1,8,9]%0A[2,3,5]%0A[2,6436341,6436343]%0A[4,121,125]%0A[121,48234375,48234496]%0A%0A[1,1,2]%0A[1,2,5]%0A[1,9,8]%0A[4,12872682,12872686]%0A[6,8,14]%0A[7,5,12]&m=2) [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 43 bytes ``` import StdEnv $a b c=a<b&&a+b==c&&gcd a b<2 ``` [Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4xLJVEhSSHZNtEmSU0tUTvJ1jZZTS09OUUBKGxj9D@4JBGo1FZBRcFQwULB8v@/5LScxPTi/7qePv9dKvMSczOTiwE "Clean – Try It Online") Similar to basically everything else because the direct test is the same. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 30 bytes Saved 2 bytes thanks to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy). ``` (a,b,c)->a<b==gcd(a,b)&&a+b==c ``` [Try it online!](https://tio.run/##Pc5LCoMwEADQqwwuxNBxkY8xgepFxEVMUQQpQbqwp08nIXUT3vwT3Lm3W4grDBAbhwt61o7uuQzD5l8pweraPSj00YVwfJsL2hHCub8/xCoFFXh3HM2KcDGGME0cwSDYmSwQJEJXqJXUUvE/ZEorBC54enJXtjKCqn1XpKzOJWpCEIWirCVaunevMr3QRtzKkzp/iKvknuZSdZ5Z/AE "Pari/GP – Try It Online") [Answer] # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 83 bytes ``` &:&:03p&:04pw>03g04g\:v_1w03g04g+w1.@ 00: [[email protected]](/cdn-cgi/l/email-protection)[^j7 _^;>0.@;j7;>0.@;:%g00\p ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X81KzcrAuABImBSU2xkYpxuYpMdYlcUblkPY2uWGeg5cBgZWCkBgnuWgZxAdl2WuAAbxcdZ2BnoO1lnmENpKNd3AIKbg/39LBQsFQwA "Befunge-98 (FBBI) – Try It Online") The input which is a triple of integers `[A,B,C]` is feeded into Befunge as space-separated integers `C B A`. [Answer] # Mathematica 35 bytes ``` CoprimeQ @@ # && #[[1]] + #[[2]] == #[[3]] & ``` if order is important: ``` CoprimeQ @@ # && Sort[#]==# && #[[1]] + #[[2]] == #[[3]] & ``` or... ``` And[CoprimeQ @@ #, Sort@# == #, #[[1]] + #[[2]] == #[[3]]] & ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~42~~ 41 bytes ``` \d+ $* A`^(11+)\1*,\1+, ^(1+)(,1+\1)\2\1$ ``` [Try it online!](https://tio.run/##NU05DgIxDOz9jkVKNm7Gca6Sik9YaJGgoKFA/D94OYo5PKORn7fX/XGZh3Dapl0TLSsdt3MAUjSsbEhMfqYYGMkQTQzLnODOg4QzF@equWbFTzMpQ@AotKt28bCVr9FRyTsWZ/E1eHD/LHqT2uVvKlX/AaXGxbM3 "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 1 byte thanks to @Deadcode. Explanation: ``` \d+ $* ``` Convert to unary. ``` A`^(11+)\1*,\1+, ``` Check that A and B have no common factor. ``` ^(1+)(,1+\1)\2\1$ ``` Check that A < B and A + B = C. [Answer] # Common Lisp, 51 bytes ``` (lambda(a b c)(and(< a b)(=(+ a b)c)(=(gcd a c)1))) ``` [Try it online!](https://tio.run/##RY/NTsMwEIRfZVQJsSsurOM4DlCOfQJuiINrF6iUNlUbDr341du1G9SDdz7PrH82DtvT4ULDOB7wPR5BAWtExnaPRyKBR88ggwZtVWcb11iZtVHPQozoKnkh640GXXsD27viQ2CqmnqPoIefz/rOOG/@oXQ7fVWsQodWfWakEaS/24UJExZZnhPuBVi@a8kvn6swnDZn5NeP49/0e85f@WGBOhBIZwy7dQrzgBT2id5KyLSkpwqx4E9MuokszHy59SpcAQ) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `g`, 10 bytes ``` ⟨ḣ¯=|Þ⇧|ġṅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBZyIsIiIsIuKfqOG4o8KvPXzDnuKHp3zEoeG5hSIsIiIsIlsxLCAxLCAyXVxuWzEsIDIsIDVdXG5bMSwgOSwgOF1cbls0LCAxMjg3MjY4MiwgMTI4NzI2ODZdXG5bNiwgOCwgMTRdXG5bNywgNSwgMTJdIl0=) Checks if the difference between the last two numbers equals the first one, if its sorted in ascending order, and if the gcd = 1 ]