text
stringlengths
180
608k
[Question] [ Consider a stream/file with one integer per line. For example: ``` 123 5 99 ``` Your code should output the sum of these numbers, that is `227`. The input format is strictly one integer per line. You cannot, for example, assume the input is on one line as an array of integers. You can take input either from STDIN, in form of a filename, or a file with a name of your choice; you can choose which one. No other ways of getting input are allowed. The input will contain at least one integer. You can assume all integers are non-negative and that their total sum is less than `232`. [Answer] ## Bash + coreutils, 16 bytes ``` xargs|tr \ +|bc ``` **[Try it online!](https://tio.run/nexus/bash#@1@RWJReXFNSpBCjoKBdk5T8/7@hkTGXKZelJQA)** There are two spaces after the `\`. This works for negative numbers as well. **Explanation:** ``` xargs # known trick to turn newlines into spaces, while adding a #trailing newline when printing the result (needed for bc) |tr \ + # turn spaces into '+'s |bc # calculates the sum ``` You may wonder why `tr \\n +|bc` isn't better, since it turns newlines directly into '+'s. Well, that has 2 unforeseen errors: * if the input has a trailing newline, then it is converted to a trailing '+', hence there is no number after it to perform the addition * and the most weird issue is that bc requires a trailing newline after the input, but you just replaced all of the input newlines with '+'s. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` |O ``` Explanation: ``` | Get input as array O Sum ``` [Try it online!](https://tio.run/nexus/05ab1e#@1/j//@/oZExlymXpSUA "05AB1E – TIO Nexus") [Answer] # [MATL](https://github.com/lmendo/MATL), 2 bytes ``` Us ``` This expects the input in a text file called `defin`. *Gif or it didn't happen*: [![enter image description here](https://i.stack.imgur.com/a2cpD.gif)](https://i.stack.imgur.com/a2cpD.gif) Or [**try it online!**](https://tio.run/##S0oszvifnFiiYKeQkpqWmfc/P7kksSxVQVe3ILEkQ0E/v6BEPzexJAcokFqWmKOgBOaEFiv9/29oZMxlymVpCQA) (*thanks to Dennis for the set-up!*) ### Explanation When a MATL program is run, if a file called `defin` is found (the name refers to "default input"), its contents are automatically loaded as text and pushed to the stack as a string before executing the code. Function `U` evaluates the string to convert it to a column vector of numbers, and `s` computes the sum, which is implicitly displayed. [Answer] # [Japt](https://github.com/ETHproductions/japt), 2 bytes ``` Nx ``` ### Explanation ``` Implicit: parse STDIN into array of numbers, strings, and arrays N Get the resulting parsed array. x Sum. Implicit: output result of last expression ``` [Try it online!](https://tio.run/nexus/japt#@@9X8f@/oZExlymXpSUA "Japt – TIO Nexus") [Answer] # Paste + bc, 13 bytes ``` paste -sd+|bc ``` Explanation: ``` paste -s Take one line at a time from input d+ Joining by '+' |bc Pass as expression to bc ``` Another shell answer! [Answer] # [Perl 6](https://perl6.org), 13 bytes ``` say sum lines ``` [Try it](https://tio.run/nexus/perl6#@19QWqJQXJqrkJOZl1r8/7@hkTGXKZelJQA "Perl 6 – TIO Nexus") ## Explanation * `lines()` returns a list of lines from `$*IN` or `$*ARGFILES` a “magic” command-line input handle. * `sum(…)` was added to Perl 6 to allow `[+] List` to be optimized for Positionals that can calculate their sum without generating all of their values like `1..100000` (I just thought `sum` was just too cute here to use `[+]` like I normally would) * `say(…)` call the `.gist` method on its input, and prints it with an additional newline. [Answer] # C, 53 bytes ``` r;main(i){for(;~scanf("%d",&i);r+=i);printf("%d",r);} ``` [Answer] # [Python 3](https://docs.python.org/3/), 28 bytes ``` print(sum(map(int,open(0)))) ``` Taken from [this tip](https://codegolf.stackexchange.com/a/70670/12012). I've been told this won't work on Windows. [Try it online!](https://tio.run/nexus/python3#@19QlJlXolFcmquRm1igAWTr5Bek5mkYaALB//@GRsZcplyWlgA "Python 3 – TIO Nexus") [Answer] # [Retina](https://github.com/m-ender/retina), ~~11~~ 7 bytes -4 thanks to Martin Ender ``` .* $* 1 ``` [Try it online!](https://tio.run/nexus/retina#@6@nxaWixWX4/78hlxGXMZcJlwGXJQA "Retina – TIO Nexus") --- Convert to unary: ``` .* $* ``` Count the number of `1`s: ``` 1 ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 20 bytes ``` (([]){[{}]{}([])}{}) ``` [Try it online!](https://tio.run/nexus/brain-flak#@6@hER2rWR1dXRtbXQti1lbXav7/b8hlxGXMZcJlwGXJZQYA "Brain-Flak – TIO Nexus") ## Explanation This is a golf off of [a solution made by Riley in chat](http://chat.stackexchange.com/transcript/message/36243146#36243146). His solution was: ``` ([])({<{}>{}<([])>}{}) ``` If your familiar with Brain-Flak this is pretty self-explanatory. It pushes the stack height and pops one value as it counts down, at the end it pushes the sum of all the runs. It is a pretty good golf but he zeros both `{}` and `([])` however these will have a values that only differ by one so if instead we remove the masks and make one of the two negative they should nearly cancel out. ``` ([])({[{}]{}([])}{}) ``` Since they always differ by one we have the unfortunate circumstance where our answer is always off by the stack height. In order to remedy this we simply move the beginning of the push to encompass the first stack height. ``` (([]){[{}]{}([])}{}) ``` [Answer] # Python 2, 40 bytes ``` import sys;print sum(map(int,sys.stdin)) ``` [Answer] # [Perl 5](https://www.perl.org/), 9 bytes 8 bytes of code + `-p` flag. ``` $\+=$_}{ ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@K8So22rEl9b/f@/oZExlymXpSUA "Perl 5 – TIO Nexus") With `-p`, the input is read one line at a time, stored in `$_` each time. We use `$\` as accumulator, because thanks to `-p` flag, it's implicitly printed at the end. The unmatched `}{` are used so `-p` flag only prints `$\` once at the end instead of printing `$_` and `$\` at each line it reads like it normally does. [Answer] ## R,11 bytes ``` sum(scan()) ``` `scan` takes the input, one number per line. And `sum`, well, sums. [Answer] # Pure Bash, ~~37~~ 36 bytes *Thanks to @KevinCruijssen for a byte!* ``` while read a;do((b+=a));done;echo $b ``` [Try it online!](https://tio.run/nexus/bash#@1@ekZmTqlCUmpiikGidkq@hkaRtm6ipCWTmpVqnJmfkK6gk/f9vaGTMZcplackFAA "Bash – TIO Nexus") [Answer] ## Haskell, 32 bytes ``` interact$show.sum.map read.lines ``` [Try it online!](https://tio.run/nexus/haskell#@5@bmJlnm5lXklqUmFyiUpyRX65XXJqrl5tYoFCUmpiil5OZl1r8/7@hkTGXKZelJQA "Haskell – TIO Nexus"). `interact` collects the whole input from stdin, passes it to the function given as its argument and prints the string it gets back from this function. The function is: ``` lines -- split input into list of lines at nl map read -- convert every line to a number (read is polymorphic, -- but as want to sum it later, the type checker knows -- it has to be numbers) sum -- sum the list of numbers show -- convert back to string ``` [Answer] # PHP, 22 bytes ``` <?=array_sum(file(t)); ``` This assumes there is a file named "t" with a list of integers. `file()` opens a file and returns an array with each line stored a separate element in the array. `array_sum()` sums all the elements in an array. [Answer] # Awk, 19 bytes ``` {s+=$1}END{print s} ``` Explanation: ``` {s+=$1} For all lines in the input, add to s END End loop {print s} Print s ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 14 bytes ``` 0[+?z2=a]dsaxp ``` [Try it online!](https://tio.run/nexus/dc#@28QrW1fZWSbGJtSnFhR8P@/oZExlymXpSUA "dc – TIO Nexus") Explanation: ``` [ ] sa # recursive macro stored in register a, does the following: + # - sum both numbers on stack # (prints to stderr 1st time since there's only 1) ? # - read next line, push to stack as number z # - push size of stack 2 # - push 2 =a # - if stack size = 2, ? yielded something, so recurse # - otherwise end macro (implicit) 0 # push 0 (accumulator) d # duplicate macro before storing it x # Call macro p # The sum should be on the stack now, so print it ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 5 bytes ``` q~]1b ``` [Try it online!](https://tio.run/nexus/cjam#@19YF2uY9P@/oZExlymXpSUA "CJam – TIO Nexus") ### How it works ``` q e# Read all input from STDIN. ~ e# Evaluate that input, pushing several integers. ] e# Wrap the entire stack in an array. 1b e# Convert from base 1 to integer. e# :+ (reduce by sum) would work as well, but 1b handles empty arrays. ``` [Answer] # Python, ~~38~~ 30 bytes ``` lambda n:sum(map(int,open(n))) ``` In python, files are opened by `open('filename')` (obviously). They are, however, iterables. Each time you iterate through the file, you get the next line. So map iterates over each list, calling `int` on it, and then sums the resulting list. Call with the filename as input. (i.e. `f('numbers.txt')`) 8 bytes saved by using `map(int, open(n))` instead of a list comprehension. Original code: ``` lambda n:sum([int(i)for i in open(n)]) ``` [Answer] ## Mathematica, 19 bytes Assumes Mathematica's notebook environment. ``` Tr[#&@@@Import@"a"] ``` Expects the input to be in a file `a`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes ``` ƈFпFỴVS ``` STDIN isn't really Jelly's thing... [Try it online!](https://tio.run/nexus/jelly#@3@sw@3whEP73R7u3hIW/P@/oZExlymXpSUA "Jelly – TIO Nexus") ### How it works ``` ƈFпFỴVS Main link. No arguments. Implicit argument: 0 п While loop; while the condition returns a truthy value, execute the body and set the return value to the result. Collect all results (including 0, the initial return value) in an array and return that array. ƈ Body: Yield a character from STDIN or [] if the input is exhausted. F Condition: Flatten, mapping 0 to [], '0' to "0", and [] to [] (falsy). F Flatten the result. Ỵ Split at newlines. V Evaluate the resulting strings. S Take the sum. ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes ``` ṇịᵐ+ ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9wZ/vD3d0Pt07Q/v9fydDImMuUy9JS6X8UAA "Brachylog – TIO Nexus") ### Explanation ``` ṇ Split the Input on linebreaks ịᵐ Map: String to Integer + Sum ``` [Answer] # Pure bash, 30 ``` read -d_ b echo $[${b//' '/+}] ``` [Try it online.](https://tio.run/nexus/bash#@1@UmpiioJsSr5DElZqcka@gEq1SnaSvr86lrq9dG/v/v6GRMZcpl6UlAA) * `read`s the input file in one go into the variable `b`. `-d_` tells `read` that the line delimiter is `_` instead of `newline` * `${b//'``newline``'/+}` replaces the newlines in `b` with `+` * `echo $[ ... ]` arithmetically evaluates the resulting expression and outputs it. [Answer] # Vim, 16 bytes/keystrokes ``` :%s/\n/+ C<C-r>=<C-r>"<C-h> ``` Since V is backwards compatible, you can [Try it online!](https://tio.run/nexus/v#@2@lWqwfk6evzeVs46xbZGcLJpWAZIYd1///hlxGXMZcJlwGXBb/dcsA "V – TIO Nexus") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 3 bytes ``` s.Q ``` [Try it online!](https://tio.run/nexus/pyth#@1@sF/j/v6GRMZcpl6UlAA "Pyth – TIO Nexus") ``` .Q Read all of standard input, evaluating each line. s Take the sum. ``` [Answer] # [jq](https://stedolan.github.io/jq/), 5 bytes `add`, plus the command line flag `-s`. For example: ``` % echo "1\n2\n3\n4\n5" | jq -s add 15 ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 2 bytes ``` kΣ ``` [Try it online!](https://tio.run/nexus/actually#@599bvH//4ZGxlymXJaWAA "Actually – TIO Nexus") Explanation: ``` kΣ (implicit input - read each line, evaluate it, and push it to the stack) k pop all stack elements and push them as a list Σ sum (implicit output) ``` [Answer] # dc, 22 ``` [pq]sq0[?z2>q+lmx]dsmx ``` This seems rather longer than it should be, but it is tricky to decide when the end of the file is reached. The only way I can think of to do this is check the stack length after the `?` command. [Try it online](https://tio.run/nexus/dc#@x9dUBhbXGgQbV9lZFeonZNbEZtSnFvx/7@hkTGXKZelJQA). ``` [pq] # macro to `p`rint top-of-stack, then `q`uit the program sq # save the above macro in the `q` register 0 # push `0` to the stack. Each input number is added to this (stack accumulator) [ ] # macro to: ? # - read line of input z # - push stack length to stack 2 # - push 2 to the stack >q # - if 2 > stack length then invoke macro stored in `q` register + # - add input to stack accumulator lmx # - load macro stored in `m` register and execute it d # duplicate macro sm # store in register `m` x # execute macro ``` Note the macro `m` is called recursively. Modern `dc` implements tail recursion for this sort of thing, so there should be no worries about overflowing the stack. [Answer] # Ruby, ~~19~~ 15 bytes Loving that new `#sum` in Ruby 2.4 :) ``` p$<.sum(&:to_i) ``` This program accepts input from either stdin or any filename(s) given as command line argument ]
[Question] [ # Goal You have to print the ASCII printable characters' code page (0x20-0x7E). The output should look like this: ``` !"#$%&'()*+,-./ 0123456789:;<=>? @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\]^_ `abcdefghijklmno pqrstuvwxyz{|}~ ``` # Rules * The output should be **exactly** like shown above, but trailing whitespace is OK. * **No builtins that trivialize the question** *(e.g. the ones that print the ASCII table)* **!** They can be posted for documentation purposes, but will not be in the leaderboards. * Standard rules for I/O and loopholes apply. * Lowest bytecount wins. ## Good Luck! *P.S. This challenge is well-known, but a straight "print every single printable ASCII character" has somehow never been done here.* [Answer] # [Python 3](https://docs.python.org/3/), 42 bytes ``` print(('%c'*16+'\n')*6%(*range(32,127),9)) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ0NdNVldy9BMWz0mT11Ty0xVQ6soMS89VcPYSMfQyFxTx1JT8/9/AA "Python 3 – Try It Online") Includes a trailing tab on the last line and a trailing newline. [Answer] # [Python 3](https://docs.python.org/3/), 52 bytes ``` for i in range(95):print(chr(i+32),end='\n'[~i%16:]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFTITNPoSgxLz1Vw9JU06qgKDOvRCM5o0gjU9vYSFMnNS/FVj0mTz26LlPV0MwqVvP/fwA "Python 3 – Try It Online") [Answer] # [Prelude](https://esolangs.org/wiki/Prelude), ~~50~~ 42 bytes ``` 88+ 6(1-) v^^( 1-++!)^6-!) 1- v+(1-) v(1- ``` [Try it online!](https://tio.run/##KyhKzSlNSf3/38JCm8tMw1BXU6EsLk5DQcFQV1tbUTPOTFdRk8tQV6FMGyIHJP//BwA "Prelude – Try It Online") ### Explanation ``` 88+ 6(1-) 1- v+ ``` Push \$16\$ to Voice 1 and \$95\$ to Voice 3. ``` v^^ (1-) ``` For each value from \$95\$ down to \$1\$, push that value and two copies of \$16\$ to Voice 2. When the loop ends, the stack in Voice 2 is `[..., 0, 0, 0, 95, 16, 16, 94, 16, 16, ..., 1, 16, 16]`. ``` ( 1-++! ) ``` For each triplet of values in Voice 2, sum them and subtract \$1\$, then print the result as an ASCII character... ``` ) v(1- ``` in groups of 16... ``` ^6-! ``` with a newline appended to each group. Printing fails on the (non-existent) 96th character because the triplet of values summed is `[0, 0, 0]`, with the result that the code attempts to convert \$-1\$ to ASCII and thus exits with an out-of-range error. --- # [Fugue](https://esolangs.org/wiki/Fugue) [![Fugascii](https://i.stack.imgur.com/Ns83N.png)](https://i.stack.imgur.com/Ns83N.png) Fugue is a musical encoding for Prelude. *Fugascii*\*, a short trio for woodwinds, was generated from the Prelude code above using a script that I wrote for this purpose. Read all about it in [this answer](https://codegolf.stackexchange.com/a/242799/92901). \* The title is a pun on a previous Fugue composition of mine, [*Fugacity*](https://codegolf.stackexchange.com/a/242799/92901). [Answer] # [Zsh](https://www.zsh.org/), 26 bytes ``` printf %s {\ ..~}|fold -16 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuha7Cooy80rSFFSLFapjFPT06mpr0vJzUhR0Dc0gCqDqYOoB) [Answer] # [R](https://www.r-project.org/), 35 bytes ``` write(intToUtf8(32:126,T),1,16,,"") ``` [Try it online!](https://tio.run/##K/r/v7wosyRVIzOvJCQ/tCTNQsPYyMrQyEwnRFPHUMfQTEdHSUnz/38A "R – Try It Online") [Answer] # [Rust](https://www.rust-lang.org), 58 bytes ``` ||for i in' '..''{print!("{: <1$}",i,i as usize%16/15+1)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqLS4ZMGmtDyF3MTMPA3NaoWc1BKFNAXbpaUlaboWN61qatLyixQyFTLz1BXU9fTU69WrC4oy80oUNZSqrbhsDFVqlXQydTIVEosVSoszq1JVDc30DU21DTVrISYst1ZI09CsVYDwFiyA0AA) ## Explanation * The answer is a closure expression implementing the `Fn()` trait. * `print!` can pad outputs to a given length: `print!("{:x<5}", 'a')` → `axxxx` * The length can come from an argument: `print!("{:x<1$}", 'a', 5)` → `axxxx` * The padding char can be a raw newline in place of the `x` in this example. * In my program, the length is either 1 (just the char) or 2 (char + newline). [Answer] # MS-DOS (.COM format), ~~33~~ ~~30~~ 26 bytes * -3 thanks to Deadcode * -4 by using `INT 29H` to output Iterates through 20H and 7EH, printing each character and a line break between the 16th character of each line. ``` 0000 B0 20 CD 29 40 3C 7F 74 10 A8 0F 75 F5 50 B0 0A 0010 CD 29 B0 0D CD 29 58 EB E9 C3 ``` Assembly version (TASM): ``` IDEAL P8086 MODEL TINY CODESEG ORG 100H MAIN: MOV AL,20H ; Start at ' ' PRINT: INT 29H ; Print character INC AX ; Increment character CMP AL,7FH ; Done? JZ DONE ; Yes, exit TEST AL,0FH ; End of line? JNZ PRINT ; No, next character PUSH AX ; Save current character MOV AL,0AH ; Print CR+LF INT 29H MOV AL,0DH INT 29H POP AX ; Restore current character JMP PRINT ; Next character DONE: RET END MAIN ENDS ``` [Answer] # [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), ~~87~~ 82 bytes (3×28=84 codels) *Thanks @Bubbler for -5 bytes by changing `4 dup * 2 *` to a more space efficient `8 4 *`* ``` eeeumtqcsqrrjlvuddtrjcqdjes_eeeu ?????rr?jujrnvmsjiqqc _eeuu kdvtrbbbbb???vv qq? ``` [Try Piet online!](https://piet.bubbler.one/#eJxVTdEKwjAM_Jc8X6FZV237K6MPMisMpg6mT-K_m2QyWHOQXi65-9D4vDYqw8BnbIhghkcPjgjSOqmEE1iVTuFtInKvLOlRAKeKg0mW0QFqJC2JqET2NCmogcZZoF3tRnHzyZZrsdwfsdtr5T_MK22kVtDaFirknCPQPN3lz16esLaOVG6XeW2g6bG8X6LR9wfYpTr-) Might add a more detailed explanation later if I feel like to, but here's an explanation image generated by Bubbler's Piet interpreter for now. Can 100% be golfed, but I'm too lazy to do that right now lol. ### Explanation image [![](https://i.stack.imgur.com/lrORO.png)](https://i.stack.imgur.com/lrORO.png) The basic algorithm is to initially push `32` to the stack, then keep incrementing and outputting the character until `127`, after which the code stops. At each iteration, it checks if the number+1 is a multiple of 16, and prints a newline if it is. ### Longer explanation Here's the ascii piet version of the code, with newlines added for clarity: ``` eeeumtqcsqrrjlvuddtrjcqdjes_ eeeu ?????rr?jujrnvmsjiqqc _ eeuu kdvtrbbbbb???vv qq? ``` I'll be going over the code section by section. Initialization: ``` eeeum eeeu eeuu ``` Push 8, Push 4, multiply. This puts `32` onto the stack (the codepoint for space) Top half of the loop: ``` tqcsqrrjlvuddtrjcqdje ``` What it does: ``` Commands Stack DP, CC dup [32,32] right left out (char) [32] right left 1 + Dup [33,33] right left 4 dup * dup * 2 / 1 - [33,33,127] right left - ! ! [33,1] right left DP+ [33] down left ``` Basically, it adds `1` to the current codepoint and checks if it is equal to `127`. If it is, then `DP+` will turn the pointer `0` times and terminate the code. Otherwise, `DP+` will turn the pointer `1` time and continue the loop. Bottom right portion of the loop: ``` ?jujrnvmsjiqqc ???vv qq? ``` What it does: ``` Command Stack DP, CC dup [33,33] down left 4 dup * [33,33,16] left right % [33,1] left right ! 3 * [33,0] left right 1 CC+ [33,0] left left DP+ [33] left right ``` This checks if the current codepoint is a multiple of 16 (remember that we added 1 to the codepoint in the top half of the loop). If it is a multiple of 16, then `DP+` will turn the DP to face downwards. Otherwise, the DP stays facing left. This is based on the observation that all the characters before a newline all have codepoints that are 1 less than a multiple of 16. For example, let's say that at the beginning of this portion, the stack is `[48]`. This means that the ascii `47`, or `/`, just got printed, and then that value was incremented by `1` from the top half of the loop. After taking this value modulo 16 and applied `!` on the value, the stack becomes `[48,1]`. The `1` on the stack is then multiplied by `3` which causes `DP+` to turn the DP 3 times, resulting in the DP facing down. Bottom branch of the loop: ``` t ? kdvtrbbbbb ``` What it does: ``` Command Stack DP, CC 1 5 dup + [33,1,10] left right out (char) pop [33] left right ``` Basically just prints out a newline. Top branch of the loop: ``` t rr ?????rr? ``` Nothing actually happens here. The code just passes through and enters back into the loop. One thing to note is that the reason why we did `CC+` earlier was to get through the `r` block. Before the `CC+`, the CC was facing right, but that poses a problem when we go through the `r` block, because the code will continue execution through the top left of the block, which will break the entire code. Instead, we toggle the CC once to switch it to the left, which causes the code to exit out of the block from the bottom left. Once the top half is entered again, `dup out (char)` is ran, printing out another character, and the loop continues. Loop exit: ``` s_ _ ``` Once the loop reaches `127`, the loop is exited. `s` is essentially a noop that does nothing, and the program terminates in the `_` block. [Answer] # [Python 3](https://docs.python.org/3/), 71 bytes *-2 bytes thanks to @pxeger* ``` for i in range(6):print(''.join(chr(j+i*16+32)for j in range(16-i//5))) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFTITNPoSgxLz1Vw0zTqqAoM69EQ11dLys/M08jOaNII0s7U8vQTNvYSBOkOguh2tBMN1Nf31RTU/P/fwA "Python 3 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 66 bytes ``` for i in range(6):print bytearray(j+i*16+32for j in range(16-i/5)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWN53S8osUMhUy8xSKEvPSUzXMNK0KijLzShSSKktSE4uKEis1srQztQzNtI2NQEqzEEoNzXQz9U01NSEmQQ2EGQwA) Based on @mousetail's solution; submitted as my own answer by their suggestion. [Answer] # Rust, ~~74~~ ~~72~~ ~~70~~ 64 bytes ``` (' '..'').any(|i|print!("{i}")>if i as u8%16>14{print!(" ")}); ``` Text contains non-printable characters so might not render correctly. @Antiip saved me some bytes. [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqLS4ZMHqtDyF3MTMPA1NheqlpSVpuhY3HTTUFdT19NTr1TX1EvMqNWoyawqKMvNKFDWUqjNrlTTtMtMUMhUSixVKLVQNzewMTaph0lxKmrWa1lwQcxbWQugFCyA0AA) [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~110~~ 100 bytes ``` [S S S T T T T T N _Push_31][N S S N _Create_Label_LOOP][S S S T N _Push_1][T S S S _Add][S N S _Duplicate][S S S T T T T T T T N _Push_127][T S S T _Subtract][N T S T N _If_0_Jump_to_undefined_Label][S N S _Duplicate][T N S S _Print_as_character][S N S _Duplicate][S S S T S S S S N _Push_16][T S T T _Modulo][S S S T T T T N _Push_15][T S S T _Subtract][N T T N _If_neg_Jump_to_Label_LOOP][S S S T S T S N _Push_10_\n][T N S S _Print_as_character][N S N N _Jump_to_Label_LOOP] ``` 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/##PYxBCoBADAPPySvyNZEF9yYo@PyaxsUeQjsZ@hzzHte57aNKEnpIiX0QzqxfgZAO0Bj823jGWOryYhi7y0@y6gU) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** ``` Integer n = 31 Start LOOP: n = n + 1 If (n==127): Stop program with error by jumping to undefined Label Print n as character to STDOUT If (n modulo 16 < 15): Go to next iteration of LOOP Print '\n' Go to next iteration of LOOP ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~64~~ 86 bytes ``` +++++[>++>++++++>+<<<-]>>++>+[-[>+<[->>+<<]]>>[-<<+>>]<+++++++++++++++[<<.+>>-]<<<.>>] ``` [Try it online!](https://tio.run/##VYvBCcAwDAMHMs4EQosYP5pAoRT6KGR@V8mv@kjcof4e13POcVfZStCMe6kAeHKTcBmEc9EUDAeMTNg/ATRxT52bfNUH "brainfuck – Try It Online") No longer prints 0x7f as the last character. With many thanks to @Jiří for the fix. [Answer] # x86-32 machine code (Linux executable) 27 bytes cut-down NASM listing: Address | machine code | source ``` global _start _start: ; Linux processes (and thus static executables) start with registers zeroed, except ESP asciitable: 00 B020 mov al, ' ' 02 B20A mov dl, 0xa 04 89E7 mov edi, esp ; space above ESP on the stack is argc, argv[] and env[] array elements, and the env strings. We overwrite that. .loop: 06 AA stosb 07 40 inc eax ; there is no branch condition for AF, the half-carry flag :/ 08 A88F test al, 0x8f ; detect mod16 and when we've gone past printable 0A 7503 jnz .nonewline 0C 92 xchg eax, edx 0D AA stosb 0E 92 xchg eax, edx .nonewline: ; FLAGS still set from earlier TEST 0F 79F5 jns .loop ; stop at 0x80, beyond what the syscall uses ; mov [edi-1], 0xa ; no trailing newline 11 B004 mov al, 4 ; __NR_write ; ebx=0 from process startup; writing to stdin happens to work on a terminal 13 89E1 mov ecx, esp 15 8D5060 lea edx, [eax-4 + 0x7f-0x20 + 5] ; exclusive range, 5 newlines; final line does not end with newline as whitespace isn't required 18 CD80 int 0x80 ; write(0, ecx, 100) ; mov eax,1 ; exit(ebx) ; int 0x80 1A CC int3 ; abort program ``` Fill bytes into a buffer (overwriting stack memory above ESP, starting with argc, argv[], and into env[]). We go a bit beyond 0x7e because that makes the stop condition cheaper, but those bytes aren't printed: we have to generate an explicit length in EDX anyway, so we just omit it. We make one `write(0, buf, 100)` system call. `0` is STDIN\_FD, but on a normal xterm/konsole/gnome\_terminal, FD 0,1, and 2 are all read+write duplicates of the same file description. So we save 1 byte for `inc ebx`. If you want to pipe the output into something to hexdump for example, `./asciitable 0>&1 | hexdump -C` Instead of existing cleanly, we use `int3` to raise a debug exception, resulting in the OS delivering SIGTRAP, killing the process. A typical shell will then print `Trace/breakpoint trap (core dumped)`, but that's the shell, not this program. This saves 3 bytes vs. `mov al, 1` / `int 0x80` (the upper bytes of EAX are zeroed, unless `write` returned an error). I considered letting execution just fall off the end (to probably `00 00` padding added by the linker, which decodes as `add [eax], al` and will segfault), but we're already stretching things a bit by only counting the `.text` section of the executable, not the whole file size. (Unlike a DOS `.com`, there *is* metadata) Our output doesn't end with a newline; as the question says, no trailing whitespace is required after the `0x7e` `~` character. The mod16 detection via checking the low bits 4 of AL is fairly straightforward, but was borrowed from ErikF's [the x86-16 MS-DOS answer](https://codegolf.stackexchange.com/questions/249247/print-the-ascii-code-page/249314#249314) which I read first before thinking about how I'd do it. But to enable a `jns` as the loop branch without a separate `cmp`, we also set the MSB in our mask for `test`. That's not a spot we wanted a newline anyway. I'd hoped to be able to branch on FLAGS from `inc al` (2 bytes), but since we'd also need something for newlines, this is even better: we can now use `inc eax` (1 byte) and still branch on the MSB of AL. Using mov dl, 0xa (2B) / xchg/stosb/xchg (1B each) instead of `mov byte [edi], 0xa` (3 bytes) / `inc edi` (1 byte but clobbers FLAGS) was the key to that, saving another `test` or `cmp` for a net saving of 1 byte. Demo: ``` $ nasm -felf32 asciitable.asm $ ld -melf_i386 -o asciitable asciitable.o $ ./asciitable !"#$%&'()*+,-./ 0123456789:;<=>? @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\]^_ `abcdefghijklmno pqrstuvwxyz{|}~Trace/breakpoint trap (core dumped) $ ./asciitable 0>&1 | cat # suppresses signal diagnostic from shell !"#$%&'()*+,-./ 0123456789:;<=>? @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\]^_ `abcdefghijklmno pqrstuvwxyz{|}~peter@volta:/tmp$ $ ./asciitable 0>&1 | hexdump -C 00000000 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f | !"#$%&'()*+,-./| 00000010 0a 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e |.0123456789:;<=>| 00000020 3f 0a 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d |?.@ABCDEFGHIJKLM| 00000030 4e 4f 0a 50 51 52 53 54 55 56 57 58 59 5a 5b 5c |NO.PQRSTUVWXYZ[\| 00000040 5d 5e 5f 0a 60 61 62 63 64 65 66 67 68 69 6a 6b |]^_.`abcdefghijk| 00000050 6c 6d 6e 6f 0a 70 71 72 73 74 75 76 77 78 79 7a |lmno.pqrstuvwxyz| 00000060 7b 7c 7d 7e |{|}~| 00000064 $ strace ./asciitable 0>/dev/null execve("./asciitable", ["./asciitable"], 0x7ffc63d167c0 /* 55 vars */) = 0 [ Process PID=2670503 runs in 32 bit mode. ] strace: WARNING: Proper structure decoding for this personality is not supported, please consider building strace with mpers support enabled. write(0, " !\"#$%&'()*+,-./\n0123456789:;<=>"..., 100) = 100 --- SIGTRAP {si_signo=SIGTRAP, si_code=SI_KERNEL} --- +++ killed by SIGTRAP (core dumped) +++ Trace/breakpoint trap (core dumped) ``` [Try it online!](https://tio.run/##XVPBbhMxEL37K96tIJKQ0lagRD0gQSSkChAgcYiiyGvPbky99mJ7m01/vh17k7awh13P2H7z5s1bGSO1lT1Maxnbh4fah1YmfL5ZgQZSfZKVJVwIiGVjfSUttjHJkMT4WeDFs8SNcf2ALnhFDBvxSjqNtOsj@HQy6gVmfI2CgL1JOwRqTEwUIu4peNITPqmoYyI/vwsZlTHl0kKg9XeQdoIznI2B5mA@yDEgbfhq7E6EYicVQVb@jjIUvGM6lCurW5gIGRo1ye@79QaZLLmyCkEeQJZacilOMLZBeZfvBuOaOAN@Exg37INJxNsyzcTMet8xy5h8rASMUwDJ4V@VGClQru48qiCd2kF5p00yTI8HgI@rSSm3k7aeKiZzQG1lg8VbgUQxFQHmw4da4I@7x8x5R3trHAkMateUkiyDHp6I/JdeFrGqA/Nes2SbUcHlka824hlywemnmtLmihEofR5hjmzy/bGaeE5floa3268/tkUmwRFVw/UcdfDtySmjE/puiXyI1UXynNPGsQRdR1yRE3sfbvMAJfMJrXFMJvNluJOwq0@4xjngiDTpIuWvL99moXdHSqSGYg8BSzJ3yuGaVZle4g238L6ezod3c15fbTIee9D20bB3eEoNTXCFoypxiTozQA6gPeVhJvaHHv18PAYZsd9x36MPTXRnib3@tzeBdLZHQp7jXJykzBM6L92UaZy28/IiM2In8y/DsjVB8t/6CA "Assembly (fasm, x64, Linux) – Try It Online") with an `inc ebx` added so it writes to stdout and thus shows up in the tio.run output pane. IDK why it didn't show in the debug pane. (32-bit code supported by having FASM make an executable directly, instead of NASM.) ## TODO: a function instead of program, filling a buffer We'd obviously save the syscall code, but could no longer write past the end of the actual stop point. So would need maybe 1 more byte in the loop to go back to `cmp al, 0x7e` / `jne` as the loop condition. [Answer] # x86-16 machine code, PC DOS, ~~24~~ 19 bytes ``` 00000000: b020 bb0a 0daa 40a8 0f75 0393 ab93 3c7e . [[email protected]](/cdn-cgi/l/email-protection)....<~ 00000010: 7ef3 c3 ~.. ``` Listing: ``` B0 20 MOV AL, 20H ; starting codepoint BB 0D0A MOV BX, 0D0AH ; CR/LF chars CP_LOOP: AA STOSB ; write AL to buffer 40 INC AX ; increment to next char A8 0F TEST AL, 0FH ; is end of line? 75 03 JNZ CP_NEXT ; jump if so 93 XCHG AX, BX ; save current codepoint AB STOSW ; write CR/LF to buffer 93 XCHG AX, BX ; restore codepoint CP_NEXT: 3C 7E CMP AL, 07EH ; <= 7EH? 7E F3 JLE CP_LOOP ; if so, keep looping C3 RET ; return to caller ``` [![enter image description here](https://i.stack.imgur.com/LHxZN.png)](https://i.stack.imgur.com/LHxZN.png) Using @PeterCordes's suggestion to write to an output buffer instead of direct to console. Callable function, output to string buffer `ES:[DI]`. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~21~~ 17 bytes -4bytes thanks to Traws! ``` `0:`c$6 16#32+!95 ``` It's my first answer in K! So there might be some optimizations ^^ ``` `0:`c$6 16#32+!95 32+!95 / Creates an array from 32 to 126 6 16# / Reshapes it to 16 columns and 6 lines (16 can me replaced by 0N) `c$ / For each elements of this array/matrix, convert the int to a char `0: / Print the result whitout ( and " ``` [Try it online!](https://ngn.codeberg.page/k/#eJxLMLBKSFYxUzA0UzY20la0NAUAJKADsQ==) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) **Without builtin:** ``` ₃L31+çJ6ä» ``` [Try it online.](https://tio.run/##yy9OTMpM/f//UVOzj7Gh9uHlXmaHlxza/f8/AA) **With builtin (5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)):** ``` žQ6ä» ``` [Try it online.](https://tio.run/##yy9OTMpM/f//6L5As8NLDu3@/x8A) **Explanation:** ``` ₃L # Push a list in the range [1,95] 31+ # Add 31 to each ç # Convert the codepoint-integers to ASCII characters J # Join the list together to a string 6ä # Split it into 6 parts » # Join by newlines # (after which the result is output implicitly) žQ # Push a string of all ASCII characters 6ä» # Same as above ``` [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 18 bytes ``` @!~r@' +]16co)++un ``` [Try it online!](https://tio.run/##SyotykktLixN/V9W9t9Bsa7IQV1BO9bQLDlfU1u7NO9/4H8A "Burlesque – Try It Online") ``` @!~ # Push ! and ~ to stack r@ # Range between them ' +] # Prepend " " 16co # Chunks of 16 )++ # Concat un # Intercalate newlines between blocks and join ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 35 bytes ``` -join(' '..'~')-split'(.{16})'-ne'' ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/f9fNys/M09DXUFdT0@9Tl1Tt7ggJ7NEXUOv2tCsVlNdNy9VXf3/fwA "PowerShell Core – Try It Online") ``` (' '..'~') # create a list of characters from <space> to ~ -join # join the list to a single string -split'(.{16})' # split the string every 16 chars ... -ne'' # ... and let only non-empty strings pass. ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 12 bytes ``` 6‿16⥊' '+↕95 ``` [Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=NuKAvzE24qWKJyAnK+KGlTk1) Output has a trailing space character. BQN's [affine character space](https://mlochbaum.github.io/BQN/tutorial/expression.html#character-arithmetic) is quite neat here: adding a number to a character gives another character. So: create a range from zero to 95 (`↕95`), add it to the space character (`' '+`), and reshape to 6-row, 16-column format (`6‿16⥊`). --- # [BQN](https://mlochbaum.github.io/BQN/), 26 bytes ``` @+100⥊⍉(32+⍉6‿16⥊↕95)∾6⥊10 ``` [Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=QCsxMDDipYrijYkoMzIr4o2JNuKAvzE24qWK4oaVOTUp4oi+NuKlijEwCg==) Longer version with output string that is truly "**exactly** like shown above", written before the edit allowing trailing whitespace. Creates a transposed array of character values (`32+⍉6‿16⥊↕95`), appends a newline value 10 to each column (`∾6⥊10`), re-transposes (`⍉`) & extracts the first 100 values (`100⥊`), and finally converts to characters (`@+`). [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), 10 bytes ``` ¬ ~5ñ16|á ``` [Try it online!](https://tio.run/##K/v//9AahTrTwxsNzWoOL@T6/x8A "V (vim) – Try It Online") Explanation: ``` ¬ # Insert characters between the code points... ~ # "space" and "~" 5ñ # 5 Times... 16| # Go to the 16th character on this line á<cr> # Append a newline ``` Hexdump: ``` 00000000: ac20 7e35 f131 367c e10d . ~5.16|.. ``` [Answer] # [Perl 5](https://www.perl.org/), 30 bytes ``` say map$/x!($_%16).chr,32..126 ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIhN7FARb9CUUMlXtXQTFMvOaNIx9hIT8/QyOz//3/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online") [Answer] # [sed](https://www.gnu.org/software/sed/) `-r`, 94 bytes ``` s/.*/ABCDEFGHIJKLMNO\nPQRSTUVWXYZ/ saa !"#$%\&'()*+,-./\n0123456789:;<=>?\n@&[\\]^_\n`\L&{|}~a ``` [Try it online!](https://tio.run/##K05N@f@/WF9PS9/RydnF1c3dw9PL28fXzz8mLyAwKDgkNCw8IjJKn6s4MVFBUUlZRTVGTV1DU0tbR1dPPybPwNDI2MTUzNzC0sraxtbOPibPQS06JiY2Lj4mLyHGR626prYu8f//f/kFJZn5ecX/dYsA "sed 4.2.2 – Try It Online") This is probably the best that can be done in sed, which has no functionality for ranges of characters. The main byte saving is in the fact we can generate `ABCDEFGHIJKLMNOPQRSTUVWXYZ` and then use `\L` to get the lowercase version. [Answer] # PHP, ~~43~~ 40 bytes ``` <?=chunk_split(join(range(' ','~')),16); ``` Simply outputs the expected text, without any trailing newlines. Just run `php file.php` and it should produce the output. Try it on: <https://onlinephp.io/c/013ce> --- Thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan) for -3 bytes. [Answer] # [Vyxal 2.14.1](https://github.com/Vyxal/Vyxal), 9 bytes ``` kPð+s16ẇ⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrUMOwK3MxNuG6h+KBiyIsIiIsIltdIl0=) So turns out `kP` isn't *actually* all of printable ascii - it's missing the space character, and it isn't in the right order either, meaning that for the purposes of this challenge, it shouldn't be banned, as it doesn't print "the ascii table" and it isn't exactly "trivial" either. (And if it isn't allowed, then that's grounds enough for VTCing this challenge as needs details or clarity, because "trivialising the challenge" isn't objectively defined - there's an argument to be made that `kPð+s` isn't a trivial built-in). ## Explained ``` kPð+s16ẇ⁋ kPð+ # a string of 0-9a-Z + python's string.punctuation + space s # sorted to be in printable ascii order 16ẇ # split into parts of length 16 ⁋ # joined on newlines ``` ## [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` kP6/⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrUDYv4oGLIiwiIiwiW10iXQ==) Bug fixes make this 5 bytes in reality. [Answer] # [R](https://www.r-project.org/), 38 bytes ``` intToUtf8(rbind(matrix(32:126,16),10)) ``` [Try it online!](https://tio.run/##K/qfWJycmRlfkpiUk2r7PzOvJCQ/tCTNQqMoKTMvRSM3saQos0LD2MjK0MhMx9BMU8fQQFPzf3JiiQaSPs3/AA "R – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 12 bytes ``` 6 16⍴' '…'~' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94L@ZgqHZo94t6grqjxqWqdepg0T/FwAA "APL (Dyalog Extended) – Try It Online") `' '…'~'` inclusive range from space to tilde `6 16⍴` cyclically **r**eshape into the required number of rows and columns [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 10 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ♣⌡╒T≥$y☻/n ``` [Try it online.](https://tio.run/##ASAA3/9tYXRoZ29sZv//4pmj4oyh4pWSVOKJpSR54pi7L27//w) **Explanation:** ``` ♣ # Push 128 ⌡ # Decrement it by 2 to 126 ╒ # Pop and push a list in the range [1,126] T # Push 31 ≥ # Pop and remove the first 31 items from the list $ # Convert each codepoint-integer to a character y # Join the list to a string ☻ # Push 16 / # Pop and split the string into parts of size 16 n # Join the list by newlines # (after which the entire stack is output implicitly as result) ``` [Answer] # [jq](https://stedolan.github.io/jq/) `-nr`, 39 bytes ``` [range(32;127)]|implode|scan(".{1,16}") ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70oq3B5tJJuXpFS7IKlpSVpuhY31aOLEvPSUzWMjawNjcw1Y2sycwty8lNSa4qTE_M0lPSqDXUMzWqVNCHKoboWQGkA) The best I can do without regex is 40 bytes: ``` 16*range(2;8)|[.+range(16-./99)]|implode ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70oq3B5tJJuXpFS7IKlpSVpuhY3NQzNtIoS89JTNYysLTRrovW0ITxDM109fUtLzdiazNyCnPyUVIh6qLYFUBoA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` UT⪪⪫…· ¦~ω¹⁶ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8kPz09JzWkKDNXQ9OaK6AoM69EI7ggJ7NEwys/M0/DMy85p7Q4syw1KDEvPVVDSUFJR0GpTklTR6EciA3NNDWt////r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` UT ``` Disable automatic padding (would normally output a trailing space on the last line). ``` ⪪⪫…· ¦~ω¹⁶ ``` List the characters from to `~` inclusive, join them together, split into groups of 16, and implicitly print each group on its own line. Save 6 bytes by using the builtin `γ` in place of `⪫…· ¦~ω`. [Try it online!](https://tio.run/##S85ILErOT8z5/z8kPz09JzWkKDNXQ9OaK6AoM69EI7ggJ7NEQ0lBMUZJWUVVTV1DU0tbR1dP38DQyNjE1MzcwtLK2sbWzt7B0cnZxdXN3cPTy9vH188/IDAoOCQ0LDwiMio6JiY2Lj4hMSk5JTUtPSMzKzsnNy@/oLCouKS0rLyisqq6prZOSUfB0ExT0/r///@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. ]
[Question] [ # Description Subtract the next P numbers from a N number. The next number of N is N + 1. Look at the examples to get what I mean. # Examples: ``` Input: N=2,P=3 Calculate: n - (n+1) - (n+2) - (n+3) //Ending with 3, because P=3 Calculate: 2 - 2+1 - 2+2 - 2+3 //Replacing N with 2 from Input Calculate: 2 - 3 - 4 - 5 Output: -10 Input: N=100,P=5 Calculate: n - (n+1) - (n+2) - (n+3) - (n+4) - (n+5) Calculate: 100- 101 - 102 - 103 - 104 - 105 Output: -415 Input: N=42,P=0 Calculate: n Calculate: 42 Output: 42 Input: N=0,P=3 Calculate: n - (n+1) - (n+2) - (n+3) Calculate: 0 - 1 - 2 - 3 Output: -6 Input: N=0,P=0 Calulate: n Calculate: 0 Output: 0 ``` # Input: **N**: Integer, positive, negative or 0 **P**: Integer, positive or 0, not negative # Output: Integer or String, leading 0 allowed, trailing newline allowed # Rules: * No loopholes * This is code-golf, so shortest code in bytes wins * Input and Output must be as described [Answer] # Python 2, ~~26 24~~ 23 bytes -2 bytes thanks to @Adnan (replace `p*(p+1)/2` with `p*-~p/2`) -1 byte thanks to @MartinEnder (replace `-p*-~p/2` with `+p*~p/2` ``` lambda n,p:n-p*n+p*~p/2 ``` Tests are on [**ideone**](http://ideone.com/gRzpwa) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5~~ 3 bytes Saved 2 bytes thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) ``` Ý+Æ ``` **Explanation** Takes P then N as input. ``` # implicit input, ex 5, 100 Ý # range(0,X): [0,1,2,3,4,5] + # add: [100,101,102,103,104,105] Æ # reduced subtraction: 100-101-102-103-104-105 ``` [Answer] ## CJam, 8 bytes ``` {),f+:-} ``` [Test suite.](http://cjam.aditsu.net/#code=2%203%0A100%205%0A42%200%0A0%203%0A0%200%5D2%2F%7B~%0A%0A%7B)%2Cf%2B%3A-%7D%0A%0A~p%7D%2F) Too bad that the closed form solution is longer. :| ### Explanation ``` ), e# Get range [0 1 ... P]. f+ e# Add N to each value to get [N N+1 ... N+P]. :- e# Fold subtraction over the list, computing N - (N+1) - (N+2) - ... - (N+P). ``` [Answer] ## Haskell, 21 bytes ``` a#b=foldl1(-)[a..a+b] ``` [Answer] ## Javascript (ES6), ~~20~~ ~~19~~ 18 bytes ``` n=>p=>n+p*(~p/2-n) ``` *Saved 1 byte by currying, as suggested by Zwei* *Saved 1 byte thanks to user81655* ### Test ``` let f = n=>p=>n+p*(~p/2-n) console.log(f(2)(3)) console.log(f(100)(5)) console.log(f(42)(0)) console.log(f(0)(3)) console.log(f(0)(0)) ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 4 bytes ``` r+_/ ``` [Try it online!](http://jelly.tryitonline.net/#code=citfLw&input=&args=MTAw+NQ) ### How it works ``` r+_/ Main link. Arguments: n, p + Yield n+p. r Range; yield [n, ..., n+p]. _/ Reduce by subtraction. ``` [Answer] # Haskell, ~~19~~ 18 bytes ``` n#p=n+sum[-n-p..n] ``` Previous 19 bytes solutions ``` n#p=n-n*p-(p*p+p)/2 n#p=n-sum[n+1..n+p] ``` [Answer] # C#, 21 20 bytes *Edit: Saved one byte thanks to [TheLethalCoder](https://codegolf.stackexchange.com/users/38550/thelethalcoder)* ``` N=>P=>N-P++*(N+P/2); ``` **[Try it online!](https://ideone.com/IA7KSq)** Full source, including test cases: ``` using System; namespace substract { class Program { static void Main(string[] args) { Func<int,Func<int,int>>s=N=>P=>N-P++*(N+P/2); Console.WriteLine(s(2)(3)); //-10 Console.WriteLine(s(100)(5)); //-415 Console.WriteLine(s(42)(0)); //42 Console.WriteLine(s(0)(3)); //-6 Console.WriteLine(s(0)(0)); //0 } } } ``` [Answer] ## Mathematica, 15 bytes ``` #2-##-#(#+1)/2& ``` An unnamed function that receives `P` and `n` as its parameters in that order. Uses the closed form solution `n - n*p - p(p+1)/2`. [Answer] # Perl, ~~23~~ 22 bytes Includes +1 for `-p` Give n and p (in that order) on separate lines of STDIN: ``` subtract.pl 2 3 ^D ``` `subtract.pl`: ``` #!/usr/bin/perl -p $_-=eval"+2+\$_++"x<> ``` (using `''` quotes to save the `\` invokes a 2 byte penalty because it can't be combined with `-e`) Same idea and length: ``` #!/usr/bin/perl -p $_+=eval"-1-++\$_"x<> ``` Surprisingly doing the actual calculation is shorter than using the direct formula (these `$`'s really hurt for arithmetic) [Answer] ## C++, ~~54~~ 51 bytes ``` [](int N,int P){int F=N;while(P--)F-=++N;return F;} ``` ~~[](int N,int P){int F;for(F=N;P;F-=++N,P--);return F;}~~ ## Test: ``` #include <iostream> int main(void) { int N, P; std::cin >> N >> P; auto f = [](int N,int P){int F=N;while(P--)F-=++N;return F;}; std::cout << f(N,P) << std::endl; return 0; } ``` [Answer] ## Pyke, 6 bytes ``` m+mhs- ``` [Try it here!](http://pyke.catbus.co.uk/?code=m%2Bmhs-&input=100%0A5&warnings=0) ``` m+ - map(range(input_2), +input_1) mh - map(^, +1) s - sum(^) - - input_1 - ^ ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~19~~ 17 bytes ``` hHyL,?+y:Lx+$_:H+ ``` ### Explanation ``` hH Input = [H, whatever] HyL, L = [0, …, H] ?+ Sum the two elements in the Input y Yield the range from 0 to the result of the sum :Lx Remove all elements of L from that range + Sum the remaining elements $_ Negate the result :H+ Add H ``` [Answer] # Forth, 36 bytes Simple computation of `n - (p*n + (p^2+p) / 2)` ``` : f 2dup dup dup * + 2/ -rot * + - ; ``` [**Try it online**](https://repl.it/DJYh) [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` :y+s- ``` Inputs are `P` and then `N`. [Try it at MATL Online!](https://matl.io/?code=%3Ay%2Bs-&inputs=5%0A100&version=19.1.0) ### Explanation ``` : % Take P implicitly. Range [1 2 ... P] % Stack: [1 2 ... P] y % Take N implicitly at the bottom of the stack, and push another copy % Stack: N, [1 2 ... P], N + % Add the top two arrays in the stack , element-wise % Stack: N, [N+1 N+2 ... N+P] s % Sum of array % Stack: N, N+1+N+2+...+N+P - % Subtract the top two numbers % Stack: N-(N+1+N+2+...+N+P) % Implicitly display ``` [Answer] ## Batch, 30 bytes ``` @cmd/cset/a%1-(%1*2+%2+1)*%2/2 ``` Takes `n` and `p` as command-line parameters and prints the result without a trailing newline. [Answer] ## [S.I.L.O.S](https://github.com/rjhunjhunwala/S.I.L.O.S), 80 bytes ``` GOTO b lbla n+1 m-n i-1 GOTO d lblb readIO n=i m=n readIO lbld if i a printInt m ``` Try it online with test cases: [2,3](http://silos.tryitonline.net/#code=R09UTyBiCmxibGEKbisxCm0tbgppLTEKR09UTyBkCmxibGIKcmVhZElPCm49aQptPW4KcmVhZElPCmxibGQKaWYgaSBhCnByaW50SW50IG0&input=&args=Mg+Mw) [100,5](http://silos.tryitonline.net/#code=R09UTyBiCmxibGEKbisxCm0tbgppLTEKR09UTyBkCmxibGIKcmVhZElPCm49aQptPW4KcmVhZElPCmxibGQKaWYgaSBhCnByaW50SW50IG0&input=&args=MTAw+NQ) [42,0](http://silos.tryitonline.net/#code=R09UTyBiCmxibGEKbisxCm0tbgppLTEKR09UTyBkCmxibGIKcmVhZElPCm49aQptPW4KcmVhZElPCmxibGQKaWYgaSBhCnByaW50SW50IG0&input=&args=NDI+MA) [0,3](http://silos.tryitonline.net/#code=R09UTyBiCmxibGEKbisxCm0tbgppLTEKR09UTyBkCmxibGIKcmVhZElPCm49aQptPW4KcmVhZElPCmxibGQKaWYgaSBhCnByaW50SW50IG0&input=&args=MA+Mw) [0,0](http://silos.tryitonline.net/#code=R09UTyBiCmxibGEKbisxCm0tbgppLTEKR09UTyBkCmxibGIKcmVhZElPCm49aQptPW4KcmVhZElPCmxibGQKaWYgaSBhCnByaW50SW50IG0&input=&args=MA+MA) [Answer] # R, ~~17~~ 14 bytes ``` N-N*P-sum(0:P) ``` Thanks to billywob for golfing away 3 bytes. Previous answer: ``` N-sum(N+if(P)1:P) ``` Note that 1:0 expands to the vector (1,0) so we need the if(P) condition (or to use `seq_len`, but that is more bytes). Without the condition, we would get the wrong output if P=0. If P is zero, then the sum expands to `sum(N+NULL)`, then to `sum(numeric(0))`, which is zero. [Answer] # PHP, 33 Bytes ``` $n-=$n*$p+array_sum(range(0,$p)); ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` RS+×_×- ``` Arguments are `P, N` Test it on [**TryItOnline**](http://jelly.tryitonline.net/#code=UlMrw5dfw5ct&input=&args=NQ+MTAw) How? ``` RS+×_×- - takes two arguments: P, N R - range(P): [1,2,3, ... ,P] S - sum: 1+2+3+ ... +P × - multiply: P*N + - add: 1+2+3+ ... +P + P*N _ - subtract: 1+2+3+ ... +P + P*N - N - - -1 × - multiply: (1+2+3+ ... +P + P*N - N)*-1 = -1-2-3- ... -P - P*N + N = N - (N+1) - (N+2) - (N+3) - ... - (N+P) ``` [Answer] # Pyth - 6 bytes ``` -F}Q+E ``` [Test Suite](http://pyth.herokuapp.com/?code=-F%7DQ%2BE&test_suite=1&test_suite_input=2%0A3%0A100%0A5%0A42%0A0%0A0%0A3%0A0%0A0&debug=0&input_size=2). [Answer] # Java, ~~67~~, 63 bytes Golfed: ``` int x(int n,int p){return-((p%2<1)?p*p/2+p:p/2*(p+2)+1)+n-p*n;} ``` Ungolfed: ``` int x(int n, int p) { return -((p%2<1) ? p*p/2+p : p/2 * (p+2) + 1) + n - p*n; } ``` Basically I did some math on the formula. The `n - p*n` part takes care of the all `n`'s in the formula. Then I used a super fun property of summing together linearly increasing set of integers (arithmetic series): I used the sum of first and last integer and then multiply it by `set.length / 2` (I also check for the parity and handle it appropriately). Try it: <https://ideone.com/DEd85A> [Answer] # Java 7, ~~43~~ 40 bytes ``` int c(int n,int p){return n-p*n+p*~p/2;} ``` # Java 8, 19 bytes ``` (n,p)->n-p*n+p*~p/2 ``` Shamelessly stolen from [*@JonathanAllan*'s amazing Python 2 formula](https://codegolf.stackexchange.com/a/91915/52210). **Original answer (~~61~~ 60 bytes):** ``` int c(int n,int p){int r=n,i=1;for(;i<p;r-=n+++i);return r;} ``` **Ungolfed & test cases:** [Try it here.](https://ideone.com/cwJp03) ``` class M{ static int c(int n, int p){ return n - p*n + p*~p / 2; } public static void main(String[] a){ System.out.println(c(2, 3)); System.out.println(c(100, 5)); System.out.println(c(42, 0)); System.out.println(c(0, 3)); System.out.println(c(0, 0)); } } ``` **Output:** ``` -10 -415 42 -6 0 ``` [Answer] # [Fourier](http://github.com/beta-decay/fourier), 34 bytes ``` I~No~OI~P>0{1}{@P+N(N^~NO-N~ON)Oo} ``` [**Try it online!**](http://fourier.tryitonline.net/#code=SX5Ob35PSX5QPjB7MX17QFArTihOXn5OTy1Ofk9OKU9vfQ&input=NDIKMA) [Answer] ## [Labyrinth](https://github.com/m-ender/labyrinth), 15 bytes ``` ?:?:}*-{:)*#/-! ``` or ``` ??:}`)*{:)*#/-! ``` Uses the closed form solution `n - n*P - P*(P+1)/2`. [Answer] # php, 38 bytes ``` <?=$argv[1]*(1-$a=$argv[2])-$a++*$a/2; ``` [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 12 bytes ``` perz?+{.-}r[ ``` [Try it online!](https://tio.run/##SyotykktLixN/f@/ILWoyl67Wk@3tij6/39DAwMFUwA "Burlesque – Try It Online") ``` pe #Read input as P, N rz #Range (0,N) ?+ #Add P to each {.-}r[ #Reduce via subtraction ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` +ṡƒ- ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIr4bmhxpItIiwiIiwiMTAwXG41Il0=) Port of Jelly answer. ## How? ``` +ṡƒ- +ṡ # Inclusive range [a, a + b] ƒ- # Reduce by subtraction ``` [Answer] # TI-Basic, 17 bytes ``` Prompt N,P N-NP-.5(P²+P ``` Alternatives: ``` Prompt N,P N-P(P/2+.5+N ``` ``` Prompt N,P N-NP-.5P(P+1 ``` ``` Prompt N,P N-.5P(2N+P+1 ``` [Answer] # Pyth, 11 bytes ``` Ms+Gm_+GdSH ``` A function `g` that takes input of `n` and `p` via argument and prints the result. It can be called in the form `gn p`. [Try it online](https://pyth.herokuapp.com/?code=Ms%2BGm_%2BGdSH%3B%0Ag2+3%3B%0Ag100+5%3B%0Ag42+0%3B%0Ag0+3%3B%0Ag0+0&debug=0) **How it works** ``` Ms+Gm_+GdSH Function g. Inputs: G, H M g=lambda G,H: SH 1-indexed range, yielding [1, 2, 3, ..., H] m_+Gd Map lambda d:-(G+d) over the above, yielding [-(G+1), -(G+2), -(G+3), ..., -(G+H)] +G Add G to the above, yielding [G, -(G+1), -(G+2), -(G+3), ..., -(G+H)] s Reduce on addition with base case 0, yielding G-(G+1)-(G+2)-(G+3)... -(G+H) Implicitly print ``` ]
[Question] [ *(inspired by [this challenge](https://puzzling.stackexchange.com/q/42278) over on Puzzling -- **SPOILERS** for that puzzle are below, so stop reading here if you want to solve that puzzle on your own!)* If a letter in a word occurs alphabetically later than the previous letter in the word, we call that a *rise* between the two letters. Otherwise, **including if it's the same letter**, it's called a *fall*. For example, the word `ACE` has two rises (`A` to `C` and `C` to `E`) and no falls, while `THE` has two falls (`T` to `H` and `H` to `E`) and no rises. We call a word *Bumpy* if the sequence of rises and falls alternates. For example, `BUMP` goes rise (`B` to `U`), fall (`U` to `M`), rise (`M` to `P`). Note that the first sequence need not be a rise -- `BALD` goes fall-rise-fall and is also Bumpy. ### The challenge Given a word, output whether or not it's Bumpy. ### Input * A word (not necessarily a dictionary word) consisting of ASCII alphabet (`[A-Z]` or `[a-z]`) letters only, in [any suitable format](http://meta.codegolf.stackexchange.com/q/2447/42963). * Your choice if the input is all uppercase or all lowercase, but it must be consistent. * The word will be at least 3 characters in length. ### Output A [truthy/falsey](http://meta.codegolf.stackexchange.com/a/2194/42963) value for whether the input word is Bumpy (truthy) or not Bumpy (falsey). ### The Rules * Either a full program or a function are acceptable. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. ### Examples Truthy: ``` ABA ABB BAB BUMP BALD BALDY UPWARD EXAMINATION AZBYCXDWEVFUGTHSIRJQKPLOMN ``` Falsey: ``` AAA BBA ACE THE BUMPY BALDING ABCDEFGHIJKLMNOPQRSTUVWXYZ ``` --- ## 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=93005,OVERRIDE_USER=42963;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] # MATL, 4 bytes ``` d0>d ``` Explanation: ``` d % Implicitly take input. Take difference between each element 0> % Check whether diff's are positive. Should result in [0 1 0 1 ...] pattern. d % Again take the difference. Any consecutive rises or falls results in a % difference of 0, which is a falsy value in MATL ``` This is my first MATL entry, so I wonder how much improvement there can be from this naive port from my MATLAB/Octave attempt (which would be `@(a)all(diff(diff(a)>0))`). Note that the `all` is not necessary because any zero makes an array false, so there's no `A` in the MATL port. [Answer] ## JavaScript (ES6), ~~75~~ ~~69~~ ~~63~~ ~~46~~ 43 bytes Saved 3 bytes thanks to Neil: ``` f=([c,...s])=>s[1]?c<s[0]^s[0]<s[1]&&f(s):1 ``` Destructuring the string parameter instead of `s.slice(1)`. --- Previous solution: Saved 17 bytes thanks to ETHproductions: ``` f=s=>s[2]?s[0]<s[1]^s[1]<s[2]&&f(s.slice(1)):1 ``` What happened from the previous solution step by step: ``` f=(s,i=0,a=s[i++]<s[i])=>s[i+1]&&(b=a^(a=s[i]<s[i+1]))?f(s,i):b // (63) Original f=(s,i=0,a=s[i++]<s[i])=>s[i+1]&&(b=a^(s[i]<s[i+1]))?f(s,i):b // (61) No point in reassigning `a`, it's not used again f=(s,i=0,a=s[i++]<s[i])=>s[i+1]&&(b=a^s[i]<s[i+1])?f(s,i):b // (59) Remove unnecessary parentheses f=(s,i=0)=>s[i+2]&&(b=s[i++]<s[i]^s[i]<s[i+1])?f(s,i):b // (55) `a` is now just a waste of bytes f=(s,i=0)=>s[i+2]?(b=s[i++]<s[i]^s[i]<s[i+1])?f(s,i):b:1 // (56) Rearrange conditional expressions to allow for more golfing f=(s,i=0)=>s[i+2]?(b=s[i++]<s[i]^s[i]<s[i+1])&&f(s,i):1 // (55) Rearrange conditional expression f=(s,i=0)=>s[i+2]?(s[i++]<s[i]^s[i]<s[i+1])&&f(s,i):1 // (53) `b` is now also a waste of bytes f=(s,i=0)=>s[i+2]?s[i++]<s[i]^s[i]<s[i+1]&&f(s,i):1 // (51) Remove unnecessary parentheses f=s=>s[2]?s[0]<s[1]^s[1]<s[2]&&f(s.slice(1)):1 // (46) Use `s.slice(1)` instead of `i` ``` --- Previous solutions: 63 bytes thanks to ETHproductions: ``` f=(s,i=0,a=s[i++]<s[i])=>s[i+1]&&(b=a^(a=s[i]<s[i+1]))?f(s,i):b ``` 69 bytes: ``` f=(s,i=0,a=s[i++]<s[i])=>i+1<s.length&&(b=a^(a=s[i]<s[i+1]))?f(s,i):b ``` 75 bytes: ``` f=(s,a=s[0]<s[1])=>{for(i=1;i+1<s.length&&(b=a^(a=s[i++]<s[i])););return b} ``` All letters in a word must have the same case. [Answer] # LabVIEW, 36 equivalent bytes Golfed down using logical equivalences: [![golfed](https://i.stack.imgur.com/1zSUL.png)](https://i.stack.imgur.com/1zSUL.png) Ungolfed: [![ungolfed](https://i.stack.imgur.com/rduiZ.png)](https://i.stack.imgur.com/rduiZ.png) First we convert to lowercase, then to byte array. Trim off the first element of the byte array as it has no precedent. Then, for each element in the array, check if it's greater than the previous one (U8 char maps to ASCII as you expect) and store the result for the next iteration, as well as in an array for viewing overall bumpiness. If the current and prior boolean check are equal, we terminate the loop and it's not bumpy. Else, it's bumpy! [Answer] # Python, 56 bytes ``` lambda s:all((x<y)^(y<z)for x,y,z in zip(s,s[1:],s[2:])) ``` All test cases are at **[ideone](http://ideone.com/4eYofK)** Zips through triples of characters in s and tests that all such triples have left and right pairs with different rise/fall properties. Works for either all uppercase or all lowercase. [Answer] # Ruby, ~~57~~ 48 bytes Expects input to be all uppercase. ``` ->s{!s.gsub(/.(?=(.)(.))/){($&<$1)^($1<$2)}[?f]} ``` See it on repl.it: <https://repl.it/D7SB> ## Explanation The regular expression `/.(?=(.)(.))/` matches each character that's followed by two more characters. `(?=...)` is a positive lookahead, meaning we match the subsequent two characters but don't "consume" them as part of the match. Inside the curly braces, `$&` is the matched text—the first character of the three—and `$1` and `$2` are the captured characters inside the lookahead. In other words, if the string is `"BUMPY"`, it will first match `"B"` (and put it in `$&`) and capture `"U"` and `"M"` (and put them in `$1` and `$2`). Next it will match `"U"` and capture `"M"` and `"P"`, and so on. Inside the block we check if the first pair of characters (`$&` and `$1`) is a rise and the second (`$1` and `$2`) is a fall or vice versa, much like most of the other answers. This `^` expression returns `true` or `false`, which gets converted to a string and inserted in place of the match. As a result, our example `"BUMPY"` becomes this: ``` "truetruefalsePY" ``` Since we know the input is all uppercase, we know `"f"` will only occur as part of `"false"` and `!result[?f]` gives us our answer. [Answer] # C#, ~~64~~ ~~63~~ 55 bytes ``` unsafe bool B(char*s)=>1>s[2]||*s<s[1]!=*++s<s[1]&B(s); ``` *-8 bytes from Scepheo's suggestions* This is a port of [Hedi's solution](https://codegolf.stackexchange.com/a/93014/58106) to C#. I also came up with a recursive solution, but the recursion wasn't as good. My original solution is below. ### My Original C#, ~~96~~ ~~94~~ 91 bytes ``` unsafe bool B(char*s,bool f=1>0,int i=0)=>1>s[1]||(s[0]<s[1]?f:1>i?!(f=!f):!f)&B(s+1,!f,1); ``` *-2 bytes by using `1>0` instead of `true`.* *-3 bytes from Scepheo's suggestions for the port solution above* Calls itself recursively checking that the rising/falling alternates each time. Ungolfed: ``` // unsafe in order to golf some bytes from string operations. // f alternates with each recursive call // i is 0 for the first call, 1 for all subsequent calls unsafe bool B(char* s, bool f = 1 > 0, int i = 0) => 1 > s[1] ? 1 > 0// (instead of 1 == s.Length) check if s[1] = NULL, and return true. : ( s[0] < s[1] ? f // Rising, so use f... : // Else falling 1 > i ? !(f=!f) // But this is the first call, so use true (but flip f)... : !f // Not first call, so use !f... ) & B(s+1, !f, 1) // ...AND the previous value with a recursive call // s+1 instead of s.Substring(1) ; ``` [Answer] # C 59 Bytes ``` r;f(s)char*s;{for(r=0;r=*s?~r&1<<(*s>=*++s):0;);return!*s;} ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 6 bytes ``` OI>0IẠ ``` Based on @sanchises' [answer.](https://codegolf.stackexchange.com/a/93009/6710) [Try it online!](http://jelly.tryitonline.net/#code=T0k-MEnhuqA&input=&args=RVhBTUlOQVRJT04) or [Verify all.](http://jelly.tryitonline.net/#code=T0k-MEnhuqAKw4figqzigqw&input=&args=W1snQUJBJywnQUJCJywnQkFCJywnQlVNUCcsJ0JBTEQnLCdCQUxEWScsJ1VQV0FSRCcsJ0VYQU1JTkFUSU9OJywnQVpCWUNYRFdFVkZVR1RIU0lSSlFLUExPTU4nXSwKWydBQUEnLCdCQkEnLCdBQ0UnLCdUSEUnLCdCVU1QWScsJ0JBTERJTkcnLCdBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWiddXQ) ## Explanation ``` OI>0IẠ Input: string S O Convert each char in S to an ordinal I Get the increments between each pair >0 Test if each is positive, 1 if true else 0 I Get the increments between each pair Ạ Test if the list doesn't contain a zero, 1 if true else 0 ``` [Answer] # JavaScript (ES6), 65 bytes ``` s=>[...s].map(C=>(c?(R=c<C,i++?t&=r^R:0,r=R):t=1,c=C),c=r=i="")|t ``` `.map` is [definitely not the best solution](https://codegolf.stackexchange.com/a/93014/42545). [Answer] # Python 2, 88 bytes Simple solution. ``` s=input() m=map(lambda x,y:y>x,s[:-1],s[1:]) print all(x-y for x,y in zip(m[:-1],m[1:])) ``` [**Try it online**](https://repl.it/D7DP) If same letters in a row were neither a rise nor a fall, the solution would be 79 bytes: ``` s=input() m=map(cmp,s[:-1],s[1:]) print all(x-y for x,y in zip(m[:-1],m[1:])) ``` [Answer] # Perl, 34 bytes Includes +3 for `-p` (code contains `'` so `-e` can't be used) Give uppercase input on STDIN: ``` bump.pl <<< AAA ``` `bump.pl` ``` #!/usr/bin/perl -p s%.%$&.z lt$'|0%eg;$_=!/(.)\1./ ``` [Answer] ## Python, 51 bytes ``` g=lambda a,b,c,*s:((a<b)^(b<c))*(s==()or g(b,c,*s)) ``` Takes input like `g('B','U','M','P')` and outputs `1` or `0`. Uses argument unpacking to take the first three letters and check if the first two compare differently from the second two. Then, recurses on the remainder, using multiplication for `and`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to @Dennis (use a cumulative reduction) ``` <2\IẠ ``` All test cases are at **[TryItOnline](http://jelly.tryitonline.net/#code=PDJcSeG6oArFvMOH4oKsS-KCrFk&input=&args=IkFCQSIsIkFCQiIsIkJBQiIsIkJVTVAiLCJCQUxEIiwiQkFMRFkiLCJVUFdBUkQiLCJFWEFNSU5BVElPTiIsIkFaQllDWERXRVZGVUdUSFNJUkpRS1BMT01OIiwiQUFBIiwiQkJBIiwiQUNFIiwiVEhFIiwiQlVNUFkiLCJCQUxESU5HIiwiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVoi)** How? ``` <2\IẠ - main link takes an argument, s, e.g. "BUMP" or "BUMPY" < - less than comparison (a dyad) 2 - literal 2 (a nilad) \ - n-wise overlapping reduction when preceded by a dyad-nilad chain (i.e. reduce the list by pairs with less than) e.g. [1,0,1] or [1,0,1,1] I - consecutive differences, e.g. [-1,1] or [-1,1,0] Ạ - All, 0 if any values are 0 else 1, e.g. 1 or 0 ``` Works for either all uppercase or all lowercase. [Answer] # Japt, 8 bytes ``` Uä> ä- e ``` [Test it online!](http://ethproductions.github.io/japt/?v=master&code=VeQ+IOQtIGU=&input=IkVYQU1JTkFUSU9OIg==) ### How it works ``` Uä> ä- e // Implicit: U = input string Uä> // Map each pair of chars X, Y in U to X > Y. ä- // Map each pair of items in the result to X - Y. // If there are two consecutive rises or falls, the result contains a zero. e // Check that every item is truthy (non-zero). // Implicit: output last expression ``` [Answer] # C# 105 104 Bytes ``` bool f(char[]x){int t=1;for(int i=2,p=x[1],f=x[0]-p>>7;i<x.Length;)f^=t&=p<(p=x[i++])?1-f:f;return t>0;} ``` 105 bytes Solution: ``` bool f(char[]x){bool t=1>0,f=x[0]<x[1];for(int i=2,p=x[1];i<x.Length;)f^=t&=p<(p=x[i++])?!f:f;return t;} ``` [Try it online](https://repl.it/D72K/1) Using an array of chars saved one byte since the space can be omitted after the brackets. `f(string x)` vs `f(char[]x)` It is 101 bytes if I can return an int 1/0 instead of bool true/false ``` int f(char[]x){int t=1;for(int i=2,p=x[1],f=x[0]-p>>7;i<x.Length;)f^=t&=p<(p=x[i++])?1-f:f;return t;} ``` [Answer] # Haskell, 52 bytes ``` f x=and$g(/=)$g(>)x where g h y=zipWith h(tail y)y ``` I suspect I could get this a chunk smaller if I managed to get rid of the "where" construct, but I'm probably stuck with zipWith. This works by making a list of the rises (True) and falls (False), then making a list of if the ajacent entries in this list are different --- This is my first attempt at one of these, so I'll go through my thought process in case I've gone horribly wrong somewhere. ### Ungolfed Version (168 bytes) ``` isBumpy :: [Char] -> Bool isBumpy input = and $ areBumps $ riseFall input where riseFall ax@(x:xs) = zipWith (>) xs ax areBumps ax@(x:xs) = zipWith (/=) xs ax ``` ### Shorten names, remove type information (100 bytes) ``` f x = and $ g $ h x where h ax@(x:xs) = zipWith (>) xs ax g ax@(x:xs) = zipWith (/=) xs ax ``` ### Move h into the main function as it is only used once (86 bytes) ``` f ax@(x:xs) = and $ g $ zipWith (>) xs ax where g ax@(x:xs) = zipWith (/=) xs ax ``` ### Realise that areBumps and riseFall are similar enough to abstract (73 bytes) ``` f x = and $ g (/=) $ g (>) x where g h ya@(y:ys) = zipWith h ys ya ``` ### Note that (tail y) is shorter than ya@(y:ys) (70 bytes) ``` f x = and $ g (/=) $ g (>) x where g h y = zipWith h (tail y) y ``` ### Tidy up; remove unneeded spaces (52 bytes) ``` f x=and$g(/=)$g(>)x where g h y=zipWith h(tail y)y ``` [Answer] # Java 7, ~~157~~ ~~153~~ ~~150~~ ~~125~~ 117 bytes ``` int c(char[]z){for(int i=2,a,b,c;i<z.length;i++)if(((a=z[i-1])<(c=z[i])&(b=z[i-2])<a)|(a>=c&b>=a))return 0;return 1;} ``` **Ungolfed & test cases:** [Try it here.](https://ideone.com/xyVeXO) ``` class M{ static int c(char[] z){ for(int i = 2, a, b, c; i < z.length; i++){ if(((a = z[i-1]) < (c = z[i]) & (b = z[i-2]) < a) | (a >= c & b >= a)){ return 0; //false } } return 1; //true } public static void main(String[] a){ System.out.print(c("ABA".toCharArray()) + ", "); System.out.print(c("ABB".toCharArray()) + ", "); System.out.print(c("BAB".toCharArray()) + ", "); System.out.print(c("BUMP".toCharArray()) + ", "); System.out.print(c("BALD".toCharArray()) + ", "); System.out.print(c("BALDY".toCharArray()) + ", "); System.out.print(c("UPWARD".toCharArray()) + ", "); System.out.print(c("EXAMINATION".toCharArray()) + ", "); System.out.print(c("AZBYCXDWEVFUGTHSIRJQKPLOMN".toCharArray()) + ", "); System.out.print(c("AAA".toCharArray()) + ", "); System.out.print(c("ACE".toCharArray()) + ", "); System.out.print(c("THE".toCharArray()) + ", "); System.out.print(c("BUMPY".toCharArray()) + ", "); System.out.print(c("BALDING".toCharArray()) + ", "); System.out.print(c("ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray()) + ", "); } } ``` **Output:** ``` 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 ``` [Answer] ## PowerShell v2+, 83 bytes ``` param($n)($a=-join(1..($n.Length-1)|%{+($n[$_-1]-lt$n[$_])}))-eq($a-replace'00|11') ``` A little bit of a different approach. This loops through the input `$n`, each iteration seeing whether the previous character `$n[$_-1]` is `-l`ess`t`han the current character `$n[$_]`, then casting the result of that Boolean operator to an int with `+`. Those are `-join`ed together into a string, stored into `$a`. We then check whether `$a` is `-eq`ual to `$a` with any substrings of `00` or `11` removed. [Answer] # Python 2.7, 84 bytes ``` s=input() b=s[0]<s[1] o=1 for i in range(len(s)-1):o&=(s[i]<s[i+1])==b;b^=1 print o ``` Returns 1 for bumpy, 0 for otherwise Learned some cool stuff with bitwise & and ^. Starts with boolean b defining first pair as up/down, then tests and flips b for each following pair. o flips to false if test fails and sticks. Requires quotes around input (+4 bytes for raw\_input() if that breaks some rule) [Test It](https://repl.it/D7Z5) [Answer] ## Python 2.7 (again, ~~84~~ 83 bytes) ``` def a(s):x=s[1:];return[cmp(s[0],x)]+a(x) if x else [] print len(set(a(input())))>1 ``` Or, ~~78~~ 77 bytes without the print. ~~By the way, the above 56 byte Python 2.7 example breaks on, for example, `"abbab"` or any other input with repeated characters.~~ Never mind, didn't read instructions. Revising. Okay, down to 83. The triples one is nicer though. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 9 bytes ``` SÇ¥0›¥_O_ ``` **Explanation** ``` SÇ # convert to list of ascii values ¥ # take delta's 0› # check if positive, giving a list of 1's and 0's # if they alternate, the word is bumpy ¥ # take delta's again, if we have any 0's in the list the word is not bumpy _ # logical negation, turning 0 into 1 and everything else to 0 O # sum, producing 0 for a bumpy word and 1 for a non-bumpy word _ # logical negation, inverting the previous 1 into 0 and vice versa ``` [Try it online!](http://05ab1e.tryitonline.net/#code=U8OHwqUw4oC6wqVfT18&input=YnVtcA) [Answer] ## [CJam](http://sourceforge.net/projects/cjam/), 15 bytes ``` l2ew::<2ew::^:* ``` [Try it online!](http://cjam.tryitonline.net/#code=cU4vezpMOwoKTDJldzo6PDJldzo6XjoqCgpdbn0v&input=QUJBCkFCQgpCQUIKQlVNUApCQUxECkJBTERZClVQV0FSRApFWEFNSU5BVElPTgpBWkJZQ1hEV0VWRlVHVEhTSVJKUUtQTE9NTgpBQUEKQkJBCkFDRQpUSEUKQlVNUFkKQkFMRElORwpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWg) (As a linefeed-separated test-suite.) ### Explanation ``` l e# Read input. 2ew e# Get all (overlapping) pairs. ::< e# Check whether each pair is strictly ascending (1) or not (0). 2ew e# Get all (overlapping) pairs. ::^ e# Take the bitwise XOR of each pair, giving 1 if a rise and a fall alternate, e# and zero if there are two rises or two falls in succession. :* e# Product. Gives 1 only if the previous step yielded a list of 1s, meaning e# that any two consecutive rises/falls will turn this into a zero. ``` [Answer] # PHP, 80 bytes ``` $s=$argv[1];for($c=$s[0];$n=$s[++$i];$c=$n,$d=$e)if($d===$e=$n>$c)break;echo!$n; ``` or ``` for($c=$argv[1][0];$n=$argv[1][++$i];$c=$n,$d=$e)if($d===$e=$n>$c)break;echo!$n; ``` empty output for false, `1` for true or [Hedi´s recursive approach](https://codegolf.stackexchange.com/a/93014/42545) ported and a little golfed for 70 bytes: ``` function f($s){return!$s[2]|$s[0]<$s[1]^$s[1]<$s[2]&&f(substr($s,1));} ``` Actually, this should recurse infinitely for bumpy words, but it does not! [Answer] # Haskell, ~~30~~ 37 bytes ``` q f=tail>>=zipWith f;k=and.q(/=).q(>) ``` Usage: ``` Prelude> k <$> words "ABA ABB BAB BUMP BALD BALDY UPWARD EXAMINATION AZBYCXDWEVFUGTHSIRJQKPLOMN" [True,True,True,True,True,True,True,True,True] Prelude> k <$> words "AAA BBA ACE THE BUMPY BALDING ABCDEFGHIJKLMNOPQRSTUVWXYZ" [False,False,False,False,False,False,False] ``` [Answer] # PHP 7, ~~137~~ 118 bytes ``` for($i=0;$i<strlen($argv[1])-2;$i++)if(((($s[$i]<=>$s[$i+1])<0)?1:0)==((($s[$i+1]<=>$s[$i+2])<0)?1:0)){echo"0";break;} ``` Empty output for Bumpy, `0` for Not Bumpy. This is my first attempt at code golfing and I have to improve a lot, but it was a wonderful method to learn new things for me. I also wanted to challenge myself on that task by using the new PHP 7 [Spaceship Operator](http://php.net/manual/en/migration70.new-features.php) which seems very interesting. ~~Anyway I'm not satisfied about it, first of all for the fact that I had to add an extra `if(isset($s[$i+2]))` to check if the variable exist because I did not find another workaround to the problem, but this is it for now.~~ (Note: I fixed that simply by changing `strlen($s)-1` to `strlen($s)-2`, I couldn't really see that before...). **Testing code:** ``` $as = array("ABA", "ABB", "BAB", "BUMP", "BALD", "BALDY", "UPWARD", "EXAMINATION", "AZBYCXDWEVFUGTHSIRJQKPLOMN", "AAA", "BBA", "ACE", "THE", "BUMPY", "BALDING", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); foreach ($as as $s) { for($i=0;$i<strlen($s)-2;$i++)if(((($s[$i]<=>$s[$i+1])<0)?1:0)==((($s[$i+1]<=>$s[$i+2])<0)?1:0)){echo"0";break;} } ``` **[Test online](http://sandbox.onlinephpfunctions.com/code/526f124febcbded3dcb007d4ed7b79a036ae3bcc)** [Answer] # Javascript ES6, 100 bytes ``` d="charCodeAt";a=b=>{f=r=0;for(i=1;i<b.length;i++){if(b[d](i)<=b[d](i-1)){f=1}else{r=1}}return f&&r} ``` Try it here: ``` d="charCodeAt";a=b=>{f=r=0;for(i=1;i<b.length;i++){if(b[d](i)<=b[d](i-1)){f=1}else{r=1}}return f&&r} alert(a(prompt())); ``` Oh come on two people already beat me to it by 40 bytes... whatever [Answer] # Python 3, ~~148 139~~ 127 bytes ``` def _(w):*r,=map(lambda a,b:0>ord(a)-ord(b)and-1or 1,w,w[1:]);s=len(r)%2==0and r+[r[0]]or r;return sum(s)in(-1,1)and s==s[::-1] ``` testing code ``` positives = ('ABA', 'ABB', 'BAB', 'BUMP', 'BALD', 'BALDY', 'UPWARD', 'EXAMINATION', 'AZBYCXDWEVFUGTHSIRJQKPLOMN') negatives = ('AAA', 'BBA', 'ACE', 'THE', 'BUMPY', 'BALDING', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') for w in positives: print(_(w), w) assert _(w) for w in negatives: print(_(w), w) assert not _(w) ``` [Answer] **C, ~~65~~ ~~57~~ 60 bytes** ``` r;f(char*s){for(r=0;*++s&&(r=~r&1<<(*s>*(s-1))););return r;} ``` is fix of ``` r;f(char*s){for(;*++s&&(r=~r&1<<(*s>*(s-1))););return r;} ``` that works correctly with any data only at single function call (when the global variable `r` is initialized to zero). But in any case this is shorter than previous solution (65 bytes) due to use of `for` instead of `while`. But previous (the following) is a little easier to understand: ``` r;f(char*s){while(*++s)if(!(r=~r&1<<(*s>*(s-1))))break;return r;} ``` My solution is based on bitwise `&` with inverted previous and current direction code, where direction code can be `2` (`1<<1`) for character code increase (`*s > *(s-1)`) or `1` (`1<<0`) otherwise. Result of this operation became 0 if we use the same direction code as previous and current, i.e. when word is not Bumpy. **UPDATE:** Code for testing: ``` #include <stdio.h> #include <string.h> r;f(char*s){for(;*++s&&(r=~r&1<<(*s>*(s-1))););return r;} int main(void) { char * Truthy[] = { "ABA", "ABB", "BAB", "BUMP", "BALD", "BALDY", "UPWARD", "EXAMINATION", "AZBYCXDWEVFUGTHSIRJQKPLOMN" }; char * Falsey[] = { "AAA", "BBA", "ACE", "THE", "BUMPY", "BALDING", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"}; int posTestNum = sizeof(Truthy) / sizeof(char *); int negTestNum = sizeof(Falsey) / sizeof(char *); int i; int rate = 0; int tests = 0; int res = 0; printf("Truthy (%d tests):\n", posTestNum); for (i = 0; i < posTestNum; i++) { tests++; printf("%s - %s\n", Truthy[i], f(Truthy[i]) ? (rate++, "OK") : "Fail"); r = 0; } printf("\nFalsey (%d tests):\n", negTestNum); for (i = 0; i < negTestNum; i++) { tests++; printf("%s - %s\n", Falsey[i], f(Falsey[i]) ? "Fail" : (rate++, "OK")); r = 0; } printf("\n%d of %d tests passed\n", rate, tests); return 0; } ``` [Answer] # PHP, 100 bytes ``` for($s=$argv[1];$i<strlen($s)-1;$i++)$s[$i]=$s[$i+1]>$s[$i]?r:f;echo str_replace([rr,ff],'',$s)==$s; ``` Replaces every char of the string (except the last one obviously) with an `r` for rise or an `f` for fall and then checks whether `rr` or `ff` occur in the string. To avoid that the last remaining character interfers with that, input must be all uppercase. I'm very unsatisfied with the loop, for example I have a feeling that there must be a way to combine the `$i++` into one of the several `$i`s used in the loop, but I failed to find that way. Maybe someone else sees it. (That's also why I posted my code, despite it being 20 (!) bytes longer than Titus' nice solution.) [Answer] # Java 8, ~~114~~ 90 bytes ``` (c,b)->{b=c[0]<c[1];for(int i=2;i<c.length;i++)if(c[i]>c[i-1]!=(b=!b))return 0;return 1;}; ``` # Ungolfed test program ``` public static void main(String[] args) { BiFunction<char[], Boolean, Integer> func = (c, b) -> { b = c[0] < c[1]; for (int i = 2; i < c.length; i++) { if (c[i] > c[i - 1] != (b = !b)) { return 0; } } return 1; }; System.out.println(func.apply("ABCDEFG".toCharArray(), false)); System.out.println(func.apply("AZBYCXDGEF".toCharArray(), false)); System.out.println(func.apply("ZXZXZX".toCharArray(), false)); System.out.println(func.apply("ZXCYZ".toCharArray(), false)); System.out.println(func.apply("AAA".toCharArray(), false)); } ``` ]
[Question] [ In this challenge, you are going to take a number and turn it into a string, but not in the common way. You will use the `aaaaa` way! The `aaaaa` way is simply replacing each digit of the input number with the letter at that position in the alphabet. For example, `11111` would become `aaaaa` and `21223` would become `babbc`. If the number is less than 5 digits you need to left-pad it with an "A". For example, `12` would be `AAAab`. ## Rules * Your code can be a function or a complete program that outputs to STDOUT. * The returned string must be 5 letters. * It's obvious that the input would be a 1 to 5 digits number that has digits from 1 to 9. * You can get both input and output in number and strings or in array form like [1,2,1,3,1] and ['a','b','a','c','a']. --- ## Test cases ``` In: 43213 -> Out: dcbac In: 8645 -> Out: Ahfde In: 342 -> Out: AAcdb In: 99991 -> Out: iiiia ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so smallest program wins! [Answer] # [Python](https://www.python.org), 44 bytes ``` lambda s:f"{s:05}".translate("bcdefghiAa"*9) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3dXISc5NSEhWKrdKUqoutDExrlfRKihLzinMSS1I1lJKSU1LT0jMyHROVtCw1oXrUC4oy80o00jRMjI0MjTV10jQszExMQbSxiRGIsgQCQ02o8gULIDQA) Takes an integer and returns a string. [Answer] # JavaScript (ES6), 48 bytes Expects an integer and returns a string. ``` f=(n,k=5)=>k?f(n/10|0,k-1)+"Aabcdefghi"[n%10]:'' ``` [Try it online!](https://tio.run/##XcnNDoIgAADge0/B3JowNUCwVRs1n6N1QH6UcNCyderdyc0u@V2/u3zLST3d41WFqE1KVsBQetEgcfYXCwOm5ENKX1FUZK3slDa2H1x2DVtKbqc8TyqGKY5mN8YeWshZTRlCAGOgVSfV5r/BYc@bpdvBarNuwHj961bpbtXHGV3azWT6Ag "JavaScript (Node.js) – Try It Online") --- # [C (gcc)](https://gcc.gnu.org/), 48 bytes ``` k;f(n){k++>4?k=0:f(n/10)|putchar(n?n%10+96:65);} ``` [Try it online!](https://tio.run/##JY7RDoIwDEXf@YqGxGTLIG4wiDCRDzE8LDPggk4DGElwv@6c0Jfb296eVMWdUs71okUGLz0hJ173FS293TOKP8/XpK5yQKY2O0ZJkZd5hoV1d6kNwrAEANpMcJGTPDdQwQI8TVgawSHnWQQpTyIofDGwIvDh9jGg/4H2WSq8HIF7IWRjbbTZL1eibsQ6bNGMt87/M6IwXJ0NrPuq9ia70cXvHw "C (gcc) – Try It Online") ## 47 bytes This version was suggested by [@jdt](https://codegolf.stackexchange.com/users/41374/jdt). ``` i;f(*o,x){for(i=5;i;x/=10)o[--i]=x?96+x%10:65;} ``` [Try it online!](https://tio.run/##VY3RCoIwGIXvfYofQdhylqaObEkPYl6IMBnYJmo0EF@9tUSpzs2Bc77//HVQt5VsjBGMo50iGk9c9UjkKRNMH/IoxKoIAlHm@ppRX3tReKYpm42QI9wrIRGGyQGrTyBk9xiHooQcJkjiYxQTONEkJRAnRwKZVQQzW3j7BtByZOmQWbtAYs33t8VtVVtgXRYl@6tUQX8SjhQBjb9B11uII9fbp@1wky4BtbazM5tXzduqGUzwfAM "C (clang) – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), ~~69~~ ~~67~~ ~~63~~ 61 bytes ``` f(x,o,i)char*o;{for(memset(o,65,i=5);x;x/=10)o[--i]=x%10+96;} ``` [Try it online!](https://tio.run/##TVDbboMwDH0uX2F1qpSM0EG5qChlP8J4QCnQSJBUhEqREL@@zEF9mF/sc2wfX0QkxlYN7kMqMb7uHdzMcpf6/PgO/lOzVANyrieWaSapeLTzp@Zrr2cydZPpFqJZkTNZ5ZRbbr@qJKa6jiLZVPaUxGFZ8M1JtcDUSkUorEFw8FCq52sxdQMVrJCllyRlcC2ynEGaXRiUaAlsHKtxFJC9BWtjju4GGbow9GqHXc1i6q0oG46k3xN0ne/ALw@a@vCJBy09OZ7OuflRxze9BcHmfkU/toNxET6iEtfyDw "C (clang) – Try It Online") * thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for saving 4+2 bytes [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes input as a string. ``` c+48 ù'A5 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Yys0OCD5J0E1&input=IjI0OCI) ``` c+48 ù'A5 :Implicit input of string c+48 :Map charcodes, adding 48 to each ù'A5 :Left pad with "A" to length 5 ``` [Answer] # [Python 3](https://docs.python.org/3/), 50 bytes ``` lambda l:''.join(chr(96+i)for i in l).rjust(5,'A') ``` Takes a list of integers as input [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHHSl1dLys/M08jOaNIw9JMO1MzLb9IIVMhM08hR1OvKKu0uETDVEfdUV3zf0FRZl6JRppGtImOsY6RjqGOcaymJhdc1ELHTMdExxRFzBgoYoQiYqkDgYZA0f8A "Python 3 – Try It Online") [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 5 bytes (10 nibbles) ``` &"A"5+'`' ``` ``` + # add each element of input '`' # to '`' character & # then justify the text "A" # using the "A" character 5 # to a width of 5 ``` [![enter image description here](https://i.stack.imgur.com/tYu9H.png)](https://i.stack.imgur.com/tYu9H.png) [Answer] # [Factor](https://factorcode.org), 29 bytes ``` [ >dec 48 v+n 5 65 pad-head ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY5NqsJAEIT3c4rai4L5kRgh4OoReLgRV8HFOOkYcRzzZjrCQzyJm2z0Fh7E2xgde9NFVX9FX--VVHy03fO8WuaLnxR7soY0HP21ZBQ5OLY7s3U4SK5HjbSO7Ed740Rv3EEfldQOjSXm_6YnGDORL1Jw3dNi_pvPlymykhRMe9iQzXyvKDTxreVqmDwKn0cJTgODGJMYjSyHNckSa3_zDNIMlTgjCoNxiGQSxQijANN-xrigQIX-EY0R1iCpaiG-ZNf5_QI) -6 from chunes. [Answer] # [Fig](https://github.com/Seggan/Fig), \$14\log\_{256}(96)\approx\$ 11.524 bytes ``` $t5$J*/A5OC+96 ``` [Try it online!](https://fig.fly.dev/#WyIkdDUkSiovQTVPQys5NiIsIls4LDYsNCw1XSJd) [Answer] # [sed](https://www.gnu.org/software/sed/), 42 bytes ``` y/123456789/abcdefghi/ :a s/^.{,4}$/A&/ ta ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlWbSSrqtS7IKlpSVpuhY3tSr1DY2MTUzNzC0s9ROTklNS09IzMvW5rBK5ivXj9Kp1TGpV9B3V9LlKEiE6oBoXbDExNjI05rIwMzHlMjYx4rIEAkOIHAA) [Answer] # Excel (ms365), ~~63~~ 61 bytes -2 Thanks to [@EngineerToast](https://codegolf.stackexchange.com/users/38183/engineer-toast) for 61 bytes: ``` =RIGHT(CONCAT("AAAA",CHAR(96+MID(A1,SEQUENCE(LEN(A1)),1))),5) ``` Or, the original answer for 63 bytes: ``` =CONCAT(MID("Aabcdefghi",MID(TEXT(A1,"00000"),ROW(1:5),1)+1,1)) ``` [![enter image description here](https://i.stack.imgur.com/E1mzH.png)](https://i.stack.imgur.com/E1mzH.png) --- Note that it can probably be done with less bytes if input is an array of numbers but thought I'd take a single integer as startpoint. [Answer] # [Julia](https://julialang.org), 48 bytes ``` ~x=replace(lpad(x,5,'A'),('1':'9'.=>'a':'i')...) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FjcN6ipsi1ILchKTUzVyChJTNCp0THXUHdU1dTTUDdWt1C3V9Wzt1BOBrEx1TT09PU2oPs3cxAKNOh2FaBNjI0NjHQULMxNTHQVjEyMdBUsgMIzVVKixUyjOyC-HaIBZCAA) # [Julia 1.0](http://julialang.org/), ~~67~~ 65 bytes ``` ~x=getindex.([Dict(0:9 .=>['A';'a':'i'])],[0;0;0;0;x][end-4:end]) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/v67CNj21JDMvJbVCTyPaJTO5RMPAylJBz9YuWt1R3Vo9Ud1KPVM9VjNWJ9rAGgIrYqNT81J0TayAZKzm/7poEx1jHSMdQx3jWIUaO4WCosy8kpw8rrpoCx0zHRMd01gFBVRxY6CoEUgUTdxSBwINkc35DwA "Julia 1.0 – Try It Online") -2 bytes thanks to @MarcMush: replace `[[0,0,0,0];x]` with `[0;0;0;0;x]` * Function is defined with the unary operater `~` * The dictionary is wrapped in an array to allow [passing multiple values](https://discourse.julialang.org/t/how-can-i-access-multiple-values-of-a-dictionary-using-a-tuple-of-keys/56868?u=ashlin_harris). * For padding, I concatenate a zero array and the input array. Only the last five elements `[end-4:end]` are used. [Answer] # POSIX Shell Command Language + Utilities, 26 bytes ``` printf %05d $1|tr 0-9 Aa-i ``` Self-explanatory: printf renders the argument padded to five columns with zeroes, then tr does the transformation per spec. Transcript of test cases: ``` $ cat a.sh; echo; wc -c a.sh printf %05d $1|tr 0-9 Aa-i 26 a.sh $ ./a.sh 8645; echo Ahfde $ ./a.sh 43213; echo dcbac $ ./a.sh 8645; echo Ahfde $ ./a.sh 342; echo AAcdb $ ./a.sh 99991; echo iiiia ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 13 bytes Full program prompting for digit number list ``` 'A'@=¯5↑⎕⊇⌊⎕A ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94L@6o7qD7aH1po/aJj7qm/qoq/1RTxeQ4QiS/a8ABgVcJgrGCkYKhgrGXDARCwUzBRMFUzjfGMgzgvMsFSDQEAA "APL (Dyalog Extended) – Try It Online") `⎕A` uppercase **A**lphabet `⌊` Lowercase that `⎕⊇` use the input to select from that (1-indexed) `¯5↑` take the last 5 elements of that, adding padding elements on the left `'A'` put "A"s where equal to the padding element [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` øA∑\A5ø↳ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiw7hB4oiRXFxBNcO44oazIiwiIiwiWzQsIDMsIDIsIDEsIDNdXG5bOCwgNiwgNCwgNV1cblszLCA0LCAyXVxuWzksIDksIDksIDksIDFdXG5bMSwgMl0iXQ==) Finally, a use for some of the more niche string digraphs. Takes input as a list of digits, outputs a single string. ## Explained ``` øA∑\A5ø↳ øA # Get the nth letter of the alphabet for each digit in the input ∑ # Join as a single string \A # Push the string "A" to the stack 5 # Push the number 5 to the stack ø↳ # And left pad the single string from early with "A"s until it's 5 characters long ``` [Answer] # [simply 0.11](https://github.com/ismael-miguel/simply/), 66 bytes This abuses bugs in the parser, to save bytes. It works with the commit [98783927a8a232b8e0afb46f380e02348b0f7cbb](https://github.com/ismael-miguel/simply/tree/98783927a8a232b8e0afb46f380e02348b0f7cbb) - current commit at the time. The behaviour will, VERY LIKELY, change in the future. Creates an anonymous function that receives an array of numbers, and outputs the value. ``` fn($L){if$l=&len($L)<5for$_ in$l..4out'A'each$L as$i;out!ABCL[$i]} ``` ## Example of usage: This should output `"AAfcf"`. ``` $fn = fn($L){if$l=&len($L)<5for$_ in$l..4out'A'each$L as$i;out!ABCL[$i]} call $fn([5,2,5]); ``` ## How it works? It simply checks the length of the array, and if it is lower than 5, it outputs 1 to 5 `'A'`s. It goes from 0 to 4 because it uses a range operator. Going from 4 to 4, is just 1 iteration - the number 4 itself. Going from 0 to 4, is 5 iterations - the number 0, number 1, number 2, number 3 and number 4. Then, it uses the pre-existing constant `!ABCL`, which contains the letters from `a` to `z`, in lowercase. The values in the array are used as indexes into the constant. ## Ungolfed Very code-y looking: ``` $fn = fn($list) => { $len = &len($list); if $len < 5 then { for $_ in $len..4 { echo 'A'; } } foreach $list as $index { echo !ABCL[$index]; } }; ``` Pseudo-code looking: ``` Set $fn to an anonymous function($list) Begin. Set $len to the result of calling &len($list). In case $len < 5 then Begin. Loop from $len to 4 as $_ Begin. Show the value 'A'. End. End. Loop through $list as $index Begin. Show the contents of !ABCL[$index]. End. End. ``` All versions do the exact same. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 12 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` (h5,'A*\É▄\§ ``` Input as a list of digits; output as string. [Try it online.](https://tio.run/##y00syUjPz0n7/18jw1RH3VEr5nDno2ktMYeW//8fbaRjqGMEhMaxXNEmOsY6ID6IbaFjpmOiYwpkGQNpIyBtqQOBhrEA) Or alternatively: ``` ▄▒\(§y♫α'A═╡ ``` Input as a list of digits; output as a string wrapped inside a list. [Try it online.](https://tio.run/##y00syUjPz0n7///RtJZH0ybFaBxaXvlo5upzG9UdH02d8Gjqwv//o410DHWMgNA4livaRMdYB8QHsS10zHRMdEyBLGMgbQSkLXUg0DAWAA) **Explanation:** ``` ( # Decrease each digit in the (implicit) input-list by 1 # (because MathGolf uses 0-based indexing) h # Push the length of the list (without popping) 5, # Calculate 5-length 'A* '# Repeat "A" that many times \ # Swap so the list as at the top again É # For-each over the digits, using 3 characters as inner code-block: ▄ # Push the lowercase alphabet \ # Swap so the current digit is at the top § # Index the digit into the alphabet # (after which the entire stack joined together is output implicitly as result) ``` ``` ▄ # Push the lowercase alphabet ▒ # Convert it to a list of characters \ # Swap so the (implicit) input-list is at the top ( # Decrease each digit by 1 (because MathGolf uses 0-based indexing) § # Index each digit in the list into the alphabet list y # Join it back together again ♫ # Push 10000 α # Pair it with the earlier string 'A═ '# Pad both to an equal length by left-padding with "A" ╡ # Remove the last item from the pair (the 10000) # (after which the entire stack joined together is output implicitly as result) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ₃+>çΔ'Aš5.£ ``` Input as a list of digits; output as a list of characters. (If the inputs would have been 0-based (digits `0-9` mapping to `a-j`) instead of 1-based, the `>` could have been dropped.) [Try it online](https://tio.run/##yy9OTMpM/f//UVOztt3h5eemqDseXWiqd2jx///RFjpmOiY6prEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/R03N2naHl5@bou54dKGp3qHF/2t1/kdHG@kY6hjpGOsYx@pEmwBpEB/EttAx0zHRMQWyjIG0EZC21IFAw9hYAA). Or alternatively: ``` 5j9LðšA¬uì‡ ``` Both input and output as a string. [Try it online](https://tio.run/##yy9OTMpM/f/fNMvS5/CGowsdD60pPbzmUcPC//8tzExMAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/0yxLn8Mbji50PLSm9PCaRw0L/@v8j1YyMjQyNlbSUTIxNjIE0RZmJqZAytjECEhaAoGhUiwA). **Explanation:** Unfortunately 05AB1E lacks a left-pad up to length builtin (unless by spaces), so most of the bytes are to account for that in the first program.. ``` ₃+> # Add 96 to each value ç # Convert each from a codepoint-integer to a character Δ # Loop until the result no longer changes: 'Aš '# Prepend an "A" 5.£ # Leave (up to) the last 5 characters from the list # (after which the result is output implicitly) ``` ``` 5j # Left-pad the (implicit) input-string with spaces up to length 5 9L # Push list [1,2,3,4,5,6,7,8,9] ðš # Prepend a space: [" ",1,2,3,4,5,6,7,8,9] A # Push the lowercase alphabet: "abcdefghijklmnopqrstuvwxyz" ¬ # Push its first character (without popping): "a" u # Uppercase it: "A" ì # Prepend it: "Aabcdefghijklmnopqrstuvwxyz" ‡ # Transliterate the space-padded input from [" ",1,2,3,4,5,6,7,8,9] to # "Aabcdefghij..." # (after which the result is output implicitly) ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), ~~17~~ 15 bytes *Edit: -2 bytes thanks to Razetime* ``` ¯5↑"AAAA"∾+⟜'`' ``` [Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=QWFhYSDihpAgwq814oaRIkFBQUEi4oi+K+KfnCdgJwpBYWFhIDHigL8y4oC/Mw==) ``` +⟜'`' # add each element of input to the '`' character ∾ # join this to "AAAA" # "AAAA" (shorter than (5⥊'A')) _5↑ # take -5 elements # (which takes 5 elements from the end) ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 64 bytes ``` >>>>>+>,[>,]<<<<<<-[---[----<+>]<++.>>-]>[<-[----->+<]>---.[-]>] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v/fDgS07XSi7XRibcBAN1pXF4x1bbTtYm20tfXs7HRj7aIhErq6dto2sXZAWi8aKBr7/7@JobkpAA "brainfuck – Try It Online") ## Explanation ``` >>>>>+> ``` Move to position 5, make the value there 1, and move to position 6. ``` ,[>,] ``` Read the digits into consecutive positions from there onward. ``` <<<<<< ``` Move 6 positions to the left. From here, each 0 before the 1 in position 5 indicates an `A` to be output. ``` -[---[----<+>]<++.>>-] ``` Subtract 1. Loop while it's not 0 (thus was not 1): * Subtract 3 more, making −4. * Loop subtracting 4 and adding 1 to the left, producing (256-4)/4=63 in the cell to the left. * Move left, add 2 more for 65, and output that (`A`). * Move right twice, for a net movement of 1 to the right, and subtract 1 (and repeat). ``` >[<-[----->+<]>---.[-]>] ``` Move right. Loop while it's not 0 (over all the digits): * Move left and subtract 1, making −1. * Loop subtracting 5 and adding 1 to the right, adding (256-1)/5=51 to the digit's character code. * Move right and subtract 3, for a net +48 to the digit's character code. 48 is the difference between `1` and `a`, and likewise for the other digits (as both digits and letters are contiguous in ASCII). * Output the letter produced from the digit. * Zero that position (as it will be reused in the next iteration) and move right (and repeat). [Answer] # [R](https://www.r-project.org), 38 bytes ``` \(d)intToUtf8(tail(c(!1:5,d+31),5)+65) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY31WI0UjQz80pC8kNL0iw0ShIzczSSNRQNrUx1UrSNDTV1TDW1zUw1oaot04CSJjrGOkY6hjrGmppcIL6FjpmOCVAdhGcMZBtB2ZY6EGioCTVgwQIIDQA) Takes input as a vector of digits, outputs a string. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 21 bytes ``` T`d`_l ^ AAAA !`.{5}$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyQhJSE@hyuOyxEIuBQT9KpNa1X@/zcxNjI05rIwMzHlMjYx4rIEAkMA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` T`d`_l ``` Translate digits to lowercase letters. ``` ^ AAAA ``` Prefix four `A`s. ``` !`.{5}$ ``` Take the last 5 letters. A port of @Jiří's sed answer is also 21 bytes: ``` T`d`_l +`^.{0,4}$ A$& ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyQhJSE@h0s7IU6v2kDHpFaFy1FF7f9/E2MjQ2MuCzMTUy5jEyMuSyAwBAA "Retina 0.8.2 – Try It Online") Link includes test cases. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 9 bytes ``` .[\A5m@Gt ``` [Test suite](https://pythtemp.herokuapp.com/?code=.%5B%5CA5m%40Gt&test_suite=1&test_suite_input=%5B4%2C3%2C2%2C1%2C3%5D%0A%5B8%2C6%2C4%2C5%5D%0A%5B3%2C4%2C2%5D%0A%5B9%2C9%2C9%2C9%2C1%5D&debug=0) This answer uses a sufficiently different approach from the existing Pyth answer(s). ##### Explanation: ``` .[\A5m@Gt | Full code .[\A5m@GtdQ | with implicit variables ------------+---------------------------------------------------- m Q | Replace each number d in the input with @G | the character of the lowercase alphabet with index td | d minus 1 .[\A5 | Pad the array on the left with A to a length of 5 ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 13 bytes ``` "A"^-5$`c$96+ ``` [Try it online!](https://ngn.codeberg.page/k/#eJxNj81qwzAQhO96ikX40FIU4d/YEhR87KkPEFIsyfIPSeTWlqlNaZ+9slxCZ077McvONgyX+I2kQaWCIntCyLKv4LT+jKwBgIVXw4U/VI3or3zhKx8fz9/InkL4M8diEz47GDkQOcccSyGl8tAhjsuyFNKPCcSw5VymVlLsmRwySCB1ua6ptUexA35R1ftiAbvdxd5pu4go6qx9nxilaqh1O1ybw2SFuuhFdcK0+qCGG/2Y9WT7wUw0SqNjmlMz36QeiR3IZMfetKQ3xD9BPsWK0IthkMRRGAN5htfZMvBFPc+zJIU79209j5MI/vGttOeFU3jnvvcvN7RnGg==) * ``c$96+` convert input of digits to corresponding letters * `-5$` left-pad to length 5 with spaces * `"A"^` fill spaces with "A" (and implicitly return) [Answer] # [Python](https://docs.python.org/3.8/), ~~42~~ 41 bytes -1 thanks to [loopy walt](https://codegolf.stackexchange.com/users/107561/loopy-walt)'s suggestion to use XOR, `^`, instead of addition. ``` lambda a:[chr(96^d)for d in[33]*5+a][-5:] ``` An unnamed function that accepts a list of integers from \$[1,9]\$ and returns a list of characters. **[Try it online!](https://tio.run/##PYzBDoIwGIPvPkVvbPp7gAkBEnyROZPpXCBRWOYuhvDsc/Ng08PXNqn7hHGZRet8tMMlPvXrZjR0L@@jZ11zNdwuHgbTLIVQ@/qglTzWvYq5Do93SAuYPBEEoSKUCRRBtoSGkOo6J/HDKmNH@LtUvN8hyflpDswWlq35c@MYzlgty4FvBY9f "Python 3.8 (pre-release) – Try It Online")** [Answer] # [Thon](https://github.com/nayakrujul/thon), 19 bytes ``` n"Aabcdefghi"b5"A"J ``` Input as a number (e.g. `824`). Output as a string (e.g. `AAhbd`). **Explanation** ``` n"Aabcdefghi"b5"A"J n // Input a number "Aabcdefghi" // Push the string of letters b // Convert the number to Base-"Aabcdefghi" (see below) 5"A"J // Fill with "A" up to 5 characters // (implicit output) ``` Converting to base-`"Aabcdefghi"` is a trick to replace every `"1"` with `"a"`, every `"2"` with `"b"`, etc. # [Thon (Symbols)](https://github.com/nayakrujul/thon-symbols), 16 [bytes](https://github.com/nayakrujul/thon-symbols/blob/main/Codepage.md) (Note: this language is newer than the challenge) ``` )ş{í1-å`;}""]5AṚ ``` **Explanation** ``` )ş{í1-å`;}""]5AṚ ) // Create an empty list ş // Get input as a string { } // For each character in the input: í // Convert to an integer 1- // Subtract 1 å` // Push the lowercase alphabet and get the character ; // Append to the list ""] // Join the list by an empty string 5AṚ // Fill the string with "A" up to 5 characters // (implicit output) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes ``` ✂⁺×⁴A⭆S§β⊖ι±⁵ ``` [Try it online!](https://tio.run/##JYpBCoMwFAWvElw9Id1pKXQldOOiItgLpPFhAzGV@C29/W@gsxtm/Mtl/3ZRdcwhCaYYPDHGY8cjrNzRWFN1VW3NJGVY7m5Dn7ZD/ooSOunTzC@e1tzoM1cm4YxQF6wZuDgh2iJX1cu5afX0iT8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` A Literal string `A` × Repeated ⁴ Literal integer `4` ⁺ Concatenated to S Input as a string ⭆ Map over digits β Predefined variable lowercase alphabet § Indexed by ι Current digit ⊖ Decremented ✂ Sliced from ⁵ Literal integer `5` ± Negated ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 18 bytes ``` V-5lzp"A")Vzp@GtsN ``` [Try it online!](https://tio.run/##K6gsyfj/P0zXNKeqQMlRSTOsqsDBvaTY7/9/YxMjAA "Pyth – Try It Online") ### Explanation ``` V-5lzp"A")Vzp@GtsN V # For loop with N as variable z # Input l # Length -5lz # Subtract length of input from 5 p"A" # Prints "A" ) # End of for loop p # Print without any additional newline G # Initialized to "abcdefghijklmnopqrstuvwxyz" sN # Cast N to an integer t # Subtract 1 @ # Get element at index ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 39 bytes ``` -join($args|%{[char](96+$_)})|% *ft 5 A ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkqZgq1D9XzcrPzNPQyWxKL24RrU6OjkjsShWw9JMWyVes1azRlVBK61EwVTB8X8tl5oCUIuJgrGCkYKhgjGEa6FgBhQyhXCMgUwjCNMSCg3/AwA "PowerShell – Try It Online") Takes integers as unnamed arguments. Nothing fancy, just adds 96 to get to the ASCII code of 'a', casts to a char, joins the chars to a string, then pipes the string to % (an alias for ForEach-Object), which will call the string's member "PadLeft". Output is implicit. [Answer] # [Ruby](https://www.ruby-lang.org/), 37 bytes -3 bytes thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus) ``` ->a{a.map{''<<_1+96}.join.rjust 5,?A} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY3VXXtEqsT9XITC6rV1W1s4g21Lc1q9bLyM_P0irJKi0sUTHXsHWuhij0LSkuKFdKio010jHWMdAx1jGNjuWBiFjpmOiY6pkgixkC-ERLfUgcCDWNjIQYuWAChAQ) [Answer] # [J-uby](https://github.com/cyoce/J-uby), 34 bytes I think I’m finally starting to get the hang of J-uby. A few bytes shorter than [my Ruby answer](https://codegolf.stackexchange.com/a/252777/11261). ``` :*&(:+&96|:chr)|:join|~:rjust&?A&5 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWN5WstNQ0rLTVLM1qrJIzijRrrLLyM_Nq6qyKskqLS9TsHdVMoSo9C0pLihXcoqNNdIx1jHQMdYxjY7lgYhY6ZjomOqZIIsZAvhES31IHAg1jYyEGLlgAoQE) ]
[Question] [ Your goal is simple: the program must turn the screen of your computer **totally black**. After the program is started, the screen must quickly turn completely black, and remain so until the program is exited (any key, or alt+F4, mouse movement, etc.), after which things should turn back to normal. So **shutting down the computer or turning the power of the monitor off is NOT allowed**. Not a single non-black pixel should be visible during this time, not even a blinking cursor. The user should not do any preparation (moving the mouse outside the screen, disconnecting cables, etc. or user input after the program started), just start the program. You can safely assume the computer has only one monitor attached. We also assume a standard desktop or notebook computer, because doing it on a specific device without a normal monitor would be too simple. If you use any external resources (a black image, a GUI file, etc.) their size in bytes is added to your code size. It's OK if it only works on one OS family, or if it requires opengl etc., but requiring a very specific hardware configuration is frowned upon. Your source code must be written in a programming language, not just a configuration file some other program (like a screen saver) will use. [Answer] **Assembly** (bootloader) 131 chars / 512 bytes compiled (actually smaller, but bootsector must be 512 bytes long.) It is a simple boot loader. When computer starts, BIOS will load it from disk (floppy). Then it enters into graphics mode and just hangs. When user presses the power button, program will end and computer will enter to mode where is was before running program. Tested with VirtualBox. It will compile with nasm: ``` nasm -f bin file.asm -o start.img ``` Source code: ``` [BITS 16] [ORG 0x7C00] cli mov AX,0x0 mov SS,AX mov SP,0x9000 sti mov AH,0x0 mov AL,0x13 int 0x10 times 510 - ($-$$) db 0 dw 0xAA55 ``` [Answer] ## Bash, 28 or 12 Assuming default installation of Ubuntu 12.04 LTS. ``` gnome-screensaver-command -a ``` Automatically starts the screensaver, which is a black screen by default. **Edit**: As suggested by @Glenn Randers-Pehrson, here's one with 12 bytes ``` /*/*/gn*d -a ``` Note that this may not work if you have another file on your system that satisfies this name, say `/tmp/1/gnd`. But it's code-golf, who cares? --- Check out [my other bash answer](https://codegolf.stackexchange.com/a/26793/12205) if you don't use Gnome screensaver! [Answer] # QBASIC (31) ``` SCREEN 7 WHILE INKEY$="" WEND ``` [Answer] # Java : 165 Simple Java, just creates a fullscreen black frame. To exit you have to Alt+Tab back to the console and Ctrl-C, but that seems simple enough. ``` import java.awt.*;class B{public static void main(String[]a){Frame f=new Frame();f.setExtendedState(6);f.setUndecorated(1>0);f.setBackground(Color.BLACK);f.show();}} // line breaks below import java.awt.*; class B{ public static void main(String[]a){ Frame f=new Frame(); f.setExtendedState(6); f.setUndecorated(1>0); f.setBackground(Color.BLACK); f.show(); } } ``` [Answer] Applesoft ][ BASIC (17) ``` 1 HGR2:GET X:TEXT ``` [Answer] # Bash - 57 ~~26~~ ``` C=/s*/*/*/*/b*ess;(A=$(cat $C);echo 0;cat;echo $A)|tee $C ``` On a laptop this will set the screen backlight brightness to 0 via `/sys/class/backlight`, on a tablet or phone this will set the screen led brightness to 0 via `/sys/class/leds` [Answer] I know this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") but I couldn't resist. Just make sure you don't have any browser windows open (in this case, Chrome); Execute this **PitchBlack.bat (~~31~~ 24 bytes)**: ``` chrome --kiosk file:///1 ``` If placed in the same directory of your *Chrome.exe* file, this batch will execute Chrome in **kiosk mode** and it will open a file called **/1 (~~49~~ ~~41~~ 34 bytes)** in fullscreen: ``` <body bgcolor=0 style=cursor:none> ``` *Et voilà!* **Total byte count: ~~80~~ ~~72~~ 58** Thanks to @ace :) To exit the program, you must go for a classic **ALT+F4**; You don't actually have to do any preparation *after* the program starts (neither before, you just have to place `/1` and the batch file), so it's fine with the rules. Please note that if you get your cursor towards the screen borders, it *may* become visible. The OP didn't say this was not allowed, since > > After the program is started, the screen must quickly turn completely black, and remain so until the program is exited (any key, or alt+F4, **mouse movement**, etc.), after which things should turn back to normal. > > > So this should be totally ok! :P [Answer] # C# - ~~211~~ ~~202~~ ~~200~~ ~~196~~ 179 bytes ``` using System.Windows.Forms;class A{static void Main(){Cursor.Hide();new Form{BackColor=System.Drawing.Color.Black,WindowState=(FormWindowState)2,FormBorderStyle=0}.ShowDialog();}} ``` Hides the cursor and shows a full-screen black window. Can be closed with `Alt`+`F4` **Un-golfed code**: ``` using System.Windows.Forms; class A { static void Main() { Cursor.Hide(); new Form { BackColor = System.Drawing.Color.Black, WindowState = (FormWindowState)2, // FormWindowState.Maximized FormBorderStyle = 0 // FormBorderStyle.None }.ShowDialog(); } } ``` I don't need to cast to `FormBorderStyle`, because that's not necessary if the integer is `0`. [Answer] # C# ~~175~~ ~~171~~ 167 ``` class P{static void Main(){SendMessage(65535,274,61808,2);}[System.Runtime.InteropServices.DllImport("user32")]static extern int SendMessage(int a,int b,int c,int d);} ``` A lot of the answers here don't actually make the screen *black*: on an LCD screen, the backlight remains on and bleeds through, leaving you with a darkish grey. This little snippet actually tells Windows to turn off the screen, the same as what the inactivity timer does (Note: this doesn't violate the "no power off" rule because it really just causes the monitor to go into standby. *Most* monitors will turn back on when input is resumed. Also, that rule's intention seems to be to make sure the program can turn it back on - see below.) Move the mouse or press a key to turn the screen back on. Monitor power off adapted from <https://stackoverflow.com/a/713519/1030702> [Answer] # Amiga assembly ASM-One - ~~228~~ 219 chars, 172 bytes compiled (168 bytes optimized) It's been 20 years since I last coded a single line in Amiga assembly, so bear with me. :-) The Amiga was a bit more involved than the PC in terms of setting up a blank screen, so tried to get rid of as much setup and teardown as possible. There's no disabling of interrupts or multitasking; no double WaitTOF; no view replacement; etc. I wouldn't even have written this for the quickest and dirtiest demo. Which means this: * is bad practice * may not be entirely safe * may not always work * even with those disclaimers, probably has stupid mistakes owing to 20 years of neglected assembly. ... although it's been tested on emulated A500 and A1200, with or without fast memory. Compiles to a standard executable. Mouse click exits. ``` l=$dff080 move.l 4,a6 lea g,a1 jsr -408(a6) move.l d0,a1 move.l 38(a1),d4 jsr -412(a6) move.l #c,l w:btst #6,$bfe001 bne w move.l d4,l rts g:dc.b "graphics.library",0 SECTION d,DATA_C c:dc 256,512,384,0,-1,-2 ``` Less golfed: ``` COP1LC equ $dff080 move.l $4, a6 ; ExecBase lea gfxname, a1 jsr -408(a6) ; OpenLibrary (old, hence no need for clearing d0) move.l d0, a1 move.l 38(a1), d4 ; store copper list jsr -414(a6) ; CloseLibrary ; Yeah, if I had a penny for the times I saw that left out ; but I just... can't... move.l #copper,COP1LC ; write copper list wait: btst #6, $bfe001 ; Check mouse click bne wait move.l d4, COP1LC ; restore copper list rts gfxname: dc.b "graphics.library", 0 SECTION data, DATA_C copper: dc.w $0100, $0200 ; disable bitplanes dc.w $0180, $0000 ; color 0 = black dc.w $ffff, $fffe ; end ``` [Answer] # Python / Pygame 199 127 125 92 ``` from pygame import*;display.set_mode((9,9),-1<<31);mouse.set_visible(0) while 1:event.pump() ``` Thanks to some tips from ace. [Answer] # TI-BASIC, 7 6 ``` Shade(Ymin,Ymax ``` Works both in the terminal (home screen) or as a program. Pressing `ON` or most other buttons returns to the terminal/home screen. [Answer] # Commodore 64 (16 bytes) ``` ROL $A903 BRK STA $D020 STA $D011 JSR $FF8A JMP ($032C) ``` It has been more than 20 years since I used Turbo Assembler, so I can only provide source for use in VICE's monitor. Assemble this at $032C and `save`[1] through $033B. `Reset` and `LOAD"PITCHDARK",8,1`. Hit good ol' `Runstop+Restore`[2] to get back to normal. How does it work? Here's the true source: ``` 032C 2E 03 .BY 2E 03 032E A9 00 LDA #$00 0330 8D 20 D0 STA $D020 ; set border color 0333 8D 11 D0 STA $D011 ; set VIC blanking mode 0336 20 15 FD JSR $FF8A ; reset the vectors we trampled 0339 6C 2C 03 JMP ($032C) ; call the real CLALL ``` $032C is the [kernal](http://en.wikipedia.org/wiki/KERNAL) `CLALL` or "Close All Channels And Files" vector. As part of its cleanup, the BASIC `LOAD` command does a `CLR` which in turn calls `CLALL`. We replace the `CLALL` vector with a pointer to our own routine immediately after the vector. We set the border to black and cover the screen with the border, and then call `RESTOR` at $FF8A. The last vector replaced by `RESTOR` is `SAVE` at $0332-0333 which means the last 8 bytes are undisturbed. We then exit via the restored `CLALL` vector to continue `LOAD`'s execution. Thanks for this, it was fun trip down memory lane, relearning how to do an autorun program :) [1] use save and not bsave so that load with ,1 works correctly [2] Escape + PageUp in x64, probably. [Answer] ## sh/X11 on Arch Linux, 26 ``` b=/b*/*ht;$b =0;read;$b =7 ``` [Answer] # Bash, 37 Uses `unclutter` to hide the mouse pointer and a fullscreen session of `xterm` to black the screen. The cursor will reappear for a moment if you move it, but if you leave it alone the screen will be black until you press Ctrl+C. It will take a few seconds for the mouse cursor to disappear (as long as you don't move it). If this isn't fast enough, add the `-grab` option to `unclutter` for an additional 6 chars. ``` unclutter&xterm -fu -bg black -e yes '' ``` **WARNING:** this will leave a process of `unclutter` running even after you press Ctrl+C, use `killall unclutter` to stop it. ## Explanation `unclutter &` launches `unclutter`. The `&` is there so we can get on with the next command instead of waiting for this one to terminate. `xterm -fullscreen` launches XTerm, whose background is black by default. The `-e yes ''` option causes XTerm to run `yes ''`, thereby printing the empty string forever. This serves to hide the terminal cursor, and also provides the Ctrl+C functionality. [Answer] ## Bash, 31 (or 52) On a TTY, use the following script (assuming your default TTY background is black, which is true at least for Ubuntu 12.04 LTS): ``` setterm -foreground black clear ``` Your TTY would still be fully functional even after using this script :) If this isn't allowed, use the following (52 bytes): ``` x='setterm -foreground' $x black clear read $x white ``` And press `Enter` to terminate the script. Special thanks to @nyuszika7h. [Answer] # Processing, 113 ``` void setup(){noCursor();size(displayWidth, displayHeight);background(0);}boolean sketchFullScreen(){return true;} ``` I tried putting the code above onto draw() to save some bytes, but it didn't work. Press Alt-F4 to quit. [Answer] # ZX Spectrum Basic (29 bytes) ``` 1 FOR x=0 TO 255 2 FOR y=0 TO 175 3 PLOT x,y 4 NEXT y 5 NEXT x ``` Iterates over the screen, plotting black pixels which are automatically cleared when the program finishes. The ZX Spectrum's edition of basic uses single bytes as commands and no newlines, if counting displayed characters you get 61 chars. [Answer] ## Lua + LÖVE (50) ``` love.mouse.setVisible()love.window.setFullscreen"" ``` Both functions are supposed to take a boolean argument, yet this works. [Answer] ## QBasic, 9 bytes ``` CLS:SLEEP ``` `CLS` clears the screen, `SLEEP` without any arguments holds execution until a key is pressed. [Answer] # SmileBASIC, 15 bytes ``` XSCREEN 4 EXEC. ``` Pressing START or SELECT will end the program. `XSCREEN 4` sets the display mode to show a 320\*480 image spanning both screens. This should clear everything, so an `ACLS` is not required. `EXEC.` makes the code repeat by constantly running the program in slot 0. I wasn't able to do `XSCREEN 4EXEC.` because you can't have a number directly before `E` [Answer] # Sinclair BASIC - 28 chars ``` BORDER 0:PAPER 0:CLS:PAUSE 0 ``` The thing about Sinclair BASIC was each keyword had it's own character code (taking up one byte), so this would actually take up 13 bytes including spaces. [Answer] # SmileBASIC, 23 bytes Runs forever until the program is force-killed with START or SELECT. This makes both screens *completely black*, going so far to disable 3D (thus turning off the 3D LED on o3DS.) ``` ACLS:XSCREEN 3@L GOTO@L ``` [Answer] # Most POSIX compatible shells (at least `bash` and `zsh`), 21 Needs to be run on a tty ``` tput civis;clear;read ``` First command hides the cursor, second command clears the screen (duh) and third command reads a line of text [Answer] # BASH - 14 chars `pmset sleepnow` does the job! (typed into my Mac's Terminal) [Answer] # Bash: 48 characters ``` eval xrandr\ --output\ DP1\ --{off,auto}\;read\; ``` CW because not clear whether it qualifies due to the way it works: * The produced black screen is real power saving: it cuts off information sending to display 1. * Many computer displays when detect signal loss, will temporarily or periodically show their own notice. (Note that DP1 is the first *connected* display. If you have a laptop, its embedded display is eDP1.) [Answer] # [HTML Application](https://en.wikipedia.org/wiki/HTML_Application) (.hta), 102 bytes ``` <HTA:APPLICATION CAPTION=no innerborder=0 border=dialog scroll=0 windowstate=maximize><body bgcolor=0> ``` [Answer] # TI-80 BASIC, 5 bytes ``` ZOOM OUT ZOOM OUT GRIDON ``` [Answer] # Chip-8, 0 bytes > > [T]he original Chip-8 interpreter began execution from 0x01FC. The interpreter includes two permanent Chip-8 instructions at this location that are always executed at the start of every programme. The first of these, 0x00E0, clears the display RAM by setting all the bits to zero. The second, 0x004B, calls a machine language routine within the interpreter that switches the VIP’s display on. > > > Source: <http://laurencescotford.co.uk/?p=75> ]
[Question] [ **Write a program that count from 1 to 100 in [Roman Numerals](http://en.wikipedia.org/wiki/Roman_numerals)** and print these numbers by standard output. Each one of the numbers must be separated by spaces. You cannot use any built in function to transform to roman numerals nor external application or library to do so. The desired result is ``` I II III IV V VI VII VIII IX X XI XII XIII XIV XV XVI XVII XVIII XIX XX XXI XXII XXIII XXIV XXV XXVI XXVII XXVIII XXIX XXX XXXI XXXII XXXIII XXXIV XXXV XXXVI XXXVII XXXVIII XXXIX XL XLI XLII XLIII XLIV XLV XLVI XLVII XLVIII XLIX L LI LII LIII LIV LV LVI LVII LVIII LIX LX LXI LXII LXIII LXIV LXV LXVI LXVII LXVIII LXIX LXX LXXI LXXII LXXIII LXXIV LXXV LXXVI LXXVII LXXVIII LXXIX LXXX LXXXI LXXXII LXXXIII LXXXIV LXXXV LXXXVI LXXXVII LXXXVIII LXXXIX XC XCI XCII XCIII XCIV XCV XCVI XCVII XCVIII XCIX C ``` As it is a code golf challenge, **shortest code wins**. [Answer] ## Perl 69 bytes ``` s;.;y/XVI60-9/CLXVIX/dfor$a[$_].="32e$&"%72726;gefor 1..100;print"@a" ``` Works by way of magic formula. The expression `"32e$&"%72726` transforms each digit in the following manner: *0⇒32, 1⇒320, 2⇒3200, 3⇒32000, 4⇒29096, 5⇒56, 6⇒560, 7⇒5600, 8⇒56000, 9⇒50918* After applying the translation `y/016/IXV/`, we have this instead: *0⇒32, 1⇒32**I**, 2⇒32**II**, 3⇒32**III**, 4⇒29**I**9**V**, 5⇒5**V**, 6⇒5**VI**, 7⇒5**VII**, 8⇒5**VIII**, 9⇒5**I**9**X**8* The rest of the digits (`2-57-9`) are removed. Note that this could be improved by one byte by using a formula which translates `012` instead of `016`, simplifying `/XVI60-9/` to `/XVI0-9/`. I wasn't able to find one, but maybe you'll have better luck. Once one digit has been transformed in this manner, the process repeats for the next digit, appending the result, and translating the previous `XVI`s to `CLX` at the same time the translation for the new digit occurs. **Update** Exhaustive search didn't reveal anything shorter. I did, however, find an alternative 69 byte solution: ``` s;.;y/XVI0-9/CLXIXV/dfor$a[$_].="57e$&"%474976;gefor 1..100;print"@a" ``` This one uses a `0-2` substitution for `IXV`, but has a modulo that's one digit longer. --- ## Update: ~~66~~ 65 bytes This version is notably different, so I should probably say a few words about it. The formula it uses is actually one byte longer! Unable to shorten the formula any more than it is, I decided to golf down what I had. It wasn't long until I remembered my old friend `$\`. When a `print` statment is issued, `$\` is automatically appended to the end of the output. I was able to get rid of the awkward `$a[$_]` construction for a two byte improvement: ``` s;.;y/XVI60-9/CLXVIX/dfor$\.="32e$&"%72726;ge,$\=!print$"for 1..100 ``` Much better, but that `$\=!print$"` still looked a bit verbose. I then remembered an alternative, equal length formula I had found which didn't contain the number `3` in any of its digit transforms. So, it should be possible to use `$\=2+print` instead, and substitute the resulting `3` with a space: ``` s;.;y/XVI0-9/CLXIIX V/dfor$\.="8e$&"%61535;ge,$\=2+print for 1..100 ``` Also 67 bytes, due to the necessary whitespace between `print` and `for`. > > **Edit**: This can be improved by one byte, by moving the `print` to the front: > > > > ``` > $\=2+print!s;.;y/XVI0-9/CLXIIX V/dfor$\.="8e$&"%61535;gefor 1..100 > > ``` > > Because the substitution needs to evaluate completely before the `print`, the assignment to `$\` will still occur last. Removing the whitespace between `ge` and `for` will issue a deprecation warning, but is otherwise valid. > > > But, if there were a formula which didn't use a `1` anywhere, `$\=2+print` becomes `$\=print` for another two bytes worth of savings. Even if it were one byte longer, it'd still be an improvement. As it turns out, such a formula does exist, but it is one byte longer than the original, resulting in a final score of **65 bytes**: ``` $\=print!s;.;y/XVI60-9/CLXXI V/dfor$\.="37e$&"%97366;gefor 1..100 ``` --- ## Methodology The question was asked how one might go about finding such a formula. In general, finding a magic formula to generalize any set of data is matter of probability. That is, you want to choose a form which is as likely as possible to produce something similar to the desired result. Examing the first few roman numerals: ``` 0: 1: I 2: II 3: III 4: IV 5: V 6: VI 7: VII 8: VIII 9: IX ``` there is some regularity to be seen. Specifically, from *0-3* and then again from *5-8*, each successive term increases in length by one numeral. If we wanted to create a mapping from digits to numerals, we would want to have an expression that *also* increases in length by one digit for each successive term. A logical choice is *k • 10d* where *d* is the corresponding digit, and *k* is any integer constant. This works for *0-3*, but *4* needs to break the pattern. What we can do here is tack on a modulo: *k • 10d % m*, where *m* is somewhere between *k • 103* and *k • 104*. This will leave the range *0-3* untouched, and modify *4* such that it won't contain four `I`s. If we additionally constrain our search algorithm such that the modular residue of *5*, let's call it *j*, is less than *m / 1000*, this will ensure that we also have regularity from *5-8* as well. The result is something like this: ``` 0: k 1: k0 2: k00 3: k000 4: ???? 5: j 6: j0 7: j00 8: j000 9: ???? ``` As you can see, if we replace `0` with `I`, *0-3* and *5-8* are all guaranteed to be mapped correctly! The values for *4* and *9* need to be brute forced though. Specifically, *4* needs to contain one `0` and one `j` (in that order), and *9* needs to contain one `0`, followed by one other digit that doesn't appear anywhere else. Certainly, there are a number of other formulae, which by some fluke of a coincidence might produce the desired result. Some of them may even be shorter. But I don't think there are any which are as likely to succeed as this one. I also experimented with multiple replacements for `I` and/or `V` with some success. But alas, nothing shorter than what I already had. Here is a list of the shortest solutions I found (the number of solutions 1-2 bytes heavier are too many to list): ``` y/XVI60-9/CLXVIX/dfor$\.="32e$&"%72726 y/XVI0-9/CLXIXV/dfor$\.="57e$&"%474976 y/XVI0-9/CLXIVXI/dfor$\.="49e$&"%87971 y/XVI0-9/CLXIIXIV/dfor$\.="7e$&"%10606 # y/XVI0-9/CLXIIXIV/dfor$\.="7e$&"%15909 # These are all essentially the same y/XVI0-9/CLXIIXIV/dfor$\.="7e$&"%31818 # y/XVI0-9/CLXIIX V/dfor$\.="8e$&"%61535 # Doesn't contain 3 anywhere y/XVI60-9/CLXXI V/dfor$\.="37e$&"%97366 # Doesn't contain 1 anywhere ``` [Answer] # HTML + JavaScript + CSS (137) HTML (9) ``` <ol></ol> ``` JavaScript (101) ``` for(i=1;i<=100;i++){document.getElementsByTagName('ol')[0].appendChild(document.createElement('li'))} ``` CSS (27) ``` ol{list-style:upper-roman​} ``` Output ![Numbered list with roman numerals](https://i.stack.imgur.com/khaj3.png) ... [Demo on JSBin](http://jsbin.com/unotis/1/edit) [Answer] # Python 116 better golfed code of scleaver's answer: ``` r=lambda a,b,c:('',a,2*a,3*a,a+b,b,b+a,b+a+a,b+3*a,a+c);print' '.join(i+j for i in r(*'XLC')for j in r(*'IVX'))+' C' ``` [Answer] # Python, 139 ``` print' '.join(' '.join(i+j for j in ' _I_II_III_IV_V_VI_VII_VIII_IX'.split('_'))for i in ' _X_XX_XXX_XL_L_LX_LXX_LXXX_XC'.split('_'))+' C' ``` [Answer] ## C, 177 160 147 chars There are shorter solutions, but none in C, so here's my try. New solution, completely different from my previous one: ``` char*c; f(n){ printf("%.*s",n%5>3?2:n%5+n/5,c+=n%5>3?n%4*4:2-n/5); } main(i){ for(;i<100;putchar(32)) c="XLXXXC",f(i/10), c="IVIIIX",f(i++%10); puts("C"); } ``` ## Previous solution (160 chars): Logic: 1. `f` prints a number from 1 to 10. `c` is the digits used, which can be `IVX` or `XLC`. Called once for the tens once for the ones. 2. If `n%5==0` - print nothing or `c[n/5]` which is `I` or `V` (or `L` or `C`). 3. If `n%4==4` - `4` or `9` - print `I` (or `X`), by `n+1`. 4. If `n>4` - print `5` (i.e. `V` or `L`) then `n-5`. 5. If `n<4` - print `I` then `n-1` (i.e. `n` times `I`). ``` char*c; p(c){putchar(c);} f(n){ n%5? n%5>3? f(1),f(n+1): n>4? f(5),f(n-5): f(n-1,p(*c)): n&&p(c[n/5]); } main(i){ for(;++i<101;p(32)) c="XLC",f(i/10), c="IVX",f(i%10); p(10); } ``` [Answer] # Mathematica 159 150 142 ``` c = {100, 90, 50, 40, 10, 9, 5, 4, 1}; Table["" <> Flatten[ConstantArray @@@ Thread@{StringSplit@"C XC L XL X IX V IV I", FoldList[Mod, k, Most@c]~Quotient~c}], {k, 100}] ``` ![roman numerals](https://i.stack.imgur.com/AlFCK.png) --- **Built-in solution**: `IntegerString`, 38 chars ``` IntegerString[k, "Roman"]~Table~{k, 100} ``` [Answer] ## JavaScript, 123 Inspired by a longer version I came across in a Polish newsgroup (at least, Chrome thought it was Polish). ``` for(i=100,a=[];n=i--;a[i]=r) for(r=y='',x=5;n;y++,x^=7) for(m=n%x,n=n/x^0;m--;) r='IVXLC'[m>2?y+n-(n&=-2)+(m=1):+y]+r; alert(a) ``` [Answer] # Q (~~81~~ 80) 2nd cut: ``` 1_,/'[($)``X`XX`XXX`XL`L`LX`LXX`LXXX`XC cross``I`II`III`IV`V`VI`VII`VIII`IX],"C" ``` 1st cut: ``` 1_,/'[$:[``X`XX`XXX`XL`L`LX`LXX`LXXX`XC cross``I`II`III`IV`V`VI`VII`VIII`IX]],"C" ``` [Answer] ## Python, 168 ``` r=lambda n,l,v:(r(n,l[1:],v[1:])if n<v[0]else l[0]+r(n-v[0],l,v))if n else'' for i in range(1,101):print r(i,'C XC L XL X IX V IV I'.split(),[100,90,50,40,10,9,5,4,1]), ``` **Explanation** Using these values, take the largest value not greater than n and subtract it from n. Repeat until n is 0. ``` 'C' = 100 'XC' = 90 'L' = 50 'XL' = 40 'X' = 10 'IX' = 9 'V' = 5 'IV' = 4 'I' = 1 ``` [Answer] ## Ruby 1.9, 140 132 ``` r=" " 100.times{r+=?I 0while[[?I*4,"IV"],["VIV","IX"],[?X*4,"XL"],["LXL","XC"],[/(.)((?!\1)[^I])\1/,'\2']].any?{|q|r.sub! *q} $><<r} ``` This literally counts from 1 to 100 in Roman numerals. Starts with a blank string, then loops through appending "I" and then repeatedly applying a series of substitution rules, effectively adding 1. Edit: Added version number, since `?I` only works in 1.9, and used @Howard's changes to trim some characters. [Answer] ## Ruby 112 chars ``` 101.times{|n|r=' ';[100,90,50,40,10,9,5,4,1].zip(%w(C XC L XL X IX V IV I)){|(k,v)|a,n=n.divmod k;r<<v*a};$><<r} ``` Basically using the `to_roman` method [explained here](http://www.rubyquiz.com/quiz22.html), but using a zipped array for brevity. [Answer] **perl 205** ``` @r = split //, "IVXLC"; @n = (1, 5, 10, 50, 100); for $num (1..100) { for($i=@r-1; $i>=0; $i--) { $d = int($num / $n[$i]); next if not $d; $_ .= $r[$i] x $d; $num -= $d * $n[$i]; } $_ .= " "; } s/LXXXX/XC/g; s/XXXX/XL/g; s/VIIII/IX/g; s/IIII/IV/g; print; ``` Golfed: ``` @r=split//,"IVXLC";@n=(1,5,10,50,100);for$num(1..100){for($i=@r-1;$i>=0;$i--){$d=int($num/$n[$i]);next if!$d;$_.=$r[$i]x$d;$num-=$d*$n[$i];}$_.=" ";}s/LXXXX/XC/g;s/XXXX/XL/g;s/VIIII/IX/g;s/IIII/IV/g;print; ``` [Answer] **MUMPS 184** ``` S V(100)="C",V(90)="XC",V(50)="L",V(40)="XL",V(10)="X",V(9)="IX",V(5)="V",V(4)="IV",V(1)="I" F I=1:1:100 S S=I,N="" F Q:'S S N=$O(V(N),-1) I S&(S'<N ) S S=S-N W V(N) S N="" w:'S " " ``` Same algorithm as @cardboard\_box, from whom I've taken the explanation verbatim - **Explanation** Using these values, take the largest value not greater than n and subtract it from n. Repeat until n is 0. ``` 'C' = 100 'XC' = 90 'L' = 50 'XL' = 40 'X' = 10 'IX' = 9 'V' = 5 'IV' = 4 'I' = 1 ``` [Answer] # [R](https://www.r-project.org/), 85 bytes ``` R=.romans for(r in 1:100){while(r>0){cat(names(R[I<-R<=r][1])) r=r-R[I][1]} cat(" ")} ``` [Try it online!](https://tio.run/##K/r/P8hWryg/NzGvmCstv0ijSCEzT8HQytDAQLO6PCMzJ1WjyA7ITE4s0chLzE0t1giK9rTRDbKxLYqNNozV1OQqsi3SBYqBeLVcIGVKCkqatf//AwA "R – Try It Online") Uses the random `utils` package variable `.romans` to get the *values* of the roman numerals, but does the conversion by itself; the builtin approach would be 20 bytes: `cat(as.roman(1:100))` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 61 [bytes](https://github.com/abrudz/SBCS) ``` ∊{'IVXLC'[∊5 3 1+{(⍺=0)↓⍺↑⍨⊃¯2,⍨⍵~0}⌿0 5⊤1+⍵⊤⍨3⍴10],' '}¨⍳100 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9DUh0Vat7hkX4OKtHA9mmCsYKhtrVGo96d9kaaD5qmwxkPGqb@Kh3xaOu5kPrjXRArN6tdQa1j3r2GyiYPupaYqgNFADSQBnjR71bDA1iddQV1GsPAdVtNjQwAFnzPw0A "APL (Dyalog Unicode) – Try It Online") (I know there's already an APL answer, but wanted to re-solve it anyway) Adapted and golfed from Nikolay Nikolov's piece of code that supports up to M at the bottom of [this page](http://dfns.dyalog.com/n_roman.htm). ### How it works ``` ∊{'IVXLC'[∊5 3 1+{(⍺=0)↓⍺↑⍨⊃¯2,⍨⍵~0}⌿0 5⊤1+⍵⊤⍨3⍴10],' '}¨⍳100 ∊{'IVXLC'[...],' '}¨⍳100 ⍝ Less interesting part ⍳100 ⍝ 1-based range; 1 to 100 inclusive { ... }¨ ⍝ Compute a representation for each number 'IVXLC'[ ],' ' ⍝ Index into the string and pad with a space ∊ ⍝ Concatenate the strings ∊5 3 1+{(⍺=0)↓⍺↑⍨⊃¯2,⍨⍵~0}⌿0 5⊤1+⍵⊤⍨3⍴10 ⍝ Interesting part ⍵⊤⍨3⍴10 ⍝ Last 3 decimal digits of ⍵ 0 5⊤1+ ⍝ Divmod of each digit +1 by 5 { }⌿ ⍝ Compute the partial roman representation: ⍝ Digit 0 1 2 3 4 ⍝ Div 0 0 0 0 1 ⍝ Mod 1 2 3 4 0 ⍝ Result [] [0] [0 0] [0 0 0] [0 1] ⍝ Digit 5 6 7 8 9 ⍝ Div 1 1 1 1 2 ⍝ Mod 1 2 3 4 0 ⍝ Result [1] [1 0] [1 0 0] [1 0 0 0] [0 2] ⊃¯2,⍨⍵~0 ⍝ ¯2 if mod is 0, keep mod otherwise ⍺↑⍨ ⍝ Overtake div with the above ⍝ (¯2: add 0 to the left; other: add (mod-1) 0s to the right) (⍺=0)↓ ⍝ Drop one if div is 0 5 3 1+ ⍝ Offset each nested array to point to correct roman unit ∊ ⍝ Flatten ``` --- OP said "You cannot use any built in function to transform to roman numerals" but didn't say about a built-in that does arithmetic over roman numerals, so this one could be technically valid: # [APL (Dyalog Unicode)](https://www.dyalog.com/), 29 [bytes](https://github.com/abrudz/SBCS) ``` ⎕CY'dfns' ∊,∘' '¨{⍳⍵}roman'C' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@jvqnOkeopaXnF6lyPOrp0HnXMUFdQP7Si@lHv5ke9W2uL8nMT89Sd1UGq/6cBAA "APL (Dyalog Unicode) – Try It Online") This one leverages the [library operator `roman`](http://dfns.dyalog.com/n_roman.htm) that does various arithmetic over roman numerals (that is, the input is also a roman numeral). So this basically computes the 1-based range `{⍳⍵}` over `roman` numerals with the input value `'C'` (100), appends a space to each string `,∘' '¨` and flattens them `∊`. [Answer] ## APL 128 I tried an indexing solution in APL: ``` r←⍬ i←1 l:r←r,' ',(' CXI LV CX'[,⍉((1+(4 4 2 2⊤0 16 20 22 24 32 36 38 39 28)[;1+(3⍴10)⊤i])×3)-4 3⍴2 1 0])~' ' →(100≥i←i+1)/l r ``` It can be 4 bytes shorter in index origin 0 instead of 1 but the real space hog is the generation of the index matrix via: ``` 4 4 2 2⊤0 16 20 22 24 32 36 38 39 28 ``` So far I have not been able to generate the indices on the fly! [Answer] # LaTeX (138) ``` \documentclass{minimal} \usepackage{forloop} \begin{document} \newcounter{i} \forloop{i}{1}{\value{i} < 101}{\roman{i}\par} \end{document} ``` [Answer] # Python, 125 ``` ' '.join(i+j for i in['']+'X XX XXX XL L LX LXX LXXX XC C'.split()for j in['']+'I II III IV V VI VII VIII IX'.split())[1:-38] ``` [Answer] # PHP, ~~38~~ 37 bytes `<ol type=I><?=str_repeat("<li>",100);` -1 byte thanks to @manatwork Same idea as [Patrick](https://codegolf.stackexchange.com/a/9305/46313)'s answer, but in a more compact language. Beats [Mathematica](https://codegolf.stackexchange.com/a/9209/46313)! [Try it Online!](https://www.tehplayground.com/qcW56dxu0vdkYYY2) [Answer] **VBA (Excel), 245 bytes** created Function for Repetition and Replace - **91 bytes** `Function s(a,b):s=String(a,b):End Function Function b(x,y,z):b=Replace(x,y,z):End Function` using immediate window (**154 bytes**) `p="I":for x=1to 100:?b(b(b(b(b(b(b(b(s(x,p),s(100,p),"C"),s(90,p),"XC"),s(50,p),"L"),s(40,p),"XL"),s(10,p),"X"),s(9,p),"IX"),s(5,p),"V"),s(4,p),"IV"):next` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 152 bytes ``` a->{String[] t=",X,XX,XXX,XL,L,LX,LXX,LXXX,XC,,I,II,III,IV,V,VI,VII,VIII,IX".split(",");for(int i=1;i<100;i++){a+=t[i/10]+t[i%10+10]+" ";}return a+"C";} ``` [Try it online!](https://tio.run/##NY/BasMwDIbvfQphGNjYzZKzl116Cmy9FEag9KClbnGXOsFRCiPk2TO5ZOj/sSQL8emGD9x2vQu388/StDgM8Ik@TBsAH8jFCzYO9tOBog9XiHJNUNmZRwZC8g3sIUAJC27f18HjCagUpjZ1EvvDcNSsp7mxM6YyVRL7y3BUrKe5UYts6FtPUhih7KWLkmHAl4X1b0WeW6@1mlCXdPSvRX7S/L4UuU6pAGHn6GiMAVCLHVeLZdR@/G4ZdSV@dP4Mdz5U/gOjSjcDHH4HcvesGynr@YfaIEMWpRBKpTXzZl7@AA "Java (OpenJDK 8) – Try It Online") **Explanation:** ``` String[] t=",X,XX,XXX,XL,L,LX,LXX,LXXX,XC,,I,II,III,IV,V,VI,VII,VIII,IX".split(","); //Create an array of numerals, first half represents tens place, second half represents ones place for(int i=1;i<100;i++){ //Loop 99 times a+=t[i/10]+t[i%10+10]+" "; //Add tens place and ones place to the string }return a+"C"; //Add numeral for 100 and return the string ``` [Answer] # TeX, 354 bytes ``` \let~\let~\d\def~\a\advance~\b\divide~\x\expandafter~\f\ifnum{~~\newcount~\n~\i~\j~\k~\u~\v}~~\or\d\p#1{\ifcase#1C~2~L~5~X~2~V~5~I\fi}\d\q#1{\p{#1~}}\d\r{\j0 \v100\d\m{\d\w{\f\n<\v\else\p\j\a\n-\v\x\w\fi}\w\f\n>0\k\j\u\v\d\g{\a\k2\b\u\q\k}\g\f\q\k=2\g\fi\a\n\u\f\n<\v\a\n-\u\a\j2\b\v\q\j\else\p\k\fi\x\m\fi}\m}\i1\d\c{ \f\i<101 \n\i\r\a\i1 \x\c\fi}\c\bye ``` Some explanation: TeX provides a built-in command `\romannumeral` for converting numbers to Roman numerals. As the question doesn't allow to use built-in functions, the above code is a golfed version of the same algorithm Knuth's original TeX compiler uses for `\romannumeral` (see *TeX: The Program*, § 69, `print_roman_int`) re-implemented in TeX. As he wants to leave the joy of puzzling out how this code works to the reader, Knuth refuses to give an explanation of this part of the code. So I'll follow suit and just give an ungolfed and slightly modified version, which is closer to the original than the above code: ``` \newcount\n \newcount\j \newcount\k \newcount\u \newcount\v \def\chrnum#1{\ifcase#1m\or 2\or d\or 5\or c\or 2\or l\or 5\or x\or 2\or v\or 5\or i\fi} \def\chrnumM#1{\chrnum{#1\or}} \def\roman#1{% \n=#1\relax \j=0\relax \v=1000\relax \def\mainloop{% \def\while{% \ifnum\n<\v \else \chrnum\j \advance\n -\v \expandafter\while \fi }\while \ifnum\n>0\relax \k=\j \advance\k 2\relax \u=\v \divide\u \chrnumM\k \ifnum\chrnumM\k=2\relax \advance\k 2\relax \divide\u \chrnumM\k \fi \advance\n \u \ifnum\n<\v \advance\n -\u \advance\j 2\relax \divide\v \chrnumM\j \else \chrnum\k \fi \expandafter\mainloop \fi }\mainloop } \newcount\i \i=1 \def\countloop{% \ifnum\i<100\relax \roman\i\ \advance\i 1 \expandafter\countloop \fi }\countloop \bye ``` ]
[Question] [ We have lots of horizontal axis for numbers, but I honestly think they're kind of boring. Your task today is to build me a portion of a diagonal axis between two distinct non-negative integers given as input. ## How to build a diagonal axis? * Let's take an example, with the input `0, 5`. Our axis should look like this: ``` 0 1 2 3 4 5 ``` * However, our axis should look nice for numbers that have more digits too! If the input is, for instance `0, 14`, the new axis should be: ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ``` * The idea is that the first digit of next number on the axis must always be placed exactly after the last digit of the previous number. To understand the idea even better, here is another example with `997, 1004`: ``` 997 998 999 1000 1001 1002 1003 1004 ``` --- ## Rules * You may assume that input is in ascending or descending order (you may choose between `5,3` and `3,5`). * You may also assume that the difference between the two integers is lower than 100. * You may have a leading newline or a consistent leading space (on each line). Trailing spaces / newlines are fine as well. * [Default Loopholes are forbidden.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * You can take input and provide output by [any standard mean](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes in every language wins! --- ## Other Test Cases * `1, 10`: ``` 1 2 3 4 5 6 7 8 9 10 ``` * `95, 103`: ``` 95 96 97 98 99 100 101 102 103 ``` * `999999, 1000009`: ``` 999999 1000000 1000001 1000002 1000003 1000004 1000005 1000006 1000007 1000008 1000009 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ ~~7~~ 6 bytes Thanks to *Magic Octopus Urn* for saving a byte! It somehow works, but honestly I have no idea why. ### Code ``` Ÿvy.O= ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//6I6ySj1/2///oy1NdRQMDUxjAQ "05AB1E – Try It Online") ### Explanation ``` Ÿ # Create the range [a, .., b] from the input array vy # For each element .O # Push the connected overlapped version of that string using the previous version of that string. The previous version initially is the input repeated again. Somehow, when the input array is repeated again, this command sees it as 1 character, which gives the leading space before each line outputted. After the first iteration, it reuses on what is left on the stack from the previous iteration and basically attaches (or overlaps) itself onto the previous string, whereas the previous string is replaced by spaces and merged into the initial string. The previous string is then discarded. We do not have to worry about numbers overlapping other numbers, since the incremented version of a number never overlaps entirely on the previous number. An example of 123 and 456: 123 456 Which leaves us " 456" on the stack. = # Print with a newline without popping ``` [Answer] # [Python 2](https://docs.python.org/2/), 43 bytes ``` lambda a,b:'\v'.join(map(str,range(a,b+1))) ``` Makes use of vertical tab to make the ladder effect. The way thet `\v` is rendered is console dependent, so it may not work everywhere (like TIO). [![running code](https://i.stack.imgur.com/yThNu.png)](https://i.stack.imgur.com/yThNu.png) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 8 bytes ``` F…·NN⁺¶ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzMvOae0OLMsNSgxLz0VyC0oLfErzU1KLdLQ1FFA4WpqcikoBBRl5pVoOKakaCjF5CnpZGpqWv//b6BgaPJft@y/bnEOAA "Charcoal – Try It Online") Link is to the verbose version of the code. Input in ascending order. * 1 byte saved thanks to ASCII-only! [Answer] # R, ~~70~~ ~~69~~ 61 bytes ``` function(a,b)for(i in a:b){cat(rep('',F),i,' ');F=F+nchar(i)} ``` Function that takes the start and end variable as arguments. Loops over the sequence, and prints each element, prepended with enough spaces. `F` starts as `FALSE=0`, and during each iteration, the amount of characters for that value is added to it. `F` decides the amount of spaces printed. [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jUSdJMy2/SCNTITNPIdEqSbM6ObFEoyi1QENdXSdEUydTR51LXdM6xDZEOy85IxGoULP2f5qGoY6CkYHmfwA "R – Try It Online") -8 bytes thanks to @Giuseppe [Answer] # C#, ~~90~~ ~~89~~ 85 bytes ``` s=>e=>{var r="";for(int g=0;e>s;g+=(s+++"").Length)r+="".PadLeft(g)+s+"\n";return r;} ``` *Saved 1 byte thanks to @LiefdeWen.* *Saved 4 bytes thanks to @auhmaan.* [Try it online!](https://tio.run/##jZCxasMwEIZ3P4XQJKHGOLShGFVeCp1cCO3QpYtwzq4gPhWdEijBz@5KCbQpdPA3iEP6/uNHHa1Gj35GOwJ92g7Y6xdFGItTwRLd3hKx7Xm@3GQo2ug6dvRux56tQyF/nn6lzNMBuweH8eZqohgcDk3DemZmMg2Y5nS0gQXDue59EMlig6k0NKQHZQQppTiXZQs4xA8ZVBLLrd210EcxSEWKvyPXAeIhIAt6mnXxp8WjR/J7KN@Ci9A6BNGLSoqNlHqJt75bItb1fVKrapG8zuqirZts3i4rkDl3SNQ58m/mBdLX5cjVzqm4nNP8DQ "C# (Mono) – Try It Online") Full/Formatted version: ``` namespace System { class P { static void Main() { Func<int, Func<int, string>> f = s => e => { var r = ""; for (int g = 0; e > s; g += (s++ + "").Length) r += "".PadLeft(g) + s + "\n"; return r; }; Console.WriteLine(f(0)(5)); Console.WriteLine(f(0)(14)); Console.WriteLine(f(997)(1004)); Console.WriteLine(f(1)(10)); Console.WriteLine(f(95)(103)); Console.WriteLine(f(999999)(1000009)); Console.ReadLine(); } } } ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~58~~ 54 bytes ``` def f(a,b,s=''):print s;b<a or f(a+1,b,' '*len(s)+`a`) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI1EnSafYVl1d06qgKDOvRKHYOskmUSG/CCSlbQiUVFdQ18pJzdMo1tROSEzQ/J@mYaBjZKD5HwA "Python 2 – Try It Online") [Answer] # Mathematica, 59, bytes ``` Grid[(DiagonalMatrix@Range[1+##]/. 0->""+1)-1,Spacings->0]& ``` **input** > > [10,15] > > > -3 bytes @JungHwanMin problem with 0 fixed (see comments for details) thanx to @ngenisis [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` rD⁶ṁ$;¥\Y ``` [Try it online!](https://tio.run/##y0rNyan8/7/I5VHjtoc7G1WsDy2Nifz//78lGPw3NAABSwA "Jelly – Try It Online") [Answer] # Mathematica, 48 bytes ``` Rotate[""<>Table[ToString@i<>" ",{i,##}],-Pi/4]& ``` since there are so many answers, I thought this one should be included **input** > > [0,10] > > > **output** [![enter image description here](https://i.stack.imgur.com/fm0VB.jpg)](https://i.stack.imgur.com/fm0VB.jpg) [Answer] # C, ~~166~~ ~~134~~ ~~95~~ 82 Bytes ## New Answer Just as a function not as a whole program. ``` f(a,b){int s=0,i;while(a<=b){i=s;while(i--)printf(" ");s+=printf("%i\n",a++)-1;}} ``` Thanks to Falken for helping knock off 13 Bytes (and fix a glitch)! Thanks to Steph Hen for helping knock off 12 Bytes! Thanks to Zacharý for help knock off 1 Byte! ## Old Answers Got rid of the int before main and changed const char\*v[] to char\*\*v and got rid of return 0; ``` main(int c,char**v){int s=0;for(int a=atoi(v[1]);a<=atoi(v[2]);a++){for(int i=0;i<s;i++)printf(" ");printf("%i\n",a);s+=log10(a)+1;}} int main(int c,const char*v[]){int s=0;for(int a=atoi(v[1]);a<=atoi(v[2]);a++){for(int i=0;i<s;i++)printf(" ");printf("%i\n",a);s+=log10(a)+1;}return 0;} ``` This is my first time golfing and I wanted to try something in C. Not sure if I formatted this correctly, but I had fun making it! ``` int main(int c, const char * v[]) { int s = 0; for(int a=atoi(v[1]); a<=atoi(v[2]); a++) { for(int i=0; i<s; i++) printf(" "); printf("%i\n",a); s += log10(a)+1; } return 0; } ``` **Explanation** ``` int s = 0; // Number of spaces for each line for(int a=atoi(argv[1]); a<=atoi(argv[2]); a++) { // Loop thru numbers for(int i=0; i<s; i++) printf(" "); // Add leading spaces printf("%i\n",a); // Print number s += log10(a)+1; // Update leading spaces ``` **Usage** [![enter image description here](https://i.stack.imgur.com/k53tC.png)](https://i.stack.imgur.com/k53tC.png) [Answer] ## C++, ~~167~~ 165 bytes -2 bytes thanks to Zacharý ``` #include<string> #define S std::string S d(int l,int h){S r;for(int m=0,i=l,j;i<=h;){for(j=0;j<m;++j)r+=32;S t=std::to_string(i++);r+=t;r+=10;m+=t.size();}return r;} ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~25~~ 24 bytes -1 thanks to [Zacharý](https://codegolf.stackexchange.com/users/55550/zachar%c3%bd). Assumes `⎕IO←0` for zero based counting. Takes the lower bound as left argument and the upper bound as right argument. ``` {↑⍵↑⍨¨-+\≢¨⍵}(⍕¨⊣+∘⍳1--) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/0vygVT1o7aJj3q3gskVh1boasc86lx0aAVQqFbjUe9UIKtrsfajjhmPejcb6upq/v9voFCSr2BowmVpaQ5mGRiYcBlCWFyWphCGMVAWBKAKgMASAA "APL (Dyalog Unicode) – Try It Online") `(`…`)` apply the following tacit function between the arguments:  `-` subtract the upper lower from the upper bound  `1-` subtract that from one (i.e. 1 + ∆)  `⊣+∘⍳` left lower bound plus the integers 0 through that  `⍕¨` format (stringify) each `{`…`}` apply the following anonymous on that (represented by ⍵):  `≢¨` length of each (number)  `+\` cumulative sum  `-` negate  `⍵↑⍨¨` for each stringified number, take that many characters from the end (pads with spaces)  `↑` mix list of strings into character matrix [Answer] # [Retina](https://github.com/m-ender/retina), ~~81~~ 78 bytes ``` .+ $* +`\b(1+)¶11\1 $1¶1$& 1+ $.& $.& (.+) $.1$* +1`( *)(.+?)( +)¶ $1$2¶$1$3 ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYtLOyEmScNQW/PQNkPDGEMuFUMgQ0WNyxAoqaemAMRcChp62ppAnqGKlgKXtmGChoKWJlDIXlNDAaQNqEXF6NA2IGn8/78Fl6ERAA "Retina 0.8.2 – Try It Online") Takes input as a newline-separated list of two integers. Edit: Saved 3 bytes by stealing the range-expansion code from my answer to [Do we share the prime cluster?](https://codegolf.stackexchange.com/questions/147254) Explanation: ``` .+ $* ``` Convert both inputs to unary. ``` +`\b(1+)¶11\1 $1¶1$& ``` While the last two elements (a, b) of the list differ by more than 1, replace them with (a, a+1, b). This expands the list from a tuple into a range. ``` 1+ $.& $.& ``` Convert back to decimal in duplicate. ``` (.+) $.1$* ``` Convert the duplicate copy to spaces. ``` +1`( *)(.+?)( +)¶ $1$2¶$1$3 ``` Cumulatively sum the spaces from each line to the next. [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~14~~ 13 bytes ``` V}FQ =k+*dlkN ``` [Try it online!](http://pyth.herokuapp.com/?code=V%7DFQ%0A%3Dk%2B%2adlkN&input=999999%2C+1000009&debug=0) [Answer] # [LOGO](https://sourceforge.net/projects/fmslogo/), 53 bytes ``` [for[i ? ?2][repeat ycor[type "\ ]pr :i fd count :i]] ``` There is no "Try it online!" link because all online LOGO interpreter does not support template-list. That is a template-list (equivalent of lambda function in other languages). Usage: ``` apply [for[i ? ?2][repeat ycor[type "\ ]pr :i fd count :i]] [997 1004] ``` (`apply` calls the function) will print ``` 997 998 999 1000 1001 1002 1003 1004 ``` Note: This uses turtle's `ycor` (Y-coordinate) to store the number of spaces needed to type, therefore: * The turtle need to be set to home in its default position and heading (upwards) before each invocation. * `window` should be executed if `ycor` gets too large that the turtle moves off the screen. Description of `window` command: `if the turtle is asked to move past the boundary of the graphics window, it will move off screen.`, unlike the default setting `wrap`, which `if the turtle is asked to move past the boundary of the FMSLogo screen window, it will "wrap around" and reappear at the opposite edge of the window.` Explanation: ``` for[i ? ?2] Loop variable i in range [?, ?2], which is 2 input values repeat ycor That number of times type "\ space character need to be escaped to be typed out. pr :i print the value of :i with a newline fd count :i increase turtle's y-coordinate by the length of the word :i. (Numbers in LOGO are stored as words) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` Ÿʒ¾ú=þv¼ ``` [Try it online!](https://tio.run/##AR4A4f8wNWFiMWX//8W4ypLCvsO6PcO@dsK8//85NQoxMDM "05AB1E – Try It Online") -2 thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan). [Answer] # JavaScript (ES8), ~~69~~ ~~67~~ 62 bytes Takes input as integers, in ascending order, using currying syntax. Returns an array of strings. ``` x=>y=>[...Array(++y-x)].map(_=>s="".padEnd(s.length)+x++,s="") ``` --- ## Try it ``` o.innerText=(f= x=>y=>[...Array(++y-x)].map(_=>s="".padEnd(s.length)+x++,s="") )(i.value=93)(j.value=105).join`\n` oninput=_=>o.innerText=f(Math.min(i.value,j.value))(Math.max(i.value,j.value)).join`\n` ``` ``` label,input{font-family:sans-serif}input{margin:0 5px 0 0;width:100px;} ``` ``` <label for=i>x: </label><input id=i type=number><label for=j>y: </label><input id=j type=number><pre id=o> ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 bytes ``` òV £¯Y ¬ç +X ``` Takes input in either order and always returns the numbers in ascending order, as an array of lines. [Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=8lYKo69ZIKznICtY&inputs=MAo1,MAoxNA==,OTk3CjEwMDQ=,MQoxMA==,OTUKMTAz,OTk5OTk5CjEwMDAwMDk=&flags=LVI=) with the `-R` flag to join the array with newlines. ## Explanation Implicit input of `U` and `V`. ``` òV £ ``` Create inclusive range `[U, V]` and map each value to... ``` ¯Y ¬ç ``` The values before the current (`¯Y`), joined to a string (`¬`) and filled with spaces (`ç`). ``` +X ``` Plus the current number. Resulting array is implicitly output. [Answer] # [Python 2](https://docs.python.org/2/), ~~65 63 62~~ 61 bytes *-2 bytes Thanks to @Mr. Xcoder: `exec` doesn't need braces* *-1 bye thanks to @Zacharý: `print s*' '` as `print' '*s`* ``` def f(m,n,s=0):exec(n-m+1)*"print' '*s+`m`;s+=len(`m`);m+=1;" ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI1cnT6fY1kDTKrUiNVkjTzdX21BTS6mgKDOvRF1BXatYOyE3wbpY2zYnNU8DyNS0ztW2NbRW@p@mYaBjaKL5HwA "Python 2 – Try It Online") [Answer] # JavaScript, 57 bytes ``` f=(x,y,s='')=>y>=x?s+` `+f(x+1,y,s.replace(/./g,' ')+x):s ``` [Answer] # Python 2, 60 59 bytes -1 byte thanks to Mr.Xcoder for defining my s=0 as an optional variable in my function. ``` def f(l,u,s=0): while l<=u:print' '*s+`l`;s+=len(`l`);l+=1 ``` [Try it online!](https://tio.run/##HcixCoAgFEDRva94W5oOWjRY@S8NKQoPk1Sir7fsTocbn@zOMNZ6GAuWIC88aUGXDm7n0QBuuizx8iH30A@J7biviWk0gXykKzItqyWSgxS0s0TNXIrp11/7LUXrCw) I think it is possible to transfer this into a lambda version, but I do not know how. I also think that there is some sort of mapping between the spaces and the length of the current number, but this I also did not figure out yet. So I think there still is room for improvement. What i did was creating a range from the lowerbound `l`to the upper bound `u` printing each line with a space multiplied with a number `s`. I am increasing the multiplier with the length of the current number. [Answer] # Python 2, 78 77 79 bytes ``` def f(a,b): for i in range(a,b+1):print sum(len(`j`)for j in range(i))*' '+`i` ``` [Try it online!](https://tio.run/##RcoxDoAgDADA3Vd0k6qDMvKaYgQt0WoQB19fw@R6uest2ylWdQkRovHDjK6BeGZgYIHsZQ1V@wndlVkK3M9h9iCGEmF96X@M2LXQ9sSk0YyDHVE/ "Python 2 – Try It Online") `f(A, B)` will print the portion of the axis between A and B inclusive. First time I answer a challenge! Uses and abuses Python 2's backticks to count the number of spaces it has to add before the number. -1 byte thanks to [Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) +2 because I forgot a `+1` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~41~~ 38 bytes *-3 bytes Thanks to [ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only)* ``` t(x,v){while(x<=v)printf("%d\v",x++);} ``` Works on RedHat6, accessed via PuTTY [![Proof](https://i.stack.imgur.com/kWgYj.png)](https://i.stack.imgur.com/kWgYj.png) [Try it online!](https://tio.run/##S9ZNT07@/79Eo0KnTLO6PCMzJ1Wjwsa2TLOgKDOvJE1DSTUlpkxJp0JbW9O69n9uYmaehmZ1iYaBjimIDwA "C (gcc) – Try It Online") [Answer] # [V](https://github.com/DJMcMayhem/V), 16 bytes ``` ÀñÙywÒ $pça/jd ``` [Try it online!](https://tio.run/##K/v//3DD4Y2HZ1aWH56koFLAeHi5UKJ@Vsr//6b/DU0B "V – Try It Online") This would be way easier if I could take `start` `end - start` but I think that's changing the challenge a bit too much. This takes the start number as input in the buffer and the end number as an argument. It actually creates the ladder from `start` to `start + end` and then deletes everything after the end number. [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` vii&:"t~@Vh ``` [**Try it online!**](https://tio.run/##y00syfn/vywzU81KqaTOISzj/39Lcy5DA1MA "MATL – Try It Online") ### Explanation This works by generating a string for each number and concatenating it with a logically-negated copy of the previous string. Thus char 0 is prepended 0 as many times as the length of the previous string. Char 0 is displayed as a space, and each string is displayed on a different line ``` v % Concatenate stack (which is empty): pushes [] ii % Input two numbers &: % Range between the two numbers " % For each t % Duplicate ~ % Logical negation. This gives a vector of zeros @ % Push current number V % Convert to string h % Concatenate with the vector of zeros, which gets automatically % converted into chars. % End (implicit). Display stack (implicit), each string on a diferent % line, char 0 shown as space ``` [Answer] # [Swift 4](https://swift.org/blog/swift-4-0-release-process/), 115 bytes I think nobody would have posted a Swift solution anyway... ``` func f(l:Int,b:Int){for i in l...b{print(String(repeating:" ",count:(l..<i).map{String($0).count}.reduce(0,+)),i)}} ``` [Try it online!](http://swift.sandbox.bluemix.net/#/repl/597f2a514ed958681150d0b9) [Answer] ## Perl, 19 bytes **Note: `\x0b` is counted as one byte.** Along with others, I thought using cursor movements would be the shortest route, this does mean it doesn't work on TIO: ``` print"$_\x0b"for<>..<> ``` ### Usage ``` perl -e 'print"$_\x0b"for<>..<>' <<< '5 10' 5 6 7 8 9 10 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~10~~ 9 bytes ``` òV åÈç +Y ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=8lYg5cjnICtZ&input=OTk3LCAxMDA0Ci1S) Returns an array of lines; `-R` flag included to join on newlines for easier viewing. ### Explanation ``` òV åÈ ç +Y UòV åXY{Xç +Y} Ungolfed Implicit: U, V = inputs, P = empty string UòV Create the range [U, U+1, ..., V-1, V]. åXY{ } Cumulative reduce: Map each previous result X and current item Y to: Xç Fill X with spaces. +Y Append Y. Implicit: output result of last expression ``` --- Old version, 10 bytes: ``` òV £P=ç +X ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=8lYgo1A95yArWA==&input=OTk3LCAxMDA0Ci1S) ``` òV £ P= ç +X UòV mX{P=Pç +X} Ungolfed Implicit: U, V = inputs, P = empty string UòV Create the range [U, U+1, ..., V-1, V]. mX{ } Map each item X to: Pç Fill P with spaces. +X Append X. P= Re-set P to the result. Implicitly return the same. Implicit: output result of last expression ``` [Answer] # D, ~~133~~ ~~127~~ ~~126~~ ~~125~~ ~~121~~ 119 bytes ``` import std.conv,std.stdio;void f(T)(T a,T b,T s=0){for(T j;j++<s;)' '.write;a.writeln;if(a-b)f(a+1,b,s+a.text.length);} ``` Jelly and APL were taken. [Try it online!](https://tio.run/##JYxNDsIgEEb3PQW7QkBS1ugtuAAI6DQtmDJpTYxnx1EX30/e4sXeYX3UDVnDqK@17Op7KFDtXiGyzJ3gjnnlWKC0yyReuW6EZjtLeW5WjGzUxwaYrP/vUixk7k9BUEujgmrSa0xP1EsqN7wL@x6Gn371UDgZuVFmItz7Bw) If you're fine with console-dependent results (goes off the same principle as Giacomos's C answer) here's one for ~~72~~ 71 bytes: ``` import std.stdio;void f(T)(T a,T b){while(a<=b){a++.write;'\v'.write;}} ``` ## How? (Only D specific tricks) * `f(T)(T a,T b,T s=0)` D's template system can infer types * `for(T j;j++<s;)` Integers default to `0`. * `' '.write;a.writeln` D lets you call `fun(arg)` like `arg.fun` (one of the few golfy things D has) * `a.text.length` Same as above, and D also allows you to call a method with no parameters as if it was a property (`text` is conversion to string) * One thing that might be relevant (I didn't use this though) newlines can be in strings! [Answer] # Java 8, 79 bytes ``` (a,b)->{for(String s="";a<=b;System.out.printf("%"+s.length()+"d\n",a++))s+=a;} ``` [Try it online!](https://tio.run/##LYyxasMwFAB3f4UQFCTkiJbSoSjO0E4dOmVsOzzLkiPXlozeU6AEf7urIdMNd9wEVzik1cVp@N3tDIjsE0Jkt2Yt/RwsQwKquKYwsKUacaYc4vj1A3lEWbupHnShMGtfoqWQon4L7yliWVw@fkRyo8vtnSfmWbcLaHt5ON18yvcdw45zA8euN@c/JLfoVEivVZEX/IEr1LOLI12EVHz4jrwFpaRE1YHZdtN4Dda6lcTrS8ueHp@labZm2/8B) ]
[Question] [ This is a problem on Luogu OJ. I decided to post it here because on Luogu OJ, many people, including me and my friend, are interested about how to solve this problem within the fewest characters. Your task is to output the following ASCII-art: ``` ************ ####....#. #..###.....##.... ###.......###### ### ### ........... #...# #...# ##*####### #.#.# #.#.# ####*******###### #.#.# #.#.# ...#***.****.*###.... #...# #...# ....**********##..... ### ### ....**** *****.... #### #### ###### ###### ############################################################## #...#......#.##...#......#.##...#......#.##------------------# ###########################################------------------# #..#....#....##..#....#....##..#....#....##################### ########################################## #----------# #.....#......##.....#......##.....#......# #----------# ########################################## #----------# #.#..#....#..##.#..#....#..##.#..#....#..# #----------# ########################################## ############ ``` This is code-golf, so shortest program wins. [Answer] # [Brainfuck](https://github.com/TryItOnline/brainfuck), 1347 bytes Why do i do this to myself ``` +++++[>+++++++++>+++++++>++++++>++++++++>+++++++++>++<<<<<<-]>+>>++>++<<>...............>............>>.<<<...............<....<....>.<.>>>>>.<<<.............<.<..>...<.....>..<....>>>>>.<<<.............<...<.......>......>..<<<++[->>>............<...<<]>>>>>>.<<<................<<...........>>.....<<<++[->>>..........<.<...>.<<]>>>>>>.<<<...............<..>>.<<.......>.......<<<++[->>>..........<.<.>.<.>.<<]>>>>>>.<<<............<....>>.......<<......>...<<<++[->>>..........<.<.>.<.>.<<]>>>>>>.<<<...........<<...>><.>>...<<<.>>>....<<<.>>>.<<...<....>>..........<.<.>.<.>.>..........<.<.>.<.>.>>>>.<<<...........<<....>>>..........<<..<.....>>...........<...>............<...>>>>.<<<...........<<....>>>....<....>.....<<<....>>>>>.<<<.....<<<++[->>>........<....<<]>>>>>>.<<<...<<<++[->>>........<......<<]>>>>>>.<<<<<<+++++++[->>........<<]>>......>>>>.<<<<<<+++[->>.<...>.<......>.<.>.<<]>>.>>>..................<<<.>>>>.<<<<<<+++++++[->>......<<]>>.>>>..................<<<.>>>>.<<<<<<+++[->>.<..>.<....>.<....>.<<]<+++++[->>>....<<<]>>>>>>>.<<<<<<+++++++[->>......<<]>>>....<.>>>..........<<<.>>>>.<<<<<<+++[->>.<.....>.<......>.<<]>>>....<.>>>..........<<<.>>>>.<<<<<<+++++++[->>......<<]>>>....<.>>>..........<<<.>>>>.<<<<<<+++[->>.<.>.<..>.<....>.<..>.<<]>>>....<.>>>..........<<<.>>>>.<<<<<<+++++++[->>......<<]>>>....<............ ``` [Try it online!](https://tio.run/##rVNbCsIwEPz3KqU5wTAXkX6oIIjgh@D5Y16bJpukPhfapsnszL5yvB8ut/PjdLV28rbnJMb6S70fVgg2L5zItEFTW/VPGodXCOSXO3UQdlDwAArOr6LDACy4LO8dAJfg7B00Fgv7TOGwjj/utVQhQp/BBhlSBVRpRnSMz4gQRURrnPyaMPyQiJz@LBHIEmhUK@L@5kDI1NEht5YqxaZdrxix1hbojElbnTiBqiwDmAIGVLw7c4H0EBmZEhhAaVCkX7knRs1mng6zpfaRq@hzvXAytci80vSU5rZyKrnq5khXZf4@wa/KTdZ/Ui9sZ@0T "Brainfuck ‚Äì Try It Online") The "readable" version : ``` +++++[>+++++++++>+++++++>++++++>++++++++>+++++++++>++<<<<<<-]>+>>++>++ << >...............>............>>. <<<...............<....<....>.<.>>>>>. <<<.............<.<..>...<.....>..<....>>>>>. <<<.............<...<.......>......>..<<<++[->>>............<...<<]>>>>>>. <<<................<<...........>>.....<<<++[->>>..........<.<...>.<<]>>>>>>. <<<...............<..>>.<<.......>.......<<<++[->>>..........<.<.>.<.>.<<]>>>>>>. <<<............<....>>.......<<......>...<<<++[->>>..........<.<.>.<.>.<<]>>>>>>. <<<...........<<...>><.>>...<<<.>>>....<<<.>>>.<<...<....>>..........<.<.>.<.>.>..........<.<.>.<.>.>>>>. <<<...........<<....>>>..........<<..<.....>>...........<...>............<...>>>>. <<<...........<<....>>>....<....>.....<<<....>>>>>. <<<.....<<<++[->>>........<....<<]>>>>>>. <<<...<<<++[->>>........<......<<]>>>>>>. <<<<<<+++++++[->>........<<]>>......>>>>. <<<<<<+++[->>.<...>.<......>.<.>.<<]>>.>>>..................<<<.>>>>. <<<<<<+++++++[->>......<<]>>.>>>..................<<<.>>>>. <<<<<<+++[->>.<..>.<....>.<....>.<<]<+++++[->>>....<<<]>>>>>>>. <<<<<<+++++++[->>......<<]>>>....<.>>>..........<<<.>>>>. <<<<<<+++[->>.<.....>.<......>.<<]>>>....<.>>>..........<<<.>>>>. <<<<<<+++++++[->>......<<]>>>....<.>>>..........<<<.>>>>. <<<<<<+++[->>.<.>.<..>.<....>.<..>.<<]>>>....<.>>>..........<<<.>>>>. <<<<<<+++++++[->>......<<]>>>....<............ ``` [Answer] # T-SQL, ~~322 298~~ 288 bytes ``` SELECT CONCAT('',DECOMPRESS(CAST('H4sIAAAAAAACA6WRQYrEIBQF955CqJ0wdf/jjehM2rwOdofUQvIoHj9f65m2UMLRsYNng/4ZQU0NThjUtBFLDXwRBpWIWYfGpCaIRCy5cZswuFVX6U3bOAA73/+8nXYw2368uWwfj3r5MKzfq4W0UHhEQcUBsk0/b9yafllX9P/YpeDu7rVDTF6226WoPpy6bMUmPZ66UH4BHz4rVE8EAAA='as XML).value('.','varbinary(max)'))) ``` Uses G-Zip compression built into SQL 2016 and later, along with Base64 encoding, [see this tips post for details](https://codegolf.stackexchange.com/a/190648/70172). In SSMS, you'll either have to output as text after fiddling with SSMS character limits in settings, or just copy-and-paste the output to the code window: [![enter image description here](https://i.stack.imgur.com/KPRAx.png)](https://i.stack.imgur.com/KPRAx.png) **EDITS**: Saved 24 bytes with a better compressed string, thanks to @someone; saved 10 bytes with an implicit conversion using `CONCAT`, thanks to @digscoop. [Answer] # [MarioLANG](https://esolangs.org/wiki/MarioLANG), ~~3287 3286 3285~~ 1771 Bytes I had to do this for the theme. ``` +>+>.>.>.>.>.>.>.>)>(>.>.>. +"+".".".".")")".")".".".". +++........)..).....)...... +++.(.........)...)...(.... +++.......)...)...))....... +++.(...)...((.......)..... +++.(.....)..(....(...)().. +++.(.).....)(....((((.().. +++.....).(.)(............. +++..(..).....(.....)..)).. +)+)....).).(.(.........).. +++)..(..(..(.............. +++)...((.(.(......)..(.(.. +++)...((..(.).......)..(.. +++....((.(..).....((.)(... +++........(.........(..).. +++..(.)......)......(..... +++....)................(.. +++......(....(......)...(. +++....(.(.).)(....).)..)(. +++......(...)(..(......... +++........).....(.(.)(..). +++.....(............)..(). +++.)..)................... +++..)).....)....(.)..).)). +++....)..).)............). +++..............)........( +++.......)....(...(....... +++.)))..).....(.(......... +++(..)..)(.............(.. +++(.....)..)..)......(.... +++(..(...).)..)........).) +++(..(....(.(.....)..).... ++++(.(...((.(.......(..... ++++.........()....(.(..(.. ++++)....))......)......... ++++...(..)..)......))...(. ++++)........)..)(..)...)(. ++)+...(..()...)).......... ++++(.....(...(....)(.(.(). ++++(...).(.....(...(...... ++++(........)..().(.((.).. ++++.(.))..((.............. ++++.(.....((...).......... ++++.(.)(..((....(.)....(( )+++...................... +)++.)..)..).....).(..).)( ++++.......))..((..(...... ++++....((....)..(....(... ++)+.....(.(....)..)..(..) ++++..).((.(.......)...... ++++.))...........(.....(( ++++.....)).......()...... ++++.....)).(.)....)....). ++++.(......(()).......... ++++)....(.).....)........ ++++.......)..(.(.......() ++++)....)(...(..(.....(.. ++++.......(.)(.)......(.( ++++.....()(............). ++++().(..).....(.....)).. ++++...()))......)....))() +!+!.!.!.!.!.!.!.!.!.!.!.! =#=#=#=#=#=#=#=#=#=#=#=#=# ``` [Try it online!](https://tio.run/##dVRbasMwEPz3LZL@zCDQDeq75KsU2hR6f3Ct1T7lVIpD4tlZzb70/fj9/Pl6PD@Oo@1t72Vzx/y1tXu7d908d5dH9tZa67oon27fE0NPsDxwrL6n0oIn1khmxSfVlViCjqmGiZ2rOzZZUMzXxGBHuHcKj43z/2CWaAZvikDv1aVhQ76zxBYFc7kWjukUnglSxTnXcRxcS/LGbGU89mUh@0RyO8vkWsTvTBolMVh4LAlYesI8iFDHSr5G7IrxhU73ydRfmKZkjo@VzKKlpOZ0sPSgSEI@j2SOIGuZWV8aCY75NORCKAZPY0hiwvwsMxlYmy8ROqK2ESDofNWizcslduchq2TUvTFPtbbirDuVhzK0obOkktL/DIx9sSg87wVI15tOyDl4MWN2GQC1wZ0H4@lsABsvPREsegvSrwtp/pxoE4OaSz0o30uWLi8qDaeymGvK7DCn1qMMGQ6Di4wBabSMKfCrGLgUjSlBkcUSch4BMLWWFhJ5ApqrJmIEkngQ1zlt4OUWZmpVljYmh4xbu/WXe3t/@28fxx8 "MarioLANG ‚Äì Try It Online") I managed to save 1514 bytes by converting it from the simple straight code below to the 27x64 block above using elevators ``` +++++++++++++++++++++++++++++++++++++++++++++)++++++++++++++++++++++++++++++++)+++++++++++++++++++++++++++++++++++)++++++++++++++++++++++++++++++++++++++++++++++)++++++++++)++++++++++++++++++++++++++++++++++++++++++((((...............))))...........(.(((...............)....)....(.).).(((.............).)..(...).....(..)....).(((.............)...).......(......(..............)...(............)...)).(((................))...........((...............).)...(.(..........).)...(.)).(((...............)..))).(((.......(.................).).(.).(.(..........).).(.).(.)).(((............)....))).......(((......(.............).).(.).(.(..........).).(.).(.)).(((...........))...(.)))...((.))....((.)).(((...)....((..........).)...(.(..........).)...(.)).(((...........))....))..........(((..).....((...........)...(............)...)).(((...........))....))....((((....))))....((.....).(((.............)....(........)....)).(((...........)......(........)......)).((..............................................................)).((.)...(.)......(.).(..)...(.)......(.).(..)...(.)......(.).(..((..................)).)).((...........................................((..................)).)).((.)..(.)....(.)....(..)..(.)....(.)....(..)..(.)....(.)....(.....................)).((..........................................(....).((..........)).)).((.).....(.)......(..).....(.)......(..).....(.)......(.(....).((..........)).)).((..........................................(....).((..........)).)).((.).(.)..(.)....(.)..(..).(.)..(.)....(.)..(..).(.)..(.)....(.)..(.(....).((..........)).)).((..........................................(....)........... =========================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================. ``` [Try it online!](https://tio.run/##7VJbCsMgEPzvSXYoeIMeJl@l0Af0/mCMumqy27CS9M@BxGQdx9nR1/R9fJ7T@@79tQc4TDBydHrHSgpwayCg@SWnUMqLwgDBWGqOmLN85RWSyJzEr0PLILEEiim3ti09JymSJVUOMYlmQuyXWo8PaUUpi5xv8aj23CsL7gKp76RPDRPbRHrCALbhxnnImG1n1erx9eM7l4n6RanarEBie8HKPHcISSLnw7uA77WlpjkIqr3edmVQti2Dufazabs1Pjjd2ToTS2VP8CRXIrPow1w902HF5TYwMDAwMPBPOO9n "MarioLANG ‚Äì Try It Online") ~~This is horrible and I'm very sorry.~~ Loops can get really expensive (bytes wise) in MarioLANG if you're not smart about them and also I'd almost lost the will to live by the time I'd got this far so Mario literally just runs in a straight line, first setting 6 memory cells to the correct ASCII values, then switching between them to output in the right order. This can definitely be golfed down further and if you really hate yourself I highly suggest you give it a go. (Saved one byte by deleting last equals (floor character) since Mario hits the last instruction as he falls even without it and another by realising that he could actually hit two instructions in the fall.) # 5413 Bytes ``` +++++>)+++++++++)+++++++)++++++)++++++++)+++++++++)++((((((-[!)+))++)++(()...............)............)).(((...............(....(....).(.))))).(((.............(.(..)...(.....)..(....))))).(((.............(...(.......)......)..(((++>-)))............(...(([!)))))).(((................((...........)).....(((++>-)))..........(.(...).(([!)))))).(((...............(..)).((.......).......(((++>-)))..........(.(.).(.).(([!)))))).(((............(....)).......((......)...(((++>-)))..........(.(.).(.).(([!)))))).(((...........((...))(.))...(((.)))....(((.))).((...(....))..........(.(.).(.).)..........(.(.).(.).)))).(((...........((....)))..........((..(.....))...........(...)............(...)))).(((...........((....)))....(....).....(((....))))).(((.....(((++>-)))........(....(([!)))))).(((...(((++>-)))........(......(([!)))))).((((((+++++++>-))........(([!))......)))).((((((+++>-)).(...).(......).(.).(([!)).)))..................(((.)))).((((((+++++++>-))......(([!)).)))..................(((.)))).((((((+++>-)).(..).(....).(....).(([!(+++++>-)))....((([!))))))).((((((+++++++>-))......(([!)))....(.)))..........(((.)))).((((((+++>-)).(.....).(......).(([!)))....(.)))..........(((.)))).((((((+++++++>-))......(([!)))....(.)))..........(((.)))).((((((+++>-)).(.).(..).(....).(..).(([!)))....(.)))..........(((.)))).((((((+++++++>-))......(([!)))....(........... ====="=======================================================#========================================================================================================================================================================="=======================#==================================================="=========================#====================================================="===========================#====================================================="===========================#=================================================================================================================================================================================================================================================================="====================#=================="======================#===================="==============#======================"==========================#=============================================="============#=========================================="==========================#======"============#====================="============#========================================"========================#============================================"============#========================================"============================#============================================"============#==================. ! < ! < ! < ! < ! < ! < ! < ! < ! < ! < ! < ! < ! < ! < ! < ! < ! < #=======================================================" #=======================" #=========================" #===========================" #===========================" #====================" #======================" #==============" #==========================" #============" #==========================" #============" #============" #========================" #============" #============================" #============" ``` [Try it online!](https://tio.run/##3VbbjoMgEH3vV8jwMhMjX4D7I/vUp80me0n2/xNXQFRQWoSJiZ2krcXDOZwzY9Pv@9/n79f952MYWlNv1Pqi8JPidXuFtrp3QS3RtEIqrOA7kRo3RAic38a7I4R2UGgA5HHmym1IgD1uljcbEEeHndkQY3F0sE9l74YG3NqWyx7RWHjEhlMGUTgpPnKvJCOuzrSclMoZ7RcidKTm3sTgLxE3sgHz/mJCSIXHw7m9FHnctOwZIy7pIu6MyjYeN4VxLglcjLQw9wh1K6jF@MFZIy1qGhffs6UvKprReUbUI71je/0JaHny5unFmdm33nt9Ij5FH3U1JR3ZP8BQrb2xzqa/1K03BX1Zyf4qBYwOgDkPYE8YXqJn5w6DzI5RZnDKw42RFR4ky2jIbOYycWCxzqzNrq9ujSnRlJVurlKC0YFgzkOwJyxeomfnDoPOjlFncOrDjdEVHjTLaOhs5jJxwWKdWbtS3/1@lv5Ngcs8MpLRgWTOQ7InLF@iZ@cOA2THCBmccLgxUOEBWEYDspnLxCWLdWbtSv1h@Ac "MarioLANG ‚Äì Try It Online") This is a port of [The random guy's answer](https://codegolf.stackexchange.com/a/192780/83666) using [Dennis's Brainfuck to MarioLANG converter](https://codegolf.stackexchange.com/a/63273/83666) making very minor changes to save a couple of bytes. While it's obviously much longer, it includes more features of the language and better shows how the language works so I thought I'd include it. [Answer] # [PHP](https://php.net/), ~~176~~ 155 bytes -21 bytes thanks to [Ryan Moore](https://codegolf.stackexchange.com/users/40930/ryan-moore)'s super compressed string. This version uses raw output of [gzdeflate](https://www.php.net/manual/en/function.gzdeflate.php) and contains unprintable binary data, so the code itself and TIO link cannot be posted here, but here is a hex dump of it: ``` 000000 3c 3f 3d 67 7a 69 6e 66 6c 61 74 65 28 27 a5 91 000010 81 06 04 21 00 44 01 e8 2b e2 01 71 ef ff 3f ef 000020 5c 91 76 f6 64 57 0f 31 c6 98 a6 ea 95 b6 50 c2 000030 03 50 c5 ab 83 0e 47 41 4d 1b 1c d0 a9 e9 86 2c 000040 35 70 62 38 a8 84 cc 38 34 06 35 41 24 64 c9 c5 000050 6d 40 e7 55 5c fd a5 6d fd 00 54 9f 5f 5e b5 4d 000060 40 d5 a7 2f 37 d3 f3 53 ef 1f b3 0e 22 e2 90 2e 000070 14 8e 28 a8 d8 41 b6 ea 73 e3 55 fb df b8 a2 3a 000080 8e ad 4a de 6d ef 0f 16 cd cb ba 9d ca e8 59 eb 000090 b2 8a 9d 3a 6d 5d f8 02 27 29 3b ``` Thanks to [@dzaima](https://codegolf.stackexchange.com/users/59183/dzaima), here is a TIO which uses bash to create and run this file: [Try it online!](https://tio.run/##HZFJTmUxEAT3nCIuAPI8HMejYNP9BbTEou/@SfvpLcpDZGWle/t6fz5/fiavn7x9/Hn8@377/vjLfx7vj@fT3A/8wG/8JGVyI1XSIiXSIFlyIEVcwWVapNqXQ1lxxWISJuBUGELAWJYudpY7ddZys/eRX/tyTlwcUiEntnoEYsboimUkaqElVqNGeiIahrucF2f83Yi0TvGYRcgES5jYjh1MQ6usSkm4cblw5otkQ3J4qRdKYIxT@3D861QaLhwro0r@cmpEmghfmRiP5z3P/NpUoXFjoG6i/kWXxrxcEidoymTGaazM9Gw59ycLu@nXuXMno2pw63IyiA2UdZKWyVmOq36zyEL9MbE7UwK6oFna5cp5h0WT1cZcx57aKE@bGJPR6QpTRTsvE5VOv5w60x3lHvp2uKjJCsadh3YV338B "Bash ‚Äì Try It Online") This basically reverses the deflate and prints the result. Save it as a binary file then execute it like this: `php mario.php` --- # [PHP](https://php.net/), ~~239~~ 216 bytes -23 bytes thanks to [Ryan Moore](https://codegolf.stackexchange.com/users/40930/ryan-moore)'s super compressed string. ``` <?=gzinflate(base64_decode('pZGBBgQhAEQB6CviAXHv/z/vXJF29mRXDzHGmKbqlbZQwgNQxauDDkdBTRsc0Knphiw1cGI4qITMODQGNUEkZMnFbUDnVVz9pW39AFSfX161TUDVpy830/NT7x+zDiLikC4Ujiio2EG26nPjVfvfuKI6jq1K3m3vDxbNy7qdyuhZ67KKnTptXfgC')); ``` [Try it online!](https://tio.run/##BcHbboIwAADQz1GzB@SSMrKZBSgg62SrAmt4WbgVClJLFAR@np0jarGu7x@HamGcXtNHuc3Sewm0v6LMb0W53YjEs6wK16aDLWCPzCTHUVqkkXy6itGdCVyOXoey/pol@FkFeEoHCNvCCs/3fI@4qNlTzj1f6/3w9A2xF0ROm5y4m0WQx/FiiF/VMN0LJTKQwwjGYn5V91IQ6tPLAtkXa20tahi7KY6nAP7TxHSkA/JB08tI7dQRTlkw630xD3UCdIR4KB6EVvZmt3tb138 "PHP ‚Äì Try It Online") Same as above version, but used [base64\_encode](https://www.php.net/manual/en/function.base64-encode.php) on output of `gzdeflate`, so the code is readable and TIO link is available too. This basically reverses the base64 and deflate and prints the result. [Answer] # LaTeX, ~~452~~ 448 bytes Created with bigram replacement (and one trigram) instead of programming a loop to replace multiple consecutive symbols. ``` \newlinechar`+\def~#1{\catcode`#1=13\lccode`~=`#1\lowercase{\def~}}~$#1#2{~#1{#2#2}}~l#1#2#3{~#1{#2#3}}\catcode`#=12$_*$[_$]{ }$^]$!^$<#$><$=>$&=$@.$:@$)-$()$?($/&lx#.$;xl'#@l"<#l`!^l|!]lv#+lc:@lw><lk#:lh`]lg'.lf.#lq#|ld<:lr<@lnfc~s{?)v}la/=li'klj^#l,js\typeout{h [[[+h >:x+` '":.d+` "c.wh"`"+!!:c.h gqgvh <*>"!! ;q;v`>[_*w` ;q;v| @f_*.[.*":|gqgv| :[[_d.| "`"+| :[^[*:+` >!>+| w!w+/&=w+g#cxrnxrnx<?sa"?sikrkkrkk&>va<,kndn<:n#,a<,xi'<.i'<.i'#,a<^=>} ``` # LaTeX, 506 bytes Most likely there will be a more efficient variant, but this is what I managed to get by hand (no built in compression tools in LaTeX...). I created a small loop to replace consecutive sequences. ``` \def\|{\catcode`}\def~#1{\|#1=13\lccode`~=`#1\lowercase{\def~}}\| =12~@#1#2{\ifnum#1>0#2@{\numexpr#1-1}{#2}\fi}\|#=12~){@3}~({@4}~?{(.}~/{( }~<{@9 }~>{< }~_{>)#}~[{<#).#}~]{<#.#.#}~^{#).#@6.#.#}~!{#@{18}-#}~={@{42}#}~'{?}~&{#..#?#?#}~;{/#@9--#}~:{#@5.#@6.#}~"{#.#..#?#..#}\newlinechar`+\typeout{>/@{12}{*}+>/(#?#.+> #..)#@5.##?+> )#@7.@6#) _ _+>@5 @{11}.@5 @2[+>/##*@7#@7 @2]+> (#@7*@6#) @2]+>).#)*.(*.*)#?@2[+>?@9**##@5._ _+>?(*/@5*?+> (#@8 (#+>@6#@8 @6#+@{62}#+)^!+=!+)&@{20}#+=;+):;+=;+)";+=/@{12}#} ``` Terminal output (of both codes): ``` This is pdfTeX, Version 3.14159265-2.6-1.40.20 (TeX Live 2019) (preloaded format=pdf latex) restricted \write18 enabled. entering extended mode (./mariocg.tex LaTeX2e <2018-12-01> ************ ####....#. #..###.....##.... ###.......###### ### ### ........... #...# #...# ##*####### #.#.# #.#.# ####*******###### #.#.# #.#.# ...#***.****.*###.... #...# #...# ....**********##..... ### ### ....**** *****.... #### #### ###### ###### ############################################################## #...#......#.##...#......#.##...#......#.##------------------# ###########################################------------------# #..#....#....##..#....#....##..#....#....##################### ########################################## #----------# #.....#......##.....#......##.....#......# #----------# ########################################## #----------# #.#..#....#..##.#..#....#..##.#..#....#..# #----------# ########################################## ############ ) ``` [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 138 bytes ``` 00000000: a591 410a 0321 0003 efbe 6261 6e42 e7ff ..A..!....banB.. 00000010: cf2b b522 6e5a 6cc5 3908 2184 18bd eed4 .+."nZl.9.!..... 00000020: 8912 1e80 2ade 1db4 3b82 9a76 f794 c695 ....*...;..v.... 00000030: 6ec8 7205 0e0c 0795 9019 874a 1677 1009 n.r........J.w.. 00000040: 5972 717d 4363 2bae bed2 d676 00aa ff5f Yrq}Cc+....v..._ 00000050: 5eb5 0e40 d5df 2f17 e9f1 a99a 1f33 0f22 ^..@../......3." 00000060: e290 2e14 8e28 a8d8 4096 eaf1 c156 fbd7 .....([[email protected]](/cdn-cgi/l/email-protection).. 00000070: b8a2 f663 a992 bded edc1 a279 5ab7 5219 ...c.......yZ.R. 00000080: 3d6b 9d56 b152 a7ad 134f =k.V.R...O ``` [Try it online!](https://tio.run/##XdFLaxVBEAXgvb/imJUYKLuq34aAj50bIQvBLJR@VLswuZBAFBf@9muNdxLEgtkMzVenT/eH3m/028Pt8ej2eY0WKyOwa3BeGPbPQ1dXJEmMpEGgeS2A6C3Rc7Lp7fCO6NlJYDPGko4eRex8bEhjRPjqCoRLAJc@oTqDGed0dri@oXqCHg0xo1QWsBYHaVPBswf4XgS15YSVa8BINW45iF7ad0H04x/Dm5F0FGRxEU7dgMt2vjquKDk0cMoZ7FwFDnRP@3ygn09GMCPWLMicJ4JPHtKbousUzGQ5nGsNa0Xr4/P93e/343wzthxfdyNuhvYtQnCYcS7I4gyti9FqtRzLe7hlbeEL0RuiV6ckns52I5mhUq0K5YCiUtDKLAiuJmgzaHC0UvrMpz7oxV@I6NPTXbIZvTTBSnYNWyzoU@0h5rAckiti6xlRrJ7NGHsfv67p6tEoZviZOuq0dZ2joOU2wT5YAf/N5XfbfmXCx@PxDw "Bubblegum ‚Äì Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~235~~ 213 bytes ``` ‚Äú¬µ!√¶eƒ±√ß»∑&#√∞%√∏&$d…ìe√±e√∑∆ù$∆§&…ì'¬§"' 'dd%d·∫ée»§d∆§∆¨dd∆≤d∆ù‚Äòs2‚Å¥+‚±Æ23¬§≈º·∫é·π£j∆≠∆í‚Äú√á=√ág∆≤'‚Ǩ$f»§e∆≤‚Ǩf∆ài√Üf¬øf√ê…¶√á!√ó√áe2j√ë√欵√æ¬øg8i‚Ǩ√欵√æ¬Ω%4∆ù5∆ù2f∆≤√ó√ó¬Ω∆≤;#¬Ωf¬øf¬Ω∆≤5¬§6∆≤‚Ǩg¬¨g¬Ωi¬¨‚±Æv√ò√ò√ò·∏≥∆Å·∏≥√û√û√û‚±Æp≈ì√ü√ü√üd≈ì‚Åæ≈ì≈í≈í≈íd≈ì‚Å欧o‚Äòb50U+√ò0U‚Äò≈í·πô·πÅ1x‚±Æ‚Äú&√∞·∫è·π™¬∂·∫è√ó·πò‚Å∑∆á‚Åæ1·∫í·πÅn#‚Äôb64¬§¬§·ªã‚Äú *#.-‚ÄùY ``` [Try it online!](https://tio.run/##LU9dSwJBFP0r2qoLSaGmEkQ/w4deZXZFkQqCqLfdHtog6MN9UKGthwaDsNAt07VWYW570Z8x80fsbsW5M3Pu5Zx75zaMZvN0tVLWnRgloWd8D@FpMc5oMEjDJJNiS9eAoQFj9FLIM0tXF3xNT@iMpZmcXhkLzpBjnzH0GXrK6hwVlP2eVcPXwpbg0RdpZPDYwBds0QhwdsGpoa@rs37KXHADfWImXtTh3BRzE26WPXCS0AbHKDTgFmZiRGde266T7j8L00X0SugVTPRJ2RYh@juaCOMGMS8JXv7tWxMUYV306TfH0IkhJ29o0wX3Mah@GLnwEINFrrJnkRu1Yvxlgh/QRtVSrpKFTq5CPGrJoCsDO39CXlooAwM5vZbBs/igF9oy6Ch7jA6Z83JKYntfU1a3Wi4KLrj8vCRPYl3b3FCWt7da/QA "Jelly ‚Äì Try It Online") Uses a combination of run-length encoding and replacement of common length-2 sequences with a single digit. Does not use any standard compression library like gzip. Overall has 169 bytes of compressed data and 44 of code. ## Explanation ### Step 1: replace values in the data between 17 and 39 with prestored pairs of bytes ``` ‚Äú¬µ...∆ù‚Äò | Base-250 integer list 9, 33, 22, 101, 25, 23, 26, 38, 35, 24, 37, 29, 38, 36, 100, 155, 101, 27, 101, 28, 150, 36, 151, 38, 155, 39, 3, 34, 39, 32, 39, 100, 100, 37, 100, 209, 101, 154, 100, 151, 152, 100, 100, 153, 100, 150 s2 | Split into twos ¬§≈º | Zip the following as a nilad with this: ‚Å¥ | - 16 +‚±Æ23 | - Add this to implicit range from 1 to 23 ·∫é | Tighten (join outermost lists) ∆í‚Äú√á...o‚Äò | Reduce using the following, and starting with the base-250 integer list 14, 61, 14, 103, 153, 39, 12, 36, 102, 154, 101, 153, 12, 102, 156, 105, 13, 102, 11, 102, 15, 160, 14, 33, 17, 14, 101, 50, 106, 16, 31, 9, 31, 11, 103, 56, 105, 12, 31, 9, 31, 10, 37, 52, 150, 53, 150, 50, 102, 153, 17, 17, 10, 153, 59, 35, 10, 102, 11, 102, 10, 153, 53, 3, 54, 153, 12, 103, 7, 103, 10, 105, 7, 149, 118, 18, 18, 18, 217, 143, 217, 20, 20, 20, 149, 112, 30, 21, 21, 21, 100, 30, 142, 30, 19, 19, 19, 100, 30, 142, 3, 111 ∆≠ | - Alternate between: ·π£ | - Splitting j | - And joining ``` ### Step 2: Run-length decode and convert to string ``` b50 | Convert to base 50 U | Reverse order of bytes +√ò0 | Add 0,0 U | Reverse order again (effectively the last three links add in leading zeros where needed) ‚Äò | Increment by 1 ≈í·πô | Run length decode ·πÅ ¬§ | Mould like the following as a nilad: 1x‚±Æ ¬§ | - 1 repeated each of the following as a nilad: ‚Äú&...#‚Äô | - Base-250 integer 36418435425519061363927141799858777786 b64 | - Convert to base 64 ·ªã‚Äú *#.-‚Äù | Index into " *#.-" Y | Join ith newlines ``` [Answer] # Bash + coreutils + xz, ~~243~~ ~~242~~ 240 bytes ``` base64 -d<<<4AROAJpdABBtAVsJZEAxAEVT46Z4yzQSDRh1V2s3yKKQ3CiFBCqNr55BVH/f7Qz/mkCIrVe+i4qcFSY5BEjUGbKH55TbsFibiXAoQ8LLpf0KeeR/Qj+UVG3Y3+Xx/Xt+0BI+rKPZCnr2NYt5PB4YsQBJeHbN+TCDB9VxVA5l2MZerD23kdk9GwTt9T7j2LGzPwyNGnq9XrJxWS3PWQOEtp8A|xz -qdFraw ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 211 bytes ``` Xr9.HC.Z"x√ö]ç√Å √Ç@E %Q‚¬≤.NŠ[@‚ ^LI¬¶ ¬∞Š√±¬æ$√¶>A¬º√õƒx]√ꬣc√¥ 2√å√ø√¶?&¬∞sT M3ù¬´D √ä√á‰b√ù/√⬨}√å √è√û‘L¬¶&›¬°%¬ÆR$è√®Wè+…m√∂>3Ž`!Wr¬¢“√™0-√º {*√∑Kšj√é√á√ã√°√Ç√è√ím*√º√∫Y√ì^ . √ï¬ØŽ√鬥√ì,√¶†]√≥¬´ –√éR√§P¬®√ØB #¬™5C√∏¬Æ√ûš?√á√á¬∏z-vx√ã"<G6" .-*# ``` [Try it online!](https://tio.run/##Dc5dK0MBAAbgJpp9NCTc2bHNLsYOWZTSNkbIRyw1H22JG6mVRhpy4Yi1D2dYXGxRQ6e1aRsW0qLe94fN/sDTs3d0sFOrrYZGxRmPuG4KM@3HFc80lNytU7rW3mVIeBcXVYhtuCHpAu3zqlk1FLUOZcSa@IZfCxXnOKrM4Dxs9PMaz9usCENM8M9IxWVFeb9txaBZaHbgAYVJPWOMILrFhwFG8XrKhNDAJB9xMw/FigyyvSh61RYkmfMh2YeLID@dagfkzR5fCE9IdTI/aGdVe2Lj1xzSu5QZYZxZSnXnNmhjlT9rTAU0YofAO5QgU0aFqX4quDT4@YGCgHvK3q5Gviwhx9KEvtuM/LCH3yjWJ2kXIy315Pexyn4YZtw0Nj1i0gqi3Wau1f4B "Pyth ‚Äì Try It Online") Compression method: Since there's only 6 characters, the space, newline as well as `#.-*`, replace each of these with a letter from `a-f`. Afterwards, run-length encode the whole thing (`aaaaaccc` -> `5a3c` etc.), then compress using zlib. ``` Xr9.HC.Z"..."<G6"\n .-*#" # Complete program (last " is implicit) "..." # zlib-compressed string .Z # decompress C # read that as a base 256 integer .H # convert to hex string r9 # run-length decode X <G6"\n .-*#" # translate "abcdef" to "\n .-*#" ``` The compressed string is ``` _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f 000_ 78 da 5d 8d c1 09 c2 40 10 45 0b 10 25 51 82 b2 001_ 2e 4e 01 8a 5b 40 82 0b 5e 13 4c 01 49 07 a6 07 002_ 0b b0 8a 05 f1 be 24 e6 3e 41 bc db 83 78 1f 5d 003_ d0 a3 63 f4 20 32 cc ff 1f e6 3f 26 b0 73 11 54 004_ 0e 09 4d 08 33 9d ab 44 0c ca c7 89 62 dd 2f c9 005_ ac 7d cc 20 02 cf de 91 4c a6 26 9b a1 25 ae 52 006_ 07 24 8f e8 57 8f 2b 85 6d f6 3e 07 33 8e 60 21 007_ 57 72 a2 93 16 ea 30 2d fc 0a 7b 2a f7 4b 9a 6a 008_ ce c7 cb e1 c2 cf d2 6d 2a fc fa 59 d3 5e 09 2e 009_ 15 20 d5 af 8e ce b4 d3 2c e6 86 0e 5d f3 ab 20 00a_ 96 ce 52 17 04 e4 50 a8 ef 42 0c 1e 23 aa 35 43 00b_ f8 ae de 9a 3f c7 0f c7 b8 7a 01 2d 76 78 cb ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~¬†265¬†~~ 264 bytes *Saved 1 byte thanks to @Night2* Deflated. ``` _=>require('zlib').inflateRawSync(Buffer('pVJbDoAwCPvfKZb0b4nc/3jCRAWGOrN+qNiV8litDs2geKqCQQyQZ/inMnS8SpQRKSsYkoYw2la6ESuSpCEcq27IjPt5eDmCXFQ6jCTFl1yqYSW1/tAxzBcvp+9l6BCnJ3eqr6Wmi4H9LoHzLPNYQukd6k04bspjtA345Z7K1QDnPX2O0uKn0QcWnE13b9EoXXE1XeEtWnU12AE','base64'))+'' ``` [Try it online!](https://tio.run/##BcHJcoIwAADQzwmMrbKJerAzGLBWXIi0Al46JAYnGBOWoNWfp@@V@T1vScMq9S7kmfbFvP@dfzS07lhDNfDiDAN9yETBc0UP@SN@CqItuqKgjQaq4xr70nvA6F6EJ2xgR5CRXcKDl3zum92g3rHjlDPlt9aFhjVE6IlOIya2Ip7GFTqEcZtdZfaweO4GcRdXMCC1NfkqIzWm/g2mS@SW8HvJzWedxYk5Ut7fa0Hu1WDG3QUUa5vWjZvcmLOabeTqtYl2GequZ/dqOLitSuXZzvg0CU3kiyi19kYXCgORRASmjWeBTNPATGmgEvFjWl4A3gDOW@o6QNcHAPREilZyOuTyohWarvf/ "JavaScript (Node.js) ‚Äì Try It Online") --- # [JavaScript (Node.js)](https://nodejs.org), 318 bytes Consecutive string substitutions. ``` _=>[...`L=J00BP FM1A46E.##3B 2G@;<9#7#:7#8.653*42-1.0 #`].reduce((s,c,i)=>s.split(Buffer([94-i])).join(c+`A= >9SOKQ< <N0#0H<> ?0C5;D3 13:498#653*42-1.0 #`[i]),`?T]=JT29#.\\A[O9\\[3.I?10#?0C779D.?TSYJT0*I#77 UBUJ2=8*I? UBUW3<8*.=.*[YYW9]8Z.K0#?0CK9=4=*9\\272WI7I F;6I AX3X3X@HV#@HA>>0L>0L>;2CVR>EZEZPRVRM^0<^0<^#RV462`) ``` [Try it online!](https://tio.run/##VY1Nb4JAAETv/AqSvQDVzbIgsMKC4EcFtVpErAItBqHBGDGi/fsUe2vmHebyZk6Hn0Od3crrvXupjnlT0OaLmhGEMJ1TDyFnxUwWoi0rYwiA5DD4daAbBKigrwINKj1JkHFXhIgFaQJv@fGR5RxXd7JOyVOzhvX1XN4551EU@Y2LiNwtE56Hp6q8cNlLalPWJOvl7N1gjTcE0NQwWQsNe/pIYkSpLxMN/HuIWruTWkFCvQATAOPYjpYkjiMJupaIQOuqKhlBK1jvvAAJLlBVduNsPEw1wbWedSsZmgApFKLdbksSbQ9nf96MUJkK7RZW8dZVXWaiKy5jf0htBtMQDKa2aaL5Ex0PQ98c78f7lR/6i09kPAF@KCs45ZusutTVOYfn6psrOJ5vfgE "JavaScript (Node.js) ‚Äì Try It Online") --- [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~322~~ ~~320~~ ~~318~~ 316 bytes -2 bytes thanks to ceilingcat. ``` f(i,c){for(i=0;c="/<q/TDQAq-QBSERDq-SGV.S,Sq/!K/QCQ*QCQq/R1W/\"QAQAQ*QAQAQq,T7V-QAQAQ*QAQAQq+CQ3A4A1SD*QCQ*QCQq+D:RE+S,Sq+D4$5Dq-T(Tq+V(Vq____RqQCQFQARCQFQARCQFQARocQq__]ocQqQBQDQDRBQDQDRBQDQD_Vq__\\$QjQqQEQFREQFREQFQ$QjQq__\\$QjQqQAQBQDQBRAQBQDQBRAQBQDQBQ$QjQq__\\$\\"[i++];)for(;c--%16;)printf(L" *.#-\n"+c/16-2);} ``` [Try it online!](https://tio.run/##XVBBTsMwEDyTVxRTJDuOawKlSJgenDrlAJe1o3DAVYUsBRmJFFfcqr49dSIQEbvaGWlmZw/r2LtzXddgnzlyaHZ77JdXwi0Rfwi8UiADg8KUWgVmHuuZyUzg508cVpDGCVznL9wikLHTAUNW3dVsLNAV3Mi5zI1Kf2NU3euS9seomk9v4/EKV4HWuA7bWDrEpTVIPcadg2hueoICFCg9wm0ftHYKH9EtYa1/Bgblz5JDtND/eLRmLXr1lG4E6Z8hHGOX@UKQr71vvxv8jCbp7ILZFlHH8wW7JuLYRWfy@eZbTJJDctZgIpJjdwI "C (gcc) ‚Äì Try It Online") [Answer] ## Bash + coreutils, ~~269~~ ~~262~~ 261 Bytes ``` base64 -d <<<H4sICLN9e10CA01BUklPAKVSWw6AMAj73ymW9G+J3P94wkQFhjqzfqjYlfJYrQ7NoHiqgkEMkGf4pzJ0vEqUESkrGJKGMNpWuhErkqQhHKtuyIz7eXg5glxUOowkxZdcqmEltf7QMcwXL6fvZegQpyd3qq+lpouB/S6B8yzzWELpHepNOG7KY7QN+OWeytUA5z19jtLip9EHFpxNd2/RKF1xNV3hLVp1tWPaAR8+K1RPBAAA|gunzip ``` A bit trivial - nothing clever happening here. I'm not sure if I'm allowed to use gzip like this. If I'm not I have no doubt someone will shout at me. (better if I remove pointless spaces/quotes) Thanks to @manatwork for saving a byte [Try it online!](https://tio.run/##BcFLjoIwAADQq7gnE@mAIMtiKsinUg2i7hDKrzi0CgKNd2fee6TvalloVnUrV38fdgG2KFB3UAV2zNoI@pdzMhowhI2pzc/EchRPiyx9ZGRfNUIWorm1hXd7ERN3bi1KhkLmFDqXnvpBIkZn9nI83wkxT4YKvZgglev3w3yQJr2Wm7Kd4mM3sumeZ@KJ2r4wSZiN18AoPndaEj7nmhBKy7vBXp8NeztLmaCAu5Tjo2P6N5Ng5ZjQuY/hRgKr6YOaW8jd8wnnv@uTvwcTvmhVcOGgT6IUnraKD06RDSH8PtI3NfTVT/4thz9Z82X5Bw "Bash ‚Äì Try It Online") [Answer] # Python3, 921 916 752 751 539 534 476 bytes And here's a mandatory fair version. I used a script to count the individual characters, should be identical: ``` w,s,d,r=' *.#' m='--' n=m*5 A=d*2 B=d*3 C=d*4 D=d*5 E=d*6 F=r*2 G=r*3 H=r*4 I=r*6 J=r*42 K=w*10 L=K+w M=L+w N=M+w O=w*15 P=w*4 Q=w*8 R=d+r S=r+R+R T=B+r U=r+T V=r+A W=r+d+F+T+E X=r+C Y=r+E+F+D Z=R+A+X+V a=r+P+r+n+r b=J+P+r c=F+A+X+X e=b+n+r f=s*12 g=d*7 h=s*3 j=s*4 k=r*62 l=m*9 o=r*11 p=r*21 z='\n' for i in"OfzOHCrdzNVGDFCzNGgINwGMGzOwDEOUKUzOFsGHNPSKSzMHhjINSKSzLThdjdsGCKUKUzLCjhhFDLGMGzLCjPjsCzNHQHzLIQIzkzUEWWrdFlrzJrlrzVXXccpzezrDYYrEazezrZFZFZazboz":print(end=eval(i)) ``` [Try it online!](https://tio.run/##HY9bb9pAEIXfz69A6YMTL6lqLmlaaR6I79jY3DFRX4CFGIcYax3V6v55Oo5W@vacOTOrnerfZ34t@8@Vut2abt2VXUVGx/z@zcAHGY@PBkr6MIcYkTR7eGH2YTMHcJhDuMwneKQ49Zl9BMwBQuYTxq3uIaLGtH4gpkg0mFDMTGjCTNtgiClfA8yYz5iTFAoLUmIu5ljSC7sVuyXWzBE2TCk8sRQuMtY2tkyXKw5eaS5GIhNr7Lg2FUqUPL2ncatxIO8rzXCk/Vdyotq0enjjHX4iZ9NHwRzgvf19Dxde/ReubCwLVbujBU3Gn9LA6ao65865vEtPOg1sJXWy9h3P1on/FiaNP/F12jhuuopWOvVqP0imi2ihJ0FehEmr4mUuC1n7dtS2xHaR554Tt3Osp0XNLwWzQMfhLNTveuVuNkp6F6XHirHOssOh0ketnO1WubtWvXp8dnp/1Xe/K3UuP@@PpaTj393l/vzwcLv9Bw) **Courtesy of the awesome guys in the comments that are much better than me!** And here's the (python3) script for any others who might want to generate some code and are too lazy/efficient to count manually: ``` mario = ''' ************ ####....#. #..###.....##.... ###.......###### ### ### ........... #...# #...# ##*####### #.#.# #.#.# ####*******###### #.#.# #.#.# ...#***.****.*###.... #...# #...# ....**********##..... ### ### ....**** *****.... #### #### ###### ###### ############################################################## #...#......#.##...#......#.##...#......#.##------------------# ###########################################------------------# #..#....#....##..#....#....##..#....#....##################### ########################################## #----------# #.....#......##.....#......##.....#......# #----------# ########################################## #----------# #.#..#....#..##.#..#....#..##.#..#....#..# #----------# ########################################## ############ ''' curr_char = "" count = 0 for i in mario: if i == curr_char: count += 1 else: if curr_char != '\n': if curr_char == ' ': curr_char = 'w' elif curr_char == '#': curr_char = 'r' elif curr_char == ".": curr_char = "d" elif curr_char == "-": curr_char = "m" elif curr_char == '*': curr_char = 's' print(curr_char + '*' + str(count), end="+") else: print(",", end="") curr_char = i count = 1 ``` # Python3 loophole abused, 167 bytes Since nothing was said about standard loopholes, I'll sneak this one in here while I can. TIO doesn't like urllib for some reason, if anyone knows a site to host the script on please tell me to. Obviously a link shortener could save some bytes, but I didn't want to go down that rabbit-hole any further. ``` from urllib.request import * import re print(re.split("</?code>",str(urlopen("https://codegolf.stackexchange.com/q/192715/85978").read()))[1].replace("\\n","\n")[:-1]) ``` [Answer] # [Keg](https://github.com/JonoCode9374/Keg), ~~2204~~ ~~1012~~ ~~745~~ 722 bytes ``` (35*| )(34*|\*) (35*| )(4|\#)(4|\.)\#\. (35*| )\#\.\.(3|\#)(5|\.)\#\#(4|\.) (76+| )(3|\#)(7|\.)(6|\#) (2|(34*| )(3|\#)) (82*| )(65+|\.)(5| )(2|( | )\#(3|\.)\#) (35*| )\#\#\*(7|\#)(7| )(2|(91+| )\#\.\#\.\#) (34*| )(4|\#)(7|\*)(6|\#) (2|(91+| )\#\.\#\.\#) (65+| )(3|\.)\#(3|\*)\.(4|\*)\.\*(3|\#)(4|\.)(2|(91+| )\#(3|\.)\#) (65+| )(4|\.)(91+|\*)\#\#(5|\.)(65+| )(3|\#)(34*| )(3|\#) (65+| )(4|\.)(4|\*) (5|\*)(4|\.) (2|(8| )(4|\#)) (2|(8| )(6|\#)) (88*2-|\#) (3|\#(3|\.)\#(6|\.)\#\.\#)\#(92*|\-)\# (67*1+|\#)(92*|\-)\# (3|\#\.\.\#(4|\.)\#(4|\.)\#)(54*|\#) (67*|\#) \#(91+|\-)\# (3|\#(5|\.)\#(6|\.)\#) \#(91+|\-)\# (67*|\#) \#(91+|\-)\# (3|\#\.\#\.\.\#(4|\.)\#\.\.\#) \#(91+|\-)\# (67*|\#) (34*|\#) ``` [Try it online!](https://tio.run/##fVJBEoMgDLz7Cma4AI7OVAX0L1w7PfQL/t1mE6JMp/XQSpLNZtnwfr6Ow80x7Ma7eQl7Cb7TeNmL5f/RF1tGzeNcRjdzNdaqFVzncuqZi6sZOZdwNsZNO4/QKoHXicMUewZGBITqeApQ4PbNYFsCSJlasNujV038A3pp5GdcSSWYPx0QILLGOjh4uuIiX5o5X1a0FI3ESiEQ1NEKX6J4EBtbWhe@OnmkgdLIwsVVY6r29bwYJ89UUkPXMA1CC/bzRkmXSCUKN/K9DHSi6TlALKlqkujFknWt15eWhFfCunOorhpQguXq1oehk3/AbvvrchoFEt3zyBO2/jg@ "Keg ‚Äì Try It Online") *Saved 267 bytes thanks to @Sriotchilism O'Zaic, -23 thanks to a bug fix.* ## 1012 byte program ``` (35*| )(34*|\*)\ (35*| )(4|\#)(4|\.)\#\.\ (35*| )\#(2|\.)(3|\#)(5|\.)(2|\#)(4|\.)\ (76+| )(3|\#)(7|\.)(6|\#)(72*| )(3|\#)(34*| )(3|\#)\ (82*| )(65+|\.)(35*| )\#(3|\.)\#(91+| )\#(3|\.)\#\ (35*| )(2|\#)\*(7|\#)(98+| )\#\.\#\.\#(91+| )\#\.\#\.\#\ (34*| )(4|\#)(7|\*)(6|\#)(76+| )\#\.\#\.\#(91+| )\#\.\#\.\#\ (65+| )(3|\.)\#(3|\*)\.(4|\*)\.\*(3|\#)(4|\.)(91+| )\#(3|\.)\#(91+| )\#(3|\.)\#\ (65+| )(4|\.)(91+|\*)(2|\#)(5|\.)(65+| )(3|\#)(34*| )(3|\#)\ (65+| )(4|\.)(4|\*)(4| )(5|\*)(4|\.)\ (67+| )(4|\#)(8| )(4|\#)\ (65+| )(6|\#)(8| )(6|\#)\ (88*2-|\#)\ \#(3|\.)\#(6|\.)\#\.(2|\#)(3|\.)\#(6|\.)\#\.(2|\#)(3|\.)\#(6|\.)\#\.(2|\#)(92*|\-)\#\ (67*1+|\#)(92*|\-)\#\ \#(2|\.)\#(4|\.)\#(4|\.)(2|\#)(2|\.)\#(4|\.)\#(4|\.)(2|\#)(2|\.)\#(4|\.)\#(4|\.)(37*|\#)\ (67*|\#)(4| )\#(91+|\-)\#\ \#(5|\.)\#(6|\.)(2|\#)(5|\.)\#(6|\.)(2|\#)(5|\.)\#(6|\.)\#(4| )\#(91+|\-)\#\ (67*|\#)(4| )\#(91+|\-)\#\ \#\.\#(2|\.)\#(4|\.)\#(2|\.)(2|\#)\.\#(2|\.)\#(4|\.)\#(2|\.)(2|\#)\.\#(2|\.)\#(4|\.)\#(2|\.)\#(4| )\#(91+|\-)\#\ (67*|\#)(4| )(34*|\#) ``` [Try it online!](https://tio.run/##nVPBDoMwCL3vK0y8VIwma7XVf@l12WG/4L@7AkWqLlvcQYvA4z2gvh7PdTVuhKVqjBtgidDEmziGJdb07ptYx34LxNpYdBpHCSPZtki@meBbKknOQAmebQsaQEb5SKCJY35subqQOVZg5nu7c6hSIo@ATKnsPHFekkzPBhQHAoeixYB9i0D/G4wKWXef5aSx9VgMz6TD6TBOqj@1kQsqAPXYYrrKeB7bDkwa0rsiJOhGfGi14WkzFe814mUhE9iO7UK/lwuRFV71z2nNscuNB8Bu9165X@kcyjPjr8dcAOmVLRpQXoWSjqXgcvzffERyLPaVh27VUajV@v/Hf2vhn7xu1vUN "Keg ‚Äì Try It Online") This is just a run-length encoding of the ascii picture but implemented in Keg ## Old program ``` \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \*\*\*\*\*\*\*\*\*\*\*\*\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \#\#\#\#\.\.\.\.\#\.\ \ \ \ \ \ \ \ \ \ \ \ \ \ \#\.\.\#\#\#\.\.\.\.\.\#\#\.\.\.\.\ \ \ \ \ \ \ \ \ \ \ \ \ \ \#\#\#\.\.\.\.\.\.\.\#\#\#\#\#\#\ \ \ \ \ \ \ \ \ \ \ \ \ \ \#\#\#\ \ \ \ \ \ \ \ \ \ \ \ \#\#\#\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \.\.\.\.\.\.\.\.\.\.\.\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \#\.\.\.\#\ \ \ \ \ \ \ \ \ \ \#\.\.\.\#\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \#\#\*\#\#\#\#\#\#\#\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \#\.\#\.\#\ \ \ \ \ \ \ \ \ \ \#\.\#\.\#\ \ \ \ \ \ \ \ \ \ \ \ \ \#\#\#\#\*\*\*\*\*\*\*\#\#\#\#\#\#\ \ \ \ \ \ \ \ \ \ \ \ \ \#\.\#\.\#\ \ \ \ \ \ \ \ \ \ \#\.\#\.\#\ \ \ \ \ \ \ \ \ \ \ \ \.\.\.\#\*\*\*\.\*\*\*\*\.\*\#\#\#\.\.\.\.\ \ \ \ \ \ \ \ \ \ \#\.\.\.\#\ \ \ \ \ \ \ \ \ \ \#\.\.\.\#\ \ \ \ \ \ \ \ \ \ \ \ \.\.\.\.\*\*\*\*\*\*\*\*\*\*\#\#\.\.\.\.\.\ \ \ \ \ \ \ \ \ \ \ \#\#\#\ \ \ \ \ \ \ \ \ \ \ \ \#\#\#\ \ \ \ \ \ \ \ \ \ \ \ \.\.\.\.\*\*\*\*\ \ \ \ \*\*\*\*\*\.\.\.\.\ \ \ \ \ \ \ \ \ \ \ \ \ \ \#\#\#\#\ \ \ \ \ \ \ \ \#\#\#\#\ \ \ \ \ \ \ \ \ \ \ \ \#\#\#\#\#\#\ \ \ \ \ \ \ \ \#\#\#\#\#\#\ \#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\ \#\.\.\.\#\.\.\.\.\.\.\#\.\#\#\.\.\.\#\.\.\.\.\.\.\#\.\#\#\.\.\.\#\.\.\.\.\.\.\#\.\#\#\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\#\ \#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\#\ \#\.\.\#\.\.\.\.\#\.\.\.\.\#\#\.\.\#\.\.\.\.\#\.\.\.\.\#\#\.\.\#\.\.\.\.\#\.\.\.\.\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\ \#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\ \ \ \ \#\-\-\-\-\-\-\-\-\-\-\#\ \#\.\.\.\.\.\#\.\.\.\.\.\.\#\#\.\.\.\.\.\#\.\.\.\.\.\.\#\#\.\.\.\.\.\#\.\.\.\.\.\.\#\ \ \ \ \#\-\-\-\-\-\-\-\-\-\-\#\ \#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\ \ \ \ \#\-\-\-\-\-\-\-\-\-\-\#\ \#\.\#\.\.\#\.\.\.\.\#\.\.\#\#\.\#\.\.\#\.\.\.\.\#\.\.\#\#\.\#\.\.\#\.\.\.\.\#\.\.\#\ \ \ \ \#\-\-\-\-\-\-\-\-\-\-\#\ \#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\#\ \ \ \ \#\#\#\#\#\#\#\#\#\#\#\# ``` [Try it online!](https://tio.run/##xVS7DoMwDNz9FUi3IdVfxFp16P/PQSiYxhBsE6iiWyCOcz6/vu9PStNgYjwBOX5YwSuWLzLv51ulD6s/ctlYAQX8SG2rp3bYcQu8HEmktjWS61HphRtvfh8mOxx24dKdEYviLrvkJnPyxs5bBFYN7mZe3q5Nhu7E53tuz32c1PjE4PScHD/LN/ujI6iood4J5U65bnsF8D/tcXatAId92mKLZ/55/DrM1lyvXastwtpLa71WaLb11lpFSjM "Keg ‚Äì Try It Online") I know this probably won't win any competitions, but hey, it looks nice. Literally just escaping every character and printing it. I mean, it could be golfed, but don't you just love ascii art programs? [Answer] # [Bash](https://www.gnu.org/software/bash/), 486 bytes ``` a=#.#.#O#.#.# b=#e#O#e# c=I#w# S="Tb T3f#. R#d2g1f R2i5S2Q2 UmT$b T1*6V$a Q3]5R$a Pe#Y.Z.*2fO$b Pf\`1gP2Q2 PfZI[f R3M3 P5M5 EEA #e#h#.1e#h#.1e#h#.1wu# EDwu# #d#f#f1d#f#f1d#f#fD EC$c #g#h1g#h1g#h#$c EC$c #.#d#f#d1.#d#f#d1.#d#f#d#$c ECI;" p(){ for((i=$[d-$2];i>0;i--)){ printf "$1";} } IFS= while read -r -d '' -n1 c;do printf -vd %d "'$c" [ $d -le 47 ]&&printf "$c"||[ $d -le 69 ]&&p '#' 47||[ $d -le 86 ]&&p ' ' 69||[ $d -le 98 ]&&p '*' 86||[ $d -le 109 ]&&p '.' 98||p '-' 109 done<<<$S ``` [Try it online!](https://tio.run/##XY3dboJAEIXv5yk2zNZVE4gLhWqQJk2lCRdGFNukWpMiywpJq4398UJ8droqNaSZzJnZ@c7MLuPPrCxjDw0Vo5PC0sNU9SlC4gW4Q4g8bbqEqSXRgAkKc8UlTMzcjsyxCY/vU6ogbztPNIaxtbAnqoYpPhszo23KkaKhfHnlq/BoD@UsmKt1a2hBaA9t8P07UH9laPC67r4R/MFRUaBEyWs6AP@eJoArzHiVqN7noXHyC/6vng2Bq8FHs7UHudk2m7lH50Kn5sLNbzturuut1p58bPP1lyQa5Zp7gAMED5EHuyx/S8k2jQXRt0QXhDGirzlJXLGBakP/EeRKEI3RRIM5ocqqdq5vyKLRuBxNtKK4MKd3YoQhU74a6DoVUOH0aqDXrUCbKVMN8M7fLYMpV1GoTmfHMYjNOu33@zQqy18 "Bash ‚Äì Try It Online") The Run-Length Encoded string $S generated by the non-golfed program here: [Try it online!](https://tio.run/##pVJLT4NAEL7vrxhZDBYDKY3pI4SDlyYejIdeTNoeELZ2kwYqbbSJ8bfjLiywLFus6RwYZuf75v0WHrZ5Tk77NDvC03wRIBp4aJ/R5BjdDeAbgRC6gSWYFBzyAR6sfThuSVJ7KymIGzDMyKh9ZHcgHSAWSOcTTnCbgrmk9y/zBYtbhVhWT@vVyjwZ51KdD9CmbSj6QSgjYQxOBk4MlgVOwlqJ0NeW7ghoXLEPcVpHiMIDKToD2jRuYWvA9fPjazAa@cBKCB4mtdv3GyQ0SG9SIsczLdKWkCLmdKxFuhLSK5GzqRbpSMhhifSG2vTkEEbttRdN3wRMxwY4KdOU6Xc@DRbP6L@GqPPML0x9iwIz7r8YGvAVe2t5o3GaECSuNc8Vgi2JGg0zcZlgt@1hj8LjlgqpNNcVXi6doIrZacJtRK2IB1XMbtU21iUu8LhNxwqds8QwNCH@ovNqGNO1i48Yw@XFc3SzDDHEiydXseulaheD5X@k@Npe5sdXCSo6FJdQXspZy@nIv7Jr6SIBru70vKUt/mIpBqZklrrrs7rUa7JKXeE@69qskvwC "Bash ‚Äì Try It Online") Then variables $a,$b,$c in $S were substituted by manual inspection, and a single back-tick had to be escaped in $S to allow variables to be used. [Answer] # Perl, ~~422~~ ~~396~~ ~~370~~ ~~366~~ 365 characters ``` print"f c* f 4#4.#. d #..3#5.##4. d 3#7.6#e 3#c 3# 10 b.f #3.#a #3.# f ##*7#11 2<#.>#a 2<#.># c 4#7*6#d 2<#.>#a 2<#.># b 3.#3*.4*.*3#4.2<a #3.#> b 4.a*##5.b 3#c 3# b 4.4*4 5*4. d 4#8 4# b 6#8 6# 3e# 3<#3.#6.#.#>#12-# 2b#12-# 2<#..#4.#4.#>#.2<.#4>.15# 2a#4 #a-# 3<#5.#6.#>4 #a-# 2a#4 #a-# 3<#.#..#4.#..#>4 #a-# 2a#4 c#"=~s/.<(.+?)>/$1x$&/ger=~s/\w+(.)/$1x hex$&/ger; ``` Run-length encoded in 2 steps: consecutive characters and consecutive patterns of multiple characters. [Try it online!](https://tio.run/##XU/LTsMwELz7K6xOhVpX3eD4ESSC@REuSeoAEkJVQIITvx7GaTjQw3p3ZzQz63Oe3sI8n6fX98/NqAejRu3hBaJOGiIOQcCdm0MjEZl9YCl7q3sZNZygW14qAdPAWl23kET40tVAy8ZEnK6JXlPnjHgjxjGlbi9WiYyXzoDp/V9ggbzxOpjlHI87FtHIIUK5zGqLOvJ6JNj6CFX3a2eglH/5QjGIUxIbyHTwGt1xUYdFnVbgHyWrgVzxAzYPPx@VtDs5PO5TtbXf25vqOU8Fffo67GRfMP2SV/x@nn8B "Perl 5 ‚Äì Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) + tar, 265 = 9+256 bytes This script works with Windows and Linux. The script extracts the output from the tar archive `t` (256 bytes). The `t` should be placed in the same directory as the script. ``` tar xOf t ``` [Try it online!](https://tio.run/##pVRbTsMwEPz3KVbdj0JEfIYiBIgvJHqCEDaKpTSO3E2BirsHO3Vo4qQlVUfKY70ez3ptTaU/yWxzKooGoTJUUWIIOLdPYiAxaa52JN5oo3cUvzBtILsDhvhJm5QgfjRGm/uUlS5hrQoqufh@0CWrsiYhblYLAUNEPYQ5tJAWKIcZO@gz8vARIU1Kn3UYLRqEoSzII8KK3KJBOK46winhdj4O6RjQHcs3Y2KJ/@iuGsuUUfvybZhfvJt9PAzfxNmd69h/hzp5MNj/F0FumLV5vAqi3aG/CYebcjKKR7hIfZLuBbC7p6ejyeJno21YoNzb3bloTL1GtbcrPBddq9pv02J1Cz@wJo6dzVi/gcybkXCGtU8zbe0pE2K5bNzA12sG3Dy7@bkqPryDMSDomquaQZWWkbzbqHM72Ko9Nb8 "PowerShell ‚Äì Try It Online") The powershell script to create the tar archive `t`: ``` (@" ************ ####....#. #..###.....##.... ###.......###### ### ### ........... #...# #...# ##*####### #.#.# #.#.# ####*******###### #.#.# #.#.# ...#***.****.*###.... #...# #...# ....**********##..... ### ### ....**** *****.... #### #### ###### ###### ############################################################## #...#......#.##...#......#.##...#......#.##------------------# ###########################################------------------# #..#....#....##..#....#....##..#....#....##################### ########################################## #----------# #.....#......##.....#......##.....#......# #----------# ########################################## #----------# #.#..#....#..##.#..#....#..##.#..#....#..# #----------# ########################################## ############ "@) | Set-Content f -Force tar zcfo t f ``` [Answer] # Python 3, 551 bytes ``` [print(" *#.-\n"[ord(x[1])-35]*(ord(x[0])-35),end="")for x in ["2#/$$(2#'%'&$%$&$(0#$%%&&%(&%%'&$(0#&%*&)%1#&%/#&%$(3#.&2#$%&&$%-#$%&&$%$(2#%%$$*%4#$%$&$%$&$%-#$%$&$%$&$%$(/#'%*$)%0#$%$&$%$&$%-#$%$&$%$&$%$(.#&&$%&$$&'$$&$$&%'&-#$%&&$%-#$%&&$%$(.#'&-$%%(&.#&%/#&%$(.#'&'$'#($'&$(0#'%+#'%$(.#)%+#)%$(a%$($%&&$%)&$%$&%%&&$%)&$%$&%%&&$%)&$%$&%%5'$%$(N%5'$%$($%%&$%'&$%'&%%%&$%'&$%'&%%%&$%'&$%'&8%$(M%'#$%-'$%$($%(&$%)&%%(&$%)&%%(&$%)&$%'#$%-'$%$(M%'#$%-'$%$($%$&$%%&$%'&$%%&%%$&$%%&$%'&$%%&%%$&$%%&$%'&$%%&$%'#$%-'$%$(M%'#"[x:x+2]for x in range(0,454,2)]] ``` First code golf! [Try it online!](https://tio.run/##fVHtboMwDHwVlNiOQwlQPqRp0h5hewHGj0rttv4JFeoP9vTMCazqunUSJ5/N5XyE0@f5Y/D1PHen8ejPrJJU5@7Vq24Y9zx12966uu1TXtoytjY7@P2TUvZtGJMpOfqkU5UuALjSBg0BAgGXGhCJkAnDTHrClCxupRYC4FrnVImK5IRba/BABEix0dEnwl1x4EK2pGCxvKvIdfAiADICeSSB@7Up1zKVkEz5JVOYGTCaYclscCMIcyvMCtsJFgcb9@Fd3pqw5WWt4TYg3o6Rd3/zB9E9o5GEbj3D0Q9vKlxpfurD93/7oej/7299VDc9Tpuqv/zYceffD1xmTdtkle37ef4C "Python 3 ‚Äì Try It Online") [Answer] # PHP, ~~608~~ ~~565~~ 557 bytes Uses GMP, the `5kJvr...` string was created by first using substitutions to convert the original to base ~~5~~ 6, then GMP to convert to base 62. ``` <?=str_replace(range(0,5),str_split("\n-.#* "),gmp_strval(gmp_init('5kJvrGbxP8CrM96cfgUaH1i7H5NT19NW3eSlwbRNO6MzND4omDb8BkvVwnTb1bQtCr6pet0EVt9BQnTuRSwcrL1Gnzs6dMEKAPctFQDrnbXv3eIzlyPYhZpGTwostpxBRJa7bvJvVVgoVjErM9sLKVxa0YkOaOUgMAP6orzz4ZGzb5iQ4qGDDuUOEiKmrcGTHp58srEheAqQSRQE4dOMlauXH4i06DY6tY8gu4maD2BFa68FA7s9sQG9VplFHpecaduYnzLoZgz18xwunIlSkFyIFCUyVMgVxvN7wxtyFZZSAli6DRyV1EobXZtiRa60mYyIZTYL79x190EjhCRAlBM1Lk11FJCeOFkKpAYW8M1hzUpghKA07J31gHpvlkFFKA4dSXvoZwGPbcrGOsmcsi5GAbhB2MIJe9XJGrA7KcSeMfOdxany7HEcesx8oewhtlRHnwxmG8qu8WwA8fjm1S82LMGrq3t',62),6)); ``` [Run online.](https://3v4l.org/p4QgJ) [Answer] # Python3, 557 bytes Run length encoded, then a few repeated substrings (spaces then three "#", "-" surrounded by blocks, etc) manually extracted. Definitely room for improvement ``` u,v,w,x,y,z="*.-#\n " t=z*4 s=x+w*18+x r=t+x+w*10+x+y q=x+v*3+x+v*6+x+v+x p=x+v*2+x+v*4+x+v*4+x o=x+v*5+x+v*6+x n=x+v+x+v*2+x+v*4+x+v*2+x m=z*10+x+v+x+v+x l=z*10+x+v*3+x print(t*4+u*12+y+z*15+x*4+v*4+x+v+y+z*13+x+v*2+x*3+v*5+x*2+v*4+y+z*13+x*3+v*7+x*6+z*14+x*3+t*3+x*3+y+t*4+v*11+z*5+l*2+y+z*15+x*2+u+x*7+z*7+m*2+y+t*3+x*4+u*7+x*6+z*3+m*2+y+z*11+v*3+x+u*3+v+u*4+v+u+x*3+v*4+l*2+y+z*11+v*4+u*10+x*2+v*5+z*11+x*3+t*3+x*3+y+z*11+v*4+u*4+t+u*5+v*4+y+z*13+x*4+t*2+x*4+y+z*11+x*6+t*2+x*6+y+x*62+y+q*3+s+y+x*42+s+y+p*3+x*20+y+x*42+r+o*3+r+x*42+r+n*3+r+x*42+t+x*11) ``` --- # Python3, 789 bytes Fun with random number generators. The image is run length encoded, then broken into chunks of 6. The first chunk (indices for the symbol to print) is generated from a pseudo-random number generator. The second is a base64 encoding of the 6 numbers. ``` from random import* for a,b in zip([24743,129678,6328,31748,115,39591,43781,6080,105810,23721,53737,47694,64624,41381,26725,50462,13767,37213,119081,62980,29054,29054,29054,88178,27000,29054,29054,22423,17293,29054,53737,4887,17293,29054,29054,29054,53737,4887],[4366013200,2167672897,13976478019,12938928579,1328349251,1124376643,18371322817,10754461761,1090785345,1293447436,1241780289,11828203585,1141125187,3240640705,1091310209,11895611659,4479791875,13976490244,6627279364,1106776456,2164547651,2164547651,2164547651,1387008082,1141121089,1141121156,1141121156,1151866180,1157894218,2248429702,1141137477,1151864906,1090785354,2181316674,1141121089,1107562626,1141121092,11889283146]): seed(a) while b: b,i=divmod(b,64) print(" \n#-.*"[randrange(6)]*i,end="") ``` [Answer] # C, ~~1142~~ ~~1068~~ 1044 bytes It's not very good, but I made it. Basically, I went line by line and any place one function plus two or more function calls was shorter than the original text, I replaced the text with a function. ``` s=32;a=42;h=35;d=46;m=45;p(c,n){while(n--){putchar(c);}}n(){puts("");}c(){printf("#.#.#");}o(){printf("#...#");}z(){p(m,18);p(h,1);n();}x(char*c){printf("%s",c);}y(){p(h,42);x(" #----------#\n");}main(){p(s,15);p(a,12);n();p(s,15);x("####....#.\n");p(s,13);x("#..###.....##....\n");p(s,13);p(h,3);p(d,7);p(h,6);p(s,14);p(h,3);p(s,12);p(h,3);n();p(s,16);p(d,11);p(s,15);o();p(s,10);o();n();p(s,15);p(h,2);p(a,1);p(h,7);p(s,17);c();p(s,10);c();n();p(s,12);p(h,4);p(a,7);p(h,6);p(s,13);c();p(s,10);c();n();p(s,11);x("...#***.****.*###....");p(s,10);o();p(s,10);o();n();p(s,11);x("....**********##.....");p(s,11);p(h,3);p(s,12);p(h,3);n();p(s,11);x("....**** *****....\n");p(s,13);p(h,4);p(s,8);p(h,4);n();p(s,11);p(h,6);p(s,8);p(h,6);n();p(h,62);n();o();x("......#.##...#......#.##...#......#.##");z();p(h,43);z();x("#..#....#....##..#....#....##..#....#....");p(h,21);n();y();x("#.....#......##.....#......##.....#......# #----------#\n");y();x("#.#..#....#..##.#..#....#..##.#..#....#..# #----------#\n");p(h,42);p(s,4);p(h,12);n();} ``` It saves 99 bytes over just using straight printf. Saved 69 bytes by removing *int* and *void* specifiers, and the *#include <stdio>*. Saved another 2 bytes by declaring *i* as global instead of in the *for* loop. Saved another 3 bytes changing printf to putchar in two places. Removed another 21 bytes with changes suggested by @Christian Gibbons: Removed variable declarations at the beginning, changed the *for* loop to a decrementing *while* loop, changed '\n' to 10 in the *n()* function. Saved another 3 bytes changing *putchar(10)* to *puts("")*, courtesy of [this answer](https://codegolf.stackexchange.com/a/49605/45728). ### 1143 bytes ``` main(){printf(" ************\n ####....#.\n #..###.....##....\n ###.......###### ### ###\n ........... #...# #...#\n ##*####### #.#.# #.#.#\n ####*******###### #.#.# #.#.#\n ...#***.****.*###.... #...# #...#\n ....**********##..... ### ###\n ....**** *****....\n #### ####\n ###### ######\n##############################################################\n#...#......#.##...#......#.##...#......#.##------------------#\n###########################################------------------#\n#..#....#....##..#....#....##..#....#....#####################\n########################################## #----------#\n#.....#......##.....#......##.....#......# #----------#\n########################################## #----------#\n#.#..#....#..##.#..#....#..##.#..#....#..# #----------#\n########################################## ############\n");} ``` Try it online [here](https://onlinegdb.com/S1Mcnk9Ur). ### Ungolfed (ish) ``` s=32;a=42;h=35;d=46;m=45; // ASCII indices of (space) * # . - symbols. p(c,n){ // Prints c, n times. while(n--){ putchar(c);}} n(){ // Prints a newline. puts("");} c(){ // Prints a piece of the coins. Used 4 times. printf("#.#.#");} o(){ // Prints a piece of the coins, and the ground. Used 5 times. printf("#...#");} z(){ // Prints a piece of the ground. Used twice. p(m,18);;p(h,1);n();} x(char*c){ // Wrapper for printf. Used 10 times. printf("%s",c);} y(){ // Prints a piece of the ground. Used twice. p(h,42);x(" #----------#\n");} main(){ p(s,15);p(a,12);n(); p(s,15);x("####....#.\n"); p(s,13);x("#..###.....##....\n"); p(s,13);p(h,3);p(d,7);p(h,6);p(s,14);p(h,3);p(s,12);p(h,3);n(); p(s,16);p(d,11);p(s,15);o();p(s,10);o();n(); p(s,15);p(h,2);p(a,1);p(h,7);p(s,17);c();p(s,10);c();n(); p(s,12);p(h,4);p(a,7);p(h,6);p(s,13);c();p(s,10);c();n(); p(s,11);x("...#***.****.*###....");p(s,10);o();p(s,10);o();n(); p(s,11);x("....**********##.....");p(s,11);p(h,3);p(s,12);p(h,3);n(); p(s,11);x("....**** *****....\n"); p(s,13);p(h,4);p(s,8);p(h,4);n(); p(s,11);p(h,6);p(s,8);p(h,6);n(); p(h,62);n(); o();x("......#.##...#......#.##...#......#.##");z(); p(h,43);z(); x("#..#....#....##..#....#....##..#....#....");p(h,21);n(); y();x("#.....#......##.....#......##.....#......# #----------#\n"); y();x("#.#..#....#..##.#..#....#..##.#..#....#..# #----------#\n"); p(h,42);p(s,4);p(h,12);n();} ``` [Answer] # [Python](https://docs.python.org/3/), ~~340~~ 378 bytes I messed up the encoding in the original answer, here's one based on LZW compression. Might revisit my original answer at some point. ``` n=0 for c in'"/AVHF`N.o,>D\\5:{/RD?{C._Q\\%r7,SUOXGh8<}nA^Qddb<=Vb7;L@QPi[XJ65W=p|@<fxMl2+C1gro(x%m"Iz0+B?9d</tYaj.!:6(T#_/5el1Hl{[W&g*A.Oc1*4zf#[{WfLr@Km_jgFkg#1D`&Ik9r\'{M]7c&# X1,U#]=>}JFwVexi7nzbKnS-@-y{IA=l#="EVj=8L`%"9w@zoc9!:q/rT\\OMd]/p^ksiT?P_yj,':n=n*94+ord(c)-32 d=[*' *\n#.-'] s=c=' ' while n:i=n%202;d+=[c+(i>=len(d)and c[0]or d[i][0])];c=d[i];s+=c;n//=202 print(s) ``` [Try it online!](https://tio.run/##FdDLVoJQGEDhOU@BshQEBbFMAX/FNMvS1Ly2AG/niB6kg6FreaGe3Wz2TfZk786HTUDvrlcKWcYNQhaxhPJxpTp6aczf5SBdrtt2Xo@Uj3olqsmznm0nwkK6P@xMnjfF0i@tTnsYL0swWhaMltnrEmvy@pAfw@7HLLmntp@Tauo6DIRT4ivevGSlx4qGS8rhc@HJMf1BGHAzJb/y1Rc/ssbJtViVO0gV7y8uZ0VjtxWab18zb93Yrjm1Pk82t1po81HbKaAkx07U9JBzoPz72jiOVidSoJflG@1nzMw5albB5yD@NPKg2Jon4trRvARIi@nfSjiw7U4bO8puut2TQaU7O3tpXqdARe1eCkIsoFTmLsdgsESeFW3KyRneYfaAgGd55rgh/oqlOgGayGVzBpbAQpJAyuCvqIBTC4pZZGWd20tsEeemlGMg@LexlwAZVFHgFjK7kNCDsE9dr38 "Python 3 ‚Äì Try It Online") [Answer] ## Pure JavaScript 419 bytes (no lib) Compression (1 step: count each char in hex e.g. `**********` gives `*a`, 2 step: convert two chars like \*1 or #4 to single char witch free ascii code) ``` let d=` ************ ####....#. #..###.....##.... ###.......###### ### ### ........... #...# #...# ##*####### #.#.# #.#.# ####*******###### #.#.# #.#.# ...#***.****.*###.... #...# #...# ....**********##..... ### ### ....**** *****.... #### #### ###### ###### ############################################################## #...#......#.##...#......#.##...#......#.##------------------# ###########################################------------------# #..#....#....##..#....#....##..#....#....##################### ########################################## #----------# #.....#......##.....#......##.....#......# #----------# ########################################## #----------# #.#..#....#..##.#..#....#..##.#..#....#..# #----------# ########################################## ############` c=d.replace(/(.)\1*/g,(m, g)=>g+m.length.toString(16)).replace(/(.)([1-6])/g,(m,g,e)=> String.fromCharCode(' .#-*'.indexOf(g)*6- -(e-1)+58)) console.log(c.length,c); ``` Decompression ``` c=` f*c fICF@ dFAHDGC dH.7K eH cH :0.b fFBF aFBF fGR#7:1F@F@F aF@F@F cI*7K dF@F@F aF@F@F bBFT@U@RHC aFBF aFBF bC*aGD bH cH bCU=VC dI 8I bK 8K He FBFEF@GBFEF@GBFEF@GL2F GbL2F FAFCFCGAFCFCGAFCFCF5 Ga=F-aF FDFEGDFEGDFEF=F-aF Ga=F-aF F@FAFCFAG@FAFCFAG@FAFCFAF=F-aF Ga=#c` console.log(c.replace(/[:-Z]/g,m=>(z=m.charCodeAt(0)-58,' .#-*'[z/6|0]+(1+z%6))).replace(/([ #.\-*])([0-9a-f]+)/g,(m,g,e)=>g.repeat('0x'+e))) ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 971 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) I simply copied the whole string to the compressor. I realized that the string wasn't compressed a lot. ``` "Œæ‚Üî‚Å¥‚ÄöœÉ‚ïî‚Üî√¶z¬Ω‚Ü쬴ƒº;¬æ‚Öù‚Üë¬∂q$+ŒæœÅI#‚Üî@‚â•Œí‚ÅÑ,;‚àÜn2BŒ°¬æ~¬´n‚ñºog‚ï§iCŒò‚册¥Z‚ñë‚àë‚ÑÆE3ƒç‚îÄ√¶`‚Öì+‚Üë≈æS]ƒ∑√∏ 'Œ±N¬≤'Q-œâ‚Öû¬±≈æ<e‚Å¥Œö‚Ññ6‚ĺDfŒ∏‚à´‚Öû)i‚â†Ph‚ïó8B‚ÄΩ`HŒî‚Üí‚îò‚Üìd5‚àë‚à´h‚ï§kŒñŒúY‚Öû|‚å°Œ£œá¬°GŒ•q¬´‚â°‚îÄŒ∑e‚Üí¬∞~‚Åπ*‚ñëŒ∫RŒùycƒç‚ñ°¬±H‚Öîb¬æ‚ÑÆ‚ïó‚ÜïŒò*Œ∂Œú9‚ŵD√¶qƒìœÖ¬¶Jn|¬º‚ñ≤≈´-‚Åπ¬°‚ïó;g¬≤T‚ÑÆF6u*Œµ¬§3‚Öúv‚ñ†‚îî$}Q;‚ñíMKŒ∑BqŒø‚Å∞X‚ï¨/LŒ≤‚îåI‚糖笧¬æ‚ñ∫'‚ñàp¬πA0E‚àëQXŒ≥9¬ßƒçŒ°T‚ñíŒæ‚Åæn‚ÄöŒ•‚à´√¶¬§3I-‚Üï√¶A‚ÅÑgTq‚àö≈°k3>‚ĺŒºœÉ¬§j:Zk‚ñ∫‚ÜìœÉ¬æ≈Ü*‚àë*‚琉öPn◊Ä√¶S~3j‚Äö~‚ñàfo‚ïîŒï‚ĺ‚ñ†¬§œÖ œÅ{¬¶OœÑ‚óÑŒº`]≈óS‚ñìŒ∫Œú4y‚ïë6AŒ®≈´0‚ÅΩ:uMœÜ^œÖŒ∫‚â§&/‚ïê;Œü‚ↂÑñ3‚Üí‚ÅÑŒò¬±≈´<R¬∞œâ.cƒ£¬≤‚Å¥◊ÄKƒì~Œò60ŒïŒ∏^Œï¬ΩrA‚ïê‚óÑ‚Öû‚ïë‚Å∂jH¬≤Œ≤X8ŒìMO≈°Œπ‚â§9#$XŒö∆®]¬∂ƒºA¬æ‚Öõx‚ñ≤Œï|F‚ñ†¬æ∆®(Œ•5Œ®B[‚Üë‚àö‚ÑÆ‚Ö@‚Ü샺\TB‚å†w‚Öù¬≥Œ≤≈°ƒ´Œ∑o¬§Œ©¬¶‚àëCTŒï≈Ü≈æAh‚Ä≤DŒ±œàH?¬°ŒôO‚ÄΩHœâŒï?‚óã√ܬ¶Œñ`‚àô¬≤u ‚Å∂¬æ‚ïöiƒº‚Å∂Œ†7‚ÅæœÅ‚ÑÆ‚ñë;(Œü¬≤9‚Öîv‚óã‚å°‚ÅΩ¬æ‚ÄΩ‚Üë‚æj∆߬¨h¬º‚îåY‚ñ≤¬πƒìhŒºŒû*‚Å¥ƒÅ‚â†cmeeW‚ÑÆADC‚ïꬨ[9i≈°E‚Öõ~‚Ññk‚Öî‚Ññlƒ∑¬º‚Öõ‚àÜ$qŒíR‚îêŒì¬¶‚Öî}\Œ¶‚ĺŒ©x√∏G‚ÅæŒìO≈ó‚Öüzœà;¬π]m‚ïë‚ñë‚Üî‚ïê;‚ÜëœÑŒ©√ÜŒòœáW¬ªG‚àûŒßQT_L Œî nƒì‚ĺ‚Ññ>Œ∂∆ߜŌï‚ÜîŒõŒª‚ÜëEƒ´≈°√Ü‚ÜëgWIŒº≈´‚ñà‚Åπ‚îîŒôf‚å°EŒò‚Å∂cœÖ‚ïê<‚ÖúLjŒ§lœÑ‚Öû‚ÖüŒüB‚ïö@‚ñë‚ÅΩiƒç-|dŒò≈æ‚ÅΩŒ•‚ñ†tPp‚ŵŒ∏‚ïù‚îÇ‚Öúv+M8¬≥Œ§‚ïùŒπ‚ñë‚館∂≈´¬æoƒ´‚Öúo‚ï•\VŒ®Œñ6¬±‚â°‚àÜhl?Œ¶ƒ£ƒ´X‚ïö√¶‚Üí#%C\aG‚ÄõŒô‚å†?ŒûJ‚ÅÑ‚ïê‚Å¥v¬∞¬±‚à´‚Å∏dy‚ñ∫ƒ´Œπ◊ă£&œáeƒ£ ~x≈°/L¬ªœà(Œû]Œ¥‚Äõƒ£√¶‚îÄ‚ïó∆®‚ïöa*‚Ä∞‚ñ†Œ•‚ñ°L$.Œõ‚îî‚âà‚Ä≤9ŒΩ‚Äöv‚ñ묶+ŒõŒæ∆ߌüƒºBKŒ≥√∑Œ†*IŒù‚ÄöœÅTGŒú-^gŒó?√Ü[ƒÅ‚蓼Öìc&‚ñ∫Œ¥√¶‚Üì¬∞‚àö>R%‚îò‚ŵƒ´‚ï•$J‚ñ≤kœàŒ≤‚ñ≤Œß‚ïù0œàŒ≥Œ±p¬æ‚ĺ~Œ≥!Œπ‚Öî_Œ≥œà‚ÅÑ‚Öù‚ïꃣ√Ü‚Å¥A¬ª‚îºJŒª‚àÜ‚â§≈°'Œ£RŒ°Œ©d4¬¨hAVb¬¨zbH‚Å∏œâŒ∏yV¬ª‚Åπ‚ÑñŒæ‚ï§*¬∞KŒΩ-G[‚ïêŒ∂‚àôŒµY‚Üî‚ÅæXp‚Å∑œá<‚Åπ‚âà‚âà‚îê>¬∞(√Ü#¬ºi‚îåŒ≥Œ¥‚à´+ŒµœÖƒºDET‚å°‚àÜ‚ïêŒΩ<xzŒò‚Å∞‚å°hS¬ªŒöKƒº‚Å∞G*mŒµ‚ñ≤GŒñŒªDŒó_Œóx‚ïù‚Å¥ŒòŒªLœÉ‚ïùœàB~œá[Œù#ŒóhŒ°\Œª2Y‚àôœà¬§i‚å†}Œª‚ñí‚îÇŒ±ŒæqzP‚Öú¬∂¬≤‚Äò ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIyJXUwM0JFJXUyMTk0JXUyMDc0JXUyMDFBJXUwM0MzJXUyNTU0JXUyMTk0JUU2eiVCRCV1MjE5MyVBQiV1MDEzQyUzQiVCRSV1MjE1RCV1MjE5MSVCNnElMjQrJXUwM0JFJXUwM0MxSSUyMyV1MjE5NEAldTIyNjUldTAzOTIldTIwNDQlMkMlM0IldTIyMDZuMkIldTAzQTElQkUlN0UlQUJuJXUyNUJDb2cldTI1NjRpQyV1MDM5OCV1MjMyMCV1MDNCNFoldTI1OTEldTIyMTEldTIxMkVFMyV1MDEwRCV1MjUwMCVFNiU2MCV1MjE1MysldTIxOTEldTAxN0VTJTVEJXUwMTM3JUY4JTIwJTI3JXUwM0IxTiVCMiUyN1EtJXUwM0M5JXUyMTVFJUIxJXUwMTdFJTNDZSV1MjA3NCV1MDM5QSV1MjExNjYldTIwM0NEZiV1MDNCOCV1MjIyQiV1MjE1RSUyOWkldTIyNjBQaCV1MjU1NzhCJXUyMDNEJTYwSCV1MDM5NCV1MjE5MiV1MjUxOCV1MjE5M2Q1JXUyMjExJXUyMjJCaCV1MjU2NGsldTAzOTYldTAzOUNZJXUyMTVFJTdDJXUyMzIxJXUwM0EzJXUwM0M3JUExRyV1MDNBNXElQUIldTIyNjEldTI1MDAldTAzQjdlJXUyMTkyJUIwJTdFJXUyMDc5KiV1MjU5MSV1MDNCQVIldTAzOUR5YyV1MDEwRCV1MjVBMSVCMUgldTIxNTRiJUJFJXUyMTJFJXUyNTU3JXUyMTk1JXUwMzk4KiV1MDNCNiV1MDM5QzkldTIwNzVEJUU2cSV1MDExMyV1MDNDNSVBNkpuJTdDJUJDJXUyNUIyJXUwMTZCLSV1MjA3OSVBMSV1MjU1NyUzQmclQjJUJXUyMTJFRjZ1KiV1MDNCNSVBNDMldTIxNUN2JXUyNUEwJXUyNTE0JTI0JTdEUSUzQiV1MjU5Mk1LJXUwM0I3QnEldTAzQkYldTIwNzBYJXUyNTZDL0wldTAzQjIldTI1MENJJXUyNTZDJXUwMTBEJUE0JUJFJXUyNUJBJTI3JXUyNTg4cCVCOUEwRSV1MjIxMVFYJXUwM0IzOSVBNyV1MDEwRCV1MDNBMVQldTI1OTIldTAzQkUldTIwN0VuJXUyMDFBJXUwM0E1JXUyMjJCJUU2JUE0M0ktJXUyMTk1JUU2QSV1MjA0NGdUcSV1MjIxQSV1MDE2MWszJTNFJXUyMDNDJXUwM0JDJXUwM0MzJUE0aiUzQVprJXUyNUJBJXUyMTkzJXUwM0MzJUJFJXUwMTQ2KiV1MjIxMSoldTI1NjQldTAzOUFQbiV1MDVDMCVFNlMlN0UzaiV1MjAxQSU3RSV1MjU4OGZvJXUyNTU0JXUwMzk1JXUyMDNDJXUyNUEwJUE0JXUwM0M1JTIwJXUwM0MxJTdCJUE2TyV1MDNDNCV1MjVDNCV1MDNCQyU2MCU1RCV1MDE1N1MldTI1OTMldTAzQkEldTAzOUM0eSV1MjU1MTZBJXUwM0E4JXUwMTZCMCV1MjA3RCUzQXVNJXUwM0M2JTVFJXUwM0M1JXUwM0JBJXUyMjY0JTI2LyV1MjU1MCUzQiV1MDM5RiV1MjI2MCV1MjExNjMldTIxOTIldTIwNDQldTAzOTglQjEldTAxNkIlM0NSJUIwJXUwM0M5LmMldTAxMjMlQjIldTIwNzQldTA1QzBLJXUwMTEzJTdFJXUwMzk4NjAldTAzOTUldTAzQjglNUUldTAzOTUlQkRyQSV1MjUzQyV1MjU1MCV1MjVDNCV1MjE1RSV1MjU1MSV1MjA3NmpIJUIyJXUwM0IyWDgldTAzOTNNTyV1MDE2MSV1MDNCOSV1MjI2NDklMjMlMjRYJXUwMzlBJXUwMUE4JTVEJUI2JXUwMTNDQSVCRSV1MjE1QngldTI1QjIldTAzOTUlN0NGJXUyNUEwJUJFJXUwMUE4JTI4JXUwM0E1NSV1MDNBOEIlNUIldTIxOTEldTIyMUEldTIxMkUldTIxNTQldTAzQjFAJXUyMTkzJXUwMTNDJTVDVEIldTIzMjB3JXUyMTVEJUIzJXUwM0IyJXUwMTYxJXUwMTJCJXUwM0I3byVBNCV1MDNBOSVBNiV1MjIxMUNUJXUwMzk1JXUwMTQ2JXUwMTdFQWgldTIwMzJEJXUwM0IxJXUwM0M4SCUzRiVBMSV1MDM5OU8ldTIwM0RIJXUwM0M5JXUwMzk1JTNGJXUyNUNCJUM2JUE2JXUwMzk2JTYwJXUyMjE5JUIydSUwOSV1MjA3NiVCRSV1MjU1QWkldTAxM0MldTIwNzYldTAzQTA3JXUyMDdFJXUwM0MxJXUyMTJFJXUyNTkxJTNCJTI4JXUwMzlGJUIyOSV1MjE1NHYldTI1Q0IldTIzMjEldTIwN0QlQkUldTIwM0QldTIxOTEldTI1M0MldTAzQkVqJXUwMUE3JUFDaCVCQyV1MjUwQ1kldTI1QjIlQjkldTAxMTNoJXUwM0JDJXUwMzlFKiV1MjA3NCV1MDEwMSV1MjI2MGNtZWVXJXUyMTJFQURDJXUyNTUwJUFDJTVCOWkldTAxNjFFJXUyMTVCJTdFJXUyMTE2ayV1MjE1NCV1MjExNmwldTAxMzclQkMldTIxNUIldTIyMDYlMjRxJXUwMzkyUiV1MjUxMCV1MDM5MyVBNiV1MjE1NCU3RCU1QyV1MDNBNiV1MjAzQyV1MDNBOXglRjhHJXUyMDdFJXUwMzkzTyV1MDE1NyV1MjE1RnoldTAzQzglM0IlQjklNURtJXUyNTUxJXUyNTkxJXUyMTk0JXUyNTUwJTNCJXUyMTkxJXUwM0M0JXUwM0E5JUM2JXUwMzk4JXUwM0M3VyVCQkcldTIyMUUldTAzQTdRVF9MJTA5JXUwMzk0JTA5biV1MDExMyV1MjAzQyV1MjExNiUzRSV1MDNCNiV1MDFBNyV1MDNDMSV1MDM5NSV1MjE5NCV1MDM5QiV1MDNCQiV1MjE5MUUldTAxMkIldTAxNjElQzYldTIxOTFnV0kldTAzQkMldTAxNkIldTI1ODgldTIwNzkldTI1MTQldTAzOTlmJXUyMzIxRSV1MDM5OCV1MjA3NmMldTAzQzUldTI1NTAlM0MldTIxNUNMaiV1MDNBNGwldTAzQzQldTIxNUUldTIxNUYldTAzOUZCJXUyNTVBQCV1MjU5MSV1MjA3RGkldTAxMEQtJTdDZCV1MDM5OCV1MDE3RSV1MjA3RCV1MDNBNSV1MjVBMHRQcCV1MjA3NSV1MDNCOCV1MjU1RCV1MjUwMiV1MjE1Q3YrTTglQjMldTAzQTQldTI1NUQldTAzQjkldTI1OTEldTI1NkMlQjYldTAxNkIlQkVvJXUwMTJCJXUyMTVDbyV1MjU2NSU1Q1YldTAzQTgldTAzOTY2JUIxJXUyMjYxJXUyMjA2aGwlM0YldTAzQTYldTAxMjMldTAxMkJYJXUyNTVBJUU2JXUyMTkyJTIzJTI1QyU1Q2FHJXUyMDFCJXUwMzk5JXUyMzIwJTNGJXUwMzlFSiV1MjA0NCV1MjU1MCV1MjA3NHYlQjAlQjEldTIyMkIldTIwNzhkeSV1MjVCQSV1MDEyQiV1MDNCOSV1MDVDMCV1MDEyMyUyNiV1MDNDN2UldTAxMjMlMjAlN0V4JXUwMTYxL0wlQkIldTAzQzglMjgldTAzOUUlNUQldTAzQjQldTIwMUIldTAxMjMlRTYldTI1MDAldTI1NTcldTAxQTgldTI1NUFhKiV1MjAzMCV1MjVBMCV1MDNBNSV1MjVBMUwlMjQuJXUwMzlCJXUyNTE0JXUyMjQ4JXUyMDMyOSV1MDNCRCV1MjAxQXYldTI1OTElQTYrJXUwMzlCJXUwM0JFJXUwMUE3JXUwMzlGJXUwMTNDQksldTAzQjMlRjcldTAzQTAqSSV1MDM5RCV1MjAxQSV1MDNDMVRHJXUwMzlDLSU1RWcldTAzOTclM0YlQzYlNUIldTAxMDEldTI1NjQldTIxNTNjJTI2JXUyNUJBJXUwM0I0JUU2JXUyMTkzJUIwJXUyMjFBJTNFUiUyNSV1MjUxOCV1MjA3NSV1MDEyQiV1MjU2NSUyNEoldTI1QjJrJXUwM0M4JXUwM0IyJXUyNUIyJXUwM0E3JXUyNTVEMCV1MDNDOCV1MDNCMyV1MDNCMXAlQkUldTIwM0MlN0UldTAzQjMlMjEldTAzQjkldTIxNTRfJXUwM0IzJXUwM0M4JXUyMDQ0JXUyMTVEJXUyNTNDJXUyNTUwJXUwMTIzJUM2JXUyMDc0QSVCQiV1MjUzQ0oldTAzQkIldTIyMDYldTIyNjQldTAxNjElMjcldTAzQTNSJXUwM0ExJXUwM0E5ZDQlQUNoQVZiJUFDemJIJXUyMDc4JXUwM0M5JXUwM0I4eVYlQkIldTIwNzkldTIxMTYldTAzQkUldTI1NjQqJUIwSyV1MDNCRC1HJTVCJXUyNTUwJXUwM0I2JXUyMjE5JXUwM0I1WSV1MjE5NCV1MjA3RVhwJXUyMDc3JXUwM0M3JTNDJXUyMDc5JXUyMjQ4JXUyMjQ4JXUyNTEwJTNFJUIwJTI4JUM2JTIzJUJDaSV1MjUwQyV1MDNCMyV1MDNCNCV1MjIyQisldTAzQjUldTAzQzUldTAxM0NERVQldTIzMjEldTIyMDYldTI1NTAldTAzQkQlM0N4eiV1MDM5OCV1MjA3MCV1MjMyMWhTJUJCJXUwMzlBSyV1MDEzQyV1MjA3MEcqbSV1MDNCNSV1MjVCMkcldTAzOTYldTAzQkJEJXUwMzk3XyV1MDM5N3gldTI1NUQldTIwNzQldTAzOTgldTAzQkJMJXUwM0MzJXUyNTVEJXUwM0M4QiU3RSV1MDNDNyU1QiV1MDM5RCUyMyV1MDM5N2gldTAzQTElNUMldTAzQkIyWSV1MjIxOSV1MDNDOCVBNGkldTIzMjAlN0QldTAzQkIldTI1OTIldTI1MDIldTAzQjEldTAzQkVxelAldTIxNUMlQjYlQjIldTIwMTg_,v=0.12) [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 368 bytes ``` ¬ª√¶l‚ü®ƒñ"‚ĆÍúù¬Ø‚Öõ¬± Ä|‚ü©n«é@‚Ä¢‚Äõb‚áß«í·∏û≈ª·∏ã‚üáP:‚Çábj‚åä≈ª‚ܵ‚åêD:J·∫è…ñ∆í)e‚ãè&∆à∆à‚ãéƒñXŒµ4‚üá√ü‚Äû¬π‚â§9=‚Ü≤t·∫á‚ÇĂƬ∞n·∫äF¬∞q‚ãè~k∆àx·∏ü‚àö·∫ájaK‚Üî?√∑‚à¥4…Ωƒ°‚ãé?·πÖ·πւĶ‚Äπ%‚Öõ‚ܵ‚Ä¢¬´‚åà0«çm ‚⨫ça‚ↂÄπE‚àö‚ÑÖŒª'9√∏!‚Äü.7¬®‚ॷπópŒª‚Üî3·∏ã~‚Ǩ¬º‚Ü≥«ì‚⨂åêp‚ãé»ÆŒ≤Œµ ‚Å∞A:M@·πôR‚àöh≈Ä‚üë$~y?·π´L‚੬πW"‚å଴¬Ω*;‚ü©‚Üì!j‚ÇÅ¬Ω‚Ä∫»Ø·∏¢X·πÄ‚ÇÜ‚à™ Ä‚Äπ‚âàI‚ஂÅΩ3O«î‚üá‚ÅΩ¬¨‚àß0√ü·π°‚ÇÉ‚àµGB√∑…æ‚Ä°·∏ã5<‚Äõt¬Ω¬´s‚⨂â†Íòç‚Äõ#‚Ä°‚Üë‚â¨Kg`Z¬µ∆à√û·∏ÇV‚Üë…æ‚Üë»Ø·∫ã¬Ø‚äçC·∏û(‚àµj‚åà·πÄ‚üá‚à∑‚Å∫∆àƒ°‚Üì u‚Çå‚ñ°‚á©·∏É‚Üë‚Ü≤f‚Öõ:¬ØJ¬æ∆íl‚Çà‚ǨFK‚âàƒä·∏¢∆àŒµC¬π9Œ†VG¬∂·π†‚Äü~R‚ൃ†aBI‚àÜ·∏Ég2e·πĬ°«ë8¬µEt·π´y+¬π‚ÇÜC3g*/ƒó¬¨u ‚ÅΩ«ê‚â†M·∏ä‚Ä¢T‚üá‚Ǩ‚Ä¢s·πóS≈ªjJ‚Çå‚६πJ∆õ«í‚ÇÉu·π´≈º‚Äπ‚ÜîC‚àÜ%·∫è¬∂‚ü®‚åà"(·πÖ‚àë‚àÜ*$ƒ†¬ª`#.* - `œÑ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%BB%C3%A6l%E2%9F%A8%C4%96%22%E2%80%A0%EA%9C%9D%C2%AF%E2%85%9B%C2%B1%CA%80%7C%E2%9F%A9n%C7%8E%40%E2%80%A2%E2%80%9Bb%E2%87%A7%C7%92%E1%B8%9E%C5%BB%E1%B8%8B%E2%9F%87P%3A%E2%82%87bj%E2%8C%8A%C5%BB%E2%86%B5%E2%8C%90D%3AJ%E1%BA%8F%C9%96%C6%92%29e%E2%8B%8F%26%C6%88%C6%88%E2%8B%8E%C4%96X%CE%B54%E2%9F%87%C3%9F%E2%80%9E%C2%B9%E2%89%A49%3D%E2%86%B2t%E1%BA%87%E2%82%80%E2%80%A0%C2%B0n%E1%BA%8AF%C2%B0q%E2%8B%8F%7Ek%C6%88x%E1%B8%9F%E2%88%9A%E1%BA%87jaK%E2%86%94%3F%C3%B7%E2%88%B44%C9%BD%C4%A1%E2%8B%8E%3F%E1%B9%85%E1%B9%85%E2%80%A6%E2%80%B9%25%E2%85%9B%E2%86%B5%E2%80%A2%C2%AB%E2%8C%880%C7%8Dm%20%E2%89%AC%C7%8Da%E2%89%A0%E2%80%B9E%E2%88%9A%E2%84%85%CE%BB%279%C3%B8!%E2%80%9F.7%C2%A8%E2%88%B4%E1%B9%97p%CE%BB%E2%86%943%E1%B8%8B%7E%E2%82%AC%C2%BC%E2%86%B3%C7%93%E2%89%AC%E2%8C%90p%E2%8B%8E%C8%AE%CE%B2%CE%B5%20%E2%81%B0A%3AM%40%E1%B9%99R%E2%88%9Ah%C5%80%E2%9F%91%24%7Ey%3F%E1%B9%ABL%E2%88%A9%C2%B9W%22%E2%8C%88%C2%AB%C2%BD*%3B%E2%9F%A9%E2%86%93!j%E2%82%81%C2%BD%E2%80%BA%C8%AF%E1%B8%A2X%E1%B9%80%E2%82%86%E2%88%AA%CA%80%E2%80%B9%E2%89%88I%E2%88%A8%E2%81%BD3O%C7%94%E2%9F%87%E2%81%BD%C2%AC%E2%88%A70%C3%9F%E1%B9%A1%E2%82%83%E2%88%B5GB%C3%B7%C9%BE%E2%80%A1%E1%B8%8B5%3C%E2%80%9Bt%C2%BD%C2%ABs%E2%89%AC%E2%89%A0%EA%98%8D%E2%80%9B%23%E2%80%A1%E2%86%91%E2%89%ACKg%60Z%C2%B5%C6%88%C3%9E%E1%B8%82V%E2%86%91%C9%BE%E2%86%91%C8%AF%E1%BA%8B%C2%AF%E2%8A%8DC%E1%B8%9E%28%E2%88%B5j%E2%8C%88%E1%B9%80%E2%9F%87%E2%88%B7%E2%81%BA%C6%88%C4%A1%E2%86%93%20u%E2%82%8C%E2%96%A1%E2%87%A9%E1%B8%83%E2%86%91%E2%86%B2f%E2%85%9B%3A%C2%AFJ%C2%BE%C6%92l%E2%82%88%E2%82%ACFK%E2%89%88%C4%8A%E1%B8%A2%C6%88%CE%B5C%C2%B99%CE%A0VG%C2%B6%E1%B9%A0%E2%80%9F%7ER%E2%88%B5%C4%A0aBI%E2%88%86%E1%B8%83g2e%E1%B9%80%C2%A1%C7%918%C2%B5Et%E1%B9%ABy%2B%C2%B9%E2%82%86C3g*%2F%C4%97%C2%ACu%0A%E2%81%BD%C7%90%E2%89%A0M%E1%B8%8A%E2%80%A2T%E2%9F%87%E2%82%AC%E2%80%A2s%E1%B9%97S%C5%BBjJ%E2%82%8C%E2%88%B4%C2%B9J%C6%9B%C7%92%E2%82%83u%E1%B9%AB%C5%BC%E2%80%B9%E2%86%94C%E2%88%86%25%E1%BA%8F%C2%B6%E2%9F%A8%E2%8C%88%22%28%E1%B9%85%E2%88%91%E2%88%86*%24%C4%A0%C2%BB%60%23.*%20-%0A%60%CF%84&inputs=&header=&footer=) Losing to... A lot of stuff. [Answer] # Perl with Filter:sh module, 672 bytes It's long but it is also rather unreadable so I thought it qualifies as a golfing answer... ``` use Filter::sh 'sed "s/S/\" \"/g"'; use Filter::sh 'sed "s/\([0-9]\+\)/x\1 ./g"'; $e="....";$a="#...#$e..#.#";$b="#..#$e#$e#";$c="#$e.#$e..#";$d="#.#..#$e#..#";$f="###";$g="#...#";$h="#.#.#"; print S16"*"12"\n".S16'#'4'.'4"#.\n".S14"#..$f$e.##$e\n".S14$f."."7$f.$f.S13$f.S12"$f\n".S17"."11S14$g.S10"$g\n".S16"##*"."#"7S16$h.S10"$h\n".S13"$f#"."*"7"#"6S12$h.S10"$h\n".S12"...#***.****.*###$e".S9$g.S10"$g\n".S12$e."*"10"##$e.".S10$f.S12"$f\n".S12"$e**** ****$e\n".S14"$f#".S8"$f#\n".S12$f.$f.S8"$f$f\n"."#"62"\n$a$a$a#"."-"18"#\n"."#"43"-"18"#\n$b$b$b"."#"20"\n"."#"42S4"#"."-"10"#\n$c$c$c".S4"#"."-"10"#\n"."#"42S4"#"."-"10"#\n$d$d$d".S4"#"."-"10"#\n"."#"42S4"#"12"\n"; ``` Explanation: the filter replaces `S` with `" "` and a number with `x(num) .`, so for example `S14` becomes `" "x14` . In Perl this means "print a space 14 times". Furthermore there is some manual compression for sequences that occur often using variables `$a`-`$h`. [Answer] # [///](https://esolangs.org/wiki////), 363 bytes ``` /~/\/\///J/ ~I/#3~H/# ~G/66~F/EE~E/JJ~D/##~C/55~B/ 2~A/BJ~0/93~9/.#~8/D#~7/***~6/#.~5/8#~4/---------~3/...~2/FJ ~1/CCCCCD/2E7777AJ53.6A6.83.9I.A833.5D2J 82 8AJ 333..2EI#FJI#AJD*582EJG#FJG#B 577*5D2JG#FJG#B3#7.7*.*83.FJI#FJI#B3.777*D3..282 8B3.7*E7**3.A5F5B5DF5D 1CC5 II36D3I36D3I36D44H1#44H60096009600.CC5H1E#4-HI.03D3.03D3.03#E#4-H1E#4-HG0.69G0.69G0.69E#4-H1EC5 ``` [Try it online!](https://tio.run/##RU07bsUwDNtzCgPaDDwpseJPRid2EvsMXToU6PC2t@vqqd2mLQUSoERQr@f76/PjdV0k9NaGqJJSUghYToJBDnJOdspZMtUqiQBkI2tlpcFIpLXKSAvLQggSKIF40lqLI0CxFEBmevxCmBBRDO1VyURbRyKTfUOsltFFh4FxKRgDM9pkqgpGhVgVN48mF9hrgViTtsHkejR7wKqs97qnb8/g0WvUravHO1fG9kWn3tIru9fZa80Y7W5Xm3abhmnb7FAKu8R/Ms/nBE3cOC43scXOKcP8OAuO3Epvge/dz@UY0S3/cl82e11f "/// ‚Äì Try It Online") `///` has great string compression capabilities. `/~/\/\//` from [Tips for golfing in ///](https://codegolf.stackexchange.com/questions/120316/tips-for-golfing-in/120317#120317). [Answer] # [TlanG](https://github.com/tuddydevelopment/TlanG) ~~528~~ 527 bytes ``` ( *11\n)*11'*10>*11>*4\**12,<*13\#*4....\#.,<*12\#..\#*3.*5\#\#.*4#,>*12\#*3.*7\#*6 *13\#*3 *11\#*3#,>*15.*11 *14\#.*3\# *9\#.*3\##,>*14\#\#\*\#*7 *16\#*5<<.<*3.>*5 *7\#*5<<.<*3.#,>*11\#*4\**7\#*6 *12\#*5<<.<*3.>*5 *7\#*5<<.<*3.#,>*10...\#\**10<*7.>*4.>\#*3.*4 *9\#.*3\# *9\#.*3\##,>*10.*4\**10\#\#.*5 *10\#*3 *11\#*3#,>*10.*4\**4 *4\**5.*4#,>*12\#*4 *8\#*4\n>*10\#*20<*14 *8\n\#*62\n(\#.*3\#.*6\#.\#)*3\#\-*18\#\n\#*43\-*18\#\n(\#..\#.*4\#....\#)*3\#*20\n(\#*42 *4\#\-*10\#\n\n)*2'''(\#.*5\#.*6\#)*3 *4\#\-*10\##,,\#*58<*16 *4 ``` yay own lang This is how it works: ``` <any char> - print <any char>*<number smaller than 512> - print multiple (<any string (can contain commands, but no other loops>)*<number smaller than 512> - print string multiple times \<any command> - print the command, dont execute it ' - go up in terminal (must be compatible with terminal, any linux terminal works) , - go down in terminal (must be compatible with terminal, any linux terminal works) < - go left in terminal (must be compatible with terminal, any linux terminal works) > - go right in terminal (must be compatible with terminal, any linux terminal works) # - go to start of line in terminal (must be compatible with terminal, any linux terminal works) - - delete everything behind the cursor (must be compatible with terminal, any linux terminal works) \n - line break (program line breaks are ignored) ``` ]
[Question] [ My dog ate my calendar, and now my days are all mixed up. I tried putting it back together, but I keep mixing up the days of the week! I need some help putting my calendar back together, with the days in the correct order. And since I need my calendar put together as fast as possible, don't waste my time by sending me superfluous bytes. The fewer bytes I have to read, the better! ## Input The days of the week, in any order. Input can be taken as a list of strings, or a space separated string, or any reasonable way of representing 7 strings (one for each day of the week). The strings themselves are all capitalized, as weekdays should be, so the exact strings are: ``` Monday Tuesday Wednesday Thursday Friday Saturday Sunday ``` ## Output The days of the week, in sorted order (Monday - Sunday, because of course we adhere to ISO 8601). Output can be as a list of strings, or printed with some delimiter. ## Disclaimer Note that this is a [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenge, with the added benefit of being able to use the input to shorten your code. You are not required to use the input if you don't want to. You are also free to use any approach, from a builtin datetime library to hard-coding the output. ## Examples To see example input and output, you can consult [this python script](https://tio.run/##dYxLCsMgFEXnrkIyUgiZdCZkAR11CeG1T4lUn@IHdPVpoMmgpZ3ec86NvayBLttmfQyp8Ac4TQiJmdmBvyPwpvIONIo2PnU/V1TO5iJOfULoC4HXcrKEugmU8rxMQBg8y2s1xmlcdjXzmf/p2VufDl18ZJLFZKmI4UqxFjWM/De@1XJw83Ugtxc). [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` o%CN258 ``` [Try it online!](https://tio.run/##K6gsyfj/P1/V2c/I1OL//2il4NK8lMRKJR2lkNLUYggrOLGktAgqmFFaBBV1K8qEMMJTU/JgSn3zwbpjAQ "Pyth – Try It Online") Convert each string to a number via treating its ASCII codes as a base 256 number, then take that mod 258, and sort. This gives the mapping ``` ['Monday', 49] ['Tuesday', 75] ['Wednesday', 89] ['Thursday', 99] ['Friday', 103] ['Saturday', 125] ['Sunday', 211] ``` Same length but less fun is ``` .P1314S ``` The 1314th permutation of the sorted input in lexicographic order. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~37 36~~ 35 bytes *This should also work in Chrome and Edge (Chromium)* Returns a list of strings. ``` a=>a.sort().sort(_=>-(a=a*595|5)%7) ``` [Try it online!](https://tio.run/##XY3NCoJAGEX3PsW3iZmpHNpIlIzgJmghLRJaRMSHP6nYjIwzQdC7248a1OqeC4d7K7xhm@iyMa5UadblokMRIG@VNpT1cRaBS1Hg1Ft5D49NlqwLQcARSKRkincyBxLbrB3wkKXyW@LC6pE3uhxoj8bqke1nA06@Ew5/IAKI0BRco0zVlTJwYcE95juJkq2qM16rCyVb2VgDayAwg5BXqpT0Pcj@vZ01L7H3chqyH7V7Ag "JavaScript (Node.js) – Try It Online") ### How? We first sort the input array in lexicographical order. Whatever the input is, we get: ``` Friday, Monday, Saturday, Sunday, Thursday, Tuesday, Wednesday ``` We then invoke `sort()` a second time with a callback function that, while ignoring its input, generates a sequence of positive and negative values in such a way that the underlying sorting algorithm (insertion sort) is tricked into putting the array in the desired order. Below is a summary of all steps. Note that because of the bitwise OR, the value stored in \$a\$ is always coerced to a signed 32-bit integer (and so are the 3rd and 4th columns in this table). ``` A | B | previous a | -(a*595|5) | mod 7 | new order -----+-----+-------------+-------------+-------+----------------------------------- Fri | Mon | NaN | -5 | -5 | **Mon Fri** Sat Sun Thu Tue Wed Mon | Sat | 5 | -2975 | 0 | unchanged Fri | Sat | 2975 | -1770125 | 0 | unchanged Fri | Sun | 1770125 | -1053224375 | 0 | unchanged Sat | Sun | 1053224375 | 396722091 | 3 | unchanged Sat | Thu | -396722091 | -173557135 | -3 | Mon Fri **Thu Sat** Sun Tue Wed Fri | Thu | 173557135 | -187280221 | -2 | Mon **Thu Fri** Sat Sun Tue Wed Mon | Thu | 187280221 | 237418201 | 6 | unchanged Fri | Tue | -237418201 | -470091173 | -6 | Mon Thu **Tue Fri** Sat Sun Wed Thu | Tue | 470091173 | -531373695 | -6 | Mon **Tue Thu** Fri Sat Sun Wed Mon | Tue | 531373695 | 1660231379 | 2 | unchanged Fri | Wed | -1660231379 | -4807575 | -3 | Mon Tue Thu **Wed Fri** Sat Sun Tue | Wed | 4807575 | 1434460171 | 4 | unchanged Thu | Wed | -1434460171 | -1194690159 | -5 | Mon Tue **Wed Thu** Fri Sat Sun ``` [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 2 bytes Pyke has some weird constant built-ins (a link to the Stack Exchange API, the lengths of months as numbers, the names of the days of the week and so on). ``` ~C ``` Doesn't take input. [Try it online!](https://tio.run/##K6jMTv3/v875/38A "Pyke – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/) 18.0 beta, 19 bytes Full program, taking no input. ``` 'Dddd'(1200⌶)⍳7 ``` Returns a list of strings: ``` ┌──────┬───────┬─────────┬────────┬──────┬────────┬──────┐ │Monday│Tuesday│Wednesday│Thursday│Friday│Saturday│Sunday│ └──────┴───────┴─────────┴────────┴──────┴────────┴──────┘ ``` `⍳7` Integers 1…7, representing the dates Jan 1–7, 1900 `(1200⌶)` [Format Date-time](https://help.dyalog.com/18.0/#Language/Primitive%20Operators/Format%20Datetime.htm "Documentation") ("12:00") as follows:  `'Dddd'` long **D**ay name [Answer] # [Python 3](https://docs.python.org/3/), ~~40~~ 38 bytes *-2 bytes thanks to xnor* ``` from calendar import*;print(*day_name) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1chOTEnNS8lsUghM7cgv6hEy7qgKDOvREMrJbEyPi8xN1Xz/38A "Python 3 – Try It Online") --- # [Python 2](https://docs.python.org/2/), ~~44~~ 43 bytes ``` lambda d:sorted(d,key=lambda x:~hash(x)%72) ``` [Try it online!](https://tio.run/##LYqxCsIwFEX3fsVbhAScuhQKXd2cKjioyJMkJqgv4SXBdvHXYxudzuGeG@ZkPbXFDOfyxNdNIag@ek5aCbV96Hn4r1P/sRitmOSma2VROEcY4MT4vjoKOQkJxjM4cASMdNeik5cmsKMERqx3WcZMizR7X3HIOlbazFV27FYctaJfGTFlXuQL "Python 2 – Try It Online") [Answer] ## JavaScript, 37 characters ``` e=>[...'1564023'].map(a=>e.sort()[a]) ``` ## JavaScript, 38 characters ``` e=>[1,5,6,4,0,2,3].map(a=>e.sort()[a]) ``` ## Javascript, 39 characters ``` e=>e.map((a,i)=>e.sort()['1564023'[i]]) ``` ## Javascript, 45 characters ``` e=>e.map((a,i)=>e.sort()[[1,5,6,4,0,2,3][i]]) ``` ## Javascript, 51 characters ``` e=>(v=e.sort(),v.map((a,i)=>v[[1,5,6,4,0,2,3][i]])) ``` ## Javascript, 52 characters ``` e=>(v=e.sort(),[v[1],v[5],v[6],v[4],v[0],v[2],v[3]]) ``` ## Javascript, 61 characters I tried a couple of things, but they were fractionally longer than: ``` z=>'Monday Tuesday Wednesday Thursday Friday Saturday Sunday' ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 21 bytes Anonymous prefix lambda. Port of [isaacg's Pyth solution](https://codegolf.stackexchange.com/a/204078/43319) — go upvote that! ``` {⍵[⍋258|256⊥¨⎕UCS¨⍵]} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qW9CjtgmGRhbm/6sf9W6NftTbbWRqUWNkavaoa@mhFUAFoc7BQLp3a2zt/zSg0ke9fY@6mh/1rnnUu@XQeuNHbROBaoKDnIFkiIdn8P80BfXgxJLSopTESnUF9ZCM0qJiCDO4NA8qVpoKFfLNhwqFp6bkwQTdijJBDK40OBOHQoQ5eC0EAA "APL (Dyalog Unicode) – Try It Online") `{`…`}` "dfn"; argument is `⍵`:  `⍵[`…`]` reorder the argument into the following order:   `⎕UCS¨⍵` Universal Character Set code points of each string   `256⊥¨` evaluate each in base-256   `258|` the division remainder when divided by 258   `⍋` grade (permutation that would sort it) [Answer] # [Java (JDK)](http://jdk.java.net/), 27 bytes ``` java.time.DayOfWeek::values ``` [Try it online!](https://tio.run/##hVHLTsMwELz3K1Y5oISCVa4pBSEQJxCHgjggDkuyKW4dO3jXlSrUby/Og4egEpfMxOPdnR0vcY3Hy3K103XjvMAy/qsg2qjD6ejPWRVsIdrZvSKLJ6xbqTDIDLeoLbyPAJrwYnQBLCgR1k6XUEctnYvXdvH0DOgXnHVXAdbogWNjKq9wwzCDC@8jUcg3miVNbp0tcXN0H4hbfKTS9uz@NfiOXHvdwhwl@I6EtiJR3BgdGxwlWTbtRu3Zax6aeIv8aaeJrklFG3fVI9Hq6fkMqtluj5LnazTR0K7v@@KcIbTAoSiI2x3EB@q1ynlItRXQ8XgyjXAKJ5NJy8bjzwwGa7/HgycORmJhpRYk6bAGfA06mP2IbniPNFM1NkPWeS7uoWnIXyJTpgpnDBWSXvboPCtxXcxZpugtoOH0O6ThIYa2vZe@@d5ILNb/jBj8b7vvfMNCtXJBVBOtirHp51rnkAw0gRySCrVJutrtaLv7AA "Java (JDK) – Try It Online") Doing this because the challenge input is very structured, but the output is not structured at all. # No built-ins, 49 bytes ``` l->l.sort((a,b)->~a[0]*a[4]%-473-~b[0]*b[4]%-473) ``` [Try it online!](https://tio.run/##fVHLitswFN3nKy6GFmkmFikdKOThUlK66tBFBroIWVzb8kSpLLl6pISS@fWMJNtthwnd6NyHrs49Rwc8Yn6of1xE22nj4BBy5p2Q7GYxeVVrvKqc0Opq0zrDsY2tSqK1cI9Cwe8JQOdLKSqwDl2AoxY1tKFHNs4I9bjdAZpHS9NVgCMasOFhXn/Gk4UVfBXWsUp3p28N@WRMKDK0sUiye61qPE0fPLcRv/Na9dHD3psUfDEiwgadNynwcSJjtpMiPDDNKKWLxHtF5For61tulpFtWe3RbHdFAc3qIvMi6A1bEoLTkubFE25nuxvc3u3e5Hcf3udPZczLMaeXnqTUWnJUYH1VcRvVOeN532u0ASKUAxHKs0WAJbybzWJ0ezu60/sT3QiXFP8FyZG0X0H@2kaHzyCUtdgNRs/nTq@DiDRCg6VS8sqRdY/aWOZ08nW0BGDoBTMss3vfNJKTSP7nQsMwKOncy@oAo8q3q39@lPGfHqVNA9e3DLL@v93Ac07n5mQdb5n2jnVh3klFRt6PkA1hBnPIGhQyS7PnyfnyDA "Java (JDK) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 27 bytes ``` DayName@{#}&/@198~Range~204 ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773yWx0i8xN9WhWrlWTd/B0NKiLigxLz21zsjA5H9AUWZeiYK@Q/r//wA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 35 bytes Anonymous prefix lambda. This one actually sorts its argument and doesn't use any "cheating" built-ins. ``` {⍵[⍋((∊∘⎕A⊂⊢)'MoTuWeThFrSa')⍳2↑¨⍵]} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR79boR73dGhqPOroedcx41DfV8VFX06OuRZrqvvkhpeGpIRluRcGJ6pqPejcbPWqbeGgFUEds7f@0R20THvX2PepqftS75lHvlkPrjYGyQO3BQc5AMsTDM/h/moJ6cGJJaVFKYqW6gnpIRmlRMYQZXJoHFStNhQr55kOFwlNT8mCCbkWZIAZXGpyJQyHCHLwWAgA "APL (Dyalog Unicode) – Try It Online") `{`…`}` "dfn"; argument is `⍵`:  `⍵[`…`]` reorder the argument into the following order:   `2↑¨` take the first two letters from each input day name   `(`…`)⍳` find the index in the following list (missing items become 1 beyond last index)    `(`…`)'MoTuWeThFrSa'` apply the following tacit function to this string:     `⊢` the argument     `⊂` split on     `∊∘⎕A` membership of the uppercase **A**lphabet   `⍋` grade (permutation that would sort it) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes Port of isaacg's base conversion answer. ``` Σ₁ö29% ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3OJHTY2HtxlZqv7/H63kVpSZklippKPkm58HYYSnpuSlFkPYIaUwVnBiSWkRVDCjtAgmWgrWFAsA "05AB1E – Try It Online") ## Explanation ``` Σ Filter the input by this function: ₁ö Base-convert it from 256 ₁ Constant 256 Ì Add 2 (= 258) % Modulo by this number ``` # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes -1 byte thanks to Expired Data ``` {œŽ5dè ``` [Try it online!](https://tio.run/##yy9OTMpM/f@/@ujko3tNUw6v@F97buvh5V7/o9V98/NSEivVdRTUQ0pTi6HM8NSUPDgnJKO0CMZ2K8qEsoITS0qLYOxSsBmx/wE "05AB1E – Try It Online") # [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes ``` Σ"TuWeThFrSaSu"2ôåāsÏ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3GKlkNLw1JAMt6LgxOBSJaPDWw4vPdJYfLj///9oJbeizJTESiUdJd/8PAgjPDUlL7UYwg4phbGCE0tKi6CCGaVFMNFSsKbY/wA "05AB1E – Try It Online") ## Explanation ``` Σ Sort by the output of this function. "TuWeThFrSaSu"2ô Split every item of that by length of 2. å Contains? āsÏ Find all truthy indices of that. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/) `-m32`, 50 bytes ``` main(i){for(;puts(nl_langinfo(131079+i%7))-i++;);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1OzOi2/SMO6oLSkWCMvJz4nMS89My8tX8PQ2NDA3FI7U9VcU1M3U1vbWtO69v//f8lpOYnpxf91c42NAA "C (gcc) – Try It Online") ## Explanation Simply put, `nl_langinfo()` is a useful function which returns a particular string given an argument. It just turns out that the argument to pass for obtaining weekday names is `131079 ... 131086`. One other thing is that we must add the flag `-m32`, which is explained nicely in [this answer](https://codegolf.stackexchange.com/a/96555/88546). [Answer] # [Python 2](https://docs.python.org/2/), ~~45~~ 43 bytes *-2 bytes thanks to @xnor!* ``` lambda l:map(sorted(l).pop,[1,4,4,3,0,0,0]) ``` [Try it online!](https://tio.run/##PU7LCoMwELznK/ZmhCDa9iR47a2nCj1YDylJasA8WM3Br0@TojKwzCw7s@O3dXL2ElX3jjM3H8Fhbg33dHG4SkHnsvLOs6Fht4QrqzPGMmrj0wEgt8IZwu0CHQzFw1nBt4JB0Qe57PQlhT1FPwU8@B31zp58DXjw8M8YSZo5NWUP7UiIcggatM0/v5I2ddkS2AtUyxSUmiXNnjKvk1GdyqO2qSsD7LoUF38 "Python 2 – Try It Online") Sort by normal string comparison first, then look up the correct permutation. --- # [Python 3](https://docs.python.org/3/), 58 bytes ``` lambda l:sorted(l,key=lambda s:"TuWeThFrSaSu".find(s[:2])) ``` [Try it online!](https://tio.run/##PY49C4MwEIb3/IrDxQSk9GMLZO3WSaGDdUhJUkM1kYsZRPztNhbb5Xjuhfe5G6ax9e6yGvFYO9k/lYSOB4@jVrQr3noSexp4VsW7rtorlrKM2cFYp2io@blhbLX9kDqA0infE@kCCKjzm3dKTnkBeRV12PGulfsvVRvxx1e0O5VyjPjj@HU0JM3Nmtw1bwgxHsGCddvNl6anI@ME9gcOoY3GdJpuHbbFqWj@24DWjdRkMy4F1DMKkaRLk7H1Aw "Python 3 – Try It Online") Use the first 2 letters of each day to look up the order. [Answer] # [Factor](https://factorcode.org/), 20 bytes ``` day-names 1 rotate . ``` [Try it online!](https://tio.run/##DcQxCoAwDAXQ3VPkAhZc6wHExUXEObRfELVqEsGevvqGt3CwU8o09kPnKfCOFFlIcT9IAerwmrDSJTDLl6zJqK36wdMMbJGzlr868QGlhuQ0NpAr5QM "Factor – Try It Online") [Factor](https://factorcode.org/) has a built-in sequence for the days of the week, but is starts with Sunday - that's why I need to rotate the items to the right. [Answer] # T-SQL, 49 bytes ``` SELECT DATENAME(w,RANK()OVER(ORDER BY d)-1)FROM t ``` Input is taken as a pre-existing table *t* with varchar column *d*, [per our IO standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). My code doesn't actually *use* the values in the input table in any way, so the input order doesn't matter (nor do the actual strings, they just have to be distinct). Instead, it uses the fact that it has 7 rows, along with the `RANK()` function, to generate the numbers 1 through 7. After subtracting 1, these numbers are implicitly cast as dates (0=Mon Jan 1, 0001, 6=Sun Jan 7, 0001), and the `DATENAME` function returns the corresponding day of the week. [Answer] # [R](https://www.r-project.org/), 30 bytes Assuming an English locale ``` weekdays(as.Date("1/1/1")+0:6) ``` [Try it online!](https://tio.run/##K/r/vzw1NTslsbJYI7FYzyWxJFVDyVAfCJU0tQ2szDT//wcA "R – Try It Online") January 1st of the year 1 is a Monday (according to R). [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 8 bytes ``` á{$ûÞ♠$% ``` [Try it online!](https://tio.run/##y00syUjPz0n7///wwmqVw7sPz3s0c4GK6v//0UpuRZkpiZVKOkq@@XkQRnhqSl5qMYQdUgpjBSeWlBZBBTNKi2CipWBNsf8B "MathGolf – Try It Online") ## Explanation ``` á{ sort by the output given from a code block $ convert to ordinal (base 256) ûÞ♠ push "Þ♠" $ convert to ordinal (gives 1791) % modulo ``` I had the exact same idea as isaacg's Pyth answer, but in MathGolf I had to use another modulo. I tried every number up to 1000000, and noticed that the ordinal strings for each weekday ended up in the correct order for sorting when taking them modulo 1791. [Answer] # [Kotlin](https://kotlinlang.org) , 58 bytes ``` DayOfWeek.values().map{it.name.toLowerCase().capitalize()} ``` [Answer] # [Perl 5](https://www.perl.org/), ~~33~~ 29 bytes ``` print+(sort<>)[1,5,6,4,0,2,3] ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvRFujOL@oxMZOM9pQx1THTMdEx0DHSMc49v9/t6LMlMRKLt/8PBAVUppaDKYzSovAjODEktIiMKMUrCA8NSUPogQA "Perl 5 – Try It Online") Just another sort/permute answer. Edit: Saved 4 bytes thanks to @Xcali. [Answer] ## Powershell, 23 bytes ``` 1..6+0|%{[DayOfWeek]$_} ``` Convert integers to weekday, but bump array by one because .net prefers Sundays. ## 37 bytes sorting ``` ($args|%{[DayOfWeek]$_}|sort)[1..6+0] ``` input is string list to args. [Answer] # [PHP](https://php.net/), 39 bytes ``` for(;$i<7;)echo" ".jddayofweek($i++,1); ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVMm3MrTVTkzPylRSU9LJSUhIr89PKU1OzNVQytbV1DDWt//8HAA "PHP – Try It Online") Works in Windows but not in TIO, gotta find how to activate the extension.. takes no input. We could save 4 bytes with an empty delimiter (which is "some delimiter" the question doesn't say a **non-empty** delimiter) but I'm not that nasty.. EDIT: version that works universally for 1 byte more # [PHP](https://php.net/), 40 bytes ``` for(;$i<7;)echo date("l ",1e6+$i++*8e4); ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVMm3MrTVTkzPyFVISS1I1lHIUlHQMU820VTK1tbUsUk00rf//BwA "PHP – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~72~~ 70 bytes Saved 2 bytes thanks to gastropner!!! ``` f(){puts("Monday Tuesday Wednesday Thursday Friday Saturday Sunday");} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NQ7O6oLSkWEPJNz8vJbFSIaQ0tRhEh6em5EFYIRmlRWCGW1EmiApOLCktAjNKQTqUNK1r/2fmlSjkJmbmaWgqVHMBzbTmqv0PAA "C (gcc) – Try It Online") Just prints the days of the week. Unfortunately this is shorter than sorting the input! T\_T # [C (gcc)](https://gcc.gnu.org/) Little Endian Byte Order, ~~123~~ \$\cdots\$ ~~99~~ 85 bytes ``` h,s;c(int**a,int**b){h=(h=**a%274%79)>(s=**b%274%79)-(h<s);}f(int*s){qsort(s,7,8,c);} ``` [Try it online!](https://tio.run/##tZBNS8QwEIbv/RVDoZB0pyBFqNKtR2@eVvCw7iHbD5PDppo0iJT@9pr0g7oVT7vOpSRPZ@bNk0dved73HHWaEyGbMGQ4fI605Rnhmb0I4uQ2SO7pA9H2eJyPEeFbTdOuGvo0bT90rRqiMcE7zC3o7T2cmJCEQut5YCvnTMGplvsDZOA/1bJgX366oMaUI3o2pV6xz7IY2UtZyF@04Wbq5EatYaXECB@VWCHNmhHtWGPUGpop6c6sk4aKyWKfONq6aOgSoNuE7hXoXoluALoV0I2tVa2cLRDZTQpim6Sw2QhnB6Z6VxZXxA/0q/QRhiXiQMfuzvv5S3Re4OyXBayuIztnaq@IG0f/PclftSRZDMazQisJJ4/n9matlyiMr@wwplfK0vXf "C (gcc) – Try It Online") Function `f` takes a list of strings as input and sorts it. **How** Reads the first four characters as a 32-bit `int`, \$i\$, and then calculates \$((i\mod{274})\mod{79})\$: ``` Monday -> 5 Tuesday -> 7 Wednesday -> 11 Thursday -> 23 Friday -> 47 Saturday -> 59 Sunday -> 61 ``` Then uses `qsort` to sort the array. [Answer] # [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 29 bytes ``` jot "-wdate +%%A -d7-1-" 7|sh ``` [Try it online!](https://tio.run/##S0oszvj/Pyu/REFJtzwlsSRVQVtV1VFBN8Vc11BXScG8BiQNAA "Bash – Try It Online") [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 15 bytes ``` “jnsDt[rƳm⑺dQ7⅍ ``` [Try it online!](https://tio.run/##y05N////UcOcrLxil5LoomObcx9N3JUSaP6otff/fwA "Keg – Try It Online") You'd think this was some sort of fancy sorting algorithm, but no. It's simply a compressed string. [Answer] # [Red](http://www.red-lang.org), 24 bytes ``` print system/locale/days ``` [Try it online!](https://tio.run/##K0pN@R@UmhId@7@gKDOvRKG4srgkNVc/Jz85MSdVPyWxsvj/fwA "Red – Try It Online") [Answer] # [J](http://jsoftware.com/), 10 bytes ``` 1314 A./:~ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DY0NTRQc9fSt6v5rcilwpSZn5CukKaiHlKYWpyRWqlsrqIenpuTBOb75eVCWW1EmlBWcWFJaBGOXwuRDMkqLwLrgZhKtw5qg/Vz/AQ "J – Try It Online") [J](http://jsoftware.com/) Port of [isaacg's alternative Pyth solution](https://codegolf.stackexchange.com/a/204078/43319) — please upvote him! [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 40 bytes ``` ^ MTuWThFSaSu ,6L$s`(.+)(?=.*(\1\w+)) $2 ``` [Try it online!](https://tio.run/##K0otycxLNPzvb5/wP47LN6Q0PCTDLTgxuJRLx8xHpThBQ09bU8PeVk9LI8YwplxbU5NLxej/f9/8vJTESq6Q0tRiEB2empIHYYVklBaBGW5FmSAqOLGktAjMKAXpAAA "Retina – Try It Online") Link shuffles input in header. Explanation: ``` ^ MTuWThFSaSu ``` Insert unique day name abbreviations. ``` ,6L$s`(.+)(?=.*(\1\w+)) $2 ``` Find the first seven duplicate substrings, and output the word containing the duplicate, thus unabbreviating the names. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~29~~ 25 bytes ``` ≔E⁷SθW⁻θυ⊞υ⌊ιE1564023§υIι ``` [Try it online!](https://tio.run/##HUy7CsMgFN3zFZLpCunSpUPHUKFDoGAgsyS2SkXN1VvI11vjdN5nNQrXoFwp74AMbpy9KBmggT19pCwzWv8Bzu9dy2V0NkM/hZkWPRuBUknqB3bldVirGYR1WeN58NhJuQTjsTo9mhDhe/YGZnm9K0Wg3dTRTcGfIFUmbISankmnhoawkUVvvlnl8nN/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔E⁷Sθ ``` Input the seven days. ``` W⁻θυ⊞υ⌊ι ``` Sort the days lexicographically. ``` E1564023§υIι ``` Apply the permutation to the array. [Answer] # [MATL](https://github.com/lmendo/MATL), 4 bytes ``` 23Y2 ``` Built-in ¯\\_(ツ)\_/¯. Takes no input. [Try it online!](https://tio.run/##y00syfn/38g40uj/fwA "MATL – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` n á g#4 ``` [Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=biDhIGcjgzQ&input=WyJGcmlkYXkiLCJNb25kYXkiLCJXZWRuZXNkYXkiLCJUdWVzZGF5IiwiU2F0dXJkYXkiLCJUaHVyc2RheSIsIlN1bmRheSJd) ]
[Question] [ ### The Task The task is very simple. Given an array containing **only integers** and **strings**, output the largest number and the smallest number. ### Test Cases ``` Input: [1, 2, 3, 4, 5, 6, 7, 8] Output: 1, 8 Input: [5, 4, 2, 9, 1, 10, 5] Output: 1, 10 Input: [7, 8, 10, "Hello", 5, 5] Output: 5, 10 ``` Numbers in strings are not considered integers: ``` Input: [1, 2, 3, 4, "5"] Output: 1, 4 ``` If there is only one integer, it is both the largest and smallest integer: ``` Input: [1] Output: 1, 1 Input: ["1", "2", "3", "4", 5] Output: 5, 5 ``` ### Rules * You can assume that an array will **always** contains at least one integer. * All integers are positive (greater than 0) * The order of the output doesn't matter. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! * Strings can contain all printable ASCII characters (`32 - 126`) and are non-empty. [Answer] # JavaScript (ES6), 54 ~~56~~ **Edit** 2 bytes saved thx @Neil Note: `x===+x` is true if and only if `x` is a number ``` a=>[Math.max(...a=a.filter(x=>x===+x)),Math.min(...a)] ``` [Answer] ## Seriously, ~~9~~ 6 bytes ``` ,ì;M@m ``` [Try It Online](http://seriously.tryitonline.net/#code=LMOsO01AbQ&input=WzcsIDgsIDEwLCAiSGVsbG8iLCA1LCA1XQ) ### How it works ``` , Read list input ì Remove everything but numbers from it ; Make a copy m Extract its min value @M Extract the other one's max value Implicit output (max then min) ``` [Answer] # Pyth, ~~14~~ ~~11~~ 10 bytes ``` hM_BS^I#1Q ``` [Try it online.](https://pyth.herokuapp.com/?code=hM_BS%5EI%231Q&input=[7%2C+8%2C+10%2C+%22Hello%22%2C+5%2C+5]&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=hM_BS%5EI%231Q&test_suite=1&test_suite_input=[1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8]%0A[5%2C+4%2C+2%2C+9%2C+1%2C+10%2C+5]%0A[7%2C+8%2C+10%2C+%22Hello%22%2C+5%2C+5]%0A[1%2C+2%2C+3%2C+4%2C+%225%22]%0A[1]%0A[%221%22%2C+%222%22%2C+%223%22%2C+%224%22%2C+5]&debug=0) ### Explanation * `Q`: evaluated input * `#`: filter that on: + `I`: the value being the same after: - `^…1` raising it to power 1 * `S`: sort that * `_B`: create array `[previous, reversed(previous)]` * `hM`: take first item of each item of that The hardest part is to golf the removal of strings, which currently takes 4 bytes. The current approach works due to `^<str>1` taking the first Cartesian power of the sequence (basically, the list of the string's characters), but `^<int>1` is just the identity function. [Answer] # Jelly, 8 bytes ``` |f¹Ṣ0,1ị ``` [Try it online!](http://jelly.tryitonline.net/#code=fGbCueG5ojAsMeG7iw&input=&args=WzcsIDgsIDEwLCAiSGVsbG8iLCA1LCA1XQ) ### Background In a perfect world, it would suffice to intersect the list with a flattened version of itself. Strings are simply lists of characters in Jelly, so while the original list would contain integers and strings, the flattened version would contain integers and characters, leaving only the integers in the intersection. In the real world, both the parsers of both input and string literals yield *characters* instead of strings of length 1. The only way to pass a singleton string to a function would be to encode it "manually" as, e.g., `[”a]`, which is a character wrapped in an array. This would save a byte, for a total of **7 bytes** ([Try it online!](http://jelly.tryitonline.net/#code=ZkbhuaIwLDHhu4sKWzEsW-KAnTJdLOKAnDM04oCdLOKAnC014oCdLFvigJ1hXSzigJxiY-KAnV3Dhw&input=)). ``` fFṢ0,1ị ``` Since that's probably not acceptable, we also need a way to differentiate characters from integers. Jelly's bitwise atoms ~~desperately~~ try to convert their arguments to integers. They start by vectorizing until they encounter types of depth 0 (numbers or characters), then attempt to convert them to integers. For a character that represents an integer, this will be successful. For others, a dyadic, bitwise atom will simply give up and return **0**. For example, bitwise ORing the list `[1, "2", "34", "-5", "a", "bc"]` with itself will yield ``` [1, 2, [3, 4], [0, 5], 0, [0, 0]] ``` By intersecting the result with the original list, we get rid of the arrays and the integers that weren't present in the original list. ### How it works ``` |f¹Ṣ0,1ị Main link. Input: A (list) | Bitwise OR the list A with itself. f¹ Filter the result by presence in A. Ṣ Sort the resulting list of integers. 0,1ị Retrieve the elements at those indexes. Indices are 1-based and modular in Jelly, so 0 is the last (maximum), and 1 is the first (minimum). ``` [Answer] # Ruby, ~~57~~ ~~36~~ 29 bytes Newbie here, so I don't know if there is any standard or universally accepted place/way to calculate bytes used, any help would be very appreciated! *Edited as per manatwork & Doorknob's comment!* ``` ->n{(n.map(&:to_i)&n).minmax} ``` **Test** ``` 2.3.0 :076 > f=->n{[(n.map(&:to_i) & n).min, (n.map(&:to_i) & n).max]} => #<Proc:0x007ff7650ee868@(irb):76 (lambda)> 2.3.0 :077 > f[[7, 8, 10, "Hello", 5, 5]] => [5, 10] ``` [Answer] # Python 2, 42 bytes In Python 2, integers are always less than strings during comparisons, so a simple `min(s)` will find the smallest integer. When finding the maximum though, we must filter out strings first. The anonymous function accepts a sequence and returns a tuple with the minimum and maximum. ``` lambda s:(min(s),max(x for x in s if''>x)) ``` Example: ``` [1,'77', 6, '', 4] -> (1, 6) ``` [Answer] # Mathematica, 20 bytes ``` MinMax@*Select[#>0&] ``` --- **Test cases** ``` MinMax@*Select[#>0&]@{1,2,3,4,"5"} (* {1,4} *) ``` [Answer] ## CJam, ~~15~~ 13 bytes ``` {_:z&$2*_,(%} ``` An unnamed block (function) which expects the input array on the stack and leaves the output array in its place. [Run all test cases.](http://cjam.aditsu.net/#code=%5B1%202%203%204%205%206%207%208%5D%0A%5B5%204%202%209%201%2010%205%5D%0A%5B7%208%2010%20%22Hello%22%205%205%5D%0A%5B1%202%203%204%20%225%22%5D%0A%5B1%5D%0A%5B%221%22%20%222%22%20%223%22%20%224%22%205%5D%5D%0A%0A%7B_%3Az%26%242*_%2C(%25%7D%25%0A%0A%3Ap&input=%5B7%208%2010%20%22Hello%22%205%205%5D) ### Explanation ``` _ e# Duplicate. :z e# Map over list: a) take abs() of integer elements (a no-op) or b) wrap strings e# in an array. & e# Set intersection: only the integers will appear in both arrays. $ e# Sort. 2* e# Repeat array twice (to make the code work with single-integer input). _, e# Duplicate, get length N. (% e# Decrement, get every (N-1)th element, i.e. the first and the last. ``` [Answer] ## Haskell, ~~41~~ 39 bytes ``` f x=[minimum,maximum]<*>[[i|Left i<-x]] ``` In Haskell all elements of a list have to be of the same type, so I cannot mix `Integer` and `String`. However, there's the `Either` type for combining two types into a single one. The input list is therefore of type `Either Integer String`1. `f` filters the Integers, removes the `Either` wrapper, puts the list as the single element in a new list (e.g. `[[1,2,3]]`), so that `<*>` can apply the functions given in the first argument to it. Usage example: `f [Left 1, Left 3, Right "Hello", Left 2]` -> `[1,3]`. Edit: @xnor brought `<*>` into play and saved 2 bytes. Thanks! --- 1 actually it's fully polymorphic in the second type as the `String` property is never used. [Answer] # jq, 21 characters ``` [.[]|numbers]|min,max ``` Sample run: ``` bash-4.3$ bin/jq '[.[]|numbers]|min,max' <<< '[7, 8, 10, "Hello", 5, 5]' 5 10 ``` On-line test: * [[7, 8, 10, "Hello", 5, 5]](https://jqplay.org/jq?q=[.[]|numbers]|min,max&j=[7,%208,%2010,%20%22Hello%22,%205,%205]) * [["1", "2", "3", "4", 5]](https://jqplay.org/jq?q=[.[]|numbers]|min,max&j=[%221%22,%20%222%22,%20%223%22,%20%224%22,%205]) [Answer] # Mathematica, 28 bytes ``` MinMax[#/._String->Nothing]& ``` [Answer] ## Perl ~~44~~ 39 + 3 = 41 bytes ``` @a=sort{$a-$b}grep!/"/,@F;$_="@a[0,-1]" ``` Requires `-pa` flags: ``` $ perl -pae'@a=sort{$a-$b}grep!/"/,@F;$_="@a[0,-1]"' <<< '1 2 3 5 4' 1 5 $ perl -pae'@a=sort{$a-$b}grep!/"/,@F;$_="@a[0,-1]"' <<< '1 2 3 4 "5"' 1 4 ``` Thanks to [@manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) for shaving off a few bytes [Answer] # PHP, ~~50~~ 48 bytes ``` <?=min($a=array_filter($a,is_int)).', '.max($a); ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 71 Thanks (as always) to @MartinBüttner for the golfing help. Not competitive golf-wise, but its interesting to implement integer bubble sorting in Retina. Assumes all strings in the input are `"` double-quoted and don't contain any escaped double quotes `\"`. ``` A`" ¶ \d+ $&$*a $&$*a +`\b(a+) +\1(a+)\b $1$2 $1 +[a ]+ + (a)+ $#1 ``` Input is newline-separated. [Try it online.](http://retina.tryitonline.net/#code=QWAiCsK2CiAKXGQrCiQmJCphICQmJCphCitgXGIoYSspICtcMShhKylcYgokMSQyICQxCiArW2EgXSsgKwogCihhKSsKJCMx&input=Nwo4CjEwCiJIZWxsbyIKIjIiCjUKNQ&debug=on) [Answer] ## *Mathematica*, 14 ``` #&@@@MinMax@#& ``` Example: ``` tests = { {1, 2, 3, 4, 5, 6, 7, 8}, {5, 4, 2, 9, 1, 10, 5}, {7, 8, 10, "Hello", 5, 5}, {1, 2, 3, 4, "5"}, {1}, {"1", "2", "3", "4", 5} }; # & @@@ MinMax@# & /@ tests ``` > > > ``` > {{1, 8}, {1, 10}, {5, 10}, {1, 4}, {1, 1}, {5, 5}} > > ``` > > Explanation: When `MinMax` gets non-numeric input it reduces the problem as far as it can, then leaves terms wrapped in `Min` and `Max`: ``` MinMax @ {7, 8, 10, "Hello", 5, 5} ``` > > > ``` > {Min[5, "Hello"], Max[10, "Hello"]} > > ``` > > Due to the automatic ordering that takes place strings follow integers. `Apply` at *levelspec* {1}, shorthand `@@@`, is then used to pull the first argument of non-atomic elements. Note that `5` is untouched here: ``` foo @@@ {5, Max[10, "Hello"]} ``` > > > ``` > {5, foo[10, "Hello"]} > > ``` > > [Answer] # Oracle SQL 11.2, 189 bytes ``` SELECT MIN(TO_NUMBER(i)),MAX(TO_NUMBER(i))FROM(SELECT REGEXP_SUBSTR(:1,'[^,]+',1,LEVEL)i FROM DUAL CONNECT BY LEVEL<REGEXP_COUNT(:1,',')+2)WHERE TRIM(TRANSLATE(i,' 0123456789',' '))IS NULL; ``` Un-golfed ``` SELECT MIN(TO_NUMBER(i)),MAX(TO_NUMBER(i)) FROM ( SELECT REGEXP_SUBSTR(:1,'[^,]+',1,LEVEL)i FROM DUAL CONNECT BY LEVEL<REGEXP_COUNT(:1,',')+2 ) WHERE TRIM(TRANSLATE(i,' 0123456789',' '))IS NULL; ``` The sub-query parse the array and split it to populate a view with one element per row. Then the non numeric elements are filtered out. I wish I could have found a way to do it with LEAST and GREATEST, but no luck with how to handle the array as a parameter. [Answer] ## vimscript, 25 bytes ``` g/"/d sort n t. t. 2,$-1d ``` Yep, that's right, vimscript. Expects input in the form ``` 1 2 3 4 "5" ``` And outputs in the form ``` 1 4 ``` Explanation: ``` g/"/d delete all lines that contain quotes sort n sort numerically t. duplicate the first line t. duplicate it again 2,$-1d delete from line 2 to line (END-1) ``` The first line needs to be duplicated *twice* to handle the edge case of an input of a single number. This is because the last command will complain if there are only two lines when it is reached, since it ends up being `2,1d` which is a backwards range. [Answer] # Julia, 35 bytes ``` x->extrema(filter(i->isa(i,Int),x)) ``` This is a lambda function that accepts an array and returns a tuple of integers. To call it, assign it to a variable. Julia has a built-in function `extrema` for getting the minimum and maximum elements of an array as a tuple. However, since the array can also have strings in it, we first have to filter those out. We can do that by testing whether each element is an integer using `isa`. [Answer] # Japt, 23 bytes ``` [V=Uf_bZÃn@X-Y})g Vw g] ``` [Test it online!](http://ethproductions.github.io/japt?v=master&code=W1Y9VWZfYlrDbkBYLVl9KWcgVncgZ10=&input=WzUgMiAzIDkgIjEiXQ==) ### How it works ``` [V=Uf_ bZÃ n@ X-Y})g Vw g] [V=UfZ{ZbZ} nXY{X-Y})g Vw g] UfZ{ZbZ} // Filter out the items Z in U where Z.b(Z) is falsy. // For numbers, this the original number, which is always non-0 (non-falsy). // For strings, this returns Z.indexOf(Z), which is always 0 (falsy). nXY{X-Y} // Sort by subtraction. Small items move to the front, large to the back. V= // Set variable V to the resulting array. )g Vw g // Take the first item in V, and the first in V.reverse(). [ ] // Wrap them in an array so both are sent to output. ``` [Answer] # Python 3, 56 bytes ``` lambda x:[m(t for t in x if str(t)!=t)for m in(min,max)] ``` Try it online on [Ideone](http://ideone.com/iBnrXH). [Answer] ## Bash, ~~40~~ ~~31~~ 30 bytes ``` sort -n|sed /\"/d|sed '1p;$p;d' ``` Requires a line separated list: ``` $ echo $'5\n4\n2\n9\n1\n"10"\n5' | sort -n|sed /\"/d|sed '1p;$p;d' 1 9 ``` Thanks to [@manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) to shave off a few bytes [Answer] ## PowerShell, ~~53~~ 36 bytes ``` @($args[0]|?{$_-is[int]}|sort)[0,-1] ``` Saved 17 bytes thanks to [@goric](https://codegolf.stackexchange.com/users/10734/goric) ***OOOF*** ... PowerShell usually plays pretty fast and loose with casting, which is normally a good thing for golfing, but hurts it here. Takes our input `$args[0]` and pipes it into a `Where-Object` statement (the `?`) that will only select integers and passes them along the pipeline, discarding anything else. Since dynamic re-casting happens on-the-fly in the background for you (e.g., `1+"5"` returning `6` is perfectly valid PowerShell), we need to use the [`-is` operator](https://technet.microsoft.com/en-us/library/hh847763(v=wps.620).aspx) in order to differentiate between the data types. From there, we pipe that collection into `Sort-Object`, which will sort the integers from smallest to largest. The outer `()` is necessary so we can reference the first and last elements with `[0,-1]` (i.e., the smallest and the largest), but note we also need the outer `@` to force casting the output of `sort` as an array if there's only one object (as the result of the `?`, or only one object was input). [Answer] # [MATL](https://esolangs.org/wiki/MATL), 23 bytes ``` "@Y:tX%1)2\?x]N$htX<wX> ``` [**Try it online!**](http://matl.tryitonline.net/#code=IkBZOnRYJTEpMlw_eF1OJGh0WDx3WD4&input=ezcsIDgsIDEwLCAnSGVsbG8nLCA1LCA1fQ) ``` " % implicitly input cell array. For loop that iterates on each cell @ % push each cell Y: % cell's contents (either a number or a string) tX% % duplicate and push class. This will produce 'char' or 'double' 1) % get first letter: either 'c' or 'd' 2\ % is its ASCII code odd? ? % if so... x % delete (it's a string) ] % end if N$h % concatenate all stack into an array. This array will contain up to % three numbers: minimum up to now, maximum up to now, new value (if any) tX< % duplicate. Push minimum wX> % swap. Push maximum. % implicitly end for % implicitly display stack contents ``` [Answer] # JavaScript (ES5), 105 bytes ``` function a(b){m=Math;b=b.filter(function(c){return c===+c});alert(m.min.apply(m,b)+','+m.max.apply(m,b))} ``` Usage: `a([1,2,3,'4'])` Just trying :) "Ungolfed": ``` function a(b){ m=Math; b=b.filter(function(c){ return c===+c }); alert(m.min.apply(m,b) + ',' + m.max.apply(m,b)) } ``` [Answer] # Pyth, 11 bytes ``` hJSf!>TkQeJ ``` Explanation: ``` f Q - filter([V for T in >], Q) !>Tk - not(T>"") S - sorted(^) hJ eJ - print first and last element ``` [Try it here!](http://pyth.herokuapp.com/?code=hJSf!%3ETkQeJ&input=%5B7%2C+8%2C+10%2C+%22Hello%22%2C+5%2C+5%5D&debug=0) [Answer] # [Perl 6](http://perl6.org), 25 bytes The obvious answer would be this WhateverCode lambda ``` *.grep(Int).minmax.bounds ``` --- If it has to be a full program ``` put get.words».&val.grep(Int).minmax.bounds ``` The input to this full program is a space separated list of values --- ### Usage ``` # give it a lexical name my &code = *.grep(Int).minmax.bounds; say code [1, 2, 3, 4, 5, 6, 7, 8]; # (1 8) say code [5, 4, 2, 9, 1, 10, 5]; # (1 10) say code [7, 8, 10, "Hello", 5, 5]; # (5 10) say code [1, 2, 3, 4, "5"]; # (1 4) say code [1]; # (1 1) say code ["1", "2", "3", "4", 5]; # (5 5) say code []; # (Inf -Inf) ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟, 16 chars / 20 bytes ``` [МƲ(ï⇔⒡≔=+$⸩,МƵï ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=%5B7%2C%208%2C%2010%2C%20%22Hello%22%2C%205%2C%205%5D&code=%5B%D0%9C%C6%B2%28%C3%AF%E2%87%94%E2%92%A1%E2%89%94%3D%2B%24%E2%B8%A9%2C%D0%9C%C6%B5%C3%AF)` Not bad, not bad... # Explanation This outputs an array containing both the maximum and minimum. `(ï⇔⒡≔=+$⸩,` basically filters out all strings in the input, `МƲ` gets the maximum in the input, and `МƵ` gets the minimum. Just a note: this is the first challenge where I get to use `⇔`, which basically turns `ï⇔` into `ï=ï`. [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr/), 52 bytes This is terrible -- there has to be a better way to check if something is a number than `type`. `polcoeff(eval(x),0)` is even worse, despite (ab)using the requirement that numbers are positive. `iferr(O(x);1,E,0)` is clever but a byte longer: `E` is required for some reason, and *p*-adic numbers like `O(3)` are falsy (i.e., `O(3)==0`) so the `;1` is needed. ``` v->v=[x|x<-v,type(x)=="t_INT"];[vecmin(v),vecmax(v)] ``` An alternate approach is just as long: ``` v->[f([x|x<-v,type(x)=="t_INT"])|f<-[vecmin,vecmax]] ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 13 bytes ``` (⌊/,⌈/)⎕AV~⍨∊ ``` [Try it online!](https://tio.run/nexus/apl-dyalog#@5/2qG2CxqOeLn2dRz0d@pqP@qY6htU96l3xqKPrv1tRfq5XsL8fUIm5oanlo55t/9MUYIIK6tGGOgpGOgrGOgomOgqmOgpmOgrmOgoWsepcKKpMwfJAhZY6CkAdhgZAxehqQPogUkoeqTk5@UpgAzGUIVuoZKqEIY0uoGQINEjJCEQYgwgTJbChAA "APL (Dyalog Unicode) – TIO Nexus") `∊` enlist (flatten – this makes all the strings into characters in the big list) `⎕AV~⍨` remove all characters in the **A**tomic **V**ector (the character set – leaves numbers) `(`…`)` apply the following tacit function:  `⌊/` the minimum across  `,` appended to  `⌈/` the maximus across [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 124 bytes ``` a->{int s[]={0,0},t;for(Object i:a)try{t=(int)i;s[0]=s[0]<1|t<s[0]?t:s[0];s[1]=s[1]<t?t:s[1];}catch(Exception e){}return s;} ``` [Try it online!](https://tio.run/##rVDLTsMwELz3K1Y5JZIbxX3waBoQByQulEOPVQ6u64JD6kT2plAFf3uw01biTi7j9T5mZ6dgRzauaqGK3WfHS2YMvDKp2hGAVCj0nnEBK//tE5scePi2LQT3IYtSV7AjBwYZSg4rUJBBx8YPresGs8mzNiGJJZjuK32ZBLlgEepTi1nouiKZmk2SZx6W9AeXPnjEhX9chfoKzZfYp2ieWs6Qf4TP31zUKCsFImqtFthoBSa1Xer11M22dHouso6V3MHB3RWuUUv13ms/H7U@GRSHuGowrl0JSxUWzpO4QVnGT1qzk4mxOo@FKuahEl9wdaClBCYEpgRmBOYEbgjcErizUdQ781/2ec/rFtwTcJto4pYMxe11nimDF1GWVdAfMBj9X2OCeTAUbUCdzmDiYephFgyp@UpkR7b7BQ "Java (OpenJDK 8) – Try It Online") Java 8 lambda function, takes array as input and gives out array `{min, max}`. Non competing, because the input has to be an integer array. Fixed and -1 byte thanks to Kevin Cruijssen ]
[Question] [ Given an integer \$1 < n < 10 \$ generate a table like below. For \$n = 5\$, ``` 1 2 3 4 5 2 2 3 4 5 3 3 3 4 5 4 4 4 4 5 5 5 5 5 5 ``` For \$n = 8\$, ``` 1 2 3 4 5 6 7 8 2 2 3 4 5 6 7 8 3 3 3 4 5 6 7 8 4 4 4 4 5 6 7 8 5 5 5 5 5 6 7 8 6 6 6 6 6 6 7 8 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 ``` Shortest code wins! Trailing whitespace allowed Output format isn't strict, you can output a 2D list/matrix in any reasonable format. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` »þ ``` [Try it online!](https://tio.run/##y0rNyan8///Q7sP7/h9ud///3wIA "Jelly – Try It Online") Outputs an `n x n` matrix. If the output format is required, [4 bytes](https://tio.run/##y0rNyan8///Q7sP7Etz///9vAQA) This is simply a table of maximums. For each cell \$A\_{i,j}\$ in the output, the result is equal to \$\max(i,j)\$. The 4 byte answer has ``` to reuse the argument, and `G` to format the output as a grid. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 bytes ([SBCS](https://github.com/abrudz/SBCS)) Anonymous tacit prefix function. ``` ∘.⌈⍨⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HHDL1HPR2Pelc86t38P@1R24RHvX2Pupof9a551Lvl0HrjR20TH/VNDQ5yBpIhHp7B/9MUTLnSFCwA "APL (Dyalog Unicode) – Try It Online") `∘.⌈⍨` maximum-table for `⍳` **i**ntegers 1 through the argument [Answer] # [Factor](https://factorcode.org/), 35 bytes ``` [ [1,b] dup [ max ] cartesian-map ] ``` [Try it online!](https://tio.run/##JYs7CgIxEIb7PcV/AHfBQpC1sRMbG7EKKWazowbNw8ks6OljxPZ7XMlpkno5H0@HEYH0PgjFGxc8WCI//yjJzILCr4Wjay4Lq36y@KjYdd0G22pg1qvJYl4yTLvesHAkysVT7ANl2NYMP5pCToUx@X39Ag "Factor – Try It Online") `cartesian-map` Takes two sequences (in this case, both are [1, n]) and applies a quotation to each pair of elements, resulting in a matrix. In effect, we are mapping `max` over a coordinate matrix. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 16 bytes ``` Max~Array~{#,#}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zexos6xqCixsq5aWUe5Vu1/QFFmXkm0Qlq0WaxC7H8A "Wolfram Language (Mathematica) – Try It Online") [Answer] ## [<>^v](https://github.com/Astroide/---v#v), ~~93~~ 89 bytes ``` i,tTv v`j1< >I)iIT‹!0jv v < >J)jJI≥v_~ v >~ v ^ v≤TJ<\23< ` ^ < ``` ##### Explanation `i` pops the top of the stack (by default 0) and stores it into the variable `i`. `,` reads an integer from stdin, then `t` pops it and stores it into variable `t`. `T` pushes to the stack the value of the variable `t` and `v` redirects the intruction pointer towards the end of the next line. `<` tells the instruction pointer to go left. `1` pushes 1 onto the stack and `j` stores it into the variable `j`, and ``` prints a newline. Then `v` and `>` sends the instruction towards the right on the next line. `I` pushes the variable `i`'s value onto the stack, `)` increments it, `i` takes it and puts it into `i`, `I` pushes the value of `i` onto the stack and `T` brings onto the stack the number that was previously read to stdin. `‹` compares them and terminates the program if the grid has finished printing. Then it initializes `j` to 0 and sends the instruction pointer into a loop that increments `j`, then prints a space (`\23` (pointer is currently going left, that's why it is reversed) pushes 32 (ASCII id of " ") and prints it) (`32\` is used instead of `" "~` because it is one character shorter), prints `j` if `j` is lower than `i`, or else prints `i`. When `j` is greater or equal to `t`, it exits the loop, prints a new line and goes back into the outer loop. In the code, the `t` variable contains the number read from stdin, `i` is the current line number, and `j` is the current character number. [run online](https://v.astroide.repl.co/#0612ddba136b8e8dbfa17856b3b57444e0a9924d0f4ea1f8756a2793257af9da) [Answer] # [J](http://jsoftware.com/), 9 bytes ``` 1+>./~@i. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6zkE6Pm7/DbXt9PTrHDL1/mtypSZn5CukKZjCGBb/AQ "J – Try It Online") ## Explanation ``` 1+>./~@i. input: n i. range from 0 to n-1 inclusive /~ table: >. max(n, n) 1+ add 1 to each ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 19 bytes ``` @(n)max([1:n]',1:n) ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQSNPMzexQiPa0CovVl0HSGr@T8wr1rDQ/A8A "Octave – Try It Online") [Answer] # [R](https://www.r-project.org/), 30 bytes ``` function(n)outer(1:n,1:n,pmax) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jTzO/tCS1SMPQKk8HhAtyEys0/4elJpfkF2VWpWqkaWoYWVlq/gcA "R – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 3 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╗ìΦ ``` [Run and debug it](https://staxlang.xyz/#p=bb8de8&i=9) [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 40 bytes ``` param($a)1..$a|%{"$(,$_*($_-1)+$_..$a)"} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SZlv9vyCxKDFXQyVR01BPTyWxRrVaSUVDRyVeS0MlXtdQU1slHiSsqVT7v5aLS00lTcGUS0kJzLD4/x8A "PowerShell Core – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 49 bytes ``` f=lambda x:x*[x]and[a+[x]for a in f(x-1)]+[[x]*x] ``` [Try it online!](https://tio.run/##HclBDoMgEEDRtT0FOwExqXVnwkkoizFAO0kdCboYT0/V3cv/@di/K421JvuDZQ4geGLt2AMFB92JtBYBAkkkyf2gfOfOqNnXa@A1CtAnypcZnmp6NLkg7RKNThKV2WK27ZtaEyncUPUP "Python 3 – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 6 bytes ``` ƛ£⁰ƛ¥∴ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C6%9B%C2%A3%E2%81%B0%C6%9B%C2%A5%E2%88%B4&inputs=5&header=&footer=) Returns an array of arrays ``` ƛ # (1...input) Map... £ # Push to register ⁰ƛ # (1...input) Map... ¥ # Register ∴ # Maximum of the two ``` Or, for grid output, 10 bytes: ``` ƛ£⁰ƛ¥∴;Ṅ;⁋ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C6%9B%C2%A3%E2%81%B0%C6%9B%C2%A5%E2%88%B4%3B%E1%B9%84%3B%E2%81%8B&inputs=5&header=&footer=) ``` ƛ ; # (1...input) Map... £ # Push to register ⁰ƛ ; # (1...input) Map... ¥ # Push register ∴ # Max Ṅ # Joined by spaces ⁋ # Joined by newlines. ``` [Answer] # [Python 2](https://docs.python.org/2/), 48 bytes ``` r=range(1,input()+1) for x in r:print[x]*x+r[x:] ``` [Try it online!](https://tio.run/##FcxLCoAgEADQ/ZzCnb82RREFnkRaRFm5GWUwmE5vdYD38lOuhF3d0h6clLKSoxXPoNomYr6L0rbVcCQSLCIKmjNFLJ4Xw5Y8z0v9EAQOm/oLbYbaQQ8DjDC9 "Python 2 – Try It Online") Prints a list for each row. [Answer] # [Julia](http://julialang.org/), 19 bytes ``` !n=max.((1:n)',1:n) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/XzHPNjexQk9Dw9AqT1NdB0T@T8ksLshJrNRQNNX8DwA "Julia 1.0 – Try It Online") [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 10 bytes ``` {x|\x}1+!: ``` [Try it online!](https://ngn.bitbucket.io/k#eJxLs6quqImpqDXUVrTi4kpTMAViCy4AT14FuQ==) Somewhat surprisingly, using a seeded scan `x|\x` returns the same results as an each-right (`x|/:x`) or each-left (`x|\:x`). * `1+!:` generate `1..n` from the (implicit) input * `{x|\x}` set up a scan, seeded with the input, run over the input [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 70 bytes ``` a => new int[a][].Select((x,p)=>new int[a].Select((y,q)=>p>q?p+1:q+1)) ``` I'm sure there is a shorter way to do this, but I can't find it. [Try it online!](https://tio.run/##VY3LCsIwEEX3/Yqhq4TGQpfaNi5EQXHnwkXtooapBOr0kRTr18co@Lqr4Z7DXGVmymi3GUllmqyA7ZrGKw7VucHs9/ZQSgm1FyEHV0EugfAGvi@qsijjAzaoLGOT6Hguv@gD7qL3oJP9souSRR8lnLs0CFYtmbbB@Dhoi3tNyIwdNF3iXauJhScKxWuVzfn71fQc/7PASxP3Sd0D "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # TI-Basic, ~~38~~ 41 bytes ``` Input N identity(N→[A] For(I,1,N For(J,1,N max(I,J→[A](I,J End End [A] ``` Output is stored as a matrix in `Ans` and is displayed. [Answer] # [Rust](https://www.rust-lang.org/), 84 bytes ``` |n|(1..=n).fold("".into(),|a,i|(1..=n).fold(a,|b,j|format!("{}{} ",b,i.max(j)))+" ") ``` [Try it online!](https://tio.run/##VY3BCsIwEETv@Yp1T7u4BHuWfkyKBra0W6kRCk2@PcbqxbnOzHvr65lqNJiDGjHsDlqme4Ktr9kydd73xj4u040QvVpaiCUH0f8uSB5kzHFZ55BOhHvZC6AMon4OG43MfEaHXK@Hoe1AQQ0ao7v8tJ881qaY7CCgwEbK/L0UV1x9Aw "Rust – Try It Online") The output will be a `String`. The newline is given literally inside quotes, which saves one byte. [Answer] # [C (gcc)](https://gcc.gnu.org/), 65 bytes ``` i,j;f(n){for(i=1;n/i;)printf(j/n?j=!++i,"%d\n":"%d ",i>++j?i:j);} ``` [Try it online!](https://tio.run/##DcoxCoAwDADAWV9RC0JCK@LgYlA/4iKVSgJGKW7i26vTLReaPYSc2QtFUHzimYDHjrRlwiux3hGk1VnGyjn2tt4WtcOPsZ4n52TmQZDe/E9zrKyA5imLCD1S@eYP "C (gcc) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 35 bytes ``` ->x{(1..x).map{|y|[y]*y+[*y+1..x]}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf166iWsNQT69CUy83saC6prImujJWq1I7GohBwrG1tf81jPT0DA2gCipqChTSooHi/wE "Ruby – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs a 2D-array. ``` õ@õwX ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9UD1d1g&input=OAotUQ) ``` õ@õwX :Implicit input of integer U õ :Range [1,U] @ :Map each X õ : Range [1,U] wX : Max of each with X ``` Or, if outputting a 1D-array is allowed: # [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` õ ïw ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9SDvdw&input=OAotUQ) ``` õ ïw :Implicit input of integer U õ :Range [1,U] ï :Cartesian product with itself w :Reduce each pair by Max ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 56 bytes ``` n=>[...Array(n)].map((_,x,a)=>a.map((_,y)=>x>y++?-~x:y)) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i5aT0/PsagosVIjTzNWLzexQEMjXqdCJ1HT1i4Rxq0EcirsKrW17XXrKqwqNTX/J@fnFefnpOrl5KdrpGlYAEUA "JavaScript (Node.js) – Try It Online") Outputs an array of arrays. Thanks to Shaggy for -5 bytes Thanks to Arnauld for further -2 bytes # [JavaScript (Node.js)](https://nodejs.org), 71 bytes ``` n=>[...Array(n)].map((_,x,a)=>a.map((_,y)=>x>y++?-~x:y).join``).join` ` ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i5aT0/PsagosVIjTzNWLzexQEMjXqdCJ1HT1i4Rxq0EcirsKrW17XXrKqwqNfWy8jPzEhKgNFfC/@T8vOL8nFS9nPx0jTQNC03N/wA "JavaScript (Node.js) – Try It Online") Outputs string ## History ``` n=>[...Array(n)].map((_,x,a)=>a.map((_,y)=>-~x>++y?-~x:y)) // 58 n=>[...m=Array(n)].map((_,a)=>[...m].map((_,b)=>-~a>++b?-~a:b)) // 63 n=>[...(m=Array(n))].map((_,a)=>[...m].map((_,b)=>-~a>++b?-~a:b)) // 65 n=>[...(m=Array(n)).keys()].map(a=>[...m.keys()].map(b=>-~a>++b?-~a:b)) // 71 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` Lã€àsä ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f5/DiR01rDi8oPrzk/6Hd/y0A "05AB1E – Try It Online") Outputs as a 2D list. Link includes a footer to format the output. ``` Lã€àsä # full program € # list of... à # maximum... € # s... à # of... € # each element of... ã # list of distinct combinations of two elements in... L # [1, 2, 3, ..., # ..., implicit input... L # ]... ã # repeated twice... ä # split into pieces of length... s # implicit input # implicit output ``` [Answer] # [Haskell](https://www.haskell.org/), 28 bytes ``` f n=(<$>[1..n]).max<$>[1..n] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz1bDRsUu2lBPLy9WUy83sQLO@5@bmJmnYKuQm1jgq1BQlJlXoqCikKZg@v9fclpOYnrxf93kggIA "Haskell – Try It Online") Generates each row by taking the max of each element of `[1..n]` and a fixed value equal to the row number. ``` map(max 3)[1,2,3,4,5] = [3,3,3,4,5] ``` We use `<$>` as an infix synonym for `map`. It would be nice to reuse the `<$>[1..n]`, but it runs into type-checking issues **26 bytes, doesn't work** ``` f n|q<-(<$>[1..n])=q$q.max ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hr6bQRlfDRsUu2lBPLy9W07ZQpVAvN7Hif25iZp6CrUJuYoGvQkFRZl6JgopCmoLp/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online") If a 1D output is allowed, we can do: **25 bytes** ``` f n=max<$>[1..n]<*>[1..n] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY3scJGxS7aUE8vL9ZGC8r4n5uYmadgq1BQlJlXoqCikKZg@v9fclpOYnrxf93kggIA "Haskell – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 67 bytes ``` lambda n:[print(*(max(y,x)+1 for y in range(n))) for x in range(n)] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKrqgKDOvRENLIzexQqNSp0JT21AhLb9IoVIhM0@hKDEvPVUjT1NTEyxWgSwW@z9Nw0LzPwA "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~51~~ 49 bytes ``` lambda n:mgrid[:n,:n].max(0)+1 from numpy import* ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKje9KDMl2ipPxyovVi83sULDQFPbkCutKD9XIa80t6BSITO3IL@oROt/QVFmXolGmoaFpuZ/AA "Python 3 – Try It Online") [Answer] # T-SQL (277 bytes) Not sure how inputs are handled in SQL but my first declared parameter is the input. I also can't get an online T-SQL compiler that runs this. But this will run in your SSMS just fine. ``` DECLARE @a int = 7DECLARE @ int=1DECLARE @c int=1DECLARE @b nvarchar(max)='SELECT'WHILE @<=@a BEGIN SET @c=1WHILE @c<=@a BEGIN SET @b+=IIF(@c=1,'',',')+STR(IIF(@c<@,@,@c))+'AS['+STR(@c)+']'SET @c+=1 END SET @b+=IIF(@<@a,'UNION ALL SELECT','')SET @+=1 END EXEC sp_executesql @b; ``` It's a naive approach with nothing special, except that it dynamically builds up a query. The query it generates is: ``` SELECT 1AS[ 1], 2AS[ 2], 3AS[ 3]UNION ALL SELECT 2AS[ 1], 2AS[ 2], 3AS[ 3]UNION ALL SELECT 3AS[ 1], 3AS[ 2], 3AS[ 3] ``` [Answer] # [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate), 80 bytes ``` ((${$2+1}|1)( $2){$2-1}( ${$4+1}{1-$4/$~1}| ${$2+1}{1-$2/$~1}){$~1-$2+1}\n){$~1} ``` Takes the argument from the command-line. [Try it here!](https://replit.com/@dloscutoff/regenerate) ### Explanation (Spaces are replaced with underscores to improve visibility.) Each line is generated in three parts. Top-level structure: ``` ( ) Group 1: a line of output (...) Group 2: the first digit (...){...} Group 3: repetitions of the first digit (...){...} Group 4: count up to N \n Add a newline {$~1} Repeat, generating N lines ``` Group 2, the first digit on each line: ``` ( ) ${$2+1} Add 1 to the previous value of group 2 | Or, if group 2 has not been previously matched... 1 Use 1 ``` Group 3, the rest of the digits on the line that are identical to the first number: ``` (_$2) The most recent value of group 2 (with a space in front of it) {$2-1} repeated (group 2) - 1 times ``` Group 4, the remaining numbers on the line, starting with (group 2) + 1 and counting up to N: ``` ( ${$4+1}{1-$4/$~1}| ${$2+1}{1-$2/$~1}){$~1-$2+1} ( ) _ Space ${$4+1} Previous value of group 4, plus 1 { } Repeat the value this many times: $4/$~1 1 if group 4 == N, 0 otherwise 1- Subtract from 1: 1 -> 0 and 0 -> 1 So if the new value would have been N+1, it instead becomes empty string | If the previous value of group 4 was not a number, the arithmetic fails, and we instead use... _ Space ${$2+1} Last value of group 2, plus 1 {1-$2/$~1} Repeat 0 times if group 2 == N { } Repeat the above $~1-$2+1 N - (group 2) + 1 times ``` ### Worked example Suppose the input is 3. **Line 1:** * Group 2: not previously matched, so `1` * Group 3: `1` repeated `1-1` = 0 times, so empty string * Group 4 is repeated `3-1+1` = 3 times: 1. Group 4 not previously matched, so followed by `2` repeated `1-1/3` = 1 time (the division is integer division) 2. Previous value of group 4 is `2`, so followed by `3` repeated `1-2/3` = 1 time 3. Previous value of group 4 is `3`, so followed by `4` repeated `1-3/3` = 0 times Result: `1 2 3` **Line 2:** * Group 2: previous value is `1`, so `2` * Group 3: `2` repeated `2-1` = 1 time * Group 4 is repeated `3-2+1` = 2 times: 1. Previous value of group 4 is , which is not a number, so followed by `3` repeated `1-2/3` = 1 time 2. Previous value of group 4 is `3`, so followed by `4` repeated `1-3/3` = 0 times Result: `2 2 3` **Line 3:** * Group 2: previous value is `2`, so `3` * Group 3: `3` repeated `3-1` = 2 times * Group 4 is repeated `3-3+1` = 1 time: 1. Previous value of group 4 is , which is not a number, so followed by `4` repeated `1-3/3` = 0 times Result: `3 3 3` [Answer] # [ayr](https://github.com/ZippyMagician/ayr), 5 bytes ``` ^:\`~ ``` # Explained ``` ~ One-range to N ` Commute (copy arg to make next symbol dyadic) \ Table ^: Of maxes ``` [Answer] # Nim, ~~138~~ 122 bytes ``` proc x(i:int)= for x in 1..i: for j in 1..x:stdout.write($x&" ") for j in x+1..i:stdout.write($j&" ") echo() ``` ]
[Question] [ *Not to be confused with [Least Common Multiple](https://codegolf.stackexchange.com/questions/94999/least-common-multiple).* Given a list of positive integers with more than one element, return the most common product of two elements in the array. For example, the MCM of the list `[2,3,4,5,6]` is `12`, as a table of products is: ``` 2 3 4 5 6 --------------- 2 | # 6 8 10 12 3 | # # 12 15 18 4 | # # # 20 24 5 | # # # # 30 6 | # # # # # ``` *Thanks DJMcMayhem for the table* As `12` appears the most times (two times as `2*6` and `3*4`). Note that we aren't including the product of an element and itself, so `2*2` or `4*4` do not not appear in this list. However, identical elements will still be multiplied, so the table for `[2,3,3]` looks like: ``` 2 3 3 ---------- 2 | # 6 6 3 | # # 9 3 | # # # ``` With the MCM being `6`. In the event of a tie, you may return any of the tied elements, or a list of all of them. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest byte count for each language wins! ### Test-cases: ``` [2,3,4,5,6] -> 12 [7,2] -> 14 [2,3,3] -> 6 [3,3,3] -> 9 [1,1,1,1,2,2] -> 2 [6,200,10,120] -> 1200 [2,3,4,5,6,7,8,8] -> 24 [5,2,9,10,3,4,4,4,7] -> 20 [9,7,10,9,7,8,5,10,1] -> 63, 70, 90 or [63,70,90] ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes ``` {⊇Ċ×}ᶠọtᵒth ``` [Try it online!](https://tio.run/##ATAAz/9icmFjaHlsb2cy//974oqHxIrDl33htqDhu4104bWSdGj//1syLDMsNCw1LDZd/1o "Brachylog – Try It Online") ### Explanation ``` { }ᶠ Find all: ⊇Ċ× Product of a subset of 2 elements ọtᵒ Order by occurrences th Take the last element and discard the number of occurrences ``` [Answer] # [R](https://www.r-project.org/), ~~54~~ ~~50~~ 41 bytes ``` order(-tabulate(combn(scan(),2,prod)))[1] ``` [Try it online!](https://tio.run/##K/r/P78oJbVIQ7ckMak0J7EkVSM5PzcpT6M4OTFPQ1PHSKegKD9FU1Mz2jD2v5GCsYKJgqmCmYK5goWCxX8A "R – Try It Online") Alternatively, for ~~54~~ ~~53~~ 44 bytes: ``` names(sort(-table(combn(scan(),2,prod))))[1] ``` [Try it online!](https://tio.run/##K/r/Py8xN7VYozi/qERDtyQxKSdVIzk/NylPozg5MU9DU8dIp6AoP0UTCKINY/8bKRgrmCiYKpgpmCtYKFj8BwA "R – Try It Online") In principle, the latter version outputs the relevant result even without the `names` function, but followed by the count of such most frequent products, which isn't asked for... Thanks to CriminallyVulgar for -4 and -1, and Giuseppe for -9 on both. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ŒcP€Æṃ ``` [Try it online!](https://tio.run/##y0rNyan8///opOSAR01rDrc93Nn8////aCMdYx0THVMds1gA "Jelly – Try It Online") or [Check out the test suite](https://tio.run/##y0rNyan8///opOSAR01rDrc93Nn8/3A7kOn@/3@0kY6xjomOqY5ZrI5CtLmOEYgCiRmDGIY6EGgEETfTMTIw0DEEIiMDmDqwXh1zHQsdC5CQKVCtJUgJSAYEzUGilkAFQDFLsDpTsAmxAA). ### How it works ``` ŒcP€Æṃ – Full program / Monadic link. Œc – Unordered pairs without replacement. P€ – Product of each. Æṃ – Mode (most common element). Alternative: ŒcZPÆṃ ``` [Answer] # Pyth, 12 bytes ``` eo/QN=*M.cQ2 ``` [Test suite](https://pyth.herokuapp.com/?code=eo%2FQN%3D%2aM.cQ2&input=%5B2%2C3%2C4%2C5%2C6%5D&test_suite=1&test_suite_input=%5B7%2C2%5D%0A%5B1%2C1%2C1%2C1%2C2%2C2%5D%0A%5B6%2C200%2C10%2C120%5D%0A%5B2%2C3%2C4%2C5%2C6%2C7%2C8%2C8%5D%0A%5B5%2C2%2C9%2C10%2C3%2C4%2C4%2C4%2C7%5D%0A%5B9%2C7%2C10%2C9%2C7%2C8%2C5%2C10%2C1%5D&debug=0) First, we take all 2 element combinations of the input without replacement (`.cQ2`). Then, we map each of these pairs to their product (`*M`). Next, we overwrite the input variable with the list of products (`=`). Next, we sort the list of products by the number of occurrences in the list of products (`o/QN`). Finally, the take the final element of the sorted list (`e`). [Answer] # [MATL](https://github.com/lmendo/MATL), ~~8~~ 7 bytes ``` 2XN!pXM ``` [Try it online!](https://tio.run/##LYu9CoAwDIR338L9hja1f7urTg6FUtBdwcH3j2mUCzm4@@46npN3prKOd1l43rgSHCZ4hDbUCJLfEyfufrf4RNoGkDGwcmR@WOeISEiSeAFzB3rRFSXMUkuUlfI6by8 "MATL – Try It Online") *(-1 byte by using the method from @Mr. Xcoder's [Jelly answer](https://codegolf.stackexchange.com/a/170052/8774).)* ``` 2XN % nchoosek - get all combinations of 2 elements from input !p % get the product of each combination XM % 'mode': get the most common value from that ``` --- Older answer: ### 8 bytes ``` &*XRXzXM ``` [Try it online!](https://tio.run/##LYu9CoAwEIN3H8RBMrRX@7e7uohDoRR0183Jlz@vteS4QPLlPp@LDx6ntKU3rbzsnAkGMyxcGbIHya@JETfdNX5Rax1IKWg5Uh1uc3gEBEmsgLECtajyEkapJYqNsm1ePg "MATL – Try It Online") ``` &* % multiply input by its transpose, % getting all elementwise products XR % take the upper-triangular portion of that, % zeroing out repetitions and mainly self-multiplications Xz % remove the zeroed out parts XM % 'mode' calculation - get the most common value from that ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` æ2ùP.M ``` -2 bytes thanks to *@Kaldo*. [Try it online](https://tio.run/##MzBNTDJM/f//8DKjwzsD9Hz//4820jHWMdEx1TGLBQA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/p5ulir6TwqG2SgpK9y//Dy4wO7wzQ8/2v8z/aSMdYx0THVMcslivaXMcISIJEjIG0oQ4EGoFFzXSMDAx0DIHIyACqCKxNx1zHQscCKGIKVGgJUgCSAEFzoKAlUBooZAlWZQrWDhQ1BtsAAA). **Explanation:** ``` æ # Take the powerset of the input-list # i.e. [2,3,3] → [[],[2],[3],[3],[2,3],[2,3],[3,3],[2,3,3]] 2ù # Leave only the inner lists of size 2: # i.e. [[],[2],[3],[3],[2,3],[2,3],[3,3],[2,3,3]] → [[2,3],[2,3],[3,3]] P # Take the product of each remaining pair # i.e. [[2,3],[2,3],[3,3]] → [6,6,9] .M # Only leave the most frequent value(s) in the list # i.e. [6,6,9] → [6] ``` [Answer] # Mathematica, 32 bytes *-17 bytes (and a fix) thanks to [JungHwan Min](https://codegolf.stackexchange.com/users/60043).* ``` Commonest[1##&@@@#~Subsets~{2}]& ``` Pure function. Takes a list of numbers as input and returns the list of MCMs as output. [Answer] # MATLAB, 43 bytes ``` I=input('');i=I'*I*1-eye(nnz(I));mode(i(:)) ``` It's also kind of a tongue twister! **Explanation** ``` I=input(''); % Takes an input like "[2,3,4,5,6]" i=I'*I % Multiplies the input by its own transverse *1-eye(nnz(I)); % Multiplies by 1-identity matrix to remove diagonal mode(i(:)) % Calculates most common value and prints it ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~41~~ 38 bytes ``` {key max bag(@_ X*@_)∖@_»²: *{*}:} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzo7tVIhN7FCISkxXcMhXiFCyyFe81HHNIf4Q7sPbbJS0KrWqrWq/V@cWKmQplGjEq@pkJZfxBVtpGOsY6JjqmMWq8MVba5jBKJAYsYghqEOBBpBxM10jAwMdAyByMgApg6sV8dcx0LHAiRkClRrCVICkgFBc5CoJVABUMwSrM4UbEKs9X8A "Perl 6 – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~12~~ 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╢êv^⌐ö►♣Ä» ``` [Run and debug it](https://staxlang.xyz/#p=b688765ea99410058eaf&i=[2,3,4,5,6]%0A[7,+2]%0A[2,3,3]%0A[1,1,1,1,2,2]%0A[6,200,10,120]%0A[2,3,4,5,6,7,8,8]%0A[5,2,9,10,3,4,4,4,7]%0A[9,7,10,9,7,8,5,10,1]&a=1&m=2) [Answer] # [Python 3](https://docs.python.org/3/), ~~77~~ 72 bytes ``` f=lambda k,*l,m=[]:l and f(*l,m=m+[k*x for x in l])or max(m,key=m.count) ``` [Try it online!](https://tio.run/##LYzbDoMgDEDf/Yo@omsWxXlN/BJCFjZ1MwIao4t@vStslLTl9JT5WN@TTc@zb7Qyj1bBiJFG0whZa1C2hZ75t7mIMdqhnxbYYbCgZUitUTszOHZHY67PabNreDrj7oxF2VfHyrAOAOZlsCujr7qP0myw87aykM4pOKZ4wwxzGYgCOWVHUqoJ/oJ7miOPY0zo8vgv@TUssMSSSEZi5QQ3cFEQrGhMqPJW5tflFw "Python 3 – Try It Online") [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 59 bytes ``` Last##~SortBy#`&&:`~##{Flat[UpperTriangle&1!Table&_!`*]^^0} ``` [Try it online!](https://tio.run/##VU1NC4JAEL37KyY2PMQcTDNT6FLQKSLITsuWm60WRIm7l4j667a1buTwhvl6bx5Xiucn0RSQTJsll4qQ1@ZWq9mdZK6bZC9CHosLV3RbVaJO6zO/lhfhDnspP@i672UDttt5z2YlxFHSflXlJXPW9fmqUiHVnEshaYFAHdBBfYQAYYQQIowZmmWE4NveEAI7Bt1xiPCD/6ca697z9PqTvtd91rohaJ@Jhr2G3x@xURmeQWQZ8VfzOcdWHbYmzGGseQM "Attache – Try It Online") Still working on golfing this down a bit, but I think this is near optimal for the approach I've chosen. ## Explanation This is a composition of three functions: 1. `{Flat[UpperTriangle&1!Table&_!`*]^^0}` 2. `SortBy#`&&:`~` 3. `Last` The first function does the bulk of the computation: ``` {Flat[UpperTriangle&1!Table&_!`*]^^0} { } anonymous lambda; input: _ (e.g.: [2,3,4,5,6]) Table&_!`* shorthand for Table[`*, _] this creates a multiplication table using the input e.g.: 4 6 8 10 12 6 9 12 15 18 8 12 16 20 24 10 15 20 25 30 12 18 24 30 36 UpperTriangle&1! takes the strict upper triangle of this matrix e.g.: 0 6 8 10 12 0 0 12 15 18 0 0 0 20 24 0 0 0 0 30 0 0 0 0 0 Flat[ ]^^0 flattens this list and removes all 0s e.g.: [6, 8, 10, 12, 12, 15, 18, 20, 24, 30] ``` The second is a bit complicated but does something rather simple. First, it is useful to know that `f&n` is a function which, when called with arguments `...x`, returns `f[...x, n]`. `f&:n` is similar, returning `f[n, ...x]`. Now, let's decompose this: ``` ( ~SortBy ) # (`& &: `~) ``` First, `f#g` creates a fork. With input `n`, it returns `f[n, g[n]]`. However, in this case, `f` is the function `~SortBy`. `~f` reverses the arguments of the function. This means that `~f#g` is equivalent to `f[g[n], n]`, or here, `SortBy[(`& &: `~)[n], n]`. ``& &: `~` follows the form `f&:n`. But what are ``&` and ``~`? They are "operator quotes", and return a function equivalent to the quoted operator. So, in this case, ``&` is the same thing as `${ x & y }`. With that in mind, this expression is equivalent to the following for binary operators: ``` f&:n <=> ${ f[n, x] } <=> ${ (`&)[`~, x] } <=> ${ `~ & x } ``` This yields the function ``~&x`, where `x` is the result from the first function. `n ~ a` counts the occurrences of `n` in `a`. So, this returns a function which counts the occurrences of the argument in the computed array from function 1. Going back to `SortBy`, this each element in the array by the number of times it appears in it. Finally, `Last` takes the element which occurs the most. Ties are broken by the sorting algorithm. [Answer] # JavaScript (ES6), ~~72~~ 70 bytes ``` a=>a.map(m=o=(y,Y)=>a.map(x=>Y--<0?m=(o[x*=y]=-~o[x])<m?m:o[r=x]:0))|r ``` [Try it online!](https://tio.run/##dY/BbsIwDIbvfYocE@SCm9KWIAzPgSofIgbTJkJQmaYiTbx6l8JApWVxDnH05cvvT/ttT5vq4/gVH/zbttlRY2lpx84epSNP8gxrdb@oabmO4wWuHElf1iM6M8WXcGK1cCs392VFNc9RqZ@q2fjDye@3471/lztZakhhChnkLB5LKTGZiERHPbYA3aGe2Gn0wpvyKzbvowncSnf0N3SQIAeNCEnYGrmXFjH6bzYoYAYz7ogHebPwvWnN7ZO2Cr6zA68JvkCaqza7xuG/2VIQBYIwKHwlytCGziA3vw "JavaScript (Node.js) – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~29 27~~ 19 bytes ``` {⌈/⊢/⊣¨⌸∊⍵}⍳∘≢↓¨⊢×⊂ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRT4f@o65FQLz40IpHPTsedXQ96t1a@6h386OOGY86Fz1qmwwU71p0ePqjrqb/aY/aJjzq7XvUN9XT/1FX86H1xo/aJgJ5wUHOQDLEwzP4/6PeVWmHVmhYKpgrGBoogCgLBVMQ01BTQcNIwVjBBMg1A7LNFYygIsZA2hhKGypAoBFY1kzByMAArNnIAFk72FQLoIgpUKElSAFIAgTNNQE "APL (Dyalog Unicode) – Try It Online") Tacit fn. Thanks to Adám for the tacit version and 2 bytes. Thanks to ngn for 8 bytes! ### How: ``` {⌈/⊢/⊣¨⌸∊⍵}⍳∘≢↓¨⊢×⊂ ⊢×⊂ ⍝ Multiply each element with the entire argument, then ⍳∘≢↓¨ ⍝ Remove 1 from the first, two from the next etc. (removes repeated multiplications); ⍝ The result is then fed into the function: { ∊⍵} ⍝ Flatten the result; ⊣¨⌸ ⍝ Key; creates a matrix in which each row corresponds to a unique product; ⊢/ ⍝ Get the rightmost column of the matrix; ⌈/ ⍝ Get the highest value. ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md "Thunno 2 Codepage") ``` 2ċ€pṀ ``` #### Explanation ``` 2ċ€pṀ # Implicit input 2ċ # Combinations of length 2 of the input €p # Product of each pair in this list Ṁ # Mode of this list # Implicit output ``` #### Screenshot [![Screenshot](https://i.stack.imgur.com/tb9wYm.png)](https://i.stack.imgur.com/tb9wY.png) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` WθF×⊟θθ⊞υκI⊟Φυ⁼№υι⌈Eυ№υλ ``` [Try it online!](https://tio.run/##PYs9C8IwEIZ3f0XGC5xgB1HpWHQrZHArHY4SSTAxzZf672Oi4Lvc3fPcuygKiyNTyktpIxl4zm4uMLhqKyMIt1aCzHPORI4KMrI77zci6EeCgWL6vly0STI0efaZTITB5errrWt5pLe22cJIa0N/Z/gvfSnTdMIDdjts44j7tnbzXLZP8wE "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Wθ ``` While the input array is non-empty... ``` ×⊟θθ ``` ... pop the last element and multiply the rest of the array by that element... ``` F...⊞υκ ``` ... and push the results to the predefined empty list. ``` ⌈Eυ№υλ ``` Count the number of times each product appears in the list and take the maximum... ``` Φυ⁼№υι... ``` ... then filter for the products whose count equals that maximum... ``` I⊟ ``` ...then pop the last element and cast to string for implicit print. [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` Ṡ►#mΠṖ2 ``` [Try it online!](https://tio.run/##yygtzv6fG5yvnaCtpKBrp6CkUfyoqbFI89C2/w93Lng0bZdy7rkFD3dOM/r//3@0kY6xjomOqY5ZLFe0uY4RkASJGANpYyhtqAOBRmBZMx0jAwMdQyAyMoAqBmvXMdex0LEAipgCFVqCFIAkQNAcKGgJlAYKWYJVmYK1xwIA "Husk – Try It Online") ## Explanation ``` Ṡ►#mΠṖ2 -- example input [3,3,3] Ṗ2 -- subsequences of length 2: [[3,3],[3,3],[3,3]] mΠ -- map product: [9,9,9] Ṡ -- apply # -- | count occurences in list ► -- to maxOn that list: [9] ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~20~~ 16 bytes * -4 bytes from @Shaggy --- ``` £s°Y m*XÃc ñ@è¥X ``` [Try it online!](https://tio.run/##y0osKPn//9Di4kMbIhVytSIONydzHd7ocHjFoaUR//9HW@qY6xga6IAoCx1TENMwVkE3AwA "Japt – Try It Online") [Answer] # [CJam](https://sourceforge.net/projects/cjam/), ~~70~~ 68 bytes ``` q',/S*~_,(:L{LX-,0a\+[{X1++}*](;{_X=\_Y=@*\}fY}fX]~;]_{\_@e=}$\;_,(= ``` [Try it online!](http://cjam.aditsu.net/#code=q%27%2C%2FS*~_%2C1-%3AL%7BLX-%2C0a%5C%2B%5B%7BX1%2B%2B%7D*%5D(%3B%7B_X%3D%5C_Y%3D%40*%5C%7DfY%7DfX%5D~%3B%5D_%7B%5C_%40e%3D%7D%24%5C%3B_%2C1-%3D&input=%5B1%2C2%2C3%2C4%5D) ## Explanation ``` q',/S*~ Turn input string into a valid CJam array _,( Find the length of the array and subtract 1 :L Assign the result to L { }fX Outer for loop LX-,0a\+[{X1++}*](; Create an array with all the array indexes bigger than X { }fY Inner for loop _X=\_Y=@*\ Create a multiple of array[X] and array[Y] (Guaranteed to be from a unique combination of factors) ~;] Casts away all stack items except for an array of the multiples _{\_@e=}$\; Sorts array by number of occurrences (largest number of occurences at the end) _,(= Gets the last element of the array ``` You will need to scroll right to see the explanations as the code is quite long, as well as the explanations. --- This was an absolute nightmare to write. CJam doesn't have a powerset function (unlike a ton of other golfing languages - great choice on my part), which means that I had to manually find the powerset. However, this gave me the opportunity to ignore any invalid number of factors, unlike other answers with a powerset function. This should be golfable, considering I'm terrible at CJam. --- ### Changes: [Helen](https://codegolf.stackexchange.com/users/58707/helen) cut off 2 bytes! Old: `q',/S*~_,1-:L{LX-,0a\+[{X1++}*](;{_X=\_Y=@*\}fY}fX]~;]_{\_@e=}$\;_,1-=` New: `q',/S*~_,(:L{LX-,0a\+[{X1++}*](;{_X=\_Y=@*\}fY}fX]~;]_{\_@e=}$\;_,(=` By changing the `1-`s to simply `(` we get the same effect but with a lower byte count. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~7~~ 6 bytes *-1 byte thanks to The Thonnu* ``` 2ḋvΠ∆M ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiMuG4i3bOoOKIhk0iLCIiLCJbMiwzLDQsNSw2XVxuWzcsMl1cblsyLDMsM11cblszLDMsM11cblsxLDEsMSwxLDIsMl1cbls2LDIwMCwxMCwxMjBdXG5bMiwzLDQsNSw2LDcsOCw4XVxuWzUsMiw5LDEwLDMsNCw0LDQsN11cbls5LDcsMTAsOSw3LDgsNSwxMCwxXSJd) [Answer] # [Java (JDK 10)](http://jdk.java.net/), 132 bytes ``` a->{int l=a.length,i=l,j=0,r=99999,m[]=new int[r];for(;i-->0;)for(j=l;--j>i;)m[a[i]*a[j]]++;for(;r-->0;)i=m[r]<i?i:m[j=r];return j;} ``` [Try it online!](https://tio.run/##ZVFdb4IwFH33V9yYmMi8EMT5iXXxZcke9uTeCA@dgmsHhbTFxRh@u2vBjZlRSHvuuef2Hi6nJ@ryw@eV5WUhNXCDvUqzzHsIe/9iaSX2mhXCkmX1nrE97DOqFLxSJuDSA7hFlababKeCHSA33HCnJRPHKAYqj8ppUgHeihehn28110zoKN5ACuRK3c3FQMgI9bJEHPUHMpIhJz5KsrQP5lFMRPIFViXjMC3kMGSuu/FDx545yULX5RsWOnlEIxY/0IjH8WjUZso2k5HciNfsia3yiBNTRya6kgJ4WF/DpsemK9O3TpRWQG6dA1wCnOAjTnFW409ojkEHLD/p4OQejrFdwV/JDAPfx7F5A/@@UHMRznGBi46YGvXSplvernnHLU2yYZaNZtrUvJF168v@hsZb42zV@nN@7e3OSie5V1TaK83kdDrsD9QKBoeB6CNspaRn5emiHevQih2E1KNlmZ23yoy1jTntZXXPfvX1Gw "Java (JDK 10) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~96~~ 94 bytes -2 bytes thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi) (using `sortOn(0<$)` instead of `length`)! ``` import Data.List f a|b<-zip[0..]a=last.last.sortOn(0<$).group$sort[x*y|(i,x)<-b,(j,y)<-b,i/=j] ``` [Try it online!](https://tio.run/##TU/LboMwELzzFauIg2kWl0AJoYJe2mOqHnqkqHJUkjjlYWFHJVX@ndoOjeK1VuOZ2ZF3z@R3VdfjyBvR9QpemGJ0zaVytsDOm8z/5aIIKC1ZXjOpqG1SO99aEmSuR3d9dxSuYYrh7nQmHAcv8zdIDniygN/nh3KsBtaIupKQOwAFFCFG@IAxLkv9RigSDCdklGjC0Q1e4KXCq3OJYRDgQt8wuBm2sZjgClcTG@uh1BiNaCqZhFTbNJ1ad2yjjFI6TsN4Czk0TLx@AvkYpP8E4qjeVb9uwQW5735gkDCfwwy0NDPIkmSrec/TKfpQII//m1@pvmJfF5xnGewq9dy1qmqVHPWO5gd/ "Haskell – Try It Online") [Answer] ## MATLAB 39 bytes ``` a=input(''); b=triu(a'*a,1); mode(b(b~=0)) ``` Also check out [answer by Jacob Watson](https://codegolf.stackexchange.com/a/170084/80759) [Answer] # SQL Server, 93 bytes ``` SELECT TOP 1a.a*b.a FROM @ a JOIN @ b ON a.i<b.i GROUP BY a.a*b.a ORDER BY COUNT(a.a*b.a)DESC ``` Input is assumed to come from a table of the form ``` DECLARE @ TABLE (A int, i int identity); ``` Example table population: ``` INSERT INTO @ VALUES (9), (7), (10), (9), (7), (8), (5), (10), (1); ``` Explanation: I assume a "list of integers" will have an index associated with them, which in my case is the column `i`. The column `a` contains the values of the list. I create products of every pair, where the left pair comes in the list earlier than the right pair. I then group on the product, and sort by the most populous number. I'm a little sad I didn't get to use any cte or partitioning clauses, but they were just too long. `SELECT` is a very expensive keyword. # Alternative, 183 bytes ``` WITH c AS(SELECT a,ROW_NUMBER()OVER(ORDER BY a)r FROM @),d AS(SELECT a.a*b.a p,COUNT(a.a*b.a)m FROM c a JOIN c b ON a.r<b.r GROUP BY a.a*b.a)SELECT TOP 1p FROM d ORDER BY m DESC ``` If SQL doesn't get to have a separate index column, here is a solution where I create an index using the `ROW_NUMBER` function. I personally don't care about the order, but an order is required and using the `a` column is the shortest. [Answer] # [CJam](https://sourceforge.net/p/cjam), 29 bytes ``` q~:L,2m*{:-},{Lf=:*}%$e`:e>1= ``` [Try it online!](https://tio.run/##S85KzP3/v7DOykfHKFer2kq3VqfaJ83WSqtWVSU1wSrVztD2//9oYwUgjAUA "CJam – Try It Online") [Answer] ## Burlesque - 8 bytes ``` Jcp)pdn! J duplicate cp cross product )pd map . product n! most common element ``` [Try it online here.](http://cheap.int-e.eu/~burlesque/burlesque.cgi?q=%7B2%203%204%205%206%7DJcp%29pdn%21) (and yes, Burlesque also has a command for "least common element") [Answer] # J, ~~29~~ ~~25~~ ~~24~~ 23 bytes ``` (0{~.\:1#.=)@(</#&,*/)~ ``` [Try it online!](https://tio.run/##VY3LCsIwEEX3/YqLBdtITSdpkzTFgiC4cuXanbSIGz9A6K/HvBRkCCT33DN5ug2vFkwjKjQgjP7sOU7Xy9nV9F75bRQln9ixPrTlttm1bHWsmO@PF4TEhAUSHXoo6Jz2MTWQ6a1/pQ4pSZrII79FIYki0Qg3QSHJRv//k98@YMgsScpTG6RQCWMSrhcfmwBstFRczDBz6A4wBFgq3Ac "J – Try It Online") ## how ``` (~. {.@\: 1 #. =)@(</ #&, */)~ (</ #&, */)~ NB. all products, dups removed: */ NB. create the times table </ NB. lower triangular ones matrix &, NB. flatten each and # NB. filter based on lower triangle @ NB. pass that result to (~. {.@\: 1 #. =) NB. get the most frequent list item: \: NB. sort down ~. NB. the uniq elements 1 #. = NB. by their count {.@ NB. and take the first element ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 95 bytes ``` x=>x.SelectMany(y=>(x=x.Skip(1)).Select(z=>y*z)).GroupBy(y=>y).OrderBy(y=>y.Count()).Last().Key ``` [Try it online!](https://tio.run/##dU5NC4JAEL33KzzuxiStVha5eygqoqKgY3QwW0GyVVYl1@i321qewhiYN@/Nmw8/7flpWC1z4bvrhcjvXHqXiLuhyBjUyQgMWhWUFeaRR9zPdp5QSFGGCqqlW5gggnHTQyVlqltqvpJxnsw@RoXNvbxy2TBzHuciQ9qz9VKN5oarato5SH0MBUjwx@n8tMCGAQxh9ML4t@eA1aLWE3aLbv/RCXzDat02AQdIH2oY6zd0SWpX9QY "C# (Visual C# Interactive Compiler) – Try It Online") Less golfed code: ``` // x is a list of integers x=> // iterate over each integer and // return a list per element. // flatten the list of lists to 1 list x.SelectMany(y=> // skip the current value and save // newly offset list to x so that it // can be incrementally offset // again next pass (x=x.Skip(1)) // compute the product .Select(z=>y*z)) // get the unique products .GroupBy(y=>y) // sort the products by number // of occurrences .OrderBy(y=>y.Count()) // pick the product with the // greatest number of occurrences .Last().Key ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` ►=mΠṖ2 ``` [Try it online!](https://tio.run/##yygtzv6fG5yvnaCtpKBrp6CkUfyoqbFI89C2/4@m7bLNPbfg4c5pRv///4820jHWMdEx1TGL5Yo21zECkiARYyBtDKUNdSDQCCxrpmNkYKBjCERGBlDFYO065joWOhZAEVOgQkuQApAECJoDBS2B0kAhS7AqU7D2WAA "Husk – Try It Online") `►=` gives -1 over the other answer. `×*` has too many duplicates and doesn't give the right value. [Answer] # [Julia 1.0](http://julialang.org/), ~~99~~ 83 bytes ``` ~=length !x=argmax(sum.(.==(1:max((M=[x[i]x[j] for i=1:~x for j=i+1:~x])...)),[M])) ``` [Try it online!](https://tio.run/##TY/PboMwDMbP4ylMtUOiWYg/BQpSpk3atU8Q5YAGawMprQjVsktfnSUBTZNz8M/299np70o2iVmWB1PdeJrPQWhYM50ujSH6folIxBhJaofkyLjhUhjeC/i6TiBZUj@MT3smXxwIGkURpciPgtKlZR/ycybBE08xwz3mWAhgr5CkaGslpivtcZvIPBcOsz@sHCa4RrppvEGBaRxjYl8ab76W/2/DEg94WBV@S24dKidxAy7KtWllNAhujdZdCwwapQhv@WCbDMLBf3EAOcLQ/WjSUkGD2yTHWY1k964UzJ2eNazyGp7XZGcd3/T5@g0hr@wldmvlD8r9zWL5BQ "Julia 1.0 – Try It Online") -16 bytes (!!) thanks to MarcMush: * Remove `*` (use implicit multiplication) * Replace `map` with a broadcast * Replace `findmax` with `argmax` * Use the return value of a variable assignment * Use `sum` instead of `count` ]
[Question] [ [A000330 - OEIS](https://oeis.org/A000330) # Task Your task is simple, generate a sequence that, given index `i`, the value on that position is the sum of squares from `0` upto `i` where `i >= 0`. # Example: ``` Input: 0 Output: 0 (0^2) Input: 4 Output: 30 (0^2 + 1^2 + 2^2 + 3^2 + 4^2) Input: 5 Output: 55 (0^2 + 1^2 + 2^2 + 3^2 + 4^2 + 5^2) ``` # Specification: * You may take no input and output the sequence indefinitely; * You may take input `N` and output the `Nth` element of the sequence; * You may take input `N` and output the first `N` elements of the sequence. [Answer] # [Python 2](https://docs.python.org/2/), 22 bytes ``` lambda n:n*~n*~(n*2)/6 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKk@rDog08rSMNPXN/qflFylkKmTmKRQl5qWnahgaaFpxKRQUZeaVKGTqKOnaKemkaWRq/gcA "Python 2 – Try It Online") This uses the closed-form formula **n \* (n+1) \* (2\*n+1) / 6**. The code performs the following operations: * Multiplies **n** by (`n*`): + The bitwise complement of **n** (`~n`), which essentially means **-1-n**. + And by the bitwise complement of **2n** (`*~(n*2)`), which means **-1-2n**. * Divides by **6** (`/6`). # [Python 2](https://docs.python.org/2/), 27 bytes ``` f=lambda n:n and f(n-1)+n*n ``` [Try it online!](https://tio.run/##BcFBCoAgEAXQfacYWmkpZEuh7mLY1EB9Rdx0@um9@vW7YFXl7UnvkRMhghIysYEPdsYE5dJISEAt4TpNWGwcqDZBJ3Gj30fHRqz@ "Python 2 – Try It Online") Saved 1 byte thanks to [Rod](https://codegolf.stackexchange.com/users/47120/rod) and 1 thanks to [G B](https://codegolf.stackexchange.com/users/18535/g-b). [Answer] # JavaScript (ES6), 16 bytes ``` n=>n*(n+++n)*n/6 ``` ### Demo ``` let f = n=>n*(n+++n)*n/6 for(n = 0; n < 10; n++) { console.log('a(' + n + ') = ' + f(n)) } ``` ### How? The expression `n+++n` is parsed as `n++ + n` (1). Not that it really matters because `n + ++n` would also work in this case. Therefore: ``` n*(n+++n)*n/6 = n * (n + (n + 1)) * (n + 1) / 6 = n * (2 * n + 1) * (n + 1) / 6 ``` which [evaluates to **sum(k=0...n)(k²)**](https://oeis.org/A000330). --- *(1) This can be verified by doing `n='2';console.log(n+++n)` which gives the integer `5`, whereas `n + ++n` would give the string `'23'`.* [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes ``` :Us ``` ... or them? [**Try it online!**](https://tio.run/##y00syfn/3yq0@P9/EwA "MATL – Try It Online") ### Explanation ``` :Us : % Implicit input n. Push range [1 2 ... n] U % Square, element-wise s % Sum of array. Implicit display ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` ÝnO ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8Nw8////TQA "05AB1E – Try It Online") **Explanation** ``` O # sum of n # squares of Ý # range [0 ... input] ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 36 bytes ``` ({<(({}[()])())>{({})({}[()])}{}}{}) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6PaRkOjujZaQzNWU0NT064ayNGECdRW1wKR5v//pgA "Brain-Flak – Try It Online") ``` # Main algorithm ( ) # Push the sum of: {({})({}[()])}{} # The square of: { } # 0 to i # Stuff for the loop <(({}[()])())> # Push i-1, i without counting it in the sum {} # Pop the counter (0) ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 34 bytes ``` ({(({}[()])()){({}[()])({})}{}}{}) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6NaQ6O6NlpDM1ZTQ1OzGs6urtWsra4FIs3//00B "Brain-Flak – Try It Online") # How does it work? Initially I had the same idea as [Riley](https://codegolf.stackexchange.com/a/145553/56656)1 but it felt wrong to use a zeroer. I then realized that ``` {({}[()])({})}{} ``` Calculates n2 - n. Why? Well we know ``` {({})({}[()])}{} ``` Calculates n2 and loops n times. That means if we switch the order of the two pushes we go from increasing the sum by n + (n-1) each time to increasing the sum by (n-1) + (n-1) each time. This will decrease the result by one per loop, thus making our result n2 - n. At the top level this -n cancels with the n generated by the push that we were zeroing alleviating the need for a zeroer and saving us two bytes. # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 36 bytes ``` ({({})(({}[()])){({})({}[()])}{}}{}) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6Nao7pWUwNIRGtoxmpqQrhQXm11LRBp/v9vCgA "Brain-Flak – Try It Online") Here is another solution, its not as golfy but it's pretty strange so I thought I would leave it as a challenge to figure out how it works. If you are not into Brain-Flak but you still want the challenge here it is as a summation. ![Picture](https://a-ta.co/mathjax/!XGRpc3BsYXlzdHlsZVxzdW1fe2k9MX1ebiBcbGVmdCggKDJpIC0gMSkgKyBcc3VtX3tqPTF9XntpLTF9ICggMmotMSApIFxyaWdodCk=.svg) --- 1: I came up with my solution before I looked at the answers here. So no plagiarism here. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` R²S ``` [Try it online!](https://tio.run/##y0rNyan8/z/o0Kbg////mwAA "Jelly – Try It Online") FGITW # Explanation ``` R²S Main Link R Generate Range ² Square (each term) S Sum ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 3 bytes ``` ṁ□ḣ ``` [Try it online!](https://tio.run/##yygtzv7//@HOxkfTFj7csfj///@mAA "Husk – Try It Online") [Answer] ## [Hexagony](https://github.com/m-ender/hexagony), 23 bytes ``` ?'+)=:!@/*"*'6/{=+'+}/{ ``` [Try it online!](https://tio.run/##y0itSEzPz6v8/99eXVvT1krRQV9LSUvdTL/aVltdu1a/@v9/03/5BSWZ@XnF/wE "Hexagony – Try It Online") ### Explanation Unfolded: ``` ? ' + ) = : ! @ / * " * ' 6 / { = + ' + } / { . . . . . . . . . . . . . . ``` This is really just a linear program with the `/` used for some redirection. The linear code is: ``` ?'+){=+'+}*"*'6{=:!@ ``` Which computes **n (n+1) (2n+1) / 6**. It uses the following memory edges: [![enter image description here](https://i.stack.imgur.com/OSVZf.png)](https://i.stack.imgur.com/OSVZf.png) Where the memory point (MP) starts on the edge labelled **n**, pointing north. ``` ? Read input into edge labelled 'n'. ' Move MP backwards onto edge labelled 'n+1'. + Copy 'n' into 'n+1'. ) Increment the value (so that it actually stores the value n+1). {= Move MP forwards onto edge labelled 'temp' and turn around to face edges 'n' and 'n+1'. + Add 'n' and 'n+1' into edge 'temp', so that it stores the value 2n+1. ' Move MP backwards onto edge labelled '2n+1'. + Copy the value 2n+1 into this edge. } Move MP forwards onto 'temp' again. * Multiply 'n' and 'n+1' into edge 'temp', so that it stores the value n(n+1). " Move MP backwards onto edge labelled 'product'. * Multiply 'temp' and '2n+1' into edge 'product', so that it stores the value n(n+1)(2n+1). ' Move MP backwards onto edge labelled '6'. 6 Store an actual 6 there. {= Move MP forwards onto edge labelled 'result' and turn around, so that the MP faces edges 'product' and '6'. : Divide 'product' by '6' into 'result', so that it stores the value n(n+1)(2n+1)/6, i.e. the actual result. ! Print the result. @ Terminate the program. ``` In theory it might be possible to fit this program into side-length 3, because the `/` aren't needed for the computation, the `:` can be reused to terminate the program, and some of the `'"=+*{` might be reusable as well, bringing the number of required commands below 19 (the maximum for side-length 3). I doubt it's possible to find such a solution by hand though, if one exists at all. [Answer] # [Ohm v2](https://github.com/MiningPotatoes/Ohm), 3 bytes ``` #²Σ ``` [Try it online!](https://tio.run/##y8/INfr/X/nQpnOL//83@Q8A "Ohm v2 – Try It Online") **Explanation** ``` # Range ² Square Σ Sum ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 3 bytes ``` ô²x ``` [Try it here.](https://ethproductions.github.io/japt/?v=1.4.5&code=9LJ4&input=NQ==) -1 thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy). Explanation: ``` ò²x ô² Map square on [0..input] x Sum ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 46 bytes ``` {(({})[()])}{}{({({})({}[()])}{}<>)<>}<>({{}}) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/v1pDo7pWM1pDM1aztrq2WqMaxAVimIiNnaaNHZDUqK6urdX8/98UAA "Brain-Flak – Try It Online") [Answer] # [CJam](https://sourceforge.net/p/cjam), 10 bytes ``` ri),{_*+}* ``` [**Try it online!**](https://tio.run/##S85KzP3/vyhTU6c6Xku7Vuv/fxMA "CJam – Try It Online") ``` ri e# Input integer n ) e# Add 1 , e# Range [0 1 ... n] { }* e# Fold (reduce) _ e# Duplicate * e# Multiply + e# Add ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 14 bytes ``` Tr[Range@#^2]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@z@kKDooMS891UE5zihW7X9AUWZeiYK@g0IaiKg20VEwrf3/3wQA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` ⟦^₂ᵐ+ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZXGPmpoebp2g/f@/6f8oAA "Brachylog – Try It Online") ### Explanation ``` ⟦ Range ^₂ᵐ Map square + Sum ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 3 bytes ``` R;* ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/z/IWuv/fxMA "Actually – Try It Online") Takes `N` as input, and outputs the `N`th element in the sequence. Explanation: ``` R;* R range(1, N+1) ([1, 2, ..., N]) ;* dot product with self ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~7~~ 5 bytes *2 bytes saved thanks to @Mego* ``` +.×⍨⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRtvcPTH/WueNS7GchXOARiGBoAAA) **How?** `⍳` - range `+.×` - dot product `⍨` - with itself [Answer] ## R, 17 bytes ``` sum((0:scan())^2) ``` Pretty straightforward, it takes advantage from the fact that `^` (exponentiation) is vectorized in **R**. [Answer] ## [CJam](https://sourceforge.net/p/cjam), 9 bytes ``` ri),_.*:+ ``` [Try it online!](https://tio.run/##S85KzP3/vyhTUydeT8tK@/9/EwA "CJam – Try It Online") ### Explanation ``` ri e# Read input and convert to integer N. ), e# Get range [0 1 2 ... N]. _ e# Duplicate. .* e# Pairwise products, giving [0 1 4 ... N^2]. :+ e# Sum. ``` Alternatively: ``` ri),2f#:+ ``` This squares each element by mapping `2#` instead of using pairwise products. And just for fun another alternative which gets inaccurate for large inputs because it uses floating-point arithmetic: ``` ri),:mh2# ``` [Answer] # [Julia](http://julialang.org/), ~~16~~ 14 bytes *2 bytes saved thanks to @MartinEnder* ``` !n=(x=1:n)⋅x ``` [Try it online!](https://tio.run/##yyrNyUw0/f9fMc9Wo8LW0CpP81F3a8X/tPwihUwFWwVDK0MDLs6Cosy8kpw8DcVMTa7UvJT/AA) **How?** `(x=1:n)` creates a range of `1` to `n` and assign to `x`, `⋅` dot product with `x`. [Answer] ## [Labyrinth](https://github.com/m-ender/labyrinth), 11 bytes ``` :!\ + : *:# ``` [Try it online!](https://tio.run/##y0lMqizKzCvJ@P/fSjGGS1vBikvLSvn/f1MA "Labyrinth – Try It Online") Prints the sequence indefinitely. ### Explanation The instruction pointer just keeps running around the square of code over and over: ``` :!\ Duplicate the last result (initially zero), print it and a linefeed. : Duplicate the result again, which increases the stack depth. # Push the stack depth (used as a counter variable). :* Square it. + Add it to the running total. ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 15 bytes ``` Iu):^\+*p*6u@O, ``` [Try it online!](https://tio.run/##Sy5Nyqz4/9@zVNMqLkZbq0DLrNTBX@f/f1MA "Cubix – Try It Online") My code is a bit sad `):` Computes `n*(n+1)*(2n+1)/6` ``` I u ) : ^ \ + * p * 6 u @ O , . . . . . . . . . ``` ``` ^Iu : read in input, u-turn : stack n :)\ : dup, increment, go right..oh, hey, it cheered up! : stack: n, n+1 + : sum : stack: n, n+1, 2*n+1 * : multiply : stack: n, n+1, 2*n+1, (n+1)*(2*n+1) p : move bottom of stack to top : stack: n+1, 2*n+1, (n+1)*(2*n+1), n * : multiply 6 : push 6 u : right u-turn , : divide O : output @ : terminate ``` [Answer] # [Befunge](https://github.com/catseye/Befunge-93), 16 bytes ``` &::2*1+*\1+*6/.@ ``` Using the closed-form formula **n\*(n+1)\*(2n+1)/6**. [Try it online!](https://tio.run/##S0pNK81LT/3/X83KykjLUFsrBojN9PUc/v83AQA "Befunge – Try It Online") # [Befunge](https://github.com/catseye/Befunge-93), 38 bytes ``` v>::*\1-:v0+_$.@ &^ < _\:^ >:#^_.@ ``` Using a loop. [Try it online!](https://tio.run/##S0pNK81LT/3/v8zOykorxlDXqsxAO15Fz4FLLU7BRgEE4mOs4rjsrJTj4vUc/v83BQA "Befunge – Try It Online") [Answer] ## Haskell, 20 bytes ``` f 0=0 f n=n*n+f(n-1) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P03BwNaAK00hzzZPK087TSNP11Dzf25iZp6CrUJBUWZeiYKKQpqC6X8A "Haskell – Try It Online") [Answer] # Excel, 19 bytes ``` =A1^3/3+A1^2/2+A1/6 ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~15~~ ~~13~~ 11 bytes Saved 2 bytes thanks to *Not a tree* ``` 0:n:l1-:*+! ``` [Try it online!](https://tio.run/##S8sszvj/38AqzyrHUNdKS1vx/38A "><> – Try It Online") Outputs the sequence indefinitely. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 5 bytes thanks to Steven H ``` s^R2h ``` Explanation: ``` s^R2h Full program - inputs from stdin and outputs to stdout s output the sum of h range(input), with ^R2 each element squared ``` --- My first solution ``` sm*ddUh ``` [Try it online!](https://tio.run/##K6gsyfj/vzhXKyUl@P9/cwA "Pyth – Try It Online") Explanation: ``` sm*ddUh Full program - inputs from stdin and outputs to stdout s sum of m Uh each d in range(input) *dd squared ``` [Answer] # [J](http://jsoftware.com/), ~~10~~ 9 bytes ``` 4%~3!2*>: ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqCjYKBgBcS6egrOQT5u/01U64wVjbTsrP5rcnGlJmfkK6QpmMAYpv8B "J – Try It Online") *Saved 1 byte using an explicit formula, thanks to miles!* --- ## J, 10 bytes ``` 1#.]*:@-i. ``` J has a range function, but this gives us number from `0` to `N-1`. To remedy this, we can just take the argument and subtract the range from it, giving us a range from `N` to `1`. This is done with `] -i.`. The rest of the code simply square this list argument (`*:@`) and then sums it (`1#.`). ## Other contenders **11 bytes**: `1#.*:@i.@>:` **13 bytes**: `1#.[:,@:*/~i.` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `S`, 2 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` R² ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faGm0UrBS7IKlpSVpuhaLgw5tWlKclFwM5S9YaAJhAAA) #### Explanation ``` R² # Implicit input R # Range of input ² # Square each # Sum the list # Implicit output ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 3 bytes ``` R:∙ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FkuDrB51zFxSnJRcDBVZsNSAy4TLFMIBAA) ``` R:∙ R Range : Duplicate ∙ Dot product ``` Because there isn't a square built-in yet. ]
[Question] [ I find it deeply weird that this is possible in Ruby (I won't immediately say how): ``` obj = #code redacted print obj.state # Some value. LValue = obj print obj.state # Different value! ``` Your challenge is to create code roughly of this form. Create an object and assign it to a variable. It should have some defined attribute (or deterministic, idempotent method) like `state` above, that changes after the object is assigned to a new identifier (`LValue` above), *even if* you still use the old identifier (`obj` above) to refer to it. **Edit for emphasis**: `state` or the equivalent must be idempotent, so creating an accessor that modifies the value, or for any other reason returns different results when called several times in a row, isn't a valid solution. Or, more simply, it has to be the assignment that changes the state. Any language with assignment is eligible, although there are probably some where there's no fully legitimate solution. I'll post my Ruby answer if nobody else gets it after a few days, and accept highest-voted answers on a rolling basis. [Answer] ## C++ This is trivial using the right tools. ``` #include <iostream> using namespace std; class Obj { public: int state; Obj& operator= (Obj& foo) { foo.state++; this->state = foo.state - 2; return *this; } }; int main() { Obj a, b, c, d; a.state = 3; b.state = 4; cout << a.state << " " << b.state << "\n"; c = a; d = b; cout << a.state << " " << b.state << " " << c.state << " " << d.state << "\n"; return 0; } ``` Output: ``` 3 4 4 5 2 3 ``` [Answer] # PHP (debug build, >= 5.4) We use refcount of the object in a getter. (So, by the assignment, refcount increases and value changes) ``` class State { public function __get($arg) { ob_start(); debug_zval_dump($this); // e.g. "object(State)#1 (0) refcount(6)" return ob_get_clean()[29]; } } $obj = new State; var_dump($obj->state); $a = $obj; var_dump($obj->state); ``` [Answer] # C# Two simple options: ``` class Obj { public int state; public static implicit operator int(Obj o) { return o.state++; } } static int LValueI; static Obj LValueM { set { value.state++; } } static void Main() { var obj = new Obj { state = 1 }; LValueI = obj; Console.WriteLine(obj.state); //2, caused by the implicit cast. LValueM = obj; Console.WriteLine(obj.state); //3, caused by the property setter. Console.ReadLine(); } ``` Or we could simply write to the same memory: ``` [StructLayoutAttribute(LayoutKind.Explicit)] class Program { [FieldOffset(0)] int state = 1; [FieldOffset(1)] int LValue; void Test() { var obj = this; Console.WriteLine(state); //1 LValue = state; Console.WriteLine(state); //257 Console.ReadLine(); } static void Main() { new Program().Test(); } } ``` [Answer] # TeX, much shorter than other answers here ``` \setbox0=\hbox{Hello world!} % Put stuff in the box 0. \message{\the\wd0} % Print the width of the box => non-zero \setbox2=\box0 % Put the box instead in box 2. \message{\the\wd0} % Now box 0 is void, hence has zero width. ``` As a typesetting system, TeX has a "box" type, which contains typeset material. Since the most common use case is to move this material around, split it, etc, rather than making copies of it, boxes are normally deleted when used (or rather, "box" variables are pointers and only one pointer at a time can point to an actual box in memory). No need for any magic. [Answer] ## C++11 (So you guys have forgotten about unique\_ptr/shared\_ptr :-) ) ``` #include <iostream> #include <memory> using namespace std; int main() { std::unique_ptr<int> u1(new int(0)), u2; std::shared_ptr<int> s1 = std::make_shared<int>(0), s2; std::cout<<u1.get()<<" "<<u2.get()<<" "<<std::endl; std::cout<<s1.use_count()<<" "<<s2.use_count()<<" "<<std::endl; u2 = std::move(u1); s2 = s1; std::cout<<u1.get()<<" "<<u2.get()<<" "<<std::endl; std::cout<<s1.use_count()<<" "<<s2.use_count()<<" "<<std::endl; return 0; } ``` [Answer] # Fortran 03 This is somewhat similar to Hugo's D answer, but is a little more hidden (partly because who the #$%^ knows Object Oriented Fortran)? ``` module objects implicit none type ObjDef integer :: state contains procedure :: initObject procedure :: printObject procedure :: setNew end type contains subroutine initObject(this) class(ObjDef) :: this this%state = this%state + 1 end subroutine initObject subroutine printObject(this) class(ObjDef) :: this print '(a,i0)',"this%state = ",this%state end subroutine printObject subroutine setNew(this,that) class(ObjDef) :: this,that that%state = this%state end subroutine setNew end module objects program objectChange use objects type(ObjDef) :: a,b call initObject(a) call printObject(a) call b%setNew(a) call printObject(a) end program objectChange ``` The output is ``` this%state = 1 this%state = 0 ``` If you can figure out what happened, bonus points to you! If not: > > When calling the procedure `setNew` in the form `call b%setNew(a)`, `b` is implicitly the first argument, not the second. > > > [Answer] ## PowerShell This creates an object whose `state` property is the names of the variables that point to the object. ``` $a = @{}| Add-Member -MemberType:16 -PassThru state -Value { (gv|?{$this -eq $_.Value}|%{$_.Name}) -join ','} 'Before: ' + $a.state $b = $a 'After: ' + $a.state ``` Output ``` Before: a,this After: a,b,this ``` *Note:* This doesn't work if the assignment happens in a child scope. ``` 'Before: ' + $a.state &{$b = $a} 'After: ' + $a.state ``` Outputs ``` Before: a,this After: a,this ``` [Answer] # Perl 5 Here's one way to do it in Perl: ``` package Magic { sub new { bless {state => 1} } use overload '""' => sub { $_[0]{state}++ }; } use feature 'say'; my $obj = new Magic; say $obj->{state}; substr($_, 0) = $obj; say $obj->{state}; ``` This outputs: ``` 1 2 ``` **Explanation:** This is a straightforward application of [overloading](http://perldoc.perl.org/overload.html). Specifically, I overload the string conversion operator `""`, which gets called when the overloaded object is assigned to [`substr()`](http://perldoc.perl.org/functions/substr.html) (which, yes, is a legal lvalue in Perl). There are also plenty of [special variables](http://perldoc.perl.org/perlvar.html) in Perl which stringify anything assigned to them. For example, the following also works: ``` my $obj = new Magic; say $obj->{state}; $0 = $obj; say $obj->{state}; ``` --- ## Alternative solution Here's another way to it: ``` package Magic { use Devel::Peek 'SvREFCNT'; sub new { bless \my $foo } sub state { SvREFCNT ${$_[0]} } } use feature 'say'; my $obj = new Magic; say $obj->state; my $other = $obj; say $obj->state; ``` Here, `state` is a method (we could make it an attribute with further tie / overload shenanigans, but that would complicate things) that literally counts the number of references to the object. Thus, unlike in the first solution, you actually have to assign `$obj` to a normal variable that can hold an object reference to make the state change. [Answer] # JavaScript Ok, so i made a shorter version that works as SSCCE, but does no longer try to parse JavaScript properly, so the reference counting might not work when put inside a more complex script. ``` (function run () { var lineOne = getLine (1), a, b, x, y, z; var x = { get state () { var x=/([a-z]+)\s*=\s*([a-z]+)/,c; return 1 + Object.keys (c = run.toString ().split ('\n').slice (0,getLine (2)).filter (function (a) {return (x.test (a))}).reduce (function (a,b,c,d) {var r=b.match (x),t=r[2];while (a[t]){t=a[t]};a[r[1]]=t;return a}, {v:0})).reduce (function (a,b) {return (c[b]=="x"?1:0) + a},0) } }; console.log (x.state); //1 console.log (x.state); //1 y = x; console.log (x.state); //2 z = y; console.log (x.state); //3 a = z; b = a; console.log (x.state); //5 a = null; console.log (x.state); //4 b = null; console.log (x.state); //3 })() //1 1 2 3 5 4 3 function getLine(n) { try { to } catch (dat) { var stack = dat.stack.split('\n'); for (var i = 0; i < stack.length; i++) { if (~stack[i].indexOf ('getLine')) break; } return dat.stack.split ('\n')[i + ~~n].match (/:(\d+)/)[1] - ~~window.hasOwnProperty ('__commandLineAPI') } } ``` [Answer] # Python It's cheating a little, but how about: ``` import gc class A(object): @property def state(self): return len(gc.get_referrers(self)) a = A() print a.state b = {"x": a} print a.state a.y = a print a.state del a print b["x"].state ``` [Answer] ## C++11 though this can be extended for other languages that supports implicit / explicit destrucors ``` #include <iostream> using namespace std; class Foo { int *ptr; public: Foo() { ptr = new int(0); } int state() { return *ptr; } ~Foo() { (*ptr)++; } }; int main() { Foo a, b; cout << a.state() << " " << b.state() << "\n"; { Foo c, d; c = a; d = b; } cout << a.state() << " " << b.state() << "\n"; return 0; } ``` > > The default assignment operator performs a shallow copy. So the receiving object still owns the pointer and any change implicitly affects the original object; > > > [Answer] ## Scala Implicit conversions let you accomplish this while assigning to a normal local variable: ``` import scala.language.implicitConversions class Obj { var counter = 0 } implicit def o2s(x: Obj): String = { x.counter += 1 x.toString } val obj = new Obj println(obj.counter) val s: String = obj println(obj.counter) ``` You can accomplish that with inferred types, too: ``` var s = "" s = obj ``` You can also use a custom setter method, though that requires the L-value to be a field: ``` object L { var _value = new Obj def value = _value def value_=(x: Obj): Unit = { _value = x x.counter += 1 } } val obj = new Obj println(obj.counter) L.value = obj println(obj.counter) ``` [Answer] ## D ``` struct Obj { int state; void opAssign (ref Obj other) { ++other.state; } } void main () { import std.stdio; Obj obj, lvalue; writeln(obj); lvalue = obj; writeln(obj); } ``` Output: ``` Obj(0) Obj(1) ``` [Answer] # Ruby As promised, here's the answer that inspired the question. ``` obj = Class.new { def self.state; to_s[/</] ? "Has not been assigned\n" : "Assigned to #{to_s}"; end } print obj.state LValue = obj print obj.state ``` `Class.new` creates an anonymous class. Calling `to_s` on an anonymous class gives the default string representation of objects, which looks like `#<Class:0x007fe3b38ed958>`. However, once the class has been assigned to a constant, `to_s` becomes that constant. In Ruby, a constant is a variable that begins with an uppercase letter, so `obj` is a reference to the class that allows it to stay anonymous. My code wraps `to_s` in a `state` method, so the output becomes ``` Has not been assigned Assigned to LValue ``` Unlike most of the solutions here, this only works once: assigning `obj` to another constant won't change its string representation, and neither will assigning a new value to `LValue`. [Answer] **In Java** I thought this was impossible in Java. But… *Main class :* ``` public class MyAppOfCats { public static void main(String[] args) { Cat tom = new Cat(); System.out.println(tom.state()); // Output : NOT-BEST-CAT Cat.bestCat = tom; System.out.println(tom.state()); // Output : BEST-CAT } } ``` *Class Cat :* ``` public class Cat { static Cat bestCat; public Cat() { super(); } public String state() { return ((this == Cat.bestCat) ? "BEST-CAT" : "NOT-BEST-CAT"); } } ``` I have been inspired by @tbodt. [Answer] # C++ This behavior is actually specified in the standard (and that's why it was deprecated). ``` #include<iostream> #include<memory> int main() { std::auto_ptr<int> a(new int(0)); std::cout<<a.get()<<'\n'; std::auto_ptr<int> b = a; std::cout<<a.get()<<'\n'; } ``` Output ``` some address 0 ``` The process that causes this is the same as Abhijit's answer but without requiring a `std::move` and the same as marinus' answer but using a standard class instead of defining it myself. Edit: I'm adding some explanation. In the output, "some address" will actually be a hex value for the address of the allocated integer. `std::auto_ptr` releases its stores pointer when assigned to another `auto_ptr` and sets its internal pointer to 0. Calling `get()` retrieves access to the stores pointer. [Answer] # Python ``` import sys class K:state = property(sys.getrefcount) ``` [Answer] # Python 2.x I couldn't find a proper way to do this without defining an extra class. ``` class State(object): def __init__(self): self.state = 0 def __set__(self, obj, other): # Keep different references other.state += 1 self.state += 2 class Program(object): obj, value = State(), State() # Create two State-objects def __init__(self): print "Before assignment:", self.obj.state, self.value.state # 0 0 self.value = self.obj # Set value to obj (supposedly) print "After assignment:", self.obj.state, self.value.state # 1 2 self.value = self.obj print "2nd assignment:", self.obj.state, self.value.state # 2 4 Program() ``` [Answer] # Java All the other solutions use their language's form of operator overloading. Java doesn't have operator overloading, so I thought I was stuck. But I came up with something. Here's the main class: ``` public class Program { public static void main(String[] args) { Thing thing = new Thing(0); System.out.println(thing.getState()); Thing.otherThing = thing; Thread.sleep(1); System.out.println(thing.getState()); } } ``` There are a few suspicious lines, but they wouldn't do anything if the `Thing` class was completely normal. It isn't: ``` public class Thing { private int state; public Thing(int state) { this.state = state; } public int getState() { return state; } // Please do your best to ignore the rest of this class. public static volatile Thing otherThing; static { Thread t = new Thread() { public void run() { Thing t = otherThing; while (true) if (t != otherThing) { t = otherThing; t.state++; } } }; t.setDaemon(true); t.start(); } } ``` It's not guaranteed to work because of the threads, but I tested it on JDK 1.8u5, and it works there. [Answer] # Common Lisp I define state as the number of special variables bound to a vector. So, assignment to a special variable changes the state. ``` (defgeneric state (object) (:documentation "Get the state of this object.")) (defmethod state ((object vector)) ;; The state of a vector is the number of symbols bound to it. (let ((count 0)) ;; Iterate each SYM, return COUNT. (do-all-symbols (sym count) ;; When SYM is bound to this vector, increment COUNT. (when (and (boundp sym) (eq (symbol-value sym) object)) (incf count))))) (defparameter *a* #(this is a vector)) (defparameter *b* nil) (defparameter *c* nil) (print (state *a*)) (setf *b* *a*) (print (state *a*)) (print (state *a*)) (setf *c* *a*) (print (state *a*)) ``` Output: ``` 1 2 2 3 ``` It only works with assignments to special variables, not to lexical variables, nor to slots within an object. Beware that `do-all-symbols` looks in all packages, so it misses variables that have no package. It might double-count symbols that exist in more than one package (when one package imported the symbol from another package). # Ruby Ruby is almost the same, but I define state as the number of constants referring to an array. ``` class Array # Get the state of this object. def state # The state of an array is the number of constants in modules # where the constants refer to this array. ObjectSpace.each_object(Module).inject(0) {|count, mod| count + mod.constants(false).count {|sym| begin mod.const_get(sym, false).equal?(self) rescue NameError false end } } end end A = %i[this is an array] puts A.state B = A puts A.state puts A.state C = A puts A.state ``` Output: ``` state-assign.rb:9:in `const_get': Use RbConfig instead of obsolete and deprecated Config. 1 2 2 3 ``` This is a generalization of [histocrat's answer](https://codegolf.stackexchange.com/a/30303/4065) to Ruby objects that are not classes or modules. The warning appears because the Config constant autoloads some code that made the warning. [Answer] # C++ The result may differ in different platforms. Tested on [ideone](http://ideone.com/nx8yjo). ``` #include <iostream> #include <cassert> // File format: [ciiiiciiii...] a char (1 byte) followed by its state (4 bytes) // Each group takes 5 bytes char Buffer[30]; // 5*6, six groups struct Group { char c; int state; }; int main(void) { assert(sizeof(char) == 1); assert(sizeof(int) == 4); Group& first_group = *(Group*)(&Buffer[0]); // Group 1 is at 0 Group& second_group = *(Group*)(&Buffer[5]); // Group 2 is at 5 first_group.c = '2'; first_group.state = 1234; std::cout << first_group.state << std::endl; second_group = first_group; std::cout << first_group.state << std::endl; return 0; } ``` Output: ``` 1234 13010 ``` [Answer] ## C# ``` class A { public int N { get; set; } public override string ToString() { return N.ToString(); } } class B { public int N { get; set; } public override string ToString() { return N.ToString(); } public static implicit operator A(B b) { b.N = -b.N; return new A { N = b.N }; } } public static void Test() { A a = new A { N = 1 }; B b = new B { N = 2 }; Console.WriteLine("a is {0}, b is {1}", a, b); Console.WriteLine("a is {0}, b is {1}", a, b); a = b; Console.WriteLine("a is {0}, b is {1}", a, b); Console.WriteLine("a is {0}, b is {1}", a, b); } ``` Output: ``` a is 1, b is 2 a is 1, b is 2 a is -2, b is -2 a is -2, b is -2 ``` ]
[Question] [ Your task is to write a non-empty computer program comprised of some sequence of bytes. If we choose a particular byte in the program and remove all instances of it from the program, the modified program should output the removed byte. For example if our program were ``` aabacba ``` Then `bcb` would output `a`, `aaaca` would need to output `b` and `aababa` would output `c`. It does not matter what the unmodified program does. Answers will be scored in bytes with the goal being to minimize the number of bytes. [Answer] ## zsh, ~~603~~ ~~594~~ ~~566~~ ~~561~~ ~~548~~ ~~440~~ ~~415~~ ~~399~~ ~~378~~ 370 bytes ``` ec ho \\n;ca t<<<$'\x20';exi t d$c -e8BC6P d0c -eKp $'\172\163\150' $'\055\143' $'\146\157\162 v \151\156 \173\043\056\056\134\175\175\073\173 \146\147\162\145\160 \055\161 $\166 '$0$'\174\174\074\074\074$\166\073\175' $'\145v\141\154' $':\073\072\046\046\145\170\151\164';#%&()*+,/9=>?@ADEFGHIJLMNOQRSTUVWXYZ[]^_`jklmsuwy 0# $#;for b in {$..z};{ fgrep -q $b $0||<<<$b;} ``` Depends on coreutils + `dc`. [Try it online!](https://tio.run/##TVFpc9MwFPyuX7GTiIgrjpzIDmDXLZSj3PdZF0hsuUlJ5dR2g0ma3x6eFShoZp9W2nfsSMtysklGFaLxqNTOspwgDIXOM7HRCZvkiGMTJCNUYRhyEdd9KQJdT1GxlCfo6lv39v1XLJUNfzpnlOIO@7HrD2LXkwJ0lp4Xu2pguat8uh@S3scCRF2CT2Q4iKUieL6FO1B051lI0kjHtljZYtpJ9CW23X0XnKIPwaV1oCzkP1j5TytPWJvKW1BoDKjG2x2rSjIvaY60sxoDcuvSVyJoX@lcvXb9xs3e7Z1od@/u/QcPHx08fvLs@YuXr9@8fff@w8dPn78cHn399v3kx@y0PP/5i8k2eDvI8gJjTA1W3HGW62CF7LjQc3TPwMfg8uKiedxxsN7QuzPWpNdNuoiNwEpAOI5YizVLcwZaOqFv6Rq0Cn2aL6bmGIe8PsJOhJbVqwLdFC1etxBefmpU6bJqmE1Jp1mGS@2vhKiX6kXPnM9m6HS2c4TJK8wLXWpTNZ6SPNXC9vi/kqwZvfkN) That was... a journey. This answer has three parts. The first 4 lines handle certain special cases to simplify the code that follows. The next 2 lines and the last line both accomplish essentially the same thing, but exactly one is run with any given character removal. They are written with mostly complementary character sets, so that removing any character breaks only one at most, allowing the other to continue to function. Looking at the first part, we first handle * newline removal with `ec\nho \\n` * space removal with `ca t<<<$'\x20'` (followed by `exi t` to avoid running later code, which would result in extraneous output) * `$` removal with `d$c -e8BC6P` (`8BC6` = `9226` is `36*256 + 10`, and 36 and 10 are the byte values of the `$` and newline characters respectively; we use hex digits in decimal to avoid having to include them in the large comment in line 6) * `0` removal with `d0c -eKp` (`K` gets the decimal precision, which is `0` by default) In the next part, the only characters used (aside from the garbage at the end of the second line) are `$'\01234567v;`, space, and newline. Of these, four have been accounted for, so the remainder (`'\1234567v`) cannot occur in the last line. Expanding the octal escapes (`$'\123'` represents the ASCII character with value 1238), we get: ``` zsh -c 'for v in {#..\}};{ fgrep -q $v '$0'||<<<$v;}' eval ':;:&&exit' ``` The first line loops through all characters used in the program and searches for each one in its own source code (`$0` is the filename of the script being run), printing any character that is not found. The second line looks a little strange, and appears to do the same thing as `exit` with a bunch of nops. However, encoding `exit` as octal directly results in `$'\145\170\151\164'`, which does not contain `2` or `3`. We actually need to make this *less* resilient to removals. This is because if any of `'\014567v` are removed, breaking the first line, the second line also breaks, allowing the remainder of the code to execute. However, we need it to also break if `2` or `3` are removed so that lines 3 and 4 can run. This is accomplished by shoehorning in `:` and `;`, which have a 2 and 3 in their octal representation respectively. The junk at the end of line 2 is simply there to ensure every printable ASCII character appears at least once, as the way the checking is done by looping through each one requires this. If `exit` was not called in the first section (i.e. it was mangled by the removal of one of `'\01234567v`), we move on to the second, in which we must accomplish the same thing without using any of these characters. The last line is similar to the decoded first line, except that we can contract the range of the loop to save a few bytes, because we already know that all characters except for `'\01234567v` have been covered. It also has `0# $#` before it, which comments it out and prevents it from producing extraneous output if `0` or `$` were removed. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 1 byte ``` 1 ``` [Try it online!](https://tio.run/##K0otycxLNPz/H4gA "Retina – Try It Online") When all instances of the single byte (`1`) are removed, the output is `1`. Simple enough. [Answer] ## Lenguage, 216173027061157310 bytes `216173027061157310 = (144115617572598740 + 144115241762960340 + 144115194786755540) / 2`. There are `216173027061157310 - 144115617572598740` `$`s, `216173027061157310 - 144115241762960340` `#`s and `216173027061157310 - 144115194786755540` spaces. The 144115617572598740 `#`s and spaces encode the following BF program: ``` ++++++[>++++++<-]>. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwyi7SC0jW6snd7//wA) The 144115241762960340 `$`s and spaces encode the following BF program: ``` +++++++[>+++++<-]>. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwKi7cCUjW6snd7//wA) The 144115194786755540 `$`s and `#`s encode the following BF program: ``` ++++++++[>++++<-]>. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwqi7UCkjW6snd7//wA) Edit: Saved 72057832274401770 bytes thanks to @Nitrodon. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 byte ``` 0 ``` Completely different from the Retina answer. *whistles* [Try it online!](https://tio.run/##y0rNyan8/9/g/38A "Jelly – Try It Online") [Answer] # Polyglot\*, 1 byte ([awaiting confirmation](https://codegolf.stackexchange.com/questions/171789)) ``` 0 ``` [Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/3@D/fwA "Triangularity – Try It Online") (using Triangularity) \*: This works in a (rather wide) variety of languages (except for esolangs like 4, ><> and the like and some other exceptions). Identical to [the Jelly answer](https://codegolf.stackexchange.com/a/171797/59487) in source code, but the method of I/O is different – Output is via exit code. When one removes `0` from the source code, they're left with an empty program, which often doesn't error and yields exit code **0** in the majority of languages. [Answer] # [sed](https://www.gnu.org/software/sed/), 1 byte ``` ``` [Try it online!](https://tio.run/##K05N0U3PK/3/n@v/fwA "sed – Try It Online") Completely different from the Retina answer, or the Jelly answer. [Answer] # [Unary](https://esolangs.org/wiki/Unary) (non-competitive), 96 bytes ``` 00000000: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000010: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000020: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000030: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000040: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000050: 0000 0000 0101 0101 0101 0101 0101 0101 ................ ``` Here is [`xxd`](https://linux.die.net/man/1/xxd) dump. A wider definition of Unary language allows any characters in its source code. But I havn't find a compiler or interpreter which would work for this. So I marked this answer as non-competitive. If you can find one which posted before this question asked, I will link to it. [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 143 bytes ``` <\Hs+:+:PPPs\ \sM:+:+H HP+:+:PPPs++\ HsssssssM+++\ ;HssssMMMMM++\ ;o+:+:PPs++\ +:+:P+:PPP\H+P:P+: ssssMMMMMM\H sHsssMMMMM+\ Hsssss+++\ HMMMMMMs ``` [Try it online!](https://tio.run/##PYzLCcAwDEPvXsUbtB1AF4MH8LkfKOSg/XEbh0QnSTzpau/58M48AtRNN3dnSNB@rxD4LFVDwCHTnvaK1lWxDbTIsjUMqHcrC7aAEGs6b@sTg2DmBw "Gol><> – Try It Online") This contains the characters `<\Hs+:PM;o` and newline * `<` [Try it online!](https://tio.run/##PYy7CQAxDEN7r@INcguoMXgA1/eBgxTaH9/FIVEliSdd/T0f3pkBatPm7gwJ2u8VAl@lagg4ZTrSUdGGKvaJFlm2hgH1YWXDFhBiT9dtfWISzPwA "Gol><> – Try It Online") * `\` [Try it online!](https://tio.run/##PYzLDcAwCEPvrMIGaQfwBYkp@pEq5eD9RUNo45Mf2D77c9y8InZQmzZ3p9CGUwj8P6kKWDIdsE2yVFKvXMammyWop5OVNAixat9grqHejHgB "Gol><> – Try It Online") * `H` [Try it online!](https://tio.run/##RYzLDcAwCEPvrOIN0q4QiQE49yNVysH7ixRQWp@ejfE5nuPm5b4b0dBUlSbG/jJEVwSYsNQRZksMpRtVzF5ivhk0SL5ut5/XYs7Vle4T "Gol><> – Try It Online") * `s` [Try it online!](https://tio.run/##LYy7DcBACEN7VvEGlwzgBokBqPORIl2R/UUOiBueAL9zPsf9XhG7EwPDzFxcF4FC@1eACxU5NmqmcPY5uajrhCVK/akvTTeWAi2qRHw "Gol><> – Try It Online") * `+` [Try it online!](https://tio.run/##RYw9DoBQCIN3joQegIWEA3T2JzF5Q@8fBF/ULgX6lX1c28kjc4VRNSIIAV3VxOI9GKccsjyzt2oZTRRQ1iiqEiof4TCh/fz8Uz5TZt4 "Gol><> – Try It Online") * `:` [Try it online!](https://tio.run/##PYy7DQAxCEN7VmGEuwHcRGIA6vtIJ6Xw/iKE6OICYXj23b/r5RNxOqhqZnRxNlUIbB1UXcClfKQ7yrapsn2CxeUyM46cKptqDiF25u@rMiyCEQM "Gol><> – Try It Online") * `P` [Try it online!](https://tio.run/##PYzLDcAwDELvXoUN0g7AxRv43I9UKQf2l9s4ajgBenD257h1Ze5BoaEpLOSfAY1VAGHUlGOkraIPVeyLGwYtamgL8qCJa/Lf1RcnocwX "Gol><> – Try It Online") * `M` [Try it online!](https://tio.run/##PYy7DcBADEJ7r8IGlwxA6QFc5yNFusL7yznbSqgeCDjnc9x@RexGx8BQVTcxXwgK9csAE3oLaTY2LppdKlNYEyM0UbJnFM/B/4I@jHgB "Gol><> – Try It Online") * `;` [Try it online!](https://tio.run/##PYy7CQAxDEN7r@INwg2gxuABXN8HDlJof3yXmESVJJ509fd8eGceAWrT5u4MCdrvFQJfpWoIWDLdyYZG6gVObto5C6gPK5u1gBB7uU7rsQhmfg "Gol><> – Try It Online") * `o` [Try it online!](https://tio.run/##PYzLCcAwDEPvXkUbpB1AF4MH8LkfKPTg/XEbh0QnSTzpfJ/jjitzdwYampmFi4f@HhTaLAEXxpCip62idlUcZIFla@eEdSuLVacE13K@1iUHEZkf "Gol><> – Try It Online") * Newline [Try it online!](https://tio.run/##PUy5DcAwCBzoNnAyAA0SA1DnkSK5YH8RnsRX3X/O57jtct@VDANDREzVOCiI5LeAyBuMEFspTqSa3ctasRopQZKuJscHrdl3mG/Usbm/ "Gol><> – Try It Online") I wanted to solve this in a 2D language, but most 2D languages are ruled out from this challenge. Gol><> works because of the large number of operations including operations with overlapping functionality, this ensures that we can write a meaningful program with any 1 character banned. We use the standard [radiation-hardening](/questions/tagged/radiation-hardening "show questions tagged 'radiation-hardening'") technique for 2D languages here. The removal of characters causes the length of a line to change which creates a new alignment and sends the pointer down a new path untouched by the radiation. Each character gets its own line of the program and which line is run is triggered by the removal. We could possibly choose a smaller character set to work with `<\Ho;P1+` and newline should work, however the lines would be very long making this overall more costly. ]
[Question] [ Mr. Binary Counterman, son of Mr. Boolean Masker & Mrs. Even Oddify, follows in his parents’ footsteps and has a peculiar way of keeping track of the digits. When given a list of booleans, he counts the 1s and 0s separately, numbering the 1s with the odds & the 0s with the evens. For example, when he looks at `1 1 0 0 1 0` he counts: `1st odd, 2nd odd, 1st even, 2nd even, 3rd odd, 3rd even` and copies it down as `1 3 2 4 5 6` Mr. Binary Counterman thinks it looks prettier to start counting odds at 1 and evens at 2. However the pattern is more symmetric if you start counting evens at 0. You may do either. So either `1 3 2 4 5 6` or `1 3 0 2 5 4` are good given the list above. As input you may take any representation of a boolean list or binary number, the output should be the list of resulting numbers with any delimiter. (But the list elements should be separate & identifiable.) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least bytes wins. ## Test Cases ``` 1 0 1 0 1 0 1 2 3 4 5 6 1 1 1 1 1 3 5 7 0 0 0 0 2 4 6 8 0 1 1 0 0 2 1 3 4 6 0 1 1 0 0 1 0 1 1 2 1 3 4 6 5 8 7 9 0 0 1 0 0 1 1 1 2 4 1 6 8 3 5 7 0 2 1 1 1 1 1 0 0 0 1 3 5 2 4 6 ``` [Answer] # JavaScript (ES6), 29 bytes ``` a=>a.map(v=>b[v]+=2,b=[0,-1]) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQKPM1i4puixW29ZIJ8k22kBH1zBW839yfl5xfk6qXk5@ukaaRrShjoEOFMdqanJhyIIhFhkDHTDEKmMINhGvHNROXCbD1OBQgc2lOF0Pc@d/AA "JavaScript (Node.js) – Try It Online") [Answer] # [J](http://jsoftware.com/), 12 bytes ``` +2*/:<.&/:\: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tY209K1s9NT0rWKs/mtypSZn5ANlDRWMFYwUTBR0rRTSwFxDIGmALmuqYKZgrmCJpgpMAtkw1SCVZjA1BghzQMpA5pjC7DGE6zX4DwA "J – Try It Online") Explanation: Self plus twice the minimum of ascending and descending ranks. Given a boolean array `1 1 0 0 1 1 1`, ascending rank `/:@/:` and descending rank `/:@\:` are computed as follows: ``` array: 1 1 0 0 1 1 1 asc. rank: 2 3 0 1 4 5 6 desc. rank: 0 1 5 6 2 3 4 minimum: 0 1 0 1 2 3 4 ``` # [APL(Dyalog Unicode)](https://dyalog.com), 9 bytes [SBCS](https://github.com/abrudz/SBCS) ``` ⊢+2×⍋⌊⍥⍋⍒ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31dP/UdsEAwA&c=e9S1SNvo8PRHvd2Peroe9S4FMXonAQA&f=S1MwUDAEQgMFA640BBtMAtlgMQOorCFc3AAA&i=AwA&r=tryAPL&l=apl-dyalog&m=train&n=f) [Answer] # [Risky](https://github.com/Radvylf/risky), 44 bytes ``` __0+0+_0+0+__0+0+_0+0+__0+0+_0+0+__0+0+_0+?1__0+0+_0+0+__0+0+_0!-_0!_{1+_0+0_[2_{0+__{1 ``` [Try it online!](https://radvylf.github.io/risky?p=WyJfXzArMCtfMCswICsgX18wKzArXzArMCArIF9fMCswK18wKzAgKyBfXzArMCtfMCs_XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDFcbl9fMCswK18wKzAgKyBfXzArMCtfMCEtIF8gMCFfezErXzArMCBfIFsyX3swK19fezEiLCJbWzEsIDAsIDEsIDEsIDBdXSIsMF0) **How it works:** This is a really low level explanation: ``` ... + __0+0+_0+? ; the input array 1 ; map with the following pairs: ... + __0+0+_0!- ; [0, -1] _ ; map to 0!_{1+_0+0 ; range with same length _ ; map to [ ; absolute value + ; of the sum of 2_{0 ; twice the index in the range and __{1 ; the offset (0 or -1) ``` That's useless, though. Here's a better description of how this works: Risky has an operator called "map pairs" which takes an array, and maps the items according to a set of rules. The rules are arrays, starting with the item to be replaced, and with (typically) one item to map to. However, if multiple are specified, they'll be used in order. This answer generates those mappings, which look like `[[0, 2, 4, 6, ...], [1, 1, 3, 5, 7, ...]]`. It does this by mapping `[0, -1]` to `[2_{0+__{1` over a range `[0, x)`, which is essentially `(x, n) => abs(2 * x + n)`, where `x` is the number in the range and `n` is either `0` or `-1`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ,CÄḤ×ƊS_ ``` [Try it online!](https://tio.run/##y0rNyan8/1/H@XDLwx1LDk8/1hUc//9w@9FJD3fO0Iz8/z/aUEfBQEcBQcbqKIDEoAjEMwDLGUCZhjDFmAJIxiBpRJaEy4BtQbEKZgsA "Jelly – Try It Online") -2 bytes thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler) ## How it works ``` ,CÄḤ×ƊS_ - Main link. Takes a binary list B on the left C - Complement. Flip the bits of B , - Pair with B: [B, B'] Ɗ - Last 3 links as a monad f([B, B']): Ä - Cumulative sum of each Ḥ - Unhalve × - Multiply modified B by B and modified B' by B' S - Columnwise sum _ - Subtract B, elementwise ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ?J±2:T±2 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=P0qxMjpUsTI&input=WzEgMSAwIDAgMSAwXQ) * `J` is initially `-1`, * `T` is initially `0`, and, * `±` is the shortcut for `+=`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ,CỤ€⁺«/Ḥ_ ``` [Try it online!](https://tio.run/##y0rNyan8/1/H@eHuJY@a1jxq3HVotf7DHUvi/x9uPzrp4c4ZmpH//0cb6igY6CggyFgdBZAYFIF4BmA5AyjTEKYYUwDJGCSNyJJwGbAtKFYh2WKIRRMA "Jelly – Try It Online") My convoluted port of my own APL/J answer. # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` CỤỤ«ỤỤ$Ḥ_ ``` [Try it online!](https://tio.run/##y0rNyan8/9/54e4lQHRoNYRWebhjSfz/w@1HJz3cOUMz8v//aEMdBQMdBQQZq6MAEoMiEM8ALGcAZRrCFGMKIBmDpBFZEi4DtgXFKiRbDLFoAgA "Jelly – Try It Online") Small modification of caird's 10-byter port. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 6 bytes ``` η^_O·α ``` [Try it online!](https://tio.run/##yy9OTMpM/V9TVmmrpGunoGR/eF@wi8v/c9vj4v0PbT@38b@OkpLOf0MFMOQyUABDIA3io7DAJEwNTATM5zLkMoSrMgAA "05AB1E – Try It Online") ``` η # prefixes of the input ^ # XOR the first value of the input with the first prefix, second value of input with second prefix, ... _ # boolean negate O # sum each modified prefix · # double all integers α # absolute difference to the input ``` `η^_` can be replaced with `δQÅl` (equality table; lower-triangular matrix), which is a byte longer but might be shorter in some other language. ``` δQÅlO·α ``` [Try it online!](https://tio.run/##yy9OTMpM/V9TVmmrpGunoGR/eF@wi8v/c1sCD7fm@B/afm7jfx0lJZ3/hgpgyGWgAIZAGsRHYYFJmBqYCJjPZchlCFdlAAA "05AB1E – Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 28 bytes ``` $b=0,-1;$args|%{($b[$_]+=2)} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SZlv9XyXJ1kBH19BaJbEovbhGtVpDJSlaJT5W29ZIs/Z/LRcQqKmkKRgoGAKhAZgGs/8DAA "PowerShell Core – Try It Online") Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [solution](https://codegolf.stackexchange.com/a/229685/97729), thanks ! ### Initial implementation, 35 bytes ``` switch($args){0{++$e*2}1{$o++*2+1}} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SZlv9v7g8syQ5Q0MlsSi9WLPaoFpbWyVVy6jWsFolX1tby0jbsLb2fy0XEKippCkYKBgCoQGYBrP/AwA "PowerShell Core – Try It Online") [Or starting with 0 (35 bytes)](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SZlv9v7g8syQ5Q0MlsSi9WLPaoFolVVtby6jWsFolH8TQNqyt/V/LBQRqKmkKBgqGQGgApsHs/wA "PowerShell Core – Try It Online") Takes the input as a list of `0/1`'s Returns a list of integers ## Explanation ``` switch($args){ # For each argument passed as an integer 0{++$e*2} # if it is 0, output an even number, starting from 2 1{$o++*2+1}} # if it is 1, output an odd number, starting from 1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 bytes ``` ċṪ$ƤḤ+ ``` [Try it online!](https://tio.run/##y0rNyan8//9I98Odq1SOLXm4Y4n2////ow10DIHQQMcATALZsQA "Jelly – Try It Online") Basically a translation of an old version of ovs' [05AB1E answer](https://codegolf.stackexchange.com/a/229702/98955). ## Explanation ``` ċṪ$ƤḤ+ Main monadic link Ƥ Map over prefixes $ ( ċ Count the occurences of Ṫ the last item after removing it $ ) Ḥ Unhalve + Add the original list ``` [Answer] # 8086 machine code, ~~21~~ 18 bytes ``` 00000000: b0 01 b2 02 d1 eb 72 01 92 aa 40 40 72 01 92 e2 ......r...@@r... 00000010: f3 c3 .. ``` Function. ``` [bits 16] [cpu 8086] section .text ; nasm syntax ; INPUT: ; DI: destination byte array ; BX: bit pattern (little endian) ; CX: count of bits ; OUTPUT: ; stored to DI global mrbitctr mrbitctr: ; Count odd bits in AL mov al, 1 ; Count evens in DL mov dl, 2 .loop: ; Shift right BX one bit. This will put ; the lowest bit in CF. shr bx, 1 ; Was the bit set? If so, jump. jc .no_swap ; Even: swap .swap: ; Pull the old switcheroo to select evens xchg ax, dx ; Odd: don't swap .no_swap: ; Store to DI and increment stosb ; Add 2 to AL by incrementing AX twice ; Note: INC does not affect the carry flag inc ax inc ax ; swap back if even jc .no_swap_back .swap_back: xchg ax, dx .no_swap_back: ; Loop CX times. loop .loop .end: ret ``` * 3 bytes: swap twice [Answer] # [Dyalog APL](https://www.dyalog.com/), ~~24~~ 23 bytes ``` (⍵ׯ1+2×+\⍵)+N×2×+\N←~⍵ ``` The list of evens and the list of odds are generated separately and added elementwise with the `+` in the middle. Here's what it looks like with the problem's example input: ``` Evens: ⍵ The input → 1 1 0 0 1 0 ~ Negate it → 0 0 1 1 0 1 N← Let N be the negated list → 0 0 1 1 0 1 +\ Take the running sum → 0 0 1 2 2 3 2× Multiply by two → 0 0 2 4 4 6 N× Multiply by the negated list → 0 0 2 4 0 6 Odds: ⍵ The input → 1 1 0 0 1 0 +\ Take the running sum → 1 2 2 2 3 3 2× Multiply by two → 2 4 4 4 6 6 ¯1+ Subtract 1 → 1 3 3 3 5 5 ⍵× Multiply by the list → 1 3 0 0 5 0 Together: (~⍵)×2×+\~⍵ Evens → 0 0 2 4 0 6 (⍵ׯ1+2×+\⍵) Odds → 1 3 0 0 5 0 + Add elementwise → 1 3 2 4 5 6 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20TqjUe9W49PP3QekNto8PTtWOAPE1tjToQdXg6WATErlUwBEIDIASS//8DAA "APL (Dyalog Classic) – Try It Online") [Answer] # [J](http://jsoftware.com/), 27 26 25 bytes ``` <@({.-~2*#\)/.~@/:~/:&;/: ``` [Try it online!](https://tio.run/##ZY29CgIxEIR7n2JQ8DwxPxtNTleFA8HK6mo78RAbH0DIq8clMY0yTLPfzOwzTXUz4shosIIFi5XGabic06FfvLWKbjm7tkbH3nA0PN8bTu3kfnu8AILDGht4BCjGKAdbXSIk3KOrNKsQJ72AbSG2qBLKq6Eyypt/1Eu7w@4n9f1P6QM "J – Try It Online") * `/.~@/:~` Sort and group by value * `({.-~2*#\)` Create `2 4 6 ...` to the length of each group, and subtract the first element of each group from that (vectorized), so that the the 1 group becomes `1 3 5 ...` * The grouping screws up the order though, so we have to... * `/:&;/:` Resort it according to the grade up of the original input, which makes it correct again. ## [J](http://jsoftware.com/), bonus: translation of [AviFS's APL answer](https://codegolf.stackexchange.com/a/229684/15469) into J (28 bytes) ``` ([:+/**-&1 0)@,:&(2*]*+/\)-. ``` [Try it online!](https://tio.run/##bY0xC8IwEIV3f8XDoW3SJk1ik@qBIAhOTq7WSSzFxf8/xSMxi8rx4LjvvXfPuNb1jD2hRgcDYimN4@V8is2V2l5KVVkYceioapy8ybafhNJRrB735YUZDIvyiTeHDQZ4BCj6Z7HMPcZC02TiOBewzcTkKcSm1lCYTZ0/1HN6xO7L9flv4xs "J – Try It Online") Just because I liked it and wanted to see how they'd compare. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), ~~15~~ 9 bytes ``` ₌⇧⇩⇧$⇧∵d+ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%82%8C%E2%87%A7%E2%87%A9%E2%87%A7%24%E2%87%A7%E2%88%B5d%2B&inputs=%5B0%2C1%2C1%2C0%2C0%2C1%2C0%2C1%2C1%5D&header=&footer=) Me when APL port ## Explained ``` ₌⇧⇩⇧$⇧∵d+ ₌⇧⇩ # grade up input, grade down input ⇧$⇧ # grade each of those up ∵d # 2 * the minimum of those two lists + # added to the input ``` [Answer] # [Python 2](https://docs.python.org/2/), 43 bytes ``` b=[2,1] for e in input():print b[e];b[e]+=2 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8k22kjHMJYrLb9IIVUhMw@ICkpLNDStCooy80oUkqJTY61BhLYtUHG0oY6BDhTHAgA "Python 2 – Try It Online") -5 bytes and fix thanks to @xnor The program is now reusable [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, 29 bytes Takes input as space separated digits (or any other non-digit separator). ``` gsub(/\d/){($`*2+?1).count$&} ``` [Try it online!](https://tio.run/##KypNqvz/P724NElDPyZFX7NaQyVBy0jb3lBTLzm/NK9ERa32/39DBQMFKOYyVABDLgMFMOQyAPNRWFC1EDUwETCfyxCqH6z3X35BSWZ@XvF/3QIA "Ruby – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 38 bytes ``` f(h:t)=h:f[x+mod(x-h-1)2*2|x<-t] f e=e ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00jw6pE0zbDKi26Qjs3P0WjQjdD11DTSMuopsJGtySWK00h1Tb1f25iZp6CrUJBUWZeiYKKQppCtKGOoY4BEALJWK7/AA "Haskell – Try It Online") The recursion happens on “the `t`ail of the list, but with all elements `x` that have the same parity as the `h`ead incremented by 2.” Like so: ``` f [1,1,0,0,1,0] = 1 : f [3,0,0,3,0] = 1 : 3 : f [0,0,5,0] = 1 : 3 : 0 : f [2,5,2] = 1 : 3 : 0 : 2 : f [5,4] = 1 : 3 : 0 : 2 : 5 : f [4] = 1 : 3 : 0 : 2 : 5 : 4 : f [] = [1,3,0,2,5,4] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` ṢŒg2ḷ$\€ÄFị@ỤỤ$ ``` [Try it online!](https://tio.run/##y0rNyan8///hzkVHJ6UbPdyxXSXmUdOawy1uD3d3OzzcvQSIVP7//2@gYwiEBjoGYBLIBgA "Jelly – Try It Online") ``` ṢŒg2ḷ$\€ÄFị@ỤỤ$ Main Link; take a list of 0s and 1s Ṣ Sort the list Œg Group runs of equal elements € For each group $\ Cumulatively reduce by 2ḷ x => 2 (that is, all but the first element become 2) Ä Cumulative sum, vectorizing to depth 1 F Flatten ị@ Index into (reverse order) ỤỤ$ The input graded up twice ``` Grading up twice returns the permutation to index into another list to get the same ordering or something like that. I think that's how it works. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 15 bytes ``` {x+2*(<<x)&<>x} ``` [Try it online!](https://ngn.bitbucket.io/k#eJxVjl0KhDAMhN97inkSqz4kVi0uZY/jGQrLenbTNP4RCp1vkky2zy/3Y9emlH2TvvnvHIMQMGLGhB0birYnXhAejWs5kt4JizKq5Up3UF4p64Ynn2UiYn37llN3sm69806fLLcdyKtRPqL4VOztTrou4CuBDttBLIk=) A K port of [@Bubbler's J and APL solutions](https://codegolf.stackexchange.com/a/229690/75681) - don't forget to upvote it! [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~9~~ 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╜♪N·{☼►◄ ``` [Run and debug it](https://staxlang.xyz/#p=bd0d4efa7b0f1011&i=%5B0,+1,+0,+1,+0,+1%5D%0A%5B0,+0,+0,+0%5D%0A%5B1,+1,+1,+1%5D%0A%5B1,+0,+0,+1,+1%5D%0A%5B1,+0,+0,+1,+1,+0,+1,+0,+0%5D%0A%5B1,+1,+0,+1,+1,+0,+0,+0%5D%0A%5B1%5D%0A%5B0%5D%0A%5B0,+0,+0,+1,+1,+1%5D%0A&m=2) Inspired by Arnauld's idea. 0-indexed, takes the bits flipped. ## Explanation ``` AEsF{Q2+}& AEs swap the input with [1,0] F foreach i: { }& modify the element at i in 2,1 Q print without popping 2+ add 2 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 29 bytes ``` (a=0@-1;a[[#~Mod~2]]+=2&/@#)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XyPR1sBB19A6MTpauc43P6XOKDZW29ZITd9BWVPtf0BRZl5JtLKuXZqDcqxaXXByYl5dNVe1oY6BDhTX6oC4YAhiGuiAIYRpCFaEyoHqgyuGCcKEwOYhDIWYxlX7HwA "Wolfram Language (Mathematica) – Try It Online") Boring answer. Mathematica's `+=` etc. operators have different precedence than assignment `=` etc. operators. This gives them higher precedence than `&`, so unlike `=` expressions they don't need to be parenthesized on the left side of `&`. (`//=`, introduced in 12.2, is slightly different from both aforementioned groups). [Answer] # [C (clang)](http://clang.llvm.org/), 52 bytes -1 thanks to [@AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco), by using clang instead of gcc. ``` f(a,l)int*a;{for(int b[]={0,-1};l--;)*a++=b[*a]+=2;} ``` [Try it online!](https://tio.run/##jZNdb4MgFIbv/RXGZIkfmBRU1DB@SdcL2tnFpHONsGRb4293B7Trob2Z5iTwwPtyDh@H/HBSw9s8H2NFTkk/mFSJy/FjjKEZ7rc7edmQnE7ilOciSVWWyf02VbtMMjHNdo7ptLGT01CNo/omoWt3X@fuYLpX1w11/9MlwSUI4bP9XrgmrLlI3PjK7NJyI/pnC0WfZUl4HkF0jKOn1zAiyzLbfrcKzp9Gx1H0b/k1s3uHl8F6TEFgE3xX/RDjjA21W0HJhqwxib@xcR1jpCAlqQhHY5pKfusZtsx0P3ZYeQHqGquZLJG6WI7D/VjtOIO1OWmwuvDU5aKmrgJPXy566vL3si9lhRwqz2HdCa@OynOCahpSkxY7VrJFjvxa0dXxzo9fK6O2tsf94bJBbrVzw3pHGFbUkiJF4/YdKx6IbjxFezvBh3Nob6fI7neytffAdd2DMZTAvYGbT9dLuFAGFEIzjxZAIXTh0RIohC49WgGF0JVHOVAIzT1aA4XQtUcboBC68WgLFEK39pHMvw "C (clang) – Try It Online") --- # [C (gcc)](https://gcc.gnu.org/), 53 bytes ``` f(a,l)int*a;{for(int b[]={0,-1};l--;a++)*a=b[*a]+=2;} ``` [Try it online!](https://tio.run/##jZPfboMgFMbvfQpjssRaTAoqahhP0vWCWtuYdF0jLNnW@OzugLoe2ptpTgI/@L7D4U@TnppmHI@xIudVdzGJErfjRx9DM9xvd/K2ISkdxDlNhVqvV4mS@22idmvJxDDaSabVxs5OQtX36puErt1@XdvGtAfXDXX3066CWxDCZ/udcE1IOknc@MxsbrkR3auFooOc4bUH0TGOXg5hRKY02243C66fRsdR9G/5srJHh7eL9RiCwC7wXXWXGK/YULsXlGzIHIP4G@vnMUYykpOCcDSmqeT3nmHTTPdjh5lnoC6xmskcqbPpPNyP1Y4zyM1JhdWZp84nNXUVePp80lO3fm/1uSyQQ@E5zDvh1VF4TlBNRUpSY8dC1siRLxUtjg9@fKmM2tqe94fLCrmVzg3rHWFYUUqKFJXbd6x4IrryFPX9BJ/Oob6fInvcydreA9d1D8ZQAvcGbj6dL@FEGVAIzTyaAYXQmUdzoBA692gBFEIXHuVAITT3aAkUQpcerYBC6MqjNVAIXdtHMv4C "C (gcc) – Try It Online") [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 21 bytes ``` *>>.&{(%.{$_}+=2)-$_} ``` [Try it online!](https://tio.run/##TU7LDoJADLz3K@aAPFQIuyDgAX7FYISEiGBAYwjh27Hs4iOT3abT6XTuRVdH822AWSKdt1nmmaO98UbjNO1S6bhc57LtYNdVU/QO3AxG1exhtM8H/@c6b66pZWGkPh9Q2jz0Xm13YWmaKRVNs4CP9ZGARIAQB0TEjQLXgImYyIcCSVZESBZCqNWFEmox@iNXV/Ebsk2CGEdt9RFpSciVTb@3SHICxhpDX9ZR1P03 "Perl 6 – Try It Online") Maps each element to the index into an anonymous hash, incrementing that value by two (initially zero), and finally subtracting the element itself to distinguish between odd and even.This could also be extended to values beyond 0 and 1 simply by changing the `2` to another number. [Answer] # [Julia](http://julialang.org/), ~~33~~ 30 bytes ``` f(x,y=[0,-1])=x.|>i->y[i+1]+=2 ``` [Try it online!](https://tio.run/##VU7RCsMgDHzPV@RRqR1m7/ZHxIfBKjiKG20GFvrvrnV1wxyBu@Ny5PGewo1Szl4ktRqrVU9OmnTZhtAPqw0duc5cM48LL2hQgCXUeK5Thyw4qMaCL6USasV59wtXs1ql719a2ySAf87IGCKWRwD3ec0h8hQFy0b63WgdCWO85w8 "Julia 1.0 – Try It Online") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 42 bytes ``` d[1]=1{for(;a++<NF;d[b]+=2)$a=+d[b=$a%2]}1 ``` [Try it online!](https://tio.run/##SyzP/v8/Jdow1tawOi2/SMM6UVvbxs/NOiU6KVbb1khTJdFWG8i2VUlUNYqtNfz/30DBEAgNFAzAJJANAA "AWK – Try It Online") So this one is one test with a codeblock, and a naked `1` to print all the commandline arguments. It replaces each commandline argument with the appropriate even/odd counter in the codeblock. The "test" for the codeblock is always truthy and it just used to initialize the "odd" counter to `1`. ``` d[1]=1{ } ``` The code block runs through each commandline argument, ``` for(;a++<NF; ) ``` Then sets that argument to the current value of the even/odd counter with: ``` $a=+d[b=$a%2] ``` And at the end of the loop, increments the current counter by 2 in preparation for the next match. ``` d[b]+=2 ``` Once that's done, it just need to print out all the arguments. ``` 1 ``` [Answer] # [Zsh](http://www.zsh.org), 23 bytes ``` for x echo $[x+a$x++*2] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwdbi1BIFAwVDIDQA02D20tKSNF2L7Wn5RQoVXKnJGfkKKtEV2okqFdraWkaxENkFUApKAwA) Starts even numbers at 0. Explanation: * `for x`: for each `$x` in the input, * `$[]`: arithmetic expansion * `++`: increment and return original value * `a$x`: the variable named `a0` or `a1` (which correspond to the number of 0s and 1s seen so far) * `x+*2`: double and add `x` to get the correct value * `echo` : print (can't use `<<<` because the mutation wouldn't work in the subshell it creates) [Answer] # [Desmos](https://desmos.com/calculator), 64 bytes ``` a(l)=\sum_{n=1}^{[1...length(l)]}l[n] b=1-l f(l)=2ba(b)+2la(l)-l ``` Just implements the strategy shown in [AviFS's Dyalog APL answer](https://codegolf.stackexchange.com/a/229684/96039). [Try It On Desmos!](https://www.desmos.com/calculator/zfuptadr5z) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/4ekzmudvzs) ## Explanation: `a(l)=\sum_{n=1}^{[1...length(l)]}l[n]`: Function that takes in a list \$l\$ and returns the running total of \$l\$. `b=1-l`: Variable that stores the inputted list, but with each bit flipped. `f(l)=2ba(b)+2la(l)-l`: Function that takes in a list of bits \$l\$ and outputs the correct answer, based on the strategy mentioned above. [Answer] # [R](https://www.r-project.org/), 42 bytes ``` function(x,y=seq(x)*2){x[x]=y-1;x[!x]=y;x} ``` [Try it online!](https://tio.run/##jZFhC4IwEIa/@yuu9WULA6emhuyXSB9CDASbpRMm0W@30wxiGY6DcQye9@69txnyupOqaK5nKYZLJ3NV1pJqtxdtcaea7Xz20Jk@iX7PU51txi7Vzy@MtqpRdUmLauzaW1UqSjhw8LDwJS4BwhgTgjNnFZuQH2zLwYcAQjhA5DgWs7FMgQDheBX2prWN6T5OjiCxgGffJs6n5SN7gfkK/I8QWkkghqOVnY/gglyIn2jM9jYGvp6EkYFldAsJvOObchhe "R – Try It Online") *-8 bytes thanks to [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)* Takes input as booleans: `TRUE`(`1`) and `FALSE`(`0`). Straightforward approach, but takes advantage of truncating the replacement to the length of items being replaced. --- Different approach: ### [R](https://www.r-project.org/), 47 bytes ``` function(x,n=0:-1)for(i in x)show(n[i]<-n[i]+2) ``` [Try it online!](https://tio.run/##lZFNCoMwEIX3nmLIKkEFk/rXUk/SdiGiNNAmJUbq7W1MFQoqjQwMQ8J8zHtPDZXshK7VsxTF0HSi0lwK3AeiiE4hJY1UmAMX0JP2Lt9YXPjtHI7dZ@RnF7daaclx/Rin9vXgGiMKFCJTpqMAASKE@JR4VWn/DsAghgTSq0DE8/6yLGeDxQxtD8vW6k0JZE6MyCpb3jJqSiF3ZEwOrVCoVZTu40wO0W2e0ZdDBkdnjTN3nRqbd6N2j29Liltmy7R2ZL2e1TdvNvs8fAA "R – Try It Online") Takes input incremented by 1: `2` (for `1`) and `1` (for `0`). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 43 bytes ``` (.)(?<=((\1)|.)*(1)?) $#3$*2$4¶ 2 11 1+ $.& ``` [Try it online!](https://tio.run/##K0otycxL/P9fQ09Tw97GVkMjxlCzRk9TS8NQ016TS0XZWEXLSMXk0DYuIy5DQy5DbS4VPbX//w0NQBAoAhQzAAIuA0NDGAmUAQmCWCAGlyFIGVANAA "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input as a string of bits. 1-indexed. Explanation: ``` (.)(?<=((\1)|.)*(1)?) ``` For each bit, count the number of preceding identical bits. If the current bit is `1` then count it separately otherwise include the current bit in the count. ``` $#3$*2$4¶ ``` Record a `2` for each duplicate plus one extra for a `1` bit. ``` 2 11 ``` Convert to unary. ``` 1+ $.& ``` Convert the sum back to decimal. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` IEθ⁺Iι⊗№…θκι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQKNQRyEgp7QYIpCpqaPgkl@alJOaouGcXwpSV5mck@qckQ9WmA2UztQEA@v//w0NDAwNDYDkf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string of bits. 0-indexed. Explanation: ``` θ Input string E Map over characters ι Current character I Cast to integer ⁺ Plus ⊗ Doubled № Count of ι Current character in θ Input string … Truncated to length κ Current index I Cast to string Implicitly print on separate lines ``` [Answer] # [Perl 5](https://www.perl.org/) (`-ap`), 27 bytes ``` $_+=$x[$_]++*2for@F;$_="@F" ``` [Try it online!](https://tio.run/##K0gtyjH9/18lXttWpSJaJT5WW1vLKC2/yMHNWiXeVsnBTen/fwMFAwVDBTD5L7@gJDM/r/i/bmIBAA "Perl 5 – Try It Online") ]
[Question] [ Given an input string only containing the characters `A-Z`, `a-z`, and spaces, remove all occurrences of the uppercase and lowercase versions of the first character of the string (if the first character is `A` remove all `A`s and `a`s, if the first character is (space) remove all spaces), and print the output. Example cases: * `Testing Testing One Two Three` -> `esing esing One wo hree` * `Programming Puzzles and Code Golf` -> `rogramming uzzles and Code Golf` * `How much wood would a woodchuck chuck if a woodchuck could chuck wood` -> `ow muc wood would a woodcuck cuck if a woodcuck could cuck wood` * `{space}hello world` -> `helloworld` * `welcome to WATER WORLD` -> `elcome to ATER ORLD` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins! Notes: * Input will always be 2 or more valid characters. * Output will never be an empty string. [Answer] # Perl, 13 bytes ``` #!perl -p /./,s/$&//gi ``` Counting the shebang as one, input is taken from stdin. --- **Sample Usage** ``` $ echo Testing Testing One Two Three | perl remove-first.pl esing esing One wo hree $ echo \ Testing Testing One Two Three | perl primo-remove.pl TestingTestingOneTwoThree ``` [Answer] # brainfuck, 219 bytes ``` +[+[>+<+<]>],[<+<+>>-]>[<<[->]>[<]>-]++++[<++++++++>-]<<[[-]----[>-<----]>-<<[>+>+<<-]<,[[>+>>>+>>+>+<<<<<<<-]>>[<<+>>-]<<[>->+<<-]>[[-]+<]>[>]<<[>>+<<-]>>[<-<+>>-]<[[-]+>]>>[<]<<<<[>>>+<<<-]>>>-[>>.<<-]>>>[[-]<]<<<<<,] ``` (Requires tape that either allows the pointer to go to the negatives or loops to the end if it tries. Also requires `,` to return 0 at EOF. In my experience, most interpreters meet these requirements by default.) This actually turned out to be pretty easy! I wouldn't be surprised if it's golfable (I have some idea of where there might be wasted bytes but I'm not super sure if it'll pan out). Still, getting it work wasn't really a challenge at all. This code treats everything with an ASCII value below 97 as an uppercase character. If the first character is space, it'll try to remove any occurrences of a "lowercase space" (i.e. `chr(32+32)`, i.e. `@`) from the string. This is okay, because only letters and spaces will ever be present. **With comments:** ``` to make comments shorter: everywhere it says "fc" means "first character" #################################### GET FC #################################### +[+[>+<+<]>] shortest way to get 96 any number above 89 and less than 97 would work because this is only for figuring out if the first character is capital ,[<+<+>>-] create two copies of the first character ### current tape: | fc | fc | 000 | 096 | ### ### pointer: ^ ### ########################### FIND MAX(FC MINUS 96; 0) ########################### >[ 96 times: << go to the cell with the first char [->] if not 0: sub one and move right ### current tape: | fc | char being worked on | 000 | 096 | ### ### pointer: ^ OR ^ ### >[<]> collapse the wavefunction; sync the branches -] ### current tape: | fc | fc is lowercase ? nonzero : zero | 000 | 000 | ### ### pointer: ^ ### ############################# GET BOTH CASES OF FC ############################# ++++[<++++++++>-] get 32 (add to uppercase character to get lowercase) <<[ if the character is already lowercase: [-] clear the lowercase flag ----[>-<----]>- sub 64 from the cell with 32 <] <[>+>+<<-] add fc to the 32 or minus 32 to get both cases ### current tape: | 000 | fc | other case of fc | ### ### pointer: ^ ### ###################### LOOP THROUGH REMAINING CHARACTERS ####################### <,[ for each character: [>+>>>+>>+>+<<<<<<<-] make four copies (only 3 are strictly needed; 4th will resync a branch) >> go to the first case of fc [<<+>>-]<<[>->+<<-] subtract one case of fc from one copy >[[-]+<] if the result is nonzero set it to 1 >[>]<< go to the other case of fc (and resync branches) [>>+<<-]>>[<-<+>>-] subtract other case of fc from other copy <[[-]+>] if the result is nonzero set it to 1 >>[<] resync branches using extra copy <<<<[>>>+<<<-]>>> add results together - subtract 1 if the character exactly matched either case: 1 plus 0 minus 1 = 0 if the character exactly matched neither case: 1 plus 1 minus 1 = 1 if the character exactly matched both cases: impossible [ if the result is 1: >>.<< output character - set cell to 0 to kill loop ] >>>[[-]<] clean up remaining copies <<<<<, get next character; or end loop if done ] ``` [Answer] # CJam, 8 bytes ``` q(_32^+- ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q(_32%5E%2B-&input=Testing%20Testing%20One%20Two%20Three). ### How it works ``` q e# Read all input from STDIN. ( e# Shift out the first character. _32^ e# Push a copy and XOR its character code with 32. e# For a letter, this swaps its case. e# For a space, this pushes a null byte. + e# Concatenate these two characters. - e# Remove all occurrences of both from the input string. ``` [Answer] # Pyth, 7 bytes ``` -zrBhz2 ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?test_suite=0&code=-zrBhz2&test_suite_input=Testing%20Testing%20One%20Two%20Three%0AProgramming%20Puzzles%20and%20Code%20Golf%0AHow%20much%20wood%20would%20a%20woodchuck%20chuck%20if%20a%20woodchuck%20could%20chuck%20wood&input=Testing%20Testing%20One%20Two%20Three) or [Test Suite](http://pyth.herokuapp.com/?test_suite=1&code=-zrBhz2&test_suite_input=Testing%20Testing%20One%20Two%20Three%0AProgramming%20Puzzles%20and%20Code%20Golf%0AHow%20much%20wood%20would%20a%20woodchuck%20chuck%20if%20a%20woodchuck%20could%20chuck%20wood&input=Testing%20Testing%20One%20Two%20Three) Nice. The new bifurcate operator (only 8 days old) helps here to save one char. I think this is the first code, that uses this feature. ### Explanation ``` -zrBhz2 implicit: z = input string hz take the first character of z rB 2 B generates a list, containing the original char and the result of r.2 applied to the char, which swaps the case -z remove these two chars from z and print the result ``` [Answer] # Pyth, 8 bytes ``` -zr*2hz3 ``` [Try it online](https://pyth.herokuapp.com/?code=-zr%2A2hz3&input=Testing%20Testing%20One%20Two%20Three&debug=0) Uses Pyth's version of python's `str.title` to convert a string of the first letter twice into the form `"<Upper><Lower>"`. Then it removes each element from the input that is in that string. Spaces work fine because they are unaffected by `str.title`. [Answer] # MATLAB, 28 bytes ``` @(S)S(lower(S)~=lower(S(1))) ``` [Answer] ## JavaScript (ES6), ~~38~~ 36 bytes This does not depend on the [`flags` parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) which is Mozilla-specific. ``` f=x=>x.replace(RegExp(x[0],'gi'),'') ``` ## CoffeeScript, ~~39~~ 37 bytes For once it's shorter in JS than CoffeeScript! ``` f=(x)->x.replace RegExp(x[0],'gi'),'' ``` [Answer] ## PHP, 41 bytes Takes one [command-line argument](https://php.net/manual/en/reserved.variables.argv.php). Short open tags need to be enabled for PHP < 5.4. ``` <?=str_ireplace($argv[1][0],'',$argv[1]); ``` [Answer] # Perl, 27 bytes This is a complete program, although it's just based on 2 regexes that could probably copied into a Retina program to save bytes on I/O. ``` $_=<>;m/(.)/;s/$1//gi;print ``` Edit: Looks like this has already been beaten with somebody using the `-p` option. Oh, and using `$&` instead of `$1`. [Answer] ## [Minkolang 0.9](https://github.com/elendiastarman/Minkolang), ~~23~~ 33 bytes No way this will win but eh, it's fun! ``` " Z"od0c`1c*-$I[odd0c`1c*-2c=?O]. ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=o%24I%5Bodd%22Z%22%6048**-0c%3D%3FO%5D.&input=How%20much%20wood%20would%20a%20woodchuck%20chuck%20if%20a%20woodchuck%20could%20chuck%20wood) ### Explanation ``` " Z" Makes it easier to uppercase od Take first character of input and duplicate 0c`1c*- Uppercase if needed $I[ ] Loop over the input odd Take character from input and duplicate twice 0c`1c*- If it's lowercase, uppercase it. 0c=? Check to see if it's equal to first character O If not, output as character . Exit ``` (This might fail in some edge cases, like if the first character is a symbol.) [Answer] # [TECO](https://en.wikipedia.org/wiki/TECO_(text_editor)), ~~15~~ 14 bytes Editing text? When in doubt, use the Text Editor and COrrecter! After much trial-and-error (mostly error), I think this is the shortest generic TECO program that will do the job. ``` 0,1XA<S^EQA$-D> ``` Or, in human-readable form ``` 0,1XA ! Read the first character of the string into the text area of ! ! Q-buffer A. ! < ! Loop, ! S^EQA$ ! searching for the text in Q-buffer A in either lowercase or ! ! uppercase, ! -D ! and deleting it, ! > ! until the search fails. ! ``` `$` represents the escape key, and `^E` represents the sequence `CTRL`+`E`. Depending on the flavor of TECO you're using, it may recognize these ASCII substitutions, or it may not. According to the manual, some dialects of TECO accept this 13-byte version (using a find-and-delete command instead of separate "find" and "delete" commands) instead: ``` 0,1XA<FD^EQA$> ``` [Answer] # Pip, 8 bytes ``` aR-Xa@0x ``` Takes the string as a command-line argument (will need to be quoted if it contains spaces). Explanation: ``` a gets cmdline arg; x is "" (implicit) a@0 First character of a X Convert to regex - Make regex case-insensitive aR x Replace all matches of that regex in a with empty string Autoprint (implicit) ``` This solution has the extra bonus of working on strings containing *any* printable ASCII characters. (The `X` operator backslash-escapes anything that's not alphanumeric.) [Answer] ## Python, 66 char ``` a=raw_input() print a.replace(a[0],'').replace(a[0].swapcase(),'') ``` [Answer] # Julia, 34 bytes ``` s->replace(s,Regex(s[1:1],"i"),"") ``` This creates an unnamed function that accepts a string and returns a string. It constructs a case-insensitive regular expression from the first character in the input and replaces all occurrences of that with an empty string. [Answer] # Python 2, 43 ``` lambda s:s.translate(None,(s[0]*2).title()) ``` This is somewhat based on my Pyth answer, but it's also related to some comments from ThomasKwa and xnor from [here](https://codegolf.stackexchange.com/questions/61618/remove-all-occurrences-of-the-first-letter-of-a-string-from-the-entire-string?page=1&tab=votes#comment148536_61626). Mostly posting because I wanted this answer to exist. [Answer] # Mathematica, 47 bytes ``` StringDelete[#,#~StringTake~1,IgnoreCase->1>0]& ``` [Answer] # R, 43 bytes ``` cat(gsub(substr(s,1,1),"",s<-readline(),T)) ``` This is a full program that reads a line from STDIN and writes the modified result to STDOUT. Ungolfed: ``` # Read a line from STDIN s <- readline() # Replace all occurrences of the first character with an empty # string, ignoring case r <- gsub(substr(s, 1, 1), "", s, ignore.case = TRUE) # Write the result to STDOUT cat(r) ``` [Answer] # Ruby, 25 bytes Anonymous function: ``` ->s{s.gsub /#{s[0]}/i,""} ``` Full prgram, 29 bytes: ``` puts gets.gsub /#{$_[0]}/i,"" ``` [Answer] # Python, 61 bytes (way too many) ``` lambda x:"".join(map(lambda y:(y.lower()!=x[0].lower())*y,x)) ``` I imagine there is a better way to go about doing this, but I can't seem to find it. Any ideas on removing the `"".join(...)`? [Answer] # [Ouroboros](https://github.com/dloscutoff/Esolangs/tree/master/Ouroboros), 61 bytes Hey, it's shorter than C++! Ha. ``` i..91<\64>*32*+m1( )L!34*.(;Si.1+!24*(Y.@@.@=@.@32-=\@+2*.(yo ``` In Ouroboros, each line of the program represents a snake with its tail in its mouth. Control flow is accomplished by eating or regurgitating sections of tail, with a shared stack to synchronize between snakes. ### Snake 1 `i.` reads a character from input and duplicates it. `.91<\64>*32*` pushes `32` if the character was an uppercase letter, `0` otherwise. `+`ing that to the character converts uppercase letters to lowercase while leaving lowercase letters and spaces unchanged. All this has been taking place on snake 1's stack, so we now push the value to the shared stack (`m`) for snake 2 to process. Finally, `1(` eats the last character of snake 1's tail. Since that's where the instruction pointer is, the snake dies. ### Snake 2 `)` has no effect the first time through. `L!34*` pushes `34` if the shared stack is empty, `0` otherwise. We then `.` dup and `(` eat that many characters. * If the shared stack was empty, this puts the end of the snake right after the `(` we just executed. Therefore, control loops back to the beginning of the line, where `)` regurgitates the characters we just ate (having previously pushed an extra copy of `34`) and repeat the stack-length test. * If the shared stack was not empty, no characters are eaten, ';' drops the extra `0`, and execution continues: `Si` switches to the shared stack and inputs another character. `.1+!24*` pushes `24` if that character was -1 / EOF, `0` otherwise. On EOF, `(` swallows 24 characters--including the IP--and the snake dies. Otherwise, execution continues. `Y` yanks a copy of the top of the shared stack (the character we just read) to snake 2's own stack for future use. Then `.@@.@=@.@32-=\@+2*` calculates whether the new character is equal to the first character or to the first character minus 32, pushing `2` if so and `0` if not. We `.` duplicate and `(` eat that many characters: * If the characters matched, we go straight back to the head of the snake, where `(` regurgitates the 2 characters we just ate and execution proceeds with the next character. * If not, we `y`ank the character back from snake 2's stack, `o`utput it, and then loop. ### See it in action ``` // Define Stack class function Stack() { this.stack = []; this.length = 0; } Stack.prototype.push = function(item) { this.stack.push(item); this.length++; } Stack.prototype.pop = function() { var result = 0; if (this.length > 0) { result = this.stack.pop(); this.length--; } return result; } Stack.prototype.top = function() { var result = 0; if (this.length > 0) { result = this.stack[this.length - 1]; } return result; } Stack.prototype.toString = function() { return "" + this.stack; } // Define Snake class function Snake(code) { this.code = code; this.length = this.code.length; this.ip = 0; this.ownStack = new Stack(); this.currStack = this.ownStack; this.alive = true; this.wait = 0; this.partialString = this.partialNumber = null; } Snake.prototype.step = function() { if (!this.alive) { return null; } if (this.wait > 0) { this.wait--; return null; } var instruction = this.code.charAt(this.ip); var output = null; if (this.partialString !== null) { // We're in the middle of a double-quoted string if (instruction == '"') { // Close the string and push its character codes in reverse order for (var i = this.partialString.length - 1; i >= 0; i--) { this.currStack.push(this.partialString.charCodeAt(i)); } this.partialString = null; } else { this.partialString += instruction; } } else if (instruction == '"') { this.partialString = ""; } else if ("0" <= instruction && instruction <= "9") { if (this.partialNumber !== null) { this.partialNumber = this.partialNumber + instruction; // NB: concatenation! } else { this.partialNumber = instruction; } next = this.code.charAt((this.ip + 1) % this.length); if (next < "0" || "9" < next) { // Next instruction is non-numeric, so end number and push it this.currStack.push(+this.partialNumber); this.partialNumber = null; } } else if ("a" <= instruction && instruction <= "f") { // a-f push numbers 10 through 15 var value = instruction.charCodeAt(0) - 87; this.currStack.push(value); } else if (instruction == "$") { // Toggle the current stack if (this.currStack === this.ownStack) { this.currStack = this.program.sharedStack; } else { this.currStack = this.ownStack; } } else if (instruction == "s") { this.currStack = this.ownStack; } else if (instruction == "S") { this.currStack = this.program.sharedStack; } else if (instruction == "l") { this.currStack.push(this.ownStack.length); } else if (instruction == "L") { this.currStack.push(this.program.sharedStack.length); } else if (instruction == ".") { var item = this.currStack.pop(); this.currStack.push(item); this.currStack.push(item); } else if (instruction == "m") { var item = this.ownStack.pop(); this.program.sharedStack.push(item); } else if (instruction == "M") { var item = this.program.sharedStack.pop(); this.ownStack.push(item); } else if (instruction == "y") { var item = this.ownStack.top(); this.program.sharedStack.push(item); } else if (instruction == "Y") { var item = this.program.sharedStack.top(); this.ownStack.push(item); } else if (instruction == "\\") { var top = this.currStack.pop(); var next = this.currStack.pop() this.currStack.push(top); this.currStack.push(next); } else if (instruction == "@") { var c = this.currStack.pop(); var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(c); this.currStack.push(a); this.currStack.push(b); } else if (instruction == ";") { this.currStack.pop(); } else if (instruction == "+") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(a + b); } else if (instruction == "-") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(a - b); } else if (instruction == "*") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(a * b); } else if (instruction == "/") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(a / b); } else if (instruction == "%") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(a % b); } else if (instruction == "_") { this.currStack.push(-this.currStack.pop()); } else if (instruction == "I") { var value = this.currStack.pop(); if (value < 0) { this.currStack.push(Math.ceil(value)); } else { this.currStack.push(Math.floor(value)); } } else if (instruction == ">") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(+(a > b)); } else if (instruction == "<") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(+(a < b)); } else if (instruction == "=") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(+(a == b)); } else if (instruction == "!") { this.currStack.push(+!this.currStack.pop()); } else if (instruction == "?") { this.currStack.push(Math.random()); } else if (instruction == "n") { output = "" + this.currStack.pop(); } else if (instruction == "o") { output = String.fromCharCode(this.currStack.pop()); } else if (instruction == "r") { var input = this.program.io.getNumber(); this.currStack.push(input); } else if (instruction == "i") { var input = this.program.io.getChar(); this.currStack.push(input); } else if (instruction == "(") { this.length -= Math.floor(this.currStack.pop()); this.length = Math.max(this.length, 0); } else if (instruction == ")") { this.length += Math.floor(this.currStack.pop()); this.length = Math.min(this.length, this.code.length); } else if (instruction == "w") { this.wait = this.currStack.pop(); } // Any instruction not covered by the above cases is ignored if (this.ip >= this.length) { // We've swallowed the IP, so this snake dies this.alive = false; this.program.snakesLiving--; } else { // Increment IP and loop if appropriate this.ip = (this.ip + 1) % this.length; } return output; } // Define Program class function Program(source, speed, io) { this.sharedStack = new Stack(); this.snakes = source.split(/\r?\n/).map(function(snakeCode) { var snake = new Snake(snakeCode); snake.program = this; snake.sharedStack = this.sharedStack; return snake; }.bind(this)); this.snakesLiving = this.snakes.length; this.io = io; this.speed = speed || 10; this.halting = false; } Program.prototype.run = function() { if (this.snakesLiving) { this.step(); this.timeout = window.setTimeout(this.run.bind(this), 1000 / this.speed); } } Program.prototype.step = function() { for (var s = 0; s < this.snakes.length; s++) { var output = this.snakes[s].step(); if (output) { this.io.print(output); } } } Program.prototype.halt = function() { window.clearTimeout(this.timeout); } var ioFunctions = { print: function(item) { var stdout = document.getElementById('stdout'); stdout.value += "" + item; }, getChar: function() { if (inputData) { var inputChar = inputData[0]; inputData = inputData.slice(1); return inputChar.charCodeAt(0); } else { return -1; } }, getNumber: function() { while (inputData && (inputData[0] < "0" || "9" < inputData[0])) { inputData = inputData.slice(1); } if (inputData) { var inputNumber = inputData.match(/\d+/)[0]; inputData = inputData.slice(inputNumber.length); return +inputNumber; } else { return -1; } } }; var program = null; var inputData = null; function resetProgram() { var stdout = document.getElementById('stdout'); stdout.value = null; if (program !== null) { program.halt(); } program = null; inputData = null; } function initProgram() { var source = document.getElementById('source'), stepsPerSecond = document.getElementById('steps-per-second'), stdin = document.getElementById('stdin'); program = new Program(source.value, +stepsPerSecond.innerHTML, ioFunctions); inputData = stdin.value; } function runBtnClick() { if (program === null || program.snakesLiving == 0) { resetProgram(); initProgram(); } else { program.halt(); var stepsPerSecond = document.getElementById('steps-per-second'); program.speed = +stepsPerSecond.innerHTML; } program.run(); } function stepBtnClick() { if (program === null) { initProgram(); } else { program.halt(); } program.step(); } ``` ``` .container { width: 100%; } .so-box { font-family: 'Helvetica Neue', Arial, sans-serif; font-weight: bold; color: #fff; text-align: center; padding: .3em .7em; font-size: 1em; line-height: 1.1; border: 1px solid #c47b07; -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset; text-shadow: 0 0 2px rgba(0, 0, 0, 0.5); background: #f88912; box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset; } .control { display: inline-block; border-radius: 6px; float: left; margin-right: 25px; cursor: pointer; } .option { padding: 10px 20px; margin-right: 25px; float: left; } h1 { text-align: center; font-family: Georgia, 'Times New Roman', serif; } a { text-decoration: none; } input, textarea { box-sizing: border-box; } textarea { display: block; white-space: pre; overflow: auto; height: 40px; width: 100%; max-width: 100%; min-height: 25px; } span[contenteditable] { padding: 2px 6px; background: #cc7801; color: #fff; } #stdout-container, #stdin-container { height: auto; padding: 6px 0; } #reset { float: right; } #source-display-wrapper { display: none; width: 100%; height: 100%; overflow: auto; border: 1px solid black; box-sizing: border-box; } #source-display { font-family: monospace; white-space: pre; padding: 2px; } .activeToken { background: #f88912; } .clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } .clearfix { display: inline-block; } * html .clearfix { height: 1%; } .clearfix { display: block; } ``` ``` <!-- Designed and written 2015 by D. Loscutoff Much of the HTML and CSS was taken from this Befunge interpreter by Ingo Bürk: http://codegolf.stackexchange.com/a/40331/16766 --> <div class="container"> <textarea id="source" placeholder="Enter your program here" wrap="off">i..96<\64>*32*+m1( )L!34*.(;Si.1+!24*(Y.@@.@=@.@32-=\@+2*.(yo</textarea> <div id="source-display-wrapper"><div id="source-display"></div></div></div><div id="stdin-container" class="container"> <textarea id="stdin" placeholder="Input" wrap="off">Testing Testing One Two Three</textarea> </div><div id="controls-container" class="container clearfix"><input type="button" id="run" class="control so-box" value="Run" onclick="runBtnClick()" /><input type="button" id="pause" class="control so-box" value="Pause" onclick="program.halt()" /><input type="button" id="step" class="control so-box" value="Step" onclick="stepBtnClick()" /><input type="button" id="reset" class="control so-box" value="Reset" onclick="resetProgram()" /></div><div id="stdout-container" class="container"><textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea></div><div id="options-container" class="container"><div class="option so-box">Steps per Second: <span id="steps-per-second" contenteditable>1000</span></div></div> ``` [Answer] # C, 60 bytes `n,c,d;main(){for(;read(0,&c-n,1);n=2)d-c&31&&n&&putchar(d);}` Edit: Fixed a bug which caused a null byte to be printed at the beginning [Answer] # Vim, 30 Keystrokes Sorry to unearth, but i don't see any Vim answer D: ``` If<Right>xh@x.<Esc>"xy07|@x2|~0"xd7|@x0x ``` Explanation: 1. `If<Right>xh@x.<Esc>` Write a (recursive) macro around the first character Moving left (`h`) is needed to stay at the left of the next unread character 2. `"xy0` Copy the macro in the register `x` 3. `7|` Move to the 7th char 4. `@x` Run the macro from `x` 5. `2|~` Switch the case of the first char (actually at the 2nd position) 6. `0"xd7|` Cut the macro in the register `x` 7. `@x` Run the macro from `x` 8. `0x` Remove the place-holder `.` [Answer] # [Zsh](https://www.zsh.org/)\*, 21 bytes ``` <<<${1//(#i)${1:0:1}} ``` [Try it online!](https://tio.run/##VY49y8JAEIR7f8UQLbRSW0kj7ytaCIoeWMe7TS64yUpyIRLJbz/zgYXN7Myzw7JNaX1JTp4O9HKUGzIJy30SzxdvH4bh7L1eLufTdNGZzWqzblvfTmIEikqX5gm@85QTVC1QtiAK@sa5kKSIsqzfnqumYSoR5QZ/Ygh74XhoHaRGVmmLWsR0UrFBNARtK/3AqGn8C4fa6Hs6XIIlZulywSOoibVkBCe4bdXugtvpcvwPvHf9z5rJOajdVX0A "Zsh – Try It Online") (\*) Using `setopt extendedglob` [Answer] # Haskell, 52 bytes ``` import Data.Char t=toUpper r(h:s)=filter((t h/=).t)s ``` [Answer] # TI-BASIC, 164 bytes For TI-83+/84+ series graphing calculators. ``` Input Str1 1→X "sub(Str1,X,1→u "ABCDEFGHIJKLMNOPQRSTUVWXYZ zyxwvutsrqponmlkjihgfedcba u+sub(Ans,54-inString(Ans,u),1 For(X,2,length(Str1 If 2<inString(Ans+Str1,u Ans+u End sub(Ans,3,length(Ans)-2 ``` TI-BASIC is clearly the wrong tool for the job. * It doesn't have a command to remove characters, so we need to loop through the string and append characters if they don't match what is to be removed. * It doesn't support empty strings, so we need to start the string with the two letters to be removed, build the output onto the end, and chop the first two characters off. * It doesn't have case-change commands, so we need to hardcode the entire alphabet... + twice... + Did I mention lowercase letters take two bytes each in the TI-BASIC encoding? I'm not 100% sure, but I spent over six hours on this, and it seems to be the shortest possible solution. To test this with non-uppercase inputs (or to type it into your calculator), make a different program with the contents `AsmPrgmFDCB24DEC9`, and run it using `Asm([whatever you named it]` to enable lowercase typing mode. [Answer] # Lua, ~~93~~ 78 Bytes ``` a=io.read()m=a:sub(1,1):upper()print(({a:gsub("["..m..m:lower().."]","")})[1]) ``` [Answer] # Common Lisp, 77 ``` (princ(let((x(read-char)))(remove-if(lambda(y)(char-equal x y))(read-line)))) ``` Curse these long function names (and parentheses (but I still love them anyway (:3))). [Answer] # C, ~~65~~ 61 bytes ``` main(c,v)char**v;{for(c=**++v;*++*v;**v-c&31&&putchar(**v));} ``` Compiles with warnings. Reads string from `argv[1]`. [Online example](http://coliru.stacked-crooked.com/a/65c14e06d9808e5a) [Answer] # C++, ~~100~~ ~~99~~ 98 bytes ``` #include<ios> int main(){for(int c,f=getchar();~(c=getchar());)tolower(c)-tolower(f)&&putchar(c);} ``` Just one more byte to get under 100. `getchar()` returns `-1` when it reads end of stream, so that's why the `~` is in `for` cycle. (`~-1 == 0`) Ungolfed ``` #include <ios> int main() { for (int c, f = getchar(); ~(c = getchar()); ) tolower(c) - tolower(f) && putchar(c); } ``` [Answer] # AppleScript, ~~209~~ 201 bytes My only consolation is that I beat Brainfuck. ``` set a to(display dialog""default answer"")'s text returned set n to a's characters's number set o to"" repeat n if not a's character n=a's character 1 then set o to a's character n&o set n to n-1 end o ``` How this works is that I take input through `a`, get the length of `a` and mark it as `n`, and set an output variable `o`. For every character that I find that does not contain the first character of a (`a's character 1`), I concatenate it to `o`. The final line prints `o`. Note: This automatically supports all Unicode. c: ]
[Question] [ The partial sums of a list of integers [a1, a2, a3, ..., an] are s1 = a1 s2 = a1 + a2 s3 = a1 + a2 + a3 ... sn = a1 + a2 + ... + an We can then take the list of partial sums [s1, s2, s3, ..., sn] and compute its partial sums again to produce a new list, and so on. Related: [Iterated forward differences](https://codegolf.stackexchange.com/q/47005/20260) **Input:** * A non-empty list of integers * A positive number of iterations, **Output:** Print or return the list of integers that results from taking the partial sums that many times. Fewest bytes wins. Built-ins are OK even if they outright solve the problem. **Test cases:** ``` f([-3, 4, 7, -1, 15], 1) == [-3, 1, 8, 7, 22] f([-3, 4, 7, -1, 15], 3) == [-3, -5, 1, 14, 49] ``` **Leaderboard:** ``` var QUESTION_ID=59192,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/61321/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] # J, 5 bytes ``` +/\^: ``` Try it online on [J.js](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=3%20(%2B%2F%5C%5E%3A)%20_3%204%207%20_1%2015). ### How it works * `/\` is an adverb (function that takes a left argument) that cumulatively reduces by its argument. * Thus `+/\` is the *cumulative sum* verb. * `^:` is the *power conjunction*; `(f ^: n) y` applies `f` a total of `n` times to `y`. * The verb-conjunction train `+/\^:` forms an adverb that repeats `+/\` as many times as specified in its (left) argument. `x (+/\^:) y` gets parsed as `(x (+/\^:)) y`, which is equivalent to executing `(+/\^:x) y`. *Thanks to @Zgarb for his help with the explanation.* [Answer] # Mathematica, 19 bytes Well, if built-ins are okay... ``` Accumulate~Nest~##& ``` Defines a function with the same signature as the examples in the challenge. I'm pretty sure, thanks to the long name `Accumulate` that this will be easily beaten by the golfing languages and the APL-family, though. :) To elaborate on LegionMammal978's comment for those who don't Mathematica: `##` represents a *sequence* of the function's parameters (which is like a list that automatically "splats" wherever it's inserted, if you're more familiar with that term from your language's of choice). The `~` are syntactic sugar for infix function invocation, so if we call the function with parameters `list` and `n` and expand everything, we get: ``` Accumulate~Nest~## Nest[Accumulate, ##] Nest[Accumulate, list, n] ``` Which happens to be exactly the argument order expected by `Nest`. [Answer] ## Haskell, ~~26~~ 23 bytes ``` (!!).iterate(scanl1(+)) ``` This defines an anonymous function, invoked as follows: ``` > let f = (!!).iterate(scanl1(+)) in f [-3,4,7,-1,15] 3 [-3,-5,1,14,49] ``` Thanks to @nimi for saving 3 bytes. ## Explanation ``` (!!). -- Index by second argument from iterate( ) -- the infinite list obtained by iterating scanl1(+) -- the partial sums function (left scan by +) to first argument ``` [Answer] # APL, ~~9~~ 8 bytes ``` {+\⍣⍺⊢⍵} ``` This defines a dyadic function that accepts the iterations and list as left and right arguments. *Thanks to @NBZ for golfing off 1 byte!* Try it online on [TryAPL](http://tryapl.org/?a=3%20%7B+%5C%u2363%u237A%u22A2%u2375%7D%20%AF3%204%207%20%AF1%2015&run). ### How it works * `⍺` and `⍵` are the left and right arguments to the function. * `+\` is cumulative reduce by sum. * `⍣⍺` repeats the preceding operator `⍺` times. * `⊢⍵` applies the identity function to `⍵`. This is a shorter way of parsing the code as `(+\⍣⍺)⍵` instead of `+\⍣(⍺⍵)`. In conjunction, we apply `+\` a total of `⍺` times to `⍵` [Answer] # Matlab, 41 bytes ``` function f(l,n);for i=1:n;l=cumsum(l);end ``` Quite straightforward. I still think it is quite annoying not having a built in way of making piecewise defined anonymous functions, or anchors in recursions. Ungolfed: ``` function f(l,n); for i=1:n; l=cumsum(l); end ``` [Answer] # JavaScript (ES6) 38 Surprisingly small using .map recursively ``` f=(l,n,t=0)=>n?f(l.map(x=>t+=x),n-1):l function test() { var n, v, i = I.value v = i.match(/\-?\d+/g).map(x=>+x) n = v.pop() console.log(v,n) O.innerHTML = I.value + ' -> ' + f(v,n) + '\n' + O.innerHTML; } test() ``` ``` <input id=I value='[-3, 4, 7, -1, 15], 3'><button onclick="test()">-></button> <pre id=O></pre> ``` [Answer] # K, ~~7~~ 3 bytes ``` {y+\/x} ``` Very similar to the J solution. `+\` precisely performs a partial sum, and when `/` is provided with a monadic verb and an integer left argument it iterates a specified number of times, like a "for" loop. The rest is just wrapping it up neatly to suit the order of arguments. ``` {y+\/x}[-3 4 7 -1 15;1] -3 1 8 7 22 {y+\/x}[-3 4 7 -1 15;3] -3 -5 1 14 49 ``` Tested in Kona and [oK](http://johnearnest.github.io/ok/index.html?run=%20%7By%2B%5C%2Fx%7D%5B-3%204%207%20-1%2015%3B3%5D). ## Edit: If I'm allowed to reverse the arguments, as @kirbyfan64sos determined, I can dispense with the function wrapping entirely: ``` +\/ ``` Invoked like: ``` +\/[3;-3 4 7 -1 15] ``` This works properly in both k2.8 and k5. It doesn't work in oK since that interpreter does not yet support curried (aka "projected") adverbs, and it doesn't appear to work properly in Kona for less clear reasons. *edit*: As of a few days ago, the `+\/` formulation also works in oK. [Answer] # Pyth, 9 bytes ``` usM._GvwQ ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=usM._GvwQ&test_suite=0&input_size=2&test_suite_input=%5B-3%2C%204%2C%207%2C%20-1%2C%2015%5D%0A1%0A%5B-3%2C%204%2C%207%2C%20-1%2C%2015%5D%0A3&input=%5B-3%2C%204%2C%207%2C%20-1%2C%2015%5D%0A3) or [Test Suite](http://pyth.herokuapp.com/?code=usM._GvwQ&test_suite=1&input_size=2&test_suite_input=%5B-3%2C%204%2C%207%2C%20-1%2C%2015%5D%0A1%0A%5B-3%2C%204%2C%207%2C%20-1%2C%2015%5D%0A3&input=%5B-3%2C%204%2C%207%2C%20-1%2C%2015%5D%0A3) ### Explanation ``` usM._GvwQ implicit: Q = input list vw input number u Q repeat the following instruction ^ times to G = Q ._G sequence of prefixes of G sM sum them up ``` [Answer] # Julia, 29 bytes ``` f(x,y)=y>0?f(cumsum(x),y-1):x ``` This really doesn't need much explanation. It's a recursive function, if `y==0` then just output x. Otherwise decrement y, perform a cumsum, and recurse. Probably not the most golfed possible Julia solution, I'm still working on it. [Answer] # [Labyrinth](https://github.com/mbuettner/labyrinth), 73 bytes ``` ;? ," ; # #;}= ; # "#;( _ ;={()" #;; ( { " ; { !\(@ +=( = " " " ":{:" ``` It's been a while since I answered something in Labyrinth, and this seemed doable. :) Input format is a flat list with the number of iterations first (and then the list to apply the partial sums to). Delimiters don't matter all, as long as there is no character after the last integer, so you can use something readable like: ``` 3 | -3, 4, 7, -1, 15 ``` Output is newline-separated: ``` -3 -5 1 14 49 ``` [Answer] # R, 75 bytes It's long but a different take...computing the desired sequence directly instead of cumulative sums: ``` function(x,n)sapply(1:length(x),function(i)sum(x[1:i]*choose(i:1+n-2,n-1))) ``` Noting that the coefficients of the terms of xi for cumsum^n(x) are diagonals of Pascal's triangle. i.e. ``` cumsum^3(x) = choose(2,2) * x1, choose(3,2) * x1 + choose(2,2) *x2, choose(4,2) * x1 + choose(3,2) * x2 + choose(2,2) * x3, .... ``` edit: to make a function [Answer] # Python 2, 67 This uses the same summation as [Anthony Roitman](https://codegolf.stackexchange.com/a/61335/36885), and the same recursion as [Morgan Thrapp](https://codegolf.stackexchange.com/a/61369/36885). ``` f=lambda l,n:f([sum(l[:i+1])for i in range(len(l))],n-1)if n else l ``` I developed this solution before I saw theirs, and then it just seemed easier to post it as an answer rather than a comment to either or both of them. [Answer] ## Python, 113 93 89 76 bytes ``` def f(l,n): for i in[0]*n:l=[sum(l[:j+1])for j in range(len(l))]; print(l) ``` It works for both of the test cases. Thanks to Status, Morgan Thrapp, and Ruth Franklin for helping me golf the program down to 93, 89, and 76 bytes respectively. [Answer] # [Gol><> 0.3.10](https://github.com/Sp3000/Golfish/wiki), 22 bytes ``` SI C>rFlMF:}+ NRl<C}<; ``` The first integer is taken to be the iteration number and the rest make up the list. The final list is outputted newline-separated. The language is still quite young and unstable, but since I'm pretty set on these operators I thought it'd be okay. ### Explanation ``` SI Read integer, moving down on EOF (first line runs as loop) r Reverse stack, putting iteration number on top [outer loop] F Do #(iterations) times [inner loop] lMF Do #(length of stack - 1) times : Duplicate top of stack } Rotate stack rightward (top goes to bottom) + Add the top two elements of the stack C Continue inner loop, moving down from F when loop is over } Rotate once more C Continue outer loop, moving down from F when loop is over lRN Print stack as (num + newline) ; Halt ``` To see why this works, let's try a small example `[5 2 1]`: ``` [5 2 1] -- : --> [5 2 1 1] -- } --> [1 5 2 1] -- + --> [1 5 3] [1 5 3] -- : --> [1 5 3 3] -- } --> [3 1 5 3] -- + --> [3 1 8] -- } --> [8 3 1] ``` [Answer] # [R](https://www.r-project.org/), 32 bytes ``` function(l,i)diffinv(l,,i)[0:-i] ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNHJ1MzJTMtLTOvDMgGcqINrHQzY/@naSRr6BrrmOiY6@ga6hiaauoYanJhChpr/gcA "R – Try It Online") `diffinv` is the `inv`erse of `diff`, with optional parameters `lag`, `differences`, and `xi`; `lag` defaults to `1` so we skip it and we compute the the inverse of the \$n^\text{th}\$ difference; `xi` defaults to `0`, so it prepends `i` instances of `0` to the inverse difference list, which we discard by negative indexing. [Answer] ## Python, 52 bytes ``` f=lambda l,n:n*l and f(f(l[:-1],1)+[sum(l)],n-1)or l ``` A recursive function that recurses both on the list `l` and the number of iterations `n`. Let's break it down. First, let's consider a recursive function `g` that iterated the partial sum just once. ``` g=lambda l:l and g(l[:-1])+[sum(l)] ``` For an empty list `l`, this returns `l` itself, the empty list. Otherwise, the last entry of the partial sums of `l` is the overall sum of `l`, which is appended to the recursive result for all but the last element of `l`. Now, let's look at a function `f` that applies `g` for `n` iterations. ``` f=lambda l,n:n and f(g(l),n-1)or l ``` When `n` is `0`, this returns the list `l` unchanged, and otherwise, applies `g` once, then calls `f` recursively with one fewer iteration remaining. Now, let's look again at the actual code, which combines the two recursions into a single function. The idea is to treat `g(l)` as the special case `f(l,1)`. ``` f=lambda l,n:n*l and f(f(l[:-1],1)+[sum(l)],n-1)or l ``` We took `f(g(l),n-1)` from the previous definition, expanded `g(l)` into `g(l[:-1])+[sum(l)]`, and then replaced `g(_)` with `f(_,1)` to confined the recursive calls to `f`. For the base case, we want to return `l` whenever `n==0` or `l==[]`. We combine these by noting that either one makes `n*l` be the empty list, which is Falsy. So, we recurse whenever `n*l` is non-empty, and return `l` otherwise. Even though there are two recursive calls to `f`, this does not cause an exponential blow-up the recursive definition of the Fibonacci numbers, but remains quadratic. [Answer] # C++ (61 + 17 = 78 bytes) ``` #include<numeric> void f(int*a,int*e,int n){for(;n--;)std::partial_sum(a,e,a);} ``` Test case: ``` #include <iostream> #include <iterator> int main() { int a[] { -3, 4, 7, -1, 15 }; f(a, std::end(a), 3); for (auto i : a) std::cout << i << " "; } ``` This takes a slight liberty with the specification: it uses a C-style array, passing pointers to the beginning and end of the array. Internally, as you can see, it's only an *extremely* thin wrapper around the `std::partial_sum` in the standard library. Rather than actually return the resulting value, it just modifies the array that's passed in. If we don't mind pushing definitions of things to the limit (and, arguably, a bit beyond) we can define a "function" in a lambda expression: ``` #include<numeric> #include <iostream> #include <iterator> int main() { int a[] { -3, 4, 7, -1, 15 }; int *e = std::end(a); int n=3; auto f=[&]{for(;n--;)std::partial_sum(a,e,a);}; f(); for (auto i : a) std::cout << i << " "; } ``` This reduces the definition of the function(-like object) to this piece: ``` [&]{for(;n--;)std::partial_sum(a,e,a);}; ``` ...for 40 bytes (+17 for the `#include`). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` SƤ¡ ``` [Try it online!](https://tio.run/##y0rNyan8/z/42JJDC////x@ta6yjYKKjYK6joGuoo2BoGvvfGAA "Jelly – Try It Online") This is my ([Mr Xcoder](https://codegolf.stackexchange.com/posts/145388/revisions)'s) method. # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` +\¡ ``` [Try it online!](https://tio.run/##y0rNyan8/1875tDC////R@sa6yiY6CiY6yjoGuooGJrG/jcGAA "Jelly – Try It Online") This is [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/)'s solution. # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` Ä¡ ``` [Try it online!](https://tio.run/##y0rNyan8//9wy6GF////j9Y11lEw0VEw11HQNdRRMDSN/W8MAA "Jelly – Try It Online") This is a newer solution. ### Method #1 ``` SƤ¡ - Full program, dyadic. ¡ - Apply repeatedly, N times. Ƥ - Map the preceding link over the prefixes of the list. S - Sum. - Output implicitly ``` ### Method #2 ``` +\¡ - Full program, dyadic. ¡ - Apply repeatedly, N times. \ - Cumulative reduce by: + - Addition. ``` ### Method #3 ``` Ä¡ - Full program, dyadic. ¡ - Apply repeatedly, N times. Ä - Cumulative sums. ``` [Answer] # CJam, 13 bytes ``` q~{{1$+}*]}*p ``` [Test it here.](http://cjam.aditsu.net/#code=q~%7B%7B1%24%2B%7D*%5D%7D*p&input=%5B-3%204%207%20-1%2015%5D%203) [Answer] ## Haskell, ~~52~~ 47 bytes First ever code golf 'attempt', and I'm very much a Haskell beginner, so comments are gladly welcomed! It was not clear in the question as to any necessary format of the function call, or whether it was taken by an argument to the program, so I used the exclamation mark as the function identifier to save a couple of spaces. ``` 0!a=a i!a=(i-1)![sum$take j a|j<-[1..length a]] ``` Usage (GHCi): ``` $ ghci partialsums.hs GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. [1 of 1] Compiling Main ( partialsums.hs, interpreted ) Ok, modules loaded: Main. *Main> 1![-3, 4 ,7 ,-1 ,15] [-3,1,8,7,22] *Main> 3![-3, 4 ,7 ,-1 ,15] [-3,-5,1,14,49] ``` [Answer] ## R, 41 bytes ``` function(x,n){for(i in 1:n)x=cumsum(x);x} ``` [Answer] # C#, 52 + 85 = ~~148~~ 137 bytes ``` using E=System.Collections.Generic.IEnumerable<int>; ``` and ``` E I(E s,int i){int t=0;return i<1?s:I(System.Linq.Enumerable.Select(s,v=>t+=v),i-1);} ``` It uses unorthodox practices (`v=>t+=v`), but this is PPCG. Also note the stack depth constraint. [Answer] # Python 3, 73 Could probably be golfed down a bit further. ``` def f(n,i): p=0;c=[] for m in n:p+=m;c+=[p] f(c,i-1)if i else print(n) ``` This version uses numpy, which feels a little like cheating, but here it is: # Python 3 (with numpy), 72 ``` from numpy import* def f(n,i): if i:c=cumsum(n);f(c,i-1) else:print(n) ``` [Answer] # C++14, ~~102~~ ~~103~~ 94 + 17 (include) = 111 bytes ``` #include<vector> auto f(std::vector<int>a,int n){for(;n--;)for(int i=0;i<a.size()-1;++i)a[i+1]+=a[i];return a;} ``` Ungolfed, with test case ``` #include <vector> #include <iostream> auto f(std::vector<int> a, int n) { for (; n--;) for (int i = 0; i < a.size() - 1; ++i) a[i + 1] += a[i]; return a; } int main() { auto t = f({-3, 4, 7, -1, 15}, 3); for (int i : t) std::cout << i << " "; } ``` ~~Relies on order of evaluation. Not sure if it is UB or not, but works~~ It's compiler dependent, so I changed it. [Answer] # Octave, 24 bytes ``` @(l,n)l*triu(0*l'*l+1)^n ``` [Answer] ## Burlesque, 10 bytes ``` {q++pa}jE! ``` it's not very efficient in general but it does the trick. ``` blsq ) {-3 4 7 -1 15} 1 {q++pa}jE! {-3 1 8 7 22} blsq ) {-3 4 7 -1 15} 3 {q++pa}jE! {-3 -5 1 14 49} ``` [Answer] # C++14, 67 bytes As unnamed lambda modifying its input, requiring `c` as a random-access-container like `vector<int>`. ``` [](auto&c,int n){while(n--)for(int i=0;i++<c.size();c[i]+=c[i-1]);} ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~4~~ 3 bytes Saved 1 byte thanks to [Dominic Van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) ``` !¡∫ ``` [Try it online!](https://tio.run/##yygtzv7/X/HQwkcdq////x@ta6xjomOuo2uoY2ga@98YAA "Husk – Try It Online") ``` !¡∫ ¡ Repeatedly apply the following function to the first argument, making an infinite list ∫ Cumulative sum (one cycle) ! Index into this list with the second argument ``` [Answer] # Lua (67 bytes) ``` function x(t,n)return load("return "..table.concat(t,"+",1,n))()end ``` Explanation: `table.concat(t,"+",1,n)` gives the string formed by concatenation of elements of `t` from 1 to n using `+` as connector, i.e. `t[1]+...+t[n]`. `load(<string>)()`, as its name suggests, loads a string to be executed as a function. In this case, a function with zero arguments given by `table.concat`. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes ``` (¦ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIowqYiLCIiLCIzXG5bLTMsIDQsIDcsIC0xLCAxNV0iXQ==) ]
[Question] [ ### Introduction In the wake of the [left-pad npm package](https://www.npmjs.com/package/left-pad) [fallout](https://www.reddit.com/r/programming/comments/4bjss2/an_11_line_npm_package_called_leftpad_with_only/), let's have a code golf for implementing left-pad. The *left-pad* function consists of 2 default arguments and 1 additional argument, in the form **string**, **length**, (**padchar**). If the padchar is not given, this is **standardized** to a *space character*. Let's take an example with two arguments: ``` left_pad("abc", 6) ``` First, we observe the length of the string, which is **3**. After this, we need to pad this string in the left until the length of the full string has reached the length given in the function. In this case **6**. Since the padchar is *not given*, we need to pad this with spaces: ``` abc ``` This is a string with 3 spaces and the initial string, resulting into a string with length 6. Here is an example with the padchar given: ``` left_pad("abc", 6, "-") ``` We just do the same as the example above, but replace the spaces with the padchar. In this case, the hyphen: ``` ---abc ``` ### The Task Given the **string**, **length**, and *maybe* the additional argument **padchar**, output the left-padded string. You can assume that the length number is equal or greater than the length of the string. The padchar will always consist of 1 character. ### Test cases ``` left_pad("string", length, ("padchar")) === "left-padded string" left_pad("foo", 5) === " foo" left_pad("foobar", 6) === "foobar" left_pad("1", 2, "0") === "01" left_pad("1", 2, "-") === "-1" ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the smallest number of bytes wins! [Answer] ## Pyth, ~~13~~ 11 bytes ``` +*.xwd-Qlzz ``` [Try it here](http://pyth.herokuapp.com/?code=%2B%2a.xwd-Qlzz&input=foo%0A5&debug=0). Takes input from STDIN as the string on the first line, length on the second line, and padding char optionally on a third line. [Answer] ## JavaScript (ES6), 43 bytes ``` f=(s,n,p=" ",r=p)=>(r+=s+="")[n]?s:f(r,n,p) ``` [Answer] # Javascript ES6, 35 bytes ``` (s,l,c=' ')=>c.repeat(l-s.length)+s ``` [Try it.](https://jsfiddle.net/ff41ht4c/2/) I believe this is the shortest possible implimentation currently possible in Javascript. [Answer] # JavaScript (ES6), 37 43 44 bytes ``` (a,n,c=' ')=>((c+'').repeat(n)+a).substr(-n) ``` Test: ``` > f=(a,n,c)=>((c?c:" ").repeat(n)+a).substr(-n) < function (a,n,c)=>((c?c:" ").repeat(n)+a).substr(-n) > f('foo', 5) === ' foo'; < true > f('foobar', 6) === 'foobar'; < true > f(1, 2, 0) === '01'; < true > f(1, 2, '-') === '-1'; < true ``` Not sure if you want to count the function declaration, I'd inline this. [Answer] # Python 3, ~~33~~ ~~31~~ 29 bytes ``` lambda a,b,x=" ":a.rjust(b,x) ``` ~~Fairly straightforward.~~ Thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor) for reminding me `str.rjust` is a thing. :P For the same length (also thanks to xnor): ``` lambda a,b,x=" ":(x*b+a)[-b:] ``` Previous solution: ``` lambda a,b,x=" ":x*(b-len(a))+a ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~11~~ 9 bytes Code: ``` g-ð³0@×¹« ``` Explanation: ``` g # Implicit first input, take the length. - # Substract the length with the second input. ð³ # Push a space and if the third input exists, also the third input. 0@ # Reposition the first element of the stack to the top (zero-indexed). × # Multiply the character with the difference in length. ¹« # Concatenate the first input to the string. ``` Uses **CP-1252** encoding. [Try it online](http://05ab1e.tryitonline.net/#code=Zy3DsMKzMEDDl8K5wqs&input=Zm9vCjUKLQ). [Answer] # Mathematica, 13 bytes ``` StringPadLeft ``` Builtin-only answer #3 (first was `Range`, second was `Surd`) Or less builtin: (35 bytes) ``` ##2~StringRepeat~(#3-Length@#2)<>#& ``` [Answer] ## JavaScript (ES5), 70 bytes Using recursion... ``` function f(s,c,p,u){return(s+'').length<c?f((p==u?' ':p+'')+s,c,p):s} ``` My initial go was only 57 bytes: ``` function f(s,c,p){return s.length<c?f((p||" ")+s,c,p):s} ``` But only passed the first 2 tests: ``` > f('foo', 5) === ' foo'; true > f('foobar', 6) === 'foobar'; true > f(1, 2, 0) === '01'; false > f(1, 2, '-') === '-1'; false ``` I still like the shorter one, because in practise, passing numbers to a string manipulation function isn't a feature I would need. [Answer] # JavaScript ES7, 16 bytes ``` ''.padStart.bind ``` built-ins ftw! Only works on Firefox 48 and above. Valid as this feature was added March 12. This takes input like: ``` (''.padStart.bind)(arg1)(arg2,arg3) ``` [Answer] # Julia, 4 bytes ``` lpad ``` Passes all the test cases: ``` julia> lpad("foo", 5) " foo" julia> lpad("foobar", 6) "foobar" julia> lpad(1, 2, 0) "01" julia> lpad(1, 2, '-') "-1" ``` [Answer] # Javascript (ES6), 55 bytes ``` (a,n,c=' ',s=a+'')=>(new Array(++n-s.length).join(c)+s) ``` Create an empty array of values and join version. ``` (a,n,c=' ')=>{a+=''; return new Array(++n-a.length).join(c)+a} ``` Is more readable but the `return` adds a few more characters. [Answer] # Bash, 57 Bytes Parameters: *string width padchar* ``` printf -vX %$2s;Y="${X// /${3- }}$1";echo -n "${Y:${#1}}" ``` Make a string of *width* spaces. Convert each space character into *padchar*. Write padding then *string*. [Answer] # Python, 41 bytes ``` lambda a,b,x=' ':str(a).rjust(b,str(x)) ``` Without the builtin rjust, 43 bytes: ``` lambda a,b,x=' ':str(x)*int(b/2%3)+str(a) ``` (not what one expects it to do, but it passes the test suite) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` L⁴_ẋ@⁵⁵⁶<?¤³ ``` *So* many variable references. Wasn't Jelly supposed to be a *tacit* language? [Try it online!](http://jelly.tryitonline.net/#code=TOKBtF_huotA4oG14oG14oG2PD_CpMKz&input=&args=ImFiYyI+Ng+Ii0i) ### How it works ``` L⁴_ẋ@⁵⁵⁶<?¤³ Main link Arguments: string (³), length (⁴), padchar (⁵, defaults to 10) L Compute the length of ³. ⁴_ Subtract the length from ⁴. ¤ Combine the two links to the left into a niladic chain: ⁵ Yield ⁵. ⁵⁶<? Yield ⁵ if ⁵ < ⁵, else ⁶. Comparing a number with itself gives 0 (falsy), but comparing a string / character list with itself gives [0] (truthy). ẋ@ Repeat the result to the right as many times as specified in the result to the left. ³ Print the previous return value and return ³. ``` [Answer] # JavaScript (ES6), 34 bytes I used a recursive solution. ``` f=(s,l,c=' ')=>s[l-1]?s:f(c+s,l,c) ``` [Answer] # [Lua](https://www.lua.org/), 39 38 bytes ``` s,n,c=...print((c or" "):rep(n-#s)..s) ``` [Try it online!](https://tio.run/##yylN/P@/WCdPJ9lWT0@voCgzr0RDI1khv0hJQUnTqii1QCNPV7lYU0@vWPP///@JScn/zf7rAgA "Lua – Try It Online") Thanks to c-- for saving a byte. [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ùVWªS ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=%2bVZXqlM&input=ImZvbyIgNiAiLSI) ``` ù # left-pad the input string with: V # second input (length) WªS # third input, or space if not specified ``` Or, for 1 byte: ``` ù ``` But this isn't a full program, so I don't think it counts. It can be called `AùBC` where A is the string, B is the length, and C is (optionally) the padding character. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~91~~ 86 bytes Takes 2 or 3 arguments on the command line. Also uses the rare ["-->" operator](https://stackoverflow.com/questions/1642028/what-is-the-operator-in-c-c)! *-5 bytes from [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) and [c--](https://codegolf.stackexchange.com/users/112488/c)* ``` l;main(c,v)int**v;{for(l=atoi(v++[2]);l-->strlen(*v);)putchar(c-3?*v[2]:32);puts(*v);} ``` [Try it online!](https://tio.run/##HcrBDoIwDIDh12kHvcDBhEZ9EMNhaVCW1M2M0Qvx2Svx@n@/0EvEXfkdUwbpDVNuIRgfz1JBr7GVBNZ1j2FGVqLb1qouGYIh42dvssYKQuM92LlM44B81u3vX3dfF9XiF6cf "C (gcc) – Try It Online") [Answer] # Powershell, ~~87~~ ~~67~~ ~~incorrect counted 54~~, 46 Bytes ``` function f($s,$l,$c=' '){$c*($l-$s.length)+$s} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/P600L7kkMz9PIU1DpVhHJUdHJdlWXUFds1olWUtDJUdXpVgvJzUvvSRDU1uluPZ/moJSWn6@koIpF4SVlFikpGAG4hgqKRgpKBkoIdi6Sv8B "PowerShell – Try It Online") [Answer] # [Pike](http://pike.lysator.liu.se), 67 bytes ``` mixed n(mixed a,int b,mixed x){return x!=""?x:" "*(b-strlen(a))+a;} ``` *sigh*. The empty string `""` evaluates to `true`. *Why!?* mixed mixed mixed mixed mixed Pike soup... [Answer] ## [Pyke](https://github.com/muddyfish/PYKE), 12 bytes (noncompeting) added input node, bugfix on len node, change default results on assign node after the challenge was posted. ``` \ =zzjl-z*j+ ``` Explanation: ``` \ =z - assign default input for `z` to be " " (Will still prompt but no input will return a space instead) zj - j = input() l - len(j) - - eval_or_not_input() - ^ z* - ^*input() j+ - ^+j ``` [Answer] # JavaScript ES6, 38 bytes ``` (s,l,c=" ")=>(c.repeat(l)+s).slice(-l) ``` An alternate solution. [Answer] # [Arturo](https://arturo-lang.io), 34 bytes ``` $=>[++repeat ??attr""" "&-size<=&] ``` [Try it](http://arturo-lang.io/playground?ElsxF0) Arturo has `pad` but here's a non-builtin. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` □ðJ3Ẏ÷ø↳ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJ+IiwiIiwi4pahw7BKM+G6jsO3w7jihrMiLCIiLCIhbGVmdF9wYWRcXCgoLiopXFwpID09PSBcIiguKilcIlxubGVmdF9wYWQoXCJmb29cIiwgNSkgPT09IFwiICBmb29cIlxubGVmdF9wYWQoXCJmb29iYXJcIiwgNikgPT09IFwiZm9vYmFyXCJcbmxlZnRfcGFkKFwiMVwiLCAyLCBcIjBcIikgPT09IFwiMDFcIlxubGVmdF9wYWQoXCIxXCIsIDIsIFwiLVwiKSA9PT0gXCItMVwiIl0=) Link is to test suite. Somehow, vyncode also gives 8 bytes. ## Explained ``` □ðJ3Ẏ÷ø↳ □ðJ # append a space to all input arguments 3Ẏ # take the first 3 items of that ÷ # dump everything to the stack ø↳ # call the built-in left pad function. ``` [Answer] # Ruby, 42 bytes ``` def left_pad(s,t,p=" ");p*(t-s.size)+s;end ``` Parameters: string, size, padchar. Test suite below; should print all "true"s, just put everything in the same file. ``` puts left_pad("foo", 5) == " foo" puts left_pad("foobar", 6) == "foobar" puts left_pad("1", 2, "0") == "01" puts left_pad("1", 2, "-") == "-1" ``` [Answer] # Java 8, ~~86~~ 88 bytes This is a function. The third argument is a `varargs` to allow the optional pad char (defaults to `' '`) ``` String p(String s,int l,char...p){return s.length()<l?p((p.length>0?p[0]:' ')+s,l,p):s;} ``` Recursion! +2 bytes (added brackets because of incompatible type error) [Answer] # PHP, ~~54~~ 48 bytes Uses Windows-1252 encoding. ``` function(&$s,$l,$p=~ß){$s=str_pad($s,$l,$p,0);}; ``` Run like this (`-d` added for easthetics only): ``` php -r '$f = function(&$s,$l,$p=~ß){$s=str_pad($s,$l,$p,0);}; $s="foo";$f($s,5);echo"$s\n";' 2>/dev/null ``` Old version (without the builtin): ``` function(&$s,$l,$p=~ß){for(;strlen($s)<$l;)$s=$p.$s;}; ``` # Tweaks * Saved 6 bytes by using `str_pad` instead of a loop. Leaving the old one for reference, as builtins are frowned upon [Answer] ## R, 50 bytes Late to the party again but here it goes: ``` function(s,n,p=" ")cat(rep(p,n-nchar(s)),s,sep="") ``` This simply prints the output to stdout but does not actually return the padded string (wasn't sure if this is a requirement for the challenge). If this is needed, the solution is slightly longer at 61 bytes: ``` function(s,n,p=" ")paste0(c(rep(p,n-nchar(s)),s),collapse="") ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 212 bytes ``` ,----------[++++++++++<[<]<+>>[>],----------]<[<]<<<,----------[<[-<++++++++++>]<[->+<]>>>++++++++[-<----->]<++[-<+>],----------]>>[-<<<->>>]++++[>++++++++<-]><<+>,[<->[-<<+>>]]<[->>[-<<<+>>>]<<]<<[->.<]>>>>>[.>] ``` ## Explained ``` ,----------[ While it isn't a newline ++++++++++ Restore the character <[<]<+>>[>] Increment the counter behind the array and return ,----------] Read and repeat <[<]<<< navigate behind the length ,----------[ While it isn't a newline <[-<++++++++++>]<[->+<]>> x10 the stored number >++++++++[-<----->]<++ sub 39 [-<+>] Copy into stored ,----------] Read and repeat >>[-<<<->>>] Subtract the counter from the target ++++[>++++++++<-]> Prepare a space <<+>,[<->[-<<+>>]] If the next byte isnt eof then we copy it left two and zero the test byte <[->>[-<<<+>>>]<<] If the text bit is still high copy space in there instead <<[->.<] While the counter is positive write the pad char >>>>>[.>] Write the rest of the string ``` Arguments separated by linefeeds. If no pad char is present, a linefeed after the length must still be included. [Try it online!](https://tio.run/##VY4xCsNQDEP3XMVxtm5CFzEe0kKgFBoo9Pw/@i79Tb1ZerJ8fa335/a@PVqbfUzYGAQSRgbzBGTJwDmDcPxyFOI0JMmvJqBQebXY/02VuG66Eln4CEImhM8ht0N6KKvgE7EeQf9I0lKdchZma9u@T5fpAA "brainfuck – Try It Online") [Answer] # [Go](https://go.dev), 110 bytes ``` import."strings" func l(n int,c...string)string{q,p:=c[0]," " if len(c)>1{p=c[1]} return Repeat(p,n-len(q))+q} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fY5BisIwFIb3OUV4ICSYFisoIugZZLYzgpmQlGD7mqbpbEpPMEeYTRE8hEfxNtNa3amrH_7v8b7_75QW3cVJdZSpprm0SGzuCh9iMHmAcx1MtLrio6uCt5hWQEyNimYMqcUgVBzHI-FjNKVw6436nO0FUCDW0EwjU3ybNK6vk31LvA61R_qhnZaBOYHRcFJyPi3bu_X3Jhk2MU4bsus_B8PgMPk5fCGIXr8QYIoCOH8Glzf4Lf0LPheQgIDZW0whGvh9UteN-Q8) Uses Go's variadic arguments feature to have an optional argument. Expects at minimum 1 string passed to the function (the string to be padded); the first string after that is the padding character. A solution were all arguments are explicit is significantly shorter: ### [Go](https://go.dev), 76 bytes, no variadic arguments ``` import."strings" func l(s,c string,n int)string{return Repeat(c,n-len(s))+s} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70oPX_BzoLE5OzE9FSF3MTMPK7M3IL8ohI9pbTcEqWlpSVpuhY3fWBixSVFmXnpxUpcaaV5yQo5GsU6yQoQMZ08hcy8Ek0Ip7ootaS0KE8hKLUgNbFEI1knTzcnNU-jWFNTu7gWauYssBEgGzU0Faq5AoD6StI0lBJUyxJi8pR0gIYrpeXnAxlKCkDCVFMTl5KkxCKYKjMcqgxBCgyAhBE-BbpQBVAXLlgAoQE) ]
[Question] [ There are 95 [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters: ``` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` In the [Consolas font](http://en.wikipedia.org/wiki/Consolas) (the Stack Exchange code block default), some of the characters have mirrors around a vertical axis of symmetry: * These pairs of characters are mirrors of each other: `()` `[]` `{}` `<>` `/\` * These characters are mirrors of themselves: `! "'*+-.8:=AHIMOTUVWXY^_ovwx|` (Note that space is one.) * These do not have mirrors: `#$%&,012345679;?@BCDEFGJKLNPQRSZ`abcdefghijklmnpqrstuyz~` (`i`, `l`, `0`, `#`, and probably other characters are their own mirrors in some fonts but we'll stick to the Consolas shapes.) A string is said to be a mirror of itself if it is made with **only the 39 mirror characters**, arranged such that the string has a central vertical line of symmetry. So `](A--A)[` is a mirror of itself but `](A--A(]` is not. Write a one-line even-length program that is a mirror of itself. When N copies of its left half have been prepended to it and N copies of its right half have been appended to it, it should output N+1. N is a non-negative integer. For example, if the program was `](A--A)[` (left half: `](A-`, right half: `-A)[`), then: * Running `](A--A)[` should output `1`. (N = 0) * Running `](A-](A--A)[-A)[` should output `2`. (N = 1) * Running `](A-](A-](A--A)[-A)[-A)[` should output `3`. (N = 2) * Running `](A-](A-](A-](A--A)[-A)[-A)[-A)[` should output `4`. (N = 3) * . . . * Running `](A-](A-](A-](A-](A-](A-](A-](A-](A-](A--A)[-A)[-A)[-A)[-A)[-A)[-A)[-A)[-A)[-A)[` should output `10`. (N = 9) * etc. ### Rules * Output to stdout or your language's closest alternative. There may be an optional trailing newline. No input should be taken. * The process should theoretically work for N up to 215-1 or beyond, given enough memory and computing power. * A full program is required, not just a [REPL](http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) command. **The shortest initial program (N = 0 case) in bytes wins.** [Answer] # GolfScript, 10 bytes ``` !:{)::(}:! ``` Try it online with Web Golfscript: [N = 0](http://golfscript.apphb.com/?c=ITp7KTo6KH06IQ%3D%3D), [N = 1](http://golfscript.apphb.com/?c=ITp7KTohOnspOjoofTohOih9OiE%3D), [N = 2](http://golfscript.apphb.com/?c=ITp7KTohOnspOiE6eyk6Oih9OiE6KH06IToofToh), [N = 3](http://golfscript.apphb.com/?c=ITp7KTohOnspOiE6eyk6ITp7KTo6KH06IToofTohOih9OiE6KH06IQ%3D%3D), [N = 41](http://golfscript.apphb.com/?c=ITp7KTohOnspOiE6eyk6ITp7KTohOnspOiE6eyk6ITp7KTohOnspOiE6eyk6ITp7KTohOnspOiE6eyk6ITp7KTohOnspOiE6eyk6ITp7KTohOnspOiE6eyk6ITp7KTohOnspOiE6eyk6ITp7KTohOnspOiE6eyk6ITp7KTohOnspOiE6eyk6ITp7KTohOnspOiE6eyk6ITp7KTohOnspOiE6eyk6ITp7KTohOnspOiE6eyk6ITp7KTohOnspOiE6eyk6ITp7KTohOnspOiE6eyk6Oih9OiE6KH06IToofTohOih9OiE6KH06IToofTohOih9OiE6KH06IToofTohOih9OiE6KH06IToofTohOih9OiE6KH06IToofTohOih9OiE6KH06IToofTohOih9OiE6KH06IToofTohOih9OiE6KH06IToofTohOih9OiE6KH06IToofTohOih9OiE6KH06IToofTohOih9OiE6KH06IToofTohOih9OiE6KH06IToofTohOih9OiE6KH06IToofTohOih9OiE6KH06IToofToh) Web GolfScript has a 1024 character limit, but the Ruby interpreter handles **N = 32767** perfectly: ``` $ curl -Ss http://www.golfscript.com/golfscript/golfscript.rb > golfscript.rb $ echo '"!:{):"32768*":(}:!"32768*' | ruby golfscript.rb > mirror-level-32767.gs $ ruby golfscript.rb mirror-level-32767.gs 32768 ``` ### How it works Without any input, GolfScript initially has an empty string on the stack. In the first left half, the following happens: * `!` applies logical NOT to the empty string. This pushes `1`. * `:{` saves the integer on the stack in the variable `{`. Yes, that is a valid identifier, although there's no way to retrieve the stored value. * `)` increments the integer on the stack. * `:` is an incomplete instruction. The the subsequent left halves, the following happens: * `:!` (where `:` is a leftover from before) saves the integer on the stack in the variable `!`. Yes, that is also a valid identifier. This breaks the `!` command, but we don't use it anymore. * `:{`, `)` and `:` work as before. In the first right half, the following happens: * `::` (where `:` is a leftover from before) saves the integer on the stack in the variable `:`. Yes, *even that* is valid identifier. As with `{`, there's no way to retrieve the stored value. * `(` decrements the integer on the stack, yielding the number of left halves. * `}`, since it is unmatched and terminates execution immediately. This is an undocumented feature. I call them *supercomments*. The remaining code is simply ignored. [Answer] # Z80 Machine Code, ~~8~~ 6 bytes\* `<8ww8>` \* Assumes certain conditions by entering from Amstrad BASIC ``` < INC A // A=A+1 8w JR C, #77 ## C is unset unless A has overflowed, does nothing w LD (HL), A // Saves A to memory location in HL (randomly initialised) 8> JR C, #3E ## C is still unset, does nothing ``` `A` is initially 0 when entered from BASIC. It increments `A` *n* times, then writes it *n* times to the same memory location (which is set to a slightly random location by BASIC)! The `JR` Jump Relative operation never does anything since the `C` flag is always unset, so is used to "comment out" the following byte! This version is slightly cheating by assuming certain entry conditions, namely entering from BASIC guarantees that `A` is always 0. The location of `(HL)` is not guaranteed to be safe, and in fact, is probably a dangerous location. The below code is much more robust which is why it's so much longer. # Z80 Machine Code, 30 bytes As ASCII: `o!.ww.!>A=o>{))((}<o=A<!.ww.!o` Basically, the first half guarantees creation of a zero value and the second half increments it and writes it to memory. In the expanded version below `##` denotes code that serves no purpose in its half of the mirror. ``` o LD L, A ## !.w LD HL, #772E // Load specific address to not corrupt random memory! w LD (HL), A ## Save random contents of A to memory .! LD L, #21 ## >A LD A, #41 // A=#41 = DEC A // A=#40 o LD L, A // L=#40 >{ LD A, #7B ## ) ADD HL, HL // HL=#EE80 ) ADD HL, HL // HL=#DD00. L=#00 at this point (( JR Z, #28 ## } LD A, L // A=L < INC A // A=L+1 o LD L, A // L=L+1 = DEC A // A=L A LD B, C ## < INC A // A=L+1 !.w LD HL, #772E // Load address back into HL w LD (HL), A // Save contents of A to memory .! LD L, #21 ## o LD L, A // L=A ``` Breakdown of allowed instructions: ``` n op description -- ---- ----------- 28 LD LoaD 8-bit or 16-bit register 3 DEC DECrement 8-bit or 16-bit register 1 INC INCrement 8-bit or 16-bit register 1 ADD ADD 8-bit or 16-bit register Available but useless instructions: 3 JR Jump Relative to signed 8-bit offset 1 DAA Decimal Adjust Accumulator (treats the A register as two decimal digits instead of two hexadecimal digits and adjusts it if necessary) 1 CPL 1s ComPLement A 1 HALT HALT the CPU until an interrupt is received ``` Out of the 39 instructions allowed, 28 are load operations (the block from 0x40 to 0x7F are all single byte `LD` instructions), most of which are of no help here! The only load to memory instruction still allowed is `LD (HL), A` which means I have to store the value in `A`. Since `A` is the only register left with an allowed `INC` instruction this is actually quite handy! I can't load `A` with 0x00 to start with because ASCII 0x00 is not an allowed character! All the available values are far from 0 and all mathematical and logical instructions have been disallowed! Except... I can still do `ADD HL, HL`, add 16-bit `HL` to itself! Apart from directly loading values (no use here!), INCrementing `A` and DECrementing `A`, `L` or `HL` this is the only way I have of changing the value of a register! There is actually one specialised instruction that could be helpful in the first half but a pain to work around in the second half, and a ones-complement instruction that is almost useless here and would just take up space. So, I found the closest value to 0 I could: 0x41. How is that close to 0? In binary it is 0x01000001. So I decrement it, load it into `L` and do `ADD HL, HL` twice! `L` is now zero, which I load back into `A`! Unfortunately, the ASCII code for `ADD HL, HL` is `)` so I now need to use `(` twice. Fortunately, `(` is `JR Z, e`, where `e` is the next byte. So it gobbles up the second byte and I just need to make sure it doesn't do anything by being careful with the `Z` flag! The last instruction to affect the `Z` flag was `DEC A` (counter-intuitively, `ADD HL, HL` doesn't change it) and since I know that `A` was 0x40 at that point it's guaranteed that `Z` is not set. The first instruction in the second half `JR Z, #28` will do nothing the first 255 times because the Z flag can only be set if A has overflowed from 255 to 0. After that the output will be wrong, however since it's only saving 8-bits values anyway that shouldn't matter. The code shouldn't be expanded more than 255 times. The code has to be executed as a snippet since all available ways of returning cleanly have been disallowed. All the RETurn instructions are above 0x80 and the few Jump operations allowed can only jump to a positive offset, because all 8-bit negative values have been disallowed too! [Answer] # Pip, ~~12~~ ~~8~~ 4 bytes *Now with 66% fewer bytes!* ``` x++x ``` * `x` is a variable, preinitialized to `""`. In numeric context, this becomes `0`. * The first half, sans the final `+`, makes an expression of the form `x+x+...+x`. This is a valid statement that does nothing. * The second half, including the final `+` from the first half, makes an expression of the form `++x+x+...+x`. `++x` increments `x` to `1`, and the rest adds it to itself N times. Because expressions are evaluated left-to-right in Pip, the increment is guaranteed to happen first, and the result is equal to the number of mirror levels. * At the end, the value of this expression is auto-printed. Unfortunately, Pip doesn't do well processing huge expressions: this solution causes a `maximum recursion depth exceeded` error for N above 500 or so. Here's a previous solution that doesn't, for **8 bytes**: ``` x++oo++x ``` [More on Pip](http://github.com/dloscutoff/pip) [Answer] # J, ~~16~~ 14 bytes ``` (_=_)]++[(_=_) ``` Usages: ``` (_=_)]++[(_=_) 1 (_=_)]+(_=_)]++[(_=_)+[(_=_) 2 (_=_)]+(_=_)]+(_=_)]++[(_=_)+[(_=_)+[(_=_) 3 ``` Explanation: * J evaluates from right to left. * `(_=_)` is `inf equals inf` which is true, has a value of `1`, so the expression becomes `1+]...[+1`. (`(8=8)` would also work but this looks cooler. :)) * `[` and `]` return their the left and right arguments respectively if they have 2 arguments. If they get only 1 they return that. * `+` adds the 2 arguments. If it gets only 1 it returns that. Now let's evaluate a level 3 expression (going from right to left): ``` (_=_)]+(_=_)]++[(_=_)+[(_=_) NB. (_=_) is 1 1]+1]+1]++[1+[1+[1 NB. unary [, binary + 1]+1]+1]++[1+[2 NB. unary [, binary + 1]+1]+1]++[3 NB. unary [, unary + 1]+1]+1]+3 NB. unary +, binary ] 1]+1]+3 NB. unary +, binary ] 1]+3 NB. unary +, binary ] 3 ``` As we see the right half of the `1`'s gets added and the left side of the `1`'s gets omitted resulting in the desired integer `N`, the mirror level. [Try it online here.](http://tryj.tk/) [Answer] # Haskell, 42 bytes ``` (8-8)-(-(8-8)^(8-8))--((8-8)^(8-8)-)-(8-8) ``` Luckily a line comment in Haskell (-> `--`) is mirrorable and half of it (-> `-`) is a valid function. The rest is some math to get the numbers `0` and `1`. Basically we have `(0)-(-1)` with a comment for `N=0` and prepend `(0)-(-1)-` in each step. If floating point numbers are allowed for output, we can build `1` from `8/8` and get by with 26 bytes: # Haskell, 26 bytes ``` (8-8)-(-8/8)--(8\8-)-(8-8) ``` Outputs `1.0`, `2.0`, etc. [Answer] # CJam, 14 bytes ``` ]X+:+OooO+:+X[ ``` Try it online in the CJam interpreter: [N = 0](http://cjam.aditsu.net/#code=%5DX%2B%3A%2BOooO%2B%3A%2BX%5B), [N = 1](http://cjam.aditsu.net/#code=%5DX%2B%3A%2BOo%5DX%2B%3A%2BOooO%2B%3A%2BX%5BoO%2B%3A%2BX%5B), [N = 2](http://cjam.aditsu.net/#code=%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOooO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5B), [N = 3](http://cjam.aditsu.net/#code=%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOooO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5B), [N = 41](http://cjam.aditsu.net/#code=%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOo%5DX%2B%3A%2BOooO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5BoO%2B%3A%2BX%5B) Note that this code finishes with an error message. Using the Java interpreter, that error message can be suppressed by closing or redirecting STDERR.1 ### How it works In the left halves, the following happens: * `]` wraps the entire stack in an array. * `X` appends `1` to that array. * `:+` computes the sum of all array elements. * `Oo` prints the contents of empty array (i.e., nothing). In the first right half, the following happens: * `o` prints the integer on the stack, which is the desired output. * `O+` attempts to append an empty array to the topmost item of the stack. However, the stack was empty before pushing `O`. This fails and terminates the execution of the program. The remaining code is simply ignored. 1According to the meta poll [Should submissions be allowed to exit with an error?](http://meta.codegolf.stackexchange.com/questions/4780), this is allowed. ]
[Question] [ ### Description Chicken McNugget numbers are numbers that can be expressed as a sum of \$6\$, \$9\$ or \$20\$ - the initial sizes of the famous [Chicken McNuggets](https://en.wikipedia.org/wiki/Chicken_McNuggets) boxes sold by McDonald's. In that sum, a number may occur more than once, so \$6 + 6 = 12\$ is such a number too, and the number must "contain" at least one of the mentioned sizes. The first Chicken McNugget numbers are: \begin{align\*}&6\\ &9\\ &6 + 6 = 12\\ &6 + 9 = 15\\ &9 + 9 = 6 + 6 + 6 = 18\\ &20\\ &6 + 6 + 9 = 21\\ &\dots \end{align\*} ### Challenge Your task is to write a program or function, that, given a positive integer, determines whether this number can be expressed in the described way, therefore is such a Chicken McNugget number. It should then output a truthy or falsy value based on its decision. ### Test cases ``` 6 -> true 7 -> false 12 -> true 15 -> true 21 -> true 40 -> true 42 -> true ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins and the standard loopholes apply! [Answer] # Python, 27 bytes ``` lambda n:0x82492cb6dbf>>n&1 ``` [Try it online!](https://tio.run/##BcFBDkAwEAXQq8xK2l1bIki4CBYthiZ8TWPB6cd76XuOG6VwP8npr7B6QmfexlWtW0K9Bh4GFFZSjnjUCOI7EyiCsse@KWuMpsjECnrW8gM "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 24 bytes ``` lambda n:0<=n--n%3*20!=3 ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPysDGNk9XN0/VWMvIQNEWKJlfpJCnkJmnUJSYl56qYahjaGCgacWlkJmmkZdfogAkNTWtCooy80qArP8A "Python 3 – Try It Online") ## Explanation With `6` and `9` alone, one can make all integers divisible by `3` which are greater than `3`, as is stated in [ovs's comment to the challenge](https://codegolf.stackexchange.com/questions/132702/chicken-mcnugget-numbers#comment325678_132702). It is assumed that one can also make `0`. In conclusion, one can make `0,6,9,12,15,...`. With one instance of `20`, one can make: `20,26,29,32,35,...`. With two instances of `20`, one can make: `40,46,49,52,55,...`. Three instances is never necessary, for `3 x 20 = 10 x 6`. --- Notice that the cases where no `20` is needed is also divisible by 3; the cases where one `20` is needed leaves a remainder of `2`; the cases where two `20` is needed leaves a remainder of `1`. The number of `20` needed can hence be calculated by `(-n)%3`. Then, we do `n-(((-n)%3)*20)` to remove the number of `20` needed from the number. We then check that this number is non-negative, but is not `3`. [Answer] # [Python 2](https://docs.python.org/2/), 28 bytes ``` lambda n:-n%3-n/20<(n%20!=3) ``` [Try it online!](https://tio.run/##NdDLTsMwEIXhfZ7CLColUiocX2bsCj8JsAgiKZWKqaxs@vThrxCLsxifb7yY2337@qluX8vbfp2/Pz5nU0/HevDH@uzsS18Pzj4VP@zb3M7LZop5ldHk0UyORJJG4yyZSCDUTgnG8@5x3hOsp/N4TxfoAjuBPrAX6AN9YDdgAiZiIiZiIn9EXMRFXMRFXMQJTnCCE5zgBCc4wQlOcIpTnOIUpzjFKU5xilNcwiVcwiVcwiVcwiVcwiVcxmVcxmVcxmVcfpwIl3H5cStr37uulfVy3ZbWr2Ob63npp3Gy0zB0t3apm2ml/N34f95/AQ "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ṗ3’æ.“©µÞ‘ċ ``` [Try it online!](https://tio.run/##ASoA1f9qZWxsef//4bmXM@KAmcOmLuKAnMKpwrXDnuKAmMSL/zByNDDDh8OQZv8 "Jelly – Try It Online") ### How it works ``` ṗ3’æ.“©µÞ‘ċ Main link. Argument: n ṗ3 Cartesian power; yield all 3-tuples over [1, ..., n]. ’ Decrement all coordinates. “©µÞ‘ Yield [6, 9, 20]. æ. Take the dot product of each 3-tuple and [6, 9, 20]. ċ Count the occurrences of n (Positive for Chicken McNuggets numbers). ``` [Answer] # [Haskell](https://www.haskell.org/), 36 bytes ``` f n|n<1=n==0 f n=any(f.(n-))[6,9,20] ``` [Try it online!](https://tio.run/##DcoxDsIwDIXhvafwwJBIBsVJKVSqT1J1yEBERGtVwILE3dM3vMH@v2f@vB7r2loh@9skaqqhw6HZfq5cnJ29nwceOYalVZ2FKTIlpp7pynRjujNJwFAEf0GQAUOSERo84h@hI2yCSzAJvU9Lt@Vqur@rfU9uyzsVqr4d "Haskell – Try It Online") ## Explanation This solution is about as straightforward as it can get. The first line declares that for any number less than 1 it is a McNugget number if `n==0`. That is to say that `0` is a McNugget number and all negative numbers are not. The second line declares that for all other numbers, `n` is a McNugget number if it minus any of the Nugget sizes is a McNugget number. This is a pretty simple recursive search. [Answer] # [Python 3](https://docs.python.org/3/), 48 46 42 bytes ``` lambda n:n+50in b'2345679:<=?@BCEHIKNQTW]' ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKk/b1CAzTyFJ3cjYxNTM3NLKxtbewcnZ1cPT2y8wJDxW/X9BUWZeiYZSTJ6SXlZ@Zp5GcUmRRp6mgraCkoKuHZDQVgCJpAHFNBXS8osU8hSA5hUl5qWnapgaaGpq/gcA "Python 3 – Try It Online") Switches `True` and `False`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` _20$%3$¿o>3 ``` [Try it online!](https://tio.run/##y0rNyan8/z/eyEBF1Vjl0P58O@P/hgYGQYfbD094uGP@fwA "Jelly – Try It Online") Port of [my Python answer](https://codegolf.stackexchange.com/a/132708/48934), but slightly modified: subtract `20` until divisible by `3`, then check whether it belongs to `0,6,9,...` by mapping `0` to the input (by using `or`), and then check if it is greater than `3`. The only three numbers that produce `0` upon completing the first step is `0`, `20`, or `40`, with the first one being out of the domain, and the rest being greater than `3`. [Answer] # Mathematica, 53 bytes ``` !Flatten@Table[Tr/@Tuples[{6,9,20},i],{i,#}]~FreeQ~#& ``` [Answer] # Mathematica, 30 bytes ``` {6,9,20}~FrobeniusSolve~#!={}& ``` [Try it on Wolfram Sandbox.](http://sandbox.open.wolframcloud.com/) [Answer] # Mathematica, 20 bytes ``` 0<=#-20Mod[-#,3]!=3& ``` Anonymous function. Takes a number as input and returns `True` or `False` as output. Logic copied from [Leaky Nun's answer](https://codegolf.stackexchange.com/a/132708), with some added abuse of `Inequality`. [Answer] # x86-64 Machine Code, 22 bytes ``` 48 B8 41 92 34 6D DB F7 FF FF 83 F9 40 7D 03 48 D3 E8 83 E0 01 C3 ``` The above bytes define a function in 64-bit x86 machine code that determines whether the input value is a Chicken McNugget number. The single positive integer parameter is passed in the `ECX` register, following the [Microsoft 64-bit calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_x64_calling_convention) used on Windows. The result is a Boolean value returned in the `EAX` register. **Ungolfed assembly mnemonics:** ``` ; bool IsMcNuggetNumber(int n) ; n is passed in ECX movabs rax, 0xFFFFF7DB6D349241 ; load a 64-bit constant (the bit field) cmp ecx, 64 jge TheEnd ; if input value >= 64, branch to end shr rax, cl TheEnd: and eax, 1 ; mask off all but LSB ret ``` Obviously, this plays heavily off of [Anders Kaseorg's solution in Python](https://codegolf.stackexchange.com/a/132717/58518), in that it is based around a bit-field representing the values that are Chicken McNugget numbers. Specifically, each bit in this field that corresponds to a valid Chicken McNugget number is set to 1; all other bits are set to 0. (This considers 0 to be a valid Chicken McNugget number, but if you don't like that, your preference is a single-bit modification away.) We start off by simply loading this value into a register. It is a 64-bit value, which already takes 8 bytes to encode, plus we need a one-byte REX.W prefix, so we are really being quite spendthrift in terms of bytes, but this is the heart of the solution, so I guess it's worth it. We then shift the field right by the input value.\* Finally, we mask off all but the lowest-order bit, and that becomes our Boolean result. However, since you cannot shift by more than the number of bits actually in the value, this works only for inputs from 0–63. To support higher input values, we insert a test at the top of the function that branches to the bottom of the input value is >= 64. The only thing interesting about this is the we *preload* the bit-field constant in `RAX`, and then branch down to the instruction that masks off the lowest-order bit, thus ensuring that we always return 1. **[Try it online!](https://tio.run/##LY9Rb4IwFIWfub/ihsWkRVxwEMXgfED0T9iF1ILaRGApdWmy@NfHruLDyUnznZ6eqtlZqWFQXdtbVBdp0KWLbVfVhy/8RF@4JBUuJyVz4VYfwsWJcItCuCIXbr8k7UelMfmKcpFwS@JRPN4tyHfpyHfEIurZxn4GvZVWKyzzrrtiWUprjT7ebF2WjDV9KY@ac2QBzdm7ljPdWk6LXusyAHjTrbreqhrXva10937ZAFAKG6nbRxylOavw@akgeBx@OPyCd@oMPrGmuigjW@M8mmc4nWoOHiW8b0P8xPzxbTbRXNjZBidaWGH9EHWIL0QbM/Du4IFnanszLTXCfRj@1Okqz/0waxbJPw "C (gcc) – Try It Online")** (The C function call there is annotated with an attribute that causes GCC to call it using the Microsoft calling convention that my assembly code uses. If TIO had provided MSVC, this wouldn't be necessary.) \_\_ \* As an alternative to a shift, we could have used the x86 `BT` instruction, but that's 1 byte longer to encode, so no advantage. Unless we were *forced* to use a different calling convention that didn't conveniently pass the input value in the `ECX` register. This would be a problem because `SHR` *requires* that its source operand be `CL` for a dynamic shift count. Therefore, a different calling convention would require that we `MOV`ed the input value from whatever register it was passed in to `ECX`, which would cost us 2 bytes. The `BT` instruction can use *any* register as a source operand, at a cost of only 1 byte. So, in that situation, it would be preferable. `BT` puts the value of the corresponding bit into the carry flag (CF), so you would use a `SETC` instruction to get that value in an integer register like `AL` so it could be returned to the caller. --- **Alternative implementation, 23 bytes** Here is an alternative implementation that uses modulo and multiplication operations to determine whether the input value is a Chicken McNugget number. It uses the [System V AMD64 calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI), which passes the input value in the `EDI` register. The result is still a Boolean, returned in `EAX`. Note, though, that unlike the above code, this is an *inverse* Boolean (for implementation convenience). It returns `false` if the input value is a Chicken McNugget number, or `true` if the input value is *not* a Chicken McNugget number. ``` ; bool IsNotMcNuggetNumber(int n) ; n is passed in EDI 8D 04 3F lea eax, [rdi+rdi*1] ; multiply input by 2, and put result in EAX 83 FF 2B cmp edi, 43 7D 0E jge TheEnd ; everything >= 43 is a McNugget number 99 cdq ; zero EDX in only 1 byte 6A 03 push 3 59 pop rcx ; short way to put 3 in ECX for DIV F7 F1 div ecx ; divide input value by 3 6B D2 14 imul edx, edx, 20 ; multiply remainder of division by 20 39 D7 cmp edi, edx 0F 9C C0 setl al ; AL = (original input) < (input % 3 * 20) TheEnd: C3 ret ``` What's ugly about this is the need to explicitly handle input values >= 43 by a compare-and-branch at the top. There are obviously other ways of doing this that don't require branching, like [caird coinheringaahing's algorithm](https://codegolf.stackexchange.com/a/132767/58518), but this would take a *lot* more bytes to encode, so isn't a reasonable solution. I figure I'm probably missing some bit-twiddling trick that would make this work out more elegantly and be fewer bytes than the bitfield-based solution above (since encoding the bitfield itself takes so many bytes), but I've studied this for a while and still can't see it. Oh well, [try it online](https://tio.run/##LU/tbsIwDPxdP4XphNRAGS1lfKgMaZT1JZZpKiGUSG06pQFFmnj1dS7jh@XL3dkXi0kpRNeJRrcWxbkw6FaLrDnKj098RZ@71Z67aM5dkhNOuMupz3bcLXv@nbv1mrvFG2HSXgjnS6qYOPLsZ9zF/Szxe@Ijml1n3GURVeKn0NrCKoFfu6apMBhRdO40C5S2jNIfP0kB4ElpUV2OEjetParm@bwFIBfWhdK9HQtTivB@wGjUP64MfsA7NQbvsqJ1UUptg3EUpzgeKwYeObxvQ/op8P@zg6Fi3E62OFTccuuHqEIcPDTFWIo4naKRtawP0pCqr9K0Eg90gCw0Ke2lsgPwbuCBZ6S9GE3BcOu6X3GqirLtJvVi/gc "C (gcc) – Try It Online") anyway! [Answer] # 05AB1E, 17 16 bytes ``` ŽGç₂в©IED®âO«]I¢ ``` [Try it online!](https://tio.run/##ASUA2v9vc2FiaWX//8W9R8On4oKC0LLCqUlFRMKuw6JPwqtdScKi//85 "05AB1E – Try It Online") Explanation ``` ŽGç₂в The list [6, 9, 20] © Store this list in register_c IE Loop <input> number of times ®â Cartesian product stack contents with list in register_c O Sum up the contents of each sub array D « List duplicated before taking Cartesian product, concat ] End for loop I¢ Count occurences of input ``` [Answer] # JavaScript (ES6), ~~69~~ 64 bytes ``` n=>'ABCDEFHIKLNOQRTWXZ]`cfl'.includes(String.fromCharCode(n+65)) ``` ``` f= n=>'ABCDEFHIKLNOQRTWXZ]`cfl'.includes(String.fromCharCode(n+65)) ``` ``` <input onkeydown=a.innerHTML=f(this.value)> <pre id=a> ``` Outputs `false` for Chicken McNugget numbers, `true` otherwise. [Answer] # Java, ~~21~~ ~~57~~ 24 bytes **[Try it online!](https://tio.run/##ZZFfa9swFMXf/SlOCxtOopjETveH1IZstGyQ9cVsL2MMxZFdpc61ka7ThZLPnl1nCRvsQUic@9O590gbvdPjpjW0WT8d7bZtHGMjWtSxraPhPAiKWnuPj4@2eDL0pXjoqsrwQ7ddGefxEgRA6@xOs4FnzbZAaUnXyA3ffiY2lXEZ7hfL/O7nt8Xy612OFGSe8Un7x57JwoVzeu8j7ZfWcyh@OAHny99/4AUThalCrJAozBRuFN4qvBOxL0hlKvpUCtM3sqQ0fS@04LHosdCxsIlwiTCJ1GcJDoPB/DR8t6pl6PPsu8ausdWWwpydpUq6a1f5gQTt5yobh9ASw0qKyVy2W8xu5hiN7AUB8r1ns42ajiN5GeKaQosRrjHOYH61pmCzTq9Fufr3WaKiIZbGPhQroRV0wZ2uT2QZHmmchTROaRi/SobxZJClk9d0lSZHBdtH6Tsfgn79F2rVNLXRJC5/f7bsqGDbUHR/Plw@S@HDHzxDKdaSlS7RnOHOiU2k27beh3TqeggOx98)** Golfed: ``` n->(n-=n*2%3*20)>=0&n!=3 ``` Ungolfed: ``` import java.util.*; public class ChickenMcNuggetNumbers { private static final Set<Integer> FALSE_VALUES = new HashSet<>(Arrays.asList( new Integer[] { 0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, 28, 31, 34, 37, 43 })); public static void main(String[] args) { for (int i = 0; i < 45; ++i) { System.out.println(i + " -> expected=" + !FALSE_VALUES.contains(i) + ", actual=" + f(n->(n-=n*2%3*20)>=0&n!=3, i)); } } public static boolean f(java.util.function.Function<Integer, Boolean> f, int n) { return f.apply(n); } } ``` [Answer] # [Add++](https://github.com/SatansSon/AddPlusPlus), 35 bytes ``` D,f,@,A6$%0=@20$%0=A3$%0=A8<A43<s1< ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ03HQcfRTEXVwNbByABEORqDSQsbRxNjm2JDm////5sYAQA "Add++ – Try It Online") Look ma, no while loops. Or strings. Or lists. Or really anything that helps save bytes. But mainly because Add++ doesn't know what any of those are. 3 months later, I realised that this was invalid, and fixed it. Somehow, that golfed it by 13 bytes. This is a function that takes one argument and tests whether that argument is a Chicken McNugget number or not. ## How it works ``` D,f,@, - Create a monadic (one argument) function called f (example argument: 3) A - Push the argument again; STACK = [3 3] 6 - Push 6; STACK = [3 3 6] $ - Swap the top two values; STACK = [3 6 3] % - Modulo; STACK = [3 3] 0 - Push 0; STACK = [3 3 0] = - Are they equal? STACK = [3 0] @ - Reverse the stack; STACK = [0 3] 20 - Push 20; STACK = [0 3 20] $ - Swap the top two values; STACK = [0 20 3] % - Modulo; STACK = [0 3] 0 - Push 0; STACK = [0 3 0] = - Are they equal? STACK = [0 0] A - Push the argument; STACK = [0 0 3] 3 - Push 3; STACK = [0 0 3 3] $ - Swap the top two values; STACK = [0 0 3 3] % - Modulo; STACK = [0 0 0] 0 - Push 0; STACK = [0 0 0 0] = - Are they equal? STACK = [0 0 1] A - Push the argument; STACK = [0 0 1 3] 8 - Push 8; STACK = [0 0 1 3 8] < - Less than; STACK = [0 0 1 0] A - Push the argument; STACK = [0 0 1 0 3] 43 - Push 43; STACK = [0 0 1 0 3 43] < - Less than; STACK = [0 0 1 0 0] s - Sum; STACK = [1] 1 - Push 1; STACK = [1 1] < - Less than; STACK = [0] ``` [Answer] # [Python 2](https://docs.python.org/2/), 51 bytes *-1 byte thanks to @LeakyNun* ``` lambda n:max(n>43,25<n>n%3>1,5<n>n%3<1,n in[20,40]) ``` [Try it online!](https://tio.run/##LcmxCoAgFAXQX3lLoOBgVkuUP1INRlkP6hriUF9vDW0HzvWkPcBk34/5cOe8OEJ7ulvA1pUyTQeLorKl@tWVCsQYjFa1nmS@IiMNTD5E4i8oOmyraLSWxJ4QEnnBcsov "Python 2 – Try It Online") Footer prints all non McNugget numbers [Answer] # [Pyth](https://github.com/isaacg1/pyth), 15 bytes ``` fg.{CM" "{T./ ``` [Try it online!](http://pyth.herokuapp.com/?code=fg.%7BCM%22%06%09+%22%7BT.%2F&test_suite=1&test_suite_input=0%0A6%0A7%0A12%0A15%0A21%0A40%0A42&debug=0) The string contains the characters corresponding to codepoints 6, 9, and 20. [Answer] # Haskell, ~~64~~ 56 bytes I didn't do any bit trickery, but looking at the other answers it might actually be shorter to import the `Bits` module and use those methods. This approach checks much more directly. ``` f x=(\l->elem x[i*6+j*9+k*20|i<-l,j<-l,k<-l,x/=0])[0..x] ``` [Answer] # Javascript, ~~92~~ ~~78~~ 72 bytes \*saved 14 bytes thanks to @Jonasw ``` a=>!(a in[0,1,2,3,4,5,7,8,10,11,13,14,16,17,19,22,23,25,28,31,34,37,43]) ``` Uses the fact that "All integers are McNugget numbers except 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, 28, 31, 34, 37, and 43." from @LeakyNun's comment [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 19 bytes ``` ⊢∊6 9 20+.×⍨∘↑∘⍳3⍴⊢ ``` with `⎕IO←0` Same algorithm with [Dennis's answer](https://codegolf.stackexchange.com/a/132709/6972) [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qn/6O2CQb/04Dko65Fjzq6zBQsFYwMtPUOT3/Uu@JRx4xHbRNBZO9m40e9W4BKuICagIrTgBTlzP//zbjMuQyNuAxNuYwMuUwMuEyMAA "APL (Dyalog Classic) – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), 26 bytes ``` .+ $* ^(1{6}|1{9}|1{20})+$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLK07DsNqstsaw2hJEGBnUamqr/P9vxmXOZWjEZWjKZWTIZWLAZWIEAA "Retina – Try It Online") [Answer] # Excel, 87 bytes ``` =AND(OR(MOD(A1,3)*MOD(A1,20)*IF(A1>43,MOD(A1-40,3),1)*IF(A1>23,MOD(A1-20,3),1)=0),A1>5) ``` Alternatively, 92 bytes: ``` =CHOOSE(MOD(A1,3)+1,A1>3,IF(A1>43,MOD(A1-40,3)=0,A1=40),IF(A1>23,MOD(ABS(A1-20),3)=0,A1=20)) ``` [Answer] # PHP, 69+1 bytes ``` for($n=$argn;$n>0;$n-=20)if($n%3<1)for($k=$n;$k>0;$k-=9)$k%6||die(1); ``` exits with `1` for a Chicken McNugget Number, `0` else. Run as pipe with `-n` or [try it online](http://sandbox.onlinephpfunctions.com/code/62476ac2ca9c1cef991499ce4c7cfd847e062c40). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` Œṗḟ€“©µÞ‘Ạ ``` [Try it online!](https://tio.run/##y0rNyan8///opIc7pz/cMf9R05pHDXMOrTy09fC8Rw0zHu5a8P9wO1DQ@fCGIwse7u4@uschC6QGrExB107hUcPcSCAv61HjvkPbgHBr0P//pgYA "Jelly – Try It Online") Outputs in the opposite direction; returning `false` indicates that the input is a Chicken McNugget number. The TIO footer swaps this for you. ## How it works ``` Œṗḟ€“©µÞ‘Ạ - Main link. Takes an integer n on the left Œṗ - Integer partitions of n; all ways to sum integers to n “©µÞ‘ - Yield [6, 9, 20] € - Over each partition P: ḟ - Remove all 6s, 9s and 20s Ạ - Are all resulting lists non-empty? ``` [Answer] # [Python 2](https://docs.python.org/2/), 61 bytes ``` lambda n:n in[int(c,36)for c in'1234578ABDEGHJMNPSV']+[37,43] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKk8hMy86M69EI1nH2EwzLb9IIRkoom5oZGxiam7h6OTi6u7h5esXEBymHqsdbWyuY2Ic@7@gCKhDIU3D2FzzPwA "Python 2 – Try It Online") [Answer] # Mathematica, 59 bytes ``` !Select[IntegerPartitions@#,{6,9,20}~SubsetQ~#&]=={}&&#!=0& ``` [Answer] # Javascript 37 bytes Takes a positive integer `n` and outputs `true` for Chicken McNugget numbers and `false` for others. ``` F=n=>!(n<0||(n%6&&!F(n-9)&&!F(n-20))) ``` ## Explanation ``` F=n=>!( // negate the internal test for non-Chicken McNugget numbers n<0 || ( // if n < 0, or n%6 && // if n % 6 is truthy, !F(n-9) && // and n-9 is not a Chicken McNugget number !F(n-20) // and n-20 is not a Chicken McNugget number // then n is not a Chicken McNugget number ) ) ``` The recursion on this function is heinous, and for any sufficiently large `n`, you will exceed call stack limits. Here's a version that avoids those limits by checking if `n` is larger than the largest non-Chicken McNugget number (43 bytes [bonus points for being the largest non-Chicken McNugget number?]): ``` F=n=>n>43||!(n<0||(n%6&&!F(n-9)&&!F(n-20))) ``` ``` F=n=>n>43||!(n<0||(n%6&&!F(n-9)&&!F(n-20))) $('#input').on('keyup', () => $('#output').text(F(parseInt($('#input').val(), 10)))) ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="input" /> <span id="output"></span> ``` [Answer] # JavaScript ES5, 46 bytes ``` n=>n>5&&(!(n%20)||(n<24?!(n%3):n<44?n%3-1:1)); ``` **Explicit boolean answer, 50 bytes:** ``` n=>!!(n>5&&(!(n%20)||(n<24?!(n%3):n<44?n%3-1:1))); ``` Clumsy, but it gets the job done. Returns `false` or `0` for every value that isn't 0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, 28, 31, 34, 37, or 43, and `true`, `-1`, or `1` for everything else. Explicit solution returns `true` or `false` only. ``` n=>!!( ); forces Boolean type (optional) n>5 false for 0, 1, 2, 3, 4, 5 (and negative inputs) !(n%20) explicit true for 20, 40 n<24?!(n%3) false for 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23 n<44?n%3-1 false for 25, 28, 31, 34, 37, 43 ``` [Answer] # Clojure 33 bytes An on ok quick attempt: `#(-> %(rem 20)(rem 9)(rem 6)(= 0))` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 44 bytes ``` n->n&&#(1/(1-x^6)/(1-x^9)/(1-x^20)%x^n++)==n ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1y5PTU1Zw1Bfw1C3Is5ME0JbQmkjA03Virg8bW1NW9u8/2n5RRp5QF0GOgqmQFxQlJlXAhRQUtC1AxJpGnmampr/AQ "Pari/GP – Try It Online") ]
[Question] [ ### Task Find the set of numbers such that the binary representation contains two or more runs of `1` separated by at least one `0`. For example, the for the numbers that are 4 bits long: ``` 0 0000 (no ones) 1 0001 (only one run) 2 0010 (only one run) 3 0011 (only one run) 4 0100 (only one run) 5 0101 Valid 6 0110 (only one run) 7 0111 (only one run) 8 1000 (only one run) 9 1001 Valid 10 1010 Valid 11 1011 Valid 12 1100 (only one run) 13 1101 Valid 14 1110 (only one run) 15 1111 (only one run) ``` ### Input An integer provided to the application via some input in the range `3 .. 32`. This represents the maximum number of bits to count up to. The input of `n` indicates that the numbers `0 .. 2n-1` need to be examined. ### Output A delimited (your choice) list of all numbers meeting the criteria. The numbers are to be presented in numeric order. An extra trailing delimiter is acceptable. Data structure enclosures (e.g. `[]` and similar) are also acceptable. ### Example ``` Input: 3 Output: 5 Input: 4 Output: 5, 9, 10, 11, 13 Input: 5 Output: 5, 9, 10, 11, 13, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 29 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - the answer with the least amount of bytes wins. [Answer] ## Python, 48 ``` lambda n:[i for i in range(2**n)if'01'in bin(i)] ``` I had been vastly overthinking this. We just need to check if the binary expansion contains `'01'`. For there to be two runs of ones, the one on the right must be preceded by a `0`. If there's only one run, there won't be any leading `0`'s, so that won't happen. --- Old answer: ``` lambda n:[i for i in range(2**n)if len(set(bin(i).split('0')))>2] ``` The Python binary representation works very nicely here. A binary number is written like `bin(9)=='0b10110'`. Splitting at `'0'` results in a list of * Empty strings to the left of the initial `0`, between any two consecutive `0`'s, and to the right of any final `0` * The letter `b` followed by one or more leading ones * Runs of `1`'s that are not leading The first two categories always exist, but the last one only exists if there is a run one `1`'s that doesn't contain the leading `'1'`, and so only if there's more than one run of `1`'s. So, it suffices to check if the list contains more than `2` distinct elements. Python 3.5 saves 2 chars by unpacking `{*_}` in place of `set(_)`. [Answer] ## Ruby, ~~44~~ ~~40~~ 38 chars [crossed out 44 is still regular 44 ;(](https://codegolf.stackexchange.com/questions/48100/very-simple-triangles/48101#comment113015_48101) ``` ->n{(0..2**n).select{|x|/01/=~'%b'%x}} ``` An anonymous function (proc, actually) that takes an integer and returns an array. ~~Uses the regex `/10+1/`: a `1`, at least one `0`, and then another `1`.~~ @histocrat points out that if `01` is anywhere in the string, there *must* be a `1` somewhere before it. [Answer] # Pyth, 12 bytes ``` f<2r.BT8U^2Q ``` [Try it online.](https://pyth.herokuapp.com/?code=f<2r.BT8U%5E2Q&input=5) ### Idea The binary representation of any positive number always begins with a run of **1**s, possibly followed by other, alternating runs of **0**s and **1**s. If there are at least three separate runs, two of them are guaranteed to be runs of **1**s. ### Code ``` (implicit) Store the evaluated input in Q. ^2Q Calculate 2**Q. f U Filter; for each T in [0, ..., 2**Q-1]: .BT Compute T's binary representation. r 8 Perform run-length encoding. This returns a list of character/run-length pairs. <2 Discard the trailing two pairs. This returns a non-empty array if there are more than 2 runs. Keep T if the array was truthy (non-empty). ``` [Answer] # Julia, ~~43~~ 41 bytes ``` n->filter(i->ismatch(r"01",bin(i)),1:2^n) ``` This creates an unnamed function that accepts an integer and returns an array. It uses histocrats's regex trick (used in Doorknob's answer), where `01` will only match if there's a preceding 1. Ungolfed: ``` function f(n::Int) # Take the integers from 1 to 2^n and filter them down to # only those such that the binary representation of the integer # matches the regex /01/. filter(i -> ismatch(r"01", bin(i)), 1:2^n) end ``` [Answer] # Matlab, ~~79 68 64~~ 59 The idea is interpreting the binary number as array of zeros and ones, and then calculating the absolute difference between each pair of neighbours. If we have two or more times a difference of 1, then we obviously have a run of two or more ones. Note that this only works if we represent the binary number without leading zeros. ``` @(n)find(arrayfun(@(k)sum(~~diff(dec2bin(k)+0))>1,1:2^n-1)) ``` Old versions: ``` k=1:2^input('')-1;k(arrayfun(@(k)sum(~~diff(dec2bin(k)+0))>1,k)) for k=1:2^input('')-1;if sum(~~diff(dec2bin(k)+0))>1;disp(k);end;end for k=1:2^input('')-1;if sum(~~conv(dec2bin(k)+0,[-1,1],'v'))>1;disp(k);end;end ``` [Answer] # JavaScript (ES7), ~~89~~ ~~85~~ ~~72~~ ~~69~~ 62 bytes Holy cow, creating ranges in JS is not easy. ~~Perhaps it would be shorter with an actual `for` loop.~~ Nope, I lied; it's actually a bit longer. Oh well. I guess I'll just have to settle for 27 bytes saved. (7 thanks to Mwr247!) ``` x=>[for(a of Array(1<<x).keys())if(/01/.test(a.toString(2)))a] ``` Works properly in the latest versions of Firefox, but probably not in any other browser. Try it out: ``` <!-- Try the test suite below! --><strong id="bytecount" style="display:inline; font-size:32px; font-family:Helvetica"></strong><strong id="bytediff" style="display:inline; margin-left:10px; font-size:32px; font-family:Helvetica; color:lightgray"></strong><br><br><pre style="margin:0">Code:</pre><textarea id="textbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><pre style="margin:0">Input:</pre><textarea id="inputbox" style="margin-top:5px; margin-bottom:5px">5</textarea><br><button id="testbtn">Test!</button><button id="resetbtn">Reset</button><br><p><strong id="origheader" style="font-family:Helvetica; display:none">Original Code Output:</strong><p><div id="origoutput" style="margin-left:15px"></div><p><strong id="newheader" style="font-family:Helvetica; display:none">New Code Output:</strong><p><div id="newoutput" style="margin-left:15px"></div><script type="text/javascript" id="golfsnippet">var bytecount=document.getElementById("bytecount");var bytediff=document.getElementById("bytediff");var textbox=document.getElementById("textbox");var inputbox=document.getElementById("inputbox");var testbtn=document.getElementById("testbtn");var resetbtn=document.getElementById("resetbtn");var origheader=document.getElementById("origheader");var newheader=document.getElementById("newheader");var origoutput=document.getElementById("origoutput");var newoutput=document.getElementById("newoutput");textbox.style.width=inputbox.style.width=window.innerWidth-50+"px";var _originalCode="x=>[for(a of Array(1<<x).keys())if(/01/.test(a.toString(2)))a]";function getOriginalCode(){if(_originalCode!=null)return _originalCode;var allScripts=document.getElementsByTagName("script");for(var i=0;i<allScripts.length;i++){var script=allScripts[i];if(script.id!="golfsnippet"){originalCode=script.textContent.trim();return originalCode}}}function getNewCode(){return textbox.value.trim()}function getInput(){try{var inputText=inputbox.value.trim();var input=eval("["+inputText+"]");return input}catch(e){return null}}function setTextbox(s){textbox.value=s;onTextboxChange()}function setOutput(output,s){output.innerHTML=s}function addOutput(output,data){output.innerHTML+='<pre style="background-color:'+(data.type=="err"?"lightcoral":"lightgray")+'">'+escape(data.content)+"</pre>"}function getByteCount(s){return(new Blob([s],{encoding:"UTF-8",type:"text/plain;charset=UTF-8"})).size}function onTextboxChange(){var newLength=getByteCount(getNewCode());var oldLength=getByteCount(getOriginalCode());bytecount.innerHTML=newLength+" bytes";var diff=newLength-oldLength;if(diff>0){bytediff.innerHTML="(+"+diff+")";bytediff.style.color="lightcoral"}else if(diff<0){bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgreen"}else{bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgray"}}function onTestBtn(evt){origheader.style.display="inline";newheader.style.display="inline";setOutput(newoutput,"");setOutput(origoutput,"");var input=getInput();if(input===null){addOutput(origoutput,{type:"err",content:"Input is malformed. Using no input."});addOutput(newoutput,{type:"err",content:"Input is malformed. Using no input."});input=[]}doInterpret(getNewCode(),input,function(data){addOutput(newoutput,data)});doInterpret(getOriginalCode(),input,function(data){addOutput(origoutput,data)});evt.stopPropagation();return false}function onResetBtn(evt){setTextbox(getOriginalCode());origheader.style.display="none";newheader.style.display="none";setOutput(origoutput,"");setOutput(newoutput,"")}function escape(s){return s.toString().replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}window.alert=function(){};window.prompt=function(){};function doInterpret(code,input,cb){var workerCode=interpret.toString()+";function stdout(s){ self.postMessage( {'type': 'out', 'content': s} ); }"+" function stderr(s){ self.postMessage( {'type': 'err', 'content': s} ); }"+" function kill(){ self.close(); }"+" self.addEventListener('message', function(msg){ interpret(msg.data.code, msg.data.input); });";var interpreter=new Worker(URL.createObjectURL(new Blob([workerCode])));interpreter.addEventListener("message",function(msg){cb(msg.data)});interpreter.postMessage({"code":code,"input":input});setTimeout(function(){interpreter.terminate()},1E4)}setTimeout(function(){getOriginalCode();textbox.addEventListener("input",onTextboxChange);testbtn.addEventListener("click",onTestBtn);resetbtn.addEventListener("click",onResetBtn);setTextbox(getOriginalCode())},100);function interpret(code,input){window={};alert=function(s){stdout(s)};window.alert=alert;console.log=alert;prompt=function(s){if(input.length<1)stderr("not enough input");else{var nextInput=input[0];input=input.slice(1);return nextInput.toString()}};window.prompt=prompt;(function(){try{var evalResult=eval(code);if(typeof evalResult=="function"){var callResult=evalResult.apply(this,input);if(typeof callResult!="undefined")stdout(callResult)}}catch(e){stderr(e.message)}})()};</script> ``` (Snippet taken from [this page](http://meta.codegolf.stackexchange.com/questions/7113/a-golfing-snippet)) Suggestions welcome! [Answer] # Haskell, ~~68~~ ~~61~~ 53 bytes Improvement from Damien ``` g x|x`mod`4==1=x>4|2>1=g$x`div`2 a x=filter g[1..2^x] ``` History: This fixes the bug(Switched == and =, and square instead of power of two). And replace true with 2>1 and false with 1>2. Also thanks to point out that 2^x is always fail. Thanks to Thomas Kwa and nimi ``` g x|x<5=1>2|x`mod`4==1=2>1|2>1=g$x`div`2 a x=filter g[1..2^x] ``` Originally ``` g x|x<5=False|x`mod`4=1==True|2>1=g$x`div`2 a x=filter g[1..(x^2-1)] ``` If it have to be full program, ``` g x|x<5=False|x`mod`4==1=True|2>1=g$x`div`2 main=interact$show.a a x=filter g[1..2^(read x)] ``` [Answer] # APL, ~~34~~ 27 bytes ``` {0~⍨{⍵×2<+/2≢/⍵⊤⍨⍵/2}¨⍳2*⍵} ``` This creates an unnamed monadic function that accepts an integer on the right and returns an array. Explanation: ``` }¨⍳2*⍵} ⍝ For each integer from 1 to 2^input... ⍵⊤⍨⍵/2 ⍝ Get the binary representation as a vector 2≢/ ⍝ Pairwise non-match, yielding a boolean vector 2<+/ ⍝ Check whether the number of trues is >2 ⍵× ⍝ Yield the integer if so, otherwise 0 {0~⍨{ ⍝ Remove the zeros from the resulting array ``` Saved 7 bytes thanks to Dennis! [Answer] # [C (gcc)](https://gcc.gnu.org/), 111 99 bytes ``` long i,x;main(a,b)char**b;{for(;++i<1L<<atol(b[1]);x>>ffsl(~x)-1&&printf("%ld,",i))x=i>>ffsl(i)-1;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z8nPy9dIVOnwjo3MTNPI1EnSTM5I7FISyvJujotv0jDWls708bQx8YmsSQ/RyMp2jBW07rCzi4trThHo65CU9dQTa2gKDOvJE1DSTUnRUdJJ1NTs8I2E6oiE6jAuvb///@mAA "C (gcc) – Try It Online") 12 bytes shaved of thanks to @ceilingcat! Ungolfed: ``` int main(int a, char **b) { for(long i = 0, x = 0; ++i < (1LL << atol(b[1])); ) { x = i >> (ffsl(i) - 1); if (x >> (ffsl(~x) - 1)) printf("%ld,", i); } } ``` The function ffsl() gives you the index of the first bit that is set in a long integer. So we loop from `i = 1` to 2^number\_of\_bits. We set `x` to `i` shifted right until we have removed all consecutive zero bits on the least significant end. Then, we shift `x` right until we have removed all consecutive 1 bits at the least signficant end. If the result is still non-zero, we found a match. [Answer] # R, 55 47 bytes (with some help from @Alex.A) ``` cat(grep("10+1",R.utils::intToBin(1:2^scan()))) ``` R doesn't have a built in function to display converted numbers in a convenient way, so I'm using `R.utils::intToBin` for this, while all the rest is pretty much just report the location of the matched regex expression and print to STDOUT while separated by a space. [Answer] # CJam, 14 ``` 2qi#{2b2,#)},p ``` 3 bytes shorter thanks to Dennis. [Try it online](http://cjam.aditsu.net/#code=2qi%23%7B2b2%2C%23)%7D%2Cp&input=5) [Answer] # JavaScript (ES6), ~~69~~ ~~68~~ ~~67~~ 62 bytes ``` a=>[...Array(1<<a).keys()].filter(i=>/01/.test(i.toString(2))) ``` Today I discovered a new shorter way to dynamically fill arrays without the use of fill or map. Doing `x=>[...Array(x).keys()]` will return an array of range 0 to x. If you want to define your own range/values, use `x=>[...Array(x)].map((a,i)=>i)`, as it's just a few bytes longer. [Answer] ## Java, ~~214~~ ~~165~~ ~~155~~ ~~154~~ ~~148~~ ~~141~~ 110 bytes This submission exploits the fact that a binary string representation of a number in Java never has a leading zero. If the string "01" appears in the binary representation of a number, that *must* mark the second occurrence of the number "1". Golfed: ``` String f(int l){String r="";for(long i=5;i<1L<<l;++i)if(Long.toString(i,2).contains("01"))r+=i+", ";return r;} ``` Ungolfed: ``` public class NumbersWithMultipleRunsOfOnes { public static void main(String[] a) { // @formatter:off String[][] testData = new String[][] { { "3", "5" }, { "4", "5, 9, 10, 11, 13" }, { "5", "5, 9, 10, 11, 13, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 29" } }; // @formatter:on for (String[] data : testData) { System.out.println("Input: " + data[0]); System.out.println("Expected: " + data[1]); System.out.print("Actual: "); System.out.println(new NumbersWithMultipleRunsOfOnes().f(Integer.parseInt(data[0]))); System.out.println(); } } // Begin golf String f(int l) { String r = ""; for (long i = 5; i < 1L << l; ++i) if (Long.toString(i, 2).contains("01")) r += i + ", "; return r; } // End golf } ``` Program output (remember, trailing delimiters are acceptable): ``` Input: 3 Expected: 5 Actual: 5, Input: 4 Expected: 5, 9, 10, 11, 13 Actual: 5, 9, 10, 11, 13, Input: 5 Expected: 5, 9, 10, 11, 13, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 29 Actual: 5, 9, 10, 11, 13, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 29, ``` [Answer] # JavaScript (ES6) 76 ``` f=n=>Array(1<<n).fill().map((_,x)=>/01/.test(x.toString(2))?x+',':'').join`` //TEST for(i=1;i<16;i++)O.innerHTML+=i+' -> '+f(i)+'\n' ``` ``` <pre id=O></pre> ``` [Answer] # K5, 19 bytes This operates along similar principles as Dennis' solution, but with fewer builtins to take advantage of. ``` {&2<+/'~0=':'+!x#2} ``` First, generate a series of binary x-tuples (`+!x#2`), then for each tuple find every point that a digit does not match the previous if we treat the -1st element of the list as 0 for this purpose (`~0=':'`). Our solutions are where two is less than the sum of each run count. (`&2<+/'`). Showing each intermediate step is clearer: ``` 4#2 2 2 2 2 !4#2 (0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1) +!4#2 (0 0 0 0 0 0 0 1 0 0 1 0 0 0 1 1 0 1 0 0 0 1 0 1 0 1 1 0 0 1 1 1 1 0 0 0 1 0 0 1 1 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 1 0 1 1 1 1) ~0=':'+!4#2 (0 0 0 0 0 0 0 1 0 0 1 1 0 0 1 0 0 1 1 0 0 1 1 1 0 1 0 1 0 1 0 0 1 1 0 0 1 1 0 1 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 1 1 0 0 1 1 0 0 0) +/'~0=':'+!4#2 0 1 2 1 2 3 2 1 2 3 4 3 2 3 2 1 2<+/'~0=':'+!4#2 0 0 0 0 0 1 0 0 0 1 1 1 0 1 0 0 &2<+/'~0=':'+!4#2 5 9 10 11 13 ``` And all together: ``` {&2<+/'~0=':'+!x#2}'3 4 5 (,5 5 9 10 11 13 5 9 10 11 13 17 18 19 20 21 22 23 25 26 27 29) ``` [Answer] # Pip, 13 + 1 = 14 bytes Takes input from the command line and uses the `-s` flag for spaces between output numbers. ``` 01NTB_FI,2**a ``` Pretty straightforward: build `range(2**a)` and filter on `lambda _: "01" in toBinary(_)`. I was pretty happy about thinking up the `01` idea independently. No quotes are needed around `01` because it scans as a numeric literal (numbers and strings are the same type in Pip). [Answer] # Julia, 40 bytes ``` n->filter(i->count_ones(i$i>>1)>2,1:2^n) ``` This uses a somewhat different approach to the other Julia solution - rather than doing a string search for "01" in the bit string, it uses some mathematics to determine whether the number satisfies the condition. `i$i>>1` will have ones only in the places where the digit changes from zero to one, or one to zero. As such, there must be at least three ones for `i` to switch back and forth between zero and one enough times. `count_ones` finds the number of ones, and then `filter` removes the ones that don't have enough ones. [Answer] ## C++, ~~197~~ ~~188~~ 141 bytes Note: this was written and tested using MSVC++ 2013. It appears that `#include`ing `<iostream>` includes all of the necessary C headers to make this work. It also appears that the code is no longer truly C++, but compiling using C++ allows that header trick which reduces the code size compared to including a bunch more C headers. Using `printf` instead of `cout` also saves a couple bytes. Golfed: ``` #include<iostream> int main(int a,char**b){char c[34];for(long i=5;i<1L<<atol(b[1]);++i){_ltoa(i,c,2);if(strstr(c,"01"))printf("%ld\n",i);}} ``` Ungolfed: ``` #include <iostream> int main(int a, char **b) { char c[34]; for (long i = 5; i < 1L << atol(b[1]); ++i) { _ltoa(i, c, 2); if (strstr(c, "01")) printf("%ld\n", i); } } ``` [Answer] ## Perl 5, ~~55~~ ~~53~~ ~~49~~ ~~47~~ 41 bytes ``` sprintf("%b",$_)=~/01/&&say for 0..2**<> ``` ~~54~~ ~~52~~ ~~48~~ ~~46~~ 40 bytes, plus one for the `-E` flag instead of `-e`. --- Thanks to [xnor](/u/20260) for [the hint](/a/61419) about using `/01/` instead of `/10+1/`, which saved two bytes. Thanks to [Dennis](/u/12012) for the advice to use `<>` instead of `$ARGV[0]`, which saved six bytes. [Answer] **C, ~~84~~ 81 bytes** ``` long i,j,k;main(){for(scanf("%ld",&j);++i<1L<<j;k&k+1&&printf("%ld ",i))k=i|i-1;} ``` This is based on the comments I made on another C answer to this question about the possibility of using simple bitwise operators. It works by switching all trailing 0 bits to 1 in the statement i|(i-1). Then it switches all trailing 1 bits to 0 using k&(k+1). This will result in a zero if there is only one run of ones and non-zero otherwise. I do make the assumption that long is 64-bit but could correct this at the expense of three bytes by using int64\_t instead. Ungolfed ``` long i,j,k; main() { for(scanf("%ld",&j);++i<1L<<j;) { k=i|(i-1); if((k&(k+1)) == 0) printf("%d ",i); } } ``` [Answer] # Pyth, ~~20~~ ~~17~~ 16 bytes ``` f:.BT"10+1"ZU^2Q ``` [Live demo.](https://pyth.herokuapp.com/?code=f%3A.BT%2210%2B1%22ZU%5E2Q&input=4&debug=1) [Answer] # Python 2.7, 89 bytes ``` print[i for i in range(1,2**input())if[n[:1]for n in bin(i)[2:].split("0")].count("1")-1] ``` I think this could be golfed a bit. [Answer] # TI-BASIC, ~~34~~ ~~32~~ 30 bytes For a TI-83+/84+ series calculator. ``` For(X,5,e^(Ans If log(sum(2=int(4fPart(X/2^randIntNoRep(1,Ans Disp X End ``` For a number to contain two runs of 1s, it must contain two `10`s when we tack a trailing zero onto the binary representation. Rather than generate the binary representation and check for a `10`, we test pairs of bits mathematically by using remainder by 4 (`int(4fPart(`), which will give `2` where there is a `10`. Because we don't care about order, `randIntNoRep(` is the [shortest](https://codegolf.stackexchange.com/a/52069/39328) way to generate the list of exponents. We use `log(` to check for the number of runs: * If there are at least 2 runs, then the `log(` is positive, and the number is displayed. * If there is one run, then the `log(` is 0, and the number is not displayed. * If there are no runs (which first happens at X=2^Ans), then `log(` throws an ERR:DOMAIN, stopping the output at exactly the right point. We use `e^(Ans` as the ending argument of the `For(` loop—it's always greater than `2^Ans`, but `e^(` is a single token, so it's one byte shorter. Input/output for N=4: ``` 4:prgmRUNSONES 5 9 10 11 13 ``` Then the calculator throws an error; the error screen looks like this: ``` ERR:DOMAIN 1:Quit 2:Goto ``` When 1 is pressed, the home screen is displayed again: ``` 4:prgmRUNSONES 5 9 10 11 13 Error ``` TI calculators store all numbers in a BCD float with 14 digits of precision, not an int or binary float. Therefore, divisions by powers of two greater than `2^14` may not be exact. While I have verified that the trickiest numbers, `3*2^30-1` and `2^32-1`, are handled correctly, I have not ruled out the possibility of rounding errors. I would however be surprised if there were errors for any input. [Answer] * this doesnt beat flawr's answer but i couldnt resist the charm of the question ## matlab~~(90)~~(70) ``` j=input('');for l=2:j-1,a=1;for k=l:-1:2,a=a+2^k;a:a+2^(k-1)-2,end,end ``` ## execution `4` ans = ``` 5 ``` ans = ``` 9 10 11 ``` ans = ``` 13 ``` ## principle * The series of numbers are a result of consequent strip of 1's, which does mean f(n,l)=2^l+2^(l+1)+....2^n Any number taken from the interval ]f(n,l),f(n,l)+2^(l-1)[ where l>1 verifies this condition, so the outcome is a result of the negation of this series in terms of n. x=1 x=x+1=`01`, x=x+2^0=`11`, x=x+1=`001`, x=x+2^1=`011`, x=x+2^0=`111`, x=x+1=`0001`, x=x+2^2=`0011`, x=x+2^1=`0111`, x=x+2^0=`0111`, x=x+1=`1111` ... x+1, x=x+2^n, x=x+2^(n-1)...x=x+2^0 My program prints the range between each two lines (if exists) --- > > **Edit:** unfortunately that doesnt make it golfed more but i wanted to add another approach of proceding this idea > > > after a period of struggle i succeded to find a mathematical representation for this series which is: 2^l(0+1+2^1+...2^k) with l+k < n =2^l(2^k-1) **score=90** ``` @(n)setdiff(0:2^n-1,arrayfun(@(x)2^mod(x,(n+1)-fix(x/(n+1)))*(2^fix(x/(n+1))-1),0:(n+1)^2)) ``` [Answer] # C, ~~103~~ 102 bytes ``` long i,x;main(int a,char**b){for(;++i<1L<<atoi(b[1]);)for(x=i;x>4&&(x%4!=1||!printf("%ld,",i));x/=2);} ``` Expanding (actually contracting) on G.Sliepen entry, taking advantage of xnor remark on the `01` pattern in the binary representation, but using only standard functions and some bit twiddling. Ungolfed version: ``` long i, x; main(int a, char**b) { for (; ++i < 1L << atoi(b[1]);) { for (x = i; x > 4 && (x % 4 != 1 || !printf("%ld,", i)); x /= 2) ; } } ``` The inner loop scans `i` for the binary pattern `01` by iteratively shifting `x` to the right as long as it has 3 bits left. `printf` returns the number of characters printed, hence never `0`, so the inner loop test fails after the `printf`, avoiding the need for a `break` statement. # C++, ~~129~~ 128 bytes Adapting the same idea, the C++ variant is here: ``` #include<iostream> long i,x;int main(int a,char**b){for(;++i<1L<<atoi(b[1]);)for(x=i;x>4&&(x%4!=1||!(std::cout<<i<<','));x/=2);} ``` Technically, I should make `i` a `long long` to ensure 64 bit operation and compute upto `2^32` for an extra 5 bytes, but modern platforms have 64 bit ints. [Answer] # JavaScript ES6, 60 bytes ## Code ``` n=>[...Array(1<<n).keys()].filter(g=x=>x>4?x%4==1|g(x>>1):0) ``` [Try it online!](https://tio.run/##BcHRCsIgFADQ975iL8G9W8mMQdC8Rt8RPchSuSUaOsJB/27nvMzXlCXzZz3G9LTNUYuk70KIW85mA6lURPG2WwF8CMdhtRk8VdJVT9e6n4jkz0PVWuJlxOZSBqZxZnWeeRhw13VLiiUFK0LycOp7PjhgxPYH "JavaScript (Node.js) – Try It Online") ## Explanation ``` [...Array(1<<n).keys()] Create an array of numbers from 0 to 2^n-1 .filter( Find the numbers which meet criteria g=x=>x>4? :0 If x is less than or equal to four return zero (false/invalid) x>4?x%4==1| If the binary pattern ends with 01 return one (true/valid) g(x>>1) Otherwise bitshift right by one and try again ``` [Answer] # PowerShell, 80 bytes ``` while([Math]::Pow(2,$args[0])-gt$n++){$n|?{[Convert]::ToString($n,2)-match"01"}} ``` [Answer] # Python, 44 Bytes Okay, this could probably be shorter but it's my first codegolf: ``` x=1 while True: if '01' in bin(x): print(x) x+=1 ``` Think this answers the question, please don't down vote if it doesn't, just post whats wrong with it below. [Answer] another different matlab answer of good score. ## matlab ~~60~~(57) ``` @(n)find(mod(log2(bitcmp(1:2^n,fix(log2(1:2^n)+1))+1),1)) ``` ## execution ``` >> @(n)find(mod(log2(bitcmp(1:2^n,fix(log2(1:2^n)+1))+1),1)) ``` `ans =` ``` @(n)find(mod(log2(bitcmp(1:2^n,fix(log2(1:2^n)+1))+1),1)) ``` `>> ans(5)` `ans =` ``` 5 9 10 11 13 17 18 19 20 21 22 23 25 26 27 29 ``` --- * ***The idea*** is picking up numbers x where the binary representation of -(x)+1 doesnt contain only one occurence of `1` example: `0000111` is rejected because ~x=`1111`,~x+1=`00001` contains one digit=1 `0100111` is accepted because ~x=`1011`,~x+1=`0111` contains many 1's [Answer] # k4, ~~32~~ 28 bytes ``` {&1<+/'1='-':'0b\:'o:!*/x#2} ``` --- explanation ``` */x#2 /x^2 o:! /assign o to [0,x^2 -1), e.g. for x=2, o<-0 1 2 3 0b\:' /get binary value of each array elem -':' /get delta of adjacent digits in each binary num +/'1=' /sum each array to find how many deltas=1 &1< /return elems where there were greater than 1 deltas=1 ``` ]
[Question] [ Write a program to play the popular English nursery rhyme. [![Sheet music](https://i.stack.imgur.com/t6uGH.png)](//commons.wikimedia.org/wiki/File:Twinkle_Twinkle_Little_Star.png) (This file is licensed under the Creative Commons [Attribution-Share Alike 3.0 Unported](//creativecommons.org/licenses/by-sa/3.0/deed.en) license. Attribution: [Helix84](//en.wikipedia.org/wiki/User:Helix84) at the [English language Wikipedia](//en.wikipedia.org/wiki/); [Blahedo](//en.wikipedia.org/wiki/User:Blahedo) at the [English language Wikipedia](//en.wikipedia.org/wiki/).) Some Wikipedia articles that may be useful: * [Twinkle Twinkle Little Star](http://en.wikipedia.org/wiki/Twinkle_Twinkle_Little_Star) (has an audio clip of what your program's output should sound like) * [Modern musical symbols](http://en.wikipedia.org/wiki/Modern_musical_symbols) (to learn about the music notation used above) * [Musical note#Note frequency (in hertz)](https://en.wikipedia.org/wiki/Musical_note#Note_frequency_(in_hertz)) (the formula for calculating the frequency of each note) Some guidelines for your submission: * Your program must use the computer's sound card. If your programming language doesn't have convenient access to audio hardware, your program must create an output file in some standard format such as WAV or MIDI. * Your program must actually generate its output. For example, embedding the Ogg Vorbis file from Wikipedia would not be allowed. * The audio quality must be acceptable. At the very least, the song should be easily recognizable. Preferably, it should sound good as well. * The focus should be on code size, sound quality, or both (explain which one you decided on). Elegant solutions would also be great. Have fun! * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins [Answer] ### QBasic (56) ``` A$="CCGGAAG2FFEEDDC2" B$="GGFFEED2" PLAY "L4"+A$+B$+B$+A$ ``` Focus is on reminiscence :) (Don't have a QBasic to test this though) [Answer] ### JavaScript (~~214~~ ~~212~~ 211 characters) Open Safari, Opera, or Google Chrome to [JavaScript Shell](http://www.squarefree.com/shell/shell.html), then enter the code below: ``` for(s="",y=192e3;x=--y/4e3|0;)s+="~ "[(y%4e3>800|x%8==1)&Math.pow(2,"024579702457245702457970"[x>>1]/12)*y/31%2];open("data:audio/wav;base64,UklGRiXuAgBXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQHuAgCA"+btoa(s)) ``` Unminified for readability (even then it may be hard to understand): ``` for(s = "", y = 192E3; x = --y / 4E3 | 0;) { s += "~ "[(y % 4E3 > 800 | x % 8 == 1) & Math.pow(2, "024579702457245702457970"[x >> 1] / 12) * y / 31 % 2]; } open("data:audio/wav;base64,UklGRiXuAgBXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQHuAgCA" + btoa(s)); ``` With several more characters, it could work on Firefox as well, but you can change the `audio/wav` part to at least save the WAV file. [Answer] ## **C# (Length: LOL)** So, what I did here was implement support for generating a .wav file from the string used for the QBasic solution in C# (single octave, no accidentals). Emphasis was on: 1. Avoiding `unsafe` code blocks 2. Not wasting *too* much of my time doing it 3. Making it *relatively* simple to extend --- ``` using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.IO; namespace ConsoleApplication1 { public static class Extension { public static byte[] ToByteArray(this object o) { return o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) .SelectMany(x => { var value = x.GetValue(o, null); if (value.GetType().Equals(typeof (UInt16))) { return BitConverter.GetBytes((UInt16) value); } if (value.GetType().Equals(typeof (UInt32))) { return BitConverter.GetBytes((UInt32) value); } if (value.GetType().Equals(typeof(char[]))) { return ((char[]) value).Select(y => Convert.ToByte(y)); } if (value.GetType().Equals(typeof(byte[]))) { return (byte[]) value; } throw new NotImplementedException(); }).ToArray(); } } public class Wave { public readonly byte[] WavFile; public Wave(string notes) { var header = new Header(); var data = new List<Chunk>(); var f = new Fmt(8000); data.Add(f); data.Add(new WavData(notes, f)); var thefile = data.SelectMany(x => x.ToByteArray()).ToArray(); header.Size = (uint)thefile.Length + 4; WavFile = header.ToByteArray().Concat(thefile).ToArray(); } class WavData: Chunk { private static IEnumerable<byte> RenderNote(string note, int length, Fmt fmt) { double frequency; switch (note) { case "A": frequency = 440; break; case "B": frequency = 493.883; break; case "C": frequency = 261.626; break; case "D": frequency = 293.665; break; case "E": frequency = 329.628; break; case "F": frequency = 349.228; break; case "G": frequency = 391.995; break; default: throw new NotImplementedException("Unsupported Note"); } var result = new byte[fmt.SampleRate / length * 2]; // For 120BPM tempo for (int i = 0; i < result.Length; i++) { double time = (i % fmt.SampleRate) / (double)fmt.SampleRate; double position = time * frequency; if (result.Length - i <= fmt.SampleRate / 16) result[i] = 127; else result[i] = (byte)Math.Round((Math.Sin(position * 2 * Math.PI) + 1) * 127); } return result; } public WavData(string notes, Fmt fmt) { Samples = new byte[0]; foreach (var note in Regex.Matches(notes, @"[A-G][1|2|4|8]?").OfType<Match>().Select(x => x.Value)) { Samples = Samples.Concat(RenderNote(note[0] + "", note.Length > 1 ? note[1] - '0' : 4, fmt)).ToArray(); } } public override char[] Id { get { return "data".ToCharArray(); } } public override uint DataSize { get { return (uint)Samples.Length; } } public byte[] Samples { get; private set; } } class Fmt : Chunk { public Fmt(UInt32 sampleRate) { CompressionCode = 1; // Unknown/PCM Channels = 1; SampleRate = sampleRate; SignificantBits = 8; } public override char[] Id { get { return "fmt ".ToCharArray();} } public override uint DataSize { get { return 16; } } public UInt16 CompressionCode { get; private set; } public UInt16 Channels { get; private set; } public UInt32 SampleRate { get; private set; } public UInt32 AvgBytesPerSecond { get { return SampleRate*BlockAlign; } } public UInt16 BlockAlign { get { return (UInt16) (SignificantBits/8*Channels); } } public UInt16 SignificantBits { get; private set; } } class Header { public Header() { Type = "RIFF".ToCharArray(); RiffType = "WAVE".ToCharArray(); Size = 0; } public char[] Type { get; private set; } public UInt32 Size { get; set; } public char[] RiffType { get; private set; } } abstract class Chunk { public abstract char[] Id { get; } public abstract UInt32 DataSize { get; } } } class Program { public static void Main(string[] args) { var p1 = "CCGGAAG2"; var p2 = "FFEEDDC2"; var p3 = "GGFFEED2"; var w = new Wave(p1+p2+p3+p3+p1+p2); using (var f = new FileStream("testfile.wav", FileMode.Create)) f.Write(w.WavFile, 0, w.WavFile.Length); } } } ``` [Answer] # C - 520 ``` #include <linux/fd.h> #include <time.h> struct timespec t,p;char*q="AAHHJJH FFEECCA HHFFEEC HHFFEEC AAHHJJH FFEECCA";x,y,z,v,w;main(){x=open("/dev/fd0",3);for(y;q[y];y++){clock_gettime(CLOCK_MONOTONIC,&p);if(q[y]>' ')for(w=z=0;z<4e8;z+=t.tv_nsec,w++){struct floppy_raw_cmd s={0};s.flags=FD_RAW_NEED_SEEK;v=!v;s.track=v;ioctl(x,FDRAWCMD,&s);clock_gettime(CLOCK_MONOTONIC,&t);t.tv_nsec=(w+1)*5e8/pow(2.,q[y]/12.)-(t.tv_sec-p.tv_sec)*1e9-t.tv_nsec+p.tv_nsec;t.tv_sec=0;nanosleep(&t,0);}t.tv_nsec=2e8;nanosleep(&t,0);}} ``` Why use past century's hardware like speakers and headphones? This excellent piece of code lets you play the song on a modern piece of hardware: a floppy drive! No special requirements: * An IDE floppy drive * Linux kernel * Compile with `-lm` * Make sure the program can access `/dev/fd0`, so either chown the device or run as superuser Bends the rules a bit, but let's for a second consider the floppy drive a sound device, and the IDE controller an integrated sound card. [Answer] # [Desmos](https://desmos.com/calculator), ~~148~~ 116 bytes *The viewport has been manually changed to x=0 to 20, and y=0 to 12, because the audio trace feature in Desmos is affected by the viewport (the song will become distorted if the viewport is moved or zoomed in/out). I'm not sure if that contributes to the byte count or not. For now, I'm going to assume that it doesn't affect byte count, but please let me know otherwise if this isn't the case.* ``` A=join(F(0,7,9,7,x),F(5,4,2,0,x)) B=F(7,5,4,2,x) F(a,b,c,d,x)=\join([a,b,c]\{x<1,1.1<x<2.1\},d\{x<2\}) join(A,B,B,A) ``` [Try It On Desmos!](https://www.desmos.com/calculator/pnm7lbdzlp) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/llggyk9mhd) I focused on both song quality and code length (basically, shortest code in which the audio still sounds good). To play the audio, click the `join(A,B,B,A)` expression (it should be outlined in blue). Then press `ALT`+`T`, and after that, `H`, after which you will hear the audio play if everything is done correctly. Big thanks to [@hyper-neutrino](https://codegolf.stackexchange.com/users/68942/hyper-neutrino) for helping me find the sequence of numbers that represents the notes in [chat](https://chat.stackexchange.com/transcript/message/61003548#61003548). I was having a very hard time finding that myself; I don't know a thing about music lol. ### Explanation This answer takes advantage of one of Desmos's accessibility features: [Audio Tracing](https://www.desmos.com/accessibility#audio-trace), which can play any graph as a sound. By plotting horizontal line segments at specific places in the viewport, the audio tracing will be able to play that line segment as a single note for a certain duration, depending on how long that line segment is. Specifically, the viewport is split as follows: > > Bottomest vs toppest lines of the graph correspond to the range of an octave... the 12 steps within this range correspond to the half-tones in the music scale. ([Source](https://desmosgraphunofficial.wordpress.com/2021/05/03/music-inside/)) > > > As I am not familiar with music at all, I pretty much have no idea what this means, but hopefully that is understandable to all of you that know music. The next part is to actually find the sequence of y-values so that it will play the song. As I mentioned above, hyper-neutrino basically did all the work and found the correct sequence of y-values which play the song (I pretty much have no idea how he found them; something about intervals and semitones?). The sequence is as follows: ``` 0 0 7 7 9 9 7, 5 5 4 4 2 2 0, 7 7 5 5 4 4 2, 7 7 5 5 4 4 2, 0 0 7 7 9 9 7, 5 5 4 4 2 2 0 ``` where every 7th note (the note before each comma, and the last note) is a half note, meaning it is played twice as long as the other notes, which are quarter notes. Graphically, this means that the line segment that represents a half note is twice as long as that of a quarter note. With that out of the way, the next thing to do is to actually put all of this into Desmos. So how are we going to do this? Well, first I found that a line segment of length 1 is long enough for a note, so each quarter note will be length 1, while each half note will be length 2. Secondly, we will need to put a short pause in between every note, or else two repeated notes will just play as one half note instead. I decided to use a 0.1 length pause in between each note. My plan was to construct a huge list of line segments which Desmos can graph and audio trace over. A pattern I noticed with the notes is that every 7 notes always follows a `a a b b c c d (half note)` pattern. To take advantage of that, I made a function `F` which takes in 4 notes `a,b,c,d` and constructs a list of line segments in accordance to that pattern. Let's take a look at it: ``` F(a,b,c,d,x)=\join([a,b,c]\{x<1,1.1<x<2.1\},d\{x<2\}) ``` The function `F` takes first takes in 4 notes `a,b,c,d`, then `x` because we are plotting something (the function won't work without it). Let's first take a look at the first part of the function: ``` [a,b,c]\{x<1,1.1<x<2.1\} ``` Because of the list `[a,b,c]`, this entire expression results in a list of 3 horizontal line segments: one segment at y levels `a`, `b`, and `c`. Now let's take a look at the domain restriction. It splits the lines `y=[a,b,c]` into two parts: one where `x<1` and another where `1.1<x<2.1`, effectively splitting it into two line segments of length 1 with a 0.1 gap in between them (the viewport is from x=0, so `x<1` is functionally the same as `0<x<1`). The audio trace will first play the `x<1` segment (one quarter note), then a very short pause later, play the `1.1<x<2.1` segment (another quarter note). It does this for `a`, then `b`, then `c`. Finally, this list is joined with `d\{x<2\}`, which is a line segment of length 2 at y level `d`. This will play the note `d` for twice as long, emulating a half note. With a full understanding of function `F`, we can now encode the number sequence shown earlier with `F`. First note that the first 14 notes (`0 0 7 7 9 9 7, 5 5 4 4 2 2 0`) are repeated at the end as well. Also, the middle 14 notes (`7 7 5 5 4 4 2, 7 7 5 5 4 4 2`) is just `7 7 5 5 4 4 2` repeated twice. We can encode `0 0 7 7 9 9 7` as `F(0,7,9,7,x)` and `5 5 4 4 2 2 0` as `F(5,4,2,0,x)`. By joining the two resultant lists and storing it in a variable `A`, we can re-use these 14 notes at the end of the song. We can encode `7 7 5 5 4 4 2` as `F(7,5,4,2,x)` and set it to a variable `B` so that we can re-use these notes. Finally, we can join the notes like so: `join(A,B,B,A)` to get the final sequence of notes. Desmos will then automatically graph all the line segments in the resultant list, which we can then audio trace over. [Answer] ## Python (259) ``` import pysynth c=('c',4) g=('g',4) a=('a',4) b=('b',4) d=('d',4) e=('e',4) f=('f',4) g2=('g',2) c2=('c',2) d2=('d',2) s=(c,c,g,g,a,a,g2,f,f,e,e,d,d,c2,g,g,f,f,e,e,d2,g,g,f,f,e ,e,d2,c,c,g,g,a,a,g2,f,f,e,e,d,d,c2) pysynth.make_wav(s,fn="s.wav") ``` [Answer] # bash + say + gunzip, 136 bytes `say`, of course, being the OS X text-to-speech command. This is... dorky. Yeah, let's go with dorky. ``` printf '<117 bytes>'|gunzip|sh ``` The 117 bytes is, of course, a gzip stream containing unprintable characters. Here's an xxd dump of the script including those characters: ``` 00000000: 7072 696e 7466 2027 1f8b 085c 305c 305c printf '...\0\0\ 00000010: 305c 305c 3002 032b 4eac 54d0 2d0b c9c8 0\0\0..+N.T.-... 00000020: cf4d 2c56 c8e7 c2ca 75cc cb4b c4ce 71cb .M,V....u..K..q. 00000030: ccc7 c90b 4b4d 85f0 7252 530b 14f4 4ca0 ....KM..rRS...L. 00000040: c2de 8945 a979 4061 6cbc e0c4 dcc4 bc92 ...E.y@al....... 00000050: 8c44 dc02 2e89 7999 a939 685c 5c74 7723 .D....y..9h\\tw# 00000060: ec44 755c 6e2a 8f8a ee19 581b 8767 1402 .Du\n*....X..g.. 00000070: 5c30 fa36 7e25 2599 025c 305c 3027 7c67 \0.6~%%..\0\0'|g 00000080: 756e 7a69 707c 7368 unzip|sh ``` ## Explanation The 117 bytes is the following script gzipped: ``` say -vThomas o say -vThomas o say -vAnna o say -vAnna o say -vFiona o say -vFiona o say -vVeena o sleep .4 say -vKaren o say -vKaren o say -vSamantha o say -vSamantha o say -vDaniel o say -vDaniel o say -vThomas o sleep .4 say -vVeena o say -vVeena o say -vKaren o say -vKaren o say -vSamantha o say -vSamantha o say -vDaniel o sleep .4 say -vVeena o say -vVeena o say -vKaren o say -vKaren o say -vSamantha o say -vSamantha o say -vDaniel o sleep .4 say -vThomas o say -vThomas o say -vAnna o say -vAnna o say -vFiona o say -vFiona o say -vVeena o sleep .4 say -vKaren o say -vKaren o say -vSamantha o say -vSamantha o say -vDaniel o say -vDaniel o say -vThomas o ``` That's right, I just made a bunch of different `say` voices say "o." To figure out which ones, I wrote a script using [aubionotes](https://github.com/aubio/aubio) to get a quick-and-dirty estimate of each voice's pitch, then did a lot of trial and error the find ones that sound mostly right. I considered trying to golf this manually, but there's so much repetition that I figured Zopfli would make shorter work of it, so I took the easy way out. [Answer] ## C, 277 characters ``` #include<math.h> a[]={0,7,9,7,5,4,2,0,7,5,4,2,7,5,4,2,0,7,9,7,5,4,2,0},i,j,f;main(){unsigned char b[8000];f=open("/dev/dsp",1);for(i=0;i<24;i++){for(j=0;j<8000;j++){b[j]=(i%4==3 ||j/400%20!=9?1+sinf(j*powf(2,a[i]/12.)):1)*127;}for(j=0;j<8000;j+=write(f,b+j, 8000-j));}close(f);} ``` ## Perl, 203 characters ``` open F,'>:raw','/dev/dsp';for$a(0,7,9,17,5,4,2,10,7,5,4,12,7,5,4,12,0,7,9,17,5,4 ,2,10){$b=pack'C*',map 127*($a>9||$_/400%20!=9?1+sin($_*2**($a%10/12)):1),0.. 7999;$b=substr$b,syswrite F,$b while length$b} ``` Conveniently, [OSS](http://en.wikipedia.org/wiki/Open_Sound_System)'s `/dev/dsp` defaults to 8kHz mono u8; all I do here is open the device and write computed samples. [Answer] ## C, 96 chars ``` main(t){for(;++t>>16<3;)putchar(t*!!(t>>9&7|!(-t>>12&7))*(96+"#d|dOE3#dOE3dOE3"[t>>13&15])>>5);} ``` Produces raw 8-bit unsigned mono audio data in classic [bytebeat](http://canonical.org/~kragen/bytebeat/) style. Recommended sample rates for playback are between 8 and 16 kHz; changing the sample rate changes the tempo and pitch. To compile and play under Linux, save the code above as `twinkle.c` and run the following commands: ``` gcc twinkle.c -o twinkle ./twinkle | aplay ``` Some notes on how the code works: * The general trick used for bytebeat compositions like this is that `putchar()` takes an integer value but only prints the low eight bits of it. Thus, `putchar(t)`, where `t` is an increasing counter, generates a sawtooth wave, and the frequency of the wave can be altered by multiplying `t` with a suitable value. * `!!(t>>9&7|!(-t>>12&7))` produces the repeating 6+1 note pattern. Specifically, `!!(t>>9&7)` evaluates to `0` whenever `t>>9 & 7 == 0` and to `1` otherwise. Thus, it produces a 512-sample gap in the waveform every 4096 samples, while the `!(-t>>12&7)` eliminates every eighth such gap. * `96+"#d|dOE3#dOE3dOE3"[t>>13&15]` generates the melody: the ASCII code of each characters in the string plus 96 gives the relative frequency of the corresponding note. Actually, the values are the approximate frequencies in Hz of concert pitch notes in the 3rd / small octave, i.e. with A corresponding to 220. However, since the base tone with which these values are multiplied is about 64 Hz (when played at 16 kHz, or 32 Hz when played at 8 kHz), we need to scale the result down by five octaves with `>>5` to get the frequency back into a reasonable range. Ps. If you want to try this code on a JavaScript-based bytebeat player, replace `[t>>13&15]` with `.charCodeAt(t>>13&15)`. [Answer] ## [HyperCard](http://en.wikipedia.org/wiki/HyperCard) 2.2 - 113 ``` play harpsichord "c c g g a a gh fq f e e d d ch gq g f f e e dh gq g f f e e dh cq c g g a a gh fq f e e d d ch" ``` **Usage:** Start HyperCard, type ⌘M to open the Message Box, paste the code above, and press enter. `harpsichord` may be replaced with `flute` or `boing` to get different sounds. [Answer] # PowerShell: 207 **Golfed code:** ``` filter n {switch($_){C{262}D{294}E{330}F{349}G{392}A{440}}}$t="CCGGAAGFFEEDDCGGFFEEDGGFFEEDCCGGAAGFFEEDDC";1..6|%{$t[0..5]|n|%{[console]::beep($_,600)};$t[6]|n|%{[console]::beep($_,1200)};$t=$t.SubString(7)} ``` **Ungolfed, with comments:** ``` # Filter to define note frequencies. filter n {switch($_){C{262}D{294}E{330}F{349}G{392}A{440}}} # Notes for Twinkle, Twinkle, Little Star. $t="CCGGAAGFFEEDDCGGFFEEDGGFFEEDCCGGAAGFFEEDDC" # Run through each phrase in the song. 1..6|%{ # Play first six notes as quarter notes. $t[0..5]|n|%{[console]::beep($_,600)} # Play seventh note as half note. $t[6]|n|%{[console]::beep($_,1200)} # Left-shift $t by 7 notes. $t=$t.SubString(7) } ``` Not the greatest-sounding rendition of the song ever, but it works. [Answer] ## JavaScript, ~~194 177~~ 176 Now that WebAudio is a thing, I thought it would be fun to write this. (Yes, I know ES6 and WebAudio came out after the challenge was posted.) Tested on Microsoft Edge. ``` a=new AudioContext,o=a.createOscillator(i=0) o.connect(a.destination) setInterval(_=>o.frequency.value=4*[65,73,82,87,98,110]['045432104321432104543210'[i++]]|0,1e3) o.start(1) ``` Given the lack of strict output requirements, I took the liberty of detuning some frequency values to be divisible by 4. It still sounds passable, relative-pitch wise. The final notes are off by -11, -10, -9, -6, 0, and 0 cents, for c, d, e, f, g, and a respectively, giving a total window of 11 cents. Not great to the trained ear, but recognizable as the tune, which is all the challenge requires. There are also no breaks between notes, but that wasn't a requirement either. [Answer] ## Arduino, 688 ``` int length=15;char notes[]="ccggaag ffeeddc ggffeed ggffeed ccggaag ffeeddc";int beats[]={1,1,1,1,1,1,2,1,1,1,1,1,1,2,4};int tempo=300;void playTone(int tone,int duration){for(long i=0;i<duration*1000L;i+=tone*2){digitalWrite(11,HIGH);delayMicroseconds(tone);digitalWrite(11, LOW);delayMicroseconds(tone);}}void playNote(char note, int duration){char names[]={'c','d','e','f','g','a','b','C'};int tones[]={1915,1700,1519,1432,1275,1136,1014,956};for(int i=0;i<8;i++){if(names[i]==note){playTone(tones[i], duration);}}}void setup(){pinMode(11, OUTPUT);}void loop(){for(int i=0;i<length;i++){if(notes[i]==' '){delay(beats[i]*tempo);}else{playNote(notes[i],beats[i]*tempo);}delay(tempo/2);}} ``` Plug in the buzzer on output 11. I concentrated mainly on **quality**, but also on code length. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 93 bytes ``` Sound[s=SoundNote;If[#>9,s[#-10,2],{s@#,s@#}]&/@Join[a={0,7,9,17,5,4,2,10},b={7,5,4,12},b,a]] ``` [Answer] # Python ~~317~~ ~~305~~ 301 This is my solution, using only standard python libraries: ``` import math,wave,struct;d=24000;r=1100.;t=wave.open("t.wav","w");t.setparams((1,2,int(r),d,"NONE",""));a=[0,7,9,7];b=[5,4,2,0];c=[7,5,4,2] for h in[math.sin(6*[240*2**(j/12.)for j in a+b+c+c+a+b][x/1000]*(x/r))*(x%500>9 or x/1000%4>2)for x in range(d)]:t.writeframes(struct.pack('h', int(h*64000/2))) ``` And here it is with some more whitespace for readability: ``` import math,wave,struct;d=24000;r=1100. a=[0,7,9,7];b=[5,4,2,0];c=[7,5,4,2];s=[240*2**(j/12.) for j in a+b+c+c+a+b] z=[math.sin(6*s[int(x/1000)]*(x/r))*(x%500>10 or int(x/1000)%4>2) for x in range(d)] t=wave.open("t.wav","w");t.setparams((1,2,int(r),d,"NONE","")) for h in z:t.writeframes(struct.pack('h', int(h*64000./2))) ``` [Answer] # Powershell, ~~120~~ 117 bytes `[Console]::beep`, note labels and frequencies inspired by [Iszi](https://codegolf.stackexchange.com/a/15739/80745) ``` ($a='ccggaaGffeeddC')+'ggffeeD'*2+$a|% t*y|%{[console]::beep((0,110,0,65,73,82,87,98)[$_-band7]*4,600+600*($_-lt97))} ``` **Main idea**: * The melody is encoded in a string. * The notes are encoded with chars `A`,`C`,`D`,`E`,`F`,`G`. * Uppercase means a `double duration`. * 3 lower bits (`$_-band7`) of each note uses as index in the frequencies array (`A->1`,`C->3`,`D->4`...) * This script uses the reduced sampling rate for frequencies: `(0,110,0,65,73,82,87,98)[$_-band7]*4` instead Iszi's `(0,440,0,262,294,330,349,392)[$_-band7]`. `[console]::Beep` is not the most accurate musical instrument, so it can slightly fake :) **Explanation**: For each char from the melody string `ccggaaGffeeddCggffeeDggffeeDccggaaGffeeddC`, the script: * lookups frequensies from the array using the lower bits as index * calculates a duration based on char uppercase/lowercase * calls `[console]::beep` to play the note [Answer] # SmileBASIC, 45 bytes ``` BGMPLAY"{M=CCGGAAG2FFEEDDC2}{M}[GGFFEED2]2{M} ``` [Answer] # [Raku](https://raku.org/), 115 bytes ``` for 'xPHPZ`jxPZ`jPZ`jxPHPZ`jx'.ords.kv ->\i,\p {print 9*(4*$_ div p%2&&2900>$_)*(3==i%4||!(1500>$_>1400))for ^3e3} ``` Pipe to `aplay` to listen. [Answer] # C (MSVC + Win32), 163 bytes ``` #include<windows.h> #include<math.h> main(){for(char*s="DDKKMMK IIHHFFD KKIIHHF KKIIHHF DDKKMMK IIHHFFD ";*s;s++)*s-32&&Beep(220*pow(1.06,*s-65),s[1]-32?400:800);} ``` In Windows 7, Beep was rewritten to pass the beep to the default sound device for the session. This is normally the sound card, except when run under Terminal Services, in which case the beep is rendered on the client. ]
[Question] [ Given a non-empty string of lowercase ASCII letters `a-z`, output that string with each consecutive “run” of the same letter lengthened by one more copy of that letter. For example, `dddogg` (**3** `d`’s, **1** `o`, **2** `g`’s) turns into `ddddooggg` (**4** `d`’s, **2** `o`’s, **3** `g`’s). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): the shortest answer in bytes wins. ## Test cases ``` aabbcccc -> aaabbbccccc doorbell -> ddooorrbbeelll uuuuuuuuuz -> uuuuuuuuuuzz q -> qq xyxyxy -> xxyyxxyyxxyy xxxyyy -> xxxxyyyy ``` [Answer] # [Python 3](https://docs.python.org/3/), 44 bytes ``` for c in input():print(c,end=c[id==c:]);id=c ``` [Try it online!](https://tio.run/nexus/python3#@5@WX6SQrJCZB0QFpSUamlYFRZl5JRrJOql5KbbJ0ZkptrbJVrGa1kBG8v//Kfn5RUmpOTkA "Python 3 – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` .¡€ĆJ ``` Explanation: ``` Example input: "dddogg" .¡ Split into chunks of consecutive equal elements stack: [['ddd', 'o', 'gg']] € For each... Ć Enclose; append the first character to the end of the string stack: [['dddd', 'oo', 'ggg']] J Join array elements into one string stack: ['ddddooggg'] Implicitly output top element in stack: "ddddooggg" ``` [Try it online](https://tio.run/nexus/05ab1e#@693aOGjpjVH2rz@/y8EAA "05AB1E – TIO Nexus") or as a [test suite](https://tio.run/nexus/05ab1e#qymr/K93aOGjpjVH2rz@6/xPTExKSgYCrpT8/KKk1JwcrlIYqOIq5KqoBEGuioqKyspKAA). Enclose is a pretty new builtin; it's the first time I've used it. Very convenient ;) # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` γ€ĆJ ``` `.¡` has been replaced by `γ` in the latest update. [Answer] # [Retina](https://github.com/m-ender/retina), 11 bytes ``` (.)\1* $1$& ``` [Try it online!](https://tio.run/nexus/retina#U9VwT/ivoacZY6jFpWKoovb/f2JiUlIyCHCl5OcXJaXmcJXCQBVXIVdFJQhyVVRUVFZWAgA "Retina – TIO Nexus") Replaces each run of characters with one of the run's characters followed by the run itself. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` r9hMMr8 ``` [Test suite](http://pyth.herokuapp.com/?code=r9hMMr8&test_suite=1&test_suite_input=%22aabbcccc%22%0A%22doorbell%22%0A%22uuuuuuuuuz%22%0A%22q%22%0A%22xyxyxy%22%0A%22xxxyyy%22&debug=0). ## How it works ``` r9hMMr8 example input: "xxyx" r8 run-length encoding [[2, "x"], [1, "y"], [1, "x"]] hMM apply h to each item this takes advantage of the overloading of h, which adds 1 to numbers and takes the first element of arrays; since string is array of characters in Python, h is invariant on them [[3, "x"], [2, "y"], [2, "x"]] r9 run-length decoding xxxyyxx ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` Y'QY" ``` [Try it online!](https://tio.run/nexus/matl#@x@pHhip9P@/ekp@flFSak6OOgA "MATL – TIO Nexus") ### Explanation Consider input `'doorbell'`. ``` Y' % Implicit input. Run-length encoding % STACK: 'dorbel', [1 2 1 1 1 2] Q % Increase by 1, element-wise % STACK: 'dorbel', [2 3 2 2 2 3] Y" % Run-length decoding. Implicit display % STACK: 'ddooorrbbeelll' ``` [Answer] ## [Alice](https://github.com/m-ender/alice), 17 bytes ``` /kf.>o./ @i$QowD\ ``` [Try it online!](https://tio.run/nexus/alice#@6@fnaZnl6@nz@WQqRKYX@4S8/9/Sn5@UVJqTg4A "Alice – TIO Nexus") ### Explanation ``` /.../ @...\ ``` This is a framework for programs which operate entirely in Ordinal mode and are essentially linear (simple loops can be written, and one is used in this program, but it's trickier to work with otherwise branching control flow here). The instruction pointer bounces diagonally up and down through the code from left to right, then gets shifted by one cell by the two mirrors at the end, and the moves back from right to left, executing the cells it skipped on the first iteration. The linearised form (ignoring the mirrors) then basically looks like this: ``` ifQ>w.Doo.$k@ ``` Let's go through this: ``` i Read all input as a string and push it to the stack. f Split the string into runs of equal characters and push those onto the stack. Q Reverse the stack, so that the first run is on top. > Ensure that the horizontal component of the IP's movement is east. This doesn't do anything now, but we'll need it after each loop iteration. w Push the current IP address to the return address stack. This marks the beginning of the main loop. . Duplicate the current run. D Deduplicate the characters in that run so we just get the character the run is made up of. o Output the character. o Output the run. . Duplicate the next run. When we've processed all runs, this will duplicate an implicit empty string at the bottom of the stack instead. $ If the string is non-empty (i.e. there's another run to process), execute the next command otherwise skip it. k Pop an address from the return address stack and jump there. Note that the return address stack stores no information about the IP's direction, so after this, the IP will move northwest from the w. That's the wrong direction though, but the > sets the horizontal component of the IP's direction to east now, so that the IP passes over the w again and can now execute the next iteration in the correct direction. @ Terminate the program. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` Œg;Q$€ ``` [Try it online!](https://tio.run/nexus/jelly#@390Urp1oMqjpjX///9Xr6gEQXUA "Jelly – TIO Nexus") Only works as a full program (i.e. stringified output). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` ḅ{t,?}ᵐc ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9wR2t1iY597cOtE5L//1dKyc8vSkrNyVH6HwUA "Brachylog – TIO Nexus") ### Explanation ``` Example input: "doorbell" ḅ Blocks: ["d","oo","r","b","e","ll"] { }ᵐ Map: ["dd","ooo","rr","bb","ee","lll"] t Tail: "d" | "o" | "r" | "b" | "e" | "l" ,? Prepend to input: "dd" | "ooo" | "rr" | "bb" | "ee" | "lll" c Concatenate: "ddooorrbbeelll" ``` [Answer] ## C, 49 bytes ``` i;f(char*s){for(;putchar(*s);)i=s[i]^s[1]||!s++;} ``` See it [work online](https://ideone.com/u836gV). [Answer] # [Python 2](https://docs.python.org/2/), 47 bytes ``` f=lambda s:s and-~(s[0]*2!=s[:2])*s[0]+f(s[1:]) ``` [Try it online!](https://tio.run/nexus/python2#NU3BDsIgFLv7Fc93GnMzuiPJ/BHCAUSSJQwczARc5q8jmNgmTdtDm/VoxCyVgEADCKv6TxPYhbfDcQyMDpy0NZ50aa@Uk6ydhwCTBYZCSHkvwA5QOeflw5jqX3@8a1qqxFT5czGmlJDTAzz9ZFfAbYf@BtuO57I9i7UJXXkjJH8B "Python 2 – TIO Nexus") [Answer] # C, 53 bytes ``` i;f(char*s){for(;i=*s++;)putchar(i^*s?putchar(i):i);} ``` [Try it online!](https://tio.run/nexus/c-gcc#@59pnaaRnJFYpFWsWZ2WX6RhnWmrVaytba1ZUFoCEtfIjNMqtodzNK0yNa1r/@cmZuZpADVoKKWkpOSnpyuBBAE "C (gcc) – TIO Nexus") [Answer] # PHP, 40 Bytes ``` <?=preg_filter('#(.)\1*#',"$1$0",$argn); ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/a48381f186d4e112423529ae856670a0a00fb2f3) ## PHP<7.1, 44 Bytes Version without Regex ``` for(;a&$c=$argn[$i++];)echo$c[$c==$l].$l=$c; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/9b3b474ac9ffb310df673f475597ef9bedd918f4) [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 bytes 7 bytes of code, +1 for the `-P` flag. ``` ó¥ ®+Zg ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=86UgritaZw==&input=ImFhYmJiY2MiIC1Q) ### Explanation This uses the `ó` (partition on falsy) built-in that I just added yesterday: ``` ó¥ ® +Zg ó== mZ{Z+Zg} ó== // Split the input into runs of equal chars. mZ{ } // Replace each item Z in this array with Z+Zg // Z, concatenated with the first char of Z. -P // Join the resulting array back into a string. // Implicit: output result of last expression ``` [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 33 bytes ``` \~..,}/',\<.-/.<@;$>.${;/${/"$.>$ ``` ### Expanded: ``` \ ~ . . , } / ' , \ < . - / . < @ ; $ > . $ { ; / $ { / " $ . > $ . . . . ``` [Try it online!](https://tio.run/nexus/hexagony#@x9Tp6enU6uvrhNjo6err2fjYK1ip6dSba2vUq2vpKJnp/L/f0p@flFSak4OAA "Hexagony – TIO Nexus") The pseudo-code is more or less: ``` char = readchar() while (char > 0) print(char) run_char = char do print(char) char = readchar() while (run_char == char) ``` [Answer] # JavaScript (ES6), ~~33~~ 30 bytes ``` s=>s.replace(/(.)\1*/g,"$1$&") ``` --- ## Try It ``` f= s=>s.replace(/(.)\1*/g,"$1$&") i.addEventListener("input",_=>o.innerText=f(i.value)) console.log(f("aabbcccc")) // aaabbbccccc console.log(f("doorbell")) // ddooorrbbeelll console.log(f("uuuuuuuuuz")) // uuuuuuuuuuzz console.log(f("q")) // qq console.log(f("xyxyxy")) // xxyyxxyyxxyy console.log(f("xxxyyy")) // xxxxyyyy ``` ``` <input id=i><pre id=o> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` n2\׿ ``` [Try it online!](https://tio.run/nexus/jelly#@59nFHN4@tE9////V0/Jzy9KSs3JUQcA "Jelly – TIO Nexus") ### How it works ``` n2\׿ Main link. Argument: s (string) n2\ Reduce all overlapping slices of length two by non-equal. For input "doorbell", this returns [1, 0, 1, 1, 1, 1, 0]. × Multiply the characters of s by the Booleans in the resulting array. This is essentially a bug, but integer-by-string multiplication works as in Python. For input "doorbell", this returns ['d', '', 'o', 'r', 'b', 'e', '', 'l']. Note that the last character is always left unchanged, as the Boolean array has one fewer element than s. ż Zip the result with s, yielding an array of pairs. For input "doorbell", this returns [['d', 'd'], [[], 'o'], ['o', 'o'], ['r', 'r'], ['b', 'b'], ['e', 'e'], [[], 'l'], ['l', 'l']]. (implicit) Print the flattened result. ``` [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 23 bytes ``` ,[.[->->+<<]>[[-]>.<],] ``` [Try it online!](https://tio.run/nexus/brainfuck#@68TrReta6drp21jE2sXHa0ba6dnE6sT@/9/YmJSUjIIcKXk5xclpebkcJXCQBVXIVdFJQhyVVRUVFZWAgA "brainfuck – TIO Nexus") ### Explanation ``` , read the first input character [ main loop to be run for each input character . output the character once [->->+<<] subtract from previous character (initially 0), and create a copy of this character >[ if different from previous character: [-] zero out cell used for difference (so this doesn't loop) >.< output character again from copy ] , read another input character ] ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `J`, 3 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` ġ€ẹ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNCVBMSVFMiU4MiVBQyVFMSVCQSVCOSZmb290ZXI9JmlucHV0PSUyMmFhYmJjY2NjJTIyJTIwLSUzRSUyMCUyMmFhYWJiYmNjY2NjJTIyJTBBJTIyZG9vcmJlbGwlMjIlMjAtJTNFJTIwJTIyZGRvb29ycmJiZWVsbGwlMjIlMEElMjJ1dXV1dXV1dXV6JTIyJTIwLSUzRSUyMCUyMnV1dXV1dXV1dXV6eiUyMiUwQSUyMnElMjIlMjAtJTNFJTIwJTIycXElMjIlMEElMjJ4eXh5eHklMjIlMjAtJTNFJTIwJTIyeHh5eXh4eXl4eHl5JTIyJTBBJTIyeHh4eXl5JTIyJTIwLSUzRSUyMCUyMnh4eHh5eXl5JTIyJmZsYWdzPUNKZQ==) #### Explanation ``` ġ€ẹ # Implicit input ġ # Group consecutive € # Single function map: ẹ # Enclose (append # first character) # Join into a string # Implicit output ``` [Answer] # [Perl 6](https://perl6.org), 18 bytes ``` {S:g/)>(.)$0*/$0/} ``` [Try it](https://tio.run/nexus/perl6#RU5LbsMgEN3PKWYRNZA6JqsuasXqHdqlN@ZTyxLxD6ggUU7WXS/mAo3VGTF6n5knnFH49VKKCi4Bn8QoFZ7X2/trx2hNSro7HdjuxO5rdN@sMhbPqPtBGUJ/vksz6d4Sho054P5Y7zNgtAIXUz/idgWTbgd8zqcVfI7LI@VYI8GmHyZnC2yUn5SwSiLFGyD2BtNHSLZpgZtdYFbgvkopx65LKTLBiDtoW85FrKS2iWQmINoLV1r/bY@RLZyrKGhwW12T6f7pFeakzDP4kDoR70PYHvg0H3KG4Rc "Perl 6 – TIO Nexus") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 S # replace and return :global # all occurrences / )> # don't actually remove anything after this (.) # match a character $0* # followed by any number of the same character /$0/ # replace with the character (before the match) } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` .¡DÔ‚ø˜J ``` [Try it online!](https://tio.run/nexus/05ab1e#@693aKHL4SmPGmYd3nF6jtf//xWVIAgA "05AB1E – TIO Nexus") Explanation: ``` .¡DÔ‚ø˜J .¡ Split equal runs of input D Duplicate Ô Take connected-uniquified ‚ Pair connected-uniquified equal runs with original equal runs ø Zip ˜ Deep-flatten (i.e. normal flattening) J Join elements together ``` [Answer] ## Haskell, 36 bytes ``` f(a:b:c)=a:[a|a/=b]++f(b:c) f x=x++x ``` Usage example: `f "aab"` -> `"aaabb"`. [Try it online!](https://tio.run/nexus/haskell#@5@mkWiVZJWsaZtoFZ1Yk6hvmxSrrZ2mARLiSlOosK3Q1q74n5uYmadgq1BQlJlXoqCikJtYoJCmEK2UmJiUlAwESjpKKfn5RUmpOTlAZikMVAE5hUBcUQmCSrH/AQ "Haskell – TIO Nexus") When the string has at least two chars, bind `a` to the first char, `b` to he second and `c` to the rest of the string. The output is `a` followed by `a` if `a` is not equal to `b` followed by a recursive call with `b:c`. If there's only one char, the result is two times this char. [Answer] ## CJam, 10 bytes ``` le`1af.+e~ ``` [Try it online!](https://tio.run/nexus/cjam#@5@TmmCYmKannVr3/z8A "CJam – TIO Nexus") Explanation: ``` e# Input: doorbell l e# Read line: | "doorbell" e` e# Run-length encode: | [[1 'd] [2 'o] [1 'r] [1 'b] [1 'e] [2 'l]] 1a e# Push [1]: | [[1 'd] [2 'o] [1 'r] [1 'b] [1 'e] [2 'l]] [1] f.+ e# Vectorized add to each: | [[2 'd] [3 'o] [2 'r] [2 'b] [2 'e] [3 'l]] e~ e# Run-length decode: | "ddooorrbbeelll" e# Implicit output: ddooorrbbeelll ``` [Answer] # Ruby, 30 bytes ``` ->s{s.gsub(/((.)\2*)/){$1+$2}} ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/) with [AGL](https://github.com/abrudz/agl), 11 bytes ``` ⊢é⍨2-0,2=/, ``` [Try it online!](https://tio.run/nexus/apl-dyalog#e9Q31c0zQj0tMyfVSl9fP7@gRD8xPUff0d1HL6UyMSc/Xf2/T2peeklGat6jtgmPuhYdXvmod4WRroGOka2@zn@4pHpiYlJSMhCoc8GFUvLzi5JSc3KQhEphoApJsBCJXVEJgsgCFRWVlZXqAA "APL (Dyalog Unicode) – TIO Nexus") `,` ravel\* `2=/` pair-wise comparison (shows which characters to leave as-is) `0,` prepend a zero (indicating that the initial character should be duplicated) `2-` subtract that from two (gives 2 for the letters which need to be duplicated, and 1 for the rest) `⊢é⍨` replicate the argument using that (`é` is just the function `/`) --- \* This is a no-op on strings, but makes scalar characters into strings. Not required, as argument should be a string, but it makes the tests look neater, and we need a no-op function here anyway. To remove this feature, use `⊢` instead of `,`. [Answer] ## Batch, 140 bytes ``` @set/ps= @set r= :g @if not "%s:~,1%"=="%s:~1,1%" set r=%r%%s:~,1% @set r=%r%%s:~,1% @set s=%s:~1% @if not "%s%"=="" goto g @echo %r% ``` Takes input on STDIN. [Answer] ## sed, ~~18~~ 15 bytes (+1 for -r) ``` s/(.)\1*/\1&/g ``` ## Original solution ``` s/((.)\2*)/\1\2/g ``` [Answer] ## R, 36 bytes ``` gsub("((.)\\1*)","\\2\\1",scan(,"")) ``` [Answer] ## PowerShell, 50 bytes ``` {-join([char[]]$_|%{if($_-ne$p){($p=$_)}$_});rv p} ``` [Try it online!](https://tio.run/nexus/powershell#NYdBCoAgFAWv0uKLCnmC6CQhplZURJpQaObZzRbN8GAellIpXcA1Hoxxaty2kufPXc5R5sPnF96HEPCDqj5HtpplJ52epes4B/GguEwEBNtHsDQSsC0ImkAk2rirsinnFw) [Answer] # Mathematica, ~~34~~ 21 bytes *Thanks to Martin Ender for finding the* right *way to do this in Mathematica, saving 13 bytes!* ``` ##&[#,##]&@@@Split@#& ``` Pure function using an array of characters as both input and output formats. `Split` separates a list into its runs of equal characters. `##&[#,##]&` is a function that returns a sequence of arguments: the first argument it's fed, then all of the arguments (so repeating the first one in particular); this is applied (`@@@`) to every sublist of the `Split` list. [Answer] # Java, ~~151~~ ~~146~~ 60 bytes ``` String f(String s){return s.replaceAll("((.)\\2*)","$1$2");} ``` * -5 bytes, thanks to @FryAmTheEggman * -86 bytes, thanks to @KevinCruijssen **Regex** ``` ( ) group (.) a character \\2* optional repetition ``` **Detailed** ``` import java.util.*; import java.lang.*; import java.io.*; class H { public static String f(String s) { return s.replaceAll("((.)\\2*)","$1$2"); } public static void main(String[] args) { f("dddogg"); } } ``` ]
[Question] [ Here is a simple, bite-sized (byte-sized?) code golf: given a non-empty list of positive integers less than 10, print a [block-diagonal](http://en.wikipedia.org/wiki/Block_matrix#Block_diagonal_matrices) matrix, where the list specifies the size of the blocks, in order. The blocks must consist of positive integers less than 10. So if you're given as input ``` [5 1 1 2 3 1] ``` Your output could be, for instance, ``` 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 ``` or ``` 1 2 3 4 5 0 0 0 0 0 0 0 0 6 7 8 9 1 0 0 0 0 0 0 0 0 2 3 4 5 6 0 0 0 0 0 0 0 0 7 8 9 1 2 0 0 0 0 0 0 0 0 3 4 5 6 7 0 0 0 0 0 0 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 9 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 0 0 0 0 0 0 0 0 0 0 0 3 4 0 0 0 0 0 0 0 0 0 0 0 0 0 5 6 7 0 0 0 0 0 0 0 0 0 0 8 9 1 0 0 0 0 0 0 0 0 0 0 2 3 4 0 0 0 0 0 0 0 0 0 0 0 0 0 5 ``` or something like that. The elements in the matrix must be separated by (single) spaces, and the rows separated by (single) newlines. There must not be leading or trailing spaces on any lines. You may or may not print a trailing newline. You may write a function or program, taking input via STDIN (or closest alternative), command-line argument or function argument, in any convenient string or list format (as long as it isn't preprocessed). However, the result must be printed to STDOUT (or closest alternative), as opposed to returned from a function, say. You must not use any built-in functions designed to create block-diagonal matrices. This is code golf, so the shortest submission (in bytes) wins. # Leaderboards I expect the array-based languages (like J and APL) to have the edge here, but I don't want that to discourage people from trying to do as well as they can in their language of choice. So here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. So why not try and grab a spot on the latter? 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 ``` ``` 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 getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=0,c=0,p=-1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);t++;c=p==o?c:t;i=i.replace("{{PLACE}}",c+".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);p=o;$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=45550;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/ ``` ``` 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>Language<td>Size<tbody id=answers></table></div><div id=language-list><h2>Winners by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}</td><td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table> ``` [Answer] # J, 7 bytes Thanks for [FUZxxl](https://codegolf.stackexchange.com/users/134/fuzxxl) for the 2-byte improvement. Array based languages should be counted here in a different competition as they have a huge advantage. :) ``` =/~@#<\ (=/~@#<\) 3 1 1 2 1 1 1 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 ``` Another 7-byte approach: ``` #]=@##\ ``` Explanation for the old version `([:=/~]#<\)`: The first step is generating `n` piece of similar things (e.g. numbers) for every list element `n`. These should be different from the other elements'. E.g. using the natural numbers `3 1 1 2` becomes `0 0 0 1 2 3 3`. To save on bytes we use the boxed prefixes of the list: ``` ]#<\ 3 1 1 2 ┌─┬─┬─┬───┬─────┬───────┬───────┐ │3│3│3│3 1│3 1 1│3 1 1 2│3 1 1 2│ └─┴─┴─┴───┴─────┴───────┴───────┘ ``` With the `=/~` verb we create a table of Descartes products of these boxed prefixes and each cell will be `1` if the two entries are equal `0` otherwise. [Answer] # APL, 10 ``` ∘.=⍨∆/⍋∆←⎕ ``` Example: ``` ∘.=⍨∆/⍋∆←⎕ ⎕: 5 1 1 2 3 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 ``` Explanation: * `∆←⎕`: read input, store in `∆`. * `⍋∆`: find permutation that sorts `∆` (this gives an unique value for each value in the input) * `∆/`: for each of those unique values, repeat it `N` times, where `N` is the corresponding value in the input * `∘.=⍨`: make a matrix comparing each value in that list to the other values. [Answer] # R, ~~69~~ 63 ``` function(x)write(+outer(i<-rep(1:length(x),x),i,"=="),1,sum(x)) ``` Test Case: ``` (function(x)write(+outer(i<-rep(1:length(x),x),i,"=="),1,sum(x)))(c(5,1,1,3,1)) 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 ``` The outer function does most of the work here, then its just a case of getting the output looking right - Thanks to @Vlo for his help with that [Answer] # Python 3, ~~103~~ ~~97~~ ~~82~~ ~~78~~ 76 bytes ``` def P(L,n=0):k,*L=L;exec("print(*[0]*n+[1]*k+[0]*sum(L));"*k);L and P(L,n+k) ``` Using splat to take advantage of the space-separating nature of `print`, with a bit of recursion. [Answer] # Ruby, ~~86~~ ~~90~~ 83 bytes My first golf ever! ``` ->l{n=l.reduce :+;s=0;l.map{|x|x.times{puts ([0]*s+[1]*x+[0]*(n-x-s))*" "};s+=x}} ``` Receives an array with the integers, prints the expected result: ``` $ (->l{n=l.reduce :+;s=0;l.map{|x|x.times{puts ([0]*s+[1]*x+[0]*(n-x-s))*" "};s+=x}}).call([5, 1, 1, 2, 3, 1]) 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 ``` **Edit:** Thanks to Martin Büttner for helping me shortening some things! [Answer] # Matlab, ~~60~~ 54 bytes This would be Matlab's special field *IF* we could use builtin functions... Thanks @sanchises for fixing the error I missed. ``` c=0;a=input('');for A=a;v=c+1:c+A;d(v,v)=1;c=c+A;end;d ``` [Answer] # Matlab, 53 bytes Though it is only one char shorter than the other Matlab fragment, I figured the code is sufficiently different to warrant a new answer: ``` d=[];a=input('');for A=a;v=1:A;d(end+v,end+v)=1;end;d ``` The main trick is of course out of bounds indexing, but this is combined with using `end` as a variable to make it more compact. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 6 bytes ``` ∘.=⍨⍸⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM9DUjM0LN91LviUe@OR31TQWL/07hMFQyB0EjBWMGQK40LwjIBAA "APL (Dyalog Extended) – Try It Online") A full program that takes the input vector from stdin and prints the matrix. --- If a function returning a matrix were allowed: # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 5 bytes ``` ∘.=⍨⍸ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HHDD3bR70rHvXu@J/2qG3Co96@R31TPf0fdTUfWm/8qG0ikBcc5AwkQzw8g/@nKZgqGAKhkYKxgiEA "APL (Dyalog Extended) – Try It Online") APL wins back against J and K with the extended domain for `⍸`. ### How it works ``` ∘.=⍨⍸ ⍸ ⍝ Where; convert to an array that, ⍝ for each element n at index i, has n copies of i ∘.=⍨ ⍝ Outer product by element-wise equality on self ``` [Answer] # CJam, 21 ``` q~{T):Ta*~}%_f{f=S*N} ``` Try it at <http://cjam.aditsu.net/> **Explanation:** ``` q~ read and evaluate the input array {…}% transform each number using the block T):T increment T (initially 0) a* wrap T in an array and repeat it <number> times ~ dump the repeated numbers so they end up in a flat array _ duplicate the array f{…} for each array item and the array f= compare the current item with each item, resulting in an array of 1 and 0 S* join with spaces N add a newline ``` [Answer] # Python 3, 79 ``` def f(l,s=0): for x in l:r=[0]*sum(l);r[s:s+x]=[1]*x;s+=x;exec("print(*r);"*x) ``` Tracks the leftmost index of the block as `s` and makes the `x` entries after it be `1`, where `x` is the current block size. This row is then printed `x` times. Python 3 is needed to do `print(*r)`. [Answer] # Haskell, 118 116 bytes ``` (#)=replicate f i=putStr$[e#(unwords$sum h#"0"++e#"1"++sum t#"0")|(h,e:t)<-map(`splitAt`i)[0..length i-1]]>>=unlines ``` Usage: `f [2,1,1,3]` Output: ``` 1 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 1 1 1 ``` How it works: ``` [0..length i-1] for each index n of the input list i (h,e:t)<-map(`splitAt`i) split i at n and let e be the element at index n let h be the list of elements to the left of e let t be the list of elements to the right of e foreach triple h, e, t make a list of sum h # "0" ++ sh copies of "0" (sh = the sum of the elements of h) followed by e # "1" ++ e copies of "1" followed by sum t # "0" st copies of "0" (st = the sum of the elements of t) unwords join those list elements with spaces inbetween e # make e copies >>=unlines join those lists with newlines inbetween putStr print ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 12 bytes ``` 5:'=/:/2#,&: ``` [Try it online!](https://ngn.bitbucket.io/k#eJxLszK1UrfVt9I3UtZRs+LiSlMwUjAEQmNrINMQyDFWMLEGAIiaBt4=) `5:` is "debug print". Since the default formatting of a matrix is not what is wanted here, it is printed row-wise via `'`. --- if function returning a matrix (list of lists) were allowed: # [K (ngn/k)](https://codeberg.org/ngn/k), 9 bytes ``` =/:/2#,&: ``` [Try it online!](https://ngn.bitbucket.io/k#eJxLs7LVt9I3UtZRs+LiSlMwUjAEQmMgyxDINlYwAQBl1AXS) Took almost two years to golf a byte from [the previous ngn/k answer](https://codegolf.stackexchange.com/a/194793/78410) :P The algorithm itself is the same. The problem with making something a train is that you're allowed to reference the input only once. This code solves the problem by making `=/:` reduce over the two copies of the vector `&x`. [Answer] # Pyth, ~~23~~ 21 bytes [GitHub repository for Pyth](https://github.com/isaacg1/pyth) ``` Ju+G*]GHQYFNJjdmsqdNJ ``` Input is a list of integers, like `[3, 1, 1, 2]`. Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/) Uses a quite similar idea as randomra's J code. The first part of the code `Ju+G*]GHQY` generates `n` parts of similar things. For the example input `[3, 1, 1, 2]` the result looks like this: ``` [ [], [], [], [[], [], []], [[], [], [], [[], [], []]], [[], [], [], [[], [], []], [[], [], [], [[], [], []]]], [[], [], [], [[], [], []], [[], [], [], [[], [], []]]] ] ``` First three identical elements, than one element , then one element again and at the end two identical elements. ``` Ju+G*]GHQY u QY reduce the input Q, start with empty list G=[] for each H in input, replace the value of G by: +G*]GH G+[G]*H J store the result in J ``` The second part of the code is comparing the elements of the Cartesian product and printing it. ``` FNJjdmsqdNJ FNJ for N in J: m J map each element d of J to qdN the boolean value of d == N s and convert it to an integer (0 = False, 1 = True) jd print the resulting list seperated by d (=space) ``` [Answer] # C++ , 294 bytes [*Compiler used - GCC 4.9.2*](http://ideone.com/c869XT) ``` #include<bits/stdc++.h> using namespace std; #define F(a,b) for(a=0;a<b;a++) #define V vector<int> int n,i,j,s,o; main(){V v;while(cin>>n)v.push_back(n),s+=n;vector<V> m(s,V(s,0));F(i,v.size()){F(j,v[i])F(n,v[i])m[j+o][n+o]=1;o+=v[i];}F(j,s){F(n,s)cout<<m[j][n]<<((n==s-1)?"":" ");cout<<"\n";}} ``` Explanation -: ``` #include<bits/stdc++.h> using namespace std; #define F(a,b) for(a=0;a<b;a++) #define V vector<int> int n, i, j, s, o; /* n = Used to take inputs, and as an iterator after that i, j = Iterators s = sum of all the inputs o = offset ( used to find the location of the starting cell of the next matrix of 1's ) */ main() { V v; while ( cin >> n ) // Take input { v.push_back( n ), s += n; } vector<V> m( s, V( s, 0 ) ); // m is a matrix of size (s*s) with all elements initialized to 0 F( i, v.size() ) { F( j, v[i] )F( n, v[i] )m[j + o][n + o] = 1; // Assign 1 to the required cells o += v[i]; // Add the value of the current element to the offset } F( j, s ) // Output the matrix { F( n, s )cout << m[j][n] << ( ( n == s - 1 ) ? "" : " " ); // Prevent any trailing whitespace cout << "\n"; } } ``` [Answer] # K, 30 bytes ``` {"i"$,/x#',:',/'g=\:\:x#'g:<x} ``` Basically stole marinus's answer ``` k){"i"$,/x#',:',/' g=\:\:x#'g:<x}5 1 1 2 3 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 ``` [Answer] # Java, 163 ``` a->{int n=a.stream().mapToInt(x->x).sum(),t=0,j,k;for(int i:a){for(j=0;j++<i;System.out.println("\b"))for(k=0;k<n;)System.out.print(k>=t&k++<t+i?"1 ":"0 ");t+=i;}} ``` A consumer which accepts a list of integers. Readable version, with boilerplate code: ``` java.util.function.Consumer<java.util.List<Integer>> c = a -> { int n = a.stream().mapToInt(x -> x).sum(), t = 0, j, k; for (int i : a) { for (j = 0; j++ < i; System.out.println("\b")) { for (k = 0; k < n;) { System.out.print(k >= t & k++ < t + i ? "1 " : "0 "); } } t += i; } }; ``` Invoke using: ``` List list = Arrays.asList(5, 1, 1, 2, 3, 1); c.accept(list); ``` [Answer] # Python 2, ~~163~~ 114 bytes gnibbler golfed this a bunch. ``` h=input() r=range l=len(h) for i in r(l): for k in r(h[i]):print" ".join("01"[i==j]for j in r(l)for x in r(h[j])) ``` [Answer] # Python 3, 74 ``` def f(a,p=0):n=a.pop(0);exec("print(*'0'*p+'1'*n+'0'*sum(a));"*n);f(a,p+n) ``` [Answer] # JavaScript (ES6), 103 ~~107~~ 103 bytes as an anonymous function, not counting `F=` (but you need this to test it) ``` F=l=>alert(l.map((n,y)=>(l.map((n,x)=>Array(n).fill(x==y|0))+'\n').repeat(n)) .join('').replace(/,/g,' ')) ``` **Test** In Firefox/FireBug console ``` F([5,1,1,2,3,1]) ``` *Output* ``` 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 ``` [Answer] # Octave, ~~49~~ 41 bytes ``` @(a)(c=repelems(b=1:length(a),[b;a]))'==c ``` [Answer] # Pyth, ~~31~~ 30 ``` FbQVbjd++*]0Z*b]b*]0--sQbZ)~Zb ``` A pretty naive program, takes the input on stdin. This can probably be golfed more ;) Thanks @Jakube for pointing out a wasted char [Try it here](https://pyth.herokuapp.com/) [Answer] # Perl, 69 ``` #!perl -na $j=s/./0 x$&/ger;print+($j|$i.1x$_)=~s/\B/ /gr x($i.=0 x$_,$_)for@F ``` Uses standard input: ``` $ perl a.pl <<<"1 2 3" 1 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 0 1 1 1 ``` [Answer] # R, ~~117~~ ~~144~~ ~~137~~ ~~133~~ ~~129~~ 123 bytes Reasonably verbose at the moment. Should be able to shave a few more out. Gained a number of bytes formatting it correctly, but saved some swapping out the matrix for an array. Thanks to Alex for the tip on the replacing sep with s and removing the function name. Dropped the array completely and used a series of reps to build each line. Although soundly beaten by Miff, his solution made me realise I could drop the s=' ' altogether. ``` function(i){s=sum(i);i=cumsum(i);b=0;for(n in 1:s){d=i[i>=n][1];cat(c(rep(0,b),rep(1,d-b),rep(0,s-d)),fill=T);if(d==n)b=d}} ``` And the test ``` > (function(i){s=sum(i);i=cumsum(i);b=0;for(n in 1:s){d=i[i>=n][1];cat(c(rep(0,b),rep(1,d-b),rep(0,s-d)),fill=T,s=' ');if(d==n)b=d}})(c(5,1,1,3,1)) 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 > ``` [Answer] ## Batch - 226 Bytes ``` @echo off&setLocal enableDelayedExpansion&set c=0&for %%a in (%*)do set/ac+=1&for /l %%b in (1,1,%%a)do (set l=&set d=0&for %%c in (%*)do (set/ad+=1&for /l %%d in (1,1,%%c)do if !d!==!c! (set l=!l!1)else set l=!l!0) echo !l!) ``` Takes input from stdin (`C:\>script.bat 5 1 1 2 3 1`) and echo's output. Unfortunately I couldn't get that last echo on the same line, otherwise I could probably call the whole line within `cmd/von/c` to avoid having to enable delayed expansion the long way. Nice and neat - nothing but grunt work: ``` @echo off setLocal enableDelayedExpansion set c=0 for %%a in (%*) do ( set /a c+=1 for /l %%b in (1,1,%%a) do ( set l= set d=0 for %%c in (%*) do ( set /a d+=1 for /l %%d in (1,1,%%c) do if !d!==!c! (set l=!l!1) else set l=!l!0 ) echo !l! ) ) ``` [Answer] # Haskell, 124 ``` (%)=replicate d l=fst$foldr(\x(m,n)->(m>>mapM_(\_->putStrLn$unwords$n%"0"++x%"1"++(sum l-n-x)%"0")[1..x],n+x))(return(),0)l ``` Produces output by combining IO actions through `mapM_` and `foldr`. The function `d` should be given a list of ints. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ĖŒṙ⁼þ`G ``` [Try it online!](https://tio.run/##y0rNyan8///ItKOTHu6c@ahxz@F9Ce7///831TEEQiMdYx1DAA "Jelly – Try It Online") Same approach as the J answer. ``` G Grid format ⁼þ a table of whether or not pairs of elements are equal, from Œṙ the run-length decoded Ė enumeration of the input, ` compared with itself. ``` [Answer] # [Julia 1.6](https://julialang.org), 68 bytes ``` >(L,c=0)=((x,l...)=L;print(("0 "^c*"1 "^x*"0 "^sum(l)*" ")^x);l>c+x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6Fjdd7DR8dJJtDTRtNTQqdHL09PQ0bX2sC4oy80o0NJQMFJTikrWUDIFUhRaYV1yaq5GjqaXEpaQZV6FpnWOXrF2hCTFrq51GtKmOgiEYGekoGAMZsVA5mH0A) port of [Sp3000's answer](https://codegolf.stackexchange.com/a/45564/98541) needs julia 1.6 for `x,l...=L` output as a matrix would save a lot of bytes but printing it as expected uses more bytes: `!L=(l=[(a=1;L.|>i->(a+=1)ones(i))...;]).==l'` [(44bytes)](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6Fjd1FH1sNXJsozUSbQ2tffRq7DJ17TQStW0NNfPzUos1MjU19fT0rGM19Wxtc9QhevalZBYX5CRWaihqRJvqKBiCkZGOgjGQEaupCVEEswAA) [Answer] # [Uiua](https://uiua.org), 20 bytes 4 bytes for constructing the array; 16 bytes for formatting the output :/ ``` ≡(&p↘1/⊂)∵⊂@ +@0⊞=.⊚ ``` [Try it online!](https://www.uiua.org/pad?src=QmxvY2tEaWFnIOKGkCDiiaEoJnDihpgxL-KKginiiLXiioJAICtAMOKKnj0u4oqaCkJsb2NrRGlhZyBbNSAxIDEgMiAzIDFdCg==) ## Explanation ``` ⊞=.⊚ # construct the table in the same way as other array languages +@0 # convert numbers to characters /⊂ ∵⊂@ # interleave spaces (including leading space) ↘1 # remove said leading space ≡(&p ) # and print each line ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` żẋf:v=⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCLFvOG6i2Y6dj3igYsiLCIiLCJbNSwxLDEsMiwzLDFdIl0=) -1 byte thanks to lyxal. Same approach as a lot of the array-language answers ``` ẋ # Repeat elements of ż # [1...len(input) ẋ # By numbers in the input f # Flatten :v= # Table by equality ⁋ # Format as grid ``` [Answer] # K (ngn/k), 14 bytes: [`{5:'x=\:x:&x;}`](https://ngn.bitbucket.io/k#eJxLs6o2tVKvsI2xqrBSq7Cu5eJKUzBWMFQwVTDmAgBx9gbV) fixed. now prints to stdout ]
[Question] [ The challenge is simple. Give the shortest code possible to reproduce the classic 2-player game of pong <http://en.wikipedia.org/wiki/Pong> . The level of graphics and functionality should be as close as possible to this javascript demonstration <http://codeincomplete.com/posts/2011/5/14/javascript_pong/demo.html> (but without the extra options you can click on on the left or the frame, fps etc. information in the bottom right). As always the code must be written in a free language (in both senses) and should be runnable on linux. Any libraries used must also be free, easily available and not be written for the purposes of this competition (and also not already contain a working version of Pong!). [Answer] ## sed, 35 [Raising the bar](https://codegolf.stackexchange.com/a/10847) a bit with a postage-stamp sed meditation. ``` s/> / >/ s/ </< / s/0</0>/ s/>1/<1/ ``` The meditation is enjoyed on stdin/stdout on two computers, not necessarily connected by a network. The meditation begins in the state ``` 0 < 1 ``` with guru zero on the left and one on the right. The angle bracket moves left and right, and if a guru maneuvers their number to contact the cursor as it comes to their side, their score is increased by one, and they become elated with joy. The meditation is initiated by typing the above state into `sed -f medi.sed`, and the computer responds with the next state. The dutiful guru types that state into the meditation, reading aloud the next key they will press, with both gurus pressing the holy key to `enter` the future at the same time. The dutiful computer replies with the next state. This, in turn, is read aloud while typed in unison as with the last. Continue advancing into the future until infinite bliss is achieved. Gurus desiring a challenge may play 'turbo' mode, wherein the gurus attempt to collaboratively predict the computer's next state, and typing it into the prompt instead of the current state. Gurus will have the wisdom to verify agreement between their predictions before entering the future. [Answer] ## Javascript, 883 (+ 70 HTML) ``` c=document.getElementById('c').getContext('2d') c.fillStyle="#FFF" c.font="60px monospace" w=s=1 p=q=a=b=0 m=n=190 x=300;y=235 u=-5;v=3 setInterval(function(){if(w&&!s)return;s=0 c.clearRect(0,0,640,480) for(i=5;i<480;i+=20)c.fillRect(318,i,4,10) m+=p;n+=q m=m<0?0:m;m=m>380?380:m n=n<0?0:n;n=n>380?380:n x+=u;y+=v if(y<=0){y=0;v=-v} if(y>=470){y=470;v=-v} if(x<=40&&x>=20&&y<m+110&&y>m-10){u=-u+0.2;v+=(y-m-45)/20} if(x<=610&&x>=590&&y<n+110&&y>n-10){u=-u-0.2;v+=(y-n-45)/20} if(x<-10){b++;x=360;y=235;u=5;w=1} if(x>640){a++;x=280;y=235;u=-5;w=1} c.fillText(a+" "+b,266,60) c.fillRect(20,m,20,100) c.fillRect(600,n,20,100) c.fillRect(x,y,10,10)},30) document.onkeydown=function(e){k=(e||window.event).keyCode;w=w?0:k=='27'?1:0;p=k=='65'?5:k=='81'?-5:p;q=k=='40'?5:k=='38'?-5:q;} document.onkeyup=function(e){k=(e||window.event).keyCode;p=k=='65'||k=='81'?0:p;q=k=='38'||k=='40'?0:q} /* Variable index: a -> left player score b -> right player score c -> context e -> event i -> counter for dashed line k -> keycode m -> left paddle y n -> right paddle y p -> left paddle y velocity q -> right paddle y velocity s -> is start of game u -> ball x velocity v -> ball y velocity w -> game is waiting (paused) x -> ball x y -> ball y */ ``` The script can be placed at the end of `<body>` or called `onLoad`. It needs the following canvas element: ``` <canvas id="c"width="640"height="480"style="background:#000"></canvas> ``` Player 1 uses the `q` and `a` keys, and player 2 uses the `p` and `l` keys. Press the `esc` key to pause and any key to start/continue. *You can play it in your browser **[here](http://jsfiddle.net/GbwHf/3/embedded/result/)***. I wasn't sure of the physics to use, so I started off with a simple reflection method and then added some variety and experimented with it a bit. The ball's velocity in the y direction is affected by where on the paddle you hit the ball, so you have some control over where the ball goes. The ball's velocity in the x direction slowly increases with each hit in the rally. I suspect that it will be beaten quite easily by solutions using libraries, but I had fun making it in plain javascript. [Answer] ## Python 2 (with [pygame](http://www.pygame.org/download.shtml)) 650 bytes **Features** * **1 and 2 player modes** - When the game begins, press `1` for 1 player, or `2` for 2 players. The game will not begin until one of these keys is pressed. * **Increasing ball speed** - Each volley, the ball speed is increased so that after 10 volleys it has increased by approximately 50%, after 20 it will be 50% faster than that, etc. * **Variable ball deflection** - Ball deflection is based on two factors: what portion of the paddle it strikes, and whether or not the paddle is moving upon impact. If the ball strikes the paddle near one of the ends, it will be deflected more strongly than if it strikes near the middle (almost as if it were a curved surface). Additionally, if the paddle is in motion, the motion of the paddle is added to the deflection. In order to obtain the strongest deflection, the ball must strike near the end of the paddle, and the paddle must be in motion towards that same end. This is very similar to the original Pong for Atari 2600. * **Pause** - The game may be paused at any time by pressing the `Space` bar. Play will resume upon pressing the space bar a second time. * **Controls** - As with the example, player 1 moves with the `Q` and `A` keys, and player 2 moves with `P` and `L`. ``` from pygame import* init();d=display;s=d.set_mode((640,480)) g=p=16;j=q=80;x=y=200;o=t=h=v=1;z=m=n=0;w=[255]*3 while s.fill(time.wait(3)): event.get();k=key.get_pressed();t^=o*k[32];o=1-k[32];z=z or-k[49]-k[50]*2;e=k[113]-k[97];f=[k[112]-k[108],(h>0)*cmp(y,q-32)][z];a=p<g;b=q-[y,x][a] if p%608<g:m,n,p,h,v=[m+1-a,m,n+a,n,g+a*592,p,1-a*2,h/-.96,1,b/32.+~[f,e][a]][-g<b<j::2] for r in[(0,x,g,j),(624,y,g,j),(p,q,g,g)]+[(316,i*31,8,15)for i in range(g)]:draw.rect(s,w,r) if z*t:v*=(0<q<464)*2-1;x-=(0<x-e<400)*e/.6;y-=(0<y-f<400)*f/.6;p+=h;q+=v c=font.SysFont('monospace',j,1).render('%3d %%-3d'%m%n,1,w);s.blit(c,(320-c.get_width()/2,0));d.flip() ``` `cmp` is no longer defined in Python 3. The code above can be made Python 3 compatitble by prepending the following: ``` def cmp(a, b): return (a>b)-(a<b) ``` Sample screen capture: ![](https://i.stack.imgur.com/5sVcP.png) *Note: the font used for the score may vary from system to system.* [Answer] # HTML & JavaScript (take 2) - 525 Since the OP didn't seem to care much about the "as close as possible" part, here's an alternative solution that I mercilessly simplified, stripped and golfed. Q/A and P/L to play, but every other key also has an effect. Again, the code is fully self-contained and I tested it in Chromium 25 on Linux. I can golf it even further if you can accept small bugs or greater degradation of graphics quality/gameplay. ``` <canvas id=c><script>C=c.getContext('2d');f=C.fillRect.bind(C) S=[-1,I=J=0];A=B=210;X=Y=1 function g(n){++S[n];N=Math.random(M=n*613+9)*471}D=document D.onkeydown=D.onkeyup=function(e){d=!!e.type[5];k=e.keyCode k&1?I=k&16?d:-d:J=k&4?-d:d} g(0);setInterval(function(){A-=A<I|A>420+I?0:I B-=B<J|B>420+J?0:J M+=X;N+=Y N<0|N>471?Y=-Y:0 M==622&N>B&N<B+51|M==9&N>A&N<A+51?X=-X:M>630?g(0):M||g(1) f(0,0,c.width=640,c.height=480) C.fillStyle='tan';C.font='4em x';C.fillText(S,280,60) f(0,A,9,60);f(631,B,9,60);f(M,N,9,9)},6)</script> ``` Thanks Shmiddty [Answer] # Processing, 487 characters ``` int a=320,b=240,c=2,d=2,e=0,f=0,g=0,h=0,i=15,j=80,k=640, l=160,m;void setup(){size(k,b*2);}void draw(){background (0);if(keyPressed){if(key=='q'&&g>0)g-=i;if(key=='a'&&g< j*5)g+=i;if(key=='o'&&h>0)h-=i;if(key=='l'&&h<j*5)h+=i;} rect(0,g,i,j);for(m=0;m<k;m+=30)rect(312,m,i,i);rect(a,b ,i,i);rect(625,h,i,j);a+=c;b+=d;c*=a<i&&(b>g&&b+i<g+j)|| a>610&&(b>h&&b+i<h+j)?-1:1;d*=b<0||b>=465?-1:1;if(a<0){f ++;a=0;b=240;c=2;}if(a>k){e++;a=625;b=240;c=-2;}textSize (j);text(e,l,j);text(f,3*l,j);} ``` Sample screenshot: ![enter image description here](https://i.stack.imgur.com/1WZ7K.png) This code was made with shortness in mind, so it is pretty buggy (the ball sometimes goes through the paddle, or wraps around it). Controls are Q/A for Player 1 and O/L for Player 2. [Answer] # TI-Basic, ~~328~~ 326 [bytes](https://codegolf.meta.stackexchange.com/a/4764/98541) ``` AxesOff:ZInteger:GridOn 99→Xscl:2→Yscl:1→U:1→V Pt-Change(0,0 Line(Xmin,0,Xmin,9 Line(Xmax,0,Xmax,9 While 1 If 30≤abs(Y -V→V Pt-Change(X,Y If X≥46:Then If Y≥E and Y≤E+9:Then -U→U Else IS>(A,9 X-90→X End End If X≤-46:Then If Y≥D and Y≤D+5:Then -U→U Else IS>(B,9 X+90→X End End If 9<max(A,B Stop X+U→X:Y+V→Y Pt-Change(X,Y Text(1,43,A,":",B getkey→G If G=21 1→I If G=41 -1→I If G=25 1→J If G=34 -1→J I(G≠31→I J(G≠26→J D+I→D:E+J→E For(θ,-1,9,10 Pt-Change(Xmin-not(I),D+θ-I/2 Pt-Change(Xmax+not(J),E+θ-J/2 End End ``` This program is very basic (constant speed and angles) but since there's is no precise specifications, the strict minimum will do Since a long press is not detectable (or 2 keys pressed at the same time), an extra key is used to stop the movement of the racket Here is the result at ~5x speed: [![program demo](https://i.stack.imgur.com/0aGPd.gif)](https://i.stack.imgur.com/0aGPd.gif) [Answer] # HTML & JavaScript - 1663 Against my better judgment, I took the crazy approach of golfing the actual code from the demo. I removed some features and interface elements, but generally it works exactly the same - 0, 1 or 2 to choose the number of human players, Q/A and P/L to move. Unless I made some mistakes, gameplay should be identical, pixel for pixel and millisecond for millisecond, to the original at 640\*480 (hint: resizing the browser window changes the game size in the demo). It just doesn't give instructions, doesn't announce the winner and doesn't handle esc. The code is fully self-contained and I tested it in Chromium 25 on Linux. Firefox doesn't like it very much. ``` <body bgcolor=0><canvas id=c height=480><script>R=Math.random C=c.getContext('2d');f=C.fillRect.bind(C) S=[l=G=I=J=K=L=0,0];r=17;u=463;o=24;q=12;z=10;s=640;v=36 function T(z,t,u,v){P=0;if(e=v*E-u*F){a=(u*t-v*z)/e;b=(E*t-F*z)/e a<0|a>1|b<0|b>1?0:P={x:M+a*E,y:N+a*F,d:u,s:0,X:X,Y:Y}}}function i(p,q,h){T(p-22*(E<0),q,0,h) P?0:T(p,q-h*(F<0),22,0)}function U(p){if(p.a)if(M<p.x&X<0|M>p.x+q&X>0)p.u=0 else{P=p.P;if(P&&P.X*X>0&P.Y*Y>0&P.s<p.l/z)P.s+=t else{E=X*z;F=Y*z;i(M-p.x+5,s*q,s*o) if(p.P=P){y=P.y;while(y<r|y>u)y=y<r?34-y:y>u?u+u-y:y P.y=y+R(e=(p.l+2)*(X<0?M-p.x-q:p.x-M)/64)*2*e-e}}P?p.u=P.y<p.y+25?1:P.y>p.y+35?-1:0:0}y=p.y-p.u*t*198 p.y=y<q?q:y>408?408:y}function W(n,x){a=9.6;b=[~8,3,62,31,75,93,~2,7,-1,u][n] b&4&&f(x,o,v,a);b&64&&f(x,o,a,o) b&2&&f(x+v,o,-a,o);b&8&&f(x,43.2,v,a) b&32&&f(x,48,a,o);b&1&&f(x+v,48,-a,o) b&16&&f(x,72,v,-a)}A={u:0,x:0,y:210};B={u:0,x:628,y:210} function g(n){if(++S[n]>8)G=A.a=B.a=0 else{N=R(M=n?635:5)*446+r;Y=157.5;X=n?-Y:Y A.l=z+S[0]-S[1];B.l=20-A.l}}D=document D.onkeydown=D.onkeyup=function(e){d=!!e.type[5] k=e.keyCode-45;if(k>2&k<6&d&!G){G=S=[-1,0];A.a=k<4;B.a=k<5 g(0)}k^31?k^35?k^20?k^v?0:I=d:J=d:K=d:L=d A.a?0:A.u=I-J;B.a?0:B.u=K-L} setInterval(function(){t=new Date()/1000-l;l+=t;U(A);U(B) if(G){E=t*X+4*t*t;F=t*Y+4*t*t x=M+E;y=N+F;m=X+t*(X>0?8:-8);n=Y+t*(Y>0?8:-8) if(n>0&y>u){y=u;n=-n}if(n<0&y<r){y=r;n=-n}p=m<0?A:B i(M-p.x+5,N-p.y+5,70) if(P){if(P.d){y=P.y;n=-n}else{x=P.x;m=-m}n*=n*p.u<0?.5:p.u?1.5:1}M=x;N=y X=m;Y=n;M>645?g(0):M<-5&&g(1)}c.width=s;C.fillStyle='#fff' f(0,0,s,q);f(0,468,s,q);for(j=o;j--;)f(314,6+o*j,q,q) W(S[0],266.5);W(S[1],338.5) f(0,A.y,q,60);f(s,B.y,-q,60);G&&f(M-5,N-5,z,z)},50/3)</script> ``` Some credits to Shmiddty for improvements [Answer] # C# - 1283 characters This can be golfed quite a bit more but here it is. ``` using System;using System.Drawing;using System.Runtime.InteropServices;using System.Windows.Forms;using r=System.Drawing.RectangleF;namespace f{public partial class f:Form{public f(){InitializeComponent();}private void f_Load(object sender,EventArgs e){var t=this;var s=new r(0,0,300,300);var q=new r(0,0,15,50);var o=new r(0,0,15,50);var x=new PointF(150,150);var v=.06F;var h=v;var b=new r(x.X,x.Y,15,15);var p1=0;var p2=0;var p=new PictureBox{Size=t.Size,Location=new Point(0,0)};t.Controls.Add(p);p.Paint+=(wh,n)=>{var g=n.Graphics;Action<Brush,r>f=g.FillRectangle;var k=new SolidBrush(Color.Black);var w=new SolidBrush(Color.White);var d=new byte[256];GetKeyboardState(d);var l=q.Location;var _1=.1F;q.Location=new PointF(0,d[90]>1?l.Y+_1:d[81]>1?l.Y-_1:l.Y);l=o.Location;o.Location=new PointF(269,d[77]>1?l.Y+_1:d[79]>1?l.Y-_1:l.Y);f(k,s);f(w,q);f(w,o);Func<r,bool>i=b.IntersectsWith;h=i(q)||i(o)?-h:h;v=b.Top<1||b.Bottom>t.Height-30?-v:v;b.Offset(h,v);if(b.Left<0){p2++;b.Location=x;}if(b.Right>290){p1++;b.Location=x;}f(w,b);for(int j=0;j<19;)f(w,new r(140,(j+(j++%2))*15,10,10));var a=new Font("Arial",20);g.DrawString(p1.ToString(),a,w,100,12);g.DrawString(p2.ToString(),a,w,170,12);p.Invalidate();};}[DllImport("user32.dll")]static extern bool GetKeyboardState(byte[]s);}} ``` Edit: Didn't see the requirement for a free, linux-runnable language... [Answer] # [K (oK) + `iKe`](https://github.com/JohnEarnest/ok), ~~393~~ 335 bytes ``` q:p:-15+h%2 d:w,h b:-2+d%2 v:5 -1 s:t:0 tick:{b::v+0|d&b $[$[0>*b;t+::1;w<*b;s+::1;0];b::-2+d%2;0] v*::$[(&/(b>(0;p-5))&b<(10;p+30))|&/(b>(w-15;q-5))&b<(w;q+30);-1;1],1} draw:{((;gray);(((0;p);(w-5;q));;30 5#1);(b;;5 5#1);((w%4;0);;~,/'+text(),$t);((-10+3*w%4;0);;~,/'+text(),$s))} kd:{$[x=81;p-::5;x=65;p+::5;x=80;q-::5;x=76;q+::5;0]} ``` [Try it online!](https://johnearnest.github.io/ok/ike/ike.html?ike.html?key=C7Tx-lFa) My first K answer! Was really fun to do in K. Kinda sad that the question spec isn't too specific about the implementation. This answer has points based scoring, involves two players and no AI. [Answer] # [Tcl/Tk](http://tcl.tk/), 932 bytes ***Must be run in the interactive shell*** ``` gri [can .c -w 1024 -he 768 -bg #000] proc A {} {set ::v [expr (int(rand()*36)+1)*20]} proc R {C t\ X} {.c cr r $C -f #aaa -t $t} proc I {} {incr ::v 20} time {R "504 [I] 520 [I]"} 18 R "0 0 1024 20" R "0 748 1024 768" R "0 340 20 440" b R "1004 340 1024 440" B R "40 [A] 60 [I]" P lmap n 4\ 5 T F\ S {.c cr t ${n}62 60 -ta $T -te 0 -fi #aaa -font {"" 56}} proc C t\ n {lindex [.c coo $t] $n} lmap {a b c d e} {q b 1 >20 -20 a b 3 <740 20 p B 1 >20 -20 l B 3 <740 20} {bind . $a "if \[C $b $c]$d {.c move $b 0 $e}"} lassign {0 0 20 20} F S y x proc M {} {lmap {_ a b c d e f} {0 <40 b 20 S 960 980 2 >984 B -20 F 80 100} {if [C P $_]$a {if [C P 1]>=[C $b 1]&&[C P 3]<=[C $b 3] {bell set ::x $c} {.c itemco $d -te [incr ::$d] if \$::$d>8 {tk_messageBox -message WINNER! lmap T F\ S {.c itemco $T -te [set ::$T 0]}} .c coo P $e [A] $f [I]}}} .c move P $::x [set ::y [expr [C P 1]<40?20:[C P 3]>727?-20:$::y]] after 99 M} M focus -f . ``` ***Note:*** ``` #There is an Enter at the end ``` Just a very minimal version of Pong, where the ball only runs in diagonal angles and always has same velocity. [![enter image description here](https://i.stack.imgur.com/qrtlI.png)](https://i.stack.imgur.com/qrtlI.png) ]
[Question] [ Given a list of at least two words (made only of lowercase letters), construct and display an ASCII ladder of the words by alternating the direction of writing first to the right, then to the left, relatively to the initial direction from left to right. When you finish writing a word, change the direction and only then start writing the next word. If your language doesn't support lists of words, or it's more convenient for you, you can take the input as a string of words, separated by a single space. Leading and trailing whitespaces are allowed. `["hello", "world"]` or `"hello world"` ``` hello w o r l d ``` Here we start by writing `hello` and when we come to the next word (or in the case of the input as a string - a space is found), we change the relative direction to the right and continue to write `world` ## Test cases: ``` ["another", "test", "string"] or "another test string" -> another t e s tstring ["programming", "puzzles", "and", "code", "golf"] or "programming puzzles and code golf" -> programming p u z z l e sand c o d egolf ["a", "single", "a"] or "a single a" -> a s i n g l ea ``` ## Wining criteria The shortest code in bytes in every language wins. Don't let be discouraged by the golfing languages! [Sandbox](https://codegolf.meta.stackexchange.com/a/17694/75681) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes ``` F⮌A«↑⮌ι‖↗ ``` [Try it online!](https://tio.run/##NYlBCsMgEADPySvEkwvpB9oX9FaEnkIOYlYjGJWNySGlb9/WQk8zzNjFkM0mMrtMQmk8kDZU91T2qgBAvPruQSFVdX2WQfx/ALj1nUYX0f6WDn6p3/ZmHkdZKHsy6xqSl4OQZT/PiFtTk@YGm2ds9Dk6OU18OeIH "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Works by drawing the text backwards, transposing the canvas after every word. 10 bytes for string input: ``` F⮌S≡ι ‖↗←ι ``` [Try it online!](https://tio.run/##DcxLCsMgFEbhcbKKn4wU2g2kKyh0UFK6ADHXBxgVvUkhpWu3jj/O0U4VnVRozaQCsdBBpZK4x7zzi4uPVkgpUT@etYPwEt9x0KoSJkwzFjKBNIv5nRdvHcvbOKxk1B54xrPnnR5k@ALf6ddaLskWtW19jLyfZ6AKFVfotBJsCmZs1yP8AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Draws the text backwards, transposing the canvas for spaces. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~94~~ ~~78~~ 74 bytes -4 from [Johan du Toit](https://codegolf.stackexchange.com/questions/186005/construct-a-word-ladder?answertab=votes#comment445975_186015) ``` o,f;g(int*s){for(o=f=0;*s;s++)*s<33?f=!f:printf("\n%*c"+!f,f*(o+=!f),*s);} ``` [Try it online!](https://tio.run/##ZYxBCsIwEEX3nmIMCElaQejOWLyAR3AT0kwspJmSSREqnr1Gt@4@/73/3TE4t23UoglyTEWzeiFlST32J6PZcNMozZeuu2K/x/Ocq4RS3NNBO9HssUUtqalItXVr3ttkxyTVaxfkTTx8jARPynEQysxLYSlq@DGbqDx8huK5AJf6G/6cOVPIdpoqg3lZ1@gZbBrA0eAhUMT/V@AqRw/227y3Dw "C (gcc) – Try It Online") Prints the ladder, one character (of the input) at a time. Takes a space-separated string of words. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~19~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` €θ¨õšøíJD€gs24SΛ ``` -3 bytes thanks to *@Emigna*. [Try it online.](https://tio.run/##yy9OTMpM/f//UdOaczsOrTi89ejCwzsOr/VyAQqkFxuZBJ@b/f9/tFJBUX56UWJubmZeupKOUkFpVVVOajGQlZiXAiST81NSgVR6fk6aUiwA) **General explanation:** Just like [*@Emigna*'s 05AB1E answer](https://codegolf.stackexchange.com/a/186006/52210) (make sure to upvote him btw!!), I use [the Canvas builtin `Λ`](https://codegolf.stackexchange.com/a/175520/52210). The options I use are different however (which is why my answer is longer..): * `b` (the strings to print): I leave the first string in the list unchanged, and add the trailing character to each next string in the list. For example `["abc","def","ghi","jklmno"]` would become `["abc","cdef","fghi","ijklmno"]`. * `a` (the sizes of the lines): This would be equal to these strings, so `[3,4,4,7]` with the example above. * `c` (the direction to print in): `[2,4]`, which would map to `[→,↓,→,↓,→,↓,...]` So the example above would step-by-step do the following: 1. Draw `abc` in direction `2`/`→`. 2. Draw `cdef` in direction `4`/`↓` (where the first character overlaps with the last character, which is why we had to modify the list like this) 3. Draw `fghi` in direction `2`/`→` again (also with overlap of trailing/leading characters) 4. Draw `ijklmno` in direction `4`/`↓` again (also with overlap) 5. Output the result of the drawn Canvas immediately to STDOUT **Code explanation:** ``` €θ # Only leave the last characters in the (implicit) input-list ¨ # Remove the last one õš # And prepend an empty string "" instead ø # Create pairs with the (implicit) input-list í # Reverse each pair J # And then join each pair together to single strings D€g # Get the length of each string (without popping by duplicating first) s # Swap so the lengths are before the strings 24S # Push [2,4] Λ # Use the Canvas builtin (which outputs immediately implicitly) ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~17~~ ~~12~~ ~~11~~ 10 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ø⁸⇵{⟳K└×∔⤢ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JUY4JXUyMDc4JXUyMUY1JXVGRjVCJXUyN0YzJXVGRjJCJXUyNTE0JUQ3JXUyMjE0JXUyOTIy,i=JTVCJTIyYW5vXy8lM0V0aGVyJTIyJTJDJTIwJTIydGVfLyUzRXN0JTIyJTJDJTIwJTIyc3RyXy8lM0VpbmclMjIlMkMlMjAlMjIlMjElMjElMjIlNUQ_,v=8) Explanation: ``` ø⁸⇵{⟳K└×∔⤢ full program taking array as input (loaded with ⁸) ø push an empty canvas ["test", "str"], "" ⁸⇵{ for each input word, in reverse: "str", "test" (showing 2nd iter) ⟳ rotate the word vertically "str", "t¶e¶s¶t" K pop off the last letter "str", "t¶e¶s", "t" └ swap the two items below top "t¶e¶s", "str", "t" × prepend "t¶e¶s", "tstr" ∔ vertically append "t¶e¶s¶tstr" ⤢ transpose the canvas "test s t r" ``` [Answer] # JavaScript (ES8), ~~91 79~~ 77 bytes Takes input as an array of words. ``` a=>a.map((s,i)=>i&1?[...s].join(p):s+=p+=''.padEnd(s.length-!i),p=` `).join`` ``` [Try it online!](https://tio.run/##fY8xbsMwDEX3nML1UEuwI6BrAaVTT5EGMGHJsgKaFES1BXJ51/LYIdPj8P7/4B1@QKYcUzkTO7/NdgN7AbNCUkqGqO0lvr59XI0xcjN3jqSSfpfept52nUngPskpMegplOX8EvWQ7Hga9eGO4zYxCaM3yEHN6touHpHboWl/OaNrb7rpm@6LOn36bwJxWXyubvFSKqXkSOFZKGUOGda1ansgfT8e6KWeQK5i2r@sDIzz0/Vjb6/BQ4fd1dsf "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array a.map((s, i) => // for each word s at position i in a[]: i & 1 ? // if this is a vertical word: [...s].join(p) // split s and join it with p : // else: s += // add to s: p += // add to p: ''.padEnd( // as many spaces s.length // as there are letters in s - !i // minus 1 if this is the 1st word (because it's not connected ), // with the last letter of the previous vertical word) p = `\n` // start with p = linefeed ).join`` // end of map(); join everything ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes Saved 1 byte thanks to *Grimy* ``` €ðÀD€g>sŽ9÷SΛ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UdOawxsON7gA6XS74qN7LQ9vDz43@///aKWCovz0osTc3My8dCUdpYLSqqqc1GIgKzEvBUgm56ekAqn0/Jw0pVgA "05AB1E – Try It Online") **Explanation** ``` # example input ["Hello", "World"] €ðÀ # push a space after each word # STACK: ["Hello"," ","World"," "] D # duplicate €g> # get the length of each word in the copy and add 1 # these are the lengths to draw # STACK: ["Hello"," ","World"," "], [6, 2, 6, 2] s # swap the list of word to the top of the stack Ž9÷S # push [2, 5, 4, 1] # this is the list of directions to draw # 1=northeast, 2=east, 4=south, 5=southwest Λ # paint on canvas ``` [Answer] # [Python 2](https://docs.python.org/2/), 82 bytes ``` b=p=0 r='' for w in input(): for c in w:r+='\n'.ljust(p)*b+c;p+=1-b b^=1 print r ``` [Try it online!](https://tio.run/##JYzdDoIwDEbv9xRLbwBRI15i9iSIyQbjx4xt6UZQXh4pJk1Oe9p@/hsHZ@/bMoxG86LUH91wBIBNCS9uDEWSsM4hX/ho9/JzTLOScVINqaXEXCRPm1zNew4x9dlJ5c3D56K4KMbVSxTM42gjx@0go/AKBm2MgzOHxaFpoWYVSOvioJFk1CESQ9xf@mPr0fUop4nmfePndTU6UCttS2hcq4m9M90/70jY783hJdQ/ "Python 2 – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 57 bytes ``` ->,[[.<+>,],[<<[-]++++++++++.--[-<++++>]>[-<+<.>>]>.<,],] ``` [Try it online!](https://tio.run/##PcoxDoAgDEDR3gfaEzS9SMOAqISIYDAuXh5h8U9v@EvzqexPOHpHsarERqyzyqzozB8hKvKUOJlikiHi8brer1Zj8@eZSoTred@83eDLCqGuG8Sa9w8 "brainfuck – Try It Online") Takes input as NUL separated strings. Note that this is using EOF as 0, and will stop working when the ladder exceeds 256 spaces. ### Explanation: ``` - Initialise counter as -1 >,[ Start ladder [.<+>,] Print the first word, adding the length of it to the counter ,[ Loop over each letter of the second word <<[-]++++++++++. Print a newline --[-<++++>] Create a space character >[-<+<.>>] Print counter many spaces >.<, Print the letter and move to the next letter ] , Repeat until there are no more words ] ``` [Answer] # JavaScript, 62 bytes ``` a=>' '+a.replace(/./g,c=>1-c?(a=!a,''):a?(p+=' ',c):p+c,p=` `) ``` [Try it online!](https://tio.run/##lY85DsIwEEV7TjHQ2FYWlhLJcJWMnIkBDR7LNiDl8sF0iI76//eXGz4xu3SNpQsy0jLZBe1JgWqwTxQZHeltv/Wts6d9584a7RpbpcwRzzo2tjpbZ46xcW20w2owi5OQhaln8XrSmwsxC7wk8bgxZvWtqk59OgiLPux@tEpikHKhBIVygVzSNfg/E2ISn/B@ryTExzwzZcAwgqtPwQtP/y6CXKOYACu4vAE "JavaScript (Node.js) – Try It Online") Thanks [Rick Hitchcock](https://codegolf.stackexchange.com/users/42260/rick-hitchcock), 2 bytes saved. --- # JavaScript, 65 bytes ``` a=>a.replace(/./g,c=>1-c?(t=!t,''):t?p+c:(p+=p?' ':` `,c),t=p='') ``` [Try it online!](https://tio.run/##lY@7bsMwDEX3fAWTRTL8SJvRgOJfMSHTSgpGFCS2AfzzjroV3TIfnPv4wh8sPt@T9lEW2le3o7vikCkxerLn4Rw6766fvZ@suqN2xjSjTqn1o02tS5MBM86HufNNpy65incvsQjTwBLsak83YhZ4Subl1DSHv9T05reKUO3l4x@rJkbRG2VQKgpF8z2GNxNSlpDx8agmpO9tYyqAcQFfz0IQXt9dBKVGMQFWcX8B "JavaScript (Node.js) – Try It Online") ``` a=>a.replace(/./g,c=>( // for each character c in string a 1 - c ? // if (c is space) (t = !t, // update t: boolean value describe word index // truthy: odd indexed words; // falsy: even indexed words '') : // generate nothing for space t? // if (is odd index) which means is vertical p+c : // add '\n', some spaces, and a sigle charater // else (p+=p?' ':'\n', // prepare the prepend string for vertical words c) // add a single character ), t=p='' // initialize ) ``` [Answer] # [Aheui (esotope)](https://github.com/aheui/pyaheui), ~~490~~ ~~458~~ 455 bytes ``` 삭뱃밸때샏배샐배새뱄밿때빠뱋빼쌘투@밧우 @두내백뱃빼선대내백뱃섣@여우샐처샐추 희차@@@뭏누번사@빼뭏오추뻐@@@배 By@@@새대백@@@우뻐색 Legen@@빼쵸누번@@빼 DUST@@@샌뽀터본섣숃멓 @@@@@@@오어아@먛요아@@샏매우 @@@@@아@@@@@@오@@@@@서어 @@@@@희차@@요 ``` [Try it online!](https://tio.run/##XZBRSsNAEIbfc4pcrdgYC21TKn3pU0lWjBhMxFZjVQgaaIUUNm0qCSZ4oJmyR4izSU1rYRiWf/75ZnZaF9qoU5ZoriC2gKcwc9BygXO0vCrbEDPgP6RDFkB8C1mOjr@zI5EHwBc454p83XtgJsBjSSEHC8CZNAqyD/LgU0Ru4uLal/lrquzeIuRLqtUBKxdsBmsbzQqf5aSgH5IVvr2DjcuZ76J4biS5Jw3k8UGZc@pB64askSiuRHFd5bs9g5bcpvW0RiFrKPKtyDciT47YDhSTHeOwSeknaFvw@aA05eOQuz4mOGOSt3zB@bR@VxQXFuH@XP96/hwnoFOFvRL6tPn4gDStLAdDQx@2er1OX1cHo/G4q12qrX5bPTPamqob3fNf "Aheui (esotope) – Try It Online") Slightly golfed by using full-width characters(2 bytes) instead Korean(3 bytes). # Explanation Aheui is befunge-like esolang. Here is code with color: [![Aheui code with color](https://i.stack.imgur.com/wIDnW.png)](https://i.stack.imgur.com/wIDnW.png) ?1 part checks if current character is space or not. ?2 parts check whether words had written right-to-left or top-to-down. ?3 part is break condition of loop which types spaces. ?4 parts check if current character is end of line(-1). Red part is stack initialization. Aheui uses stacks (from `Nothing` to `ㅎ` : 28 stacks) to store value. Orange part takes input(`뱋`) and check if it is space, by subtracting with `32`(ascii code of space). Green part add 1 to stack which stores value of length of space, if writing right-to-left. Purple part is loop for printing spaces, if writing up-to-down. Grey part check if current character is `-1`, by adding one to current character. Blue part prints current character, and prepare for next character. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 15 bytes ``` ò mrÈ+R+YÕùT±Xl ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=8iBtcsgrUitZ1flUsVhs&input=WyJwcm9ncmFtbWluZyIsICJwdXp6bGVzIiwgImFuZCIsICJjb2RlIiwgImdvbGYiXQ) ``` ò mrÈ+R+YÕùT±Xl :Implicit input of string array ò :Partition into 2s m :Map each pair r : Reduce by È : Passing through the following function as X & Y + : Append to X R : Newline + : Append YÕ : Transpose Y ù : Left pad each line with spaces to length T± : T (initially 0) incremented by Xl : Length of X :Implicitly join and output ``` [Answer] ## bash, 119 chars ``` X=("\e7" "\n\e8") w="$@" l=${#w} d=0 for((i=0;i<l;i++));do c="${w:$i:1}" [ -z $c ]&&d=$((1-d))||printf ${X[$d]}$c done ``` This uses ANSI control sequences to move the cursor - here I'm only using save `\e7` and restore `\e8`; but the restore has to be prefixed with `\n` to scroll the output if it's already at the bottom of the terminal. For some reason it doesn't work if you're not *already* at the bottom of the terminal. \* shrug \* The current character `$c` is isolated as a single-character substring from the input string `$w`, using the `for` loop index `$i` as the index into the string. The only real trick I'm using here is `[ -z $c ]` which will return `true`, i.e. the string is blank, when `$c` is a space, because it's unquoted. In correct usage of bash, you would quote the string being tested with `-z` to avoid exactly this situation. This allows us flip the direction flag `$d` between `1` and `0`, which is then used as an index into the ANSI control sequence array, `X` on the next non-space value of `$c`. I'd be interested to see something that uses `printf "%${x}s" $c`. Oh gosh let's add some whitespace. I can't see where I am... ``` X=("\e7" "\n\e8") w="$@" l=${#w} d=0 for ((i=0;i<l;i++)); do c="${w:$i:1}" [ -z $c ] && d=$((1-d)) || printf ${X[$d]}$c done ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 65 bytes ``` {$/=0;.map:{$/+=$++%2??!.comb.fmt("%$/s"," ").print!!.say*.comb}} ``` [Try it online!](https://tio.run/##HYxNCoMwGAX3OcVnUNGmxNJFFxXxIt2kJlEhfyQpRcWzp6G7eczwnPDqkfQGtYQhHWU33HqqmXtmJENJSHUfx4JOVr@p1LHBVdkFfMUIt9T51cSioIFtl39xnklaD41ajQgtHAiA0K/1PNBa9nnlEvDLYHSmRShlIUvFETM2LsJDFCFCiPl2Rs7b2TOtM4P77LsSAZjhMFkuYLZKIgYhSyWA/QA "Perl 6 – Try It Online") Anonymous code block that takes a list of words and prints straight to STDOUT. ### Explanation ``` { } # Anonymous code block $/=0; # Initialise $/ to 0 .map:{ } # Map the list of words to $/+= # Increment $/ by $++%2?? # For even indexes .comb # Each letter of the word .fmt( ) # Formatted as "%$/s" # Padded with $/-1 spaces ,"\n" # Joined by newlines .print # And printed without a newline ! # Boolean not this to add 0 to $/ !! # For odd indexes .say # Print with a newline *.comb # And add the length of the word ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal/wiki), 19 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page) ``` FLθ¿﹪鲫↓§θι↗»«§θι↙ ``` Input as a list of strings [Try it online (verbose)](https://tio.run/##dYyxCsIwEIZ3nyJkSiAujnUSVCi0IIJT6RCaNA2kuTRNq1R89hiLg4vDf3d8x/c3HfcNcBPjGTwppFWhIwOlG4TylpQgJgNEsx2lz4QQunhtA8mOcLcMHUJuhXyQgWlK9@u/hFmS7OauWnVhZa@Ukxnlr/9X/PQWsv2aMVYVdh6U532vrcIMu2lZjBzTxa1IswEh01JgWlzXcTubNw) or [try it online (pure)](https://tio.run/##S85ILErOT8z5///9nmXv96w5t@PQ/vc7V53beWjTodWP2iYfWn5ux7mdj9qmH9p9aDWMM/P//@hopYKi/PSixNzczLx0JR2lgtKqqpzUYiArMS8FSCbnp6QCqfT8nDSl2FgA) **Explanation:** Loop in the range `[0, input-length)`: ``` For(Length(q)) FLθ ``` If the index is odd: ``` If(Modulo(i,2)){...} ﹪鲫...» ``` Print the string at index `i` in a downward direction: ``` Print(:Down, AtIndex(q,i)); ↓§θι ``` And then move the cursor once towards the top-right: ``` Move(:UpRight); ↗ ``` Else (the index is even): ``` Else{...} «... ``` Print the string at index `i` in a regular right direction: ``` Print(AtIndex(q,i)); §θι ``` And then move the cursor once towards the bottom-left: ``` Move(:DownLeft); ↙ ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~89~~ 88 bytes ``` s=i=-1 r='' for w in input():r+=[('\n'+' '*s).join(' '+w),w][i];s-=i*len(w);i=~i print r ``` [Try it online!](https://tio.run/##JU27DsIwDNzzFZGX9AFIICZQJmDmA0qHioY2KMSRExRg4NdLUiRLd76z79w7jGg30@F8PEkCgMlLLZdrRlIIdkPikWubxj1DUe6olk0hLlbUgovKl6s7alskXsdyEdtGt3u/lLoyyhax3Gv51cyRtoHTNCNLFYypl7ryXFltpwZGZQzCgkNEMj20rIHOYhgVZTEoHzL6kP6H2XWEA3WPR96T456fj1E@0872Ga7Yq4wDmts/b05I92bWO2h/ "Python 2 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 122 bytes ``` a=>{int i=0;var t="\n";foreach(var z in a)Write(i++%2<1?z+(t+="".PadRight(z.Length-(i<2?1:0))):string.Join(t,z.Skip(0)));} ``` [Try it online!](https://tio.run/##jY8xT8MwEIX3/oqTJSRHaaO2Y5O0YkUdEB0YgOFwLskJ147sAyQjfntI6YKYMr739N17Z@LKRB5vjbB3VZTArnt62bf1iPX@i50A1@vyAwNIrZ6dKlsfCE2vL1YCdoDZY2AhzXl@s602h5RryWulintsHrjrRafiSK6TfqW52h42u3WWZbtrVXHn2WlZpuL0xoO@JOX3WC5arRBewUADBK0qToNl0VO4@C07siP9X0xMT9Z6@PTBNrMZdF56mv6jKHBdNZsdgu8Cns8TA8N7SpYioGvA@Iag83b@coQ4HbEE@AcZfwA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~47~~ ~~45~~ 43 bytes ``` ;[`(([:<@(+/)\#&>##$#:@1 2)@])`([' '"0/[)}] ``` [Try it online!](https://tio.run/##NclBC4IwAIbhu7/iw0XbqGZ2nBqDoFOnrkty6LRCnahdhH67CdHhvTzva/YFLZFIUGyxh1zaCZyul/Mc6YwxLWPFNgG/kfWRkBWRKsSBq5RnTFNQfx9o/kln7o12GJEIaAmbP5wqEUfiHnq/QWEwPNuqtjD0T13vqt40zeLo3tNU2wGmLZC7wqJydUm9@Qs "J – Try It Online") I found a fun, different approach... I started messing around with left pads and zips with cyclic gerunds and so on, but then I realized it would be easier to just calculate each letter's position (this boils down to a scan sum of the correctly chosen array) and apply amend `}` to a blank canvas on the razed input. The solution is handled almost entirely by Amend `}`: ``` ; [`(([: <@(+/)\ #&> # # $ #:@1 2)@])`([ ' '"0/ [)} ] ``` * `; ( single verb that does all the work ) ]` overall fork * `;` left part razes the input, ie, puts all the letters into a contiguous string * `]` right part is the input itself * `(stuff)}` we use the gerund form of amend `}`, which consists of three parts `v0`v1`v2`. + `v0` gives us the "new values", which is the raze (ie, all the characters of the input as one string), so we use `[`. + `v2` gives us the starting value, which we are transforming. we simply want a blank canvas of spaces of the needed dimensions. `([ ' '"0/ [)` gives us one of size `(all chars)x(all chars)`. + The middle verb `v1` selects which positions we will put our replacement characters in. This is the crux of the logic... * Starting at position `0 0` in the upper left, we notice that each new character is either 1 to the right of the previous position (ie, `prev + 0 1`) or one down (ie, `prev + 1 0`). Indeed we do the former "len of word 1" times, then the latter "len of word 2" times, and so on, alternating. So we'll just create the correct sequence of these movements, then scan sum them, and we'll have our positions, which we then box because that's how Amend works. What follows is just the mechanics of this idea... * `([: <@(+/)\ #&> # # $ 1 - e.@0 1)` + First `#:@1 2` creates the constant matrix `0 1;1 0`. + `# $` then extends it so it has as many rows as the input. eg, if the input contains 3 words it will produce `0 1;1 0;0 1`. + `#&> #` the left part of that is an array of the lengths of the input words and `#` is copy, so it copies `0 1` "len of word 1" times, then `1 0` "len of word 2 times", etc. + `[: <@(+/)\` does the scan sum and box. [Answer] # T-SQL, 185 bytes ``` DECLARE @ varchar(max)='Thomas Clausen Codegolf Script' ,@b bit=0,@s INT=0SET @+=':'WHILE @ like'%_:%'SELECT @b+=len(left(@,1))-1,@=stuff(@,1,1,'')+iif(left(@,@b)='','',' '+space(@s))+trim(left(@,1)),@s+=len(left(@,~@b))PRINT stuff(@,1,1,'') ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1055394/construct-a-word-ladder)** [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 51 bytes ``` 1,2,`\w+ ;$& +(m`^(.(.*?)) ?;(.) $1¶$.2* $3; ; |;$ ``` [Try it online!](https://tio.run/##FcxLCsIwEIDh/ZxiFlHSB4HWZRZdegmRBpM@YJqUSUqheC4P4MVi3f3wwc8uzd40@SLvfW7qtu4fewVaXKGSS/@USqqyKwrstFQFiOb7EaotUdw0aHxrATlPjijgHpgsGB/S5BiTiwlj4tmPsHIY2SzL2bhux0EuovEWX8E6HAMNYDCeSA4NDGHj/8tGnD0aoh8 "Retina – Try It Online") A rather straightforward approach that marks every other word and then applies the transformation directly. ### Explanation ``` 1,2,`\w+ ;$& ``` We mark every other word with a semicolon by matching each word, but only applying the replacement to the matches (which are zero indexed) starting from match 1 and then 3 and so on. ``` +(m`^(.(.*?)) ?;(.) $1¶$.2* $3; ``` `+(m` sets some properties for the following stages. The plus begins a "while this group of stages changes something" loop, and the open bracket denotes that the plus should apply to all of the following stages until there is a close bracket in front of a backtick (which is all of the stages in this case). The `m` just tells the regex to treat `^` as also matching from the beginning of lines instead of just the beginning of the string. The actual regex is pretty straightforward. We simply match the appropriate amount of stuff before the first semicolon and then use Retina's `*` replacement syntax to put in the correct number of spaces. ``` ; |;$ ``` This stage is applied after the last one to remove semicolons and spaces at the end of words that we changed to vertical. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 58 bytes ``` (?<!^(\S* \S* )*\S*) ¶ ¶? +`(..(.)*¶)((?<-2> )*\S) $1 $3 ``` [Try it online!](https://tio.run/##HYxRCsIwEET/9xQrVEgqFtRfsZ8ewF@RBpPWwjZbNilCD9YD9GIxFWaGgXmMuNh7k/bq3iRVX3cv9XyUuFmXOTWsS1aNAIdGVZWqdLkuWmX0eL79GQ3FCYtLSh9HxPhlIQvGc/w4wehCxBCl9x2Mwp2YYcgdx2meyQU03uKbrcOOqQWDIY/k0EDLk2xfNmDv0RD9AA "Retina 0.8.2 – Try It Online") Link includes test cases. Alternative solution, also 58 bytes: ``` ( \S*) $1¶ +` (.) ¶$1 ¶ +`(..(.)*¶)((?<-2> )*\S) $1 $3 ``` [Try it online!](https://tio.run/##FcxNCoMwFATg/TvFLCwklgq221KXPYBbF4Ym/sAzkSRS8GAewIul6W74hhlv4mxVuoh3nwS6tpSgoj4PuvYQlaTzKGoQMmQRVZWtPA8pRPO83V@QZdfKPEDxSGkyzA5f51mTsi5OxiOaEBGin@1Iq3ejV8uSM9Zt39kEKKvxcdpgdDyQQsglGyga3Ob/XzpgtlDMPw "Retina 0.8.2 – Try It Online") Link includes test cases. I'm deliberately not using Retina 1 here, so I don't get operations on alternate words for free; instead I have two approaches. The first approach splits on all letters in alternate words by counting preceding spaces, while the second approach replaces alternate spaces with newlines and then uses the remaining spaces to help it split alternate words into letters. Each approach has to then join the last vertical letter with the next horizontal word, although the code is different because they split the words in different ways. The final stage of both approaches then pads each line until its first non-space character is aligned under the last character of the previous line. Note that I don't assume that words are just letters because I don't have to. [Answer] ## J, ~~35~~ 33 bytes ``` 3 :'[;.0>(,|:)&:,.&.>/_98{.;:|.y' ``` This is a verb that takes the input as a single string with the words separated by spaces. For example, you could call it like this: ``` 3 :'[;.0>(,|:)&:,.&.>/_98{.;:|.y' 'programming puzzles and code golf' ``` The output is a matrix of letters and spaces, which the interpreter outputs with newlines as required. Each line will be padded with spaces so they have the exact same length. There's one slight problem with the code: it won't work if the input has more than 98 words. If you want to allow a longer input, replace the `_98` in the code by `_998` to allow up to 998 words, etc. --- Let me explain how this works through some examples. Suppose we have a matrix of letters and spaces that we imagine is a partial output for some words, starting with a horizontal word. ``` [m=: 3 3$'vwx y z' vwx y z ``` How could we prepend a new word before this, vertically? It's not hard: just turn the new word to a single-column matrix of letters with the verb `,.`, then append the output to that single-column matrix. (The verb `,.` is convenient because it behaves as an identity function if you apply it to a matrix, which we use for golfing.) ``` (,.'cat') , m c a t vwx y z ``` Now we can't just iterate this way of prepending a word as is, because then we'd only get vertical words. But if we transpose the output matrix between each step, then every other word will be horizontal. ``` (,.'dog') , |: (,.'cat') , m d o g catv w xyz ``` So our first attempt for a solution is to put each word into a single-column matrix, then fold these by appending and transposing between them. ``` > (,|:)&.>/ ,.&.>;: 'car house dog children' c a r housed o g children ``` But there's a big problem with this. This puts the first letter of the next word before turning a right angle, but the specification requires turning before putting the first letter, so the output should be something like this instead: ``` c a rhouse d o gchildren ``` The way we achieve this is to reverse the entire input string, as in ``` nerdlihc god esuoh rac ``` then use the above procedure to build the zig-zag but turning only after the first letter of each word: ``` n e r d l i h c gode s u o h rac ``` Then flip the output: ``` [;.0> (,|:)&.>/ ,.&.>;:|. 'car house dog children' car h o u s edog c h i l d r e n ``` But now we have yet another problem. If the input has an odd number of words, then the output will have the first word vertical, whereas the specification says that the first word must be horizontal. To fix this, my solution pads the list of words to exactly 98 words, appending empty words, since that doesn't change the output. [Answer] # [PowerShell](https://docs.microsoft.com/en-us/powershell/), ~~101 89~~ 83 bytes -12 bytes thanks to [mazzy](https://codegolf.stackexchange.com/users/80745/mazzy). ``` $args|%{$l+=if(++$i%2){$_.length-1;$t+=$_}else{1;$_|% t*y|%{$t+=' '+' '*$l+$_}}};$t ``` [Try it online!](https://tio.run/##dVLRboMwDHz3V1hVmKHQSdvjpkr8CWMlpUgpYUmqdqV8O3MIneik5cG@i@@cxEqnz9LYg1RqFJ@4xX4UpantLeqFSrfNPk5T0USvSS@KZyXb2h02L@/CpVtRDFJZ2TMrbhG69bf3cIGAUkJas581w8DqcQCIiTLMOSZJhjHttQ7cA96COCfw19CAvM5TDNhMUU2xAsozpEnIfjproyqa7WWr3UEGOaKbs5yzve9bZ5q29o1odvhOTlrnc6jeW3ZG16Y8Hr0Bf1e3wKcFvv6D1QLLBbZlWy0or90j1Y/0j1jWWu3DQBb39I/oTterktZDPsKnna6kz95CcB8YWGighRoUyDJ0KqchcB816UtK8IYR9tPR4pKh6PibiCJww/gJ@efkYSYrEYsLbuQXl5K3j1b0ZljBMP4A) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~74~~ 65 bytes ``` -join($args|%{$_|% t*y|%{($p+=(' ',' ')[!$p]*!$i)*$i;$_};$i=!$i}) ``` [Try it online!](https://tio.run/##dVLbTsMwDH3PVxiWkXaM/QCatDfENyA0wmq6oCwpccpgl28fTtqhDgk/2MeufU7qpPFbDLRGa0/yFeawP929e@MKqUNNh/FeLg9jiJNvhoVsbueFAjVVQpVPV7J5nlxJU06kuZfL4700c06P5ekoRLFQIpF6AWzb7DscsrfZV0ItpqByo2Kw9cFWqpzmce18XGPXDhD7iH2kc51iMK5ORKqfSEwRKabYfT1TNsHXQW82aQB@rRngdoB3/2A7wDjApF01SNlWl6m/TP80Y@3tW7eQwTnTTzTtbmeREmSJFFa@whTTiBLnhQkSRjhRCytQd0w6L4F5bO7XqoQDjGGfpSV@NbiKWE1BEt@9XHblgNTayIUbfhILAhgBNVbHyDwzeIzQEgJvGkJrEdSD@UQHGqyhCP4NdASLmnHceuArrWg2m6lLxTv8KHqd/N6uX9x1mVtGZ/lfG0HrVn6zQceUa0Ms5FjfQ2XSsb6hH@jumsTx9AM "PowerShell – Try It Online") [Answer] # [R](https://www.r-project.org/), 126 bytes ``` function(x,`>`=strrep)for(i in seq(x)){H=i%%2;cat(paste0(' '>!H,' '>F*!H,e<-'if'(H,x,strsplit(x,''))[[i]])) F=F+nchar(e[1])-H} ``` [Try it online!](https://tio.run/##pc5BasMwEAXQvU/hGMKMWhmSbFN7aXwHxxChjByBI6mSAialZ3cl36BkNn828/74VTWrehoZtTW48Gt7bUL0nhxT1qMutSkDfePC2E/f6P3@dJYiohMh0gGhgHbXcyih7T7SQl81aAXY84UnJbhZx4QCMDYMehwZK7qm@zTyLjzScBxZ3f@uCiVWwth4J1/xsooUYs4kaDNV6ShXwsXU/5mLAVZstPN28uLxyFhi3fP1minkVZhbDmlvlHOys3q/Tmy/p7J5Q8U74voH "R – Try It Online") * -3 bytes thanks to @Giuseppe [Answer] ## T-SQL, 289 bytes ``` DECLARE @ VARCHAR(MAX)='a a',@I INT=1,@S INT=0,@B INT=0WHILE @I<=LEN(@)IF SUBSTRING(@,@I,1)=''IF @B=0SELECT @S-=1,@=STUFF(@,@I,1,' '+SPACE(@S)),@I+=@S+3,@B=1 ELSE SELECT @=STUFF(@,@I,1,''),@S+=1,@B=\ELSE IF @B=0SELECT @I+=1,@S+=1 ELSE SELECT @=STUFF(@,@I,0,' '+SPACE(@S)),@I+=@S+3PRINT @ ``` This runs on SQL Server 2016 and other versions. @ holds the space-delimited list. @I tracks the index position in the string. @S tracks the total number of spaces to indent from the left. @B tracks which axis the string is aligned with at point @I. The byte count includes the minimal example list. The script goes through the list, character by character, and changes the string so that it will display according to the requirements. When the end of the string is reached, the string is PRINTed. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 75 bytes ``` a=>a.map(x=>i++&1?[,...x].join(` `.padEnd(n)):(n+=x.length,x),n=i=0).join`` ``` [Try it online!](https://tio.run/##jdBBTsMwEIXhfU8xygLZSmrBFuSy4hQFyUPsOK4mM5ZtIOrlQ8QSFmX//dLTu@An1rGk3I4sPmyT3dCe0CyY1WpPqe/vHp7PgzFmfTMXSazcwZmM/oW9Yq0fFfd2NRQ4tnlY9cA22Xv9Q53bnkbhKhQMSVST6hDeYQQPAabO1EypOXB66F6504ffeA5EAl9SyN/GyNLmUKCF2qC2kjjejnKRWHBZdgz543qlUAHZw7hfAVHoHyMR6l5TAPxjt28 "JavaScript (Node.js) – Try It Online") ### Explanation and ungolfed ``` function f(a) { // Main function: return a.map( // Map through all words: function(x) { if (i++ & 1) // If i % 2 == 1 (i.e. vertical): return [,...x].join( // Since the first one needs to have its own linefeed // and indentation, add a dummy item to the start. "\n".padEnd(n) // Join the array with the padded line feeds. ); else { // If i % 2 == 0 (i.e. horizontal): n += x.length; // Add the length of this string to the variable that // counts how long the padded line feeds should be. return x; // Append the string at the end without line feeds. } }, n = i = 0 // Initialize variables. // n: the length of the padded line feeds // (including the line feed) // i: keeps track of the direction ).join("") // Join all stuffs and return. } ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ìZΣFτëWº═φ‼R ``` [Run and debug it](https://staxlang.xyz/#p=8d5ae446e78957a7cded1352&i=programming%0Apuzzles%0Aand%0Acode%0Agolf%0A%0Aa%0Asingle%0Aa&a=1&m=1) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes ``` Ẉm2Ä’x2Ż⁶xⱮṛ;⁷ɗ;ⱮY¥ƭ" ``` [Try it online!](https://tio.run/##y0rNyan8///hro5co8MtjxpmVhgd3f2ocVvFo43rHu6cbf2ocfvJ6dZATuShpcfWKv3//1@poCg/vSgxNzczL11JR6mgtKoqJ7UYyErMSwGSyfkpqUAqPT8nTQkA "Jelly – Try It Online") A full program taking the input as a list of strings and implicitly outputting to stdout the word ladder. [Answer] # [C (gcc)](https://gcc.gnu.org/), 93 87 bytes Thanks to gastropner for the suggestions. This version takes an array of strings terminated by a NULL pointer. ``` c,d;f(s,t)char**s,*t;{for(c=d=0;t=*s++;d=!d)for(;*t;c+=!d)printf("\n%*c"+!d,d*c,*t++);} ``` [Try it online!](https://tio.run/##XVHJTsMwEL3nK1wjpHgpAvXAwYQvqLhxAg7W2E4iOXZku1Rq1V8n2AlL4OJZ3rw3Mx7YtgDTBFwJU0eeCHQyUBo5TeJsfKihUc2tSA2NjAnVbBQpWZFhYCUaQ@@SqfGru6aA2UZxRSGzGSPiMl31DuxBafQQk1La3HSPVZUJaJC9q4sjQwscla6I0hy8E3Su0FciphBf3lAzpxDCnbbWY47w0QersvP0vN/zBZPOp06HgiYdU7GZ3rv2b9kYfBvkMCwAHg@nk9WxuNIVRQxe6WJbb82/DrNmJtq5QK7Qi/iZOS8RVjOjsgP/ddluHdyvg7tvqKguovmdj7Ao09hkcZH/RaDxkGKNMSHI1OU2RFSX6QOMlW2ctsdP "C (gcc) – Try It Online") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 152 bytes ``` <>([()])<>{<>({}<>{()<({}<>)><>}<>)<>{}{<>({}<((()()()()()){})>)({<({}[()]<((((()()()()){}){}){})>)>()}{})<>(({}<>({}))[({}[{}])])<>}{}}<>{}{({}<>)<>}<> ``` [Try it online!](https://tio.run/##TU1bDsMgDOM48UdvgLhI1Q/WB6pGoWLaT1HOngW6SVOi2IoT@1H8noYt@qeIdTQSJlhXlVZWJNhO4KxroCv@ikSEX6EyHKi242bRRPoX71YbAitRh26rAxjbU@WpJ6vKPeSO7akiZ8mh@OPYUzDn@7ri@jI@LWbOy2pCjpsM8wc "Brain-Flak – Try It Online") I suspect this can be shorter by combining the two loops for odd and even words. ]
[Question] [ Given an integer N >= 1, output the mean number of bits in an integer from 0 to N - 1 # Specification * The output can be calculated as the sum of the number of bits in the binary representation of each integer from 0 to N-1, divided by N. * The binary representation of an integer has no leading zeroes in this context, with the exception of zero, which is represented as 0 in binary. * The output should be accurate to at least 7 significant figures. # Example N = 6 ``` 0: 0 : 1 bit 1: 1 : 1 bit 2: 10 : 2 bits 3: 11 : 2 bits 4: 100 : 3 bits 5: 101 : 3 bits ``` Mean number of bits = (1 + 1 + 2 + 2 + 3 + 3) / 6 = 2 # Test cases Input => output ``` 1 => 1 2 => 1 3 => 1.3333333 4 => 1.5 5 => 1.8 6 => 2 7 => 2.1428571 ``` --- # Leaderboard Snippet (from [here](https://codegolf.meta.stackexchange.com/questions/5139/leaderboard-snippet)) ``` var QUESTION_ID=80586,OVERRIDE_USER=20283;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:400px;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> ``` Note that the sum (before dividing to find the mean) is a [sequence on OEIS](http://oeis.org/A083652). [Answer] # Pyth, 6 bytes ``` .Oml.B ``` [Try it online here](http://pyth.herokuapp.com/?code=.Oml.B&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7&debug=0). ``` .Oml.BdUQ Filling in implict vars .O Average of list m UQ Map over [0..input) l Length of .B Binary string representation of int d Lambda var ``` [Answer] # Jelly, 6 bytes ``` R’BFL÷ ``` [Try it online!](http://jelly.tryitonline.net/#code=UuKAmUJGTMO3&input=&args=Nw) ``` R’BFL÷ Main monadic chain. Argument: n R yield [1, 2, ..., n] ’ decrement; yield [0, 1, ..., n-1] B convert to binary; yield [[0], [1], [1,0], [1,1], ...] F flatten list; yield [0, 1, 1, 0, 1, 1, ...] L length of list ÷ divide [by n] ``` [Answer] # Octave, 29 bytes ``` @(n)1+sum(fix(log2(1:n-1)))/n ``` **Explanation** ``` log2(1:n-1) % log2 of numbers in range [1..n-1] % why no 0? because log2(0) = -Inf :/ fix( ) % floor (more or less, for positive numbers) sum( ) % sum... wait, didn't we miss a +1 somewhere? % and what about that missing 0? /n % divide by n for the mean 1+ % and add (1/n) for each of the n bit lengths % (including 0!) ``` Sample run on [ideone](http://ideone.com/3i9BsB). [Answer] # Python 3, 43 bytes ``` def f(n):x=len(bin(n))-2;return(2-2**x)/n+x ``` Makes use of the formula on the [OEIS page](http://oeis.org/A083652). Surprisingly, a named function is somehow cheaper here because of the assignment to `x`. Alternative approach for 46 bytes: ``` lambda n:-~sum(map(int.bit_length,range(n)))/n ``` Unfortunately, the `-~` is necessary since `(0).bit_length()` is `0`, but even then it'd be a byte too long. [Answer] # Julia, 27 bytes ``` n->endof(prod(bin,0:n-1))/n ``` [Try it online!](http://julia.tryitonline.net/#code=Zj1uLT5lbmRvZihwcm9kKGJpbiwwOm4tMSkpL24KCmZvciBuIGluIDE6NwogICAgcHJpbnRsbihuLCAiID0-ICIsIGYobikpCmVuZA&input=) ### How it works Since `*` is string concatenation in Julia, `prod` can be used to concatenate an array of strings. It optionally takes a function as first argument that it maps over the second one before taking the actual "product", so `prod(bin,0:n-1)` is the string of the binary representation of all integers in the desired range. Taking the length with `endof` and dividing by **n** yields the mean. [Answer] ## Julia, 28 bytes ``` n->mean(ceil(log2([2;2:n]))) ``` Since `bin` doesn't automatically map over arrays, we're using `ceil(log2(n))` to get the number of bits in `n-1`. This works out nicely because Julia's `a:b` notation is inclusive on both ends, so `2:n` is a range from 2 to `n`, but we're really calculating the number of bits for numbers in the range `1:n-1`. Unfortunately though, we need to tack on an extra `2` to account for 0. [Try it online!](http://julia.tryitonline.net/#code=Zj1uLT5tZWFuKGNlaWwobG9nMihbMjsyOm5dKSkpCnByaW50bG4oZigxMjM0NTYpKQ&input=) [Answer] # MATL, 9 bytes ``` q:ZlksG/Q ``` [**Try it Online!**](http://matl.tryitonline.net/#code=cTpabGtzRy9R&input=Ng) [Modified version with all test cases](http://matl.tryitonline.net/#code=YGl0cTpabGtzdy9RRFRd&input=MQoyCjMKNAo1CjYKNw) **Explanation** ``` % Implicitly grab input (N) q: % Create array from 1:N-1 Zl % Compute log2 for each element of the array k % Round down to the nearest integer s % Sum all values in the array G % Explicitly grab input again / % Divide by the input Q % Add 1 to account for 0 in [0, ... N - 1] % Implicitly display the result ``` [Answer] # MATL, 9 bytes ``` :qBYszQG/ ``` [Try it online!](http://matl.tryitonline.net/#code=OnFCWXN6UUcv&input=Nw) **Explanation** ``` :qBYszQG/ : % take vector [1..n] q % decrement by 1 to get [0..n-1] B % convert from decimal to binary Ys % cumulative sum (fills in 0's after first 1) z % number of nonzero elements Q % increment by 1 to account for zero G % paste original input (n) / % divide for the mean ``` [Answer] # Jelly, 8 bytes Not shorter, but interesting algorithm, and my first Jelly submission: ``` Rl2Ċ»1S÷ R 1 to n l2 log2 Ċ ceiling »1 max of 1 and... S sum ÷ divided by n ``` [Answer] # Jelly, 10 bytes ``` BL©2*2_÷+® ``` From Sp3000's suggestion. [Try it here.](http://jelly.tryitonline.net/#code=QkzCqTIqMl_DtyvCrg&input=&args=Nw) # Jelly, 11 bytes ``` æḟ2’Ḥ÷_BL$N ``` Not very short but I need some tips. [Try it here.](http://jelly.tryitonline.net/#code=w6bhuJ8y4oCZ4bikw7dfQkwkTg&input=&args=Nw) Using the same formula as in [Sp3000's answer](https://codegolf.stackexchange.com/a/80594/25180). (It's not very hard to get it yourself, by differentiating geometric progression.) [Answer] # Java, ~~135~~ ~~95~~ 90 bytes ``` float a(int n){int i=0,t=0;for(;i<n;)t+=Integer.toString(i++,2).length();return t/(n+0f);} ``` [Answer] # Python 3, 46 Bytes ``` lambda x:sum(len(bin(i))-2for i in range(x))/x ``` Call it like ``` f = lambda x: sum(len(bin(i))-2for i in range(x))/x print(f(6)) # 2.0 ``` *I had to revert the map revision because it failed for input of 5* [Answer] # J, ~~21~~ ~~17~~ 15 bytes From 17 bytes to 15 bytes thanks to @Dennis. ``` +/@:%~#@#:"0@i. ``` Can anyone help me golf this?... ### Ungolfed version ``` range =: i. length =: # binary =: #: sum =: +/ divide =: % itself =: ~ of =: @ ofall =: @: binarylength =: length of binary "0 average =: sum ofall divide itself f =: average binarylength of range ``` [Answer] ## 05AB1E, ~~9~~ 7 bytes **Code:** ``` L<bJg¹/ ``` **Explanation:** ``` L< # range from 0..input-1 b # convert numbers to binary J # join list of binary numbers into a string g # get length of string (number of bits) ¹/ # divide by input ``` [Try it online](http://05ab1e.tryitonline.net/#code=TDxiSmfCuS8&input=Nw) Edit: saved 2 bytes thanks to @Adnan [Answer] ## Clojure, ~~71~~ ~~64~~ 63 bytes It looks like ratios are ok according to [Which number formats are acceptable in output?](http://meta.codegolf.stackexchange.com/questions/9263/which-number-formats-are-acceptable-in-output) `(fn[n](/(inc(apply +(map #(.bitLength(bigint %))(range n))))n))` * n=1 => 1 * n=7 => 15/7 ungolfed (and slightly rewritten for ease of explanation) ``` (fn [n] (-> (->> (range n) ;;Get numbers from 0 to N (map #(.bitLength (bigint %))) ;;Cast numbers to BigInt so bitLength can be used (apply +) ;;Sum the results of the mapping (inc)) ;;Increment by 1 since bitLength of 0 is 0 (/ n))) ;;Divide the sum by N ``` ### old answer that used (float): `(fn[n](float(/(inc(apply +(map #(..(bigint %)bitLength)(range n))))n)))` output is like: * n=1 => 1.0 * n=7 => 2.142857 [Answer] # C#, 87 bytes ``` double f(int n){return Enumerable.Range(0,n).Average(i=>Convert.ToString(i,2).Length);} ``` I wrote a C# answer because I didn't see one. This is my first post to one of these, so please let me know if I'm doing anything wrong. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 5 bytes ``` ʁbfL/ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=r&code=%CA%81bfL%2F&inputs=6&header=&footer=) ``` ʁ # 0...a b # Turn each into base 2 f # Flatten L # Get the length / # Divide by the input ``` [Answer] ## JavaScript (ES7), ~~38~~ 32 bytes ``` n=>(l=-~Math.log2(n))-(2**l-2)/n ``` Using @sp3000's formula (previous version was a recursive solution). ES6 version for 34 bytes: ``` n=>(l=-~Math.log2(n))-((1<<l)-2)/n ``` Explanation of formula: Consider the case of N=55. If we write the binary numbers (vertically to save space), we get: ``` 11111111111111111111111 111111111111111100000000000000001111111 11111111000000001111111100000000111111110000000 111100001111000011110000111100001111000011110000111 11001100110011001100110011001100110011001100110011001 0101010101010101010101010101010101010101010101010101010 ``` The size of this rectangle is *nl* so the average is just *l* but we need to exclude the blanks. Each row of blanks is twice as long as the previous so the total is 2 + 4 + 8 + 16 + 32 = 64 - 2 = 2l - 2. [Answer] # [Perl 6](http://perl6.org), ~~34~~ 32 bytes ``` {$_ R/[+] map *.base(2).chars,^$_} ``` ``` {$_ R/[+] map {(.msb||0)+1},^$_} ``` ### Explanation: ``` { $_ # the input R/ # divides ( 「$a R/ $b」 is the same as 「$b / $a」 ) [+] # the sum of: map { ( .msb # the most significant digit (0 based) || 0 # which returns Nil for 「0.msb」 so use 0 instead # should be 「(.msb//0)」 but the highlighting gets it wrong # it still works because it has the same end result ) + 1 # make it 1 based }, ^$_ # 「0 ..^ $_」 all the numbers up to the input, excluding the input } ``` ### Test: ``` use v6.c; # give it a name my &mean-bits = {$_ R/[+] map {(.msb||0)+1},^$_} for 1..7 { say .&mean-bits } say ''; say mean-bits(7).perl; say mean-bits(7).base-repeating(10); ``` ``` 1 1 1.333333 1.5 1.8 2 2.142857 <15/7> (2. 142857) ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 14 bytes ``` (+/1⌈(⌈2⍟⍳))÷⊢ range ← ⍳ log ← ⍟ log2 ← 2 log range ceil ← ⌈ bits ← ceil log2 max ← ⌈ fix0 ← 1 max bits sum ← +/ total ← sum fix0 self ← ⊢ div ← ÷ mean ← sum div self ``` [Answer] ## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), 23 bytes ``` n$z1z[i1+2l$M$Y+]kz$:N. ``` [Try it here!](http://play.starmaninnovations.com/minkolang/?code=n%24z1z%5Bi1%2B2l%24M%24Y%2B%5Dz%24%3AN%2E&input=6) ### Explanation ``` n$z Take number from input and store it in register (n) 1 Push 1 onto the stack z[ For loop that repeats n times i1+ Loop counter + 1 2l$M log_2 $Y Ceiling + Add top two elements of stack ] Close for loop z$: Float divide by n N. Output as number and stop. ``` Pretty straightfoward implementation. [Answer] # JavaScript ES5, 55 bytes ``` n=>eval(`for(o=0,p=n;n--;o+=n.toString(2).length/p);o`) ``` ## Explanation ``` n => // anonymous function w/ arg `n` for( // loop o=0, // initalize bit counter to zero p=n // copy the input ;n-- // will decrease input every iteration, will decrease until it's zero ;o+= // add to the bitcounter n.toString(2) // the binary representation of the current itearations's .length // length /p // divided by input copy (to avergage) );o // return o variable ``` [Answer] ## [Hoon](https://github.com/urbit/urbit), 71 bytes ``` |= r/@ (^div (sun (roll (turn (gulf 0 (dec r)) xeb) add)) (sun r)):.^rq ``` ...I'm pretty sure this is actually the first time I've used Hoon's floating point cores. It's actually an implementation written in Hoon that jets out to SoftFloat, since the only data types in Hoon are atoms and cells. Create a function that takes an atom, `r`. Create a list from [0..(r - 1)], map over the list taking the binary logarithm of the number, then fold over that list with `++add`. Convert both the output of the fold and `r` to `@rq` (quad-precision floating point numbers) with `++sun:rq`, and then divide one by the other. The oddest thing in this snippet is the `:.^rq` at the end. `a:b` in Hoon means "evaluate a in the context of b". `++rq` is the core that contains the entire quad-precision implementation, like a library. So running `(sun 5):rq` is the same thing as doing `(sun:rq 5)`. Luckily, cores in Hoon are like nesting dolls; when you evaluate the arm `++rq` to get the core, it adds the entire stdlib to it as well, so you get to keep roll and turn and gulf and all that fun stuff instead of being stuck with *only* the arms defined in `++rq`. Unluckily, rq redefines `++add` to be floating-point add instead, along with not having `r` in its context. `.` (the entire current context) does, however. When evaluating an expression in a context, the compiler looks for the limb depth-first. In our case of `a:[. rq]` it would look in the entire current context for `a` before moving on to looking in `rq`. So `add` will look up the function that works on atoms instead of floating-point numbers...but so will `div`. Hoon also has a feature where using `^name` will ignore the first found reference, and look for the second. From there, it's simply using the syntatic sugar of `a^b` being equal to `[a b]` to evaluate our snippet with both our current context and the quad-precision float library, ignoring the atomic div in favor of `++div:rq`. ``` > %. 7 |= r/@ (^div (sun (roll (turn (gulf 0 (dec r)) xeb) add)) (sun r)):.^rq .~~~2.1428571428571428571428571428571428 ``` [Answer] ## Actually, 7 bytes: ``` ;r♂├Σl/ ``` [Try it online!](http://actually.tryitonline.net/#code=O3LimYLilJzOo2wv&input=NQ) Explanation: ``` ;r♂├Σl/ ; duplicate input r push range(0, n) ([0, n-1]) ♂├ map binary representation Σ sum (concatenate strings) l/ divide length of string (total # of bits) by n ``` If it weren't for a bug that I just discovered, this solution would work for 6 bytes: ``` r♂├♂læ ``` `æ` is the builtin mean command. [Answer] # Vitsy, 26 bytes This is a first attempt, I'll golf this down more and add an explanation later. ``` 0vVV1HV1-\[2L_1+v+v]v1+V/N ``` [Try it online!](http://vitsy.tryitonline.net/#code=MHZWVjFIVjEtXFsyTF8xK3Yrdl12MStWL04&input=&args=Nw) [Answer] ## PowerShell v2+, 64 bytes ``` param($n)0..($n-1)|%{$o+=[convert]::ToString($_,2).Length};$o/$n ``` Very straightforward implementation of the spec. Loops from `0` to `$n-1` with `|%{...}`. Each iteration, we `[convert]` our input number `$_` to a string base`2` and take its `length`. We accumulate that in `$o`. After the loops, we simply divide `$o/$n`, leaving that on the pipeline, and output is implicit. As long as this is, it's actually shorter than the formula that Sp & others are using, since `[math]::Ceiling()` and `[math]::Log()` are ridiculously wordy. Base conversion in PowerShell is yucky. [Answer] ## Perl 5.10, 54 bytes ``` for(1..<>){$u+=length sprintf"%b",$_;$n++}$u/=$n;say$u ``` Pretty much straightforward. `sprintf"%b"` is a neat way to output a number in binary in Perl without using additional libraries. [Try it online!](https://ideone.com/P8XRsE) [Answer] # CJam, ~~13~~ ~~12~~ 11 bytes *One byte saved thanks to @Sp3000, and another thanks to @jimmy23013* ``` rd_,2fbs,\/ ``` [**Try it online!**](http://cjam.tryitonline.net/#code=cmRfLDJmYnMsXC8&input=Nw) ### Explanation Straightforward. Applies the definition. ``` rd e# read input and convert to double _ e# duplicate , e# range from 0 to input minus 1 2fb e# convert each element of the array to binary s e# convert to string. This flattens the array , e# length of array \ e# swap / e# divide ``` [Answer] # Jolf, 10 bytes ``` /uΜr0xdlBH ``` [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=L3XOnHIweGRsQkg&input=NQ) ## Explanation ``` /uΜr0xdlBH Μr0x map range 0..x dlBH over lengths of binary elements /u divide sum of this by implicit input (x) ``` [Answer] # Swift, 72 bytes ``` func f(n:Double)->Double{return n<1 ?1:f(n-1)+1+floor(log2(n))} f(N-1)/N ``` ]
[Question] [ In any programming language that existed before this question was asked, write a program (not a function) that outputs the characters `Hello world!` followed by a newline. Your program: * should not use any character more than once (including whitespace) * should only use ASCII characters * should not use any built-in libraries * should not get input (user, file, filename, system variable, internet, anything) * should not output anything else Winner is whoever has the most votes after 14 days and abides to the six rules. The sixth rule is that you cannot use H9+, HQ9+, HQ9+B, HQ9++, HQ9+2D, Hello, Hello+, Hello++, Hexish, CHIQRSX9+, or Fugue. Also, all answers which require implementations that are newer than this challenge must be marked as non-competing. --- **Disclaimer:** This question was posted with the assumption that [Hello world! with limited repetition](https://codegolf.stackexchange.com/questions/18721/hello-world-with-limited-repetition) did not cause any damage to your computer or your brain in the process of coming up with the answers. [Answer] # Raku (~~29~~ 28 characters) This was somewhat annoying, but I finally managed to make a program for this task. Thanks go to the [great #perl6 community](https://web.archive.org/web/20140128181911/http://irclog.perlgeek.de/perl6/2014-01-20#i_8146203), for helping me with this task. It took me two hours, hope you enjoy. The output is completely up to specification, including a newline. ``` say Q[@A`DO world!]~|<HeLhg> ``` There are four tokens of interest. * `say` This outputs the argument with new line at end. The new line after the command itself is needed as a space replacement. * `Q[@A`DO world!]` This is the first string. `Q[]` is for raw strings (like `r""` in Python). It can take any delimiter (or pair of them), in this case `[]`. In this case, I use this for quotes, I don't need raw string behavior. * `~|` This is stringwise (`~`) bitwise or (`|`) operator. * `<HeLhg>` `<>` is list literal, which takes space separated list of elements. In this case, it has one element, and used as a scalar, it gives a string. [Answer] # Perl 5.10+: 24 chars ``` say+He,YZX^q(567 world!) ``` OK, I think this is as short as it gets in Perl. Run with `perl -M5.010` (or just `perl -E`) to enable the Perl 5.10+ `say` feature. [Answer] # [Perl 5](https://www.perl.org/) with `-M5.010`, 29 bytes ``` say+He.v108 x2,q(O world!)^$" ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVLbI1WvzNDAgqvCSKdQw1@hPL8oJ0VRM05F6f//f/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online") I've gained a lot of knowledge since I first attempted this. Still not as short as the other answers, but the best I can come up with! [Answer] # Vim 7.3, 18 keystrokes ``` :h-cu 9j3wy$<C-^>P<End>r!o ``` Copies the string `Hello world` from [this helpfile](http://vimdoc.sourceforge.net/htmldoc/if_tcl.html), which unfortunately has been removed in never versions of Vim. [Answer] # Golfscript 42 33 I might as well golf this, considering that I had to fit some of the code and all of the data in the same block with no way of delimiting the two I think this is a pretty short result. Unlike my first submission the block code is now a fully integrated part of the data, thus `{1` do not only begin the block and put a `1` on the stack, it is also the data that defines the `H`, and so forth. The array creation now includes the empty input string, which means that I don't have to crop the beginning as there is only one character between the empty string and the `H`, that character is cut away when I take every second character, and the empty string eventually is output as nothing. ``` {1wZ$Qei^Ak 3h-)ulmsogr7}.`*]2%n+ ``` Online demo: <http://golfscript.apphb.com/?c=ezF3WiRRZWleQWsgM2gtKXVsbXNvZ3I3fS5gKl0yJW4r> ``` [{1$^(r iFNGDJUHv98oIMgtplbh4m}.`\*]6>2%n+ ``` Defines a code block. Makes a copy of the code block and converts it to string. Uses the code block to iterate over the string. For each iteration the code will make a copy of the previous char value, xor it with the current char value, and subtract 1. The resulting string then has the first 6 characters removed, and every second character removed. Finally a line feed is appended. "r iFNGDJUHv98oIMgtplbh4m" is just two undeclared variables, they do nothing, but they are carefully constructed to produce the desired result. Online demo: <http://golfscript.apphb.com/?c=W3sxJF4ociBpRk5HREpVSHY5OG9JTWd0cGxiaDRtfS5gXCpdNj4yJW4r> [Answer] # [Befunge-98](https://github.com/catseye/FBBI), ~~34~~ 31 bytes ``` f"v!dlrow +c<>a,kb@#*98e':g05-3 ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/P02pTDElpyi/nEs72cYuUSc7yUFZy9IiVd0q3cBU1/j/fwA) Uses quite a few different methods to avoid duplicated characters. First, we use wrapping string literal to avoid using two `"`s. This adds " world!" to the stack. Going left on the second line, we add 9 to the extra `f` to make the `o` of the "Hello". We `g`et the character from cell 5,0 (`l`) and then duplicate it. The `'` is used to fetch the letter `e`. Multiply 9 by 8 to get 72, the ASCII value of `H`. We then print it everything using `ck,`, and flip the direction with the `>` to reuse the `,` to print the newline (`a`). [Answer] # [Elixir](https://elixir-lang.org/), 37 bytes ``` IO.puts~c(He#{[?n-2,108]}\x6f world!) ``` [Try it online!](https://tio.run/##S83JrMgs@v/f01@voLSkuC5ZwyNVuTraPk/XSMfQwCK2NqbCLE2hPL8oJ0VR8/9/AA "Elixir – Try It Online") I can't guarantee that this would have worked back in 2014 when this challenge was posted, and Elixir was still pre-1.0 (and thus, whether it is formally "competing", but looking at their release notes, I think it should be OK). Anyway, I'm happy that I finally found a valid solution to this task using a conventional general purpose language other than Perl! ### Walkthrough ``` IO.puts #Print with trailing newline ~c(...) #Sigil: charlist with interpolation He #Start of literal string... #{...} #Interpolated block [?n-2,108] #A list of codepoints for 2 'l's \x6f #Hex code for 'o' world! #...and done! ``` [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 17 bytes ``` Hel:o Wn1+rp4-d\! ``` [Try it online!](https://tio.run/##y05N///fIzXHKl8hPM9Qu6jARDclRvH/fwA "Keg – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` kh\!+, ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJraFxcISssIiwiIiwiIl0=) Basically the normal way of printing "Hello World!" in Vyxal. [Answer] # [Vim](https://www.vim.org), 21 keystrokes ``` 2iHelo WORLD!Escgu8h10X ``` [Try it online!](https://tio.run/##K/v/3yjTIzUnXyHcP8jHRVE6vdQiw9Ag4v9/AA "V (vim) – Try It Online") Vim adds a newline at the end of the file so there's no need to add it explicitly. ### To run it locally: 1. Save the code to a file *(here hello\_world.vim)* replacing `Esc` with `` (`\x1b`). 2. run `vim -u NONE -s hello_world.vim hello_world.txt`. 3. [exit Vim](https://stackoverflow.com/questions/11828270/how-do-i-exit-vim). [Answer] # [Uiua](https://uiua.org), 30 bytes ``` &p+mod107\*-,:@$ H`eFMbv/5la ``` [Try it online!](https://www.uiua.org/pad?src=JnAr4pe_MTA3XMOXLSziiLZAFSQgSGBlFkZNYnYvNWxhCg==) (Note that the formatter automatically converts some ASCII tokens to Unicode equivalents, but you can verify the solution by copy-pasting the code above and running it manually.) [Verify the restrictions!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3U4tti9TVCrRz81MMDcxjtHR1rBxEVRQ8ElLF3HyTyvRNcxLVuQqKMvNKNHJS8zSKNRVsbRXArNQSIE9TEyqZmJOjkV-UopGsqWBjq2BoZK6Qll-kkKyQmacAVAWxDGonzG4A) Contains two ASCII control characters; I'm assuming this is valid based on the existing Vim answers. This code solves the duplicate character problem by finding an integer `p` and a list of integers `L` such that the cumulative product of `L` modulo `p` gives the desired string. Also, a character literal is used twice because both "convert string to a list of charcodes" and "convert a list of charcodes to string" require a character literal, and it is chosen so that the resulting `p` and `L` meet the no-duplicates requirement. `$ <string>` is a multiline string literal that continues through lines that start with `$` and ends at a newline after that. ``` &p+mod107\*-,:@$ H`eFMbv/5la $ H`eFMbv/5la push a string literal, S @ push a character literal, c ,: swap and over; c S c - S-c; convert S to charcodes and subtract c's charcode \* cumulative product mod107 % 107 + add c; add c's charcode and convert to string &p print with newline ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 8 bytes ``` `dx/&\p4 ``` [Try it online!](https://staxlang.xyz/#c=%60dx%2F%26%5Cp4&i=&a=1) Just a compressed string literal. Luckily Stax lets me go without the closing backtick. [Answer] An answer from <https://codegolf.stackexchange.com/a/55425/118820>: > > **Stuck, 0 bytes** > > > Well, can't get shorter than that... An empty program > will output `Hello, World!` in [Stuck](http://esolangs.org/wiki/Stuck). > > > Even Stuck comes with 3 plugins, but we don't need they. [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 25 bytes ``` "v!dlrow H>{7-5k:`e01ga} ``` [Try it online!](https://tio.run/##S8/PScsszvj/X6lMMSWnKL9cgcvDrtpc1zTbKiHVwDA9sfb/fwA "Gol><> – Try It Online") ``` "v!dlrow push "v!dlrow " where v is the bottom of the stack >{ bring v to the top 7- subtract 7 from v to get o 5k: fetch 5th number down the stack which is l, and duplicate it `e push e 01g fetch H from the code area a} put 10 (newline) at the bottom of the stack H print the whole stack as chars from top to bottom and halt ``` # [Gol><>](https://github.com/Sp3000/Golfish), 30 bytes ``` "\>mX.R Mkp r<;|%q`*o+a:Fd~ ``` [Try it online!](https://tio.run/##S8/PScsszvj/XynGLjeCUU8wiFnWN7uAq8jGuka1MEErXzvRyi2l7v9/AA "Gol><> – Try It Online") Same strategy as [my own Uiua answer](https://codegolf.stackexchange.com/a/266319/78410) applied to Gol><>. Uses printing offset of 10 (`a+o`) so that the newline can be printed without an explicit stack item. ``` "\... push a backslash and the string, and then reflect down r< ~ reverse stack and discard the backslash |...Fd repeat the loop 13 times: o+a: print the current number plus 10 as char %q`* multiply modulo 113 ; halt ``` ]
[Question] [ Given a positive integer (0 and above, no maximum), convert it into a grade following these rules: ``` A = 100+ B = 90 - 99 C = 80 - 89 D = 70 - 79 E = 60 - 69 F = 59 and less. ``` This felt a little boring, so make the grade a `+` if it's 7,8 or 9 and a `-` if it's 0,1 or 2. Ignore this for the F and A cases. An example: **Input:** ``` 65 ``` **Output:** ``` E ``` Test cases: ``` 0 -> F 20 -> F 65 -> E 72 -> D- 75 -> D 80 -> C- 99 -> B+ 102 -> A 864 -> A ``` No trailing spaces. One newline after output is fine, but keep it consistent. Functions and full programs are both fine. This is code golf, so shortest code wins. This was inspired by an Ask Ubuntu question, [How to write a shell script to assign letter grades to numeric ranges?](https://askubuntu.com/questions/621466/how-to-write-a-shell-script-to-assign-letter-grades-to-numeric-ranges). The answers are in bash and python, so slightly spoilers. --- **Leaderboard:** 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 ``` ``` var QUESTION_ID=49876;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 getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/; ``` ``` 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, ~~72~~ ~~70~~ 62 bytes ``` lambda n:"FA"[n>59:1+n/100]or chr(75-n/10)+"+-"[(n+3)%10/3::2] ``` This is an anonymous function that takes an int and returns the grade as a string. (thanks to @MartinBüttner, @grc and @TheNumberOne for tips) [Answer] # CJam, ~~34 33~~ 32 bytes ``` riAmd)4/"- +"=S-\Ae<5e>_~'L+o5%< ``` Okay, I've tried multiple approaches now and am unable to get this below 33, so here goes the explanation: ``` ri e# Read the input and convert to integer Amd e# Take divmod of the input with 10. This leaves the e# number/10 and number%10 on stack )4/ e# Increment the mod by 1 and integer divide by 4. "- +"=S- e# This converts 0,1,2 to 0 and 7,8,9 to 2. Pick - or + e# respectively and remove space in case of 3,4,5 and 6 \Ae<5e> e# To the divisor by 10 scope it to range of [5,10] _~ e# Take a copy and do number * -1 - 1 'L+ e# Add it to char L. This gets us the required grade o e# Output the grade. This removes it from stack 5% e# We now have scoped divisor on stack. Do mod with 5 < e# Both 5 and 10 will return 0, in which case, we don't e# want the + or -. So we do a substr(0, 0). e# 5 represents F and 10, A. For others, it will do e# substr(0,X) where X > 0. Since the string is only e# 1 char long, it doesn't affect at all. ``` *UPDATE*: 1 byte saved thanks to a pointer by Dennis [Try it online here](http://cjam.aditsu.net/#code=riAmd)4%2F%22-%20%2B%22%3DS-%5CAe%3C5e%3E_~'L%2Bo5%25%3C&input=92) [Answer] # Retina, 43 + 15 = 58 bytes ``` ...+ A .[012] $&- .[789] $&+ ^9. B ^8. C ^7. D 6. E \d.* F ``` [**Retina**](https://github.com/mbuettner/retina) is a regex language created by Martin Büttner, where the odd-numbered files are the regex to match with, and the even-numbered files are what to replace it with. Each line is a separate file, so I've added 15 bytes for each additional file. ## Explanation It starts by making anything with 3 or more digits an A. It adds a `-` if it is two-digit number ending with 0, 1, or 2, and `+` if it ends with 7, 8, or 9. The numbers are then mapped to their grade (e.g. a number starting with 9 is given a B). Any number left over is automatically an F. Unfortunately, `;`` must be prepended to all but to the last regex to suppress intermediate output. Update: version 0.5.0 has intermediate output off by default, allowing me to save a few bytes. [Answer] ## C, 99 bytes I'm new here, I hope I'm following the rules. ``` char b[3];char*f(n){b[1]=0;n<60?*b=70:n>99?*b=65:(*b=75-n/10,b[1]=n%10<3?45:n%10>6?43:0);return b;} ``` This function takes the mark as a parameter and returns the grade as a NULL-terminated string. ## Explanation Added whitespace: ``` char b[3]; char *f(n) { b[1] = 0; n<60 ? *b = 70 : n>99 ? *b = 65 : ( *b = 75 - n / 10, b[1] = n % 10 < 3 ? 45 : n % 10 > 6 ? 43 : 0 ); return b; } ``` Global variables are automatically initialized to zero, so b is filled with NULLs. Since only the first two characters are ever touched, we only have to worry about putting a NULL in b[1] if the grade has only one character. This NULL is inserted at the very beginning of the function. The n parameter is implicitly int. If the grade is less than 60, then it's set to 'F', if it's bigger than 99 it's set to 'A'. In the other cases, the base grade is given by `'E' - (n - 60) / 10`, which simplifies to `75 - n / 10`. `n % 10` gets the units digit of the mark. If it's less than 3 then a - is appended, if it's bigger than 6 a + is appended, otherwise b[1] is nulled (which it already was). ## Test cases ``` #include <stdio.h> char b[3];char*f(n){b[1]=0;n<60?*b=70:n>99?*b=65:(*b=75-n/10,b[1]=n%10<3?45:n%10>6?43:0);return b;} int main() { printf(" 0 -> %s\n", f(0)); printf(" 20 -> %s\n", f(20)); printf(" 65 -> %s\n", f(65)); printf(" 72 -> %s\n", f(72)); printf(" 75 -> %s\n", f(75)); printf(" 80 -> %s\n", f(80)); printf(" 99 -> %s\n", f(99)); printf("102 -> %s\n", f(102)); printf("864 -> %s\n", f(864)); return 0; } Output: 0 -> F 20 -> F 65 -> E 72 -> D- 75 -> D 80 -> C- 99 -> B+ 102 -> A 864 -> A ``` [Answer] # Pyth, 33 bytes ``` +C-75K@S[/QTT5)1<-@"- +"/heQ4d%K5 ``` Try it online: [Demonstration](https://pyth.herokuapp.com/?code=%2BC-75K%40S%5B%2FQTT5)1%3C-%40%22-+%2B%22%2FheQ4d%25K5&input=80&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=FQ.Q%2B%2B%60Q%22+-%3E+%22%2BC-75K%40S%5B%2FQTT5)1%3C-%40%22-+%2B%22%2FheQ4d%25K5&input=%22Test+Cases%3A%22%0A0%0A20%0A65%0A72%0A75%0A80%0A99%0A102%0A864&debug=0) ### Explanation: ``` implicit: Q = input [/QTT5) create the list [Q/10, 10, 5] S sort @ 1 take the element in the middle K store in K (this results in a number between 5 and 10) -75K 75 - K C char with ASCII-value ... @"- +"/heQ4 "- +"[(Q%10 + 1) / 4] - d remove spaces < %K5 slice [:K%5] + add these two chars and print ``` [Answer] # ><> (Fish), ~~78~~ 71 bytes ``` iii0)?/:0({:'6'(@@+?/'{'01. ;$-o:'4'(?\'7'(?;'+'o ;o'A'\ \'-'o;o'F'\ ``` Method: * We read the codepoints of first 3 characters `x,y,z` from the input. If a character is not present the value of its variable's will be `-1` implicitly. (`ord(c)` will mark the codepoint of the character `c`) * If `z > 0` (3 digit input) print `A` and exit. * If `x < ord('6') or y < 0` (input < 60) print `F` and exit. * Print the character with codepoint `123 - x`. * If `y < ord('4') print`-` and exit. * If `y > ord('6') print`+` and exit. * Exit. [Answer] # C, 67 65 Surprisingly, this is quite close to the python solution. ``` f(i){printf(i<60?"F":i>99?"A":"%c%s",75-i/10,"-\0+"+(i%10+1)/4);} ``` But in order for this program, to come to such great shortness, sacrifices had to be made: * If an `F` or an `A` is printed `printf` doesn't even look at the other arguments passed. This is a quite nasty hack. * If `(i%10+1)/4` evaluates to `1` (no `+` or `-` should be appended to the grade), the `%s` formatter receives a pointer to a `\0` byte, so nothing is printed. Also quite funny, because I didn't know that you could take the address of an indexed string literal. (e.g. `&"string"[i]`) (**edit**: `"string"+i` is even *shorter*! Thanks @nutki) Here the output of the program for the numbers 57 to 102. I made it a hexdump, so we can be sure no weird `\0` bytes have been printed. ``` % seq 44 115 | xargs -n1 ./grade | xxd 0000000: 4646 4646 4646 4646 4646 4646 4646 4646 FFFFFFFFFFFFFFFF 0000010: 452d 452d 452d 4545 4545 452b 452b 452b E-E-E-EEEEE+E+E+ 0000020: 442d 442d 442d 4444 4444 442b 442b 442b D-D-D-DDDDD+D+D+ 0000030: 432d 432d 432d 4343 4343 432b 432b 432b C-C-C-CCCCC+C+C+ 0000040: 422d 422d 422d 4242 4242 422b 422b 422b B-B-B-BBBBB+B+B+ 0000050: 4141 4141 4141 4141 4141 4141 4141 4141 AAAAAAAAAAAAAAAA ``` The `main` method used: ``` main(c,v)char**v;{f(atoi(v[1]));} ``` [Answer] # CJam, ~~41~~ ~~39~~ ~~37~~ 34 bytes This is way too long, but I don't think I'll be golfing it further for now. ``` qiAmd'K@Ae<5e>:X-X5%g@)4/"- +"=*S- ``` [Test it here.](http://cjam.aditsu.net/#code=qiAmd'K%40Ae%3C5e%3E%3AX-X5%25g%40)4%2F%22-%20%2B%22%3D*S-&input=72) Or [run all test cases here.](http://cjam.aditsu.net/#code=qN%2F%7BS%2F0%3D%0A%0AiAmd'K%40Ae%3C5e%3E%3AX-X5%25g%40)4%2F%22-%20%2B%22%3D*S-%0A%0A%5DoNo%7D%2F&input=0%20%20-%3E%20F%0A20%20-%3E%20F%0A65%20-%3E%20E%0A72%20-%3E%20D-%0A75%20-%3E%20D%0A80%20-%3E%20C-%0A99%20-%3E%20B%2B%0A102%20-%3E%20A%0A864%20-%3E%20A) Three bytes saved by Optimizer. ## Explanation *(Slightly outdated)* ``` qi e# Read input and convert to integer. 'K1$ e# Push the character K, then copy the input. A/ e# Divide by 10. Ae<5e> e# Clamp the result to the range 5..10."; - e# Subtract from K to get the grade. _'Am e# Duplicate get difference to A. 5%g e# Check that its neither 0 (A) nor 5 (F). @ e# Pull up the other copy of the input. A%)4/ e# ((i % 10) + 1) / 4 "- +"= e# Use that to select -, space, or +. * e# Multiply it with the earlier boolean so that e# it vanishes for A and F. S- e# Remove the space if there is one. ``` [Answer] # GNU sed, 73 + 1 = 74 bytes The + 1 is for the -r parameter. ``` s/^[1-5]?.$/F/ s/.{3,}/A/ s/[7-9]$/+/ s/[3-6]$// s/[0-2]$/-/ y/9876/BCDE/ ``` [Answer] # Python 2, ~~94~~ ~~88~~ ~~84~~ 69 bytes ``` lambda g:g>99and'A'or[chr(75-g/10)+'-+'[g%10>2:1-(g%10>6)],'F'][g<60] ``` [Answer] # JavaScript (ES6), 66 bytes Straight. ``` F=n=>n<60?'F':n>99?'A':'EDCB'[n/10-6|0]+(n%10>6?'+':n%10<3?'-':'') // TEST (in Firefox) for(i=0;i<111;i++)document.write(i+'='+F(i)+' ') ``` [Answer] # R, ~~107~~ ~~105~~ 99 bytes Not a very good effort I'm afraid, but I will try and golf it more later. ``` cat(LETTERS[11-(r=min(max(scan(),59),100))%/%10],if(r>59&r<100)c('-','','+')[(r%%10+1)/4+1],sep='') ``` **Edit** Dropped a couple of `if`s. Fixed the case and an incorrect result for 100. ~~Now to get rid of the `ifelse`s~~. Got rid of `ifelse`s. [Answer] # Perl, 66 62 bytes This can probably be golfed more. Also a different way might be better. ``` $_=$_>99?A:$_<60?F:s/\d$/$&>6?"+":$&<3?"-":""/re;y/9876/BCDE/ ``` +1 for `-p` Run with: ``` echo 72 | perl -pE'$_=$_>99?A:$_<60?F:s/\d$/$&>6?"+":$&<3?"-":""/re;y/9876/BCDE/' ``` [Answer] # Javascript (ES6), ~~78~~ 79 bytes This really isn't the smartest option, but I did what I could. ``` F=n=>'FEDCBA'[n[2]?5:n<60?0:n[0]-5]+(n[2]||n<60?'':'-+\n'[n[1]<3?0:n[1]>6?1:2]) ``` Simply pass the grade **as a string**, and it will return it's grade letter. The string part in **very** important. You can check a testcase here: ``` console._RELAY_TO_DOC=true; //non-es6 version: function F(n){return 'FEDCBA'[n[2]?5:n<60?0:n[0]-5]+(n[2]||n<60?'':'-+\n'[n[1]<3?0:n[1]>6?1:2])} var testcases=[0,20,65,72,75,77,80,90,99,100,102,180,1000], results={}; for(var i in testcases) { results[testcases[i]]=F(testcases[i]+''); } console.log(results); ``` ``` <script src="http://ismael-miguel.github.io/console-log-to-document/files/console.log.min.js"></script> ``` ~~If the aditional space after the letter isn't allowed, I will happily remove it.~~ **It wasn't!** This increased my code by 1 byte, but nothing (too) serious. [Answer] # C#, ~~143~~ ~~127~~ ~~112~~ 88 bytes ``` string g(int n){return n>=100?"A":n<=59?"F":(char)(75-n/10)+(n%10>6?"+":n%10<3?"-":"");} ``` I tried to be clever by doing ASCII number mods, but it seems I wasn't alone! Thanks to Tim for advice on lists instead of ifs. Thanks to DarcyThomas for pointing out I could use nested ternary operators. [Answer] # Haskell, 78 bytes The first line feels wasteful, costing 14 bytes, but I couldn't find a shorter version without it. ``` (#)=replicate a="A":a f=(!!)$60#"F"++[g:s|g<-"EDCB",s<-3#"-"++4#""++3#"+"]++a ``` ## Explanation The operator `#` is a shorthand for creating n copies of its second argument. List `a` is an infinite list of Strings "A". Function `f` indexes into a list of all grades for n=0,1,... The list comprehension builds the "middle part" of this list (grades E to B); `g` is a single Char that is prepended to the String `s` (which may be empty). ## Usage ``` ghci> map f [0,20,65,72,75,80,99,102,864] ["F","F","E","D-","D","C-","B+","A","A"] ``` [Answer] ## C, 102 bytes ``` int f(int h){int b,c;printf("%c%c",b?65:!c?70:75-h/10,!(b=h>99)*(c=h>59)*(((h%10<3)*45+(h%10>6)*43))); ``` } ## Usage ``` #include <stdio.h> int f(int ); int main(){ int c; scanf("%d",&c); f(c); } ``` [Answer] # dc, 52 ``` [Anq]sa[Fnq]sf[q]sn16o?A~rd9<ad6>f20r-n1+4/d1=n45r-P ``` ### Output ``` $ for i in {0,20,65,72,75,80,99,102,864}; do printf "{%s -> %s} " $i $(dc -e '[Anq]sa[Fnq]sf[q]sn16o?A~rd9<ad6>f20r-n1+4/d1=n45r-P' <<< $i); done {0 -> F} {20 -> F} {65 -> E} {72 -> D-} {75 -> D} {80 -> C-} {99 -> B+} {102 -> A} {864 -> A} $ $ ``` [Answer] # TI-Basic, 79 74 76 Bytes ``` Input N If N>99 105->N sub("FFFFFFEDCBA",1+int(N.1),1 If Ans!="F Ans+sub("--- +++",1+fPart(N.1),1 Ans ``` [Answer] # TI-BASIC, ~~69~~ ~~68~~ 66 bytes ``` .1Ans sub("F?E-E+D-D+C-C+B-B+A",1+2max(0,min(9,int(2Ans)-11)),int(e^(Ans<10 and Ans≥6 and iPart(2.2-5fPart(Ans ``` TI-BASIC is not good for string manipulation. Input on the calculator homescreen, in the form of [number]:[program name]. Formatted: ``` .1Ans sub( //Syntax for the substring command is sub(string, index, length) "F?E-E+D-D+C-C+B-B+A" //String that encodes possible grades ,1+2max(0,min(9, )) //Starts at "F" if input <60, "A" if >=100 int(2Ans)-11 //(Input-55)/5, so starts at "E" from 60 to 64, //second E from 65-69, D from 70 to 74, &c. ,int(e^( //length 1 if false, 2 (includes +/-) if true Ans<10 and Ans≥6 and //grade between 60 and 100 iPart( //1 if abs. val. of below >= 0.2 2.2-5fPart(Ans //2.2-.5(last digit) ``` This can probably be golfed further. [Answer] # C#, 82 bytes ``` Func<int,string>g=s=>s>99?"A":s<60?"F":(char)(75-s/10)+(s%10<3?"-":s%10>6?"+":""); ``` Here's a [fiddle](https://dotnetfiddle.net/5lFuU5) with some test-cases. [Answer] # JavaScript (ES6), ~~86~~ 83 bytes What's really eating up characters is the `String.fromCharCode` and the +/- condition... I strongly suspect there's a clever way to shorten at least one of them. ``` f=n=>n>99?'A':n<60?'F':String.fromCharCode(75.9-n/10|0)+(n%10<3?'-':n%10>6?'+':''); ``` [Answer] # PHP5.5, 73 bytes Once again, not the shortest one. But it works! ``` <?=($n=$_GET[n])<59?F:($n>99?A:'BCDE'[$n[0]-6].'+-'[$n[1]<3?1:2*$n[1]<5]) ``` I've classified it under PHP5.5 instead of just PHP since this uses syntax that is only valid for PHP5.5 and PHP5.6. You can read about string and array dereferencing in the manual: <http://php.net/manual/en/migration55.new-features.php> [Answer] # Perl, 52 ``` #!perl -p $_=$_>99?A:$_<60?F:"$_"^"s";y/JK7890-6/BC+++\-\--/d ``` [Answer] # Ruby, 58 Bytes Couldn't believe that there are no Ruby ones here. On reflection it's fairly similar to some that are here already but anyway: ``` ->x{x<60?'F':x>99?'A':(75-x/10).chr+'+-'[(x+3)%10/3].to_s} ``` [Try it here](http://rubyfiddle.com/riddles/0c011) [Answer] # Excel, 100 bytes ``` =IF(A1<60,"F",IF(A1>99,"A",MID("EDCB",INT(A1/10)-5,1)&IF(MOD(A1,10)<3,"-",IF(MOD(A1,10)>6,"+","")))) ``` ]
[Question] [ Assume we have a string, and we want to find the maximum repeated sequence of every letter. For example, given the sample input: ``` "acbaabbbaaaaacc" ``` Output for the sample input can be: ``` a=5 c=2 b=3 ``` Rules: * Your code can be function or a program - for you to choose * Input can be by stdin, file or function parameter * The output should contain only characters that appear in the input * Input max length is 1024 * The output order does not matter, but it has to be printed in the form [char]=[maximum repeated sequence][delimiter] * The string can contain any character The competition ends on Thursday 3rd at 23:59 UTC. [Answer] # 8086 machine code, 82 80 Contents of the `x.com` file: ``` B7 3D 89 DF B1 80 F3 AA 0D 0A 24 B4 01 CD 21 42 38 D8 74 F7 38 17 77 02 88 17 88 C3 31 D2 3C 0D 75 E9 BF 21 3D B1 5E 31 C0 F3 AE E3 EE 4F BB 04 01 8A 05 D4 0A 86 E0 0D 30 30 89 47 02 3C 30 77 04 88 67 03 43 89 3F 89 DA B4 09 CD 21 47 EB D7 ``` It only supports repetitions of up to 99 characters. Source code (served as input for the `debug.com` assembler), with comments! ``` a mov bh, 3d ; storage of 128 bytes at address 3d00 mov di, bx mov cl, 80 rep stosb ; zero the array db 0d 0a 24 ; 10b mov ah, 1 int 21 ; input a char inc dx ; calculate the run length cmp al, bl ; is it a repeated character? je 10b cmp [bx], dl ; is the new run length greater than previous? ja 11a mov [bx], dl ; store the new run length ; 11a mov bl, al ; remember current repeating character xor dx, dx ; initialize run length to 0 cmp al, d ; end of input? jne 10b ; no - repeat mov di, 3d21 ; start printing run lengths with char 21 mov cl, 5e ; num of iterations = num of printable characters ; 127 xor ax, ax repe scasb ; look for a nonzero run length jcxz 11b ; no nonzero length - exit dec di mov bx, 104 ; address of output string mov al, [di] ; read the run length aam ; convert to decimal xchg al, ah or ax, 3030 mov [bx+2], ax cmp al, 30 ; was it less than 10? ja 145 mov [bx+3], ah ; output only one digit inc bx ; adjust for shorter string ; 145 mov [bx], di ; store "x=" into output string mov dx, bx ; print it mov ah, 9 int 21 inc di jmp 127 ; repeat ; 150 rcx 50 n my.com w q ``` Here are some golfing techniques used here that I think were fun: * array's address is `3d00`, where `3d` is the ascii-code for `=`. This way, the address for array's entry for character `x` is `3d78`. When interpreted as a 2-character string, it's `x=`. * Output buffer is at address `104`; it overwrites initialization code that is no longer needed. End-of-line sequence `0D 0A 24` is executed as harmless code. * The `aam` instruction here doesn't provide any golfing, though it could... * Writing the number twice, first assuming it's greater than 10, and then correcting if it's smaller. * Exit instruction is at an obscure address `11b`, which contains the needed machine code `C3` by luck. [Answer] # CJam, ~~27~~ ~~26~~ 25 bytes ``` l:S_&{'=L{2$+_S\#)}g,(N}/ ``` [Try it online.](http://cjam.aditsu.net/) ### Example ``` $ cjam maxseq.cjam <<< "acbaabbbaaaaacc" a=5 c=2 b=3 ``` ### How it works ``` l:S " Read one line from STDIN and store the result in “S”. "; _& " Intersect the string with itself to remove duplicate characters. "; { " For each unique character “C” in “S”: "; '=L " Push '=' and ''. "; { " "; 2$+_ " Append “C” and duplicate. "; S\#) " Get the index of the modified string in “S” and increment it. "; }g " If the result is positive, there is a match; repeat the loop. "; , " Retrieve the length of the string. "; ( " Decrement to obtain the highest value that did result in a match. "; N " Push a linefeed. "; }/ " "; ``` [Answer] ## J - 52 bytes Well, a simple approach again. ``` f=:([,'=',m=:":@<:@#@[`(]m~[,{.@[)@.(+./@E.))"0 1~~. ``` Explanation: ``` f=:([,'=',m=:":@<:@#@[`(]m~[,{.@[)@.(+./@E.))"0 1~~. ~~. Create a set of the input and apply it as the left argument to the following. ([,'=',m=:":@<:@#@[`(]m~[,{.@[)@.(+./@E.))"0 1 The function that does the work "0 1 Apply every element from the left argument (letters) with the whole right argument (text). @.(+./@E.) Check if the left string is in right string. (]m~[,{.@[) If yes, add one letter to the left string and recurse. ":@<:@#@[ If not, return (length of the left string - 1), stringified. [,'=', Append it to the letter + '=' ``` Example: ``` f 'acbaabbbaaaaacc' a=5 c=2 b=3 f 'aaaabaa' a=4 b=1 ``` If free-form output is allowed (as in many other answers), I have a **45 bytes** version too. These boxes represent a list of boxes (yes, they're printed like that, although SE's line-height breaks them). ``` f=:([;m=:<:@#@[`(]m~[,{.@[)@.(+./@E.))"0 1~~. f 'acbaabbbaaaaacc' ┌─┬─┐ │a│5│ ├─┼─┤ │c│2│ ├─┼─┤ │b│3│ └─┴─┘ f 'aaaabaabba' ┌─┬─┐ │a│4│ ├─┼─┤ │b│2│ └─┴─┘ ``` [Answer] # Ruby, 72 ``` (a=$*[0]).chars.uniq.map{|b|puts [b,a.scan(/#{b}+/).map(&:size).max]*?=} ``` This takes input from command line arguments and outputs to stdout. [Answer] # GolfScript, 26 bytes ``` :s.&{61{2$=}s%1,/$-1=,n+}% ``` [Try it online.](http://golfscript.apphb.com/?c=IyBDYW5uZWQgdGVzdCBpbnB1dDoKOyJhY2JhYWJiYmFhYWFhY2MiCgojIEFjdHVhbCBwcm9ncmFtIGNvZGU6CjpzLiZ7NjF7MiQ9fXMlMSwvJC0xPSxuK30l) Explanation: * `:s` saves the input string in the variable `s` for later use. * `.&` extracts the unique characters in the input, which the rest of the code in the `{ }%` loop then iterates over. * `61` pushes the number 61 (ASCII code for an equals sign) on top of the current character on the stack, to act as an output delimiter. * `{2$=}s%` takes the string `s` and replaces its characters with a 1 if they equal the current character being iterated over, or 0 if they don't. (It also leaves the current character on the stack for output.) * `1,/` takes this string of ones and zeros, and splits it at zeros. * `$` sorts the resulting substrings, `-1=` extracts the last substring (which, since they all consist of repetitions of the same character, is the longest), and `,` returns the length of this substring. * `n+` stringifies the length and appends a newline to it. Ps. If the equals signs in the output are optional, the `61` can be omitted (and the `2$` replaced by `1$`), for a total length of **24 bytes**: ``` :s.&{{1$=}s%1,/$-1=,n+}% ``` [Answer] ## CoffeeScript, 109 bytes I like regex. ``` f=(s)->a={};a[t[0]]=t.length for t in s.match(/((.)\2*)(?!.*\1)/g).reverse();(k+'='+v for k,v of a).join '\n' ``` Here is the compiled JavaScript you can try in your browser's console ``` f = function(s) { var a, t, _i, _len, _ref; a = {}; _ref = s.match(/((.)\2*)(?!.*\1)/g).reverse(); for (_i = 0, _len = _ref.length; _i < _len; _i++) { t = _ref[_i]; a[t[0]] = t.length; } return a; }; ``` Then you can call ``` f("acbaabbbaaaaacc") ``` to get ``` c=2 a=5 b=3 ``` [Answer] # [Python 3](https://docs.python.org/3/), 69 bytes ``` s=input() for c in set(s): i=0 while-~i*c in s:i+=1 print(c,'=',i) ``` [Try it online!](https://tio.run/##JclBCoAgEEDRvaeYnVoGRTvBw@hgOBAqakSbrm5Cf/E2Pz8tpLj3Xg3FfDUh2ZEKIFCE6puoUjMgszK4A51@eWn6n6bZbAxyodgEKm64Itm7RWetc4MR4gc "Python 3 – Try It Online") Even golfed Python can be very readable. I think this code is fully idiomatic except for the `-~i` for `i+1` and the single-letter variables. Thanks to pxeger for saving 1 byte. Example runs: ``` >>> helloworld e = 1 d = 1 h = 1 l = 2 o = 1 r = 1 w = 1 >>> acbaabbbaaaaacc a = 5 c = 2 b = 3 ``` [Answer] # [Pyth](http://ideone.com/xBaxnq), 24 25 26 (or 29) ``` =ZwFY{Z=bkW'bZ~bY)p(Yltb ``` Test can be done here: [link](http://ideone.com/fork/lSBjJG) Outputs in the format: ``` ('a', 5) ('c', 2) ('b', 3) ``` Explanation: ``` =Zw Store one line of stdin in Z FY{Z For Y in set(Z): =bk b='' W'bZ while b in Z: ~bY b+=Y ) end while p(Yltb print (Y, len(b)-1) ``` Python: ``` k="" Z=copy(input()) for Y in set(Z): b=copy(k) while (b in Z): b+=Y print(_tuple(Y,len(tail(b)))) ``` For proper (a=5) output, use: ``` =ZwFY{Z=bkW'bZ~bY)p++Y"="`ltb ``` 29 characters [Answer] # C, 126 125 119 bytes ``` l,n,c[256];main(p){while(~(p=getchar()))n*=p==l,c[l=p]=c[p]>++n?c[p]:n;for(l=256;--l;)c[l]&&printf("%c=%d\n",l,c[l]);} ``` Running: ``` $ gcc seq.c 2>& /dev/null $ echo -n 'acbaabbbaaaaacc' | ./a.out c=2 b=3 a=5 ``` [Answer] ## *Mathematica*, ~~74~~ ~~72~~ 69 ``` Print[#[[1,1]],"=",Max[Tr/@(#^0)]]&/@Split@Characters@#~GatherBy~Max& % @ "acbaabbbaaaaacc" ``` > > > ``` > a=5 > c=2 > b=3 > > ``` > > Not very good but strings are not *Mathematica*'s best area. Getting better though. :-) [Answer] # *C#* (LinQPad) ## 146 This is tsavino's answer but shorter. Here, I used `Distinct()` instead of `GroupBy(c=>c)`. Also the curly braces from the `foreach-loop` are left out: ``` void v(string i){foreach(var c in i.Distinct())Console.WriteLine(c+"="+(from Match m in Regex.Matches(i,"["+c+"]+")select m.Value.Length).Max());} ``` --- ## 136 I tried using a `lambda expression` instead of the normal query syntax but since I needed a `Cast<Match>` first, the code became 1 character longer... Anyhow, since it can be executed in LinQPad, you can use `Dump()` instead of `Console.WriteLine()`: ``` void v(string i){foreach(var c in i.Distinct())(c+"="+(from Match m in Regex.Matches(i,"["+c+"]+")select m.Value.Length).Max()).Dump();} ``` --- Further study of the code got me thinking about the `Max()`. This function also accepts a `Func`. This way I could skip the `Select` part when using the lambda epxression: ``` void v(string i){foreach(var c in i.Distinct())(c+"="+Regex.Matches(i,"["+c+"]+").Cast<Match>().Max(m=>m.Value.Length)).Dump();} ``` Thus, final result: # *128* **Update:** Thanks to the tip from Dan Puzey, I was able to save another 6 characters: ``` void v(string i){i.Distinct().Select(c=>c+"="+Regex.Matches(i,"["+c+"]+").Cast<Match>().Max(m=>m‌​.Value.Length)).Dump();} ``` Length: # 122 [Answer] # Ruby, 58 ``` h={} gets.scan(/(.)\1*/){h[$1]=[h[$1]||0,$&.size].max} p h ``` Takes input from STDIN, outputs it to STDOUT in the form `{"a"=>5, "c"=>2, "b"=>3}` [Answer] # C# in LINQPad - 159 Bytes Well, at least I beat T-SQL ;P Won't beat anyone else, but I thought I'd share it anyway. ``` void v(string i){foreach(var c in i.GroupBy(c=>c)){Console.WriteLine(c.Key+"="+(from Match m in Regex.Matches(i,"["+c.Key+"]+")select m.Value.Length).Max());}} ``` Usage: ``` v("acbaabbbaaaaacc"); ``` Suggestions are always welcome! [Answer] # Powershell ~~80~~ ~~77~~ 72 ``` $x=$args;[char[]]"$x"|sort -u|%{"$_="+($x-split"[^$_]"|sort)[-1].length} ``` You need to run it on console... [Answer] # Perl - 65 71 76 characters My first code golf! For each answer, copy to golf.pl and run as: ``` echo acbaabbbaaaaacc | perl golf.pl ``` My shortest solution prints each character as many times as it appears, since that is not prohibited by the rules. ``` $_=$i=<>;for(/./g){$l=length((sort$i=~/$_*/g)[-1]);print"$_=$l "} ``` My next-shortest solution (85 90 characters) only prints each character once: ``` <>=~s/((.)\2*)(?{$l=length$1;$h{$2}=$l if$l>$h{$2}})//rg;print"$_=$h{$_} "for keys %h ``` [Answer] # F# - 106 ``` let f s= let m=ref(Map.ofList[for c in 'a'..'z'->c,0]) String.iter(fun c->m:=(!m).Add(c,(!m).[c]+1))s;m ``` In FSI, calling ``` f "acbaabbbaaaaacc" ``` gives ``` val it : Map<char,int> ref = {contents = map [('a', 8); ('b', 4); ('c', 3); ('d', 0); ('e', 0); ('f', 0); ('g', 0); ('h', 0); ('i', 0); ...];} ``` However, to print it without the extra information, call it like this: ``` f "acbaabbbaaaaacc" |> (!) |> Map.filter (fun _ n -> n > 0) ``` which gives ``` val it : Map<char,int> = map [('a', 8); ('b', 4); ('c', 3)] ``` [Answer] # Javascript, 116 bytes ``` y=x=prompt();while(y)r=RegExp(y[0]+'+','g'),alert(y[0]+'='+x.match(r).sort().reverse()[0].length),y=y.replace(r,'') ``` Sample output: ``` lollolllollollllollolllooollo l=4 o=3 acbaabbbaaaaacc a=5 c=2 b=3 helloworld h=1 e=1 l=2 o=1 w=1 r=1 d=1 ``` [Answer] ## T-SQL (2012) 189 171 Edit: removed `ORDER BY` because rules allow any output order. Takes input from a CHAR variable, `@a`, and uses a [recursive CTE](http://technet.microsoft.com/en-us/library/ms190766%28v=SQL.105%29.aspx) to create a row for each character in the string and figures out sequential occurrences. After that, it's a simple `SELECT` and `GROUP BY` with consideration for the order of the output. [Try it out](http://sqlfiddle.com/#!6/d41d8/19777/0) on SQL Fiddle. ``` WITH x AS( SELECT @a i,''c,''d,0r,1n UNION ALL SELECT i,SUBSTRING(i,n,1),c,IIF(d=c,r+1,1),n+1 FROM x WHERE n<LEN(i)+2 ) SELECT d+'='+LTRIM(MAX(r)) FROM x WHERE n>2 GROUP BY d ``` Assigning the variable: ``` DECLARE @a CHAR(99) = 'acbaabbbaaaaacc'; ``` Sample output: ``` a=5 c=2 b=3 ``` [Answer] # Haskell - 113 ~~120~~ bytes ``` import Data.List main=interact$show.map(\s@(c:_)->(c,length s)).sort.nubBy(\(a:_)(b:_)->a==b).reverse.sort.group ``` Tested with ``` $ printf "acbaabbbaaaaacc" | ./sl [('a',5),('b',3),('c',2)] ``` [Answer] # JavaScript [83 bytes] ``` prompt().match(/(.)\1*/g).sort().reduce(function(a,b){return a[b[0]]=b.length,a},{}) ``` Run this code in the browser console. For input "`acbaabbbaaaaacc`" the console should output "`Object {a: 5, b: 3, c: 2}`". [Answer] # JavaScript - 91 ``` for(i=0,s=(t=prompt()).match(/(.)\1*/g);c=s[i++];)t.match(c+c[0])||alert(c[0]+'='+c.length) ``` **EDIT:** My first solution obeys the rules, but it prints several times single char occurrences like `abab` => `a=1,b=1,a=1,b=1` so I came out with this (**101** chars), for those not satisfied with my first one: ``` for(i=0,s=(t=prompt()).match(/((.)\2*)(?!.*\1)/g);c=s[i++];)t.match(c+c[0])||alert(c[0]+'='+c.length) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 18 bytes ``` mȯJ'=§eo;←osL►Lk←g ``` [Try it online!](https://tio.run/##yygtzv7/P/fEei9120PLU/OtH7VNyC/2eTRtl082kJn@//9/pcTkpMTEpCQgAQTJyUoA "Husk – Try It Online") 11 bytes if we ignore the exact input format and display as a list of pairs instead. [Answer] # [Husk](https://github.com/barbuz/Husk), 16 bytes ``` mS:(:'=s▲`mg¹#)U ``` [Try it online!](https://tio.run/##yygtzv7/PzfYSsNK3bb40bRNCbnph3Yqa4b@//8/MTkpMTEpCUiggORkAA "Husk – Try It Online") **Explanation:** ``` m U # for each of the unique elements of the input S: # prepend the element to (:'= ) # '=' prepended to ▲ # the maximum of # # the number of times it occurs in `mg¹ # each group of identical items in the input, s # converted into a string ``` I saw that [Razetime](https://codegolf.stackexchange.com/users/80214/razetime) had answered this in [Husk](https://github.com/barbuz/Husk), so I had to have a go too... [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ŒriƇṀj”=ʋⱮQY ``` [Try it online!](https://tio.run/##y0rNyan8///opKLMY@0PdzZkPWqYa3uq@9HGdYGR////V0pMTkpMTEoCEkCQnKwEAA "Jelly – Try It Online") -2 bytes thanks to Unrelated String! [8 bytes](https://tio.run/##y0rNyan8///opKLMY@0PdzacnP5o47rA/4fbj056uHPG//9KiclJiYlJSUACCJKTlQA) to output as a list of pairs ## How it works ``` ŒriƇṀj”=ʋⱮQY - Main link. Takes a string S on the left ʋ - Group the previous 4 links into a dyad f(S, C): Œr - Run-length encode S Ƈ - For each sublist in rle(S), keep it if: i - It contains C Ṁ - Maximum As all elements are in the form [C, n] for integers n, Python considers the maximum as the greatest n j”= - Join with "="; Yields [C, "=", n] Q - Get the unique characters of S Ɱ - For each unique character C in S, yield f(C, S) Y - Join by newlines and output ``` [Answer] ## Bash / GNU core utils (40) ``` fold -1|uniq -c|sort -k2 -k1r|uniq -f1 ``` [Try it online!](https://tio.run/##S0oszvj/Py0/J0VB17CmNC@zUEE3uaY4v6hEQTfbCIgNi6CiaYb//ycmJyUmJiUBCSBITgYA) Output when input is "acbaabbbaaaaacc": ``` 5 a 3 b 2 c ``` Explanation: * `fold -1` adds a newline after each character * `uniq -c` counts the number of consecutive identical lines * `sort -k2 -k1r` sorts the result so as the maximum count for each character comes first * `uniq -f1` keeps only the first line for each character [Answer] # Julia, 85 ``` f(s)=(l=0;n=1;a=Dict();[c==l?n+=1:(n>get(a,l,1)&&(a[l]=n);n=1;l=c) for c in s*" "];a) julia> f("acbaabbbaaaaacc") {'a'=>5,'c'=>2,'b'=>3} ``` [Answer] # Python3 - ~~111~~, ~~126~~, ~~115~~ ~~114~~ 111 bytes Executable code that will read 1 line (only use lowercase letters a-z) ``` d={}.fromkeys(map(chr,range(97,123)),0) for c in input():d[c]+=1 [print("%s=%d"%(p,d[p]))for p in d if d[p]>0] ``` Edit: Excluded unnecessary output on request from @Therare The output looks nice ``` ~/codegolf $ python3 maxseq.py helloworld l=3 o=2 h=1 e=1 d=1 w=1 r=1 ``` [Answer] # JavaScript - 141 137 125 I don't like regex :) ``` function g(a){i=o=[],a=a.split('');for(s=1;i<a.length;){l=a[i++];if(b=l==a[i])s++;if(!b|!i){o[l]=o[l]>s?o[l]:s;s=1}}return o} ``` Run ``` console.log(g("acbaabbbaaaaacc")); ``` outputs ``` [ c: 2, a: 5, b: 3 ] ``` [Answer] # Javascript, 109 104 100 98 bytes ``` function c(s){q=l={};s.split('').map(function(k){q[k]=Math.max(n=k==l?n+1:1,q[l=k]|0)});return q} ``` Example usage: ``` console.log(c("aaaaaddfffabbbbdb")) ``` outputs: ``` { a: 5, d: 2, f: 3, b: 4 } ``` [Answer] # PHP, 104 102 96 ``` <?php function _($s){while($n=$s[$i++]){$a[$n]=max($a[$n],$n!=$s[$i-2]?$v=1:++$v);}print_r($a);} ``` usage ``` _('asdaaaadddscc'); ``` printed ``` Array ( [a] => 4 [s] => 1 [d] => 3 [c] => 2 ) ``` ]
[Question] [ We've had a lot of [quine](/questions/tagged/quine "show questions tagged 'quine'") challenges, but a lot of the quine formats are similar, lets create some variance in our quines. Your task is to create a selection of programs in the same language (at least 2), all of which output their own source code, however, none of these programs can share any characters. For example, if you create a program using: ``` printf+qw(printf+qw(%s)x2)x2 ``` Your next program cannot include any of: ``` %()+2finpqrstwx ``` and so on. ## Rules * You may use unicode characters, but you must still score in bytes. * All programs must meet the [community definition of a proper quine](https://codegolf.meta.stackexchange.com/a/4878/9365). This means that the empty string does not count as a valid quine, among other things. * [Standard loopholes are forbidden.](https://codegolf.meta.stackexchange.com/q/1061/9365) * Functions or full programs are allowed as long as they meet the above definition. * Symbol independent languages (including Lenguage and Headsecks) are disallowed. * Most programs wins, with shortest total code as a tie breaker. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~3~~, 5 quines, 46 bytes ``` 2A2A ``` [Try it online!](https://tio.run/##K/v/38jRyPH/fwA "V – Try It Online") Hexdump: ``` 00000000: 3241 3241 2A2A ``` Explanation: ``` 2 " 2 times... A " (A)ppend the following text... 2A " '2A' ``` --- ``` 5­­­a5­­­a ``` [Try it online!](https://tio.run/##K/v/3/TQWhBMhNH//wMA "V – Try It Online") Hexdump: ``` 00000000: 35ad adad 6135 adad ad61 5...a5...a ``` Explanation: ``` 5--- " 5 - 3 times... a " (a)ppend the following text... 5---a " '5---a' ``` --- ``` 1«I1«I ``` [Try it online!](https://tio.run/##K/v/3/DQak8Q/v8fAA "V – Try It Online") Hexdump: ``` 00000000: 31ab 4931 ab49 1.I1.I ``` Explanation: ``` 1« " 1 + 1 times... I " (I)nsert the following text... 1«I " '1«I' ``` --- Here's where they start to get funky... ``` ñi34x@-qPÉÑ~ÿ ``` [Try it online!](https://tio.run/##K/v///DGTDFjE@kKB93CgMOdhyfWHd7//z8A "V – Try It Online") Hexdump: ``` 00000000: f169 1633 341b 7840 2d71 50c9 d17e ff .i.34.x@-qP..~. ``` Explanation: ``` ñ " Wrap all the following in macro '"q': i<C-v>34 " Insert character code 34 `"` <esc> " Return to normal mode x " Delete the character we just inserted. Now, running `@-` will be equal to running `"` P " Paste... @- " From Register... q " "q ÉÑ " Insert 'Ñ' at the beginning of this line ~ " Toggle the case of the character we just inserted ÿ " Black magic ``` --- ``` :norm é:":p ``` [Try it online!](https://tio.run/##K/v/3yovvyhX4fBKKyWrgv//AQ "V – Try It Online") Hexdump: ``` 00000000: 3a6e 6f72 6d20 e93a 223a 70 :norm .:":p ``` Explanation: ``` :norm " Run the following commands as if typed: é: " insert ':'. Somehow also does black magic and resets the value of '":` ":p " Paste the last ex command to be run ('norm é:":p') ``` This answer is filled with black magic. Quines 1 and 4 are not new, but the other 3 all have never been found before, so more than half of these quines were just discovered today. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~2 3 4~~ 5 quines, ~~14 18 81 65 59 56 326 265 247 229~~ 216 bytes ### 3 bytes ``` ”ṘṘ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw9yHO2cA0f//AA "Jelly – Try It Online") Standard quine. `”Ṙ` is the one character literal for `Ṙ`. `Ṙ` prints the string representation of this then the string `Ṙ` implicitly gets printed. ### 4 bytes ``` ⁾⁾ḤḤ ``` [Try it online!](https://tio.run/##y0rNyan8//9R4z4gerhjCRD9/w8A "Jelly – Try It Online") `⁾` begins a two character string literal and `Ḥ` doubles it's argument. With a string input, `Ḥ` gets mapped onto each character. Thus `Ḥ` acting on the string `⁾Ḥ` yields `⁾⁾ḤḤ`, the source code. ### 11 bytes ``` ȮṾṖƊ}“ȮṾṖƊ} ``` [Try it online!](https://tio.run/##y0rNyan8///Euoc79z3cOe1YV@2jhjlIvP//AQ "Jelly – Try It Online") On the right hand side, `“ȮṾṖƊ}` is the string literal for `ȮṾṖƊ}`. The string closing character is tacitly added at EOF. To the left of the string literal, `Ɗ` wraps `ȮṾṖ` into a single monad and `}` turns it into a dyad which uses it's right argument, the string literal. `Ȯ` prints the string (`ȮṾṖƊ}`), `Ṿ` creates a string representation of the string (`“ȮṾṖƊ}”`) and `Ṗ` removes the `”` character. The string `“ȮṾṖƊ}` is left after the monad and is implicitly printed. ### ~~38 49~~ 36 bytes ``` 32,52,52,7884,106,64,44,7884 44Ọj@,Ọ ``` [Try it online!](https://tio.run/##y0rNyan8/9/YSMcUjMwtLEx0DA3MdMxMdExMwFwFE5OHu3uyHHSA5P//AA "Jelly – Try It Online") First time I've ever used a space in Jelly golfing. The list of numbers at the beginning holds the `ord` of the rest of the characters in code. After that: ``` jṛ44Ọ$,Ọ j Join this list with... ṛ right argument. Avoiding using ¤ so I can use it in the next program. 44Ọ chr(44)==',': [106, ',', ...] $ Causes Ọ to act on 44 before j acts on it. , Pair this list with... Ọ chr of each number in the list. Yields jṛ44Ọ$,Ọ ``` ### ~~270 198 180~~ 162 bytes ``` ⁽¢_;⁽⁽¤;⁽¡_;⁽⁽¡;⁽¡¤;⁽$+;⁽⁽y;⁽Ẹ$;⁽⁺$;⁽AƑ;⁽?€;⁽b⁽;⁽¢¡;⁽_⁽;⁽¡¡;⁽¤ị;⁽ØJ;⁽µṭ;⁽€⁽;⁽¡S;⁽;⁽;⁽¡ʠ;⁽¤ị;⁽ØJ;⁽¤F;⁽ḊṄ;⁽ȧF ¢_⁽¤¡_⁽¡¡¤$+⁽yẸ$⁺$AƑ?€b⁽¢¡_⁽¡¡¤ịØJµṭ€⁽¡S;⁽¡ʠ¤ịØJ¤FḊṄȧF ``` [Try it online!](https://tio.run/##y0rNyan8//9R495Di@KtgRSItQTEOLQQzl8I4UPEVbShwpUg@uGuHSoQ/i4w7XhsIoiyf9S0BkQnATFY8yKIIfEw/kKooUse7u4GMQ7P8ALztz7cuRZsXtMauNJgaygTwj21AKvOJW5g9@zoerizBcQ6sdyNC@gnsBTQL1BLDy1R0Qa5HeRukJuB7gW5NQnqRoQyoOlAk8HugbgF6g6Q/XDZJW4Q@4B2/f8PAA "Jelly – Try It Online") Uses base 250 numbers and indexes into Jelly code page. Saved 72 bytes by changing the algorithm. Was using each number to index in to Jelly's code page but am now converting the integer back to base 250 then indexing into Jelly's code page, basically halving the number of literals I need in the first line. This also reduces the number of unique characters needed, but I can't think of a way to make any more quines. I've used up `⁾“”` which create string literals and `Ọ` and `ØJ` which create strings from numbers. I can't think of any other ways of making strings. I still have the digit `9` and `‘’` available, so if there is a another way of making strings from numbers it may be possible to make another quine. [Answer] # [Haskell](https://www.haskell.org/), 3 quines, 1119 bytes ## Quine 1, 51 bytes An anonymous `IO` action printing directly to stdout. ``` putStr`mappend`print`id`"putStr`mappend`print`id`" ``` [Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZZxvzv6C0JLikKCE3saAgNS8loaAoM68kITMlQQmnBNf///@S03IS04v/60Y4BwQAAA "Haskell – Try It Online") ## Quine 2, 265 bytes The function `f` takes a dummy argument and returns a string. ``` f c=[b=<<g]!!0++show g;b c=[[[show 9!!0,show 1!!0..]!!6..]!!c];g=[93,0,90,52,82,89,52,51,51,94,84,24,24,39,34,34,106,95,102,110,0,94,50,89,0,90,52,82,82,82,106,95,102,110,0,48,24,24,39,35,106,95,102,110,0,40,24,24,39,37,37,84,24,24,45,37,37,84,24,24,90,84,50,94,52] ``` [Try it online!](https://tio.run/##bY5NDoIwEIXXHIPEhYYJaUuLnUBP4bJhAUTAiD8RjMevnS5MoyZf2td5M/M6tcv5OM/u0p6u5v5cD@tjM2x3bkh6YztT12OTpizLlun2Ssaqo7K14YXegKC4V3nuG8tw9k01GosFMEAGSoD2IAnFCZSgJYhAgVBIgrMSUPlLAOeMRiUoRnPxlsBPq9TRNvXHZ5G/Jz75Un1XfJgO0fQB0Tj3Bg "Haskell – Try It Online") ## Quine 3, 803 bytes Everything after the `LANGUAGE` pragma is an anymous function taking a dummy argument and returning a string. ``` {-#LANGUAGE CPP#-}(\q(_:_:_:_:_:_:_:_:z)y(#)_->(y(\k x->'&':q:k:q:x)#y(\k x->'%':q:'\\':k:q:x)$y(:)#y(:)$ \x->x)z)'\''__TIME__(\(?)v k x->v$k?x)$ \(&)(%)v->v&'{'&'-'&'#'&'L'&'A'&'N'&'G'&'U'&'A'&'G'&'E'&' '&'C'&'P'&'P'&'#'&'-'&'}'&'('%'\\'&'q'&'('&'_'&':'&'_'&':'&'_'&':'&'_'&':'&'_'&':'&'_'&':'&'_'&':'&'_'&':'&'z'&')'&'y'&'('&'#'&')'&'_'&'-'&'>'&'('&'y'&'('%'\\'&'k'&' '&'x'&'-'&'>'%'\''&'&'%'\''&':'&'q'&':'&'k'&':'&'q'&':'&'x'&')'&'#'&'y'&'('%'\\'&'k'&' '&'x'&'-'&'>'%'\''&'%'%'\''&':'&'q'&':'%'\''%'\\'%'\\'%'\''&':'&'k'&':'&'q'&':'&'x'&')'&'$'&'y'&'('&':'&')'&'#'&'y'&'('&':'&')'&'$'&' '%'\\'&'x'&'-'&'>'&'x'&')'&'z'&')'%'\''%'\\'%'\''%'\''&'_'&'_'&'T'&'I'&'M'&'E'&'_'&'_'&'('%'\\'&'('&'?'&')'&'v'&' '&'k'&' '&'x'&'-'&'>'&'v'&'$'&'k'&'?'&'x'&')'&'$'&' '%'\\'&'('&'&'&')'&'('&'%'&')'&'v'&'-'&'>'&'v' ``` [Try it online!](https://tio.run/##pZHfa8IwEMf/lUDS5PLQfyCgpUgpgoowfQsEHyYbdWNurqSKf3t3qdcfrg8b2PBpk7vL3feuL7uv4vlwqOtLzBfpKt@mecZm6zWPr/sJ2CM4c7/OugKuXTyFCmzBfDxVUpmjKRCveWeMglFZq8gjKjDBbbRgFgO8PmtllXJuM19mzoGFRJesuVyKIvEhDqSGSJdokeqCdWKEIwskRVZIjmzpHPYZwpAZsiY43b0igNJQllTH5iCVCw088D0jGqkoH6ezo6JTslfD4gWp9F1QFKYhcdHGkERD0cOzpxL832mjcdrG0NxrX@qPcmLQpRlJ6G2iUUGS/GAMbaLbyO4EqFaAIzbIHFnSP23tXa@hYkIJS@p73P/NJ8iX/OqGDZNJckAzrz5xn6hmo@dt9/o@@fg@PZ0@xR50/QM "Haskell – Try It Online") ## Characters Quine 1: ``` "S`adeimnprtu ``` Quine 2: ``` !+,.0123456789;<=[]bcfghosw ``` Quine 3: ``` #$%&'()-:>?ACEGILMNPTU\_kqvxyz{} ``` ## How it works ### Quine 1 ``` putStr`mappend`print`id`"putStr`mappend`print`id`" ``` Quine 1 is a modified version of my recent [Golf you a quine](https://codegolf.stackexchange.com/a/161036/) answer (with improvements by H.PWiz): * Since full programs are not needed, `main=` has been removed. * `<>` and `$` have been replaced by their near-synonyms `mappend` and `id`. This frees up the vital characters `=<>` and the helpful operator `$` for the other quines. ### Quine 2 ``` f c=[b=<<g]!!0++show g;b c=[[[show 9!!0,show 1!!0..]!!6..]!!c];g=[93,0,......] ``` Quine 2 uses somewhat similar methods to program 2 of my recent [Mutually Exclusive Quines](https://codegolf.stackexchange.com/a/154282/) answer, but adapted to quine itself directly and especially to avoid using character literals, which are needed for quine 3. Both of these are achieved with the help of the `show` function, which by sheer luck hasn't had any of its characters used yet. This quine uses tabs instead of spaces, but I've used spaces below for readability. * `g` is the quine data, as a list of integers at the end of the code. Each number represents a character from the rest of the code. + The numbers are shifted by `9`, so that tab is `0`. This makes the encoding a bit shorter by allowing the lowercase letters for the function and variable names to fit in 2 digits. * `b c=[[[show 9!!0,show 1!!0..]!!6..]!!c]` is a function to convert a number to a character (actually a one-character string). + `[[show 9!!0,show 1!!0..]!!6..]` is a character range starting with a tab character, which is indexed into with `!!c`. + The tab character itself is produced by indexing into another range `[show 9!!0,show 1!!0..]`, starting with the digit characters `'9'` and `'1'` and jumping down in steps of 8. + The digit characters are produced by indexing into the `show` string of the corresponding digit. * `f c=[b=<<g]!!0++show g` is the main function. `c` is a dummy argument. + `b=<<g` uses `=<<` to convert each number in `g` to its character. (The use of `=<<` rather than e.g. `map` is why `b` needs to wrap its returned character in a list.) + `show g` gives the string representation of `g`'s list, and `++` concatenates the strings. + Because `=<<` has lower precedence than `++`, some bracketing is needed. To avoid using `()` (reserved for quine 3), `[...]!!0` indexes into a list with one element. ### Quine 3 By design of the other quines, quine 3 still has access to parentheses, lambda expressions, character literals, and the string/list constructor `:`. This will be enough to construct a function that *prepends* the quine's code to a string. Unfortunately, all lower case vowels (except sometimes `y`) have been used, leaving no useful alphanumeric builtin functions. Also `[]""` are gone. This leaves no normal way to construct an empty string to *start* pretending the code to. However, nearly all uppercase letters are still available, so a `LANGUAGE` pragma to get a language extension is possible. Again by sheer luck, `CPP` (enable C preprocessor) is the only language extension named with only uppercase letters. And CPP macros often have uppercase names. So to get the essential empty string, the quine enables `CPP`, uses the `__TIME__` macro to get a string constant of the form `"??:??:??"` (conveniently guaranteed to always have the same length), and pattern matches on it. ``` {-#LANGUAGE CPP#-}(\q(_:_:_:_:_:_:_:_:z)y(#)_->(y(\k x->'&':q:k:q:x)#y(\k x->'%':q:'\\':k:q:x)$y(:)#y(:)$ \x->x)z)'\''__TIME__(\(?)v k x->v$k?x)$ \(&)(%)v->v&'{'&'-'&...... ``` After the language pragma, the quine consists of a lambda expression binding its parameters to these four arguments (leaving a final dummy parameter `_` to be applied later): * `q` bound to `'\''`, giving a single quote character; * `_:_:_:_:_:_:_:_:z` bound to `__TIME__`, aka a string like `"??:??:??"`, thus making `z` an empty string; * `y` bound to `(\(?)v k x->v$k?x)`, a lambda combinator used to help convert the quine data from left associated ("foldl") to right associated ("foldr") form; * The operator `(#)` bound to `\(&)(%)v->v&'{'&'-'&...`, the quine data itself. The quine data is given in a form of Church encoding, a lambda expression with parameters `(&)(%)v`. * By applying the expression to particular values to instantiate `(&)`, `(%)` and `v`, this encoding can be used either to build the core code of the quine or to rebuild the quine data representation itself. * By Haskell's default fixity rule, `&` and `%` become left associative operators inside the lambda. Thus the character parameters become combined with the initial `v` starting from the left. * For most characters `k`, there is a corresponding `&'k'`. * When `k` is `'` or `\`, which need to be escaped inside character literals, the encoding is instead `%'\k'`. Since the data encoding is left associative, but strings are built in a right associative manner, the combinator `y = (\(?)v k x->v$k?x)` is introduced to bridge the mismatch. * `y(...)` is intended to build suitable functions for using as the quine data's `(&)` and `(%)` operators. * `v` is a function from strings to strings (the quine data's intended `v`s being examples). * `k` is a character, `x` a string, and `?` an operator that combines them into a new string. (For the core code, `(?)=(:)`. For actually reconstructing the quine data representation, it's more complicated.) * Thus `y(?)v k = \x->v$k?x` is another function from strings to strings. * As an example of how this changes associativity, if `(&)=y(:)`: ``` (v&k1&k2&k3) x = (((v&k1)&k2)&k3) x = y(:)(y(:)(y(:)v k1)k2)k3 x = y(:)(y(:)v k1)k2 (k3:x) = y(:)v k1 (k2:(k3:x)) = v (k1:(k2:(k3:x))) = v (k1:k2:k3:x) ``` More generally, when `(#)` is the quine data function and `f1,f2` are functions combining characters with strings: ``` (y(f1)#y(f2)$v) x = (...(y(f1)(y(f1)v '{') '-')...) x = v(f1 '{' (f1 '-' (... x))) ``` applying the quine data function with `(&)=y(f1)` and `(%)=y(f2)`, and this uses the prescribed `f1` and `f2` to combine the quine data's characters with `x`, and then passes the resulting string to `v`. The body of the main lambda expression puts this all together: ``` (y(\k x->'&':q:k:q:x)#y(\k x->'%':q:'\\':k:q:x)$y(:)#y(:)$ \x->x)z ``` * `'&':q:k:q:x` for a character `k` prepends `&'k'` to the string `x`, while `'%':q:'\\':k:q:x` prepends `%'\k'`, which are their original quine data forms. * Thus `y(\k x->'&':q:k:q:x)#y(\k x->'%':q:'\\':k:q:x` are the right parameters for rebuilding the quine data representation, prepended to the final `z` (the empty string), and then passed on to the following function. * `y(:)#y(:)` are the right parameters to prepend the quine's core code to a string, without other modification. * Finally the `\x->x` gets to do nothing with the constructed quine, which is returned. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 3 quines, 274 bytes ### Quine 1, 52 bytes ``` my&d={S{\d}=$_};say d Q{my&d={S{\d}=$_};say d Q{4}} ``` [Try it online!](https://tio.run/##K0gtyjH7/z@3Ui3Ftjq4Oial1lYlvta6OLGSK4UrsBqXuEltLdf//wA "Perl 6 – Try It Online") ### Quine 2, 102 bytes ``` printf |(q[printf |(q[@]xx 2 Z~|(q[printf |(q[!3]]Xx qw[1 0]))]xx 2 Z~|(q[printf |(q[!3]]Xx qw[1 0])) ``` [Try it online!](https://tio.run/##K0gtyjH7/7@gKDOvJI2zRqMwGonJ4hBbUcFpxBlVhyahaBwbG1HBWVgebchpEKupSaSy//8B "Perl 6 – Try It Online") ### Quine 3, 120 bytes ``` <'.EVAL'.UC,' GIVEN ',「「PRINT "<'.EVAL'.UC,' GIVEN ',「「".UC,.UC,"」」>.LC",".EVAL.EVAL".UC」」>.lc.EVAL.EVAL ``` [Try it online!](https://tio.run/##K0gtyjH7/99GXc81zNFHXS/UWUddwd0zzNVPQV3n/d5FQBQQ5OkXoqCET4kSSBCEld7vXQxEdno@zko6SmANYAKkACaVk4wQ//8fAA "Perl 6 – Try It Online") [Verification of distinct sets of bytes](https://tio.run/##K0gtyjH7n1up4JCcn5JarGCrEM1VmFBQlJlXksZZo1EYjcRkcYitqOA04oyqQ5NQNI6NjajgLCyPNuQ0iNXUJFJZgg7QKht1PdcwRx91vVBnHXUFd88wVz8FdZ33excBUUCQp1@IghI@JUogQRBWer93MRDZ6fk4K@kogTWACZACmFROMkIcbHlupVqKbXVwdUxKra1KfK11cWIlVwpXYDUucZPaWq6EWGsucIAlAgMLEmp2dnqpeSAWkBGcWmLNxQXUAFQQbRCroKGmCWIZAnVBBQ3hgkYIQQNkwf//AQ) There was a lot of maneuvering in getting that third quine. Perl 6 has 4 methods of output (that I'm aware of), `say`, `put`, `print` and `printf`. Both `say` and `put` output newlines, as I can't use both. `put`, `print`, `printf` all contain `p` and `t`. We can get around this partially by using `EVAL` to use the uppercase `PRINT`. From there, I don't think it's possible to get 4 quines... (though perhaps something like `shell "echo 'quine'"` might work) We can then get around spacing issues by using different type of whitespace to separate operators, spaces, tabs and newlines. ### Explanations: ### Quine 1: ``` my&d={ }; # Declare a function d which S{\d}=$_ # Which substitutes a digit with the string again say # Print with a newline d # The function Q{my&d={S{\d}=$_};say # Applied to the string with the program d Q{4}} # With a digit where the it should be inserted again ``` ### Quine 2: This is a quine in the format `printf |(q[printf q[%s]]xx 2)`, i.e. it formats a copy of the string into itself. However we can't use `s` since that's used in the previous quine's `say`. So we use the string OR operator (`~|`) on `@` and `!3`, to produce the `%s` part, but we can't do that to both the format string and the string to be inserted, so we have to do `Z~` with the extra string and an empty string, though we then can't use `,` to separate the two, so we then do `Xx qw[1 0]` to string multiply by 1 and 0. ``` printf |( ) # Print with formatting q[...] # The string of the program xx 2 # Duplicated Z~| ( ) # String or'd with q[...] # A copy to insert the %s Xx # String multiplied to qw[1 0] # itself and an empty string ``` ### Quine 3: This is an EVAL quine that tries its best to make everything uppercase to avoid conflict with the other quines. This involves a *lot* of `EVAL`s as well as quite a few `lc` and `uc` to convert between cases. ``` <...>.lc.EVAL # Evaluate the lowercase version of the string which results in .EVAL given 「print "<'.eval'.uc,' given ',「「".uc,.uc,"」」>.lc",".eval.eval".uc」 .EVAL # Evaluate again .EVAL given 「...」 # Set the string to $_ and pass it to .EVAL print "<'.eval'.uc,' given ',「「".uc # Print the first half of the quine uppercased ,.uc # Print the string uppercased ,"」」>.lc" # Print the .lc part lowercased ,".eval.eval".uc # Print the EVAL part uppercased ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), ~~4 5~~ 6 quines, 193,535 bytes ## 9 bytes ``` ÿ'ÿ⌐_'ÿ⌐_ ``` [Try it online!](https://tio.run/##y00syUjPz0n7///wfvXD@x/1TIiHUv//AwA "MathGolf – Try It Online") ## 45 bytes ``` û]∙ûxôû¬ûûûûû╡¬ûô╡û╡xûxxû¬ô]∙xô¬ûûû╡¬ô╡╡xxx¬ô ``` [Try it online!](https://tio.run/##y00syUjPz0n7///w7thHHTMP7644vOXw7kNrDu@GwUdTF4K5W4AMMK8CqKgCrGYLSAtQA0w5RClIIUhZRQWI8/8/AA "MathGolf – Try It Online") ## 49 bytes ``` ùa6æù\a\ù+6┼ù\ùùùùù\ù§\+ùΣ\Σa6æ\a\+6┼\ùùùù\§\+Σ\Σ ``` [Try it online!](https://tio.run/##y00syUjPz0n7///wzkSzw8sO74xJjDm8U9vs0ZQ9QPbhnTAIZB5aHqN9eOe5xTHnFoOUAhWClcEVxYAUgKX//wcA "MathGolf – Try It Online") ## 99 bytes ``` """▐ ⌠▌ ⌠▌ ⌠▌ ⌠ ⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠ ⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠"`~ ``` [Try it online!](https://tio.run/##y00syUjPz0n7/19JSenRtAkKj3oWPJrWg0mBmbRENLeAJKSUUPf/PwA "MathGolf – Try It Online") ## 4488 bytes ``` ♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠(((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠(((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((DÄß─·ö♠,♦M-$*DÄß─ö7($$$qq$Äq╘ ``` [Try it online!](https://tio.run/##y00syUjPz0n7///RzAUaQxgMiPMJW0qhs@Da6ey9IZ4YRj0/GqfDw/vDM9KGeVIctt4bbSMM5jbCaBoYzaijReyo90a9N@qi0SQwLGPZ5XDL4fmPpjQc2n54G1CrzqOZy3x1VbRgwoe3mWuoqKgUFqocbil8NHXG//8A "MathGolf – Try It Online") ## 188,845 bytes I'm can't really link to this one, so here's a Perl 6 program that [generates the actual quine](https://tio.run/##PVBLbsIwFNz7FC5FMgFjxc6HpAEpB@gNEIu0QKFKME1BCljOoouqiy667aYS66qqOEBVCfYcIhdJ7RBVsuT35s2bGXs5SWO3LJMNDCM4gKiNCE/HGPgmpoxhQH2GGbMxsC0fu46Hgec7mJqUqplpK5bZ0zRGXbVgadRiPqZWr4eBoxjYoVQRPNv3sOcwV5WObavSNTEEqHh9qhwDAFSG5lZlCCOS8hVPWwxmWdsgSbRsCWSgDJIhHXXJ0BxJg9zz@aKFLpBRb2Y6ffH@KU57qa9ECCnlrHj56Cfi@H38Ovz0D79CKEPtmTe3OQrNc7szQuO0t/tCDmTx/BYEUuG7/yOlkKi2WUabmEdjZdbMami6jmPd1yNyy5ObOnTldI6u3tjxuvX/1vnzSuMx2sDG9WRxt5pBPoUP6/licgUbeadSruQU61LTKiQoyz8) [Verification of distinctness](https://tio.run/##7ZbPi9pAFMfv@SumNhCjY0hijFoVpPS4pYceVdpsjV2LGn@WuGmklKXswYOH3aVe2pWF7aEtZUG2iC2Cc/ePmH/EzoxRWloopWzblZiBefPm8973PWeU1M1mRV9WuyBrgAwQQoJkNYuQS8pQUVXIKUkVqqoGOS2ahHosAblEMgYVWVHInqwRSo5TTFV0EhCl3qiahEo0HodcjBAwpigESGjJBEzEVJ2YMU0jpi5DwAm4/4IppjiO1MDvkxqyhtS02lYzqALbDolS1agHHUEUbCDllEJEyskFV5SeWOVaULghiF6kTavHw3fO4sKlU9VxXNfdw4ev01UHfUQf5l/S85njEEGq2eP3e0JWXi1HYlZcXGhpx824@OUglXKJf7QZruu4gidTN7oVyygSMd72XKVOpULX3pb0yKruekUzpVXppMdwIuJ9v179PZbjZsvogsCOWXvc3gNWCTQ65Zp5CwR6YZaa5VtjzJNix0UbflYhaIuJhRgnwu9iWObb3bbZYvmydi6UChXWG/c7VarXqZUbHRPsUgxkMuDeU7NpkJa@9ZNwSCQ9pdWOKJUqRptGeHk9v5f@p7TUNOum0TaLqeUSzQQ0w/3BA2/i0LSAD4doaqMxms7fo@n6wccjthwTg61sAtmMGdMQErDGVygFKWbbdMGhiaGjczTJG3k0Cev46DOx0WT9EHP@Nh9Gk8VZfnFGUQIybAPlKcC2uUAggE8GAPdP8Un/x4mZVzmuXOC3RuBhj8PD0@A1/vyT8n8t@odlbcL/cnvX/DL4zftnuh3tb@ehbflV3Nr2/HeE//kdwb8D/g/V/4v12/Pb8yvyr8BWnvIddIDe4KPn80/okoRCPDy/G@FDaze6jAd5nm80eHTQwMevvgI) ~~I can most definitely squeeze another quine out of this, though I think I've run out of ways to push strings straight to the stack, so I'll have to resort to stranger methods. Even *stranger* methods incoming as I try for a sixth quine. In some cases the quines could be shorter, but I'm reducing used bytes in preparation.~~ Okay, I might *technically* be able to do one more quine, since I still have a few operators that I need (push string, increment string, duplication, mapping, popping), it's the looping that constricts us. The `{}` are the only operators that can can indicate a code block of arbitrary length, and I really need them in the 6th quine. I could use some of the other code blocks, but they're limited, and I doubt the looping sections are going to be that short, since we're running out of easy operators. Okay, some belated explanations: All the quines have almost the same structure: * Push a string, or list of strings, or list of characters to the stack. * Combine it all into one list * Duplicate the list * Map over the copy, printing/pushing the characters used to get the original characters * Print the original list of characters as a string ### Quine 1: This is basically the same as the one I posted in the normal quine question. ``` ÿ'ÿ⌐_'ÿ⌐_ ÿ Push the next 4 bytes as a string 'ÿ⌐_ Stack ["'ÿ⌐_"] 'ÿ Push the byte ÿ (I realise I could have used this in a later quine) ⌐ Rotate the ÿ to the bottom of the stack : ["ÿ", "'ÿ⌐_"] _ Duplicate top of stack: ["ÿ", "'ÿ⌐_", "'ÿ⌐_"] Implicitly print stack joined together : ÿ'ÿ⌐_'ÿ⌐_ ``` ### Quine 2 ``` û Push the next 2 bytes as a string ]∙ Stack: ["]∙û"] û û... Repeat this for the rest of the code ] Wrap the stack in an array : [["]∙","xô"...]] ∙ Triplicate : [[..],[..],[..]] x Reverse the top array ô Loop over the array, executing the next 6 instructions Stack: [[..],[..],str] ¬ Rotate the stack : [str,[..],[..]] ûûû╡ Push the string "ûû" and discard the left character ¬ Rotate the "û" to the bottom : ["û",str,[..],[..]] This produces the initialisation part ô Loop over the array with the next 6 characters again ╡╡xxx¬ Basically discard the string ô Flatten the last copy of the array onto the stack Implicitly output the code ``` ### Quine 3: ``` ùa6æù\a\ù+6┼ù\ùùùùù\ù§\+ùΣ\Σa6æ\a\+6┼\ùùùù\§\+Σ\Σ ù... Push the next 3 bytes as a string You know how this goes a Wrap the top element in an array 6æ Repeat the next 4 instructions 6 times \ Swap the two top items a Wrap the top item in an array \ Swap back + Combine the two arrays This puts all the strings into a single array 6 Push a 6 ┼ Push the element two items down (the array) \ Swap with the 6 (this basically duplicates the array) ùùùù Push "ùùù" \§ Swap and get the 6th character (wrapping) \ Swap with array : ["ù", [..]] + Prepend to array (implicitly mapping) Σ\Σ Join both the lists to strings and output ``` ### Quine 4: ``` """▐ ⌠▌ ⌠▌ ⌠▌ ⌠ ⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠ ⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠"`~ "" Push the empty string "..." Push some code : ['','...'] ` Copy the top two elements of the stack : ['','...','','...'] ~ Evaluate the top element as code : ['','...',''] ▐ Prepend the empty string to the code ⌠ Push a space and increment by 2 to get a quote ▌ Prepend to the array ⌠▌ ⌠▌ ⌠ Repeat three more times, leaving the last on top : ['', '""...','"'] ⌠⌠... Push a space and increment until it reaches a '`' ⌠⌠... Repeat for the '~' : ['','"""...','"','`','~'] Implicitly output ``` ### Quine 5: ``` ♠ Push 256 ((... Decrement until it reaches the correct byte representing the code Repeat for each character of the code DÄ Repeat the next instruction 14 times ß Wrap the top 4 elements in an array ─ Flatten the resulting monstrosity · Triplicate the array ö Map the next 7 instructions over the array Stack : [[..],[..],num] ♠ Push 128 , Reverse subtraction : [[..],[..],128-num ♦M-$ Push the ( character * Repeat it 128-num times DÄß─ Gather that up in an array and flatten again ö Map the next 6 instructions 7($$$qq 7($$$q Print a ♠, without newline q Print the brackets without newline Stack : [[..],[..]] $ Map the number to their values in the code page Äq Map print over each element ╘ Discard the last element of the stack ``` ### Quine 6: The reason this quine is *so* much longer than the others is that incrementing strings uses unicode representations, which really sucks for the some of the characters in the code, especially when we're trying to create the character `⌂` in the code, which inflates the code by over 8000 characters, which then inflates the representation part by a very large amount. ``` ⌂ Push an * character ))... Increment until we reach the right character + 8 ♫{ } Repeat 10000 times α Wrap the top two elements in an array ♫{ } Then repeat 10000 times m{{}} Shallowly flatten the array h∞< Double the array m{ Map the doubled array to ïí½<¿{ If it is the first half of the array ⌂⌂ Push two asterisks )))... Increment into a '⌂' (there are something like 8000 )s here, with a couple of ! to help @ Rotate the top three elements Stack : ["⌂",char,"*"] 0{ α4<{}=}← Repeat while the asterisk is not the char ⌂⌡) Push a ) @ Rotate it under the char ) Increment the asterisk ;; Pop the extra copies of the character }{ Else ⌡⌡⌡⌡} Subtract 8 from the character }{} End map and flatten array Print implicitly ``` This last quine would be reduced significantly if MathGolf was consistent on whether strings used the native code page or not. [Answer] # Python 2, 2 quines, ~~434~~ ~~353~~ ~~349~~ 446 bytes This was mostly just to see if I could do it in Python. 30 bytes (including a trailing newline): ``` z='z=%r;print z%%z';print z%z ``` and 416 bytes, with no trailing newline: ``` exec"696d706f7274207379730a793d222222696d706f7274207379730a793d7b7d0a7379732e7374646f75742e777269746528276578656322272b792e666f726d6174282722272a332b792b2722272a33292e656e636f6465282268657822292b27222e6465636f64652822686578222927292222220a7379732e7374646f75742e777269746528276578656322272b792e666f726d6174282722272a332b792b2722272a33292e656e636f6465282268657822292b27222e6465636f6465282268657822292729".decode("hex") ``` (Golfed 81 bytes thanks to Lynn but added a load due to caring about the newline.) # Explanation The first one is just the standard [short Python quine](https://stackoverflow.com/questions/6223285/shortest-python-quine), but modified not to use `_`. Since this is Python 2 it also doesn't use `(` or `)`. The second one took some thought. The long string is encoded using the `hex` codec (thus guaranteeing that it will only contain `0`-`9` and `a`-`f`) and decodes as ``` import sys y="""import sys y={} sys.stdout.write('exec"'+y.format('"'*3+y+'"'*3).encode("hex")+'".decode("hex")')""" sys.stdout.write('exec"'+y.format('"'*3+y+'"'*3).encode("hex")+'".decode("hex")') ``` This uses quine trickery to get its own source code, then encodes it using `hex_codec`, and then prints it surrounded by `exec"".decode("hex")`, using `sys.stdout.write` to avoid printing a newline. Running this code outputs the second quine, which is how I generated it. I suspect that more than two is impossible in Python, though I would like to see it if I'm wrong! # If you don't mind eval quines Ørjan Johansen suggested the following for the pre-encoded second quine ``` y="""import sys sys.stdout.write('exec"'+('y='+'"'*3+y+'"'*3+';exec y').encode("hex")+'".decode("hex")')""";exec y ``` which would score 30+248=**278** bytes for the following output: ``` exec"793d222222696d706f7274207379730a7379732e7374646f75742e777269746528276578656322272b2827793d272b2722272a332b792b2722272a332b273b65786563207927292e656e636f6465282268657822292b27222e6465636f64652822686578222927292222223b657865632079".decode("hex") ``` The use of `exec` in this way is not cheating according to the PPCG [proper quine rules](https://codegolf.meta.stackexchange.com/a/12358/21034) but it feels somewhat cheaty to me (elegant and clever, but still cheaty), because some characters are being used as both code and data. (Although my version does use `exec`, the code and the data are separate.) So I will keep my score at 446. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~2~~ 3 quines, ~~106~~ 172 bytes The first one is a pretty verbose version of my [N char quine answer](https://codegolf.stackexchange.com/a/161567/16484). ``` [91,57,49,100,185,44,85,44,186,57,51,100,185,44,186,49,48,100,185,44,186,85,109,100,185,172,93,172] [91d¹,U,º93d¹,º10d¹,ºUmd¹¬]¬ ``` [Try it here](https://tio.run/##y0osKPn/P9rSUMfUXMfEUsfQwEDH0MJUx8REB0IaWpiBpEwNkaVAgkDFJhbogkCWoQHCFENzIx1LYxAVywW0I@XQTp1QnUO7LI1BrEO7DA0gdGgukD60JvbQmv//AQ). The second quine is [ETHProduction's greater good quine](https://codegolf.stackexchange.com/a/71932/16484), which is a good standard quine for Japt. ``` "iQ ²"iQ ² ``` [Try it here](https://tio.run/##y0osKPn/XykzUOHQJgj5/z8A). The third one uses ```` and char-code XORing to store the data. ``` T=`f=fR;Zff-R-ReX%`;`T=\``+T+Tc^# ``` [Try it here](https://tio.run/##y0osKPn/P8Q2Ic02Lcg6Ki1NN0g3KDVCNcE6IcQ2JiFBO0Q7JDlOme3/fwA). Since `()'` are still available, it *might* be possible to squeeze out one more quine. [Answer] # Javascript ES6, 2 quines, 43 + 22 = 65 bytes Quine 1: ``` (function f(){return[,f,'))'].join('(')}()) ``` Quine 2: ``` g=z=>"g="+g+";g``";g`` ``` [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), ~~2~~ 3 quines, ~~17 28 27~~ 26 bytes ## 6 bytes ``` "r2ssH ``` [Try it online!](https://tio.run/##S8/PScsszvj/X6nIqLjY4/9/AA "Gol><> – Try It Online") ## ~~11 10~~ 9 bytes ``` '3d*Wo{|; ``` [Try it online!](https://tio.run/##S8/PScsszvj/X904RSs8v7rG@v9/AA "Gol><> – Try It Online") ## 11 bytes ``` Eh`#Ma0piS0 ``` [Try it online!](https://tio.run/##S8/PScsszvj/3zUjQdk30aAgM9jg/38A "Gol><> – Try It Online") Gol><> has three ways to print any char: * `o` Pop one value and print as char * `H` Pop everything, print as char, and halt * `S"..."` Print string literal without affecting the stack at all But I couldn't find a way to write a quine using `S"..."` as the only output method, so I came up with the above two, utilizing the two kinds of string literals. The third one (by Jo King) uses the `p` command to create the `"` in `S"` on the fly, which in turn prints everything except the zero at the end. Then `Eh` prints the zero and exits. Now that we used up all the output commands AND the `p` command, I believe it's impossible to create another quine (unless someone comes up with the `S"` quine without `p`). [Answer] # [Ruby](https://www.ruby-lang.org/), 2 quines, 27 + 44 = 71 bytes ``` $><<<<2*2<<2 $><<<<2*2<<2 2 ``` [Try it online!](https://tio.run/##KypNqvz/X8XOBgiMtIyABBcKx@j/fwA "Ruby – Try It Online") ``` s=%q{s=%q{S};s[?S]=s;puts s};s[?S]=s;puts s ``` [Try it online!](https://tio.run/##KypNqvz/v9hWtbAaTATXWhdH2wfH2hZbF5SWFCsUo/O5/v8HAA "Ruby – Try It Online") I'm mainly limited by methods of output, here. There are quite a few ways of manipulating strings, but aside from `$><<` all the usable output methods seem to intersect too much. I think there might be a way out with `eval` but it's tricky having to nest multiple string manipulations of different kinds. [Answer] # [><>](https://esolangs.org/wiki/Fish), 2 quines, 8 + 16 = 24 bytes ### 8 bytes ``` #o<}-1:" ``` [Try it online!](https://tio.run/##S8sszvj/XznfplbX0Erp/38A "><> – Try It Online") Taken from [this answer](https://codegolf.stackexchange.com/a/151268/34718). --- ### 16 bytes ``` 'r3d*d8*7+e0p>>| ``` [Try it online!](https://tio.run/##S8sszvj/X73IOEUrxULLXDvVoMDOrub/fwA "><> – Try It Online") This is based on the `'r3d*>o<` quine, except `o` and `<` cannot be used, so I replaced `<` with `|` and dynamically created `o` (111 = 8\*13 + 7) and placed it where the 2nd `>` is. --- **2 quines is the limit** Unfortunately, we're limited by the number of output commands. `n` is not useful because it only outputs numbers, so `o` must be executed in any quine. The only way to dynamically create `o` is with `p`. So one quine can use `o`, and another can create it with `p`, but there can be no 3rd quine. It might be possible to have a third quine leave the source code on the stack if that counts. [Answer] # Java 10, 2 quines, ~~1448~~ 1248 bytes # ~~1350~~ 1122 bytes ``` \u0076\u002D\u003E\u007B\u0076\u0061\u0072\u0020\u0072\u003D\u0022\u0076\u002D\u003E\u007B\u0076\u0061\u0072\u0020\u0072\u003D\u0025\u0063\u0025\u0073\u0025\u0031\u0024\u0063\u003B\u0072\u002E\u0066\u006F\u0072\u006D\u0061\u0074\u0028\u0072\u002C\u0033\u0034\u002C\u0072\u002C\u0039\u0032\u0029\u002E\u0063\u0068\u0061\u0072\u0073\u0028\u0029\u002E\u0066\u006F\u0072\u0045\u0061\u0063\u0068\u0028\u0063\u002D\u003E\u0053\u0079\u0073\u0074\u0065\u006D\u002E\u006F\u0075\u0074\u002E\u0070\u0072\u0069\u006E\u0074\u0066\u0028\u0025\u0031\u0024\u0063\u0025\u0063\u0025\u0033\u0024\u0063\u0075\u0025\u0025\u0030\u0034\u0058\u0025\u0031\u0024\u0063\u002C\u0063\u0029\u0029\u003B\u007D\u0022\u003B\u0072\u002E\u0066\u006F\u0072\u006D\u0061\u0074\u0028\u0072\u002C\u0033\u0034\u002C\u0072\u002C\u0039\u0032\u0029\u002E\u0063\u0068\u0061\u0072\u0073\u0028\u0029\u002E\u0066\u006F\u0072\u0045\u0061\u0063\u0068\u0028\u0063\u002D\u003E\u0053\u0079\u0073\u0074\u0065\u006D\u002E\u006F\u0075\u0074\u002E\u0070\u0072\u0069\u006E\u0074\u0066\u0028\u0022\u005C\u005C\u0075\u0025\u0030\u0034\u0058\u0022\u002C\u0063\u0029\u0029\u003B\u007D ``` [Try it online.](https://tio.run/##7VRNT8MwDL3zK3zsDqCSNGmricu6cWMXJC7AIWQDdZSA1o8L2m8vrRPJhooJCXFDal3Xtd@L/SrvTGdOd5vn3lamruHKlO79BKB0zXb/aOwW1uMrQPdabsBGN@Ojm82H2GG4h6tuTFNaWIODC@jv2jhO9WjFcrRyhZEFxfU5@gJzYvIl5gvxawSFOZL8lPkSa0VCOXLB0JBLe5ZLiusl48VakbGqAnE8WkKRT19ztD6SMy6s0tnXvsKZs0n@5GyJolqO5mvDHNgkFUbSnFh8R1pRp4HLsyjWtdeCzVwjjl4xHM1O/s3Mpxr56fEczyuYlTFNWB3HL5ifkw1asz/tX/0/VB9zVEE2Pa6m@Il2/dzvnbf2oRr2Tlg/uJ5ehuUVXTf70j3d3oOZ@c3lzmzk2qoKS@vQfwA) Equivalent to: ``` v->{var r="v->{var r=%c%s%1$c;r.format(r,34,r,92).chars().forEach(c->System.out.printf(%1$c%c%3$cu%%04X%1$c,c));}";r.format(r,34,r,92).chars().forEach(c->System.out.printf("\\u%04X",c));} ``` **Explanation:** ``` v->{ // Method with empty unused parameter and no return-type var r="v->{var r=%c%s%1$c;r.format(r,34,r,92).chars().forEach(c->System.out.printf(%1$c%c%3$cu%%04X%1$c,c));}"; // Unformatted source code r.format(r,34,r,92) // Formatted quine .chars() // Loop over the characters as integers .forEach(c->System.out.printf("\\u%04X",c));} // Print "\u" with hexadecimal value of these characters ``` --- # 126 bytes ``` v->{int i='}'-'[';var s="v->{int i='}'-'[';var s=%c%s%c;System.console().printf(s,i,s,i);}";System.console().printf(s,i,s,i);} ``` `System.console()` will return `null` when none is provided, so [TIO returns a `NullPointerException` in this case](https://tio.run/##jY9NCoMwEIX3PcUgSBJQLxDsDepG6Ea6SGNaYmMUEwNFPHs6VreFwjyG@XnwvU4EkXftK0ojnIOL0HY5AWjr1fQQUkG1jQBh0C1Iet1aYBx3KwrLeeG1hAoslBBDfl7QC7okK8lJQ3gQE7gy@XVIZepSyeu386ov5GDdYBRlxTjh94O6TGcoxtfkj5/Id6ZxvhtkOtC@6D0Go7VHx7O5gWB7KltIamdjjkBr/AA). To prove it's a working quine, replace `System.console()` with `System.out`: [Try it online.](https://tio.run/##fY9NCoMwEIX3PcUgSCKoFwj2BnUjdCNdTKMtsRrFxECRnD0dq9sW5jHMz4Pvdegw65pXkD0aAxdUej0BKG3b@YGyhXIbAdyoGpD8ujWXCNp5EpWxaJWEEjQUEFx2XskLqmCeZaxmwuEMpoh@HWIZm1iK6m1sO@TjYvNppr8HN6lKSYnw0d9rEDvHtNx74jhwvrgDheGVJcezvgEmexKdS66Xvj9C@PAB) **Explanation:** ``` v->{ // Method with empty unused parameter and no return-type int i='}'-'['; // Integer `i` = 34 (unicode value for double-quote) var s="v->{int i='}'-'[';var s=%c%s%c;System.console().printf(s,i,s,i);}"; // Unformatted source code System.console().printf(s,i,s,i);} // Print formatted quine ``` --- **General explanation:** In Java a [quine](/questions/tagged/quine "show questions tagged 'quine'") is usually done like this: * The `String s` contains the unformatted source code. * `%s` is used to input this String into itself with the `s.format(...)`. * `%c`, `%1$c` and the `34` are used to format the double-quotes. * `s.format(s,34,s)` puts it all together. In which case the shortest quine lambda-function in Java 10 would be this (**82 bytes**): ``` v->{var s="v->{var s=%c%s%1$c;return s.format(s,34,s);}";return s.format(s,34,s);} ``` [Try it online.](https://tio.run/##dY7BCoJAEIbvPcUgCSuoEHUTe4O8BF2iw7RqrK2r7IwLIT67rSh0CmZg/vkP39egw6Qp37PUSAQXVGbcASjDla1RVlAsEeDKVpkXSHHrVAkuyvx38uuHGFlJKMBADrNLzqNDC5QHvzOUIYWHvcxsxYM1QGnd2RZZUHw8xRRlU/C/mrOV0w9P7Tkbzi0erdcVq9r9ARhtrh/iqk27gdPeVyxMKoUZtI427Wn@Ag) Since the only way to have two quines in Java is using the unicode version with `\uHEXA`, which is converted to characters during compilation, I'm unable to use the characters `0123456789ABCDEF\u` in the non-unicode version. So, the smaller non-unicode version will use `System.console()` instead of `return` or `System.out` (both containing a 'u'), and will use `'}'-'['` and two times `%c` instead of `34` and `%1$c`. Some things to note about the unicode version: * I'm on purpose using `%04X` instead of `%04x` (for uppercase Hexadecimal instead of lowercase). * I'm using `92`, `%c` and `%3$c` to format the slashes. * Using a capital `\U` instead of lowercase `\u` isn't allowed apparently, otherwise I would have just used `return` in the shorter non-unicode version. ]
[Question] [ A Sphenic Number is a number that is the product of exactly three distinct primes. The first few Sphenic numbers are `30, 42, 66, 70, 78, 102, 105, 110, 114`. This is sequence [A007304](https://oeis.org/A007304) in the OEIS. ## Your Task: Write a program or function to determine whether an inputted integer is a Sphenic number. ## Input: An integer between 0 and 10^9, which may or may not be a Sphenic Number. ## Output: A truthy/falsy value indicating whether the input is a Sphenic Number. ## Examples: ``` 30 -> true 121 -> false 231 -> true 154 -> true 4 -> false 402 -> true 79 -> false 0 -> false 60 -> false 64 -> false 8 -> false 210 -> false ``` ## Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins. [Answer] ## bash, 43 bytes ``` factor $1|awk '{print $2-$3&&$3-$4&&NF==4}' ``` [Try it online!](https://tio.run/##HY5NCsIwGET3PcVQPpJVoPlREdouXXqHNDa0qInUiAXr2WNwZlaPt5jBPqfsbELb8pWj99lbl@ICkpt9X8E/j2UOCaQEacZICzKMnU9dZ748r5UvasAcoBtIJaG0hNwZlDYKhyMa7MtMdYkVSkY3RYiAmgJEj/oPh3ICHhSKFUZscPH2uhch5R8 "Bash – Try It Online") Input via command line argument, outputs `0` or `1` to stdout. Fairly self-explanatory; parses the output of `factor` to check that the first and second factors are different, the second and third are different (they're in sorted order, so this is sufficient), and there are four fields (the input number and the three factors). [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` _YF7BX= ``` [Try it online!](https://tio.run/##y00syfn/Pz7Szdwpwvb/f0MDUwA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8D8@0s3cKcL2v0vIf2MDLkMjQy4jY0MuQ1MTLiA0MOIyt@Qy4DIDIhMA). ### Explanation ``` _YF % Implicit input. Nonzero exponents of prime-factor decomposition 7 % Push 7 B % Convert to binary: gives [1 1 1] X= % Is equal? Implicit display ``` [Answer] # C, ~~88~~ ~~78~~ ~~126~~ ~~58~~ ~~77~~ 73 + 4 (`lm`) = 77 bytes ``` l,j;a(i){for(l=1,j=0;l++<i;fmod(1.*i/l,l)?i%l?:(i/=l,j++):(j=9));l=i==1&&j==3;} ``` Ungolfed commented explanation: ``` look, div; //K&R style variable declaration. Useful. Mmm. a ( num ) { // K&R style function and argument definitions. for ( look = 1, div = 0; // initiate the loop variables. look++ < num;) // do this for every number less than the argument: if (fmod(1.0 * num / look, look)) // if num/look can't be divided by look: if( !(num % look) ) // if num can divide look num /= look, div++; // divide num by look, increment dividers else div = 9; // if num/look can still divide look // then the number's dividers aren't unique. // increment dividers number by a lot to return false. // l=j==3; // if the function has no return statement, most CPUs return the value // in the register that holds the last assignment. This is equivalent to this: return (div == 3); // this function return true if the unique divider count is 3 } ``` [Try it online!](https://tio.run/##JcxBDoIwEADAr5gmJLu2COjJLg0f8dIslLRZwACejF@3kviAGS5H5pzFJPIQ8R2WFcQ1JrmaROs2UpiWHprLOVZiBLtYSGchVu4gWqOF5O6IJC45d6NPZpp8nOE/EbfXuiZ8rnHeA6ji1ttTsT1mZVhr44GxU/v6GpRVwcs2KDyKLwfx45ZLmX4 "C (gcc) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~6~~ 3 bytes ``` ḋ≠Ṫ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO7kedCx7uXPX/v5Gx4X8A "Brachylog – Try It Online") ### Explanation ``` ḋ The prime factorization of the Input… ≠ …is a list of distinct elements… Ṫ …and there are 3 elements ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 11 bytes ``` rimFz1=7Yb= ``` [Try it online!](https://tio.run/##S85KzP3/vygz163K0NY8Msn2/39DA1MA "CJam – Try It Online") Or [verify all test cases](https://tio.run/##S85KzP1f/T8nM9etytDWPDLJ9n@BYW36f2MDLkMjQy4jY0MuQ1MTLiA0MOIyt@Qy4DIDIhMA). ### Explanation Based on my MATL answer. ``` ri e# Read integer mF e# Factorization with exponents. Gives a list of [factor exponent] lists z e# Zip into a list of factors and a list of exponents 1= e# Get second element: list of exponents 7 e# Push 7 Yb e# Convert to binary: gives list [1 1 1] = e# Are the two lists equal? Implicitly display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ÆEḟ0⁼7B¤ ``` [Try it online!](https://tio.run/##y0rNyan8//9wm@vDHfMNHjXuMXc6tOT////GBgA "Jelly – Try It Online") Uses Luis Mendo's algorithm. Explanation: ``` ÆEḟ0⁼7B¤ ÆE Prime factor exponents ḟ0 Remove every 0 ⁼7B¤ Equal to 7 in base 2? ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ÆE²S=3 ``` [Try it online!](https://tio.run/##y0rNyan8//9wm@uhTcG2xv@P7jnc/qhpjfv//8YGOgqGRoY6CkbGQMLQ1ERHAYQMjHQUzC11FICyZiBsAgA "Jelly – Try It Online") ### How it works ``` ÆE²S=3 Main link. Argument: n ÆE Compute the exponents of n's prime factorization. ² Take their squares. S Take the sum. =3 Test the result for equality with 3. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` ≡ḋ3Ẋ≠p ``` [Try it online!](https://tio.run/##yygtzv7//1Hnwoc7uo0f7up61Lmg4P///8YGAA "Husk – Try It Online") Returns 1 for sphenic numbers and 0 otherwise. ### Explanation ``` ≡ḋ3Ẋ≠p Example input: 30 p Prime factors: [2,3,5] Ẋ≠ List of absolute differences: [1,2] ≡ Is it congruent to... ? ḋ3 the binary digits of 3: [1,1] ``` In the last passage, congruence between two lists means having the same length and the same distribution of truthy/falsy values. In this case we are checking that our result is composed by two truthy (i.e. non-zero) values. [Answer] # Ruby, ~~81~~ ~~49~~ 46 bytes Includes 6 bytes for command line options `-rprime`. ``` ->n{n.prime_division.map(&:last)==[1]*3} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOk@voCgzNzU@JbMsszgzP08vN7FAQ80qJ7G4RNPWNtowVsu49n@BQlq0kWWsDpAyNoBQhmDKBEoZxf7/l19QAtRf/F@3CGwiAA "Ruby – Try It Online") [Answer] # Mathematica, 31 bytes ``` SquareFreeQ@#&&PrimeOmega@#==3& ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 5 bytes ``` ÓnO3Q ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8OQ8f@PA//@NDQA "05AB1E – Try It Online") Uses Dennis's algorithm. [Answer] # Pyth, 9 bytes ``` &{IPQq3lP ``` [Try it here.](http://pyth.herokuapp.com/?code=%26%7BIPQq3lP&input=30&debug=0) [Answer] # [Actually](https://github.com/Mego/Seriously), 7 bytes ``` w♂N13α= ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/7/80cwmP0Pjcxtt//83NgAA "Actually – Try It Online") Explanation: ``` w♂N13α= w Push [prime, exponent] factor pairs ♂N Map "take last element" 1 Push 1 3 Push 3 α Repeat = Equal? ``` [Answer] # [Haskell](https://www.haskell.org/), 59 bytes ``` f x=7==sum[6*0^(mod(div x a)a+mod x a)+0^mod x a|a<-[2..x]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwtbc1ra4NDfaTMsgTiM3P0UjJbNMoUIhUTNRG8gDs7QN4qDMmkQb3WgjPb2K2Nj/uYmZebYFRZl5JSppCiYGRv8B "Haskell – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 bytes ``` k k@è¥X ÉÃl ¥3 ``` [Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=awprQOilWCDJw2wgpTM=&inputs=MzA=,MTIx,MjMx,MTU0,NA==,NDAy,Nzk=,MA==,NjA=,NjQ=) [Answer] # [J](http://jsoftware.com/), 15 bytes ``` 7&(=2#.~:@q:)~* ``` [Try it online!](https://tio.run/##y/r/P03B1krBXE3D1khZr87KodBKs06Liys1OSNfQUNHL03JQFPB2EDB0MhQwcjYUMHQ1EQBCA2MFMwtFQwUzIDI5P9/AA "J – Try It Online") ## Explanation ``` 7&(=2#.~:@q:)~* Input: integer n * Sign(n) 7&( )~ Execute this Sign(n) times on n If Sign(n) = 0, this returns 0 q: Prime factors of n ~:@ Nub sieve of prime factors 2#. Convert from base 2 = Test if equal to 7 ``` [Answer] # Dyalog APL, 26 bytes ``` ⎕CY'dfns' ((≢,∪)≡3,⊢)3pco⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdOSM1Ofv/o76pzpHqKWl5xepcGhqPOhfpPOpYpfmoc6GxzqOuRZrGBcn5QCUg9f/BGriMDbi4ICxDI0MY08gYzjQ0NYExEQwDIxjT3BLGMoMbZGYCAA) [Answer] # Mathematica, 44 bytes ``` Plus@@Last/@#==Length@#==3&@FactorInteger@#& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvs/IKe02MHBJ7G4RN9B2dbWJzUvvSQDxDJWc3BLTC7JL/LMK0lNTy1yUFb7H1CUmQdUl6bvUG1soKNgaGSoo2BkDCQMTU10FEDIwEhHwdxSRwEoawbCJrX/AQ "Mathics – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~54~~ 53 bytes ``` lambda n:sum(1>>n%k|7>>k*k%n*3for k in range(2,n))==6 ``` *Thanks to @xnor for golfing off 1 byte!* [Try it online!](https://tio.run/##FYxBCoMwFETX7SlmE4zyCyaxSoXkJN1YWluJfiXqotC7pwbmzeINzPLdPjOb2MPiHsduejw7cLvuk1TOsfC/xjlfeMGF6ecAj4EROn6/pCbOc2vrmDwnb0qC0oqgzVHqWhFSSk1oboRjrRNVez4tYeBNZsLsuDiINYOAZEIvj9M8/gE "Python 3 – Try It Online") [Answer] **C, 91 102 bytes, corrected (again), golfed, and tested for real this time:** ``` <strike>s(c){p,f,d;for(p=2,f=d=0;p<c&&!d;){if(c%p==0){c/=p;++f;if(c%p==0)d=1;}++p;}c==p&&f==2&&!d;}</strike> s(c){int p,f,d;for(p=2,f=d=0;p<c&&!d;){if(c%p==0){c/=p;++f;if(c%p==0)d=1;}++p;}return c==p&&f==2&&!d;} ``` /\* This also works in 93 bytes, but since I forgot about the standard rules barring default int type on dynamic variables, and about the not allowing implicit return values without assignments, I'm not going to take it: ``` p,f,d;s(c){for(p=2,f=d=0;p<c&&!d;){if(c%p==0){c/=p;++f;if(c%p==0)d=1;}++p;}p=c==p&&f==2&&!d;} ``` (Who said I knew anything about C? ;-) Here's the test frame with shell script in comments: ``` /* betseg's program for sphenic numbers from */ #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <math.h> /* compile with -lm */ /* l,j;a(i){for(l=1,j=0;l<i;i%++l?:(i/=l,j++));l=i==1&&j==3;} */ #if defined GOLFED l,j;a(i){for(l=1,j=0;l++<i;fmod((float)i/l,l)?i%l?:(i/=l,j++):(j=9));l=i==1&&j==3;} #else int looker, jcount; int a( intval ) { for( looker = 1, jcount = 0; looker++ < intval; /* Watch odd intvals and even lookers, as well. */ fmod( (float)intval/looker, looker ) ? intval % looker /* remainder? */ ? 0 /* dummy value */ : ( inval /= looker, jcount++ /* reduce the parameter, count factors */ ) : ( jcount = 9 /* kill the count */ ) ) /* empty loop */; looker = intval == 1 && jcount == 3; /* reusue looker for implicit return value */ } #endif /* for (( i=0; $i < 100; i = $i + 1 )) ; do echo -n at $i; ./sphenic $i ; done */ ``` I borrowed betseg's previous answer to get to my version. This is my version of betseg's algorithm, which I golfed to get to my solution: ``` /* betseg's repaired program for sphenic numbers */ #include <stdio.h> #include <stdlib.h> #include <limits.h> int sphenic( int candidate ) { int probe, found, dups; for( probe = 2, found = dups = 0; probe < candidate && !dups; /* empty update */ ) { int remainder = candidate % probe; if ( remainder == 0 ) { candidate /= probe; ++found; if ( ( candidate % probe ) == 0 ) dups = 1; } ++probe; } return ( candidate == probe ) && ( found == 2 ) && !dups; } int main( int argc, char * argv[] ) { /* Make it command-line callable: */ int parameter; if ( ( argc > 1 ) && ( ( parameter = (int) strtoul( argv[ 1 ], NULL, 0 ) ) < ULONG_MAX ) ) { puts( sphenic( parameter ) ? "true" : "false" ); } return EXIT_SUCCESS; } /* for (( i=0; $i < 100; i = $i + 1 )) ; do echo -n at $i; ./sphenic $i ; done */ ``` [Answer] # Javascript (ES6), 87 bytes ``` n=>(a=(p=i=>i>n?[]:n%i?p(i+1):[i,...p(i,n/=i)])(2)).length==3&&a.every((n,i)=>n^a[i+1]) ``` Example code snippet: ``` f= n=>(a=(p=i=>i>n?[]:n%i?p(i+1):[i,...p(i,n/=i)])(2)).length==3&&a.every((n,i)=>n^a[i+1]) for(k=0;k<10;k++){ v=[30,121,231,154,4,402,79,0,60,64][k] console.log(`f(${v}) = ${f(v)}`) } ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~135~~ 121 bytes * Quite long since this includes all the procedures: prime-check, obtain-prime factors and check sphere number condition. ``` lambda x:(lambda t:len(t)>2and t[0]*t[1]*t[2]==x)([i for i in range(2,x)if x%i<1and i>1and all(i%j for j in range(2,i))]) ``` [Try it online!](https://tio.run/##XYwxDsIwEAR7XnFNpDtE4bi0cD7iuDBKAheZS2K5MK83JKJANLtbzM76yo9FdN1sX2N43oYAxeB3ZRNHwUydDjJAdsqfs2v30N7aQugYpiUBAwukIPcR9aUQT1Aavrb7ibujQozIzXzQ8y/NRJ7qv0QpMif4eDZkMmtiycD1DQ "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 59 bytes ``` lambda x:6==sum(5*(x/a%a+x%a<1)+(x%a<1)for a in range(2,x)) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCyszWtrg0V8NUS6NCP1E1UbtCNdHGUFNbA0Kn5RcpJCpk5ikUJealp2oY6VRoav4vKMrMK1FI0zAxMNL8DwA "Python 2 – Try It Online") [Answer] # J, 23 bytes ``` 0:`((~.-:]*.3=#)@q:)@.* ``` [Try it online!](https://tio.run/##y/r/P91WT0HBwCpBQ6NOT9cqVkvP2FZZ06HQStNBT4urAChpbKBgZGyoYGhqomBiYMSVBhSyUDA0MlQwUTC3VDBQMAMiEwWu1OSMfIV0hQIYI@3/fwA "J – Try It Online") Handling 8 and 0 basically ruined this one... `q:` gives you all the prime factors, but doesn't handle 0. the rest of it just says "the unique factors should equal the factors" and "the number of them should be 3" [Answer] # PHP, 66 bytes: ``` for($p=($n=$a=$argn)**3;--$n;)$a%$n?:$p/=$n+!++$c;echo$c==7&$p==1; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/285093bffbdb0bb5f7ac3cb1125b6bbb91c4f5e1). Infinite loop for `0`; insert `$n&&` before `--$n` to fix. **breakdown** ``` for($p=($n=$a=$argn)**3; # $p = argument**3 --$n;) # loop $n from argument-1 $a%$n?: # if $n divides argument $p/=$n # then divide $p by $n +!++$c; # and increment divisor count echo$c==7&$p==1; # if divisor count is 7 and $p is 1, argument is sphenic ``` **example** argument = `30`: prime factors are `2`, `3` and `5` other divisors are `1`, 2\*3=`6`, 2\*5=`10` and 3\*5=`15` their product: `1*2*3*5*6*10*15` is `27000` == `30**3` [Answer] # VB.NET (.NET 4.5), 104 bytes ``` Function A(n) For i=2To n If n Mod i=0Then A+=1 n\=i End If If n Mod i=0Then A=4 Next A=A=3 End Function ``` I'm using the feature of VB where the function name is also a variable. At the end of execution, since there is no return statement, it will instead pass the value of the 'function'. The last `A=A=3` can be thought of `return (A == 3)` in C-based languages. Starts at 2, and pulls primes off iteratively. Since I'm starting with the smallest primes, it can't be divided by a composite number. Will try a second time to divide by the same prime. If it is (such as how 60 is divided twice by 2), it will set the count of primes to 4 (above the max allowed for a sphenic number). [Try It Online!](https://tio.run/##hdJRS8MwEAfw596nOPYgK1JJ02xjDxGCOhhYXxz44ku3ZXrQXaBNxW9fY1UMKCRvCb/8udzljfqhaYt909OhYOuLs2M31u44tBbrEm7pjIRNj8Tevthu3Ax88OQYzZxz2LgOScudQ4btCRnDzXAgdq@WwVzqEvhZE9zxEbenPwKNVvBg3z0YbXQ1sZ/8MXsc9lg3xJBlN45719qrp468vSe281klEItrnOFFqKQSeQ4Zfq9/dCnLXx02CS6riIdNKn2hovSFSnCFUelJLGSEhUzw1TrKXq0TWsSVpHq4jDu@TGoV6@mVn@MNQ53G/PXDxg8) [Answer] # JavaScript (ES6), 80 bytes ``` n=>(p=(n,f=2)=>n%f?p(n,f+1):f,(a=p(n))<n&&(b=p(n/=a))<n&&(c=p(n/=b))==n&a<b&b<c) ``` Using a recursive function to get the smaller factor. Output 1 if sphenic, false if there are 2 or less factors and 0 otherwise **Test** ``` F= n=>(p=(n,f=2)=>n%f?p(n,f+1):f,(a=p(n))<n&&(b=p(n/=a))<n&&(c=p(n/=b))==n&a<b&b<c) ;[30,121,231,154,4,402,79,0,60,64,8,210].forEach( x=>console.log(x,F(x)) ) ``` [Answer] # Dyalog APL, ~~51~~ ~~49~~ ~~48~~ ~~46~~ ~~45~~ 43 bytes ``` 1∊((w=×/)∧⊢≡∪)¨(⊢∘.,∘.,⍨){⍵/⍨2=≢∪⍵∨⍳⍵}¨⍳w←⎕ ``` [Try it online!](http://tryapl.org/?a=%7B1%u220A%28%28w%3D%D7/%29%u2227%u22A2%u2261%u222A%29%A8%28%u22A2%u2218.%2C%u2218.%2C%u2368%29%7B%u2375/%u23682%3D%u2262%u222A%u2375%u2228%u2373%u2375%7D%A8%u2373w%u2190%u2375%7D30&run) (modified so it can run on TryAPL) I wanted to submit one that doesn't rely on the dfns namespace whatsoever, even if it is **long**. [Answer] # J, ~~15~~ ~~14~~ 19 bytes Previous attempt: `3&(=#@~.@q:)~*` Current version: `(*/*3=#)@~:@q: ::0:` # How it works: ``` (*/*3=#)@~:@q: ::0: Input: integer n ::0: n=0 creates domain error in q:, error catch returns 0 q: Prime factors of n ~:@ Nub sieve of prime factors 1 for first occurrence 0 for second (*/*3=#)@ Number of prime factors is equal to 3, times the product across the nub sieve (product is 0 if there is a repeated factor or number of factors is not 3) ``` This passes for cases 0, 8 and 60 which the previous version didn't. [Answer] # Regex (ECMAScript), 46 bytes ``` ^((?=(xx+?)\2*$)(?=(x+)(\3+$))\4(?!\2+$)){3}x$ ``` [Try it online!](https://tio.run/##TY/BbsIwEER/BSIEu6QJCdAecE1OPXDh0B6bVrJgcdwax7INpFC@PQ2VKvU2ozfS6H2Io/Abp2xIvFVbcvvafNJX67ihU@@Z5FNjAc58ORm37wAFh6aJCyyn4wH@thihnMUDxHIORb@c3uJldm0G7XhyxjTUL8EpIwFTr9WG4OEumSMyzzN2qpQmAM0dia1WhgCxz81Ba7xIrlNvtQowSkbI1A7AcJlqMjJUuJx@fyu/FmtQ3ArnaWUCyNfsDfEP0H9glnmRL24YQ@XqU7QyR6HVtueEkbToRbFmu9oBU4@cmIpj7A6jJkodWRIBFKZ7ETYVuE7OD4e2Uwpws8iZPQQfXDdh12ubJfl9lv0A "JavaScript (SpiderMonkey) – Try It Online") This works similarly to [Match strings whose length is a fourth power](https://codegolf.stackexchange.com/questions/19262/match-strings-whose-length-is-a-fourth-power/21951#21951) and very similarly to part of [Is this a consecutive-prime/constant-exponent number](https://codegolf.stackexchange.com/questions/164911/is-this-a-consecutive-prime-constant-exponent-number/179412#179412): ``` ^ ( # Loop the following: (?=(xx+?)\2*$) # \2 = smallest prime factor of tail (?= (x+)(\3+$) # \3 = tail / {smallest prime factor of tail}; \4 = tool to make tail = \3 )\4 # tail = \3 (?!\2+$) # assert that tail is no longer divisible by \2 ){3} # Execute the loop exactly 3 times x$ # assert tail == 1 ``` ]
[Question] [ Your job is quite simple, write a program that prints `Hello, world!`, that when twisted creates a program that prints `Twister!`. ## How strings are twisted The twisting algorithm is very simple. Each column is shifted down by its index (col 0 moves down 0, col 1 moves 1, ...). The column shift wraps to the top. It kinda looks like this: ``` a ba cba ---- cba cb c ``` With everything under the line wrapping to the top. Real example: ``` Original: \\\\\\\\\\\\ ............ ............ ............ Twisted: \...\...\... .\...\...\.. ..\...\...\. ...\...\...\ ``` (Further examples and a twisters in your favorite language are [here](https://codegolf.stackexchange.com/questions/70696/golf-a-string-twister)) ## Scoring Your program must be a padded rectangle. This is code-golf so lowest byte count wins! ## Rules * Your first program must print `Hello, world!`. Only one trailing newline is allowed. * Your first and second programs must be in the same language. * Your second program must print `Twister!`. Only one trailing newline is allowed. * Your program must have at least 2 rows and 2 columns. [Answer] # Python 2, 59 bytes ``` print " Hello, world!"[ 2::] #rint "T w i s t e r !"[ ::2] ``` Twisted: ``` print "T weils,twerrd!"[ ::2] #rint " H l o o l !"[ 2::] ``` Basically, puts the `Twister!` data in the odd indices of the string and then changes from removing the first two (padding) characters to removing every other character instead. [Answer] ## [Fission](https://github.com/C0deH4cker/Fission), ~~215~~ ~~162~~ ~~56~~ ~~53~~ 50 bytes Here is a start: ``` D1 \\ "" TH we il sl to e, r !w "o 1r ;l 1d ;! " ``` [Try it online!](http://fission.tryitonline.net/#code=RDEKXFwKIiIKVEgKd2UKaWwKc2wKdG8KZSwKciAKIXcKIm8KMXIKO2wKMWQKOyEKICI&input=) When twisted: ``` D" \1 "\ T" wH ie sl tl eo r, ! "w 1o ;r 1l ;d ! ``` [Try it online!](http://fission.tryitonline.net/#code=RCIKXDEKIlwKVCIKd0gKaWUKc2wKdGwKZW8KciwKISAKIncKMW8KO3IKMWwKO2QKICE&input=) ### Explanation The `Hello, world!` code is fairly simple: * `D` spawns a single atom, going downwards. * The two `\` (mirrors) deflect it onto the second column. * `"Hello, world!"` prints the required string. * `1` is a portal. It teleports the atom to the next `1` in reading order, retaining its direction (that's the one next to the `r`). * The atom still moves down, into the `;` which destroys the atom and terminates the program. The control flow for the `Twister!` code is a bit more... twisted... * Again, `D` spawns the atom. * `\` deflects it to the right, into the `1`. * Now the portal sends the atom to the next `1`. The atom hits the `o` which just changes its mass, but we can ignore that. The code wraps around so the atom hits the same `1` again, skipping down two rows. Again, we can ignore the `l`, the atom wraps around and hits the `1` again. Now there is no further `1` in the code so the atom skips all the way back to the `1` at the top. * After wrapping around the edges once more, the atom is deflected again by `\`, now going down again. * `"Twister!"` prints the required code. * `1` teleports the atom once more, past the first `;`, but there is another `;` waiting for it to terminate the program. [Answer] ## [Fission](https://github.com/C0deH4cker/Fission), 35 bytes Fission approach #3 (#4 counting the one I edited out of my first post). ``` R"Hello, " \"tri" T;L"!dlrow"/"es!w ``` [Try it online!](http://fission.tryitonline.net/#code=UiJIZWxsbywgIiBcInRyaSIKVDtMIiFkbHJvdyIvImVzIXc&input=) ``` R;H"ldor w /"er!" T"Le!ll,o""\"tsiw ``` [Try it online!](http://fission.tryitonline.net/#code=UjtIImxkb3IgdyAvImVyISIKVCJMZSFsbCxvIiJcInRzaXc&input=) ### Explanation This one is actually the simplest of the Fission solutions yet. In both programs there are two entry points: `R` creates a right-going atom and `L` a left-going atom. In either case, the `;` destroys one of them immediately. Now in the `Hello, world!` program, the atom first prints half the string with `"Hello, "`, then `\` and `/` (which are mirrors) deflect the atom onto the second line going left. `"world!"` (read in the direction of the moving atom) prints the rest of the string. `L` is now a no-op and `;` destroys this atom as well, terminating the program. The `Twister!` program is essentially the same but rotated by 180 degrees. This time, the `L` atom survives, and starts printing with `"Twist"`. The `\` and `/` again deflect it onto the other line, now going right. `"er!` prints the remainder of the string, `R` is a no-op and `;` terminates the program. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~33~~ ~~31~~ 29 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md) ### Original ``` “ɗ⁻%OḶ$“¡¦ḟṠ»Ṫ “ɗ⁻%OḶ$“¡¦ḟṠ»Ḣ ``` [Try it online.](http://jelly.tryitonline.net/#code=4oCcyZfigbslT-G4tiTigJzCocKm4bif4bmgwrvhuaoK4oCcyZfigbslT-G4tiTigJzCocKm4bif4bmgwrvhuKI&input=) ### Twisted ``` “ɗ⁻%OḶ$“¡¦ḟṠ»Ḣ “ɗ⁻%OḶ$“¡¦ḟṠ»Ṫ ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCcyZfigbslT-G4tiTigJzCocKm4bif4bmgwrvhuKIK4oCcyZfigbslT-G4tiTigJzCocKm4bif4bmgwrvhuao&input=) ### How it works In each program, each line defines a link. The last one is the main link, and it is executed when the program starts. Since there are no references to the first link, it is simply ignored. For both programs, `“ɗ⁻%OḶ$“¡¦ḟṠ»` yields the list `['Hello, world!', 'Twister!']`, using [Jelly's static dictionary compression](https://codegolf.stackexchange.com/a/70932). The only difference between the original and the twisted code is the last character of the main link. `Ḣ` selects the first string of the list, and `Ṫ` selects the last one. [Answer] # Fission, 53 ``` R"Hello, world!"; R;."..!..!!.!".\. .;T..w..i".se.t/. ``` [Try it online!](http://fission.tryitonline.net/#code=UiJIZWxsbywgd29ybGQhIjsKUjsuIi4uIS4uISEuISIuXC4KLjtULi53Li5pIi5zZS50Ly4&input=) and twisted: ``` R;.e..o..w..l..". R"T"lw!,i!os!dt\; .;H..l.. "!re"!/. ``` [Try it online!](http://fission.tryitonline.net/#code=UjsuZS4uby4udy4ubC4uIi4KUiJUImx3ISxpIW9zIWR0XDsKLjtILi5sLi4gIiFyZSIhLy4&input=) [Answer] # Japt, ~~67~~ ~~61~~ 57 bytes *Saved 6 bytes thanks to @JAtkin, 4 bytes thanks to @Ian* ``` "Tzwzizsztzezzzzzzrzzzz!"rz; "Hzezlzlzoz,z zwzorlzdz!"rz; ``` Twisted: ``` "Hzezlzlzoz,z zwzorlzdz!"rz; "Tzwzizsztzezzzzzzrzzzz!"rz; ``` Test it online: [Original](http://ethproductions.github.io/japt?v=master&code=IlR6d3ppenN6dHplenp6enp6cnp6enohInJ6OwoiSHplemx6bHpveix6IHp3em9ybHpkeiEicno7&input=), [Twisted](http://ethproductions.github.io/japt?v=master&code=Ikh6ZXpsemx6b3oseiB6d3pvcmx6ZHohInJ6OwoiVHp3eml6c3p0emV6enp6enpyenp6eiEicno7&input=) ### How it works ``` "Tzwzizsztzezzzzzzrzzzz!"rz; // Take this string and remove all "z"s. "Hzezlzlzoz,z zwzorlzdz!"rz; // Take this string and remove all "z"s. // Implicit: output *last* expression ``` [Answer] # Python, 398 ~~414 380 456~~ bytes\* Managed to update so that it is compliant with the rules, but I still hesitate to call this competitive. Since the commented lines are needed for it to run, I've included them in the byte count ~~This solution does not follow the rules, as it will print error messages in addition to the allowed output.~~ I just wanted to see if this could be done in python. It can, but it is *not* pretty. ``` print'Hello, world!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' ``` When twisted becomes ``` print'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Twister!' #rint'Hwister!' #rint'Teister!' #rint'Twlster!' #rint'Twilter!' #rint'Twisoer!' #rint'Twist,r!' #rint'Twiste !' #rint'Twisterw' #rint'Twister!o #rint'Twister!'r #rint'Twister!' l #rint'Twister!' d #rint'Twister!' ! ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 87 bytes ## Untwisted ``` main(){puts(1?"Hello, world!":"Twister!");} mai (){puts(0?"Hello, world!":"Twister!");} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oLSkWMPQXskjNScnX0ehPL8oJ0VRyUoppDyzuCS1SFFJ07qWC6hWAabWAL/a//8B "C (gcc) – Try It Online") # Twisted ``` mai (){puts(1?"Hello, world!":"Twister!");} main(){puts(0?"Hello, world!":"Twister!");} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MVNBQ7O6oLSkWMPQXskjNScnX0ehPL8oJ0VRyUoppDyzuCS1SFFJ07qWC6g2D6bWAL/a//8B "C (gcc) – Try It Online") [Answer] # Brainfuck, ~~467~~ ~~367~~ 285 bytes ## Untwisted ``` +[ [[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++[.>]<<<<.+++.------.<<-.>>>>+.>>] [[--[<++++>--->+<]>-]<<<<.<<<-.<<+.>-.+.<----.>--.>>---.[-]]] [ -[[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++[.>]<<<<.+++.------.<<-.>>>>+.>>]+[[--[<++++>--->+<]>-]<<<<.<<<-.<<+.>-.+.<----.>--.>>---.[-]]] ``` [Try it online!](https://tio.run/##rY5BCoJRCIT3neLtxTnB4EXExf8HQQQtgs7/Gu0IJSii3wxzvo778/a@PvZelmtluodnhIV3kUVNbRWO0F0DMLNEFFW9Y1gHOcxANV5JvccrjLL4StggKcxh4Giju0GkV9VFWZb/MY79FGfvDw "brainfuck – Try It Online") ## Twisted ``` [ [[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++[.>]<<<<.+++.------.<<-.>>>>+.>>] [[--[<++++>--->+<]>-]<<<<.<<<-.<<+.>-.+.<----.>--.>>---.[-]]] +[ -[[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++[.>]<<<<.+++.------.<<-.>>>>+.>>]+[[--[<++++>--->+<]>-]<<<<.<<<-.<<+.>-.+.<----.>--.>>---.[-]]] ``` [Try it online!](https://tio.run/##rY5BCoJRCIT3neLtxTnB4EXExf8HQQQtgs7/Gu0IJTqIfg6er@P@vL2vj73XSmW6h2eEhXeQRam6CkdoLgHMLBFFRfcY1kEOM1CNV1Lr8QqjLL4nbJAU5jBwbqOrQaRX1WVZLv/jO/bTO3t/AA "brainfuck – Try It Online") ]
[Question] [ The [random Fibonacci sequence](https://en.wikipedia.org/wiki/Random_Fibonacci_sequence) is defined as follows: $$ f\_n = \begin{cases} f\_{n-1}+f\_{n-2} \text{ with probability } 1/2 \\ f\_{n-1}-f\_{n-2} \text{ with probability } 1/2 \\ \end{cases} $$ $$ f\_1 = f\_2 = 1 $$ i.e. whether the next term is the sum or difference of the previous two is chosen at random, independently of previous terms. Your task is to implement this sequence. Each random realization of the sequence must use consistent values. For example, if \$f\_3 = 2\$, \$f\_4\$ must then be either \$2+1 = 3\$ or \$2-1 = 1\$. This can be thought of as the sequence "remembering" previous values. This means that [this](https://tio.run/##XY09DsIwDIXn@hRvjFWKlCKWSj0JYkBqAhnqRFYYOH1IAixMtt7P99IrP6KcSgl7ipqhN9niTrQ5D2@EFxqChyAILvaA@bpAXX6qwFK3PoVjO0GyaRnGusLW5vCNVtBkGWN/ZqY/ffrp5KMitK2Kuztz7vMYK42GpI3vTWAu5Q0) example program is invalid, as previous values in the sequence are not maintained by later values. Furthermore, you should explain how your program meets the \$1/2\$ probability requirement. As is standard for [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenges, you can perform one of three tasks: * Take a positive integer \$n\$ as input and output \$f\_n\$ * Take a positive integer \$n\$ as input and output \$f\_1, f\_2, ..., f\_n\$ * Output the sequence indefinitely with no end Again, as is standard, you may use either \$0\$ or \$1\$ indexing, but the two initial values \$f\_1 = f\_2 = 1\$ must be used. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code, in bytes, wins. ## Examples ``` n -> possible values of f_n | probabilities of values 1 -> 1 | 1 2 -> 1 | 1 3 -> 2, 0 | 1/2, 1/2 4 -> 3, 1, -1 | 1/4, 1/2, 1/4 5 -> 5, 3, 1, -1 | 1/8, 1/8, 3/8, 3/8 6 -> 8, 4, 2, 0, -2 | 1/16, 1/8, 1/4, 5/16, 1/4 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` λ₂D(‚Ω+ ``` -1 byte thanks to *@ovs*. Prints the infinite sequence. [Try it online.](https://tio.run/##yy9OTMpM/f//3O5HTU0uGo8aZp1bqf3/PwA) **Explanation:** ``` λ # Create a recursive environment to output the infinite sequence, # implicitly starting at a(0)=1 # (push a(n-1) implicitly) ₂ # Push a(n-2) (NOTE: all negative a(n) are 0, so a(-1)=0) D # Duplicate a(n-2) ( # Negate the copy: -a(n-2) ‚ # Pair them together: [a(n-2), -a(n-2)] Ω # Pop and push a random item + # And add it to the a(n-1) # (after which the infinite list is output implicitly) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 20 [bytes](https://github.com/abrudz/SBCS) ``` {⍵,(¯1*?2)⊥¯2↑⍵}/⎕⍴1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862tP@Vz/q3aqjcWi9oZa9keajrqWH1hs9apsIFKzVB6p81LvF8D9Q3f80LlOuNC5DAwA "APL (Dyalog Unicode) – Try It Online") Takes n from stdin and prints first n terms. ``` {⍵,(¯1*?2)⊥¯2↑⍵}/⎕⍴1 ⍝ Full program. Input: n { }/⎕⍴1 ⍝ Reduce a vector of n ones... ¯2↑⍵ ⍝ Last two items ([0 1] for the first iteration) (¯1*?2) ⍝ 1 or -1 ⊥ ⍝ Base convert (or polynomial evaluate), ⍝ giving f(x-2)+f(x-1) or -f(x-2)+f(x-1) with 50% chance each ⍵, ⍝ Append to the previous iteration ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ ~~13~~ 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs the `n`th term, 1-indexed. Uses JavaScript's `Math.random()` as seen [here](https://github.com/ETHproductions/japt/blob/master/src/japt-interpreter.js#L133). ``` @Zä+iÍö)Ì}g ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFrkK2nN9inMfWc&input=OA), [check the first `n` terms](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFrkK2nN9inMfWhC7A&input=OA) or [view the distributions across 10,000 runs](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=TLLGQFrkK2nN9inMfWfD%2bSD8IPHKy84rIjp7RMovTCB4MiBzIPk2fSUiw7c&input=OA) ``` @Zä+iÍö)Ì}g :Implicit input of integer U @ :Function taking an array as argument via parameter Z Zä : Consecutive pairs of Z reduced by + : Literal "+" i : Insert Í : "n" at index 2 with wrapping, resulting in "n+" : (Hooray for shortcut abuse!) ö : Random character from that string, where XnY=Y-X ) : End reduction Ì : Get last element } :End function g :Starting with [0,1], repeatedly run it through that function, : pushing the result back to it each time :Implicit output of Uth element, 0-indexed ``` To explain how the shortcut abuse works here: `Í` is Japt's shortcut for `n2<space>` which is primarily intended to be used for converting binary strings to integers (e.g., `"1000"Í="1000"n2 =8`). However, when you pass a 2 character+space shortcut like that to another method - in this case `i` - the space is used to close that method and the 2 characters are split & passed to that method as separate arguments. Which is handy here as the `i` method for strings expects one argument containing the string to be inserted and another, optional integer argument for the index it's to be inserted at. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) I'm pretty sure 10 is as good as it'll get in Jelly; I had some much longer solutions along the way. ``` 1ṫ-ḅØ-XṭƲ¡ ``` A monadic Link accepting an integer, which yields all values up to and including that 0-indexed index (i.e. \$n \to [f\_0, f\_1,\cdots, f\_n]\ |\ f\_0=f\_1=1 : f\_n = f\_{n-1} \pm f{n-2} \$). **[Try it online!](https://tio.run/##AR8A4P9qZWxsef//MeG5qy3huIXDmC1Y4bmtxrLCof///zk5 "Jelly – Try It Online")** ### How? ``` 1ṫ-ḅØ-XṭƲ¡ - Link: integer, n 1 - set the left argument to 1 ¡ - repeat this n times: Ʋ - last four links as a monad f(left): e.g. left = [1,1,2,3,5,8] ṫ- - tail from 1-based, modular index -1 [5,8] (tailing 1 from index -1 yields [1]) Ø- - signs (a nilad) [-1,1] ḅ - convert from base (vectorises) [3,13] (i.e. [5×-1¹+8×-1°, 5×1¹+8×1°]) X - random choice 3? ṭ - tack [1,1,2,3,5,8,3] ``` [Answer] # perl -061 -M5.010, 46 43 bytes ``` say$,while($,,$/)=($/,$/+$,-2*$,*(.5<rand)) ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJFpzwjMydVQ0VHR0Vf01ZDRR9Ia6vo6BppqehoaeiZ2hQl5qVoav7//y@/oCQzP6/4v66BmeF/XV9TPQNDAwA "Perl 5 – Try It Online") This prints the infinite series. Saved three bytes using a suggestion from Nahuel Fouilleul. ## How does it work? First trick is the command line switch `-061`. This sets the input record to `1` (as the ASCII value of `1` is 49, aka 61 in octal). The input record separator is `$/`. We then use two variables to keep state, `$,`, which initially is the empty string, but Perl will treat that as `0` when used as a number. `$/` is set to `1`, as discussed above. In an infinite loop, we set `$,` to `$/`, and `$/` to `$, + $/`, and then, with probability .5, subtract `2 * $,` from the latter. We then print `$,`. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 45 bytes Outputs f(n) using RandomInteger 0 or 1 ``` #&@@Nest[+##|(-1)^Random@0[[0]]#&@@#&,0|1,#]& ``` [Try it online!](https://tio.run/##FczBCsIwDADQXxECRbGy9AOEgEdBxHkrFaKGOlhb2OJB2L9HPT94hfUlhXV4sOW9gSM6yaxxC7Csd2Fzu3B9tkIYI6b0Z3Ael@AhOTtPQ9UVHeXTt0np0N5VZ7ryfZSYIyQfEJPr6HdkoYBmXw "Wolfram Language (Mathematica) – Try It Online") *-6 bytes from @att* I also tried this `46 bytes` ``` If[#>1,#0[#-1]+(-1)^RandomInteger[]#0[#-2],#]& ``` but the sequence could not "remember" the previous values [Answer] # Python 2, ~~66~~ 64 bytes Outputs the sequence infinitely. ``` from random import* a=b=1 while 1:print a;a,b=b,b+choice([-a,a]) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocSXaJtkacpVnZOakKhhaFRRl5pUoJFon6iTZJukkaSdn5Gcmp2pE6ybqJMZq/v8PAA "Python 2 – Try It Online") ### Python 2, 73 bytes Outputs the nth term of the sequence. ``` from random import* a,b=0,1 exec"a,b=b,b+choice([-a,a]);"*input() print a ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocSXqJNka6BhypVakJiuBOEk6SdrJGfmZyaka0bqJOomxmtZKWpl5BaUlGppcBUWZeSUKif//GwMA "Python 2 – Try It Online") [Answer] # [J](http://jsoftware.com/), 28 22 bytes *-6 thanks to Bubbler!* ``` 0{1&({,]#.~_1^?@2)&1 1 ``` [Try it online!](https://tio.run/##VYq7CgIxEEX7/YpLAnlIHGcsR8RFwUosbOO63YL@QiC/HmO3Frc459xPM@QXHBUeCQzt2xIuj9u1cREXSpos1Vlep3EfnUAa7mfCwCUUXbcxO/71Yd3FUt7M3f5fYvN@CAdkfWrNilAJiWB3VGOXWEzgCGFmO0XDeFOHLw "J – Try It Online") ``` 0{1&({,]#.~_1^?@2)&1 1 1& … &1 1 a verb that will apply 1&… on 1 1 y (the input) times ?@2 0 or 1 _1^ 1 or _1 ]#.~ to base, e.g. 3 5: (3* 1^1)+(5* 1^0) = 8 or (3*_1^1)+(5*_1^0) = 2 {, prepend tail of list, i.e. 5 8 or 5 2 0{ take first element ``` [Answer] # JavaScript (ES6), ~~68 67 66 53~~ 52 bytes *Saved 2 bytes thanks to @Shaggy* Returns the **n**-th term, 0-indexed. ``` f=(n,p=1,q=0)=>n?f(n-1,Math.random()<.5?p+q:p-q,p):p ``` [Try it online!](https://tio.run/##PY7BTsMwDIbvPIUPg9prGtqJCxsdN26IB5gmLbQptN2SrIkQqOpevbhF42DZv7/f@t2oL@WLrnYhMbbU41jlaITLM3HOU8q35rlCk2TCxeflJcFXFT5lp0xpT0jLh7sVCUdrN1a2QwM5pBsw8ASP3OKYoL8BmJAPKjDtBwHtn6tlV5am03Q1AnTaM@VA2sx6Otvxcs/b5PKvJjhwFdZ4e9TyaD/woHDRm4FgDYv@7b3RRZCt/vFzNMmTcsjJW86NIQKMuM1o1@7hnj8hGexL/a1LXNFkuaWIZGNrg5GAiIYDvzSMvw "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = 0-indexed input p = 1, // p = previous value q = 0 // q = penultimate value ) => // n ? // if n is not equal to 0: f( // do a recursive call: n - 1, // decrement n Math.random() // set p to either: < 0.5 ? p + q // p + q : p - q, // or p - q p // copy the previous value in q ) // end of recursive call : // else: p // return the last value ``` [Answer] # [><>](http://esolangs.org/wiki/Fish), 22 bytes ``` 1|.00<-x+40.08&:{&:}n: ``` [Try it Online!](https://tio.run/##S8sszvj/v0YhztCQq0I3xo4rRtvOKq/WSq3aSs3u/38A) This is usually a terrible language for challenges involving randomness, since the only source of randomness in ><> is `x`. But in this case things works out alright. `x` sends the instruction pointer in a random direction, so it either wraps around to itself in the y-direction, or hits a `+` or `-` with equal probability. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~58 57~~ 47 bytes ``` a,b;f(x){a=--x?f(b=x),b+=rand(x=b)%2?a:-a,x:1;} ``` [Try it online!](https://tio.run/##bc5LCoMwFIXhuau4FISE3oCJD4qSuhEnidbiwFCsg4C49jS2DhLoGX8/nJ49@945hboZiaWbkozZdiRaWor6KhdlBmKlpqloVc0U2po3u5vMCrOaDBC6JfA@FJB1mh8ko7RJ4LV4MQK5cGB3SAfo/IB35oIj4TERf4iISR4SgZDBj@UxK0KWI3AExuG0RWzL0JYY8NOXsa9Cf0Mo8HvEJ@IMqiPw290H "C (gcc) – Try It Online") * Saved 1 thanks to @ceilingcat * Saved 10 thanks to @Dominic van Essen Recursive solution which starts all the calls needed before executing them, the last call initialize values. ``` a,b; - aux variables f(x){ - function tacking an integer **n** and returning **n**th term 1 indexed. a= - return trough eax register --x?f(b=x) - call recursively before doing the job x=b - local x used as temp ,b+=rand()%2?a:-a - rnd fib step ,x - assign temp(x) to a :1;} - stop recursion and initialize a to 1 ``` [Answer] # [R](https://www.r-project.org/), ~~69~~ ... 55 bytes -1 byte thanks to Giuseppe (which led to a further -4 bytes), and -1 byte thanks to Dominic van Essen (which led to a further -1 byte) ``` F=0:1;repeat cat(" ",{F=F[2]+F[1]*(0:-1)^sample(2)}[1]) ``` [Try it online!](https://tio.run/##K/r/383WwMrQuii1IDWxRCE5sURDSUFJp9rN1i3aKFbbLdowVkvDwErXUDOuODG3ICdVw0izFiio@f8/AA "R – Try It Online") Prints the sequence indefinitely, separated by spaces. `F` is initialized as the vector `[1 1]`. At each step, draw a random permutation of the vector `[1 2]` with `sample(2)`. This means that `(0:-1)^sample(2)` is either `[0^1 (-1)^2]=[0 1]` or `[0^2 (-1)^1]=[0 -1]` (with probability 1/2 each). In both cases, `F[1]` takes the previous value of `F[2]`, and depending on the random draw, `F[2]` becomes either `F[2]+F[1]`or `F[2]-F[1]`. Finish the step by printing the first value of `F`. Note that I can make this 2 bytes shorter by using a stupid delimiter between sequence values: [Try online](https://tio.run/##K/r/383WwMrQuii1IDWxRCE5sUQjRKfazdYt2ihW2y3aMFZLw8BK11AzrjgxtyAnVcNIsxYoqPn/PwA "R – Try It Online") a 53 byte version which uses the string `TRUE` as delimiter. [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 26 bytes ``` {1,1,*+* *(-1,1).pick...*} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2lDHUEdLW0tBS0MXyNTUK8hMztbT09Oq/V@cWKmQFh1naBD7HwA "Perl 6 – Try It Online") Outputs a lazy infinite list. This is pretty much identical to the normal fibonacci program, but with `*(-1,1).pick` tacked on to randomly flip the sign of the second parameter. [Answer] # [Python 3](https://docs.python.org/3/), 77 bytes ``` from random import* f=lambda n,t=0,o=1:o if n<2else f(n-1,o,o+choice((-t,t))) ``` A recursive function which accepts \$n\$ and yields a possible \$f\_n\$. **[Try it online!](https://tio.run/##DcY7DsMgDADQvafwaFIj5SN1qMphaIIVpGAj6iWnp0zv1dtOla13blqgRTkGuVRtNj04XLF8jwhCFmbSsLwVMoN81nT9EjCKX0hJn/upeU@I3sicc722LIaMr/E/ "Python 3 – Try It Online")** Or see the [first few as sampled 10K-distributions](https://tio.run/##TY3BDoIwEETvfMXGU1dLQvVG7MkPMVhaaVJ2SVkPhvDtCMrBuUwyyXszvKVjuixLyNxDbqhdK/YDZzkWwaamf7QNkBZbabamZogB6Hr2afQQFJVGs@aT6zg6r1QpWhDxZ3OckncSmcZdCTd@kfhcFIEzEETaLp9eGQ2mwrqANUOOJCocyE401zDtjPquihBhg@9/cLUGcT7g8gE "Python 3 – Try It Online"). [Answer] # [Red](http://www.red-lang.org), 75 bytes ``` func[n][a: b: 1 loop n - 1[set[a b]reduce[b b +(a * pick[1 -1]random 2)]]a] ``` [Try it online!](https://tio.run/##ZY07DoMwEER7TjFylY8QMekocoi0qy38WUsoxLYMKMcnBJQiyrTz3kwRv9zFE1fFRJ@ezSjiEdOrCh2WMEdHkcl0sB00hpQyImpoGmUiA8tF/OyELCzOB4MTcu8epFFr3hfRHpkNL0WymGm19QVUYU0ufaRsfDNI@BQtVH2D4q3crtov@o@HVbhizMbJLvAPOEGpipc3 "Red – Try It Online") Returns the `n`th term. [Answer] # x86 machine code, 21 bytes The rdtsc version is the same size for x86-64 machine code. [`rdrand reg`](https://www.felixcloutier.com/x86/rdrand) (3 bytes) gives us a truly random number. Branching on its sign bit is cheap. By testing only 1 bit, the 50/50 probability is obviously satisfied exactly with zero bias. [`rdtsc`](https://www.felixcloutier.com/x86/rdtsc) (2 bytes) gives us a "reference cycle" timestamp whose low bits are *somewhat* random (it takes at least 25 cycles to run back-to-back RDTSC instructions, but the counter isn't running *that* much faster than we're sampling it). Testing one bit with `test al, 1` leads to significant correlation between consecutive decisions, but `test al,al` / `jnp` (branch on the parity flag, horizontal xor of the low 8 bits) gives surprisingly good results, and could be used on pre-IvyBridge machines that lack `rdrand`. Both of them golf to the same overall size in 32-bit mode. [Try it online!](https://tio.run/##fVRLb5wwEL7zK@YStVXZDSRNVC3KIS@pvfSQ5LBSFK0MDODW2FvbZNn8@e3YUBY2Dw4Yj@2Z@R6GGYN1KrYzyUy92yXZuoEfzGxQiEAXPD1ZwOhJIJpxmWMLmWqkBS7h9noZgkbbaGn8/GoZuK2t0gBoeOhePiKQUSRtQ3ik0Nf4aZKYaj1GT3ABcei/Z7GbRP7kb8zaF5jnSmIwF0qtFz6sc2syePtJ4PZmubi9XFKSB17jvWX1Gq5d16gDf9yisW5kIoRvr44LtYGUWwNMI0EwKC1nQmxBM5mrOoGKl1W3QyoLRkHdZFXXrnxxw1yqlcSSWfRR@vSpHR37pQ5Jy/Lcrzl2Br4IqEvjxsCD7zYnb9FNoaCDxQQvJcTnXr6RekkyqIf5nGpl7cUZlPwZDdgKQV6cd5RkzCDlM42wZj5oicy1xlofyPK/AB8xT6wfishl5s6/c2Yv/0hx6DR/tdm1HsGi5wFi2HBbqcZ6yrgsg2QomE0KEgVSrZGAFAVmlrCToLMYelYWoCQFmKTAmtKpAiLic8O2pieKiriFeGpDZwkiNOcTX9E8dK993zGkW4tgKqXJhcQ6VTJME44yBF7XcOypPgbTpHDyydAtq9cCa/Kec1rFsj@9wczUYEMFJ6Ql29Bu4AaKZu/YsQkxb9/3oBc6bz/0oLfbES96bR2IAfJpfCDX6czD5tJY3RDrSu7/EF0z4UCeQz4OTjMdcOLbp3SQkmVzEg@M874DT9J1ugRHKHNe7CZXoxQqZQJWxjJtg27ogNXq2V@NEM5G@DK6@eB/h30jdzcP99fwjNr8R3N4K6mYRpZvqb4wOM0CQ5a7y183kzRd/bS/a13vwWjFiRP398lC1H6PJgStsOX2M5X/AqcnM0fE5dXP3T8 "Assembly (nasm, x64, Linux) – Try It Online") NASM listing for `rdrand` version: `EAX rfib(ECX)`, callable from C with MS `__fastcall` ``` 21 rfib: ;;; 0-indexed. ecx=5 gives the n=6 test case results. 22 00000020 31C0 xor eax, eax 23 00000022 99 cdq ; EDX = fib[-1] = 0 24 00000023 40 inc eax ; fib[0] = 1 25 00000024 E30E jecxz .done ; ecx=0 : return 1 without looping 27 .loop: 28 00000026 0FC7F7 rdrand edi 29 00000029 85FF test edi, edi ; 1 byte shorter than sar reg, imm / xor / sub 2's complement bithack 30 0000002B 7902 jns .no_negate ; the top bit is fully random 31 0000002D F7DA neg edx 32 .no_negate: 33 0000002F 0FC1D0 xadd eax, edx ; like xchg + add, and same size 34 00000032 E2F2 loop .loop 35 .done: 36 00000034 C3 ret size = 0x35 - 0x20 = 0x15 = 21 bytes ``` Note that `xadd` doesn't actually save any bytes vs. `xchg eax, edx` / `add eax, edx`. It's just fun. And it's "only" 3 uops, instead of 4 total, on Intel Skylake with register operands. (Normally the instruction is only used with the `lock` prefix and a memory destination, but it fully works with registers). Test case: ``` bash loop to test the ECX=5 case $ asm-link -m32 -dn random-fib.asm && { declare -A counts; counts=(); for i in {1..10000}; do ./random-fib; ((counts[$?]++));done; for i in "${!counts[@]}"; do echo "result: $(( i > 128 ? i-256 : i )): ${counts[$i]} times";done } result: 8: 617 times result: 4: 1290 times result: 2: 2464 times result: 0: 3095 times result: -2: 2534 times ``` --- NASM listing for **`rdtsc` version**: `EBX rfib2(ECX)`. This version would be the same size in 64-bit mode; doesn't need 1-byte `inc`. RDTSC writes EAX and EDX so we can't take advantage of `cdq` in the init. ``` 2 rfib2: ; 0-index count in ECX, returns in EBX 3 00000000 31F6 xor esi, esi 4 00000002 8D5E01 lea ebx, [esi+1] ; fib[0] = 1, fib[-1] = 0 5 00000005 E30D jecxz .done 6 .loop: 7 00000007 0F31 rdtsc ; EDX:EAX = TimeStamp Counter 8 9 00000009 84C0 test al, al ; low bits are essentially random; high bits not so much 10 0000000B 7B02 jnp .no_negate 11 0000000D F7DE neg esi 12 .no_negate: 13 0000000F 0FC1F3 xadd ebx, esi 14 00000012 E2F3 loop .loop 15 .done: 16 ; returns in EBX 17 00000014 C3 ret size = 0x15 = 21 bytes ``` Test results for ECX=5: ``` result: 8: 668 times (ideal: 625) result: 4: 1217 times (ideal: 1250) result: 2: 2514 times (ideal: 2500) result: 0: 3135 times (ideal: 3125) result: -2: 2466 times (ideal: 2500) ``` vs. with `test al, 1` / `jnz` to use just the low bit of the TSC as the random value: ``` # test al,1 / jnz version: correlation between successive results. result: 8: 115 times result: 4: 79 times result: 2: 831 times result: 0: 3070 times result: -2: 5905 times ``` `test al,4` happens to work reasonably well for long runs on my Skylake CPU (i7-6700k) which ramps up to 3.9GHz at the energy\_performance\_preference=balance\_performance I'm using, vs. a reference (TSC) frequency of 4008 MHz ([more info on x86 constant-TSC stuff](https://stackoverflow.com/questions/13772567/how-to-get-the-cpu-cycle-count-in-x86-64-from-c/51907627#51907627)). I imagine there's some strange alchemy of branch prediction, and `rdtsc` itself having ~25 cycle throughput (core clocks) on Skylake (<https://uops.info>). Results are generally better distributed with `test al,al` / `jnp` though, so prefer that to take entropy from all 8 low bits. When CPU frequency is low (idle), so the TSC is not close to the same frequency as the core, taking entropy from a single bit might work even better, although the parity of the low 8 bits is probably still best. I haven't tested on a CPU with turbo disabled where non-boost core clock exactly equals the TSC reference clock. That could more easily lead to bad patterns if the `rdtsc` throughput happens to be a power of 2 or something, perhaps favouring some sequence that lets branch prediction lock on. All my testing has been with one invocation of the function per process startup. A Linux static executable is pretty efficient to start up, but is still *vastly* more expensive than calling the function in a loop from inside the process. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 38 bytes Prints the sequence indefinitely. Adapted from [J42161217's answer](https://codegolf.stackexchange.com/a/211171/98349). ``` #0[Echo@+##,RandomChoice@{#,-#}]&[0,1] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/1/ZINo1OSPfQVtZWScoMS8lP9c5Iz8zOdWhWllHV7k2Vi3aQMcw9v///wA "Wolfram Language (Mathematica) – Try It Online") Ungolfed: ``` f[a_, b_] := ( Echo[a+b]; f[a+b, RandomChoice[{a,-a}]] ); f[0, 1] ``` [Answer] # [R](https://www.r-project.org/), ~~55~~ ~~54~~ ~~53~~ ~~52~~ ~~51~~ ~~49~~ ~~48~~ 47 bytes *Edit: -1 byte, and again -1 byte thanks to Giuseppe, -1 byte thanks to AZTECCO* ``` cat(1);repeat cat(" ",T<-sign(rt(1,1))*F+(F=T)) ``` [Try it online!](https://tio.run/##K/r/PzmxRMNQ07ootSA1sUQBxFNSUNIJsdEtzkzP0ygCSuoYampquWlruNmGaGr@//8fAA "R – Try It Online") or [check the n=6 distribution](https://tio.run/##TY7BboMwEETP@Cu2itTYBVQcqRxQ3GO@gFuUAzFLWZWsW2MaVVW@nRqUSr3t7O7MPD/P8wZa7IgRmhG6iW0gxxAc2B7tO7Q0Bk/nadlWwnd0NuLvS7L6Ecm1pwEl73PO9aKTep@P9MbSB6kzrdTTIZUHUyuR3ERSi5sQm3v4lUIPbEqQZRxwwAtyANeBb7h1F4htjhtrCUb8nJAtKnhckD6G5huIQT/r6BwrYd3EwTzoaldo0TkvaT1Xu5eyKBYqNgu7LCPF@nvkVBf6ZP6LVEc4fyZu5VczTGjWuDyesu29aWt8NLRytcVVDFfHbFWvxUnM8y8). Full program taking no input. Returns full random fibonacci sequence. Program to return `n`th element using the same approach is [48 bytes](https://tio.run/##jY7NToQwFIXX06e4xsRpBWI7iSwY65InYDeZRSlFGuFW2@LEGJ8dC2ri0s3N/fvOOX5ZUAatkLLjZbCjofhQYCFYI4N9QuojFblg7LbOaC0bdsyapSTkGjrTWzSgAvQz6mgdQnSgB6OfobMhetvO67YifqKJS7VmxPe2lb8ARfZB/mXaZJx8rq7f@hcbB0BZAi1TY0YzGYzgevAKOzdBMnGotLYQzOtsUBsGN2uql1G9g0UQdyKRoSLazRjllagOXJDeeWq3c3W4LzlP6XYo18i0ZGS3/Z4wE1yc5d8hEymcby129E2Ns5GbXJFO@f7HaS99Ajq6YWmVxNkp36ZHfibL8gU). Commented: ``` cat(1); # First, print the first element (1) # (T is initialized to 1 by default, # and F is initialized to 0). repeat # Now, repeat indefinitely: cat(" ", # output " ", followed by... T<- # T, updated to equal... sign(rt(1,1)) # the sign of 1 randomization of # the t-distribution with 1 degree-of-freedom # (distribution is centred around zero, # so sign is [+1,-1] with probability [.5,.5])... *F # times F (second-last value)... +(F=T)) # plus T (last value)... # while updating F to equal T. ``` [Answer] # Dotty, 75 bytes ``` val| :Stream[Int]=1#::1#::(|zip|.tail map(_*((math.random*2).toInt*2-1)+_)) ``` [Try it online](https://scastie.scala-lang.org/I8IXodG1R0WSFd6avRN2hw) Same as below. # Scala, ~~91~~ ~~87~~ ~~85~~ 84 bytes *Saved 4 bytes thanks to corvus\_192* ``` val| :Stream[Int]=1#::1#::(|zip|.tail map{t=>t._2+t._1*((math.random*2).toInt*2-1)}) ``` [Try it online](https://scastie.scala-lang.org/b4lxtOFoQA2SfdZ77rWWKg) `|` is a `Stream` so that previous elements are remembered. To get the nth element, you can use `|(n-1)` (it's 0-indexed). To get the first n elements, use `|.take(n)` (`l.take(n).toList` to force it). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` ≔⁰θ≔¹ηFN«≔⁺η×θ⊖⊗‽²ι≔ηθ≔ιη»Iθ ``` [Try it online!](https://tio.run/##NY27CsIwGIVn8xT/@AciqINLJ7GLixTxBdI0mkAu5uYiPnuMtD3L4YNzEYpH4bmp9ZSSfjrcMQi0IwvtGahGDx8BL@5V8rXYUUakFD5ks4QGUxIqBndtZcLAoJciSitdlhP2voym@Y27yVs80L8Y6La69tV8uaKeP79kiNplPPOUMVDa1Xqs27f5AQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs the `n`th number. Explanation: ``` ≔⁰θ≔¹η ``` Start with 0 as the `i`th number and `1` as the `i+1`th number. ``` FN« ``` Loop `n` times. ``` ≔⁺η×θ⊖⊗‽²ι ``` Calculate the next number. ``` ≔ηθ≔ιη ``` Shuffle the values around. ``` »Iθ ``` Output the `n`th number. 29 bytes to output the first `n` numbers: ``` F²⊞υ¹FN⊞υ⁺§υ±¹×§υ±²⊖⊗‽²I✂υ⁰±² ``` [Try it online!](https://tio.run/##bYy9DsIwEIP3PkXGi1Qk2oGlE6JLlyoCXiBNDhopPyi5IN4@NCww4MWyP8tqlVEFaUu5hcig50zktEJuWceH5tNN/pFpzm7BCPzLhc0JjjR5ja@aZ7xLQug4b9nVOPwH@wpHVBEdekINY8iL3fwsvQ6u8qqhEdF4gpNMBBdrFNaP/e/NNirlUHZP@wY "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F²⊞υ¹ ``` Start with `1` as the first and second numbers. ``` FN ``` Loop `n` times. ``` ⊞υ⁺§υ±¹×§υ±²⊖⊗‽² ``` Calculate the next number. ``` I✂υ⁰±² ``` Output all but two of the numbers. [Answer] # [Icon](https://github.com/gtownsend/icon), 70 bytes ``` procedure n() f:=[1,1] while write(f[2])&push(f,f[1]+?[1,-1]*f[2]) end ``` [Try it online!](https://tio.run/##y0zOz/ufk5mXrVCUmJeSn/u/oCg/OTWltChVIU9DkyvNyjbaUMcwlqs8IzMnVaG8KLMkVSMt2ihWU62gtDhDI00nLdowVtseqEjXMFYLLMOVmpeCZExuYibIJAUggFiRWZUK5YPEQYoB "Icon – Try It Online") Prints the sequene indefinitely. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~56~~ ~~53~~ 52 bytes *Edit: -3 bytes thanks to AZTECCO, -1 byte thanks to ceilingcat* ``` x;y;r(n){for(x=y=1;--n;)x=~-(rand()&2)*y+(y=x);x=y;} ``` [Try it online!](https://tio.run/##LY7LCsIwEEX3/YpBUGZai49FNzF/4qbGVFPMpKYptEj99ZiAq7lwzxmuqh9KxTiLRXhk@nTO4ywXeRJ1zYJm@a3Rt3xH2p2pXCpc5EwiEWKNhxLG1g4vDW4KwxQgycCyAWzCE/RLW80BXAf5gbPQmZvjVikDo35PmpUmKA@FSZBtDSN9ChgzCxiM1XgkEgXk2sjmn/p088Y@Lewv8tSIvqqyCINPfYeb7f3Km71Hk@y1WGP8AQ "C (gcc) – Try It Online") Non-recursive answer in C. Function that returns `n`th (one-based) element of random fibonacci sequence. ``` x;y; # x & y hold last and last-but-one elements; r(n){ # n is index of element we're looking for; for(x=y=1; # initialise first two elements to 1; --n;) # now loop by decreasing n until it is zero, x= # update x to become equal to: ~-(rand()&2)*y # plus-or-minus y... +(y=x) # plus x # (while updating y to equal the current x). ;x=y;} # after looping, return y. ``` **Note**: Following some discussion in the comments here and in [AZTECCO's answer](https://codegolf.stackexchange.com/questions/211166/implement-the-random-fibonacci-sequence/211181#211181), a consensus was reached that it is not necessary to initialize the random seed *within a function*. Of course, that this means that the *calling program* should do so, or the function may give the same sequence of pseudo-random output every time the calling program is run. A [74 byte](https://tio.run/##JY7BboMwEETvfMUqUipvXJRQKTlku82P9EId05iENTUg2Yr4dhfa08zojUZjym9jco6U6E5BCT7vWl@q8xBquaoXQWp8UJETVyQly8eBMLL6o7h9u6RzmVCrxBEpcqQ573cw1F3/sOCnsZ9GWAZA@AjqNN7APmxnZQTfwLrhO2jcl5faGAeD/ZmsGIuw2xduKXW1E4XPAtbg@Ej/rl10fdXygdr36kSt1msL@rDgRm2210/ZvAblEGku5px/AQ) variant of the function can itself initialize the random seed itself (but only on first call, so that subsequent calls from the same program run give different output). [Answer] # [Bash](https://www.gnu.org/software/bash/), 65 bytes ``` a=1;b=1;while :;do echo $a;t=$b;:$[b+=$RANDOM&1?$a:-$a];a=$t;done ``` [Try it online!](https://tio.run/##DYoxC8IwFAZ3f8UHPkSRgnVsCCK4quAqDi/2xVQkKUmkg/rbY4aD4zjDyRW7XOFTWLfKVCY3vASd6gPk7gKIVdZkVEdXs9Z02Z8O5@Oi3RF3DfFNsaZcZy/lN7P4wgn3aLYbzPF8p4zkwgQ7xKo1su@RchhhQ4RwEgSLKKNwHvyj/AE "Bash – Try It Online") Endlessly outputs the latest and greatest version of the sequence. [Answer] # [Swift](https://swift.org/), 77 bytes ``` sequence(first:(1,1)){a,b in(b,.random() ?a+b:a-b)}.lazy.forEach{print($0.0)} ``` Outputs until `Int` overflow. [Answer] # [Lua](https://www.lua.org/), 81 bytes ``` t={1,1}for i=1,...do t[i]=t[i]or t[i-1]+t[i-2]*(math.random(2)*2-3)print(t[i])end ``` [Try it online!](https://tio.run/##yylN/J@bWJKhV5SYl5KfW5yamqKRX6xXkpmbqqGp@b/EttpQx7A2Lb9IIdPWUEdPTy8lX6EkOjPWFkQARYGUrmGsNogyitXSQDJKw0hTy0jXWLOgKDOvRAOkXDM1L@X///@GBgA "Lua – Try It Online") Takes number of members to be printed as an argument. Replace `...` with `1/0` to print sequence forever at const of one byte. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` ‡₍+-℅d11Ḟ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigKHigo0rLeKEhWQxMeG4niIsIiIsIjYiXQ==) Prints the infinite list. ``` Ḟ # Create an infinite list from... 11 # [1, 1] ‡ d # And a function taking two arguments... ₍ ℅ # Choose randomly from... +- # sum of previous two, difference of previous two ``` [Answer] # Excel VBA, ~~49~~ 48 bytes Saved 1 byte thanks to [Taylor Raine](https://codegolf.stackexchange.com/questions/211166/implement-the-random-fibonacci-sequence/255269?noredirect=1#comment570230_255269) and using the VBA native function instead of evaluating the Excel function. ``` b=1:Do:c=a+b*IIf(Rnd()<.5,1,-1):a=b:b=c:?a:Loop ``` Code is input and run in the immediate window. Output is the infinite sequence. Here's what it looks like if it was formatted into a subroutine instead: ``` b = 1 Do c = a + b * IIf(Rnd() < .5,1,-1) a = b b = c Debug.Print a Loop ``` The [Rnd() function](https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/rnd-function) outputs a value in the range [0,1) hence the `<.5` check. I out the 6th term in the sequence 1,000 times (since that's an example in the question) and found the following distribution of values: | **Value** | **Count** | **Percent** | | --- | --- | --- | | -8 | 45 | 4.5% | | -4 | 48 | 4.8% | | -2 | 252 | 25.2% | | 0 | 322 | 32.2% | | 2 | 264 | 26.4% | | 4 | 47 | 4.7% | | 8 | 22 | 2.2% | ]
[Question] [ The prospect of this challenge is: * If your program is run normally, all of the code in the speech marks (`"` - double quotes) should be printed. * If your program is wrapped in double quotes (in turn inverting the speech marks), the code that is normally not in quotes should be printed. E.g: Let's say you have the following code: ``` fancyStuff("myCode"); "I like".isGreat(); ``` If I run it, I would expect an output of: ``` myCode I like ``` However, if I wrapped it in quotes, I would get: ``` "fancyStuff("myCode"); "I like".isGreat();" ``` When this code is run, the expected output would be: ``` fancyStuff( ); .isGreat(); ``` Obviously, the above example is not a functional response in any language. Your job is to write the code that performs in this way. # Rules * Standard loopholes apply. * The printed values, in both quoted and unquoted forms, must be non-empty, or consist solely of whitespace. This also means that all programs must include at least one set of quotes. * However, trailing/preceeding whitespace is allowed. * No looking at your own code, required file names, etc. * Unmatched quotes are disallowed * If there are multiple strings, they can either be printed as newlines (as in the example), or in some other *human-readable* way - no arrays or objects * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] # [Python 2](https://docs.python.org/2/), 20 bytes ``` print";print'print'" ``` -7 bytes thanks to tsh [Try it online!](https://tio.run/##K6gsycjPM/qfnJ@SqmCroKSkFPO/oCgzr0TJGkypQ0il/0AZLqgiEBVtpWsYq6CsUJSam1@WqlBSlJiZk5mXrpCXWg6kU7m4UitSkzVAKjUhTHUldW0QVxvI0PwPAA "Python 2 – Try It Online") --- # Old answer: # [Python 2](https://docs.python.org/2/), 27 bytes ``` '';print";print 2*"'';print ``` [Try it online!](https://tio.run/##K6gsycjPM/qfnJ@SqmCroKSkFPNfXd26oCgzr0QJQikYaSnBhP4DFXBB1YKoaCtdw1gFZYWi1Nz8slSFkqLEzJzMvHSFvNRyIJ3KxZVakZqsAVKpCWGqK6lrg7jaQIbmfwA "Python 2 – Try It Online") ### Train of thought behind this answer: Begin with a simple print, because we need to print *something*. ``` print"a" ``` We also need to print something in the inverted case, ie. have a print inside quotes. ``` print"print" ``` The non-inverted case is pretty good at this point. Let's focus on the inverted case. We now start with the string `print`, which can't be followed immediately by a print statement. Let's fix this with a semicolon. ``` print";print" ``` Good stuff. Except, the inverted code doesn't actually print anything. We'll need to print the `print` at the start, because it ends up in quotes, but also print whatever comes after the second quote, because it ends up in quotes too. The obvious way around this is to append `print` and multiply the last string by 2. ``` print";print 2*"print ``` Now the inverted code works fine, though we have to be wary of the fact that the section before the first quote and the section after the second quote need to be kept the same throughout future changes. As for the non-inverted code, it throws a syntax error - once again, we need to introduce a semicolon to separate expressions. ``` ;print";print 2*";print ``` Python doesn't really like the look of that lone semicolon, so we must satisfy the snake's hunger with two of the same no-op expression, inserted before the first semicolon and the last semicolon. Most expressions will work fine in the first case, but in the second case it must follow `print";print 2*"` in the non-inverted code without breaking anything. We can use `''`, which simply gets concatenated with the prior string. ``` '';print";print 2*"'';print ``` [Answer] # CSS, 66 bytes ``` body:after{content:"{}body:after{content:'body:after{content:}'}"} ``` ``` "body:after{content:"{}body:after{content:'body:after{content:}'}"}" ``` Not so much questions may be solved by CSS... [Answer] # [HQ9+](https://esolangs.org/wiki/HQ9+)[see notes below], 1016 bytes ``` "Hello World"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""Hello World ``` Use the implementation on <https://esolangs.org/w/index.php?title=HQ9%2B&oldid=59995> and compile the interpreter with MinGW GCC 5.3.0 on Windows. I'm not sure if it works with other version of compiler, since an undefined behavior of C is required to terminate the program. The buffer is 1000 bytes long. And source code greater than 1000 bytes do the trick. I'm not sure how these happened. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` "A"§ ``` Outputs concatenated without separator. [Try it online](https://tio.run/##yy9OTMpM/f9fyVHp0PL//wE) or [try it online with surrounding quotes](https://tio.run/##yy9OTMpM/f9fSclR6dBypf//AQ). **Explanation:** ``` # Program without surrounding quotes will output string "A" "A" # Push "A" to the stack § # Cast it to a string # (output the top of the stack implicitly as result) # Program with surrounding quotes will output string "§" "" # Push an empty string to the stack A # Push the alphabet to the stack: "abcdefghijklmnopqrstuvwxyz" "§" # Push "§" to the stack # (output the top of the stack implicitly as result) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 4 bytes ``` "P"s ``` Try it [unquoted](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=IlAicw) or [quoted](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=IiJQInMi) `P` is the Japt variable for the empty string and the `s` method slices a string - without any arguments, it does nothing. --- Or, ever so slightly less trivial: ``` "+"u ``` Try it [unquoted](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=IisidQ) or [quoted](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=IiIrInUi) The first one uppercases `+` and the second one appends `u` to an empty string. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~113~~ ~~112~~ ~~107~~ ~~70~~ 64 bytes ``` Write(".f();static void f(this string s){Write(s+')'+';');}//"); ``` *Saved 5 bytes thanks to @negative seven* [Unquoted](https://tio.run/##Sy7WTS7O/P8/vCizJFVDSS9NQ9O6uCSxJDNZoSw/M0UhTaMkI7NYobikKDMvXaFYsxqisFhbXVNdW91aXdO6Vl9fSdP6/38A "C# (Visual C# Interactive Compiler) – Try It Online") and [Quoted](https://tio.run/##Sy7WTS7O/P9fKbwosyRVQ0kvTUPTurgksSQzWaEsPzNFIU2jJCOzWKG4pCgzL12hWLMaorBYW11TXVvdWl3TulZfX0nTWun/fwA "C# (Visual C# Interactive Compiler) – Try It Online") After a while, I realized that my solution was too complicated. The newest program shown here simply hides the rest of the program in a comment to avoid errors when wrapped in quotes. When wrapped in quotes, `Write(` is passed onto an extension method, which prints it along with `);`. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 11 bytes ``` say ".say~" ``` [Try it online!](https://tio.run/##K0gtyjH7/784sVJBSQ9I1in9/w8A "Perl 6 – Try It Online") Prints `.say~` with a trailing newline. Seems too easy. Am I missing something? When [wrapped in quotes](https://tio.run/##K0gtyjH7/1@pOLFSQUkPSNYpKf3/DwA "Perl 6 – Try It Online"), produces `say` with a space and trailing newline. [Answer] # [Foo](https://esolangs.org/wiki/Foo), 4 bytes ``` "P"s ``` [Try it online!](https://tio.run/##S8vP//9fKUCp@P9/AA "Foo – Try It Online") [Also works in Japt.](https://codegolf.stackexchange.com/a/187171/25180) ### 5 bytes (UTF-8) ``` "A"§ ``` [Try it online!](https://tio.run/##S8vP//9fyVHp0PL//wE "Foo – Try It Online") [Also works in 05AB1E.](https://codegolf.stackexchange.com/a/187166/25180) ### 9 bytes ``` "!""$;"$; ``` [Try it online!](https://tio.run/##S8vP//9fSVFJScUaiP7/BwA "Foo – Try It Online") [Also works in Runic Enchantments.](https://codegolf.stackexchange.com/a/187165/25180) ### 11 bytes ``` say ".say~" ``` [Try it online!](https://tio.run/##S8vP//@/OLFSQUkPSNYp/f8PAA "Foo – Try It Online") [Also works in Perl 6.](https://codegolf.stackexchange.com/a/187190/25180) ### 20 bytes ``` print";print'print'" ``` [Try it online!](https://tio.run/##S8vP//@/oCgzr0TJGkypQ0il//8B "Foo – Try It Online") [Also works in Python 2.](https://codegolf.stackexchange.com/a/187168/25180) ### 69 bytes ``` body::after{content:"{}body::after{content:'body::after{content:}'}"} ``` [Try it online!](https://tio.run/##S8vP//8/KT@l0soqMa0ktag6OT@vJDWvxEqpuhabsDo2wVr1WqXa//8B "Foo – Try It Online") [Also works in CSS.](https://codegolf.stackexchange.com/a/187194/25180) Hmm... Foo is a highly adaptable language. [Answer] ## [><>](https://esolangs.org/wiki/Fish), ~~18~~ 9 bytes ``` "|o<"r>o| ``` *-9 bytes thanks to Jo King* [Try it online!](https://tio.run/##S8sszvj/X6km30apyC6/5v9/AA) ([quoted](https://tio.run/##S8sszvj/X0mpJt9Gqcguv0bp/38A)) ### Explanation ``` "|o<"r>o| "|o<" Pushes the quoted characters onto the stack r Reverses the stack >o| Outputs all characters on stack & errors ``` ``` ""|o<"r>o|" "" No-op | Reverses the IP direction "r>o|" Pushes the quoted characters onto the stack (backwards) |o< Outputs all characters on stack & errors ``` [Answer] # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 12 bytes ``` <@,k4"<@,k4" ``` [Unquoted](https://tio.run/##S0pNK81LT9W1tPj/38ZBJ9tECUL@/w8A "Befunge-98 (FBBI) – Try It Online") [Quoted](https://tio.run/##S0pNK81LT9W1tPj/X8nGQSfbBEoq/f8PAA "Befunge-98 (FBBI) – Try It Online") Both cases print `<@,k4`. Either (or both) of the `@`s can be replaced with `q` instead. [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 9 bytes ``` "!""$;"$; ``` [Try it online!](https://tio.run/##KyrNy0z@/19JUUlJxRqI/v8HAA "Runic Enchantments – Try It Online") and [`""!""$;"$;"`](https://tio.run/##KyrNy0z@/19JSVFJScUahP7/BwA) From Kevin Cruijssen, who essentially fixed my first attempt utilizing what I did in my second. Going down the "fungoids never have unmatched quotes" rule-bending "there's something about this that shouldn't be OK" route, alluded to in my own comment: ## 7 bytes ``` 0".""$; ``` [Try it online!](https://tio.run/##KyrNy0z@/99ASU9JScX6/38A "Runic Enchantments – Try It Online") and [`"0".""$;"`](https://tio.run/##KyrNy0z@/1/JQElPSUnFWun/fwA) Under normal circumstances, this program executes as `0".""$;0".""$;` pushing an integer `0`, then the string `.`, concatenates `$;0`, NOP, concatenates an empty string, prints top-of-stack (the string `.$;0`) and terminates. Wrapping it in quotes produces `"0".""$;"` which pushes a string-`0`, NOPs, concatenates an empty string, prints top-of-stack, and terminates (rendering the previously un-printed integer `0` in string form). The last `"` is left unexecuted (and not part of the *original* program anyway). Fungoids don't have string literals, they have a command that toggles "read own source as a string" mode and some form of "instruction pointer has reached the source boundary" rule (usually edge-wrap), so the same source-code-positional-byte acts as both "begin string" and "end string" instruction, creating a string literal of that entire row/column (excluding the `"` itself). [Answer] ## Haskell, 31 bytes ``` putStr"#1;(#)=const<$>putStr--" ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzv6C0JLikSEnZ0FpDWdM2OT@vuMRGxQ4iqqur9D83MTPPNu3/v@S0nMT04v@6yQUFAA "Haskell – Try It Online") Or enclosed in quotes: [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX6mgtCS4pEhJ2dBaQ1nTNjk/r7jERsUOIqqrq6T0PzcxM8827f@/5LScxPTi/7rJBQUA "Haskell – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 4 bytes ``` ";"q ``` [Try it online!](https://tio.run/##y00syUjPz0n7/1/JWqnw/38A "MathGolf – Try It Online") The `;` and `q` can be exchanged for a lot of different commands, including no-ops. [Answer] # [Ruby](https://www.ruby-lang.org/), 8 bytes ``` p";p'p'" ``` [Try it online!](https://tio.run/##KypNqvz/v0DJukC9QF3p/38A "Ruby – Try It Online") Wraps output in quotes, which may be illegal. # [Ruby](https://www.ruby-lang.org/), 17 bytes ``` puts";puts'puts'" ``` [Try it online!](https://tio.run/##KypNqvz/v6C0pFjJGkSqgwml//8B "Ruby – Try It Online") [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 25 bytes ``` print("-print`print()`-") ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEtLshMSS3Kzc/LTq38/7@gKDOvRENJF0wnQHiaCbpKmv//AwA "JavaScript (SpiderMonkey) – Try It Online") ``` "print("-print`print()`-")" ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEtLshMSS3Kzc/LTq38/1@poCgzr0RDSRdMJ0B4mgm6SppK//8DAA "JavaScript (SpiderMonkey) – Try It Online") Trivial but functional. [Answer] # [Japt](https://github.com/ETHproductions/japt), 4 bytes ``` "P"u ``` Unquoted, it converts the string `P` to uppercase. Quoted, it prints `u`. [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=IlAidQ) # [Japt](https://github.com/ETHproductions/japt), 4 bytes ``` "P"w ``` Unquoted, it reverses the string `P`. Quoted, it prints `w`. [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=IlAidw) [Answer] # R, 16 bytes ``` ";print(";");" ``` Note that the above code is not wrapped in the additional quotation marks and has both leading and trailing spaces. [Try it (non-wrapped version)](https://tio.run/##K/r/X0HJuqAoM69EQ8laSdNaSeH/fwA) [Answer] # AppleScript, 9 bytes ``` return"&" ``` ### Explained: ``` return"&" -- returns "&" ``` Quoted: ``` "return"&"" -- implied return of the string "return" concatenated with "" ``` ]
[Question] [ Here is an example of an input of **monoliths**. There are 4 in this example. ``` _ | | _ | | _ | | | | | | | | _ _| |_| |___| |____| |_ ``` The first monolith is 4 units high, the second is 2, the third is 3, and the last is 1. # The task Your program should output the heights of the monoliths in order from left to right. The output format can be in any sort of list or array. # Notes * The input can be taken as any dimensional string, list of strings, or list of characters. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **lowest bytes wins**. * You are to assume that monoliths always have the same width, and are always at least 1 `_` away from another. * They can come in any height, and in any quantity. # I/O ``` _ | | _ | | _ | | | | | | | | _ _| |_| |___| |____| |_ >> [4,2,3,1] _ | | _ | | | | _ | | _ _| |_| |__| |_| |_ >> [2,1,4,1] _ _ _ | |_| |_| |_____ >> [1,1,1] ____________________ >> undefined behavior _ | | | | | | | | | | | | | | | | | | | | | | >> [11] _ _ _ _ _ _ | | _ | | _ | | _ | | _ | | | |_| |_| |_| |_| |_| |_| |_| |_| |_| | >> [1,2,1,2,1,2,1,2,1,2] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), (8?) 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ỵ=”|Sḟ0m2 ``` A monadic link accepting a list of characters as specified and returning a list of integers. Note: **8 bytes** if a list of strings, one per line, was really intended to be an allowed input format - just remove the `Ỵ`. **[Try it online!](https://tio.run/##y0rNyan8///h7i22jxrm1gQ/3DHfINfo////ChAQzwWhaxRqqMNCMRIigGETVB1cbzyyOEQLTGM8F5AVHx8PImE4HkqCKQA "Jelly – Try It Online")** ### How? ``` Ỵ=”|Sḟ0m2 - Link: list of characters, s Ỵ - split at newlines ”| - literal '|' = - equals (vectorises) S - sum (vectorises, hence counts the number of '|' in every column) ḟ0 - filter out zeros (only keep the results from the sides of the towers) m2 - modulo index with 2 (keep only the left side measurements) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ỴṚZi€”_ỊÐḟ’ ``` [Try it online!](https://tio.run/##y0rNyan8///h7i0Pd86KynzUtOZRw9z4h7u7Dk94uGP@o4aZ////V1CI51KoAUIogPHiQRwgC8KFKIApi@eKBzLBOB5KgikA "Jelly – Try It Online") [Answer] # JavaScript (ES6), ~~79~~ 78 bytes *-1 byte thanks to @Shaggy* ``` a=>a.map((b,i)=>b.replace(/_/g,(_,j)=>o[j]=a.length-i-1),o=[])&&o.filter(x=>x) ``` Takes input as an array of strings. ## Test Snippet ``` f= a=>a.map((b,i)=>b.replace(/_/g,(_,j)=>o[j]=a.length-i-1),o=[])&&o.filter(x=>x) I.value=" _\n | |\n _ | |\n | | _ | | _\n_| |_| |__| |_| |_" ``` ``` <textarea id=I rows=7 cols=30></textarea><br><button onclick="O.value=`[${f(I.value.split`\n`).join`, `}]`">Run</button> <input id=O disabled> ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` |Rζ'_δkJ®0‚K ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/JkjP6fAO9fhzW7K9Dq0zeNQwy/v/fwWFeC6FGiCEAhgvHsQBsiBciAKYsniueCATjOOhJJgCAA "05AB1E – Try It Online") `ζ` has been replaced by `.Bø` on TIO since it hasn't been pulled there yet. [Answer] # Dyalog APL, 29 bytes ``` {0~⍨↑+/(⌈/⍴¨⍵)↑¨(⍳≢⍵)×⌽⍵='_'} ``` Run with `⎕IO←0`. [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qn/6O2CQb/04BktUHdo94Vj9omautrPOrp0H/Uu@XQike9WzWBQodWaDzq3fyocxGIf3j6o569QIaterx67f//2UC96goK8eoK6go1QAgFCH48iAtkwQQgimBKQerigRwwjoeSYEqd61HvqmyuNIVsLqgdCiiGwwHUbIhFqHaBxSAMFHtgDIQdAA) **How?** `⌽⍵='_'` - where `⍵` is `'_'`, top lines first `×`- multiply by ... `(⍳≢⍵)` - the range of `⍵` (zero indexed) `↑¨` - for each line, pad with zeros by ... `(⌈/⍴¨⍵)` - the maximal length `↑+/` - sum the rows zipped and flatten `0~⍨` - removes zeros [Answer] # C++, ~~171~~ 169 bytes ``` #import<vector> #import<iostream> int f(std::vector<std::string>s){for(int a,j,i=0,k=s.size()-1;a=s[k][i];++i)if(a==32){for(j=0;(a=s[k-++j][i])-95;);std::cout<<j<<" ";}} ``` [Try it online!](https://tio.run/##pVDbboMwDH3nK6zsJREwdZv2sCbhR7oKIQZVqLiIpH0Y49tZLqQrlVpprSPHdnLic@K86@Jdnk/Tk6i7tlfsWOSq7ZPA16KVqi@yOglEo6DEUn2t1w7EbK6vRbNLJBnKtscGlEVVJPgq2nP5LMV3gUn8QjMuN/vtRmxpGAoiSpxx/vbqHlV8RbEFxGFYGRCJP94poZYgbw@KsYoxBIiO42Qo6kw0mARDANquSQJVSAUcBgSQogjBj16z/dWpKXXmDxzIQw0u1YX1dN5tQCO17CU2NGdagTFAnw1y12caYEF@spnbCVlqsWcuWejwyb81mH7OdT/fZf7UHd1ck4f2e6boJ3U1mvmlcBrhjXgxhht@qTQYp18) # C++ (GCC), 150 bytes *Thanks to @aschepler!* ``` #import<vector> #import<iostream> int f(auto s){for(int a,j,i=0,k=s.size()-1;a=s[k][i];++i)if(a==32){for(j=0;(a=s[k-++j][i])-95;);std::cout<<j<<" ";}} ``` [Try it online!](https://tio.run/##pVDLboMwELzzFSv3Yguo0lY9NLb5kTRCiEJkIjDCTg@lfDv1A6dJpEZqsmi9D493hyn7Pt2V5Tw/iLaXg2afVanlkEWhFlLpoSraLBKdhhoXBy1BkbGWA7adImkSwVfJnqtHJb4qTNInWnC12W83YkvjWBBhXnH@8uwfNXxFsQOkcdxYEEnfXimhSn@s16U8aMYaxhAgOk2zXdEWosMkGiMw5lCeJHO5oSe6XQa6Uho4jAggRwmCb/Mt9lvntjRZaHhQgFpcbgrn@XK6gCbqttfYrjnhCowBeu@Qvz7hAGfLj7bs9kTOubieT854hOTfHOw872ZemLL81A3T/JC7zltUDEr9Ga1@ORwlvBIvZLjil0yjaf4B) [Answer] # [Python 2](https://docs.python.org/2/), 75 bytes ``` lambda s:[x.index('_')for x in map(None,*s.split('\n')[::-1])if'_'in x[1:]] ``` [Try it online!](https://tio.run/##bZDBDoIwDIbve4rGyzaDRDwukUfwBYAsGCAukUFcDxjl2bFsoBzs0q3t/n5L1z/x1tnThLVDB2fIOOcAmsGb1mJrpueEopAGwSrTTFPoXS@7PwgXMeahsOF9zeMCeQv3lRBswGvwg86y4Gy9XB7/ifQfo3LBWEMD59O9bK9VCU5lQ2xsVQ@Cay6b7gEDGAtt2YtLZ@to72LX3w0KnlsuM6UOSSFNQ2JSDVmiimKau3Du8v@p/KD9w1iE3es4AqQpvJIxt7uYlG2JAiNoBEo5fQA "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 bytes ``` z ·mb'_ fw0 ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=eiC3bWInXyBmdzA=&input=IiAgXwogfCB8ICAgICAgICBfCiB8IHwgIF8gICAgfCB8CiB8IHwgfCB8ICAgfCB8ICAgICBfCl98IHxffCB8X19ffCB8X19fX3wgfF8i) ### Explanation ``` z ·mb'_ fw0 : Implicit input z : Rotate the input clockwise. This puts the "floor" against the left side. · : Split the 2D string into lines. m : Replace each column (now row) X with b'_ : the index of '_' in X (0-indexed). This gives us the output list, with : 0's and -1's mixed in representing the columns that are not monoliths. f : Take only the items X where w0 : max(X, 0) is truthy. Since 0 is falsy, this removes anything <= 0. : Implicit: output result of last expression ``` [Answer] ## PowerShell, 133 bytes ``` param($s)$r=,0*($l=($s=$s-replace'\| \|',' 1 ')[0].Length);1..$s.Count|%{$z=$_-1;0..($l-1)|%{$r[$_]+=(''+$s[$z][$_]-as[int])}};$r-ne0 ``` Looks like it's not very competitive; it does a regex replace to turn the towers into columns of 1, makes an array of 0 the length of the input string, then steps through the lines adding up the 1s. Tests ready to run: ``` $s1 = @' _ | | _ | | _ | | | | | | | | _ _| |_| |___| |____| |_ '@-split"`r?`n" $s2 = @' _ | | | | | | | | | | | | | | | | | | | | | | '@-split"`r?`n" $s3 = @' _ | | _ | | | | _ | | _ _| |_| |__| |_| |_ '@-split"`r?`n" $s4 = @' _ _ _ | |_| |_| |_____ '@-split"`r?`n" $s5 = @' _ _ _ _ _ _ | | _ | | _ | | _ | | _ | | | |_| |_| |_| |_| |_| |_| |_| |_| |_| | '@-split"`r?`n" ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~48~~ 38 bytes ``` ^ ¶ {`(¶.*)*¶_(.*¶)+ $#2 $& }`¶. ¶ G`. ``` [Try it online!](https://tio.run/##K0otycxL/P8/juvQNq7qBI1D2/S0NLUObYvX0AOSmtpcKspGCipqXLUJQBmQGvcEvf//FeK5ahRqFKAAyokHsYEsMA8iDVMEVhEPwvFQEkwBAA "Retina – Try It Online") Link includes first example. Explanation: A line is prefixed which will collect the results. As each column is repeatedly deleted in turn, those that contains a `_` above ground level have the the number of remaining lines in the column counted. Finally the now blank lines are deleted. Edit: Saved 10 bytes thanks to inspriation from @FryAmTheEggman. [Answer] # Java 8 - ~~229 Bytes~~ 213 Bytes ``` s->{Map<Integer,Integer> m=new TreeMap();String[] l=s.split("\n");for(int i=0,j=-1;i<l.length-1;++i){s=l[i];while((j=s.indexOf("_",j+1))>=0){m.put(j,i);}}for(int i:m.values()){System.out.print(l.length-i-1+",");}} ``` [Try it online!](https://tio.run/##tVFNU4MwEL3zK3Y4JUIz7VVK7x6qh3qrHSbStA2GwJDQ6iC/HZdPtZ56MLBk92Xz8l5I@JnPslzoZP/WyDTPCgsJYqy0UrG7wHFixY2BNZe6cgCktqI48FjAI7Q1wDmTe4jJxhZSH4HTANEaA19juZUxdmoIoTGzVbXm@fIBKY6i8Id5BWmoxQWeCyFwmdCgp9ruQIWGmVxJS9wX7dLgkBUEBYAM534SzhaBXCqmhD7aExaeJ2llQrWVu@BykkoQkiCB1Hvx/nQgbuT6ibegdBXOaZWyvLQk8SUN6nrivU/ZmatSGEJptfkwVqQsKy3LUZAl01lytvBc3223NmgXneblq0Kng@HuSlK8MTJZ4cXR0MrpbgxAs5g4LkCEtjxMPvEZxi8oahHMfmB967hh6I6w7iIavt3kOvgz@hOvvShNprVRDFxLmMa3gl7RH1Ed3CfXgsbkNjEtXx8938gyuLuVbSL5vwRGSbXj1M0X "Java (OpenJDK 8) – Try It Online") **Ungolfed:** ``` public static void foo(String input) { Map<Integer, Integer> map = new TreeMap(); // Raw types!! String[] lines = input.split("\n"); for (int i = 0, j = -1; i < lines.length - 1; ++i) { input = lines[i]; while ((j = input.indexOf("_", j + 1)) >= 0) { map.put(j, i); } } for(int i:map.values()) { System.out.print(lines.length - i - 1 + ","); } } ``` Woo, first post. Any help improving it would be great. ~~I *know* I can get rid of that `indexOf` written twice.~~ Knew it! I toyed with the idea of changing the types in the map from Integer to Long but I think that's a dead end. --- I know there is [a much, much better Java 8 solution already](https://codegolf.stackexchange.com/a/129130/61976), but that takes `char[][]` as input which I think is easier to work with in this case than String. [Answer] # Java 8, ~~133~~ ~~117~~ ~~116~~ 114 bytes ``` a->{for(int l=a.length-1,i=0,j;i<a[0].length;i++)if(a[l][i]<33){for(j=0;a[j][i]<33;j++);System.out.print(l-j+",");}} ``` Takes the input as a ~~`String[]`~~ `char[][]` (← saves 16 bytes). -2 bytes in exchange for less readable output thanks to *@OlivierGrégoire* by changing `print(l-j+",")` to `println(l-j)`. **Explanation:** [Try it here.](https://tio.run/##7VXBcoIwEL33K3a8CCMwdjxG@gf14pFhMimiJo3BgWing/l2mmJ6qQipCqdm2GGyeXm7mzwWRo7Ez/apYKv3KuGkKOCVUFE@AVAh03xNkhQW31OAY0ZXkDjJluRRHMVAXKT9Spt@CkkkTWABAkKoiP9SrrPc0RzAQxLwVGzk1n/2aDj1GKJzEk1j40V0MnHp2iERjyMaz2czt97LwikiETM@xDQKLT8Lme6C7CCDfa7JuXC4z1ykVIXOeewPb1znYdKpU97pgpyl1PhNnfW5GhEkjkg/4KecshzD2KsNm/djTHl1vItxjncyuJMFF@4pXhOvfV5/i3eNtysetoiHf/E0zXGH/3JNqVrnAA3iG/nXxshsapEZ3HXl7cduY@1H3s2Pe@S3kWk75n6ZtGN6kQXuuP5b5NBVatuX0EOZuDHMrdbjLdic6D9mIMwQPRjf@ft9zHp7X8TW/W/I9cc1n@HmRlLqSVVf) ``` a->{ // Method with character 2D-array parameter and no return-type for(int l=a.length-1, // Length of the 2D char-array - 1 i=0,j; // Index-integers i<a[0].length;i++) // Loop (1) over the 2D char-array if(a[l][i]<33){ // If the base of the current column is a space for(j=0;a[j][i]<33; // Loop (2) over the cells in this column as long as // we encounter spaces (from top to bottom) j++ // And increase `j` every time, to go down the column ); // End of loop (2) System.out.println(l-j); // Print the amount of rows - `j` } // End of if-block // End of loop (1) (implicit / single-line body) } // End of method ``` [Answer] # Haskell, ~~75~~ 74 bytes ``` import Data.List;f=filter(>0).map(length.fst.span(<'!').reverse).transpose ``` The input is expected as a list of strings (rowwise). [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 14 bytes ``` 0~⍨⍳∘≢+.×'_'=⊖ ``` with `⎕IO←0` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qn/6O2CQb/00Bk3aPeFY96Nz/qmPGoc5G23uHp6vHqto@6poHUAeXTFID0/0dtE9UVFOIVMIE6ENYAIRTEY0qAhZCUwCQgQjCJeLBEPJALxvFQEkypAwA "APL (Dyalog Classic) – Try It Online") --- This function train equivalent to `{((⍳≢⍵)+.×('_'=⊖⍵))~0}` [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` &nxG2\&fx-Xz ``` Input is a char matrix, with `;` as row separator. [Try it online!](https://tio.run/##y00syfn/Xy2vwt0oRi2tQjei6v//aHWFeAUsQN1aQV2hBgihIB6LDFgMSQ1cBiIGk4mHyMQD@WAcDyXBlHosAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmfEOH1Xy2vwssoRi2tQjei6r@6rq6ueoRLyP9odYV4BSxA3VpBXaEGCKEgHosMWAxJDVwGIgaTiYfIxAP5YBwPJcGUeiwX0AkIEI9sFhzALYEIx2MVhrsJzkC1FsZQgNgZD7UtHmEETAXUfVDHxasrWIOkoCoopeAejkfzMiYN9lY8wkN4aHTn48HqsQA). [Answer] # C#, ~~150~~ ~~144~~ 137 bytes ``` using System.Linq;a=>a.SelectMany((i,h)=>i.Select((c,w)=>new{c,w,d=a.Length-1-h}).Where(o=>o.c==95&o.d>0)).OrderBy(o=>o.w).Select(o=>o.d) ``` Full/Formatted version: ``` using System; using System.Collections.Generic; using System.Linq; class P { static void Main() { Func<char[][], IEnumerable<int>> f = a => a.SelectMany((i, h) => i.Select((c, w) => new { c, w, d = a.Length - 1 - h }) .Where(o => o.c == 95 & o.d > 0)) .OrderBy(o => o.w) .Select(o => o.d); Console.WriteLine(string.Concat(f(new char[][] { " _ ".ToArray(), " | | _ ".ToArray(), " | | _ | | ".ToArray(), " | | | | | | _ ".ToArray(), "_| |_| |__| |___| |_".ToArray(), }))); Console.ReadLine(); } } ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` ooYssqtO>) ``` Input is a padded character matrix. [Try it online!](https://tio.run/##y00syfn/Pz8/sri4sMTfTvP//2h1hXgFLEDdWkFdoQYIoSAeiwxYDEkNXAYiBpOJh8jEA/lgHA8lwZR6LAA "MATL – Try It Online") [Answer] # Mathematica, 48 47 39 bytes ``` Last/@(Reverse@Most@#~Position~"_")& ``` [Try it online!](https://tio.run/##ZVDLCsIwELznK0IEURCKepRCxKtCUW@1hKCtDWhTkkUQxF@veUppEzY7O@zshH1yqMVVd12V7rmGhM7Oije6lbqkx/JVKpMPUgOdfDOpBQjZfAkj8@kGIZC7mqutUvydZvx2FPcackvxKxhhQk@gRHM/tQ8B@WRBLg0pCicsNSzTnjwnCGOG8MfccGLFbGGQL31DbGOIGeiChdclUgST1cgE9@b/jxvvnfpmjvGgZxTB32Q9NLEyHyg2h89ZUZeZpQCmuDLhNoHQkFqNqXX3Aw "Mathics – Try It Online") `Function` which expects a rectangular array of characters. Takes `Most` of the array (all but the last row), `Reverse`s it, then takes the `Transpose`\*, then finds all `Position`s at which the `_` character appears. The relevant heights are the `Last` elements of each `Position`. \* `` is the `3` byte private use character [`U+F3C7`](https://unicode-table.com/en/search/?q=U%2BF3C7) which represents [`\[Transpose]`](http://reference.wolfram.com/language/ref/character/Transpose.html.en) in Mathematica. Note that this doesn't work in [Mathics](http://mathics.github.io/), so the [TIO link](https://tio.run/##ZVDLCsIwELznK0IEURCKepRCxKtCUW@1hKCtDWhTkkUQxF@veUppEzY7O@zshH1yqMVVd12V7rmGhM7Oije6lbqkx/JVKpMPUgOdfDOpBQjZfAkj8@kGIZC7mqutUvydZvx2FPcackvxKxhhQk@gRHM/tQ8B@WRBLg0pCicsNSzTnjwnCGOG8MfccGLFbGGQL31DbGOIGeiChdclUgST1cgE9@b/jxvvnfpmjvGgZxTB32Q9NLEyHyg2h89ZUZeZpQCmuDLhNoHQkFqNqXX3Aw "Mathics – Try It Online") just uses `Transpose`. [Answer] # [Ruby](https://www.ruby-lang.org/), 82 bytes Takes in a list of lines. ``` ->l{l.map! &:chars;(l.pop.zip(*l).map{|s|s.join.count ?|}-[i=0]).select{0<1&i+=1}} ``` [Try it online!](https://tio.run/##TYlBDoIwEEX3nKImhoCGCWyV6kGQNFhLLBnbhsJCac9eURJxkj//vZl@vD5DSy8hO@GE8GjMhsQHfm96e0wQjDbwkibZYfr5Tc46C52WCrge1UDOzmeVpHmdghUo@DDlZRHLPS28D4a01baEXjQ3QKmErQNZh0UrO@JmY/82r@WyQMTm/uYHbw "Ruby – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 9 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` I{ _WH╥?O ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=SSU3QiUyMF9XSCV1MjU2NSUzRk8_) Takes input as an array of arrays of strings (characters). Explanation: ``` I rotate the array clockwise { for each element _ push "_" W get its index in the array (0 if not found, 1 if its the ground, >1 if its what we need) H decrease that ╥ palindromize (duplicates the number, if it's <0, then errors and pushes 0, if =0, pushes 0, if >0, then pushes the number palindromized (always truthy)) ? if that, then T output in a new line the original decreased index ``` [Answer] ## JavaScript (ES6), 108 104 88 bytes Saved 16 bytes thanks to @JustinMariner ``` i=>i.map((s,h)=>{while(t=r.exec(s))m[t.index]=i.length-h-1},m=[],r=/_/g)&&m.filter(e=>e) ``` Input taken as an array of strings ``` let input = [ ' _', ' | | _', ' | | _ _ | |', ' | | | | | | | | _', '_| |_| |_| |__| |____| |_' ] let anonymousFunction = i=>i.map((s,h)=>{while(t=r.exec(s))m[t.index]=i.length-h-1},m=[],r=/_/g)&&m.filter(e=>e) console.log(anonymousFunction(input)) ``` [Answer] ## CJam, ~~15~~ 14 bytes 1 byte saved thanks to @BusinessCat ``` {W%z'_f#{0>},} ``` This is a block that takes an array of strings on the stack and outputs an array. ### Explanation: ``` W% e# Reverse z e# Zip '_f# e# Get the index of '_' in each element (-1 if not found) {0>}, e# Filter where positive ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~18~~ 17 bytes 15 bytes of code, +2 for `-rp` flags. ``` _FI_@?'_MRVgZDs ``` Takes input from stdin. [Try it online!](https://tio.run/##K8gs@P8/3s0z3sFePd43KCw9yqX4/38FhXguhRoghAIYLx7EAbIgXIgCmLJ4rnggE4zjoSSY@q9bVAAA "Pip – Try It Online") ### Explanation ``` g is list of lines from stdin (-r flag); s is space RVg Reverse g ZDs Zip (transpose), filling gaps with a default char of space M Map this function: _@?'_ Index of _ in each line (or nil if it doesn't appear) _FI Filter, keeping only the truthy (nonzero, non-nil) values Autoprint in repr format (-p flag) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~19~~ ~~15~~ 14 bytes ``` f>T0mx_d\_.tQd ``` [Test it online!](https://pyth.herokuapp.com/?code=f%3ET0mx_d%5C_.tQd&input=%5B%22++_%22%2C%22+%7C+%7C++++++++_%22%2C%22+%7C+%7C++_++++%7C+%7C%22%2C%22+%7C+%7C+%7C+%7C+++%7C+%7C+++++_%22%2C%22_%7C+%7C_%7C+%7C___%7C+%7C____%7C+%7C_%22%5D&debug=0) The input is a list of lines. **Explanations** ``` .tQd # Transpose, pad with spaces mx_d\_ # For each line, reverse it, find the position of "_" (-1 if not found) f>T0 # Filter on positions greater than zero ``` [Answer] # Octave, 31 bytes ``` @(a)(s=sum(a>95))(s>0)(1:2:end) ``` Takes a 2D array of chars as input. [Verify all test cases!](https://tio.run/##pVLdDoIgFL6Opzh3wF22dZHO1ns0x5ji1kxtod2Yz25Hj@Bsy5tg55ePj49BnTb6ZYbhIrQUNrZtKfT5dJRYnPdSBOEhNFUmhzzWlY1YY2yTamssxNCxK@MAiqN/45zHUquxxMw1COSgI05hMZma/RR4wogaVpx@zJTEvz5i6lGyoncJT8YNjPhHLBliHWLW4ZETkNb/8olnA1ik/4yc9Lk7bcQv7RtGGvoIr5/XTyjwDYMQqrY0d@EfVjK2y272IfKlB13RS8nwIwwf "Octave – Try It Online") [Answer] # [Perl 6](http://perl6.org/), 65 bytes ``` {m:ex/^^(\N+)_([\N*\n]+:)/.sort(*[0].chars).map(+*[1].comb(" "))} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OtcqtUI/Lk4jxk9bM14jOsZPKyYvVttKU1@vOL@oREMr2iBWLzkjsahYUy83sUBDWyvaECiQn5ukocSlpKlZ@99aoTixUiFNozintKgAqDQ/t0DzvwIIxCso4Ke5QMwaICRAcwFxPBEYAA "Perl 6 – Try It Online") * `m:exhaustive/^^(\N+)_([\N*\n]+:)/` searches the input string for all underscores, and returns a match object for each, where the first capturing parentheses contain the preceding part of the line on which the underscore is found, and the second capturing parentheses contain the entire rest of the string. The rest of the string must contain at least one newline, so we don't count the underscores at ground level. The `:exhaustive` flag allows these matches to overlap. * `.sort(*[0].chars)` sorts these match objects by the number of characters in the part of the line preceding each underscore. This orders them left-to-right. * `.map(+*[1].comb("\n"))` maps each match object to the number of newline characters in the part of the input string trailing each underscore--that is, the height. The `\n` is an actual newline character, saving one byte. [Answer] # [Python 2](https://docs.python.org/2/), 58 bytes ``` lambda l:[s.index('_')+1for s in zip(*l[-2::-1])if'_'in s] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHHKrpYLzMvJbVCQz1eXVPbMC2/SKFYITNPoSqzQEMrJ1rXyMpK1zBWMzMNKA8ULo79X1CUmVeikabBFa2ugADxEEpdh0sBSbgGCJGE47EKg3nxMOF4qHA8kAfGcIZ6LJem5n8A "Python 2 – Try It Online") Taking input as list of strings. [Answer] # PHP, 119 bytes ``` function($s){$r=array_map(null,...$s);foreach($r as$k=>&$v)if($v=array_count_values($v)['|'])echo($v+$r[$k+2]=0)." ";}; ``` Let's break this down! Our input here is a 2D array of chars. ``` $r=array_map(null,...$s) // Neat little snippet to transpose the array foreach($r as$k=>&$v) // Loop through the array, grabbing each row of our 2D array (which is now each column of the monolith) if($v=array_count_values($v)['|']) // Count the number of '|' characters in the column (which is the height of our monolith), and if it's greater than 0 (truthy in PHP)... echo($v+$r[$k+2]=0)." "; // Output that number, and simultaneously set the row 2 indices down to null (to remove duplicate values) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes input as an array of lines. ``` Õ®x2 èSÃf ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=tw&code=1a54MiDoU8Nm&input=IiAgXwogfCB8ICAgICAgICBfCiB8IHwgIF8gICAgfCB8CiB8IHwgfCB8ICAgfCB8ICAgICBfCl98IHxffCB8X19ffCB8X19fX3wgfF8i) (header splits input string to array) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=tw&code=1a54MiDoU8Nm&input=WwoiICBfCiB8IHwgICAgICAgIF8KIHwgfCAgXyAgICB8IHwKIHwgfCB8IHwgICB8IHwgICAgIF8KX3wgfF98IHxfX198IHxfX19ffCB8XyIKCiIgICAgICAgICAgIF8KICAgICAgICAgIHwgfAogIF8gICAgICAgfCB8CiB8IHwgIF8gICB8IHwgIF8KX3wgfF98IHxfX3wgfF98IHxfIgoKCiIgXyAgIF8gICBfIAp8IHxffCB8X3wgfF9fX19fIgoKIl9fX19fX19fX19fX19fX19fX19fIgoKIiBfCnwgfAp8IHwKfCB8CnwgfAp8IHwKfCB8CnwgfAp8IHwKfCB8CnwgfAp8IHwiCgoiICAgICBfICAgICAgIF8gICAgICAgXyAgICAgICBfICAgICAgIF8KIF8gIHwgfCAgXyAgfCB8ICBfICB8IHwgIF8gIHwgfCAgXyAgfCB8CnwgfF98IHxffCB8X3wgfF98IHxffCB8X3wgfF98IHxffCB8X3wgfCAiCl0tbVI) ``` Õ®x2 èSÃf :Implicit input of array Õ :Transpose ® :Map x2 : Trim left è : Count S : Spaces à :End map f :Filter ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ṖZ=”_UT€F ``` [Try it online!](https://tio.run/##y0rNyan8///hzmlRto8a5saHhjxqWuP2/@HuLYfbNf//j@ZSUlJSUIjnUqgBQiiA8eJBHCALwoUogCmL54oHMsE4HkqCKaBxOhAzFZCMgwOwaRCDkc0Gi0AYSObCGHAzQaogmAsmB7Ua1V6Y@ThpLhATZjEeGsUaPBhoMVcsAA "Jelly – Try It Online") Unfortunately, [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/129112/66833) is still shorter, as I assume input is a list of lines, so don't count the `Ỵ`. However, I reckon this is an interesting enough approach to post ## How it works ``` ṖZ=”_UT€F - Main link. Takes a list of lines L on the left Ṗ - Remove the last line Z - Transpose =”_ - Check each character for equality with "_" U - Reverse each row € - For each row T - Yield the indices of 1 F - Flatten ``` ]
[Question] [ We'll call the consecutive distance rating of an integer sequence the sum of the distances between consecutive integers. Consider `2 9 3 6 8 1`. ``` 2 9 3 6 8 1 <----5----> <-2-> <--3--> ``` \$2\$ and \$1\$ are consecutive integers, and their distance apart in the sequence is \$5\$. \$2\$ and \$3\$ are consecutive integers, and their distance apart in the sequence is \$2\$. \$9\$ and \$8\$ are consecutive integers, and their distance apart in the sequence is \$3\$. The consecutive distance rating is the sum of these distances: \$10\$. ## Challenge Given a possibly empty list of positive, **unique** integers, find its consecutive distance rating. ## Format You must accept a list of integers and output an integer in [any reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). ## Rules * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes (in each language) wins. ## Test cases ``` [] -> 0 [33] -> 0 [65 57 78 32 81 19 50 24 85 3 97 43 10 73] -> 0 [1 2] -> 1 [2 1] -> 1 [1 2 3] -> 2 [1 3 2] -> 3 [31 63 53 56 96 62 73 25 54 55 64] -> 26 [54 64 52 39 36 98 32 87 95 12 40 79 41 13 53 35 48 42 33 75] -> 67 [94 66 18 57 58 54 93 53 19 16 55 22 51 8 67 20 17 56 21 59] -> 107 ``` [Answer] # [Python 2](https://docs.python.org/2/), 60 bytes ``` lambda l:sum(abs(l.index(x)-l.index(x+(x+1in l)))for x in l) ``` [Try it online!](https://tio.run/##PU9bbsIwEPzPKeaPWAWU9dtI6UXSqgoliEjGRCEUevp0kxTklTW7Hs/Mdr/D6ZLkeCw/xlif94cacXe9nfN6f83jtk2H5pE/xOYF37ioTYhCiOOlxwNzM95PbWxAuwxxnVCir@9fbepuQy621y62Q77C5h0rwYSy@akjq/dNF@vvhl9Waz6C31LZpiFPjLqeEY55FOv5Lss0Vp@TRpFVSj2RNTAOzkNJeAIFmAJSwxsoBAetQAXci0@QM6SskqAn5CkWipwa9U9S7ESwCobLIlhYyVqQbKphDKxePtms4oHlGesEKOYuiRyCAUlozhCgOeAspgy0h2aygjOzhnVZFVjDgvy0kvGTR5jpvBXZyU9KGIJnMmQBclMqSTBhWaRwfw "Python 2 – Try It Online") [Answer] # [J](http://jsoftware.com/), 22 bytes ``` [:+/&,|@(#\-/#\)*1=-/~ ``` [Try it online!](https://tio.run/##TY1Bb4JAFITv/opJN3F3FRberghsoCFt4qnpwat4UTFqoiSVQxuIf51upQcO7zDzvpm59C@KH5FbcHgIYd35Cu/rj1W/sfNg6nWFYKUfsFLOKPeDRy8nn28Kw1NktmDOb1VX@K2VZakg5hq7n6a6DyAxdVYFEw6YiYxJ@Xi1Z7UFHEhP0MP3rf7id1yr5lQf5KTan2pQiBxHaKQwWCIBDf5gcz5WxozVMkIUI05gNBICpYhC6AWSyDWlMRbmrzz@z9AzQ25orLWb638B "J – Try It Online") Consider `f 2 9 3 6 8 1`: * `-/~` Table of differences: ``` 0 _7 _1 _4 _6 1 7 0 6 3 1 8 1 _6 0 _3 _5 2 4 _3 3 0 _2 5 6 _1 5 2 0 7 _1 _8 _2 _5 _7 0 ``` * `1=` Where are they 1? ``` 0 0 0 0 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` * `|@(#\-/#\)` Table of absolute value of index differences: ``` 0 1 2 3 4 5 1 0 1 2 3 4 2 1 0 1 2 3 3 2 1 0 1 2 4 3 2 1 0 1 5 4 3 2 1 0 ``` * `*` Elementwise product of those tables: ``` 0 0 0 0 0 5 0 0 0 0 3 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` * `[:+/&,` Sum of that table flattened: ``` 10 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` iⱮ‘aạ¥JS ``` [Try it online!](https://tio.run/##JY4xSkVBDEX7WcVZwksyycxswVYQLC0slL8BO7FxC7YWdiL4sRDtdCXvbeSZ@UJIbuDm5N5eHw53@36zvb9t909X69fzz8vZ@b5@f6yfx@3h9eL3MfvlvhezEo43WseULsjAF7TSHWM0qiELzYqgRZE5mZvlbkIYnhWMIDSNaBIr7kQtKSJ1XgwsPf9vGsMRpSZ4UPPrCWJO7dQ0G83LyNtA@sznfTLHyZYRJSZfFRc60dAFaTOFCj7@AA "Jelly – Try It Online") -1 byte thanks to Unrelated String! ## How it Works ``` iⱮ‘aạ¥JS - Main link. Takes a list L on the left ‘ - Increment all elements in L Ɱ - Over each incremented element: i - Get its 1-based index in L, or 0 if not present Call this list of indices I J - Indices of L; [1, 2, 3, ..., len(L)] ¥ - Last 2 links as a dyad f(I, J): ạ - Absolute difference, element wise, between I and J a - And; Where there are non-zeroes in I, replace the value with corresponding difference S - Sum ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` ãʒÆ}kÆÄO ``` [Try it online!](https://tio.run/##LY4xTgQxDEWvwgFeMbZjJ@7pOcBoCpAoEAUFNR3aA3AFzsAJpqPgSoMzu1KUxPb7/v/t/fHp5fn4@7k/9u/fr/3y8bpf9s@H41jXjbvVbN7heKcPTBmCJL6gjeEY2WmGLPSTFXQ@itwqbm27DkwIw@sEGYSWDi2DhjvRJlP/qLKkiRV2Ne6kI0orq6RVjnOPOW3QCja6T3mWPJAxQ/uYm/MkK7fEdFHFhUF0dEH6zKKC57b9Aw "05AB1E – Try It Online") ``` ã # all pairs of integers from the input ʒ } # keep those where the following results in 1: Æ # reduce by subtraction k # for each integer in each pair get the index in the input list Æ # reduce each pair of indices by subtraction Ä # take absolute value O # sum all distances ``` [Answer] # [Red](http://www.red-lang.org), ~~88~~ 77 bytes ``` func[b][s: 0 forall b[s: s + absolute offset? b any[find head b 1 + b/1 b]]s] ``` [Try it online!](https://tio.run/##RZBNboQwDIX3nOJptlVVnMT5mUV7h26jLGAgmpEYqIBZ9PTUobQTRYrtfHrP9tx322ffxVTl85Yf4yW2KS5n1MjT3AwD2pIteEHTLtPwWHtMOS/9@oEWzfgd823scO2bTnISrH0jtCktaROBvrlcpR4ryBGP/dH6CCyDHZyHVvAECuAaysAzNIKD0aAa7g8nqCNSoGcNz3/9T2iC1WC5FsHCKpGBEj8DZlhzYJJaqYhGgBbytxWHwCAFI@YBRjrbpTTDeBiBNRwfCkEULMiXSdgX/bDDMgzZ4qUUmOBhHVQNcqUjReCQqhS/5tu4It6noazv9Pp@Qi7b234A "Red – Try It Online") Uses [@xnor's method](https://codegolf.stackexchange.com/a/229732/75681) - don't forget to upvote it! [Answer] # [R](https://www.r-project.org/), 47 bytes ``` sum(abs(seq(a<-scan())-(b=match(a+1,a,0)))*!!b) ``` [Try it online!](https://tio.run/##hY/NasMwEITvfYqJe5HSDXglrX4gfYu@gGMcashfLYceSp/dlYOb0kMpCDSMZj7tDtMe2w3211M79ueT6jU@kNvm9MvVPR5fujzifWgul26Y8vWoml1WuXtTzXYzF5TWG7V7PjZj@6qaJ6aGaq31erXa6enzYa9aZSiRJU@RWOubs1zWLsILSaAQyRqKTJxIajKOopRiCuQscU3hO85kFmXuyOLRz7tdEnkcxnOvusOs8uXQj6qyDG8h5XgkD28QLIxAHETgXUUVqrLCX/2S8yVqYBNsQURYgxiQBGzgaoQEx@DbH1bgIlwJWwT5D50K2oMjJEDiPFG6UTiB/TydMRBGhA8wNTjMOxiGpDt5@gI "R – Try It Online") with test wrapper stolen from [pajonk's answer](https://codegolf.stackexchange.com/a/229743/95126) stolen from [Kirill L's answer](https://codegolf.stackexchange.com/a/229746/95126) [Answer] # [R](https://www.r-project.org/), 45 bytes ``` sum(abs(seq(a<-scan())-match(a+1,a)),na.rm=T) ``` [Try it online!](https://tio.run/##hY/NasMwEITvfYrBvUh0U7ySVj@QvkVeQDUONSROYjv0UPrsrhzclB5KQaBhNPPtapj32G6wv/bN1J161Wl8YGxy/8vVHR537TjhfcjnczvM4/Wo8uuoxvai8nazFJTWm2OemjeVn5iy1tTn5@H4stPz58NeNcpQIkueIrHWN2e9rF2FF5JAIZI1FJk4kdRkHEUpxRTIWeKawnecyazK3JHFo593uybGaZhOnWoPixrPh25SlWV4CynHI3l4g2BhBOIgAu8qqlBp/We/5HyJGtgEWxAR1iAGJAEbuBohwTH4NsMKXIQrYYsg/6FTQXtwhARIXDZKNwonsF@2MwbCiPABpgaH5Q@GIelOnr8A "R – Try It Online") Merged solutions: mine and [@Dominic's](https://codegolf.stackexchange.com/a/229751/55372). --- Previous solution: ### [R](https://www.r-project.org/), 48 bytes ``` x=scan();`*`=match;sum(abs(x*x-(x+1)*x),na.rm=T) ``` [Try it online!](https://tio.run/##hY9basMwEEX/u4qL@yOlk@KRNHqQZhdZQNyQUEPiBNuhhtK1u3JwU/pRCgINV2fOjNrxgJclDtdm19fnRtUaH@h2VfMr1TUeN/uux3tbXS77dhzWE6P0arvYrk9Vv3tbddeTql47NSyGpRqeWC8GTU313J7WGz1@PhzUThlKZMlTJNb6lsyXtXPhhSRQiGQNRSZOJCUZR1FyYwrkLHFJ4RtnMnNl7sqc0c@7nYmub/tzrfbHqeoux7pXhWV4C8nHI3l4g2BhBOIgAu8KKlBo/Wd/5nxGDWyCzYoIaxADkoANXImQ4Bh8m2EFLsJl2CLIf@qU1R4cIQESp43SzcIJ7KftjIEwInyAKcFh@oNhSLqbxy8 "R – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 60 bytes ``` n=>n.map((e,i)=>z+=(j=n.indexOf(e+1))+1?j>i?j-i:i-j:0,z=0)|z ``` [Try it online!](https://tio.run/##PZHNcpswFIX3PMXZGcY2QRKSUDoii0637a4b4pmojpxCCXiAZBq3fXb3CmzPaHF19Z1zf9S4dzfuh/o4bbv@2Z8P9tzZsktf3TGO/aZObHla27ixXVp3z/73t0Ps1yxJ1uyhKeuHZlvf19vmPtucbJb8PZ33fTdOmPw4fXajH2HxVO2wLZFFlRDXSElIDV1AcBQMzEBm4DkKCQGjkQuwDPrGM/A5ZFHFwa4hZbEgPFzEBRJUiUEJSDoKRkFx8gKnojmkhMoXkYoqSijKkY@BIHbpSMNIMI6cejDIqcHZTEjkBXKCBbScPZSOKkMeCqwII8ki1DAzTlMxFepxDslQEAyegenQFWeQZhkk00/peGzrKV49dqvkU7Ts8Jf/@O7at3mHt33O/@Jb2BK@vaqCyyoh4U2SHvrhi9v/vKB/LpZuGNwH2fl319JTle3SwR9bt/fxHe5eNlhtZp9A961P2/4lPsSzKoG1Fl/fXn/4IUjZLoD/kvN/ "JavaScript (Node.js) – Try It Online") [Answer] # [R](https://www.r-project.org/), 48 bytes ``` `?`=diff;sum(abs(?o<-order(x<-scan()))*!1<?x[o]) ``` [Try it online!](https://tio.run/##VZDdSsQwEIXvfYqKN4mcQifJ5Acr@xLeibBrt116Ybu0XVwQn71Oa1WEXExOznxzJsPcZGWeNZeumtq@U63OPrKxOnT/VN1md0/1OGXvw@F8rod5v9s/HtumeRgvb@rwOqpdX@b9cKwHdS3zpV9pre9vqdxdn/sXPX/eNKpSBgkWHhGktShtN9Un6VkvlbJ2KzyDA0KENYgESuACxiGytKcAZ0EFwo@dYLbKbOBVw9@7/XVYgrdgOR7JwxvBwMg8B2Z4t9nk6kURhiQW53eUgMQgAyfDE5wkW1GW4SKcmC0Cb4QkBA@KyyYcF35azbIM@WWWMWCSr/ABpgCFJZEhcNJ6/gI "R – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~50~~ 48 bytes ``` ->a{r=-1;a.sum{((a.index(a[r+=1]+1)||r)-r).abs}} ``` [Try it online!](https://tio.run/##FYtBCsMgFESv8pdKVPpttZVgLyIuDG2gi5ZiCLQkObuZLIYH82bqPPzbGJu@l6VGzX0x0/xehCjm9Xk8f6Kk2kXOHct1rVJXacowbVv70phSuCjyXhHfFLkrchBdOIMIBwTeOUXWgqwIE4@pPUEdF2iL2oWc2w4 "Ruby – Try It Online") Thanks @ovs for -2 bytes. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes ``` sᶠ{↻h₂-ȧ1&b}ˢcl ``` [Try it online!](https://tio.run/##NU87CsJAEL3KYGG1grPfbKMHCSmMhRYBQQsRsbEI2HkEsbG10UIvIHiK5CLxjUmK2fm99@Ztvp7Nl7titdDNfjug0YQG22ld3uvjsXqdDtXj3Gyq52Vfl@8lZqPPjYf54XudF02Tppmi1Bh5vVPkgqKQKDJaUcKKOGI2VqQteuyNogiIRWaMw58InJYMDvc9oF1puq1B7dE4CQ8dhNeiAYCcxgmH7K2gpfMyESWYMMLojcFBBJJRW3GBvRWznbrBzgJrhYs@OFGMoggVTtpvuqS9GTuWfJV960GD6aAIiAdU4wiH1rbG2MUs@wE "Brachylog – Try It Online") ``` sᶠ Find every substring of the input. { }ˢ Keep only those for which ȧ the absolute value of - the difference of ↻h₂ the first and last elements 1 is 1, &b and remove their first elements. c Concatenate them, l and output their combined length. ``` [Answer] # [Julia 1.0](http://julialang.org/), 63 55 bytes Inspired by the answer of xnor Improved version, thanks @MarcMush: ``` !x=sum(abs,[(I=indexin)(i,x)-I(i+(i+1∈x),x) for i=x]) ``` [Try it online!](https://tio.run/##TVBLasMwFFzXp3gJWUhUgepre@HucwbjRUpSUEnVkNigI@ScvYg7L1ZIQULvjWbmjfQ1neJe53le5e46fYv9x1X1YtfFdDjmmKSIKsvtTsRXLP17u2UJgD5/LhS7PMg5pvM0Ukf9Lo39oCo@rC1F8Ip8rahuFFmjqNGKdAvsTZFx6HFvFbWgOJwacP3QgmpKCaX@h0Lz7OyTZtEG9J53gC12MGwJDifBRI8zuCJgIDDIlohlWfSIikwtyBq141y4dxy/DLC4c@A61qKvfTFt2RRGulne7ptlcluE/H4dliQGYg9TUAKoBnN0vYQ3gH07VEN1/2uKie5fXb2cLzGNpyTWm0jbd9qIlYhSrmV1TIf5Dw "Julia 1.0 – Try It Online") First version: ``` !x=sum(abs.([indexin(i,x)-indexin(i+(i+1 in x),x) for i in x])) ``` [Try it online!](https://tio.run/##TVBLbsIwFFw3p3ggFrYwVf1NvKD7niHKggqQXFGDIJFy@3QeMVAplj3jmXnj/AyntNPjNC3G7W34Fbvv27toU94fxpRFUqPcPMEan6aUaZTg6Xi@UrrDTsop5cvQ05bar9y3nap4s7Ycglfka0V1o8gaRY1WpCO4D0XGAePeKoqQOOwadP3wQmrKEU79j4XnhexLZgEDsOcVEIsVDEdCw00w0WMPrhiYCExyJGpZNj2qolOEWOPsuBfuHdcvAyzuHLSOvcC1L6GRQxGkm/ntvpknx2Lk9@swNzEwe4RCEiA1mKPrubwB7WNXddXzf99/dfV2uabcn7JYrhJtPmklFiJJuZTVIe@nPw "Julia 1.0 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` I↨¹Eθ↔↨¹⁻⌕Aθ⊕ικ ``` [Try it online!](https://tio.run/##HYvNCsIwEIRfJcctRLAm6Q@eqiB4KAgeSw@xDRhMU21SXz9OXfjYGWZmeOplmLVL6bZYH@msQ6T7OlGr3/ThrHmE2a3R0EkHQ631a6CL9WPj3BZf/bCYyfhoRrJZxtkL5Nn/jil1nZKcFUAdOBM1KDirK3z4qoRW6EPLPWclcpnDC/SBQCbRldsWvlR9n3Zf9wM "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array E Map over elements ι Current value ⊕ Incremented ⌕A Find all (i.e. at most one) matches θ In input array ⁻ Vectorised subtract κ Current index ↨¹ Take the sum ↔ Take the absolute value ↨¹ Take the sum I Cast to string Implicitly print ``` Note that base 1 conversion is used to sum as this works on empty lists. [Answer] # [Red](http://www.red-lang.org), 129 bytes ``` func[a][s: 0 b: sort copy a while[b/2][s: s + either b/2 - b/1 = 1[absolute(index? find a b/2)- index? find a b/1][0]b: next b]s] ``` [Try it online!](https://tio.run/##bVDLasMwELznK@bYUkK9klYPQ@k/9Gp0sB2FGIIdbIemX@@u3FPtgJDQ7MzO7I7ptHylUxUP7dBPqS2xnO99W9WxmkoUh6bENIwz2uH2g/rwfemuqWre1Vqe8IbUzZc0QiAc5SZ8gKq6mYbrfU4vXX9Kj0@c5UWdSa9HbDGKVRHFp0@PGU2c4nIbuz5b5kCQaP//Wm8Ry2AH56EVPIECuIAy8AyN4GA0qIDb6QhqCynQExaeSPVerAlWg@VYBAurxBNKwhkww5otX3ArJWkfoEXyN4BDYJCCkcgBRuZZe2qG8TBC1nC8bRWklQX5vAj22TGsKtkF2eyuFJjgYR1UAXI5oyJw2G9AwsAKleLyCw "Red – Try It Online") sorts the array, and adds the index difference to `s` if pair of elements has an absolute difference of 1. Not sure how to shorten the reuse of `index? find`, but I think it can be shortened. `abs` alias for `absolute` is not available, even in version 0.6.4. [Answer] # Excel, 52 bytes ``` =LET(x,A:A,SUM(IFERROR(ABS(ROW(x)-XMATCH(x-1,x)),))) ``` Input numbers in column A. For each number x in column A look for x-1. If found add the difference in rows between x and x-1. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `s`, 13 bytes ``` ›vḟv›ƛ&›[¥ε|0 ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=%E2%80%BAv%E1%B8%9Fv%E2%80%BA%C6%9B%26%E2%80%BA%5B%C2%A5%CE%B5%7C0&inputs=%5B2%2C9%2C3%2C6%2C8%2C1%5D&header=&footer=) A port of the jelly answer, and I think the best I'm gonna get. ## Attempted port of Jonas, 21 bytes ``` Ẋƛ÷ε1=;?Lɾƛ?Lɾ-ȧ;f*∑½ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E1%BA%8A%C6%9B%C3%B7%CE%B51%3D%3B%3FL%C9%BE%C6%9B%3FL%C9%BE-%C8%A7%3Bf*%E2%88%91%C2%BD&inputs=%5B2%2C9%2C3%2C6%2C8%2C1%5D&header=&footer=) ## Old version, 23 bytes ``` L²(⁰Ẋni÷ε1=[n6ḋ÷ε&+])¥½ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=L%C2%B2%28%E2%81%B0%E1%BA%8Ani%C3%B7%CE%B51%3D%5Bn6%E1%B8%8B%C3%B7%CE%B5%26%2B%5D%29%C2%A5%C2%BD&inputs=%5B2%2C9%2C3%2C6%2C8%2C1%5D&header=&footer=) I still think there's a bit more I can do. ## Older version, 28 bytes ``` L(x|L(←x i⁰niε1=[n←xε&+]))¥½ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=L%28x%7CL%28%E2%86%90x%20i%E2%81%B0ni%CE%B51%3D%5Bn%E2%86%90x%CE%B5%26%2B%5D%29%29%C2%A5%C2%BD&inputs=%5B2%2C9%2C3%2C6%2C8%2C1%5D&header=&footer=) This. Is. Horrible. [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` tQ!=&f-|s ``` [Try it online!](https://tio.run/##y00syfn/vyRQ0VYtTbem@P//aCMFSwVjBTMFCwXDWAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##JY49agNBDEZ7n@K5cRdYSSPNqHDnCwTSLQanSRVXdpm7bzS7MAiNeN/P8/v9uz229@f5evn5@Httt69tvZ9WsxrheKcPTBmCJL6gjeEY2WmGLPSJClpTkWPnuNl@NSEMrxdkEFoStLwb7kQrpNaoX@kSK@qI7KQjSquQpFWD3cacNmgFG91LnaUOZMy2PqZv7mAVlpgZqrgwiI4uSJ9NVPC8/wM "MATL – Try It Online"). ### How it works Consider input `[2 9 3 6 8 1]` as an example. ``` tQ % Implicit input. Duplicate, add 1; element-wise % STACK: [2 9 3 6 8 1], [3 10 4 7 9 2] ! % Transpose % STACK: [2 9 3 6 8 1], [3; 10; 4; 7; 9; 2] = % Test for equality (element-wise with broadcast) % STACK: [0 0 1 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0; 0 1 0 0 0 0; 1 0 0 0 0 0] &f % Two-output find: row and column indices of nonzeros % STACK: [6; 5; 1], [1; 2; 3] -| % Minus, absolute value (element-wise) % STACK: [5; 3; 2] s % Sum. Implicit display % STACK: 10 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-mx`](https://codegolf.meta.stackexchange.com/a/14339/), ~~16~~ ~~11~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Inspired by [xnor's solution](https://codegolf.stackexchange.com/a/229732/58974). ``` VaWbU+WøUÄ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW14&code=VmFXYlUrV/hVxA&input=WzMxIDYzIDUzIDU2IDk2IDYyIDczIDI1IDU0IDU1IDY0XQ) ``` VaWbU+WøUÄ :Implicit map of each U at 0-based index V in input array W Va :Absolute difference of V and Wb : Index in W of U+Wø : U + Does W contain UÄ : U+1 :Implicit output of sum of resulting array ``` [Answer] # [Python 3](https://docs.python.org/3/), 91 bytes ``` def f(l):c=sorted(l);return sum(abs(l.index(x)-l.index(y))for x,y in zip(c,c[1:])if y-x==1) ``` [Try it online!](https://tio.run/##NczNCgIhEADgV5njDMwG7kLUhk@y7KH8IcFU1AXt5a0O3b7Tl3p9xrAML7eZr7zwmS8s9qGNBYueViVLzNXor2/Z1CMHKMcL74@C/uSCNg0bTX92IhszNO7gArxdQsVqE@tOzkKfmpSCRsouVPztND4 "Python 3 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes ``` Tr@Abs[s@@@Outer[s=#-#2&,#,#]~Position~1]& ``` [Try it online!](https://tio.run/##LU3NCoMwGLv7GgVPEey/HhzdE0zYbuKhE8d6UMF2J9FX73QTQkLyfSGDDe9@sMF1Nr6q@JjN9ekbb4y5fUI/N74iGWEpCEi71ZN3wU3jRts01rMbQ0Oyy8uQNt3unR23JVlWJAvnBysJqaELcIaCgpaQOZhAIcFRaggOmkP/finYIQz0dDhj/j9wCsUhdyiUCortPbB9QEBKKLEma/wC "Wolfram Language (Mathematica) – Try It Online") Essentially a port of [Jonah's J answer](https://codegolf.stackexchange.com/a/229738/81203). [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~20 17~~ 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ã_ÎaZo)¥1©ZÊ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=41/OYVpvKaUxqVrK&input=WzMxIDYzIDUzIDU2IDk2IDYyIDczIDI1IDU0IDU1IDY0XQ) * saved 5 thanks to @Shaggy! ``` ã_ - subsections passed trough ÎaZo) * abs difference of 1st and last element(then removed) ¥1 * == 1? ©ZÊ * take lenght/else 0 -x flag to sum ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 54 bytes ``` $=([o,...a])=>o?a.indexOf(o+1)+a.indexOf(o-1)+2+$(a):0 ``` [Try it online!](https://tio.run/##VVDRaoNAEHzvVyySB00u4ql3aooJfSkUCv2AEMiRamoIXog2LYR8u52tqU2E45zZndnZ25mTaTbH6tBOT2lX5t0od5dW@L5vVl4@twvjV/V78f1WunYivckNnAKGk5FrvFnQlZ/1pq1sTW3RtK4RdKy2H61H5wfCt7F105Kpm6/iSDmV0DwOBbsv/L3duuvl6Gz8na1q1yHHu6xoOqe1uMrEIM/z3pwW5BxM0zg0I2c8puenl1cajx1YXx5@YyxXggLAHkTRHdRKkEoEJamgKBSUSkEyAxcICmNg1CNBGVpi3BJ0cu8AQQhCDgRc5B3BHXABF95yEdMgo/9sYDVoxUdjKo4OeSJaOSgCKdw6Zi896JjXXOMxCB@x9m8hJM@gkfiPOT3qMS95nROhFqM3Zi1wouCtk8E7Y2/4ybR/KJX2ObKrnh9L6j5XCA8F75QdADFOJv0qIWiV8bME8O5@AA "JavaScript (V8) – Try It Online") [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 24 \log\_{256}(96) \approx \$ 19.75 bytes ``` 2zPgAu-1=keez0AhEeAuADES ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhY7jKoC0h1LdQ1ts1NTqwwcM1xTHUsdXVyDIdJQVQvWRhvpWOoY65jpWOgYxkIEAQ) #### Explanation ``` 2zP # All pairs in the input g # Filtered by: Au- # Does the difference 1= # Equal 1? k # End filter e # Map over the list: e # Map over the pair z0Ah # Get the index in the input E # End both maps e # Map over this list: AuAD # Get the absolute difference E # End map S # Sum this list # Implicit output ``` [Answer] # [Scala 3](https://www.scala-lang.org/), 122 bytes Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=bVPNjtMwEJY49ilGFQdbuFWd_xRSiQMHJBYkVpyqHrypsxuUJlXiQmHVJ-GyHODCE8Fj8AR8ttsVlD240_lm5vtmRpMv34dSNSr8sRxP2u6j6tvx6tej393Ve10aulB1S7cjorWuaAOHqf56mNPzvleflpemr9vrFZ_Tu7Y2VLhMog-qobUyCsCrejDMgUTMOVzQjIt_oDB8AExiQXEqKM0EhYGgTAqSObCZoCCCj3goKEdKBCsBpw_xoCwALM_gwEH_wTYbvNwVnUdCTxWet49QglhsX4KW8JLAtoN8OwW6jWGTyNImZ9U2mtgMq4v5QstwmhnD5aiU-B_ZARGP7B6OaiFiEXIjWws_jaGQpGcKuVUAq8z8RuPM95QfWexWZeJ7DMAUQyGzPHAhKlM_VgA4zu3OZil3AnzkTNX1xFgDKUF6v8XZ6DWnZxN3A_x4E_4qej3sGnsoOLly1yijXR0_pmxxTqZp2TB-6xLn9NhXCHpxJAZ00hC4TlPeALk98Rb3DRzGnvQwsm_k5e9V5341y5etWRUL_HIqvu1MNcl-fm6KRTOtkHWhtmxvnbpd6_2biu2fsLpizbTsWoNPYQAgOZekm0Hj7vjGtnNbKngTWSxed61-6ry6WFx2G83Q781UXQ3sL04-qTk_8Omw2_gOvh68vbvz9g8) ``` l=>l.flatMap(x=>l.indexOf(x+(if(l.contains(x+1))1 else 0))match{case -1=>None;case i=>Some(Math.abs(l.indexOf(x)-i))}).sum ``` Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=bVNNi9swED30ll8xhB4kqoTI3w5NoYceCt0WuvQU9qBN5F0Xxw620qYs-SW97GVLof-ov6ZvZCeQdA9Gnjcz782Ip5-_upWpTPhnOZ7UzXfT1uObx6edKybZ3xe_m9uvduXoypQ1PYyI1ragDQJh2rtuTm_b1vxYXru2rO9u5Jy-1KWjha8k-mYqWhtnAHwoOyc8SCR8IBXNpDqDwvAZMIkVxamiNFMUBooyrUjnwGaKgggx8qGiHCURTg04fY4HbQFgfQEHHvoP5mrwSt90mQl7qvByfKQS5GL-EoyELwl4HNTzFpg2xplETJtcdHM24QrWxX4hMxx3xnI5OjX-I14Q-YjvYVALkYtQG3Ev4jSGQpJeKOSsAFad9TcaZ_1M-cDCt6qTfsYATDEUMuZBCFGd9msFgOOc72yWSi8gR_4ompaEqCClyO63sI1dS3o98R6Qgyd6V7S221VsFDhvtauMs75PDiVb2MlVtejGn33hnF72HYreDcSAjhoK7nSreyAPR97FaYDDuCc9jPgbDHyuOvfuXL6vHTsYx8nAnJ0WKLwyW7GnxZseKeu13X8qxP6VKAtPMV01tcOr6IBpKTXZqrOwoMRbwWin3QnSSEw0c31sanuOlwxfNxsrsNH91Nx24lxQ0oRKebymg5x2u41f7NA_2OHdPg7nPw) ``` def calculate(list: List[Int]): Int = { list .flatMap(x => list.indexOf(x + (if (list.contains(x + 1)) 1 else 0)) match { case -1 => None case i => Some(Math.abs(list.indexOf(x) - i)) } ) .sum } ``` [Answer] # [Uiua](https://uiua.org), 12 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` /+⌵/-⍉⊚=1⊞-. ``` [Try it!](https://uiua.org/pad?src=0_2_0__ZiDihpAgLyvijLUvLeKNieKKmj0x4oqeLS4KCmYgW10KZiBbMzNdCmYgWzY1IDU3IDc4IDMyIDgxIDE5IDUwIDI0IDg1IDMgOTcgNDMgMTAgNzNdCmYgWzEgMl0KZiBbMiAxXQpmIFsxIDIgM10KZiBbMSAzIDJdCmYgWzMxIDYzIDUzIDU2IDk2IDYyIDczIDI1IDU0IDU1IDY0XQpmIFs1NCA2NCA1MiAzOSAzNiA5OCAzMiA4NyA5NSAxMiA0MCA3OSA0MSAxMyA1MyAzNSA0OCA0MiAzMyA3NV0KZiBbOTQgNjYgMTggNTcgNTggNTQgOTMgNTMgMTkgMTYgNTUgMjIgNTEgOCA2NyAyMCAxNyA1NiAyMSA1OV0K) ``` /+⌵/-⍉⊚=1⊞-. ⊞-. # difference table ⊚=1 # coordinates of ones ⍉ # transpose ⌵/- # absolute difference of columns /+ # sum ``` ]
[Question] [ This is my first challenge, so I'm keeping it fairly simple. If you've ever typed `telnet towel.blinkenlights.nl` on your command line and pressed enter, you will have experienced the joy of asciimation. Asciimation is, quite simply, doing an animation with ascii art. Today we will be doing a very basic asciimation of a person doing jumping jacks. There will be two ascii pictures that we will put together into one asciimation. Number 1: ``` _o_ 0 / \ ``` Number 2: ``` \o/ _0_ <blank line> ``` Note that the second one has a blank line at the end. So your program should do these steps: 1. Clear the console screen. 2. Print the correct ascii art image. 3. Set a flag or something so you know to do the other image next time. 4. Wait a moment (about a second). 5. Continue at 1. # Rules * Your program must be a (theoretically) infinite loop. * The programming language you use must have been created before this challange was posted. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. * Standard loopholes apply. Enjoy! [Answer] # CJam, ~~51~~ ~~45~~ ~~42~~ ~~38~~ 36 bytes ``` "c\o/ _0_""^[c_o_ 0 / \^["{_o\6e4m!}g ``` The above uses caret notation; the sequence `^[` is actually the ASCII character with code point 27. I've borrowed the escape sequence (`^[c`) from [@DomHastings' answer](https://codegolf.stackexchange.com/a/57138) ([with his permission](https://codegolf.stackexchange.com/questions/57120/asciimation-jumping-jacks/57138?noredirect=1#comment137801_57138)) to save 4 bytes. ### Verification You can recreate the file like this: ``` base64 -d > jj.cjam <<< ImNcby8KXzBfIiIbY19vXwogMAovIFwbIntfb1w2ZTRtIX1n ``` To run the code, download the [CJam interpreter](https://sourceforge.net/p/cjam/wiki/Home/) and execute this: ``` java -jar cjam-0.6.5.jar jj.cjam ``` This will work on any terminal that supports [console\_codes](http://man7.org/linux/man-pages/man4/console_codes.4.html) or an appropriate subset.1 ### How it works ``` e# Push both jumping jacks on the stack. "c\o/ _0_" "^[c_o_ 0 / \^[" e# When chained together, they contain two occurrences of the string "\ec", e# which resets the terminal. Encoding the ESC byte in the second string e# eliminates the need two escape a backslash before the string terminator. { e# Do: _o e# Copy the jumping jack on top of the stack and print the copy. \ e# Swap the order of the jumping jacks. 6e4m! e# Calculate the factorial of 60,000 and discard the result. e# This takes "about a second". }g e# Since the discarded factorial was non-zero, repeat the loop. ``` --- 1 The jumping jacks will look better if you hide the terminal's cursor before running the program. In Konsole, e.g., you can set the cursor's color to match the background color. This has to be done via your terminal's settings, since `^[c` resets the terminal. [Answer] # Pyth - ~~41~~ ~~40~~ 39 bytes ``` .VZ"\x1b[H\x1b[J"@c"_o_ 0 / \\\o/ _0_"Tb .p9 ``` (I'm counting the `\x1b`'s as one byte since SO destroys special characters). Clearly doesn't work online since its a) an infinite loop and b) uses terminal escape codes. ``` # Infinite loop "..." Print escape sequences to clear screen @ Modular indexing c T Chop at index ten into the constituent frames "..." Frames 1 & 2 concatenated (Pyth allows literal newlines in strings) ~ Post assign. This is an assign that returns the old value. h Increment function. Putting it after an assign makes it augmented assign. Z Variable auto-initialized to zero. .p9 Permutations(range(9), 9). Takes about a second on my machine. ``` I was surprised to find out that augmented-assign worked with post-assign. Pyth is awesome. [Answer] # QBasic, ~~58~~ 54 bytes Tested on [QB64](http://www.qb64.net) and at [Archive.org](https://archive.org/details/msdos_qbasic_megapack). ``` CLS ?"_o_ ?0 ?"/ \ SLEEP 1 CLS ?"\o/ ?"_0_ SLEEP 1 RUN ``` The right language for the problem can be surprisingly competitive, even if it is usually verbose. The `?` shortcut for `PRINT` helps too, of course. `CLS` is **cl**ear **s**creen; `RUN` without arguments restarts the program, which is the shortest way to get an infinite loop. The only other trick here is printing `0` for the midsection of the first picture. QBasic puts a space in front of (and after) nonnegative numeric values when it prints them, resulting in `0` . Saved 2 characters over `" 0`. I may also point out that the delay in this code is *literally a second*, and is not machine-dependent. ;^P [Answer] # Perl *(\*nix)*, 54 bytes ``` sleep print"\x1bc",$-++%2?'\o/ _0_ ':'_o_ 0 / \ 'while 1 ``` (`\x1b` is counted as 1 byte but escaped for easier testing.) The above has been tested with Bash and shortened by another byte thanks to [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis)! # Perl *(Windows)*, 56 bytes ``` sleep print"\x1b[2J",$-++%2?'\o/ _0_ ':'_o_ 0 / \ 'while 1 ``` Thanks to [@Jarmex](https://codegolf.stackexchange.com/u/26977) for his testing and advice! [Answer] # Javascript (ES6), ~~109~~ ~~93~~ ~~79~~ 70 bytes + HTML, ~~12~~ 10 bytes = ~~120~~ ~~106~~ ~~91~~ 80 bytes Fairly straightforward. Uses template strings to store the images, and toggles a boolean value to determine which to use. **NOTE:** This solution may not be valid, as it does not actually use a console. However, I don't believe it's possible to clear a browser console using JS, at least not while using Firefox. ``` a=!1,setInterval(_=>O.innerHTML=(a=!a)?`_o_ 0 / \\`:`\\o/ _0_`,1e3) ``` ``` <pre id=O> ``` [Answer] # Bash, ~~86~~ 84 bytes ``` while sleep 1;do printf "\e[2J_o_\n 0\n/ \\";sleep 1;printf "\r\e[2J\o/\n_0_\n";done ``` [Answer] # [Dash](https://wiki.debian.org/Shell), 67 bytes Also `bash`, `ksh`, `zsh`, `ash`, `yash` and probably many more besides. While it apparently works in these other shells, their own features and idiosyncrasies may allow for further golfing. I'll leave that as an exercise for the reader. Notably **not** `fish` or `tcsh`. ``` f(){ clear;echo "$1";sleep 1;f "$2" "$1";};f '_o_ 0 / \' '\o/ _0_' ``` [Try it online!](https://tio.run/##S0kszvj/P01Ds1ohOSc1scg6NTkjX0FJxVDJujgnNbVAwdA6Dcg1UoKI1QJ56vH58VwKBlz6CjHqCuox@fpc8Qbx6v//AwA "Dash – Try It Online") (with STDERR issue -- see **Caveats**) [Try it online!](https://tio.run/##S0kszvifWlGQX1SiEOIa5GtbVmJoYPA/TUOzWiE5JzWxyDo1OSNfQUnFUMm6OCc1tUDB0DoNyDVSgojVAnnq8fnxXAoGXPoKMeoK6jH5@lzxBvHq//8DAA "Dash – Try It Online") (with visible escape codes issue -- see **Caveats**) # How it works Hopefully fairly self explanatory, even so: Set up a function `f` which * Clears screen * Prints contents of `$1` * Sleeps 1 second * Calls `f` passing `$1` and `$2` in reverse order. This means the next iteration will display the "other" glyph before flipping them again... and so on. Outside of the function is the initial call to `f` with literal depictions of the two character glyphs as two arguments. # Caveats TIO's terminal implementation doesn't handle the `clear` well -- produces an error to STDOUT. If you add `export TERM=vt100` as a header the error stops and it displays the literal escape string. This is a feature/limitation of TIO, not an issue with my submission. I've included links to both for reference. Code should work as intended in a "proper" terminal. The recursion will eventually cause it to fail. Tried a soak test with `sleep 0` in a Docker container and it threw a Segmentation Fault within a minute. Adding a trivial counter, which may or may not have quantum implications, it managed ~15000 iterations in my environment. So like 4 hours with the `sleep` -- and who's going to watch it **that** long? :-) But I'd still argue that this complies with "theoretically" infinite, because it could go forever if it had "theoretically" infinite resources. That's my story and I'm sticking to it. [Answer] # Python 2, 99 bytes Runs on Windows ``` import os,time g=0 while 1:os.system("cls");print["\\o/\n_0_","_o_\n 0 \n/ \\"][g];time.sleep(1);g=~g ``` For UNIX machines, add two bytes: ``` import os,time g=0 while 1:os.system("clear");print["\\o/\n_0_","_o_\n 0 \n/ \\"][g];time.sleep(1);g=~g ``` [Answer] # awk - 95 92 86 84 83 ``` END{ for(;++j;) system("clear;printf '"(j%2?"_o_\n 0\n/ \\":"\\o/\n_0_")"';sleep 1") } ``` Nice workout :D Just wondered if this was doable. No prices to gain though... ;) If someone wants to test this: after you run the program you have to press Ctrl+D (end of input) to actually start the END block. To terminate it I have to use Ctrl+Z. I also have this, which is only 74 bytes, but it starts with pausing a second which isn't the wanted behaviour I think ``` END{ for(;1;print++j%2?"_o_\n 0\n/ \\":"\\o/\n_0_") system("sleep 1;clear") } ``` [Answer] # Batch - 82 bytes Edit: Muted the timeout command and removed the extra newline. ``` cls&echo _o_&echo 0&echo / \&timeout>nul 1&cls&echo \o/&echo _0_&timeout>nul 1&%0 ``` I've seen 2 other similar batch answers so I didn't really want to post this, but this is my first ever golf. [Answer] # BBC BASIC, 75 bytes Note that tokenisation pulls it down to 75 bytes. The whitespace is added in by the IDE. ``` g=0 10 IFg=0THENPRINT"\o/":PRINT"_0_"ELSEPRINT"_o_":PRINT" 0 ":PRINT"/ \" g=1-g:WAIT 100CLS:GOTO10 ``` [![Properties showing program size](https://i.stack.imgur.com/UIoh2.jpg)](https://i.stack.imgur.com/UIoh2.jpg) [Answer] # JavaScript ES6, ~~100~~ 95 bytes ``` (f=_=>{console.log(_?`_o_ 0 / \\`:`\\o/ _0_`) (b=setTimeout)(q=>(clear(),b(b=>f(!_))),1e3)})() ``` Logs to the console. Tested on Safari Nightly [Answer] # Batch, ~~151~~ ~~130~~ 118 bytes ``` cls @echo _o_ @echo 0 @echo / \ @PING -n 2 127.0.0.1>NUL cls @echo \o/ @echo _0_ @PING -n 2 127.0.0.1>NUL %0 ``` [Answer] # CBM 64 BASIC V2, ~~121~~ ~~119~~ ~~112~~ 117 bytes ``` 2?CHR$(147)+"\o/":?" 0":?"/ \" 3GOSUB7 4?CHR$(147)+"_o_":?"_0_" 5GOSUB7 6RUN 7A=TI 8IFTI-A<60THENGOTO8 9RETURN ``` [Answer] # Julia, 70 bytes (on **Windows**, by replacing `clear` with `cls`, thanks to undergroundmonorail) ``` n(i=1)=(sleep(1);run(`cls`);print(i>0?"_o_ 0 / \\":"\\o/ _0_");n(-i)) ``` ### On Linux, 72 bytes ``` n(i=1)=(sleep(1);run(`clear`);print(i>0?"_o_ 0 / \\":"\\o/ _0_");n(-i)) ``` This uses actual newlines rather than `\n` to save a byte; otherwise, the `i` is either 1 or -1 as the "flag", and it uses recursion to achieve the infinite loop. Call it as either `n(1)` or just `n()`. Also, `run(`clear`)`/`run(`cls`)` uses a shell command to clear the window, because Julia doesn't have a built-in window-clear command. [Answer] # Windows Batch, 83 ~~89~~ **Edit** removed the empty line after the clarification by OP ``` @cls&echo _o_&echo 0&echo./ \&timeout>nul 1&cls&echo \o/&echo _0_&timeout>nul 1&%0 ``` ~~If you get rid of the empty line in the jumping man (that cannot be seen anyway), the score is 83~~ Note: `timeout` is not present in Windows XP. It works in Vista or newer versions. Moreover `timeout` is not precise to the second, so it's a perfect choice to implement step 4 (Wait a moment (*about a second*)) [Answer] # Javascript (ES6), 82 bytes A modification of my [previous answer](https://codegolf.stackexchange.com/a/57123/42545) that uses the console. Works partially in Firefox, but only clears the console in Chrome, AFAIK. ``` a=!0,c=console,setInterval(_=>c.log(c.clear(a=!a)|a?`_o_ 0 / \\`:`\\o/ _0_`),1e3) ``` As always, suggestions welcome! [Answer] # JavaScript, ~~92~~ ~~91~~ 89 bytes ``` x=0;setInterval(function(){console.log("\033c"+["_o_\n 0\n/ \\","\\o/\n_0_"][x^=1])},1e3) ``` * No ES6 features (but would be significantly shorter with them) * Works with Node.js on Linux (don't know about other environments) * Partially works in Chrome's console (`c` is shown instead of clearing the console, breaking the output) Removing `"\033c"+` from the above code, the following works in the browser, but doesn't clear the console. ``` x=0;setInterval(function(){console.log(["_o_\n 0\n/ \\","\\o/\n_0_"][x^=1])},1e3) ``` [Answer] # CBM BASIC v2.0 (68 characters) ``` 0?"S_o_q||0q||N M":goS1:?"SMoN":?"_0_":goS1:gO 1wA161,255,pE(161):reT ``` The above requires some explanation, since Stack Exchange markup doesn't properly represent PETSCII characters: * The program is shown here for convenience in lowercase, but can and should be entered and run in uppercase mode on a Commodore 64. * The first and third "S" characters are actually in reverse video, and produced by pressing the `CLR` key (`SHIFT`+`HOME`). * The "q" characters are actually in reverse video, and produced by pressing the down cursor (`CRSR ⇓`). * The "|" characters are actually in reverse video, and produced by pressing the left cursor (`SHIFT`+`CRSR ⇒`). [Answer] # TI-Basic, ~~58~~ 56 bytes ``` While 1 ClrHome If not(Ans Disp "_o_"," 0","/ \ If Ans Disp "\o/","_0_" not(Ans If dim(rand(70 End ``` -2 bytes for assuming that the code is run on a fresh interpreter. [Answer] ## Ruby, 79 bytes ``` k=!0;loop{puts((k)?"\e[H\e[2J_o_\n 0\n/ \\":"\e[H\e[2J\\o/\n_0_");k=!k;sleep 1} ``` Requires escape codes. [Answer] # Forth, 86 bytes Requires GNU Forth for the escaped strings. To run in a non-GNU Forth, just change `S\"` to `S"`, and the escaped characters won't print correctly. ``` : P PAGE TYPE CR 999 MS ; : R BEGIN S\" \\o/\n_0_" P S\" _o_\n 0 \n/ \\" P 0 UNTIL ; R ``` [Answer] # [beeswax](http://rosettacode.org/wiki/Category:Beeswax), ~~119~~ 113 bytes ``` ph0`J2[`}ghq'-<gh0N}`0`}gN`/o\`Ngh0`J`< >g}`o`}N` `0>'d`0 `N`/ \`0hg>-'phg}`[2`b dF1f+5~Zzf(.FP9f..F3_# d < ``` Explanation of the important parts of the program: ``` left to right right to left 3FBf or fBF3 27 ASCII code for (esc) 3 [x,x,3]• set lstack 1st to 3 F [3,3,3]• set lstack to 1st B [3,3,27]• 1st=1st^2nd f push lstack 1st on gstack —————— 9PF.(f or f(.FP9 102400 counter to roughly match a wait time of 1 s on my i5 2410M Laptop 9 [x,x,9]• set lstack 1st to 9 P [x,x,10]• increment 1st F [10,10,10]• set lstack to 1st . [10,10,100]• 1st=1st*2nd ( [10,10,102400]• 1st=1st<<2nd (100<<10=102400, arithmetic shift left) f push lstack 1st on gstack —————— zZ~5+f or f+5~Zz 95 ASCII for '_' z [0,0,0]• initialize lstack to zero Z [0,0,90]• get value from relative coordinate (0,0), which is the location of `Z` itself, ASCII(Z)=90 ~ [0,90,0]• flip 1st and 2nd lstack values 5 [0,90,5]• set lstack 1st to 5 + [0,90,95]• 1st = 1st+2nd f push lstack 1st on gstack ``` The `f`’s push the values on the gstack (global stack) for later use. These values are accessed by the `0gh` (or the mirrored `hg0`) and `hg` (`gh`) instructions. `h` rotates the gstack upwards, `g` reads the top value of gstack and pushes it onto the lstack (local stack) of the bee (instruction pointer). ``` }`o`}N` 0 `N`/ \` sequence to print the standing man N`\o/`Ng}`0`}N sequence to print the jumping man }`[2J` equivalent to the ANSI escape sequence (esc)[2J to clear the screen >-'p or >-'q or > p loop for counting down (wait 1 s) d < b < d'-< ``` In-depth explanation follows later, if needed. Maybe with animation. [Answer] # [Noodel](https://tkellehe.github.io/noodel/), noncompeting 24 bytes Noncompeting because *Noodel* was born after the challenge was created:) ``` ”ṛ|ọBCḊCBCḣ“\o/¶_0_ḷėçḍs ``` [Try it:)](https://tkellehe.github.io/noodel/editor.html?code=%E2%80%9D%E1%B9%9B%7C%E1%BB%8DBC%E1%B8%8ACBC%E1%B8%A3%E2%80%9C%5Co%2F%C2%B6_0_%E1%B8%B7%C4%97%C3%A7%E1%B8%8Ds&input=&run=true) ### How it works ``` ”ṛ|ọBCḊCBCḣ # Creates a string that gets decompressed into "_o_¶¤0¤¶/¤\" and places it into the pipe. “\o/¶_0_ # Creates a string and places it into the pipe. ḷ # Unconditionally loop the code up to a new line or end of program. ė # Takes what is in the front of the pipe and puts it into the back. ç # Clears the screen and prints. ḍs # Delays for one second. ``` --- There currently is not a version of *Noodel* that supports the syntax used in this challenge. Here is a version that does: **24 bytes** ``` \o/¶_0_ _o_¶¤0¤¶/¤\ḷçėḍs ``` ``` <div id="noodel" code="\o/¶_0_ _o_¶¤0¤¶/¤\ḷçėḍs" input="" cols="5" rows="5"></div> <script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script> <script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script> ``` [Answer] # [Nim](http://nim-lang.org/), 107 bytes ``` import os,terminal var f=0 while 0<1:eraseScreen();sleep 999;echo ["_o_\n 0 \n/ \\","\\o/\n_0_\n"][f];f=1-f ``` Don't [Try it online!](https://tio.run/##DcjBCsMgDADQe78ieNqgo/boXL9ix6aIlEgFTUos2@e7vePjXHvP9RS9QNp4kdbMsQyfqJAWO3yPXAjsa36SxkbvXYn4dvetEJ3gnPO0HwKrCRKQwQLyBIhmNIgyIQf7b7OtafNpmR@p9x8 "Nim – Try It Online") ]
[Question] [ Let's play Russian Roulette! Normally, this would be a race to write the shortest MOD 6 program, but that's not very realistic, as the chance of winning decreases with each click. Here are the rules: 1. Emulate a real [six-shooter](https://en.wikipedia.org/wiki/Revolver): * A single bullet is placed into one of the six chambers, and the barrel is spun once, only before playing. * The chance of losing on the *n*th try is 1/6. * The chance of losing *after* *n* tries is 1/(6-n) * You are guaranteed to lose in, at most, 6 tries. 2. Losing: * Display the text `*BANG!*` * Terminate the program. 3. Winning: * "Winning" means the gun does not fire, but the bullet is one chamber closer to the hammer. * Display the text `*click*` * Present a "trigger" to the user, along with the ability to terminate the program (e.g. "ctrl+c", see below). 4. Program specific: * Pulling the trigger is some form of user input, including the first try. (This can be a keystroke, a mouse click, whatever; text prompts are not required.) * Only one instance of the program is allowed until it is terminated. (Running a new instance of the program is akin to giving the barrel a good spin, i.e. the probability of losing on the next click is reset to 1/6.) Shortest code wins! ### Leaderboard ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 66763; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 38512; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] ## Ruby, 51 bytes ``` [*['*click*']*rand(6),'*BANG!*'].map{|x|gets;$><<x} ``` Ungolfed: ``` [ *( # Unwrap the following array into the outer one ['*click*'] * rand(6) # An array of 0-5 clicks, see Array#* ), '*BANG!*' # The End ].map do |x| # Shortest way to iterate I was able to find gets # Await input $> << x # Shove the output string to `stdout` end # Return value is an array of several (0-5) `stdout`s. Who cares. ``` ### or ``` (['*click*']*rand(6)<<'*BANG!*').map{|x|gets;$><<x} ``` Ungolfing left for the readers. Not that difficult * Again, kudos to Martin, this time for a trick with `$><<` as a `puts` replacement. * Doesn't output newlines, but that was not required. * The shorter, the simpler. The gist of the required behaviour is to do 0-5 clicks and then fire. For that, outputs are accumulated inside the array. * **2 more bytes** can be shaved off if outputs like `"*click*"` are okay (what's required is printed in the end), by replacing `$><<` with `p`. I wasn't sure if this would still follow the rules. --- ### ~~68~~ 64 bytes (another approach) ``` [*0..5].shuffle.find{|x|gets;x<1||puts('*click*')};puts'*BANG!*' ``` * Kudos to [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) for -4 extra bytes. I didn't put much thought into the algorithm (it can possibly be even more compact, but not so clear), but I really like the model inside it: * An array emulates a barrel with its elements being chambers' contents. Since only one element is a bullet, rotating it and shuffling it are equivalent. * `0` is a bullet. Other numbers are not. * `find` finds a first return value for which the block is neither `false` nor `nil`. * `||`-expression is implicitly returned from the block. It's a short-circuit: it returns its first operand (unless it's `nil` or `false`) or a second one (otherwise). So it either returns `true` (if `x<1` or, clearer but longer `x == 0`) or the return value of `puts`, while... * `puts` always returns `nil`. Yep. * `gets` requests input. Merely hitting `Enter` suffices. * `Ctrl`+`C` terminates the program [Answer] # JavaScript, 64 bytes ``` for(i=6;i<7&&prompt();)alert(new Date%i--?"*click*":i="*BANG!*") ``` ## Explanation To pull the trigger enter any text into the prompt. Enter nothing or click cancel to terminate. ``` for( i=6; // i = number of chambers i<7 // i equals "*BANG!*" (not less than 7) if we lost &&prompt(); // see if we should do another shot ) alert( // alert the result new Date%i-- // use the current time in milliseconds as a random number, this is safe // to use because the gap between shots is greater than i (max 6ms) ?"*click*" // on win pass "*click*" to alert :i="*BANG!*" // on lose alert "*BANG!*" and set i to not less than 7 ) ``` [Answer] # Lua, ~~82~~ 75 bytes Pretty long, but there's lot of verbose in lua. ``` for a=math.random(6),1,-1 do io.read()print(a>1 and"*click*"or"*BANG!*")end ``` [Answer] # LabVIEW, 46 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490) Creates an Array of 0s and one 1, has a loop to wait for clicks and outputs the string. It initially says BANG becuase i forgot to reset the indicator before starting it. Also note that this is a gif, if if does not play/load for you please reopen the page. [![](https://i.stack.imgur.com/JQySU.gif)](https://i.stack.imgur.com/JQySU.gif) [Answer] ## Pyth, ~~31~~ ~~30~~ 28 bytes ``` FN.S6 EI!N"*BANG!*"B"*click* ``` Almost certainly can be improved. Input any number to pull the trigger, blank input to terminate early (with an error). Explanation: ``` FN for N in... .S6 shuffle(range(6))... E get a line of input I!N if N is falsy (i.e. 0) "*BANG!*" implicit output B break "*click* else, print click ``` [Answer] ## Seriously, ~~27~~ 25 bytes ``` "*BANG!*"6J"*click*"nW,X. ``` No online link because there is no way to do a prompt with piped input. The program can be CTRL-C'd at any time to ~~chicken out~~ terminate. Explanation: ``` "*BANG!*"6J"*click*"nW,X. "*BANG!*" push "*BANG!*" 6J push a random integer in [0,6) (n) "*click*"n push "*click*" n times W while loop (implicitly closed at EOF): ,X. get input and discard, pop and print top of stack ``` [Answer] # Pyth, 23 bytes ``` VO6"*click*" w;"*BANG!* ``` Really simple. A random number of iterations 0 - 5 display click and request a line of input, followed by a bang at the end. [Answer] # PHP, 52 bytes ``` *<?=$n=&rand(0,6-$argi)?click:"BANG!*";$n||@\n?>* ``` Requires the `-F` command line option, counted as three. The trigger is pulled by pressing `Enter`. Because `-F` literally runs the script again for every input (I kid you not), `die` and the like won't actually terminate, so we exit via suppressed runtime error instead, `@\n`. --- **Sample Usage** ``` $ php -F primo-roulette.php *click* *click* *BANG!* $ ``` [Answer] # Perl 5, 43 bytes Run with `perl -p`. Stable bullet variant - i.e. bullet position is decided only once in very beginning. ``` $i//=0|rand 6;$_=$i--?'*click*':die'*BANG*' ``` [Answer] # C, ~~110~~ ~~74~~ 72 bytes Thanks to Dennis for getting rid of the includes and a lot less bytes. ``` main(r){for(r=time(0)%6;getchar(),r--;)puts("*click*");puts("*BANG!*");} ``` ``` main(r) { for(r=time(0)%6;getchar(),r--;) puts("*click*"); puts("*BANG!*"); } ``` [Answer] # [Candy](https://github.com/dale6john/candy), 36 bytes About half the program is the text to print out :( ``` :6H_(=b"*click*"(;):=)"*BANG!*\n"(;) ``` long form: ``` getc digit6 rand range0 # build a range from 0 .. rand# while popA # these are the *click* instances stack2 "*click*" while printChr endwhile getc popA endwhile "*BANG!*\n" # out of luck while printChr endwhile ``` [Answer] # Python, 81 Bytes ``` import time for i in["*click*"]*(int(time.time())%6)+["*BANG!*"]:input();print(i) ``` inspired by the Ruby(51) and Python solutions [Answer] # [PlatyPar](https://github.com/cyoce/PlatyPar), ~~26~~ 25 bytes ``` 6#?;wT"*click*"O;"*BANG!* ``` Explanation: ``` 6#?; ## random integer [0,6) w ; ## while stack.last T ## stack.last-- "*click*"O ## alert "*click*" "*BANG!* ## alert "*BANG!*" ``` [Try it online](https://rawgit.com/cyoce/PlatyPar/643376e725da78b61e052aeb65385798d548c923/page.html?code=6%23%3F%3BwT%22*click*%22O%3B%22*BANG%21*)! [Answer] # Emacs Lisp, ~~94~~ 89 bytes ``` (set'b(%(random)6))(dotimes(a(+ b 1))(read-string"")(message(if(eq a b)"BANG""*click*"))) ``` Ungolfed: ``` (set 'b (% (random) 6)) (dotimes (a (+ b 1)) (read-string"") (message (if (eq a b) "BANG" "*click*"))) ``` [Answer] # R, ~~86~~ ~~80~~ 77 bytes As usual, R has awesome features to code golfing but looooooong function names. ``` sapply(sample(0:5),function(n){!n&&{cat('*BANG!*');q()};readline('*click*')}) ``` [Answer] # Python 2, ~~108~~ ~~104~~ ~~102~~ ~~100~~ 98 bytes My first attempt at golfing: ``` from random import* a=[1]+[0]*5 shuffle(a) for i in a:input();print("*click*","*BANG!*")[i];" "[i] ``` Maybe I should add that the program doesn't terminate *correctly* when you lose, it just throws an exception (which results in termination): ``` Traceback (most recent call last): File "russian_roulette.py", line 4, in <module> for i in a:input();print("*click*","*BANG!*")[i];" "[i] IndexError: string index out of range ``` [Answer] # Python 3, 95 bytes Also my first golf attempt, also in Python 3. I swear Bruce and I aren't the same person. ``` from random import* for a in range(randint(0,5)):input();print("*click*") input();print("*bang*") ``` **Ungolfed:** ``` from random import* for a in range(randint(0,5)): input() print("*click*") input() print("*bang*") ``` Generate a random number between 0 and 5 inclusive, print *click* that many times, then print *bang*. Press enter/return to pull the trigger. [Answer] # Perl 5, 40 bytes ``` <>,print"*$_*"for(click)x rand 5,'BANG!' ``` Run without command line options, the trigger is pulled by pressing `Enter`. [Answer] ## C, 96 bytes (Without counting comment) ``` #define R 4//chosen by playing russian roulette, guaranteed to be random int main(){for(;c++<R&&puts(c<R?"Fire?":"☠Bang!☠");getchar(),puts("*click*"));} ``` ### Formatted : ``` #define R 4 // chosen by playing russian roulette, guaranteed to be random int main(int c) { for( ; c++ < R && puts(c < R ? "Fire?" : "☠Bang!☠") ; getchar(), puts("*click*") ); } ``` ### Explanation : There also is a click when it fires, that's the sound of the hammer being released. After the bang you need to hit enter to take the gun out of the dead man's hand, rigor mortis squeezed his finger around the trigger. While you are prying his hand open you hear another click as the trigger snaps back into normal position. [Answer] ## Common Lisp, 109 ``` (do(g(b(nthcdr(random 6)#1='(t()()()()() . #1#))))(g)(read-char)(princ(if(setf g(pop b))"*BANG!*""*click*"))) ``` Not very competitive, but I like circular lists: ``` (do (;; auxiliary variable x x ;; initialize infinite barrel, rotate randomly (b (nthcdr (random 6) #1='(t()()()()() . #1#)))) ;; we end the loop when x is T (a bullet is fired) (x) ;; press enter to shoot (read-char) ;; pop from b, which makes b advance down the list. The popped value ;; goes into x and is used to select the appropriate string for ;; printing. (princ (if (setf x(pop b)) "*BANG!*" "*click*"))) ``` [Answer] # Perl 5, 43 bytes 42 bytes + `-p` command line option. Just press `enter` to trigger. ``` $_=0|rand 7-$.<++$i?die"*BANG!*":"*click*" ``` Thanks to Dom Hastings for his help! Original answer was 67 bytes: ``` $i++;$a=$i>=int(rand(6));print$_=$a?'*BANG!*':'*click*';last if($a) ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 41 bytes ``` 6Yr`j?t@=?'*BANG!*'DT.}'*click*'DT]}T.]]x ``` To pull the trigger, input a non-empty string (such as `'try'`). To terminate, input an empty string ### Examples In this case the trigger was pulled once and... bad luck: ``` >> matl > 6Yr`j?t@=?'*BANG!*'DT.}'*click*'DT]}T.]]x > > try *BANG!* ``` In this case the user stopped (note the final empty input) after two lucky pulls: ``` >> matl > 6Yr`j?t@=?'*BANG!*'DT.}'*click*'DT]}T.]]x > > try *click* > try *click* > ``` ### Explanation ``` 6Yr % random avlue from 1 to 6 ` % do...while j % input string ? % if nonempty t % duplicate the orignal random value @ % loop iteration index = % are the equal? ? % if so '*BANG!*'D % display string T. % unconditional break } % else '*click*'D % display string T % true value, to go on with do...while loop ] % end if } % else T. % unconditional break ] % end ] % end x % delete original random value ``` [Answer] # [Perl 6](http://perl6.org), ~~58~~  53 bytes ``` for ^6 .pick(*) {get;say <*BANG!* *click*>[?$_];!$_&&last} # 58 bytes ``` ``` $ perl6 -pe '$///=^6 .pick;$_=$/--??"*click*"!!say("BANG!")&&last' # 52+1= 53 bytes ``` Press enter to pull the trigger, or ctrl+c to put it down. [Answer] # Python 2, ~~88~~ 84 bytes This solution is inspired by the python 3 solutions already given. I chose python 2 to remove the print parenthesis even though this changes the behavior of input(). ``` import time for i in[0]*int(time.time()%6)+[1]:input();print("*click*","*BANG!*")[i] ``` * I am using modulo of the time as a random function (good enough for russian roulette) * the player input should be "i" then Enter (otherwise input() will throw an error), this trick relies on the fact that the input can be "whatever". [Answer] # Ruby, 45+1=46 Not as clever as [D-side](https://codegolf.stackexchange.com/a/66783/6828)'s but slightly shorter. With command-line flag `p`, run ``` rand(7-$.)<1?(puts'*BANG*';exit):$_='*click*' ``` The user can pull the trigger with return and leave with control-c. `p` causes the program to run in a loop, reading lines from STDIN and outputting `$_`. Each time it runs, it increments `$.`. So on the first run, it chooses a random positive integer less than 6, then 5, then 4, and so on. On the first 0, we output manually and exit, until then we output implicitly. (and now I notice that there's already a very similar Perl. Oh well.) [Answer] # Perl 5, ~~69~~ ~~51~~ 49 bytes ``` map{<>;print"*click*"}1..rand 6;<>;print"*BANG!*" ``` There is probably some more golfing potential, I will look into this. Changes: * Saved 8 bytes by removing `$l` and some semicolons, and 10 bytes by changing `<STDIN>` to `<>` * Saved 2 bytes thanks to Oleg V. Volkov [Answer] # VBA, 126 bytes Golf Version for Minimal Bytes ``` Sub S() r=Int(5*Rnd()) e: a=MsgBox("") If a=1 Then: If i=r Then MsgBox "*BANG!*" Else: MsgBox "*click*": i=i+1: GoTo e End Sub ``` Fun Version that Makes The Buttons more Clear for Increased User Acceptance. ``` Sub RR() r = Int(5 * Rnd()) e: a = MsgBox("Are you Feeling Lucky?", 4) If a=6 Then: If i=r Then MsgBox "*BANG!*", 16 Else: MsgBox "*click*", 48: i=i+1: GoTo e End Sub ``` Some Fun with Custom Forms and You could make a pretty Slick Game in VBA. [Answer] # APL, 39/65 bytes ``` {⍞⊢↑⍵:⍞←'*BANG*'⋄∇1↓⍵⊣⍞←'*click*'}6=6?6 ``` Pretty straightforward answer. [Answer] # C, 180 Bytes ``` #include<stdio.h> #include<stdlib.h> #include<time.h> int main(){srand(time(NULL));int r,i=6;while(i!=1){getchar();r=rand()%i;if(r){puts("CLICK");}else{puts("BANG");exit(0);}i--;}} ``` My first attempt at code golf, there's probably a lot of room for improvement :) [Answer] # Julia, 71 bytes ``` b=rand(1:6);while b>0 readline();print(b>1?"*click*":"*BANG!*");b-=1end ``` Press `Enter` to fire or `Ctrl`+`C` to quit. The latter ends with an `InterruptException`. Ungolfed: ``` # Set an initial bullet location b = rand(1:6) while b > 0 # Read user input readline() # Check the location if b > 1 print("*click*") else print("*BANG!*") end b -= 1 end ``` ]
[Question] [ Given two positive integers, W and H, output an ASCII-art box whose border is made of slashes (`/` and `\`) with W "spikes" on the top and bottom edges, and H "spikes" on the left and right edges. The box's interior is filled with spaces. A "spike" is simply two slashes coming together to form an arrow shape: ``` /\ \/ / \ \ / ``` So the output for `W = 4, H = 3` would be ``` /\/\/\/\ \ / / \ \ / / \ \/\/\/\/ ``` as there are 4 spikes on the top pointing up, 4 on the bottom pointing down, 3 on the left pointing left, and 3 on the right pointing right. Here are some other input/output pairs: ``` W H [spiky slash box] 1 1 /\ \/ 1 2 /\ \/ /\ \/ 2 1 /\/\ \/\/ 2 2 /\/\ \ / / \ \/\/ 1 3 /\ \/ /\ \/ /\ \/ 3 1 /\/\/\ \/\/\/ 2 3 /\/\ \ / / \ \ / / \ \/\/ 3 2 /\/\/\ \ / / \ \/\/\/ 10 1 /\/\/\/\/\/\/\/\/\/\ \/\/\/\/\/\/\/\/\/\/ 10 2 /\/\/\/\/\/\/\/\/\/\ \ / / \ \/\/\/\/\/\/\/\/\/\/ 4 5 /\/\/\/\ \ / / \ \ / / \ \ / / \ \ / / \ \/\/\/\/ ``` No lines in the output should have leading or trailing spaces. There may optionally be one trailing newline. **The shortest code in bytes wins.** [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes ``` BײNײN/\ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98pv0JDS8NIR8Ezr6C0xK80Nym1SENTU0cBq6CSfkyMkqb1//@GCkb/dcv@6xbnAAA "Charcoal – Try It Online") ### Explanation ``` B Box ײN Next input as number * 2 ײN Next input as number * 2 /\ With border "/\" ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 18 bytes ``` '\/',iE:]!+)O6Lt&( ``` Try it at [MATL Online!](https://matl.io/?code=%27%5C%2F%27%2CiE%3A%5D%21%2B%29O6Lt%26%28&inputs=4%0A3&version=20.2.2) ### Explanation Consider inputs `W = 4`, `H = 3`. The code builds the row vectors `[1 2 3 4 5 6 7 8]` (range from `1` to `2*W`) and `[1 2 3 4 5 6]` (range from `1` to `2*H`). Transposing the latter and adding to the former with broadcast gives the matrix ``` 2 3 4 5 6 7 8 9 3 4 5 6 7 8 9 10 4 5 6 7 8 9 10 11 5 6 7 8 9 10 11 12 6 7 8 9 10 11 12 13 7 8 9 10 11 12 13 14 ``` Modular indexing into the string `\/` produces the desired result in the matrix border: ``` /\/\/\/\ \/\/\/\/ /\/\/\/\ \/\/\/\/ /\/\/\/\ \/\/\/\/ ``` To remove the non-border values, we set them to `0` (when interpreted as char it is displayed as space): ``` /\/\/\/\ \ / / \ \ / / \ \/\/\/\/ ``` Commented code: ``` '\/' % Push this string. Will be indexed into , % Do twice i % Input a number E % Multiply by 2 : % Range ] % End ! % Transpose + % Add ) % Index O % Push 0 6L % Push [2 -1+1j]. As an index, this means 2:end t % Duplicate &( % Write 0 into the center rectangle. Implicit display ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~69~~ 68 bytes -1 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) ``` lambda w,h:'/\\'*w+'\n'+'\\%s/\n/%s\\\n'%((' '*~-w,)*2)*~-h+'\\/'*w ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFcJ8NKXT8mRl2rXFs9Jk8dSMSoFuvH5OmrFsfEAAVUNTTUFRTUtep0y3U0tYw0gYwMkCJ9oI7/BUWZeSUKaRqGOoaaXBCOujoXQtQIi6gRVrVGOsZYRE11TDX/AwA "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~90~~ ~~88~~ ~~87~~ 82 bytes *~~1~~ 6 bytes saved thanks to Lynn* ``` a#b=[1..a]>>b x!y|i<-(x-1)#" "=x#"/\\":(y-1)#['\\':i++"/",'/':i++"\\"]++[x#"\\/"] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P1E5yTbaUE8vMdbOLomrQrGyJtNGV6NC11BTWUlBQcm2QllJPyZGyUqjEiQUrR4To26Vqa2tpK@ko64PYQKlY7W1o4EqY2L0lWL/5yZm5tkWlJYElxT55KmU5uVk5qUWq5gpmvwHAA "Haskell – Try It Online") Still feels really long, I'll see what I can do. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` „/\|∍`S¦`).B∞∊ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcM8/ZiaRx29CcGHliVo6jk96pj3qKPr/39DLmMA "05AB1E – Try It Online") ### Explanation ``` „/\|∍`S¦`).B∞∊ Arguments: x, y „/\ Push the string "/\" | Push inputs as array: [x,y] ∍ Push the string extended/shortened to those lengths ` Flatten S Push seperate chars of second string ¦` Remove first char and flatten again ) Wrap stack to an array .B Squarify ∞∊ Mirror on both axes ``` This only creates the top left corner, x characters wide and y characters tall. It then mirrors this on both axes: ``` x=3, y=2 /\/| \ | ---+ ``` [Answer] ## JavaScript (ES6), 84 bytes Takes input in currying syntax `(w)(h)`. ``` w=>h=>'/\\'[R='repeat'](w)+` ${`\\${p=' '[R](w-1)}/ /${p}\\ `[R](h-1)}`+'\\/'[R](w) ``` ### Demo ``` let f = w=>h=>'/\\'[R='repeat'](w)+` ${`\\${p=' '[R](w-1)}/ /${p}\\ `[R](h-1)}`+'\\/'[R](w) function upd() { O.innerHTML = W.value+'x'+H.value+'\n\n'+f(W.value)(H.value) } upd() ``` ``` <input id=W type=range value=5 min=1 max=10 oninput="upd()"> <input id=H type=range value=5 min=1 max=10 oninput="upd()"> <pre id=O> ``` [Answer] # [Swift 3](https://www.swift.org), 166 bytes ``` func f(a:Int,b:Int){let k=String.init(repeating:count:),n="\n";var r="\\"+k(" ",a-1)+"/";print(k("/\\",a)+n+k(r+n+String(r.characters.reversed())+n,b-1)+k("\\/",a))} ``` **[Full test suite.](http://swift.sandbox.bluemix.net/#/repl/598c093a3d85b53110d41c94)** The closure version is a bit longer, unfortunately (175 bytes): ``` var g:(Int,Int)->String={let k=String.init(repeating:count:),n="\n";var r="\\"+k(" ",$0-1)+"/";return k("/\\",$0)+n+k(r+n+String(r.characters.reversed())+n,$1-1)+k("\\/",$0)} ``` **[Test suite with the closure version.](http://swift.sandbox.bluemix.net/#/repl/598c097d3d85b53110d41c95)** [Answer] # [Retina](https://github.com/m-ender/retina), ~~77~~ 73 bytes ``` \d+ $* 1+|1(?=1* (1+)) $1¶ 1 /\ .((..)*.) /$1¶$1/ ¶$ (?<=¶.+).(?=.+¶) ``` [Try it online!](https://tio.run/##HUs7DsIwDN3fKTwEyU4kp07ajapjL9GhSDCwMCBGzpUD5GIhYXhf@70fn@fr1i68n@24BzgPsvA13lbzxBZE4KwWGOIBZVYVr4I4SmcRnQHermstGkT7TkMtAmot0wwjQ@owSl0T8t/nriPncZ/Gw4SF5h8 "Retina – Try It Online") Link includes test cases. Takes input in the format `<height> <width>`. Explanation: ``` \d+ $* ``` Convert the inputs to unary. ``` 1+|1(?=1* (1+)) $1¶ ``` Multiply the inputs, but add a newline so that the result is a rectangle. ``` 1 /\ ``` Create the spiky top. ``` .((..)*.) /$1¶$1/ ``` Duplicate each spiky row, but with the spikes offset on the second row. ``` ¶$ ``` Delete trailing newlines. ``` (?<=¶.+).(?=.+¶) ``` Delete the inside of the box. (Note space on last line.) [Answer] # Excel, 95 bytes ``` =REPT("/\",A1)&" "&REPT("\"&REPT(" ",2*A1-2)&"/ /"&REPT(" ",2*A1-2)&"\ ",B1-1)&REPT("\/",A1) ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~41~~ 39 bytes Prompts for a list of `[H,W]` ``` '\'@2@1⊢¯1⌽@1{⌽⍉⍵,'/\'⍴⍨≢⍵}⍣4⊢''⍴⍨2×⎕-1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9uCAzu9Ipv@K/eoy6g5GD4aOuRYfWGz7q2etgWA0kH/V2PurdqqOuH6P@qHfLo94VjzoXAQVqH/UuNgEqVYeKGh2e/qhvqq4hyMT/CmAAM5jLWMGEC03IUMEQXcgIU8hQwQhTFYaQMTaNxpiqsJhljMVdBlgchiFmqmACAA "APL (Dyalog Unicode) – Try It Online") `⎕-1` prompt for input (mnemonic: stylized console) and subtract 1 `2×` multiply by two `''⍴⍨` use that to reshape an empty string (pads with spaces) `⊢` yield that (serves to separate it from `4`) `{`…`}⍣4` apply the following function four times:  `≢⍵` tally (length of) the argument  `'/\'⍴⍨` cyclically **r**eshape `"/\"` to that length  `⍵,` append that to the right side of the argument  `⌽⍉` transpose and mirror (i.e. turn 90°) `¯1⌽1` cyclically rotate the 1st row one step to the right `⊢` yield that (serves to separate it from `1`) `'\'@2@1` put a backslash at the 2nd position of the 1st major item. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~170~~ ~~166~~ ~~158~~ ~~155~~ ~~108~~ 105 *-3 bytes thanks to cleblanc* ``` x,y;f(w,h){for(y=h*=2;y--;puts(""))for(x=w*2;x--;)putchar(!x|x==w*2-1|!y|y==h-1?x&y&1|~x&~y&1?47:92:32);} ``` [Try it online!](https://tio.run/##hY5BDoMgEEX3ngJdGDCQCLZpKiFepBtja3VRNFQrRPTqFl1Xu5rJe/kzvyDPolgWjQ0v4YArNJaNgkZUkWDcEMLbvnvDIEBo5VoMEePaYeR4UeUK@tpqsWJCrW@sEaIiNNOhCamddTi7mZ0u6ZWlCUN8WmrZgVdeS/hp6jsCowdACSkGFHG3tsr5EgaEkJsMNrRZtm/ZYZYdZt3lZN8mx63iv/rg8wmD82/rmHp0vZIg5t7kLV8 "C (gcc) – Try It Online") ~~I think this can be golfed further with a less straightforward approach, I'll see what I can do when I find the time.~~ Ok I cannot find any other way to reduce the number of bytes for that code. Explanation: a simple double-loop printing the box char by char. When printing a border: if both x and y coordinates are either even or odd, it displays a `/`, otherwise, a `\` is displayed If not a border, a space character is displayed instead [Answer] # [///](https://esolangs.org/wiki////), ~~172~~ 117 bytes So, because the output consists of `///`s and `whitespace`s, there should be submissions in those 2 languages. Put the input after the code in `W,H` as unary number (unary for /// is [allowed](https://codegolf.meta.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary), thanks to Challenger5 for suggestion) (use `*` to represent digit, separate with `,`) format. ``` /W/VV//V/\\\///`/\\\\\\\\\\\\\V/,/W>+ V`/`\>+W !V!``WV>+WV- V`\ `\W+ V`/ `/W-!V`\ W``\\V`\V>!//!*/+%-%!//*/ //%/ ``` [Try it online!](https://tio.run/##RYsxCsUwDEP3nsIesiQNukGOYS8e9IdCh265P6lDhy8QeghpPr95X3MtOMwAQ0QA4M6/DCd8NBEjGKO5iJqSbsnWdx8Hw7/FQXjXXTmZZ4YNBbSilV6SKkSAgpo602u9 "/// – Try It Online") (with input `W=4, H=3`) [Answer] # [Python 3](https://docs.python.org/3.6/), 87 82 bytes **Edit:** Saved 5 bytes thanks to [@officialaimm](https://codegolf.stackexchange.com/users/59523/officialaimm), [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) and [@tsh](https://codegolf.stackexchange.com/users/44718/tsh) ``` def f(a,b,n="\n"):r="\\"+" "*~-a+"/";print("/\\"*a+n+(r+n+r[::-1]+n)*~-b+"\\/"*a) ``` [Try it online!](https://tio.run/##LY6xDsIwDETn9isiT3GSKk1SliAk/oMytIKILm4VdWHh14MJXZ5PvrN123t/rRRKeTyTSHIys6ELjAQYM88RNAgB6tNNGiyct7zQLsGyoSZNWmZGvsXYubsm5Nys@cqyiyWtWfBDsZCQ0hmHhumZvmpfdTg2oeofXf@P9tUZzAkxtk3thm1zNLiC8j2WLw) [Answer] # J, 48 bytes ``` ' '&((<,~<<0 _1)})@(+:@[$(1&|.,:])@('\/'$~+:)@]) ``` ## ungolfed ``` ' '&((< ,~ <<0 _1)}) @ (+:@[ $ (1&|. ,: ])@('\/' $~ +:)@]) ``` ## explanation ``` (+:@[ $ (1&|. ,: ])@('\/' $~ +:)@]) creates box, but interior filled with slashes ('\/' $~ +:)@] take right arg, W, doubles it, then fills that @ many characters with '\/' repeating (1&|. ,: ]) stacks (,:) the above on top of itself rotated by one char, producing top and bottom spikes $ reshape to.. (+:@[ double the length of the left arg, height this creates the sides, as well as a filled interior @ ' '&((< ,~ <<0 _1)}) removes slashes from interior by using the complement form of amend }. ie, replace everything but the first and last row and first and last col with a space ``` [Try it online!](https://tio.run/##y/r/P81WT0FdQV1NQ8NGp87GxkAh3lCzVtNBQ9vKIVpFw1CtRk/HKhbIV4/RV1ep07bSdIjV5EpNzshXMFRIUzCEMNXVIbQRUMgIVcgYKGTy/z8A "J – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes ``` 4FNÈi¹}·„\/NÉiR}N·Λ ``` [Try it online!](https://tio.run/##ASgA1/8wNWFiMWX//zRGTsOIacK5fcK34oCeXC9Ow4lpUn1OwrfOm///Mwo0 "05AB1E – Try It Online") Takes arguments reversed. [Answer] # [Haskell](https://www.haskell.org/), ~~84~~ 79 bytes ``` w%h=[[last$"/\\"!!mod(x+y)2:[' '|x>1,y>1,x<2*w,y<2*h]|x<-[1..2*w]]|y<-[1..2*h]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v1w1wzY6OiexuERFST8mRklRMTc/RaNCu1LTyCpaXUG9psLOUKcSiCtsjLTKdSqBZEZsTYWNbrShnh5QJDa2phLGyYiN/Z@bmJmnYKuQm1jgq1BQWhJcUuSTp6CiYKxq8h8A "Haskell – Try It Online") Example usage: `3%6` yields a list of lines. Use `mapM putStrLn $ 3%6` to pretty-print the box. [Answer] # Java 8, 141 bytes A curried lambda from width to height to output. ``` w->h->{String f="/",b="\\",t=f,o=b,p="";char i=1;for(;i++<w;t+=b+f,o+=f+b)p+=" ";t+=b;o+=f;for(i=10;--h>0;)t+=i+b+p+f+i+f+p+b;return t+i+o;} ``` [Try It Online](https://tio.run/##fZA9b8IwEIZn8itOnhI5cYPazThjpQ6dGIHBDjYYgm05lyCE@O2p@ehWdTjJ99x70j0@yFFWPmh32B4newo@IhwSYwPajpnBtWi9Y5@vB8@yMKjOttB2su/hW1oH12wWoh0lauhRYhr@xhdfDvVOx/IPssRo3a5pwICYzlWzr5rrk4ER5I2USpD1mpQoTOmFKoMghLd7GcGKOTc@5txSujhzpELRlKHCUFUEKggAeVB@Z49oWql5Ve2bmhdpYqmigRpqUwWqeNQ4RAeYgOe3acaT0VPzJTR6u4VTks2fJ642IOOuL@7us@WlR31ifkCW/sFhbpgMobvkL1cWZOx1avL7zqreFMW/gXkKFOmEW3abpo/p/Qc) (no, `return t+i+o;` was not intentional) ## Ungolfed lambda ``` w -> h -> { String f = "/", b = "\\", t = f, o = b, p = "" ; char i = 1; for (; i++ < w; t += b + f, o += f + b) p += " "; t += b; o += f; for (i = 10; --h > 0; ) t += i + b + p + f + i + f + p + b; return t + i + o; } ``` This solution is atypically picky about input size since a `char` is used to count up to the width input. Fortunately, the algorithm is bad enough that at those sizes program completion is probably already an issue. I chose to use `char` for the loop index so I could reuse it later as a cheap alias for `'\n'`. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~22~~ ~~21~~ 13 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` /\”m;HΙ»mč+╬¡ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=Li4lMjIvJTVDJXUyMDFEbSUzQkgldTAzOTklQkJtJXUwMTBEKyV1MjU2QyVBMQ__,inputs=MyUwQTQ_) (expects both inputs on stack so `..` (and `"` because a string hasn't been explicitly started) - take number input twice is added for ease-of-use) Explanation: ``` /\” push "/\" m mold to the 1st inputs length ; get the other input ontop of stack H decrease it Ι push the last string - "/\" » rotate it right - convert to "\/" m mold "\/" to the length of 2nd input - 1 č chop into characters + prepend the 1st molded string to the character array of the 2nd ╬¡ quad-palindromize ``` [Answer] # Mathematica, 87 bytes ``` Table[Which[1<i<2#2&&1<j<2#," ",OddQ[i+j],"\\",1>0,"/"],{i,2#2},{j,2#}]~Riffle~" "<>""& ``` Try it in [Mathics](https://tio.run/##y00sychMLv6fZvs/JDEpJzU6HMjNiDa0ybQxUjZSUzO0yQIydJQUlHT8U1ICozO1s2J1lGJilHQM7Qx0lPSVYnWqM3WASmt1qrOAdG1sXVBmWlpOap0Sl5KNnZKS2v@Aosy8EgUHhbRoEx3T2P8A "Mathics – Try It Online") (it prints extra spaces at the start of most lines for some reason), or at the [Wolfram sandbox](https://sandbox.open.wolframcloud.com/)! Takes two integers as input. It's a fairly naïve solution, but all of the clever things I tried had more bytes. Something that nearly works is ``` ArrayPad[Array[" "&,2#-2],1,{{"/",s="\\"},{s,"/"}}]~Riffle~"\n"<>""& ``` except it fails if either dimension is 1 (input is a list containing the dimensions). [Answer] # [Pyth](https://pyth.readthedocs.io), ~~40 39~~ 38 bytes ``` +++*Q"/\\"b*tE+++K++\\*d*2tQ\/b_Kb*"\/ ``` This takes the two integers separated by a newline. **[Full test suite.](https://pyth.herokuapp.com/?code=%2B%2B%2B%2aQ%22%2F%5C%5C%22b%2atE%2B%2B%2BK%2B%2B%5C%5C%2ad%2a2tQ%5C%2Fb_Kb%2a%22%5C%2F&input=5%0A3&test_suite=1&test_suite_input=1%0A1%0A%0A1%0A2%0A%0A2%0A1%0A%0A2%0A2%0A%0A1%0A3%0A%0A3%0A1%0A%0A2%0A3%0A%0A3%0A2%0A%0A10%0A1%0A%0A10%0A2%0A%0A4%0A5%0A&debug=0&input_size=3)** [Answer] # [Ruby](https://www.ruby-lang.org/), ~~62 61~~ 60 bytes ``` ->r,c{["/\\"*c]+["\\#{w=" "*~-c}/",?/+w+?\\]*~-r+["\\/"*c]} ``` -1 byte thanks to Arnauld [Try it online!](https://tio.run/##KypNqvyfZvtf165IJ7k6Wkk/JkZJKzlWO1opJka5utxWSUFBSatON7lWX0nHXl@7XNs@JiYWKFAEVqEPUlv7v6C0pFghLdpExySWC8xW1wUCdS6ouKGOIVZxExzihkBz/gMA "Ruby – Try It Online") [Answer] # [Actually](https://github.com/Mego/Seriously), 38 bytes ``` "/\"*;.R;l¬' *"\/"@j;R(D(╗WD(;.(;.(Wé╜ ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/19JP0ZJy1ovyDrn0Bp1BS2lGH0lhyzrIA0XjUdTp4e7aFjrgVD44ZWPps75/9@YywQA "Actually – Try It Online") [Answer] # [J](http://jsoftware.com/), 39 bytes ``` (' \/'{~=/&(2&|)(*>:)~0=*/&(*|.))&i.&+: ``` [Try it online!](https://tio.run/##y/r/P03B1kpBQ10hRl@9us5WX03DSK1GU0PLzkqzzsBWC8jXqtHT1FTL1FPTtuLiSk3OyFcwUkhTMDT4/x8A "J – Try It Online") Takes two arguments as `height` on the LHS and `width` on the RHS. [Answer] # ><>, 180 Bytes ``` 0&0\ a*+>i68*-:0(?v$ /)\^0&1v?)0&~/ ? 0 v:$< / \:<-1oo'/\' \~$:@2*0&\ '/'1>&o1->a\ /'/'>o$:2*>1-:1)?\~$&1=?\ '\'0//?(3:o/?/'\'/ \o*48 / \ /?)0\ &:&1=/; \ \:~ '/'/\<oo'\' ``` [Answer] **VBA (Excel) , 161 Bytes** ``` Sub a() c=[A2]*2 r=[B2]*2 For i=1To r For j=1To c b=IIf(i=1 Or j=1 Or i=r Or j=c,IIf((i+j) Mod 2,"\","/")," ") d=d & b Next d=d & vbCr Next Debug.Print d End Sub ``` [Answer] # R, ~~160 bytes~~ 152 bytes ``` p=function(x,n){paste(rep(x,n),collapse='')} function(w,h){f=p(' ',w*2-2) cat(paste0(p('/\\',w),'\n',p(paste0('\\',f,'/\n/',f,'\\\n'),h-1),p('\\/',w)))} ``` [Try it online!](https://tio.run/##TYxBCsMgEEX3OYW7mSkTbEO7zE3ciCgpBCPRkkDI2e1EKHQ3/73/Z601qVGFT3TlvUTcOdKRbC4eV59aZLfMs03ZjwB0dvm/vvFERxCSEBTwdhv6gTpnC7YfdxSujRFDDCYCp5@AiwYWG3U7jBFPPPUPkpZEfa2IzprxyS@qXw "R – Try It Online") Thanks BLT for shaving off 8 bytes. [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 123 bytes ``` ?1-sesf[/\]su[lfsh[lunlh1-dsh0<q]dsqx]dsrx[[ \]P[lf2*2-st[32Plt1-dst0<z]dszx]dsmx[/ /]Plmx92Ple1-dse0<l]slle0<l10P[\/]sulrx ``` It's far from the shortest, but, if one takes the last two lines and rotates them `pi/2` radians clockwise to an "upright" position, it kind of looks like a [totem pole](https://s-media-cache-ak0.pinimg.com/736x/58/e4/79/58e4791f09400e842056c0aa7682f18d--vancouver-bc-canada-vancouver-british-columbia.jpg). Takes input as two space-separated integers. [Try it online!](https://tio.run/##Fc29CsMwDATgPU/RuWD8UwotGPoK3mVNtYMHpZDIAZGXd@XlbrgPrnzH@HjDlVewGfkEWrkBnT9q3hRuLu5YeBeNQwCWjElJuAfDHR4hUZ@su3ipuCbbBOxiMdEmb93r3KuLhEw027sE2eoVHTLG8/b6Aw "dc – Try It Online") [Answer] # Mathematica, 116 bytes ``` (c=Column;o=Table;v=""<>o[" ",2*#-2];w=""<>o["/\\",#];c[{w,c@o[c[{"\\"<>v<>"/","/"<>v<>"\\"}],#2-1],Rotate[w,Pi]}])& ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 18 bytes ``` Ài/\Ùæ$Àäkllòjjkè ``` Answer wouldn't require the `ll` if `<M-h>ollow` left 2 char columns alone :( [Try it online!](https://tio.run/##ASIA3f92///DgGkvXBvDmcOmJMOAw6RrbGzDsmpqa8Oo////OP84 "V – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 188 bytes ``` a=>b=>string.Join("\n",new int[2*b].Select((x,i)=>string.Concat(string.Concat(new int[a].Select(y=>i%2==0?"/\\":"\\/")).Select((y,j)=>i>0&i<2*b-1&j>0&j<2*a-1?" ":""+y)))) ``` Byte count also includes: ``` using System.Linq; ``` [Try it online!](https://tio.run/##ZVBNT4NAED13f8VIYt21lALVi3VpGhMPRhNjTTxIDyuuug1dKrv9IE1/Ow5UMegkMG8@3puZTUw/yXJZrozS7zAtjJUL71bpzxEhWiykWYpEfufJjgBakgpjYFLjQ6YyY4VVCawz9Qp3QmnKmtKOdDrXK51cKm1d@EXG5jg0iuANeCl49MKjQ8q7yVDAibXjarkBbH4OT19m3lSmMrGUbl3Fmt6rTCfC0nb0QxMNqeCROg4598fOII6dCyeOBw5jjWbhzlFTRX5XXeKwftCdI54jFv1g7AAynF7B0MpRc9nh8GowTluubLuy@VCpBErrEnDA3UyWSu9Bild8YkkZgyMOepWmrEXctaLK1iIHhRK1lDddpsrSE/ekWX@Lq2vr3YvcSLrFsx6zSZ6LgrLRP62fNZ5yZWW9xxtVz/6M4T@YMehB9fJ/iHvSRnuyL8/cIQncAL@QhOhD9AHmhjWuPMZ@1eAjOnPPvwA "C# (.NET Core) – Try It Online") I started making explanation command-by-command but it stopped making sense midway... Basic gist is to make full spiky box, and then hollow out the middle. I used Linq for the sake of using Linq, probably can be shorter using just standard iterations. Here's explanation going middle-out (the inner-most command first): First, create rows for the full box, and concatenate to a single string ``` string.Concat(new int[a].Select(y => i % 2 == 0 ? "/\\" : "\\/")) ``` Then get each character in a row, and if it isn't the outline of the box, replace with space, concatenate them back into one string for each row ``` string.Concat(PREVIOUS_STEP.Select((y, j) => i > 0 & i < 2 * b - 1 & j > 0 & j < 2 * a - 1 ? " " : "" + y)) ``` Finally, get each row and concatenate them together with newlines (also includes generating of a collection for rows) ``` string.Join("\n", new int[2 * b].Select((x, i) => PREVIOUS_STEP)); ``` ]
[Question] [ In celebration of [HyperNeutrino](https://codegolf.stackexchange.com/users/68942/hyperneutrino) getting back his account and rep, [following Mr. Xcoder](https://codegolf.stackexchange.com/q/128075/20260). [![HyperNeutrino's flair](https://i.stack.imgur.com/vDxGx.png)](https://codegolf.stackexchange.com/users/68942/hyperneutrino) Apologies for rotating the picture for drawability. --- Print or output this ASCII art exactly. You may have trailing spaces and/or a trailing newline. ``` _______________ / \ / / \ \ / / \ \ / / \ \ / / \ \ / / \ \ \ / \ / \ / \ / \ _____________ / \_______________/ ``` This depicts one of the two resonance structures of the molecule [benzene](https://en.wikipedia.org/wiki/Benzene) [![enter image description here](https://i.stack.imgur.com/9tig3.png)](https://en.wikipedia.org/wiki/Benzene) Related: [Concentric hexagons](https://codegolf.stackexchange.com/questions/37440/draw-concentric-ascii-hexagons), [asterisk-filled hexagons](https://codegolf.stackexchange.com/questions/104604/could-you-make-me-a-hexagon-please) **Leaderboard:** ``` var QUESTION_ID=128104,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/128104/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] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes ``` ×_⁷↙←×_⁸↖⁶→↗⁶P×_⁸↘↓↙⁵‖B ``` [Try it online!](https://tio.run/##S85ILErOT8z5///w9PhHjdsftc181DYBzN7xqG3ao8Ztj9omPWqbDmS837MBJj7jUdtkkMrGrY8apr3fs@j/fwA "Charcoal – Try It Online") Explanation: Prints the lines in the following order, then reflects everything horizontally: ``` 5_______ / / 6 / ↙ / / ↗ / 4 / \ \ \ \ ↖ 1→_____ 3______←2 ``` [Answer] ## JavaScript (ES6), ~~144~~ ~~143~~ ~~140~~ ~~138~~ 134 bytes A recursive function drawing the output character by character with a purely conditional expression. ``` f=(p=363)=>(m=p%28-14,x=m<0?-m:m,y=p/28|0,p--)?`\\/ _ `[m+14?x<8-y&y<2|x<8&y>11?3:x==y+8|x==19-y|x==16-y&y>5&x>5?m<0^y>5:2:4]+f(p):'' ``` ### How? For each position **0 < p ≤ 363**, we define: * **m = (p MOD 28) - 14** * **x = | m |** * **y = ⌊ p / 28 ⌋** Below is a breakdown of the formula which picks the appropriate character from `[ '\', '/', ' ', '_', '\n' ]`. ``` m + 14 ? // if this is not an end of line: x < 8 - y & y < 2 | // if this is either part D x < 8 & y > 11 ? // or part E: 3 // output '_' : // else: x == y + 8 | // if this is either part A x == 19 - y | // or part B x == 16 - y & y > 5 & x > 5 ? // or part C: m < 0 ^ y > 5 // output '/' or '\' depending on the quadrant : // else: 2 // output a space : // else: 4 // output a Line-Feed ``` And below are the different parts in the coordinate system defined above: ``` | 13 12 11 10 09 08 07 06 05 04 03 02 01 00 01 02 03 04 05 06 07 08 09 10 11 12 13 ---+--------------------------------------------------------------------------------- 12 | . . . . . . E E E E E E E E E E E E E E E . . . . . . 11 | . . . . . B . . . . . . . . . . . . . . . B . . . . . 10 | . . . . B . . C . . . . . . . . . . . C . . B . . . . 09 | . . . B . . C . . . . . . . . . . . . . C . . B . . . 08 | . . B . . C . . . . . . . . . . . . . . . C . . B . . 07 | . B . . C . . . . . . . . . . . . . . . . . C . . B . 06 | B . . C . . . . . . . . . . . . . . . . . . . C . . B 05 | A . . . . . . . . . . . . . . . . . . . . . . . . . A 04 | . A . . . . . . . . . . . . . . . . . . . . . . . A . 03 | . . A . . . . . . . . . . . . . . . . . . . . . A . . 02 | . . . A . . . . . . . . . . . . . . . . . . . A . . . 01 | . . . . A . . D D D D D D D D D D D D D . . A . . . . 00 | . . . . . A D D D D D D D D D D D D D D D A . . . . . ``` ### Demo ``` f=(p=363)=>(m=p%28-14,x=m<0?-m:m,y=p/28|0,p--)?`\\/ _ `[m+14?x<8-y&y<2|x<8&y>11?3:x==y+8|x==19-y|x==16-y&y>5&x>5?m<0^y>5:2:4]+f(p):'' o.innerHTML = f() ``` ``` <pre id=o></pre> ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 50 bytes ``` •ι¡≠ït]4uƵŽΣ”9g½ùöèri|)á,ćè’∍é•5B3ÝJ"/ _\"‡4¡.B».∞ ``` [Try it online!](https://tio.run/##AV0Aov8wNWFiMWX//@KAos65wqHiiaDDr3RdNHXGtcW9zqPigJ05Z8K9w7nDtsOocml8KcOhLMSHw6jigJniiI3DqeKAojVCM8OdSiIvIF9cIuKAoTTCoS5Cwrsu4oie//8 "05AB1E – Try It Online") --- ***The compression:*** The strategy here was to build half the object, then mirror the image across the halfway mark. To do this, I first built the left half, with front padding: ``` 11111122222222 111110 11110110 1110110 110110 10110 0110 3 13 113 1113 1111311222222 11111322222222 ``` But no right padding, this is because the `.B` function in 05AB1E can be used to make every element equal in length using spaces. This allows for me to omit the extraneous spaces to the right and just delimit by newlines. I then, took this pattern, and removed all newlines replacing them with `4` to get: ``` 1111112222222241111104111101104111011041101104101104011043413411341113411113112222222411111322222222 ``` Compressing this with base-255 results in: ``` •ι¡≠ït]4uƵŽΣ”9g½ùöèri|)á,ćè’∍é•5B ``` Where the two `•` is denoting a base-255 compressed string and 5B is converting it to base-5. --- ***The second part, after the compressing:*** ``` 3ÝJ # Push '0123'. "/ _\" # Push '/ _\'. ‡ # Replace each in b with a on c. 4¡ # Split on 4's (the newlines I replaced). .B # Boxify for the mirror (adds padding to longest element). » # Join by newlines. .∞ # Mirror image. ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 61 bytes ``` i/ /±¹ \ \ \²µ /6ñGÙlxxhPHÄãxx>ñv$r_jwr w.Gkkl13r_jviwr_jd ``` [Try it online!](https://tio.run/##K/v/P1NfQUH/0MZDOxViFBRiuGIObTq0VUFf2uzwRvfDM3MqKjICPA63HF5cUWF3eGOZSlF8VnmRQrmee3Z2jqExkFeWWQ4kU/7/BwA "V – Try It Online") Hexdump: ``` 00000000: 692f 2020 2fb1 b920 5c20 205c 0a5c b2b5 i/ /.. \ \.\.. 00000010: 202f 1b36 f147 d96c 7878 6850 48c4 e378 /.6.G.lxxhPH..x 00000020: 783e f176 2472 5f6a 7772 2077 2e47 6b6b x>.v$r_jwr w.Gkk 00000030: 6c31 3372 5f6a 7669 7772 5f6a 64 l13r_jviwr_jd ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~226~~ ~~213 bytes~~ 179 bytes My first golf! ``` b,f,s,u='\/ _' print'\n'.join([s*6+u*15,s*5+f+s*15+b]+[s*(4-n)+'/ /'+s*(13+2*n)+'\ \\'for n in range(5)]+[s*n+b+s*(25-2*n)+f for n in 0,1,2,3]+[s*4+b+s*2+u*13+s*2+f,s*5+b+u*15+f]) ``` [Try it online!](https://tio.run/##PY7BDoIwEETvfsXetnQXkUK9@SXWGJtYxcNCKBz8@gp78DZ5eZOZ6bu8R3GlRE6ceb1gaOCOh2keZMEgePyMg5hrtmdabes5W0@J8hYp3mjjpq@lImygwQ2btiNndxAgBEzjDAKDwPyQ19P4SitCcVedr1VN8NdO3LLjTq1eLbfPdhqSjkf9QelWlfID "Python 2 – Try It Online") I tried looping the bits that I could find a pattern on, and hardcoded the rest. Setting the different characters to a variable helped save quite a lot of bytes. Edit: Decided to append to the same array instead of joining multiple times. Saved 13 bytes. Edit 2: Thanks to @ValueInk, @jacoblaw, @WheatWizard, @CalculatorFeline, and @Challenger5, saved 34 bytes [Answer] # [J](http://jsoftware.com/), 155 bytes ``` ('_ /\',LF){~5#.inv 95x#.32-~3 u:'0_C5NcBe''e2kA/jhk>5y~l<Z:AN<QG)V7m>l"x!@A-jp8E%XEh&"$''j(sP8Z!b#e7})]_,L"LCUu)kqsBQ5_5bt}`bq ":1cv(gU;|{I~n5q@(ISCK `'[< ``` [Try it online!](https://tio.run/##FcYLC8FQGIDhv/I5w7dT24x1wiyZhWTJJZJL09YyG2MNTTh/fXjrqTfMfS@4AFEAAf@BxEEF/UdWwJpJdj8X0YHKFn9LX5wJyjF@QJNlgqLVZK7BXUfVsdjY6/qIfi0yK2EQtdmTn4y1bo6N6YAu6@f2iWSFjimH10avtOoFZVJEDMV00lgXXMGvf@jOkWxiW4s7jZK0O2UOc2@fvZsA0aveQzwsWu/XkMcs6YjDuTWCPW6MnOZf "J – Try It Online") This is a function that expects no input. E.g., `f =: <code>` then `f ''`. ## Explanation I encoded this using the following steps. Assume that the desired compression string is contained in the variable `h`. ``` k=:'_ /\',LF *NB. the dictionary used to encode the string* k i. h *NB. numbers corresponding to indices in `k`* 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 4 1 1 1 1 2 1 1 2 1 1 1 1 1 1 1 1 1 1 1 3 1 1 3 4 1 1 1 2 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 3 4 1 1 2 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 3 4 1 2 1 1 2 1 1 1 ... 5x#.k i. h *NB. base 5 to decimal* 4571656960356964266407389291886526966074643634545109498506871241033015964671946641835339522170115810676380078148856766959449166714046433431522704650346045752930168245684048485736756807881102718244115576453623363843561553955078139 95#.inv 5x#.k i. h *NB. decimal to base 95* 16 63 35 21 46 67 34 69 7 69 18 75 33 15 74 72 75 30 21 89 94 76 28 58 26 33 46 28 49 39 9 54 23 77 30 76 2 88 1 32 33 13 74 80 24 37 5 56 37 72 6 2 4 7 74 8 83 48 24 58 1 66 3 69 23 93 9 61 63 12 44 2 44 35 53 85 9 75 81 83 34 49 21 63 21 66 84 93 64 66 8... quote u:32+95#.inv 5x#.k i. h *NB. base 95 to ASCII repr of string* '0_C5NcBe''e2kA/jhk>5y~ll"x!@A-jp8E%XEh&"$''j(sP8Z!b#e7})]_,L"LCUu)kqsBQ5_5bt}`bq ":1cv(gU;|{I~n5q@(ISCK `' ``` Then, we just need to decode this. `5#.inv 95x#.32-~3 u:` performs the inverse of what I just described, giving us the list of indices. Then, `('_ /\',LF){~` applies the appropriate characters to each index. [Answer] # Mathematica, 227 bytes ``` t=Table;T[x_,y_,z_,v_]:=""<>{x,y~t~v,z};Column[Join[b={""<>"_"~t~15},{T["/"," ","\\",15]},t[T["/ /"," ","\\ \\",i],{i,11,19,2}],t[T["\\"," ","/",i],{i,25,19,-2}],{T["\\ ","_"," /",13]},{""<>{"\\",b,"/"}}],Alignment->Center] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 47 43 41 bytes ``` ↗⁶F¹⁵_↓↘⁶←↙⁶↷⁴↑F¹⁵_↖⁶M⁴→↗⁵M¹¹→↓↘⁵M⁵↙↑F¹³_ ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9R2/RHjdve71l2aOejxq3xj9omP2qbARR51DbhUdtMMGP7o8Ytj9omIqmZBtayFiw@CWzCViD30E6gPIgPMWIrWMVWkClQzYc2x///DwA "Charcoal – Try It Online") I did not know a thing about Charcoal until right now, I felt like "I have no idea of what I'm doing" while trying to figure out this answer... I'm quite sure this can be golfed a lot. Updates: * I managed to save 4 bytes learning to use cursor directions and movements! * 2 more bytes saved after realizing the drawing was not exactly as asked. ^\_\_^U [Answer] # Ruby, 117 bytes ``` 13.times{|i|s=[?_*(15--i%12*1.3),"/%#{i*2+8}s"%?\\,''][(i%12%11+3)/5].center(27) i>0&&(s[i-=7]=?\\)&&s[~i]=?/ puts s} ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~129~~ ~~114~~ 102 bytes *Thanks to ovs for -12 bytes!* ``` 6eea¶5/15\¶4c1b3c3b2c5b1c7bc9b\25d1\23d2\21d3\19d4\2ee_2d5\eea/ e aa d /¶ c /2/1 b \2\¶ a ___ \d+ $* ``` [Try it online!](https://tio.run/##Dcy7DcMwDAXA/k3hIpVdCKSsBN6FgMBfkSZFkNk0gBZTPMDdN3/vj66FZ6bO0Qo1meN0surV2JuRv8wvE25BwjVYmKIKXXEKZ3aOJrctSKgiUOaAo3AhGITvDYreOyQOPPZtrT8 "Retina – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~92~~ ~~86~~ 80 bytes ``` '_15×6ú'/5úð8׫.∞5F'/4N-ú'/2ú«ð6N+׫.∞}4F'\Núð13N-׫.∞}'\4ú'_7×2ú«.∞'\5ú'_8׫.∞» ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fPd7Q9PB0s8O71PVND@86vMHi8PRDq/UedcwzdVPXN/HTBUkYHd51aPXhDWZ@2jDJWhM39Rg/kHpDY6AamKh6jAlQfbz54elgLSAx9RhTkBDc2EO7////mpevm5yYnJEKAA "05AB1E – Try It Online") --- ## Explanation in parts The bar at the top ``` '_ # underscore 15× # repeated 15 times 6ú # with 6 spaces in front ``` The line immediately below the bar ``` '/ # forward slash 5ú # with 5 spaces in front ð # space 8× # repeated 8 times « # concatenated with the earlier string .∞ # intersected mirror (i.e middle space not affected) # mirroring: " / " => " / \ " ``` The remainder of the upper portion of the hexagon ``` 5F # for N in 0..4 '/ # forward slash 4N- # 4 - N ú # spaces in front of the slash '/ # another forward slash 2ú # with 2 spaces in front « # concatenated with the other string ð # a space character 6N+ # N + 6 × # times « # concatenated with the other string .∞ # intersected mirror } # end for ``` The remainder except for the last 2 lines ``` 4F # for N in 0 .. 3 '\ # backslash Nú # with N spaces in front ð # a space 13N- # 13 - N × # repeated « # concatenated with other string .∞ # intersected mirror } # end for ``` The second to last line ``` '\ # backslash 4ú # with 4 spaces in front '_ # underscore 7× # repeated 7 times 2ú # with 2 spaces in front « # concatenated with earlier string .∞ # intersected mirror ``` The last line ``` '\ # backslash 5ú # with 5 spaces in front '_ # underscore 8× # repeated 8 times « # concatenated with other string .∞ # intersected mirror ``` The `»` at the end joins everything on newlines. [Answer] # C#, 210 199 bytes Encodes the length of space runs and underscore runs: ``` var h=@"5KL4/>\L3/1/:\1\L2/1/<\1\L1/1/>\1\L0/1/@\1\L/1/B\1\L\H/L0\F/L1\D/L2\B/L3\1I1/L4\K/L";for(var i='M';--i>'/';)h=h.Replace(""+i,i>75?"\n":"".PadLeft(i>72?i-60:i-47," _"[i/73]));Console.Write(h); ``` Ungolfed: ``` var h = @"5KL4/>\L3/1/:\1\L2/1/<\1\L1/1/>\1\L0/1/@\1\L/1/B\1\L\H/L0\F/L1\D/L2\B/L3\1I1/L4\K/L"; for (var i = 'M'; --i > '/'; ) h = h.Replace("" + i, i > 75 ? "\n" : "".PadLeft(i > 72 ? i - 60 : i - 47, " _"[i / 73])); Console.Write(h); ``` [Try It Online!](https://tio.run/##Fc1Ba4MwGMbxrxJyMWHV16idYKYt3RgbTaFshx6aMYJN5wtOh3GFUfrZnTn9fzyXp3Zh3Q92@nXYfZH3Pzfab1m3xjmyv7rRjFiTS48nsjPYMX6dLmYgTbmmy63KoNIqBQGFFlolMx48xIzKI56x9pi78dUvoGL9DEroJ1CJ3oBKtXgVoDK9BUXluR@YP8Ay2AUyDLEKIJC8KZvozf60praM0jtcYJUvV1R3tKA02puTsueRzWOywvA@LjDM8gUln/SIkKcfnMvHvnN9a6PDgKNlDZfT7Tb9Aw) [Answer] # [Retina](https://github.com/m-ender/retina), 129 bytes ``` 5$* ¶ \G (?=( *)) ¶$1/ /$`11$* $`\ \ r`(?<=( *)) \G $1\$'19$* $'/¶ ^ 6$* 15$*_¶5$* /15$* \ ¶$ ¶ \ 13$*_ /¶5$* \15$*_/ ``` [Try it online!](https://tio.run/##JY0xDgIxDAR7v2ILS5e7xrIQSEigK@8TFoSCgobixNvygHwsbC6uVtrZ8f7@fb6v1uSsC2oBT2JDWu8JyzxLLeoGmGZ3EpoDCNlzWm@DQGyiHjr5tfeT1SIPuTA7lc9auth65o42GU@o8RN7qgcSB26t/QE "Retina – Try It Online") Completely different approach, yet coincidentally the same length! [Answer] # [Paintbrush](https://github.com/alexander-liao/paintbrush), 43 bytes, non-competing ``` 13→'_8×←↓s/5{↙s/3→s/3←}↓'\6×↘↑'_8×→↖'_7×←▕┣ ``` ### Explanation ``` 13→'_8×←↓s/5{↙s/3→s/3←}↓'\6×↘↑'_8×→↖'_7×←▕┣ Program 13→ Move the pointer 13 spaces right '_ Push '_' onto the stack 8× Multiply it 8 times ← Draw out '________' moving to the left ↓ Move down s/ Set that cell to a slash 5{ } Execute function 5 times ↙ Move the pointer one spot down and one spot to the left s/ Set that cell to a slash 3→ Move 3 spaces right s/ Set that cell to a slash 3← Move 3 spaces left ↓ Move down '\ Push r'\' 6× Multiply it 6 times ↘ Draw out r'\\\\\\' moving down-right ↑ Move up '_ Push '_' 8× Multiply it 8 times → Draw out '________' moving to the right ↖ Move the pointer one spot up and one spot to the right '_ Push '_' 7× Multiply it 7 times ←▕┣ Draw out '_______' moving to the left ▕ Remove the rightmost column ┣ Mirror the entire grid to the right, overlapping the inner column, flipping some characters that have backwards variants ``` Beta Testing in the Real World: ``` Charcoal: 1 Paintbrush: 0 ``` Gotta make a lot of improvements, huh. :P [Answer] # [///](https://esolangs.org/wiki////), 152 bytes ``` /,/ //'/\\!!!//&/\\"\\ //%/\/"\/!!//#/_____//"/,\\//!/,, /! ### !\/!!!\\ ,"% \& "% "&"%!\& \%!"&\%!,"&\'!!\/ \'! "/ "'! \/ "',"/ ,"\,##___"/ !\\###\/ ``` [Try it online!](https://tio.run/##FU07CkMxDNtzClsmyWLQhQSlQ6FDt3d/UsWDPkaWn9/7@X6ec9iMIDelzCSXBaRBTooQ77L4ukOCLZHJ7mBGVY28kfRFY4ZWGLEw01IzsQxt3M5whDnAAdO12G3XUFf5gbWb3Cqe8wc "/// – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~58~~ 55 bytes ``` '/__\ '7XyP9BY+3l7:14&(6Xy_3TF_5M&(&v0'Zj'(t2&P_h)[]9Z( ``` [**Try it online!**](https://tio.run/##y00syfn/X10/Pj5GQd08ojLA0ilS2zjH3MrQRE3DLKIy3jjELd7UV01DrcxAPSpLXaPESC0gPkMzOtYySuP/fwA) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 111 bytes ``` J\/K\\+*6d*15\_+++*5dJ*15dKV5+++*-5hNd"/ /"*+yN11d+++KddK)V4+++*NdK*-25yNdJ)+++++*4dK*2d*13\_*2dJ+++*5dK*15\_J ``` This code basically prints the lines one after another (in the naive way of doing it). Yeah it sucks, but right now I'm in no state of doing better, and I too still wanted to pay tribute to [HyperNeutrino](https://chat.stackexchange.com/users/281362). [Try it online!](https://pyth.herokuapp.com/?code=J%5C%2FK%5C%5C%2B%2A6d%2A15%5C_%2B%2B%2B%2A5dJ%2A15dKV5%2B%2B%2B%2A-5hNd%22%2F%20%20%2F%22%2A%2ByN11d%2B%2B%2BKddK%29V4%2B%2B%2B%2ANdK%2A-25yNdJ%29%2B%2B%2B%2B%2B%2A4dK%2A2d%2A13%5C_%2A2dJ%2B%2B%2B%2A5dK%2A15%5C_J&debug=0) [Answer] # [PHP](https://php.net/), 122 bytes ``` <?=gzinflate(base64_decode("ddDBDQAgCEPRO1N0AxYicf8tFK2JIPT4HycA34iTHRVxJqwvGLvme8LXrxRAKoVmBZypoMNFjbmUtMEl/OV2WHqYTg")); ``` [Try it online!](https://tio.run/##K8go@P/fxt42vSozLy0nsSRVIymxONXMJD4lNTk/JVVDKSXFxckl0DHd2TUgyN/Qz8CxIjIzOc2ixM3byMszIMTEozLZ0dgkM8QjKKzCq7C8zN2nLDfVwieiqCLI0Ts/LNcpqrIg39fPLSspN7TE1zVH3z/MKNyjMDIkXUlT0/r//695@brJickZqQA "PHP – Try It Online") # [PHP](https://php.net/), 158 bytes ``` for(;~$c='f000 e/o1d/b/k\b1c/b/m\b1b/b/o\b1a/b/q\b1/b/s\b1\y/ a\w/ b\u/ c\s/ d\b00___b/ e\000/'[$i++];)echo$c>_?str_pad("",ord($c)^96):strtr($c,[_____,"\ "]); ``` [Try it online!](https://tio.run/##FcxBCoMwEAXQ/RwjBDQYmLgptLb1II4NJlGUUpJGS@mmV7fTWfzH/4tJc9rPbeKcYi6br/SXYjLGwIixDujwTq727IN1bGQH9skyK0MfhIHeCI5eCJ5WhEDOGGutQxiJ32HRyaWq@kaNfo7SX227btmmIZRC6JhDKb26HQ/qxPOWuenO/k8LAtGrZt9/ "PHP – Try It Online") # [PHP](https://php.net/), 165 bytes ``` <?=strtr("5566666 57/3334 5 13552513352713332 13355 213335 2433335 0 433355 0743333054333505 476666_ 057466666/",[" / ","/ /","\ \ "," ","\\"," ",___," "]); ``` [Try it online!](https://tio.run/##JYwxDsIwFEP3nsL6E0hFSfNjMgDiIBRFqELqBFXp1ZlDfvBg@3nwMi@lnK@Xz7Zu607Io6ljcqoaO2JQMnBQZUjVNcA6EQxqRG3pYaXuPrXFs7EnYrLHDM8U27mT/iZwnfTigEoyAqMhTMbjH6TPOVuT@/5Uyvf1PkyPaX7@AA "PHP – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~53~~ 52 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` /↕Υ¦‛¾}`¼Pσ↕ΗΦ▒∙⌠N►4┼ΥjΠ⌡jOT?»m,┌∆Χ⁶↑┌≠Γ‽‼║%Ν□‘7«n╬⁷ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=LyV1MjE5NSV1MDNBNSVBNiV1MjAxQiVCRSU3RCU2MCVCQ1AldTAzQzMldTIxOTUldTAzOTcldTAzQTYldTI1OTIldTIyMTkldTIzMjBOJXUyNUJBNCV1MjUzQyV1MDNBNWoldTAzQTAldTIzMjFqT1QlM0YlQkJtJTJDJXUyNTBDJXUyMjA2JXUwM0E3JXUyMDc2JXUyMTkxJXUyNTBDJXUyMjYwJXUwMzkzJXUyMDNEJXUyMDNDJXUyNTUxJTI1JXUwMzlEJXUyNUExJXUyMDE4NyVBQm4ldTI1NkMldTIwNzc_) [Answer] # [Python 2](https://docs.python.org/2/), 187 bytes ``` a=`int("7YSUQZDJS0I3J2QJ40G9WNPIRBTBC1KF0F3X5WDMBW8CG5BVDHBJQ71V3UHCSY3TR8LC4IIEE5SZ",36)`[:-1] for i in"0666666_!6__!5/!3\\!9\n!844!422!211!1 ".split("!"):a=a.replace(i[0],i[1:]) print a ``` [Try it online!](https://tio.run/##Hc7JCoJAGADge0/hP6eEltk0E7yMtmgLmZqZig1RNBAm1qWnt@h7gq/5vO/PmnaddM6qfvfRJIuS8OQFEfZZQMOA48U03e78vYiFS1ZzPGdHI/U2IrXchSEO3lIE4YQcWLJ0o4zFe2vtct@fzYzohAbM1M@5PSRl7/ZsNaWpGmHzrwKzqsAYAysKmBY1WJwDpxQoIUA0NHo1D/X7ANJt6chRe20e8nLtqxyXA5UTu9R7Tfsra7Lrvg "Python 2 – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 169 bytes ``` var d=new char[364];for(int i=10;i-->0;)for(int j="ppnggffggn"[i]-97;j-->0;)d[28*"amlhbccbha"[i]+"ggh{fguva|"[i]-2813+j*("b|~}"[i/3]-97)]="_/\\\n"[i/3];Console.Write(d); ``` Ungolfed: ``` var d = new char[364]; for (int i = 10; i-- > 0; ) for (int j = "ppnggffggn"[i] - 97; j-- > 0; ) d[28 * "amlhbccbha"[i] + "ggh{fguva|"[i] - 2813 + j * ("b|~}"[i / 3] - 97)] = "_/\\\n"[i / 3]; Console.Write(d); ``` For each stroke I encoded the start position, length, character used, and direction within various strings. I saved a few bytes by grouping up similar strokes. Sadly, this prints a little weird in tio. This is because I'm not printing out real spaces. Looks fine in my console, though. So probably this submission doesn't count. Here's the link anyways. [Try it online! (fake spaces 169 bytes)](https://tio.run/##NczNC4IwHMbxf2XspIaVGb0w7NI5CDp0UIk55/yJbbJNI8z@dXuj6@f58jDjM6X52BqQAp3uxvIrYTU1Bh17Y6kFhjoFOTpQkI7bjx3VKI8kvyFWUh2Hq2VKCqUdkBZBFMwJ@P5uTty/VRFuGilEUQghcQypv12T6tfk8WLjYXqty4yxrKSfeYKFKPtCtB19fPPFJggnlefg7PEc3jILPxduGuHLLEkS@SOyV9Komk/PGix3cpeMwzC@AA "C# (.NET Core) – Try It Online") [Try it online! (real spaces 191 bytes)](https://tio.run/##NYxda8IwGEb/yktuTHT1q7I5QgfD68FAYRdWRpqm6VtqIknskFr/eucH3p7nnEf6SFqn@qNHo2F98kHtuayF9/Dd@iACSmgs5vAl0FDW9o1wkEMCRv3BOrhrRQcweIlfF2y8satSuE/nxIkyXlhH0QTAZDblGEUfU86erErI4WC0LgqtDdniLnp/49XDybfz5ZCIfV1mUmaluM0jonXZFvrYiPNdny9n8agaUpKdL92VTOLbBdsl5HeSpql5IL6yxttajX8cBkVzxvuu6/8B) [Answer] # [Python 2](https://docs.python.org/2/), ~~154~~ 138 bytes ``` print'eNp10MEJAEEIA8C/VaSDNBTY/rtYlByci+aZER8BMqcnqiR6FG7/IPd87w0c/pQMYBrFJmxhQDstljJSQUrb5euhZzBe6PI3aQ=='.decode('base64').decode('zip') ``` [Try it online!](https://tio.run/##PcjNCoIwAADgx1kSNPtTLx5czlBQnFagtzkHLkznXJS@/Lr1HT@56G4cDsZIJQYNeCb3doqTAOM48C7wQcswQ7cKKl31aGFiS2tceCid2DCJwomuLozz1nM/NoOSpBVSUfL6diScdf9MSnJXzZm/u3pF3MnjIyW@D3YtZ2PLN6ChM3dOwPrHKiSwjPkB "Python 2 – Try It Online") [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), ~~67~~ 54 bytes ``` 00000000: 55c9 310d 0040 0804 c1fe 55e0 0043 24f8 [[email protected]](/cdn-cgi/l/email-protection)$. 00000010: 77f1 c955 cc96 3b95 d65e 6697 4d76 0b93 w..U..;..^f.Mv.. 00000020: cf06 f847 0448 d1e6 0ceb 5722 8421 1010 ...G.H....W".!.. 00000030: d95b 7e60 ad3f .[~`.? ``` [Try it online!](https://tio.run/##dY67DkFBFEV7X7GJ@uTMe4aCREGjFIVEmJeG8tL59Ws8O6vcJ3udHbsYz@XUXfqeP0xgTApQgjOYNYM9ayRRSzsUfmYKUlcPbEgQzamxIVqMafA2iOZwrgqkYAxSChYqBoNsTYG1wUFnZ8ExKOD2Kk@J9pXWV/o6ZHOkyhbVawfW2iOL0kqpRBgnJbyWAqI9A9qAJa2eO7YjGv4cqjlyMBGuWMYxq4r/0O5@oFnfPwA "Bubblegum – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 200 bytes ``` char o[28];i,j,k,p;f(){for(k=0;k<39;puts(o))for(memset(o,k&&k<32?32:95,27),i=3;i--;k++)for(j=3;j--;o[24-i*3+j]=" _\\/"[p])o[i*3+2-j]=" _/\\"[p="U@@@B@HH@``@@BB@HH@``@@p@@L@@C@p@EL@UC@"[k]-64>>j*2&3];} ``` [Try it online!](https://tio.run/##PY/NCsIwEITP9ilKDyWxCUrif6wuiuDBq6c2aClVk1BTbD0Vn71GBU8z8@0yMDm95nnX5bfs4duEzaRQRBNDKnFBuL3YBzLxUJgln4vq2dTIYvyBZVHWRYMsMWHojmzN2WI@JmyKiYq5UJQKE0XfV@2ydtm1j6jq80jLOPBPaToIkkpim3wYoz86SFNH4@AIABvY7@F8dubvKoADwNbp7gDHLQSJkXQyWq10n4Vcilen7o1fZuqOsNd6PbdBeK/uDQ "C (gcc) – Try It Online") [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), 872 bytes ``` {iii}iicccccc{iiiiii}iii{c}ccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}ddddd{c}ccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcc{i}iiiiic{d}ddddd{c}c{iiiiii}c{dddddd}cc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddcc{i}iiiiic{d}ddddd{c}ccc{iiiiii}c{dddddd}cc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddcc{i}iiiiic{d}ddddd{c}ccccc{iiiiii}c{dddddd}cc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddcc{i}iiiiic{d}ddddd{c}ccccccc{iiiiii}c{dddddd}cc{iiiiii}c{{d}ii}ddc{iiii}dddc{d}dddddcc{i}iiiiic{d}ddddd{c}ccccccccc{iiiiii}c{dddddd}cc{iiiiii}c{{d}ii}ddc{{i}dd}iic{dddddd}{c}{c}ccccc{i}iiiiic{dddd}iiic{ii}iic{iiiiii}c{dddddd}{c}{c}ccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}{c}{c}c{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}ccccccccc{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cc{iiiiii}iii{c}ccc{dddddd}dddcc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciii{c}ccccc{ddddd}iic ``` [Try it online!](https://tio.run/##lZPRDoAgCEW/qI9qUovnHpnfTooKTtOpLw655yxywnXCje9zMBMiekQnKxapRnI@HRGE0kNcsV@yJKlQhL40FcgOIyusowYik8gR@Ll3Ves2xeveTfOOeEOdLmpNuqyluMlH51hw2NDqBwmhTdjIlRozQ2iC/DLViGNwNr8@gNJq/2ZvM139eiAnHfMH "Deadfish~ – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 45 bytes ``` »R√UǏ8x⟑9↓ḋSŀ«+Ġ↵‡⊍6-}h≥kẇ⊍ḣW£»`/ _\,`τ⌐øŀ⁋øM ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCu1LiiJpVx484eOKfkTnihpPhuItTxYDCqyvEoOKGteKAoeKKjTYtfWjiiaVr4bqH4oqN4bijV8KjwrtgLyBfXFwsYM+E4oyQw7jFgOKBi8O4TSIsIiIsIiJd) ]
[Question] [ ### Introduction For the ones who don't know, a palindrome is when a string is equal to the string backwards (with exception to interpunction, spaces, etc.). An example of a palindrome is: ``` abcdcba ``` If you reverse this, you will end up with: ``` abcdcba ``` Which is the same. Therefore, we call this a palindrome. To palindromize things, let's take a look at an example of a string: ``` adbcb ``` This is not a palindrome. To palindromize this, we need to merge the reversed string into the initial string **at the right of the initial string**, leaving both versions intact. The shorter, the better. The first thing we can try is the following: ``` adbcb bcbda ^^ ^^ ``` Not all characters match, so this is not the right position for the reversed string. We go one step to the right: ``` adbcb bcbda ^^^^ ``` This also doesn't match all characters. We go another step to the right: ``` adbcb bcbda ``` This time, **all characters match**. We can *merge* both string *leaving the intact*. The final result is: ``` adbcbda ``` This is the *palindromized string*. --- ### The Task Given a string (with at least one character) containing only **lowercase letters** (or uppercase, if that fits better), output the **palindromized string**. --- ### Test cases ``` Input Output abcb abcba hello hellolleh bonobo bonobonob radar radar hex hexeh ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! [Answer] # Pyth (commit b93a874), 11 bytes ``` .VkI_IJ+zbB ``` [Test suite](https://pyth.herokuapp.com/?code=.VkI_IJ%2BzbB&test_suite=1&test_suite_input=abcb%0Abonobo%0Aradar%0Ahex&debug=0) This code exploits a bug in the current version of Pyth, commit [b93a874](https://github.com/isaacg1/pyth/commit/b93a8740ed847dadfeab62e1b01db815d0d88775). The bug is that `_IJ+zb` is parsed as if it was `q_J+zbJ+zb`, which is equivalent to `_I+zb+zb`, when it should (by the design intention of Pyth) be parsed as `q_J+zbJ`, which is equivalent to `_I+zb`. This allows me to save a byte - after the bug is fixed, the correct code will be `.VkI_IJ+zbJB`. I'll explain that code instead. Basically, the code brute forces over all possible strings until it finds the shortest string that can be appended to the input to form a palindrome, and outputs the combined string. ``` .VkI_IJ+zbJB z = input() .Vk For b in possible strings ordered by length, +zb Add z and b, J Store it in J, _I Check if the result is a palindrome, I If so, J Print J (This line doesn't actually exist, gets added by the bug. B Break. ``` [Answer] ## Python, 46 bytes ``` f=lambda s:s*(s==s[::-1])or s[0]+f(s[1:])+s[0] ``` If the string is a palindrome, return it. Otherwise, sandwich the first letter around the recursive result for the remainder of the string. Example breakdown: ``` f(bonobo) b f(onobo) b b o f(nobo) o b b o n f(obo) n o b b o n obo n o b ``` [Answer] ## Haskell, 36 bytes ``` f s|s==reverse s=s|h:t<-s=h:f t++[h] ``` More readably: ``` f s |s==reverse s = s |(h:t)<-s = h:(f t)++[h] ``` If the string is a palindrome, return it. Otherwise, sandwich the first letter around the recursive result for the tail of the string. The string `s` is split into `h:t` in the second guard, obviating a filler `1>0` for this case. This is shorter than doing `s@(h:t)` for the input. [Answer] # Jelly, ~~11~~ 10 bytes ``` ṫỤfU$Ḣœ^;U ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmr4bukZlUk4biixZNeO1U&input=&args=aGVsbG8) ### How it works ``` ṫỤfU$Ḣœ^;U Main link. Argument: s (string) Ụ Yield all indices of s, sorted by their corr. character values. ṫ Tail; for each index n, remove all characters before thr nth. This yields the list of suffixes of s, sorted by their first character, then (in descending order) by length. $ Combine the two links to the left into a chain: U Upend; reverse all suffixes. f Filter; only keep suffixes that are also reversed suffixes. This gives the list of all palindromic suffixes. Since all of them start with the same letter, they are sorted by length. Ḣ Head; select the first, longest palindromic suffix. œ^ Multiset symmetric difference; chop the selected suffix from s. U Upend; yield s, reversed. ; Concatenate the results to the left and to the right. ``` [Answer] # Pyth - ~~16~~ 12 bytes *4 bytes saved thanks to @FryAmTheEggman.* FGITW, much golfing possible. ``` h_I#+R_Q+k._ ``` [Test Suite](http://pyth.herokuapp.com/?code=h_I%23%2BR_Q%2Bk._&input=%22adbcb%22&test_suite=1&test_suite_input=%22abcb%22%0A%22hello%22%0A%22bonobo%22%0A%22radar%22%0A%22hex%22&debug=0). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~16~~ ~~6~~ 5 bytes (Non-competing) ``` :Ac.r ``` [Try it online!](http://brachylog.tryitonline.net/#code=OkFjLnI&input=ImJvbm9ibyI&args=Wg) When I posted my initial answer, it was still on the old implementation in Java. Since I have reprogrammed everything in Prolog, it now works as it should have in the first place. ### Explanation ``` (?):Ac. Output is the concatenation of Input with another unknown string A .r(.) The reverse of the Output is the Output ``` Backpropagation makes it so that the first valid value for `A` it will find will be the shortest that you can concatenate to Input to make it a palindrome. ### Alternate solution, 5 bytes ``` ~@[.r ``` This is roughly the same as the above answer, except that instead of stating "Output is the concatenation of the Input with a string `A`", we state that "Output is a string for which the Input is a prefix of the Output". [Answer] ## JavaScript (ES6), 92 bytes ``` (s,a=[...s],r=a.reverse().join``)=>s.slice(0,a.findIndex((_,i)=>r.startsWith(s.slice(i))))+r ``` Computes and slices away the overlap between the original string and its reversal. [Answer] # Retina, ~~29~~ 25 ``` $ ¶$_ O^#r`.\G (.+)¶\1 $1 ``` [Try it online!](http://retina.tryitonline.net/#code=JArCtiRfCk9eI3JgLlxHCiguKynCtlwxCiQx&input=Ym9ub2Jv) Big thanks to [Martin](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) for 11 bytes saved! This just creates a reversed copy of the string and smooshes them together. The only really fancy part of this is the reversing method: `O^#r`.\G`, which is done by using sort mode. We sort the letters of the second string (the ones that aren't newlines and are consecutive from the end of the string, thanks to the `\G`) by their numeric value, which, since there are no numbers, is 0. Then we reverse the order of the results of this stable sort with the `^` option. All credit for the fancy use of `\G` belongs to Martin :) [Answer] # CJam, 18 ``` q__,,{1$>_W%=}#<W% ``` [Try it online](http://cjam.aditsu.net/#code=q__%2C%2C%7B1%24%3E_W%25%3D%7D%23%3CW%25&input=bonobo) **Explanation:** ``` q read the input __ make 2 copies ,, convert the last one to a range [0 … length-1] {…}# find the first index that satisfies the condition: 1$> copy the input string and take the suffix from that position _W%= duplicate, reverse and compare (palindrome check) < take the prefix before the found index W% reverse that prefix at the end, the stack contains the input string and that reversed prefix ``` [Answer] ## Lua, ~~89~~ 88 Bytes I beat the Javascript! \o/ **Saved 1 byte thanks to @LeakyNun ^^** It's a full program, takes its input as command-line argument. ``` i=1s=...r=s:reverse()while s:sub(i)~=r:sub(0,#r-i+1)do i=i+1 end print(s..r:sub(#r-i+2)) ``` ## ungolfed ``` i=1 -- initialise i at 1 as string are 1-indexed in lua s=... -- use s as a shorthand for the first argument r=s:reverse() -- reverse the string s and save it into r while(s:sub(i)~=r:sub(0,#r-i+1))-- iterate while the last i characters of s do -- aren't equals to the first i characters of r i=i+1 -- increment the number of character to skip end print(s..r:sub(#r-i+2)) -- output the merged string ``` [Answer] # Prolog, 43 bytes ``` a(S):-append(S,_,U),reverse(U,U),writef(U). ``` This expects a codes string as input, e.g. on SWI-Prolog 7: `a(`hello`).` ### Explanation This is basically a port of my Brachylog answer. ``` a(S) :- % S is the input string as a list of codes append(S,_,U), % U is a list of codes resulting in appending an unknown list to S reverse(U,U), % The reverse of U is U writef(U). % Write U to STDOUT as a list of codes ``` [Answer] # Octave, ~~78~~ 75 bytes Saved 3 bytes thanks to Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ! ``` function p=L(s)d=0;while~all(diag(s==rot90(s),d++))p=[s fliplr(s(1:d))];end ``` ideone still fails for named functions, but [here](http://ideone.com/JSDPVJ) is a test run of the code as a program. [Answer] # Perl, 37 bytes Based on xnor's answer. Includes +2 for `-lp` Run with input on STDIN, e.g. ``` palindromize.pl <<< bonobo ``` `palindromize.pl`: ``` #!/usr/bin/perl -lp s/.//,do$0,$_=$&.$_.$&if$_!~reverse ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes ``` Ṙ⋎ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZjii44iLCIiLCJyYWNlYyJd) ``` ⋎ # Merge on longest prefix/suffix with... Ṙ # Input reversed ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 18 bytes Code: ``` ©gF¹ðN×®«ðñD®åi,q ``` Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w4LCqWdGwrnDsE7Dl8KuwqvDsMOxRMKuw6VpLHE&input=Ym9ub2Jv) [Answer] ## Pyke, 15 bytes ``` D_Dlhm>m+#D_q)e ``` [Try it here!](http://pyke.catbus.co.uk/?code=D_Dlhm%3Em%2B%23D_q%29e&input=radar) [Answer] ## J, 20 bytes ``` ,[|.@{.~(-:|.)\.i.1: ``` This is a monadic verb. [Try it here.](http://tryj.tk) Usage: ``` f =: ,[|.@{.~(-:|.)\.i.1: f 'race' 'racecar' ``` ## Explanation I'm using the fact that the palindromization of **S** is **S + reverse(P)**, where **P** is the shortest prefix of **S** whose removal results in a palindrome. In J, it's a little clunky to do a search for the first element of an array that satisfies a predicate; hence the indexing. ``` ,[|.@{.~(-:|.)\.i.1: Input is S. ( )\. Map over suffixes of S: -: Does it match |. its reversal? This gives 1 for palindromic suffixes and 0 for others. i.1: Take the first (0-based) index of 1 in that array. [ {.~ Take a prefix of S of that length: this is P. |.@ Reverse of P. , Concatenate it to S. ``` [Answer] ## Haskell, 68 bytes ``` import Data.List f i=[i++r x|x<-inits i,i++r x==x++r i]!!0 r=reverse ``` Usage example: `f "abcb"` -> `"abcba"`. Search through the `inits` of the input `i` (e.g. `inits "abcb"` -> `["", "a", "ab", "abc", "abcb"]`) until you find one where it's reverse appended to `i` builds a palindrome. [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~17~~ 16 bytes Loosely inspired in [@aditsu's CJam answer](https://codegolf.stackexchange.com/a/77103/36398). ``` `xGt@q:)PhttP=A~ ``` [**Try it online!**](http://matl.tryitonline.net/#code=YHhHdEBxOilQaHR0UD1Bfg&input=J2Jvbm9ibyc) ### Explanation ``` ` % Do...while loop x % Delete top of stack, which contains a not useful result from the % iteration. Takes input implicitly on first iteration, and deletes it G % Push input t % Duplicate @q: % Generate range [1,...,n-1], where n is iteration index. On the first % iteration this is an empty array ) % Use that as index into copy of input string: get its first n elements Ph % Flip and concatenate to input string t % Duplicate. This will be the final result, or will be deleted at the % beginning of next iteration tP % Duplicate and flip =A~ % Compare element-wise. Is there some element different? If so, the % result is true. This is the loop condition, so go there will be a % new iteration. Else the loop is exited with the stack containing % the contatenated string % End loop implicitly % Display stack contents implicitly ``` [Answer] # Ruby, 44 bytes This answer is based on xnor's [Python](https://codegolf.stackexchange.com/a/77116/47581) and [Haskell](https://codegolf.stackexchange.com/a/77115/47581) solutions. ``` f=->s{s.reverse==s ?s:s[0]+f[s[1..-1]]+s[0]} ``` [Answer] # Oracle SQL 11.2, 195 bytes ``` SELECT MIN(p)KEEP(DENSE_RANK FIRST ORDER BY LENGTH(p))FROM(SELECT:1||SUBSTR(REVERSE(:1),LEVEL+1)p FROM DUAL WHERE SUBSTR(:1,-LEVEL,LEVEL)=SUBSTR(REVERSE(:1),1,LEVEL)CONNECT BY LEVEL<=LENGTH(:1)); ``` Un-golfed ``` SELECT MIN(p)KEEP(DENSE_RANK FIRST ORDER BY LENGTH(p)) FROM ( SELECT :1||SUBSTR(REVERSE(:1),LEVEL+1)p FROM DUAL WHERE SUBSTR(:1,-LEVEL,LEVEL)=SUBSTR(REVERSE(:1),1,LEVEL) CONNECT BY LEVEL<=LENGTH(:1) ); ``` [Answer] ## Seriously, 34 bytes ``` ╩╜lur`╜╨"Σ╜+;;R=*"£M`MΣ;░p╜;;R=I. ``` The last character is a non-breaking space (ASCII 127 or `0x7F`). [Try it online!](http://seriously.tryitonline.net/#code=4pWp4pWcbHVyYOKVnOKVqCLOo-KVnCs7O1I9KiLCo01gTc6jO-KWkXDilZw7O1I9SS5_&input=J2FkYmNiJw) Explanation: ``` ╩╜lur`╜╨"Σ╜+;;R=*"£M`MΣ;░p╜;;R=I.<NBSP> ╩ push inputs to registers (call the value in register 0 "s" for this explanation) ╜lur push range(0, len(s)+1) ` `M map (for i in a): ╜╨ push all i-length permutations of s " "£M map (for k in perms): Σ╜+ push s+''.join(k) (call it p) ;;R= palindrome test * multiply (push p if palindrome else '') Σ summation (flatten lists into list of strings) ;░ filter truthy values p pop first element (guaranteed to be shortest, call it x) ╜;;R=I pop x, push s if s is palindromic else x .<NBSP> print and quit ``` [Answer] # C#, 202 bytes I tried. ``` class P{static void Main(string[]a){string s=Console.ReadLine(),o=new string(s.Reverse().ToArray()),w=s;for(int i=0;w!=new string(w.Reverse().ToArray());){w=s.Substring(0,i++)+o;}Console.WriteLine(w);}} ``` Ungolfed: ``` class P { static void Main(string[] a) { string s = Console.ReadLine(), o = new string(s.Reverse().ToArray()), w = s; for(int i = 0; w!=new string(w.Reverse().ToArray());) { w = s.Substring(0, i++) + o; } Console.WriteLine(w); Console.ReadKey(); } } ``` Can anyone provide me with any ideas to group the two calls to .Reverse().ToArray() ? A separate method is more bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Ṗ;¥ƤUŒḂƇḢ ``` [Try it online!](https://tio.run/##y0rNyan8///hzmnWh5YeWxJ6dNLDHU3H2h/uWPT/cPujpjWR//8rJSYlJynpKChlANXmgxhJ@Xn5SWBWUWJKYhFErgJEJaaA1AIA "Jelly – Try It Online") ## How it works ``` Ṗ;¥ƤUŒḂƇḢ - Main link. Takes a string S on the left U - Reverse s ¥ - Group the previous 2 links into a dyad f(p, r): Ṗ - Remove the last element of p ; - Concatenate the truncated p to r Ƥ - Over each prefix p of s, yield f(p, rev(s)) Ƈ - Keep those for which the following is true: ŒḂ - Is a palindrome? Ḣ - Take the first ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 24 bytes ``` {t@*&{x~|x}'t:x,/:|',\x} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqrrEQUutuqKupqJWvcSqQkffqkZdJ6ai9n@auoZSYlJykpK1UkZqTk4@kE7Kz8tPAjGKElMSi8ASFUqa/wE "K (ngn/k) – Try It Online") Feels like it could be golfed more... * `,\x` make list of prefixes of input * `t:x,/:\'` append the reverse of each prefix to the original input, storing in `t` * `*&{x~|x}'` identify the index of the first item in the list that is a palindrome * `t@` retrieve that list item and return it from the function [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 41 bytes ``` ;_FA|C=A{a=a+1~C=_fC||_XC\C=A+right$(B,a) ``` Explanation: ``` ;_FA| Read A$ from the cmd line, then flip it to create B$ C=A Set C$ to be A$ { Start an infinite DO-loop a=a+1 Increment a (not to be confused with A$...) ~C=_fC| If C$ is equal to its own reversed version |_XC THEN end, printing C$ \C=A+ ELSE, C$ is reset to the base A$, with right$(B the right part of its own reversal ,a) for length a (remember, we increment this each iteration DO and IF implicitly closed at EOF ``` [Answer] # Haskell, 46 bytes ``` f l|l==reverse l=l|(h:t)<-l=l!!0:(f$tail l)++[l!!0] ``` I'm wondering if there's a way to remove the parenthesis in `(f$tail l)++[l!!0]`... ]
[Question] [ ### Introduction: I think we all know it, and it has probably been translated in loads of different languages: the "Head, Shoulders, Knees and Toes" children song: > > Head, shoulders, knees and toes, knees and toes > > Head, shoulders, knees and toes, knees and toes > > And eyes and ears and mouth and nose > > Head, shoulders, knees and toes, knees and toes > > [wikipedia](https://en.wikipedia.org/wiki/Head,_Shoulders,_Knees_and_Toes) > > > --- ### Challenge: **Input:** A positive integer. **Output:** Output one of the following words based on the input as n-th index: ``` head shoulders knees toes eyes ears mouth nose ``` Here the body parts are appended with the indexes: ``` Head (0), shoulders (1), knees (2) and toes (3), knees (4) and toes (5) Head (6), shoulders (7), knees (8) and toes (9), knees (10) and toes (11) And eyes (12) and ears (13) and mouth (14) and nose (15) Head (16), shoulders (17), knees (18) and toes (19), knees (20) and toes (21) Head (22), shoulders (23), knees (24) and toes (25), knees (26) and toes (27) Head (28), shoulders (29), knees (30) and toes (31), knees (32) and toes (33) And eyes (34) and ears (35) and mouth (36) and nose (37) Head (38), shoulders (39), knees (40) and toes (41), knees (42) and toes (43) etc. ``` ### Challenge rules: * You are of course allowed to use 1-indexed input instead of 0-indexed. But please specify which one you've used in your answer. * The output is case insensitive, so if you want to output it in caps that's fine. * You should support input up to at least 1,000. ### General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](http://meta.codegolf.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call. * [Default Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code. * Also, please add an explanation if necessary. ### Test cases (0-indexed): ``` Input: Output: 0 head 1 shoulders 7 shoulders 13 ears 20 knees 35 ears 37 nose 98 knees 543 nose 1000 knees ``` [Answer] ## JavaScript (ES6), ~~91~~ ~~88~~ 87 bytes ``` n=>'knees,toes,head,shoulders,eyes,ears,mouth,nose'.split`,`[(245890>>(n%22&~1))&6|n%2] ``` ### How it works We have 4 distinct pairs of words that always appear together: 'head' is always followed by 'shoulders', 'knees' is always followed by 'toes', etc. Therefore, we can use the following index: ``` 00: [ 'knees', 'toes' ] 01: [ 'head', 'shoulders' ] 10: [ 'eyes', 'ears' ] 11: [ 'mouth', 'nose' ] ``` And compress the whole sequence (in reverse order) into the following binary mask: ``` 00 00 01 11 10 00 00 01 00 00 01 ``` We use `[ 'knees', 'toes' ]` as the first pair to get as many leading zeros as possible. We pad this sequence with an extra `0` so that the extracted value is premultiplied by 2, which leads to: ``` 0b00000111100000010000010 = 245890 ``` Hence the final formula for the correct word: ``` (245890 >> (n % 22 & ~1)) & 6 | n % 2 ``` ### Test cases ``` let f = n=>'knees,toes,head,shoulders,eyes,ears,mouth,nose'.split`,`[(245890>>(n%22&~1))&6|n%2] console.log(f(0)); // head console.log(f(1)); // shoulders console.log(f(7)); // shoulders console.log(f(13)); // ears console.log(f(20)); // knees console.log(f(35)); // ears console.log(f(37)); // nose console.log(f(98)); // knees console.log(f(543)); // nose console.log(f(1000)); // knees ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~36~~ ~~35~~ 34 bytes ``` “‡ä¾ØsÏ©s¸±s“#2䤫Г—íÖÇ©¢ÄÓ#s)˜è ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oCc4oChw6TCvsOYc8OPwqlzwrjCsXPigJwjMsOkwqTCq8OQ4oCc4oCUw63DlsOHwqnCosOEw4PigJwjcynLnMOo&input=MTAwMA) or as a [Test suite](http://05ab1e.tryitonline.net/#code=fHbigJzigKHDpMK-w5hzw4_CqXPCuMKxc-KAnCMyw6TCpMKrw5DigJzigJTDrcOWw4fCqcKiw4TDg-KAnCNzKcucecOoLA&input=MAoxCjcKMTMKMjAKMzUKMzcKOTgKNTQzCjEwMDA) **Explanation** ``` “‡ä¾ØsÏ©s¸±s“ # dictionary string 'head shoulders knees toes' # # split on spaces 2ä # split in 2 parts ¤ # get the last part ['knees', 'toes'] « # concatenate and flatten # STACK: [['head', 'shoulders'], ['knees', 'toes'], 'knees', 'toes'] Ð # triplicate “—íÖÇ©¢ÄÓ # dictionary string 'eyes ears mouth nose' #s # split on spaces and swap top 2 elements of stack )˜ # wrap stack in a list and flatten è # index into list with input ``` In short, we build the list `['head', 'shoulders', 'knees', 'toes', 'knees', 'toes', 'head', 'shoulders', 'knees', 'toes', 'knees', 'toes', 'eyes', 'ears', 'mouth', 'nose', 'head', 'shoulders', 'knees', 'toes', 'knees', 'toes']` and index into it with input (0-indexed). [Answer] # Python 2, ~~158~~ ~~148~~ ~~137~~ ~~128~~ ~~114~~ ~~109~~ 104 bytes Lookup table seems better. Also shortened the big string and reordered the items. -5 bytes thanks to Rod for using string as a list. ``` c=int('602323'*2+'4517602323'[input()%22]) print"smkteehnhonoyaeooueeerasutesssdelhs"[c::8]+"ders"*(c<1) ``` initial solution: ``` n=input()%22 n-=10*(n>15) if n>=12:n-=8 else:n%=6;n-=2*(n>3) print"hskteemnehnoyaooaoeeerusduessste ls h d e r s"[n::8].strip() ``` [Answer] ## Perl, 74 bytes **73 bytes code + 1 for `-p`.** ``` $_=(@a=(head,shoulders,(knees,toes)x2),@a,eyes,ears,mouth,nose,@a)[$_%22] ``` Uses 0-based indexing. Doesn't output a separator, but that could be amended with `-l` in the flags. [Try it online](https://ideone.com/aiZv70). [Answer] # Python 2, ~~97~~ 90 Bytes There may be some math that makes it so I don't have to make the word list, but this works for now! ``` lambda n,k='head shoulders '+'knees toes '*2:(k*2+'eyes ears mouth nose '+k).split()[n%22] ``` *Thanks to Flp.Tkc for saving 7 bytes :)* [Answer] # Java 7, ~~155~~ ~~137~~ ~~131~~ ~~123~~ ~~111~~ 110 bytes ``` String c(int i){return"knees,toes,head,shoulders,eyes,ears,mouth,nose".split(",")[(245890>>(i%22&~1))&6|i%2];} ``` -12 bytes thanks to *@Neil*. -1 byte by shamelessly creating a port of [*@Arnauld*'s amazing answer](https://codegolf.stackexchange.com/a/100157/52210). Java is 0-indexed, so that's what I've used. **Ungolfed & test code:** [Try it here.](https://ideone.com/aVqcoX) ``` class M{ static String c(int i){ return "knees,toes,head,shoulders,eyes,ears,mouth,nose".split(",") [(245890>>(i%22&~1))&6|i%2]; } public static void main(String[] a){ System.out.println(c(0)); System.out.println(c(1)); System.out.println(c(7)); System.out.println(c(13)); System.out.println(c(20)); System.out.println(c(35)); System.out.println(c(37)); System.out.println(c(98)); System.out.println(c(543)); System.out.println(c(1000)); } } ``` **Output:** ``` head shoulders shoulders ears knees nose ears knees nose knees ``` [Answer] # C, ~~153 bytes~~ 141 bytes ``` *b[]={"head","shoulders","knees","toes","eyes","ears","mouth","nose"};i;char*g(a){a%=22;i=(a+4)%10;return b[a<4?a:(a&12)>8?a-8:i<2?i:a%2+2];} ``` Thanks to @cleblanc for 4 bytes. Declaring b globally throws a ton of warnings about casting to int, but didn't break for me. Ungolfed: ``` *b[]={"head","shoulders","knees","toes","eyes","ears","mouth","nose"}; i; char* g(a) { a%=22; i=(a+4)%10; return b[a < 4 ? a :(a & 12) > 8 ? a-8 :i < 2 ? i : a % 2 + 2]; } ``` It's not the smallest answer, but I liked the technique, and had fun finding a few patterns. Changelog: * Moved `b` to global to avoid `char` (4 bytes) * `a > 11 && a < 16` => `(a & 12) > 8` (2 bytes) * `i=(a-6)%10` => `i=(a+4)%10` so that `i < 2 && i >= 0` => `i < 2` (6 bytes) [Answer] # JavaScript (ES6) ~~91~~ 89 Bytes ``` f= n=>((d='head:shoulders:'+(b='knees:toes:')+b)+d+'eyes:ears:mouth:nose:'+d).split`:`[n%22] console.log(f.toString().length) console.log(f(0) === 'head') console.log(f(1) === 'shoulders') console.log(f(7) === 'shoulders') console.log(f(13) === 'ears') console.log(f(20) === 'knees') console.log(f(35) === 'ears') console.log(f(37) === 'nose') console.log(f(98) === 'knees') console.log(f(543) === 'nose') console.log(f(1000) === 'knees') ``` [Answer] ## R, 95 bytes ``` c(o<-c("head","shoulders",y<-c("knees","toes"),y),o,"eyes","ears","mouth","nose",o)[scan()%%22] ``` Creates a character vector to function as a lookup table. Takes input from stdin (`1-indexed`) and `%%22` to find the corresponding body part. Bonus: `%%` is vectorized which means that this will work with a vector inputs as well. [Test cases on R-fiddle](http://www.r-fiddle.org/#/fiddle?id=t1r8Zkb3&version=1) (Note that this is a named function because `scan` doesn't work on R-fiddle) [Answer] # jq, 80 characters (77 characters code + 3 characters command line option) ``` ((("head shoulders "+"knees toes "*2)*2+"eyes ears mouth nose ")*2/" ")[.%22] ``` Sample run: ``` bash-4.3$ jq -r '((("head shoulders "+"knees toes "*2)*2+"eyes ears mouth nose ")*2/" ")[.%22]' <<< 1000 knees ``` [On-line test](https://jqplay.org/jq?q=%28%28%28%22head%20shoulders%20%22%2b%22knees%20toes%20%22*2%29*2%2b%22eyes%20ears%20mouth%20nose%20%22%29*2/%22%20%22%29[.%2522]&j=1000) (Passing `-r` through URL is not supported – check Raw Output yourself.) [Answer] # WinDbg, ~~207~~ ~~157~~ 151 bytes ``` ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41 ``` *-50 bytes by encoding the offset/length of the body parts as ascii chars.* *-6 bytes by using a local var when looking up the offset/length.* Input is done with a value set in the pseudo-register `$t0`. How it works: ``` * Initialization, writes this string at address 0x2000000. The nonsense after the body parts * are the offsets and lengths of the body parts in the first part of the string, each of * which is incremented by 0x41 to make it a printable ascii character. ea 2000000 "headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF"; * Display the output: r$t4=(@$t0%16)*2+2000027 da1FFFFBF+by(@$t4) Lby(@$t4+1)-41 * Display output explanation: r $t4 = (@$t0%16)*2+2000027 * Set $t4 = input, @$t0, mod 22, doubled +0x2000027 by(@$t4) * byte_at(@$t4)-0x41 is the {Offset} into the string * for the start of output. The -0x41 is already subtracted * from 0x2000000 to make 0x1FFFFBF. Lby(@$t4+1)-41 * byte_at(@$t4+1)-0x41 is the {Length} of the output. da 1FFFFBF+{Offset} L{Length} * Display {Length} chars from {Offset} of the above string. ``` Sample output: ``` 0:000> r$t0=0 0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41 02000000 "head" 0:000> r$t0=1 0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41 02000004 "shoulders" 0:000> r$t0=7 0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41 02000004 "shoulders" 0:000> r$t0=0n13 0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41 0200001a "ears" 0:000> r$t0=0n20 0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41 0200000d "knees" 0:000> r$t0=0n35 0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41 0200001a "ears" 0:000> r$t0=0n37 0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41 02000023 "nose" 0:000> r$t0=0n98 0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41 0200000d "knees" 0:000> r$t0=0n543 0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41 02000023 "nose" 0:000> r$t0=0n1000 0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41 0200000d "knees" ``` [Answer] # PHP, 91 ~~102~~ ~~118~~ ~~128~~ ~~129~~ Bytes ``` <?=[head,shoulders,knees,toes,eyes,ears,mouth,nose]['0123230123234567012323'[$argv[1]%22]]; ``` 0-Indexed Down to 91 following removal of str\_split, didn't realise PHP string were accessible as a char array (a PHP 5+ thing?) ~~Down to 102 thanks to insertusername suggestion for removing string quotes and allowing the notices~~ [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 55 bytes ``` “¥ḷne“¥ṇṭḲ»ẋ2ṭ“¢1$“@⁼5⁼»µẋ2;“¥ḳVo“¥ḳ'k“£Qo“£³ạ»;⁸FḊḲ ị¢ ``` [Try it online!](//jelly.tryitonline.net#code=4oCcwqXhuLduZeKAnMKl4bmH4bmt4biywrvhuosy4bmt4oCcwqIxJOKAnEDigbw14oG8wrvCteG6izI74oCcwqXhuLNWb-KAnMKl4bizJ2vigJzCo1Fv4oCcwqPCs-G6ocK7O-KBuEbhuIrhuLIK4buLwqI&args=MTAwMQ) (1-based index) Come on! Really? As a bonus, this is the compressed string I was supposed to use instead of the top line: ``` “¡¦ṡb[wfe=⁺żɦ4Gƈġhḳ"ẇ⁴ż>oH¹8ṡʠʠḟṀUṿḶ>¬Þ:ĖẇrṗṁɼlDṫỤ¬ȷ⁶Dḥci*⁻³GḲOÞạṖṃ\» ``` Both encode this string: ``` head shoulders knees toes knees toes head shoulders knees toes knees toes eyes ears mouth nose head shoulders knees toes knees toes ``` Guess I should go exercise now :P [Answer] ## Powershell, 91 Bytes, Zero-Indexed ``` $a='head shoulders '+'knees toes '*2;($a*2+'eyes ears mouth nose '+$a).Split()[$args[0]%22] ``` Very straightforward approach, generate the array of the first 22 items using some string multiplication where possible, by compiling them with spaces and splitting at the end. (splitting is 2 bytes shorter than the equivalent setup as an array) then just find the point in that array using the modulus of the input, not exactly interesting or language-specific. Test Case: ``` PS C:\++\golf> 0..1000|%{.\hskt $_} head shoulders knees toes knees toes head shoulders knees toes knees toes eyes ears mouth nose head shoulders knees toes knees toes head shoulders knees toes .... ``` etc. [Answer] # ruby, 81 bytes Lambda function using zero indexing. ``` ->n{("head shoulders#{" knees toes "*2}eyes ears mouth nose".split*2)[n%22-6&15]} ``` **explanation** We generate the following array, of which we use the first 16 elements, covering the correct lines 2,3,4 of the song: ``` %w{head shoulders knees toes knees toes eyes ears mouth nose head shoulders knees toes knees toes eyes ears mouth nose} #last 4 elements not used ``` We take n modulo 22 to reduce it to a single verse, then we subtract 6. Now the index 6 (for example) has been changed to 0 and points to the right word. Indicies 0..5 which point to the first line of the song are now negative. We use `&15` (identical to `%16` but avoids the need for brackets) to map the 1st line of the song to the 4th line. Thus index `0` -> `-6` -> `10` **in test program** ``` f=->n{("head shoulders#{" knees toes "*2}eyes ears mouth nose".split*2)[n%22-6&15]} #call as below to test index 0..43 44.times{|i|p f[i]} ``` [Answer] # Befunge, ~~129~~ 119 bytes 0-indexed ``` &29+2*%:2/v>00p>%#7_v +%2\-"/"g2<|<:-1g007<"head*shoulders*knees*toes*eyes*ears*mouth*nose"p00 02202246022>$$:>7#:%#,_@ ``` [Try it online!](http://befunge.tryitonline.net/#code=JjI5KzIqJToyL3Y-MDBwPiUjN192CislMlwtIi8iZzI8fDw6LTFnMDA3PCJoZWFkKnNob3VsZGVycyprbmVlcyp0b2VzKmV5ZXMqZWFycyptb3V0aCpub3NlInAwMAowMjIwMjI0NjAyMj4kJDo-NyM6JSMsX0A&input=MTAwMA) **Explanation** As [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) pointed out, the words come in pairs, so we have an index of just 11 values and then add the word number % 2 to get the appropriate word in the pair. The words are pushed onto the stack as a single string separated by asterisks to save space. We test for word breaks by taking the char value modulo 7, since only the asterisk is a multiple of 7. ``` &29+2*% n = getint() % 22 // % 22 to ensure it's in range :2/2g i = index_array[n/2] // we use n/2 because words are paired -"/" i -= '/' // convert from ASCII to 1-based value \2%+ i += n%2 // get the correct word in the pair 00p index = i // save for later "head*shoulders*knees*toes*eyes*ears*mouth*nose" // push all the words onto the stack 700g1-:| while (index-1 != 0) { // the 7 is used in the drop loop 00p index = index-1 >%#7_ do while (pop() % 7) // drop up to the next '*' (%7==0) } $$ pop();pop() // get rid of index and extra 7 : 7 % _ while ((c = pop()) % 7) // output up to the next '*' (%7==0) > : , putchar(c) ``` [Answer] # SQL 2005 747 Bytes Golfed: ``` GO CREATE PROCEDURE H @n INT AS BEGIN IF NOT EXISTS(SELECT*FROM R)BEGIN INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('eyes')INSERT INTO R VALUES('ears')INSERT INTO R VALUES('mouth')INSERT INTO R VALUES('nose')INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')END SELECT W FROM R WHERE I=@n%22 END ``` Ungolfed: ``` GO CREATE PROCEDURE H @n INT AS BEGIN IF NOT EXISTS(SELECT*FROM R) BEGIN INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('eyes')INSERT INTO R VALUES('ears')INSERT INTO R VALUES('mouth')INSERT INTO R VALUES('nose')INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes') END SELECT W FROM R WHERE I=@n%22 END ``` Needs a table like this, where the first column is auto-incremented: [![enter image description here](https://i.stack.imgur.com/rRpjB.png)](https://i.stack.imgur.com/rRpjB.png) This is a one-indexed answer. The table is populated the first time stored procedure is created - it wouldn't let me do all the `INSERT` in one statement, disappointingly, this feature is only available in `>=SQL 2008`. After this, it uses the `%22` trick from the other answers. Once the table has been populated, it only uses the last part: ``` SELECT W FROM R WHERE I=@n%22 Input: Output: R 1 head R 2 shoulders R 8 shoulders R 14 ears R 21 knees R 36 ears R 38 nose R 99 knees R 54 nose R 1001 knees ``` [Answer] ## bash (with ed), 83 chars 1-indexed ``` ed<<<"a head shoulders knees toes eyes ears mouth nose . 3,4t4 1,6y 6x $(($1%22))" ``` Sample call: ``` $ bash test.sh 1001 knees ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 135 bytes ``` 6[head]6[:add6-r;ar:adA+r;ar:a]dshx7[shoulders]7lhx8[knees]8lhxA 2;aAlhx9[toes]9lhxB 3;aBlhx[eyes]C:a[ears]D:a[mouth]E:a[nose]F:a22%;ap ``` [Try it online!](https://tio.run/##Jc/NasMwEATge59iIeRUCrLV@LcXJ23PvQtRlmhbmSrr4LWp0pd3F3L7ZmAOE87b4dlulYuEwVeuwxCqp7nHWTU83uGDxFw7idOaAs3i6xRz436YSHyjHqDscVC0bpm0a5VHsD0eFY5uWp06dIS6fVVcpnWJ/k3Fk5B/77As9z1eNxfYdeD5HuXzr3jJXjLsZLxc0/h1g3llHvkbFpIFzigkD4X5gB3TbxqZNBgDegnaBmwN9gClgcJCDQUYSDlv/w "dc – Try It Online") Arrays in `dc` have to be built an element at a time, which takes up the brunt of this exercise. Since 'eyes', 'ears', 'mouth', and 'nose' only appear once in our array, we just pop them in. But for the others, we save a few bytes by putting them on the stack like `x[head]x`, where *x* is the middle of its three values, then we run the macro `[:add6-r;ar:adA+r;ar:a]dshx` to put it in the array, pull it back, put it in at the same value less six, pull it back, and then put it in one last time at the original value plus ten. We use the middle value because `dc` allows us to use hex digits even in decimal mode, and subtracting `A` is one less byte than adding `16` - this also only works because all of the middle values are under fifteen. We have to do knees and toes twice, and making our macro smart enough to sort that out is more expensive than just running the macro twice; but we do save bytes here by loading a previously stored copy of the string instead of writing it out again (`B 3;aB` vs. `B[toes]B` - I think this saves 3 bytes total). Once we have the array built, all we need to do is `22%` and then `;ap` to pull it from the array and print. [Answer] ## C#6, 138 bytes ``` string F(int i)=>(i+10)%22<4?"eyes,ears,mouth,nose".Split(',')[(i+10)%22%4]:"head,shoulders,knees,toes,knees,toes".Split(',')[(i+6)%22%6]; ``` [repl.it demo](https://repl.it/E2SC/1) Ungolfed + comments: ``` string F(int i)=> // Is it eyes/ears/mouth/nose? (i+10)%22<4 // If yes, then set index to 4-word line and take modular 4 // String array constructed by splitting comma-delimited words ? "eyes,ears,mouth,nose".Split(',') [(i+10)%22%4] // Else set index to last 6-word line and take modular 6 : "head,shoulders,knees,toes,knees,toes".Split(',') [(i+6)%22%6]; ``` [Answer] # Excel, 146 bytes ``` =MID("Head ShouldersKnees Toes Eyes Ears Mouth Nose",CHOOSE(MOD(MOD(MOD(B1+16,22),16),10)+1,1,10,19,28,19,28,37,46,55,64),9) ``` Uses @Neil's `MOD(MOD(MOD(B1+16,22),16),10)` to save `15` bytes. ]
[Question] [ Program A outputs program B's code when run, and B outputs A's source. Requirements: * Only one language across both programs * Programs are different. One program that outputs itself does not qualify. * Both programs are non-empty, or at least 1 byte in length. Trailing newlines in both source and output are ignored * ~~stdin is closed.~~ Do not read anything (so **you can't read the source** and manipulate it). Output goes to stdout. **Edit:** stdin is connected to `/dev/null`. You can order it be closed if clarified. * Do not use `random` functions. Additional: * Give explanations if possible Score is **total length**. Trailing newline does not count if it doesn't affect the program. [Answer] ## [CJam](https://sourceforge.net/p/cjam), 13 + 13 = 26 bytes ``` {sYZe\"_~"}_~ ``` [Try it online!](https://tio.run/##S85KzP3/v7o4Mio1Rim@Tqk2vu7/fwA "CJam – Try It Online") Outputs ``` {sZYe\"_~"}_~ ``` ### Explanation ``` { e# Standard quine framework, leaves a copy of the block on the stack e# for the block itself to process. s e# Stringify the block. YZe\ e# Swap the characters at indices 2 and 3, which are Y and Z themselves. "_~" e# Push the "_~" to complete the quine. }_~ ``` Since `e\` is commutative in its second and third operand, the other program does exactly the same, swapping `Z` and `Y` back into their original order. [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~11 + 13 = 24~~ 11 + 12 = 23 bytes ``` "N^_p" N^_p ``` [Try it online!](https://tio.run/##S85KzP3/X8kvLr5AiQtE/v8PAA "CJam – Try It Online") Outputs: ``` "N^_p " N^_p ``` The output has 13 bytes, but: > > Trailing newline does not count if it doesn't affect the program. > > > So I changed the space to a newline to take advantage of that. It is based on the shortest CJam proper quine: ``` "_p" _p ``` And `N^` is to xor the string with a newline, which adds a newline if there isn't a newline, and remove it if there is, for a string that each character is unique. I think I have seen that quine in the quine question, but I couldn't find it. [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 3 + 3 = 6 bytes First program: ``` 0 1 ``` [Try it online!](https://tio.run/##Kyooyk/P0zX6/9@Ay/D/fwA "RProgN 2 – Try It Online") Second program: ``` 1 0 ``` [Try it online!](https://tio.run/##Kyooyk/P0zX6/9@Qy@D/fwA "RProgN 2 – Try It Online") -2 thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender). [Answer] # C, 95 + 95 = 190 bytes *Thanks to @immibis for saving 16\*2 bytes!* ``` char*s="char*s=%c%s%c;main(i){i=%d^1;printf(s,34,s,34,i);}";main(i){i=1^1;printf(s,34,s,34,i);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z85I7FIq9hWCUqrJqsWqyZb5yZm5mlkalZn2qqmxBlaFxRl5pWkaRTrGJvogIlMTetaJSRVhrgU/f8PAA) Outputs: ``` char*s="char*s=%c%s%c;main(i){i=%d^1;printf(s,34,s,34,i);}";main(i){i=0^1;printf(s,34,s,34,i);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z85I7FIq9hWCUqrJqsWqyZb5yZm5mlkalZn2qqmxBlaFxRl5pWkaRTrGJvogIlMTetaJSRVBrgU/f8PAA) Which outputs: ``` char*s="char*s=%c%s%c;main(i){i=%d^1;printf(s,34,s,34,i);}";main(i){i=1^1;printf(s,34,s,34,i);} ``` [Answer] # Javascript, 67+67=134 bytes 1st program: ``` alert(eval(c="`alert(eval(c=${JSON.stringify(c)},n=${+!n}))`",n=0)) ``` 2nd program: ``` alert(eval(c="`alert(eval(c=${JSON.stringify(c)},n=${+!n}))`",n=1)) ``` This is based on [Herman Lauenstein's answer to Tri-interquine](https://codegolf.stackexchange.com/a/130317/70761) # Javascript (Invalid - reads source code), ~~75+75=150~~ ~~61+61=122~~ ~~58+58=116~~ 50+50=100 bytes *saved 20 bytes thanks to Tushar, 6 bytes thanks to Craig Ayre, and saved 16 bytes thanks to kamoroso94* 1st program: ``` f=_=>alert(("f="+f).replace(0,a=>+!+a)+";f()");f() ``` 2nd program: ``` f=_=>alert(("f="+f).replace(1,a=>+!+a)+";f()");f() ``` Swaps the 1s with the 0s and vice versa. They both do the same thing, just producing different output because of their source code. [Answer] ## Python 2, 63+63 = 126 bytes [Try it online](https://tio.run/##K6gsycjPM/r/39FW3dFWtci6oCgzr0TBMdrKyDhWVdVR2zHayNLK2DTWyNjKyDJWHVUeIc1Fvn6wxP//AA) First program: ``` A='A=%r;print A[:23]%%A+A[29:35]23:29]';print A[:23]%A+A[23:29] ``` outputs: ``` A='A=%r;print A[:23]%%A+A[29:35]23:29]';print A[:23]%A+A[29:35] ``` Second program: ``` A='A=%r;print A[:23]%%A+A[29:35]23:29]';print A[:23]%A+A[29:35] ``` Outputs: ``` A='A=%r;print A[:23]%%A+A[29:35]23:29]';print A[:23]%A+A[23:29] ``` [Answer] # JavaScript ([JsShell](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Introduction_to_the_JavaScript_shell)), 35 + 34 = 69 bytes 1: ``` (f=x=>print(`(f=${f})(${-x})`))(-1) ``` 2: ``` (f=x=>print(`(f=${f})(${-x})`))(1) ``` [Answer] # [Underload](https://esolangs.org/wiki/Underload), 32+32=64 bytes ``` (a~a*(:^)*S)(~(a)~a*^a(:^)**S):^ ``` [Try it online!](https://tio.run/##K81LSS3KyU9M@f9fI7EuUUvDKk5TK1hTo04jURPIjUsECwBFrOL@/wcA "Underload – Try It Online") ``` (~(a)~a*^a(:^)**S)(a~a*(:^)*S):^ ``` [Try it online!](https://tio.run/##K81LSS3KyU9M@f9fo04jUbMuUSsuUcMqTlNLK1hTIxHIBXOCNa3i/v8HAA "Underload – Try It Online") [Answer] # Mathematica, 43 + 44 = 87 bytes ``` (Print[#1[#0[#1, -#2]]] & )[HoldForm, -1 1] ``` and ``` (Print[#1[#0[#1, -#2]]] & )[HoldForm, -(-1)] ``` [Answer] # asmutils sh, 16+16 bytes, abusing the "stdin is closed" rule. ``` #!/bin/sh tr x y ``` Since stdin is closed and sh will open its script to the first available handle (rather than move it to a high numbered handle like modern shells do), tr ends up reading from a copy of the script without having ever opened it. This interquine is payload capable but inserting a payload is tricky. In addition, this original version abuses some crazy bug in the ancient kernel I used in those days. (I don't know what's up with that kernel--I found out later on it had different major and minor numbers for devices too.) If you fix the ABI changes that broke asmutils the interquine still won't work. I forget if asmutils sh has exec or not, but if it does, this is a modern version: ``` exec dd skip=0 | tr x y ``` This abuses a deliberate bug in asmutils dd; it has a performance optimization it calls llseek for skip if it can, but to save a byte it passes SEEK\_SET rather than SEEK\_CUR. This results in garbage on stderr but the interquine on stdout. Asmutils dd doesn't have an option to suppress the stderr spam. [Answer] # [><>](https://esolangs.org/wiki/Fish), 16 + 16 = 32 bytes ``` ":1-}80.r !#o# ``` and ``` #o#! r.08}-1:" ``` [Try it online!](https://tio.run/##S8sszvj/X8nKULfWwkCvSEFBQVE5X/n/fwA "><> – Try It Online") This works by using a jump in the program, the first programs jump will skip the reverse of the stack (if it reversed the stack it would be a quine). The second program doesn't skip the reverse but was it's already reversed by the flow of the program then it'll create the originial. This code will end in an error. [Answer] ## Common Lisp, 58 characters ``` #1=(let((*print-circle* t))(print'(write '#1# :circle t))) ``` ... or 24 characters if you don't mind assuming `*print-circle*` is globally set to `T` : ``` #1=(print '(write '#1#)) ``` The printed representation of the code is read as a cyclic structure, where `#1#` points back to the cons cell following `#1=`. We quote programs so that they are not executed. Since `*print-circle*` is T, the REPL takes care to emit such reader variables during printing; this is what the above code prints, and returns: ``` #1=(write '(print '#1#)) ``` When we evaluate the above code, it prints: ``` #1=(print '(write '#1#)) ``` If you want to stick with the default value for `*print-circle*`, which is NIL in a conforming implementation, then you'll have to rebind the variable temporarily: ``` #1=(let((*print-circle* t))(print'(write '#1# :circle t))) ``` Inside the body of the LET, we print things with `*print-circle*` being T. So we obtain: ``` #1=(write '(let ((*print-circle* t)) (print '#1#)) :circle t) ``` As you can see, the new program doesn't rebind `*print-circle*`, but since we are using `write`, which is the low-level function called by `print`, we can pass additional arguments such as `:circle`. The code then works as expected: ``` #1=(let ((*print-circle* t)) (print '(write '#1# :circle t))) ``` However, you need to execute the above programs as a script, not inside a REPL, because even though you print things while taking care of circular structures, both `write` and `print` also returns the value being printed; and in a default REPL, the value is also being printed, but outside of the dynamic context where `*print-circle*` is T. [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 7 + 7 = 14 bytes I wanted to try to show off a better usage of RProgN, rather than just abusing print orders... ``` 1 «\1\- ``` and... ``` 0 «\1\- ``` ## Explained ``` 1 # Push the constant, 1. (Or 0, depending on the program) «\1\- « # Define a function from this to the matching », in this case there isn't any, so define it from this to the end of the program, then continue processing. \ # Flip the defined function under the constant. 1\- # Get 1 - Constant. ``` Because this prints the stack upside down, the new constant is printed first, then the stringifed version of the function is printed. [Try it online!](https://tio.run/##Kyooyk/P0zX6/9@Q69DqGMMY3f//AQ "RProgN 2 – Try It Online") [Answer] ## [LOGO](https://sourceforge.net/projects/fmslogo/), 65 + 66 = 131 bytes ``` apply [(pr ? ` [[,? ,-?2]] )] [[apply [(pr ? ` [[,? ,-?2]] )]] 1] ``` and ``` apply [(pr ? ` [[,? ,-?2]] )] [[apply [(pr ? ` [[,? ,-?2]] )]] -1] ``` [Answer] # Python 3, 74+74=148 bytes ``` a='a=%r;b=%r;print(b%%(b,a))';b='b=%r;a=%r;print(a%%(a,b))';print(b%(b,a)) ``` and ``` b='b=%r;a=%r;print(a%%(a,b))';a='a=%r;b=%r;print(b%%(b,a))';print(a%(a,b)) ``` ~~i don't understand it either~~ [Answer] # [><>](https://esolangs.org/wiki/Fish), 12 + 12 = 24 bytes ``` '3d*!|o|!-c: ``` and ``` ':c-!|o|!*d3 ``` [Try it online!](https://tio.run/##S8sszvj/X904RUuxJr9GUTfZiisxL4VL3SpZFyyglWL8/z8A "><> – Try It Online") Both programs use a wrapping string literal to add the code to the stack, then produce the `'` command through different methods. When printing the stack it pushes the code backwards, however the `'` stays at the front. There are several variations that produce the `'`; `3d*`, `d3*`, `00g`, `:c-` when paired with `3d*` and `:9-` when paired with `00g`. A too [similar solution](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XMtJOztZRcNDJTtY2@v8fAA) to post, in Befunge-98 for 13\*2 bytes ``` "2+ck, @,kc+2 ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 18+20=38 bytes ``` "Vn|^34bL"Vn|^34bL ``` [Run and debug online!](https://staxlang.xyz/#c=%22Vn%7C%5E34bL%22Vn%7C%5E34bL&a=1) ``` "Vn|^34bL "Vn|^34bL ``` [Run and debug online!](https://staxlang.xyz/#c=%22Vn%7C%5E34bL%0A%22Vn%7C%5E34bL%0A&a=1) ## Explanation Added for completeness. Port of @jimmy23013's CJam answer. Toggles the newlines using set xor. [Answer] # Javascript (ES6), 36 + 36 = 72 bytes Program 1: ``` f=n=>('f='+f).replace(/4|5/g,n=>n^1) ``` Program 2: ``` f=n=>('f='+f).replace(/5|4/g,n=>n^1) ``` These programs work by cloning themselves and replace `5` with `4` and `4` with `5` ``` console.log(( f=n=>('f='+f).replace(/4|5/g,n=>n^1) )()) console.log(( f=n=>('f='+f).replace(/5|4/g,n=>n^1) )()) ``` [Answer] # [Klein](https://github.com/Wheatwizard/Klein), ~~26~~ 24 bytes ``` <:3+@+3<:" ``` [Try it online!](https://tio.run/##y85Jzcz7/1/eysZY20Hb2MpGXun///8GBgb/dR0B "Klein – Try It Online") ## Explanation This works the same as [my Klein Quine](https://codegolf.stackexchange.com/a/121406/56656), where it prints the source backwards followed by a `"`, the last one got away with this by being palindromic, so all we need to do is make it non-palindromic without damaging its functionality. By switching `<` and `:` we were able to do this without interfering with functionality. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 36 + 36 = 72 bytes ``` (f=(x)->print1("(f="f")("1-x")"))(1) ``` [Try it online!](https://tio.run/##K0gsytRNL/j/XyPNVqNCU9euoCgzr8RQQwnIV0pT0tRQMtStUNJU0tTUMNT8/x8A "Pari/GP – Try It Online") ``` (f=(x)->print1("(f="f")("1-x")"))(0) ``` [Try it online!](https://tio.run/##K0gsytRNL/j/XyPNVqNCU9euoCgzr8RQQwnIV0pT0tRQMtStUNJU0tTUMND8/x8A "Pari/GP – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 42 + 43 = 85 bytes, # [Python 3](https://docs.python.org/3/), 44 + 45 = 89 bytes ## Python 2 (85 bytes): ``` a='a=%r,-%d;print a[0]%%a',-1;print a[0]%a # Program 1: 42 bytes a='a=%r,-%d;print a[0]%%a',--1;print a[0]%a # Program 2: 43 bytes ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9FWPdFWtUhHVzXFuqAoM69EITHaIFZVNVFdR9cQWSTx/38A "Python 2 – Try It Online") ## Python 3 (89 bytes): ``` a='a=%r,-%d;print(a[0]%%a)',-1;print(a[0]%a) # Program 1: 44 bytes a='a=%r,-%d;print(a[0]%%a)',--1;print(a[0]%a) # Program 2: 45 bytes ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P9FWPdFWtUhHVzXFuqAoM69EIzHaIFZVNVFTXUfXEFkoUfP/fwA "Python 3 – Try It Online") ## How it works? : I started from the standard `a='a=%r;print(a%%a)';print(a%a)` quine. But instead of having `a` equal only to a string, I have `a` equal to a tuple regrouping a sting and an integer. I add the char `-` in front of my integer: * if it is equal to `-1`, `-%d` will be equal to `--1` * if it is equal to `--1`, `%d` will evaluate it as 1 so `-%d` will be equal to `-1` ## Edits: I found aferwards this pretty elegant solution. Not better, just elegant. (58 + 58 = 116 bytes): ``` a="print'a=%r;exec a.lower()'%a.swapcase()";exec a.lower() # 58 char each a="PRINT'A=%R;EXEC A.LOWER()'%A.SWAPCASE()";exec a.lower() # 116 bytes in total ``` [Try it online!](https://tio.run/##bczBCsIgGADge0/xsyFuF2FBEQwPMjwEUcMF6/ongoOh4oS1p7e6RucPvrAl690@Z@RFiJNLFDmJrXkZDchmv5pY1ZQgW1YMGhdT1cWPQgmHE2iLEQxqu/tMvTpf71Rwolr5kB0IdrmNUn0nwYZR9J0Y5N@paY7w3JJZYHKQfMI55zc "Python 2 – Try It Online") ]
[Question] [ The nth [Motzkin Number](http://mathworld.wolfram.com/MotzkinNumber.html) is the number of paths from (0, 0) to (n, 0) where each step is of the form (1, -1), (1, 0) or (1, 1), and the path never goes below y = 0. Here's an illustration of these paths for n = 1, 2, 3, 4, from the above link: [![Motzkin numbers](https://i.stack.imgur.com/wWeee.gif)](https://i.stack.imgur.com/wWeee.gif) The desired sequence is [OEIS A001006](https://oeis.org/A001006). OEIS has some other characterizations of the sequence. --- You will be given a positive integer n as input. You should output the nth Motzkin Number. Here are Motzkin numbers 1 to 10: ``` 1, 2, 4, 9, 21, 51, 127, 323, 835, 2188 ``` --- All standard input and output methods are allowed. [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. This is code golf. Fewest bytes wins. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 13 ~~14~~ bytes ``` i-2/t.5+hH4Zh ``` ### Example: ``` >> matl i-2/t.5+hH4Zh > 6 51 ``` *EDIT (June 16, 2017): you can [**try it online!**](https://tio.run/##y00syfn/P1PXSL9Ez1Q7w8MkKuP/fzMA) Note also that in modern versions of the language (that post-date this challenge) the `i` could be removed.* ### Explanation Pretty straightforward, using [the equivalence](http://mathworld.wolfram.com/MotzkinNumber.html) (see equation (10)) with the [hypergeometric function](https://en.wikipedia.org/wiki/Hypergeometric_function): $$M\_n = {}\_2F\_1 \left( \frac {1-n} 2, -\frac n 2 ; 2 ;4 \right)$$ From the definition of the hypergeometric function $${}\_2F\_1(a,b; c; z) = \sum ^ \infty \_ {n=0} \frac {(a)\_n (b)\_n} {(c)\_n} \frac {z^n} {n!}$$ it's clear that the order of the first two arguments can be interchanged, which saves one byte. ``` i % input -2/ % divide by -2 t.5+ % duplicate and add 0.5 h % horizontal concatenation into a vector H % number 2 4 % number literal Zh % hypergeometric function with three inputs (first input is a vector) ``` [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~59~~ 58 bytes ``` +`(\D*)1(1*) :$1<$2:$1>$2:$1_$2: :(_|()<|(?<-2>)>)+:(?!\2) ``` Takes input in [unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary). Input 7 (i.e. `1111111`) takes quite a while but still completes in less than a minute. I wouldn't go much further than that. [Try it online.](http://retina.tryitonline.net/#code=K2AoXEQqKTEoMSopCjokMTwkMjokMT4kMjokMV8kMjoKOihffCgpPHwoPzwtMj4pPikrOig_IVwyKQ&input=MTExMTE) ### Explanation A different characterisation of the Motzkin numbers is the number of strings of three different characters, where two of them are correctly balanced (hence the close relation to Catalan numbers, which are the same without the third character which is independent of the balancing). .NET's balancing groups are pretty good at detecting correctly matched strings, so we simply generate *all* strings of length `N` (using `_`, `<` and `>` as the three characters) and then we count how many of those are correctly balanced. E.g. for `N = 4` the valid strings are: ``` ____ __<> _<_> _<>_ <__> <_>_ <>__ <<>> <><> ``` Compared with the definition in the challenge, `_` corresponds to a `(1,0)` step, `<` to `(1,1)` and `>` to `(1,-1)`. As for the actual code, the `:` is used as a separator between the different strings. The second regex is just a golfed form [of the standard .NET regex for balanced strings](https://stackoverflow.com/a/17004406/1633117). Something to note is that there is only a single `:` inserted between strings in each step, but the second regex matches a leading *and* a trailing `:` (and since matches cannot overlap, this means that adjacent strings generated from one template in the last step cannot both match). However, this is not a problem, because at most one of those three can ever match: * If the string ending in `_` matches, the prefix without that `_` is already balanced correctly, and `<` or `>` would throw off that balance. * If the string ending in `>` matches, the string is balanced *with* that `>`, so `_` or `<` would throw off that balance. * Strings ending in `<` can never be balanced. [Answer] ## Python 2, 51 bytes ``` M=lambda n:n<1or sum(M(k)*M(n-2-k)for k in range(n)) ``` Uses the formula from Mathworld [![enter image description here](https://i.stack.imgur.com/SmW6i.gif)](https://i.stack.imgur.com/SmW6i.gif) Saves chars by putting the `M[n-1]` term into the summation as `k=n-1`, which gives `M[-1]*M[n-1]`, with `M[-1]=1` as part of the initial condition. Edit: One char shorter writing the sum recursively: ``` M=lambda n,k=0:n<1or k<n and M(k)*M(n-2-k)+M(n,k+1) ``` Other approaches that turned out longer: ``` M=lambda n,i=0:n and(i>0)*M(n-1,i-1)+M(n-1,i)+M(n-1,i+1)or i==0 M=lambda n:+(n<2)or(3*~-n*M(n-2)+(n-~n)*M(n-1))/(n+2) ``` [Answer] # Pyth, 15 bytes ``` Ls*V+KyMb1+t_K1 ``` This defines a function `y`. Try it online: [Demonstration](https://pyth.herokuapp.com/?code=Ls%2aV%2BKyMb1%2Bt_K1%0Ay1%0Ay2%0Ay3%0Ay10%0Ay100&debug=0) ### Explanation: Let `y[n]` be the `n`-th Motzkin Number. I calculate `y[n]` with the formula ``` y[n] = dot product of (y[0], ..., y[n-1], 1) and (y[n-2], ..., y[0], 1) ``` Notice that the first vector is larger than the second one (except when calculating `y[0]`). When this is the case, than Pyth automatically ignores the 1 at the end of the first vector, so that both vectors are of equal length. ``` Ls*V+KyMb1+t_K1 L define a function y(b), which returns: yMb compute the list [y[0], y[1], ..., y[b-1]] K assign it to K *V vectorized multiplication of +K 1 * K with a 1 at the end +t_K1 * reverse(K), remove the first element, and append 1 s return the sum (dot product) ``` This formula is a variation of one of the formulas listed on OEIS. It may be a little bit stupid. Because of the 1 at the end of the first vector (which make the lengths unequal), I don't actually have to give the recursion a base case. And I had hopes, that the two `+...1`s can be golfed somehow. Turns out I can't. You can define a similar recursion with a dot product of equal length vectors and define the base case `y[0] = 1` with with the same byte count. [Answer] ## CJam (20 bytes) ``` .5X]{__W%.*:++}qi*W= ``` [Online demo](http://cjam.aditsu.net/#code=.5X%5D%7B__W%25.*%3A%2B%2B%7Dqi*W%3D&input=10) As Mego noted in the comments on the question, this is very closely related to the Catalan numbers: change the `.5` to `1` and offset the index by one (or simply remove the `.5` entirely and leave the index unchanged) to get Catalan numbers. The recurrence used is > > a(n+2) - a(n+1) = a(0)\*a(n) + a(1)\*a(n-1) + ... + a(n)\*a(0). [Bernhart] > > > from the OEIS page. The corresponding recurrence for the [Catalan numbers](https://oeis.org/A000108) is listed as > > a(n) = Sum\_{k=0..n-1} a(k)a(n-1-k). > > > [Answer] ## Seriously, 21 bytes ``` ,;╗r`;τ╜█@;u@τ╣║\*`MΣ ``` Borrows some code from [quintopia's Catalan Numbers solution](https://codegolf.stackexchange.com/a/66150/45941), specifically the improvement I made in the comments. I use the following formula: [![motzkin formula](https://i.stack.imgur.com/kw3LZ.png)](https://i.stack.imgur.com/kw3LZ.png) Since `nCk` is 0 for `k > n`, I sum all the way to `n-1`, since those values will all be 0 and thus do not affect the sum. [Try it online](http://seriouslylang.herokuapp.com/link/code=2c3bbb72603be7bddb403b7540e7b9ba5c2a604de4&input=5) Explanation: ``` ,;╗r`;τ╜█@;u@τ╣║\*`MΣ ,;╗ push input, dupe, store one copy in register 0 r push range(0, n) ([0,n-1]) ` `M map the function: ;τ╜█@ dupe k, push C(n, 2*k), swap with k ;u@τ╣║\ push the kth Catalan number * multiply Σ sum ``` [Answer] # R, 64 bytes ``` f=function(n)ifelse(n<2,1,f(n-1)+sum(rev(s<-sapply(2:n-2,f))*s)) ``` Uses also the Mathworld formula of [@xnor's python answer](https://codegolf.stackexchange.com/a/66858/6741). Thanks to rules of precedence, `2:n-2` is equivalent to `0:(n-2)`. Test cases: ``` > f(0) [1] 1 > f(1) [1] 1 > f(5) [1] 21 > f(10) [1] 2188 > sapply(0:20,f) [1] 1 1 2 4 9 21 51 127 [9] 323 835 2188 5798 15511 41835 113634 310572 [17] 853467 2356779 6536382 18199284 50852019 ``` [Answer] # Mathematica, ~~31~~ 30 bytes ``` AppellF1[-#/2,.5,-#/2,2,4,4]& ``` For fun, here's a 37 byte version ``` Hypergeometric2F1[(1-#)/2,-#/2,2,4]& ``` and 52 byte version ``` SeriesCoefficient[1-x-Sqrt[1-2x-3x^2],{x,0,#+2}]/2& ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~17~~ ~~14~~ 13 bytes ``` ×US; 1;HÇƓ¡1ị ``` This uses the recurrence relation from [@PeterTaylor's answer](https://codegolf.stackexchange.com/a/66853). [Try it online!](http://jelly.tryitonline.net/#code=w5dVUzsKMTtIw4fGk8KhMeG7iw&input=MTA) ### How it works ``` ×US; Define a helper link. Left argument: a (list) ×U Multiply (×) a by its reverse (U). S Compute the sum of the resulting list. ; Prepend it to a. Return the result. 1;HÇƓ¡1ị Define the main link. 1 Set the left argument to 1. ;H Append the half of 1 to 1. Result: [1, 0.5]. Ɠ Read an integer n from STDIN. Ç ¡ Call the helper link (Ç) n times. 1ị Retrieve the result at index 1. ``` [Answer] # Mathematica, ~~44~~ ~~42~~ 34 bytes ``` Sum[#!/(i!(i+1)!(#-2i)!),{i,0,#}]& ``` A 35 bytes version: ``` Coefficient[(1+x+1/x)^#,x]/#&[#+1]& ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes ``` ÝI<ãʒ.øDŸQ}g ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8FxPm8OLT03SO7zD5eiOwNr0///NAA) While most answers use a formula or recurrence relation, this is a simple counting approach. Each possible path through the grid is represented by the list of its y coordinates. For n segments, there are a total of (n+1) points, but the first and last one are necessarily 0, so that leaves (n-1) points to specify. ``` Ý # range [0..n] I< # n - 1 ã # cartesian power ``` We now have a list of paths (not yet including the initial and final 0). By construction, none of them ever go below 0. However, some of them have illegal slopes (e.g. jump from 0 to 2), so we need to filter them out. ``` ʒ }g # count how many paths satistfy the following condition 0.ø # surround with 0 Q # is equal to DŸ # its own fluctuating range ``` `Ÿ` is the [fluctuating range](https://codegolf.stackexchange.com/questions/74855/fluctuating-ranges/) built-in. If there's any pair of non-adjacent numbers, it will fill in the missing numbers (e.g. [0, 2] becomes [0, 1, 2]). Only legal paths will be left unchanged. A perhaps more intuitive way to check for illegal slopes would be `üαà` (assert the maximum of pairwise absolute differences equals 1). However, this misses the flat [0, 0, ... 0] path, which costs one extra byte to fix. Finally, note that the actual code uses `.ø` where this explanation uses `0.ø`. Instead of surrounding the path with 0s, this surrounds the implicit input with two copies of the path. This turns the coordinate system upside-down and inside-out, but is otherwise equivalent. [Answer] # [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` îu¬@Y≤ÅÉÑ(πε ``` [Run and debug it](https://staxlang.xyz/#p=8c75aa4059f38f90a528e3ee&i=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10&a=1&m=2) I don't know how to do fancy math typesetting, but this essentially relies on a dynamic programming construction ``` M(0) = 1 M(1) = 1 M(n + 1) = M(n) + sum(M(k) * M(n - k - 1) for k in [0..n-1]) ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), ~~38~~ ~~36~~ 26 bytes ``` n->(1+x+x^2)^n++/n\x^n++%x ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P0/XTsNQu0K7Is5IMy5PW1s/L6YCRKtW/E/LL9LIU7BVMNRRMDLQUSgoyswrAQooKejaAYk0jTxNTc3/AA "Pari/GP – Try It Online") Using equation (11) from [MathWorld](http://mathworld.wolfram.com/MotzkinNumber.html): \$ M\_n = \dfrac{1}{n + 1} \dbinom{n + 1}{1}\_2 \$ where \$ \binom{n}{k}\_2 \$ is a [trinomial coefficient](http://mathworld.wolfram.com/TrinomialCoefficient.html). By definition, \$ \binom{n}{k}\_2 \$ is the coefficient of \$ x^{n + k} \$ in the expansion of \$ (1 + x + x^2)^n \$. [Answer] # Ruby, 50 straightforward implementation of the recurrence relation. ``` g=->n{n<2?1:(3*(n-1)*g[n-2]+(2*n+1)*g[n-1])/(n+2)} ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 90 bytes ``` (([{}]<(())>)<{({}()<{<>([({})]({}[({})]({}<>{}<>)))<>}<>>)}>){({}()<{}>)}{}({}{}[{}{}]<>) ``` [Try it online!](https://tio.run/##PYoxCoBADAS/s1sI2od85LjiLARRLGxD3h7XQoudnWLWe@zXtJ3jqAJaZDeAdFogEjpzNCm78Iv5O5Lmemc6v16ashDai66uapkf "Brain-Flak – Try It Online") Computes \${\binom{n}{0}}\_2 - {\binom{n}{2}}\_2\$, where \$\binom{n}{k}\_2\$ is a [trinomial coefficient](http://mathworld.wolfram.com/TrinomialCoefficient.html). I couldn't find this formula anywhere, so I can't reference it, but it can be proved in the same way as the analogous formula \$C\_n = \binom{2n}{n} - \binom{2n}{n+1}\$. [Answer] # [Haskell](https://www.haskell.org/), ~~55~~ 52 bytes Straightforward implementation of the recursion. Thanks @Delfad0r for -3 bytes! ``` a n|n>2=div((2*n+1)*a(n-1)+(3*n-3)*a(n-2))$n+2 a n=n ``` [Try it online!](https://tio.run/##Jcq9CoAgFAbQvae4Q4M/KKmzvUg0XChI0g@paOrdLWg8cDY@9zXn1pjwYPRxSbcQXkE7qVjAOKlFUDDhp5eyh/bd1yNa4QSKVI@Ei3oqXIlpcta6YW4v "Haskell – Try It Online") [Answer] # [Maxima](http://maxima.sourceforge.net/), 49 bytes Use the formula \$ M\_n=\frac{1}{n+1}\cdot[z^{n+2}](1+x+x^2)^n \$ ``` f(n):=coeff(expand((1+x+x^2)^(n+1)),x,n+2)/(n+1); ``` [Try it online!](https://tio.run/##HcxBCoMwEEbhvaf4ERczJNImy5T2KEJQQ104CcHC3D5V3@7bvD3qtsfWEgmH95zXlGjVEmUhckaNTp4nEuOYrVoxnh@3Xi3lCgkOx7f@4J9YMqjDWambHCQWPcYPeovrzR0P7Q8) [Answer] ## ES6, 44 bytes ``` f=(n,k=0)=>n<1?1:k<n&&f(k)*f(n-2-k)+f(n,k+1) ``` Straightforward port of @xnor's recursive Python solution. Needs `n<1?1:` because `n<1||` would make `f(0)` return `true`. [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-n`, 8 bytes ``` 3$ŧ←∫Ɔž≥ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJunlLsgqWlJWm6FhuNVY4uf9Q24VHH6mNtR_c96ly6pDgpuRgqu2CLIZcRlzGXCZcplxmXOZcFlyWXoQFEDgA) ``` 3$ŧ←∫Ɔž≥ Let n be the input 3$ŧ Find an n-tuple of integers in [0, 3) ← Decrement each element ∫ Take the cumulative sum Ɔž Check that the last element is 0 ≥ And that each element is non-negative ``` `-n` counts the number of solutions. ]
[Question] [ You are given four integers: \$e,s,b\in\{0,1\}\$ and \$S\in \{0,1,2,4\}\$, where \$e,s,b,S\$ stand for egg, sausage, bacon and spam respectively. Your task is to figure out whether the corresponding ingredients match a valid entry in the following menu: ``` [e]gg | [s]ausage | [b]acon | [S]pam -------+-----------+---------+-------- 1 | 0 | 1 | 0 1 | 1 | 1 | 0 1 | 0 | 0 | 1 1 | 0 | 1 | 1 1 | 1 | 1 | 1 0 | 1 | 1 | 2 1 | 0 | 1 | 4 1 | 0 | 0 | 4 1 | 1 | 0 | 2 ``` This is a subset of the menu described in the famous [Monty Python's sketch](https://www.businessinsider.com/email-term-spam-junk-mail-actually-stems-monty-python-sketch-2017-1), where dishes based on other ingredients are omitted. ## Rules * You can take \$(e,s,b,S)\$ in any order and any convenient format as long as they are clearly separated into 4 distinct values as described above (e.g. claiming that your code takes a single bitmask with all values packed in there is not allowed). *Examples:* `[1,0,1,4]`, `"1014"`, or 4 distinct arguments * Each value is guaranteed to be valid (i.e. you don't have to support \$e=2\$ or \$S=3\$). * You may return (or print) either: + a truthy value for *matching* and a falsy value for *not-matching* + a falsy value for *matching* and a truthy value for *not-matching* + 2 distinct, consistent values of your choice (please specify them in your answer) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") ## Test cases (all of them) Format: `[e, s, b, S] --> matching` ``` [ 0, 0, 0, 0 ] --> false [ 0, 0, 0, 1 ] --> false [ 0, 0, 0, 2 ] --> false [ 0, 0, 0, 4 ] --> false [ 0, 0, 1, 0 ] --> false [ 0, 0, 1, 1 ] --> false [ 0, 0, 1, 2 ] --> false [ 0, 0, 1, 4 ] --> false [ 0, 1, 0, 0 ] --> false [ 0, 1, 0, 1 ] --> false [ 0, 1, 0, 2 ] --> false [ 0, 1, 0, 4 ] --> false [ 0, 1, 1, 0 ] --> false [ 0, 1, 1, 1 ] --> false [ 0, 1, 1, 2 ] --> true [ 0, 1, 1, 4 ] --> false [ 1, 0, 0, 0 ] --> false [ 1, 0, 0, 1 ] --> true [ 1, 0, 0, 2 ] --> false [ 1, 0, 0, 4 ] --> true [ 1, 0, 1, 0 ] --> true [ 1, 0, 1, 1 ] --> true [ 1, 0, 1, 2 ] --> false [ 1, 0, 1, 4 ] --> true [ 1, 1, 0, 0 ] --> false [ 1, 1, 0, 1 ] --> false [ 1, 1, 0, 2 ] --> true [ 1, 1, 0, 4 ] --> false [ 1, 1, 1, 0 ] --> true [ 1, 1, 1, 1 ] --> true [ 1, 1, 1, 2 ] --> false [ 1, 1, 1, 4 ] --> false ``` *Spam spam spam spam. Lovely spam! Wonderful spam!* [Answer] # [Python](https://docs.python.org/3/), 32 bytes ``` "001111020114001410120110".count ``` [Try it online!](https://tio.run/##dZDNbsMgEITvfopVTqCiikl8quRrXyC9pTk4FUksIccC3KpP767z09Y2i5B2GZbh03Tf6XxpN8Oxeh9W1oKXXXMpuS9hMfZ29fxx6ds0fJ0b7wgvBXlDqQ4nl6gi91l71bRdn5TWBSlnojmYreYrXxBfcBNTUFE/jeVwK@5WtvwiuMgjx9GDT11o2qSuWnX/RA@7HVnz2LQ39Fr76PbFfx2Cvhb0MqdD8IfgD8EfOX8I/BD4IfBD4IfAD4Eff/xvoZ/JM3sI8WMS/68NhPQxSX82/oBfysjLWXNkzCGgZ5PHJPmlTZkbz7Ejzw6BfZH7Dw "Python 3 – Try It Online") Takes input in `'sbeS'` order as a single string, like `'1102'`. Simply checks whether the string appears as a substring of the hardcoded string, using the object method to avoid needing to write out a costly `lambda` to define a function. The desired strings are squished together as much as possible via overlapping. For example, the part `"001111020114` checks for `0011`, `0111`, `1111`, `1110`, and `1102`. The fact that `2` and `4` can only appear as the counts of spam, which is listed last, lets us append strings directly to their right without false positives. I played with the order of the inputs to try to overlap more, but there might be a better outcome. I suspect this approach can be beaten with a modulo chain or similar using number inputs. [Answer] # [Python 3](https://docs.python.org/3/), 31 bytes ``` oct(0x20a00924204c00c048).count ``` [Try it online!](https://tio.run/##dZBBTsMwEEX3OcUsbWEh/@AFIGXLBcqudJFGLo1kJZHtQHv64FIKJPFIkSb5Hr88/eEcj333MB2qt6lvotCnUtdaP5Wm1KbRutHmUd43/djF6fPYOkt4LsgpirV/t5Eqsh@1E203jFFIWZCwKqi92sh05ApKB@klRC@CvLuM/XXY69ikG96GtHK4MNLX4Nsuiu@s@vmJnLZb0ur20E7RS@2C3RX/czB5yeQml4Phg@GD4SPHB@MPxh@MPxh/MP5g/PHn/@rHRbzAg6kfs/p/MWDax6z9xfpNfh0jH2fhyMDBqGebx6z5Ncbk1nPuyLuDcV/1/gU "Python 3 – Try It Online") Based on [@xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [answer](https://codegolf.stackexchange.com/a/199678/88089) [Answer] # [Python 2](https://docs.python.org/2/), ~~29 28~~ 25 bytes -3 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546)! (Suffixing a string as the `hash` input) ``` lambda s:hash(s+'?pB{')%3 ``` An unnamed function accepting a string of digit characters, `egg+bacon+spam+sausage` (e.g. `'0040'`) which yields a falsey value (`0`) if on the menu or a truthy value (`1` or `2`) if not. **[Try it online!](https://tio.run/##bZJNbsMgEIX3OcVsKkChFeOwihRFyhW6zQa3/olUYys4iyrp2V0rBoXXBlug8bwPP5gZvse298VU747Tl@vKT0dh27rQyrAW@@FwFeplMw3nkx9JVBSopHe60f7oX@NYx1Ws6v5MVdNoCoPr5tldgmsqTaX76D2dPEnJmsz9ZaUpRvyIYhqiLJeU89cCOAtKC7ssShM588gZ8GKSFwNRyjFwDBwD989nxhXAoTMLSgtK@1fJcIPZabMzMDhj8MLghZ/cZ8al/6ntiuaxNMNSaChxKry4CU21FNef5RFvc2d0bpR3BqRxA6WmXw "Python 2 – Try It Online")** This was found by [dingledooper](https://codegolf.stackexchange.com/users/88546) using [this code](https://gist.github.com/Lydxn/5cc75ab94c18056427823b9d4b67dc02 "Git Hub") ([Try it online](http://clang.llvm.org/), limited to printables, which finds the above). --- **28 byter...** ``` lambda*i:hash(i)/442%89%22%5 ``` An unnamed function accepting four integers, `sausage, bacon, spam, egg` which yields a falsey value (`0`) if on the menu or a truthy value (`1`, `2`, `3`, or `4`) if not. **[Try it online!](https://tio.run/##bZLNCsIwEITvPsVeSluNmA0RVBAfwquXVPsHmharB8F3r8UmmFFDaNnOfM0km/Zxqxqr@mJ76M/mkp3MtN5UpquSOl1oraLVOlIqWvbttbY3inPqKKM9PWl3sHM3Zu4dT4rmSnlZCupacxme5t6ZMheUmWNjqbaUJCxIvienglzFn8rJUAWadw5fFXAanBr@Mjql4@RHk5BF@iwSKq8xcAwcA/eTM@AUcJhMg1ODU387GU4w2G2wB4ZkDFkYsvCf8ww4v166mdAwxsswNhpa7BsfP2NBRfJfHLi0fwE "Python 2 – Try It Online")** --- **Another 28:** ``` lambda*i:hash(i)/8883%55%8-2 ``` [Try it here!](https://tio.run/##bVLLCsIwELz7FXuRtppitkYogvgRXr2k2hdoWmw9CP57LTbBjLqEhM3MJJPdtI@@akwyFLvjcNHX7KwX9bbSXRXW0SpN0/V8s5mncTK0t9r0FOTUUUYHetL@aGIbS7sGs6K5UV6WgrpWX8dZ3ztd5oIyfWoM1YbCkAXJ9@BIkM34k1kYMg9zzHE3AZ0CpoJTJqa0OvnBJHiRzouEzGEMOgYdg@7Hp6dLQIfOFDAVMNU3k6GC3mu9NzA4Y/DC4IX/1NPTufui7YzGmD7D1GhosWt88AwEFaH3FRw80aPhBQ "Python 2 – Try It Online") (accepts `egg, spam, bacon, sausage`) --- **29 byters...** ``` lambda*i:hash(i)/676%86%9%6-2 ``` [Try it here!](https://tio.run/##dVLLCsIwELz7FXspbTVitoT6APEjvHpJtS/QtFg9CP57rbbBjI8lLGx2Jpl91LdLUZmozda79qhPyUGPy1WhmyIow1k8j71F7C29eBq19bk0F/JTaiihLd1pszPTwSZP54@y6kxpngtqan3qvL42Ok8FJXpfGSoNBQELkq/DoaAh4nc0pCFychbZ3UbAU4BU8EqPlANPvnMStEirRUJkcww8Bh4D70unw4uAh8oUIBUg1SeSoYNOtU4NDMoYtDBo4R/9dHj2v3A1os76TegHDSO2g/fvvqAs@LsKYfsA "Python 2 – Try It Online") (accepts `egg, spam, sausage, bacon`) Or one which returns `True` if on the menu or `False` otherwise: ``` lambda*i:hash(i)/64%31%14%8<2 ``` [Try it here!](https://tio.run/##bZJNDsIgEIX3nmI2TVvFyFRijNF4CLduqPYvUdpYXZh499q0EHkqIZBh3gcPhuZ5L2uTdPnu2F30NT3rabUpdVtGVbxYqWDJAatgvU265laZO4UZtZTSgV60P5q5bTM7h5O8vlFWFILaRl/7UT9aXWSCUn2qDVWGoogFyaFzLMhG/IlsGiIv55T9agKcAqWCXUaltJz85CR4kc6LhMjlGDgGjoH78elxCXDoTIFSgVJ9Kxle0LutdwcGZwxeGLzwn/f0OHdevJlQ38bPMBYaSuwKH75CQXn09QsGYNDF3Rs "Python 2 – Try It Online") (accepts `spam, sausage, egg, bacon`) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` •ʒº-ép•bsCè ``` [Try it online!](https://tio.run/##LY2xDcIwEEV7pohcx1K@45oUROwRSxRUIHkBZmAEKlghZdIxBos490xO8pP97935lqd0vZQ@nMfBNd4fGzeU3@P1fS6zXz93u6Z8Wt@lLZ3VQSCACOyITGQik2XCE57whCc8oRgssu4OnkyACILw/uAPFO2oS2tDeHTZbLUB "05AB1E – Try It Online") Inputs as a string `"Sesb"`. Outputs 0 for matching and 1 for non-matching. ``` •ʒº-ép• # compressed integer 269454360636 b # convert to binary: 11111010111100101110110100000000111100 sC # convert the input from binary: 8S + 4e + 2s + b # (this doesn't error out on digits > 1) è # use this value to index in the above bitstring ``` [Answer] # x86-16 machine code, 30 bytes ``` D0 E3 SHL BL, 1 ; e << 1 0A FB OR BH, BL ; BH = e << 1 | s D0 E7 SHL BH, 1 ; es << 1 0A C7 OR AL, BH ; AL = e << 2 | s << 1 | b D0 E0 03 SHL AL, 3 ; AL =<< 3 (80186+ only) 0A C4 OR AL, AH ; AL = spam table value B1 09 MOV CL, 9 ; search 9 entries BF 013B MOV DI, OFFSET SPAM ; in SPAM table F2/ AE REPNZ SCASB ; search table - ZF if found, NZ if not C3 RET ; return to caller SPAM DB 28H, 38H, 21H, 29H, 39H, 1AH, 2CH, 24H, 32H ; SPAM table ``` Input as `BL = e`, `BH = s`, `AL = b`, `AH = S`. Output `ZF` if valid entry, `NZ` if not valid Encodes the input values into a 6-bit binary value (`00esbSSS`), and compares against the table of known valid results. Here's output from a little test program for PC DOS that takes input from command line: [![enter image description here](https://i.stack.imgur.com/yVkGN.png)](https://i.stack.imgur.com/yVkGN.png) Note: Due to the use of `SHL AL, imm8`, this won't work on an 8088-based PC/XT. It would be +1 byte to do `MOV CL, 3 / SHL AL, CL`. [Answer] # [PHP](https://php.net/), ~~61~~ ~~59~~ ~~56~~ ~~34~~ ~~32~~ ~~30~~ 27 bytes ``` <?=74958>>33-$argn%95%34&1; ``` [Try it online!](https://tio.run/##FcwxDsIwEAXRnnMQukgMdgQRIXTcgwpoEgs4P8uOJW/xNXrt2SKm6@VYx@E0z6X02/v7sXTj0JW64xyxz7fJj@fgqXlwww03csMOO@ywww477MgOPfTQQw899NBDDz300EMPPfTQy1N/a/u@1uUT/e0P "PHP – Try It Online") Each input (ordered esbS) is read as a decimal value and the modulus buckets them into a smaller range (i.e. a hashing function), which are then looked up in the "bit table" of the constant. The hashing function has clashing values, but these all coincide when values are either truthy or falsy. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 24 bytes 21 bytes This refinement of the solution is thanks to Grimmy, who took my formatting and used stronger stack manipulation to save a bunch of whitespace and variable assignment. The following is the code (for the first time, newlines are necessary). ``` '\;* >> @^* ;>'n/\=~ ``` Grimmy's solution at the bottom takes in a string of a list of arrays and applies the following operation to all of them, even though it's not strictly necessary. Golfscript can take input as a header, which is where my TIO references. Grimmy's is much cleaner to see all the outputs. Input is a stack-dump of four elements: e, s, b, S For the following explanation, I'm going to use N as a "newline" indicator so you can understand how this works in my formatting. ``` '\;*N>>N@^*NN;>'n/\=~ #Do as instructed ' ' #String notation '\;*N ' #[Index 0] Pop s, then multiply e and b ' >>N ' #[Index 1] A trickier operation, will explain at bottom. ' @^*N ' #[Index 2] s*(e xor b) ' N ' #[Index 3] Can never be called. ' ;>' #[Index 4] Ensure e=1, s=0. ' 'n/ #Split the string on newlines (stack is e s b S "x/y/z") \ #Swap the top two elements of the stack (e s b "x/y/z" S) = #Find the (top element)th element of (second element) ~ #Then evaluate it. ``` So, why do these operations work? ``` m=0 [e]gg | [s]ausage | [b]acon | spa[m] -------+-----------+---------+-------- 1 | 0 | 1 | 0 1 | 1 | 1 | 0 As long as e=1 and b=1, s can be anything. So if m=0, our output can be e*b We do this in the program with {\;*} This removes s from the array, then multiplies e and b together. If they're both 1, yay! If not, then we get a 0. m=1 [e]gg | [s]ausage | [b]acon | spa[m] -------+-----------+---------+-------- 1 | 0 | 0 | 1 1 | 0 | 1 | 1 1 | 1 | 1 | 1 3/4 binary options. As long as we have e=1, and we DON'T have s=1, b=0, then we're good. e*NOT(s*NOT(b)) or e*(NOT(s) + b) So, why does {>>} work? It starts by checking that s>b. This should NEVER be true. So we have 0. Then we check if e>0, which is true if e=1 and the above worked. If the above *didn't* work, then e>1 will never be true. m=2 [e]gg | [s]ausage | [b]acon | spa[m] -------+-----------+---------+-------- 0 | 1 | 1 | 2 1 | 1 | 0 | 2 As long as s=1, then we have an xor situation! s*(e xor b) {@^*} pulls the e to the top of the stack, then xors it with b. Then the * multiplies that result with s. m=4 [e]gg | [s]ausage | [b]acon | spa[m] -------+-----------+---------+-------- 1 | 0 | 0 | 4 1 | 0 | 1 | 4 As long as e=1 and s=0, we don't care about b. e*NOT(s) We just do this with {;>}, which removes b from the equations, and makes sure e>s, which can only be the case is e is 1 and s is 0. ``` There we go! With brainpower combined, feast your eyes upon this beautiful creation! [Try the 21-byter online!](https://tio.run/##S8/PSStOLsosKPlvqACCBv/VY6y1uOzsuBzitLi4rO3U8/RjbOv@/wcA "GolfScript – Try It Online") [Try the old 24-byter online!](https://tio.run/##S8/PSStOLsosKPlvqGAAhCb/o6tjrLVqq@3saqsd4rRqDaqt7WpjY2zr/v8HAA "GolfScript – Try It Online") [Try all examples online on the old solution (26 bytes)! (Courtesy Grimmy)](https://tio.run/##Tc6xCsIwGMTx3acIGTvYnGQrDb5HUxdBEURF3ULy6hFC@FeyHOT43Xd93i@f8/v2@lYbH3ZMe2vmYGyspSwpTkNOIeR0PA3ZpSnkNc6lNfNYF2faW3c9iXQg@Z5ET/RET70nPOEJT3jCE566Iq4St4g1sSE2hNw0ev@eR3Ek8btdsK155M1zJK0/ "GolfScript – Try It Online") [Answer] # Python, ~~[49](https://tio.run/##dZPRaoNAEEXf/YphX9S4CRljpQ3YnwiUQtIHJUotRmV381DEb7ezNoFEdkBU7uzM3cNl@l/z3bW7qYIMTlOTX4pzDgdZSi2LfVG3QZy@JS/JLt2muzQ8xtHr6hAlqzKKVzoqviZTaqOpVwhxhK28P/AF6/U7VHmjS@@hgFwh5gqJs4CcB3IeyHmg0wM5DuQ4kONAjgM5DuQ48InDqOuTvrRALg5cxnGbhFwauEzjqeEBYqkjo7sN0GWAHII7CVwmsZyUOBucDMgwIMfgyIEWY6P7pjaBOLUi9Lz60nfKwI/uWq/qFNgNgrqdv3rvAf33Erqroa2y2r17HkkDAEoJWkIh4UBH7JxN0@VnHVCjLf@3zm/aS3trQaoirQpumx3eBJVlYmurvapbE1QiGPwPH@rKtmeZgpIIwP/0xxAGGj8C3WFQ43yXgc6Mlmj6Aw)~~ 44 bytes ``` lambda S,e,s,b:269454360636>>8*S+4*e+2*s+b&1 ``` You can [verify all test cases](https://tio.run/##dZPRaoNAEEXf/YphH6rRTcgYkTaQ/ESgFJo@KFFqMSq7m4cifrudtQlE2QFRmdk7dw@X6X7Nd9vsxhIOcB7r7JpfMjjJQmqZ7@NtiukO35Itpsfja3iKkrCI4lBH@QuOptBGk0wI8Qlb@XjgC9brI5RZrQvvqYFcI@YaibOBnAdyHsh5oNMDOQ7kOJDjQI4DOQ7kOHDGYdRtVl9aIBcHLuO4T0IuDVymMRM8QSzryNTdBugyQA7BnQQuk1hOSpwCJwMyDMgxOHKgxdjorq5MIM6NWHlede1aZeBHt41XtgrsBkHVTF@994D@OwntzdBW2dpDPY2kAQCFBC0hl3CiI3bOpm6ziw5IaNv/0ulNe2lvLaiqqFYG96W2xzpVNSYoRdD77z5UpVUcDgoKujT4H/6wgp4mDkC2vRom@57ODBZi/AM). Outputs 0 for a valid recipe and 1 otherwise. Hats off to @Arnauld for shaving me 5 bytes :) Borrows [Grimmy's](https://codegolf.stackexchange.com/a/199644/75323) approach so be sure to upvote that one as well! [Answer] # [Python 3](https://docs.python.org/3/), ~~52~~ \$\cdots\$ ~~48~~ 44 bytes ``` lambda e,s,b,S:206163194016>>8*S+e*4+s*2+b&1 ``` [Try it online!](https://tio.run/##dZFNa4QwEIbv/oqph@JHtvi6Iq0Qj/0D25v1oLuRClZFU2kRf7vdQpdFyUAOyUxmXh6e/kd/dO1xreT72hSf5aUgJUZRilMSBjHiI16iAHGaPnsnX3mRP3qhXz5iHeT8NnypxC5GW9Br0YzXe9tpur4Xq@oG0kJR3VJmZRkF4nYo//@di00DXCPkGpGxAS4DXAa4DBgzwHGA4wDHAY4DHAc4Dtw5/rTs6vsIcDqw0XHfBM4GNjb2AzcIQx1M3RwAUwA4BLMJbEwYNkXGASMDGAZwDAYPeWLRJCvH065F/VC32qnsualH7Wh3ocMhpXlaaB4yZ3qQgSulyhdS3706a3V5st31Fw "Python 3 – Try It Online") Ouputs Truthy for true and Falsy otherwise. [Answer] # [C (clang)](http://clang.llvm.org/), 49 bytes ``` f(e,s,b,S){return 206163194016>>8*S+e*4+s*2+b&1;} ``` [Try it online!](https://tio.run/##hZPLSsNAGEb3PsVQqOQKOeMQWgp5iS7VRS@JFHSQtK5Knz0qFK04Px8kizAcJofDt6t3r5v4Mk1D1lfHalut8/PYnz7G6HzT0j6wDA1t1y2KddkXoTwWvtzes7pMh3hyb5tDzHJ3vnsfvz6HbPbYVO76uGdX13Xn5nuXzff5U5xVbsh@z/Pvd5UgESQm6QXpTTIIMqRJhCemJ8IT0xPhiemJ8CTtieiJ2RPRE7MnoidmT0RPzJ6Inpg9ET0xeyJ68tOTJBkE@c8TsU/MfSL2ye0@SZJekN68MwgypO9EeF57pkkEiUl6QRqeCE/SnoiemD0RPY19IvbJ7T7TfxsEGdJ3IjyNnoiemD0RPTF7Inr@3edl@gQ "C (clang) – Try It Online") Ouputs `1` for true and `O` otherwise. [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), ~~[13](https://tio.run/##Vc@xDcJAEAXR3FVQgAMGUQGUcXJIgtwA2YHIaMBIJNAERmRQyV0jSwJYI22ywdfobTd9v4uo@bIuj@t7KOOh7u81n1dNGY81D@V5et0iIqV5O/te1zYJfQt9S33/HdqhHdox7VAP9VAP9VAP9VCPqYd8yId8yId8yId8yId8yId8yId8yId8v6/7AA)~~ 11 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) ``` “BƑṗ©N’Bị@Ḅ ``` You can [try all the test cases](https://tio.run/##Vc@xCcJQGEXh3ikyQASP2AVEMoC9hJQ2kgXsgggprKxE0AEEBzAIFgbcI1nkaaGGA6/5eVwO32pZFOsQuvKUvvZtfXhe5l15TNv7btbetqGtH8nnLxpOo648J001aKpuc12EkGWjOPq@PB5k6Brrmuj679AO7dCOfod6qId6qId6qId69D3kQz7kQz7kQz7kQz7kQz7kQz7kQz7k@135Gw)! Thank you, @Nick, for saving me 2 bytes. I'm currently tied with the [shortest 05AB1E answer](https://codegolf.stackexchange.com/a/199644/75323) :) [Answer] # [Japt](https://github.com/ETHproductions/japt), 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` "~ "øUn5 d ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=IoKbfoOcIIaBmCL4VW41IGQ&input=IjExMTIi) ``` "~ "øUn5 d Program taking U, the string in "esbS" form "~ " String with values 130,155,126,131,156,32,134,129,152 ø Does it contain Un5 The input converted from Base-5 string to a number d And converted to a char? ``` [Answer] # APL+WIN, 23 bytes ``` ×+/'é¢~⣠≠ü⌹'=⎕av[5⊥⎕] ``` Index origin = 0 Prompts for a vector 4 integers and returns 1 for true zero for false. Explanation: Converts input vector from base 5 to an integer used to index into APL+WIN's atomic character vector (extended ASCII) and checks if it is in the menu which has similarly been converted to characters. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~51 41~~ 36 bytes ``` ->*x{"J36:;>'-."[""<<x.join.oct%77]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf106rolrJy9jMytpOXVdPKVpJycamQi8rPzNPLz@5RNXcPLb2f7SBjmGsXkFRfkppcokGmKcDJbUM9PRMYjX1chMLqmsqagoUoit00qK1KmKB2gA "Ruby – Try It Online") Returns `nil` (falsy) or a string (truthy). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •ÿŸ»¢•bŽ9“«S4äøJIå ``` Input as a concatenated string of \$e||s||b||S\$. If this is not allowed, a single byte has to be added for an explicit `J`oin. Pretty straight-forward approach, so will golf it down from here. [Try it online](https://tio.run/##AS8A0P9vc2FiaWX//@KAosO/xbjCu8Ki4oCiYsW9OeKAnMKrUzTDpMO4SknDpf//MTEwMg) or [verify all test cases](https://tio.run/##Jc2hCsJQHEbxVxk3L3hkxWS3GsXgwGAyCMLakg9gNg1NvsBARNhlL7IXuW47t/wvfBx@58uhPB3TtVqHbLjds7BOQ93EX992n64Zv2X/XQ31o3tvi/iM7aaKr5SnXViML@TTwbP0FPPBDTfcmDfssMMOO@yww465Qw899NBDDz300EMPPfTQQw899Ji8/R8). **Explanation:** ``` •ÿŸ»¢• # Push compressed integer 4221990791 b # Convert it to binary: 11111011101001100111011110000111 Ž9“ # Push compressed integer 2442 « # Merge them together: 111110111010011001110111100001112442 S # Convert it to a list of digits 4ä # Split it into 4 equal-sized parts ø # Zip/transpose; swapping rows and columns, to create quartets J # Join those together Iå # And check if the input-string is in this list # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•ÿŸ»¢•` is `4221990791` and `Ž9“` is `2442`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` №%')-/36AE§γ↨θ² ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5vxRIKqmqa@rqG5s5uirpKDiWeOalpFZopOsoOCUWp2oU6igYaQKB9f//0dEmOgoGYGQYG/tftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input ingredients as a list in reverse order and outputs a Charcoal boolean i.e. `-` for matching and nothing for non-matching. Explanation: ``` θ Input list ↨ ² Convert from "base 2" §γ Index into printable ASCII №%')-/36AE Is the result contained in the given literal? Implicitly print. ``` One of my rare answers that don't use any characters with unusual widths meaning that the explanation lines up nicely for once. [Answer] # [cQuents](https://github.com/stestoltz/cQuents), 38 bytes ``` ?112,1001,Z+3,Z+6,Z+1,Z+3,1102,Z+8,Z+1 ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/397Q0EjH0MDAUCdK2xiIzYAYwjY0NDACMixAAv//A5UBAA "cQuents – Try It Online") Builds a list of all of the possible inputs (in integer form) and returns True if they are in the list. [Answer] # Excel, 67 bytes ``` =CHOOSE(D1+1,A1*C1,AND(A1,B1<=C1),AND(B1,A1+C1=1),,AND(A1,NOT(B1))) ``` Follows similar logic to that used by @Mathgeek [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “ṚE⁾’,3ḥỊ ``` A monadic Link accepting a list of integers, `[egg, sausage, bacon, spam]`, which yields a truthy value (`1`) if on the menu or a falsey value (`0`) if not. **[Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO2e5Pmrc96hhpo7xwx1LH@7u@v//f7ShjoIBGJnEAgA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##bZAxCgIxFESvkgOk@BNzBfEQS0qbZS8gWMRtBG@gaGnnARTFRjxI/kXiLrp8BiwSePyZTP60y65b1ar5WG6HuW6emvd@Vq7nct/V9@O11f7SDkfzab2otWngnXg33sm7kUAk37ERjGAkEwVSRnolmk9@SplmQgQiVkYjkA/kA/lgPlAeKI9/BsoD5f3bnbflBrmXQE0IEYgidR2IYkof "Jelly – Try It Online"). There may well be an 8 or 7 out there using a similar method, it's just a mater of finding them! ### How? ``` “ṚE⁾’,3ḥỊ - Link: list of integers “ṚE⁾’ - base 250 number = 11455143 3 - three , - pair = [11455143, 3] ḥ - Jelly's hash: use 11455143 as a salt and [1,2,3] as a domain Ị - insignificant? (effectively "equals one?") ``` --- **[Another 9](https://tio.run/##bZAxCgIxFESvkgOk@BP@HTzEktJm2QsIFsFG2MZa0Eaw034RK0XvkVwk7qLLZ8AigcefyeRPu@y6Va0lHfLQ59vufX2cStr7kIdzfd2f27K5tOMp6bhe1No08E68m@7o3UQgku/YCEYwkpkCKZVeUfPJTynzTIhAxEo1AvlAPpAP5gPlgfL4Z6A8UN6/3XlbbpB7CdSEEIFIqetApDF@AA "Jelly – Try It Online")** which takes `[egg, sausage, bacon, spam]` and yields `2` when on-menu or `1` when not: ``` “Ḋẏƭ¢’,2ḥ ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 35 34 30 bytes ``` (e,s,b,S)=>s<S?5/S-s&e+b*s:e&b ``` [Try it online!](https://tio.run/##dZPRS4NgFMXf/SvuxhizfbPdWBAzi6AGQW8@RjC16zBMh/dzBeLfbm6u@Nq84Nu55xx/HL6PYBdwVCRbPdvdNLHXTEixCpVve3d8699fX/ozHtM0vOAljcMmJQ1xkKQMHsxdKy6zSCd5BppYt1ZgBaECXwF9bynS9G5DZQFEecYaCuIy1a0zNk5tt9WTGCaDwVEfeN6JvaucTvenh6w8JSfNN5P1qHp1HCcoNuUnZZrfalg9PL88PcJXwDCqusR6fSipgVKmLtAMMQO6Q6u2DkAwV78fqPYnWnt7cCKhLF3J0kKQUO5CuQvlLhS6UOZCmQtlLpS5UOZCmQv/uHRR9ijnVSjPheZc//JQXgvNtXpMR6h@BUVFKsL@IpSRpKXQXKo/byGYBCYUmVBmOt/JfHfD1f5VL4eqe9622/wA "JavaScript (V8) – Try It Online") I wrote a random expression generator and left it running for a few hours to generate the expression following the `=>`. In this answer I am only posting unedited outputs from the generator. [Answer] **RUST, 98 Bytes** ``` fn f(e:u8,s:u8,b:u8,x:u8)->bool{match x|s<<3|e<<4|b<<5{17|20|26|42|48|49|52|56|57=>true,_=>false}} ``` [Try it here](https://tio.run/##bVDvS@QwEP3s/hWjH84Waulku@rFtofiDwRBOI77IiJtTbly2VaaFJWmf/uamQVZxJa8mXl5ecnMMBq7GY0CY5@lbHspJ5@1XQQXY/Nblc/z2abpoAmUHE8jQ1ARvHkIj4qq7/W0Lm39D96cybKlU1mWuirLVhOeOJE4cexS4dJTl/50K@FWx251khd2GFX0lBdNqY2aZ7piXbZdEMK02NPKglHWQA78liCMdV//p9B2yvi4Ll8Cp52Ox@518Hn4SdH5PXbQ/riOS/NUvVs6dEYbgX5IHuEIqsPkMAL9gLuF2C2Wu0X6CPs5V6F3mcO47rVWtZUy@6vqLPADgd1FYwmLgi9t@oG6gbaDH9wVvbBt/Eh9FScRbca4DWIbliHkOWfptp@Xoe2s7vaDg5v7PzDJX/MBK7mp2S/lx/hVen1@e3d1Kb@Rz4t5k9C38AsZBWNKiMwj88g8Eo@sR9Yj65H1yHpkPaJAQs8j@yMZEQrOU8r9T8g8Mo/Esz@yv0fBDPkg65H1yHry/wA) ]
[Question] [ Okay, so yesterday was 2nd Christmas day and my (grand)parents and me had a game of "sjoelen", as it is called in the Netherlands. The inner programmer came up in me, but just when I had the answer, I lost it. I want you to remake it. *The rules:* You have a wooden plank, a *sjoelbak*, with 4 boxes, each with their own number. When a *schijf* (A puck-like object) goes in one of the boxes you get the points above that box. ![A _sjoelbak_ with _schijven_](https://i.stack.imgur.com/wv2rm.jpg) When there is a *schijf* in all 4 of the boxes, you don't get 10 but you get 20 points. *Example:* From left to right: 3 5 4 3 Each box has at least 3 *schijven* (Plural of *schijf*) so that is 20 \* 3 = 60 points. Resulting values: 0 2 1 0 0\*2 + 2\*3 + 1\*4 + 0\*1 = 10 points. Which makes a total of 60+10 = 70 points. *The input:* The amount of *schijven* from left to right, ie "4 5 4 5", [4,5,4,5], "4\n5\n4\n5", whatever you like. *The output:* The amount of points, ie 84, as output, variable, return or on top of the stack, whatever you like. As in each and every code golf, you can not use external scripts and the code with the least bytes wins. PS: As you may have already noticed, I'm Dutch. Feel free to edit possible grammar mistakes. [Answer] # CJam, ~~23 21~~ 20 bytes ``` q~_$0=f+1m>{X):X*+}* ``` I might be able to golf a couple of bytes off this. Input is like ``` [3 5 4 3] ``` Output is the score ``` 70 ``` **How it works** ``` q~ "Read the input and evaluate into an array"; _$0= "Copy the array, sort it and get the minimum number"; "This minimum is the number of common schijven"; f+ "Increment each of the schijven by the common schijven number"; 1m> "Take 1 element from the end of the array and put"; "it in the beginning"; { }* "Reduce the elements of the array based on this block"; X):X "Increment and update the value of X (initially 1)"; * "Multiply the number of schijven with X"; + "Add it to current score"; ``` **Algorithm** * Since I have right shifted the number of schijven, the score order now becomes `[1 2 3 4]`. * Moreover, using the fact that `1 + 2 + 3 + 4 = 10`, I simply add the minimum common schijven to each one to get the effect of bonus `10` score. * Now when I reduce, I get 2 elements initially on stack, the first one, which I ignore is the one with a score of `1` each, then I multiply the second one with `2` and add it to first. In the next iteration, I get the current sum and score `3` schijven. And so on. [Try it online here](http://cjam.aditsu.net/) [Answer] # Piet, 240 (30\*8) codels, 138 containing actual code Codel size 10, for better visibility ![Piet: sjoelen point count](https://i.stack.imgur.com/SkMSc.png) Test examples: ``` D:\codegolf\npiet-1.3a-win32>npiet sjoelen_point_count_cs10.png ? 3 ? 5 ? 4 ? 3 70 D:\codegolf\npiet-1.3a-win32>npiet sjoelen_point_count_cs10.png ? 4 ? 5 ? 4 ? 5 84 ``` Flow display: Using my own shorthand for easier handling and compact display. It shows the general program flow, not the exact locations of the codels. ``` NOP ADD DIV GRT DUP INC END 0 + / > = c ~ PSH SUB MOD PTR ROL OUN X - % # @ N POP MUL NOT SWI INN OUC ? * ! $ n C 1X!nnnn=5X2X@=5X2X@=5X2X@=5X1X@** 0 * 0 @+5X1X@1X-4X1X@ ! 0 - 0 ! 0 X1!X1X6+*==X40000# <--pointer if top of stack=1 (all boxes full, 0 0 2 add 20 points, decrement count for all boxes) 0000-X1@X1X2-X1@X1X3-X1 X | pointer if top of stack=0 (not all boxes full, * V add 2a+3b+4c+d) ~N++++*X4@X2X3*X3@X1X2 ``` Full explanation: ``` (score=0) a b c d 1 PSH NOT INN INN INN INN ..... sort and duplicate the numbers ..... **1** DUP 5 PSH 2 PSH ROL DUP 5 PSH 2 PSH ROL DUP 5 PSH 2 PSH ROL DUP 5 PSH 1 PSH ROL ( a*b*c*d ) (convert to boolean) 1 if all boxes are full, 0 if at least one box is empty MUL MUL MUL NOT NOT change direction if 1 (**2**) go straight ahead if 0 (**3**) PTR ( compress 20=4*4+4 ) (0-1=-1/ neg. roll) score+20 **2** 4 PSH DUP DUP MUL ADD 6 PSH 1 PSH NOT 1 PSH SUB ROL ADD (put score back to bottom of stack) ... a=a-1, b=b-1, c=c-1, d=d-1 ... 5 PSH 1 PSH ROL 1 PSH SUB 4 PSH 1 PSH ROL 1 PSH SUB 3 PSH 1 PSH ROL 1 PSH SUB 2 PSH 1 PSH ROL 1 PSH SUB loop to **1** ( a*2 ) ( b*3 ) ( c*4 ) **3** 2 PSH MUL 2 PSH 1 PSH ROL 3 PSH MUL 3 PSH 2 PSH ROL 4 PSH MUL +2a +3b +d +score ADD ADD ADD ADD output score OUN ``` Save the image and try it out in this online Piet interpreter: [PietDev online Piet interpreter](http://www.rapapaing.com/blog/?page_id=6) [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~16~~ ~~13~~ 12 bytes -3 thanks to @Adám ``` (+/+\)1⌽⌽+⌊/ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v9fQ1tfO0bT8FHPXiDSftTTpf8/7VHbhEe9fY@6mg@tN37UNvFR39TiomQgWZKRWfy/BChb/ah366POhUVAZtqj3l1W6vnZ6o@6W9TTEjNz1IECQOmiWi5jBVMFEwVjhRIFcwMuEzDHFMixMAEA "APL (Dyalog Classic) – Try It Online") `⌽+⌊/` reverse(arg) + min(arg) `1⌽` rotate 1 to the left `+\` partial sums `+/` sum [Answer] # Mathematica, ~~38~~ ~~32~~ ~~23~~ 20 bytes ``` (#+Min@#).{2,3,4,1}& ``` (With help from *swish*) Use by tacking the input on to the end: ``` (#+Min@#).{2,3,4,1}&@{3,5,4,3} 70 ``` Alternate (36 bytes): ``` 20*Min@#+Total[(#-Min@#)*{2,3,4,1}]& ``` [Answer] # R, ~~41~~ 40 chars ``` b=min(a<-scan());sum(5*b+(a-b)*c(2:4,1)) ``` Usage: ``` > b=min(a<-scan());sum(5*b+(a-b)*c(2:4,1)) 1: 4 5 4 5 5: Read 4 items [1] 84 > b=min(a<-scan());sum(5*b+(a-b)*c(2:4,1)) 1: 3 5 4 3 5: Read 4 items [1] 70 ``` In the last example, `a` is vector `3 5 4 3`, `a-b` is `0 2 1 0`, which we multiply with vector `2 3 4 1` thus giving `0 6 4 0` which we add with `5*b` giving `15 21 19 15` (`5*b` being recycled for each member of the added vector, hence effectively adding `4*5*b`), which we finally sum, thus giving `70`. [Answer] # JavaScript (ES6), ~~93~~ 47 bytes ``` s=(a,b,c,d)=>10*Math.min(a,b,c,d)+a*2+b*3+c*4+d ``` Usage: `s(1, 2, 3, 4)` How it works: the function looks for the smallest number in the arguments, and multiplies that by `10` (not with `20`) and adds the rest of the score. It's not necessary to multiply by `20` and substract parts from the score to continue the calculation. Thanks to edc65 for sharing improvements! Un-golfed: ``` function score(a, b, c, d) { return 10 * Math.min(a, b, c, d) + a * 2 + b * 3 + c * 4 + d; } ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 15 ``` sm*hd+@QtdhSQUQ ``` Input should be given comma separated on STDIN, e.g. ``` 3,5,4,3 ``` This uses the same trick that many other solutions have used, of adding the minimum to each element to account for the bonus. The minimum is `hSQ` in the above code. To account for multiplying by 2, 3, 4, and 1, I map d over the list [0,1,2,3], and multiply the (d-l)th element of the input by d+1. Thus, the -1th element is multiplied by 1, the zeroth by 2, the first by 3 and the second by 4. Then I sum. [Answer] # J, ~~23~~ 22 chars ``` (+/ .*&2 3 4 1@(+<./)) ``` Example: ``` test =. 3 5 4 3 (+/ .*&2 3 4 1@(+<./)) test 70 ``` [Try it here.](http://tryj.tk/) (23 long explicit function definition: `v=:3 :'+/+/\.3|.y+<./y'`) [Answer] # [Ostrich v0.1.0](https://github.com/KeyboardFire/ostrich-lang/releases/tag/v0.1.0-alpha), ~~48~~ 41 characters (way too long) ``` .$0={}/:n;{n-}%)\+1:i;{i*i):i;}%{+}*20n*+ ``` This is simply the same as the old version below, except that instead of using `@` to rotate the whole stack, `)\+` (right uncons) is used instead. Old version: ``` .$0={}/:n;{n-}%{}/{4@}3*1:i;]{i*i):i;}%{+}*20n*+ ``` I have actually discovered two bugs in my very newly implemented language, annotated in the description below. (The language is currently very, very similar to Golfscript, so if you know Golfscript it should be fairly easy to read. ``` .$0= get min value (for the *20 thingy) {}/ *actually* get min value (BUG: `array number =' returns a single-element array...) :n; store as n {n-}% subtract this value from all array elements {}/ dump array onto stack {4@}3* rotate stack so that instead of 2 3 4 1, multipliers are 1 2 3 4 (BUG: negative rotations don't work) 1:i; set i (the multiplier) to 1 ]{i* multiply each array element by i i):i; increment i }% (do the previous 2 lines over each array element) {+}* add up all the array elements 20n*+ add 20*n (the min value we got in line 1) ``` Expects input as an array on STDIN, because I'm a doorknob and forgot to implement I/O in v0.1.0. Solving an actual problem in Ostrich is nice, because it shows me exactly how much more stuff I need to add to the language :D [Answer] # Python 2, 43 bytes ``` lambda i:i[1]-i[3]+2*(sum(i)+i[2]+5*min(i)) ``` Inspired by @user2487951's answer. [Answer] # [Jagl](http://github.com/globby/jagl) Alpha 1.2 - 20 bytes Input is in stdin in format `(3 4 5 6)`, output is left on stack: ``` T~dqZ*S1 5r]%{U*}/b+ ``` ~~Waiting for a response from the original poster about the output format. Since input is specified as *"whatever you like"*, I am going to assume that my input can be an array on the top of the stack.~~ Now takes input on stdin. Explanation: ``` T~ Get input from stdin and evaluate dqZ* Duplicate, get minimum, and multiply that by 10 S1 5r] Swap (so array is on top), push range 1-5 exclusive, and rotate %{U*}/ Zip arrays together, and multiply each pair b+P Get the sum of that, add the common minimum, and print ``` [Answer] # Haskell, 40 ``` g l@[a,b,c,d]=2*a+3*b+4*c+d+10*minimum l ``` instead of removing the minimum number from the rest and adding additional `20`s, this adds additional `10` for the minimum number. [Answer] # Matlab, 27 Took me a while to understand that it is single player game. With the help of anonymous function ``` f=@(N)N*[2;3;4;1]+10*min(N) ``` which is invoked with row vector ``` f([3 5 4 3]) == 70 f([7 7 9 7]) == 148 ``` [Answer] # Java, 84 bytes ``` int A(int[]a){int m=9;for(int i:a)m=i<m?i:m;return 10*m+a[3]+2*a[0]+3*a[1]+4*a[2];} ``` I have the idea this can be golfed any further, but this is it for now. Call with `A(new int[]{3,5,4,3})`, output is returned as int (Because `System.out.println()` would double the bytes) Ungolfed ``` int getScore(int[] input){ int min=9; for(int x:input) { if(x<min){ min=x; } } return 10*min + 2*input[0] + 3*input[1] + 4*input[2] + 1*input[3]; } ``` [Answer] # GolfScript, 22 bytes ``` ~3,{1$>~;}%+$(11*+{+}* ``` Reads input from stdin, in the format `[3 5 4 3]`. Writes output to stdout. (If taking the input as an array on the stack is allowed, the leading `~` may be omitted for a total of 21 bytes.) This uses a somewhat different strategy than the CJam / Pyth / etc. solutions: I first build an array with 2 copies of the first input value, 3 of the second, 4 of the third and one of the fourth. Then I sort this array, pull out the smallest element, multiply it by 11 and sum it with the other elements. [Answer] ## Python 2, 51 Uninspired, but short: ``` l=input() print l[0]*2+l[1]*3+l[2]*4+l[3]+10*min(l) ``` More pythonic: ``` l=input() print sum(map(lambda x,y:x*y,l,[2,3,4,1]))+10*min(l) ``` [Answer] # Julia, ~~48~~ 35 characters ~~`function p(m);sum([2 3 4 1].*m)+10minimum(m);end`~~ in compact assignment form: ``` p(m)=sum([2 3 4 1].*m)+10minimum(m) ``` Example: ``` julia> p([3 5 4 3]) 70 ``` [Answer] # Javascript, 97 bytes ``` a=prompt().split(" "),b=Math.min.apply(1,a);alert(20*b+2*(a[0]-b)+3*(a[1]-b)+4*(a[2]-b)+(a[3]-b)) ``` [Answer] # Javascript, ES6, 57 ``` f=(a,b,c,d)=>a*b*c*d?20+f(--a,--b,--c,--d):a*2+b*3+c*4+d ``` I wanted to see how recursion would turn out, and while it is definitely not the shortest answer, I felt like it turned out well. **`a*b*c*d`**: It takes the input values and finds the product of all of them, and evaluate that as a Boolean expression for an inline if statement. This will return false if one or more of the values is 0, and true for any other value. **`20+f(--a,--b,--c,--d)`**: If it returns true, the function returns 20 (for the *schijven* set) plus the recursive call of the function for all of the values minus one (To remove that *schijven* set). In this way it will recursively loop through until at least one of the boxes is empty. **`a*2+b*3+c*4+d`** After at least one box it empty, the else part of the inline if statement will run. It just returns the points for the remaining *schijven* in the boxes. Thus at the end all of the 20 point *schijven* sets, and the remanding points are summed up and returned from the function, producing the answer. [Answer] # Haskell 42 chars ``` f l=10*minimum l+sum(zipWith(*)[2,3,4,1]l) ``` [Answer] # HPPPL (HP Prime Programming Language), ~~58~~ 57 bytes The \* between 10 and min isn’t necessary, so I removed it. ``` EXPORT s(m) BEGIN return sum([2,3,4,1].*m)+10min(m); END; ``` HPPPL is the programming language for the HP Prime color graphing calculator/CAS. Example runs: [![HPPPL screen capture of sjoelen point count program](https://i.stack.imgur.com/C8N8V.png)](https://i.stack.imgur.com/C8N8V.png) If it doesn’t have to be a program, then it’s realizable in a ~~40~~ 39 bytes one-liner: ``` m:=[3,5,4,3];sum([2,3,4,1].*m)+10min(m) ``` [Answer] # Staq, 72 characters ``` 't't't't{aii*XX}$&iia$&ia$&a+XX+XX+|{mxx}{lxX}{k>?m!l}kkk&iiqi&ii*s*t|+: ``` Example run: ``` Executing D:\codegolf\Staq\sjoelen codegolf.txt 3 5 4 3 70 Execution complete. > ``` Staq has two stacks, one active, one passive. The `|` command switches the active stack to passive and vice versa. Everything between curly braces defines a function, the first letter after the opening brace is the function name, the rest until the closing brace is the function itself. Overriding functions, recursion and nested functions are possible. `{aii}` would define a function *a* that would increment the top of the stack twice. Every following instance of `a` in the code will be replaced by `ii`. Comments inside *Staq* prorams: `&` adds a zero on top of the stack, `[` instructs the pointer to jump to the corresponding `]` if the top of the stack is zero, `x` deletes the topmost value on the stack. So, comments can be written into the code in the form of `&[here is a comment]x` Explanation (also executable): ``` ' &[input number]x t &[copy top of active stack to passive stack]x t't't &[input next three numbers and copy them to the passive stack]x {aii*XX} &[define function a (increment twice, multiply the two topmost values, then delete the second value on the stack twice)]x $ &[move top value to the bottom of the stack]x &ii &[put zero on top of the stack, incremment twice]x a &[function a]x $&ia$&a + &[put sum of the two topmost values on top of the stack]x XX &[delete second stack value, twice]x +XX+ | &[switch active/passive stack]x {mxx} &[define function m: delete two topmost stack values]x {lxX} &[define function l: delete topmost stack value, then delete second value of remaining stack]x {k>?m!l} &[define function k: boolean top > second value? put result on top of the stack, if top>0 then execute m, if top = 0 then execute l]x kkk&ii q &[put square of top value on top of the stack]x i&ii * &[multiply two topmost values and put result on top of the stack]x s &[move bottom stack value to the top]x *t|+ : &[output result]x ``` <https://esolangs.org/wiki/Staq> The program uses one stack (initially active) to calculate 2a+3b+4c+d, and the second stack (initially passive) to calculate 10 times the minimum of the input values. Then both results are summed up and displayed. [Answer] # [PowerShell for Windows](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~48~~ 47 bytes -1 byte thanks to mazzy ``` $args|%{$a+=++$i%4*$_+$_} $a+10*($args|sort)[0] ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V8lsSi9uEa1WiVR21ZbWyVT1URLJV5bJb6WCyhiaKClAVFQnF9UohltEPu/lotLTSVNwQACwWxDJLYBhAdXY4jEBvLAbBMFYwUjFLYRmG2sYAri/wcA "PowerShell – Try It Online") ]
[Question] [ Most languages come with a built-in to search a string for all occurrences of a given substring and replace those with another. I don't know of any language that generalises this concept to (not necessarily contiguous) subsequences. So that's your task in this challenge. The input will consist of three strings `A`, `B` and `C`, where `B` and `C` are guaranteed to be of the same length. If `B` appears as a subsequence in `A` it should be replaced with `C`. Here is a simple example: ``` A: abcdefghijklmnopqrstuvwxyz B: ghost C: 12345 ``` It would be processed like this: ``` abcdefghijklmnopqrstuvwxyz || | || abcdef12ijklmn3pqr45uvwxyz ``` If there are several ways to find `B` as a subsequence, you should greedily replace the left-most one: ``` A: abcdeedcba B: ada C: BOB Result: BbcOeedcbB and NOT: BbcdeeOcbB ``` The same applies if `B` could be found in multiple disjoint places: ``` A: abcdeedcbaabcde B: ed C: 12 Result: abcd1e2cbaabcde and NOT: abcd112cbaabc2e (or similar) ``` When `B` does not appear in `A`, you should output `A` unchanged. ## Rules As stated above, take three strings `A`, `B` and `C` as input and replace the left-most occurrence of `B` as a subsequence in `A` with `C`, if there is any. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. You may take the three strings in any consistent order which you should specify in your answer. You may assume that `B` and `C` have the same length. All strings will only contain alphanumeric characters. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ## Test Cases Each test case is four lines: `A`, `B`, `C` followed by the result. ``` abcdefghijklmnopqrstuvwxyz ghost 12345 abcdef12ijklmn3pqr45uvwxyz abcdeedcba ada BOB BbcOeedcbB abcdeedcbaabcde ed 12 abcd1e2cbaabcde 121 121 aBc aBc abcde acb 123 abcde ABC ABCD 1234 ABC 012345678901234567890123456789 42 TT 0123T5678901T34567890123456789 edcbaedcbaedcbaedcba abcde 12345 edcbaedcbaedcbaedcba edcbaedcbaedcbaedcbaedcba abcde 12345 edcb1edc2aed3bae4cba5dcba daccdedca ace cra dcrcdadca aacbcbabcccaabcbabcaabbbbca abaaaccbac 1223334444 aacbcbabcccaabcbabcaabbbbca aacbcbabcccaabcbabcaabbbbcac abaaaccbac 1223334444 1ac2cb2bccc33b3bab4aa4bbbc44 ``` ## Leaderboard The Stack Snippet at the bottom of this post generates leaderboards from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` /* Configuration */ var QUESTION_ID = 77719; // Obtain this from the url // It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 8478; // 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 "http://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 "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1; if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) 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="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] ## Python 2, 88 bytes ``` def f(a,b,c,o=""): for q in a:x=q==b[:1];o+=c[:x]or q;b=b[x:];c=c[x:] print[o,a][c>''] ``` A function that takes in the three strings and outputs the result to STDOUT. The function simply does one pass over the string, taking the appropriate char and updating `b,c` as we go. For testing (after replacing the `print` with `return`): ``` S = """ <test cases here> """ for T in S.split("\n\n"): A,B,C,D = T.split() assert f(A,B,C) == D ``` [Answer] ## Java 7, 141 I think there's some more I can do with this, but I've gotta run for now. It's just a simple iterate/replace, keeping an index in A and B. ``` char[]h(char[]a,char[]b,char[]c){char[]d=a.clone();int i=0,j=0,k=b.length;for(;i<a.length&j<k;i++)if(a[i]==b[j])d[i]=c[j++];return j==k?d:a;} ``` Whitespaced for your pleasure: ``` char[]h(char[]a,char[]b,char[]c){ char[]d=a.clone(); int i=0,j=0,k=b.length; for(;i<a.length&j<k;i++) if(a[i]==b[j])d[i]=c[j++]; return j==k?d:a; } ``` [Answer] ## Lua, 121 Bytes Straightforward solution, `gsub` allows us to iterate exactly once on each character and to replace them in a new instance of the string. It takes input via 3 command-line argument and output a string to STDOUT. ``` a,b,c=...d=a:gsub(".",function(s)if b:find(s)then b=b:sub(2)x=c:sub(1,1)c=c:sub(2)return x end end)print(b~=''and a or d) ``` ### Ungolfed ``` a,b,c=... -- unpack the arguments into a, b and c d=a:gsub(".",function(s)-- iterate over each character of the first argument if b:find(s)then -- if the current character is in the set b b=b:sub(2) -- remove it from b x=c:sub(1,1) -- save the replacement character in x c=c:sub(2) -- remove it from c return x -- replace the current character with x end end) print(b~='' -- if b is empty, we replaced all the character and a or d) -- so output the result of gsub, else, output the first argument ``` [Answer] # Python 3, 127 bytes. Saved 16 bytes thanks to Katenkyo. Still working on this a bit, man was this nastier than I thought it would be. ``` f=lambda a,b,c:a.replace(b[0],c[0],1)[:a.index(b[0])+1]+f(a[a.index(b[0])+1:],b[1:],c[1:])if b and all(x in a for x in b)else a ``` Explanation: Awww yeah, recursion. Test cases: ``` assert f('abcdeedcba', 'ada', 'BOB') == 'BbcOeedcbB' assert f('abcdeedcbaabcde', 'ed', '12') == 'abcd1e2cbaabcde' assert f('012345678901234567890123456789', '42', 'TT') == '0123T5678901T34567890123456789' assert f('ABC', 'ABCD', '1234') == 'ABC' ``` [Answer] # Python 3.5, 87 bytes ``` import re lambda s,p,r:re.sub('(.*?)'.join(p),'\g<%d>'.join(r)%(*range(1,len(r)),),s,1) ``` [repl.it to verify all test cases](https://repl.it/CF26/0). ### How it works * `'(.*?)'.join(p)` builds a search pattern that matches the subsequence to be replaced and anything between its elements. Since the quantifiers are lazy, each `(.*?)` will match as few characters as possible. For the pattern `ghost`, the constructed regex is `g(.*?)h(.*?)o(.*?)s(.*?)t`. * `'\g<%d>'.join(r)%(*range(1,len(r)),)` builds the replacement string, using string formatting. Each `\g<n>` refers to the **n**th captured group, just like `\n` would. For the replacement `12345`, the constructed string is `1\g<1>2\g<2>3\g<3>4\g<4>5`. * `re.sub(...,...,s,1)` performs at most one replacement in the string `s`. [Answer] # Pyth, 27 ``` .xuXG.*HC,hSI#.nM*FxRcQ1zwQ ``` [Test Suite](http://pyth.herokuapp.com/?code=.xuXG.%2AHC%2ChSI%23.nM%2AFxRcQ1zwQ&input=%27abcdeedcbaabcde%27%0Aed%0A12&test_suite=1&test_suite_input=%27abcdefghijklmnopqrstuvwxyz%27%0Aghost%0A12345%0A%27abcdeedcba%27%0Aada%0ABOB%0A%27abcdeedcbaabcde%27%0Aed%0A12%0A%27121%27%0A121%0AaBc%0A%27abcde%27%0Aacb%0A123%0A%27ABC%27%0AABCD%0A1234%0A%27012345678901234567890123456789%27%0A42%0ATT%0A%27edcbaedcbaedcbaedcba%27%0Aabcde%0A12345%0A%27edcbaedcbaedcbaedcbaedcba%27%0Aabcde%0A12345%0A%27daccdedca%27%0Aace%0Acra&debug=0&input_size=3) The test suite omits the last two cases because they will run out of memory. The algorithm used here is to find all of the indices of each character in the second string in the first string, then find all possible orderings of those indices and take only the ones that are in sorted order. Then use the first one of these in sorted order as the list of indices in the first string to update with values from the third string. I feel like there should be something shorter than `.nM*F`... [Answer] # [MATL](https://github.com/lmendo/MATL), 33 bytes ``` y!=[]0b"@n:!<@*fX<h5Mt?}.]]?iw(}x ``` [**Try it online!**](http://matl.tryitonline.net/#code=eSE9W10wYiJAbjohPEAqZlg8aDVNdD99Ll1dP2l3KH14&input=J2FhY2JjYmFiY2NjYWFiY2JhYmNhYWJiYmJjYWMnCidhYmFhYWNjYmFjJwonMTIyMzMzNDQ0NCc) ### Explanation ``` y! % Implicitly input first two strings. Duplicate the first and transpose = % Compare the two strings element-wise. Gives a 2D array with all combinations [] % Push empty array. Indices of matching elements will be appended to this 0 % Push a 0. This is the index of last character used up in first string b % Bubble up (rearrange elements in stack) to move 2D array to top " % For each column of that array (each char of the second string) @ % Push current column n:! % Transform into column array of consecutive values starting from 1 < % Compare with index of last character used up of first string @* % Push current column again. Multiply element-wise (logical AND) fX< % Find index of first matching character, or empty if there's none h % Append to array containing indices of matching elements 5Mt % Push index of matching character again. Duplicate ?} % If it's empty . % Break loop ] % End if ] % End for % The top of the stack now contains a copy of the index of last matching % character, or an empty array if there was no match ? % If non-empty: all characters were matched i % Input third string w % Swap top two elements in stack ( % Assign the characters of the third string to first string at found indices } % Else: the original string needs to be output x % Delete (partial) array of matching indices. Leave original string in stack % End if % Implicitly display (either modified string or original string) ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~23~~ ~~22~~ 21 bytes ``` ='T€ŒpfṢ€$ḢṬœp³ż⁵$³Ḋ? ``` [Try it online!](http://jelly.tryitonline.net/#code=PSdU4oKsxZJwZuG5ouKCrCThuKLhuazFk3DCs8W84oG1JMKz4biKPw&input=&args=J2VkY2JhZWRjYmFlZGNiYWVkY2JhZWRjYmEn+J2FiY2RlJw+JzEyMzQ1Jw) Note that the last two test cases will run out of memory. ### Verification ``` $ head -n 5 test-cases abcdefghijklmnopqrstuvwxyz ghost 12345 abcdef12ijklmn3pqr45uvwxyz $ cat subseq-short while read s; do read p; read r; read o; echo $o; read timeout 1s jelly eun $1 "='T€ŒpfṢ€$ḢṬœp³ż⁵$³Ḋ?" "'$s'" "'$p'" "'$r'" (($?)) && echo '(killed)' done < test-cases $ ./subseq-short abcdef12ijklmn3pqr45uvwxyz abcdef12ijklmn3pqr45uvwxyz BbcOeedcbB BbcOeedcbB abcd1e2cbaabcde abcd1e2cbaabcde aBc aBc abcde abcde ABC ABC 0123T5678901T34567890123456789 0123T5678901T34567890123456789 edcbaedcbaedcbaedcba edcbaedcbaedcbaedcba edcb1edc2aed3bae4cba5dcba edcb1edc2aed3bae4cba5dcba dcrcdadca dcrcdadca aacbcbabcccaabcbabcaabbbbca (killed) 1ac2cb2bccc33b3bab4aa4bbbc44 (killed) ``` ### How it works ``` ='T€ŒpfṢ€$ḢṬœp³ż⁵$³Ḋ? Main link. Arguments: string s, pattern p, replacement r =' Compare each character of s with each character of p. This yields a 2D list. Each row corresponds to a char in p. T€ Compute the truthy indices of each row, i.e., the indices of all occurrences of that char in s. Œp Compute the Cartesian product of the lists of indices. $ Combine the two links to the left into a monadic chain: Ṣ€ Sort each list of indices. f Filter, removing all non-sorted lists of indices. Ḣ Head; take the first (sorted) list of indices. Ṭ Truth; generate a list with 1's at those indices. œp³ Partition; split s at all 1's, removing those characters. Ḋ? If the partition has more than more than one element: ż⁵$ Zip the partition with r. ³ Else, return s. ``` [Answer] # JavaScript (ES6), 84 bytes ``` (a,b,c)=>[...b].every((q,i)=>r[p=a.indexOf(q,p)]=~p++&&c[i],p=0,r=[...a])?r.join``:a ``` ## Explanation / Test ``` var solution = (a,b,c)=> [...b].every((q,i)=> r[p=a.indexOf(q,p)]=~p++&&c[i], p=0, r=[...a] )?r.join`` :a // Test var testCases = `abcdefghijklmnopqrstuvwxyz ghost 12345 abcdef12ijklmn3pqr45uvwxyz abcdeedcba ada BOB BbcOeedcbB abcdeedcbaabcde ed 12 abcd1e2cbaabcde 121 121 aBc aBc abcde acb 123 abcde ABC ABCD 1234 ABC 012345678901234567890123456789 42 TT 0123T5678901T34567890123456789 edcbaedcbaedcbaedcba abcde 12345 edcbaedcbaedcbaedcba edcbaedcbaedcbaedcbaedcba abcde 12345 edcb1edc2aed3bae4cba5dcba daccdedca ace cra dcrcdadca aacbcbabcccaabcbabcaabbbbca abaaaccbac 1223334444 aacbcbabcccaabcbabcaabbbbca aacbcbabcccaabcbabcaabbbbcac abaaaccbac 1223334444 1ac2cb2bccc33b3bab4aa4bbbc44` .split`\n\n`.map(c=>c.split`\n`); document.write("<pre>"+testCases.map(c=>(r=solution(c[0],c[1],c[2]))+" : "+(r==c[3]?"PASS":"FAIL")).join`\n`); ``` [Answer] ## JavaScript (ES6), ~~84~~ 76 bytes ``` (a,b,c)=>a.replace(RegExp([...b].join`(.*?)`),c.replace(/\B/g,(_,i)=>'$'+i)) ``` Because I was sure that this was a job for RegExp. Edit: Saved 8 bytes thanks to @MartinBüttner♦. A port of @KevinLau's Ruby answer took 82 bytes: ``` ([...a],[...b],[...c])=>(d=a.map(e=>e==b[0]?c.shift(b.shift()):e),b[0]?a:d).join`` ``` I also tried a recursive RegExp solution but that took 90 bytes: ``` f=(a,[b,...d],[c,...e])=>b?a.replace(RegExp(b+'(.*'+d.join`.*`+'.*)'),(_,s)=>c+f(s,d,e)):a ``` [Answer] ## Julia, ~~89~~ 70 bytes ``` f(s,a,b,i=0)=(o=join(["$a "[i+1]!=c?c:b[i+=1]for c=s]);i<endof(a)?s:o) ``` Uses an index `i` to iterate through the pattern/replacement strings as we go. -19 bytes thanks to @Dennis! [Answer] # C, 98 bytes ``` char*f(i,o,s,r)char*i,*o,*s,*r;{char*I=i,*O=o;for(;*i;++i,++o)*o=*i==*s?++s,*r++:*i;return*s?I:O;} ``` # /\* Expanded code \*/ ``` char *f(i, o, s, r) char *i, *o, *s, *r; { char *I=i, *O=o; for (; *i; ++i,++o) *o = (*i==*s) ? (++s,*r++) : *i; return *s ? I : O; } ``` Arguments are: **i**nput string, **o**utput buffer, **s**earch string, **r**eplacement. After remembering the start of input and output, we walk the input, replacing and advancing the substitution whenever we hit one. At the end, if we've run out of substitutions, return the output buffer, else the unmodified input. ## /\* Tests \*/ ``` struct T { const char *input; const char *search; const char *replace; const char *expected; }; #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int i; static const struct T test[] = { { "abcdefghijklmnopqrstuvwxyz", "ghost", "12345", "abcdef12ijklmn3pqr45uvwxyz"}, { "abcdeedcba", "ada", "BOB", "BbcOeedcbB"}, { "abcdeedcbaabcde", "ed", "12", "abcd1e2cbaabcde"}, { "121", "121", "aBc", "aBc"}, { "abcde", "acb", "123", "abcde"}, { "ABC", "ABCD", "1234", "ABC"}, { "012345678901234567890123456789", "42", "TT", "0123T5678901T34567890123456789"}, { "edcbaedcbaedcbaedcba", "abcde", "12345", "edcbaedcbaedcbaedcba"}, { "edcbaedcbaedcbaedcbaedcba", "abcde", "12345", "edcb1edc2aed3bae4cba5dcba"}, { "daccdedca", "ace", "cra", "dcrcdadca"}, { "aacbcbabcccaabcbabcaabbbbca", "abaaaccbac", "1223334444", "aacbcbabcccaabcbabcaabbbbca"}, { "aacbcbabcccaabcbabcaabbbbcac", "abaaaccbac", "1223334444", "1ac2cb2bccc33b3bab4aa4bbbc44" } }; for (i = 0; i < (sizeof test) / (sizeof test[0]); ++i) { const struct T *t = test+i; char *out = malloc(strlen(t->input)+1); char *result = f(t->input, out, t->search, t->replace); if (strcmp(t->expected, result)) printf("Failed test %d; result = \"%s\"\n", i, result); } return EXIT_SUCCESS; } ``` [Answer] # R, 76 bytes ``` function(a,b,c){s=substr;for(x in 1:nchar(b)){a=sub(s(b,x,x),s(c,x,x),a)};a} ``` uses `sub` to replace first match Ungolfed ``` function(a,b,c){ # function with 3 arguments as per description s=substr; # alias for substr (saves 1 byte) for(x in 1:nchar(b)){ # index 1 to number character in b a=sub(s(b,x,x),s(c,x,x),a)}; # replace first instance of b[x] in a # with c[x] and reassign to a a} # return a ``` [Answer] ## C++, 204 bytes ### Golfed ``` #include<iostream> #include<string> int main(){std::string a, b, c;std::cin>>a>>b>>c;int t=0;for(int x=0;x<b.length();x++){t=a.find(b[x],t);if(t!=-1){a.replace(t,1,c.substr(x,1));}}std::cout<<a;return 0;} ``` ### Ungolfed ``` #include<iostream> #include<string> int main() { std::string a, b, c; std::cin>>a>>b>>c; int t = 0; for (int x=0;x<b.length();x++) { t = a.find(b[x], t); if (t != -1) { a.replace(t,1,c.substr(x, 1)); } } std::cout<<a; return 0; } ``` [Answer] ## [Retina](https://github.com/mbuettner/retina), 63 bytes ``` .+$ $&¶;$& +`^(.)(.*¶)(.)([^;]+);(.*?)\1 $2$4$5$3; A1` ; G2=`. ``` Input is taken in order `B`, `C`, `A`, separated by linefeeds. [Try it online.](http://retina.tryitonline.net/#code=LiskCiQmwrY7JCYKK2BeKC4pKC4qwrYpKC4pKFteO10rKTsoLio_KVwxCiQyJDQkNSQzOwpBMWAKOwoKRzI9YC4&input=YWJhYWFjY2JhYwoxMjIzMzM0NDQ0CmFhY2JjYmFiY2NjYWFiY2JhYmNhYWJiYmJjYWM) [Answer] # Haskell, 87 bytes ``` x@((a,b):c)#(d:e)|a==d,([],z)<-c#e=([],b:z)|0<1=(d:)<$>x#e x#y=(x,y) a!b=snd.(zip a b#) ``` I noticed the lack of a Haskell answer, and decided to fix that. This defines a ternary function `!` with argument order pattern-replacement-string. [Try it here.](http://rextester.com/WAP55923) ## Explanation The auxiliary function `#` takes a list `x` of character pairs (pattern and replacement) and a string `y`. If the "pattern" characters in `x` form a subsequence of `y`, it returns the empty list and `y` with each pattern character replaced by its counterpart. Otherwise, it returns the pair `(x,y)`. The function `!` zips the pattern and replacement strings into `x`, applies `#` to `x` and the third string, and returns the second component of the result. ``` x@((a,b):c)#(d:e) -- First case of #: both arguments nonempty. |a==d, -- If the pattern char matches the string's head, ([],z)<-c#e -- and the pattern's tail is a subsequence of the string's tail, =([],b:z) -- tack the replacement char to the recursion result. |0<1 -- Otherwise, =(d:)<$>x#e -- recurse with the same pairs and tack string's head to result. x#y=(x,y) -- If either argument is empty, just pair them. ``` If the pattern is a subsequence of the string, the code runs in **O(n)** time, making one recursive pass through the string and greedily constructing the replacement in the process. However, if the pattern is not a subsequence, it runs in **O(2n)** time in the worst case. This is because at every position where the pattern and string have a matching character, the function calls itself to check whether the pattern is actually a subsequence, finds out it's not, and calls itself a second time to actually compute the result. [Answer] ## JavaScript (ES6), ~~100~~ 95 bytes ``` (a,b,c)=>1?(t=[...a].map(e=>b[0]==e?(u=c[0],b=b.slice(1),c=c.slice(1),u):e).join``,b==""?t:a):a ``` This is a valid JavaScript Lambda function. Outputs as function `return`. Takes in three arguments (`a,b,c`). Add `f=` at the beginning and invoke like `f(arg1,arg2,arg3)`. ``` f=(a,b,c)=>1?(t=[...a].map(e=>b[0]==e?(u=c[0],b=b.slice(1),c=c.slice(1),u):e).join``,b==""?t:a):a console.log(f(prompt("Value for A"),prompt("Value for B"),prompt("Value for C"))) ``` [Answer] # C (gcc), ~~67~~ ~~62~~ ~~61~~ 59 bytes ``` f(s,a,b)char*s,*a,*b;{*s==*a?*s=*b++,a++:1;*a&&f(s+1,a,b);} ``` [Try it online!](https://tio.run/nexus/c-gcc#VY45DsIwEEX7nAK5QMGeJiwNVoTEBTgAohgvJCxJANtsUc4ebKMgUc3T139f0@9TAwhiIku8UQMUgQreUpPnFFf@UMEYIGPLjFMcj32dZVHgXV/hoU4nbRLckdnucoJCKr0vysPxdK7q5nK9Gevuj@frTQBDoSgbYwmIwNl0Nl8Qngwv8OTirEmNh@@k/U1qJQUSkDFQnlSg9WYddQsS1KDbn@7@9UgEdEi1IlB8f4gLDjQUw4Lz0PUf "C (gcc) – TIO Nexus") [Answer] # Octave, 97 bytes ``` function A=U(A,B,C)t=0;for s=B if p=find(A(t+1:end)==s,1) D(t=p+t)=~0;else return;end;end;A(D)=C; ``` Iterate over the subsequence to replace; find first occurrence of first character, find next character in remaining string, repeat. The one interesting bit of this is: ``` D(t=p+t)=~0 D( ) %// D is a logical mask of characters to replace in the input string t=p+t %// t is the current end of D %// p is the location of the character to replace %// update t and use as index to grow D =~0 %// make it so, number 1 ``` Since ideone is still not accepting functions with names other than '', I'll just leave a sample run here. Inputs are only shown for the first few test cases for brevity. `key` is the expected output, `ans` is the function output. ``` A = abcdefghijklmnopqrstuvwxyz B = ghost C = 12345 key = abcdef12ijklmn3pqr45uvwxyz ans = abcdef12ijklmn3pqr45uvwxyz A = abcdeedcba B = ada C = BOB key = BbcOeedcbB ans = BbcOeedcbB A = abcdeedcbaabcde B = ed C = 12 key = abcd1e2cbaabcde ans = abcd1e2cbaabcde key = aBc ans = aBc key = abcde ans = abcde key = ABC ans = ABC key = 0123T5678901T34567890123456789 ans = 0123T5678901T34567890123456789 key = edcbaedcbaedcbaedcba ans = edcbaedcbaedcbaedcba key = edcb1edc2aed3bae4cba5dcba ans = edcb1edc2aed3bae4cba5dcba key = dcrcdadca ans = dcrcdadca key = aacbcbabcccaabcbabcaabbbbca ans = aacbcbabcccaabcbabcaabbbbca key = 1ac2cb2bccc33b3bab4aa4bbbc44 ans = 1ac2cb2bccc33b3bab4aa4bbbc44 ``` [Answer] # Python 3, 123 Bytes A different approach I wanted to share, which is a few bytes shorter. There are no rules against standard library/regex, right? ``` import re j=''.join m='(.*?)' def f(A,B,C): *r,l=(re.findall(m+m.join(B)+'(.*)',A)or[[A]])[0] print(j(map(j,zip(r,C)))+l) ``` PS. This is my first golf. Let me know of any issues/improvements. [Answer] # Pyth, 22 bytes ``` |eJ:Ej"(.*?)"+E\$3s.iJ ``` Verify all test cases in the [Pyth Compiler](https://pyth.herokuapp.com/?code=%7CeJ%3AEj%22%28.%2a%3F%29%22%2BE%5C%243s.iJ&test_suite=1&test_suite_input=%2212345%22%0A%22abcdefghijklmnopqrstuvwxyz%22%0A%22ghost%22%0A%22BOB%22%0A%22abcdeedcba%22%0A%22ada%22%0A%2212%22%0A%22abcdeedcbaabcde%22%0A%22ed%22%0A%22aBc%22%0A%22121%22%0A%22121%22%0A%22123%22%0A%22abcde%22%0A%22acb%22%0A%221234%22%0A%22ABC%22%0A%22ABCD%22%0A%22TT%22%0A%22012345678901234567890123456789%22%0A%2242%22%0A%2212345%22%0A%22edcbaedcbaedcbaedcba%22%0A%22abcde%22%0A%2212345%22%0A%22edcbaedcbaedcbaedcbaedcba%22%0A%22abcde%22%0A%22cra%22%0A%22daccdedca%22%0A%22ace%22%0A%221223334444%22%0A%22aacbcbabcccaabcbabcaabbbbca%22%0A%22abaaaccbac%22%0A%221223334444%22%0A%22aacbcbabcccaabcbabcaabbbbcac%22%0A%22abaaaccbac%22&debug=0&input_size=3). ### Background We build a regex from the pattern by appending a `$` and placing `(.*?)` between all characters. This regex will match the subsequence to be replaced and anything between its elements, and anything up to the end of the string. Since the quantifiers are lazy, each `(.*?)` will match as few characters as possible. For the pattern ghost, the constructed regex is `g(.*?)h(.*?)o(.*?)s(.*?)t(.*?)$`. If the pattern matches the input, the builtin `r<str><regex>3` will return an array containing the prematch (everything before the subsequence), all captured groups (everything in between and after the subsequence), and the postmatch (the empty string). If the pattern does not match, the builtin will return a singleton array containing the original input. ### How it works ``` |eJ:Ej"(.*?)"+E\$3s.iJQ (implicit) Store the first line of input in Q. +E\$ Read the third line of input (pattern) and append '$'. j"(.*?)" Join the result, separating by "(.*?)". E Read the third line of input (string). : 3 Match the string against the regex, as detailed above. J Save the returned array in J. e Extract the last element of J. This is an empty string for a successful match or the original string. | Logical OR; replace an empty string with the following: .iJQ Interleave J and the replacement. s Flatten the resulting array of strings. ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ṭœpż⁵ 0ẋai1 ⁴='-;ç\ñ⁴P? ``` This is two bytes longer than [my other Jelly answer](http://jelly.tryitonline.net/#code=PSdU4oKsxZJwZuG5ouKCrCThuKLhuazFk3DCs8W84oG1JMKz4biKPw&input=&args=J2VkY2JhZWRjYmFlZGNiYWVkY2JhZWRjYmEn+J2FiY2RlJw+JzEyMzQ1Jw), but it finishes instantly. [Try it online!](http://jelly.tryitonline.net/#code=4bmsxZNwxbzigbUKMOG6i2FpMQrigbQ9Jy07w6dcw7HigbRQPw&input=&args=J2FiYWFhY2NiYWMn+J2FhY2JjYmFiY2NjYWFiY2JhYmNhYWJiYmJjYWMn+JzEyMjMzMzQ0NDQn) ### Verification ``` $ head -n 5 test-cases abcdefghijklmnopqrstuvwxyz ghost 12345 abcdef12ijklmn3pqr45uvwxyz $ cat subseq-fast while read s; do read p; read r; read o; echo $o; read timeout 10s jelly eun $1 "Ṭœpż⁵¶0ẋai1¶⁴='-;ç\ñ⁴P?" "'$p'" "'$s'" "'$r'" (($?)) && echo '(killed)' done < test-cases $ ./subseq-fast abcdef12ijklmn3pqr45uvwxyz abcdef12ijklmn3pqr45uvwxyz BbcOeedcbB BbcOeedcbB abcd1e2cbaabcde abcd1e2cbaabcde aBc aBc abcde abcde ABC ABC 0123T5678901T34567890123456789 0123T5678901T34567890123456789 edcbaedcbaedcbaedcba edcbaedcbaedcbaedcba edcb1edc2aed3bae4cba5dcba edcb1edc2aed3bae4cba5dcba dcrcdadca dcrcdadca aacbcbabcccaabcbabcaabbbbca aacbcbabcccaabcbabcaabbbbca 1ac2cb2bccc33b3bab4aa4bbbc44 1ac2cb2bccc33b3bab4aa4bbbc44 ``` ### How it works ``` ⁴='-;ç\ñ⁴P? Main link. Arguments: pattern p, string s, replacement r ⁴=' Compare each character of s with each character of p. This yields a 2D list. Each row corresponds to a char in p. -; Prepend -1 to the 2D list, yielding a ragged array. ç\ Cumulatively reduce the array by the second helper link. P? If the product of the resulting list is non-zero: ñ Call the first helper link with the list and s as arguments. ⁴ Else, return s. Ṭœpż⁵ First helper link. Arguments: L (list of indices), r (replacement) Ṭ Truth; generate a list with 1's at those indices. œp Partition; split s at all 1's, removing those characters. ż⁵ Zip the partition with r. 0ẋai1 Second helper link. Arguments: n (integer), B (list of Booleans) 0ẋ Generate a list of n zeroes. a Perform logical AND with B. This zeroes out the with n elements of B. i1 Compute the first index of 1. ``` [Answer] # CJam, 29 bytes ``` l_ll.{2$#_3$<@+\)@>}s_2$,>@@? ``` [Try it online!](http://cjam.tryitonline.net/#code=bF9sbC57MiQjXzMkPEArXClAPn1zXzIkLD5AQD8&input=YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoKMTIzNDUKZ2hvc3Q) or [verify all test cases](http://cjam.tryitonline.net/#code=ewogICAgbF9sbC57MiQjXzMkPEArXClAPn1zXzIkLD5AQD8KCiAgICBObE5sIQp9Zw&input=YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoKMTIzNDUKZ2hvc3QKYWJjZGVmMTJpamtsbW4zcHFyNDV1dnd4eXoKCmFiY2RlZWRjYmEKQk9CCmFkYQpCYmNPZWVkY2JCCgphYmNkZWVkY2JhYWJjZGUKMTIKZWQKYWJjZDFlMmNiYWFiY2RlCgoxMjEKYUJjCjEyMQphQmMKCmFiY2RlCjEyMwphY2IKYWJjZGUKCkFCQwoxMjM0CkFCQ0QKQUJDCgowMTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkKVFQKNDIKMDEyM1Q1Njc4OTAxVDM0NTY3ODkwMTIzNDU2Nzg5CgplZGNiYWVkY2JhZWRjYmFlZGNiYQoxMjM0NQphYmNkZQplZGNiYWVkY2JhZWRjYmFlZGNiYQoKZWRjYmFlZGNiYWVkY2JhZWRjYmFlZGNiYQoxMjM0NQphYmNkZQplZGNiMWVkYzJhZWQzYmFlNGNiYTVkY2JhCgpkYWNjZGVkY2EKY3JhCmFjZQpkY3JjZGFkY2EKCmFhY2JjYmFiY2NjYWFiY2JhYmNhYWJiYmJjYQoxMjIzMzM0NDQ0CmFiYWFhY2NiYWMKYWFjYmNiYWJjY2NhYWJjYmFiY2FhYmJiYmNhCgphYWNiY2JhYmNjY2FhYmNiYWJjYWFiYmJiY2FjCjEyMjMzMzQ0NDQKYWJhYWFjY2JhYwoxYWMyY2IyYmNjYzMzYjNiYWI0YWE0YmJiYzQ0). [Answer] # Java 7, 102 bytes ``` void L(char[]s,char[]l,char[]r){for(int x=0,y=0;x<s.length&&y<l.length;x++)if(s[x]==l[y])s[x]=r[y++];} ``` **Detailed** [*try here*](http://ideone.com/rOGcgA) ``` // String, Lookup, Replacement void L(char[]s, char[]l, char[]r) { for(int x=0, y=0; x < s.length && y < l.length; x++) if(s[x] == l[y]) s[x] = r[y++]; } ``` [Answer] # Julia, ~~93~~ ~~90~~ 86 bytes ``` f(s,p,r)=(try s=join([match(Regex(join("^$p\$","(.*?)")),s).captures';[r...""]])end;s) ``` Having to test separately if the match was successful kinda destroys the score. A substitution would require casting to `Base.SubstitutionString`, which probably isn't worth it... ### Test run ``` julia> f(s,p,r)=(try s=join([match(Regex(join("^$p\$","(.*?)")),s).captures';[r...""]])end;s) f (generic function with 1 method) julia> f("aacbcbabcccaabcbabcaabbbbca","abaaaccbac","1223334444") "aacbcbabcccaabcbabcaabbbbca" julia> f("aacbcbabcccaabcbabcaabbbbcac","abaaaccbac","1223334444") "1ac2cb2bccc33b3bab4aa4bbbc44" ``` [Answer] # Julia, ~~62~~ ~~59~~ 58 bytes ``` f(s,p,r)=(try s[[i=findnext(s,c,i+1)for c=p]'],i=r,0end;s) ``` I/O is in form of character arrays. ### Verification ``` julia> f(s,p,r)=(try s[[i=findnext(s,c,i+1)for c=p]'],i=r,0end;s) f (generic function with 2 methods) julia> F(s,p,r)=join(f([s...],[p...],[r...])) # string/char array conversion F (generic function with 1 method) julia> F("aacbcbabcccaabcbabcaabbbbca","abaaaccbac","1223334444") "aacbcbabcccaabcbabcaabbbbca" julia> F("aacbcbabcccaabcbabcaabbbbcac","abaaaccbac","1223334444") "1ac2cb2bccc33b3bab4aa4bbbc44" ``` [Answer] # PHP, ~~130~~ 109 bytes I´d still like it shorter; could save 3 bytes (`""<`) if `B` was guaranteed to not contain `0`. ``` for($s=($a=$argv)[1];""<$c=$a[2][$i++];)if($p=strpos(_.$s,$c,$p+1))$s[$p-1]=$a[3][$k++];echo$k<$i-1?$a[1]:$s; ``` takes arguments from command line. Run with `-r`. Replaces the characters when it finds them; prints copy if all characters have been replaced; original else. [Answer] # Ruby, ~~70~~ ~~64~~ ~~59~~ 58 bytes Anonymous function. Walk through the string `a` to build a new string with letters replaced in accordance to the next character in `b` and `c`, then if all characters in `b` are exhausted at the end, return the newly constructed string, otherwise return the original string. @histocrat helped save 6 bytes via `gsub`. Saved 1 byte thanks to @Cyoce. ``` ->a,b,c{i=0;s=a.gsub(/./){$&==b[i]?c[~-i+=1]:$&};b[i]?a:s} ``` [Try it online!](https://tio.run/nexus/ruby#S7ON@a9rl6iTpJNcnWlrYF1sm6iXXlyapKGvp69ZraJma5sUnRlrnxxdp5upbWsYa6WiVmsNFkq0Kq79X1BaUqyQppecmJOjkJ5aUqyXnJGfW6CDg/0/NSU5KREbwZWYlJySymVoZGxiCgA "Ruby – TIO Nexus") [Answer] # Perl, 80 + 1 = 81 bytes Run with the `-p` flag ``` $a=join"(.*?)",split//,<>;$b.=$_." .\$".++$;."."for split//,<>;chop$b;s/$a/$b/ee ``` [Try it online!](https://tio.run/nexus/perl#@6@SaJuVn5mnpKGnZa@ppFNckJNZoq@vY2NnrZKkZ6sSr6ekoBejoqSnra1iraekp5SWX6SApCg5I79AJcm6WF8lUV8lST819f//xKTklNTUlOSkRDCLKzWFy9Dov27Bf11fUz0DQwMA "Perl – TIO Nexus") The code procedurally generates a search and replace regex command, which it then executes in the last bit of code. The string `ghost` in the first example gets turned into the string `g(.*?)h(.*?)o(.*?)s(.*?)t(.*?)`, which means a `g` followed by 0 or more characters, followed by an `h` followed by 0 or more characters, followed by etc. The `*?` quantifier means that the search should be non-greedy and "gobble" as few characters as possible, instead of the default of matching as much as possible. The string `12345` then gets turned into `1 .$1.2 .$2.3 .$3.4 .$4.5 .$5`, which gets evaluated after the regex is performed. Each of `$1,$2,$3,$4,$5` is actually a backreference to a capture group (in parentheses) from the first string. [Answer] ## Clojure, 113 bytes ``` #(apply str((reduce(fn[[b c r]a](if(=(first b)a)[(rest b)(rest c)(conj r(first c))][b c(conj r a)]))[%2%3[]]%)2)) ``` A basic `reduce`, not too happy about all those long `first`, `rest` and `conj` function calls. Hoping to see a better approach. ]
[Question] [ # Challenge description In this challenge, we only consider `love` and `hate` as feelings. If we want to utter a **feeling expression** of order `N`, we alternate between these two (starting with `hate`): ``` order | expression 1 I hate it. 2 I hate that I love it. 3 I hate that I love that I hate it. 4 I hate that I love that I hate that I love it. ``` The pattern follows for every positive integer `N`. Given `N`, output the correspoinding feeling expression of order `N`. # Notes * Full stop (`.`) at the end of the expression is mandatory, * Trailing and leading whitespaces (including newlines) are permitted, * Output for a non-positive or non-integer `N` is undefined, * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so make your code as short as possible! [Answer] # Python, 54 bytes ``` lambda n:("I hate that I love that "*n)[:12*n-5]+"it." ``` * Python 2: [Ideone it!](http://ideone.com/QApTy4) * Python 3: [Ideone it!](http://ideone.com/Jo3Kap) [Answer] ## [CJam](http://sourceforge.net/projects/cjam/), 36 bytes ``` ri{"hatlov"3/='IS@"e that "}/2<"it." ``` [Try it online!](http://cjam.tryitonline.net/#code=cml7ImhhdGxvdiIzLz0nSVNAImUgdGhhdCAifS8yPCJpdC4i&input=NA) ### Explanation ``` ri e# Read input and convert to integer N. { e# For each i from 0 to N-1... "hatlov"3/ e# Push ["hat" "lov"]. = e# Use i as a cyclic index into this array to alternate between e# "hat" and "lov". 'IS e# Push character 'I' and a space. @ e# Pull "hat" or "lov" on top of it. "e that " e# Push "e that " }/ 2< e# Truncate the last "e that " to just "e ". "it." e# Push "it." ``` [Answer] # C, ~~83~~ ~~76~~ ~~75~~ 74 bytes *Thanks to @Leaky Nun for saving 11 bytes and adding 4 bytes!* *Thanks to @YSC for saving a byte!* ``` i;f(n){for(i=0;n--;)printf("I %se %s",i++%2?"lov":"hat",n?"that ":"it.");} ``` [Try it on Ideone](https://ideone.com/S5ql74) [Answer] ## Javascript (ES6), ~~75~~ ~~73~~ 70 bytes ``` n=>[...Array(n)].map((_,i)=>i&1?'I love':'I hate').join` that `+' it.' ``` *Saved 2 bytes thanks to Neil* *Saved 3 bytes thanks to Whothehellisthat* ### Test ``` let f = n=>[...Array(n)].map((_,i)=>i&1?'I love':'I hate').join` that `+' it.' console.log(f(1)) console.log(f(2)) console.log(f(3)) console.log(f(4)) ``` [Answer] # Java 8, 91 bytes ``` i->{for(int j=0;j++<i;)System.out.printf("I %se %s",j%2>0?"hat":"lov",j<i?"that ":"it.");}; ``` # Ungolfed Test Program ``` public static void main(String[] args) { Consumer<Integer> c = i -> { for (int j = 0; j++ < i;) { System.out.printf("I %se %s", j % 2 > 0 ? "hat" : "lov", j < i ? "that " : "it."); } }; c.accept(1); c.accept(2); c.accept(3); } ``` [Answer] ## Mathematica, 63 bytes ``` "I love"["I hate"][[#~Mod~2]]&~Array~#~Riffle~" that "<>" it."& ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 25 bytes ``` “ṅɠT5“£ẏkg⁷»ṁj“¥ıQ»ṙ1“it. ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCc4bmFyaBUNeKAnMKj4bqPa2figbfCu-G5gWrigJzCpcSxUcK74bmZMeKAnGl0Lg&input=&args=NA) ## Explanation ``` Input: n, a number. “ṅɠT5“£ẏkg⁷» Compressed string array [' I hate', ' I love'] ṁ Cycle for n repetitions. j“¥ıQ» Join by compressed string ' that'. ṙ1 Rotate left once: move the initial space to the end. “it. Implicitly print the result, then print 'it.' ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~34~~ ~~32~~ 27 bytes Saved 5 bytes thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan). ``` “I«¢€Š I„΀Š “×¹12*5-£…it.« ``` **Explanation** ``` “I«¢€Š I„΀Š “ # "I hate that I love that " × # repeat input nr of times ¹12*5-£ # take the first input*12-5 chars of string above …it.« # append "it." # implicitly display ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oCcScKrwqLigqzFoCBJ4oCew47igqzFoCDigJzDl8K5MTIqNS3Co-KApml0LsKr&input=NA) [Answer] # R, 79 bytes ``` n=scan();for(i in n:1)cat(if((i+n)%%2)"I love"else"I hate",if(i>1)"that "else"it.") ``` Luckily in R, the default separator for `cat` is a space. (Edited from original 73 byte version which didn't quite solve the problem.) [Answer] # [Retina](http://github.com/mbuettner/retina), ~~42~~ 38 bytes Thanks to Leaky Nun for helping me golf it! ``` 11 1I love n 1 I hate n n$ it. n that ``` Input is taken in unary. [Try it online!](http://retina.tryitonline.net/#code=MTEKMUkgbG92ZSBuCjEKSSBoYXRlIG4KbiQKaXQuCm4KdGhhdCA&input=MTExMTE) **Explanation** ``` 11 1I love n ``` Replace every pair of `1`s with `1I love n`. ``` 1 I hate n ``` Replace the remaining `1`s with `I hate n`. ``` n$ it. n that ``` Replace the `n` at the end of the line with `it.` and every other n with `that`. [Answer] # Javascript (ES5), 99 94 bytes ``` function(c){for(d="",b=0;b<c;++b)d+=(b%2?"I love ":"I hate ")+(b==c-1?"it.":"that ");return d} ``` Saved 5 bytes thanks to Leaky Nun. OLD 99 byte solution: ``` function(c){for(d="",b=0;b<c;++b)d+=(0==b%2?"I hate":"I love")+" "+(b==c-1?"it.":"that ");return d} ``` Another 98 byte solution: ``` function(d){for(c=[],b=0;b<d;++b)c.push(["love","hate"][b%2]);return"I "+c.join(" that I ")+" it"} ``` My code before minification: ``` function a(n){ var hate="I hate",love="I love",it="it ",that="that ",out=""; for(var i=0;i<n;++i){out+=(i%2==0?hate:love)+" "+(i==n-1?it+".":that)}return out; } ``` [Answer] # Haskell, 70 bytes ``` g 1="I hate";g n=g(n-1)++" that "++cycle["I love",g 1]!!n (++" it.").g ``` [Answer] ## PowerShell v2+, 64 bytes ``` ((1..$args[0]|%{('I love','I hate')[$_%2]})-join' that ')+' it.' ``` Rather straightforward. Loops from `1` up to the input `$args[0]`, each iteration placing either `'I love'` or `'I hate'` on the pipeline, based on a pseudo-ternary for modulo-2 (i.e., it alternates back and forth, starting with `'I hate'`). Those strings are encapsulated in parens and `-join`ed with `' that '` to smush them together, then string concatenation `' it.'` at the end. ### Test Cases ``` PS C:\Tools\Scripts\golfing> 1..5|%{.\hate-love-conundrum.ps1 $_} I hate it. I hate that I love it. I hate that I love that I hate it. I hate that I love that I hate that I love it. I hate that I love that I hate that I love that I hate it. ``` [Answer] # php, ~~64~~ 62 bytes ``` <?=str_pad("",$argv[1]*12-5,"I hate that I love that ")."it."; ``` Unfortunately I couldn't work out a way to avoid repeating the " that I ", or at least no way to do it in less than 7 bytes. edit: saved 2 bytes thanks to @Jörg Hülsermann [Answer] ## Perl, ~~62~~ ~~54~~ 50 bytes ``` $_="I xe tx "x$_;s/tx $/it./;s/x/++$.%4?hat:lov/ge ``` (credit to [@Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel)) Demo: <http://ideone.com/zrM27p> ### Previous solutions: ``` $_="I xe that "x$_;s/x/$@++&1?lov:hat/ge;s/\w+.$/it./ ``` (credit to [@Dada](https://codegolf.stackexchange.com/users/55508/dada)) Run with `perl -pE '$_="I xe that "x$_;s/x/$@++&1?lov:hat/ge;s/\w+.$/it./'` ### First solution (only this was mine) ``` for$x(1..<>){$_.=' I '.($x%2?hat:lov).'e that'}s/\w+$/it./;say ``` In parts: ``` for $x (1..<>) { $_ .= ' I '.($x % 2 ? hat : lov).'e that' } s/\w+$/it./; say ``` Demo: <http://ideone.com/mosnVz> [Answer] # Bash + coreutils, 106 bytes: ``` for i in `seq $1`;{ printf "I %s %s " `((i%2>0))&&echo hate||echo love` `((i==$1))&&echo it.||echo that`;} ``` Simply creates a sequence starting at `1` up to and including the input integer using the `seq` built-in, and then iterates through it one by one, first outputting `hate` if the value of the iteration variable, `i`, is not divisible by `2` and `love` otherwise. In the same iteration, it then chooses to output `that` if `i` is not equal to the input value, and `it.` otherwise. [Try It Online! (Ideone)](http://ideone.com/fdCFXy) [Answer] # ///, ~~60~~ 57 bytes ``` /!/I hate //T/that // /it.//00/!TI love T//Tit./it.//0/!/ ``` *-3 bytes thanks to m-chrzan* Input in unary with trailing new line. [Try it online!](http://slashes.tryitonline.net/#code=LyEvSSBoYXRlIC8vVC90aGF0IC8vCi9pdC4vLzAwLyFUSSBsb3ZlIFQvL1RpdC4vaXQuLy8wLyEvMDAwCg&input=) [Answer] ## R, 92 90 bytes An R adaptation of @Leaky Nun's python answer. Working with strings in R is tedious as always. ``` n=scan();cat(rep(strsplit("I hate that I love that ","")[[1]],n)[6:(n*12)-5],"it.",sep="") ``` This could probably be golfed further though. Edit: saved 2 bytes by changing: `[1:((n*12)-5)]`to `[6:(n*12)-5]` [Answer] ## C, 96 Bytes ``` c;f(i){printf("I hate");for(;c<i+1/2-1;c++)printf(" that I %s",c&1?"hate":"love");puts(" it.");} ``` I didn't see the above solution from Releasing Helium Nuclei which is better. [Answer] # [MATL](http://github.com/lmendo/MATL), 37 bytes ``` :"2@o3]Qv'hate I that it. love'Ybw)Zc ``` [Try it online!](http://matl.tryitonline.net/#code=OiIyQG8zXVF2J2hhdGUgSSB0aGF0IGl0LiBsb3ZlJ1lidylaYw&input=NA) ### Explanation The code is based on the following mapping from numbers to strings: ``` 0: 'love' 1: 'hate' 2: 'I' 3: 'that' 4: 'it.' ``` The program pushes numbers to the string in groups of three: `2`, `0`, `3`; then `2`, `1`, `3`; then `2`, `0`, `3`; ... as many times as the input `n`. After that, the final `3` is transformed into a `4`, the mapping is applied to transform numbers to strings, and the strings are joined using space as separator. ``` : % Input n implicitly. Push range [1 2 ... n] " % For each 2 % Push 2 @o % Iteration index modulo 2: pushes 0 or 1 3 % Push 3 ] % End Q % Add 1 to the last 3 v % Concatenate stack contents into a numeric column vector 'hate I that it. love' % Push this string Yb % Split at spaces. Gives a cell array of five strings w % Swap to move numeric vector to top ) % Index cell array of strings with that vector. Indexing % is 1-based and modular, so 0 refers to the last string. % This gives a cell array of (repeated) strings Zc % Join those strings by spaces. Display implicitly ``` [Answer] # JavaScript (ES6), 68 bytes ``` f=(n,i)=>n?(i?' that I ':'I ')+(i&1?'love':'hate')+f(n-1,-~i):' it.' document.write('<pre>'+[ 1, 2, 3, 4, 10, 100 ].map(c=>c+': '+f(c)).join`\n`); ``` [Answer] # C#, ~~85~~ 83 bytes ``` string f(int n,int m=2)=>"I "+(1>m%2?"hat":"lov")+(m>n?"e it.":"e that "+f(n,m+1)); ``` Recursively constructs the string, using an optional parameter to keep track of which hate/love and how many to append. *-2 bytes from [this tip](https://codegolf.stackexchange.com/questions/173/tips-for-code-golfing-in-c/84382#84382) for checking the evenness/oddness of a number.* ### No optional parameter solution, ~~87~~ ~~86~~ 84 bytes ``` string h(int n)=>"I "+(0<n?"hat":"lov")+(2>n&-2<n?"e it.":"e that "+h(0<n?~n+2:~n)); ``` This one does the same thing except determines which hate/love to append based on whether the parameter is positive or negative. Each iteration the parameter approaches zero, alternating sign. [Answer] # Thue, 100 bytes ``` @::=::: >##::=>$. $::=~I hate that I love >.#::=>&# &::=~that >#<::=~I hate it. >.<::=~it. ::= >@< ``` Takes input as unary. (A string of n `#`s) [Answer] ## Pyke, 36 bytes ``` 2/"I hate ""I love "]*"that "J"it."+ ``` [Try it here!](http://pyke.catbus.co.uk/?code=2%2F%22I+hate+%22%22I+love+%22%5D%2a%22that+%22J%22it.%22%2B&input=3) ``` 2/ - input/2 * - ^ * v "I hate ""I love "] - ["I hate ", "I love "] "that "J - "that ".join(^) "it."+ - ^+"it." ``` Also 36 bytes ``` 12*5+.daෆ ű l5d+12"I ":Q*<"it."+ ``` [Try it here!](http://pyke.catbus.co.uk/?code=12%2a5%2B.d%05a%E0%B7%86%09%C5%B1%09l5d%2B12%22I+%22%3AQ%2a%3C%22it.%22%2B&input=4) (Link uses `X` instead of `I`, [this](http://pyke.catbus.co.uk/?code=12*5%2B.d%05%0A%E0%B7%86%09%C5%B1%09l5d%2B12%22I+%22%3AQ*%3C%22it.%22%2B&input=4) should work for the same amount of bytes offline where you can literally use those bytes. Online `\r` gets automatically replaced with `\n`) [Answer] # ><> (Fish), 82 Bytes ``` ' I'oov.2coo<;oooo' it.'< 'ahv'v>'et' oop26<^ooooo^o' that I '^!?:-1oo 'ol^'^>'ev' ``` Doubt it's very efficient, but it seems to more or less work. Input is via the starting stack, which makes the score 85 Bytes if you include the size of the `-v` argument required to do so. [Try it online!](https://fishlanguage.com/playground/JTWzGWskTR7KWfoz3) [Answer] # Lua , 75 Bytes ``` n=io.read();print(('I hate that I love that '):rep(n):sub(1,n*12-5)..'it.') ``` [Answer] # [///](http://esolangs.org/wiki////), 68 bytes ``` /@/1\/#love //%/hate//#/that I //%1i/% i//I %1/I % //1@#% //@/I %1it. ``` Input in unary - add more `1`s in the last section. [Try it online!](http://slashes.tryitonline.net/#code=L0AvMVwvI2xvdmUgLy8lL2hhdGUvLyMvdGhhdCBJIC8vJTFpLyUgaS8vSSAlMS9JICUgLy8xQCMlIC8vQC9JICUxMTExMWl0Lg&input=) [Answer] ## dc, 75 bytes ``` ?[1-lbP[I lov]P]sa[e that ]sb[[e it.]Pq]sc[1-[I hat]Pd2%1=ad1>clbPlxx]dsxx ``` We're really just printing one chunk of string at a time here, and not leaving any garbage on the stack. This is great, we don't need to waste any bytes dealing with a register for our counter. ``` ? #Input, works as our decrement counter [1-lbP[I lov]P]sa #Macro 'a' decrements our counter, prints string 'b', #then prints 'I lov' [e that ]sb #String 'b' [[e it.]Pq]sc #Macro 'c' prints the tail end of our message and quits [1- #I'll unfold our main macro here; first step is to #decrement our counter [I hat]P #We always start by hating 'it,' no conditional needed d2%1=a #Check the oddness of our counter; execute 'a' if odd d1>c #Check our counter; If we're done, execute 'c' lbPlxx] #Otherwise, print 'b' again and start this macro ('x') over dsxx #Stores the above macro as 'x' and runs it. ``` [Answer] ## Julia, 91 Bytes Thought I add a julia solution: ``` f(N)=string("I hate ",join(["that I love that I hate " for _ in 1:N-1])[1:12*(N-1)],"it.")) ``` ]
[Question] [ Here is a simple ASCII art [ruby](http://en.wikipedia.org/wiki/Ruby): ``` ___ /\_/\ /_/ \_\ \ \_/ / \/_\/ ``` As a jeweler for the ASCII Gemstone Corporation, your job is inspect the newly acquired rubies and leave a note about any defects that you find. Luckily, only 12 types of defects are possible, **and your supplier guarantees that no ruby will have more than one defect.** The 12 defects correspond to the replacement of one of the 12 inner `_`, `/`, or `\` characters of the ruby with a space character (). The outer perimeter of a ruby never has defects. The defects are numbered according to which inner character has a space in its place: ![defect numbers](https://i.stack.imgur.com/0UT6R.png) So a ruby with defect 1 looks like this: ``` ___ /\_/\ /_/ _\ \ \_/ / \/_\/ ``` A ruby with defect 11 looks like this: ``` ___ /\_/\ /_/ \_\ \ \_/ / \ _\/ ``` It's the same idea for all other defects. # Challenge Write a program or function that takes in the string of a single, potentially defective ruby. The defect number should be printed or returned. The defect number is 0 if there is no defect. Take input from a text file, stdin, or a string function argument. Return the defect number or print it to stdout. You may assume that the ruby has a trailing newline. You may **not** assume that it has any trailing spaces or leading newlines. The shortest code in bytes wins. ([Handy byte counter.](http://meta.codegolf.stackexchange.com/q/4944/26997)) ### Test Cases The 13 exact types of rubies, followed directly by their expected output: ``` ___ /\_/\ /_/ \_\ \ \_/ / \/_\/ 0 ___ /\_/\ /_/ _\ \ \_/ / \/_\/ 1 ___ /\ /\ /_/ \_\ \ \_/ / \/_\/ 2 ___ /\_/\ /_ \_\ \ \_/ / \/_\/ 3 ___ /\_/\ /_/ \_\ \ _/ / \/_\/ 4 ___ /\_/\ /_/ \_\ \ \ / / \/_\/ 5 ___ /\_/\ /_/ \_\ \ \_ / \/_\/ 6 ___ /\_/\ /_/ \ \ \ \_/ / \/_\/ 7 ___ /\_ \ /_/ \_\ \ \_/ / \/_\/ 8 ___ / _/\ /_/ \_\ \ \_/ / \/_\/ 9 ___ /\_/\ / / \_\ \ \_/ / \/_\/ 10 ___ /\_/\ /_/ \_\ \ \_/ / \ _\/ 11 ___ /\_/\ /_/ \_\ \ \_/ / \/_ / 12 ``` [Answer] ## Ruby 2.0, 69 bytes ``` #!ruby -Kn0rdigest p'×ñF<ìX‚ɲŸ_'.index Digest::MD5.digest(gets)[0] ``` Hexdump (to faithfully show the binary data in the string): ``` 00000000 23 21 72 75 62 79 20 2d 4b 6e 30 72 64 69 67 65 |#!ruby -Kn0rdige| 00000010 73 74 0a 70 27 d7 f1 46 3c 1f ec 58 82 c9 b2 9f |st.p'..F<..X....| 00000020 5f 02 27 2e 69 6e 64 65 78 20 44 69 67 65 73 74 |_.'.index Digest| 00000030 3a 3a 4d 44 35 2e 64 69 67 65 73 74 28 67 65 74 |::MD5.digest(get| 00000040 73 29 5b 30 5d |s)[0]| ``` Explanation: 1. The `-Kn` option reads the source file as `ASCII-8BIT` (binary). 2. The `-0` option allows `gets` to read in the whole input (and not just one line). 3. The `-rdigest` option loads the `digest` module, which provides `Digest::MD5`. 4. The code then does an MD5 of the input, takes the first byte of the digest, and gets its index in the given binary string. [Answer] # CJam, ~~27~~ 23 bytes ``` F7EC5ZV4DI8G6]qBb67%J%# ``` Convert base 11, take mod 67, take mod 19 of the result then find the index of what you have in the array ``` [15, 7, 14, 12, 5, 3, 0, 4, 13, 18, 8, 16, 6] ``` Magic! [Try it online](http://cjam.aditsu.net/#code=F7EC5ZV4DI8G6%5DqBb67%25J%25%23&input=%20%20___%0A%20%2F%5C_%20%5C%0A%2F_%2F%20%5C_%5C%0A%5C%20%5C_%2F%20%2F%0A%20%5C%2F_%5C%2F). [Answer] # Julia, ~~90~~ 59 bytes Definitely not the shortest, but the fair maiden Julia takes great care in the inspection of the royal rubies. ``` s->search(s[vec([18 10 16 24 25 26 19 11 9 15 32 34])],' ') ``` This creates a lambda function which accepts a string `s` and returns the corresponding ruby defect number. To call it, give it a name, e.g. `f=s->...`. Ungolfed + explanation: ``` function f(s) # Strings can be indexed like arrays, so we can define d to # be a vector of indices corresponding to potential defect # locations d = vec([18 10 16 24 25 26 19 11 9 15 32 34]) # Check the specified locations for defects, returning the # defect number as the index where a space was found and # was not expected. If no spaces are found, 0 is returned. search(s[d], ' ') end ``` Examples: ``` julia> f(" ___ /\\ /\\ /_/ \\_\\ \\ \\_/ \/ \\/_\\/") 2 julia> f(" ___ /\\_/\\ /_/ \\_\\ \\ \\_/ \/ \\/_\\/") 0 ``` Note that backslashes have to be escaped in the input. I confirmed with @Calvin'sHobbies that it's okay. Let me know if you have any questions or suggestions! --- **Edit:** Saved 31 bytes with help from Andrew Piliser! [Answer] # [><> (Fish)](http://esolangs.org/wiki/Fish), 177 bytes This is a long but unique solution. The program contains **no arithmetic or branching** apart from inserting input characters into fixed places in the code. Notice that all the inspected ruby-building characters (`/ \ _`) can be "mirrors" in the ><> code that change the direction of the instruction pointer (IP). We can use these input characters to build a maze from them with the code-modifying instruction `p` and at every exit (which created by a missing mirror in the input) we can print the corresponding number. ``` iiiiiiiii19pi1cpi18piiii2bpi27pii28pi3apiiiii37pi49pi36piiiii00pi45pii46p ; ;n ;nb ;n6S 0n; n3SB cn; 8SB! 4n; SB! 1n; >B! U9n; ! U5 U7n Uan; 2n; n; ; ``` The `S B U` letters are the ones changed to `/ \ _` respectively. If the input is a full ruby the final code becomes: ``` \iiiiiiii19pi1cpi18piiii2bpi27pii28pi3apiiiii37pi49pi36piiiii00pi45pii46p ; ;n ;nb ;n6/ 0n; n3/\ cn; 8/\! 4n; /\! 1n; >\! _9n; ! _5 _7n _an; 2n; n; ; ``` You can try out the program with [this great online visual interpreter](http://fishlanguage.com/). As you can't input newlines there you have to use some dummy characters instead so you can input a full ruby as e.g. `SS___LS/\_/\L/_/S\_\L\S\_/S/LS\/_\/`. (Spaces also changed to S's because of markdown.) [Answer] # CJam, ~~41 31 29~~ 28 bytes ``` "-RI)11a!"q103b1e3%A/c# ``` As usual, for non printable characters, follow [this link](https://mothereff.in/byte-counter#"%17-RI%29%0E1%15%021a!%05"q103b1e3%25A%2Fc%23). [Try it online here](http://cjam.aditsu.net/#code=%22%17-RI)%0E1%15%021a!%05%22q103b1e3%25A%2Fc%23&input=%20%20___%0A%20%2F%5C_%2F%5C%0A%2F_%2F%20%20_%5C%0A%5C%20%5C_%2F%20%2F%0A%20%5C%2F_%5C%2F) Explanation soon --- Previous approach: Pretty sure this can be reduced by changing the digits/conversion logic. But here goes the first attempt: ``` "<KJ[]\"O=":iqN-"/\\_ "4,er4b1e3%A/# ``` As usual, use [this link](https://mothereff.in/byte-counter#%22%3C%19%02%0EKJ%15%06[]%5C%22O%3D%22%3AiqN-%22%2F%5C%5C_%20%224%2Cer4b1e3%25A%2F%23) for unprintable characters. The logic is pretty simple * `"Hash for each defect":i` - This gets me the hash per defect as the index * `qN-"/\\_ "4,er` - this converts the characters to numbers * `4b1e3%A/` - this is the unique number in the base converted number * `#` Then I simply find the index of the unique number in the hash [Try it online here](http://cjam.aditsu.net/#code=%22%3C%19%02%0EKJ%15%06%5B%5D%5C%22O%3D%22%3AiqN-%22%2F%5C%5C_%20%224%2Cer4b1e3%25A%2F%23&input=%20%20___%0A%20%2F%5C%20%2F%5C%0A%2F_%2F%20%5C_%5C%0A%5C%20%5C_%2F%20%2F%0A%20%5C%2F_%5C%2F) [Answer] # [Slip](https://github.com/Sp3000/Slip/wiki), ~~123~~ 108 + 3 = 111 bytes ``` ^6 (`\\`_.?<?.?[ _]?|`_(`\.?(<.?|>)|`/.?.?>.?.?).?)| `_(`\.?<.?>?.?.?|`/(.?>.?.?.?|<`_))| `/\`_.?(.<.?>?.?)? ``` Run with the `n` and `o` flags, i.e. ``` py -3 slip.py regex.txt input.txt no ``` Alternatively, [try it online](https://slip-online.herokuapp.com/?code=%5E6%20%28%60%5C%5C%60_.%3F%3C%3F.%3F%5B%20_%5D%3F%7C%60_%28%60%5C.%3F%28%3C.%3F%7C%3E%29%7C%60%2F.%3F.%3F%3E.%3F.%3F%29.%3F%29%7C%20%60_%28%60%5C.%3F%3C.%3F%3E%3F.%3F.%3F%7C%60%2F%28.%3F%3E.%3F.%3F.%3F%7C%3C%60_%29%29%7C%20%60%2F%5C%60_.%3F%28.%3C.%3F%3E%3F.%3F%29%3F&input=%20%20___%0A%20%2F%5C_%2F%5C%0A%2F_%2F%20%5C%20%5C%0A%5C%20%5C_%2F%20%2F%0A%20%5C%2F_%5C%2F&config=no). --- Slip is a regex-like language which was made as part of the [2D pattern matching](https://codegolf.stackexchange.com/questions/47311/language-design-2-d-pattern-matching) challenge. Slip can detect the location of a defect with the `p` position flag via the following program: ``` ^6? `_[/\]|( `/|^6 `\)\`_ ``` which looks for one of the following patterns (here `S` denotes here the match starts): ``` S_/ S_\ /_S \_S S/ _ _ \S ``` [Try it online](https://slip-online.herokuapp.com/?code=%5E6%3F%20%60_%5B%2F%5C%5D%7C%28%20%60%2F%7C%5E6%20%60%5C%29%5C%60_&input=%20%20___%0A%20%2F%5C_%2F%5C%0A%2F_%2F%20%20_%5C%0A%5C%20%5C_%2F%20%2F%0A%20%5C%2F_%5C%2F&config=p) — coordinates are outputted as an (x, y) pair. Everything reads like a normal regex, except that: * ``` is used for escaping, * `<>` turn the match pointer left/right respectively, * `^6` sets the match pointer to face leftward, and * `\` slips the match pointer orthogonally to the right (e.g. if the pointer's facing rightward then it goes down a row) But unfortunately, what we need is a single number from 0 to 12 saying *which* defect was detected, not *where* it was detected. Slip only has one method of outputting a single number — the `n` flag which outputs the number of matches found. So to do this we expand the above regex to match the correct number of times for each defect, with the help of the `o` overlapping match mode. Broken down, the components are: ``` 1 11: `_`\.?<.?>?.?.? 2 10: `/\`_.?(.<.?>?.?)? 4 9: `_`/(.?>.?.?.?|<`_) 3 12: ^6 `_`/.?.?>.?.?.? 5 7: ^6 `\\`_.?<?.?[ _]? 6 8: ^6 `_`\.?(<.?|>).? ``` Yes, that's an exccessive use of `?` to get the numbers right :P [Answer] # JavaScript (ES6), 67 ~~72~~ Simply looks for blanks in the given 12 locations **Edit** Saved 5 bytes, thx @apsillers ``` F=b=>[..."0h9fnopia8evx"].map((v,i)=>b[parseInt(v,34)]>' '?0:d=i)|d ``` **Test** In Firefox / FireBug console ``` x=' ___\n /\\_/\\\n/_/ \\_\\\n\\ \\_/ /\n \\/_\\/' // no defects ;[...x].forEach((c,p,a)=>{ a[p]=' ' // put a blank y=a.join('') // rebuild a string d=F(y) // check if (d) console.log('\n'+y+'\n'+d) // if defect, output a[p]=c // remove the blamk }) ``` *Output* ``` ___ / _/\ /_/ \_\ \ \_/ / \/_\/ 9 ___ /\ /\ /_/ \_\ \ \_/ / \/_\/ 2 ___ /\_ \ /_/ \_\ \ \_/ / \/_\/ 8 ___ /\_/\ / / \_\ \ \_/ / \/_\/ 10 ___ /\_/\ /_ \_\ \ \_/ / \/_\/ 3 ___ /\_/\ /_/ _\ \ \_/ / \/_\/ 1 ___ /\_/\ /_/ \ \ \ \_/ / \/_\/ 7 ___ /\_/\ /_/ \_\ \ _/ / \/_\/ 4 ___ /\_/\ /_/ \_\ \ \ / / \/_\/ 5 ___ /\_/\ /_/ \_\ \ \_ / \/_\/ 6 ___ /\_/\ /_/ \_\ \ \_/ / \ _\/ 11 ___ /\_/\ /_/ \_\ \ \_/ / \/_ / 12 ``` [Answer] # C, ~~98~~ 84 bytes ``` g(char*b){char*c="/'-5670(&,=?",*a=c;for(;*c&&!(*b=b[*c++-30]-32?0:c-a););return*b;} ``` UPDATE: A tad bit more clever about the string, and fixed an issue with non-defected rubies. Unraveled: ``` g(char*b){ char*c="/'-5670(&,=?",*a=c; for(;*c&&!(*b=b[*c++-30]-32?0:c-a);) ; return*b; } ``` Quite straightforward, and *just* under 100 bytes. For testing: ``` #include "stdio.h" int main() { char b[100]; scanf("%35c", b); printf("%d\n", g(b)); return 0; } ``` Input to STDIN. # How it works Each defect in the ruby is located at a different character. This list shows where each defect occurs in the input string: ``` Defect 1: 17 Defect 2: 9 Defect 3: 15 Defect 4: 23 Defect 5: 24 Defect 6: 25 Defect 7: 18 Defect 8: 10 Defect 9: 8 Defect 10: 14 Defect 11: 31 Defect 12: 33 ``` Since making an array of `{17,9,15,23,24,25,18,10,8,14,31,33}` costs a lot of bytes, we find a shorter way to create this list. Observe that adding 30 to each number results in a list of integers that could be represented as printable ASCII characters. This list is as follows: `"/'-5670(&,=?"`. Thus, we can set a character array (in the code, `c`) to this string, and simply subtract 30 from every value we retrieve from this list to get our original array of integers. We define `a` to be equal to `c` for keeping track of how far along the list we have gotten. The only thing left in the code is the `for` loop. It checks to make sure we have not hit the end of `c` yet, and then checks if the character of `b` at the current `c` is a space(ASCII 32). If it is, we set the first, unused element of `b` to the defect number and return it. [Answer] # Python 2, ~~146~~ ~~88~~ ~~86~~ 71 bytes The function `f` tests each segment location and returns the index of the defect segment. A test on the first byte in the input string ensures that we return `0` if no defects are found. We now pack the segment offsets into a compact string and use `ord()` to recover them: ``` f=lambda s:sum(n*(s[ord('ARJPXYZSKIO`b'[n])-65]<'!')for n in range(13)) ``` Testing with a perfect ruby: ``` f(' ___\n /\\_/\\\n/_/ \\_\\\n\\ \\_/ /\n \\/_\\/') 0 ``` Testing with segment 2 replaced by a space: ``` f(' ___\n /\\ /\\\n/_/ \\_\\\n\\ \\_/ /\n \\/_\\/') 2 ``` *EDIT: Thanks to @xnor for the nice `sum(n*bool for n in...)` technique.* *EDIT2: Thanks to @Sp3000 for extra golfing tips.* [Answer] # Pyth, 35 31 28 bytes ``` hx"*6#,54@"C%imCds.zT67 ``` [Requires a patched Pyth](https://github.com/isaacg1/pyth/pull/66), the current latest version of Pyth has a bug in `.z` that strips off trailing characters. This version doesn't use a hash function, it abuses the base conversion function in Pyth to compute a very stupid, but working hash. Then we convert that hash to a character and look its index up in a string. The answer contains unprintable characters, use this Python3 code to generate the program accurately on your machine: ``` garbage = [42, 22, 54, 35, 44, 28, 31, 53, 52, 64, 16, 11] prg = 'hx"' + "".join(chr(c) for c in garbage) +'"C%imCds.zT67' open("golf_gen.pyth", "w").write(prg) print(len(prg)) ``` [Answer] # Haskell, 73 bytes ``` f l=last[x|x<-[0..12],l!!([0,17,9,15,23,24,25,18,10,8,14,31,33]!!x)==' '] ``` Same strategy as many other solutions: looking for spaces at the given locations. The lookup returns a list of indices from which I take the last element, because there is always a hit for index 0. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •W)Ì3ô;4(•₆вèðk> ``` [Try it online](https://tio.run/##yy9OTMpM/f//UcOicM3DPcaHt1ibaAA5j5raLmw6vOLwhmy7//@VlJQUFOLj47kU9GPi9WO49OP1FWLiY7higKS@gj6XQox@fIw@UBUA) or [verify all test cases](https://tio.run/##yy9OTMpM/f@oYZHJo4aZh5YfWnl076OmtkNrju7QAAoCmRc2lR3eUHl8rouSZ15BaYmVAtfh/Vz@pSVgtpI9SGu45uEe48NbrE3gWg6vOLwh2@6/zqFt9v@VlJQUFOLj47kU9GPi9WO49OP1FWLiY7higKS@gj6XQox@fIw@UBUA). **Explanation:** ``` •W)Ì3ô;4(• # Push compressed integer 2272064612422082397 ₆в # Converted to Base-36 as list: [17,9,15,23,24,25,18,10,8,14,31,33] è # Index each into the (implicit) input-string ðk # Get the 0-based index of the first space in the indexed characters # (-1 if not found, which means the ruby had no defects) > # And increase it by 1 (which is output implicitly as result) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•W)Ì3ô;4(•` is `2272064612422082397` and `•W)Ì3ô;4(•₆в` is `[17,9,15,23,24,25,18,10,8,14,31,33]`. ]
[Question] [ [Toki Pona](https://tokipona.org) is a constructed language with 137ish words, designed to constrain the speaker to expressing ideas in a simple and straightforward manner, reducing ideas to more essential forms. Often, people attempt to avoid directly expressing numeric quantities in Toki Pona, opting to express them in more practical terms. if one has a very large amount of money ("mani mute mute"), does it matter if it is $3,532,123 or $3,532,124? However, Toki Pona does have a basic additive number system, (as well as some others that people have proposed but are not widely used) which is capable of expressing exact quantities. Toki Pona uses the follow words for numbers: | word | value | | --- | --- | | ala | 0 | | wan | 1 | | tu | 2 | | luka | 5 | | mute | 20 | | ale | 100 | The quantity expressed by a series of these words is the sum of all of their values. A quantity must be expressed in as few words as possible, with the words ordered from greatest value to least. for instance, simply summing the values of the words, 6 could be expressed "tu tu tu", "luka wan", "wan luka", "wan wan wan wan wan wan", or some other variation. however, a valid program will only generate "luka wan" for 6. # Challenge Write a program which takes as input a non-negative integer and outputs this integer expressed in the Toki Pona number system. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Spaces are required. # Examples | input | output | | --- | --- | | 0 | ala | | 1 | wan | | 2 | tu | | 28 | mute luka tu wan | | 137 | ale mute luka luka luka tu | | 1000 | ale ale ale ale ale ale ale ale ale ale | [Answer] # [Python 2](https://docs.python.org/2/), 81 bytes ``` lambda n:n/100*'ale '+n/20%5*'mute '+n/5%4*'luka '+n%5/2*'tu '+n%5%2*'wan'or'ala' ``` [Try it online!](https://tio.run/##JYtBCsIwEEX3nmI2YTQWMo2GSsGbuBnRYDGdlJBQevoYKXwe7y3@suVPFFv9/VEDz88Xg4xieiKNHN6AZzGWlNM4l7ynU1eNoXz5X8oZqzGX3VXzlQVjamfG6mMCgUmAOug7sG23ZpehgYjGAyxpkgz@KKf6Aw "Python 2 – Try It Online") The naive approach is surprisingly effective. The overhead of an iterative or recursive method seems too high, though I'd like to be proven wrong. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~41~~ 39 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)! (Golfed the method of "coin counting".) ``` ;%\:ɗ“dÞ¦£‘Jx$ȯWị“&ḍṘṭ.½6²EmSFʂ5ȥṙẠ»Ḳ¤K ``` **[Try it online!](https://tio.run/##y0rNyan8/99aNcbq5PRHDXNSDs87tOzQ4kcNM7wqVE6sV3q4uxsoqvZwR@/DnTMe7lyrd2iv2aFNrrnBbqeaTE8sfbhz5sNdCw7tfrhj06El3v8Pt2tG/v9voKNgqKNgBEQWQJaxOZAwMDAAAA "Jelly – Try It Online")** ### How? ``` ;%\:ɗ“dÞ¦£‘Jx$ȯWị“...»Ḳ¤K - Link: non-negative integer, n “dÞ¦£‘ - [100,20,5,2] ɗ - last three links as a dyad - f(n, [100,20,5,2]): ; - (n) concatenate ([100,20,5,2]) -> [n,100,20,5,2] \ - cumulative reduce by: % - modulo -> [n, n%100, n%100%20, n%100%20%5, n%100%20%5%2] : - integer divide ([100,20,5,2]) -> [n//100, n%100//20, n%100%20//5, n%100%20%5//2, n%100%20%5%2] Jx$ - repeat indices - e.g. [0,3,2,2,0] -> [2,2,2,3,3,4,4] W - wrap -> [n] ȯ - logical OR (if n was 0 we now get [0] in place of []) “...»Ḳ¤ - ["ale","mute","luka","tu","wan","ala"] ị - index into (1-indexed and modular) K - join with spaces ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 63 bytes ``` Yay?{x:y//aYy%ab.sRLx}MZ[h20 5 2o]"ale mute luka tu wan"^s"ala" ``` Takes the number as a command-line argument. [Try it online!](https://tio.run/##K8gs@P8/MrHSvrrCqlJfPzGyUjUxSa84yKei1jcqOsPIQMFUwSg/VikxJ1Uht7QkVSGnNDtRoaRUoTwxTymuGCieqPT//39DY3MA "Pip – Try It Online") ### Explanation Yay? ``` ; Copy the command-line argument from local variable a into global variable y Ya ; If y is nonzero (truthy), y? ; Take this function (explained below) {x:y//aYy%ab.sRLx} ; and map it to pairs of items from MZ ; this list of numbers [100 20 5 2 1] ; and this string of words, split on spaces "ale mute luka tu wan" ^ s ; Else (if y is zero), output ala "ala" ``` The mapping function gets a number as its first argument `a` and the corresponding word as its second argument `b`: ``` { ; Set x to y (the input number) int-divided by a (the Toki Pona number) x: y//a ; Update y to be y mod a Y y%a ; Concatenate b (the Toki Pona word) with space... b . s ; ... and return a list of x copies of that string RL x } ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 92 bytes ``` ->n{n<1?"ala":[100,20,5,2,1].map{|i|n-=i*j=n/i;"#{%w{luka wan tu mute ale}[i%12%5]} "*j}*""} ``` [Try it online!](https://tio.run/##BcHRCsIgFADQXxHDF3FLhb1U1oeIDzdw4FIZS5mhfrudc@T3b6xqTM9Y40O8MHjANy04Z5KzhUkmzBxgr821OClHNxWv7o4vlZzV5w@gEyJKGYWcLAJvu3ZESLKYjjDdOsW4D8nFnFyw39pK25EubNXFmD7@ "Ruby – Try It Online") Saved some bytes by iterating directly through `100,20,5,2,1` and using the formula `i%12%5` to generate a unique index in the range `0..4`for each in order to lookup the word. I'm pleasantly surprised that `n-=i*(j=n/i)` works as intended without brackets. # [Ruby](https://www.ruby-lang.org/), 105 bytes ``` ->n{n<1?a=["ala"]:5.times{|i|a=*a,"#{%w{ale mute luka tu wan}[i]} "*j=n/k=[100,20,5,2,1][i];n-=j*k} a*""} ``` [Try it online!](https://tio.run/##NcxBCgIhFADQfaf4GG3EKRVmU1kHERc/cMBxRqKUMdSzW5vWD94rPT59Un24hRKu4o5KE1yQmPN4jG6171JdRUWRkX05bAUXC2uKFpbkEWKCDUPTzjQgdFbh5JUWnDPJ2cgkE@ZHlzComfq2Q0pI65KL/5zrE3Rmk87GtP4F "Ruby – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 38 bytes ``` 521f20p₁p(nḋ÷)WṪ«øßṀ∞HĊ∴ǑTṄ‟7«⌈ð+*‛Ż₅⟑ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=521f20p%E2%82%81p%28n%E1%B8%8B%C3%B7%29W%E1%B9%AA%C2%AB%C3%B8%C3%9F%E1%B9%80%E2%88%9EH%C4%8A%E2%88%B4%C7%91T%E1%B9%84%E2%80%9F7%C2%AB%E2%8C%88%C3%B0%2B*%E2%80%9B%C5%BB%E2%82%85%E2%9F%91&inputs=8&header=&footer=) ``` ‛Ż₅⟑ # Handle the base case 0 -> ala 521f20p₁p # Create the list 100,20,5,2,1 (n ) # Iterate over, pushing each time ḋ÷ # Divmod ToS (initially input) by current number, and iterate - remainder becomes new ToS WṪ # Wrap, getting all the divisions * # Dot product with «...«⌈ð+ # Words, each with a space appended ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 60 bytes ``` .+ $* 1{100} ale 1{20} mute 1{5} luka 11 tu 1 wan ^$ ala ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLy7Da0MCglisxJ1UByDYCMnNLS8Bs01qunNLsRCDTkKukFEhxlSfmccWpANUm/v9vAOQbcRlZcBkam3MBjTAAAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` .+ $* ``` Convert to unary. ``` 1{100} ale 1{20} mute 1{5} luka 11 tu 1 wan ``` Greedily match the appropriate numbers. `wan` doesn't need a space since it can only appear once. ``` ^$ ala ``` Fix `0` separately. [Answer] # [JavaScript (V8)](https://v8.dev/), ~~109~~ 96 bytes ``` x=>(g=s=>n=>(s+" ").repeat(x/n,x%=n))`ale`(100)+g`mute`(20)+g`luka`(5)+g`tu`(2)+g`wan`(1)||"ala" ``` [Try it online!](https://tio.run/##Tc7LCsIwEAXQvV8hAWGG@kgrajfpt2SQtFTTUPKoWfTfYyoI2Z17uQPzooXc046zPy1t6kWKooNBONGZDFexPcOzVbMiD/FijvEgDKIkrSTUnGM1yCn4HJqfdXiThNtGH3K54UMmb3FdGWliabaj8dADR9z9XRduCt/Lvi0Pro8y8fwJpi8 "JavaScript (V8) – Try It Online") [Answer] # Scratch, 46 blocks ``` set [output v] to [] // setup set [count v] to [1] if <(input) = [0]> then set [output v] to [ala] // 0 in toki pona else repeat [5] // every number word repeat ([floor v] of ((input) / (item (count) of [value v] // repeats every word in order set [output v] to (join (output) (item (count) of [number v] // the script that generates the number set [input v] to ((input) - (([floor v] of ((input) / (item (count) of [value v]))) * (item (count) of [value v]) // the script that updates the loop by finding a number end change [count v] by [1] // it makes sure that it will move on to the next word ``` [Try it online!](https://scratch.mit.edu/projects/566429457/) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 90 bytes ``` (n,r,t='0ala1wan2tu5luka20mute100ale'.match(n+'(\\D+)|$')[1])=>t?r?t+' '+f(r):t:f(n-1,-~r) ``` [Try it online!](https://tio.run/##jZDLDoIwEEX3fkUXJm3DsxijwSAb/0JcNFh8QWvKVDfGX8ciJOJjYZN2Med25mSO/MLrXB/O4Em1FU2RNES62oUEh7zk7MplBGZamhOPwsqAYKGtC@xXHPI9kQ4mWbZy6G2M6ZptaLKEVKfgYISdgmgaQ1wQ6THXu2va5ErWqhR@qXakICGidIHsCQJkZ43eKRtQa/FBowEF8wnnPbWwdUatvo396MMmsy77dBCD@Ov56m930Ln3n/64zQM "JavaScript (Node.js) – Try It Online") --- # [JavaScript (Node.js)](https://nodejs.org), 91 bytes ``` n=>'100ale 20mute 5luka 2tu 1wan'.replace(/(\d+)(\D+)/g,(_,a,b)=>b.repeat(n/a,n%=a))||'ala' ``` [Try it online!](https://tio.run/##jZBBDoIwEEX3nqIb0zYiLRijiSkrj0FiBihErYVAqxvujrWaoLBxkpnN@zP/Zy5why5vz41Z67qQQykGLRIccQ5KopjfrJFoq@wVUGwsih6gcdjKRkEuCSNpsaIkPa4oqwJyCiDIqEiyl0CCIZpBoJcCKO17DArwkNe6q5UMVV2RknBKD8gVY8jRxS@MRuhMJzAeobFTtn9Dx3x6H95ln1@JNjsv9f7ySz2O2XX3GR/7s/NHD08 "JavaScript (Node.js) – Try It Online") This solution may introduce a trailing space, while the first one won't. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 69 [bytes](https://github.com/abrudz/SBCS) ``` {×⍵:1↓∊(∊(⊂0 2∘⊤)@4⊢0 5 4 5⊤⍵)/' '(=⊂⊢)' ale mute luka tu wan'⋄'ala'} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/rw9Ee9W60MH7VNftTRpQHGXU0GCkaPOmY86lqi6WDyqGuRgYKpgomCKZAPVKupr66grmELVAWU0VRXSMxJVcgtLUlVyCnNTlQoKVUoT8xTf9Tdop6Yk6he@z/tUduER719j/qmevo/6mo@tN74UdtEIC84yBlIhnh4Bv8HCqQdWqFgoGCoYKRgZKFgaGyuYGhgYAAA "APL (Dyalog Unicode) – Try It Online") `×⍵` if `⍵` is positive: `' '(=⊂⊢)' ale ...'` split into a list of substrings, where each starts with a space. `0 5 4 5⊤⍵` Mixed radix decode, this results in a length 4 vector, where the first three are the 100, 20 and 5 places, and the fourth encodes the 1 and 2 places `∊(⊂0 2∘⊤)@4` split the last into two numbers `/` repeat each string from the previously generated list this many times `1↓∊` join into a single string and remove leading space `⋄'ala'` if the input was 0, return this string [Answer] # [Python 3](https://docs.python.org/3/), 143 142 132 bytes ``` def c(s): d,x={100:'ale',20:'mute',5:'luka',2:'tu',1:'wan'},'' if s==0:x+='ala' else: for i in d: x+=s//i*(d[i]+' ') s%=i print(x) ``` [Try it online!](https://tio.run/##JYzBCsIwDIbve4pcJK0rbFM8rNAnEQ9l7TA4u7G2OBGfvWaYQ/jy8f9Z3uk@h3Mpzo8wiCh1BU5t5tO1rUY7eVQnhmdOTBeNU35YVhpTRtVpfNmAX4VYAY0QjWn1VhvuWTZ@ip7fwTivQEAB3H4BB2LT0FG4K91qBJS7jQdDFSwrhSQ2Wf4wiH1TWHISkqf0ffkB "Python 3 – Try It Online") Previous submission: # [Python 3](https://docs.python.org/3/), 143 bytes ``` def c(s): if s==0: print('ala') else: d = {100:'ale',20:'mute',5:'luka',2:'tu',1:'wan'} for i in d: print(s//i*d[i],end=' ') s%=i ``` [Try it online!](https://tio.run/##LY3BCsIwEETv/Yq9yKZSaKp4aCBfIh5Ck@BiTUuTUET89rhB9zA8Zmdn11e6L@FcinUeJhFb1QB5iFpLJlg3CkmgmQ22Dbg5uupa0PAepFS8cNidGJ45MV0Uzvlh2FKYMnaDwt0E/PCNXzYgoAC2NvyLY9/T0V7p1rlgNUJ9AhAPmsovMImqFNacRMtTxrF8AQ "Python 3 – Try It Online") Thank you Jo King for pointing out non inclusion of whitespace emanresu A, have provided the links now Thank you Kevin Cruijssen and Jo King♦ for the `if s==0` contraction **Jo King♦'s solution:** # [Python 3](https://docs.python.org/3/), 116 bytes ``` def c(s,d={100:'ale',20:'mute',5:'luka',2:'tu',1:'wan'},x=''): for i in d:x+=s//i*(d[i]+' ');s%=i print(x or'ala') ``` [Try it online!](https://tio.run/##FYxLCsIwFAD3PcXbyEtsoK3ioik5ibgITYsPaxrywYh49hhnNcxi3Dved3suxSwrzCwIoz5D30vU24LiVOWZYrWLxC09dE0SY0IxSHxpi1@RFSKXDay7BwKyYGRuVeg6OjJzpVuLgHwKB0UNOE82sgy7r3uNvLCZ/QtZlyLjlTKO5Qc "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 191 bytes ``` def f(x): k=[[]]+[0]*x for i in range(1,1+x): for j,q in[[1,"wan"],[2,"tu"],[5,"luka"],[20,"mute"],[100,"ale"]]: if j<=i:p=k[i-j]+[q];k[i]=min(k[i]or p,p,key=len) return k[x]or["ala"] ``` [Try it online!](https://tio.run/##HY9BbsMgEEXX5hSIFU4mEjiqUqXhFt0hFpaKG4xDCAKFXKAH6BF7EXfw7s38mf9n4itf7@G4rl92ohOv/Zl0XmltzF4Ls6ukm@6JOuoCTWP4tlyC3G9TmzDDAyWtJbDnGJgBPQDLpcEbsKX4cesJYLeSbWMpsBgXZNNMOjfR@aLcOSqv3WHG2If5QDTq5gJvgDERInj7UosNPemSzSUF6nVFTaMZhqzPq1ss/UzFom2lCs/K3IVYMu9xJ6ZWV6Ds7@eXAd21X/tVEEkGMrwTeTwRPE38Aw "Python 3 – Try It Online") This is definitely not the shortest approach but it works in linear time using dynamic programming which was my intent. Even then, there is almost certainly a shorter linear approach, and more so probably a shorter dynamic programming method anyway. **Edit**: never mind, I'm pretty sure [this solution](https://codegolf.stackexchange.com/a/234997/68942) is straight up constant time. You may as well just go upvote that instead; I haven't golfed in a while and tunneled on the wrong approach. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 56 bytes ``` Nθ¿¬θala«F⪪”→"jρ§φ|XºM″℅^§¶⬤]r⊗x|K” ¿Σι≧÷Iιφ«×⁺ι ÷θφ≧﹪φθ ``` [Try it online!](https://tio.run/##XY/NagMxDITP3qcQPmnBhbb0J9BTaC85JISmL6Am3kREa2/WdnooeXZXS2gPvYiB0XwjbQ80biNJrYswlLwq/acf8dS@NNwBrmJW3cJ65JDRkpBVx0vy8N2YLo6Am0FYrbtbIPHwCH3JHh5AypHgHnLR8UXBOrBglTRRN6VHVr2kYZ4S78M77w8ZFyG/8Zl33sErpawrDjqtM7995nrGB/c@4VpKQr5iHfxl8TSF2ilm/vGXcVckqu1g@s9cmkutT8@zenOWHw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` ¿¬θala« ``` If `n` is zero then just print `ala`, otherwise: ``` F⪪”→"jρ§φ|XºM″℅^§¶⬤]r⊗x|K” ``` Split the compressed string `10 ale 5 mute 4 luka 2 tu 2 wan` on spaces and loop through the substrings. ``` ¿Σι ``` If this substring is numeric, ... ``` ≧÷Iιφ« ``` ... integer divide the predefined variable `1000` by its value, otherwise: ``` ×⁺ι ÷θφ ``` Integer divide the input by the predefined variable and print the space-suffixed current string that many times. ``` ≧﹪φθ ``` Reduce the input modulo the predefined variable. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 39 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` т20 5Y)vy‰`}).•Ð‰#¬êAš’ŒÞƒÜ•#ð«*J¨'ãà‚à ``` [Try it online](https://tio.run/##AU8AsP8wNWFiMWX//9GCMjAgNVkpdnnigLBgfSku4oCiw5DigLAjwqzDqkHFoeKAmcWSw57GksOc4oCiI8OwwqsqSsKoJ8Ojw6DigJrDoP//MTM3) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKS/f@LTUYGCqaRmpXFZZWPGjYk1GrqPWpYdHgCkK18aM3hVY5HFz5qmHl00uF5xyYdngOUUj684dBqLa9DK9QPLz684FHDrMML/uv8jzbQMdQx0jHVMTLQMbLQMTQA8o3NQbRBLAA). Uses the legacy version of 05AB1E (built in Python), because the new version of 05AB1E (built in Elixir) can't take the maximum on strings for \$n=0\$. This would be [**40 bytes** in the new version with an if/else construction](https://tio.run/##AU8AsP9vc2FiaWX//19pJ8Ojw6DDq9GCMjAgNVkpdnnigLBgfSku4oCiw5DigLAjwqzDqkHFoeKAmcWSw57GksOc4oCiI8OwwqvDl0rCqP//MTM3). **Explanation:** ``` т # Push 100 20 # Push 20 5 # Push 5 Y # Push 2 ) # Wrap all values into a list: [100,20,5,2] v # Foreach `y` over these values: y‰ # Divmod the (implicit) input or previous value by `y` ` # Pop and push the n//y and n%y separated to the stack }) # After the loop: wrap all values on the stack into a list .•Ð‰#¬êAš’ŒÞƒÜ• # Push compressed string "ale mute luka tu wan " # # Split it on spaces: ["ale","mute","luka","tu","wan",""] ð« # Append a space to each * # Repeat these strings the previous calculated values amount of times J # Join this list of strings to a single string ¨ # Remove the trailing space 'ãà‚ '# Pair it with dictionary string "ala" à # Pop and push the maximum string of this pair # (after which it is output implicitly as result) ``` [See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•Ð‰#¬êAš’ŒÞƒÜ•` is `"ale mute luka tu wan "` and `'ãà` is `"ala"`. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~44~~ 42 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` k♀I52ΓÉ‼/%]╖)☺ÿmuteÿluka╢→Γùwan▐ +m*y╡╖) ╙ ``` [Try it online.](https://tio.run/##y00syUjPz0n7/z/70cwGT1Ojc5MPdz5q2KOvGvto6jTNRzN2Hd6fW1qSenh/Tml24qOpix61TQIq2VmemPdo2gQF7VytykdTF4KUKjyaOvP/fwMuQy4jLlMuIwMuIwsuQwMg39gcRBsAAA) **Explanation:** ``` k # Push the input-integer ♀ # Push 100 I # Push 20 5 # Push 5 2 # Push 2 Γ # Wrap the top four values into a list: [100,20,5,2] É # Foreach over this list, using three characters as inner code-block: ‼ # Apply the following two characters separated to the stack / # Integer-divide % # Modulo ] # After the loop, wrap all (five) values on the stack into a list ╖)☺ # Push compressed string "ale" ÿmute # Push string "mute" ÿluka # Push string "luka" ╢→ # Push compressed string "tu" Γ # Wrap all four values into a list: ["ale","mute","luka","tu"] ùwan▐ # Append "wan": ["ale","mute","luka","tu","wan"] + # Append a space to each: ["ale ","mute ","luka ","tu ","wan "] m* # Repeat each string the values amount of times y # Join this list of strings together ╡ # Remove the trailing space ╖) # Push compressed string "ala" ╙ # Only leave the maximum of the top two strings on the stack # (after which the stack joined together is output implicitly as result) ``` [Answer] # TI-Basic, ~~163~~ ~~160~~ 152 bytes ``` "ale mutelukatu wan→Str2 {ᴇ2,20,5,2,1→A {3,4,4,2,3→B "ala→Str1 Input N If N:Then For(I,1,5 While N≥ʟA(I N-ʟA(I→N Str1+" "+sub(Str2,4I-3,ʟB(I→Str1 End End sub(Ans,5,length(Ans)-4 ``` -3 bytes for not storing the final output to `Str1`. -8 bytes thanks to [MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush). The output is stored in `Ans`. [Answer] # [jq](https://stedolan.github.io/jq/), ~~78~~ 77 bytes ``` ./100%.?*"ale "+./20%5*"mute "+./5%4*"luka "+.%5/2%5*"tu "+.%5%2*"wan"//"ala" ``` [Try it online!](https://tio.run/##JcxLCoNAEIThq0hDg5kU0w@dRVY5SHDRi2wSDQk4ePyJ4q4@Cv7Xry3x7VsWU@WcKOZnR9csrlwSLXU9WXhMNNd3HOIifrxrPcWeaIsP3TuRPRDULu2hMDgGjCiwfSrcYD7gpj79AQ "jq – Try It Online") A translation of dingledooper's Python approach. In jq, `/` division is floaty but `%` seems to floor the result: `123.789%100` is `23`. Thus we write something like `.%5/2%5` to get the amount of "tu"s. Slightly clever: `./100%.` will cause an error when the input is zero, and the `?` catches this and replaces with `null`, to which the `//` alternative-operator then provides `"ala"` as a fallback output. This is actually pretty useful because `""//"ala"` is not `"ala"` (i.e. `""` is not falsey in jq.) Michael Chatiskatzi saved a byte, by moving `?` around so that I don't need whitespace between `?` and `//`. Thanks! [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~118~~ 109 bytes ``` f(i){printf(i?(i-=99)>0?"ale ":(i+=80)>0?"mute ":(i+=15)>0?"luka ":(i+=3)>0?"tu ":"wan ":"ala");--i<1?:f(i);} ``` [Try it online!](https://tio.run/##jVHRboMgFH3vV9yYNIEqGa5Z1kqtH7L1gSB2ZNY2imkz46/PAaLuZckMXi7nwL2HgyBnIYahQAp3t1pV2mQZUiTd7/GRZgEvJQQJUmG6ow64tHpC4heHlO0n98jWAbo1y@DOKzvxkgeYEaIOcZbYNqwfTBu4cFUhDN0KzGcBLRvdvJ0ghY5GEEfwbMbOZNtXEyilPXN7xQevNyAfNym0zMcDrksEtqeddGujU@rEGUGesddZ8CWMJyz7jz/wSoprDchKV1UuH0YHZT49QKO@5LVAk0z85IHNjDAIQ7d7MmE2wlQazXD0ic2sf6BgnQM5glGs8UIW6PfKu2RKzU79VW0WmcC6we/WJ@kr9at@@BZFyc/NQO4/ "C (gcc) – Try It Online") New best for C. Thanks for Jo King finding 4 bytes for me. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 125 bytes ``` f=lambda n,b=1,l={1:'wan',2:'tu',5:'luka',20:'mute',100:'ale'}:n and(l[(a:=max(b for b in l if b<=n))]+' '+f(n-a,0))or'ala'*b ``` [Try it online!](https://tio.run/##DctBCsIwEEDRq8xuEhshrQhlaE4iLia0wWIyDSFFRTx77O6/xc@f@tjkMubSWnCRk58ZxHjXm@i@PeGLBc1AWHc0V8K4P/mwJUx7XdD09kiOC/5IgGVW8aaYXOK38hC2Ah5WgQhrAD850freIWAXlJzZWK23ctyMJ99yWaWqoIZR6/YH "Python 3.8 (pre-release) – Try It Online") Definitely not the shortest approach, but is the only recursive Python solution AFAIK. ## Explanation Takes in `n`, the number to translate, and two other utilities: `b` is used to indicate whether `ala` should be appended: it starts at 1 (if the original n is 0, then output `ala`, but is explicitly passed as 0 to exclude `ala` once `n` hits zero in a recursive call. An additional dictionary `l` is produced, with the numbers being mapped to the Toki Pona translations. In the body of the function, an `and` expression produces the translation with maxima if `n` is truthy, if n is zero then it jumps to the `or` expression and outputs `ala` or `''` depending on the value of `b`. This ends the recursion. If n is at least 1, we return the dictionary value with the maximal key below or equal to `n`, add a space, and then recall `f` with a reduced `n` accordingly. [Answer] # [Python 3](https://docs.python.org/3/), ~~154~~ 138 bytes ``` def f(n,p={100:'ale',20:'mute',5:'luka',2:'tu',1:'wan'},o=''): while n:t=[i for i in p if i<=n][0];n-=t;o+=p[t]+' ' return o[:-1]or'ala' ``` [Try it online!](https://tio.run/##JY7BCoMwEETP5iv2tkojJEppic2XiAehBkPtJoQNUkq/3aZ0DsNjDjMTX7wG6o/jvjhwNclo31opg/O2oOwKPDMXOhvc8mMukUHOKLXBfSb8yGARGyOqffXbAmTYjh5cSODBE0TwDvzN0jSqaaDW8hBONo48nRBQVGnhnAjCaFo9hVRWZzz@VdrE5IlrV//cU8xcN0WHElp0orsK3V9E@aq@ "Python 3 – Try It Online") -16 bytes thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king). --- This is an adaptation of [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)'s answer for Python 3 and with no space at the end: # [Python 3](https://docs.python.org/3/), 93 bytes ``` lambda n:(n//100*'ale '+n//20%5*'mute '+n//5%4*'luka '+n%5//2*'tu '+n%5%2*'wan ')[:-1]or'ala' ``` [Try it online!](https://tio.run/##LY1BCsIwFET3OUU24acRaZIaKgFPoi4iWlpMf0NJKJ4@/qKzGObBMJM@eVywq8PlVmOYH8/A0UtsW6O1ghBfHA5EVgunYC75z06cFMTyDjsKRwUFufxAUN4Ccmiu/mjuy0ozAeo2TrRmfFonzHKQu0@YSpYNqWpmmGX2zEzXMzrXXw "Python 3 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~138~~ \$\cdots\$ ~~121~~ 118 bytes ``` i;*v=L"\1\2\5\24d";f(n){n||puts("ala");for(i=4;~i;)n/v[i]?printf("wan \0$tu \0$$luka \0mute \0ale "+6*i),n-=v[i]:i--;} ``` [Try it online!](https://tio.run/##jZBbbsIwEEX/WcXIAsnOQ4SUPoSbdgPdAcmHlTjUajCIOIAK6dKbjvOiP5Vq2ePxXM/o6Kb@Jk2bRnHnGL2ReBGH8X0cLjPCc6rZRV@v@8qUlIhCEMbz3YGqaMm/FGd6flyr5HV/UNrklJyEhjiYmsrGaVF9CEy2lZF4iUICcR8cxTztR7ZtpXyf1w22wlYoTRlcJoDLFowsTblOIIJL4MHCgxD3E2Z3jxiCIKh5@zd9FwcH5HkvUyOzrqHl9MDS2MtUNrYULRHS9YpFutVvoeuw6j8O6UnQFqAWXelMnpEj4H36DKX6lLucDphs3hecscLBddvfgwmjETipM6OVEz6qg@mzDPwXQGLDbmJOf796l3DU6NRf00bIFcxKFlufZD@pntTNd5oXYlM2/ukH "C (gcc) – Try It Online") *Saved 4 bytes thanks to [ErikF](https://codegolf.stackexchange.com/users/79060/erikf)!!!* *Saved ~~14~~ 17 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!!* [Answer] # x86-16 machine code, PC DOS, 69 bytes ``` 00000000: be1c 01ba 2101 85db 740b 83c2 06ac 983b ....!...t......; 00000010: d872 f72b d8b4 09cd 2175 f3c3 6414 0502 .|.+....!u..d... 00000020: 0161 6c61 2024 2061 6c65 2024 206d 7574 .ala $ ale $ mut 00000030: 6520 246c 756b 6120 2474 7520 2420 2077 e $luka $tu $ w 00000040: 616e 2024 20 an $ ``` Listing: ``` BE 011C MOV SI, OFFSET V ; quantity values to [SI] BA 0121 MOV DX, OFFSET W ; quantity words to [DX] 85 DB TEST BX, BX ; check for zero case 74 0B JZ QOUT ; if zero, display 'ala' and exit QNEXT: 83 C2 06 ADD DX, 6 ; skip to next output string index AC LODSB ; next quantity to check into AL QLOOP: 98 CBW ; clear AH 3B D8 CMP BX, AX ; is input less than this quantity? 72 F7 JB QNEXT ; if so, check next lowest 2B D8 SUB BX, AX ; otherwise reduce input by quantity QOUT: B4 09 MOV AH, 9 ; display quantity string CD 21 INT 21H ; write to stdout 75 F3 JNZ QLOOP ; loop if value has not been reduced to zero C3 RET ; return to caller/DOS V DB 100, 20, 5, 2, 1 W DB 'ala $ ','ale $ ','mute $','luka $','tu $ ','wan $ ' ``` Callable function, input value in `BX` output to DOS `STDOUT`. Maybe not the most elegant or byte efficient way to handle output of the variable-length strings... Sample output using DEBUG (note input values are in hex): [![enter image description here](https://i.stack.imgur.com/Uwq8v.png)](https://i.stack.imgur.com/Uwq8v.png) [![enter image description here](https://i.stack.imgur.com/7qMl6.png)](https://i.stack.imgur.com/7qMl6.png) [Answer] # Excel, 116 bytes ## Formula, 83 bytes ``` =IF(A1,CONCAT(REPT(C1:C4,MOD(A1,D1:D4)/D2:D5))&IF(MOD(MOD(A1,5),2),"wan",""),"ala") ``` ## C1:D5, 33 bytes ``` C1: "ale " D1: =9^9 C2: "mute " D2: 100 C3: "luka " D3: 20 C4: "tu " D4: 5 D5: 2 ``` [Link to Spreadsheet](http://Link%20to%20Spreaadsheet) [Answer] # [Python 3](https://docs.python.org/3/), 117 bytes ``` lambda x:S(S(S(S(S(x*Q,Q*100,"ale "),Q*20,"mute "),Q*5,"luka "),Q*2,"tu ",),Q,"wan ")[:-1]or"ala" S,Q=str.replace,"q" ``` [Try it online!](https://tio.run/##NY3LDoIwEEX3fsVkVi0ZSQsxGhI@grBUF1UhNhaopUT8@joxmrs5Zx65/h3v01imvj4lZ4bLzcBateKfNWuoybRShMZ1gJKtYBmW@LMdoVse5rcijAsgMRO@zMjTY7XV5ynwu8FNS009x5CHzjtz7QifmPopgAXLtwo0FFAcQJd74E6F@eydjUJWPtgxCkvQiy9IKdMH "Python 3 – Try It Online") An obvious find and replace one. Confuses the syntax highlighter - `something or"string"` should be parsed the same as `something or "string"`, not `something o r"string"`. [Answer] # [Scala](https://scala-lang.org/), 303 bytes [Try it online!](https://tio.run/##VVA9b4MwEN3zK04Wg5041CB1qeJKHSO1U4cOURS5YBoDORA2LSrit1MHFKp48J39Pu7ZNlGlGqvPXCcO3pRB0J3TmFp4qWvox1RnkNETPu3RMdmvwK9v1QDKE04Hk1HcRezVWEeJ9yJMl1bPxBtZySt8eHeNwa8jZQs4qSIheCz4I495xMJfU38Yd95jqrswqxqtknOfKKtpwQ2Tz4t2Ni8hl/hQ3N2qzUZSS4L@FkoTTi6tu5ayLZQvrvXbj0LCqGEDkHXOQluXxtOBsDs3hK2EfP0/Ylg6FV6K@VGrGRhG3/jQQDvYbUGAqyAWgsH8H7WnuhJ9tkPQcQj6jHZsOE4DvXg1/gE) ``` def f(_n:Int)={ var n=_n if(n<1)List("ala")else{ var a=List[String]() List(100,20,5,2,1).zipWithIndex.foreach{case(k,i)=> val j=n/k a++=(s"${List("ale","mute","luka","tu","wan")(i)} "*j).split(" ") n -= j*k } a.mkString } } ``` Ungolfed version ``` object Main extends App { def f(_n: Int): String = { var n=_n if (n < 1) { val a = List("ala") a.mkString("") } else { var a = List[String]() val denominations = List(100, 20, 5, 2, 1) for ((k, i) <- denominations.zipWithIndex) { val j = n / k val word = List("ale", "mute", "luka", "tu", "wan")(i) val repeatedWord = s"$word " * j a ++= repeatedWord.split(" ") n -= j * k } a.mkString("") } } for (x <- 0 to 200) { println(s"[$x, ${f(x)}]") } } ``` [Answer] # [PHP](https://php.net/), 134 bytes ``` fn($x)=>$x?($g=fn($s,$n,&$y)=>str_repeat("$s ",$y/$n+0*$y%=$n))(ale,100,$x).$g(mute,20,$x).$g(luka,5,$x).$g(tu,2,$x).$g(wan,1,$x):ala; ``` [Try it online!](https://tio.run/##jY/hCsIgFIX/9xSXcQtXl9wWUbRWLxKEhGvQMmlK29MvJdakXwlXPH7Xc4@60v3@qCs9wbLoS8WwjYsDtkeG18LLhlDRDDt325jn@Sm1FIZF2EBE2HFUi2SO3bRAFcdM1JLSJCFnssQru1sjKfvK2t4ErQdlLGXD@SUUpV7sRC3yXl6qB2DJkhiWEJ1UlINbnDs4GVj6w5zFl2U/zNgRbUPGuY8IPhgYC6FHutoEnX62hLF53AJv9/Mg8efJH9W/AQ "PHP – Try It Online") This is the best I could do so far.. too bad `$x` has to be passed explicitly for a PHP arrow function to be able to modify it by reference.. [Answer] # [Perl 5](https://www.perl.org/), 85 bytes ``` $_="@{[map{$c=$F[0]/$_;$F[0]%=$_;(/\D+/g)x$c}qw(100ale 20mute 5luka 2tu 1wan)]}"||ala ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lbJoTo6N7GgWiXZVsUt2iBWXyXeGsxQtQWyNPRjXLT10zUrVJJrC8s1DA0MEnNSFYwMcktLUhVMc0qzExWMSkoVDMsT8zRja5VqahJzEv//N@Ay5DLiMrLgMjQ25wLqMQARxv/yC0oy8/OK/@smFuQAAA "Perl 5 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 111 bytes ``` t@((x,w):y)#n|n>=x=w++' ':t#(n-x)|1<2=y#n _#n="" f 0="ala" f n=zip[100,20,5,2,1](words"ale mute luka tu wan")#n ``` [Try it online!](https://tio.run/##FY3RCoIwFEDf/YrL9uCGt9iEoKRFP9AXiMQgJXHeRCfT8N@XvZ2HwzlvO3W1czH6uxALBlmsktNGN7OYkGUppIXngg6L3PQ1Nyun5MnJMJY0oAyzzv6JzLcdSq0U5gpPmKOuRPiMr2kXauhnX4ObOwt@hmCJ7YfY25bAQG@HB4hhbMkfGwmlPl9w7yjUqKr4Aw "Haskell – Try It Online") [Answer] # [PHP](https://php.net/), ~~108~~ 104 bytes ``` foreach([100=>ale,20=>mute,5=>luka,2=>tu,1=>wan]as$v=>$w)for(;$argn>=$v;$argn-=$v)$o.="$w ";echo$o?:ala; ``` [Try it online!](https://tio.run/##JYtBC8IgHMXvfooRHjZwoVYUme5UdAjaPSL@DGvRUtl0@/aZETze@/0Oz7Uu7iqX@m57DU2bXxilUkGnCU/7Dl6TlVRdeAHhUvlAmFQTmCsMeJQKT0U65gJD/zBK4vFPZaIC27mc4SmbCd20FttqCx2I@JOsPta3/fkkUDCD9jm2hYgUMcQRo4inbNAy8WKdnNKPdf5pzRDLwxc "PHP – Try It Online") I'm so super rusty at PHP on CG, but here it is just for fun... more or less a port of my other answer. Iterates through the each word's value and reduces the input number by that amount. Keeps reducing as long as the result is positive, each time adding the word to the output. Nothing fancy here, just the only operation used is subtraction. [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 76 bytes ``` ->\n {~flat(<ale mute luka tu wan>Zxx(n/100,n/20%5,n/5%4,n%5/2,n%2))||"ala"} ``` [Try it online!](https://tio.run/##Rc3BjoIwGATg8/IUE1a0JGiRUA/q@hLeNmbNn9huNvwUom2UVHx1hNMeZub2TauvvBk@EcJx@ysXd7IYs5DOy14Y/mthmBz2lu6gyjO08zU00@H78cCqbbirm8sWQmVlptL0@YyJKe6jusPc4GtYHk4W4TUpYk@sUXunwb4iOD99TZCwcp3nmZVFnqhxVFJmNlGyGLv4R4ddZJorfop8jRB93KhDPDsjGDE7p328i/rhDQ "Perl 6 – Try It Online") ]
[Question] [ # Introduction By definition, unique identifiers should be unique. Having multiple identifiers that are the same causes one to retrieve unexpected data. But with data arriving concurrently from multiple sources, it can be difficult to ensure uniqueness. Write a function the uniquifies a list of identifiers. This is possibly the worst puzzle fluff I have written, but you get the idea. # Requirements Given a list of zero or more positive integers, apply the following rules to each number from first to last: * If the number is the first of its kind, keep it. * If the number has previously been encountered, replace it with the lowest positive integer not found anywhere in the entire input list or any existing output. For the solution: * The solution may be a program or a function. * The input may be a string, an array, passed as arguments, or keyboard input. * The output may be a string, an array, or printed to the screen. * All numbers in the output list are distinct. # Assumptions * The input list is clean. It only contains positive integers. * A positive integer has the range from 1 to 231-1. * Less than 256 MB of memory is available for your program's variables. (Basically, no 2,147,483,648-element arrays are permitted.) # Test Cases ``` Input: empty Output: empty Input: 5 Output: 5 Input: 1, 4, 2, 5, 3, 6 Output: 1, 4, 2, 5, 3, 6 Input: 3, 3, 3, 3, 3, 3 Output: 3, 1, 2, 4, 5, 6 Input: 6, 6, 4, 4, 2, 2 Output: 6, 1, 4, 3, 2, 5 Input: 2147483647, 2, 2147483647, 2 Output: 2147483647, 2, 1, 3 ``` # Scoring Just a simple code golf. Lowest byte count by this time next week wins. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` {|∧ℕ₁}ᵐ≠ ``` [Try it online!](https://tio.run/nexus/brachylog2#@19d86hj@aOWqY@aGmsfbp3wqHPB///RZjpmOiZAaKRjFPs/CgA "Brachylog – TIO Nexus") ### Explanation ``` { }ᵐ Map on the Input: Input = Output… | …or… ∧ℕ₁ …Output is in [1,+inf) ≠ All elements of the output must be different (Implicit labeling) ``` [Answer] # Java 8, ~~158~~ 144 bytes ``` a->{int m=0;String r="",c=",",b=r;for(int x:a)b+=x+c;for(int x:a)if(r.contains(x+c)){for(;(r+b).contains(++m+c););r+=m+c;}else r+=x+c;return r;} ``` * `.contains(m+c);m++)` to `.contains(++m+c);)` to save 1 byte, and simultaneously converted to Java 8 to save 13 more bytes. **Explanations:** [Try it here.](https://tio.run/##lVDLboMwELznK0acbOGgJpCkquX@QXPpserBOKYiBYOMSVMhvp0akj5yK9LK8u7sjGd8lCe5rGptjof3QRWyafAkc9MtgNw4bTOpNPZjCzw7m5s3KOKRl1dIyv24X/ijcdLlCnsYCAxy@dj5FZTijl85VgQBUyJgAUuF5VllRxGcHyRNQ3EO1c0oz4iNVGWcd9IQj1LajTgnNkzpLxKGpcc45TYU/sZ7XTQa9iJotWutgeX9wEePdZsW3uPV6qnKDyi9Crk4nPJcY342TpdR1bqo9pArDDGRIkZ/YAre9XRK/o9NbDBjecWQMKwZNgwxw3YON2a3NYe7ZWMl36@v53DXq2SX3MfbZHfh/m3ne1hNIvHk5Ofr@kU/fAE) ``` a->{ // Method with integer-array parameter and String return-type int m=0; // Lowest integer String r="", // Result-String c=",", // Comma delimiter for result String b=r;for(int x:a)b+=x+c; // Input array as String for(int x:a) // Loop (2) over the integers in the array if(r.contains(x+c)){ // If the result already contains this integer for(;(r+b).contains(++m+c);); // Inner (3) as long as either the result-String or array-String contains the lowest integer // and raise the lowest integer before every iteration by 1 r+=m+c; // Append the result with this lowest not-present integer }else // Else: r+=x+c; // Append the result-String with the current integer // End of loop (2) (implicit / single-line body) return r; // Return the result-String } // End of method ``` [Answer] ## JavaScript (ES6), 49 bytes ``` a=>a.map(g=(e,i)=>a.indexOf(e)-i?g(++n,-1):e,n=0) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 63 bytes ``` ->a{r=*0..a.size;r.map{|i|[a[i]]-a[0,i]==[]?a[i]=(r-a)[1]:0};a} ``` [Try it online!](https://tio.run/nexus/ruby#S7ON@a9rl1hdZKtloKeXqFecWZVqXaSXm1hQXZNZE50YnRkbq5sYbaCTGWtrGx1rDxKw1SjSTdSMNoy1Mqi1Tqz9X6CQppecmJOjkFqWmKORnlpSrPk/2kxHAYhMwMgIiGIB "Ruby – TIO Nexus") **Explanation** ``` ->a{ # Anonymous function with one argument r=*0..a.size; # Numbers from 0 to array size r.map{|i| # For all numbers in range: [a[i]] # Get array with just a[i] -a[0,i] # Remove elements from array that are # also in a[0..i-1] ==[]? # Check if result is an empty array a[i]= # If true, set a[i] to: (r-a) # Remove elements from number range # that are also in input array [1] # Get second element (first non-zero) :0}; # If false, no-op a} # Return modified array ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ ~~16~~ 18 bytes ``` vy¯yåi¹gL¯K¹K¬}ˆ}¯ ``` [Try it online!](https://tio.run/nexus/05ab1e#@19WeWh95eGlmYd2pvscWu99aKf3oTW1p9tqD63//z/aTEcBiAx1FIx0FIx1FEx0FExjAQ "05AB1E – TIO Nexus") **Explanation** ``` v # for each y in input y # push y ¯yåi # if y exist in global list ¹gL # push [1 ... len(input)] ¯K # remove any number that is already in global list ¹K # remove any number that is in the input ¬ # get the first (smallest) } # end if ˆ # add to global list }¯ # end loop, push and output global list ``` [Answer] # PHP, 121 Bytes ``` <?$n=array_diff(range(0,count($g=$_GET)),$g);sort($n);$r=[];foreach($g as$v)$r[]=in_array($v,$r)?$n[++$i]:$v;print_r($r); ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/ac8f845cbf1efcffbc7bfcd1f13d2673e56da855) Expanded ``` $n=array_diff(range(0,count($g=$_GET)),$g); # create array of ascending values which are not in input array plus zero sort($n); # minimize keys $r=[]; # empty result array foreach($g as$v) # loop input array $r[]=in_array($v,$r)?$n[++$i]:$v; # if value is not in result array add value else take new unique value skip zero through ++$i print_r($r); # output result array ``` [Answer] # Python 2, 77 79 bytes ``` a=input();u=[];j=1 for x in a: u+=[[x,j][x in u]] while j in u+a:j+=1 print u ``` Takes keyboard input, like `[3, 3, 3, 3, 3, 3]`. Just keep track of the smallest positive integer `j` not used so far. For each element `x` of the input, output `x` if `x` hasn't already been used, otherwise output `j`. Finally, update `j` each time you output something. EDITED: to fix a mistake handling input of `[6, 6, 4, 4, 2, 2]`. Thanks to @Rod for pointing out the mistake as well as a fix. The mistake was that, in the event of a duplicate entry, it would output the smallest number unused to that point in the list, even if that output appeared later in the input. (This was wrong, as clarified in the post and the comments, but I still messed it up somehow.) Anyway, the fix was to simply add the input list, `a`, to the set of values that could not be output in that case. [Answer] # [Haskell](https://www.haskell.org/), ~~79~~ 76 bytes EDIT: * -3 bytes: @nimi saw that `head` could be replaced by a pattern match. `([]#)` is an anonymous function taking and returning a list. Use like `([]#)[2147483647, 2, 2147483647, 2]`. ``` (?)=notElem s#(x:y)|z:_<-[x|x?s]++filter(?(s++y))[1..]=z:(z:s)#y _#n=n ([]#) ``` [Try it online!](https://tio.run/nexus/haskell#TYzLCoMwEEX3@YqAXSQYAz5bQlNXXXTdZQgibWwDGouxVMV/t0EXLczAnXMP05TacG161ZW3fvc2tTbK0qZ8IftsP7SiqFPlnbFr32nzCE7i4tyH6iTGdHUXlGNu2v5cqwZYDw1sxPPEimMghnnIrfT9StfuP8qR9f0RYxFSKvnE0MQs9kZQeIYbUHEkpIeXRUggUrchgQmBEYEpgTGBmUPxmn7jUOaaVdzcyKEoTPbJIc6S/Yb@Twm@ "Haskell – TIO Nexus") # How it works * `?` is an abbreviated operator for checking if an element is absent from a list. * `s#l` handles the list of integers `l`, given a list `s` of integers already used. + `x` is the next integer to look at, `y` the remaining ones. + `z` is the integer chosen for the next spot. It's `x` if `x` is not an element of `s`, and the first positive integer neither in `s` nor in `y` otherwise. + `(z:s)#y` then recurses with `z` added to the used integer list. + `n` is an empty list, since nonempty lists have been handled in the previous line. * The main function `([]#)` takes a list, and calls `#` with it as second argument, and an empty list for the first argument. [Answer] # APL (Dyalog 16.0), 34 bytes ``` (s↑v~⍨⍳⌈/v+s←+/b←(⍳≢v)≠⍳⍨v)@{b}v←⎕ ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~21~~ 20 bytes ``` ~~.b?}NPY@-UhlQQ=hZNQ.\_~~ m?}edPd@-SlQQ~hZed._ ``` [Test suite](http://pyth.herokuapp.com/?code=m%3F%7DedPd%40-SlQQ~hZed._&test_suite=1&test_suite_input=%5B%5D%0A%5B5%5D%0A%5B1%2C+4%2C+2%2C+5%2C+3%2C+6%5D%0A%5B3%2C+3%2C+3%2C+3%2C+3%2C+3%5D%0A%5B6%2C+6%2C+4%2C+4%2C+2%2C+2%5D%0A%5B2147483647%2C+2%2C+2147483647%2C+2%5D&debug=0) I'll add an explanation when I have the time. [Answer] ## [C#](http://csharppad.com/gist/1516db3895c9899055e5a1571c20e86b), 135 bytes --- ### Golfed ``` (int[] i)=>{for(int x=1,v,m=0,l=i.Length,y;x<l;x++){v=i[x];for(y=0;y<l&&v==i[x]?y<x:y<l;y++)if(i[y]==v){v=++m;y=-1;}i[x]=v;}return i;}; ``` --- ### Ungolfed ``` ( int[] i ) => { for( int x = 1, v, m = 0, l = i.Length, y; x < l; x++ ) { v = i[ x ]; for( y = 0; y < l && v == i[ x ] ? y < x : y < l ; y++ ) if( i[ y ] == v ) { v = ++m; y = -1; } i[ x ] = v; } return i; }; ``` --- ### Ungolfed readable ``` // Takes an array of Int32 objects ( 32-byte signed integers ) ( int[] i ) => { // Cycles through each element on the array // x: Scan position, starts at the 2nd element // v: Value being processed // m: The next minimum value to replace // l: Size of the array, to save some byte count for( int x = 1, v, m = 0, l = i.Length, y; x < l; x++ ) { // Hold the value v = i[ x ]; // Re-scan the array for a duplicate value up the the current position ( 'x' ) IF // ... the currently hold value hasn't been modified // ... otherwise, re-scans the entire array to find a suitable value to replace for( y = 0; y < l && v == i[ x ] ? y < x : y < l ; y++ ) // Check if 'v' shares the same value with other element if( i[ y ] == v ) { // Set 'v' to the minimum value possible v = ++m; // Reset the scan position to validate the new value y = -1; } // Set the 'v' to the array i[ x ] = v; } // Return the array return i; }; ``` --- ### Full code ``` using System; using System.Collections.Generic; namespace Namespace { class Program { static void Main( String[] args ) { Func<Int32[], Int32[]> f = ( int[] i ) => { for( int x = 1, v, m = 0, l = i.Length, y; x < l; x++ ) { v = i[ x ]; for( y = 0; y < l && v == i[ x ] ? y < x : y < l ; y++ ) if( i[ y ] == v ) { v = ++m; y = -1; } i[ x ] = v; } return i; }; List<Int32[]> testCases = new List<Int32[]>() { new Int32[] { }, new Int32[] { 5 }, new Int32[] { 1, 4, 2, 5, 3, 6 }, new Int32[] { 3, 3, 3, 3, 3, 3 }, new Int32[] { 6, 6, 4, 4, 2, 2 }, new Int32[] { 2147483647, 2, 2147483647, 2 }, }; foreach( Int32[] testCase in testCases ) { Console.WriteLine( $" Input: {String.Join( ",", testCase )}\nOutput: {string.Join( ",", f( testCase ) )}\n" ); } Console.ReadLine(); } } } ``` --- ### Releases * **v1.0** - `135 bytes` - Initial solution. --- ### Notes * None [Answer] # [Python 2](https://docs.python.org/2/), 101 bytes ``` x=input() for i,n in enumerate(x):x[i]=[n,list(set(range(1,len(x)+9))-set(x))[0]][n in x[:i]] print x ``` [Try it online!](https://tio.run/nexus/python2#HYxBCsJADADvfcUeE4ygRQoW@pKQQw9RAjWWbQr5/bbK3GZgWk7m6x6A3etbi5EX86K@f7TOoZA4JptM7LTYFrBpQJ39rXCnRf3slyfi9acTkW8i/D8kjybSrdU8SrbGAw30OOmplwM "Python 2 – TIO Nexus") or [Try all test cases](https://tio.run/nexus/python2#hZBPa8QgEMXv@RRzWVbpFGrium0gxz301FsvrofQmCKkRoyBfPusfwrb0kNBcd7Ph8@ZfdAjjGSjbQXj7MGgBWNB2/VL@z7ocgOwSaM6aXEySyCLDsT39lMThpO20fPwQuljwhul8kkpmV/ZZGuUqsDrsPood@M6KRXKU9wMgSPUCCeEBkFE1OTqviIS8SYbi7eOqGb8zJ8bwc8F/ZQxbf43g2XEMxUloxib4v2bwdJnVJUGFFJjpXmRRuO8sQGOr9atAVo4LFf7toa7uGxOfwQ9wC/63k9m@K6v9nggxsmgcCwnxTnLLLouC7rfAA "Python 2 – TIO Nexus") [Answer] # [R](https://www.r-project.org/), 39 ~~46~~ bytes Creates a vector from the input, then replaces the duplicated values with a range from 1 to a million that has the input values removed. Returns a numeric vector. No input will return the empty vector numeric(0). ``` i[duplicated(i)]=(1:1e6)[-(i=scan())];i ``` [Try it online!](https://tio.run/nexus/r#@58ZnVJakJOZnFiSmqKRqRlrq2FoZZhqphmtq5FpW5ycmKehqRlrnfnfTMFMwQQIjRSM/gMA "R – TIO Nexus") This will throw a warning about the length of the replacement vector ``` i=scan() # set i as input (1:1e6) # 1 to a million (could go higher) (1:1e6)[-(i=scan())] # without input values duplicated(i) # duplicate values in i i[duplicated(i)]=(1:1e6)[-(i=scan())] # set duplicate i values to reduced range vector ;i # return result ``` [Answer] # C, ~~169 bytes~~ 133 bytes input = array a, output = modified array a ``` i=1,j,k,l;void f(int*a,int n){for(;i<n;i++)for(j=i-1;j>=0;j--)if(a[i]==a[j]){l=1;for(k=0;k<n;)if(l==a[k])k=l++?0:0;else k++;a[i]=l;}} ``` formatted ``` int i, j, k, l; void f(int* a, int n) { for (i = 1; i<n; i++) for (j = i - 1; j >= 0; j--) if (a[i] == a[j]) { l = 1; for (k = 0; k<n;) if (l == a[k]) k = l++ ? 0 : 0; else k++; a[i] = l; } } ``` Too many bytes wasted for these loop. Does anybody think of shorten the code by inventing a new algorithm (which use less loop)? I was thinking but havent found one. [Answer] # C# 7, 116 bytes ``` int[]f(int[]c){int j=0;int h()=>c.Contains(++j)?h():j;return c.Select((e,i)=>Array.IndexOf(c,e)<i?h():e).ToArray();} ``` **Indented** ``` int[] f(int[] c) { int j = 0; int h() => c.Contains(++j) ? h() : j; return c .Select((e, i) => Array.IndexOf(c, e) < i ? h() : e) .ToArray(); } ``` **Explained** * first occurrence of a number is always left as-is * consecutive occurrences of a number are drawn from `[1, 2, 3, ...]`, skipping values present in the input. **[Online Version](https://dotnetfiddle.net/LuEgXM)** [Answer] ## Clojure, 72 bytes ``` #(reduce(fn[r i](conj r(if((set r)i)(nth(remove(set r)(range))1)i)))[]%) ``` A basic reduction. If `i` is contained in the output list so far, we'll take the 2nd element (1 when 0-indexed) from the infinite list of integers `(range)` from which we have removed those numbers that have already been used. Range starts from zero so we cannot take the first element but the second. [Answer] # R, 74 bytes reads the list from stdin; returns NULL for an empty input. ``` o=c();for(i in n<-scan())o=c(o,`if`(i%in%o,setdiff(1:length(n),o)[1],i));o ``` explanation: ``` o=c() #initialize empty list of outputs for(i in n<-scan()) # loop through the list after reading it from stdin o=c(o, # set the output to be the concatenation of o and `if`(i%in%o, # if we've seen the element before setdiff(1:length(n),o)[1] # the first element not in 1,2,... ,i)) # otherwise the element o # print the output ``` `1:length(n)` may be used since we are guaranteed to never need a replacement from outside that range. [Try it online!](https://tio.run/nexus/r#FcnBCoAgDADQX9lF2MAORnjI@pIIDNMaxAbZ/1vxjq/pnJBC0RsZWECmrqZNkOgPtZFLRDYsRm3Nz86loBuvLMdzopBVWtxqmSho8@Bh@PTQtxc) [Answer] # Axiom, 169 bytes ``` f a==(r:List INT:=[];for i in 1..#a repeat(~member?(a.i,r)=>(r:=concat(r,a.i));for j in 1..repeat if~member?(j,r)and(~member?(j,a)or j=a.i)then(r:=concat(r,j);break));r) ``` ungolf and result ``` ff(a)== r:List INT:=[] for i in 1..#a repeat ~member?(a.i,r)=>(r:=concat(r,a.i)) for j in 1.. repeat if~member?(j,r)and(~member?(j,a) or j=a.i)then(r:=concat(r,j);break) r (3) -> f([]) (3) [] Type: List Integer (4) -> f([5]) (4) [5] Type: List Integer (5) -> f([1,4,2,5,3,6]) (5) [1,4,2,5,3,6] Type: List Integer (6) -> f([3,3,3,3,3,3]) (6) [3,1,2,4,5,6] Type: List Integer (7) -> f([6, 6, 4, 4, 2, 2]) (7) [6,1,4,3,2,5] Type: List Integer (8) -> f([2147483647, 2, 2147483647, 2]) (8) [2147483647,2,1,3] Type: List Integer ``` ]
[Question] [ # Text to DNA golf ## Challenge Convert input into a DNA output. ## Algorithm * Convert text into ASCII code points (e.g. `codegolf` -> `[99, 111, 100, 101, 103, 111, 108, 102]`) * String the ASCII codes together (e.g. `99111100101103111108102`) * Convert to binary (e.g. `10100111111001101001011010001000011001101011011110000110010111111011000000110`) * Pad `0`s onto the end to make an even number of characters (e.g. `101001111110011010010110100010000110011010110111100001100101111110110000001100`) * Replace `00` with `A`, `01` with `C`, `10` with `G`, and `11` with `T` (e.g. `GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA`) * Output ## Test Cases ``` codegolf > GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA ppcg > GGCTAATTGTCGCACTT } > TTGG (padding) ``` ## Specifications * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") * Your program must accept spaces in input. * Your program must work for `codegolf`. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~15~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` OVBs2UḄị“GCTA ``` [Try it online!](http://jelly.tryitonline.net/#code=T1ZCczJV4biE4buL4oCcR0NUQQ&input=&args=J2NvZGVnb2xmJw) or [verify all test cases](http://jelly.tryitonline.net/#code=T1ZCczJV4biE4buL4oCcR0NUQeKAnQrDh-KCrGrigbc&input=&args=J2NvZGVnb2xmJywgJ3BwY2cnLCAnfSc). ### How it works ``` OVBs2UḄị“GCTA Main link. Argument: s (string) O Ordinal; replace each character with its code point. V Eval. This converts the list to a string before evaluating, so it returns the integer that results of concatenating all the digits. B Binary; convert from integer to base 2. s2 Split into chunks of length 2. U Upend; reverse the digits of each chunk. Reversing means that we would have to conditionally PREPEND a zero to the last chunk, which makes no difference for base conversion. Ḅ Unbinary; convert each chunk from base 2 to integer. `UḄ' maps: [0, 1 ] -> [1, 0] -> 2 [1, 0(?)] -> [0(?), 1] -> 1 [1, 1 ] -> [1, 1] -> 3 [0, 0(?)] -> [0(?), 0] -> 0 ị“GCTA Replace each number by the character at that index. Indexing is 1-based, so the indices are [1, 2, 3, 0]. ``` [Answer] ## CJam, ~~24~~ 23 bytes *Thanks to Dennis for saving 1 byte in a really clever way.* :) ``` l:isi2b2/Wf%2fb"AGCT"f= ``` [Test it here.](http://cjam.aditsu.net/#code=l%3Aisi2b2%2FWf%252fb%22AGCT%22f%3D&input=codegolf) ### Explanation Very direct implementation of the specification. The only interesting bit is the padding to an even number of zeros (which was actually Dennis's idea). Instead of treating the digits in each pair in the usual order, we make the second bit the most significant one. That means, ending in a single bit is identical to appending a zero to it, which means we don't have to append the zero at all. ``` l e# Read input. :i e# Convert to character codes. si e# Convert to flat string and back to integer. 2b e# Convert to binary. 2/ e# Split into pairs. Wf% e# Reverse each pair. 2fb e# Convert each pair back from binary, to get a value in [0 1 2 3]. "AGCT"f= e# Select corresponding letter for each number. ``` [Answer] # Python 2, ~~109~~ 103 bytes ``` lambda s,j=''.join:j('ACGT'[int(j(t),2)]for t in zip(*[iter(bin(int(j(`ord(c)`for c in s))*2)[2:])]*2)) ``` Test it on [Ideone](http://ideone.com/pp9MHm). [Answer] # Ruby, 59 bytes ``` $_='%b0'.%$_.bytes*'' gsub(/../){:ACGT[$&.hex%7]} chomp'0' ``` A full program. Run with the `-p` flag. [Answer] # Python 3, 126 bytes ``` lambda v:"".join(["ACGT"[int(x,2)]for x in map(''.join,zip(*[iter((bin(int("".join([str(ord(i))for i in v])))+"0")[2:])]*2))]) ``` [Answer] # Python 3, 130 bytes. Saved 2 bytes thanks to vaultah. Saved 6 bytes thanks to Kevin Lau - not Kenny. I hate how hard it is to convert to binary in python. ``` def f(x):c=bin(int(''.join(map(str,map(ord,x)))))[2:];return''.join('ACGT'[int(z+y,2)]for z,y in zip(*[iter(c+'0'*(len(c)%2))]*2)) ``` Test cases: ``` assert f('codegolf') == 'GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA' assert f('ppcg') == 'GGCTAATTGTCGCACTT' ``` [Answer] # Ruby, 80 bytes ``` ->s{s=s.bytes.join.to_i.to_s 2;s+=?0*(s.size%2) s.gsub(/../){"ACGT"[$&.to_i 2]}} ``` [Answer] # Mathematica, 108 bytes ``` {"A","C","G","T"}[[IntegerDigits[Mod[Floor@Log2@#,2,1]#&@FromDigits[""<>ToString/@ToCharacterCode@#],4]+1]]& ``` Takes a string as input, and outputs a list of bases. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes ``` Cṅb₅∷[0J]B`ACGT`τ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=C%E1%B9%85b%E2%82%85%E2%88%B7%5B0J%5DB%60ACGT%60%CF%84&inputs=%7D&header=&footer=) A mess. ``` C # Charcodes ṅ # Concatenated b # To binary ₅∷[ ] # If length is odd 0J # Append a 0 B # To base10 `ACGT`τ # Convert to custom base `ACGT` (convert to base4, replace 0-3 with corresponding item of "ACGT") ``` [Answer] # Pyth, 25 bytes ``` sm@"ACGT"id2Pc.B*4sjkCMQ2 ``` [Try it here!](http://pyth.herokuapp.com/?code=sm%40%22ACGT%22id2Pc.B*4sjkCMQ2&input=%22codegolf%22&test_suite_input=%22codegolf%22%0A%22ppcg%22&debug=0) ### Explanation Burrowing the padding trick from [Martins CJam answer](https://codegolf.stackexchange.com/a/79170/49110). ``` sm@"ACGT"id2Pc.B*4sjkCMQ2 # Q = input CMQ # Map each character of Q to its character code sjk # Join into one string and convert to an integer .B*4 # Mulitply with 4 and convert to binary c 2 # Split into pairs P # Discard the last pair m # Map each pair d id2 # Convert pair from binary to decimal @"ACGT" # Use the result ^ as index into a lookup string s # Join the resulting list into on string ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 23 bytes Code: ``` SÇJb00«2÷¨C3210"TGCA"‡á ``` Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=U8OHSmIwMMKrMsO3wqhDMzIxMCJUR0NBIuKAocOh&input=cHBjZw). [Answer] # Java, 194 bytes ``` String a(int[]a){String s="",r=s;for(int i:a)s+=i;s=new BigInteger(s).toString(2)+0;for(int i=0,y,n=48;i<(s.length()/2)*2;r+=s.charAt(i++)==n?y==n?'A':'G':y==n?'C':'T')y=s.charAt(i++);return r;} ``` ### Ungolfed ``` String a(int[] a) { String s = "", r = s; for (int i : a) s += i; s = new BigInteger(s).toString(2) + 0; for (int i = 0, y, n = 48; i < (s.length() / 2) * 2; r += s.charAt(i++) == n ? y == n ? 'A' : 'G' : y == n ? 'C' : 'T') y = s.charAt(i++); return r; } ``` ### Note * Input is an array of chars (which should count as a form of String), parameter is of type `int[]` because thats one byte saved over `char[]`. ### Output ``` Input: codegolf Output: GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA Input: . Output: GTG Input: } Output: TTGG Input: wow Output: TGATAGTTGTGCTG Input: programming puzzles Output: GTGTCAGAGTTGAAGGCCGTTCCGCAGTGCATTTGGCTCGTCTGGTGTCTACTAGCCTGCGAGAGGAGTTACTTTGGATCCTTGACTTGT ``` [Answer] # Python 2.7, 135 bytes ``` def f(A):g=''.join;B=bin(int(g(map(str,map(ord,A)))))[2:];B+=len(B)%2*'0';return g('ACGT'[int(B[i:i+2],2)] for i in range(len(B))[::2]) ``` Ungolfed: ``` def f(A): g = ''.join B = bin(int(g(map(str,map(ord,A)))))[2:] # convert string input to binary B += len(B)%2 * '0' # add extra 0 if necessary return g('ACGT'[int(B[i:i+2],2)] for i in range(len(B))[::2]) # map every two characters into 'ACGT' ``` # Output ``` f('codegolf') 'GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA' ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 21 bytes ``` 'CGTA'joV4Y2HZa2e!XB) ``` [**Try it online!**](http://matl.tryitonline.net/#code=J0NHVEEnam9WNFkySFphMmUhWEIp&input=Y29kZWdvbGY) ### Explanation ``` 'CGTA' % Push string to be indexed into j % Take input string o % Convert each char to its ASCII code V % Convert to string (*). Numbers are separated by spaces 4Y2 % Push the string '0123456789' H % Push number 2 Za % Convert string (*) from base '0123456789' to base 2, ignoring spaces 2e % Reshape into a 2-column matrix, padding with a trailing 0 if needed ! % Transpose XB % Convert from binary to decimal ) % Index into string with the DNA letters. Indexing is 1-based and modular ``` [Answer] # [Factor](https://factorcode.org/) + `grouping.extras`, 95 bytes ``` [ [ present ] f map-as concat dec> >bin 2 48 pad-groups 2 group [ bin> "ACGT" nth ] "" map-as ] ``` Doesn't work on TIO because `pad-groups` postdates build 1525, the one TIO uses. Here's a picture of running it in build 2101: [![enter image description here](https://i.stack.imgur.com/ICdtC.png)](https://i.stack.imgur.com/ICdtC.png) There is no build where whitespace can be omitted after strings and `pad-groups` exists, but `pad-groups` makes it worth it. ## Explanation: It's a quotation (anonymous function) that accepts a string from the data stack as input and leaves a string on the data stack as output. Assuming `"ppcg"` is on the data stack when this quotation is called... | Snippet | Output | | --- | --- | | `[ present ] f map-as` | `{ "112" "112" "99" "103" }` | | `concat` | `"11211299103"` | | `dec>` | `11211299103` | | `>bin` | `"1010011100001111101101100100011111"` | | `2 48 pad-groups` | `"1010011100001111101101100100011111"` (append zeros so length is divisible by 2.) | | `2 group` | `{ "10" "10" "01" "11" "00" "00" "11" "11" "10" "11" "01" "10" "01" "00" "01" "11" "11" }` | | `[ bin> ] map` | `{ 2 2 1 3 0 0 3 3 2 3 1 2 1 0 1 3 3 }` | | `[ "ACGT" nth ] "" map-as` | `"GGCTAATTGTCGCACTT"` | [Answer] # [Pyth](https://github.com/isaacg1/pyth), 23 bytes ``` sm@"AGCT"i_d2c.BsjkCMQ2 ``` [Try it online!](http://pyth.herokuapp.com/?code=sm%40%22AGCT%22i_d2c.BsjkCMQ2&input=%22codegolf%22&test_suite_input=%22codegolf%22%0A%22ppcg%22&debug=0) ### Explanation Borrowing the trick from [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/79178/48934). ``` sm@"AGCT"i_d2c.BsjkCMQ2 CMQ convert each character to its byte value sjk convert to a string and then to integer .B convert to binary c 2 chop into pairs m d for each pair: _ reverse it i 2 convert from binary to integer @"AGCT" find its position in "AGCT" s join the string ``` [Answer] # Groovy, 114 bytes ``` {s->'ACGT'[(new BigInteger(((Byte[])s).join())*2).toString(2).toList().collate(2)*.with{0.parseInt(it.join(),2)}]} ``` Explanation: ``` {s-> 'ACGT'[ //access character from string (new BigInteger( //create Big Integer from string ((Byte[])s).join() //split string to bytes and then join to string ) * 2) //multiply by 2 to add 0 at the end in binary .toString(2) //change to binary string .toList() //split to characters .collate(2) //group characters by two *.with{ 0.parseInt(it.join(),2) //join every group and parse to decimal } ] } ``` [Answer] # Julia 0.4, 77 bytes ``` s->replace(bin(BigInt(join(int(s)))),r"..?",t->"AGCT"[1+int("0b"reverse(t))]) ``` This anonymous function takes a character array as input and returns a string. [Try it online!](http://julia.tryitonline.net/#code=ZiA9IHMtPnJlcGxhY2UoYmluKEJpZ0ludChqb2luKGludChzKSkpKSxyIi4uPyIsdC0-IkFHQ1QiWzEraW50KCIwYiJyZXZlcnNlKHQpKV0pCgpwcmludGxuKGYoWyJjb2RlZ29sZiIuLi5dKSkKcHJpbnRsbihmKFsicHBjZyIuLi5dKSkKcHJpbnRsbihmKFsifSIuLi5dKSk) [Answer] # Javascript ES7, ~~105~~ 103 bytes ``` s=>((+[for(c of s)c.charCodeAt()].join``).toString(2)+'0').match(/../g).map(x=>"ACGT"['0b'+x-0]).join`` ``` The ES7 part is the `for(c of s)` part. ## ES6 version, ~~107~~ 105 bytes ``` s=>((+[...s].map(c=>c.charCodeAt()).join``).toString(2)+'0').match(/../g).map(x=>"ACGT"['0b'+x-0]).join`` ``` ## Ungolfed code ``` dna = (str)=>{ var codes = +[for(c of str)c.charCodeAt()].join``; var binaries = (codes.toString(2)+'0').match(/../g); return binaries.map(x=>"ACGT"['0b'+x-0]).join`` } ``` This is my first try at golfing on PPCG, feel free to correct me if something's wrong. Thanks @AlexA for the small improvement. [Answer] # J, 52 bytes ``` 3 :'''ACGT''{~#._2,\#:".,&''x''":(,&:(":"0))/3&u:y' ``` Usage: `3 :'''ACGT''{~#._2,\#:".,&''x''":(,&:(":"0))/3&u:y' 'codegolf'` ==> `GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA` [Answer] ## [Hoon](https://github.com/urbit/urbit), ~~148~~ 138 bytes ``` |* * =+ (scan (reel +< |=({a/@ b/tape} (weld <a> b))) dem) `tape`(flop (turn (rip 1 (mul - +((mod (met 0 -) 2)))) |=(@ (snag +< "ACGT")))) ``` "abc" is a list of atoms. Interpolate them into strings (`<a>`) while folding over the list, joining them together into a new string. Parse the number with `++dem` to get it back to an atom. Multiply the number by (bitwise length + 1) % 2 to pad it. Use `++rip` to disassemble every two byte pair of the atom into a list, map over the list and use the number as an index into the string "ACGT". ``` > =a |* * =+ (scan (reel +< |=({a/@ b/tape} (weld <a> b))) dem) `tape`(flop (turn (rip 1 (mul - +((mod (met 0 -) 2)))) |=(@ (snag +< "ACGT")))) > (a "codegolf") "GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA" > (a "ppcg") "GGCTAATTGTCGCACTT" > (a "}") "TTGG" ``` [Answer] ## Common Lisp (Lispworks), 415 bytes ``` (defun f(s)(labels((p(e f)(concatenate'string e f)))(let((b"")(d""))(dotimes(i(length s))(setf b(p b(write-to-string(char-int(elt s i))))))(setf b(write-to-string(parse-integer b):base 2))(if(oddp #1=(length b))(setf b(p b"0")))(do((j 0(+ j 2)))((= j #1#)d)(let((c(subseq b j(+ j 2))))(cond((#2=string="00"c)(setf d(p d"A")))((#2#"01"c)(setf d(p d"C")))((#2#"10"c)(setf d(p d"G")))((#2#"11"c)(setf d(p d"T"))))))))) ``` ungolfed: ``` (defun f (s) (labels ((p (e f) (concatenate 'string e f))) (let ((b "") (d "")) (dotimes (i (length s)) (setf b (p b (write-to-string (char-int (elt s i)))))) (setf b (write-to-string (parse-integer b) :base 2)) (if (oddp #1=(length b)) (setf b (p b "0"))) (do ((j 0 (+ j 2))) ((= j #1#) d) (let ((c (subseq b j (+ j 2)))) (cond ((#2=string= "00" c) (setf d (p d "A"))) ((#2# "01" c) (setf d (p d "C"))) ((#2# "10" c) (setf d (p d "G"))) ((#2# "11" c) (setf d (p d "T"))))))))) ``` Usage: ``` CL-USER 2060 > (f "}") "TTGG" CL-USER 2061 > (f "golf") "TAAAAATTATCCATAAATA" ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~143~~ 121 bytes ``` filter d{if($_){"$(($_-($i=$_%2))/2|d)$i"}}-join([regex]"(..)"|% s* "$(-join($args|%{+$_})|d)0"|?{$_[1]}|%{"ACGT"[$_%8]}) ``` [Try it online!](https://tio.run/##VY3RToMwFIbveYqm6UyrY@quTMwiDVEuNa53hJAJB8aCgi2LS6DPjgeQqU2a05z/@7/W1Rdos4eydJNKQ8@yTdtnRdmAJmlbZJzFoqWM43Q5KzYsXqyFuF53qWAFtdY9VMUHDzXkcIooX60E7RbEXBLsTBnb6dx0i/aKxVZg7YZ2Dy2Lw9vI4pZKP1A0RO1dZEVvHcfjDsGz9DhNqhTyqszoktAg8JUKfBx4ZYA1nMpX42uIlJRSSSrO7bpO8rmJERJISkT/MHYAMApwJ0hHnir9uEv27vPbAZKGtCPIGjCNvzOwJAxONQaQkg1h8ZRqMMeywcUFy4g3s2MWvmz9o2mq98kXeZNwONtjkoAxg@fsdOFz1t2fQfUjHMhZ/pu@zp//61nHOv03 "PowerShell Core – Try It Online") ## Explanations Takes as an input a string transformed as a char array using splatting First, a filter to convert decimal to binary as Powershell can't do it for number larger than `long` ``` filter d{if($_){"$(($_-($i=$_%2))/2|d)$i"}} ``` This converts the char array to an int array, joins them as a string, splits with binary string concatenated with the padding in strings of length 2. It converts each substring to a number, and using modulus 8, finds the correct char in the `ACGT` string. ``` -join([regex]"(..)"|% s* "$(-join($args|%{+$_})|d)0"|?{$_[1]}|%{"ACGT"[$_%8]}) ``` [Answer] # Perl, ~~155~~ ~~148~~ 137 + 1 (`-p` flag) = 138 bytes ``` #!perl -p s/./ord$&/sge;while($_){/.$/;$s=$&%2 .$s;$t=$v="";$t.=$v+$_/2|0,$v=$_%2*5 for/./g;s/^0// if$_=$t}$_=$s;s/(.)(.)?/([A,C],[G,T])[$1][$2]/ge ``` Test it on [Ideone](http://ideone.com/MuPT0K). [Answer] # Perl 6, 57 + 1 (`-p` flag) = 58 bytes ``` $_=(+[~] .ords).base(2);s:g/..?/{<A G C T>[:2($/.flip)]}/ ``` Step by step explanation: `-p` flag causes Perl 6 interpreter to run code line by line, put current line `$_`, and at end put it back from `$_`. `.ords` - If there is nothing before a period, a method is called on `$_`. `ords` method returns list of codepoints in a string. `[~]` - `[]` is a reduction operator, which stores its reduction operator between brackets. In this case, it's `~`, which is a string concatenation operator. For example, `[~] 1, 2, 3` is equivalent to `1 ~ 2 ~ 3`. `+` converts its argument to a number, needed because `base` method is only defined for integers. `.base(2)` - converts an integer to a string in base 2 `$_=` - assigns the result to `$_`. `s:g/..?/{...}/` - this is a regular expression replacing any (`:g`, global mode) instance of regex `..?` (one or two characters). The second argument is a replacement pattern, which in this case in code (in Perl 6, curly brackets in strings and replacement patterns are executed as code). `$/` - a regex match variable `.flip` - inverts a string. It implicitly converts `$/` (a regex match object) to a string. This is because a single character `1` should be expanded to `10`, as opposed to `01`. Because of that flip, order of elements in array has G and C reversed. `:2(...)` - parses a base-2 string into an integer. `<A G C T>` - array of four elements. `...[...]` - array access operator. What does that mean? The program gets list of all codepoints in a string, concatenates them together, converts them to base 2. Then, it replaces all instances of two or one character into one of letters A, G, C, T depending on flipped representation of a number in binary. [Answer] # [Python 3](https://docs.python.org/3/), 117 bytes This answer ignores padding. Looks like it could be shorter. ``` lambda x:''.join('ACGT'[h//4]+'ACGT'[h%4]for h in [int(h,16)for h in hex(int(''.join(map(str,x.encode()))))[2:]])[1:] ``` [Try it online!](https://tio.run/##K6gsycjPM/5foWCroF5QkJyu/j8nMTcpJVGhwkpdXS8rPzNPQ93R2T1EPTpDX98kVhvGUTWJTcsvUshQyMxTiM7MK9HI0DE004QLZaRWaIBEYWbkJhZoFJcU6VTopeYl56ekamiCQLSRVWysZrShVez/giKQ8jSNCk3N/wA "Python 3 – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 92 90 bytes Does not handle padding, but is under 100. ``` lambda x,s='':f(x,'ACGT'[v%4]+s)if (v:=int(''.join(map(str,x.encode())))>>len(s)*2) else s ``` [Try it online!](https://tio.run/##Jc0xDsIgFIDhvadgMe@hTQd1ME1oQhi4AJs6YAta01ICpMHTY43/Af7Pf9JrcaeLDyUTRsD7/gmVZbcy6fkxaJLryABai7kGLqSC67o73w@Rjpbg2rLRJQRo3svocNYeYwp1bozrl8Eg3eq6yTiMdH@kxEzRkFh0jCYkYvHPUcI2WUqhOFdKKiEFF0pB5cPvvtGUli8 "Python 3.8 (pre-release) – Try It Online") # [Python 3](https://docs.python.org/3/), 113 110 bytes Spending almost 1/5 bytes on padding. ``` def f(x): v=int(''.join(map(str,x.encode())));v<<=len(bin(v))%2;c='' while v:c='ACGT'[v%4]+c;v>>=2 return c ``` [Try it online!](https://tio.run/##RU/BDoIwDD2zr9jFdIvGg3oCRrJw2A/sZjzoGILBsYw58euxeLFJ0zbv9bXPf2I3uuMyU0HBe3OHpbEtbdnMc5Il0bvIAPaPsXfsefVsimE3760zY2MZxyhSWYrBOnZDRuJ8cyiMACDZu@sHS1OOk6yVhnPanC5bU6SqEgeSBRtfwVGzXKfJhogXYdW8j0MLnAr8Rqlaa1VjwZQKRbDqWv@6FdJSSi2B/BV@Bv7bCCML2RLpQHxY3azW@PIF "Python 3 – Try It Online") # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 110 bytes ``` f=lambda x,s='':f(x,'ACGT'[v%4]+s)if(v:=(u:=int(''.join(map(str,x.encode()))))<<len(bin(u))%2>>len(s)*2)else s ``` [Try it online!](https://tio.run/##RU8xDsIwDNx5RRZkGyqGwoAqghR1yAeyIYYWEigqadQUVF5fnC61ZNnW3Vl34Tc8O78/hn4ahRQQwu0Bk5Nt9a7vlRizKAEKh2MGqtQGLt/14bqN1Dj8FhI/hWz8gAC7V9d4fFcB49Bn4876W3e3SKlOp9Z6rBn/EK3z8zmdkTY52TZaEacqRtsPwiEk0aNrHZCQ7Ebr0hhd8uBWmh3wNKWZtwQZpZRRsFo@zAEWNcPMYrZiOqxCn@xyHKLpDw "Python 3.8 (pre-release) – Try It Online") ]
[Question] [ # Challenge description A **Smith number** is a **composite** number whose sum of digits is equal to the sum of sums of digits of its prime factors. Given an integer `N`, determine if it's a Smith number or not. The first few Smith numbers are `4`, `22`, `27`, `58`, `85`, `94`, `121`, `166`, `202`, `265`, `274`, `319`, `346`, `355`, `378`, `382`, `391`, `438` (sequence [A006753](https://oeis.org/A006753) in OEIS). # Sample input / output ``` 18: False (sum of digits: 1 + 8 = 9; factors: 2, 3, 3; sum of digits of factors: 2 + 3 + 3 = 8) 22: True 13: False (meets the digit requirement, but is prime) 666: True (sum of digits: 6 + 6 + 6 = 18; factors: 2, 3, 3, 37; sum of digits of factors: 2 + 3 + 3 + 3 + 7 = 18) -265: False (negative numbers can't be composite) 0: False (not composite) 1: False (not composite) 4937775: True ``` # Notes * Your code can be a function (method) or a full working program, * Instead of words like `True` and `False`, you can use any truthy and falsy values, as long as it's clear what they are, * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so make your code as short as possible! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Æfḟȯ.DFżDSE ``` Returns **1** for Smith numbers and **0** otherwise. [Try it online!](http://jelly.tryitonline.net/#code=w4Zm4bifyK8uREbFvERTRQ&input=&args=NDkzNzc3NQ) or [verify all test cases](http://jelly.tryitonline.net/#code=w4Zm4bifyK8uREbFvERTRQotMTAwMHI0Mzg7NjY2OzQ5Mzc3NzXDh8OQZkc&input=VGhpcyBmaWx0ZXJzIFstMTAwMCwgLi4uLCA0MzgsIDY2NiwgNDkzNzc3NV0gYnkgdGhlIGxpbmsgb24gdGhlIGZpcnN0IGxpbmUsIGtlZXBpbmcgb25seSBlbGVtZW50cyBmb3Igd2hpY2ggdGhlIGxpbmsgcmV0dXJucyBhIHRydXRoeSB2YWx1ZS4). ### Background `Æf` (prime factorization) and `D` (integer-to-decimal) are implemented so that `P` (product) and `Ḍ` (decimal-to-integer) constitute left inverses. For the integers **-4** to **4**, `Æf` returns the following. ``` -4 -> [-1, 2, 2] -3 -> [-1, 3] -2 -> [-1, 2] -1 -> [-1] 0 -> [0] 1 -> [] 2 -> [2] 3 -> [3] 4 -> [2, 2] ``` For the numbers **-10, -1, -0.5, 0, 0.5, 1, 10**, `D` returns the following. ``` -11 -> [-1, -1] -10 -> [-1, 0] -1 -> [-1] -0.5 -> [-0.5] 0 -> [0] 0.5 -> [0.5] 1 -> [1] 10 -> [1, 0] 11 -> [1, 1] ``` ### How it works ``` Æfḟȯ.DFżDSE Main link. Argument: n (integer) Æf Yield the prime factorization of n. ḟ Filter; remove n from its prime factorization. This yields an empty array if n is -1, 0, 1, or prime. ȯ. If the previous result is an empty array, replace it with 0.5. D Convert all prime factors to decimal. F Flatten the result. D Yield n in decimal. ż Zip the results to both sides, creating a two-column array. S Compute the sum of each column. If n is -1, 0, 1, or prime, the sum of the prime factorization's digits will be 0.5, and thus unequal to the sum of the decimal array. If n < -1, the sum of the prime factorization's digits will be positive, while the sum of the decimal array will be negative. E Test both sums for equality. ``` [Answer] # Python 2, ~~122~~ ~~115~~ ~~110~~ 106 bytes ``` n=m=input() s=0 for d in range(2,n): while n%d<1:n/=d;s+=sum(map(int,`d`)) print n<m>s==sum(map(int,`m`)) ``` Saved 4 bytes thanks to Dennis [Try it on ideone.com](https://ideone.com/R3ly0w) ### Explanation Reads a number on stdin and outputs `True` if the number is a Smith number or `False` if it is not. ``` n=m=input() # stores the number to be checked in n and in m s=0 # initializes s, the sum of the sums of digits of prime factors, to 0 for d in range(2,n): # checks all numbers from 2 to n for prime factors while n%d<1: # while n is divisible by d # (to include the same prime factor more than once) n/=d # divide n by d s+=sum(map(int,`d`)) # add the sum of the digits of d to s print # print the result: "True" if and only if n<m # n was divided at least once, i.e. n is not prime > # and m>s (always true) and s==sum(map(int,`m`)) # s is equal to the sum of digits of m (the input) ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 19 bytes ``` @e+S,?$pPl>1,P@ec+S ``` [Try it online!](http://brachylog.tryitonline.net/#code=QGUrUyw_JHBQbD4xLFBAZWMrUw&input=NjY2) ### Explanation ``` @e+S, S is the sum of the digits of the input. ?$pP P is the list of prime factors of the input. Pl>1, There are more than 1 prime factors. P@e Split each prime factor into a list of digits. c Flatten the list. +S The sum of this list of digits must be S. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~11~~ 17 bytes ``` X›0si¹ÒSO¹SOQ¹p_& ``` **Explanation** ``` X›0si # if input is less than 2 then false, else SO # sum of digits ¹Ò # of prime factors with duplicates Q # equal to SO # sum of digits ¹ # of input & # and ¹p_ # input is not prime ``` [Try it online!](http://05ab1e.tryitonline.net/#code=WOKAujBzacK5w5JTT8K5U09RwrlwXyY&input=LTI1Ng) [Answer] ## PowerShell v3+, 183 bytes ``` param($n)$b=@();for($a=$n;$a-gt1){2..$a|?{'1'*$_-match'^(?!(..+)\1+$)..'-and!($a%$_)}|%{$b+=$_;$a/=$_}}$n-notin$b-and(([char[]]"$n")-join'+'|iex)-eq(($b|%{[char[]]"$_"})-join'+'|iex) ``` No built-in prime checking. No built-in factoring. No built-in digit-sum. Everything's hand made. :D Takes input `$n` as an integer, sets `$b` equal to an empty array. Here, `$b` is our collection of prime factors. Next is a `for` loop. We first set `$a` equal to our input number, and the conditional is until `$a` is less-than-or-equal-to 1. This loop is going to find our prime factors. We loop from `2` up to `$a`, uses `Where-Object` (`|?{...}`) to pull out [primes](https://codegolf.stackexchange.com/a/57636/42963) that are also factors `!($a%$_)`. Those are fed into an inner-loop `|%{...}` that places the factor into `$b` and divides `$a` (thus we'll eventually get to `1`). So, now we have all of our prime factors in `$b`. Time to formulate our Boolean output. We need to verify that `$n` is `-notin` `$b`, because if it is that means that `$n` is prime, and so isn't a Smith number. Additionally, (`-and`) we need to make sure that our two sets of [digit sums](https://codegolf.stackexchange.com/a/81071/42963) are `-eq`ual. The resulting Boolean is left on the pipeline and output is implicit. **NB** - Requires v3 or newer for the `-notin` operator. ~~I'm still running the input for `4937775` (this is *slow* to calculate), so I'll update this when that finishes.~~ After 3+ hours, I got a stackoverflow error. So, there's some upper-bound somewhere. Oh well. This will work for negative input, zero, or one, because the right-hand of the `-and` will barf out an error while it tries to calculate the digit sums (shown below), which will cause that half to go to `$false` when evaluated. Since STDERR is [ignored by default](https://codegolf.meta.stackexchange.com/a/4781/42963), and the correct output is still displayed, this is fine. --- ### Test cases ``` PS C:\Tools\Scripts\golfing> 4,22,27,58,85,94,18,13,666,-265,0,1|%{"$_ -> "+(.\is-this-a-smith-number.ps1 $_)} 4 -> True 22 -> True 27 -> True 58 -> True 85 -> True 94 -> True 18 -> False 13 -> False 666 -> True Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string. At C:\Tools\Scripts\golfing\is-this-a-smith-number.ps1:1 char:179 + ... "$_"})-join'+'|iex) + ~~~ + CategoryInfo : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand -265 -> False Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string. At C:\Tools\Scripts\golfing\is-this-a-smith-number.ps1:1 char:179 + ... "$_"})-join'+'|iex) + ~~~ + CategoryInfo : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand 0 -> False Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string. At C:\Tools\Scripts\golfing\is-this-a-smith-number.ps1:1 char:179 + ... "$_"})-join'+'|iex) + ~~~ + CategoryInfo : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand 1 -> False ``` [Answer] # MATL, 17 bytes ``` YftV!UsGV!Us=wnqh ``` Outputs [truthy or falsey](http://matl.tryitonline.net/#code=YGkgICAgICAgICAgJSBMb29wIHRocm91Z2ggYWxsIGlucHV0cwo_J1RSVUUnICAgICAlIElmIHRydXRoeSwgcHJpbnQgVFJVRQp9J0ZBTFNFJyAgICAlIEVsc2UsIHByaW50IEZBTFNFCl1EVCAgICAgICAgICUgQ29udGludWUgdW50aWwgd2UgcnVuIG91dCBvZiBpbnB1dHM&input=MQowClsxIDFdClsxIDBdClsxIDJdClsxIC0xXQ) arrays where a truthy output requires that *all* elements be non-zero. [**Try it online**](http://matl.tryitonline.net/#code=WWZ0ViFVc0dWIVVzPXducWg&input=NDkzNzc3NQ) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~27 25~~ 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) (further golfing ~~probably~~ [definitely](https://codegolf.stackexchange.com/a/92059/53748) possible) ``` ḢDS× ÆFÇ€SḢ DS=Ça<2oÆP¬ ``` Returns `0` for False or `1` for True All test cases at [**TryItOnline**](http://jelly.tryitonline.net/#code=4biiRFPDlwrDhkbDh-KCrFPhuKIKRFM9w4dhPDJvw4ZQwqwKw4figqw&input=&args=WzE4LDIyLDEzLDY2NiwtMjY1LDAsMSwtMSw0OTM3Nzc1XQ) How? ``` DS=Ça<2oÆP¬ - main link takes an argument, n DS - transform n to a decimal list and sum up Ç - call the previous link (ÆFÇ€SḢ) = - test for equality <2 - less than 2? a - logical and ÆP - is prime? o - logical or ¬ - not - all in all tests if the result of the previous link is equal to the digit sum if the number is composite otherwise returns 0. ÆFÇ€SḢ - link takes an argument, n again ÆF - list of list of n's prime factors and their multiplicities Ç€ - apply the previous link (ḢDS×) for each S - sum up Ḣ - pop head of list (there will only be one item) ḢDS× - link takes an argument, a factor, multiplicity pair Ḣ - pop head, the prime factor - modifies list leaving the multiplicity DS - transform n to a decimal list and sum up × - multiply the sum with the multiplicity ``` [Answer] # Actually, 18 bytes Unfortunately, Actually doesn't have a factorization builtin that gives a number's prime factors to multiplicity, so I had to hack one together. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=O3dgaSRuYE3Oo-KZguKJiM6jQCTimYLiiYjOoz0&input=Mjc) ``` ;w`i$n`MΣ♂≈Σ@$♂≈Σ= ``` **Ungolfing** ``` Implicit input n. ;w Duplicate n and get the prime factorization of a copy of n. `...`M Map the following function over the [prime, exponent] lists of w. i Flatten the list. Stack: prime, exponent. $n Push str(prime) to the stack, exponent times. The purpose of this function is to get w's prime factors to multiplicity. Σ sum() the result of the map. On a list of strings, this has the same effect as "".join() ♂≈Σ Convert every digit to an int and sum(). @ Swap the top two elements, bringing other copy of n to TOS. $♂≈Σ Push str(n), convert every digit to an int, and sum(). = Check if the sum() of n's digits is equal to the sum of the sum of the digits of n's prime factors to multiplicity. Implicit return. ``` [Answer] # Octave, ~~80~~ 78 bytes ``` t=num2str(factor(x=input('')))-48;disp(any(t<0)&~sum([num2str(x)-48 -t(t>0)])) ``` Explanation: ``` factor(x=input('')) % Take input, store as x and factor it num2str(factor(x=input('')))-48 % Convert it to an array (123 -> [1 2 3]) % and store as t any(t<0) % Check if there are several prime factors % [2 3] -> [2 -16 3] sum([num2str(x)-48 -t(t>0)]) % Check if sum of prime factor % is equal the sum of digits ``` Try it [online](https://ideone.com/kMVzhE). [Answer] # Pyth, 21 bytes ``` &&>Q1!P_QqsjQTssmjdTP ``` A program that takes input of an integer and prints `True` or `False` as relevant. [Try it online](https://pyth.herokuapp.com/?code=Q%26%26%3EQ1%21P_QqsjQTssmjdTP&test_suite=1&test_suite_input=18%0A22%0A13%0A666%0A-265%0A0%0A1%0A4937775&debug=0) **How it works** ``` &&>Q1!P_QqsjQTssmjdTP Program. Input: Q jQT Yield digits of the base-10 representation of Q as a list s Add the digits P Yield prime factors of Q (implicit input fill) mjdT Map base-10 representation across the above, yielding digits of each factor as a list of lists s Flatten the above s Add up the digits q Those two sums are equal & and >Q1 Q>1 & and !P_Q Q is not prime Implicitly print ``` [Answer] # [Perl 6](http://perl6.org/), ~~92~~ ~~88~~ 87 bytes ``` {sub f(\i){my \n=first i%%*,2..i-1;n??n~f i/n!!i} !.is-prime&&$_>1&&.comb.sum==.&f.comb.sum} ``` ``` {sub f(\i){my \n=first i%%*,2..^i;n??[n,|f i/n]!!|i} $_>.&f>1&&.comb.sum==.&f.comb.sum} ``` An anonymous function that returns a Bool. * Now does 100% manual factorization and primality checking. * Saved some bytes by testing both "input > 1" and "number of factors > 1" with one chained comparison, since m > [Ω(m)](https://en.wikipedia.org/wiki/Prime_factor#Omega_functions). ([try it online](https://glot.io/snippets/ei6u5x8unj)) *EDIT: -1 byte thanks to b2gills* [Answer] # [Brachylog (newer)](https://github.com/JCumin/Brachylog), 11 bytes ``` ¬ṗ&ẹ+.&ḋcẹ+ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompkcdy5VKikpTlfRqQMy0xJziVKXa04vK/x9a83DndLWHu3Zq66k93NGdDGL9/x9taKFjZKRjaKxjZmamE29kZqpjoGOoY2JpbG5ubhoLAA "Brachylog – Try It Online") Predicate succeeds if the input is a Smith number and fails if it is not. ``` The input ¬ṗ is not prime, & and the input's ẹ digits + sum to . the output variable, & and the input's ḋ prime factors' (getting prime factors of a number < 1 fails) c concatenated ẹ digits + sum to the output variable. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ 11 bytes ``` ìx ¥Uk x_ìx ``` *-3 bytes thanks to @Shaggy* [Try it online!](https://tio.run/##y0osKPn///CaCoVDS0OzFSrigcz//42MAA "Japt – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~36~~ 29 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") This answer owes its golfiness to Extended's `⍭` monad for returning the prime factors of a number, and that `⊤` is better at base-conversion than in Dyalog Unicode. Edit: -7 bytes thanks to dzaima. ``` {2>⍵:0⋄(⊃=+/-⊃×2<≢)+⌿10⊤⍵,⍭⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v9rI7lHvViuDR90tGo@6mm219XWB1OHpRjaPOhdpaj/q2W9o8KhrCVCNzqPetUCq9n/ao7YJj3r7HvVN9fQHqj203vhR20QgLzjIGUiGeHgG/087tMLQQsHISMHQWMHMzEzh0HojM1MFAwVDBRNLY3Nzc1MA) **Explanation** ``` {1⋄(3)2} A dfn, a function in brackets. ⋄ is a statement separator. The numbers signify the sections in the order they are explained. 2>⍵:0 If we have a number less than 2, we immediately return 0 to avoid a DOMAIN ERROR. +⌿10⊤⍵,⍭⍵ ⍭⍵ We take the factors of ⍵, our input as our right argument, ⍵, and append it to our input again. 10⊤ before converting the input and its factors into a matrix of their base-10 digits (each row is the places, units, tens, hundreds, etc.) +⌿ And taking their sum across the columns of the resulting matrix, to give us the sum of their digits, their digit-sums. (⊃=+/-⊃×2<≢) We run this section over the list of sums of digits above. ⊃=+/-⊃ We check if the main digit-sum (of our input) Is equal to the sum of our digit-sums (minus our main digit-sum that is also still in the list) ×2<≢ The trick here is that we can sneak in our composite check (if our input is prime there will be only two numbers, the digit-sum of the prime, and the digit-sum of its sole prime factor, itself) So if we have a prime, we zero our (minus our main sum) in the calculation above, so that primes will not succeed in the check. We return the result of the check. ``` [Answer] # JavaScript (ES6), ~~ 87 86 ~~ 84 bytes ``` m=>(i=2,S=0,g=n=>([...i+''].map(v=>s-=v,s=S),i-m?n%i?g(n,i++):g(n/i,S=s):s==2*S))(m) ``` [Try it online!](https://tio.run/##HYvBDkNAFEX3vuJtykyNqUi6oY@PsBQJ0dInvBGjNk2/XSd25@TeM7Z7a7uVli1i83wdPR4z5oIwUSXGakB2VmmtKQyCWs/tInbMbYS7slhKRdFc8IWKQbCiMJSpgxu51srUIibXUkoxy6M3q2BASBRMZDdHVZ0BwwPucezApfD1AHrBEnz/POnlY9/OM@/ndYatmV56MoM4t9EQN6qR2fEH "JavaScript (Node.js) – Try It Online") [Answer] # Haskell, ~~120~~ 105 bytes ``` 1%_=[];a%x|mod a x<1=x:div a x%x|0<1=a%(x+1) p z=sum[read[c]|c<-show z] s x|z<-x%2=z<[x]&&sum(p<$>z)==p x ``` [Answer] # [Rutger](https://github.com/cairdcoinheringaahing/Rutger), 504 bytes ``` x=$Input; t=Not[IsPrime[$x]]; c=(); d=p=0; i=IfElse[{l=LessThan[$x];l[1]}]; i=i[{t=0;}]; i=i[{s=Array[Str[$x]];e=Each[$s];e=e[@i];e=e[{a=Add[$d];d=a[Integer[$i]];}];Do[$e];r=2;w=While[{Decrement[$x];}];w=w[{i=IfElse[{m=Modulo[$x];Not[m[$r]];}];i=i[{a=Append[$c];v=Divide[$x];x=Integer[v[$r]];c=a[Array[Str[$r]]];}];i=i[{r=Increment[$r];}];Do[$i];}];Do[$w];h=Each[$c];h=h[@k];h=h[{l=Each[$k];l=l[@n];l=l[{a=Add[$p];p=a[Integer[$n]];}];Do[$l];}];Do[$h];}]; Do[$i]; z=Times[$t]; e=Equal[$d]; Print[z[e[$p]]; ``` [Try it online!](https://tio.run/##TVFNa8MwDL37d/iw3fZJGUbQQnsIbGOwwg7ChxB7i5njZLbTdA377ZkSt2lPepKlp6dn38Yv7YdhDzxzTRsFi/BaR8zCmzeVRr6XUrACrq4FU9DAjWAGss@NDRp7C886hG2Zu7FPWLyVf3JsMNhHap2TACvv8198jz4xatjkRYk8jFDj0qTY57BSCrmSQkGOmYua1CE3NEJk6xq5lsLDnejgozSWJta68LrSLk4SqKmDDvuzxgpeatXaenoeL6uQ@0Q3SaONTaMdLS2k2MHa7IyazhZ7OO3fpZGCJF3cQaUzjafmWYif1ZoZdVKUx6OLEZa4/E6RbEx1yi1YXLoUT2Y0UjSXZrizGXZG5YTYcSc7wJZ@LyCPlJDZP21uJ1sZfStJPKAeiaUYhoen@8Vi8fgP "Rutger – Try It Online") Rutger isn't a particularly short language, and doesn't excel at having to split an integer into its constituent digits. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 26 bytes ``` (×/≡⍥(+/⍣≡10⊤⊢)⊢×1<≢)⍭⍤⌈∘2 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@PwdP1HnQsf9S7V0NZ/1LsYyDY0eNS15FHXIk0gPjzd0OZRJ5DZu/ZR75JHPR2POmYY/U971DbhUW/fo76pnv6PupoPrTd@1DYRyAsOcgaSIR6ewf@BtHOkenFiTom6wqPuFoXUvMSknNRgR58Qrtik/IrMvHSF/DyutEMrDC0UjIwUDI0VzMzMFA6tNzIzVTBQMFQwsTQ2Nzc3BQA "APL (Dyalog Extended) – Try It Online") A golfed version of [Sherlock9's solution](https://codegolf.stackexchange.com/a/180810/78410). A nice use case for Over `f⍥g`, which performs `g` on both sides and combines the two with `f`. ### How it works ``` (×/≡⍥(+/⍣≡10⊤⊢)⊢×1<≢)⍭⍤⌈∘2 ⍝ Input: n ⌈∘2 ⍝ max(n,2) ⍭⍤ ⍝ Prime factorization of above ( ⊢×1<≢) ⍝ Side 1: if n is not composite, multiply ^ with zero ×/ ⍝ Side 2: multiply all primes to get original number ⍥( ) ⍝ Operate on each side.. 10⊤⊢ ⍝ Base-10 digits of each number +/⍣≡ ⍝ Sum all of them ≡ ⍝ Check equality of the two sides ``` [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 131 bytes ``` (load library (d F(q((X)(*(*(not(prime? X))X)(e(sum(to-base 10 X))(sum(map(q((X)(s X 48)))(chars(join(map string(prime-factors X))( ``` [Try it online!](https://tio.run/##LYzbDoIwDIbveYpediYazuKVdzwDtwMmzuyA3dDw9DiGadIv/dq/XppVSTdvGyrLR1CyJ05rgiO0@EbsGJ5CGetxJqnFHTrGghToFo3ennvuBGTprqPSfP7nHHRQNiz44cnJ4ctKs6/BeZJmOv6dH3zwllzMb9hC1rAkIM8jsiKirutINGKCvK5YnNLjJPTBai2MhzCWt@J6rRj4p3TwlUoBLQYelsRH0IUl2w8 "tinylisp – Try It Online") An unintentional golf at `join` which through some weird behaviour ends up producing the right thing. Rest of it is just the formula given in the question. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 63 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 7.875 bytes ``` ₍‡ǐvffṠṠ≈ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwi4oKN4oChx5B2ZmbhuaDhuaDiiYgiLCIiLCIyOCJd) Bitstring: ``` 110001111001001111101010000010100001001101010011001110100101010 ``` ``` ₍‡ǐvffṠṠ≈­⁡​‎‎⁡⁠⁡‏⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌­ ₍ # ‎⁡Wrap the next to items in a list ‡ǐvf # ‎⁢list of digits for each prime factor f # ‎⁣list of digits of original number ṠṠ # ‎⁤vectorised sum twice (quirk of list depth from digit lists) ≈ # ‎⁢⁡are they equal 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] ## Pyke, 16 bytes ``` Pm[`mbs(sQ[qRlt* ``` [Try it here!](http://pyke.catbus.co.uk/?code=Pm%5B%60mbs%28sQ%5BqRlt%2a&input=22) [Answer] # Java 7, ~~509~~ ~~506~~ ~~435~~ ~~426~~ ~~419~~ 230 bytes ``` boolean c(int n){return n<2|p(n)?0>1:d(n)==f(n);}int d(int n){return n>9?n%10+d(n/10):n;}int f(int n){int r=0,i;for(i=1;++i<=n;)for(;n%i<1;n/=i,r+=i>9?d(i):i);return r;}boolean p(int n){int i=2;while(i<n)n=n%i++<1?0:n;return n>1;} ``` I should have listened to *@BasicallyAlanTuring*'s comment.. > > This is one of those questions where I thought "Java+this=no", I upvoted for the idea though :P > > > Ah well.. Some programming languages use a single byte for the prime-factors or prime-check, but Java is certainly not one of them. EDIT: Halved the amount of bytes now that I had some time to think about it. **Ungolfed (sort-off..) & test cases:** [Try it here.](https://ideone.com/1ihqJd) ``` class M{ static boolean c(int n){ return n < 2 | p(n) ? 0 > 1 //false : d(n) == f(n); } // Sums digits of int static int d(int n) { return n > 9 ? n%10 + d(n/10) : n; } // Convert int to sum of prime-factors static int f(int n) { int r = 0, i; for(i = 1; ++i <= n; ){ for( ; n % i < 1; n /= i, r += i > 9 ? d(i) : i); } return r; } // Checks if the int is a prime static boolean p(int n){ int i = 2; while(i < n){ n = n % i++ < 1 ? 0 : n; } return n > 1; } public static void main(String[] a){ System.out.println(c(18)); System.out.println(c(22)); System.out.println(c(13)); System.out.println(c(666)); System.out.println(c(-256)); System.out.println(c(0)); System.out.println(c(1)); System.out.println(c(4937775)); } } ``` **Output:** ``` false true false true false false false true ``` [Answer] # [J](http://jsoftware.com/), ~~31~~ 30 bytes ``` 0&p:*](=+/)&(1#."."0@":)q: ::1 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DdQKrLRiNWy19TXVNAyV9ZT0lAwclKw0C60UrKwM/2sqcHGlJmfkA3XYKqQpGCBzDFE4Fig8Y2RevJGZKRfUHEOwiJERMs/MzAyZa2JpbG5ubsr1HwA "J – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~139~~ 136 bytes ``` S(m,i,t,h,_){t=m=m<2?2:m;for(_=h=i=1;m>1;h=1){while(m%++h);for(m/=h;i+=h%10,h/=10;);}while(t%++h);for(m=t;_+=m%10,m/=10;);m=t-h?i==_:0;} ``` [Try it online!](https://tio.run/##TcrBCsIwEATQu18RhEJiU2w89OC69iM8qoQStRtwq4Sgh9Jvj2314JyGmeeK1rmUDpK111GTtqqPyMi7Tb3ZMtweQVok9GiA9wYIjerf5O9XyVmek5oFr5HA50iZKTWt0ZSgYPiy@Mcwgs2RJ8U/NW4F1R7RbksYku@i4MZ3cipNaJ0WjpogVmN/Hc@qX4gxzzDeN7nMLqduqcVBNvHh5UzMWSkFiyGlqqo@ "C (gcc) – Try It Online") -3 bytes thanks to ceilingcat Explanation: ``` /* * Variable mappings: * is_smith => S * argument => m * factor_digits => i * arg_copy => t * least_factor => h * digit_sum => _ */ int is_smith(int argument){ /* S(m,i,t,h,_){ */ int factor_digits; int arg_copy; int least_factor; int digit_sum; /* * The cases of 0 and 1 are degenerate. * Mapping them to a non-degenerate case with the right result. */ if (argument < 2) { /* t=m=m<2?2:m; */ argument = 2; } arg_copy = argument; /* * Initializing these to 1 instead of zero is done for golf reasons. * In the end we just compare them, so it doesn't really matter. */ factor_digits = 1; /* for(_=h=i=1; */ digit_sum = 1; /* Loop over each prime factor of argument */ while (argument > 1) { /* m>1; */ /* * Find the smallest factor * Note that it is initialized to 1 in the golfed version since prefix * increment is used in the modulus operation. */ least_factor = 2; /* h=1){ */ while (argument % least_factor != 0) /* while(m% */ least_factor++; /* ++h); */ argument /= least_factor; /* for(m/=h; */ /* Add its digit sum to factor_digits */ while (least_factor > 0) { factor_digits += least_factor % 10; /* i+=h%10, */ least_factor /= 10; /* h/=10;) */ } /* ; */ } /* } */ /* In the golfed version we get this for free in the for loop. */ least_factor = 2; while (arg_copy % least_factor != 0) /* while(t% */ least_factor++; /* ++h); */ /* Restore the argument */ argument = arg_copy; /* for(m=t; */ /* Compute the arguments digit sum */ while (argument > 0) { digit_sum += argument % 10; /* _+=m%10, */ argument /= 10; /* m/=10;) */ } /* ; */ /* This return is done by assigning to first argument when golfed. */ /* m= */ if (arg_copy == least_factor) { /* t==h? */ return 0; /* prime input */ /* 0 */ } else { /* : */ return digit_sum == factor_digits; /* i == _ */ } /* ; */ } /* } */ ``` [Answer] # Racket 176 bytes ``` (define(sd x)(if(= x 0)0(+(modulo x 10)(sd(/(- x(modulo x 10))10))))) (require math)(define(f N) (if(=(for/sum((i(factorize N)))(*(sd(list-ref i 0))(list-ref i 1)))(sd N))1 0)) ``` Returns 1 if true and 0 if false: ``` (f 27) 1 (f 28) 0 (f 85) 1 (f 86) 0 ``` Detailed version: ``` (define (sd x) ; fn to find sum of digits (if (= x 0) 0 (+ (modulo x 10) (sd (/ (- x (modulo x 10)) 10))))) (require math) (define (f N) (if (= (for/sum ((i (factorize N))) (* (sd (list-ref i 0)) (list-ref i 1))) (sd N)) 1 0)) ``` [Answer] # Rust - 143 bytes ``` fn t(mut n:u32)->bool{let s=|k:u32| (2..=k).fold((0,k),|(a,m),_|(a+m%10,m/10));s(n).0==(2..n).fold(0,|mut a,d|{while n%d<1{n/=d;a+=s(d).0};a})} ``` borrowed python solution by @levitatinglion ... at least this is shorter than Java... [degolfed at play.rust-lang.org](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e2a467d637f009f3bea17115fae119aa) [Answer] # C (gcc), 177 Bytes Defines a function `Q` that returns 0 for smith numbers and nonzero for non-smith numbers ``` #define r return O(D,i){for(i=0;D>0;i+=D%10,D-=D%10,D/=10);r i;}D(O,o){for(o=1;o<O;)if(O%++o<1)r o;r O;}Q(p,q,i,j){if(p^(q=D(i=p))){for(j=0;p>1;q=D(p/=q))j+=O(q);r j^O(i);}r 1;} ``` [Try it online!](https://tio.run/##fc5Bb4MgGAbgu7/iSxcTvohRdNNulJ68kyY7Lk02RYfJUKk7GX@7E9vr5PISeOD9yrApy2V5qlStjQILVo2/1niSFFTjVHeWaBHz4hxzHYjCZzEtwkdGgsXILWg@F0TS7s47wXh3khx1TaQfBN2JoYVudZLPF9LTgWra4rRe91cyiGIt6BHvj9u1qz8z7o77SAyIbSAkGVxNe5VEI58tMD57UQTv6jZq08CXarS5wbeyyvv51Ibg5MG6eqvNWJODX8Eb@NWHOVBgRwoXwo6I/F@TJM4kyZ5h6fZPumeyLHNojT0VJtmLYy73XOxQvDvTNtKeeH5N8zzf6h5bp2dvWf4A "C (gcc) – Try It Online") Explanation: ``` // Return the sum of digits of D if D > 0, otherwise 0 O(D,i){ // While D is greater than 0: // Add the last digit of D to i, and remove the last digit from D for(i=0;D>0;i+=D%10,D-=D%10,D/=10); return i; } // Return the smallest prime factor of O if O>1 else O D(O,o){ // Iterate over numbers less than O for(o=1;o<O;) // If O is divisible by o return o if(O%++o<1) return o; // Otherwise return O return O; } Q(p,q,i,j){ // Set q to D(p) and i to p // If p != D(p) (i.e, p is composite and > 0) if(p^(q=D(i=p))){ // Iterate over the prime factors of p and store their digit sum in j for(j=0;p>1;q=D(p/=q)) j+=O(q); // i is the original value of p. If O(i)^j == 0, O(i) == j return j^O(i); } // If p was composite or < 0, return 1 return 1; } ``` [Answer] ## [C# (Visual C# Interactive Compiler)](https://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 122 bytes ``` n=>{int m=n,b=0,a=$"{n}".Sum(x=>x-'0');for(int i=2;i<m;i++)if(n%i==0){b+=$"{i}".Sum(x=>x-'0');n/=i;i=1;}return n>0&&a==b;} ``` [Try it online!](https://tio.run/##ZczBCoJAFIXhfU8xROkMao1aYzFel63atWitonAhrzAqCOKzmy7V7cf5T954eYPTq6M8RmrdrK5/CSsZTATJMAurgNwMpJvC6TjQeLx8uor3kPSeLW2hy9rwZYYQaIwrjY4jsOR0RgAphsxZMtxldAXUCL4eTdF2hhgl0rJSgEyPkz58DbbFG6ngJfcfQqwlCLbih1tRSm3JC9R9a3L3NANbye0ZRlG0lNMf) [Answer] # APL(NARS), 39 chars, 78 bytes ``` {⍵≤0:0⋄0π⍵:0⋄(2×↑a)=+/a←+/¨{⍎¨⍕⍵}¨⍵,π⍵} ``` test: ``` f←{⍵≤0:0⋄0π⍵:0⋄(2×↑a)=+/a←+/¨{⍎¨⍕⍵}¨⍵,π⍵} f¨0..10 0 0 0 0 1 0 0 0 0 0 0 ⎕fmt {⍵,f⍵}¨18,22,13,666,¯265,0,1,4937775 ┌8────────────────────────────────────────────────────────────────────┐ │┌2────┐ ┌2────┐ ┌2────┐ ┌2─────┐ ┌2──────┐ ┌2───┐ ┌2───┐ ┌2─────────┐│ ││ 18 0│ │ 22 1│ │ 13 0│ │ 666 1│ │ ¯265 0│ │ 0 0│ │ 1 0│ │ 4937775 1││ │└~────┘ └~────┘ └~────┘ └~─────┘ └~──────┘ └~───┘ └~───┘ └~─────────┘2 └∊────────────────────────────────────────────────────────────────────┘ ``` ]
[Question] [ # Challenge Write a program or function that takes a number \$n\$ and returns the smallest \$k\$ such that concatenation \$n'k\$ is a square. This sequence is described by [A071176 on the OEIS](https://oeis.org/A071176). # I/O Examples ``` input --> output 1 --> 6 (4^2) 10 --> 0 (10^2) 35 --> 344 (188^2) 164 --> 836 (406^2) 284 --> 2596 (1686^2) ``` # Rules * Input will always be a positive decimal integer * Output will be a positive decimal integer with no leading `0`'s or `0` * [Standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply * No [standard loopholes](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 shortest code in bytes wins [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞<.Δ«Å² ``` [Try it online](https://tio.run/##yy9OTMpM/f//Ucc8G71zUw6tPtx6aNP//0YWJgA) or [verify all test cases](https://tio.run/##ATsAxP9vc2FiaWX/dnk/IiDihpIgIj95wqn/4oiePC7OlMKuc8Krw4XCsv99LP9bMSwxMCwzNSwxNjQsMjg0XQ). # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [N«Å²#}N ``` [Try it online](https://tio.run/##MzBNTDJM/f8/2u/Q6sOthzYp1/r9/29kYQIA) or [verify all test cases](https://tio.run/##ATcAyP8wNWFiMWX/dnk/IiDihpIgIj95wqn/W8KuTsKrw4XCsiN9Tv8s/1sxLDEwLDM1LDE2NCwyODRd). Alternative 8-byter which works in both 05AB1E versions (credit to *@Grimmy*): ``` [N«Å²iNq ``` [Try it online](https://tio.run/##yy9OTMpM/f8/2u/Q6sOthzZl@hX@/29kYQIA) (no test suite due to the program terminate `q`). **Explanation:** ``` ∞ # Push an infinite list in the range [1, ...] < # Decrease each by 1 to make the range [0, ...] .Δ # Find the first value which is truthy for: « # Concat the value to the (implicit) input-integer Ų # And check whether it is a square number # (after which this found first value is output implicitly as result) [ # Start an infinite loop: N« # Concat the 0-based loop index to the (implicit) input-integer Ų # If it's a square number: # # Stop the infinite loop }N # After the infinite loop has stopped: push the last index # (after which this found index is output implicitly as result) [ # Start an infinite loop: N« # Concat the 0-based loop index to the (implicit) input-integer Ųi # If it's a square number: N # Push the index again q # And terminate the program # (after which this index is output implicitly as result) ``` The legacy version didn't had the `∞` builtin, and in the new version it isn't possible to push the last index `N` after a loop is terminated, which is why I decided to post both solutions. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 23 bytes ``` {(0...($_~*)**.5%%1)-1} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WsNAT09PQyW@TktTS0vPVFXVUFPXsPZ/cWKlgh5QRVp@kYKhjoKhgY6CsSmQNjPRUTCyMPkPAA "Perl 6 – Try It Online") ### Explanation ``` { } # Anonymous codeblock (0... )-1 # Find the first number ($_~*) # That when appended to the input **.5 # Has a sqrt %%1 # That is whole ``` [Answer] # [J](http://jsoftware.com/), ~~27~~ 21 bytes ``` (]+0<1|2%:,&.":)^:_&0 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NWK1DWwMa4xUrXTU9JSsNOOs4tUM/mtypSZn5CuYKdgqpCkYQjgGEI4BhGdsYgLmG5tC@BbGUMVmJhABI1NLiIiRhcl/AA "J – Try It Online") *-6 bytes thanks to FrownyFrog* * `( )^:_` invoke the verb in parens continuously until it's output stops changing * `&0` set the right argument -- the one that will change each iteration -- to 0 (the left argument, the input, will remain fixed) Now let's break down what's in the parens * `]+` the right arg plus... * `0<` 0 or 1, depending on if 0 is less than... * `1|` the reminder when 1 divides... * `2%:` the square root of... * `,&.":` the left arg (original input) catted with `,` the right arg "under" `&.` stringification `":`: ie, turn them both into strings, cat them, then convert back to an int [Answer] # JavaScript (ES7), 33 bytes Takes input as a string. ``` f=(n,k=0)=>(n+k)**.5%1?f(n,k+1):k ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjTyfb1kDT1k4jTztbU0tLz1TV0D4NJKptqGmV/T85P684PydVLyc/XSNNQ91QXVOTC13MAIugsSk2lWYmWESNLECi/wE "JavaScript (Node.js) – Try It Online") [Answer] # [R](https://www.r-project.org/), 45 bytes ``` n=scan();while((paste0(n,+F):1)^.5%%1)F=F+1;F ``` [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTujwjMydVQ6Mgsbgk1UAjT0fbTdPKUDNOz1RV1VDTzdZN29Da7b@hmcl/AA "R – Try It Online") Throws a warning for each iteration noting that it only uses the first element of the vector as a loop condition. This will run out of space for large inputs since it constructs a vector of length \$n'k\$ at each iteration; [this version](https://tio.run/##K/r/P8@2ODkxT0PTujwjMydVo7ikqCQ/U6Mgsbgk1UAjT0fbTVMzTs9UVdVQ083WTdvQ2u2/odl/AA) will work for larger inputs and should be a bit faster, at a cost of 4 bytes. [Answer] # [Perl 5](https://www.perl.org/) `-pal`, 30 bytes ``` $_=0;$_++while"@F$_"**.5=~/\./ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tbAWiVeW7s8IzMnVcnBTSVeSUtLz9S2Tj9GT///f0MuQwMuY1MuQzOTf/kFJZn5ecX/dX1N9QwMDf7rFiTmAAA "Perl 5 – Try It Online") [Answer] ## C, ~~123~~ 115 bytes (thanks, Jo King!) ``` n,k,m=10,x,p;main(){scanf("%d",&n);for(;k<m||(m*=10);++k)for(p=0;x=n*m+k,p<=x;++p)if(p*p==x)return printf("%d",k);} ``` I noticed this version can fail on not-very-large inputs due to integer overflow. So I, did a separate version, with less overflow. ## C, less overflow. 117 bytes ``` n,k,m=10,x,p;main(){scanf("%d",&n);for(;k<m||(m*=10);++k)for(p=0;x=n*m+k,p*p<=x;++p)if(p*p==x)return printf("%d",k);} ``` ## Pretty Printed: ``` n, k, m = 10, x, p; main() { scanf("%d", &n); for (; k < m || (m *= 10); ++k) for (p = 0; x = n * m + k, p * p <= x; ++p) if (p * p == x) return printf("%d", k); } ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` ;.c~^₂∧ℕ ``` Sadly enough it takes 3 bytes to check if a number is square and an extra `ℕ` is needed if the input is a square itself. ## Explanation ``` ;.c~^₂∧ℕ # Find a value ;.c # that concatenate to the input ~^₂ # gives a square number ∧ℕ # and make sure that value is a number # (otherwise we get the empty list for inputs that are square) ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/31ovuS7uUVPTo47lj1qm/v9vZGHy3xEA "Brachylog – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~47~~ 49 bytes ``` f=lambda p,i=0:int(`p`+`i`)**.5%1and f(p,i+1)or i ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRoUAn09bAKjOvRCOhIEE7ITNBU0tLz1TVMDEvRSFNAyirbaiZX6SQ@b@gCKgIKGRoZqL5HwA "Python 2 – Try It Online") [Answer] # [C++ (clang)](http://clang.llvm.org/), ~~194~~ \$\cdots\$ ~~128~~ 129 bytes ``` #import<string> #define z std::to_string int f(int n){for(int j=-1;;)for(long i=0,m=stol(z(n)+z(++j));i++<m;)if(i*i==m)return j;} ``` [Try it online!](https://tio.run/##PY7daoQwEIXvfYrBvTFVQdvdUkz0SQpFNC4jJpE49kLx2e2oSy/m9wxnvmYc02ao7XPfb2hG50lN5NE@q@DW6g6thgUmaouC3M@lBGgJuujIVqyd82fbl2kupTjGwdknYJklppzIDdESWREvURz3QkiMY2WkQDZ4w7I0wmuavYVebkxgm2FuNSh0/EvXhin@d7@6Ieer872p0UZiDeBiuyTFSgWkJ5rWPMmz5OOR5J/35P3rvkk@ZTY4WbE4jwTv4OXQuJlAKUCOENK04swtU4qjht82PCxesJkMtv0P "C++ (clang) – Try It Online") Added a byte to fix overflow error kindly pointed out by [Deadcode](https://codegolf.stackexchange.com/users/17216/deadcode). [Answer] # [Python 3](https://docs.python.org/3/), 51 bytes ``` f=lambda n,i=0:int(f'{n}{i}')**.5%1and f(n,i+1)or i ``` [Try it online!](https://tio.run/##HYzBCoMwEETv/Yq9FBMbJKlaiuDHpNXQBbMJSXoQ8dvTpQPz5vBg4l4@gfqKPoZUIO/5wu3yWtL6/qaMgTb0WITRHFndvFn/WiyQwllPSEW45qDzwLORbduNV2NpASfY34wMCbA6JgESGAVGK@hH3seg4P4cJojpfyJIyvoD "Python 3 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) -pl, 43 bytes ``` i=1;i+=1until"#{i*i}"[/^#$_(?!0.|$)/] $_=$' ``` [Try it online!](https://tio.run/##KypNqvz/P9PW0DpT29awNK8kM0dJuTpTK7NWKVo/TlklXsNe0UCvRkVTP5ZLJd5WRf3/f0MuQwMuY1MuQzMTLiMLk3/5BSWZ@XnF/3ULcgA "Ruby – Try It Online") Tests each square until it finds one that starts with the input and is followed by a number with no leading zero. I thought going in this direction rather than the more natural one would be shorter, but now I'm doubting that it is. [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~18~~ ~~16~~ ~~15~~ ~~11~~ 10 bytes Uses the floating point square root test, like most of the other answers. As such, the precision is eventually insufficient, and the smallest square it fails with is `4503599761588225` – with an input of `45035997`, it [returns `61588224`](https://tio.run/##K6gsyfhvG2VmaGoAAv@VPRVVHYq1AxOijBQMo5xsM6L@/zcxNTA2tbQ0/5dfUJKZn1f8X1c3tzSnJDMnMy8VyE5JTSpNBwA) instead of `61588225` as it should. The smallest input it fails with is `20256971`, [returning `228498166`](https://tio.run/##K6gsyfhvG2VkZGFiAAL/lT0VVR2KtQMToowUDKOcbDOi/v83MjAyNbM0N/yXX1CSmZ9X/F9XN7c0pyQzJzMvFchOSU0qTQcA) instead of `228498169` as it should. This is due to IEEE 754 floating point not being able to store precise integers greater than 252. ``` fsI@s+zT2Z ``` [Try it online!](https://tio.run/##K6gsyfhv615c5RYZ7G4bZVCgbVuVEKlkpaD0P63Y06FYuyrEKOr/f2NTg3/5BSWZ@XnF/3V1c0tzSjJzMvNSgeyU1KTSdAA "Pyth – Try It Online") Ungolfed: ``` z = input() Z = 0 for T in __import__('itertools').count(Z): tmp = int(z + str(T))**0.5 if int(tmp) == tmp: print(T) break ``` Token by token explanation: ``` fsI@s+zT2Z f # (Implicitly print) First value of T for which the following is true: Z # where T iterates over [Z, Z+1, Z+2, ...] with Z=0 +zT # the (string, since one of them is a string) concatenation of z and T s # Converted from string to integer @ 2 # To the 1/2 power sI # is Invariant under floor conversion to integer ``` # [Packed Pyth](https://github.com/isaacg1/pyth/blob/master/packed-pyth.py), 9 bytes Hex dump: `CD CE 4C 0E 6A FD 54 65 68` [Try it online!](https://tio.run/##XY6xCsIwAERnO/gNRxGiQ1pjq4h2cnByrKBjm0QShaTEain4C/pHTv2wakFQ3O5x3OPy7KxaJzMB6kAFCIFLErKqqlMeXfZ1vUvVrFKkbe7NY9M/Ns9Uqva/9oq6VNZECG1Rhh2ERcZPUtAuB0UNekEylFxZUAN/4HzcoLk1V9ADtumazkFLbNgIAbdCBt3OO1gHDW3AwMaIpmCzGJN5vISwXu9r0wv4Xx7ot/vnyOfBj1dYI9sX "Packed Pyth – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~35~~ ~~33~~ ~~30~~ ~~23~~ 21 bytes This is a program that uses only integer arithmetic. Since Python has arbitrary-precision integers, this is guaranteed to work for arbitrarily large numbers, whereas the square-root test used by most of the other answers fails with numbers greater than 252, having false positives with numbers very close to a perfect square. Assumes that the input has no leading zeroes. ``` f&J>K`*TTlzq+z`sJK)J ``` [Try it online!](https://tio.run/##K6gsyfhv615c5RYZ7G4bZVCgbVuVEKlkpaD0XyFNzcvOO0ErJCSnqlC7KqHYy1vT6/9/Y1ODf/kFJZn5ecX/dXVzS3NKMnMy81KB7JTUpNJ0AA "Pyth – Try It Online") The leading space is needed to suppress printout of the value of `T` that resulted in loop termination, since `f` returns that value. Ungolfed: ``` z = input() for T in __import__('itertools').count(1): K = str(T*T); J = K[len(z):] if len(J)!=0 and z+str(int(J))==K: break print(J) ``` # [Packed Pyth](https://github.com/isaacg1/pyth/blob/master/packed-pyth.py), 19 bytes Hex dump: `41 99 34 A7 D2 F0 2A A9 53 67 AE 2A FD 60 E7 2A 5A 99 40` [Try it online!](https://tio.run/##XY5BasJAAEXX5hSfIEQDk5gmlaBZtF105U4L1ZUxM3aGwEyYxoaAp3DnCaSb0gt0MzlYakBQ3P0H/z/@Jv3krWYpBdEgFI4DnSTOS1Xlm3C3rOv3BR9X3GmfzTEyp@bQ/Lrme/5hftzmb92c3JU5PrX3dauoS65kCF8Vpd@BX6RZzijpslfUIDskA5ZxBSJh97WNPUSm5BfIFm@LVxKDlJgFQ3iZoszrdtZWaQgIiQDBCOEjgnGEhziagiqrd7WJCewr98XZfXPk8uDGS5Vk7T8 "Packed Pyth – Try It Online") [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 28 bytes ``` sajpsq~!_+2R@)S[jfeupjq[-jE! ``` [Try it online!](https://tio.run/##SyotykktLixN/f@/ODGroLiwTjFe2yjIQTM4OisttbQgqzBaN8tV8f9/QwMA "Burlesque – Try It Online") Pretty sure this could be shorter, a lot of work is trying to drop N letters. ``` sa #Find the length of the input to know how many characters to drop j #Put at bottom ps #Parse the string to {int} q~! #Boxed "starts with" _+ #Concatenate to make {int !~} "starts with int" 2R@ # 2...inf )S[ #Infinite list of squares jfe #Find an element that starts with int up #Turn int to string jq[-jE! #Drop (length of int) characters leaving the tail ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` @s+X ¬v1}a ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QHMrWCCsdjF9YQ&input=Mjg0) [Answer] # [PHP](https://php.net/), ~~53~~ ~~47~~ 44 bytes ``` for($k=-1;fmod(sqrt($argn.++$k),1););echo$k; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRoMD1Py2/SEMl21bX0DotNz9Fo7iwqERDJbEoPU9PW1slW1PHUNNa0zo1OSNfJdv6/39DM5N/@QUlmfl5xf913QA "PHP – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` _siU ¬%1}f ``` Saved a byte thanks to @AZTECCO [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X3NpVSCsJTF9Zg&input=WzEsMTAsMzUsMTY0LDI4NF0KLW0gLVI) [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~21~~ 19 bytes -2 bytes from @ovs's simplification ``` {(1!%.,/$x,)(1+)/0} ``` [Try it online!](https://ngn.codeberg.page/k/#eJw9z9FqwyAUBuB7n8JBBwmrVRMjNsJepHTUOdOEJtpGhZTSPfs0G/PmHD9/L/6ufRT05XW3xZtlWxb0rcTkCUBoH5vD/XtuOwjhIk/uIotTp4ZRLvIu5/L4BOFAJT/mQSTJs25kzdgqnElRr4+VYLJq9mkHGPQhXH2LsXZf5uzGbueD0hez6F7Zs9lpN+FbND4MznpM94JWFPtJjWMyZOP0aWbko+5R6FVA2lmtgrEq59HgkUL+FtVsABjsNQaI0Dt0MaQVAJp65Hs6HBbsoyoBJf9EYEFJtrr5s9QkmRBrkLNfTJ3SX8IzpmIr5nIpyUXWH4ZRWvo=) * `(cond)(code)/seed` set up a while-reduce, seeded with `0`, running the `(code)` clause until the `(cond)` clause returns a non-truthy value + `(1+)` code that increments its input + `(1!%.,/$x,)` the condition/check - `.,/$x,` append the current iteration value to the original input, convert each to a string, combine them, and eval the result (this converts the result to an integer) - `1!%` check if the remainder of the square root of the iteration value is non-zero [Answer] # JavaScript (Node.js), 38 Bytes [Try it Online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@18jUSfJNtogVtPWTiNRO0lTS0vPVNXQPg0oHq2tnRSraaWd9D85P684PydVLyc/XSNNw1BTkwtNxABDyNgUU5WZCYaYkQVQ7D8A) ``` f=(a,b=[0])=>(a+b)**.5%1?f(a,[++b]):+b ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` 0ṭVƲɗ1# ``` [Try it online!](https://tio.run/##y0rNyan8/9/g4c61YYfbDm06Od1Q@b/1o4Y5Crp2Co8a5lofbuc63P6oaU3k///RhjpchgY6XMamQNrMRIfLyMIkFgA "Jelly – Try It Online") A monadic link taking as its argument an integer and returning an integer. ## Explanation ``` 0 ɗ1# | Starting with zero, find 1 integer where the following is true as a dyad, using the original argument as the right argument ṭ | - Tag onto the end V | - Evaluate after converting to string and concatenating Ʋ | - Check if perfect square ``` [Answer] # [Perl 5](https://www.perl.org/), ~~35~~ 40 bytes ``` $k=0;L:$_="$n$k"**.5;!/\./ or$k++,goto L ``` [Try it online!](https://tio.run/##DcPdCoMgGADQe5/im3xBf1YuHWPOnqBHCLoYtcKmYsEuxp7d7cDxU9hkfC/rNkF67zL4EIDH4l4@RatxzFREoxvV33DUFC0amueVVKd6qGpwAU1RlE93OOij8mG1xww0Ye0OjHWQiH2wtAS0/wa@kRPekFYSfhHkfBU/ "Perl 5 – Try It Online") [Answer] # [cQuents](https://github.com/stestoltz/cQuents), 13 bytes ``` #|1:#bA~N ?$$ ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/X7nG0Eo5ybHOj8teReX/f2NTAA "cQuents – Try It Online") ## Explanation ``` #|1 output nth element in sequence (remove to output indefinitely) : mode: sequence, output nth element in sequence # conditional: count N up, when true, add to sequence b call second line, passing A~N input concatenated to N ?$$ second line - sequence of squares - return true if a square and false if not ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` ≔⁰ηW﹪₂I⁺θη¹≦⊕ηIη ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DQEchQ9OaqzwjMydVQcM3P6U0J18juLA0sSg1KD@/RMM5sbhEIyCntFijEKRSU1NHwVBTU8E3sQBqgGdeclFqbmpeSWoKxKiAosw8qD6geuv//40sTP7rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⁰η ``` Initialise the result to zero. ``` W﹪₂I⁺θη¹ ``` Repeat until the concatenation is a square. ``` ≦⊕η ``` Increment the result. ``` Iη ``` Output the result. 36 bytes for an efficient solution: ``` ≔×χNη ``` [Try it online!](https://tio.run/##jc6/CsIwEAbw3afIeIEIWhyETlJQBJXS@gKxhuQgTdr8sY8fU8Wlk8sNx3e/@zrFXWe5TungPUoDd@yFh@2GkbMZYrjF/iEcUMqIouXqyodvrkGpAtQ6ekZOTvCQQ@0YuRONtQFUzh@1tYvlj5kUakHgiOYJFfcZslMGKoEajVzcMFLMY6SULN5/ujIyl53V2qEJ0GrsxN/qRRgZFGSclikV@11av/Qb "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Multiply the input by 10. ``` ≧⁺›₂η⌊₂ηη ``` Increment it unless it is already a square number. ``` W⌕IX⌈₂η²θ ``` Repeat until the square ceiling square root begins with the original input. ``` ≧×χ ``` Multiply by 10. ``` η✂IX⌈₂η²Lθ ``` Output the suffix of the square ceiling square root. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 24 bytes I don't feel right to have a Burlesque answer without a GolfScript answer.(Please don't mind if this is a little bit slow, although they seem to produce the right result.) ``` -1{).2$\+~.),{.*}%?)!}do ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/X9ewWlPPSCVGu05PU6daT6tW1V5TsTYl//9/QwMjAA "GolfScript – Try It Online") ## Explanation ``` -1 # The counter for the current number (it is >= 0) { # Do at least 1 time until the number is a square number ) # Increment the counter . # Copy the counter (to create an integer) 2$ # Extract the 3rd-to-top to the top \ # Make sure that the casting to string works + # Join the numbers, as well as converting the # right operand to a string (input+count) ~ # Evaluate the string to get a number . # Copy the number for the square number check ), # Generate range from 0 to the number {.*}% # Apply square for every number ? # Find out where the number is inside the sequence # (yields -1 for nonexistent) ) # Increment, to make nonexistent false and others true ! # Negate, which means we shouldn't find the first non-square number. }do # End do loop, use TOS as condition # Output the counter at the end ``` ``` [Answer] # AWK, 29 bytes ``` {while(($0x++)^.5%1);$0=x-1}1 ``` Works with `mawk`, `gawk` and `nawk` on macOS and Ubuntu but not with [TiO](https://tio.run/##SyzP/v@/ujwjMydVQ0PFoEJbWzNOz1TVUNNaxcC2Qtew1vD/f0MA "AWK – Try It Online") for some reason. [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 13 bytes ``` x={x\.nš1%¬}é ``` # Explanation ``` x={x\.nš1%¬}é # x= # Set 'x' to the input. { }é # Run the enclosed function with raising integers untill it returns truthy, and spit out that number x\. # Place the input under the current number and concatenate them together nš # Convert to a number and get the square root 1%¬ # Is this a whole number? ``` [Try it online!](https://tio.run/##Kyooyk/P0zX6/7/CtroiRi/v6EJD1UNrag@v/P//v5GFCQA "RProgN 2 – Try It Online") [Answer] # Java, ~~75~~ ~~63~~ 61 bytes Two bytes less thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). And another two less in the second version again thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)! ``` n->{int j=0;for(;Math.sqrt(new Long(n+j))%1>0;j++);return j;} ``` [Try it online!](https://tio.run/##LY7BisIwFEXX7Ve8jZDQMVQY3EQLboSBmZVLcRFrWpOpLzF5cRDpt2cqurtwLpxj1U3NnddoT7@5HVSMsHmURSRFpgU7UZHIDKJL2JJxKLbvsdpRMNh/wBeS7nVooIN1xnnzMEhg17XsXGDyR9FZxGsghvoPvh32DCvL@WzR1NJWFZdBUwoIVo5Zlj4dh8n71t@cOcFFGWQv2f4AKvSRT4HF7h5JX4RLJPzEiHVCeT/c2fOxrw@cy7IYyzHnxfLzHw) I also have another version with my first (and very different) approach, which is ~~107~~ ~~92~~ ~~93~~ 91 bytes long: ``` n->{String a;for(long i=4;!(a=i*i+++"").matches(n+"([1-9].*|0)"););return a.split(n,2)[1];} ``` [Try it online!](https://tio.run/##LY5BasMwFETX9ikUr6Q4FnEJhaI60E0vkKXx4texEzmyJKSvQEh9dlXFWc0MMzBvgjtUxg56Ot9ir8B78vXMM4@AsidTanlAqfgYdI/SaP79Mp8ndFJfdmTVIxlJE3V1fK6ZgBiNo8okK5uD2FBo5FaWZVkUjM@A/XXwVJcFbevqo@Pb3z0rmGDCDRicJsC9VRKp3r2xtu7EEkVuw49KUC@2u5FnMoPUdH1sOwLu4lmiz04Pj8PMTUBuU4d05GCtetD/RbvvGBN5tuRLjPX74Q8) Both version have been tested against the first [10000 numbers](https://oeis.org/A071176/b071176.txt). [Answer] # [Haskell](https://www.haskell.org/), ~~93~~ 88 bytes ``` [j|i<-(show.(^2))<$>[0..],i/=n,n`isPrefixOf`i,j<-[drop(length n)i],j=="0"||j!!0/='0']!!0 ``` [Try it online!](https://tio.run/##PY1BT4NAEIXv@yumxKaQwBZaNB6gF/WmsUm9EUw3ssggzJLd1daIvx2BqLeX75t5rxLmTTbNgG2ntIUbRVarhj8oEgW4tULy2K@7FVbwezT2Dxw@jZUtv6MP1IpaSf/mSZ4t32skWzLWCiRIoVAMoJEWytbCBLrZg7MMtgaCYAfL2DijcUsYRwFGK7V4seC@U4MkDXBoRTf/c5jJdHaqpJbwBeVUOmR1j0ngmkqduPu88bzkYpeFnOc@rlPy6Yhmr2WJ58fyiH6dBFmhVec2kl5tNe5i7tdp6oRO39eLRbhOV@EqH8PwPUQsCtn2kkVXMdtcxz8 "Haskell – Try It Online") [Answer] # [PHP](https://php.net/), ~~83~~ 86 bytes ``` g:substr($k=$i*++$i,0,$l=strlen($n=$argn))==$n&&("$k")[$l]&&die(substr($k,$l));goto g; ``` [Try it online!](https://tio.run/##PctBCsIwEAXQq5TyCRlboW6tgzsvIS4qljQ0TIYmXr9jV24fPF3UbnddtLFwLd93qZvHyoinrkPshx6JD0uzeAhj2oIQMUOc8y3Wlp5IL@c@cfb/fRyiMeSamzCaXYY9a41Zip0fPw "PHP – Try It Online") -9 bytes thanks to @640KB and bugs fixed (+12). Only fails for case 10 currently. ## Ungolfed ``` <?php $number=$argv[1]; $len = strlen($number); $i=0; do { $k = $i*$i; if (substr($k,0,$len)==$number && substr($k,$len,1)!='0') { die(substr($k,$len)); } $i++; } while (true); ?> ``` [Try it online!](https://tio.run/##VY3BDoIwEETv@xVrsoFWOJRzrXyI8SChygbEpoAeDN9ei5AY57S7b2bWNS6EQ@kaB0D9dK@sN3Txt@epOGugzvZocBh9HMTGZbyzURrqB74Bo6iNJuI9sf7ufEUxTFWMCWpzlS810pgtj0mCP7qwvJA7k6pUbn2Larbi3yXl2j6vPznLNMz4arizKEY/2cihPIYQCvUB "PHP – Try It Online") ]
[Question] [ Given a positive integer `n`, simplify the square root `√n` into the form `a√b` by extracting all square factors. The outputted `a,b` should be positive integers with `n = a^2 * b` with `b` as small as possible. You may output `a` and `b` in either order in any reasonable format. You may not omit outputs of `1` as implicit. The outputs for `n=1..36` as `(a,b)`: ``` 1 (1, 1) 2 (1, 2) 3 (1, 3) 4 (2, 1) 5 (1, 5) 6 (1, 6) 7 (1, 7) 8 (2, 2) 9 (3, 1) 10 (1, 10) 11 (1, 11) 12 (2, 3) 13 (1, 13) 14 (1, 14) 15 (1, 15) 16 (4, 1) 17 (1, 17) 18 (3, 2) 19 (1, 19) 20 (2, 5) 21 (1, 21) 22 (1, 22) 23 (1, 23) 24 (2, 6) 25 (5, 1) 26 (1, 26) 27 (3, 3) 28 (2, 7) 29 (1, 29) 30 (1, 30) 31 (1, 31) 32 (4, 2) 33 (1, 33) 34 (1, 34) 35 (1, 35) 36 (6, 1) ``` These are OEIS [A000188](https://oeis.org/A000188) and [A007913](https://oeis.org/A007913). Related: [A more complex version](https://codegolf.stackexchange.com/q/18535/20260). ``` var QUESTION_ID=83814,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/83814/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] # [Jelly](http://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆE;0d2ZÆẸ ``` [Try it online!](http://jelly.tryitonline.net/#code=w4ZFOzBkMlrDhuG6uA&input=&args=MjQ) or [verify all test cases](http://jelly.tryitonline.net/#code=w4ZFOzBkMlrDhuG6uAozNsOH4oKsRw&input=). ### How it works ``` ÆE;0d2ZÆẸ Main link. Argument: n ÆE Exponents; generate the exponents of n's prime factorization. ;0 Append 0 since 1ÆE returns []. d2 Divmod by 2. Z Zip/transpose to group quotients and remainders. ÆẸ Unexponent; turn the exponents of prime factorizations into integers. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 6 bytes ``` ²×¥þœi ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLCssOXwqXDvsWTaSIsIjM2w4figqxVRyIsIiIsW11d) TFW [you outgolf Dennis by 33%](https://codegolf.stackexchange.com/a/83815/78410) :P Outputs `[b, a]`. This does not use any prime factorization built-ins. Instead, it uses an array-oriented built-in `œi` (multi-dimensional index of), which is interestingly not found in any of APL/J/K/BQN. ### How it works ``` ²×¥þœi Monadic link. Input: the positive integer n. ²×¥þ Compute the table of (x^2 * y) for both x and y in 1..n For n = 3, this returns: × | 1 4 9 --+-------- 1 | 1 4 9 2 | 2 8 18 3 | 3 12 27 œi Find the multi-dimensional index of n in the matrix above [3, 1] ``` Since it finds the first occurrence in the matrix, `b` (first index) is guaranteed to be minimized, and `n` always appears at least once in the matrix at the coordinates `[n, 1]`. [Answer] # Python 2, 43 bytes ``` k=n=input() while n%k**2:k-=1 print k,n/k/k ``` Test it on [Ideone](http://ideone.com/ksc9Ch). [Answer] ## PARI/GP, 12 bytes ``` n->core(n,1) ``` `core` returns the squarefree part of `n` by default, but setting the second argument flag to 1 makes it return both parts. Output order is `(b, a)`, e.g. `(n->core(n,1))(12) -> [3, 2]`. [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` t:U\~f0)GyU/ ``` [**Try it online!**](http://matl.tryitonline.net/#code=dDpVXH5mMClHeVUv&input=MTg) ### Explanation ``` t % Take input n implicitly. Duplicate :U % Push [1 4 9 ... n^2] \~ % True for entries that divide the input f0) % Get (1-based) index of the last (i.e. largest) dividing number G % Push input again y % Duplicate index of largest dividing number U % Square to recover largest dividing number / % Divide input by that. Implicitly display stack ``` [Answer] # Julia, 32 bytes ``` \(n,k=n)=n%k^2>0?n\~-k:[k,n/k^2] ``` [Try it online!](http://julia.tryitonline.net/#code=XChuLGs9bik9biVrXjI-MD9uXH4tazpbayxuL2teMl0KCmZvciBuIGluIDE6MzYKICAgIEBwcmludGYoIiUyZCAtPiAlc1xuIiwgbiwgXChuKSkKZW5k&input=) [Answer] # Mathematica 34 bytes ``` #/.{a_ b_^_:>{a, b},_[b_,_]:>{1,b}}& ``` This says to replace all the input (`#`) according to the following rules: (1) a number, **a**, times the square root of **b** should be replaced by `{a, b}` and a function b to the power of whatever should be replaced by {1,b} . Note that the function assumes that the input will be of the form, `Sqrt[n]`. It will not work with other sorts of input. This unnamed function is unusually cryptic for Mathematica. It can be clarified somewhat by showing its full form, followed by replacements of the original shorter forms. ``` Function[ ReplaceAll[ Slot[1], List[ RuleDelayed[Times[Pattern[a,Blank[]],Power[Pattern[b,Blank[]],Blank[]]],List[a,b]], RuleDelayed[Blank[][Pattern[b,Blank[]],Blank[]],List[1,b]]]]] ``` which is the same as ``` ReplaceAll[ #, List[ RuleDelayed[Times[Pattern[a,Blank[]],Power[Pattern[b,Blank[]],Blank[]]],List[a,b]], RuleDelayed[Blank[][Pattern[b,Blank[]],Blank[]],List[1,b]]]]& ``` and ``` ReplaceAll[#, List[RuleDelayed[ Times[Pattern[a, Blank[]], Power[Pattern[b, Blank[]], Blank[]]], {a, b}], RuleDelayed[Blank[][Pattern[b, Blank[]], Blank[]], {1, b}]]] & ``` and ``` ReplaceAll[#, List[RuleDelayed[Times[a_, Power[b_, _]], {a, b}], RuleDelayed[Blank[][b_, _], {1, b}]]] & ``` and ``` ReplaceAll[#, {RuleDelayed[a_*b^_, {a, b}], RuleDelayed[_[b_, _], {1, b}]}]& ``` and ``` ReplaceAll[#, {a_*b^_ :> {a, b}, _[b_, _] :> {1, b}}] & ``` [Answer] ## 05AB1E, 14 bytes ``` Lv¹ynÖi¹yn/y‚ï ``` **Explained** ``` Lv # for each x in range(1,N) inclusive ¹ynÖi # if N % x^2 == 0 ¹yn/y‚ï # create [N/x^2,x] pairs, N=12 -> [12,1] [3,2] # implicitly output last found pair ``` [Try it online](http://05ab1e.tryitonline.net/#code=THbCuXluw5Zpwrl5bi954oCaw68&input=MTI) [Answer] # Python, 74 Bytes ``` def e(k):a=filter(lambda x:k/x**2*x*x==k,range(k,0,-1))[0];return a,k/a**2 ``` Straightforward enough. [Answer] # Pyth, 15 bytes ``` /Q^ ef!%Q^T2SQ2 ``` [Test suite.](http://pyth.herokuapp.com/?code=%2FQ%5E%0Aef%21%25Q%5ET2SQ2&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A21%0A22%0A23%0A24%0A25%0A26%0A27%0A28%0A29%0A30%0A31%0A32%0A33%0A34%0A35%0A36&debug=0) [Answer] ## Matlab, 51 bytes ``` x=input('');y=1:x;z=y(~rem(x,y.^2));a=z(end) x/a^2 ``` **Explanation** ``` x=input('') -- takes input y=1:x -- numbers from 1 to x z=y(~rem(x,y.^2)) -- numbers such that their squares divide x a=z(end) -- biggest such number (first part of output) x/a^2 -- remaining part ``` [Answer] # JavaScript (ECMAScript 2016), 40 bytes ``` n=>{for(k=n;n%k**2;k--);return[k,n/k/k]} ``` Basically a JavaScript port of [Dennis's Python 2 answer](https://codegolf.stackexchange.com/a/83819/41298). [Try it on JSBin](https://jsbin.com/gusatiqutu/1/edit?js,console). Note: it doesn't work in strict mode, because `k` is not initialized anywhere. To make it work in strict mode, `k=n` in the loop should be changed to `let k=n`. [Answer] # Haskell, ~~43>~~ 42 bytes Brute force solution. Saved 1 byte thanks to Xnor ``` f n=[(x,y)|y<-[1..],x<-[1..n],x*x*y==n]!!0 ``` [Answer] ## APL, 25 chars ``` {(⊢,⍵÷×⍨)1+⍵-0⍳⍨⌽⍵|⍨×⍨⍳⍵} ``` In English: * `0⍳⍨⌽⍵|⍨×⍨⍳⍵`: index of the largest of the squares up to n that divides completely n; * `1+⍵-`: the index is in the reversed array, so adjust the index * `(⊢,⍵÷×⍨)`: produce the result: the index itself (a) and the quotient b (that is, n÷a\*a) Test: ``` ↑{(⊢,⍵÷×⍨)⊃z/⍨0=⍵|⍨×⍨z←⌽⍳⍵}¨⍳36 1 1 1 2 1 3 2 1 1 5 1 6 1 7 2 2 3 1 1 10 1 11 2 3 1 13 1 14 1 15 4 1 1 17 3 2 1 19 2 5 1 21 1 22 1 23 2 6 5 1 1 26 3 3 2 7 1 29 1 30 1 31 4 2 1 33 1 34 1 35 6 1 ``` [Answer] # JavaScript (ECMAScript 6), 35 bytes ``` f=(n,k=n)=>n/k%k?f(n,--k):[k,n/k/k] ``` # JavaScript 1+, 37 B ``` for(k=n=prompt();n/k%k;--k);[k,n/k/k] ``` [Answer] # [J](http://jsoftware.com/), 19 bytes ``` (0|:0 2#:])&.(_&q:) ``` [Try it online!](https://tio.run/##y/r/P81WT0HDoMbKQMFI2SpWU01PI16t0Erzf2pyRr5CmoK5EReUZWIAYeno6ccbmWroqKlbKag7aBirKVlp6mjoqMcZaanrmKtV62kCRfQd0jSVDGIUDLUz9QwNDP4DAA) Same as [the Jelly solution](https://codegolf.stackexchange.com/a/83815/74681). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` K'∆²;t₍/√ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=K%27%E2%88%86%C2%B2%3Bt%E2%82%8D%E2%88%9A%2F&inputs=50&header=&footer=) Very cool and good. Outputs as `[constant, surd]` ## Explained ``` K'∆²;t₍√/ K # from the factors of the input, '∆²; # keep only square numbers t # and keep the last. ₍√/ # Push [sqrt(^), input / ^] ``` [Answer] **Python 2.7 (ungolfed) - 181 Bytes** ``` def e(n): for x in range(1,n+1): r=(1,x) for i in range(1,x+1): l=i**.5 for j in range(1,x+1): if i*j==x and l%1==0 and j<r[1]:r=(int(l),j) print x,r ``` Run as: e(number) eg. e(24) Sample output: ``` >> e(24) 1 (1, 1) 2 (1, 2) 3 (1, 3) 4 (2, 1) 5 (1, 5) 6 (1, 6) 7 (1, 7) 8 (2, 2) 9 (3, 1) 10 (1, 10) 11 (1, 11) 12 (2, 3) 13 (1, 13) 14 (1, 14) 15 (1, 15) 16 (4, 1) 17 (1, 17) 18 (3, 2) 19 (1, 19) 20 (2, 5) 21 (1, 21) 22 (1, 22) 23 (1, 23) 24 (2, 6) ``` ]
[Question] [ Inspired by [a recent Daily WTF article](https://thedailywtf.com/articles/ternt-up-guid)... Write a program or function that takes a GUID (string in the format `XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX`, where each X represents a hexadecimal digit), and outputs the GUID incremented by one. ## Examples ``` >>> increment_guid('7f128bd4-b0ba-4597-8f35-3a2f2756dfbb') '7f128bd4-b0ba-4597-8f35-3a2f2756dfbc' >>> increment_guid('06b86883-f3e7-4f9d-87c5-a047e89a19fa') '06b86883-f3e7-4f9d-87c5-a047e89a19fb' >>> increment_guid('89f25f2f-2f7b-4aa6-b9d7-46a98e3cb2cf') '89f25f2f-2f7b-4aa6-b9d7-46a98e3cb2d0' >>> increment_guid('89f25f2f-2f7b-4aa6-b9d7-46a98e3cb29f') '89f25f2f-2f7b-4aa6-b9d7-46a98e3cb2a0' >>> increment_guid('8e0f9835-4086-406b-b7a4-532da46963ff') '8e0f9835-4086-406b-b7a4-532da4696400' >>> increment_guid('7f128bd4-b0ba-4597-ffff-ffffffffffff') '7f128bd4-b0ba-4598-0000-000000000000' ``` ## Notes * Unlike in the linked article, incrementing a GUID that ends in F must “carry” to the previous hex digit. See examples above. * You may assume that the input will not be `ffffffff-ffff-ffff-ffff-ffffffffffff`. * For hex digits above 9, you may use either upper (A-F) or lower (a-f) case. * Yes, GUIDs may start with a `0`. * Your output must consist of *exactly* 32 hex digits and 4 hyphens in the expected format, including any necessary leading `0`s. * You do not have to preserve the version number or other fixed bits of the GUID. Assume it's just a 128-bit integer where none of the bits have any special meaning. Similarly, GUIDs are assumed to sort in straightforward lexicographical order rather than in the binary order of a Windows `GUID` struct. * If writing a function, the input may be of any sequence-of-`char` data type: `string`, `char[]`, `List<char>`, etc. [Answer] # [Python 2](https://docs.python.org/2/), 50 * 3 bytes saved thanks to @Dennis. ``` lambda s:UUID(int=UUID(s).int+1) from uuid import* ``` [Try it online!](https://tio.run/##K6gsycjPM/qfpmCrEPM/JzE3KSVRodgqNNTTRSMzr8QWzCjW1AOytQ01udKK8nMVSkszUxQycwvyi0q0/hcUAaUU0jSUzNMMjSySUkx0kwySEnVNTC3NdS3SjE11jRON0ozMTc1S0pKSlDT/AwA "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 85 bytes The output string is in lowercase. ``` s=>(g=(c,x=+('0x'+s[--n])+!!c)=>1/x?g(x>>4)+(x&15).toString(16):~n?g(c)+'-':'')(n=36) ``` [Try it online!](https://tio.run/##bYvBCoJAFADv/UWX9j22Z5q6WbAGQf5Ax@igqyuG7EZK7KlfNyk8FM1hLsNc80feqXtz68nYshq0HDqZQi1BLZ3kwHzHeHcmMhfk87lCmQYrt6/BpWmEHNwiiNHr7am/N6aGQODuacaskDNiO8YQjAwFDsqazraV19oaNLCk8vU2CWOK/ESMEgUVmzyiOFyXeSS2ItSaIc5@t6OffW0Hykbemvi36Q/0RxPjNrwA "JavaScript (Node.js) – Try It Online") ### Commented ``` s => ( // s = GUID g = ( // g = recursive function taking: c, // c = carry from the previous iteration x = +('0x' + s[--n]) // x = decimal conversion of the current digit + !!c // add the carry ) => // 1 / x ? // if x is numeric: g(x >> 4) + // do a recursive call, using the new carry (x & 15) // and append the next digit .toString(16) // converted back to hexadecimal : // else: ~n ? // if n is not equal to -1: g(c) // do a recursive call, leaving the current carry unchanged + '-' // and append a hyphen : // else: '' // stop recursion )(n = 36) // initial call to g with n = 36 and a truthy carry ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ ~~15~~ 18 bytes Saved 2 bytes thanks to *Kevin Cruijssen* ``` '-K1ìH>h¦Ž¦˜S·£'-ý ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fXdfb8PAaD7uMQ8uO7j207PSc4EPbDy1W1z289/9/A1eDNEsLY1NdEwMLMyBhlqSbZJ5oomtqbJSSaGJmaWaclgYA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##jY09CsJAEEb7vUgaBzaz/42dIFh6gplsBq0sBEHwKHZCKnurNBusPNQaBDsLX/G6732HI/G@r5fTuTawaaf7erkrw3Msw@u6LY9ya2Aa66IGaTFytsCaCaxLAaIYB4ZQMDifhVnFJOgEBVACgyXywCkHsJ5S7E3H2ImKKy0pzlOro5/lGTiQBWcwk/XJGxH1405mPvqi9B@lNw) **Explanation** ``` '-K # remove "-" from input 1ì # prepend a 1 (to preserve leading 0s) H # convert from hex to base 10 > # increment h # convert to hex from base 10 ¦ # remove the extra 1 Ž¦˜S· # push [8, 4, 4, 4, 12] £ # split into parts of these sizes '-ý # join on "-" ``` [Answer] # [Python 2](https://docs.python.org/2/), 82 bytes ``` q='f0123456789abcdef--' f=lambda s:[str,f][s[-1]in'f-'](s[:-1])+q[q.find(s[-1])+1] ``` [Try it online!](https://tio.run/##jY3LasNADEX3/orsxiZVGWvegXyJ8ULyWNTQunHsTb/edZumNBBIz@KC0NXR6WN5eR9xXaejEl2jsc6HmIi73AuAKuT4Sm@caTcfmnk5P0nbzA3U7TAqAdWWc3PYpmo/NdOzDGMuv7fVvm7X03kYl52UKkiNkbMF1kxgXQoQxTgwhILB@SzMqir@0@tUUfx6YxJ0ggIogcESeeCUA1hPKfamY@zky/u4l/WNt9eS4vbY6ui38AwcyIIzmMn65I1cvI96Vt949Q9wJ65s3j8HcgHuxBVVrZ8 "Python 2 – Try It Online") No imports or hex conversion. This scans from the back of the string, moving each character along the cycle `0123456789abcdef`, with `-` going to itself. After it hits a symbol other than `f` or `-`, it stops scanning leftwards, and just returns the remainder unchanged. This solution isn't specific to the UUID format -- any number of blocks of any number of hex letters would work. The base case of `[str,f][s[-1]in'f-'](s[:-1])` is a trick I haven't seen used in a golf before. It terminates the recursion without any `if`, `and`, `or`, or other explicit control flow. Based on the condition `[s[-1]in'f-']` of the last character, the code either returns `f(s[:-1])` or just `s[:-1]` unchanged. Since `str` is the identity on strings, we can select one of the functions `[str,f]` and apply it to `s[:-1]`. Note that the recursive call with `f` is not made if it is not chosen, getting around the common issue problem that Python eagerly evaluates unused options, leading to infinite regress in recursions. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 46 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous tacit prefix function. ``` ⎕CY'dfns' (∊1hex 16(|+1⌽=)⍣≡1+@32dec¨)@('-'≠⊢) ``` [Try it online!](https://tio.run/##jY@9SgNBFIX7PMV0syEM7M7Ozs4WQiCNqQRjY3lnZq8RQiLZxoCFIASzmKCIpeBPY@cT2ORR7ousw4Z0QjzFgQsf3@XA1UT4BUxmF01Dm5fBOfc4rXgnovs6GZfXLNHRTS@hh5@jLq0/afWe9Pqp9KXbfnX7ERecVm9Uf3QbpOUjrTdBMjyh@m77ndLyKVyj00Hos@PhqEHGc0yksV4JG1sQKityYTDNRAoSZZ5pj9ZyRutX9g/SdYLRFCgzlCgk5lYoAC1s4XOhNBSmTJ2VDnfGw6SPW2MZY2HCKxUbHUpbYXNQIgu7QelCp7g3HiJV3Br/2IIhbe2zMzqYzxeMg5vPqoozD9WY0e0zG8HUjS@rsvoF "APL (Dyalog Unicode) – Try It Online") `⎕CY'dfns'` **c**op**y** [the "dfns" library](http://dfns.dyalog.com/n_contents.htm) (to get [`hex` and `dec`](http://dfns.dyalog.com/n_hex.htm "Dyalog APL - Hexadecimal from decimal.")) `(`…`)`  `⊢` the argument  `≠` differs from  `'-'` a dash `(`…`)@` on the subset consisting of the locations **at** which the above criterion is true, apply:  `[dec](http://dfns.dyalog.com/c_dec.htm "Dyalog APL - Decimal from hexadecimal.")¨` convert each hexadecimal character to a decimal number  …`@32` **at** position 32 (the last digit), apply:   `1+` increment  `16(`…`)⍣≡` repeatedly apply with left argument 16 until stable:   `=` compare (gives mask where the hexadecimal digits are 16)   `1⌽` cyclically rotate one step left (this is the carry bit)   `|+` to that, add the division remainder when divided (by sixteen, thus making all 16 into 0)  `1[hex](http://dfns.dyalog.com/c_hex.htm "Dyalog APL - Hexadecimal from decimal.")`  turn digits into length-one hexadecimal character representations  `∊` **ϵ**nlist (flatten) [Answer] # Java 11, ~~152~~ ~~149~~ ~~111~~ 108 bytes ``` s->{var b=s.getLeastSignificantBits()+1;return new java.util.UUID(s.getMostSignificantBits()+(b==0?1:0),b);} ``` -38 bytes thank to *@OlivierGrégoire*. -3 bytes thanks to *@ASCII-only*. [Try it online.](https://tio.run/##rVDLasMwELznK0RONq2MI8uvGrdQeik0uYScSg8rWwpKHTlYckoJ/nZXeV2CL607hwGtdmdmdwN7wJvysy8q0BrNQarDBCGpDG8EFBwtjk@ENrbPa42svNXq9QUVzk1Bu5nt6yaWtAEjC7RACuW9xo@HPTSI5dpbc/PGQZulXCspZAHKPEujHfduljXctI1Cin/dWDmnuXk9NOawPPefZg@@e8/crOuzo/2uZZW1v6TY17JEW7uVszSNVOv3DwTueaXltzZ869Wt8Xb2y1TKUd7tYp5o6u151JnGYkYSVlLMfAaYhmmMExGEOAAiSBxGpWBs6rqnU/xFP0kFCQURmIiYYQoQYZaWMaYRpAkPCkYKMUqf@yJNbGDqJ5GliGEWA8VhQEqgURoFYpT@wH2ExYmuGJX/ooEH6D/0/QvwAF0xRp//In836fof) **Explanation:** ``` s->{ // Method with UUID as both parameter and return-type var b=s.getLeastSignificantBits() // Get the 64 least significant bits of the input-UUID's 128 bits as long +1; // And increase it by 1 return new java.util.UUID( // Return a new UUID with: s.getMostSignificantBits() // The 64 most significant bits of the input-UUID's 128 bits as long +(b==0? // And if the 64 least significant bits + 1 are exactly 0: 1 // Increase the 64 most significant bits by 1 as well : // Else: 0, // Don't change the 64 most significant bits by adding 0 b);} // And the 64 least significant bits + 1 ``` --- **Old 149 bytes answer:** ``` s->{var t=new java.math.BigInteger(s.replace("-",""),16);return(t.add(t.ONE).toString(16)).replaceAll("(.{4})".repeat(5)+"(.*)","$1$2-$3-$4-$5-$6");} ``` [Try it online.](https://tio.run/##hZAxT8MwEIX3/grLymADZ7WO4ySqigQSAwNlYEQM58QuKWlaJW4RqvLbi1vCgop6w5N9tr97z0vcISzLj0NRY9eRJ6ya/YiQqvG2dVhYMj9uCXnxbdUsSMGGRcenod@PgnQefVWQOWnI7NDB7X6HLfGzxn6SZaCLFfp3cV8tHgNzYVvWidZu6sBmFOgNpfxmovm0tX7bNswLLMugz/MHLvz6ZxoLF/jvq7u6ZpSJveo5PfYsepbw69C64gEXTSIJUQyRgiiBSFM@7Q/To8/N1tTB52B3t65Ksgpxh0SvbwT5kPWr83Yl1lsvNuHI1w1rRMFo6iYyM6UCMzYIKslTyFycQIzSyTTRpTOG8tPH/A/JcicTJx1IlxpQiBpMXqagNOaZjQsjC3cZYscuz8JoNc50EG3ApKggiWWJSuc6dpchZ@K4UCf5rctOhotwRv5A@lF/@AY) **Explanation:** ``` s->{ // Method with String as both parameter and return-type var t=new java.math.BigInteger( // Create a BigInteger s.replace("-",""), // Of the input-string with all "-" removed 16); // Converted from Hexadecimal return(t.add(t.ONE) // Add 1 .toString(16)) // And convert it back to a Hexadecimal String .replaceAll("(.{4})".repeat(5)+"(.*)", // And split the string into parts of sizes 4,4,4,4,4,rest "$1$2-$3-$4-$5-$6");} // And insert "-" after parts of size 8,4,4,4, // and return it as result ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-pl`, ~~62~~ ~~57~~ 55 bytes ``` $_="%032x"%-~gsub(?-,"").hex 7.step(22,5){|i|$_[i]+=?-} ``` [Try it online!](https://tio.run/##bY7LSgNBEEX3/RlDAgmmQqf6Vb0I@RCRUDXdFQfEDE4CEaOfbjsI7jyLs7oc7ttV3ltbHPfd0jq8dUv4Ok1XWR1g03Xr7XO9mbSdLnVcIW7C@uM@3BfHx@HpYX@Az9aS7pCkeBArDD7kBKQugGNUTCEWFTE2CkUiB@pqAq@5AKU@AFufKmXeZWVDWTEoKqAmAc8cQXKZ55EzVdcL9mqoWs00972lOCsKSGIPwWFhH3N0quafTzrzqz@@z@NlOL9ODcaXHw "Ruby – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 50 bytes ``` from uuid import* lambda u:UUID(int=UUID(u).int+1) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehtDQzRSEztyC/qESLKycxNyklUaHUKjTU00UjM6/EFswo1dQDsrUNNf@nKdgqEFLEVVAEZGikaaibpxkaWSSlmOgmGSQl6pqYWprrWqQZm@oaJxqlGZmbmqWkJSWra2r@BwA "Python 3 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~113~~ 112 bytes ``` def f(s):a=hex(int(s.replace('-',''),16)+1+2**128);return'-'.join((a[3:11],a[11:15],a[15:19],a[19:23],a[23:-1])) ``` [Try it online!](https://tio.run/##jY3NagJBEITvPkVuM6PbMv9/IU8iHmZ2p1EJ67JuIHn6zagxRBBMHYqCrv5q@Jp2x17Oc1fwBemJxfS2K59030/0tB7L8J7aQgmQhhDWCMtWYiWXSyE9ex3L9DH29bY@HPc9pWmjohDbJm2EiMJcgokiXEKIUp2DVBHElrF5GOtGnSQOKy13GjLPCbQJDjwqAypJlM7YDnMmbPGfXksWi1@uDygNSgSJLoNOyUIOnQNtU/BFtVm2eOY@73X8jls4Bl@HNfe2ms2QXdJglOyStsEqvHKf9TS/4/IfwQO7qXL/POBV8MBuImz@Bg "Python 2 – Try It Online") Without imports [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 21 bytes ``` T`FfdlL`0dlL`.[-Ff]*$ ``` [Try it online!](https://tio.run/##bc2xCgIxEITh/p5DQYSVuNkkmxc4G0s7EW7X3IAgFuL7x1Ow8y@@bpjn/Lo9rK83h6mfphHtfpzCh92ZRly2q94L9qzehDy4kaRaSBETRWNwSbnBfdAKTmAQoziJWSavrZBkqzrHq/MVg84BVZepBM0L2cmLCaXIzSTXHIHhzx2Wvvx6Aw "Retina 0.8.2 – Try It Online") Link includes test cases. `9` becomes `a`. Explanation: The regex matches all trailing `f`s and `-`s plus one preceding character. The transliteration then cyclically increments those characters as if they were hex digits. Alternate approach, also 21 bytes: ``` T`L`l T`fo`dl`.[-f]*$ ``` [Try it online!](https://tio.run/##bY2xCgIxEAX7fIeCCCvnJtkkX2BjeZ0I2b3cA@E4Qfz/eAh2TjHdMK/5/Vi17w@X2sd6rYsbK561LfV0I9yPu94TzpytBbLBlEIsiTJ8JK8MTlEazFwu4AgGMZJRUBWy0hIF0ZJnPxlPcHkeUPKWhiHLJjGypIGi56ZBinjA/dlh46sfHw "Retina 0.8.2 – Try It Online") Link includes test cases. Works by lowercasing the input to simplify the transliteration. Would therefore be 15 bytes if it only had to support lowercase. [Try it online!](https://tio.run/##bY1BCkIxDAX3/xwKIkRqmrbpCbyAOxGa/P4HgiiI968fwZ2zmN0wr@V9e9jY7k5tnBuerd/b4UK47jdjFBxZvQt5cCNJtZAiJorG4JJyh/ukFZzAIEZxErNMXnshyVZ1ibPzjEmXgKprKkHzquzkxYRS5G6Sa47A9GeHla9@fAA "Retina 0.8.2 – Try It Online") Link includes test cases. [Answer] # MATLAB, 138 bytes ``` a=1;Z=a;for r=flip(split(input(''),'-'))' q=r{:};z=dec2hex(hex2dec(q)+a,nnz(q));try z+q;a=0;catch z=~q+48;end Z=[z 45 Z];end;disp(Z(1:36)) ``` Fixed a bug in case a chunk is all zeros. Also golfed off a lot by abusing try/catch. Net result: 0 bytes saved. An attempt to 'cheat' by using `java.util.UUID` failed because the `long` value returned from `java.util.UUID.get[Most/Least]SignificantBits` gets converted to a `double` which incurs a loss of precision. I invite you to take a look at [this table](https://nl.mathworks.com/help/matlab/matlab_external/handling-data-returned-from-java-methods.html#bvizhgf) and silently utter "...but *why?*" ### Explanation The `hex2dec` function spits out a `double`, so it cannot process the entire GUID at once to avoid exceeding `flintmax`. Instead, we have to process the GUID chunk by chunck, using `split`. The variable `a` checks if we need to carry a one, and cheatingly also is the initial increment we add. The condition for carrying over is whether the lengths of the original and incremented strings are no longer equal. Original version was just under 160 bytes so I'd like to think this should not be easy to outgolf. [Answer] # [Python 2](https://docs.python.org/2/), 99 bytes ``` s='%032x'%-~int(input().replace('-',''),16) print'-'.join((s[:8],s[8:12],s[12:16],s[16:20],s[20:])) ``` [Try it online!](https://tio.run/##NYpBCsMgFET3vUf4Chr0NzVWyElCFrFNqKUYiRaaTa9uTaBvMfMYJmzpsXjMOXZQiTN@oOJf5xNxPrwTofU6hdd4mwhwYACUSUVPYS2PMtTPxXlCYm/0wGKvjcS9JRqpDlEGxS4ozEBpztDOErW9N9wKO/Lmcm35XDjiD/wA "Python 2 – Try It Online") No `uuid.UUID` usage. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 77 bytes ``` x=>{for(int i=35,c;(x[i]=(char)((c=x[i--])<48?c:c==57?65:c>69?48:c+1))<49;);} ``` [Try it online!](https://tio.run/##bZC9bsIwFIX3PIXF5Ki4Ase/BINsgifGSh1QhsgKxUuQnKilQjx7akNbVKl3uPK597Otc1yPXO9H7QZ/6pbu2IR9vQIHoMazWl0OpwB9NwCvCjp1JTzvfa1gonIInYoSoTpfErF2C6cU5WtGF27F5JqIhXua53Eny7y8jmWW9UPw3du@BkPbDz1QoGs/wO/wkoEJt3MsTEWQmRmNCJUcCVtQVGhsMaesssZMphEU0mJqsUXYcoOI1gwZWXFEmJZiW2wM3tg7uJ1ZKeITZCZYbMwgwzVBtMCVJkyywt7Bf762sW7tpyJ4jT5iKG3jjgC@N@HmBfju7ilPLl6DH9qd71qYZnmZgcSlzJLnNHt@OW2i1CE0nzABh1ukfTo@bj/S@d7@XUd1Hb8A "C# (Visual C# Interactive Compiler) – Try It Online") -1 byte thanks to @ASCIIOnly! Anonymous function that takes a `char[]` as input and [outputs by modifying an argument](https://codegolf.meta.stackexchange.com/a/4942/8340). Input is scanned from right to left and replaced using the following rules. * The `-` character is ignored and processing continues * The `F` character is converted to `0` and processing continues * The `9` character is converted to `A` and processing stops * The characters `A-E` and `0-8` are incremented by 1 and processing stops [Answer] # Powershell, 101 bytes ``` for($p=1;$d=+"$args"[--$i]){$d+=$p*(1-@{45=1;57=-7;70=23;102=55}.$d) $p*=$d-in45,48 $r=[char]$d+$r}$r ``` [Try it online!](https://tio.run/##lZPdattAEIXv9RRCbGup0ZTVan9rBEkv8hIhlF3tTmIwjSsntOD62d2pGsVqMMSZi4Eze@ZjZmA3Dz/TsL1P6/WBYd7luwM@DCXbdM2Sxe6iYH642xY3AGx1W@1YvOjY5lPZwOVOKvIo04FZGt6Jdtlw0Sm1/8xilZGpYxFW36Wqpc3Y0N309364JQAb9mw47LPsssxyirpc4KJe8EU1yev/JSfZHKUjeXWUVyS/HqUnGWa98JfdwBwH169KhcFG2BAlBB48SOUMWGwVtF6gMEpHDKGoz7H1xQuU62C1tS1gmwxIdBGs6RV4Lk2yzjcOHUHPsPkj1DoUCgWCQBNAeq8huEh92jub2j6IHgn6ti3yGTRxdJYWkdxqSjpAMF6CakX0Ujvd4gh9yyb5DHriWEgxpilO3dQCpxjTFO9Z3523vp9Bp2ngRJpNOk0DJ9Js0ir/nX/IdyOc3T2tYs3Sr03qH1Ok78W@/XsY0vZp/UiFj/TrRttYL1j5/ATpx0tf9WVqKLL94Q8 "PowerShell – Try It Online") No external library or hex conversion. Any string length. Lower case and upper case are allowed. Input string matching to `^[f-]*$` is allowed too. This script scans from the back of the string and inrement each char by the value from hashtable: * `-`: increment=1-1 * `9`: increment=1+7, result=`A` * `F`: increment=1-23, result=`0` * `f`: increment=1-55, result=`0` * increment=1 for other chars Next, the script uses `$p` to determine whether to increment the current char. Test script: ``` $f = { for($p=1;$d=+"$args"[--$i]){$d+=$p*(1-@{45=1;57=-7;70=23;102=55}.$d) $p*=$d-in45,48 $r=[char]$d+$r}$r } @( ,('f','0') ,('F','0') ,('0','1') ,('9','A') ,('A','B') ,('a','b') ,('0-f','1-0') ,('0-F','1-0') ,("7f128bd4-b0ba-4597-8f35-3a2f2756dfbb","7f128bd4-b0ba-4597-8f35-3a2f2756dfbc") ,("06b86883-f3e7-4f9d-87c5-a047e89a19f9","06b86883-f3e7-4f9d-87c5-a047e89a19fa") ,("89f25f2f-2f7b-4aa6-b9d7-46a98e3cb2cf","89f25f2f-2f7b-4aa6-b9d7-46a98e3cb2d0") ,("8e0f9835-4086-406b-b7a4-532da46963ff","8e0f9835-4086-406b-b7a4-532da4696400") ,("7f128bd4-b0ba-4597-ffff-ffffffffffff","7f128bd4-b0ba-4598-0000-000000000000") ,("89f25f2f-2f7b-4aa6-b9d7-46a98e3cb29f","89f25f2f-2f7b-4aa6-b9d7-46a98e3cb2a0") ,("ffffffff-ffff-ffff-ffff-ffffffffffff","00000000-0000-0000-0000-000000000000") ) | % { $guid,$expected = $_ $result = &$f $guid "$($result-eq$expected): $result" } ``` Output: ``` True: 0 True: 0 True: 1 True: A True: B True: b True: 1-0 True: 1-0 True: 7f128bd4-b0ba-4597-8f35-3a2f2756dfbc True: 06b86883-f3e7-4f9d-87c5-a047e89a19fA True: 89f25f2f-2f7b-4aa6-b9d7-46a98e3cb2d0 True: 8e0f9835-4086-406b-b7a4-532da4696400 True: 7f128bd4-b0ba-4598-0000-000000000000 True: 89f25f2f-2f7b-4aa6-b9d7-46a98e3cb2A0 True: 00000000-0000-0000-0000-000000000000 ``` [Answer] # [Perl 6](https://perl6.org), 65 bytes ``` {(:16(TR/-//)+1).base(16).comb.rotor(8,4,4,4,*)».join.join('-')} ``` [Test it](https://tio.run/##jY/fSsMwFMbv8xSHMWyyLW3Xpmk7tfgM6qUgSZpoZf1Dm4oy9mTe@WKz7RQVFCVwyDnn4/t9p9Htlh/6TsMjd9UpQuUznBSVanWpK0vv@iKH88MOb9YcX1961PPIck1cKTqN15y4qi6l29a2bnGyYtNbkNcX96EuqqlghzpkfxhsL6zuLJzDtqh055ai2QDNYF5UK5jXvYUdAsBjO3ajRymsusfgwY0DZxjcBZBs/Hswbq9si/ZoTH49@J6iZisqWE6Q4QxTt@/AgYFHStPbAaSfGq2szoFMvKKD78fio5J8kbq9WsHsOJ8SfyxmaH/IsuzT4XZycGKzDhKZMyp9KSiL0pgmJoxoKAITxBHPjZQOQf/RKQf9REhSE0QmMDQwsaRMCE5lmseUcZEmOlQyUGYk/K3L/V8I2jdpMoRhfsKHwiWVsWA0CoNcMJ7y0BwJf@mY7ztv "Perl 6 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 (and a bug fix) thanks to Dennis! ``` ØhiⱮṣ0µẎḅ⁴‘ḃ⁴ịØhṁj”- ``` **[Try it online!](https://tio.run/##y0rNyan8///wjIzMRxvXPdy52ODQ1oe7@h7uaH3UuOVRw4yHO5qBjIe7u4EqHu5szHrUMFf3////5mmGRhZJKSa6SQZJibomppbmuhZpxqa6xolGaUbmpmYpaUlJAA "Jelly – Try It Online")** [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 126 bytes ``` $a=("{0:X32}" -f (1+[Numerics.BigInteger]::Parse($args[0]-replace"-", 'AllowHexSpecifier')));5..2|%{$a=$a.Insert(4*$_,"-")};$a ``` [Try it online!](https://tio.run/##jZHBa8IwGMXv@StCqbPdTKlJmiaKsO00L2Owy0BEkvb7XKFTSR0Oav921zn0tMPe4Z1@j/fg7bYH8M071PUpxA2d0fYU2lkUtOnkTfAuoAxpNL5bPH9@gK@KJnms1vPNHtbgl5PJi/UNRKH162aRLpmHXW0LCFgwosOHut4enuDrdQdFhRX4YRzH0yxJ@HHQ9h2hTeabBvw@krfhatSH4m4a2lNHCLmPCO0V5Djm2pWSudRZJjOTM40iY8Jy5HmmSnQuGP2yqXJaaS0YCsiZRFMynRcZs6nMQRs7NmgvrDbIM@TIOOaOSWsVc6bsU8oaDaJwvMArCyka3ZfKVKvelGMut5JlgpdWKqMEXtk/9mKvs130/w0GAxLTIx3QlpwzNz8XhStCOnL6Bg "PowerShell – Try It Online") Pretty trivial answer. Just thought I'd get the beloved PowerShell added to the list :) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 78 bytes ``` s=>s.replace(/.([f-]*)$/,(s,y)=>('0x'+s[0]-~0).toString(16)+y.replace(/f/g,0)) ``` [Try it online!](https://tio.run/##bZCxTsMwGIT3PEUGpNg0v@s6juMIJRtPwFgq1Xb8p0UhqWIL0YVXLwYJWLjhttPddy/mzQS3ni8R5mXwN@xuoesDW/1lMs6TLSN7hMM9vduWJJRX2vWk4O/FJuz5AT44ZXF5iut5HslO0c31L4jbseSU3twyh5hHH6IzwYe8y49Zgzuh7SDBcmtA1m0DGqsaKiNQNLUa0NpMtyhqFAgCGwvSGAW2HRqQyrTaV84Kh5n2HFudopJrlUxZsI2RUFdiMFK1qkL8rw6Tvu1H2ZEljFdCWbhM50iK57mgD9nvbobL@mjciSSCPv@CWibPpmVMr@RF1xdljiTQBPwJ "JavaScript (Node.js) – Try It Online") [Answer] # Perl 5, 64 bytes ``` $c=reverse((1+hex s/-//gr)->as_hex);$c=~s/..$//;s/[^-]/chop$c/ge ``` The number of parentheses necessary here makes me sad, but `->` binds very tightly, as `->as_hex` is the quickest way I can find to get hexadecimal-formatted output. Run with `perl -Mbigint -p`. Basically, it just converts the number to a bigint hexadecimal, adds one, and then subtitutes the digits of the result back into the original value, leaving dashes untouched. [Answer] # Rust, 258 bytes ``` let x=|s:&str|s.chars().rev().scan(1,|a,c|{let d=c.to_digit(16).unwrap_or(99);match(d,*a){(15,1)=>{*a=1;Some(0)}(0..=14,1)=>{*a = 0;Some(d + 1)}_=> Some(d),}}).collect::<Vec<u32>>().iter().rev().for_each(|d| print!("{}", std::char::from_digit(*d, 16).unwrap_or('-'))); ``` yes its long.. but technically its only one line with 1 expression? and no fancy libraries? and it will not crash on a fuzz input? ungolf: ``` let x=|s:&str|s.chars().rev().scan(1, |a, c| { let d = c.to_digit(16).unwrap_or(99); match (d, *a) { (15, 1) => {*a = 1;Some(0)} (0..=14, 1) => {*a = 0;Some(d + 1)} _ => Some(d), } }).collect::<Vec<u32>>().iter().rev() .for_each(|d| print!("{}", std::char::from_digit(*d, 16).unwrap_or('-'))); ``` [try it on rust playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018) [Answer] ## 16/32/64-bit x86 assembly code, 28 bytes bytes: 83C623FDAC3C2D74FB403C3A7502B0613C677502B03088460173E9C3 code: ``` add esi, 35 ;point to end of string - 1 std ;go backwards l1: lodsb ;fetch a character cmp al, '-' je l1 ;skip '-' inc eax ;otherwise increment cmp al, '9' + 1 jne l2 ;branch if not out of numbers mov al, 'a' ;otherwise switch '9'+1 to 'a' l2: cmp al, 'f' + 1 ;sets carry if less jne l3 ;branch if not out of letters mov al, '0' ;otherwise switch 'f'+1 to '0' ;and carry is clear l3: mov [esi + 1], al ;replace character jnb l1 ;and loop while carry is clear ret ``` Call with ESI pointing to GUID. Replace ESI with SI for 16-bit, or RSI for 64-bit (and +2 bytes). [Answer] # [C (clang)](http://clang.llvm.org/), 62 bytes ``` g(char*i){for(i+=36;(*--i-45?*i+=*i-70?*i-57?1:8:-22:0)<49;);} ``` [Try it online!](https://tio.run/##fY7BbsIwEETv@xVWEJKd4CpATEI2Lrf@BHCwAgkrgUEmPkX59tQUeqhUMYfRrt5oNLWsz8a249jy@mRcTKJvro5Topcr5LGUJDO1icMfk8zTcEmVb@ZlUcrFokxFla1R4DBOyNZnfzhW9@5A14/TJ5Dt2MWQ5YL18OhmZrvXfbT@ekr@Yy@l0YAAPztCiWc6K9BX@Rx9kogeqOFea1UIr1cKwWyXaq89ws2FeMOj6Z3tbDQzAqHlD/8DftEA8A4DsCB37LyzLA3x8Rs "C (clang) – Try It Online") [Answer] # Common Lisp, 166 bytes ``` (lambda(s &aux(r(format()"~32,'0x"(1+(parse-integer(remove #\- s):radix 16)))))(format()"~{~a~^-~}"(mapcar(lambda(x y)(subseq r x y))#1='(0 8 12 16 20 32)(cdr #1#)))) ``` [Try it online!](https://tio.run/##bU/bSsQwEP2VIYtuig60SZqLsH6JCJMmkcJ2W9NdqYj99TUVBR88DwcGzmVOd@zn6cqP4zhBGjP00J9gz5lJjbA@KPS1J1StM2iTbFGSSMK0OiTvGbBae6utlZhkNKiSC2hN1yLVykTrqHGJisy6JNokEopkPCoijd6FYtDkbJSdF13aZLFOzpYWVVtdSHv0hhS2UgRS2mmZNtk/v6WCb/oFqyCMwMukgc5wBrYSwOERVlpvWFnJy2YafCA@wy1dFp5/tLxiqxT3@3phvLnjE@U5Yn86x5eYeY7D@BZh94QwVw@ZQr9Ao6sNf@wfpeQZ10/GB5o6yr9NC7xXfL74Ob5Chu2qds1hz2uw0IgSBKIGKSrehQy7ZrfFXvuNvgA) ]
[Question] [ A [Faro shuffle](https://en.wikipedia.org/wiki/Faro_shuffle) is a technique frequently used by magicians to "shuffle" a deck. To perform a Faro shuffle you first cut the deck into 2 equal halves then you interleave the two halves. For example ``` [1 2 3 4 5 6 7 8] ``` Faro shuffled is ``` [1 5 2 6 3 7 4 8] ``` This can be repeated any number of times. Interestingly enough, if you repeat this enough times, you will always end up back at the original array. For example: ``` [1 2 3 4 5 6 7 8] [1 5 2 6 3 7 4 8] [1 3 5 7 2 4 6 8] [1 2 3 4 5 6 7 8] ``` Notice that 1 stays on the bottom and 8 stays on the top. That makes this an [outer-shuffle](https://en.wikipedia.org/wiki/Out_shuffle). This is an important distinction. # The Challenge Given an array of integers *A*, and a number *N*, output the array after *N* Faro shuffles. *A* may contain repeated or negative elements, but it will always have an even number of elements. You can assume the array will not be empty. You can also assume that *N* will be a non-negative integer, although it may be 0. You can take these inputs in any reasonable manner. The shortest answer in bytes wins! # Test IO: ``` #N, A, Output 1, [1, 2, 3, 4, 5, 6, 7, 8] [1, 5, 2, 6, 3, 7, 4, 8] 2, [1, 2, 3, 4, 5, 6, 7, 8] [1, 3, 5, 7, 2, 4, 6, 8] 7, [-23, -37, 52, 0, -6, -7, -8, 89] [-23, -6, -37, -7, 52, -8, 0, 89] 0, [4, 8, 15, 16, 23, 42] [4, 8, 15, 16, 23, 42] 11, [10, 11, 8, 15, 13, 13, 19, 3, 7, 3, 15, 19] [10, 19, 11, 3, 8, 7, 15, 3, 13, 15, 13, 19] ``` And, a massive test case: ``` 23, [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, 100] ``` Should output: ``` [1, 30, 59, 88, 18, 47, 76, 6, 35, 64, 93, 23, 52, 81, 11, 40, 69, 98, 28, 57, 86, 16, 45, 74, 4, 33, 62, 91, 21, 50, 79, 9, 38, 67, 96, 26, 55, 84, 14, 43, 72, 2, 31, 60, 89, 19, 48, 77, 7, 36, 65, 94, 24, 53, 82, 12, 41, 70, 99, 29, 58, 87, 17, 46, 75, 5, 34, 63, 92, 22, 51, 80, 10, 39, 68, 97, 27, 56, 85, 15, 44, 73, 3, 32, 61, 90, 20, 49, 78, 8, 37, 66, 95, 25, 54, 83, 13, 42, 71, 100] ``` [Answer] ## vim, ~~62~~ ~~59~~ 54 ``` qrma50%mb:norm@q<cr>ggqOjdd'apjma'b@q<esc>0"qDJ<C-a>D@"i@r<esc>xxdd@" ``` Wow. This is possibly the hackiest thing I've written for PPCG, and that's saying something. Input is taken as N on the first line followed by the elements of the array, each on its own line. ``` qr first, we're going to record the contents of the @r macro. this is the macro which does the faro-shuffle operation. ma set the mark 'a at the beginning of the file 50% move to the 50% point of the file (i.e. halfway down) mb set another mark here :norm@q evaluate the recursive macro @q. we'll get to what that does later, but the interesting part here is that it's :norm@q instead of @q. this is because a recursive macro terminates at the end of the file, which means when @q terminates, @r would also abort, which would make calling it with a count impossible. running @q under :norm prevents this. gg move back to the top of the file for the next iteration q end recording O now we're inserting contents of the @q macro, the recursive part we can't record it directly because it's destructive j move to line directly below mark 'b (which was just set before @q) dd delete this line and bring it... 'ap up after mark 'a (which starts on line 1, bringing the N/2th line directly below line 1, aka line 2) jma replace mark 'a one line below this so that the next time we call 'ap, the line from the second half is interleaved with the lines from the first half 'b jump back to mark 'b (remember, 'b is the last line of the first half of the file, originally reached via 50%) @q call ourselves, causing the macro to run until hitting EOF 0"qD delete this into register "q J delete the empty line that remains <C-a> here's another interesting bit: we want to run @r N times. but 0@r means "go to column 0, and then run @r once." so we have to increment the input number... D@" and then *that* many times... i@r insert @r... xx ... and finally, delete two characters, which is the extra @r from the increment dd delete the sequence of @rs into the "" register... @" and run it! ``` I actually possibly found several vim bugs while writing this answer: * recording macros is not possible within other macros (when setting their text manually, not with `q`) or within `:*map`s. * `:let @a='<C-v><cr>'<cr>i<C-r>a` outputs two newlines, not one, for whatever arcane reason. I might investigate those further later. Thanks to [Dr Green Eggs and Ham DJ](https://codegolf.stackexchange.com/users/31716/dr-green-eggs-and-ham-dj) for 3 bytes! [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 5 bytes Code: ``` F2äø˜ ``` Explanation, input: `N`, `array`: ``` F # Do the following N times 2ä # Split the array into 2 pieces ø # Zip ˜ # Deep flatten ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=RjLDpMO4y5w&input=NwpbLTIzLCAtMzcsIDUyLCAwLCAtNiwgLTcsIC04LCA4OV0). [Answer] # Python, ~~68~~ 57 bytes ``` f=lambda n,x:n and f(n-1,sum(zip(x,x[len(x)/2:]),()))or x ``` *Thanks to @Sp3000 for golfing off 11 bytes!* Test it on [Ideone](http://ideone.com/Qv78Sp). [Answer] ## Python 2, 59 bytes ``` def f(n,L):exec"l=len(L)/2;L=(L+L[1:]*~-l)[::l];"*n;print L ``` A different approach, slightly longer than the other Python answers. Only works for positive even numbers of elements. e.g. for `1, [1,2,3,4,5,6,7,8]`, take the array and append `len(L)/2-1` copies of itself minus the first element, e.g. ``` [1,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8] ``` Then take every `len(L)/2`th element. ``` [1,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8] ^ ^ ^ ^ ^ ^ ^ ^ ``` [Answer] # Haskell, 62 bytes ``` 0!a=a n!a|s<-length a=(n-1)![a!!mod(div(s*i+i)2)s|i<-[0..s-1]] ``` Let *s* = 2·*t* be the size of the list. The *i*-th element of the new list is obtained by taking the [![enter image description here](https://i.stack.imgur.com/ZM1kJ.png)](https://i.stack.imgur.com/ZM1kJ.png)-th element of the old list, zero-indexed, modulo *s*. Proof: if *i* = 2·*k* is even, then                                          [![enter image description here](https://i.stack.imgur.com/s4ur9.png)](https://i.stack.imgur.com/s4ur9.png) and if *i* = 2·*k* + 1 is odd, then                         [![enter image description here](https://i.stack.imgur.com/7ZHnm.png)](https://i.stack.imgur.com/7ZHnm.png) Thus the values used for indexing are 0, *t*, 1, *t* + 1, 2, *t* + 2, … [Answer] # J - 12 bytes Adverb (!) taking number of shuffles on the left and the array to shuffle on the right. ``` /:#/:@$0,#^: ``` The J parser has [rules for writing tacit adverbs](http://www.jsoftware.com/help/dictionary/dicte.htm), but they have very low precedence: if you want to use a train of verbs as a left argument, you can omit an otherwise necessary set of parentheses. So the above is actually short for `(/:#/:@$0,#)^:`, which takes the number of shuffles on the left as an adverb, and then becomes a monadic function taking the array to shuffle on the right. That said, we shuffle as follows. `#` is the length of the array, so `0,#` is a two element list: 0 followed by something nonzero. Then `#/:@$` replicates that into a list as long as the input array, and takes its **sort vector**. The sort vector of a list is the information for how to sort the list: the (0-based) invdex of the smallest element, followed by the index of the next-smallest, and so on. For example, the sort vector of `0 1 0 1 ...` will thus be `0 2 4 ... 1 3 5 ...`. If J were now to sort this sort vector, it would Faro-shuffle it; but that would be trivial, since we'd get `0 1 2 3 ...` back. So we use [dyadic `/:`](http://www.jsoftware.com/help/dictionary/d422.htm) to sort the input array **as if it were** `0 2 4 ... 1 3 5 ...`, which Faro-shuffles it. Example usage below. Try it yourself at [tryj.tk](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=2%20%28%2F%3A%23%2F%3A%40%240%2C%23%5E%3A%29%201%202%203%204%205%206%207%208)! ``` 1 (/:#/:@$0,#^:) 1 2 3 4 5 6 7 8 1 5 2 6 3 7 4 8 f =: /:#/:@$0,#^: 2 f 1 2 3 4 5 6 7 8 1 3 5 7 2 4 6 8 7 f _23 _37 52 0 _6 _7 _8 89 NB. "negative 1" is spelled _1 _23 _6 _37 _7 52 _8 0 89 1 f 0 0 0 0 1 1 1 NB. odd-length lists 0 1 0 1 0 1 0 ``` [Answer] # Pyth - ~~8~~ 7 bytes *saved 1 byte thanks to @issacg* ``` usCc2GE ``` [Try it online here](http://pyth.herokuapp.com/?code=usCc2GE&input=%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8%2C+9%2C+10%2C+11%2C+12%2C+13%2C+14%2C+15%2C+16%2C+17%2C+18%2C+19%2C+20%2C+21%2C+22%2C+23%2C+24%2C+25%2C+26%2C+27%2C+28%2C+29%2C+30%2C+31%2C+32%2C+33%2C+34%2C+35%2C+36%2C+37%2C+38%2C+39%2C+40%2C+41%2C+42%2C+43%2C+44%2C+45%2C+46%2C+47%2C+48%2C+49%2C+50%2C+51%2C+52%2C+53%2C+54%2C+55%2C+56%2C+57%2C+58%2C+59%2C+60%2C+61%2C+62%2C+63%2C+64%2C+65%2C+66%2C+67%2C+68%2C+69%2C+70%2C+71%2C+72%2C+73%2C+74%2C+75%2C+76%2C+77%2C+78%2C+79%2C+80%2C+81%2C+82%2C+83%2C+84%2C+85%2C+86%2C+87%2C+88%2C+89%2C+90%2C+91%2C+92%2C+93%2C+94%2C+95%2C+96%2C+97%2C+98%2C+99%2C+100%5D%0A23&debug=0). [Answer] # Jelly, ~~9~~ 7 bytes 2 bytes thanks to Dennis! ``` œs2ZFð¡ ``` [Try it online!](http://jelly.tryitonline.net/#code=xZNzMlpGw7DCoQ&input=&args=WzEsMiwzLDQsNSw2LDcsOF0+Mg) ### Explanation ``` œs2ZFð¡ Main dyadic chain. Arguments: x,y ¡ Repeat the following y time: œs2 Split into two. Z Transpose. F Flatten. ``` ## Previous 9-byte version: ``` œs2ZF Ç⁴¡ ``` [Try it online!](http://jelly.tryitonline.net/#code=xZNzMlpGCsOH4oG0wqE&input=&args=WzEsMiwzLDQsNSw2LDcsOF0+Mg) [Answer] ## JavaScript (ES6), ~~61~~ 51 bytes ``` (n,a)=>[...a].map((e,i)=>a[(i<<n)%~-a.length||i]=e) ``` Modifies the input array in place and returns a copy of the original array. If this is unacceptable, `&&a` can be suffixed to return the modified array. Only works for small values of `n` due to the limitations of JavaScript's integer arithmetic. ~~61~~ 60 byte recursive version that works with larger `n`, based on @Lynn's formula: ``` f=(n,a,l=a.length)=>n?f(n-1,a.map((_,i)=>a[(i*-~l>>1)%l])):a ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` w:"tn2/e!1e ``` *Thanks to @Dennis for a correction* [**Try it online!**](http://matl.tryitonline.net/#code=dzoidG4yL2UhMWU&input=MjMKWzEsIDIsIDMsIDQsIDUsIDYsIDcsIDgsIDksIDEwLCAxMSwgMTIsIDEzLCAxNCwgMTUsIDE2LCAxNywgMTgsIDE5LCAyMCwgMjEsIDIyLCAyMywgMjQsIDI1LCAyNiwgMjcsIDI4LCAyOSwgMzAsIDMxLCAzMiwgMzMsIDM0LCAzNSwgMzYsIDM3LCAzOCwgMzksIDQwLCA0MSwgNDIsIDQzLCA0NCwgNDUsIDQ2LCA0NywgNDgsIDQ5LCA1MCwgNTEsIDUyLCA1MywgNTQsIDU1LCA1NiwgNTcsIDU4LCA1OSwgNjAsIDYxLCA2MiwgNjMsIDY0LCA2NSwgNjYsIDY3LCA2OCwgNjksIDcwLCA3MSwgNzIsIDczLCA3NCwgNzUsIDc2LCA3NywgNzgsIDc5LCA4MCwgODEsIDgyLCA4MywgODQsIDg1LCA4NiwgODcsIDg4LCA4OSwgOTAsIDkxLCA5MiwgOTMsIDk0LCA5NSwgOTYsIDk3LCA5OCwgOTksIDEwMF0K) ### Explanation ``` w % Take the two inputs N and A. Swap them : % Generate [1 2 ... N] " % Repeat N times tn2/ % Duplicate A. Number of elements divided by 2 e % Reshape to that number of rows ! % Transpose 1e % Reshape to one row % End (implicit) % Display (implicit) ``` [Answer] # J, ~~22~~ ~~19~~ 17 bytes 3 bytes [thanks to @Gareth](https://codegolf.stackexchange.com/a/6554/48934). 2 bytes thanks to [@algorithmshark](https://codegolf.stackexchange.com/users/5138/algorithmshark). ``` -:@#({.,@,.}.)]^: ``` ### Usage ``` >> f =: -:@#({.,@,.}.)]^: >> 2 f 1 2 3 4 5 6 7 8 << 1 3 5 7 2 4 6 8 ``` Where `>>` is STDIN and `<<` is STDOUT. ## Previous 22-byte version: ``` ({~[:,/@|:@i.2,-:@#)^: ``` ### Usage ``` >> f =: ({~[:,/@|:@i.2,-:@#)^: >> 2 f 1 2 3 4 5 6 7 8 << 1 3 5 7 2 4 6 8 ``` Where `>>` is STDIN and `<<` is STDOUT. [Answer] # Mathematica 44 bytes With 4 bytes saved thanks to @miles. ``` Riffle@@TakeDrop[#,Length@#/2]&~Nest~##& ``` --- `Riffle @@ TakeDrop[#, Length@#/2] &~Nest~## &[list, nShuffles]` splits the list into two equal sublists and shuffles (`Riffle`s) them. --- ``` Riffle @@ TakeDrop[#, Length@#/2] &~Nest~## &[Range@8, 1] ``` {1, 5, 2, 6, 3, 7, 4, 8} --- ``` Riffle @@ TakeDrop[#, Length@#/2] &~Nest~## &[Range@100, 23] ``` {1, 30, 59, 88, 18, 47, 76, 6, 35, 64, 93, 23, 52, 81, 11, 40, 69, 98, 28, 57, 86, 16, 45, 74, 4, 33, 62, 91, 21, 50, 79, 9, 38, 67, 96, 26, 55, 84, 14, 43, 72, 2, 31, 60, 89, 19, 48, 77, 7, 36, 65, 94, 24, 53, 82, 12, 41, 70, 99, 29, 58, 87, 17, 46, 75, 5, 34, 63, 92, 22, 51, 80, 10, 39, 68, 97, 27, 56, 85, 15, 44, 73, 3, 32, 61, 90, 20, 49, 78, 8, 37, 66, 95, 25, 54, 83, 13, 42, 71, 100} [Answer] # APL, ~~23~~ 21 chars ``` ({⊃,/⍵(↑,¨↓)⍨2÷⍨⍴⍵}⍣N)A ``` Without the assumption (Thanks to Dennis) and 1 char shorter: ``` ({{∊,⌿2(2÷⍨≢⍵)⍴⍵}⍣⎕)⎕ ``` Try it on [online](http://tryapl.org/?a=%7B%u2283%2C/%2C%u233F2%282%F7%u2368%u2262%u2375%29%u2374%u2375%7D%u23633%u23738&run). [Answer] # java, 109 bytes `int[]f(int[]a,int n){for(int x,q=a.length,d[];0<n--;a=d){d=new int[q];for(x=0;x<q;x++)d[(2*x+2*x/q)%q]=a[x];}return a;}` Explanation: There is a pattern to how the elements move when they are faro shuffled: let x be the original index let y be the new index let L be the length of the array * y is double x * if x is greater than or equal to half of L then increment y * keep y within the array's bounds or as code: `y=(2*x+x/(L/2))%L` This assumes that indicies start at 0. Here's the code further explained: ``` int[] faroShuffle( int[] array, int numberOfShuffles ) { //repeat the faro shuffle n times for( int index, length=array.length, destination[]; 0<numberOfShuffles--; array=destination ) { //new array to copy over the elements destination=new int[length]; //copy the elements into the new array for( index=0; index<length; index++ ) destination[(2*index+2*index/length)%length]=array[index]; //at the end of each loop, copy the reference to the new array and use it going forward } return array; } ``` [see ideone for test cases](http://ideone.com/XaSBKg) [Answer] # Julia, ~~45~~ 42 bytes ``` a\n=n>0?reshape(a,endof(a)÷2,2)'[:]\~-n:a ``` [Try it online!](http://julia.tryitonline.net/#code=YVxuPW4-MD9yZXNoYXBlKGEsZW5kb2YoYSnDtzIsMiknWzpdXH4tbjphCgpmb3IgKG4sIGEpIGluICgKICAgICgxLCAgMTo4KSwKICAgICgyLCAgMTo4KSwKICAgICg3LCAgWy0yMywgLTM3LCA1MiwgMCwgLTYsIC03LCAtOCwgODldKSwKICAgICgwLCAgWzQsIDgsIDE1LCAxNiwgMjMsIDQyXSksCiAgICAoMTEsIFsxMCwgMTEsIDgsIDE1LCAxMywgMTMsIDE5LCAzLCA3LCAzLCAxNSwgMTldKSwKICAgICgyMywgMToxMDApCikKICAgIHByaW50bG4oYVxuKQplbmQ&input=) ### How it works We (re)define the binary operator `\` for this task. Let **a** be an array and **n** a non-negative integer. If **n** is positive, we shuffle the array. This is achieved by reshaping it into a matrix of **length(a) ÷ 2** rows and two columns. `'` transposes the resulting matrix, creating of two rows, then flattening the result with `[:]`. Since Julia stores matrices in column-major order, this interleaves the two rows. Afterwards, we call `\` recursively with the shuffled **a** and **n - 1** (`~-n`) as arguments, thus performing additional shuffles. Once **n** reaches **0**, we return the current value of **a**. [Answer] ## Pyke, 7 bytes ``` VDlec,s ``` [Try it here!](http://pyke.catbus.co.uk/?code=VDlec%2Cs&input=7%0A%5B-23%2C+-37%2C+52%2C+0%2C+-6%2C+-7%2C+-8%2C+89%5D) ``` V - Repeat N times: D - a,b = a (2nd arg first time round) le - b = len(b)//2 c - a = chunk(a,b) , - a = zip(*a) s - a = sum(a, []) ``` [Answer] ## Actually, 15 bytes ``` `;l½≈@│t)HZ♂i`n ``` [Try it online!](http://actually.tryitonline.net/#code=YDtswr3iiYhA4pSCdClIWuKZgmlgbg&input=WzEsMiwzLDQsNSw2LDcsOF0KNQ) Explanation: ``` `;l½≈@│t)HZ♂i`n ` `n do the following n times: ;l½≈ push half the length of the array @ swap │ duplicate entire stack t)H last L//2 elements, first L//2 elements Z♂i zip, flatten each element ``` [Answer] # Prolog, 116 bytes ``` a([],[[],[]]). a([H,I|T],[[H|U],[I|V]]):-a(T,[U,V]). f(X,0,X). f(X,N,Y):-N>0,M is N-1,f(X,M,Z),a(Z,[A,B]),append(A,B,Y). ``` ## Usage ``` ?- f([1,2,3,4,5,6,7,8],2,X). X = [1, 5, 2, 6, 3, 7, 4, 8] ; false. ``` [Answer] # [Perl 5](https://www.perl.org/) `-lan`, 52 bytes ``` $a=<>;@F=map@F[$_,@F/2+$_],0..$#F/2while$a--;say"@F" ``` [Try it online!](https://tio.run/##K0gtyjH9/18l0dbGztrBzTY3scDBLVolXsfBTd9IWyU@VsdAT09FGcgpz8jMSVVJ1NW1Lk6sVHJwU/r/39BAR8HQUEfBAkiZArExFFvqKAApczAJlrDkMjT8l19QkpmfV/xf19dUz8DQ4L9uTmIeAA "Perl 5 – Try It Online") [Answer] # PHP, 98 bytes ``` function($a,$n){while($n--)for($z=count($a)/2;$z;)array_splice($a,$z--,0,array_pop($a));return$a;} ``` [Try it online](http://sandbox.onlinephpfunctions.com/code/f45082b60e85e0514b5f1c8e59abe07398477e02). ]
[Question] [ Inspired by [this](http://www.smbc-comics.com/index.php?db=comics&id=2874). There is a number, given as either integer, string or array of digits (your choice). Find the base in which the representation of the number will have most "4"s and return that base. ``` Number Result 624 5 444 10 68 16 ``` restrictions: * The base returned should not be greater than the input. * Numbers less than or equal to 4 should not be considered valid input, so undefined returns are acceptable [Answer] ## APL (~~31~~ 19) Now tests all possible bases. ``` ⊃⍒{+/4=K⊤⍨K⍴⍵}¨⍳K←⎕ ``` Explanation: * `⍳K←⎕`: read user input, store in K. Make a list from 1 to K, which are the bases to try. * `{`...`}¨`: for each of these, run the following function * `K⊤⍨K⍴⍵`: encode K into that base giving a list of digits (as numbers) per base. Use K digits (a big overestimate, but it doesn't matter because the unused ones will all be zero anyway). * `4=`: see which of these are equal to 4 * `+/`: sum these, now we know how many fours per base * `⊃⍒`: give the indices of the list if it were sorted downwards, so the index of the biggest one is at the front. Take the first item of this list. [Answer] ### GolfScript, 30 characters ``` .,{[2+.2$\base{4=},,\]}%$)~p]; ``` Works for any base - test the code [online](http://golfscript.apphb.com/?c=OzYyNAoKLix7WzIrLjIkXGJhc2V7ND19LCxcXX0lJCl%2BcF07Cg%3D%3D&run=true). *Comment:* This solution was based on the original version of the question. It thus may return a base larger than the input, e.g. for the input 4 it correctly returns base 5 - which is no longer valid by the new rules. [Answer] ## Python 2.x, 77 chars ``` F=lambda x:max((sum(x/b**d%b==4for d in range(99)),b)for b in range(5,99))[1] ``` Works up to base 98 and numbers at most 98 digits long. [Answer] ## J, 38 characters ``` f=.[:(i.>./)[:+/[:|:4=(10#"0(i.37))#:] ``` Usage: ``` p 624 5 p 444 10 p 68 16 ``` [Answer] ## VBA, 121 ``` Function k(a) For w=5 To a Z=0:q=a:Do:c=q Mod w:Z=Z-(c=4):q=Int(q/w):Loop Until q=0 If Z>x Then x=Z:k=w Next End Function ``` usage: * direct window: `?k(num)` * Excel formula: `=k(A1)` [Answer] ## GolfScript (23 chars) ``` ~:^,2>{^\base[4]/,~}$0= ``` or ``` ~:^,2>{^\base[4]/,}$-1= ``` or ``` ~:^,2>{^\base[4]/,}$)\; ``` Note that this takes input from stdin: for a fair comparison with Howard's GolfScript version subtract one char. --- Howard points out that the rules have changed, and it's not very logical that they now exclude `4` as a possible input when it has a valid output (any integer greater than 4). To cover that case as well requires an extra 2 characters, which can be added in all kinds of ways: ``` ~:^)),2>{^\base[4]/,}$)\; ``` or ``` ~:^,{))^\base[4]/,}$)))\; ``` being a couple of the obvious ones. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` bⱮċ€4M ``` [Try it online!](https://tio.run/##y0rNyan8/z/p0cZ1R7ofNa0x8f1/uB1I//9vZmSiY2JiomNmoWNoBgA "Jelly – Try It Online") Outputs "all" bases up to N which gives the most 4's. If you want maximal or minimal base, add `Ṁ` (max) or `Ṃ` (min) respectively. ### How it works ``` bⱮċ€4M Main link (monad). Input: integer N. bⱮ Convert N to each base of 1..N ċ€4 Count 4's in each representation M Take maximal indices ``` [Answer] # Mathematica 59 **Code** ``` Sort[{Count[IntegerDigits[n, #], 4], #} & /@ Range[5, 36]][[-1, 2]] ``` Let's give the above function a name. ``` whichBase[n_] := Sort[{Count[IntegerDigits[n, #], 4], #} & /@ Range[2, 36]][[-1, 2]] ``` **Explanation** 1. `Count[IntegerDigits[n,k],4]`: Count the number of fours in the base *k* representation of *n*. 2. `Sort` the bases from fewest to most 4s. 3. Return the base from the last item in the list, that is, the base that had the representation with the most 4's. **Some special numbers** Now let's apply whichBase to the following special numbers. ``` numbers= {1953124, 8062156, 26902404, 76695844, 193710244, 444444444, 943179076, 1876283764, 3534833124, 6357245164, 10983816964, 18325193796, 29646969124, 46672774204, 71708377284, 107789473684, 158856009316, 229956041484, 327482302084, 459444789604, 635782877604, 868720588636, 1173168843844, 1567178659764, 2072449425124, 2714896551724, 3525282954756, 4539918979204, 5801435550244, 7359635486844, 9272428079044, 11606852190676} ``` > > {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} > > > If you convert each number to the corresponding base, you will see what is special about them. [Answer] # Japt `-h`, 10 bytes `444` in base `10` is `[4,4,4]` which contains the number *and* digit `4` 3 times but `444` in base `100` is `[4,44]` which also contains the digit `4` 3 times, but only as a number once. Given the expected output in the challange for the `444` test case, I'd guess we're supposed to be counting the number 4: ``` õ ñ@ìX è¥4 ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=9SDxQOxYIOilNA==&input=NDQ0Ci1o) But if we *are* counting the digit 4 then: ``` õ ñ@ìX ¬è4 ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=9SDxQOxYIKzoNA==&input=NDQ0Ci1o) ``` õ :Range [1,...,input] ñ@ :Sort by passing each X through a function ìX : Convert the input to a base X digit array :(VERSION 1) è : Count the elements ¥4 : Equal to 4 :(VERSION 2) ¬ : Join to a string è4 : Count the occurrences of "4" :Implicitly output the last element in the sorted array ``` [Answer] # C - (114 characters) In all it's golfy glory: ``` x,k,c,d,n;main(v){scanf("%d",&v);for(k=5;v/k;++k){x=v;c=0;while(x)c+=x%k==4,x/=k;c>=d?n=k,d=c:0;}printf("%d",n);} ``` And somewhat ungolfed: ``` x,k,c,d,n; // declare a bunch of ints, initialized to 0 main(v){ // declare one more, without using an extra comma scanf("%d",&v); // get the input (v) for(k=5;v/k;++k){ // loop over each base (k) greater than or equal to (/) // our input (v) x=v; // temp value (x) set to input (v) c=0; // number of 4s in the current base (c) re-initialized while(x) // loop over our temp until it's used up c+=x%k==4, // if the next digit (x%k) is 4 (==4) increment the // current count (c+=) x/=k; // remove the current digit c>=d?n=k,d=c:0; // if the number of 4s in this base (c) is greater // than the current maximum number of 4s (d), then // save the new best base (n), and new maximum // number of 4s } printf("%d",n); // output the result } ``` Just for fun here's the output for the numbers `[0,127]` (these are the largest bases under the input number itself). > > 0, 0, 0, 0, 0, 5, 6, 7, 8, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 5, 21, 22, 23, 6, 25, 26, 27, 7, 29, 30, 31, 8, 33, 34, 35, 9, 37, 38, 39, 10, 41, 42, 43, 11, 5, 46, 47, 12, 49, 50, 51, 13, 53, 54, 55, 14, 57, 58, 59, 15, 61, 62, 63, 16, 65, 66, 67, 17, 69, 5, 71, 18, 73, 74, 75, 19, 7, 78, 79, 20, 81, 82, 83, 21, 85, 86, 87, 22, 89, 90, 91, 23, 93, 94, 5, 24, 97, 98, 99, 25, 101, 102, 103, 26, 5, 106, 107, 27, 109, 5, 111, 28, 113, 114, 5, 29, 9, 5, 5, 5, 121, 122, 123 > > > [Answer] **R - ~~148~~ 137 chars** (so, far away from the rest of the competition but still) ``` f=function(n){s=sapply;which.max(s(lapply(strsplit(s(4:n,function(x){q=n;r="";while(q){r=paste(q%%x,r);q=q%/%x};r})," "),`==`,4),sum))+3} ``` Basically transform the input from base 10 to all bases from 4 to n (using modulo `%%` and integer division `%/%`) and pick the index of the first one having the most 4s. ``` f(624) [1] 5 f(444) [1] 10 ``` [Answer] J translation of @marinus' APL solution: ``` NB. Expression form (22 characters, not including "n" - the "argument"): {.\:(+/@(4=$#:[)"0 i.)n NB. Function form (24 characters, not including "f=:"): f=:{.@\:@(+/@(4=$#:[)"0 i.) ``` Just for interest, here are some values: ``` (,.f"0)9+i.24 9 5 10 6 11 7 12 8 13 9 14 5 15 11 16 6 17 13 18 7 19 5 20 5 21 5 22 5 23 5 24 5 25 6 26 6 27 6 28 6 29 5 30 7 31 7 32 7 ``` It outputs the smallest base that gives a fouriest transform. For the last few values in the table, the representations look like “4n” (e.g 31 in base 7 is “43”). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LBε4¢}Zk> ``` -1 byte thanks to *@Cowabunghole*. If multiple bases have the same amount of 4s, it will output the smallest one (i.e. `16` will result in `6`, but `12` would also have been a possible output). [Try it online](https://tio.run/##yy9OTMpM/f/fx@ncVpNDi2qjsu3@/zczMgEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVnl4gr2SwqO2SQpK9v99nM5tNTm0qDYq2@6/zn8zIxMuExMTLjMLLkMzAA). **Explanation:** ``` L # Create a list in the range [1, (implicit) input] # i.e. 624 → [1,2,3,...,622,623,634] B # Convert the (implicit) input integer to Base-N for each N in this list # i.e. 624 and [1,2,3,...,622,623,624] # → ["1","1001110000","212010",...,"12","11","10"] ε } # Map this list to: 4¢ # Count the number of 4s in the number # → [0,0,0,0,4,0,0,0,0,1,0,2,...,0,0,0] Z # Take the max (without popping the list) # i.e. [0,0,0,0,4,0,0,0,0,1,0,2,...,0,0,0] → 4 k # Get the index of this max in the list # i.e. [0,0,0,0,4,0,0,0,0,1,0,2,...,0,0,0] and 4 → 4 > # Increase it by to convert the 0-index to our base (and output implicitly) # i.e. 4 → 5 ``` [Answer] # [k](https://en.wikipedia.org/wiki/K_programming_language), 18 bytes ``` {*>+/'4=x{y\x}'!x} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqlrLTltf3cS2oroypqJWXbGi9n@aupmRiYKJiYmCmcV/AA "K (ngn/k) – Try It Online") ``` { } /function(x) x '!x /for every y in 0, 1, ..., (x-1): {y\x} / do x in base y 4= /see which digits equal four +/' /sum, to get number of 4s per base *> /get index (which equals base) of largest number of 4s ``` [Answer] **C# with Linq 273** ``` using System;using System.Linq;class P{static void Main(){int r,z,k=int.Parse(Console.ReadLine());if(k<=4) return;Console.WriteLine(Enumerable.Range(4, k).Select(x =>{r = 0;z = k;while (z > 0){if(z % x==4){r++;}z/=x;}return new[]{r, x};}).OrderBy(n => n[0]).Last()[1]);}} ``` or ``` using System; using System.Linq; class P { static void Main() { int r, z, k = int.Parse(Console.ReadLine()); if (k <= 4) return; Console.WriteLine( Enumerable.Range(4, k).Select(x => { r = 0; z = k; while (z > 0) { if (z % x == 4) { r++; } z /= x; } return new[] { r, x }; }).OrderBy(n => n[0]).Last()[1]); } } ``` Pretty sure the number of variables can be reduced and the if's can be converted to ?s. Oh well... [Answer] C# (482 ~423 Bytes) First attempt at a 'golfed' solution. I used basically the same algorithm as the VBA above. I could probably save some bytes inlining the conversion function, or shortening the name. Like I said this is a first attempt, so please be gentle. With whitespace: ``` using System; class Program { static void Main(string[] args) { int n = int.Parse(args[0]); int c=0, m=0; string r=""; int t = 0; for (int i = 5; i < 37; i++) { while (n > 0) { r = (char)((int)(n % i) + 48 + (7 * ((int)(n % i) > 9 ? 1 : 0))) + r; n = (int)(n / i); } t = r.Length - r.Replace("4", "").Length; if (t > c) { c = t; m = i; } } Console.WriteLine("Base: " + m); } } ``` [Answer] ## Burlesque - 28 bytes ``` Jbcjro{dg}Z]J{4CN}Cmsb[~Fi?i Jbcjro create a list 1..input and convert input to an infinite list. {dg}Z] convert number to base (zipWith operation) J duplicate {4CN}Cm create comparison function 4CN count the number of fours. sb sort by [~ take the last element (which is going to be the base-n representation where count of fours is highest) Fi Find the index of this last element in the original unsorted list ?i increment (because base 1 is index 0) ``` [Try it online.](https://tio.run/##SyotykktLixN/a9jZmTy3yspOasovzolvTYq1qvaxNmv1jm3OCm6zi3TPvP/fwA) [Answer] # [Perl 6](http://perl6.org/), 44 bytes ``` {max 5..$^a,by=>{grep 4,$a.polymod($_ xx*)}} ``` [Try it online!](https://tio.run/##DccxCoAgAAXQq3xEokIcwiQIO0phpC2JYosint1aHrxg4iOby@gsVCtOJ8yc012zM6ut3NEECEY1D/7Jzl89PZDSONTaXp1B/qoNxYIelcD6CDkJBiF@5LK2Dw "Perl 6 – Try It Online") Good old [polymod](https://docs.perl6.org/routine/polymod). [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` S€►#4ṠMBḣ ``` [Try it online!](https://tio.run/##AR0A4v9odXNr//9T4oKs4pa6IzThuaBNQuG4o////zYyNA "Husk – Try It Online") ``` € The 1-based index in MB the list of the input's representations in every base Ṡ ḣ from 1 to itself S ► of its element which has the largest # number of 4 fours. ``` [Answer] # [Julia](http://julialang.org/), 50 bytes ``` n->sort(2:n+1,by=b->-sum(digits(n,base=b).==4))[1] ``` [Try it online!](https://tio.run/##LcrBCsIwDADQe76ixxbXYkccMkh/ZOyw4iaVmcmSgX59PejxwXsca5niuy5U2SfZdrVtz6fY5A9ln7wcT3sr96JiucmTzJRdIELnhjhWnUXFkBmguwIiQtcixP5yhhHgtRfWlYP9rUDJLH84V78 "Julia 1.0 – Try It Online") ]
[Question] [ Given a positive integer, output a truthy/falsy value as to whether the number can eat itself. ### Rules Leftmost is the head, rightmost is the tail If the head is greater than or equal to the tail, the head eats the tail and the new head becomes their sum. If \$sum \ge 10 \$ then the head is replaced by \$sum \mod 10\$. \$sum=0\$ cannot be ignored, however the input number will never have any leading zeroes. **Example:** ``` number=2632 head-2, tail-2 2632 -> 463 head-4, tail-3 463 -> 76 head-7, tail-6 76 -> 3 If only one digit remains in the end, the number can eat itself. ``` If at any point the head cannot eat the tail, the answer will be False. ``` number=6724 072 False (0<2) ``` ### Test Cases: ``` True: [2632, 92258, 60282, 38410,3210, 2302, 2742, 8628, 6793, 1, 2, 10, 100, 55, 121] False: [6724, 47, 472, 60247, 33265, 79350, 83147, 93101, 57088, 69513, 62738, 54754, 23931, 7164, 5289, 3435, 3949, 8630, 5018, 6715, 340, 2194] ``` This is **code-golf** so shortest code wins. [Answer] # JavaScript (ES6), ~~52 51~~ 50 bytes *Saved 1 byte thanks to @tsh* Takes input as a string. Returns a Boolean value. ``` f=n=>n>[n%10]?f(-(-n[0]-n)%10+n.slice(1,-1)):!n[1] ``` [Try it online!](https://tio.run/##jU/NToZADLzzFOvBAPmAbNv91YAnfQJvKweCoJ8hiwH19bH7JSZ689DZdtLtzLwNX8M@buf3jzquz9NxzG1su9iFeA2yv5uLuqhjkH0dSyZOsdmX8zgVUNVQljdXMUB/jGvc12VqlvWlyMPj9jn1eXmbBYGGsBIeUbtKGImOJ3IKJD@YEEkyhVYxOoNpy3qqBDDJKFMxaM0NguizZl63@2F8LaJoO/FbeGbqJPK8LFk6@2PpKYaHYdl/XBmLqhLKpsKLr9QToWEZltes6AgS6Qkke9FWuuTNa2BzBi3xpJXVKkXgJf4HhgeNzvMpRXyJvPIpFaUAEi7ZIPEqBQev/h3n@AY "JavaScript (Node.js) – Try It Online") ### Commented ``` f = n => // f = recursive function taking n (a string) n > [n % 10] // The last digit is isolated with n % 10 and turned into a // singleton array, which is eventually coerced to a string // when the comparison occurs. // So we do a lexicographical comparison between n and its // last digit (e.g. '231'>'1' and '202'>'2', but '213'<'3'). ? // If the above result is true: f( // do a recursive call: -(-n[0] - n) % 10 // We compute (int(first_digit) + int(n)) mod 10. There's no // need to isolate the last digit since we do a mod 10 anyway. + n.slice(1, -1) // We add the middle part, as a string. It may be empty. ) // end of recursive call : // else: !n[1] // return true if n has only 1 digit, or false otherwise ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` Ṛṙ-µṖÄ%⁵:ḊẠ ``` [Try it online!](https://tio.run/##HU67jUIxEMyvCieXGcn784cGrgggvATRACEICYkCTjoiCrgUiUcIlZhGfLNI3tHOaGc86@/NZjtGn859@p09rn36eR4@X7vrvN9O/X4Zz@Nr/4cXvsZYcBaOoTFbjSEnrmBSlVIUBgSWBIWLAmtmPypNYiCIwOQDMMPCtIph@bHIhTUGLT78TvVdhDOu4DYYqpCLTSghykqqHt2MkJ25CJhpMfUGOIKPMohxbYhSQZI0bV5K/P9E72rkunpvarr6Bw "Jelly – Try It Online") ### How it works ``` Ṛṙ-µṖÄ%⁵:ḊẠ Main link. Argument: n Ṛ Reverse n, after casting it to a digit list. ṙ- Rotate the result -1 units to the left, i.e., 1 unit to the right. Let's call the resulting digit list D. µ Begin a new chain with argument D. Ṗ Pop; remove the last digit. Ä Accumulate; take the cumulative sum of the remaining digits. %⁵ Take the sums modulo 10. Ḋ Dequeue; yield D without its first digit. : Perform integer division between the results to both sides. Integer division is truthy iff greater-or-equal is truthy. Ạ All; return 1 if all quotients are truthy, 0 if not. ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~63~~ 62 bytes ``` {!grep {.[*-1]>.[0]},(.comb,{.[0,*-1].sum%10,|.[1..*-2]}...1)} ``` [Try it online!](https://tio.run/##LY7NbsJADITvfQr3AKJosdb2/go1fZAoB6gClwQQiAOiefbUpj145BnZn@bSX4c0jw9YHuAT5uf78dpf4IntekNdg63vJrfC7/O4dxp6ZzHe7uOCvPvBlhDXG@4mRKSPab7tHvDVchJ2UJljcZA8F3VSgn4IqwCL14RzUC2J7ShXcUAaqnob3zUNLg@4G4bt2x82ZQ4OQrbhF9h2EU7RgQKiPhYhC6uQV1rMvhi9RlJ84izqYsgxWAk90j9KaiKXqqggSpIaqvUSxUVPr3ZkebDqVMN/s9P51G/nXw "Perl 6 – Try It Online") ### Explanation: ``` { } # Anonymous code block ( ... ) # Create a sequence .comb, # Starting with the input converted to a list of digits { } # With each element being .[0,*-1] # The first and last element of the previous list .sum%10 # Summed and modulo 10 ,|.[1..*-2] # Followed by the intermediate elements ...1 # Until the list is length 1 !grep # Do none of the elements of the sequence {.[*-1]>.[0]}, # Have the last element larger than the first? ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 83 bytes ``` n->{int r=0,h=n;while(h>9)h/=10;for(;n>9;h=(h+n)%10,n/=10)r=h<n%10?1:r;return r<1;} ``` [Try it online!](https://tio.run/##rVFNT@MwEL33V4yQKiVsyPoziRtSzhyQkDgiDqZNiLupUzlOEary28s4BYkDxz147Deeee95vNNHfbPb/jub/aF3HnaI09GbLm1Gu/Gmt@l1udh0ehjgQRsLpwXAYXztzAYGrz1ux95sYY930ZN3xr49v4B2b0M8lwLcW//o6q3ZaF9DAxWc7c36ZKwHV5GkrWz53pqujtq1itu/FSVl07uotGtVtlXU/rHxkpLEhpvYVe2tRXhHV650tR@dBXdLy@lczlrIiurejb79QKUTsIyzBBRjskggI6xAxAuBhJxhAMYJZlguMBYZC0W54glQTGIkYWGQEg@MwvRTptHdcFHJciYSEHlYbNYJZ85Zhn3IJ5Gi4DQkFacEyWVOiiCmJEW1jOUckRS5FMETFmEfzRBIViikEhyZuBIq2OTBEaGzWRryIryEKvHtDwcIUZjwUXdjvfoayPeHADx9DL7ep/3o0wP@mG@iq6XcrmD5urRXyaUrgSb19eCjGcXxhXn6lX@exP@inxbT@RM "Java (JDK) – Try It Online") ## Credits * -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [Answer] ## Mathematica, 62 bytes ``` 0(IntegerDigits@#//.{a_,r___,b_}/;a>=b:>{Mod[a+b,10],r})=={0}& ``` First calls `IntegerDigits` on the input to get a list of its digits, then repeatedly applies the following rule: ``` {a_,r___,b_} (* match the first digit, 0 or more medial digits, and the last digit... *) /;a>=b (* under the condition that the number is edible... *) :>{Mod[a+b,10],r} (* and replace it with the next iteration *) ``` The rule is applied until the pattern no longer matches, in which case either there is only one digit left (truthy) or the head is less than the tail (falsy). Instead of calling `Length[__]==1`, we can save a few bytes with `0(__)=={0}`, multiplying all elements in the list by `0` and then comparing with the list `{0}`. [Answer] # [Python 3](https://docs.python.org/3/), 50 bytes First line stolen from [Black Owl Kai's answer](https://codegolf.stackexchange.com/a/177133/64121). ``` p,*s=map(int,input()) while s:*s,k=s;p%10<k>q;p+=k ``` [Try it online!](https://tio.run/##TY7BboMwEETv@xVcqkDKwbtrY5uU3pJje@kP0NRSEAm4hqjJ19Ol6iGSZXtnnmcc7/NpHHg5jl@h2Ww2Syy3U3NpY94Nc9kN8TrnRQE/p@4csqneTmXfTLv4hOqlf/3exeemX@TZP/CRrqGGLJvTfT2yLNzCMV@zi78xJknNV2qdw@0Y4py9tZewT2lM9QNzaM/TI7R/Pzwwnym0/UIVE3gi46BS5AjYaVTAJBuxIiCrCVxF4lvPgEAgFioFxgASikwatJVFa4TcmKkyILRR4BhF8YwKwVjlJMYbZKjIsgOjrdHSIz5YrDQYch5YswH22ksvS4/CtRxF0/Ip9PoX "Python 3 – Try It Online") Output is via exit code. Fails (1) for falsy inputs and finishes (0) for truthy inputs. [Answer] # [Python 2](https://docs.python.org/2/), ~~105~~ ~~82~~ 81 bytes ``` i,x=map(int,input()),1 for y in i[:0:-1]: if i[0]%10<y:x=0 else:i[0]+=y print x ``` [Try it online!](https://tio.run/##VY/PTsMwDMbveYqoEuoGRYrt/K3olSfgBjtMIxOVoK3KJrVPX2IPDlzy5fNn/@JM6@VjHHA7je9Zd7qu661vlu7rOO364dL0w3S97Pb7BtR5nPWq@0H3r61pH@HQKt2fizOHOzBPa7t0Run8@Z1brj10q5rmwtDLVqi/9/plvuZa5SWftDx5r4H@srfh@VjG/8eISm0VesJKVQnRxaLeYGRP0YJhRREkw1UMliV6lN6QqAhwwGrkMJKgLWKDHHjjiiNC74qWUcedkUDqicAwyAUThZ0cMNxjIPbOBmdlkdLJ8@DZOoyJqZYYSskmWY8Y7QzctgTJrPwDkq1@AA "Python 2 – Try It Online") Many thanks for a massive -23 from @ØrjanJohansen Thanks to @VedantKandoi (and @ØrjanJohansen) for another -1 [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 23 bytes ``` ẹ{bkK&⟨h{≥₁+tg}t⟩,K↰|Ȯ} ``` [Try it online!](https://tio.run/##LU@7TgMxEPwVx8U1uLB3/eQDaNJScboiQVFOIlKkcChClyuIECIdf5AKAQ2ioSBfwG@cf@TYDSl2NDsaz46nq8l1fb9YzmFo6/6wK5p2Lc@FXBejNj995e1jfn6Tl6u7mdwwu5gsbmeyG5G1679fWJInPvSHn3Z6My7y/r1u8@41bx/OmnnX5P2HGlPY5vezG4ay/I9TJXgEJRKAi0p4DZE2jNZohUAgADUpECxh9MCmkFAJQyKh5iFwjgiYqlKiPPUj5gNYJWzggWM8c0TwZKcYRy8jGhYTGk2ZLujIN5IzdMRDQNqcDc5yFTLRO@NpcRATRVmkJEw2cTvkItocOxrWLX/AJFtV1XD1Bw "Brachylog – Try It Online") This is a 1 byte save over [Fatalize's solution](https://codegolf.stackexchange.com/a/177139/81957). This uses a recursive approach instead of a iterative ### Explanation ``` ẹ Input into a list of digits { } Assert that either bk | the list has at least 2 elements (see later) ⟨h{ }t⟩ | and that [head, tail] ≥₁ | | is increasing (head >= tail) + | | and their sum t | | mod 10 (take last digit) g | | as single element of a list , | concatenated with bkK K | the number without head and tail (this constrains the number to have at least 2 digits) ↰ | and that this constraint also works on the newly formed number |Ȯ | OR is a 1 digit number ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 33 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous tacit prefix function taking a string as argument. ``` {⊃⍵<t←⊃⌽⍵:0⋄3::1⋄∇10|t+@1⊢¯1↓⍵}⍎¨ ``` [Try it online!](https://tio.run/##JU@7TgNBDOz5CrotENLa3ucpBRINqZAIPxAJhSYSKdIgQgU6UOBOIMQPUKVLRUlzn@IfOWynmdmxPfbsfLU8vbmfL@9ux/GBt0/c/U7W3H7o8/1PVOP57ZmaBoT49QX8Zn1yBrz9GfbA7ZdMPHLXD7txoa6u5/57einuYU/cfoqaXZ0LXl9MZ@Ni2DlMhO7YVcRYhJPHoppKAK@MRkheq5iDUklos7mSEGhD2RsoxqhPBHekJ1LGIDpkAzxcMUWESUdlUVRfIbB6JfC6NmZf7FKNoKcSZlIdQ47BYsmk@iGpjFiqbg2kS6mGamHJInk4ZAbrBfsV1OD@AQ "APL (Dyalog Unicode) – Try It Online") `⍎¨` evaluate each character (this gives us a list of digits) `{`…`}` apply the following "dfn" to that; `⍵` is the argument (list of digits):   `⌽⍵` reverse the argument   `⊃` pick the first element (this is the tail)   `t←` assign to `t` (for **t**ail)   `⍵<` for each of the original digits, see if it is less than that   `⊃` pick the first true/false  `:` if so:   `0` return false  `⋄` then:  `3::` if from now on, an index error (out of bounds) happens:   `1` return true   `¯1↓⍵` drop the last digit   `⊢` yield that (separates `1` and `¯1` so they won't form a single array)   `t+@1` add the tail to the first digit (the head)   `10|` mod-10   `∇` recurse Once we hit a single digit, `¯1↓` will make that an empty list, and `@1` will cause an index error as there is no first digit, causing the function to return true. [Answer] # [Python 3](https://docs.python.org/3/), 77 bytes ``` p,*s=map(int,input()) print(all(n<=sum(s[i+1:],p)%10for i,n in enumerate(s))) ``` [Try it online!](https://tio.run/##FY5BT8MwDIXP86/oBS2BHmI7aZKJHceVCzfEoYygVWxplLaC/friSpZlv2e9z@U@X8bM63n8Ssf9fr@W9nE63vqihjy3Qy7LrLSGUmVV/fWq8vNxWm5qeh@e8PDRFv2A5nuszdDmZshNysst1X5OatJar5IIv5fhmpq3uqQD7OZ6l75Lf@msNqYGmc@pzM3p9eVU61g3@7Om/meljgkikQvQGQoEHCwaYJJGbAjIW4LQkfg@MiAQiIXGgHOAhCKTBeulaIuQiZk6B3LtDARGUSKjQXDeBImJDhk68hzAWe@scMQHj50FRyECW3bA0UbhsnAMbnAUzcpTGO0/ "Python 3 – Try It Online") --- And my old solution with a recursive approach # [Python 3](https://docs.python.org/3/), 90 bytes ``` f=lambda x,a=0:2>len(x)if 2>len(x)or(int(x[0])+a)%10<int(x[-1])else f(x[:-1],a+int(x[-1])) ``` [Try it online!](https://tio.run/##bU/LTsMwEDyTr/AFKVaN5N31M6L8SJVDKIkaKSRV6kP4@rDbCsGBw452xvbM@PpVLstM@z4cp@7z/aNTm@mOtsG3qZ/rTY@D@lmXtR7nUm8n2@pDp5/Bvj74C7S6n269Gpg0zEx3@D3R@7CsqpzVOKsTBkKjMqJPRgWLiRklB9YQMigkywpGx5gCyqWYyShgkdHKMHjPC0LbVE/XVaKG@lbWupy11tVD0VX1JzdEdEa5KIP3ZNmJMLATJ3g2TQQiZgLLcT7aJPHZA@cHjMTMu@idtORL/A4CE48ps5UjdqLsshQn6WjhXh9Ed/I3yO7fxvs3 "Python 3 – Try It Online") Takes input as a string. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 24 bytes ``` ẹ;I⟨⟨h{≥₁+tg}t⟩c{bk}⟩ⁱ⁾Ȯ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@Gundaej@avAKKM6kedSx81NWqXpNeWPJq/Mrk6KbsWSD9q3Piocd@Jdf//G1uYGBr8BwA "Brachylog – Try It Online") I should change `ⁱ`'s default behaviour so that it iterates an unknown number of times (currently, it iterates 1 time by default which is completely useless). I then wouldn't need the `[…];I[…]⁾`, saving 3 bytes ### Explanation This program contains an ugly fork inside a fork. There is also some plumbing needed to work on lists of digits instead of numbers (because if we remove the head and tail of `76` we are left with `0`, which doesn't work contrary to `[7,6]` where we end up with `[]`). ``` ẹ Input into a list of digits Ȯ While we don't have a single digit number… ;I ⁱ⁾ …Iterate I times (I being unknown)… ⟨ ⟩ …The following fork: c | Concatenate… ⟨ ⟩ | The output of the following fork: h t | | Take the head H and tail T of the number { } | | Then apply on [H,T]: ≥₁ | | | H ≥ T + | | | Sum them tg | | | Take the last digit (i.e. mod 10) and wrap it in a list { } | With the output of the following predicate: bk | | Remove the head and the tail of the number ``` [Answer] ## Haskell, ~~70~~ ~~64~~ 60 bytes ``` f(a:b)=b==""||a>=last b&&f(last(show$read[a]+read b):init b) ``` Input is taken as a string. [Try it online!](https://tio.run/##dY5bisJQDIbfXUUQkZYJcnI5N6GzEenDKVos1ipWmBf3XtMFDIQk5E/@fNcy3y7juCx9VY5d3XRNs91@PuW3Gcv8hm6/76u1q@br42/3upTzqbQ/a4WuPg7TYDv1ci/DBA2cHxsAeL6G6Q07uJcnVP1hPazhxEEYM7NPGBwnRklKDoUtsThGjsqYApsesyAho0nkHHqPxNT@7x0iK2q04NXcOhEOHs3HO0xCNslCjtBHl@xB9iQYOEpCr9GrEZiOkYKi55RRVDxK1mxEYgSOViyymRouZW03yxc "Haskell – Try It Online") Edit: -6 bytes by using [@Laikoni's trick](https://codegolf.stackexchange.com/a/177198/34531) of using `||` instead of separate guards. Another -4 bytes thanks to @Laikoni. [Answer] # [Perl 5](https://www.perl.org/), 64 bytes ``` {local$_=pop;1while s/(.)(.*)(.)/$1<$3?'':(($1+$3)%10).$2/e;/./} ``` [Try it online!](https://tio.run/##RU/tSgNBDPzvU6RlpXe63G2SzX54io9SWlm1eNCjRxURn/3MloI/MiRDMjOZymmU5TwX@JQO3XAzn/dQlp/x@LIbzfZpOk4Dfr0fxgJz33Rt091ptb3BR8PPm81D0xi8N9zeoms7Q30Z@q7/XebdN6yPH4BrOLzC6u1UplVpzLa1QIHJQiaSZCE4Sjpx8ugskwIQO2UoesUUqC7FzBZQSUVXS0FEG0JNfLWifyu4WoVI3oKPtehiVntmCnqsoqI6ibGSmdGpg0SXqmMWVMtAkXUSH8XXYLqkdxh0EEpZpTyrEmefa1ausRxeEmPlfX0Hsx@WPw "Perl 5 – Try It Online") [Answer] # [Python 2](https://docs.python.org/), ~~75~~ 67 bytes ``` l=lambda n:n==n[0]or n[-1]<=n[0]*l(`int(n[0]+n[-1],11)%10`+n[1:-1]) ``` **[Try it online!](https://tio.run/##fVBNS8RADL3vrwgFoXUrTJL5LO7VX@CtFlrXFRfq7NLWg7@@JmVvogMJeW8yyXtz/V4@LpnWdTyMw@fr2wC5yYdDbk13mSC3D9g9buh@LPtzXkqt9xtfI1Z3aHpB2Aiu1uskHVC85Ofp6wTLaV7gOMynuSl27zoNzhla8kw1JCIXa/CGoiCOFk3NJAmIjTAUrOToSZtC4hpQSMlGQ5JzUhB2Ddy2gpwC9jAvUylac19Vu9tV8at4Gsb5T4U@kK3BBg3aNGrNTF52ihYn6yOjkonRiDAXTFShyaEo9RRYkLPBWfUjTfIOvQBHMckoyzKJk01qkdWNwc0oKm/1FzDZf72t6w8)** Recursive lambda approach. Takes input as a string. Many thanks to Dennis for saving 8 bytes! [Answer] # [Haskell](https://www.haskell.org/), ~~69~~ 64 bytes ``` f n=read[show n!!0]#n h#n=n<10||h>=mod n 10&&mod(h+n)10#div n 10 ``` [Try it online!](https://tio.run/##ZU/LasNADLznKxRcQkv3oMc@oe6PBB8MTrBpvA5JSS75d1fytQcN0iDNjMb@/nO6XNb1DLW9nfrheB@XJ9T9Hrum7samtvWL8PUav9t5GaAC4eGg3fv4WT8Im2F6bOQ691OFFoYFdnC9TfUX3mDur3CGI0dhB4U5ZAcROesk2RM6YQVgQWU4ecUc2ZZSEQekpCJaKYSgDVP3Tz8m9g58suLNwXoRjnqhSkGPs5CRRQhVNiTMZlMCqU/kJDoFn4K3NLqkdxR1CJyLSnlRJSm@WECxLEhbTDLe2w9UfLf@AQ "Haskell – Try It Online") Example usage: `f 2632` yields `True`. *Edit:* -5 bytes because `mod (h + mod n 10) 10 = mod (h + n) 10` [Answer] # Ruby, 139 bytes ``` ->(a){a.length==1?(p true;exit):1;(a[0].to_i>=a[-1].to_i)?(a[0]=(a[-1].to_i+a[0].to_i).divmod(10)[1].to_s;a=a[0..-2];p b[a]):p(false);exit} ``` [Try it online!](https://tio.run/##RY3RCoIwGIXvfQov9xMbm0EXjumDDInfXDpQN9yMInr2VQp1d/jOdzjL2j5SahWtCMIT2WjmPg5KiZr4PC6rkeZuI5RCEtS8YdGdbaVQU7FnqDeuyB8dfiKwzt4m1xHBQe9tkPhZc8Zo0UiftxobKD254hgMbF@vLEPVmxjYZXCTz75KSsXpWLwB "Ruby – Try It Online") (has some extra code to process input, since it's a function) Ungolfed code: ``` ->(a) do if a.length == 1 p true exit if a[0].to_i >= a[-1].to_i a[0] = (a[-1].to_i + a[0].to_i).divmod(10)[1].to_s a = a[0..-2] p b[a] else p false exit end end ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 42 bytes ``` \d $*#; ^((#*).*;)\2;$ $2$1 }`#{10} ^#*;$ ``` [Try it online!](https://tio.run/##FY49CgJRDIT7ucY@Yd1CkknyftgDeAkRBS1sLMROPPsaIYQwE@ab1/39eF633TwfL9vphrJMK87zPC37w7LuT1wLCovie5k@Kl/gPC1r2TZWIwYZHVXYCeuuAmMumhBsTvTK9NswKIi0VAQRUGrKdHjL4T8iLzPWQH6HoJumMkxFEU16xoxQQ2WzjvAWnpz00bQ6gn3A3AI2fCTXkiP6h2tqnqV0@A8 "Retina 0.8.2 – Try It Online") Link include test cases. Explanation: ``` \d $*#; ``` Convert the digits to unary and insert separators. ``` ^((#*).*;)\2;$ $2$1 ``` If the last digit is not greater than the first then add them together. ``` #{10} ``` Reduce modulo 10 if appropriate. ``` }` ``` Repeat until the last digit is greater than the first or there is only one digit left. ``` ^#*;$ ``` Test whether there is only one digit left. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~26~~ ~~25~~ 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [DgD#\ÁD2£D`›i0qëSOθs¦¦« ``` Can probably be golfed a bit more.. It feels overly long, but maybe the challenge is in terms of code more complex than I thought beforehand. [Try it online](https://tio.run/##yy9OTMpM/f8/2iXdRTnmcKOL0aHFLgmPGnZlGhQeXh3sf25H8aFlQLj6/39TUwA) or [verify all test cases](https://tio.run/##HU47ikJBELzKoOkE07/5RCYvNzAR3AUVRIw2EBZeIGjiAbzCwiZeQDbUfA/hRZ7VMnTRXVNV3V/71Xq3Gb77ySg8z5cwmvTDott244/HqeP7T7d8Hv92aT5@XGfT/9v@/ot3HQ6HOCw4C8fQmK3GkBNXTFKVUhQGBJYEhosCa2YXlSYxEEhg8gKYoWHyX9YYtHjxO9F7Ec5QwGkQVyEnm1CCw0qqHtuMkJu5CCbTYurbIYKPMgbj2hClgiRp2vwg8d2J3meR8@o3U9PPFw). **Explanation:** ``` [ # Start an infinite loop D # Duplicate the top of the stack # (which is the input implicitly in the first iteration) gD # Take its length and duplicate it # # If its a single digit: # Stop the infinite loop # (and output the duplicated length of 1 (truthy) implicitly) # Else: \ # Discard the duplicate length Á # Rotate the digits once towards the left D2£ # Duplicate, and take the first two digits of the rotated number D` # Duplicate, and push the digits loose to the stack ›i # If the first digit is larger than the second digit: 0 # Push a 0 (falsey) q # Stop the program (and output 0 implicitly) ë # Else (first digit is smaller than or equal to the second digit): SO # Sum the two digits θ # Leave only the last digit of that sum s # Swap to take the rotated number ¦¦ # Remove the first two digits « # Merge it together with the calculated new digit ``` [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 144 bytes ``` bool f(std::string b){int c=b.length();while(c>1){if(b[0]<b[c-1])return 0;else{b[0]=(b[0]-48+b[c-1]-48)%10+48;b=b.substr(0,c-1);--c;}}return 1;} ``` [Try it online!](https://tio.run/##TY7BasMwEETv@gqRUpBIVGRIicnK/pGQg7SWHYEiG0umB@Nvd2U3kO5pmbc7MzgMokNcP1xAPzWWKtfHNFr9rAlZTd972rKYmus1qy501PDZhUSxMl/ehi49GIefh/OWYV1k1jJzk3dlbiiKOx9tmsZAJVgf7byRaufiXB7/TvLGPwt5PJdgsmecTA5i8pQZByEQluVlUsCybtFP7QLjZCY0z/9qmlb08H2RZXmAHe71dWzaqmWaw/sB@ykptRGldsGGxgNZ1l8 "C++ (gcc) – Try It Online") First time I'm trying something like this so if I formatted something wrong please let me know. I'm not 100% sure on the rules for stuff like using namespace to eliminate the 5 bytes "std::" so I left it in. Ungolfed: ``` bool hunger(std::string input) { int count=input.length(); while (count>1) { if (input[0]<input[count-1]) //if at any point the head cannot eat the tail we can quit the loop //comparisons can be done without switching from ascii { return false; } else { input[0]=(input[0]-48+input[count-1]-48)%10+48; //eating operation has to occur on integers so subtract 48 to convert from ASCII to a number input=input.substr(0,count-1); //get rid of the last number since it was eaten --count; } } return true; //if the end of the loop is reached the number has eaten itself } ``` [Answer] # C#, 114 bytes ``` static bool L(string n){return n.Skip(1).Reverse().Select(x=>x%16).Aggregate(n[0]%16,(h,x)=>h>=x?(h+x)%10:-1)>=0;} ``` [Try it online](https://tio.run/##TU9dS8MwFH1uf8VlOEhwC22VCpZWxNcKYh/2MPYQ4zUNdokmWamU/vaYwR4G9@Hc88HhCLcVxmI4OaUldH/O47FKrz/WKv1bpWLgzsGbNdLyI8zBee6VgA9jBmiJ8/ac0HS26E9Wg2bdt/ohOWXvOKJ1SCjrcEDhyVQ30zovKXuW0qLkHoneZ4dIbUi/mWjd9E09PZH@dqLrPHvc5rSps2oJyaVzNOoTXrnSl9r9AbiVjsKcJslXXMNFT0ZuzywofSUmL0Y7MyDbWeUxDkNys5qjvkDdwNySCOmyolX0Lmm8JYSivCtCmRX3D/8) [Answer] # [C (gcc)](https://gcc.gnu.org/) *(with string.h)*, ~~110~~ 108 bytes ``` c;f(char*b){c=strlen(b);if(!c)return 1;char*d=b+c-1;if(*b<*d)return 0;*b=(*b+*d-96)%10+48;*d=0;return f(b);} ``` [Try it online!](https://tio.run/##hY7RboMgGEav61MwGxPAuaDbWjtKH2K36y7gRyyJo43iVdNnt2Bnsrtd8p2T8wNFCzCtrYNu1A3aD17b88vpkPydeuvauE3ADYaT7KkiVxABdI3DinBr8BOQvvFj71DJZ0ULlUNRRkbVnuoFM06VCFNOdbHbkKxk@VvNg874r2Fi8jZZ59GPtA6T5JqsYhPJr5J9I4HS9y2r6yNLebKKmhy0EQZLEt6X8FtvcPrZDGPnP1Bmjy59npWI545aOtXmtXpkIg/LfPu/yG26Aw "C (gcc) – Try It Online") Still relatively new to PPCG, so the correct syntax for linking libraries as a new language is foreign to me. Also note that the function returns 0 or 1 for false/true, and printing that result to stdout does require stdio. If we're being pedantic and the exercise requires output, the language requires *stdio* that as well. Conceptually similar to @BenH's answer, but in C, so kudos where they are due (Welcome to PPCG, btw), but using recursion. It also uses array pointer arithmetic, because dirty code is shorter than clean code. The function is tail recursive, with exit conditions if the first number can't eat the last or the length is 1, returning false or true, respectively. These values are found by dereferencing a pointer to the C-String (which gives a char) at the beginning and end of the string, and doing the comparisons on them. pointer arithmetic is done to find the end of the string. finally, the last char is "erased" by replacing it with a null terminator (0). It's possible that the modulus arithmetic could be shortened by a byte or two, but I already need a shower after that pointer manipulation. [Ungolfed Version Here](https://tio.run/##hY/NTsMwEITP8VOsgirZLkFOoSXQmofgSnvwT9xaSg1KnBPKs4e1AxKcOHrmm9mxqc7GzDc@mG60LRyGaP373eWF/JZ6H85Jm32I4Ki5qJ5rRj5JkQQjAZGuDVSzPUoISFkzUqBf9G0c@wA1GhMpUhI4WJCg16aqMw6UazgAtwz@ZMSSQVNmZI0IVE87Bqta4OuhQYCnrkR@h1weMeWlV@UDzTPzXfVWixPS5fZRNM1RlPtlvxqsk46qNP4DvxodLV/bYeziM6z8MZS3GUl27tE/PZvd/WapST4qy/F/Sqb5Cw "Ungolfed Version Here") Update: Saved two bytes by replacing c==1 with !c. This is essentially c == 0. It will run an additional time, and will needlessly double itself before deleting itself, but saves two bytes. A side effect is null or zero length strings won't cause infinite recursion (though we shouldn't get null strings as the exercise says positive integers). [Answer] # Powershell, 89 bytes ``` "$args"-notmatch'(.)(.*)(.)'-or(($m=$Matches).1-ge$m.3-and(.\g(''+(+$m.1+$m.3)%10+$m.2))) ``` Important! The script calls itself recursively. So save the script as `g.ps1` file in the current directory. Also you can call a script block variable instead script file (see the test script below). That calls has same length. Note 1: The script uses a lazy evaluation of logic operators `-or` and `-and`. If `"$args"-notmatch'(.)(.*)(.)'` is `True` then the right subexpression of `-or` is not evaluated. Also if `($m=$Matches).1-ge$m.3` is `False` then the right subexpression of `-and` is not evaluated too. So we avoid infinite recursion. Note 2: The regular expression `'(.)(.*)(.)'` does not contain start and end anchors because the expression `(.*)` is greedy by default. ## Test script ``` $g={ "$args"-notmatch'(.)(.*)(.)'-or(($m=$Matches).1-ge$m.3-and(&$g(''+(+$m.1+$m.3)%10+$m.2))) } @( ,(2632, $true) ,(92258, $true) ,(60282, $true) ,(38410, $true) ,(3210, $true) ,(2302, $true) ,(2742, $true) ,(8628, $true) ,(6793, $true) ,(1, $true) ,(2, $true) ,(10, $true) ,(100, $true) ,(55, $true) ,(121, $true) ,(6724, $false) ,(47, $false) ,(472, $false) ,(60247, $false) ,(33265, $false) ,(79350, $false) ,(83147, $false) ,(93101, $false) ,(57088, $false) ,(69513, $false) ,(62738, $false) ,(54754, $false) ,(23931, $false) ,(7164, $false) ,(5289, $false) ,(3435, $false) ,(3949, $false) ,(8630, $false) ,(5018, $false) ,(6715, $false) ,(340, $false) ,(2194, $false) ) | %{ $n,$expected = $_ #$result = .\g $n # uncomment this line to call a script file g.ps1 $result = &$g $n # uncomment this line to call a script block variable $g # the script block call and the script file call has same length "$($result-eq-$expected): $result <- $n" } ``` Output: ``` True: True <- 2632 True: True <- 92258 True: True <- 60282 True: True <- 38410 True: True <- 3210 True: True <- 2302 True: True <- 2742 True: True <- 8628 True: True <- 6793 True: True <- 1 True: True <- 2 True: True <- 10 True: True <- 100 True: True <- 55 True: True <- 121 True: False <- 6724 True: False <- 47 True: False <- 472 True: False <- 60247 True: False <- 33265 True: False <- 79350 True: False <- 83147 True: False <- 93101 True: False <- 57088 True: False <- 69513 True: False <- 62738 True: False <- 54754 True: False <- 23931 True: False <- 7164 True: False <- 5289 True: False <- 3435 True: False <- 3949 True: False <- 8630 True: False <- 5018 True: False <- 6715 True: False <- 340 True: False <- 2194 ``` --- # Powershell, 90 bytes No recursion. No file name dependency and no script block name dependency. ``` for($s="$args";$s[1]-and$s-ge$s%10){$s=''+(2+$s[0]+$s)%10+($s|% S*g 1($s.Length-2))}!$s[1] ``` A Powershell implicitly converts a right operand to a type of a left operand. Therefore, `$s-ge$s%10` calculates right operand `$s%10` as `integer` and compare it as a `string` because type of the left operand is `string`. And `2+$s[0]+$s` converts a char `$s[0]` and string `$s` to `integer` because left operand `2` is integer. `$s|% S*g 1($s.Length-2)` is a [shortcut](https://codegolf.stackexchange.com/a/111526/80745) to `$s.Substring(1,($s.Length-2))` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 69 bytes ``` x=>{for(int h=x[0],i=x.Length;i>1;)h=h<x[--i]?h/0:48+(h+x[i]-96)%10;} ``` [Try it online!](https://tio.run/##TVFLa4NAEL77K4ZAQYmm@9TdGFNKr7m10IN4SEWzC0FBt9QQ/O121pbSwww7s/M9drYek3q0y3PtbN8dRjfY7nKEFoplKo73th9C2zkwxVSSKrbFtDs13cWZ3B5pHpnCHKYySWz1ZB7JXqhtaLZTaatEp9EDJfm85EGABGUFbvh05gYFdM1XWQV3lnIWg2ZMqhhSwhRWXAlKYs4wAeMEOywTmFXK/FCmeQwUm5iJD0xS4oHR@U@nPV/HfzJpxkQMIvPBViF/5pylCERCiRyKU9/UnBJklxlRXk1LinIpyzhWUmRSeFM4hDiaYiGZ0kglODJxLbT3yb0lQle31PeFfwrVwhvEbTbn2sC6Ugu2@13K7qXv6rMLV@tRBPcA4KPvrzAUONDkWLrhtrYB2tDu3vrX9aPCKPKXMyAaeX8GhsLzrKgZ432wrjnZrgntdrOHzXZAzLx8Aw "C# (Visual C# Interactive Compiler) – Try It Online") Success or failure is determined by [presence or absence of an exception](https://codegolf.meta.stackexchange.com/a/11908/8340). Input is in the form of a string. Less golfed... ``` // x is the input as a string x=>{ // h is the head for(int h=x[0], // i is an index to the tail i=x.Length; // continue until the tail is at 0 i>1;) // is head smaller larger than tail? h=h<x[--i] // throw an exception ?h/0 // calculate the next head :48+(h+x[i]-96)%10; } ``` There are a couple extra bytes to deal with converting between characters and digits, but overall that didn't affect the size too much. [Answer] # [Perl 5](https://www.perl.org/) `-pF`, 53 bytes ``` $F[0]=($F[0]+pop@F)%10while$#F&&$F[0]>=$F[-1];$_=!$#F ``` [Try it online!](https://tio.run/##K0gtyjH9/1/FLdog1lYDTGkX5Bc4uGmqGhqUZ2TmpKoou6mpgSXsbIGUrmGstUq8rSJQ@P9/U9N/@QUlmfl5xf91C9wA "Perl 5 – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 18 bytes ``` ẹ⟨k{z₁{≥₁+t}ᵐ}t⟩ⁱȮ ``` [Try it online!](https://tio.run/##HU47TgNBDL3KaFpGaMb2/CoOglIsUfiIKJFgpBVZbZEgoaTjBqkQoUFQUJATcI2diyx2Cj/bz8/PvnpoprdP8@UNjF2r1bRZ6Paiqy9fdfNctwe9WBbd9nX7rtWsKequPM7m1@d6OO764ed1HI6/dX@471Z1s@7q7o3TWZFJX@r@o66//z7H8RICglEZwCejgoXEHSZy1iAwKEDLDERiTAFEFDMa5ZhktBIM3nMBTqZARlGUgJOj1IgQWMGbnsUJnZAZneUNH20S2@wd@waIyJ2n6Emus4j3XODGQ8psRchOmCnLQyi3rTu95YQn@dllmvwD "Brachylog – Try It Online") Takes three bytes off Fatalize's solution just by virtue of non-deterministic superscriptless `ⁱ` existing now, but loses another three by doing vaguely Jelly-inspired things with `z₁` to avoid using `c`, `g`, or even `h`. (Also inspired by trying, and failing, to use a different new feature: the `ʰ` metapredicate.) ``` Ȯ A list of length 1 ⁱ can be obtained from repeatedly applying the following ẹ to the list of the input's digits: ⟨k{ }t⟩ take the list without its last element paired with its last element, z₁ non-cycling zip that pair (pairing the first element of the list with the last element and the remaining elements with nothing), { }ᵐ and for each resulting zipped pair or singleton list: ≥₁ it is non-increasing (trivially true of a singleton list); t take the last digit of + its sum. ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~94~~ 91 bytes ``` for(;$n-and$n[0]-ge$n[-1]){$n=$n-replace"^.",((+$n[0]+$n[-1]-96)%10)-replace".$"}return !$n ``` [Try it online!](https://tio.run/##rVDLTsMwELznK5bIVWOaVH4nBiFxQhw4QQUHVKpQ3IcUnMpNy6H028u6SKi9c/B4H@P1zK7aLxfWC9c0h9nGT7tl62GWEU93yWHWhuya@KL2H8S/snExd3gXfEx3xN9gI7hVU09d@jZM8ywbHEmDX0phDe1xRv84Q5Lug@s2wcMF8YdH99luXfFch2X93jjwyT5JXsKyc8V9u@5gFDYOtnWzceur5DYTRoocrBC6ysEwUWEmK8VZLgUCCMmwIkqFWBkRSaWVOXAsIrJ4ELTGQHAK39CDHZz8lwKQCZCsD/3LzBRkMhy1T11Y@nlGhw/Oz7sFpdifQeHhrEtTOJd@VzfrU@2mFCoHVcYjjupjLKUwqAZVahRWSR6LVnKGknXJqmjBao4ejCglZlqVWkWnSMJ33GCiRWVxlJI4SVplo3kZfTJ@XAGPdRX3w636d9eHHw "PowerShell – Try It Online") --- ## Test Script ``` function f($n){ for(;$n-and$n[0]-ge$n[-1]){$n=$n-replace"^.",((+$n[0]+$n[-1]-96)%10)-replace".$"}return !$n Remove-Variable n } Write-Host True values: @(2632, 92258, 60282, 38410,3210, 2302, 2742, 8628, 6793, 1, 2, 10, 100, 55, 121) | % { Write-Host " $_ $(' '*(6-$_.ToString().Length)) $(f $_.ToString())" } Write-Host False values: @(6724, 47, 472, 60247, 33265, 79350, 83147, 93101, 57088, 69513, 62738, 54754, 23931, 7164, 5289, 3435, 3949, 8630, 5018, 6715, 340, 2194) | % { Write-Host " $_ $(' '*(6-$_.ToString().Length)) $(f $_.ToString())" } ``` ## Ungolfed code: ``` function f ($inVar){ # While the Input exists, and the first character is greater than last while($inVar -and ($inVar[0] -ge $inVar[-1])){ # Calculate the first integer -> ((+$n[0]+$n[-1]-96)%10) $summationChars = [int]$inVar[0]+ [int]$inVar[-1] # $summationChars adds the ascii values, not the integer literals. $summationResult = $summationChars - 48*2 $summationModulo = $summationResult % 10 # Replace first character with the modulo $inVar = $inVar -replace "^.", $summationModulo # Remove last character $inVar = $inVar -replace ".$" } # Either it doesn't exist (Returns $True), or # it exists since $inVar[0] < $inVar[-1] returning $False return !$inVar } ``` ]
[Question] [ ## Introduction and Credit We all know and love our awesome rules to test whether a number is divisble by 11 or 3, which is just some clever sum over the digits of the number. Now this challenge takes this to a new level, by requiring you to compute the sum of the digits and then checking whether the result is a perfect integer square, neither of which operations usually can be done very short. As this property is also very hard to see when looking at a number, we want this to be done for entire lists of numbers so we can save human work. So this is *your* challenge now! This was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitely). ## Specification ### Input Your input is a list of non-negative integers, in any standard I/O format. You may choose the list format as your language needs it ### Output The output is a list of integers, in any standard I/O format. ### What to do? Filter out every integer from the input list for which the sum of the digits *is not* a a square (of an integer). The order of the elements may not be changed, e.g. if you get `[1,5,9]` you may *not* return `[9,1]` ### Potential corner cases 0 *is* a non-negative integer and thus a valid input and 0 is also a valid integer root, e.g. 0 counts as an integer square. The empty list is a valid input and output as well. ### Who wins? This is code-golf so the shortest answer in bytes wins! Standard rules apply of course. ## Test Cases ``` [1,4,9,16,25,1111] -> [1,4,9,1111] [1431,2,0,22,999999999] -> [1431,0,22,999999999] [22228,4,113125,22345] -> [22228,4,22345] [] -> [] [421337,99,123456789,1133557799] -> [] ``` ### Step-by-Step Example ``` Example input: [1337,4444] Handling first number: Sum of the digits of 1337: 1+3+3+7=14 14 is not an integer square, thus will be dropped! Handling second number: Sum of the digits of 4444: 4+4+4+4=16 16 is an integer square because 4*4=16, can get into the output list! Example output: [4444] ``` [Answer] ## Pyke, 6 bytes ``` #s,DBq ``` [Try it here!](http://pyke.catbus.co.uk/?code=%23s%2CDBq&input=%5B1337%2C4444%5D) ``` # - Filter list on truthiness: s - digital_root(^) , - sqrt(^) Bq - int(^) == ^ ``` [Answer] # Mathematica, ~~39~~ 36 bytes An anonymous function: ``` Select[AtomQ@√Tr@IntegerDigits@#&] ``` LLlAMnYP saved a byte. Thank you! Martin Ender saved three more by replacing `IntegerQ` with `AtomQ`. Clever! (The result of `√` will be exact, so it returns a compound expression like `Sqrt[5]` if its argument isn’t a square.) [Answer] # Jelly, ~~8~~ 7 bytes 1 byte thanks to [@Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000). ``` DSƲðÐf ``` [Test suite.](http://jelly.tryitonline.net/#code=RFPDhsKyw7DDkGYKw4figqw&input=&args=W1sxLDQsOSwxNiwyNSwxMTExXSxbMTQzMSwyLDAsMjIsOTk5OTk5OTk5XSxbMjIyMjgsNCwxMTMxMjUsMjIzNDVdLFtdLFs0MjEzMzcsOTksMTIzNDU2Nzg5LDExMzM1NTc3OTldXQ) ### Explanation ``` DSƲðÐf Main monadic chain. Argument: z Ðf Filter for truthiness: D convert to base 10 S sum Ʋ is perfect square ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) v2, 8 bytes ``` {ẹ+√ℤ&}ˢ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/rhrp3ajzpmPWpZolZ7etH//9GGZjqGpjqGJjqGxjqGRjqGhjqGBjqWOhY65jpmOqY6JjrGOkBRHQMgNgKyTYBiZkA5Cx3L2P9RAA "Brachylog – Try It Online") ## Explanation ``` {ẹ+√ℤ&}ˢ { }ˢ Map the following operation over {the input}, discarding elements that error: ẹ Split into a list of digits + Sum that list √ Take its square root ℤ Assert that the result is an integer & Return to the original value ``` The `&` means that the elements output are the same as those in the input list, but the `ℤ` will error out if the block's input isn't a square number, so we get the input list with elements with non-square digit sums discarded. Note that there might at first seem to be a floating point inaccuracy issue here (some very large non-square integers have integer square roots due to rounding). However, Brachylog supports bignum arithmetic, and actually has this behaviour factored into its implementation of `√`: a number which is a perfect square will have its square root reported as an integer, whereas a number which is not a perfect square (but close enough that its square root is integral) will have its square root reported as a float with an integral value. Conveniently, `ℤ` only permits the former sort of return value, giving an assertion failure for the latter. [Answer] # Pyth, 10 bytes ``` fsI@sjT;2Q ``` [Test suite.](http://pyth.herokuapp.com/?code=fsI%40sjT%3B2Q&test_suite=1&test_suite_input=%5B1%2C4%2C9%2C16%2C25%2C1111%5D%0A%5B1431%2C2%2C0%2C22%2C999999999%5D%0A%5B22228%2C4%2C113125%2C22345%5D%0A%5B%5D%0A%5B421337%2C99%2C123456789%2C1133557799%5D&debug=0) ### Explanation ``` fsI@sjT;2Q f Q Filter for the following in Q(input): jT; convert to base 10 s sum @ 2 square-root sI is integer (is invariant under flooring) ``` [Answer] # CJam, 14 bytes Thanks to @FryAmTheEggman for saving one byte! ``` {{Ab:+mq_i=},} ``` [Try it online!](http://cjam.tryitonline.net/#code=WzIyMjI4IDQgMTEzMTI1IDIyMzQ1XQoKe3tBYjorbXFfaT19LH0KCn5w&input=) This is an unnamed block that expects the input list on the stack and leaves the filtered list on it. ## Explanation ``` { e# start a new block Ab e# convert to base 10 -> split number into digits :+ e# sum th digits mq e# get the square root _ e# duplicate the result i e# convert to integer = e# check if the converted square root and the original one are equal } e# end block , e# filter the input list ``` [Answer] # Haskell - 70 60 59 bytes ``` f=filter(\x->elem(sum.map(read.pure).show$x)$map(^2)[0..x]) ``` Usage: ``` > f [0..100] [0,1,4,9,10,13,18,22,27,31,36,40,45,54,63,72,79,81,88,90,97,100] ``` Quite straightforward; computes the sum of digits and checks if floor(sqrt(y))^2 == y Edit: Stole the idea of checking list of squares from C. Quilley [Answer] ## 05AB1E, ~~19~~ 10 bytes ``` vySOtDï->— ``` **Explanation** ``` vy # for each int in list SO # digit sum tDï- # difference between sqrt() and int(sqrt()) > # increase by 1 giving 1 (true) when equal — # print current int in list if truthy ``` [Try it online](http://05ab1e.tryitonline.net/#code=dnlTT3REw68tPuKAlA&input=WzIyMjI4LCA0LCAxMTMxMjUsIDIyMzQ1XQ) Edit: Saved 9 bytes thanks to @Adnan [Answer] # [R](https://www.r-project.org/), ~~57~~ 55 bytes Use `Filter` on the vector. Assumes 32 bit integers so 10 digits max. Corner cases: returns `NULL` for the empty vector and `numeric(0)` for a vector with no valid numbers. These both have length zero so should be acceptable. -2 thanks to @Giuseppe ``` Filter(function(n)!sum(n%/%10^(0:10)%%10)^.5%%1,scan()) ``` [Try it online!](https://tio.run/##VU5bS8MwFH7vrzgixRw41VzadRP10afhm0@yQRfTrdil0qYwEH97TVI39HtJ@K6nn@qHrB6tdk1n2Qm/kkFX9vHC4Gl6blpnenahLF4N45HZ9C4VfMv4veCY@i9ubwv/UihgiNN3ktRMM0E5rUgsSBYkPBCvIXuCt1/eYzP7ciVIEicpaXWGN0dv0P4rc0h6LH2REEr4filVXiBCDJ21SAY79wIMh25s32FngMeG4AaGBHvj4OV1vY5sLoVSpV8jEdKLchlOVaooyjJcNS9s5pQdj6ZvtO8naJsPE2ugcTcDtMbu3SHjMHR/liutzaerdq2ZfgA "R – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~64~~ 54 bytes ``` $args|?{!([math]::Sqrt(([char[]]"$_"-join'+'|iex))%1)} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyWxKL24xr5aUSM6N7EkI9bKKriwqERDIzo5I7EoOjZWSSVeSTcrPzNPXVu9JjO1QlNT1VCz9v///4b/Tf5b/jc0@29k@t8QCAA "PowerShell – Try It Online") *-10 bytes thanks to mazzy* Takes input as command-line arguments (see examples below), which gets processed in PowerShell into the array `$args`. We pipe that to `?` an alias for `Where-Object` (functions similar to `filter`) in order to select our output. Our selection is based on the .NET call `[math]::Sqrt()` of the [digit-sum](https://codegolf.stackexchange.com/a/81071/42963) of the number is an integer with `!(...%1)`. Integers will result in 0, which when `not`ed becomes `True` while non-integer roots become `False`. As mentioned [elsewhere](https://codegolf.stackexchange.com/a/82562/42963) "returning" an empty array is meaningless, as it's converted to `$null` as soon as it leaves scope, so the output for an empty input is nothing. ### Examples ``` PS C:\Tools\Scripts\golfing> .\return-integers-with-square-digit-sums.ps1 1 4 9 16 25 1111 1 4 9 1111 PS C:\Tools\Scripts\golfing> .\return-integers-with-square-digit-sums.ps1 1431 2 0 22 999999999 1431 0 22 999999999 PS C:\Tools\Scripts\golfing> .\return-integers-with-square-digit-sums.ps1 22228 4 113125 22345 22228 4 22345 PS C:\Tools\Scripts\golfing> .\return-integers-with-square-digit-sums.ps1 PS C:\Tools\Scripts\golfing> .\return-integers-with-square-digit-sums.ps1 1337 4444 4444 ``` [Answer] # Python 2, 76 bytes ``` lambda l:filter(lambda n:eval(("sum(map(int,`n`))**.5==int("*2)[:-6]+")"),l) ``` [Try it here!](https://repl.it/C09S) Some abuse of eval to check for a square number, rest is pretty unspectacular. The eval statement evaluates to `sum(map(int,`n`))**.5==int(sum(map(int,`n`))**.5)` [Answer] # Oracle SQL 11.2, 213 bytes ``` WITH v AS(SELECT a,SQRT(XMLQUERY(REGEXP_REPLACE(a,'(\d)','+\1')RETURNING CONTENT).GETNUMBERVAL())s FROM(SELECT TRIM(COLUMN_VALUE)a FROM XMLTABLE(('"'||REPLACE(:1,',','","')||'"'))))SELECT a FROM v WHERE s=CEIL(s); ``` Un-golfed ``` WITH v AS ( SELECT a,SQRT(XMLQUERY( REGEXP_REPLACE(a,'(\d)','+\1') -- Add a + in front of each digit RETURNING CONTENT ).GETNUMBERVAL())s -- Evaluate the expression generated by the added + FROM (SELECT TRIM(COLUMN_VALUE)a FROM XMLTABLE(('"'||REPLACE(:1,',','","')||'"'))) -- Split string on ',' ) SELECT a FROM v WHERE s=CEIL(s) -- Is a square if square has no decimal part ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 26 bytes ``` :1f. e.(:ef+~^[X:2]h>0;.0) ``` Example: ``` ?- run_from_file('code.brachylog',[1431:2:0:22:999999999],Z). Z = [1431, 0, 22, 999999999] ``` ### Explanation This is a situation where something works a bit too well... the `~^[X:2]` part is true for both positive and negative `X`, so to avoid duplicates I have to specify that `X > 0`. The `;.0` part is here due to a bug (enumerate doesn't work on the integer 0). * Main predicate ``` :1f. Find all values of Input which satisfy predicate 1 ``` * Predicate 1 ``` e. Unify output with an element of the input ( :ef Find all elements of Output (i.e. all digits) + Sum the digits ~^[X:2] True if that sum is the result of X², whatever X is h>0 Impose that X > 0 ; OR .0 True if Output is 0 ) ``` [Answer] # Python 2, 53 bytes ``` lambda x:[n for n in x if sum(map(int,`n`))**.5%1==0] ``` Test it on [Ideone](http://ideone.com/ljN78A). [Answer] # J, ~~33~~ 27 bytes 6 bytes thanks to [@miles](https://codegolf.stackexchange.com/users/6710/miles). ``` #~[:(=<.)@%:+/"1@(10&#.inv) ``` In online interpreters, `inv` is not instored. Change that to `^:_1` instead. ### Usage ``` >> f =: #~[:(=<.)@%:+/"1@(10&#.inv) >> f 1 4 9 16 25 1111 0 << 1 4 9 1111 0 ``` Where `>>` is STDIN and `<<` is STDOUT. ### Slightly ungolfed ``` to_base_10 =: 10&#.^:_1 sum =: +/"1 sqrt =: %: floor =: <. itself =: ] equals =: = of =: @ is_integer =: equals floor test =: is_integer of sqrt copies_of =: # f =: copies_of~ [: test (sum of to_base_10) ``` ## Previous 33-byte version ``` (]=*:@<.@%:)@(+/"1@(10#.^:_1]))#] ``` ### Usage ``` >> f =: (]=*:@<.@%:)@(+/"1@(10#.^:_1]))#] >> f 1 4 9 16 25 1111 0 << 1 4 9 1111 0 ``` Where `>>` is STDIN and `<<` is STDOUT. ### Slightly ungolfed ``` to_base_10 =: 10#.^:_1] sum =: +/"1 sqrt =: %: floor =: <. square =: *: itself =: ] equals =: = of =: @ test =: itself equals square of floor of sqrt copies_of =: # f =: (test of (sum of to_base_10)) copies_of itself ``` [Answer] # Javascript 66 bytes ``` a=>a.filter(b=>(e=Math.sqrt((b+"").split``.reduce((c,d)=>c-+-d)))==(e|0)) ``` Thanks for SergioFC for saving 7 bytes [Answer] # Perl 5, 42 bytes 41, plus 1 for `-pe` instead of `-e` ``` my$s;map$s+=$_,/./g;$_ x=sqrt$s==~~sqrt$s ``` Explanation: * `-p` gets each input integer on a new line and assigns `$_` to that string. * `my$s` initializes the variable `$s` to nothing, anew for each input integer. * `map$s+=$_,/./g` grabs each numeric character and numerically adds it to `$s`. (The newline becomes 0 when numified.) * `sqrt$s==~~sqrt$s` tests whether `$s` has a nonintegral square root, and `$_ x=` makes `$_` into itself or the empty string depending on that test. * `-p` prints `$_` Thanks to [Brad Gilbert b2gills](/users/1147/brad-gilbert-b2gills) for saving three bytes. Also 41 plus 1: ``` my$s;s/./$s+=$&/ger;$_ x=sqrt$s==~~sqrt$s ``` * `s/./$s+=$&/ger` adds each numeric character to `$s` (and the newline is 0 as above) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 48 bytes ``` a=>a.filter(b=>eval([...b+""].join`+`)**.5%1==0) ``` [Try it online!](https://tio.run/##NclBCoMwEEDRqwShkOhkbEoVuphcRARHm5RISIqK10/bRf/y/ZVP3pctvA@d8tMVT4XJMvoQD7fJmaw7OcoBEeemqkZcc0hTM6m6xu5iiK6qLDntOTqM@SW9HAzc4QGmh1sH5tuolGhbobUV//fT8gE "JavaScript (Node.js) – Try It Online") # Explanation ``` a => // lambda function taking one argument a.filter( // filter the list eval( // begin eval [...b+""] // convert number to array of digits .join`+` // join them with + sign ) // close eval. we achieved sum of all digits of number **.5 // square root of number %1==0 // check for perfect square ) // end filter and return value ``` [Answer] # MATL, ~~16~~ ~~14~~ 13 bytes ``` "@tV!UsX^1\?x ``` [**Try it Online!**](http://matl.tryitonline.net/#code=IkB0ViFVc1heMVw_eA&input=WzIyMjI4LDQsMTEzMTI1LDIyMzQ1XQ) **Explanation** ``` % Implicitly grab input " % For each number in the input @t % Get this element and duplicate V % Convert to it's string representation ! % Transpose the string so each digit is on it's own row U % Convert each row to a number (separates the digits) s % Compute the sum of the digits X^ % Compute the square root 1\ % mod with 1 to determine if the square root is an integer ?x % If there is a remainder, then remove this element from the stack % Implicitly display the stack contents ``` [Answer] # Julia - 38 bytes ``` !X=filter(i->√sum(digits(i))%1==0,X) ``` It's pretty easy to see what this does. `digits` converts a number into a list of its digits, `sum` thus calculates the digit-sum, `√` will then produce a whole number if the number is a square, otherwise there will be a fractional part. `%1` will return only the fractional part, and if it's zero (`==0`), `filter` will keep it on the list, otherwise it gets filtered out. Used as `![22228,4,113125,22345]` [Answer] # Jolf, 8 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=z4h4ZCFpVXVI&input=WzEsIDQsIDksIDExMTEsIDE2LCAyNV0) ``` ψxd!iUuH ``` ## Explanation ``` ψxd!iUuH ψxd filter the input according to the input uH digit sum of H (element) U sqrt of !i is an integer? ``` [Answer] # MATLAB, ~~52~~ ~~43~~ 42 bytes ``` @(x)x(~mod(sum(dec2base(x,10)'-48).^.5,1)) ``` Creates an anonymous function named `ans` that can be called with an array as input: `ans([22228,4,113125,22345])`. [**Online Demo**](http://ideone.com/Dde5kh). The online demo is in Octave which doesn't work for the empty input, but MATLAB does. **Explanation** We convert each element in the input array to base 10 which will yield a 2D character array where each row contains the digits of a number in the array. To convert these characters to numbers, we subtract 48 (ASCII for `'0'`). We then sum across the rows, take the square root, and determine whether each value is a perfect square `~mod 1`. We then use this boolean to filter the input array. [Answer] # Clojure, 110 bytes ``` (fn[t](filter(fn[x](let[a(reduce +(*(count(str x))-48)(map int(str x)))](some #(=(* % %)a)(range(inc a)))))t)) ``` Calculates the sum of number digits and then filters out those for which there doesn't exist a number which squared is equal to the sum. You can see the result here – <https://ideone.com/ciKOje> [Answer] # [Perl 6](http://perl6.org), ~~38~~ 35 bytes ``` ~~{.grep: {($/=sqrt [+] .comb)==$/.Int}} {.grep: {($/=.comb.sum.sqrt)==$/.Int}}~~ {.grep: {($/=sqrt [+] .comb)==^$/}} {.grep: {($/=.comb.sum.sqrt)==^$/}} ``` ### Test: ``` #! /usr/bin/env perl6 use v6.c; use Test; my @tests = ( [1,4,9,16,25,1111] => [1,4,9,1111], [1431,2,0,22,999999999] => [1431,0,22,999999999], [22228,4,113125,22345] => [22228,4,22345], [] => [], [421337,99,123456789,1133557799] => [], ); plan +@tests; my &sq-digit-sum = {.grep: {($/=sqrt [+] .comb)==^$/}} for @tests -> $_ ( :key($input), :value($expected) ) { is sq-digit-sum($input), $expected, .gist } ``` ``` 1..5 ok 1 - [1 4 9 16 25 1111] => [1 4 9 1111] ok 2 - [1431 2 0 22 999999999] => [1431 0 22 999999999] ok 3 - [22228 4 113125 22345] => [22228 4 22345] ok 4 - [] => [] ok 5 - [421337 99 123456789 1133557799] => [] ``` [Answer] # C, 143 141 bytes * saved 2 bytes, @user6188402 ``` i;q(char*n){double m=0;while(*n)m+=*n++-48;m=sqrt(m)-(int)sqrt(m);return !m;}s(n,s)char**n;{i=-1;while(++i<s)if(q(n[i]))printf("%s\n",n[i]);} ``` **Ungolfed** [try online](http://ideone.com/H0W1qt) ``` int q(char*n) { double m=0; while(*n) // sum digits m+=*n++-48; // get the decimal part of its square root m=sqrt(m)-(int)sqrt(m); // true if decimal part is zero return !m; } // input is text, can be a file void s(char**n, int s) { int i=-1; while(++i<s) // for each number in input if(q(n[i])) // if is square printf("%s\n",n[i]); // output is terminal } ``` [Answer] # [Retina](https://github.com/mbuettner/retina/wiki/The-Language), 69 Because testing for perfect squares in retina. This can be [modified for generalised integer square root calculation](https://codegolf.stackexchange.com/questions/35182/integer-square-root-of-integer/82842#82842). ``` .+ $&a$& +`\b\d $*b \bb $&: +`(\bb+):(bb\1) $1 $2: G`(:a|0$) .*a ``` Input is a newline-separated list. [Try it online.](http://retina.tryitonline.net/#code=LisKJCZhJCYKK2BcYlxkCiQqYiAKIAoKXGJiCiQmOgorYChcYmIrKTooYmJcMSkKJDEgJDI6CkdgKDphfDAkKQouKmEK&input=MTQzMQoyCjAKMjIKOTk5OTk5OTk5) * Stage 1 - repeat the number on each line, and separate with `a` * Stage 2 - convert each digit before the `a` to unary expressed as `b`s, separated with spaces * Stage 3 - remove spaces - each unary now represents the digit sum * Stage 4 and 5 - Use the fact that perfect squares may be expressed 1 + 3 + 5 + 7 + ... . Split each unary up accordingly * Stage 6 - grep filter just the ones that exactly split into the above form * Stage 7 - discard all but the original number [Answer] # [Ruby](https://www.ruby-lang.org/), 39 bytes ``` ->a{a.reject{|x|x.digits.sum**0.5%1>0}} ``` [Try it online!](https://tio.run/##XY7NCoMwEITveQqh9CJrcPNj9FBfJORgrbYWCkUjWIzPbhNKWuiclvlmZ3ecz6@9P@1Z3awNHbt719rVLW6hl@E62IlO8yNNcyqPWOfbtmuiEQRUgAUwCehl4JBkdRL94PiQ4AgMcmAMqqhvMsA/RDTzKn0HIkdfzRgXMm5E9jGJjr4fBUPOlW8CDLBQZXiCcymV@p00xNCuaW@rs@6Z9NqabX8D "Ruby – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~19~~ ~~17~~ 13 bytes **Solution:** ``` (~1!%+/.:'$)# ``` [Try it online!](https://tio.run/##y9bNz/7/X6POUFFVW1/PSl1FU9nQxNhQwUjBQMHISMESBv7//w8A "K (oK) – Try It Online") **Explanation:** ``` (~1!%+/.:'$)# / the solution ( )# / apply function to list $ / convert to string .:' / value (.:) each (') +/ / sum % / square-root 1! / modulo 1 ~ / not ``` **Notes:** * -2 bytes with smarter way of identifying squares * -4 bytes thanks to ngn [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), ~~5~~ 4 bytes ``` gÅΣ° ``` [Try it online!](https://tio.run/##y00syUjPz0n7/z/9cOu5xYc2/P8fbahgomCpYGimYGSqYAgEsQA "MathGolf – Try It Online") ### Explanation: ``` gÅ Filter by the next two instructions Σ The digit sum ° Is a perfect square? ``` MathGolf is still in development, ~~so I assume implicit input is coming soon to shave off that first byte.~~ Yay! [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 5 bytes ``` 'f∑∆² ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%27f%E2%88%91%E2%88%86%C2%B2&inputs=%5B22228%2C4%2C113125%2C22345%5D&header=&footer=) ``` ' # Keep elements in input list f∑ # Whose sum of digits is ∆² # A perfect square ``` ]
[Question] [ Write a program or function that takes in three positive integers, W, H, and N. Print or return a W×H grid of `.`'s where every Nth `.` in normal English reading order is replaced with an `X`. For example, given W = 7, H = 3, N = 3, the grid is 7 characters wide and 3 high, and every third character reading from the top left is an `X`: ``` ..X..X. .X..X.. X..X..X ``` Similarly, if the input is W = 10, H = 4, N = 5, the output would be: ``` ....X....X ....X....X ....X....X ....X....X ``` ### Notes * "Normal English reading order" means going left to right on each line, from the top line to the bottom. * When N is 1 then all the `.`'s will become `X`'s. * You may use any two distinct [printable ASCII](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters in place of `.` and `X`. + If you use space () then trailing spaces are not required when the result would be visually the same. (Empty lines are still required.) + You may not using something else in place of the newlines that shape the grid. * The exact input format and order of W, H, and N is not super important. Things like `[H,W,N]` or `N\nW,H` are alright. * A trailing newline in the output is fine. * The shortest code in bytes wins! # Examples ``` W = 5, H = 3, N = 1 XXXXX XXXXX XXXXX W = 5, H = 3, N = 2 .X.X. X.X.X .X.X. W = 5, H = 3, N = 3 ..X.. X..X. .X..X W = 5, H = 3, N = 4 ...X. ..X.. .X... W = 5, H = 3, N = 5 ....X ....X ....X W = 5, H = 3, N = 6 ..... X.... .X... W = 5, H = 3, N = 7 ..... .X... ...X. W = 5, H = 3, N = 15 ..... ..... ....X W = 5, H = 3, N = 16 (or more) ..... ..... ..... W = 1, H = 1, N = 1 X W = 1, H = 1, N = 2 (or more) . W = 8, H = 6, N = 2 .X.X.X.X .X.X.X.X .X.X.X.X .X.X.X.X .X.X.X.X .X.X.X.X W = 8, H = 6, N = 3 ..X..X.. X..X..X. .X..X..X ..X..X.. X..X..X. .X..X..X W = 8, H = 6, N = 4 ...X...X ...X...X ...X...X ...X...X ...X...X ...X...X W = 8, H = 6, N = 7 ......X. .....X.. ....X... ...X.... ..X..... .X...... W = 8, H = 6, N = 16 ........ .......X ........ .......X ........ .......X W = 37, H = 1, N = 4 ...X...X...X...X...X...X...X...X...X. W = 1, H = 10, N = 8 . . . . . . . X . . ``` [Answer] # J, ~~9~~ 5 bytes ``` $":&1 ``` Uses spaces and `1`'s and expects input in the form `H W f N` Explanation: ``` $":&1 &1 bonds the fixed right argument 1 to ": ": formats the right argument number (1) to take up left argument (N) number of cells padding with spaces, resulting in " 1" $ reshape to H-by-W with repeating the string if necessary ``` Usage: ``` 3 7 ($":&1) 3 1 1 1 1 1 1 1 ``` [Try it online here.](http://tryj.tk/) [Answer] # Python 2, 60 bytes ``` w,h,n=input() s='%%%dd'%n%0*w*h exec"print s[:w];s=s[w:];"*h ``` This prints space and `0` in place of `.` and `X`. Input is taken as a tuple in the form of `w,h,n`. [Answer] ## J, 12 bytes ``` $'X'_1}#&'.' ``` This is a dyadic function that takes the array `H W` as its left argument and `N` as its right argument. Usage: ``` f =: $'X'_1}#&'.' 3 5 f 3 ..X.. X..X. .X..X ``` ### Explanation ``` $'X'_1}#&'.' '.' The character '.' #& repeated N times _1} with the last character 'X' replaced by 'X' $ reshaped into an HxW array ``` [Answer] # BBC Basic, 67 ASCII characters, tokenised filesize 43 bytes Download interpreter at <http://www.bbcbasic.co.uk/bbcwin/download.html> ``` INPUTw,h,n:WIDTHw:PRINTLEFT$(STRING$(w*h,STRING$(n-1,".")+"X"),w*h) ``` BBC basic has a handy command for limiting the field width. We use `STRING$` to make `w*h` copies of the string of `n-1` periods followed by an X. Then we use LEFT$ to truncate this to `w*h` characters. [Answer] ## [Minkolang 0.14](https://github.com/elendiastarman/Minkolang), ~~34~~ ~~30~~ ~~28~~ 22 bytes ``` n2-D1n$zn[z[1Rd6ZO]lO] ``` [Check one case here](http://play.starmaninnovations.com/minkolang/?code=n2-D1n%24zn%5Bz%5B1Rd6ZO%5DlO%5D&input=3%205%203) and [check all test cases here.](http://play.starmaninnovations.com/minkolang/?code=%28ndN2-D1ndN%24zndNlO%5Bz%5B1Rd6ZO%5DlO%5DlOlOIX%24I%29%2E&input=1%205%203%0A2%205%203%0A3%205%203%0A4%205%203%0A5%205%203%0A6%205%203%0A7%205%203%0A15%205%203%0A16%205%203%0A1%201%201%0A2%201%201%0A2%208%206%0A3%208%206%0A4%208%206%0A7%208%206%0A16%208%206) Expects input like `N W H`. ### Explanation ``` n Take number from input (N) 2- Subtract 2 D Duplicate the top of stack (which is 0 because it's empty) N-2 times 1 Push a 1 onto the stack n Take number from input (W) $z Store W in the register (z) n Take number from input (H) [ Open a for loop that repeats H times z[ Open a for loop that repeats W times 1R Rotate 1 step to the right d Duplicate top of stack 6Z Convert number to string O Output as character ] Close for loop lO Output a newline ] Close for loop ``` As Minkolang's codebox is toroidal, this will wrap around to the beginning. As every `n` will now take in `-1`, this eventually crashes with an error and no further output, which is allowed. [Answer] ## CJam (16 bytes) ``` {1$*,:)@f%:!/N*} ``` Takes input on the stack in the order `N W H`, returns string using characters `0` and `1`. [Online demo](http://cjam.aditsu.net/#code=3%207%203%0A%0A%7B1%24*%2C%3A)%40f%25%3A!%2FN*%7D%0A%0A~) ### Dissection ``` { e# Anonymous function. Stack: N W H 1$*, e# Stack: N W [0 1 ... W*H-1] :) e# Stack: N W [1 2 ... W*H] @f% e# Stack: W [1%N 2%N ... W*H%N] :! e# Map Boolean not, taking 0 to 1 and anything else to 0 / e# Split into W-sized chunks (i.e. the lines of the grid) N* e# Join the lines with newlines } ``` [Answer] ## APL, 13 bytes ``` {‚ç™,/‚çאַ‚ç∫‚祂çµ=‚ç≥‚çµ} ``` This takes `H W` as the left argument and `N` as the right argument. Explanation: ``` {‚ç™,/‚çאַ‚ç∫‚祂çµ=‚ç≥‚çµ} Dyadic function (args are ‚ç∫ on left, ‚çµ on right): ‚çµ=‚ç≥‚çµ ‚çµ = (1 2 3...‚çµ); this is ‚çµ-1 0s followed by a 1 ‚ç∫‚ç¥ Shape by the left argument; e.g. 5 3 gives a 5x3 array ‚çאַ Stringify each entry ,/ Join the strings in each row ‚ç™ Make column vector of strings ``` Try it online: [first test cases](http://tryapl.org/?a=%7B%u236A%2C/%u2355%A8%u237A%u2374%u2375%3D%u2373%u2375%7D/%A8%20%28%28%u2282%u22823%205%29%2C%A8%28%u23737%29%2C15%2C16%29%2C%28%28%u2282%u22826%208%29%2C%A82%203%204%207%29&run), [last test case](http://tryapl.org/?a=1%2037%7B%u236A%2C/%u2355%A8%u237A%u2374%u2375%3D%u2373%u2375%7D4&run). Note that although this shows boxed output, my copy of Dyalog doesn't. [Answer] # CJam, 20 Bytes ``` q~:Z;_@*,:){Z%!}%/N* ``` Takes input as H W N. [Answer] # K, ~~21~~ ~~19~~ ~~18~~ 14 bytes Takes arguments as `(H W;N)`: ``` {".X"x#y=1+!y} ``` In action: ``` f:{".X"x#y=1+!y}; f.'((3 5;1);(3 5;2);(3 7;3);(4 10;5);(3 5;16)) (("XXXXX" "XXXXX" "XXXXX") (".X.X." "X.X.X" ".X.X.") ("..X..X." ".X..X.." "X..X..X") ("....X....X" "....X....X" "....X....X" "....X....X") ("....." "....." ".....")) ``` [Answer] # MATLAB, ~~61 55~~ 54 bytes ``` function c=g(d,n);b=ones(d);b(n:n:end)=0;c=[b'+45,'']; ``` Wow, I thought MATLAB would be competitive in this one, but how wrong I was! The function creates an array of 1's of the correct dimensions, and then sets every n'th element to be 0 (MATLAB implicitly handles wrapping around the indices into 2D). We then add on 45 ('-') to this number and converted to a char array to be returned. The questions allows any distinct two ASCII characters to be used for the grid, I am using '-' in place of 'x' to save some bytes. The input format is also not fixed, so it should be supplied as `[w h],n` - i.e. an array of width and height, and then n as a second parameter. --- This also works with **Octave** and can be tried online [here](http://octave-online.net/?s=QHPazBNGkfyhbhbdFrYAnJeGZmDvKMKYapOgHyikJRbmUTQP). The function is already set up in the linked workspace, so you can simply call for example: ``` g([4,5],3) ``` Which outputs: ``` ..-. .-.. -..- ..-. .-.. ``` [Answer] ## Processing, 93 bytes (Java, 104 bytes) ``` void f(int a,int b,int c){for(int i=0;i<a*b;i++)print((i%c>c-2?"X":".")+(i%a>a-2?"\n":""));}} ``` The reason I used Processing instead of Java is that you don't need to acces the pointer by tiping `System.out` because a local variable is directly accessible. I earned 11 bytes with this. The function doesn't return the result but prints it. [Answer] # [Japt](https://github.com/ETHproductions/Japt), ~~33~~ ~~32~~ ~~27~~ 25 bytes ``` SpW-1 +Q p-~U*V/W f'.pU)¬∑ ``` Takes input in format `W H N`. Uses `¬†` and `"` in place of `.` and `X`, respectively. [Try it online!](https://codegolf.stackexchange.com/a/62685/42545) ### Ungolfed and explanation ``` SpW-1 +Q p-~U*V/W f'.pU)¬∑qR // Implicit: U = width, V = height, W = interval SpW-1 +Q // Create a string of W - 1 spaces, plus a quotation mark. p-~U*V/W // Repeat this string ceil(U*V/W) times. f'.pU) // Split the resulting string into groups of U characters. qR // Join with newlines. // Implicit: output last expression ``` Suggestions welcome! [Answer] # [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), ~~25~~ ~~23~~ ~~22~~ ~~21~~ 19 Bytes Thanks to @Sp3000 for pointing out that I don't need a duplicate and saving me 2 bytes! Takes input as `N W H`. [Try it online!](http://vitsy.tryitonline.net/#code=MX1cMFhyVlxbVlxbe0ROXWFPXQ&input=&args=Mw+Nw+NA&debug=on) ``` 1}\0XrV\[V\[{DN]aO] 1 Push 1 to the stack. } Push the backmost to the front and subtract 2. \0X Duplicate the 0 temp variable times. r Reverse the stack. V Save as final global variable. \[ ] Repeat top item times. V\[ ] Repeat global variable times. {DO Duplicate, output, then shift over an item. aO Output a newline. ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 10 bytes ``` {y#|x$"X"} ``` [Try it online!](https://ngn.codeberg.page/k#eJyNkV1rgzAUhu/zK4LrhYUaa/0aht3valeDBUqhYtVKP+zUDaXbfvs8OanVTrZJyHvCefKeN5gE5+buo55oQvsk5Dk4T5bNVxEklNGar/Md19dJmO15zRteTFfALHWb29Sfcl2jVMDSuIYFVFgIbboC1OUOtebIyga0+P8O6GC1w1wwEPDBgIEitLhA7V2BKQTayTNCdgf1o17CK8i5QqqpYJmqe9UVuqbuFCGvD6lxP5z8WwibXI1vIWKSbVWdysA0o3wTp/k+YWUVRru4jrbhMY1ZlB/M17e4rLL8WJqea3n35ntcNEaZHU772EiLbGMcwmJXEvJCH6g/o4+t2DP6BEIYE7AICiMoAmFrjrSDtNvSsg3An6V0cAfjLCL/22AfwRaQRkAWAZayHsFUeNJ7wBjmEIaAhGW6MUw9brCPYJ5syaG/ufkKQ0AG+Aa9lbne) Takes input as two arguments; `N` as the first/left arg, and `(H;W)` as the second/right arg. Uses `" "` and `"X"` as the output characters. * `|x$"X"` right pad "X" to the desired length (fills with spaces), and reverse it (to put the "X" at the end) * `y#` reshape the above to the desired dimensions; the above gets repeated over and over until it is long enough [Answer] # Pyth - ~~19~~ ~~18~~ 17 bytes Hope to golf it more. Takes input as `N\n[W, H]`. ``` jc.[k+*dtvzN*FQhQ ``` [Test Suite](http://pyth.herokuapp.com/?code=jc.%5Bk%2B%2adtvzN%2aFQhQ&test_suite=1&test_suite_input=3%0A7%2C3%0A5%0A10%2C4%0A1%0A7%2C3&debug=0&input_size=2). [Answer] # R, 66 bytes ``` function(w,h,n){x=rep(".",a<-w*h);x[1:a%%n<1]="X";matrix(x,h,w,T)} ``` This is a function that accepts three integers and returns a matrix of character values. To call it, assign it to a variable. Ungolfed: ``` f <- function(w, h, n) { # Get the area of the square a <- w*h # Construct a vector of dots x <- rep(".", a) # Replace every nth entry with X x[1:a %% n == 0] <- "X" # Return a matrix constructed by row matrix(x, nrow = h, ncol = w, byrow = TRUE) } ``` [Answer] # JavaScript (ES6), ~~65~~ 60 bytes ``` (w,h,n)=>eval('for(i=r=``;i++<w*h;i%w?0:r+=`\n`)r+=i%n?0:1') ``` ## Explanation ``` (w,h,n)=>eval(' // use eval to remove need for return keyword for( i= // i = current grid index r=``; // r = result i++<w*h; // iterate for each index of the grid i%w?0:r+=`\n` // if we are at the end of a line, print a newline character // note: we need to escape the newline character inside the template ) // string because this is already inside a string for the eval r+=i%n?0:1 // add a 0 for . or 1 for X to the result // implicit: return r ') ``` ## Test ``` W = <input type="number" id="W" value="7" /><br /> H = <input type="number" id="H" value="3" /><br /> N = <input type="number" id="N" value="3" /><br /> <button onclick="result.innerHTML=( (w,h,n)=>eval('for(i=r=``;i++<w*h;i%w?0:r+=`\n`)r+=i%n?0:1') )(+W.value,+H.value,+N.value)">Go</button> <pre id="result"></pre> ``` [Answer] ## Mathematica, 85 bytes ``` ""<>(#<>" "&/@ReplacePart["."~Table~{t=# #2},List/@Range[#3,t,#3]->"X"]~Partition~#)& ``` As with many other solutions, this creates a single row, then partitions it. [Answer] # JavaScript (ES6), 55 bytes ``` (w,h,n)=>(f=i=>i++<w*h?+!(i%n)+(i%w?"":` `)+f(i):"")(0) ``` Uses the [IIFE](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression "Immediately-Invoked Function Expression") `f` to loop to save a return statement. Output for w=5, h=3, n=7: ``` 00000 01000 00010 ``` [Answer] **C#, 185 bytes** ``` using System;class x{void a(int w,int h,int n){int c=1;for(int i=0;i<h;i++){for(int j=1;j<=w;j++){if(c%n==0){Console.Write("x");}else{Console.Write(".");}c++;}Console.WriteLine();}}} ``` For a more readable Reading: ``` using System; class x { void a(int w, int h, int n) { int c = 1; for (int i = 0; i < h; i++) { for (int j = 1; j <= w; j++) { if (c % n == 0) { Console.Write("x"); } else { Console.Write("."); } c++; } Console.WriteLine(); } } } ``` Usage: ``` new x().a(7, 3, 3); ``` [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3) `jR`, 8 bytes ``` √ó∆õ?·∏ä]¬π·∫Ü‚Äú ``` input as `W,H,N` [Try it Online!](https://vyxal.github.io/latest.html#WyJqUiIsIiIsIsOXxps/4biKXcK54bqG4oCcIiwiIiwiM1xuN1xuMyIsIjMuNC4xIl0=) ``` √ó∆õ?·∏ä]¬π·∫Ü‚Äú¬≠‚Å°‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å°‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å™‚Äè‚ņ‚Å™‚Å™‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å°‚Å™‚Äè‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚Å¢‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚ŧ‚Å™‚Äè‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚Å£‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚ŧ‚Å™‚Äè‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚ŧ‚Äã‚Äé‚Äè‚Äã‚Å¢‚ņ‚Å°‚Äå¬≠ √ó∆õ ] # ‚Äé‚Å°Map over the range H x W ?·∏ä # ‚Äé‚Å¢Divisible by N? ¬π·∫Ü‚Äú # ‚Äé‚Å£Split into chunks of length W and join on nothing # ‚Äé‚ŧj flag joins on newlines üíé ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # Julia, 50 bytes ``` f(w,h,n)=reshape([i%n<1?"X":"." for i=1:w*h],w,h)' ``` This creates a function `f` that accepts three integers and returns a 2-dimensional array of strings. Ungolfed: ``` function f(w::Integer, h::Integer, n::Integer) # Construct an array of strings in reading order a = [i % n == 0 ? "X" : "." for i = 1:w*h] # Reshape this columnwise into a w√óh array r = reshape(a, w, h) # Return the transpose return transpose(r) end ``` [Answer] # Ruby, ~~67~~ 56 bytes ``` ->w,h,n{(1..h).map{(1..w).map{o,$.=$.%n<1?1:0,$.+=1;o}}} ``` Printing an array since it is accepted. **67 bytes** ``` ->w,h,n{i=1;puts (1..h).map{(1..w).map{o,i=i%n<1?1:0,i+=1;o}.join}} ``` **Ungolfed:** ``` -> w, h, n { (1..h).map { (1..w).map { o, $. = $.%n < 1 ? 1 : 0, $.+ = 1 o } } } ``` Usage: ``` ->w,h,n{(1..h).map{(1..w).map{o,$.=$.%n<1?1:0,$.+=1;o}}}[8,6,7] => [[0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0]] ``` [Answer] ## MATLAB, 44 bytes Note: Very different approach than the one used by Tom Carpenter. ``` @(x,y)char(reshape(~mod(1:prod(x),y),x)'+46) ``` Defines an anonymous function that accepts inputs as `[W,H],N`. I approached this problem using not-the-modulo-of-*N* for an array 1:W\*H and then simply reshaping the solution to a two-dimensional array, which is then converted to a character array. Example output for `[5,3],7`: ``` ..... ./... .../. ``` [Answer] # Common Lisp, SBCL, 94 bytes ``` (lambda(a b c)(dotimes(i(* a b))(format t"~:[.~;X~]~@[~%~]"(=(mod(1+ i)c)0)(=(mod(1+ i)a)0)))) ``` ### Explanation ``` ~:[.~;X~] <-- takes argument - if argument is true write ., if false write X ~@[~%~] <-- takes argument - if argument is true write newline, if not treat argument as if it was not used ``` `(=(mod(1+ i)c)0)(=(mod(1+ i)a)0)` looks pretty silly (because it's so similiar but I don't know if it can be solved, saving bytes I use `(1+ i)` instead of `i` because `dotimes` starts from `i=0` and I want to start from `1`. It is also helpful because I can use `(* a b)` instead of `(1+(* a b))` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes input as `[W,H],N` and uses spaces instead of `.`s & `"`s instead of `X`s. ``` √ó√ÆQ√πV)√≤U√é ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=1%2b5R%2bVYp8lXO&footer=rrhxLiByUSdY&input=WzcgM10gMw) [Answer] # [Uiua](https://www.uiua.org), 17 bytes ``` ‚ÜØ‚áå‚äü‚äô‚äô(‚áå‚äÇ@X‚ÜØ:@.-1) ``` [Test pad](https://uiua.org/pad?src=0_8_0__RiDihpAg4oav4oeM4oqf4oqZ4oqZKOKHjOKKgkBY4oavOkAuLTEpCgpGIDcgMyAzCkYgMTAgNCA1CkYgNSA1IDEKRiA1IDUgMgo=) [Answer] # [Perl 5](https://www.perl.org/) `-a`, 44 bytes ``` print$_%$F[1]&&1,$/x!($_%"@F")for 1.."@F"*<> ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvRCVeVcUt2jBWTc1QR0W/QlEDKKDk4KakmZZfpGCopwdia9nY/f9vaKBgymXyL7@gJDM/r/i/rq@pnoGhwX/dRAA "Perl 5 ‚Äì Try It Online") Input format is: ``` W N H ``` Output uses `1` for the spacer and `0` for the character. [Answer] # Java, ~~185~~ 183 bytes Thanks Thomas Kwa, for saving me 2 bytes! ``` interface B{static void main(String[] a){int w = Byte.parseByte(a[0]);for(int i=0;i++<w*Byte.parseByte(a[1]);)System.out.print((i%Byte.parseByte(a[2])>0?".":"X")+(i%w<1?"\n":""));}} ``` Ungolfed (ish): ``` interface A { static void main(String[] a) { int w = Byte.parseByte(a[0]); for( int i = 0; i++ < w*Byte.parseByte(a[1]); ) System.out.print(( i%Byte.parseByte(a[2]) > 0 ? "." : "X" )+( i%w < 1 ? "\n" : "" )); } } ``` Usage: ``` $ java B 5 3 7 ..... .X... ...X. ``` Maybe java will win one day :P ]
[Question] [ Please excuse the punny title. This is a question is inspired by [A Curious Property of 82000](https://plus.google.com/101584889282878921052/posts/Fni6x2TTeaS). In it, the author points out that the number 82000 is binary in base 2, 3, 4, and 5. The post then poses the question "is there a number that is binary in bases 2, 3, 4, 5, and 6"? (For those curious, I've checked values up to 10^1,000,000 and so far the answer is no.) This got me thinking: given a number, what bases *is* it binary in? Our curious number, 82000, is actually binary in six bases: ``` Base 2 = 10100000001010000 Base 3 = 11011111001 Base 4 = 110001100 Base 5 = 10111000 Base 81999 = 11 Base 82000 = 10 ``` Not all numbers will have binary bases that are sequential. Consider the number 83521. It's binary in bases 2, 17, 289, 83520, and 83521. Your challenge is to determine and display which bases a number is binary in. # Rules * A number is considered "binary" in a given base if its representation in that base consists of only zeroes and ones. `110110` is a binary value, while `12345` is not, `A380F` is definitely not. * Your number will be provided on standard input. It will be an integer value between 2 and 2^32-1 inclusive and will be provided in base-10 format. * In ascending order, display each base greater than one that the number is binary in. Each base should be on its own line. If you include the binary value in that base (see the bonus scoring below), separate the base and the binary value with a space. Only output to standard out will be judged, standard error and other sources will be ignored. # Scoring Your score is your program's size in bytes. The lower the score, the better. **Bonus**: If your program also outputs the binary values in the found bases, multiply your score by 0.75 Your displayed binary value should have no extra punctuation, no extraneous zeroes, no decimal point, just zeroes and ones. # Examples Input: ``` 82000 ``` Output (receives bonus): ``` 2 10100000001010000 3 11011111001 4 110001100 5 10111000 81999 11 82000 10 ``` Input: ``` 1234321 ``` Output (no bonus): ``` 2 1111 1234320 1234321 ``` [Answer] # Pyth, ~~14~~ 13 ``` jbf!-jQTU2tSQ ``` Thanks to Jakube for pointing out the new `S` function. [Try it here.](https://pyth.herokuapp.com/?code=jbf!-jQTU2tSQ&input=82000&debug=0) The online version is too slow to do `1234321`. This simply converts the input to each base from 2 to itself and discards the results that contain values other than 0 and 1. ### Explanation: ``` : Q=eval(input) (implicit) jb : join on newlines the list... f! : filter away nonempty values (impliticly named T) -jQTU2 : sewtise difference of number converted to base and range(2) jQT : convert Q to base T U2 : range(2) tSQ : over the range [2 Q+1) ``` --- In addition, this is a (~~not well golfed~~ now well golfed, again thanks to Jakube) bonus version (20 \* .75 = 15): ``` VQI!-JjQK+2NU2pdKjkJ ``` [Try it here](https://pyth.herokuapp.com/?code=jbf!-jQTU2tSQ&input=82000&debug=0) [Answer] # Julia, ~~72~~ 70 bytes It's actually longer with the bonus, so no bonus here. ``` n=int(readline());for j=2:n all(i->i∈0:1,digits(n,j))&&println(j)end ``` This reads a line from STDIN, converts it to an integer, and prints the result. Despite being a brute force method, the input 1234321 took less than 1 second for me. Ungolfed + explanation: ``` # Read n from STDIN and convert to integer n = int(readline()) # For every potential base from 2 to n for j = 2:n # If all digits of n in base j are 0 or 1 if all(i -> i ∈ 0:1, digits(n, j)) # Print the base on its own line println(j) end end ``` Examples: ``` julia> n=int(readline());for j=2:n all(i->i∈0:1,digits(n,j))&&println(j)end 1234321 2 1111 1234320 1234321 julia> n=int(readline());for j=2:n all(i->i∈0:1,digits(n,j))&&println(j)end 82000 2 3 4 5 81999 82000 ``` **NOTE**: If input can be taken as a function argument rather than from STDIN (awaiting confirmation from the OP), the solution is 55 bytes. [Answer] # CJam, 20 bytes (or 27 bytes \* 0.75 = 20.25) Here is the no bonus version, 20 bytes: ``` ri:X,2f+{X\b2,-!},N* ``` [Try this here.](http://cjam.aditsu.net/#code=ri%3AX%2C2f%2B%7BX%5Cb2%2C-!%7D%2CN*&input=82000) Just for fun, here is the bonus version, 27 bytes: ``` ri:X{X\)b2,-!},1>{)SX2$bN}/ ``` [Try it online here](http://cjam.aditsu.net/#code=ri%3AX%7BX%5C)b2%2C-!%7D%2C1%3E%7B)SX2%24bN%7D%2F&input=8200) [Answer] # Mathematica, 59 bytes ``` Print/@Select[1+Range[n=Input[]],Max@IntegerDigits[n,#]<2&] ``` Ugh... `IntegerDigits` D: There isn't really much to explain about the code... 12 bytes are wasted by the requirement for using STDIN and STDOUT. I don't think I can claim the bonus. The best I've got is 84 bytes (which yields a score over 60): ``` Print@@@Select[{b=#+1," ",##&@@n~IntegerDigits~b}&/@Range[n=Input[]],Max@##3<2&@@#&] ``` [Answer] # Python 2, ~~88 86~~ 80 Fairly straightforward, no bonus. Python is nice and lenient with global variables. ``` N=input();g=lambda n:n<1or(n%b<2)*g(n/b) for b in range(2,N+1): if g(N):print b ``` Best I've managed to get for the bonus is 118\*.75 = **87.75**: ``` N=input();g=lambda n:0**n*" "or" "*(n%b<2)and(g(n/b)+`n%b`)*(g(n/b)>'') for b in range(2,N+1): if g(N):print`b`+g(N) ``` [Answer] # Python 2, 90 \* 0.75 = 67.5 ``` n=input();b=1 while b<n: b+=1;s="";c=k=n while k:s=`k%b`+s;c*=k%b<2;k/=b if c:print b,s ``` Pretty straightforward iterative approach. Without the bonus, this is 73 bytes: ``` n=input();b=1 while b<n: b+=1;c=k=n while k:c*=k%b<2;k/=b if c:print b ``` [Answer] # SQL (PostgreSQL), ~~247.5~~ ~~255~~ 230.25 (307 \* .75) Since SQL is known to be wonderful at these sorts of challenges, I thought I better put one together :) The bonus was really worthwhile for this one. It should comply with spec, but I have no easy way to test the [COPY I FROM STDIN](http://www.postgresql.org/docs/9.3/static/sql-copy.html). **Edit** Fixed order. Changed the way column R is handled to use an array. ``` CREATE TABLE IF NOT EXISTS I(I INT);TRUNCATE TABLE I;COPY I FROM STDIN;WITH RECURSIVE R AS(SELECT n,I/n I,ARRAY[I%n] R FROM generate_series(2,(SELECT I FROM I))g(n),(SELECT I FROM I)I(I)UNION ALL SELECT n,I/n,I%n||R FROM R WHERE I>0)SELECT n||' '||array_to_string(R,'')FROM R WHERE 2>ALL(R)and i=0ORDER BY n ``` As a test I just used straight inserts into the `I` table. Test run expanded and commented. ``` -- Create the table to accept the input from the copy command CREATE TABLE IF NOT EXISTS I(I INT); -- Make sure that it is empty TRUNCATE TABLE I; -- Popoulate it with a value from STDIN --COPY I FROM STDIN; INSERT INTO I VALUES(82000); -- Testing --Using a recursive CTE query WITH RECURSIVE R AS ( -- Recursive anchor SELECT n, -- base for the row I/n I, -- integer division ARRAY[I%n] R -- put mod value in an array FROM generate_series(2,(SELECT I FROM I))g(n), -- series for the bases (SELECT I FROM I)I(I) -- Cross joined with I, saves a few characters UNION ALL -- for each row from r recursively repeat the division and mod until i is 0 SELECT n, I/n, I%n||R -- Append mod to beginning of the array FROM R WHERE I>0 ) -- return from r where i=0 and r has 1's and 0's only SELECT n||' '||array_to_string(R,'') FROM R WHERE 2 > ALL(R)and i=0 ORDER BY n -- Ensure correct order ``` > > 2 10100000001010000 > > 3 11011111001 > > 4 110001100 > > 5 10111000 > > 81999 11 > > > > [Answer] # Haskell 109\*0.75 = 81.75 bytes ``` 0#x=[] n#x=n`mod`x:div n x#x f n=[show x++' ':(n#x>>=show)|x<-[2..n+1],all(<2)$n#x] p=interact$unlines.f.read ``` Usage example (note: binary values are lsb first): ``` p 82000 2 00001010000000101 3 10011111011 4 001100011 5 00011101 81999 11 82000 01 ``` Without input/output restrictions, i.e input via function argument, output in native format via REPL): ### Haskell, 67\*0.75 = 50.25 bytes ``` 0#x=[] n#x=n`mod`x:div n x#x f n=[(x,n#x)|x<-[2..n+1],all(<2)$n#x] ``` Returns a list of (base,value) pairs. The values are lsb first, e.g. (newlines/spaces added for better display): ``` f 82000 [ (2,[0,0,0,0,1,0,1,0,0,0,0,0,0,0,1,0,1]), (3,[1,0,0,1,1,1,1,1,0,1,1]), (4,[0,0,1,1,0,0,0,1,1]), (5,[0,0,0,1,1,1,0,1]), (81999,[1,1]), (82000,[0,1]) ] ``` [Answer] # R, 111 Probably a lot of room to improve this at the moment ``` i=scan();b=2:i;R=i%%b;I=rep(i,i-1);while(any(I<-I%/%b))R=cbind(I%%b,R);for(x in b)if(all(R[x-1,]<2))cat(x,'\n') ``` Runs with warnings ``` > i=scan();b=2:i;R=i%%b;I=rep(i,i-1);while(any(I<-I%/%b))R=cbind(I%%b,R);for(x in b)if(all(R[x-1,]<2))cat(x,'\n') 1: 82000 2: Read 1 item There were 17 warnings (use warnings() to see them) 2 3 4 5 81999 82000 > ``` [Answer] # Java, ~~181~~ ~~155.25(207 \* .75)~~ 151.5(202 \* .75) bytes ``` class I{public static void main(String[]a){a:for(long b=new java.util.Scanner(System.in).nextLong(),c,d=1;d++<b;){String e="";for(c=b;c>0;e=c%d+e,c/=d)if(c%d>1)continue a;System.out.println(d+" "+e);}}} ``` **Expanded with explanation:** ``` class I { public static void main(String[]a){ a:for(long b=new java.util.Scanner(System.in).nextLong(),c,d=1; //b = input(), d = base d++<b;) { //For all bases in range(2,b+1) String e=""; for(c = b;c > 0; e = c % d + e,c /= d) //Test all digits of base-d of b //e = c % d + e //Append digits to string if (c % d > 1) //Reject base if the digit is greater than 1 continue a; System.out.println(d+" "+e); //Print base and digits. } } } ``` **Original (without bonus):** ``` class I{public static void main(String[]a){long b=new java.util.Scanner(System.in).nextLong(),c,d=1;a:for(;d++<b;){c=b;while(c>0){if(c%d>1)continue a;c/=d;}System.out.println(d);}}} ``` 3.75 bytes thanks to Ypnypn :) [Answer] # R, ~~94~~ ~~83~~ 79 ``` n=scan();cat((2:n)[!sapply(2:n,function(x){while(n&n%%x<2)n=n%/%x;n})],sep="\n") ``` Usage: ``` > n=scan();cat((2:n)[!sapply(2:n,function(x){while(n&n%%x<2)n=n%/%x;n})],sep="\n") 1: 82000 2: Read 1 item 2 3 4 5 81999 82000 > n=scan();cat((2:n)[!sapply(2:n,function(x){while(n&n%%x<2)n=n%/%x;n})],sep="\n") 1: 1234321 2: Read 1 item 2 1111 1234320 1234321 ``` The core of the function is `!sapply(2:n,function(x){while(n&n%%x<2)n=n%/%x;n})` which, for each base x from 2 to n, keep the quotient n/x as long as the remainder is either 0 and 1. It then outputs the result (which is 0 if all remainders were either 1 or 0) and negates it (0 negates to TRUE, everything else negates to FALSE). Thanks to function scope, there is no need to make a dummy variable for n. The resulting vector of booleans is then used to index `2:n` and therefore outputs only the bases for which it worked. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ³bṀỊµÐfḊY ``` [Try it online!](https://tio.run/##AR8A4P9qZWxsef//wrNi4bmA4buKwrXDkGbhuIpZ////MTAw "Jelly – Try It Online") Done alongside [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) in [chat](https://chat.stackexchange.com/rooms/57815/jelly-hypertraining). ## How it works ``` ³bṀỊµÐfḊY Full program. Ðf Filter the implicitly generated range [1, input]. µ Starts a new monadic chain. ³b Convert the input to the base of the current number, as a list. Ṁ Maximum. Ị Insignificant. Checks if abs(Z) ≤ 1. Ḋ Dequeue; Removes the first element of the list (to drop base 1). Y Join by newlines. ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 28 bytes, 28 \* 0.75 = 21 ``` {{⍵⌿⍨∧/2>↑2⌷⍉⍵}(⍪,⊤∘⍵¨)1↓⍳⍵} ``` `1↓⍳⍵` all numbers from 2 to ⍵ `(⍪,⊤∘⍵¨)` each number with the representation of ⍵ in that base `{⍵⌿⍨∧/2>↑2⌷⍉⍵}` dfn to filter `↑2⌷⍉⍵` 2nd column as a matrix `2>` is 2 greater than? `∧/` boolean and `⍵⌿⍨` replicate [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/P@1R24Tq6ke9Wx/17H/Uu@JRx3J9I7tHbRONHvVsf9TbCZSo1XjUu0rnUdeSRx0zgNxDKzQNH7VNftS7GSQHNEDBwsjAwAAA "APL (Dyalog Extended) – Try It Online") [Answer] # TI-Basic, 45 bytes ``` Input N For(B,2,N If prod(seq(BfPart(iPart(N/B^X)/B),X,0,log(N)/log(B))<2 Disp B End ``` ## Explanation * Input N * For every B from 2 to N + If N is just 0 and 1 in base B - Display B * End loop ## The complicated part The second line works as follows: * For every X from 0 to logB N * B × fPart(iPart(N / BX) / B) is the Nth digit in base B, counting backwards * Consider this as a list * For each element, if the digit is less than 2, yield 1 (true), else 0 (false) * Take the product: 1 iff all elements are 1 ## Note The program runs significantly faster if a closing parenthesis `)` is placed at the end of the second line. [See here](http://tibasicdev.wikidot.com/for) for more about this. [Answer] # TI-BASIC, ~~31~~ 29 ``` For(B,2,Ans If 2>round(Bmax(fPart(Ans/B^randIntNoRep(1,32 Disp B End ``` This is probably optimal for TI-BASIC. Explanation: `randIntNoRep(1,32)` returns a random permutation of the numbers from 1 to 32 (All we need is those numbers in some order; TI-BASIC doesn't have anything like APL's iota command). 32 elements is enough because the smallest possible base is 2 and the largest number is 2^32-1. `B^randIntNoRep(1,31)` raises that list to the Bth power, which results in the list containing all of `B^1,B^2,...,B^32` (in some order). Then the input (in the `Ans`wer variable, which is input to in the form `[number]:[program name]`) is divided by that number. If your input is 42 and the base is 2, the result will be the list `21,10.5,5.25,...,42/32,42/64,[lots of numbers less than 1/2]`, again in some order. Taking the fractional part and multiplying the number by your base gives the digit at that position in the base-b representation. If all digits are less than 2, then the greatest digit will be less than 2. As Ypnypn stated, a closing parenthesis on the `For` statement speeds this up due to a parser bug. 31->31: Saved a byte but fixed rounding errors which added the byte again. 31->29: Saved two bytes by using `RandIntNoRep()` instead of `cumSum(binomcdf())`. [Answer] ## Javascript, ES6, ~~118\*.75 = 88.5~~ 110\*.75 = 82.5 ``` f=x=>{res={};for(b=2;b<=x;++b)if(!+(res[b]=(c=x=>x%b<2?x?c(x/b|0)+""+x%b:"":"*")(x)))delete res[b];return res} ``` Previous version: ``` f=x=>{res={};for(q=2;q<=x;++q)if(!+(res[q]=(c=(x,b)=>x%b<2?x?c(x/b|0,b)+""+x%b:"":"*")(x,q)))delete res[q];return res} ``` Check: ``` f(82000) Object { 2: "10100000001010000", 3: "11011111001", 4: "110001100", 5: "10111000", 81999: "11", 82000: "10" } ``` [Answer] # JavaScript (*ES6*) 65 68 bytes for a function with a parameter and console output. ``` f=n=>{s=n=>n%b>1||b<n&&s(n/b|0);for(b=1;b++<n;)s(n)||console.log(b)} ``` 65 bytes with I/O via popup ``` n=prompt(s=n=>n%b>1||b<n&&s(n/b|0));for(b=1;b++<n;)s(n)||alert(b) ``` Claiming the bonus: 88\*0.75 => 66 ``` n=prompt(s=n=>n%b>1?9:(b<=n?s(n/b|0):'')+n%b);for(b=1;b++<n;)s(n)<'9'&&alert(b+' '+s(n)) ``` [Answer] ## Mathematica, 76 \* 0.75 = 57 ``` n=Input[];G=#~IntegerDigits~b&;If[Max@G@n<2,Print[b," ",Row@G@n]]~Do~{b,2,n} ``` Initially forgot about the input requirements... Fortunately, those didn't add too much extra. [Answer] # [Ruby](https://www.ruby-lang.org/), 44 bytes ``` ->n{(2..n).select{|i|n.digits(i)-[0,1]==[]}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNITy9PU684NSc1uaS6JrMmTy8lMz2zpFgjU1M32kDHMNbWNjq2tvZ/UWphaWZRqoJSQYESF1dBgUJatIWRgYFBLJRtbGpkGPsfAA "Ruby – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 63 bytes ``` map{$t=$n;1while($f=$t%$_<2)&&($t=int$t/$_);say if$f}2..($n=<>) ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saBapcRWJc/asDwjMydVQyXNVqVEVSXexkhTTU0DKJWZV6JSoq8Sr2ldnFipkJmmklZrpKenoZJna2On@f@/hZGBgcG//IKSzPy84v@6vqZ6BoYGAA "Perl 5 – Try It Online") No bonus on this because it scores very slightly better than my version with the bonus: # [Perl 5](https://www.perl.org/), 85 bytes \* 0.75 = 63.75 ``` map{my$r;$t=$n;$r=$/.$r while($/=$t%$_)<2&&($t=int$t/$_);say"$_ 1$r"if$/<2}2..($n=<>) ``` [Try it online!](https://tio.run/##DcpBCoMwEAXQq4j8Slw00UBWSbxBzyAuLA1oDOOASPHqnbp9vDLT4kTWqXzXE@TBEdmDIowGVccnLbOCieAHxjbYplF3SZnB5ga/T2eNsepBdXrDBHtZrRVyDEMr4n5b4bTlXZ4vp7u@@wM "Perl 5 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~11~~ 10 bytes ``` ¶tfoΛε`B¹ḣ ``` [Try it online!](https://tio.run/##AR4A4f9odXNr///CtnRmb86bzrVgQsK54bij////ODIwMDA "Husk – Try It Online") -1 byte from Zgarb. ## Explanation ``` ¶tfoΛ<2`B¹ḣ ḣ list from 1..n f filter based on the result of the following o composition of 2 functions `B¹ the input in base n as digits Λ<2 are all digits < 2? t remove first element ¶ join with newlines ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` õ2 f@ìX e§1 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=9TIgZkDsWCBlpzE&input=ODM1MjE) ``` õ2 f@ìX e§1 :Implicit input of integer U õ2 :Range [2,U] f :Filter by @ :Passing each X through the following fuction ìX : Convert U to base X digit array e : All §1 : <=1 :Implicit output, joined with newlines ``` ]
[Question] [ What do you get when you cross Pascal's Triangle and the Fibonacci sequence? Well, that's what you have to find out! # Task Create a triangle that looks like this: ``` 1 1 1 2 2 2 3 5 5 3 5 10 14 10 5 8 20 32 32 20 8 ``` Basically, instead of each cell being the sum of the cells above it on the left and right, you also need to add the cell on the left above the cell on the left and the cell on the right above the cell on the right. This is [A036355](https://oeis.org/A036355). You may choose to do one of the following: * Output the \$n\$th row (indexed as you wish) * Output the first \$n\$ rows * Output all rows infinitely # Rules * Each row may be represented as a string separated by some character that is not a digit or an ordered collection of numbers. You do not need to align the triangle like I did in the example. * If you choose to output multiple rows, you need either an ordered list of rows, or a string that uses a different separator than the one you use within rows. * Please specify which task you chose in your answer, along with the input (if applicable) and output format. * You can receive input and output through any of the standard IO methods. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! ## Bounty As Scala is the [language of the month](https://codegolf.meta.stackexchange.com/questions/20585/language-of-the-month-for-january-2021-scala?cb=1), I will be giving a 50 rep bounty for any Scala answers to this question (not just if you're a first-time user). If multiple Scala answers are posted, I will be happy to put a bounty on a different Scala answer of yours instead. [Answer] # [Python 2](https://docs.python.org/2/), ~~73~~ ~~72~~ 69 bytes -1 byte thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)! -3 bytes thanks to [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus)! Prints the rows indefinitely. ``` c=a=[0] b=[1] while 1:print b;a,b=b,map(sum,zip(c*2+a,a+c*2,c+b,b+c)) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9k20TbaIJYryTbaMJarPCMzJ1XB0KqgKDOvRCHJOlEnyTZJJzexQKO4NFenKrNAI1nLSDtRJ1EbSOskayfpJGkna2r@/w8A "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~82~~ \$\cdots\$ 60 bytes ``` []%[1] u%v=v:v%foldl1(zipWith(+))[0:0:u,u++[0,0],0:v,v++[0]] ``` [Try it online!](https://tio.run/##FcexDoMgEADQvV/hUBINNDlWEr6jA72BWFHiaUmFG/x4r@nb3hKPdSKS5F8SUAWLt6bYs2OVPvQm25@5PHNdej0MARy4ZprWAQygAceG/0GULebdl2/e673GdeosdEmuMVGcD3mMpfwA "Haskell – Try It Online") *-10 thanks to @user* *-4 thanks to @ovs* Fairly new to Haskell, and never golfed in it before. Happy to be beaten! [Answer] # [J](http://jsoftware.com/), 30 bytes Returns the n'th row. ``` 0{((+|.)@(+/)@,.,:{~)&0&(1,:0) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Dao1NLRr9DQdNLT1NR109HSsqus01QzUNAx1rAw0/2typSZn5CukKRgZcIGZanYKNg5pSgYKmXqGBv8B "J – Try It Online") ### How it works * `f&0&(1,:0)` `(1,:0) f 0` will be executed `n` times * `(last two rows) g@,. (0)` append a 0 to each row and execute g, f.e. `g (2 2 2 0,: 1 1 0 0)` * `(+|.)@(+/)` sum the two rows `3 3 2 0` and add it to its reverse: `3 5 5 3` * `,:{~` append the previous row `3 5 5 3,:2 2 2 0` * `0{` after `n` iteration get the last row `3 5 5 3` [Answer] # [Scala](https://www.scala-lang.org/), ~~156..133~~ 120 bytes *-23 bytes thanks to [user](https://codegolf.stackexchange.com/users/95792/user)!* *-13 bytes thanks to [Command Master](https://codegolf.stackexchange.com/users/92727)!* ``` ()=>{var(a,b)=Seq(1,1)->Seq(1) while(1>0){println(b) val t=a a=Seq(0+:0+:b,b:+0:+0,a:+0,0+:a).transpose.map(_.sum) b=t}} ``` [Try it online!](https://tio.run/##PY7BCsIwEETv@Yo97tJa2mshAT/Ak3iWTQ0aSWNMYhVKvz3WHoTHMAzMMGlgx@Wh72bIcADzycZfEuxDgFkATOwgR8v@6kwPSCAVnLzNIAuSVPPEEbnWJI/miV3d0U5tjsT7Zp3BTrU0h2h9dh41iW1PsuCt0Fb9iq51X7UrNf9kTZiaHNmn8EimGTnguUmvkYSWeVkK/B8hiaV8AQ) Output is infinite. Explanation: ``` object M extends App { var (a, b) = Seq(1, 1) -> Seq(1) // init (a, b) := ([1, 1], [1]]) while (1 > 0) { // while true println(b) // print b val t = a // cache a in a local variable t a = Seq(0 +: 0 +: b, b :+ 0 :+ 0, a :+ 0, 0 +: a).transpose.map(_.sum) // calculate the new triangle row with // the help of the shifted lists a and b like in the example below b = t // set b the cached previous value of a } } ``` Example for n = 4: ``` 0 0 2 2 2 + 2 2 2 0 0 + 3 5 5 3 0 + 0 3 5 5 3 ----------------- = 5 10 14 10 5 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ ~~24~~ ~~19~~ ~~18~~ ~~13~~ 12 bytes -6 bytes thanks to @ovs -4 bytes thanks to @Neil, which allowed for additional -1 -2 bytes thanks to @Kevin Cruijssen ``` 1‚ηλ₂0š+0šÂ+ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f8FHDrHPbz@1@1NRkcHShNhAfbtL@/x8A "05AB1E – Try It Online") A port of the python answer, basically. Outputs the rows infinitly Explaination: ``` 1 push 1 ‚ pair. Since there is no input, it pairs 1 with 1, to get [1, 1] η prefixes, get [[1], [1, 1]] λ recursive environment ₂ push a(n-2) 0š prepend 0 to a(n-2) + sum with implicit a(n-1) 0š prepend a zero  Bifurcate - push a and reversed(a) + sum ``` [Answer] # [Haskell](https://www.haskell.org/), 81 bytes ``` q=zipWith(+) z=[0,0] f=[]:[1]:[q(a++z)$q(z++a)$q(b++[0])$0:b|(a,b)<-zip f$tail f] ``` [Try it online!](https://tio.run/##HYyxDoMgFEV3v@INDJBnE7p0MOU7HAjDI0p8kapYJtJ/p@hwc85wchf6rnOMtSZT@Bg5LxJVV4zVvXZdMNYN9tmWJCEWJZIsiHTRI1rtlNCD/0nqvXo/2gMEkYkjBFc/xJuZdjhO3jIIyLTO8LrlCuof "Haskell – Try It Online") Returns an infinite list of all rows, 1-indexed (hence the `tail` in TIO to dispose of element `0`). [Answer] # [Perl 5](https://www.perl.org/), 86 bytes ``` $,=$";@b=@c,@c=@,while say@,=map$,[$_]+($_>0)*$,[$_-1]+($_>1)*$b[$_-2]+$b[$_]||1,0..@, ``` [Try it online!](https://tio.run/##K0gtyjH9/19Fx1ZFydohydYhWcch2dZBpzwjMydVoTix0kHHNjexQEUnWiU@VltDJd7OQFMLzNM1hPANgfwkEN8oVhvMiK2pMdQx0NNz0Pn//19@QUlmfl7xf11fUz0DQwMA "Perl 5 – Try It Online") Output is infinite. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~54~~ 39 bytes ``` ≔⟦¹⟧ηFN«⊞υ⁰≔Eυ⁺κ§ηλι≔ηυ⊞ι⁰≔E⮌ι⁺κ§ιλη»Iη ``` [Try it online!](https://tio.run/##RY49C8IwEIZn@ytuvIMIVXDqVJwclIJjcYi1mkCalnyIIP72mFSjww3vc8fzXie46UauQqitlTeN7erEQFBVXEcDuNOTdwc/nHuDRPAsFvmsUd7ink@4ZlASAx9nZp7BD2fWlrP0mwSDCCgiGXuyUSTHPyZH7Xb60j9QfiqOfphxjHkzMFBEqSe9/CoaI7XDLbcOBVEVwiYs7@oN "Charcoal – Try It Online") Link is to verbose version of code. Outputs the 0-indexed nᵗʰ row. Explanation: Relies on the symmetry of the triangle. ``` ≔⟦¹⟧η ``` Start with the 0ᵗʰ row with just a `1` in it (using the predefined empty list for the "-1ᵗʰ" row). ``` FN« ``` Repeat `n` times. ``` ⊞υ⁰ ``` Append a `0` to the previous row. ``` ≔Eυ⁺κ§ηλι ``` Sum the previous and current row to a temporary variable. ``` ≔ηυ ``` Copy the current row to the previous row. ``` ⊞ι⁰ ``` Append a `0` to the new row. ``` ≔E⮌ι⁺κ§ιλη ``` Add the new row to its reverse and save that as the current row. ``` »Iη ``` Print the final row. Previous 54-byte version worked by creating the matrix formed by rotating the triangle anticlockwise by 45°: ``` Nθ⊞υEθ⁼ι¹⊞υ⟦⁰⟧Fθ«≔⟦⁰⟧ηF⁻θι⊞ηΣ⁺…⮌η²E…⮌υ²§λ⊕κ⊞υη»I✂Eυ⊟ι² ``` [Try it online!](https://tio.run/##ZY49a8MwEIbn@FfceAIFmgxdOgWTwUOKScbQQVUukYgs2/oICaW/XT27LRR6270P74c2KuheuVIaP@T0mrt3CjiKl6rN0WCWsFMDjhK2Y1YuopWwEuIPPj698XfuA7ALPqrFJkZ78ci6BMNoMbOd9TlOOVYImL1GwiF32DrW64d2VJt@wD3dKERCIySsxXf7f5p/6CY1/kR3dBIarwN15BOd8Crm4@7fldOQz6oN1iesVUx4cFYTTulMW47mXVMmu0p5Lsub@wI "Charcoal – Try It Online") Link is to verbose version of code. Outputs the 1-indexed nᵗʰ row. Explanation: ``` Nθ ``` Input `n`. ``` ⊞υEθ⁼ι¹ ``` Create a fictitious "-1ᵗʰ" row with a single `1` in the first column. This seeds the first row later. ``` ⊞υ⟦⁰⟧ ``` Create a "0ᵗʰ" row of zeros. (Because Charcoal uses cyclic indexing, I only need one zero.) ``` Fθ« ``` Loop over the desired output rows. ``` ≔⟦⁰⟧η ``` Start with a "0ᵗʰ" column of just a zero. ``` F⁻θι ``` Loop over the additional numbers needed to complete this row of the rotated triangle. ``` ⊞ηΣ⁺…⮌η²E…⮌υ²§λ⊕κ ``` Get the latest two numbers for this row plus the two numbers in the columns above and push the sum to the current row. ``` ⊞υη ``` Push the completed row to the triangle. ``` »I✂Eυ⊟ι² ``` Print the last number in each row, excluding the two initial dummy rows. [Answer] # AWK, ~~117~~ 111 bytes Prints the first `n` rows of the triangle, unformatted. Edit: Let `l` and `c` be two integers. `l c` concatenates their values as a string. For example: in the first element, `0 0` evaluates `"00"` (str). `00` would evaluate `0` (int). ``` {print a[0 0]=1;for(;++l<$1;)for(c=0;c<=l;c++)printf a[l c]=a[l-1 c-1]+a[l-1 c]+a[l-2 c-2]+a[l-2 c](c~l?RS:FS)} ``` Step by step: ``` { print a[0 0]=1; # sets the top of the triangle for(;++l<$1;) # looping for the lines for(c=0;c<=l;c++) # looping for the columns printf a[l c]= # prints the ["l c"]th element of the array, a[l-1 c-1]+a[l-1 c]+ # which is the sum of these elements of the l-1 line a[l-2 c-2]+a[l-2 c] # and these elements of the l-2 line. (c~l?RS:FS) # if it's the last column, adds a line feed, # otherwise, a space. } ``` [Try it online!](https://tio.run/##SyzP/v@/uqAoM69EITHaQMEg1tbQOi2/SMNaWzvHRsXQWhPESbY1sE62sc2xTtbW1gQrTgOqzlFIjrUFUrqGCsm6hrHaUCaEYQQUM4IzYzWS63Lsg4Kt3II1a///NwUA "AWK – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~17~~ 15 bytes ``` :;1mSż+oΘ↔Ẋż+Θ₀ ``` [Try it online!](https://tio.run/##yygtzv7/38raMDf46B7t/HMzHrVNebirC8gGMpsa/v8HAA "Husk – Try It Online") Answering [Razetime's challenge from the Husk chat](https://chat.stackexchange.com/transcript/message/57789339#57789339) ### Explanation ``` :;1mSż+oΘ↔Ẋż+Θ₀ :;1 Begin with [1] ₀ Define the sequence recursively Ẋż+Θ Pairwise sums of rows (e.g. [1,1]+[2,2,2]=[3,3,2]) m For each of these sums Sż+ Sum it to oΘ↔ itself reversed with an extra leading 0 (e.g. [3,3,2]+[0,2,3,3]=[3,5,5,3]) ``` All the sums between lines are performed with `ż+`, which sums elements at the same indices and keeps elements from the longer line unchanged. --- ## Previous solution, 17 bytes ``` ∂ƒ(:İftS‡+T0Ẋż+ΘΘ ``` [Try it online!](https://tio.run/##ASQA2/9odXNr///iiILGkig6xLBmdFPigKErVDDhuorFvCvOmM6Y//8 "Husk – Try It Online") Here's my previous solution using an original approach. ### Explanation If we rotate the triangle 45° counterclockwise, we'll find out it is actually an infinite 2D matrix: ``` 1 1 2 3 5 ... 1 2 5 10 20 ... 2 5 14 32 71 ... 3 10 32 84 ... 5 20 71 ... ... ``` This answer builds that matrix and then returns its antidiagonals, which will be the rows of the original triangle. ``` ∂ƒ(:İftS‡+T0Ẋż+ΘΘ ∂ Antidiagonals of ƒ( Fixpoint of the following function (defines the matrix recursively) :İft Set the Fibonacci sequence as the first row ΘΘ Add two empty rows before the matrix Ẋż+ and get the pairwise row sums S‡+T0 then sum this to itself transposed ``` The recursive definition computes the sums of each row with the previous one, and adds it to the sums of each column with the previous one; since the matrix is symmetric along the main diagonal, column sums are computed by transposing the row sums. Two empty rows need to be added to deal with the numbers near the sides of the triangle, where there are less than two rows/columns to sum. [Answer] # [JavaScript (V8)](https://v8.dev/), 82 bytes ``` f=(a=0,b=[1])=>print(b)+f(b,[...b,0].map((x,i)=>x+(a[i]|0)+(b[i-1]|0)+(a[i-2]|0))) ``` [Try it online!](https://tio.run/##JcpBCoAgEEDR68zgKNaqjV1EXMwEwgSFWESL7m5Gu8fnr3zxsVQtp72mlkMDDp4kxCFhmEvV/QRBk0EoOueEfHIbF4CbtA@3AY6aHo8GJKodfvZmx4@ILQO2Fw "JavaScript (V8) – Try It Online") * Missing a JavaScript answer, hoping @Arnauld is fine [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 13 12 bytes ``` 1WɓŻ+Ż++µ³¡0 ``` [Try it online!](https://tio.run/##y0rNyan8/98w/OTko7u1gUj70NZDmw8tNPj//78pAA "Jelly – Try It Online") Returns the nth row, indexed from 0. Makes use of the fact that Jelly's “repeat n times” quick `¡`, when given a dyad, behaves in [a Fibonacci-ish way](https://github.com/DennisMitchell/jellylanguage/wiki/Tutorial#65repeating-links). [Answer] # [Husk](https://github.com/barbuz/Husk), ~~29~~ ~~28~~ ~~23~~ 19 bytes * Saved 1 byte thanks to caird coinheringaahing * Saved 5 bytes thanks to Razetime! * Saved 4 bytes thanks to Leo! ``` ¡öFz+S+m↔z+ḣ´e0↔;;1 ``` [Try it online!](https://tio.run/##yygtzv7//9DCw9vcqrSDtXMftU2p0n64Y/GhLakGQLa1teH//wA "Husk – Try It Online") Outputs an infinite list, explanation coming soon. This is *really* long, so it looks like I'm not going to get the bounty anyway. ``` ¡öFz+S+m↔z+ḣ´e0↔;;1 ¡ Create infinite list by repeatedly applying function that list of previous result to create new result ;;1 Initial list of results - [[1]] Fz+S+m↔z+ḣ`e0↔ Function to get next row from previous rows ↔ Reverse previous rows (so last 2 rows are at start) `e0 [0, 0] ḣ Prefixes ([[0], [0,0]]) z+ Zip by concatenating ([0, 1, 1], [0, 0, 1]) S+ Then add those lists m↔ To their reverse ([1, 2, 1], [1, 0, 1]) F Fold over that 2-element list of lists z+ By adding them together to get the new row ``` [Answer] # [Haskell](https://www.haskell.org/), 59 bytes ``` x!y=zipWith(+)x$y++[0,0] x#y=x:(0:0:y)!y!(0:x)!x#x t=[1]#[] ``` [Try it online!](https://tio.run/##DcY7DoAgDADQ3VOU4ADBoa4kHMHZgTAwkEj8hGiH1sujb3pbfvZyHL2zkvDWtlbajLM8inMRJ0wDawnsDXr0YpWof2wVax4oxDnpmPqZ6wUBztwWaHe9CAzlvcCMQLZ/ "Haskell – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~60~~ 47 bytes ``` #3&@@@(#3&@@(1/(1-x(1+y+x+y^2x))+O@x^#)+O@y^#)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9lYzcHBQQNMaRjqaxjqVmgYaldqV2hXxhlVaGpq@ztUxCmDqEogpfY/oCgzr0TfIc3B0OA/AA "Wolfram Language (Mathematica) – Try It Online") 1-indexed. Returns the first \$n\$ rows by truncating the generating function \$\frac1{1-x(1+x+y+xy^2)}\$. --- older, **66 bytes** ``` Sum[Multinomial[#-n-2i,n-2j,i,j],{i,0,#-n},{j,0,n}]~Table~{n,0,#}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7g0N9q3NKckMy8/NzMxJ1pZN0/XKFMHSGTpZOpkxepUZ@oY6ABFa3Wqs4CsvNrYupDEpJzUuuo8kESt2v@Aosy8EgetNH2HoMS89NRoAx3L2P8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), 53 bytes ``` f(i=1,j=[])=@show(i),f([i;0]+[0;i]+[j;0;0]+[0;0;j],i) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/P00j09ZQJ8s2OlbT1qE4I79cI1NTJ00jOtPaIFY72sA6E0hmWRtAeQbWWbE6mZpAXZr/AQ "Julia 1.0 – Try It Online") call `f()` for infinite output Only correct up to 64-bit signed integer limit, replace `i=1` with `i=big(1)` to make it work for any number [Answer] # [PHP](https://php.net/), ~~124~~ ~~115~~ 112 bytes ``` echo 1;for($q=[1];print" ";$p=$q,$q=$r)for($i=-1;++$i<=count($q);)echo$r[$i]=$q[$i-1]+$q[$i]+$p[$i-2]+$p[$i].~_; ``` [Try it online!](https://tio.run/##K8go@G9jXwAkU5Mz8hUMrdPyizRUCm2jDWOtC4oy80qUuJSsVQpsVQp1gKIqRZpg@UxbXUNrbW2VTBvb5PzSvBKgDk1rTZAJKkXRKpmxQOVAStcwVhvMAFIFIL4RlBGrVxdv/f8/AA "PHP – Try It Online") Did the world want this answer? Probably not. Did it deserve it? Definetly. straightforward PHP soup that outputs all rows forever (at least until scientific notation -quickly- makes things unreadable) EDIT: saved 9 bytes by not initializing $p and $r. There wasn't enough warnings for my taste. EDIT2: saved another 3 bytes with another strategy for the newline output, thanks to `print` returning a truthy value (note that I'm aware that a byte could be saved with a "assumed constant" line separator like `print A`, but I preferred a readable output) [Answer] # [Pip](https://github.com/dloscutoff/pip) `-s`, 22 bytes ``` Y^1LaS(l+:Py)+:RVlPE0y ``` Outputs the first `n` rows. [Try it online!](https://tio.run/##K8gs@P8/Ms7QJzFYI0fbKqBSU9sqKCwnwNWg8v///7rF/80A "Pip – Try It Online") ### Explanation Each row of the triangle, represented as a list, can be obtained by a two-step process: first add the two previous rows; then take that result, reverse it, prepend 0, and add it to itself. ``` [2 2 2] +[3 5 5 3] ---------- [5 7 7 3] +[0 3 7 7 5] ------------ [5 10 14 10 5] ``` Let's start with a less-golfed version of the code: ``` Y[1]La{Pyl+:yl+:RVlPE0Sly} a is command-line argument; l is empty list (implicit) Y[1] Yank the first row into y La{ } Loop a times: Py Print y, the current row l+:y Add the two rows together, saving the result in l RVl Reverse that list, PE0 prepend 0, l+: and add it back to l (the new row) Sly Swap l and y; y is now the new row and l the row above it ``` To get to 22 bytes: * Using [this tip](https://codegolf.stackexchange.com/a/211993/16766), `[1]` → `^1`. * We can print `y` while adding it to `l`: `l+:Py`. * An assignment expression evaluates to an lvalue, so we can use it in the swap command: `S(l+:RVlPE0)y` (parentheses not necessary, added for clarity). * But then we can take the same idea one step further and replace the `l` in *that* assignment with the first `l` assignment. We'll need parentheses because assignment operators are right-associative; but since the body of the loop is now one statement, we can drop the curly braces for a net 1-byte savings: `S(l+:Py)+:RVlPE0y`. ]
[Question] [ Fermat's last theorem says that there there are no positive, integral solutions to the equation `a^n + b^n = c^n` for any `n>2`. This was proven to be true by Andrew Wiles in 1994. However, there are many "near misses" that almost satisfy the diophantine equation but miss it by one. Precisely, they are all the greater than 1 and are integral solutions of `a^3 + b^3 = c^3 + 1` (the sequence is the value of each side of the equation, in increasing order). ### Your task is given `n`, to print out the first `n` values of this sequence. Here are the first few values of the sequence: ``` 1729, 1092728, 3375001, 15438250, 121287376, 401947273, 3680797185, 6352182209, 7856862273, 12422690497, 73244501505, 145697644729, 179406144001, 648787169394, 938601300672, 985966166178, 1594232306569, 2898516861513, 9635042700640, 10119744747001, 31599452533376, 49108313528001, 50194406979073, 57507986235800, 58515008947768, 65753372717929, 71395901759126, 107741456072705, 194890060205353, 206173690790977, 251072400480057, 404682117722064, 498168062719418, 586607471154432, 588522607645609, 639746322022297, 729729243027001 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` *3‘ ḊŒc*3S€ċǵ#Ç ``` Brute-force solution. [Try it online!](https://tio.run/nexus/jelly#AR8A4P//KjPigJgK4biKxZJjKjNT4oKsxIvDh8K1I8OH//8z "Jelly – TIO Nexus") ``` *3‘ Helper link. Maps r to r³+1. ḊŒc*3S€ċǵ#Ç Main link. No arguments. µ Combine the links to the left into a chain. # Read an integer n from STDIN and execute the chain to the left for k = 0, 1, 2, ... until n matches were found. Yield the matches. Ḋ Dequeue; yield [2, ..., k]. Œc Yield all 2-combinations of elements of that range. *3 Elevate the integers in each pair to the third power. S€ Compute the sum of each pair. Ç Call the helper link, yielding k³+1. ċ Count how many times k³+1 appears in the sums. This yields a truthy (i.e., non-zero) integer if and only if k is a match. Ç Map the helper link over the array of matches. ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 31 bytes ``` :{#T#>>:{:3^}aLhH,Lb+.-H,#T=,}y ``` [Try it online!](http://brachylog.tryitonline.net/#code=OnsjVCM-Pjp7OjNefWFMaEgsTGIrLi1ILCNUPSx9eQ&input=NQ&args=Wg&debug=on) This is not complete brute force as this uses constraints. This is a bit slow on TIO (about 20 seconds for `N = 5`). Takes about 5 seconds for `N = 5` and 13 seconds for `N = 6` on my machine. ### Explanation ``` :{ }y Return the first Input outputs of that predicate #T #T is a built-in list of 3 variables #> #T must contain strictly positive values > #T must be a strictly decreasing list of integers :{:3^}aL L is the list of cubes of the integers in #T LhH, H is the first element of L (the biggest) Lb+. Output is the sum of the last two elements of L .-H, Output - 1 = H #T=, Find values for #T that satisfy those constaints ``` [Answer] # Perl, 78 bytes ``` #!perl -nl grep$_<(($_+2)**(1/3)|0)**3,map$i**3-$_**3,2..$i++and$_-=print$i**3+1while$_ ``` Brute force approach. Couting the shebang as two, input is taken from stdin. **Sample Usage** ``` $ echo 10 | perl fermat-near-miss.pl 1729 1092728 3375001 15438250 121287376 401947273 3680797185 6352182209 7856862273 12422690497 ``` [Try it online!](https://tio.run/nexus/perl#@59elFqgEm@joaESr22kqaWlYahvrFljAGQZ6@QmFqhkAhm6KvEgrpGenkqmtnZiXopKvK5tQVFmXglYWtuwPCMzJ1Ul/v9/Q4P/unk5AA "Perl – TIO Nexus") [Answer] # Mathematica, 95 bytes ``` (b=9;While[Length[a=Select[Union@@Array[#^3+#2^3&,{b,b},2],IntegerQ[(#-1)^3^-1]&,#]]<#,b++];a)& ``` Unnamed function taking a single positive integer argument `#` and returning a list of the desired `#` integers. Spaced for human readability: ``` 1 (b = 9; While[ 2 Length[ a = 3 Select[ 4 Union @@ Array[#^3 + #2^3 &, {b, b}, 2], 5 IntegerQ[(# - 1)^3^-1] & 6 , #] 7 ] < #, b++ 8 ]; a) & ``` Line 4 calculates all possible sums of cubes of integers between 2 and `b`+1 (with the initialization `b=9` in line 1) in sorted order. Lines 3-5 select from those sums only those that are also one more than a perfect cube; line 6 limits that list to at most `#` values, which are stored in `a`. But if this list has in fact fewer than `#` values, the `While` loop in lines 1-7 increments `b` and tries again. Finally, line 8 outputs `a` once it's the right length. Holy hell this version is slow! For one extra byte, we can change `b++` in line 7 to `b*=9` and make the code actually run in reasonable time (indeed, that's how I tested it). [Answer] ## Racket 166 bytes ``` (let((c 0)(g(λ(x)(* x x x))))(for*((i(in-naturals))(j(range 1 i))(k(range j i))#:final(= c n)) (when(=(+(g j)(g k))(+ 1(g i)))(displayln(+ 1(g i)))(set! c(+ 1 c))))) ``` Ungolfed: ``` (define (f n) (let ((c 0) (g (λ (x) (* x x x)))) (for* ((i (in-naturals)) (j (range 1 i)) (k (range j i)) #:final (= c n)) (when (= (+ (g j) (g k)) (+ 1 (g i))) (displayln (+ 1(g i))) (set! c (add1 c)))))) ``` Testing: ``` (f 5) ``` Output: ``` 1729 1092728 3375001 15438250 121287376 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~102~~ 98 bytes ``` def f(n,c=2):z=c**3+1;t=z in[(k/c)**3+(k%c)**3for k in range(c*c)];return[z]*n and[z]*t+f(n-t,c+1) ``` [Try it online!](https://tio.run/nexus/python2#HY1BCoMwEEWvMhshk1hE21UlJ5EswpgUCUzLMG5y@TS6e/wH/7U9ZciGR/ILvqsna59uXtVXOHgzZSK8FlOGG/JXoHQDEvmTDFnCsErSU3irwTJE3i9Q1z8fOpKbsf3kYO2RF7Y/ "Python 2 – TIO Nexus") [Answer] # Pari/GP, 107 bytes ``` F(n)=c=2;while(n>0,c++;C=c^3+1;a=2;b=c-1;while(a<b,K=a^3+b^3;if(K==C,print(C);n--;break);if(K>C, b--,a++))) ``` Finds the first 10 solutions in 10 sec. Goal: ***a^3+b^3 = c^3+1*** 1. Gets number of required solutions by function-argument ***n*** 2. Increases ***c*** from ***3*** and for each ***c^3+1*** searches ***a*** and ***b*** with ***1 < a <= b < c*** such that ***a^3+b^3=c^3+1*** . If found, decrease required number of further soulutions ***n*** by ***1*** and repeat 3. Finishes, when number of furtherly required solutions (in ***n***) equals ***0*** ***Call it*** to get the first ten solutions: ``` F(10) ``` ***Readable code*** (requires leading and trailing braces as indicators for block-notation of the function. Also for convenience prints all variables of a solution): ``` {F(m) = c=2; while(m>0, c++;C=c^3+1; a=2;b=c-1; while(a<b, K=a^3+b^3; if(K==C,print([a,b,c,C]);m--;break); if(K>C, b--,a++); ); );} ``` # Pari/GP, 93 bytes (Improvement by Dennis) ``` F(n)=c=2;while(n,C=c^3+1;a=2;b=c++;while(a<b,if(K=a^3+b^3-C,b-=K>0;a+=K<0,print(C);n--;b=a))) ``` [Answer] # Python 2, ~~122~~ 119 Bytes *why are you still upvoting? Dennis crushed this answer ;)* Welcome to the longest solution to this question :/ I managed to shave off a whole byte by making longer conditions and removing as much indentation as possible. ``` x,y,z=2,3,4 n=input() while n: if y**3+x**3-z**3==1and x<y<z:print z**3+1;n-=1 x+=1 if y<x:y+=1;x=2 if z<y:z+=1;y=3 ``` Output for `n = 5`: ``` 1729 1092728 3375001 15438250 121287376 ``` [Answer] # TI-Basic, 90 bytes There must be a shorter way... ``` Prompt N 2->X 3->Y 4->Z While N If 1=X³+Y³-Z³ and X<Y and Y<Z Then DS<(N,0 X+1->X If Y<X Then 2->X Y+1->Y End If Z<Y Then 3->Y Z+1->Z End End ``` [Answer] ## MATLAB, 94 bytes Another brute-force solution: ``` for z=4:inf,for y=3:z,for x=2:y,c=z^3+1;if x^3+y^3==c,n=n-1;c,if~n,return,end,end,end,end,end ``` Output for `n=4`: ``` >> n=4; fermat_near_misses c = 1729 c = 1092728 c = 3375001 c = 15438250 ``` Suppressing the `c=` part of the display increases the code to **100 bytes** ``` for z=4:inf,for y=3:z,for x=2:y,c=z^3+1;if x^3+y^3==c,n=n-1;disp(c),if~n,return,end,end,end,end,end >> n=4; fermat_near_misses_cleandisp 1729 1092728 3375001 15438250 ``` [Answer] # C#, ~~188~~ ~~174~~ ~~187~~ 136 bytes Golfed version thanks to TheLethalCoder for his great code golfing and tips ([Try online!](https://dotnetfiddle.net/JkmJo3)): ``` n=>{for(long a,b,c=3;n>0;c++)for(a=2;a<c;a++)for(b=a;b<c;b++)if(a*a*a+b‌​*b*b==c*c*c+1)System‌​.Console.WriteLin‌e(‌​c*c*(a=c)+n/n--);}; ``` Execution time to find the first 10 numbers: 33,370842 seconds on my i7 laptop (original version below was 9,618127 seconds for the same task). **Ungolfed version:** ``` using System; public class Program { public static void Main() { Action<int> action = n => { for (long a, b, d, c = 3; n > 0; c++) for (a = 2; a < c; a++) for (b = a; b < c; b++) if (a * a * a + b‌ * b * b == c * c * c + 1) System‌.Console.WriteLin‌e( c * c * (a = c) + n / n--); }; //Called like action(5); } } ``` Previous golfed 187 bytes version including `using System;` ``` using System;static void Main(){for(long a,b,c=3,n=int.Parse(Console.ReadLine());n>0;c++)for(a=2;a<c;a++)for(b=a;b<c;b++)if(a*a*a+b*b*b==c*c*c+1)Console.WriteLin‌​e(c*c*(a=c)+n/n--);} ``` Previous golfed 174 bytes version (thanks to Peter Taylor): ``` static void Main(){for(long a,b,c=3,n=int.Parse(Console.ReadLine());n>0;c++)for(a=2;a<c;a++)for(b=a;b<c;b++)if(a*a*a+b*b*b==c*c*c+1)Console.WriteLin‌​e(c*c*(a=c)+n/n--);} ``` Previous (original) golfed 188 bytes version ([Try online!](https://dotnetfiddle.net/wzujnR)): ``` static void Main(){double a,b,c,d;int t=0,n=Convert.ToInt32(Console.ReadLine());for(c=3;t<n;c++)for(a=2;a<c;a++)for(b=a;b<c;b++){d=(c*c*c)+1;if(a*a*a+b*b*b==d){Console.WriteLine(d);t++;}}} ``` Execution time to find the first 10 numbers: 9,618127 seconds on my i7 laptop. This is my first ever attempt in C# coding... A bit verbose compared to other languages... [Answer] # GameMaker Language, 119 bytes Why is `show_message()` so long :( ``` x=2y=3z=4w=argument0 while n>0{if x*x*x+y*y*y-z*z*z=1&x<y&y<z{show_message(z*z*z+1)n--}x++if y<x{x=2y++}if z<y{y=3z++}} ``` x,y,z=2,3,4 n=input() while n: if y**3+x**3-z3==1and x3+1;n-=1 x+=1 if y [Answer] # Axiom, 246 bytes ``` h(x:PI):List INT==(r:List INT:=[];i:=0;a:=1;repeat(a:=a+1;b:=1;t:=a^3;repeat(b:=b+1;b>=a=>break;q:=t+b^3;l:=gcd(q-1,223092870);l~=1 and(q-1)rem(l^3)~=0=>0;c:=round((q-1)^(1./3))::INT;if c^3=q-1 then(r:=cons(q,r);i:=i+1;i>=x=>return reverse(r))))) ``` ungof and result ``` -- hh returns x in 1.. numbers in a INT list [y_1,...y_x] such that -- for every y_k exist a,b,c in N with y_k=a^3+b^3=c^3+1 hh(x:PI):List INT== r:List INT:=[] i:=0;a:=1 repeat a:=a+1 b:=1 t:=a^3 repeat b:=b+1 b>=a=>break q:=t+b^3 l:=gcd(q-1,223092870);l~=1 and (q-1)rem(l^3)~=0 =>0 -- if l|(q-1)=> l^3|(q-1) c:=round((q-1.)^(1./3.))::INT if c^3=q-1 then(r:=cons(q,r);i:=i+1;output[i,a,b,c];i>=x=>return reverse(r)) (3) -> h 12 (3) [1729, 1092728, 3375001, 15438250, 121287376, 401947273, 3680797185, 6352182209, 7856862273, 12422690497, 73244501505, 145697644729] Type: List Integer ``` ]
[Question] [ Choose your favorite famous computer scientist or [computer science pioneer](http://en.wikipedia.org/wiki/List_of_pioneers_in_computer_science) who was **born in 1942 or earlier** (as 1943 marks the start of the creation of the ['first' computer](http://en.wikipedia.org/wiki/ENIAC)). They should have a Wikipedia page or other site that lists their birth year and tells how their accomplishments relate to computer science. You may choose the same as someone else but choosing someone new is encouraged. Take a name they are commonly known by. This will most likely be their first and last name but it might include abbreviations or middle names if that is more common. For example, for [Tony Hoare](http://en.wikipedia.org/wiki/Tony_Hoare) both `Tony Hoare` and `C. A. R. Hoare` would be acceptable. **All the characters in the name must be [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters).** If the name contains characters that aren't printable ASCII it's fine if you choose something approximate. e.g. `Kurt Godel` instead of `Kurt Gödel`. Take the set of unique characters in the name (e.g. `C. ARHoare`) and shift them up the printable ASCII scale by the birth year of your scientist, looping around from `~` to space. (Basically add the birth year modulo 95.) This will give you a (most likely) new set of printable ASCII characters. For example, C. A. R. Hoare was born in 1934, so shifting every character in `C. ARHoare` by 1934 (34 mod 95) characters gives `ePBctj2$5(`. This Stack Snippet will do all the shifting for you: ``` function go() {var name = document.getElementById("name").value;var year = parseInt(document.getElementById("year").value);var unique = {};for (var i = 0; i < name.length; i++) { unique[name.charAt(i)] = true; } var result = ''; for (var char in unique) { result += String.fromCharCode((char.charCodeAt(0) - 32 + year) % 95 + 32); } document.getElementById("result").value = result; } ``` ``` Name: <input type="text" id="name" value="C. A. R. Hoare"><br> Birth Year: <input type="text" id="year" value="1934"><br> <button type="button" onclick="go()">Ok</button><br> Result: <input type="text" id="result" readonly> ``` # Challenge Using this set **and only this set** (no tabs, no newlines) of shifted printable ASCII characters, write a program that prints `Hello, [name]!` to stdout or closest alternative, where `[name]` is the same exact name you chose above and shifted to get your program characters. You may use multiple characters from the set or not use some at all. For example, the theoretical program `PetBee($25` prints `Hello, C. A. R. Hoare!`. # Scoring Your score is your code size in bytes times the number of unique characters in the name you choose. The lowest sore wins. [Answer] # CJam, ~~230~~ ~~117~~ ~~115~~ ~~114~~ ~~113~~ ~~110~~ ~~107~~ 106 bytes \* 13 = 1378 ``` 23)3*c11(2#)c111(((c3*))))22 2*c32c23 3*c3))$(113))c1$)))2$)2$(32c3)))$(3)$))1($)1($)3))$)1($)1$(12$(((33c ``` [Test it here.](http://cjam.aditsu.net/) I chose `Edsger Dijkstra`, born 1930, which gives me `c#2&$1>b()* 3` (whom I really just chose because he was the first one I found whose name yielded useful characters for CJam; I've checked a dozen names since and none looked as promising). The code basically just builds the ASCII codes using `1`, `2`, `3`, `*`, `#` (exponentiation) and `(`, `)` (decrement, increment) and converts them to a character with `c`. To save some characters I can sometimes copy an earlier character with `$` (`0$` copies the top stack element, `1$` copies the second-to-top stack element and so on). Here is the breakdown of the code into characters (this is also runnable): ``` 23)3*c "(23+1)*3 -> 72 -> H"; 11(2#)c "(11-1)^2+1 -> 101 -> e"; 111(((c "111-3 -> 108 -> l"; 3*) "Turn l into string lll and split off the third l."; ))) "l+3 -> o"; 22 2*c "22*2 -> 44 -> ,"; 32c "32 -> Space"; 23 3*c "23*3 -> 69 -> E"; 3))$( "e-1 -> d"; 113))c "113+2 -> 115 -> s"; 1$))) "d+3 -> g"; 2$) "d+1 -> e"; 2$( "s+1 -> r"; 32c "32 -> Space"; 3)))$( "E-1 -> D"; 3)$)) "g+2 -> i"; 1($) "i+1 -> j"; 1($) "j+1 -> k"; 3))$) "r+1 -> s"; 1($) "s+1 -> t"; 1$( "s-1 -> r"; 12$((( "d-3 -> a"; 33c "33 -> !"; ``` [Answer] # [Marbelous](https://codegolf.stackexchange.com/questions/40073/making-future-posts-runnable-online-with-stack-snippets/40808#40808), 83 bytes \* 10 = 830 I've chosen `R Kowalski, 1941` which allows me to use: `{It9A+6=53` ``` ++63 A66333696A5A696A6A69 A5633A..+3+6+3+9++ A56A+I AA+6 =3 3653666665 +I+I+6+6+A++ ``` This one is a bit more complex than the old answer (below) since many marbles go through multiple devices, all in all most marble just have a few things added to them before being printed though. Because I didn't have subtraction or low numerals, the lower ascii codes had to be formed by adding by merging two high value marbles, since this results in addition modulo. (I've used `=3` as a deflector since it pushes every marble not equal to 3 to the right and looks like a cute cat) **output:** `Hello, R Kowalski!` **old answer:** **[Marbelous](https://codegolf.stackexchange.com/questions/40073/making-future-posts-runnable-online-with-stack-snippets/40808#40808), 113 \* 17 = 1921** Marbelous does okay here, since ever marble that falls off the board gets printed, because of its 2D nature though, it needs a few numerals + some arithmetic to not let the borad get too huge. I've chosen `Philip D. Estridge, 1937` who yields `u./26EiSj9:8*-+` as the available character set. The characters actually used are `.+-245689E` ``` 22 6865 4965686866282252686968696E2244666E65686422456E6E6E6964 --..+4+4+9+4-2-2....+4..+2-2..+9..-4+4..-2..+5+6+4 ``` The board is pretty simple, the first 3 rows are literals, ever group of two is a hexadecimal value, the fourth row are arithmetic operations to form the ascii codes that could not be written explicitly because of the limited character sets. **output:** `Hello, Philip Donald Estridge!` [You can try it out here!](https://codegolf.stackexchange.com/questions/40073/making-future-posts-runnable-online-with-stack-snippets/40808#40808) I'll now look for a possible better candidate, since it looks like marbelous might actually be competitive here. [Answer] # Insomnia, ~~103~~ ~~99~~ 98 \* 8 = 784 [George Boole](http://en.wikipedia.org/wiki/George_Boole), 1815 All 5 programs below have the same length (98) and same output. ``` oyoooyLyyyyoyLqoyyoyoLL*yyoLqy|oLq*yLyoyyoLqoq*yLyyLoyooLyyy*qL|yqoLq**LoooyoLqy|qLLo*qyLq*oq|L|oL oyoooyLyyyyoyLqoyyoyoLLy*yyoLq*oqL*LqyyyoyLyooyyoLyyLoyooLyyyL*q|qoL|q*LoooyoLqyq*LLo*qyLq*o|qL|oL oyoooyLyyyyoyLqoyyoyoLL*yyoLqy|oLq*yLyoyyoLqoq*yLyyLoyooLyyyL*qq|oL|yq*LoooyoLqyq*LLo*qyLq*o|qL|oL oyoooyLyyyyoyLqoyyoyoLLy*yyoLq*oqL*LqyyyoyLyooyyoLyyLoyooLyyyL*q|qoL|q*LoooyoLqyq*LL|qyyLy*qq*L|oL oyoooyLyyyyoyLqoyyoyoLL*yyoLq|oLq*yLyoyyoLyq|oLq|yq*LqooLoyyoyLyLoyyoyLoooyoLo|q|LLq|yyLooooyoLqyL ``` Prints `Hello, George Boole!` **Insomnia, 103 \* 6 = 618** (probably optimal and unique) If `G Boole` ([George Boole](http://en.wikipedia.org/wiki/George_Boole), 1815) is acceptable... ``` ooyoyoLoyyoyoyyLyoyoooLLoyooyyLoyyyoLooyoyoooooLyoyyoLoyoyyyoLooyyyooLoyoyooooLLyyooyoyoLyoyoooLoyooooL ``` Prints `Hello, G Boole!` --- # Insomnia, ~~94~~ ~~92~~ ~~89~~ ~~85~~ 83 \* 10 = 830 Kurt Godel, 1906. ``` kukuzkzjzkuxkujx{rxjkjxzjukukzj{ukukzjkrxujzujk{rxujjku{jxuukujrxzjuxjk{urxjxukzj{j ``` Prints `Hello, Kurt Godel!` I wrote a program to search for the solution. My second version of the program should be closer to optimal than my first version. As per @Martin Büttner's nitpick (~~100~~ ~~92~~ ~~88~~ 85 characters, same set of characters): ``` kukuzkzjzkuxkujx{rxjkjxzjukukzj{ukukzjkrxujzujk{rxujju{jxuukujrxuxjzxjk{urxjxjxukzj{j ``` Prints `Hello, Kurt Goedel!` [**Interpreter**](https://codegolf.stackexchange.com/a/41868/6638) [Answer] # Brainfuck,1846\*12 = 22152 Just to have a language other than CJam. Requires original spec Brainfuck with byte datatype, that overflows at 256. Only uses 2 characters: `+` to increment the current cell, and `.` to output the current cell. ``` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++.+++++++++++++++++.++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++. ``` **Output** ``` Hello, John McCarthy! ``` Credit goes to Coredump for revealing the following in his answer: ``` "John McCarthy" 1927 ("John McCarthy" "e+*;h~^|.0$5" 12) ``` [Answer] # "Hello, Niklaus Emil Wirth!" (Befunge-98, 222×14=3108) From [Wikipedia](https://en.wikipedia.org/w/index.php?title=Niklaus_Wirth&oldid=1198340176): > > **Niklaus Emil Wirth** (15 February 1934 – 1 January 2024) was a Swiss computer scientist. > He designed several programming languages, including Pascal, and pioneered several classic topics in software engineering. > In 1984, he won the Turing Award, generally recognized as the highest distinction in computer science, “for developing a sequence of innovative computer languages”. > > > With a shift of 34, `Niklaus Emil Wirth` (18 characters, 14 unique) ends up as `p,./$86Bg0,/By,57+`. ## Code ([try it out here](http://www.quirkster.com/iano/js/befunge.html)): ``` 88888888+++++++50p50g8+,50g88885+++++00pg,g7+,g7+,g55++,888866+++++,8888+++,50g68++,g886++5/+,g6+,g7+,50g88755+++++,g88++,g77++,8888+++,50g5+,g8+,g886++5/+,g7+,8888+++,50g887+++,g886++5/+,g85++,g87++,g88+5/+,g5/85++,50g00p ``` ## Breakdown: ``` 88888888+++++++ # Put eight '8's on the stack and add them together (ASCII 64 = `@`) 50p # Save this value in row 0, column 5 (where the 6th '8' was) 50g8+, # Fetch the value we just saved, add 8 and print it (ASCII 72 = `H`) 50g88885+++++ # Fetch it again and add 37 (4×8+5) (ASCII 101 = `e`) 00p # Save this value in row 0, column 0 (the very first character) g, # Fetch & print this value (stack is empty, so coordinates will be zero) g7+,g7+, # Fetch it again, add 7 (ASCII 108 = `l`) and print. Repeat. g55++, # Print `o` 888866+++++, # Print `,` (4×8+2×6=44) 8888+++,50g68++,g886++5/+,g6+,g7+,50g88755+++++,g # Continue in a similar fashion, 88++,g77++,8888+++,50g5+,g8+,g886++5/+,g7+,8888++ # using integer division (`/`) in +,50g887+++,g886++5/+,g85++,g87++,g88+5/+,g5/85++, # a few places 50g00p # Fetch the `@` character and put it in cell (0,0) ``` The last line places a HALT character (`@`) at the beginning of the line. When the control wraps around back to this point, the program will stop. This shouldn't actually be necessary, because the `@` character at (5,0) is still there and nothing should be output before it is reached. However, [the only online Befunge interpreter that will run this monstrosity](http://www.quirkster.com/iano/js/befunge.html) won't work properly without it. It *is* actually possible to make a working solution with just `Niklaus Wirth` (12 unique chars, `p,./$86By,57+`), but the code is much, *much* longer. (Tagged as Befunge-98 because Befunge-93 is limited to a width of 80 characters.) [Answer] # CJam, 323 bytes \* 10 = 3230 ``` 5((e5(((e2(((e2(((e2((e2c525e2e2(e2(((e2(e2((e2(((c525e5(e5(((e2(e2c2(($Be2(e2(((e2(e2e2((e2(e2e2(c2e2e2((e2e2(e2(((e2(e2c2(($((((((((((((B((((($(((((2e2(e2(e2e2((e2(((e2(e2e2((c2$2$((c2$2$525e2(((e2((e2((e2((e2e2(((e2((c2$2$22((((((($22(((((((((($22(((((($((((255((e2((e2(e2((e2(((e2((c22(((($Be2e2(e2(e2((e2(((e2(((e2(((c ``` Output: ``` Hello, C. A. R. Hoare! ``` # CJam, 662 bytes \* 10 = 6620 8700 Not to win but just because it looks possible. It used only `2e(c`. ``` 2e2e2((e2e2(((e2(((e2(((e2((e2c2e2e2(((e2e2(e2(((e2(e2((e2(((c2e2e2e2((e2((e2e2(((e2(e2c2e2e2e2((e2((e2e2(((e2(e2c2e2(e2(((e2(e2e2((e2(e2e2(c2e2((e2e2((e2e2(e2(((e2(e2c2e2((e2e2((e2(((e2(((e2((e2e2c2e2((e2(((e2e2(((e2((e2(e2(((e2(c2e2(e2(e2e2((e2(((e2(e2e2((c2e2((e2e2((e2(((e2(((e2((e2e2c2e2((e2(((e2e2(((e2((e2(e2(((e2(((c2e2(e2(e2e2((e2(((e2(e2e2((c2e2((e2e2((e2(((e2(((e2((e2e2c2e2(((e2(((e2((e2((e2((e2e2(((e2((c2e2(e2(e2e2((e2(((e2(e2e2((c2e2((e2e2((e2(((e2(((e2((e2e2c2e2e2((e2e2(((e2(((e2(((e2((e2c2e2(e2(((e2(e2e2((e2(e2e2(c2e2(((e2e2(e2(((e2(e2(((e2(((e2(((c2e2e2e2(((e2((e2(e2((e2(((e2((c2e2e2(((e2e2(e2(((e2(e2((e2(((c2e2(e2e2(e2(e2((e2(((e2(((e2(((c ``` Output: ``` Hello, C. A. R. Hoare! ``` ### Generator ``` q{i [7209 3113 41 41 41 9 1 0] { 1$3^)4%@1$+@*4/\'(*\ }%W2tW%"e2"* 'c}% ``` The trivial answer `222(((((((((((c` (generated by `q{i222_@-'(*'c}%`) has 3420 bytes. [Answer] # CJam, 16 \* ~~307~~ 288 = ~~4912~~ 4608 ``` B(7*2+cB(B(*2(+cB(B*((cB(B*((cBB*7-(((c5 8*5(+c8 2*2*cBB*2/5+cBB*7-cBB*5-cBB*Bm5-(cBB*4-cBB*7-c8 2*2*cB7*(((cBB*7-(((cBB*Bm5-(cBB*B-c8 2*2*c8B*2+8-cBB*7-(((c7 2+B*(cBB*8 2*-cBB*B-c8 2*2*cB(7*2(+cBB*7-(((cBB*7-cB(B(*2(+cB(B*((cB(B*((c8 2*2*cB7*cBB*8 2*-cB(B*((cBB*B-cB(B(*2(+cBB*7-c5(8*1+c ``` Displays: ``` Hello, Arthur John Robin Gorell Milner! ``` This is my first answer using CJam, so surely this can better golfed (any hint is welcome). --- Here is some utility code I used. Since I computed the character set for some other names, this may be useful for someone who better knows CJam (or maybe for another language). * Find the character set, along with the number of unique characters ``` (defun character-set (name year) (let* ((uniques (remove-duplicates name)) (size (length uniques)) (buffer (make-array size :element-type 'character :fill-pointer 0))) (loop for c across uniques do (vector-push (code-char (+ #x20 (mod (- (+ (char-code c) year) #x20) 95))) buffer) finally (return (values buffer size))))) ``` * Define a list of well-known figures ``` (defparameter *masters* '("Grace Murray Hopper" 1906 "Augusta Ada King, Countess of Lovelace" 1815 "Augusta Ada Byron" 1815 "Ada Lovelace" 1815 "John von Neumann" 1903 "Neumann Janos Lajos" 1903 "Charles Babbage" 1791 "John McCarthy" 1927 "Wilhelm Ackermann" 1896 "George Boole" 1815 "Kurt Godel" 1906 "Andrei Nikolaievitch Kolmogorov" 1903 "Bertrand Arthur William Russell, 3rd Earl Russell" 1872 "Arthur John Robin Gorell Milner" 1934)) ``` * Compute the allowed printable character sets, sort by size of set ``` (sort (loop for (n y) on *masters* by #'cddr collect (cons n (multiple-value-list (character-set n y)))) #'< :key #'caddr) => (("George Boole" "Q|q*Lyvo" 8) ("Ada Lovelace" "Kn*Vy!vkmo" 10) ("Kurt Godel" "Q{xz&Mujkr" 10) ("John von Neumann" "Mkyr#Qhxpdq" 11) ("Charles Babbage" "5Zd^eq4TSYW" 11) ("Grace Murray Hopper" "MiS{g &Nuvkx" 12) ("Neumann Janos Lajos" "QhxpMq#Odmrv" 12) ("John McCarthy" "e+*;h~^|.0$5" 12) ("Augusta Ada Byron" "q }~Knk*L$|yx" 13) ("Wilhelm Ackermann" "Sedh{=_gani]j" 13) ("Arthur John Robin Gorell Milner" "c78l+t%i2Bo,/1(5" 16) ("Andrei Nikolaievitch Kolmogorov" "DqgQndhlwfk#Nopjury" 19) ("Augusta Ada King, Countess of Lovelace" "KnUsq6M x~}p*Vy!vkmo" 20) ("Bertrand Arthur William Russell, 3rd Earl Russell" "&R%XL;MQovH)EVc6YWIP" 20)) ``` [Answer] # Brainf\_ck - 723 \* 12 = 8676 I did a crawl from Wikipedia's [List of computer scientists](http://en.wikipedia.org/wiki/List_of_computer_scientists) and collected the birthyears and longest names of all the people listed there. I wrote a program to run over all these and find any I could possibly do in a common language. Sadly, I was unable to find any names that could support `echo;`, `alert()`, `console.log()` (I can hope), `print`, or `main`. I mainly wanted to share my raw crawl data in case anyone wanted to similarly search for other languages (note: may be inaccurate and incomplete): [**Crawl Data**](http://pastebin.com/j2kq3Tys). **EDIT**: New crawl paste with about 40 new names from [List of computing people](http://en.wikipedia.org/wiki/List_of_computing_people) and [List of pioneers in computer science](http://en.wikipedia.org/wiki/List_of_pioneers_in_computer_science). **EDIT**: Manually cleaned up the list. I did find that [Jean David Ichbiah](http://en.wikipedia.org/wiki/Jean_Ichbiah) (1940), chief designer of Ada, provides `+-.` (the shortest of three people to do so). I generated this BF code for him. ``` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.-------------------------------------------------------------------.------------.++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++.----.+++++++++++++.------------------------------------------------------------------------------.++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++++++++++++++++.-------------.-----.--------------------------------------------------------------------.+++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++.+++++.------.+++++++.--------.+++++++.-----------------------------------------------------------------------. ``` [Alexander Keewatin Dewdney](http://en.wikipedia.org/wiki/Alexander_Dewdney) provided the most usable BF characters (`+.<>`), but came in slightly above my answer. No one I found provided `.[]`. [Answer] ## Ruby 1.8 - 250 × 18 = 4500 ``` p''<<24+48<<2+99<<9+99<<9+99<<22+89<<44<<4+28<<24/4+59<<22+88<<2+95<<22+94<<22+89<<9+99<<24/4+99<<24/4+99<<4+28<<24/4+59<<9+99<<2+99<<22+98<<2+99<<2+99<<24+94<<24/4+99<<99<<5+99<<4+28<<84/4+54<<2+95<<22+92<<2+95<<22+94<<84/4+94<<22+95<<98<<2+95<<4+29 ``` Characters available: ``` '()+./24589:;<>Efp ``` Output: ``` "Hello, Anatolii Alexeevich Karatsuba!" ``` [Anatolii Karatsuba](http://en.wikipedia.org/wiki/Anatoly_Karatsuba), born 1937, is most well known for his contributions to the field of analytic number theory (a field I personally enjoy), including the [Karatsuba Algorithm](http://en.wikipedia.org/wiki/Karatsuba_algorithm), a method for fast multiplication of arbitrary precision operands. This is the first and only name I tried. [Answer] ## GolfScript (125 \* 14 = 1750) ``` 9)99.9-&^99)).9^..)))..)~99-&.99&.99)^999)9/.(((-9-..9(/-.((9^99((.9-9-^.).9-^).)).~--999~9/.9^.((.9^99(.(.9.~-^.))..9-^))](- ``` [Online demo](http://golfscript.apphb.com/?c=OSk5OS45LSZeOTkpKS45Xi4uKSkpLi4pfjk5LSYuOTkmLjk5KV45OTkpOS8uKCgoLTktLi45KC8tLigoOV45OSgoLjktOS1eLikuOS1eKS4pKS5%2BLS05OTl%2BOS8uOV4uKCguOV45OSguKC45Ln4tXi4pKS4uOS1eKSldKC0%3D) [Douglas Engelbart](http://en.wikipedia.org/wiki/Douglas_Engelbart) (1925 - 2013) is perhaps most famous for the ["Mother of All Demos"](http://en.wikipedia.org/wiki/The_Mother_of_All_Demos). His name and year of birth give characters `!&(),-./9]^z{~`, of which this solution uses `&()-./9]^~` The basic structure of the code is `build list of numbers](-` which puts a lot of numbers in an array with the empty string that starts on the stack, then pulls out that string and uses it with the type promotion of `-` to turn the array of numbers into a string. Since there's no access to elements below the top of the stack I wrote a C# program to find short snippets that take a given integer on the top of the stack and add the next integer required. This created one small problem, when the snippet for `69` (`E`) ended with `-` and the snippet for `110` (`n`) started with `9`: it cost one char to use a longer snippet for `110`. [Answer] # [CaneCode](http://esolangs.org/wiki/CaneCode), ~~458~~ 410 \* 16 = ~~7328~~ 6560 ``` 11111111111111111111111111111111111111111111111111111111111111111111111184111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111118111111188111841111111111111111111111111111111111111111111182222222222228331184222222222222228118111111118483322222841811111111822222828483322284111182222222222222811111111111111822222222222222811111111182222228222222281111111111118418 ``` Corresponding BF: ``` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++..+++.>++++++++++++++++++++++++++++++++++++++++++++.------------.<<++.>--------------.++.++++++++.>.<<-----.>+.++++++++.-----.-.>.<<---.>++++.-------------.++++++++++++++.--------------.+++++++++.------.-------.++++++++++++.>+. ``` Outputs: ``` Hello, Jack Elton Bresenham! ``` CaneCode is just a direct symbol substitution of Brainfuck, where `12348` correspond to `+-><.` respectively. I spent about 2 hours trying to look for a short name which gave `+-.` for normal Brainfuck, with no success. [Jack Elton Bresenham](https://en.wikipedia.org/wiki/Jack_Elton_Bresenham), inventor of Bresenham's line algorithm and born 1937, gives the following characters: ``` o')1Ej2:54g8+9.3 ``` Unfortunately, while `5` (`[`) is available, the lack of `6` (`]`) means that the code still had to increment up the 100-ish area (for lowercase chars) the slow way. [Answer] # [><> (Fish)](http://esolangs.org/wiki/Fish), 163 \* 15 = 2445 ``` 47*5+:56+7*+:42)+:4+55*66*:++66+6*o:4+::o7+:oo25*+o56+:4*o42*4*o6*7+o:7+7+7+o:o:25*7++o42*:4*o45+*o:45++o:o:6+:5+o6+o:o:25*7++o24*4*o25*7*4+o:o:2+o:27*+o42)+ooooo; ``` Outputs: ``` Hello, Ivar Hjalmar Jacobson! ``` [Ivar Hjalmar Jacobson](https://en.wikipedia.org/wiki/Ivar_Jacobson), born 1939, was found thanks to [BMac's crawl data](https://codegolf.stackexchange.com/a/41783/21487). He provides the chars ``` )*+24567:;>Gopq ``` ><>, like Befunge, is a 2D stack-based language. The useful ><> commands are: * `*+24567` for arithmetic (note that `47` pushes a `4` and a `7` on the stack, not `47`) * `)` for greater than (useful for getting `1`) * `:` for duplicating the top of the stack * `o` for output * `;` for program termination `p` is also good for reflection, but I was unable to think of a good use for it. `>` is another ><> command, directing program flow rightwards, but since the program already executes in that direction it was not needed. ]
[Question] [ Write a program or function that can distinguish the following 12 trigonometric functions: [`sin`](https://de.mathworks.com/help/matlab/ref/sin.html), [`cos`](https://de.mathworks.com/help/matlab/ref/cos.html), [`tan`](https://de.mathworks.com/help/matlab/ref/tan.html), [`asin`](https://de.mathworks.com/help/matlab/ref/asin.html), [`acos`](https://de.mathworks.com/help/matlab/ref/acos.html), [`atan`](https://de.mathworks.com/help/matlab/ref/atan.html), [`sinh`](https://de.mathworks.com/help/matlab/ref/sinh.html), [`cosh`](https://de.mathworks.com/help/matlab/ref/cosh.html), [`tanh`](https://de.mathworks.com/help/matlab/ref/tanh.html), [`asinh`](https://de.mathworks.com/help/matlab/ref/asinh.html), [`acosh`](https://de.mathworks.com/help/matlab/ref/acosh.html), [`atanh`](https://de.mathworks.com/help/matlab/ref/atanh.html). Your program is given one of the above functions as [black box](https://codegolf.meta.stackexchange.com/a/13706/56433) and should output the function's name either as given above or the way it is named in your language. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins. You should show that your code works correctly by including test cases with all 12 possible inputs. If the language of your choice does not include build-ins for all of the above functions, you have to provide your own sensible implementations of the missing ones. ### Further Clarifications * Using complex numbers to query the black box is allowed if the underlying build-ins can handle them. * As \$ dom\ acosh \cap dom\ atanh = \emptyset \$ when using only real numbers, queries to the black box function can give domain errors. In this case you should assume that the black box only communicates the existence of an error, but not from which function it originates. * If instead of an error some other value, e.g. `NaN` or `null`, is returned, then your submission should be able to handle them. --- Thanks for the helpful [sandbox feedback](https://codegolf.meta.stackexchange.com/a/16569/56433)! [Answer] # Python 3.6.4 on Linux, 99 bytes Bit of a silly answer, but: ``` lambda f:"asinh acos cos cosh atan atanh tan sin asin tanh sinh acosh".split()[hash(f(.029))%19%12] ``` Requires the trigonometric functions to be one out of the built-in `cmath` module for complex in/output. [Answer] # [Perl 6](http://perl6.org/), 75 bytes ``` ->&f {([X~] ("","a"),<sin cos tan>,("","h")).min({abs(f(2i)-&::($_)(2i))})} ``` [Try it online!](https://tio.run/##LY1BCoMwEEWvMgwSMhBddNGFVM9RKCVMxRChxmLahYT06mlq3HyGx@PNa1yf5zRvIMzHDdCluhcGgrxdv3eQiAoZSV385GBYPLzZ9WrHFomaeXIy8MNLI08T1aJtZaXpf1OkmDxvgKHSjeN5jND1EPYvlY4IZllB5K4Ckct5czsvF8SFcYGZ2eLZItrDtIdqD9emHw "Perl 6 – Try It Online") As it happens, all twelve of the functions to be discriminated amongst are built-in and all take complex arguments. `[X~] ("", "a"), <sin cos tan>, ("", "h")` generates all twelve function names by reducing the three input lists with cross-product-concatenation. Given those, `.min(...)` finds the one which the smallest difference from the input function at `2i`. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~178~~ 172 bytes ``` double d;_;f(double(*x)(double)){d=x(0.9247);_=*(int*)&d%12;puts((char*[]){"acosh","sinh","asinh","atanh","tan","cosh","asin","sin","cos","atan","tanh","acos"}[_<0?-_:_]);} ``` [Try it online!](https://tio.run/##Xc7RasIwFAbg@z5FqExyyipVBNmi80FEwlnSmkIbpU1BKH31xdS0LniT/z/JxyEivQhhrbx2v1VOJOOsoH6gyR2mCtDLw51mq6/NdgeMHxJaapPAUn6sN@zWmZZSobBJTmfoYxTXVsWfcVvqMXBOg8904c7JjI@e@rvJefYE4@Vw4vvsmPJvfgY22EWpRdXJnOxrNGqlfiL3G1JjqSmQPiKEFNRtBOar2zBXt3SuGAgMCL4ZFSIVqtcQqhD9myY3XaNJxqIhsn@iqPDS2rSqHw "C (gcc) – Try It Online") # Old but cool: [C (gcc)](https://gcc.gnu.org/), 194 bytes ``` double d;_;f(double(*x)(double)){char n[]="asinhacoshatanh";d=x(0.9247);_=*(int*)&d%12;_=(_<0?-_:_);n[(int[]){10,5,5,0,14,10,4,4,9,14,0,9}[_]]=0;puts(n+(int[]){5,1,0,10,11,6,0,1,6,10,11,5}[_]);} ``` [Try it online!](https://tio.run/##XY/haoMwFEb/@xShYyNxscSiGy51exCRcBu1ETQdGqEgvvqyiHML44ZwPnI@yJXRVUprq9t06WpUccEbvAUc3skPEjJLBQPSRZkfYGy1AnkbFRjQ6sCr/I7ZMTslr4SLPMStNiF5qh7jk4tYnNlHJN4E4bpYn4qSzDGjqRtG44Q6TtxkKzOaLYUoy5zxz8mMWD/vjZTGq@5OTF9WcveW0rVB@GIfWi27qarRuQejjuo9cF3UQ6sxQXOAEGqw@zrhG7oFdnRr7AieAZ4C/xzlS8q3foNv@dKfM9RmGjRiPFgC@yWbDq6jjbr@Gw "C (gcc) – Try It Online") The `-lm` switch in TIO is merely to test. If you could write a *perfect* implementation of the standard trig functions you would get the right answer. ## Explanation The idea was to find some input value such that when I interpret the outputs of each of the trig functions as integers they have different remainders modulo 12. This will allow them to be used as array indices. In order to find such an input value I wrote the following snippet: ``` #include <math.h> #include <stdlib.h> #include <stdio.h> #include <time.h> // Names of trig functions char *names[12] = {"sin","cos","tan","asin","acos","atan","sinh","cosh","tanh","asinh","acosh","atanh"}; // Pre-computed values of trig functions double data[12] = {0}; #define ABS(X) ((X) > 0 ? (X) : -(X)) // Performs the "interpret as abs int and modulo by" operation on x and i int tmod(double x, int i) { return ABS((*(int*)&x)%i); } // Tests whether m produces unique divisors of each trig function // If it does, it returns m, otherwise it returns -1 int test(int m) { int i,j; int h[12] = {0}; // stores the modulos // Load the values for (i = 0; i < 12; ++i) h[i] = tmod(data[i],m); // Check for duplicates for (i = 0; i < 12; ++i) for (j = 0; j < i; ++j) if (h[i] == h[j]) return -1; return m; } // Prints a nicely formatted table of results #define TEST(val,i) printf("Value: %9f\n\tsin \tcos \ttan \n \t%9f\t%9f\t%9f\na \t%9f\t%9f\t%9f\n h\t%9f\t%9f\t%9f\nah\t%9f\t%9f\t%9f\n\n\tsin \tcos \ttan \n \t%9d\t%9d\t%9d\na \t%9d\t%9d\t%9d\n h\t%9d\t%9d\t%9d\nah\t%9d\t%9d\t%9d\n\n",\ val,\ sin(val), cos(val), tan(val), \ asin(val), acos(val), atan(val),\ sinh(val), cosh(val), tanh(val),\ asinh(val), acosh(val), atanh(val),\ tmod(sin(val),i), tmod(cos(val),i), tmod(tan(val),i), \ tmod(asin(val),i), tmod(acos(val),i), tmod(atan(val),i),\ tmod(sinh(val),i), tmod(cosh(val),i), tmod(tanh(val),i),\ tmod(asinh(val),i), tmod(acosh(val),i), tmod(atanh(val),i)) // Initializes the data array to the trig functions evaluated at val void initdata(double val) { data[0] = sin(val); data[1] = cos(val); data[2] = tan(val); data[3] = asin(val); data[4] = acos(val); data[5] = atan(val); data[6] = sinh(val); data[7] = cosh(val); data[8] = tanh(val); data[9] = asinh(val); data[10] = acosh(val); data[11] = atanh(val); } int main(int argc, char *argv[]) { srand(time(0)); // Loop until we only get 0->11 for (;;) { // Generate a random double near 1.0 but less than it // (experimentally this produced good results) double val = 1.0 - ((double)(((rand()%1000)+1)))/10000.0; initdata(val); int i = 0; int m; // Find the smallest m that works do { m = test(++i); } while (m < 0 && i < 15); // We got there! if (m == 12) { TEST(val,m); break; } } return 0; } ``` If you run that (which needs to be compiled with -lm) it will spit out that with a value of 0.9247 you get unique values. Next I reinterpeted as integers, applied modulo by 12, and took the absolute value. This gave each function an index. They were (from 0 -> 11): acosh, sinh, asinh, atanh, tan, cosh, asin, sin, cos, atan, tanh, acos. Now I could just index into an array of strings, but the names are very long and very similar, so instead I take them out of slices of a string. To do this I construct the string "asinhacoshatanh" and two arrays. The first array indicates which character in the string to set to the null terminator, while the second indicates which character in the string should be the first one. These arrays contain: 10,5,5,0,14,10,4,4,9,14,0,9 and 5,1,0,10,11,6,0,1,6,10,11,5 respectively. Finally it was just a matter of implementing the reinterpretation algorithm efficiently in C. Sadly I had to use the double type, and with exactly 3 uses, it was quicker to just use `double` three times then to use `#define D double\nDDD` by just 2 characters. The result is above, a description is below: ``` double d;_; // declare d as a double and _ as an int f(double(*x)(double)){ // f takes a function from double to double char n[]="asinhacoshatanh"; // n is the string we will manipulate int a[]={10,5,5,0,14,10,4,4,9,14,0,9}; // a is the truncation index int b[]={5,1,0,10,11,6,0,1,6,10,11,5}; // b is the start index d=x(0.9247); // d is the value of x at 0.9247 _=*(int*)&d%12; // _ is the remainder of reinterpreting d as an int and dividing by 12 _=(_<0?-_:_); // make _ non-negative n[a[_]]=0; // truncate the string puts(n+b[_]);} // print the string starting from the correct location ``` Edit: Unfortunately just using a raw array is actually shorter, so the code becomes much simpler. Nonetheless the string slicing was fun. In theory an appropriate argument might actually come up with the right slices on its own with some math. [Answer] # Python 3.6.5 on Linux, ~~90~~ 85 bytes ``` h=hash;lambda f:h(f(.0869))%3%2*"a"+"tscaionns"[h(f(.14864))%3::3]+h(f(.511))%5%2*"h" ``` This builds upon [orlp's answer](https://codegolf.stackexchange.com/a/168371/81278); but instead of finding 1 magic number, we find 3! This basically just saves bytes by avoiding putting the string literals for "sin", "cos", and "tan" multiple times, instead building the answer one part at a time. The first magic number is used to determine whether it's one of the "arc" trigonometric functions, prepending an "a" accordingly, the second for whether it's one of the "sin", "cos", or "tan" based functions, selecting the appropriate string, and the third for whether it's one of the hyperbolic functions, appending a "h" accordingly. Like orlp's answer, it uses the functions from Python's built-in `cmath` module as input. *Saved 5 bytes by using slice indexing into the middle string* ## Finding the Magic Numbers For completeness, here's (more or less) the script I used to find these magic numbers. I mostly just worked straight in a python terminal, so the code is messy, but it gets the job done. ``` import cmath fns = [(fn, getattr(cmath, fn)) for fn in ["sin","cos","tan","asin","acos","atan","sinh","cosh","tanh","asinh","acosh","atanh"]] count_length = lambda num, modulus, base_modulus : len(str(num).rstrip('0').lstrip('0')) + (1 + len(str(modulus)) if modulus != base_modulus else 0) min_length = float("inf") min_choice = None for modulus in range(2,10): for i in range(1,100000): num = i/100000. is_valid = True for fn in fns: val = hash(fn[1](num))%modulus%2 if (val == 0 and fn[0][0]=="a") or (val == 1 and fn[0][0]!="a"): is_valid = False if is_valid: length = count_length(num, modulus, 2) if length < min_length: min_length = length min_choice = (modulus,num) print(min_choice) min_length = float("inf") min_choice = None for modulus in range(3,10): for i in range(100000): num = i/100000. mapping = {} is_valid = True for fn in fns: fn_type = "sin" if "sin" in fn[0] else "cos" if "cos" in fn[0] else "tan" val = hash(fn[1](num))%modulus%3 if val in mapping and mapping[val] != fn_type: is_valid = False break mapping[val] = fn_type if is_valid: length = count_length(num, modulus, 3) if length < min_length: min_length = length min_choice = (modulus, num, mapping) print(min_choice) min_length = float("inf") min_choice = None for modulus in range(2,10): for i in range(1,100000): num = i/100000. is_valid = True for fn in fns: val = hash(fn[1](num))%modulus%2 if (val == 0 and fn[0][-1]=="a") or (val == 1 and fn[0][-1]!="a"): is_valid = False if is_valid: length = count_length(num, modulus, 2) if length < min_length: min_length = length min_choice = (modulus,num) print(min_choice) ``` [Answer] # [Python](https://docs.python.org/2/), ~~108~~ ~~94~~ 90 bytes Compares the result of the input function to the results of all of the functions for the value `.2`. ``` from cmath import* lambda f:[w for w in globals()if w[-1]in'shn'and eval(w)(.2)==f(.2)][0] ``` [**Try it online**](https://tio.run/##PYwxbsMwDEXn8BQEMlgKkKLOaMBjvOYArgfakSIhMiVIStWc3rWNogM//ycfGd7ZeL4sXfu1OJrHO6Fu@oLaRyxoGR/Oj@SSkFZj6c/1YLlKhiviO6pvcqJI8XGRbau3NvSfA@joZ5xmygbtHHzMp@W4/bMcXhkAirFOYd3AIcd3E6LljJ3Yt0JKOKifSYWM11t3jXG9o4SqGaOi50LJsgGafIK/WlMm3sXA5lYCNgz2yT9vfgE) *-14 bytes by [Jonathan Allen](https://codegolf.stackexchange.com/users/53748/jonathan-allan)* *-4 bytes by [Rod](https://codegolf.stackexchange.com/users/47120/rod)* [Answer] # [Dyalog APL](https://www.dyalog.com/), ~~25~~ ~~21~~ 19 bytes ``` (8-(2○⍨8-⍳15)⍳⎕2)∘○ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@Gha6G0aPp3Y96V1joPurdbGiqCSQf9U010nzUMQMoAVL2P43LEMLjSuMygrOM4SxTOMsMzjKHsw6tN0RiGyGxjZHYpkhsMyQ21BwA "APL (Dyalog Unicode) – Try It Online") -3 thanks to [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz) -2 thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn) Goes trough all the required trig functions (which in APL are `1 2 3 5 6 7 ¯1 ¯2 ¯3 ¯5 ¯6 ¯7○2`) plus some more things (this goes trough `-7..7`), finds which one matches `input○2`, and outputs that "with" `○`, which outputs as `num∘○` [Answer] # JavaScript, ~~76~~ ~~67~~ 66 bytes Not pretty but I went far too far down the rabbit hole with this over a few beers to *not* post it. Derived independently from Nit's solution. ``` b=>Object.getOwnPropertyNames(M=Math).find(x=>M[x](.8)+M==b(.8)+M) ``` [Try it online](https://tio.run/##Jc1LDoMgFIXhrTSOIKWMO7nugNq5MeGKqBh5REhrV08Lnfw5yTc4G74wqsOEdHN@0nmGPELbjZtWiS86dW/3PHzQR/o80OpIBAhMK@WzcRM5oRX9ORB@p1cBMP4Hzcq76HfNd7@QBpWPrGRlGI2r@c2ErmZlxSsXrVisUMNj2E2STHKLgVhoZ1LueztQyjdvnGQXSfMX) * Saved 6 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/) * Saved 1 bye thanks to [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2) [Answer] # [C (gcc)](https://gcc.gnu.org/) with `-lm`, ~~374~~ ~~346~~ ~~324~~ 310 bytes Thanks to Giacomo Garabello and ceilingcat for the suggestions. I was able to save a bit more space by having a helper macro do token-pasting in addition to my original macro which does stringizing. In the tests, I used a couple of non-library trig functions to confirm the validity of the results. As the results between the library and non-library functions weren't *exactly* the same floating-point value, I compared the difference of the results against a small value ε instead of using equality. ``` #import<math.h> #define q(f)f,#f, #define _(f,g)q(f##sin##g)q(f##cos##g)q(f##tan##g) #define p for(i=0;i<24;i+=2)!j[i] typedef double(*z)(double);*y[]={_(,)_(a,)_(,h)_(a,h)};i,x;*f(z g){int j[24]={x=0};char*c;for(double w;x++<9;)p&isnan(w=((z)y[i])(x))-isnan(g(x))|fabs(w-g(x))>1E-9?j[i]=1:0;p?c=y[i+1]:0;g=c;} ``` [Try it online!](https://tio.run/##bVFdc5swEHznV1zDTEcC0RonL4kgfuqv8Hg8ikCgDF9BIsZ2@eulJ3A8fejLabW6u10WGRVSzrOv667tbVILW/4oXz0/y5VucvggiirmK3ZnjkSxgiLv@0Y3vn/DsjV3bMXC30c6UG1PdLrhOtk@cR2mW/rtfa8Pnj13OTZB1g5vVU6CCyUrpDw47w/p9UgYPRLhCisXVNKJazbyQJELFPSqGwvv@@0TNo/pZuKyFH0guVNcV8GJj2GYPHPafdemEQ05pYRc6BkNUDJSGq1s4fBvJd4MOUXL5TX@FT3vnNE0ftnwbidTHArjA16KVPIJY2tkNWQ5JMZmunXJeTfV@nzEHL48jBSuHkCf26FvAIPD/T8xMzy4N/07JPCx/P9Y1aKt0Hz0lozBGMZ0nXUJ1AJXfrY6WwcuoIZGmv0BUrg6OQYoxm6mGIiFEgsnFsapLk1YkSjZ3cvaV66NeLiEYOKo4oS1Ay5zCAz3EH/9atBJ/Ig1DFdLAAbNKLIaw@j5QnaDNcTszMtD0@JXWFk@LC@TN81/pKpEYeaoqufo9Bc "C (gcc) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 86 bytes ``` #&@@Nearest[a=Join[a={Sin,Cos,Tan,Sinh,Cosh,Tanh},InverseFunction/@a];#@2&/@a->a,#@2]& ``` [Try it online!](https://tio.run/##jZHPaoQwEMbveQohILomiF6XXSylhZRSFtqbZCGI23jYCGp7WfbeZ@jj9UXsTLL2j67benAmyff7ZjLZq06Xe9VVhep3q6CnfpY9lKop2y5Xq7u6MhAOj5Vh13XLnpRhkGtcaFzpIxPmtWza8vbFFF1VmzhTckmz1IeErxWDVPp9uCSbpjJdTvl6l1EJpwdC0JagL0FjYp2JtcYN@F81hdVAtDKIVun29XCghxNIiAhutgEXNOQQIYRx6jNv/AULDxy8RUgGeXRJjnoohPqp/9gBedBDPyd/ClJOZ5x/9qMHIPoPgDcfVfhmJ6TryAL39XMuaPTx9h4knG7TUMZi5tJu0ghtqjiNhDdlR6SDTsNCNU94KuKAcgF1UnH@Mdz7DcjJPzrnP2lO/6aA4ckf1NfkHJZIjgncR@LMZ9uzDDn2nw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~71~~ 67 bytes ``` ->g{Math.methods.find{|h|g[0.5]==Math.send(h,0.5)rescue p}||:acosh} ``` [Try it online!](https://tio.run/##ZZA7a8MwFIV3/4qzKYFGdMkSUDN1KiXgNQ1FteVch0Qyegwlym93rzS4hW767neOXj59fc@Dmjcv5/u7jiRvJpLrgxxG298z5fPxWW5PSlUZjO1X9MSTtTehSwbTI@ed7lygxzylGCAAjBYbuBR5mXHTsSPRFNmIwIrDiNpCFyhV6IJMVBwVSdVS1VQ9CRmm6xil0R2hd8hDsrkBJj/aCAbpLylEbJeZ4FsIJg@F4fjndStOr08yus@whL28/qvnWl8OgFK81x7i8Cawg3ht20P7m9h/2Ib/Z/4B "Ruby – Try It Online") [Answer] # JavaScript, ~~108~~ 70 bytes I haven't tried golfing in pure Javascript in ages, so I'm sure there's stuff to improve here. ``` t=>Object.getOwnPropertyNames(m=Math).find(f=>m[f](.9,0)+''==t(.9)+'') ``` Pretty straightforward, checks every function on the `Math` prototype against an arbitrary value (0.9, many other values probably work) and compares with the result of the black box function. Tested in Google Chrome, will break if the input black box function is not one of the trigs. Cut off a ton of bytes thanks to Shaggy and Neil. ``` const answer = t=>Object.getOwnPropertyNames(m=Math).find(f=>m[f](.9,0)+''==t(.9)+''); const tests = [Math.sin, Math.cos, Math.tan, Math.asin, Math.acos, Math.atan, Math.sinh, Math.cosh, Math.tanh, Math.asinh, Math.acosh, Math.atanh]; tests.forEach(test => console.log(test + ' yields ' + answer(test))); ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 39 bytes ``` {i.^methods.first({try $^a.(i)==.(i)})} ``` [Try it online!](https://tio.run/##JcfBCoQgGEXhvU9xiRAFcTmbsEcphP5QGGtQNyI@uyWzOR/nR/H76aFwMr16vQXK7j6SPn1MWdQcC@bNauGlMaNNtr6w844QPPlLYdS92P8NnERlAJIt0JcNpCaYFZPiJOZdLqz1Bw "Perl 6 – Try It Online") By the looks of things, one of the few to use introspection. `i` here is the complex number, whose value is unique for each trig function, so by iterating through all the methods we can find the matching method and implicitly spit out its name. The `try` is needed as some (unwanted) methods have the a different signature. [Answer] # [R](https://www.r-project.org/), 73 bytes ``` function(b)Find(function(x)get(x)(1i)==b(1i),apropos('(sin|cos|tan)h?$')) ``` [Try it online!](https://tio.run/##PYtLCoAwDET3nkMwATceoLjzHvFT001abAUX3r22kLrJI29mrmxNtrdsyXmBFRcnO/z/g@eRyoXJoTFrxUjh8sFHGCA6eTcf30SCPPcDYrZVYmeh@IoaFZBaUk3qi2Zts9a59bkNuC0Y8wc "R – Try It Online") For the moment (R v3.5) it works. If in a future R version it will be added a function matching this regex, then who knows :P * -4 bytes thanks to @Giuseppe * -9 bytes thanks to @JayCe * -2 bytes using `Find` instead of `for` [Answer] # HP 49G RPL, 88.0 bytes excluding 10 byte program header Another solution using complex numbers! Enter and execute it in COMPLEX, APPROX mode. Takes the function on the stack. ``` 2. SWAP EVAL { SIN COS TAN ASIN ACOS ATAN SINH COSH TANH ASINH ACOSH ATANH } DUP 1. << 2. SWAP EVAL >> DOLIST ROT - ABS 0. POS GET ``` (the newlines don't matter) For the constant 2.0, all twelve trig functions are defined in the complex plane, so we just evaluate all twelve and see which one matches. This time, the iterative solution is longer (111.5 bytes) because of the stack shuffling needed to get it. RPL, as far as I know, doesn't let you break out of a loop early. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 72 bytes ``` f=>eval('for(s=i=0;!s||s(.8)+s!=f(.8)+s;i++)s=Math[t=i.toString(30)];t') ``` [Try it online!](https://tio.run/##Jcy9CoMwEADgV6ku3qENQpeCnKNbp45FSLD@nMSceKGT755Cu33Tt7qP0@HgPV6DvMfUUZqoHT/OQzHJAUpMdZPpeSqYO5aa0fRHw2WJSg8Xl1ckNlGe8eAww63GvokFpkGCih@NlxlyN4guudHdc7SVNZvbYaO2g1@w9YhmFQ62ulhMXw "JavaScript (Node.js) – Try It Online") ]
[Question] [ ### Background / Description Note: as @HelkaHomba points out, the actual GitHub identicons *are not actually random but based on the hash of a username* The default GitHub avatar is a 5x5-pixel image. A color is picked randomly, and then random pixels are filled in on one side (right or left, 2x5 size) using that color. Then that side is copied & flipped to the other side, across the y-axis. The pixels left over that are not filled in are #F0F0F0, or rgb(240,240,240). The center column's pixels (1x5 size) are then randomly filled in, using the same color as previously. ### Output *Note: for this challenge we will ignore the space that encloses the GitHub avatars* The program should output a 5x5 pixel image file. See <http://meta.codegolf.stackexchange.com/a/9095/42499> for specifics ### Examples *Note: these were obviously scaled up from 5x5 so you can see them* [![enter image description here](https://i.stack.imgur.com/N1EeF.png)](https://i.stack.imgur.com/N1EeF.png) [![enter image description here](https://i.stack.imgur.com/7h1ea.png)](https://i.stack.imgur.com/7h1ea.png) Good luck! [Answer] # Pyth - 27 bytes ``` .wC+Kc3O^Cm,240O256 3 15_PK ``` Obviously doesn't work online, but you can have it print color codes [here](http://pyth.herokuapp.com/?code=jbC%2BKc3O%5ECm%2C240O256+3+15_PK&debug=0). [Answer] ## [Perl 5](https://www.perl.org/), 77 bytes **This is non-competing as it only has a 256 colour palette, only works on terminals that support ANSI escape codes and doesn't actually output a 5 pixel square image, but I thought I'd post it anyway as it was fun golfing this down.** ``` sub x{"\e[48;5;@{[rand>.5?$-||=rand 254:254]}m "}say$}=x,$b=x,x,$b,$}for 0..4 ``` **Note:** the `\e` is actually ASCII char `\x1B`. ### Usage ``` perl -E 'sub x{"\e[48;5;@{[rand>.5?$-||=rand 254:254]}m "}say$}=x,$b=x,x,$b,$}for 0..4' ``` ### Explanation Nothing particularly clever except perhaps: * Use `$-` to automatically round the colour number for use in the escape sequence, used instead of `$n=0|rand 254`. ### Example output [![Yeah, you'll be stuck with whatever the last colour was, all over your -boink- terminal.](https://i.stack.imgur.com/uAvyh.png)](https://i.stack.imgur.com/uAvyh.png) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~36~~ 29 bytes ``` 5l$rtP+!kllII$r*O16tQ/XE'a'YG ``` This saves the result in file `a.png`. Replacing `'a'` by `2` in the code displays the image (scaled up) instead of saving a file: ``` 5l$rtP+!kllII$r*O16tQ/XE2YG ``` Here's an example output: [![enter image description here](https://i.stack.imgur.com/DI5GG.png)](https://i.stack.imgur.com/DI5GG.png) ### Explanation ``` 5l$r % 5×5 matrix of independent random values with uniform distribution % on the interval (0,1) tP+! % Duplicate, flip vertically, add, transpose. This gives a horizontally % symetric matrix. Center column pixels are uniformly distributed on the % interval (0,2). Rest have a triangular distribution on (0,2) k % Round down. In either of the above cases, this gives 0 and 1 % with the same probability llII$r % 1×1×3 array of independent random numbers with uniform distribution % on (0,1). This is the foreground color. * % Multiply the two arrays with broadcast. Gives a 5×5×3 array. Ones in the % 5×5 array become the random foreground color. Zeros remain as zeros. O % Push 0 16tQ/ % 16, duplicate, add 1, divide: gives 16/17, or 240/255 XE % Replace 0 by 16/17: background color 'a' % Push file name YG % Write image to that file ``` [Answer] ## Actually, 53 bytes ``` 3'≡*;╗`┘#8╙r-J┌`MΣ╝5`3"2rJ└"£n3╟;RdX+Σ`nkΣ"P6 5 5 255 ``` [Try it online!](http://actually.tryitonline.net/#code=MyfiiaEqO-KVl2DilJgjOOKVmXItSuKUjGBNzqPilZ01YDMiMnJK4pSUIsKjbjPilZ87UmRYK86jYG5rzqMiUDYgNSA1IDI1NQ&input=) Actually is bad at string processing. I think I've mentioned that before. This program outputs a P6 netpbm image using CP437, like the following: ``` P6 5 5 255 εεεεεεå♠ƒεεεεεεå♠ƒå♠ƒεεεå♠ƒå♠ƒεεεεεεεεεεεεεεεεεεεεεå♠ƒεεεεεεå♠ƒå♠ƒå♠ƒå♠ƒå♠ƒ ``` This can be converted to a PNG using ImageMagick: ``` seriously -f prog.srs | convert - out.png ``` Scaled up PNG version: [![sample output](https://i.stack.imgur.com/o8vEN.png)](https://i.stack.imgur.com/o8vEN.png) Explanation: ``` 3'≡*;╗`┘#8╙r-J┌`MΣ╝5`3"2rJ└"£n3╟;RdX+Σ`nkΣ"P6 5 5 255 3'≡* push "≡≡≡" (char 240, 3 times) ;╗ save a copy to reg0 `┘#8╙r-J┌`M map: ┘# cp437 char code, as list ([240]) 8╙r-J random value in range(2**8) that is not 240 ┌ char code Σ╝ concatenate, push to reg1 5`3"2rJ└"£n3╟;RdX+Σ`n do this 5 times: 3"2rJ└"£n do this 3 times: 2rJ└ randomly pick 0 or 1, push the value in that register 3╟ push the top 3 items to a list ;RdX+ duplicate, reverse, discard first value, append (mirror the list) Σ concatenate kΣ push stack as list, concatenate "P6 5 5 255 prepend header ``` [Answer] ## Python, ~~167~~ ~~164~~ ~~155~~ 148 bytes Output as ppm ``` from random import* print"P3 5 5 255" C,P=choice,[[240]*3,[randint(0,255)for _ in"RGB"]] exec"a,b=C(P),C(P);print' '.join(map(str,a+b+C(P)+b+a));"*5 ``` * Edit1: `range(5)` to `" "*5` * Edit2: shoved a byte at the first `print` * Edit3: Replaced list comprehension with `map` since only `str(p)` was used * Edit4: `exec""*5` instead `for _ in " "*5:` Some improvement over old, string-based code: ``` from random import* print "P3 5 5 255" j,c,a=' '.join,choice,['']*5 P=["240 "*3,j([str(randint(0,255))for _ in"RGB"])] for _ in a:a=[c(P)]*5;a[1]=a[3]=c(P);a[2]=c(P);print j(a) ``` [Answer] # Swift 2.3, ~~593~~ 585 bytes ``` var t = 0,g = UIGraphicsGetCurrentContext(),c = UIColor(hue:CGFloat(drand48()),saturation:1,brightness:1,alpha:1).CGColor srand48(time(&t)) UIGraphicsBeginImageContext(CGSizeMake(5,5)) for x in 0..<3 {for y in 0..<5 {CGContextSetFillColorWithColor(g,drand48()>0.5 ? c : UIColor.whiteColor().CGColor) var r = [CGRect(x:x,y:y,width:1,height:1)] if x<2 {let m = x==0 ? 4 : 3;r.append(CGRect(x:m,y:y,width:1,height:1))} CGContextFillRects(g,&r,r.count)}} let i = UIGraphicsGetImageFromCurrentImageContext() UIImagePNGRepresentation(i)!.writeToURL(NSURL(string:"/a/a.png")!,atomically:true) ``` **Update** # Swift 3, 551 bytes ``` var t = 0,g = UIGraphicsGetCurrentContext()!,c = UIColor(hue:CGFloat(drand48()),saturation:1,brightness:1,alpha:1).cgColor srand48(time(&t)) UIGraphicsBeginImageContext(CGSize(width:5,height:5)) for x in 0..<3 {for y in 0..<5 {g.setFillColor(drand48()>0.5 ? c : UIColor.white().cgColor) var r = [CGRect(x:x,y:y,width:1,height:1)] if x<2 {let m = x==0 ? 4 : 3;r.append(CGRect(x:m,y:y,width:1,height:1))} g.fill(&r,count: r.count)}} let i = UIGraphicsGetImageFromCurrentImageContext()! try!UIImagePNGRepresentation(i)!.write(to: URL(string:"/a/a.png")!) ``` I'm at WWDC and just got the Xcode 8 beta with Swift 3. Apple made some of the CoreGraphics calls more "Swifty," and I am able to reduce the bytecount. Swift 2 code Ungolfed: ``` var t = 0 srand48(time(&t)) UIGraphicsBeginImageContext(CGSizeMake(5,5)) let context = UIGraphicsGetCurrentContext() let color = UIColor(hue: CGFloat(drand48()),saturation:1,brightness:1,alpha:1).CGColor for x in 0..<3 { for y in 0..<5 { CGContextSetFillColorWithColor(context, drand48() > 0.5 ? color : UIColor.whiteColor().CGColor) var rects = [CGRect(x:x,y:y,width:1,height:1)] if x < 2 { let mirror = x==0 ? 4 : 3 rects.append(CGRect(x: mirror, y: y, width: 1, height: 1)) } CGContextFillRects(context, &rects, rects.count) } } let image = UIGraphicsGetImageFromCurrentImageContext() UIImagePNGRepresentation(image)!.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,inDomains:.UserDomainMask).first!.URLByAppendingPathComponent("a.png"), atomically:true) ``` This answer assumes UIKit is available and uses the Cocoa Touch framework. Some example output images: [![1](https://i.stack.imgur.com/SbTk5.png)](https://i.stack.imgur.com/SbTk5.png) [![2](https://i.stack.imgur.com/Q8Y22.png)](https://i.stack.imgur.com/Q8Y22.png) [![3](https://i.stack.imgur.com/H4m50.png)](https://i.stack.imgur.com/H4m50.png) I know I can't compete with most of the other answers but I wanted to give this a shot as a personal challenge. There is definitely room for improvement with this answer, but I think it will be hard to get this down below a few hundred bytes due to the length of the UIKit and CoreGraphics image writing method names. I opted to write an actual PNG file rather than PPM values as an exercise for myself, but shorter answers would definitely be possible if I used the PPM format. I already start out as a loss by having to declare a variable to seed `srand48` with `time`. I chose this over `arc4random()` or `arc4random_uniform()` because ultimately I would lose more bytes with those. I seed the rng to use `drand48` to generate a random color and pick when to write a color to a pixel. `CGSize` vs `CGSizeMake` and `CGRect` vs `CGRectMake`: I switch between the inline C API functions and their Swift extensions to find the shortest constructor for each. `CGSizeMake` ends up being shorter than `CGSize()`, and `CGRect`ends up being shorter than `CGRectMake()`: ``` CGSizeMake(5,5) CGSize(width:5,height:5) CGRect(x:x,y:y,width:1,height:1) CGRectMake(CGFloat(x),CGFloat(y),1,1) ``` I would have to create `CGFloat`s `x` and `y` due to the nature of the for loop. I'm really not thrilled with the 2D loop and if equality checks, but I was really struggling to find a shorter way. There's definitely room to shave off a few bytes here. Calling `CGContextFillRects` with an array of `CGRect` structs is cheaper than calling `CGContextFillRect` twice with two different values, so I save a few bytes with the array and pointer. I also save 27 bytes by not calling `UIGraphicsEndImageContext()`. While this would normally be a "bug" in production code, it's not necessary for this toy program. Colors: Colors are also a pain to deal with, since I'm creating `UIColor` objects but need to write a `CGColor` opaque type to each pixel. The shortest code I found to create a random color was to use the `UIColor` constructor and get the `CGColor` from that `UIColor`. Same with white. If I were using the Cocoa framework instead of Cocoa Touch, I might be able to save some bytes using `CGColorGetConstantColor()`, but unfortunately that method is unavailable in the Cocoa Touch SDK. Writing to to file: Writing to a file takes almost 100 bytes. I'm not sure how to even go about optimizing this. On some systems depending on your permissions, you may need to use the Documents directory which would be even longer: ``` UIImagePNGRepresentation(i)!.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,inDomains:.UserDomainMask).first!.URLByAppendingPathComponent("a.png"), atomically:true) ``` Definitely open to further optimizations. **Edit 1:** Saved a few bytes by rearranging some variable declarations. [Answer] ## Mathematica, ~~105~~ ~~102~~ ~~98~~ 94 bytes ``` c=1~RandomReal~3;r@l_:={c,4{4,4,4}/17}~RandomChoice~{l,5};Image[Join[#,r@1,Reverse@#]&@r@2] ``` ![Mathematica graphics](https://i.stack.imgur.com/Vwkef.png) `` is the [Transpose operator](http://reference.wolfram.com/language/ref/character/Transpose.html). Edit 1: Saved 3 bytes by replacing `Round` + `RandomReal` with `RandomInteger` Edit 2: Saved 4 bytes by replacing `RandomInteger` with `RandomChoice` Edit 3: Saved 4 bytes by replacing `RandomColor` and `GrayLevel` with `RandomReal` [Answer] ## MATLAB, 102 bytes Hi, this is my matlab solution: ``` p=@(x)(imwrite(floor(randi(2,5,2)*[eye(2) ones(2,1)./2 fliplr(eye(2))]),[0.9412*[1 1 1];rand(1,3)],x)) ``` The input `x` of the function is the name of the output file. For example: ``` p('output.png') ``` produces a png image called 'output.png'. Here the results of some executions of this code. [![output1.png](https://i.stack.imgur.com/v28o0.png)](https://i.stack.imgur.com/v28o0.png) [![output2.png](https://i.stack.imgur.com/UdjuG.png)](https://i.stack.imgur.com/UdjuG.png) [![output3.png](https://i.stack.imgur.com/DD9Sn.png)](https://i.stack.imgur.com/DD9Sn.png) [![output4.png](https://i.stack.imgur.com/FMGGZ.png)](https://i.stack.imgur.com/FMGGZ.png) [Answer] # Dyalog APL, ~~43~~ 42 bytes ~~`'P3',5 5 256,∊(3⍴240)(?3⍴256)[⌈(⊢+⌽)?5 5⍴0]`~~ `'P3',5 5a,∊(3⍴240)(?3⍴a←256)[⌈(⊢+⌽)?5 5⍴0]` Right to left: `?5 5⍴0` generates a 5×5 matrix of random numbers between 0 and 1 ([but never 0 or 1](http://help.dyalog.com/15.0/Content/Language/Primitive%20Functions/Roll.htm)) `(⊢+⌽)` is a train that adds the matrix with its reflection `⌈` ceiling, returns 1 or 2 for each element `(3⍴240)(?3⍴256)` colours - white-ish and a random one `[ ]` use each element of the matrix as an index in colours `'P3',5 5 256,∊` flatten and add header [Answer] ## PHP, 236 bytes I know this is an old challenge but I just like to challenge myself. ``` $o=imagecreate(5,5);$t=imagecolorallocate;$r=rand;for($c=[$t($o,240,240,240),$t($o,$r(0,255),$r(0,255),$r(0,255))];$y++<5;)for($x=-2,$a=[];$x<3;)imagesetpixel($o,$x+2,$y,isset($a[$v=abs($x++)])?$a[$v]:($a[$v]=$c[$r(0,1)]));imagepng($o); ``` Ungolfed: ``` // Store these frequently used functions $t=imagecolorallocate; $r=rand; // Create 5x5 image $o=imagecreate(5, 5); // Define array of the possible colors $c=[$t($o,240,240,240),$t($o,$r(0,255),$r(0,255),$r(0,255))]; // Loop over y axis for($y=0;$y++<5;) { // This stores values for colors used in the current row indexed by the absolute value of x starting from -2 $a = []; // Loop over x axis for($x=-2;$x<3;) { // Set a pixel of a random color for current coordinate. If it exists in the array, use the array value. imagesetpixel($o,$x+2,$y, isset($a[$v=abs($x++)]) ? $a[$v] : ($a[$v]=$c[rand(0,1)]) ); } // Empty the array $a = []; } // Output as PNG imagepng($o); ``` Sample Output: [![Github avatar](https://i.stack.imgur.com/rYsym.png)](https://i.stack.imgur.com/rYsym.png) [![Github avatar](https://i.stack.imgur.com/vNgIN.png)](https://i.stack.imgur.com/vNgIN.png) [Answer] # Javascript ES6, 296 bytes *Note:* does not produce a file, draws to a canvas. See it in action in this [JS Fiddle](http://jsfiddle.net/hh4779wy/2/). ``` s=20;W='#fff';M=Math;R=M.random;ctx=document.getElementById('c').getContext('2d');cr=`#${M.floor(R()*16777215).toString(16).slice(0,3)}`;f=Array(5).fill();a=f.map((_,i)=>f.map((_,j)=>R()*2|0));a.map((c,x)=>c.map((v,y)=>{ctx.fillStyle=y>=3?c[y==3?1:0]?cr:W:c[y]?cr:W;ctx.fillRect(y*s,x*s,s,s);})); ``` ]
[Question] [ I recently learned from [a comment](https://mathoverflow.net/q/413087/104733#comment1058750_413087) by MathOverflow user [pregunton](https://mathoverflow.net/users/115044/pregunton) that it is possible to enumerate all rational numbers using iterated maps of the form \$f(x) = x+1\$ or \$\displaystyle g(x) = -\frac 1x\$, starting from \$0\$. For example, $$0 \overset{f}{\mapsto} 1 \overset{f}{\mapsto} 2 \overset{g}{\mapsto} -\frac12 \overset{f}{\mapsto} \frac12 \overset{f}{\mapsto} \frac 32 \overset{g}{\mapsto} -\frac23 \overset{f}{\mapsto} \frac 13.$$ That is, $$ \frac13 = f(g(f(f(g(f(f(0))))))) = f\circ g\circ f\circ f\circ g\circ f\circ f(0).$$ This is an example of a *shortest path of iterated maps* to reach \$\frac13\$; every path from \$0\$ to \$\frac13\$ requires at least seven steps. --- ## Challenge Your challenge is to take two integers, `n` and `d`, and return a string of `f`'s and `g`'s that represents a shortest path of iterated maps from \$0\$ to \$\displaystyle\frac nd\$. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. #### Example ``` n | d | sequence of maps ----+----+----------------- 1 | 3 | fgffgff 3 | 1 | fff 8 | 2 | ffff 1 | -3 | gfff 2 | 3 | fgfff 0 | 9 | [empty string] 1 | 1 | f 2 | 1 | ff 1 | -2 | gff -1 | -2 | fgff 6 | 4 | ffgff -2 | 3 | gffgff 8 | 9 | fgfffffffff ``` [Answer] # [Python](https://www.python.org), 54 bytes (-1 @Jonathan Allan, -1 me) ``` f=lambda n,d:n and'gf'[p:=n*d>0]+f(p*n-d,[n,d][p])or'' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVBBboMwEFSv7if2ZjuBKKFVRJDoQ4o40JollojtglFUKT_phUv7p_Y1xTagdmXtetazMyt_fJl3e9ZqHD8Hi3H6fcS8rS4vogIViUxBpQRtkBYmy9VGPO3LLTKzUbGIiolQFqbkuqN0nn6WygyWcbLU61m2NRwy4uQinc_9XW9aaRm9UU7AdFJZ5t6R-RuPXBGc57ne9baThnEeHMafu3sABTcAMaW-fhtq9VqDRrhUpifxFNs1_QsCcHBzD1PCBt0hAfk-epg6mASI80TsOE3AyV8F19i7xmlKi7zXWphBeNFJgg6BeIXzFkdHfvTkQFh91kXTxcg7hyDhU34B) #### Old [Python](https://www.python.org), 56 bytes (@tsh) ``` f=lambda n,d:n*d<0and'g'+f(-d,n)or n and'f'+f(n-d,d)or'' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVDBTsQgEI1X_Im5AW7Z7FZjuhv7I96qlC5JF9iWxpjsn3jpRf9Jv0YGSqMTMsN7vHkz4ePLvfuTNfP8OXklqu9K1X1zfpENmEIezZ182jVG0o5uFBOyMNwOYAAphZQJnAwcpUv_szZu8oyTXN9Oum9hfyRoWNh64bej67Vn9Eo5ATdo4xm-KxZvvMAiOa9rux39oB3jPE2Yf25uIaxwBZAhje1las1rC1bBuXEjESE2a_oXBGCPffchqU7hIQlFXkVYISwTVEuHQE2XcPnXAYkdEoeQsn30yspknH3K5ENArHDZ4hHFD1GcBOucddEqD4qTU5D0Kb8) #### Old [Python](https://www.python.org), 57 bytes ``` f=lambda n,d:n//d<0and'g'+f(-d,n)or n and'f'+f(n-d,d)or'' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVDbTsQgEI2v-BPzBmTLXqox3Y39Ed-qlC5JF7ClMSb7J770Rf9Jv0YGSqMTMsM5nDkz4ePLvfuzNfP8OXklqu-jqvvm8iwbMIU8md1OPu4bI2lHN4oJWRhuBzCAlELKBE4GjtLF4EkbN3nGSa5vZ923cDgRdCxsvfDb0fXaM3qlnIAbtPEM3xWLN15gkZzXtd2OftCOcZ4mzD83txBWuALIkMb2dWrNSwtWwaVxIxEhNmv6FwTggH13IalO4SEJRV5FWCEsE1RLh0BNl3D51wGJPRLHkLJ99MrKZJx9yuRDQKxw2eIBxfdRnATrnHXRKg-Kk1OQ9Cm_) Not 100% sure this is correct. Works on all test cases, though. It's kind of a Euclidean algorithm with overshoot. #### Towards a proof of correctness The group of transformations generated by f and g is called the [Modular group](https://en.wikipedia.org/wiki/Modular_group). There is quite a bit of interesting theory but the one thing that seems relevant to us is that gg and gfgfgf are a "complete set of relations" and that the modular group is the "free product of the cyclic groups generated by g and h:=gf". This means that any element of the modular group can be uniquely written as g's alternating with either h or hh. Transforming back to f's and g's gh becomes f and ghh becomes fgf, so except for the left end which can be h or hh, i.e. gf or gfgf all valid representations are exactly the words with g's separated by at least 2 f's. And we can check that the algorithm indeed produces such words. So, are we done? I'm not sure. What's missing is that I don't know how exactly the rationals and the modular group are related. It may well be that two distinct group elements move 0 to the same rational which would send us back quite a bit if not all the way to square 1. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 53 bytes ``` f=(n,d,p='',...e)=>n?f(...e,-d,n,p+'g',n-d,d,p+'f'):p ``` [Try it online!](https://tio.run/##bZBfC4IwFMXf@xR720bbTIuwwvog0YO4Pxi2DZWgT79mZRPd2MOF3@Gec@69fJZd1da2p9pw4ZwskCac2AJCwhgTuDjri0TDSCgnmtg1VJBoP/NhlhAfrauM7kwjWGMUkgikBIAtxieQJEAqOfzVTLL1knSULHHucRbwgnsHOjqoCM9mCRaCjRccfoKreNj@Bbq@rbW6RaxC0phPqBFLmYWUM0ynOHajvV@@@y@PLJi2jJ85n9T83OH73Bs "JavaScript (Node.js) – Try It Online") Stackoverflow on last testcase. [Answer] # [Ruby](https://www.ruby-lang.org/), 45 bytes ``` f=->n,d{n==0?"":n/d<0??g+f[-d,n]:?f+f[n-d,d]} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y5PJ6U6z9bWwF5JySpPP8XGwN4@XTstWjdFJy/Wyj4NyMwDslNia/8XKKRFG@oYx/4HAA "Ruby – Try It Online") Use as `f[n,d]` basically a port of [loopy walt's python answer](https://codegolf.stackexchange.com/questions/240806/iterate-your-way-to-a-fraction/240808#240808) [Answer] # [Nibbles](http://golfscript.com/nibbles), 15.5 bytes ``` `.~$@?*@$~-@__*~@$$=`$*@$"fg " ``` That's 31 nibbles at half a byte each in the binary form. This is based on the python answer although I found an iterative solution shorter. It felt kind of awkward still though. ``` `. ~$@ Iterate while unique, starting with the tuple $ @ (which is the input arguments) ? *@$ if product of values > 0 ~-@_ _ then ($-@, @) since true clause has condition's value put in $ (unused here though) *~@ $ else (-1*@, $) $ the second value of the tuple from the if (tuple's aren't returned as first class things but splat into the context and must be reconstructed, normally very concise but here a bit awkward ``` The above code computes the sequences of numerators and denominators, now we just need to convert it to f and g. Note that it has a few extra terms since it didn't stop being unique until after the solution was found. Luckily n\*d is 0 in that case so we can use that to map it to a space. The below code is implicitly done via a map. ``` = `$ *@$ subscript using signum of n*d "fg " into this list (0 is the last since 1 based). ``` Call it like `nibbles filename.nbl 1 3` (Nibbles isn't on TIO yet). Note that this will also output 4 spaces after the answer, you could remove it by doing a filter, this would add two nibbles or 1 byte. [Answer] # [Haskell](https://www.haskell.org/), ~~44~~ 42 bytes ``` 0#d=[] n#d|n*d<0='g':(-d)#n|m<-n-d='f':m#d ``` adaption of the python solution, using guards. Ungolfing barely changes it, just adding whitespace: ``` 0#d = [] n#d | n*d<0 = 'g':(-d)#n | m<-n-d = 'f':m#d ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/30A5xTY6litPOaUmTyvFxsBWPV3dSkM3RVM5rybXRjdPN8VWPU3dKlc55X9uYmaegq1CQWlJcEmRgoqCpbL5/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online") -2 Bytes thanks to xnor, TIO link also thanks to xnor [Answer] # JavaScript (ES6), 90 bytes A naive algorithm trying all sequences of length \$k\$, starting with \$k=0\$ and incrementing \$k\$ until a solution is found. Expects `(n)(d)`. Returns an empty array instead of an empty string. ``` n=>F=(d,k)=>(g=(k,o=[],N=n,D=d)=>k--?g(k,o+'f',N-D,D)||g(k,o+'g',-D,N):!N&&o)(k)||F(d,-~k) ``` [Try it online!](https://tio.run/##bZDLDoIwEEX3fkXdQCe2PsAYNKluiEt@wLgwQhsstkSIiYnx17EI4oM2s7pnemfunA7XQ3G8pHlJlY6TirNKsfWW4ZhIYGssGJZEs92eREyRkMVGlJRuRC2PXO6SiIYkhPu9VYRLjBDBahg5jgYsDdoaN/qQUB21KnSWjDMtMMdoBhj5AGgyQVzwugZ/HT7UXU1HnwaGeh3tYWNPW3thwd7v9B6fGr5s@C455@UNFeUlVWJvmdMtaRvSBbAt6HUL/lH6RW2nWRjn@dvZ8v0rnv22wSffK3/zqic "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 44 bytes Assuming [loopy walt's method](https://codegolf.stackexchange.com/a/240808/58563) is valid (and it most probably is). Expects `(n,d)`. ``` f=(n,d)=>n*d<0?'g'+f(-d,n):n?'f'+f(n-d,d):'' ``` [Try it online!](https://tio.run/##bZBNDoIwEIX3nmJ2bbWVP2OQiBzEuCCUNhhsCRATT48iWCJtM5vJN5333tzzZ94VbdX0TGleDoNIsaKcpBe15Wc/QxLtBGacKpKoDImxU5@WkwShodCq03W5r7XEAkNAISIEPA@EFGNtVgMRhWAesGFMITTQogFl827poOGfsoV9CqcJX8tH07@g69tKyZstYvw5FIx1h7fQeFtBtkDXRY4UDr@1js9LLvdBYxPsm3t6wxs "JavaScript (Node.js) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 104 bytes ``` n=1;d=3;o;main(){if(d<0){n=-n;d=-d;}while(n){if(n<0){o=d;d=-n;n=o;printf("g");}else{n-=d;printf("f");}}} ``` [Try it online!](https://tio.run/##NclNCoMwEAbQu7hKFgMVl9M5jOSvgfRLqYKLkKs7mkK37zlKzqlCZvaycOX3mmFsy9H458M2COEe8tyPVy7B4HcYV8WPAkMqf74ZezRTmiz3ULbQQPf/OQ7uXfV0saxpUzou "C (gcc) – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 52 bytes ``` t(n,d)=if(n/d>0,Str(f,t(n-d,d)),n,Str(g,t(-d,n)),"") ``` [Try it online!](https://tio.run/##PctBCsMgEAXQq3xcKYw0JqWki@YSXYYspJIgiEhw09PbUUxX8@fN/GRPr49USpaRnHr5XcabWwZ651PuxKodu6LY5GBhiAxCqGJTCl9poRek08fMUdRF4GNDkJlg@RPragjTxmEimDpnwlgnu26HsT8MhGc/mO7memwN/U8Pwr3J1Z1rd1MoPw "Pari/GP – Try It Online") A port of [@loopy walt's Python answer](https://codegolf.stackexchange.com/a/240808/9288). Shorter (46 bytes) if we can take a rational number as input: ``` t(r)=if(r>0,Str(f,t(r-1)),r,Str(g,t(-1/r)),"") ``` [Try it online!](https://tio.run/##JYqxCsMwDER/RXiyQEJRUkoyND/RsXTwkmAoxQgv/XpHdqe79@5Kssxnaa1Gw0c@ou0TPavFg9ywIpINPp1ZxVyEgC2V8vnFBLxDsfytXkOHAF79Ay@VhWARJVhlJlBh57nLSbbO2lHH4jv/4y437@O2yvZGaBc "Pari/GP – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞ε„fg©sã}˜õš.Δ®'>„z(‚‡0s.VI`/α₄z‹ ``` Naive brute-force approach. Outputs in reversed order. If this is not allowed, a trailing `}R` will have to be added and it would be 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) instead, making the approach below 1 byte shorter. [Try it online](https://tio.run/##AUcAuP9vc2FiaWX//@KIns614oCeZmfCqXPDo33LnMO1xaEuzpTCric@4oCeeijigJrigKEwcy5WSWAvzrHigoR64oC5//9bMSwzXQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXo/0cd885tfdQwLy390Mriw4trT885vPXoQr1zUw6tU7cDildpPGqY9ahhoUGxXlhEgv65jY@aWqoeNez8X6vzPzraUMc4VifaWMcQSFroGAFJQx1dkJARWMJAxxIsZAgWMYRIg1TpQmkzHRMQD6LaAqg6FgA). A port of [*@loopyWalt*'s second Python answer](https://codegolf.stackexchange.com/a/240808/52210) is **34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**, but it outputs in the correct order: ``` "ÐPdi¬ĀiÆ0ǝ®.V'fìëõë`s(‚®.V'gì"©.V ``` [Try it online](https://tio.run/##yy9OTMpM/f9f6fCEgJTMQ2uONGQebjM4PvfQOr0w9bTDaw6vPrz18OqEYo1HDbPAYumH1ygdWqkX9v9/tKGOcSwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/pcMTAlIyD6050pB5uM3g@NxD6/TC1NMOrzm8@vDWw6sTijUeNcwCi6UfXqN0aKVe2H@d/9HRhjrGsTrRxjqGQNJCxwhIGurogoSMwBIGOpZgIUOwiCFEGqRKF0qb6ZiAeBDVFkDVsQA). **Explanation:** ``` ∞ # Push an infinite positive list: [1,2,3,...] ε # Map over each integer: „fg # Push string "fg" © # Store it in variable `®` (without popping) s # Swap so the current integer is at the top ã # Get the cartesian product }˜ # After the map: flatten the list of lists õš # Prepend an empty string .Δ # Then find the first value which is truthy for: ® # Push "fg" from variable `®` '> '# Push string ">" „z( # Push string "z(" ‚ # Pair them together: [">","z("] ‡ # Transliterate all "f" to ">" and "g" to "z(" 0 # Push 0 s # Swap so the string is at the top again .V # Evaluate as 05AB1E code: # `>`: Increase the value by 1 # `z(`: `z` will push 1/value, `(` will negate it I # Push the input-pair: [n,d] ` # Pop and push `n` and `d` separated to the stack / # Divide `n` by `d` α # Get the absolute difference between the two values ‹ # Check if this is smaller than ₄z # 1/1000 # (`α₄z‹` can't be `Q` due to floating point inaccuracies) # (after which the result is output implicitly) ``` ``` "..." # Push the recursive string defined below © # Store this string in variable `®` (without popping) .V # Evaluate it as 05AB1E code Ð # Triplicate the current pair [n,d] # (which will be the implicit input in the first call) i # If P # n*d (product of the pair) d # is >= 0: i # If ¬ # n (without popping the pair) Ā # is not 0: Æ # Push n-d (reduce by subtracting) ǝ # And insert this n-d back into the pair 0 # at index 0: [n-d,d] ®.V # Then do a recursive call 'fì '# And prepend "f" to that ë # Else: õ # Push an empty string "" ë # Else: ` # Pop and push `n` and `d` separated to the stack s # Swap the two values on the stack ( # Negate `n` ‚ # Pair them back together: [d,-n] ®.V # Then do a recursive call 'gì '# And prepend "g" to that # (after which the result is output implicitly) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~65~~ ~~62~~ ~~52~~ 48 bytes ``` NθNη¿θWφ«≔θφ≔ηζ⊞υωP←⍘LυgfF⮌↨Lυ²¿κ≧⁻ζφ«≔ζε≔φζ≔±εφ ``` [Try it online!](https://tio.run/##TY7LigIxEEXX9lcUrqogLnR2M6txJ9gizhdEqTyYGNs8FBz89kyC3eDyHG5R52RkOF2kK2Xjh5x2@XzkgFf66t7ZVLYKqoe7sY4BFcFfN/uO0WqPVwGqLiY0Ah4N9zkazALuDfrskh2C9Qk/t6ySgLWM/JOq0bhlr1PdkoC5VnNqB@oSAA984xAZ2/Z9tSIiaEW/BL0cXo8PVpuEvfU51oKxiV3kljrFVc/NT6zG2Il3rGViZBrvn92zlCV8lMXN/QM "Charcoal – Try It Online") Link is to verbose version of code. Feels like it should be a bit shorter. Explanation: ``` NθNη ``` Input `n` and `d`. ``` ¿θWφ« ``` Do nothing if `n=0`, otherwise loop until a reverse path to zero is found. (This loop uses the variable `f` which is predefined to `1000`, thus ensuring the loop happens at least once; it saves a byte over saving `n` and using `while (n)`.) ``` ≔θφ≔ηζ ``` Make new copies of `n` and `d`. ``` ⊞υω ``` Increment the length of the predefined empty list. ``` P←⍘Lυgf ``` Replace the canvas with the length interpreted as a base 2 string of `f`s and `g`s (with `f=1` and `g=0`). The string is reversed so that the last letter is always `f`. ``` F⮌↨Lυ² ``` Loop over the base 2 digits in reverse. ``` ¿κ≧⁻ζφ ``` For `1`s undo the `f` step. ``` «≔ζε≔φζ≔±εφ ``` Otherwise undo the `g` step. Switching to undoing steps saved me 10 bytes. It's possible that deciding whether to undo an `f` or `g` step based on the sign of the current fraction suffices to produce a minimal result. If that's true then the solution would only be 31 bytes: ``` NθNηWθ¿›×θη⁰«f≧⁻ηθ»«g≔ηζ≔θη≔±ζθ ``` [Try it online!](https://tio.run/##TY5BCsIwEEXX7SmGriZQQXHpypW4aBHxArFMk0Aa2yRVqHj2OFbBLh//v/nTaOmbm7QpHV0/xnrsruRxELt8yZr5oY0l4AhMC3jwJCMnF9NRwKEELUpYCwHPPDt54yIWbcFWVsl@H4JR7myUjlgZNwZul/DZeAHZQAtHzc5XQC5NC5xH/liT4g9wEr9TKW1gm1Z3@wY "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` NθNη ``` Input `n` and `d`. ``` Wθ ``` Repeat until `n=0`. ``` ¿›×θη⁰« ``` If `n/d` is positive, then... ``` f≧⁻ηθ ``` ... output an `f` and subtract `d` from `n`. ``` »« ``` Otherwise... ``` g≔ηζ≔θη≔±ζθ ``` ... output a `g`, switch `n` and `d`, and negate `n`. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~18~~ 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ÿ☺╨K▼▓¡s'↓♫[╣♥╬╩ ``` [Run and debug it](https://staxlang.xyz/#p=9801d04b1fb2ad7327190e5bb903ceca&i=+1%2F3%0A+3%2F1%0A+8%2F2%0A+1%2F-3%0A+2%2F3%0A+0%2F9%0A+1%2F1%0A+2%2F1%0A+1%2F-2%0A-1%2F-2%0A+6%2F4%0A-2%2F3%0A+8%2F9&a=1&m=2) Pretty convenient with the rational type. [Answer] # Python3, 192 bytes: ``` lambda n,d:f([(0,n/float(d),'')]) f=lambda d:r[0][-1]if(r:=[i for i in d if round(i[0],4)==round(i[1],4)])else f([j for a,b,c in d for j in[(a+1,b,'f'+c)]+([(-1/(1.0*a),b,'g'+c)]if a else[])]) ``` [Try it online!](https://tio.run/##XY9NbsMgEIX3OQU7D/W48cRV5VriJJQFCcEhcrFFnEVP70LaSNAd3@P9wPK9Xmbf9UvYRvG5TfrraDTzaAYLElr0ezvNegXDsaq44jsr/jxmCLJVsiHlLIRBSMfsHJhjzjPDnGVhvnsDLprwjQvxREqo@Hm6nVncuD5SGo94@k0mvMajBF1TlCtb1Seu6vichvZAr@2L5kkfH3oc0iyVSRVbtyU4v8IIhB3nuyd1SBn1eMiIsMmthyLY4kdhpcJJZU3e2vzj9/jp7LZc6dPK9gM) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 48 bytes Basic bruteforce approach, expects index origin 0. ``` f←-⍨\⍢⌽ g←-@0⌽ ⌽o⊣1+⍣{0=⊃⍎⍕t,⍨↓⍪o∘←'gf'[⊤⍵]}⍱t←⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXI862jP@pwGZuo96V8Q86l30qGcvVzqI72AAYgJx/qOuxYbaj3oXVxvYPupqftTb96h3aokOUP2jtsmPelflP@qYAdSgnp6mHv2oa8mj3q2xtY96N5YAxYD2/Afa8D@DS0HBUEFBwZgLxDIGsgzBLAsgy4gLKntoPUTaCK7QAMiyhElDtRjBWWAtYN2H1iPYCmZABSYQUYRJIIssAQ "APL (Dyalog Extended) – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), ~~59~~ \$\cdots\$ ~~53~~ 52 bytes ``` z;f(n,d){z=n*d>=0;n&&f(z*n-d,z?d:n,putchar(103-z));} ``` [Try it online!](https://tio.run/##dVHhaoMwEP7fpziElmgTZusYXTO7X3uKtQwxiRO6a6mOFYuvPnfRRCZjweTuvu/uy@XMRX7MsOi6RhqGXIW3JsVI7dJY4mJhWBOhULx5Vlvk5886f88ubBUnoglD2XYl1vCRlchCuM2AlgVqXdVv@HqAFG4rDgmHDQdy1hxi79ApaD@QoWjTymm1GqoTny6SXuexj1dDkd33A@zKbXMR6OtZ57V2EoEpjP0CDoEZTW8LH3unD4YMx3t6AIsR/0W5FbgezOkCzL6jRKWv1EEsnfsEVdnok2G@wfDOAdGISFgu@2w/Tz8VJCU3154/yAmtPK3@0OcLJRgWzNeKAx0gdrC3T0UOdOGYZ//@BHDTJOVxov9p74M9vrikLanPK4vQHdrptbO2@87NMSuqTnz9AA "C (clang) – Try It Online") *Port of [loopy walt](https://codegolf.stackexchange.com/users/107561/loopy-walt)'s [Python answer](https://codegolf.stackexchange.com/a/240808/9481).* *Saved ~~5~~ 6 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* *Saved a byte thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!!* Inputs integers \$n\$ and \$d\$. Outputs string of `f`'s and `g`'s that represents a shortest path of iterated maps from \$0\$ to \$\frac{n}{d}\$. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 139 bytes ``` (m=1;f=If[#3<m,If[#1!=0,Do[#0[{#1-1,-1/#1}[[k]],Append[#2,k],#3+1],{k,2}],Throw@#2]]&;While[(r=Catch[f[#1/#2,{},1]])==Null&&#1!=0,m+=1];r)& ``` [Try it online!](https://tio.run/##RY3BCoJAFEX3/UUMDIpP9OmmsAGjNm2iRdDi8RaDKSM6KmK0EL/dlIhWl8Pl3Gv1YHKrhzLTs1GzYxUmhboUJOKDhTVxq0I4tyRCGgX6CD4GAieiihmOXZc3TxIRVAwi9pBhrCCaGO6mb9@piJhl8jBlnZPTq5MeMkPraLAo4wTI7Cp1fdW1lN8n6ynkpHflfOvLZkgNIcS8@cEO9n8Il2b@AA "Wolfram Language (Mathematica) – Try It Online") Reverse recursive approach. We start with given fraction and recursively apply reverse operations until we reach `0`. Output is array with `1` for \$f\$ and `2` for \$g\$ or `Null` if `n==0`. The code is not optimal (the same results are used several times), but optimization will increase the length of the code. I'll try golfing it more, sure it's possible. Ungolfed version self-explained: ``` Clear[recurse, main]; recurse[x_, arr_, i_, max_] := If[i < max, If[x != 0, Do[recurse[{x - 1, -1/x}[[k]], Append[arr, k], i + 1, max], {k, 2}], Throw@arr ]]; main[n_, d_] := Module[{max = 1, res = Null}, While[res == Null && n != 0, res = Catch[recurse[n/d, {}, 1, max]]; max += 1 ]; res]; ``` [Answer] # [Scala](https://www.scala-lang.org/), ~~83~~ 78 bytes Saved 5 bytes thanks to the comment of @ceilingcat --- Golfed version. [Try it online!](https://tio.run/##LcsxCgIxEIXh3lMM22RGI2glLlpYWlh5gpiZLJEwG0wKQTx73IDNg5@PV7xLrs2Pp/gKNxcV5F1FucAlZ/g0lgAedbxqtdyXxnt9RZ3OMaCu@bQjM5mNxy1bJUlF4A97GobeJnTWxZkaQF7ONSl6PFo4EK2@7Qc) ``` def c(n:Int,d:Int):String=if(n*d<0)'g'+c(-d,n)else if(n*d<1)""else'f'+c(n-d,d) ``` Ungolfed version. [Try it online!](https://tio.run/##VY9Nb8IwDEDv@RVPXNqMInGbhlakHXfgxA9AoUmhqPWqNUKVoL@9pNnEx8W2nOfnuCtMbcbxZ39yhWdjKsH13ont@GpbLgqsKwlUkcqKb/EZNma9Yut/KzmQRwyqklTIc5Zcr9hYaWaz@Ojqzv1zTNgbVtMYXxzvXcKaAPWTqOczaPI1ySFh/rd/YTNEv8K7iXkI4GxqmvAlYYF96ifl3dOEEx6aQT3nKQ4qhDac5mtJ48RHxrvWalDjeAM) ``` object Main extends App { def calc(n: Int, d: Int): String = { if (n == 0 || d == 0) "" else { (n * d) match { case x if x < 0 => 'g' + calc(-d, n) case _ => { val m = n - d 'f' + calc(m, d) } } } } println(calc(9, 7)) } ``` [Answer] # SAS 101, "*Generating Ratinal Numbers in SAS 4GL - 101*" :-D Inspired by [loopy walt](https://codegolf.stackexchange.com/questions/240806/iterate-your-way-to-a-fraction/240808#240808) answer I decided to make SAS 4GL version. The code: ``` data;set;do while(n);t=d;if(n*d<0)then do;put"g"@;d=n;n=-t;end;else do;put"f"@;n=n-d;end;end;put;run; ``` SAS is quite "talkative" by all those `if`s, `then`s, `do`s, `end`s and `else`s so, even tough I did my best to "boil" bytes down, I ended up on 101. Explanation: I don't like stack overflows so instead recursion I went with iterative approach. It is SAS 4GL so the the standard input in form of a SAS dataset is expected (I added some extra test cases): ``` data i; input n d; cards; 1 3 3 1 16 4 8 2 4 1 1 -3 2 3 0 9 0 3 0 1 1 1 2 1 1 -2 -1 -2 6 4 -2 3 8 9 17 42 17 -42 17 303 42 303 99 100 990 1000 999 1002 999 -1002 1 11111 1 2 2 4 4 8 ; run; ``` Human readable code: ``` data _null_; /* 0) */ set i; /* expect input data set 1) */ put n= d= @; /* added just for printing */ do while(n); /* while numerator is not 0 */ x=d; if (n*d<0) then /* for negative print "g", then negate and flip fraction */ do; put "g" @; d = n; n = -x; end; else /* for positive print "f", then substract 1 from fraction */ do; put "f" @; n = n-d; end; end; put; /* add new line character at the end of printout 2) */ run; ``` *Footnotes:* *0) turn of production of output dataset* *1) the `set` statement takes as input the last created data set, so code generating dataset `i` has to be executed just before.* *2) the last `put;` can be skipped if the input dataset has only 1 observation what reduces length by 4 bytes to 97.* Log output: ``` n=1 d=3 fgffgff n=3 d=1 fff n=16 d=4 ffff n=8 d=2 ffff n=4 d=1 ffff n=1 d=-3 gfff n=2 d=3 fgfff n=0 d=9 n=0 d=3 n=0 d=1 n=1 d=1 f n=2 d=1 ff n=1 d=-2 gff n=-1 d=-2 fgff n=6 d=4 ffgff n=-2 d=3 gffgff n=8 d=9 fgfffffffff n=17 d=42 fgffgffffgffgffgffgffgffgffgff n=17 d=-42 gfffgffgfffffffff n=17 d=303 fgffgffgffgffgffgffgffgffgffgffgffgffgffgffgffgffgfffgffgffgffgfffgff n=42 d=303 fgffgffgffgffgffgffgffffffgfff n=99 d=100 fgffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff n=990 d=1000 fgffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff n=999 d=1002 fgf[ 332 "f" hidden for readability ]f n=999 d=-1002 gff[ 331 "gff" hidden for readability ]gff n=1 d=11111 f[ 11109 "gff" hidden for readability ]gff n=1 d=2 fgff n=2 d=4 fgff n=4 d=8 fgff NOTE: There were 29 observations read from the data set WORK.I. NOTE: DATA statement used (Total process time): real time 0.02 seconds cpu time 0.03 seconds ``` *A small comment at the end:* We are in a group of functions with composition. Function: \$ z(x) = g(f(g(f(g(x))))) = x{-}1 \$ is an inverse of \$f\$ (\$f(z(x))=x\$, \$z(f(x))=x\$) and \$g\$ is inverse of itself (\$g(g(x))=x\$) So a path from \$0\$ to \$\frac{n}{d}\$ (assuming frac is reduced) of the form: $$ \frac13 = f(g(f(f(g(f(f(0))))))) $$ can be "walked back" using inverses of \$f\$ and \$g\$ $$ 0 = z(z(g(z(z(g(z(\frac13))))))) $$ Which is "base" for the algorithm: "*1) take a fraction, 2) if the fraction is negative "flip it"(negate and inverse) else subtract 1 from it, 4) if fraction is 0 stop else got to 1)*" ]
[Question] [ Write a program that goes through a string of non-whitespace characters (you may assume that they are digits `0` to `9`, but nothing in the way they are to be processed depends on this) and adds spaces according to the following rules. 1. Let the current token be the empty string, and the previously emitted tokens be an empty set. 2. Iterate through the characters of the string. For each character, first append the character to the current token. Then if the current token is not already in the set of previously emitted tokens, add the current token to that set and let the new current token be the empty string. 3. If when you reach the end of the string the current token is empty, output the previously emitted tokens in order of emission, separated by a space character. Otherwise output the original string verbatim. **Input** The input to the STDIN should be a sequence of digits. **Output** The program should print the result as specified in step 3. **Samples** *Sample inputs* ``` 2015 10101010 4815162342 101010101010 3455121372425 123456789101112131415 314159265358979323846264338327950288419716939937 ``` *Sample outputs* ``` 2 0 1 5 10101010 4 8 1 5 16 2 3 42 1 0 10 101 01 010 3 4 5 51 2 1 37 24 25 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 3 1 4 15 9 2 6 5 35 8 97 93 23 84 62 64 33 83 27 95 0 28 841 971 69 39 937 ``` --- This is code golf, so standard CG rules apply. Shortest program in bytes wins. (Please request any clarifications in the comments. I'm still new to this. Thanks!) [Answer] # [Retina](https://github.com/mbuettner/retina), ~~68~~ 61 bytes ``` +`\b(\w+?)(?<!\b\1 .*)(\w+)$ $1 $2 (?=.* (.+)$(?<=\b\1 .+)) <empty> ``` `<empty>` is an empty line. Note the trailing space on line 3. You can run the above code from a single file with the `-s` flag. ## Explanation ``` +`\b(\w+?)(?<!\b\1 .*)(\w+)$ $1 $2 ``` This first step implements rules 1 to 6. It is a regex substitution which is applied repeatedly until the string stops changing (that's what the `+` is for). In each step we add a single space into the string from left to right (following the rules of the challenge). The regex matches the shortest string of digits which hasn't appeared in the already processed part of the string. We ensure that we're looking at a prefix of the remaining string with the word boundary `\b` and checking that we can reach the end of the string without passing spaces with `(\w+)$`. The latter also ensures that we only perform one replacement per step. ``` (?=.* (.+)$(?<=\b\1 .+)) <empty> ``` This matches any space (which is at the end of the regex), provided that the last segment of the string is the same as any other segment in the string, and replaces them with the empty string. That is, we undo the first step if it resulted in an invalid final segment, implementing rule 7. [Answer] ## Pyth, ~~24~~ 23 bytes ``` VzI!}=+kNYaY~k"";?kzjdY ``` Try it out [here](https://pyth.herokuapp.com/?code=VzI%21%7D%3D%2BkNYaY~k%22%22%3B%3FkzjdY&test_suite=1&test_suite_input=2015%0A10101010%0A4815162342%0A101010101010%0A3455121372425%0A123456789101112131415%0A314159265358979323846264338327950288419716939937&debug=0). ``` VzI!}=+kNYaY~k"";?kzjdY Implicit: z=input(), k='', Y=[], d=' ' Vz ; For N in z: =+kN Append N to k I!} Y Is the above not in Y? aY k Append k to Y ~k"" After append, reset k to '' ?k Is k truthy (i.e. not '') z Print original input jdY Otherwise print Y joined on spaces ``` Thanks to @FryAmTheEggman for saving a byte :o) [Answer] # Pyth, 22 bytes ``` faW!}=+kTYY~kdz?tkzsY ``` Leading space is important. [Answer] # Python 3, 92 bytes ``` i,n,*o=input(),"" for c in i:n+=c;o,n=[o+[n],o,"",n][n in o::2] print([" ".join(o),i][n>""]) ``` Basically a heavily golfed version of @Willem's solution. [Answer] ## Python 3, ~~100~~ 99 bytes ``` o=[];n="";i=input() for c in i: n+=c if not n in o:o.append(n);n="" print(i if n else" ".join(o)) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 91 bytes ``` :_:_{h:0<|bhN,?hh:NrcH,?hB(l1,-1=A;BbA),?rhL:I(mH:Ar:[L]c:1&;:[H]:\"~w \"w,L:[H]c:_:Ar:1&)} ``` This made me realize that there's a lot of things about the syntax I need to change... ### Explanation ``` :_:_ § Creates a list [Input,[],[]] {...} § Define a new predicate between the brackets and call it with the previous list as input h:0< § If the head of the input is negative, stop | § Else bhN, § Second element of Input is called N ?hh:NrcH, § N concatenated with the first element of Input is H ?hB(l1,-1=A;BbA), § Remaining digits A are either -1 if there's only one digit left or all the digits but the head otherwise ?rhL:I § List of used integers is called L ( mH:Ar:[L]c:1& § If H is already in L, call the predicate with input [A,H,L] ; § Else :[H]:\"~w \"w, § Print H followed by a space L:[H]c:_:Ar:1& § Call the predicate with input [A,[],M] where M is L with H appended to it ) ``` [Answer] # CJam, 26 bytes ``` LLq{+_a2$&{a+L}|}/:X+X!S** ``` [Test it here.](http://cjam.aditsu.net/#code=LLq%7B%2B_a2%24%26%7Ba%2BL%7D%7C%7D%2F%3AX%2BX!S**&input=314159265358979323846264338327950288419716939937) ## Explanation ``` L e# Push an empty array to keep track if the previous segments. L e# Push an empty array to build the current segment. q{ e# For each character in the input... + e# Add it to the current segment. _a2$& e# Duplicate and check if it's already in the segment list. { e# If not... a+L e# Add it to the list and push a new empty array for the next segment. }| }/ :X+ e# Store the trailing segment in X and add it's *characters* to the list. e# For valid splittings, this trailing segment will be empty, so that the e# list remains unchanged. X! e# Push X again and take the logical NOT. S* e# Get that many spaces, i.e. 1 for valid segments and 0 otherwise. * e# Join the list with this string between elements. ``` [Answer] # JavaScript (ES6), 109 My output format is not exactly the same of the output samples in the questioin (there is a leading space). I don't see that as a flaw, as the output format is not specified (just *The program should print the number after the number...*) Test running the snippet below in a EcmaScript 6 compliant browser. Developed with Firefox, tested and running on the latest Chrome. ``` /* Test: redirect console.log */ console.log=x=>O.innerHTML+=x+'\n'; F=s=>{for(z=s,b=l=o=' ';s[+l];)~o.search(b+(n=s.slice(0,++l)+b))||(s=s.slice(l),o+=n,l=0);console.log(s?z:o)} /* Test cases */ test = [ '2015', ,'10101010' ,'4815162342' ,'101010101010' ,'3455121372425' ,'123456789101112131415' ,'11312123133' ,'314159265358979323846264338327950288419716939937'] test.forEach(t=>{console.log('\n'+t);F(t)}) ``` ``` <pre id=O></pre> ``` [Answer] # GNU sed, 83 77 73 71 bytes (Score one extra because we require `-r` flag) ``` h s/./&_/ : /(\b[^ ]+).*\b\1_/{ s/_(.)/\1_/ t g } s/_(.)/ \1_/ t s/_// ``` The inner loop tests for a repeated sequence and appends characters as needed until a unique number appears after the separator `_`. The outer loop moves `_` along. Expanded, annotated version: ``` #!/bin/sed -rf # Stash original in hold space h # Add separator s/./&_/ : # If current candidate is a duplicate, ... /(\b[^ ]+).*\b\1_/{ # ...then attempt to lengthen it ... s/_(.)/\1_/ # ... and repeat if we succeeded, ... t # ... otherwise, restore original string g } # Insert a space, and move our separator along s/_(.)/ \1_/ t # Remove the separator if we still have it s/_// ``` [Answer] # Ruby, 57 + 1 = 58 bytes ``` s='' l={} $_.chars{|c|l[s<<c]||=s=''} l[s]||$_=l.keys*' ' ``` Uses the command line flag `-p` (or `pl` if your input has a trailing newline). Exploits several traits of Ruby Hash dictionaries: you can safely mutate the string you used to define a key without it changing the key (which doesn't work for other mutable types), `.keys` returns the keys in the order they were inserted, and the `[]||=` operator provides a terse way of branching on whether a given key is already there. [Answer] # Haskell, 105 bytes `f` does it. ``` e""s""=unwords s e t s""=concat s++t e t s(c:r)|t&c`elem`s=e(t&c)s r|0<1=e""(s&(t&c))r a&b=a++[b] f=e""[] ``` [Answer] # PHP - 148 bytes Cool challenge, lots of fun! ``` $x=fgets(STDIN);$w=array();$k='';$l='';for($i=0;$i<strlen($x);$i++){$k.=$x[$i];if(!isset($w[$k])){$l.=$k.' ';$w[$k]=1;$k='';}}echo strlen($k)?$x:$l; ``` ]
[Question] [ > > Disclaimer: The story told within this question is entirely fictional, and invented solely for the purpose of providing an intro. > > > I am an evil farmer, and to drive up the price of wheat in my area, I've decided to burn the fields of all the farmers around me. I would really like to see the fields go up in flames (so I can use my evil laugh and rub my hands together with glee), but I also don't want to be caught watching, so I need you to simulate the field being incinerated for me. ## Your Task: Write a program or function that takes as input a field, and returns the stages of it burning until the entire field is ash. A specific section of the field that is on fire is represented by an integer representing the intensity of the flame. A fire starts at "1" and moves on to "2" and then "3", and so on. Once a fire reaches "4", it catches any directly (not diagonally) adjacent areas that are flammable on fire. Once it reaches "8", it burns out on the next iteration, and turns into ash, represented by an "A". When an area has not yet been touched by fire, it is represented by a "0". For example, if the field looks like this: ``` 100 000 ``` Your program should output this: ``` 100 000 200 000 300 000 410 100 520 200 630 300 741 410 852 520 A63 630 A74 741 A85 852 AA6 A63 AA7 A74 AA8 A85 AAA AA6 AAA AA7 AAA AA8 AAA AAA ``` If you wish, you may replace the above symbols with any set of symbols you choose, as long as they are consistent and distinct from each other. ## Input: The starting position of the field, in any standard form, such as a newlined-delimated string as above. ## Output: The field in every iteration as it burns, either as an array, or as a string delimited by some character. ## Test Cases: ``` 0301 000A 555 | v 0301 000A 555 1412 010A 666 2523 020A 777 3634 030A 888 4745 141A AAA 5856 252A AAA 6A67 363A AAA 7A78 474A AAA 8A8A 585A AAA AAAA 6A6A AAA AAAA 7A7A AAA AAAA 8A8A AAA AAAA AAAA AAA ``` ## Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes wins! [Answer] # [Python 3](https://docs.python.org/3/), 232 bytes ``` def f(j): k=[[int(min(9,j[x][y]+(j[x][y]>0)or 3in(lambda k,x,y:[k[i][j]for i,j in[[x-1,y],[x+1,y],[x,y-1],[x,y+1]]if(-1<i<len(k))and(-1<j<len(k[i]))])(j,x,y)))for y in range(len(j[x]))]for x in range(len(j))] if k!=j:print(k);f(k) ``` [Try it online!](https://tio.run/##XVDBboMwDD2Xr/BO2CKVinoqLZP2HVEOmUi2BJoi1m3k65lduHRSZOe9Z728eMz3z1s6LiO0ME4h3Yuic369op0mm6kpdv42wXT7hZDgwTH14NzgrkKyJtQu@JVqWzg1MGL5VipwqWPzsiSZcMOXE0XGnqURuXJZ5H2Pkd@FvtVaglxDwpOKejY6mwq3y@uBOMORtcFe3zsLvZpVbnSvg9HRSMCgIufTet7XKhul52rrKu/rtVe1McHjvr6Ey@AS9kQ2dYLjitmNyBBGcSci8c2PX9v04VBmJBDPiDL/U5gugPfSv7SxWdfa09lzWVbk0f3YAUMav@/I9rRofVCwHaNgQ/UTOhjzBw "Python 3 – Try It Online") -3 bytes thanks to officialaimm by merging the other lambda into `f` (looks messy but saves bytes and that's all we care about) -8 bytes thanks to Mr. Xoder -26 bytes thanks to ovs -6 bytes thanks to ppperry [Answer] # JavaScript (ES6), ~~217~~ ~~210~~ ~~207~~ ~~204~~ ~~193~~ ~~192~~ 190 bytes *Saved 2 bytes thanks to @Shaggy's suggestion of using `9` as `A`.* ``` f=F=>[F,...(t=[],y=0,g=x=>(r=F[y])?(x||(t[y]=[]),r[x]+1)?(t[y][x]=r[x]<8?r[x]+(r[x]>0|[r[x-1],r[x+1],F[y-1]&&F[y-1][x],F[y+1]&&F[y+1][x]].includes(3)):9,g(x+1)):g(0,y++):t)(0)+""!=F?f(t):[]] // test code test=s=>{ var test = document.querySelector("#in").value.split`\n`.map(e => Array.from(e).map(e => parseInt(e))); var out = f(test); document.querySelector("#out").innerHTML = out.map(e => e.map(e => e.join``).join`\n`).join`\n\n`; };window.addEventListener("load",test); ``` ``` <textarea id="in" oninput="test()">0301&#10;0009&#10;555</textarea><pre id="out"></pre> ``` Uses `9` instead of `A`. Input as a 2D array of integers. Output as an array of such arrays. [Answer] # [Simulating the World (in Emoji)](http://ncase.me/simulating/), 1407 bytes? Don't you love using an [explorable explanation](http://explorabl.es/) as a programming language? The downside to this is there's usually not a very well defined program, so in this case, I'm using the JSON it exports. (if you have any better ideas, let me know) ``` {"meta":{"description":"","draw":1,"fps":1,"play":true},"states":[{"id":0,"icon":"0","name":"","actions":[{"sign":">=","num":1,"stateID":"4","actions":[{"stateID":"1","type":"go_to_state"}],"type":"if_neighbor"}],"description":""},{"id":1,"icon":"1","name":"","description":"","actions":[{"stateID":"2","type":"go_to_state"}]},{"id":2,"icon":"2","name":"","description":"","actions":[{"stateID":"3","type":"go_to_state"}]},{"id":3,"icon":"3","name":"","description":"","actions":[{"stateID":"4","type":"go_to_state"}]},{"id":4,"icon":"4","name":"","description":"","actions":[{"stateID":"5","type":"go_to_state"}]},{"id":5,"icon":"5","name":"","description":"","actions":[{"stateID":"6","type":"go_to_state"}]},{"id":6,"icon":"6","name":"","description":"","actions":[{"stateID":"7","type":"go_to_state"}]},{"id":7,"icon":"7","name":"","description":"","actions":[{"stateID":"8","type":"go_to_state"}]},{"id":8,"icon":"8","name":"","description":"","actions":[{"stateID":"9","type":"go_to_state"}]},{"id":9,"icon":"A","name":"","description":"","actions":[]}],"world":{"update":"simultaneous","neighborhood":"neumann","proportions":[{"stateID":0,"parts":100},{"stateID":1,"parts":0},{"stateID":2,"parts":0},{"stateID":3,"parts":0},{"stateID":4,"parts":0},{"stateID":5,"parts":0},{"stateID":6,"parts":0},{"stateID":7,"parts":0},{"stateID":8,"parts":0},{"stateID":9,"parts":0}],"size":{"width":9,"height":9}}} ``` Try it [here](http://ncase.me/simulating/model/?remote=-Kr2X939XcFwKAunEaMK) or here: ``` <iframe width="100%" height="450" src="http://ncase.me/simulating/model/?remote=-Kr2X939XcFwKAunEaMK" frameborder="0"></iframe> ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~103~~ ~~96~~ 88 bytes ``` ^ ¶ ;{:` T`0d`d (?<=¶(.)*)0(?=4|.*¶(?<-1>.)*(?(1)_)4|(?<=40|¶(?(1)_)(?<-1>.)*4.*¶.*)) 1 ``` [Try it online!](https://tio.run/##K0otycxL/P8/juvQNi7raqsELq6QBIOUhBQuDXsb20PbNPQ0tTQNNOxtTWr0tIBcextdQzugmIa9hqFmvKZJDUiZiUENSAosAldhAlKvp6WpyWX4/7@BsYEhl4GBgSWXqakpAA "Retina 0.8.2 – Try It Online") Uses `9` for ash; this can be changed at a cost of 4 bytes using `T`1-8`2-8A`. Edit: Saved 6 bytes thanks to @MartinEnder. Explanation: ``` ^ ¶ ``` Add a separator so that the outputs don't run into each other. (Also helps when matching below.) ``` ;{:` ``` Don't print the final state (which is the same as the previous state which has already been printed). Repeat until the pass does not change the state. Print the current state before each pass. ``` T`0d`d ``` Advance the intensity of all the fire. ``` (?<=¶(.)*)0(?=4|.*¶(?<-1>.)*(?(1)_)4|(?<=40|¶(?(1)_)(?<-1>.)*4.*¶.*)) 1 ``` Light unlit fields as appropriate. Sub-explanation: ``` (?<=¶(.)*) ``` Measure the column number of this unlit field. ``` 0 ``` Match the unlit field. ``` (?=4 ``` Look for a suitable field to the right. ``` |.*¶(?<-1>.)*(?(1)_)4 ``` Look for a suitable field in the same column (using a balancing group) in the line below. Note that if the input could be guaranteed rectangular then this could be simplified to `|.*¶(?>(?<-1>.)*)4` for a saving of 3 bytes. ``` |(?<=40 ``` Look for a suitable field to the left. (Since we're looking from the right-hand side of the field, we see the unlit field as well.) ``` |¶(?(1)_)(?<-1>.)*4.*¶.*)) ``` Look for a suitable field in the same column in the line above. Since this is a lookbehind and therefore a right-to-left match, the balancing group condition has to appear before the columns that have been matched by the balancing group. [Answer] # [Perl 5](https://www.perl.org/), 365 bytes ``` @a=map{[/./g]}<>;do{say@$_ for@a;say;my@n=();for$r(0..$#a){$l=$#{$a[$r]};for(0..$l){$t=$a[$r][$_];$n[$r][$_]=($q=$n[$r][$_])>$t?$q:$t==9?9:$t?++$t:0;if($t==4){$n[$r-1][$_]||=1if$r&&$_<$#{$a[$r-1]};$n[$r+1][$_]||=1if$r<$#a&&$_<$#{$a[$r+1]};$n[$r][$_-1]||=1if$_;$n[$r][$_+1]||=1if$_<$l}}}$d=0;for$r(0..$#a){$d||=$a[$r][$_]!=$n[$r++][$_]for 0..$#{$a[$r]}}@a=@n}while$d ``` [Try it online!](https://tio.run/##XZDhboIwFIX/@xQu3hhII5Zt/aGl0hfYExBCmiAbSQWsJMZgX93uAmNEf7XnnK@9Obc5Gs2ck0qcVNMl22D7ndrowPO6u6ibhGxZ1EYqjoKfbrISns/RAePRIICV8jvQAlYdqARMavtsSDQGrRjdBLKUQzVdhQdnMUv/AG0M5z3iYhfv8IwJgXZPeVl4vfmJX/X0Jhz4@12EZQFmvYYsmiZjZscR5JlCQj2R5J/sOXz3R2azSWYzAm2thVzQ19Y5InO9t7EQIYNCdDmA01os7ldW9vpT6iPkztEPGi4ope8Lxtijbtqyri5u88UCGtJf "Perl 5 – Try It Online") Uses '9' instead of 'A' to indicated a burned out location. **Explained** ``` @a=map{[/./g]}<>; # split input into a 2-D array do{ say@$_ for@a;say; # output the current state my@n=(); # holds the next iteration as it's created for$r(0..$#a){ # loop through rows $l=$#{$a[$r]}; # holder for the length of this row for(0..$l){ $t=$a[$r][$_]; # temporary holder for current value $n[$r][$_]=($q=$n[$r][$_])>$t?$q:$t==9?9:$t?++$t:0; #update next iteration if($t==4){ # ignite the surrounding area if appropriate $n[$r-1][$_]||=1if$r&&$_<$#{$a[$r-1]}; $n[$r+1][$_]||=1if$r<$#a&&$_<$#{$a[$r+1]}; $n[$r][$_-1]||=1if$_; $n[$r][$_+1]||=1if$_<$l } } } $d=0; # determine if this generation is different than the previous for$r(0..$#a){$d||=$a[$r][$_]!=$n[$r++][$_]for 0..$#{$a[$r]}} @a=@n # replace master with new generation }while$d ``` [Answer] # [Haskell](https://www.haskell.org/), 162 bytes ``` import Data.List i x|x<'9'=succ x|1<2=x f('3':'@':r)="30"++f r f(x:r)=x:f r f e=e a%b=a.b.a.b g=map(i<$>).(transpose%map(reverse%f)) h x|y<-g x,y/=x=x:h y|1<3=[x] ``` [Try it online!](https://tio.run/##HY2xasMwFEV3fcVDJMgirVLHeIixioaOyZQx6aAEORa1FSPJRYb@u/vs4cE958G9rQ4/puvm2fbDy0f40lGLkw2RWEh/qWZHJsP4eCDk9UEm0mSsYBVTrPJc0uKD7nYNeNRpEalaAYw0RG/vUou7wCNP2eshs/Xmk4sseu3C8Apmu0hvfo3H3HBOWpyZ6vcnpLdpLxPWtTDhcCGv6XuOJsQcJNBcqZtTSlGyqMOiVKHy1R1vrixLSnptHT5w4QzZMMZL9CcHAkbXWWcChw20iCtgXrvnfw "Haskell – Try It Online") Usage: `h` takes a field as a list of lines and returns a list of fields. An unburned field is indicated by `@` and ash by `9`, the different fires are the digits `1` to `8`. * `f` manages the spreading of the fire from left to right by replacing all unburned `@` fields which are right to a burning `3` field with `0`. * `i` increments each digit as long as it is less than `9`. * `g` applies `f` to each line, then reverses the line, applies `f` again and reverses back. Then the list of of lines is transposed and again on each line and its reverse `f` is applied. * `h` applies `g` to the input until it no longer changes and collects the results. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~308~~ ~~305~~ ~~299~~ ~~297~~ ~~295~~ 291 bytes ``` #define F B[i][v] m(A,B,k,y,m,U,i,v)char**B;{do{for(i=k=y=0;i<A;puts(""),++i)for(v=0;v<(m=strlen(B[i]));F=(U=F)>48&&F<56?F+1:F>55?65:(i+1<A&&B[i+1][v]==51||v+1<m&&B[i][v+1]==51||v-1>-1&&B[i][v-1]==52||i-1>-1&&B[i-1][v]==52)&&U<49?49:F,putchar(U),k+=U<49||U>64,++y,++v);puts("");}while(k-y);} ``` This program defines a function which takes two inputs, a pointer to an array of strings preceded by its length, as allowed by [this](https://codegolf.meta.stackexchange.com/a/13262/52405) I/O default. Outputs to STDOUT with a trailing newline. [Try it online!](https://tio.run/##RZBRb4IwFIWf568gLiGtbRPqKJmWQuCh/4An4wNB1AbBBV0XIv72rkXdHpqcfufk5txbkUNVGfO@q/eqqz3p5Ru13ejtrAUZznGDB9ziAiusYXUs@8Ui57fd@bY/90CJRgwi4CrO@Nf39QLmc4gRUtCZ2ho6Bq24XPtT3QE3FkIuBSiEhEn46fsyZlEqEV3LhLE0YmugEI0z37dZRF0JIRgdR21pO1HLrPGkhCaEvjCZ8HIc1T8mrxlL6PtFHK7ScLWW2FZ1m4AC4gYJx8exSKLQVh/s0/BvGX7/OapTDRoyWG1Ud/XaUnXAibI/VNh7nMR9NPRuszdHCeGT0AhZ0YJHcorw2d0zJvgIqAmCIDOMsV8 "C (gcc) – Try It Online") [Answer] # Octave, ~~72~~ 69 bytes ``` a=input(''),do++a(a&a<9);a+=imdilate(a==4,~(z=-1:1)|~z')&~a,until a>8 ``` The input is taken as a 2D array of numbers, and empty spots marked with `Inf`. `'A'` has been replaced with `9`. Intermediate results (as array of numbers) implicitly printed . [Try it online!](https://tio.run/##y08uSSxL/f8/0TYzr6C0RENdXVMnJV9bO1EjUS3RxlLTOlHbNjM3JTMnsSRVI9HW1kSnTqPKVtfQylCzpq5KXVOtLlGnNK8kM0ch0c7i//9oAwUFBWMgBtGG1gZQFghbWpsCSQj2zEuL5QIA "Octave – Try It Online") Explanation: In a loop the function `imdilate` (morphological image dilation) from the image package is used to simulate fire propagation. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 52 bytes\* Assumes `⎕IO←0` which is default on many systems. Takes field using 0 for empty slots, 1 for non-burning field, 2 for new fire, 5 for spreading fire, and 10 for ash. Input must be at least 3×3, which isn't a problem as additional rows and columns may be padded with zeros (spaces in OP's format). ``` {}{1=c←4⊃r←,⍵:1+4∊r/⍨9⍴⍳2⋄10⌊c+×c}⌺3 3⍣{⍺≡⎕←⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OAZHVttaFtMpBh8qiruQhI6zzq3WplqG3yqKOrSP9R7wrLR71bHvVuNnrU3WJo8KinK1n78PTk2kc9u4wVjB/1Lq5@1LvrUedCoKFAvUCttf//pyk8apuoYaRgqGCoqWEIoQwUgFATAA "APL (Dyalog Unicode) – Try It Online") My format makes it hard to check for correctness, so [**here**](https://tio.run/##RVBNS8NAEL3nV@Q2DbF017SHCAVz9OQf6KXUDwolhqAHKfGgEtK1W5RS7FEt0uDFg3rpMf6T@SPx7VaUZZiZN2/3vZ1@MmoeXfZHZ6c1zxYHh5zfi7oexsnFOcpxg9UL5w@sy8ANeFqw/uRiCcRDSJ/1rCrBuabqXZK33@hiSi55FNJvE5GhUo8aPHlileNBj/XXFcWUOUk6jK0OEFYrOECD@6zfIGnRfI6qyeoViYt1C9Mu8My4KlRVsl5UJVI@h9RWM/RA2paw5SF8c8M5GabHRiwby@4ARZvVTYq8g@me9Nt4L21BJjS/1B@7fHcrBU/VwP9@HGQ83Zgd6BVsbXjybL271kqxtAurjYBLUoheLIQgZ9uLQEgLRL240@n8wZGwxAjnP4El6Qc "APL (Dyalog Unicode) – Try It Online") is a version with added pre- and post-processing to translate from and to OP's format. `⍣{`…`}` repeat until:  `⍺` the next generation  `≡` is identical to  `⎕←⍵` the current generation, outputted `{`…`}⌺3 3` replace each cell with the result of this function applied to its Moore neighborhood:  `,⍵` ravel (flatten) the argument; gives nine-element list  `r←` assign to *r*  `4⊃` pick the fourth element; the center, i.e. the original cell value  `c←` assign to *c*  `1=` is one equal to that?  `:` if so, then:   `⍳2` first to **ɩ**ntegers; 0 1   `9⍴` **r**eshape to length nine; 0 1 0 1 0 1 0 1 0   `r/⍨` use that to filter *r* (this gets just the orthogonal neighbors)   `4∊` is four a member of that? (i.e. will there be a five in the next generation?)   `1+` add one; 1 if not caught fire or 2 if caught fire  `⋄` else (i.e the current value is 0 or ≥ 2)   `×c` the signum of *c*   `c+` *c* plus that (i.e. increase by one if on fire)   `10⌊` minimum of ten and that (as ash doesn't burn on) --- \* In Dyalog Classic, using `⎕U233A` instead of `⌺`. [Answer] # [Python 2](https://docs.python.org/2/), 325 Bytes ``` def f(x): while{i for m in x for i in m}>{9,''}: yield x;i=0 for l in x: j=0 for c in l: if 0<c<9:x[i][j]+=1 j+=1 i+=1 i=0 for l in x: j=0 for c in l: if c==0 and{1}&{x[k[1]][k[2]]==4for k in[y for y in[[i,i-1,j],[i<len(x)-1,i+1,j],[j,i,j-1],[j<len(l)-1,i,j+1]]if y[0]]}:x[i][j]+=1 j+=1 i+=1 yield x ``` `f` takes the input as a 2D array of integers, and empty spots marked with `''`. `'A'` has been replaced with `9`. The function outputs a generator of all the fields over time in the same format. [Try it online!](https://tio.run/##jVHBboMwDD3DV/i0gHCn0G2HdrAfyaKpakF1mqZVhzQQ4ttZbHroZdJiKX55tp@T@Dp0x0tYz4emheuNQvfVUuMPWZ9vU4irvdzAAwXolzMvyQOlnt2FQnbeXbPv7obg8zx9CH8GJartovVzJN@MJIJnERRIDM/Tx7hBpaZtmgzcHvp3qnWaPHZPwDElVXvmfOQSakFX@2qz7Q1Z42xRl5F14oDE/V9pX9caduEwltPT2JuTKa2N@9raun7l7FPMNoMUDgwNIa1KdBYNVb4J8anxSMVCOSR0q5KRBL0E0RVRNnYbjLZ2@vvicP@KmdvJVPiubWaMxhfUyMIa2TYRvSGbUtbeJ/c4Tdnz@Rc) [Answer] # [Octave](https://www.gnu.org/software/octave), 212 bytes ``` function r(f)b=48;f-=b;c=-16;l=f~=-c;d=17;p=@(x)disp(char(x+b));g=@()disp(' ');p(f);g();while~all(any(f(:)==[0 d c],2))m=f>0&l;f(m)+=1;k=conv2(f==4,[0 1 0;1 0 1;0 1 0],'same')&~m&l;f(k)+=1;f(f>8&l)=d;p(f);g();end ``` To run, specify a character array such as: ``` f = ['0301','000A','555 ']; ``` ... then do: ``` r(f) ``` Explanation of the code to follow... # [Try it online!](http://www.tutorialspoint.com/execute_octave_online.php?PID=0Bw_CjBb95KQMZDZkQk1EcTdTckE) Note: I tried to run this code with [tio.run](http://tio.run), but I wasn't getting any output. I had to use another service. [Answer] # PHP, ~~226 212 210 209 185~~ 177 bytes ``` for($f=file(m);$f!=$g;print" ")for($g=$f,$y=0;$r=$f[$y++];)for($x=-1;~$c=$r[++$x];$f[$y-1][$x]=$c=="0"?strstr($g[$y-2][$x].$r[$x-1].$f[$y][$x].$r[$x+1],51)/3:min(++$c,9))echo$c; ``` takes input with a trailing newline from a file named `m`; `9` for ashes. Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/ea14d97ff17d1a5928470395573dae220681c2ac). --- **first approach: PHP 7.0, 209 bytes** ``` for($f=$g=file(m);trim(join($f),"A ");print" ".join($f=$g))for($y=-1;(a&$c=$r[++$x])||$r=$f[$y-=$x=-1];)for(+$c&&$g[$y][$x]=++$c<9?$c:A,$a=4;$a--;$q=$p)$c-4|($w=&$g[$y+$p=[1,0,-1][$a]])[$q+=$x]!="0"||$w[$q]=1; ``` takes input with a trailing newline from a file named `m`. Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/bbb342b2ea57ffcef9a9b537a28f4f3e35dec117). **PHP version notes** (for old approach) * for PHP older than 7.0, replace everything after `$c-4|` with `$g[$y+$p=[1,0,-1][$a]][$q+=$x]!="0"||$g[$y+$p][$q]=1;` * for PHP older than 5.5, replace `[1,0,-1][$a]` with `$a%2*~-($a&2)` * for PHP newer than 7.0, replace `a&$c` with `""<$c`, `+$c` with `0<$c` and `$c-4` with `$c!=4` [Answer] # Octave, ~~419~~ 312 bytes ``` M=input('') %take a matrix M as input [a, b]=size(M); %size M for later while mean(mean(M))!=9 %while the whole matrix M isn't ashes M=M+round(M.^0.001); %if there is a nonzero int add 1 to it for i=1:a %loop over all values of M for j=1:b if(M(i,j)==4) %if a value of 4 is found, ignite the zeros around it if(M(max(i-1,1),j)==0) M(i-1,j)++;end if(M(min(i+1,a),j)==0) M(i+1,j)++;end if(M(i,max(j-1,1))==0) M(i,j-1)++;end if(M(i,min(j+1,b))==0) M(i,j+1)++;end elseif(M(i,j)==10) M(i,j)--; end end end M %display the matrix end ``` # [Try it online!](https://tio.run/##Xc7fCsIgFAbwe5/CrvKgC4VuavgI5wmiwJXRkeairT/08stZjZHg4Xzy48Nm37m773u0FC@3TsznwDZO8WprW3p5gVCyx4nOntfeRZEHAszsiqFFeW1u8SBwsdMLrU2yx@bKyZq1y1tIW8XoKFCQCmDtEj6pdk9BhVEG8rMGjjkHkLL08fBVFAVJo9xUyX9FamgLuW1UKuVB8cR4PiNOpSGVVFMsR8z8ufWTH5sfgaIoWQbfi8Ps@43hmuvtGw) This is my version it works, so now I still need to golf it. I think it can be a lot shorter if I find a way to find the indices of the 4 in a matrix, but I don't know how. PS: A is a 9 in my code. [Answer] # [Stencil](https://github.com/abrudz/Stencil) *(`∊`-mode)*, 22 bytes ``` S≡8:'A'⋄0::S⋄(3∊N)⌈S+s ``` [Try it online!](https://tio.run/##Ky5JzUvOzPn/P/hR50ILK3VH9UfdLQZWVsFASsP4UUeXn@ajno5g7eL//x@1TdQwUDBWMFAw1AQygBCoWlPDVAEI1RXUNf/lF5Rk5ucV/wfqAgA "Stencil – Try It Online") Just like in the test input, use integers separated by spaces for `0`-`8`, `' '` for blank and `'A'` for `A`. Remember to add trailing blanks too. ]
[Question] [ People keep telling me that the square of a number is the number multiplied by itself. This is obviously false. The correct way to square a number is to make it into a square, by stacking it on top of itself a number of times equal to the number of digits it has, and then reading all the numbers from the resultant square, both horizontally (from left to right only) and vertically (from up to down only), and then adding them together. So, for the number 123, you first create the square: ``` 123 123 123 ``` Then you take all of the rows and columns from the square, and add them together: ``` 123+123+123+111+222+333 ``` Which gives us a result of `1035`. For negative numbers, you stack normally (remember that you only count the number of *digits*, so the negative sign is not included in the length), and then read the horizontal numbers normally (with negative signs), and then ignore the negative signs for the vertical numbers. So, for the number `-144` we get the square: ``` -144 -144 -144 ``` Which gives us `-144-144-144+111+444+444`, which equals `567` For numbers with only one digit, the square is always equal to the number doubled (read once horizontally and once vertically). So `4` gives us ``` 4 ``` Which gives us `4+4`, which equals `8`. For numbers with decimal parts, stack normally (remember that only *digits* are counted in the number of times you stack the number, and therefore the decimal point is not counted), and ignore the decimal symbols when reading the vertical numbers. For example, the number `244.2` gives us ``` 244.2 244.2 244.2 244.2 ``` Which gives us `244.2+244.2+244.2+244.2+2222+4444+4444+2222`, which equals `14308.8`. Fractional or complex numbers cannot be squared. ## Your Task: I'm tired of squaring numbers my way by hand, so I've decided to automate the process. Write me a program or function that takes a float or string, whichever you prefer, as input and returns the result of squaring it my way. ## Examples: ``` 123 -> 1035 388 -> 3273 9999 -> 79992 0 -> 0 8 -> 16 -6 -> 0 -25 -> 27 -144 -> 567 123.45 -> 167282.25 244.2 -> 14308.8 2 -> 4 -0.45 -> 997.65 0.45 -> 1000.35 ``` ## Scoring: My hands are getting cramped from writing out all those squares, and my computer doesn't support copy/paste, so the entry with the least amount of code for me to type (measured in bytes for some reason?) wins! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` þSDg×+O ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8L5gl/TD07X9///XNdAzMQUA "05AB1E – Try It Online") Explanation ``` þSDg×+O Implicit input þ Keep digits S Get chars D Duplicate g Length × Repeat string(s) + Add (implicit input added to all elements) O Sum ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` fØDẋ€L$ŒV+VS ``` A monadic link accepting a list of characters (a well-formed decimal number, the single leading zero being a requirement for **-1 < n < 1**) and returning a number. **[Try it online!](https://tio.run/##y0rNyan8/z/t8AyXh7u6HzWt8VE5OilMOyz4////SroGeiamSgA "Jelly – Try It Online")** 14 bytes to accept and return numbers (input limited at **+/-10-5** by `ŒṘ`): `ŒṘfØDẋ€L$ŒV+⁸S`. ### How? ``` fØDẋ€L$ŒV+VS - Link: list of characters e.g. "-0.45" ØD - yield digit characters "0123456789" f - filter keep "045" $ - last two links as a monad: L - length (number of digit characters) 3 ẋ€ - repeat list for €ach digit ["000","444","555"] ŒV - evaluate as Python code (vectorises) [0,444,555] V - evaluate (the input) as Jelly code -0.45 + - addition (vectorises) [-0.45,443.55,554.55] S - sum 997.65 ``` [Answer] ## Haskell, ~~59~~ 56 bytes ``` f s|l<-filter(>'.')s=0.0+sum(read<$>(s<$l)++[c<$l|c<-l]) ``` The input is taken as a string. [Try it online!](https://tio.run/##FYdLCsMgFACv8hAhilXsJ6ULk4uELCRVKn2G4Et3ubs1i5lhPp6@AbHWCHSg0zHhHooYO9NJGqyxin5ZlODfjo@CHEep1LS0HovTOMuafVphgK2kdQcO2W8QYWLX251d2Kuhn01tzaM/z56d6x8 "Haskell – Try It Online") How it works ``` l<-filter(>'.')s -- let l be the string of all the numbers of the input string f s = 0.0 + sum -- the result is the sum of (add 0.0 to fix the type to float) read<$> -- turn every string of the following list into a number s<$l -- length of l times the input string followed by [c<$l|c<-l] -- length of l times c for each c in l ``` [Answer] # [Japt v2](https://github.com/ETHproductions/japt), 16 bytes ``` o\d l ¬xpV +V*Ng ``` [Test it online!](http://ethproductions.github.io/japt/?v=2.0a0&code=b1xkCmwKrHhwViArVipOZw==&input=Ii0wLjQ1Ig==) ### Explanation ``` o\d First line: Set U to the result. o Keep only the chars in the input that are \d digits. (literally /\d/g) l Second line: Set V to the result. l U.length ¬xpV +V*Ng Last line: implicitly output the result. ¬ Split U into chars. x Sum after pV repeating each V times. +V*Ng Add V * first input (the sum of the horizontals) to the result. ``` [Answer] # C# (.NET Core), ~~150~~ ~~141~~ 133 bytes ~~*Saved 9 bytes thanks to @TheLethalCoder*~~ *Saved another 8 bytes thanks to @TheLethalCoder* ``` a=>{var c=(a+"").Replace(".","").Replace("-","");int i=0,l=c.Length;var r=a*l;for(;i<l;)r+=int.Parse(new string(c[i++],l));return r;} ``` [Try it online!](https://tio.run/##dVFRa8IwEH73VxzxJV1jqK4Ot1hfBJ8cyBzsQX0IWVoDNRlJdIzS3@7SVix72AfJ5S7fHd/dCTcSxsqrKLlzsLGmsPw0qAYQ4Dz3SsDFqE945Upj563Sxe4A3BYuajkds8H2x3l5oquzFvO8NNwTaM0CcsiuPFtUF25BZJjHCEX0TX6VXEiMKCJ//FHrM6U9qCwhZSboWurCH1mTbzP@ULLcWMzUvGSRjbPApBtuncRafkOnEYudiuMDKaOIWenPVoNl9ZXd1bbSQideOi@4kw4yaNJv8Tuv76/BePJI4HE2I/AcQCAhEN6jp3Am03CN05Q0JJpOcwKTNKWTxoafpAu15l6yZoNeUNgCF0fArQIQoHQvLvpHz23mS6OdKSX9sMrLtdLytim6MvbEPUbLUAT2qErqPXrZ@2pcIwIiLAiLiL6bbTczlNDhEEVhZL3CQXfX118 "C# (.NET Core) – Try It Online") Takes a string as an input and outputs the 'squared' number as a float. --- This code follows the following algorithm: 1. Create a new string from the input, but without the decimal points and symbols, so we can get our length and the numbers for the columns from there. 2. Calculate the input times the length of the string we created at point 1. 3. For each column in our 'square', create a new string with the column number and the row length and add it to our result. Example: Input: `-135.5` 1. If we replace decimal points and symbols we get the string `1355`, which has a length of `4`. 2. The input times 4: `-135.5 * 4 = -542`. 3. Now we create new strings for each column, parse them and add them to our result: `1111`, `3333`, `5555`, `5555`. If we sum these numbers up we get `15012`, which is exactly what our program will output. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 23 bytes ``` {∋ịṫ}ᶠ⟨≡zl⟩j₎ᵐ;[?]zcịᵐ+ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/pRR/fD3d0Pd66ufbhtwaP5Kx51LqzKeTR/Zdajpr6HWydYR9vHViWDVGydoP3/v5KugZ6JqdL/KAA "Brachylog – Try It Online") Brachylog doesn't go well with floats... Explanation: ``` {∋ịṫ}ᶠ⟨≡zl⟩j₎ᵐ;[?]zcịᵐ+ Takes string (quoted) input, with '-' for the negative sign ᶠ Return all outputs (digit filter) { } Predicate (is digit?) ∋ An element of ? (input) ị Convert to number (fails if '-' or '.') ṫ Convert back to string (needed later on) ⟨ ⟩ Fork ≡ Identity l Length with z Zip ᵐ Map ₎ Subscript (optional argument) j Juxtapose (repeat) (this is where we need strings) ; Pair with literal [ ] List ? ? z Zip c Concatenate (concatenate elements) ᵐ Map ị Convert to number + Add (sum elements) ``` [Answer] ## [Husk](https://github.com/barbuz/Husk), 15 bytes ``` §+ȯṁrfΛ±TṁrSR#± ``` Takes a string and returns a number. [Try it online!](https://tio.run/##yygtzv7//9By7RPrH@5sLEo7N/vQxhAQKzhI@dDG////K@ka6JmYKgEA "Husk – Try It Online") ## Explanation It's a bit annoying that the built-in parsing function `r` gives parse errors on invalid inputs instead of returning a default value, which means that I have to explicitly filter out the columns that consist of non-digits. If it returned 0 on malformed inputs, I could drop `fΛ±` and save 3 bytes. ``` §+ȯṁrfΛ±TṁrSR#± Implicit input, e.g. "-23" #± Count of digits: 2 SR Repeat that many times: ["-23","-23"] ṁr Read each row (parse as number) and take sum of results: -46 ȯṁrfΛ±T This part is also applied to the result of SR. T Transpose: ["--","22","33"] fΛ± Keep the rows that contain only digits: ["22","33"] ṁr Parse each row as number and take sum: 55 §+ Add the two sums: 9 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~95 94 87 85~~ 84 bytes ``` def f(i):l=[x for x in i if"/"<x];k=len(l);print(k*float(i)+sum(int(x*k)for x in l)) ``` [Test Suite](https://tio.run/##PU3BDsIgFLu/ryCcYIa5MWbm5v7Cm/FgJmRkCMtkEb8e4WIPTdqm7fr1s7NNnNxTjhjj@JQKKaJpb8ZbQMptKCBtkUZa4SO@hPuwjEZaYuiwbtp6shTKuIdPlcN7f5FshWKh/6ahNKZBu@6eUJou4DNrI9F122Uvg5xI/qax5g00XQfnBKigA3YCxltgtRCQwlK0wIUoOXBgVVaZfg). # [Python 3](https://docs.python.org/3/), 78 bytes ``` lambda x:sum(float(i*len(z))for z in[[i for i in str(x)if"/"<i]]for i in[x]+z) ``` [Test Suite.](https://tio.run/##PYpBDsIgEEX3nIJ0BYq1BTS10ZNUFhglTkKhaTGpvTxOTXSS@fP@ywzv9IxBZXe5Zm/7293SuZ1ePXM@2sRg4x@BLZy7ONKFQug6oCsDMp3SyGYOrtgXZzDm57vZbBee/7WWShDVNIKccASpBEHeHXHlAaPWWhB8KjU2qXUp8aCvvmJN0w4jhMQcA87zBw "Python 3 – Try It Online") The second approach is a port to Python 3 inspired by @officialaimm's solution. [Answer] # [Python 2](https://docs.python.org/2/), ~~81~~ 74 bytes ***-7 bytes thanks to @Mr. Xcoder***: `'/'<i` * Takes in integer or float, returns float. ``` lambda x:sum(float(i*len(z))for z in[[i for i in`x`if"/"<i]]for i in[x]+z) ``` [Try it online!](https://tio.run/##PYphC4IwEIa/71cMP221TOcKk/ola6BRwwPdxBbY/vw6gzq495734aZ36L2TyV6uaejG272jS/N8jcwOvgsMNsPDsci59TONFJzWQFcG5HZpwWb77AzG/JxezDby9K@lrASp6lqQE44ghSDIuyOuPGCUSgmCT7nCJpXKJR70xVesaZppBheoZcDTBw "Python 2 – Try It Online") ## Explanation: Say `123.45` is given as input. `[i for i in`x`if"/"<x]` gives a list of stringified integers `['1','2','3','4','5']` (which is also `z`). Now we iterate through `[x]+z` i.e. `[123.45,'1','2','3','4','5']`, multiplying each element by `len(z)`, here `5` and converting each to a Float (so that strings also convert accordingly), yielding `[617.25,11111.0,22222.0,33333.0,44444.0,55555.0]`. Finally we calculate the `sum(...)` and obtain `167282.25`. [Answer] # JavaScript, ~~75~~ 62 bytes ``` a=>(b=a.match(/\d/g)).map(b=>a+=+b.repeat(c),a*=c=b.length)&&a ``` [Try it online](https://tio.run/##HY7dDoMgDIVfhSuFiaiMLS4LvsjcRUX8iwOjZK/POpv09JwvTdoFvnCYfd5C7nxv46Aj6IZ2GsQHgplo0fbFyBimDWkDmc46sdvNQqCGcbhoozuxWjeGiSUJxKfx7vCrFasf6auSV06udc3JA4uTkhP0@R1b3lAqpTjBJaEwSaWExIG8PMFf3@dpILohA4UsTfGZxc@Opq1DH38) *-2 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)* *-5 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)* (I though the function must receive a number, but now I see that lot of other answers receive string too) [Answer] # [Perl 5](https://www.perl.org/), ~~37~~ 33 + 1 (-p) = ~~38~~ 34 bytes ``` $_*=@n=/\d/g;for$\(@n){$_+=$\x@n} ``` [Try it online!](https://tio.run/##K0gtyjH9/18lXsvWIc9WPyZFP906Lb9IJUbDIU@zWiVe21YlpsIhr/b/f4N/@QUlmfl5xf91fU31DAwN/usWAAA "Perl 5 – Try It Online") *Used some tricks from Dom's code to shave 4 bytes* **Explained:** ``` @n=/\d/g; # extract digits from input $_*=@n; # multiply input by number of digits for$\(@n){ # for each digit: $_+= # add to the input $\x@n} # this digit, repeated as many times as there were digits # taking advantage of Perl's ability to switch between strings # and numbers at any point ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` ŒṘfØDẋ€L©$ŒV;ẋ®$S ``` [Try it online!](https://tio.run/##y0rNyan8///opIc7Z6QdnuHycFf3o6Y1PodWqhydFGYN5B1apxL8//9/XQM9E1MA "Jelly – Try It Online") [Answer] # Pyth, 18 bytes ``` s+RvQsM*RF_lB@jkUT ``` [Try it here.](http://pyth.herokuapp.com/?code=s%2BRvQsM%2aRF_lB%40jkUT&input=%22-0.45%22&debug=0) [Answer] # [Pyth](http://pyth.readthedocs.io), ~~21~~ 20 bytes ``` K@jkUTQ+smv*lKdK*lKv ``` [Test suite.](http://pyth.herokuapp.com/?code=K%40jkUTQ%2Bsmv%2alKdK%2alKv&test_suite=1&test_suite_input=%22123%22%0A%22388%22%0A%229999%22%0A%220%22%0A%228%22%0A%22-6%22%0A%22-25%22%0A%22-144%22%0A%22123.45%22%0A%22244.2%22%0A%222%22%0A%22-0.45%22%0A%220.45%22&debug=0) Uses a completely different approach from [@EriktheOutgolfer's answer](https://codegolf.stackexchange.com/questions/136564/square-a-number-my-way/136575#136575), which helped me golf 1 byte in chat, from 22 to 21. --- # Explanation ``` K@jkUTQ+s.ev*lKbK*lKv K@jkUTQ - Filters the digits and assigns them to a variable K. m - Map. Iterated through the digits with a variable d v - Evaluate (convert to float). *lKd - Multiplies each String digit by the length of K. s - Sum + - Sum *lKvQ - Multipies the number by the length of the digits String ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~100~~ 82 bytes Thanks a lot @TomCarpenter for teaching me that assignments have a return value and saving me `18` bytes! ``` @(v)(n=nnz(s=strrep(num2str(abs(v)),'.','')-'0'))*v+sum(sum(s'*logspace(0,n-1,n))) ``` [Try it online!](https://tio.run/##HcnBCsIwDIDhV/GWZKayzl0Lew/1EEftxWWjWQv68nV4@OGDf513qbGlcG8TVkINql@0YHvOcUMty3AQ5WnHJYYLMAA56IGoq2crC/6D7r0m22SO2LM6z0pETXKWz6soJj7d/HBl58fxQe0H "Octave – Try It Online") ### Ungolfed/Explanation ``` function f=g(v) s=strrep(num2str(abs(v)),'.','')-'0'; % number to vector of digits (ignore . and -) n=nnz(s); % length of that vector f=n*v+sum(sum(s'*logspace(0,n-1,n))) % add the number n times and sum the columns of the square end ``` The way this works is that we basically need to add the number itself `n` times and then add the sum of the columns. Summing `s' * logspace(0,n-1,n)` achieves the sum of columns, for example if `v=-123.4` that matrix will be: ``` [ 1 10 100 1000; 2 20 200 2000; 3 30 300 3000; 4 40 400 4000 ] ``` So we just need to `sum` it up and we're done. [Answer] # [Swift 4](https://swift.org/blog/swift-4-0-release-process/), ~~139~~ 134 bytes ``` func f(s:String){let k=s.filter{"/"<$0};print(Float(s)!*Float(k.count)+k.map{Float(String(repeating:$0,count:k.count))!}.reduce(0,+))} ``` [Test Suite.](http://swift.sandbox.bluemix.net/#/repl/597d7ba8c5cfd27e04c56f0d) --- # Explanation * `func f(s:String)` - Defines a function `f` with an explicit String parameter `s`. * `let k=s.filter{"/"<$0}` - Filters the digits: I noticed that both `-` and `.` have smaller ASCII-values than all the digits, and `/` is between `.`, `-` and `0`. Hence, I just checked if `"/"` is smaller than the current character, as I did in my Python answer. * `print(...)` - Prints the result. * `Float(s)!*Float(k.count)` - Converts both the String and the number of digits to Float and multiplies them (Swift does not allow Float and Int multiplication :()). So it adds the number `x` times, where `x` is the number of digits it contains. * `k.map{Int(String(repeating:$0,count:k.count))!` - `k.map{}` maps over `k` with the current value `$0`. `String(repeating:$0,count:k.count)` takes each digit, creates a String of `x` identical digits and `Float(...)!` converts it to a Floating-point number. * `.reduce(0,+)` - Gets the sum of the list above. * And finally `+` sums the two results. --- # Let's take an example! Say our String is `"0.45"`. First off, we filter the digits, so we are left with `0, 4, 5`. We convert `"0.45"` to Float and multiply by the number of digits: `0.45 * 3 = 1.35`. Then we take each digit and turn it into a String repeating that digit until it fills the width of the square (how many digits there are): `0, 4, 5 -> 000, 444, 555`. We sum this, `000 + 444 + 555 = 999`. Then we just add the results together: `1.35 + 999 = 1000.35`. [Answer] # C#, ~~139~~ 137 bytes ``` using System.Linq;n=>{var d=(n+"").Where(char.IsDigit);return d.Sum(i=>int.Parse(new string(i,d.Count())))+new int[d.Count()].Sum(_=>n);} ``` *Saved 2 bytes thanks to @Ian H.* [Try it online!](https://tio.run/##jY/BasMwDIbveQrRk01bQ7PcsuTSMRhsUNZDD2MMz1ZbQSJvttMxSp49SxroNhis/0ES0ifxy4R57dh1rGsMb9ogrD9DxFrdE78nxwR6mUqHAKtTPXYGhagjGTg4svCgiYU8j76hQbcNm2vrmtcKZzDmErZQdFyUx4P2YKEAwdPJRKrNHj0Ks9de3YUb2lGUucfYeAar1k0tqCiJo1ppH1AwfvQ2PPFO0MyqpWs4CtlrOkx67uncfD5tvxQly7zt8uSXw6Xj4CpUG08R@8dRbMUivZIy/xebL7LsEu4iKM0ylQ7gn@QjansCf1xqkzG23Rc "C# (Mono) – Try It Online") Full/Formatted version: ``` namespace System.Linq { class P { static void Main() { Func<double, double> f = n => { var d = (n + "").Where(char.IsDigit); return d.Sum(i => int.Parse(new string(i, d.Count()))) + new int[d.Count()].Sum(_ => n); }; Console.WriteLine(f(123)); Console.WriteLine(f(-144)); Console.WriteLine(f(4)); Console.WriteLine(f(244.2)); Console.ReadLine(); } } } ``` [Answer] # Mathematica, 107 bytes ``` (t=Length[s=#&@@RealDigits[#]//.{a___, 0}:>{a}];If[IntegerPart@#==0,t++];t#+Tr[FromDigits@Table[#,t]&/@s])& ``` [Answer] # PHP, ~~78~~ 88 +1 bytes ``` for($e=preg_match_all("#\d#",$n=$argn);~$c=$n[$i++];)$s+=str_repeat($c,$e);echo$s+$n*$e; ``` Run as pipe with `-nR`. May yield warnings in PHP 7.1. Repace `$c,$e` with `$c>0?$c:0,$e` to fix. [Answer] # [Python 3](https://docs.python.org/3/), 68 ~~70~~ ~~73~~ ~~77~~ bytes ``` lambda n:sum(float(n)+int(_*sum(x>"/"for x in n))for _ in n if"/"<_) ``` [Try it online!](https://tio.run/##ZY3dCsIwDEbvfYqymzWKc/2ZTFGfRCgVKRa2dMwJ8@lruwshmquck@TL8J4eAVV052vsbH@7W4bH56vnrgt24ggbjxM366zmS7ErXBjZzDwyBMi9WXrmXZqdDMRhzAeOl0KqEmD1ZdW2hA@piKgJ0eXtnqJsKAutiUjPK013pNaVpIZm1L8Xf0IsAfED "Python 3 – Try It Online") Loops over every digit character and repeats it by the number of digit characters overall, makes that into an integer, and adds that to `n`. This way `n` gets added `d` times, the horizontal part of the sum, along with the digit repetition, which is the vertical part. Originally used `str.isdigit` but `>"/"`, thanks to others in this thread, saved a lot of bytes. Saves two bytes by taking `n` as a string, but the output is messier. ``` lambda n:sum(n+int(_*sum(x>"/"for x in str(n)))for _ in str(n)if"/"<_) ``` [Try it online!](https://tio.run/##Vc3BCsIwDAbgu09RdmoU59ZG2UR9EqFMpFhw2eg6mE9fW0SMOeVL/pDxFR4D6WjP1/js@tu9E3Sc5l7SxlGQZp375VLsCjt4sQhHYgpeEgDkgfkNnE2hk4E4@nxpZa00wOor3TRMbSrGivU8tj1wqD1XjciYnpXI9wqxVNz8tvrPfhjf "Python 3 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes input as a string. ``` f\d çU cUy ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LXg&code=ZlxkIOdVCmNVeQ&input=IjEyMyI) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=ZlxkIOdVCmNVeQ&footer=Vng&input=WwoiMTIzIgoiMzg4IgoiOTk5OSIKIjAiCiI4IgoiLTYiCiItMjUiCiItMTQ0IgoiMTIzLjQ1IgoiMjQ0LjIiCiIyIgoiLTAuNDUiCiIwLjQ1IgpdLW1S) ``` f\d çU\ncUy :Implicit input of string U > "-0.45" f :Match (returns an array) \d : RegEx /\d/g > ["0","4","5"] çU :Fill with U > ["-0.45","-0.45","-0.45"] \n :Reassign to U c :Concatenate Uy : U transposed > ["-0.45","-0.45","-0.45","---","000","...","444","555"] :Implicit output of sum of resulting array > 997.65 ``` ]
[Question] [ For this challenge, an ASCII art quilt will be a block of text 24 characters wide and 18 lines tall, containing the characters `=-<>/\` in a quilt-like pattern that is horizontally and vertically symmetrical. Example quilt: ``` ======================== ------------------------ //\\//\\\//\/\\///\\//\\ <<><<>>>>><<>><<<<<>><>> /\\/\\\\/\/\/\/\////\//\ ------------------------ /\/////\\///\\\//\\\\\/\ \///\/\/\\\\////\/\/\\\/ \///\/\/\\\\////\/\/\\\/ /\\\/\/\////\\\\/\/\///\ /\\\/\/\////\\\\/\/\///\ \/\\\\\//\\\///\\/////\/ ------------------------ \//\////\/\/\/\/\\\\/\\/ <<><<>>>>><<>><<<<<>><>> \\//\\///\\/\//\\\//\\// ------------------------ ======================== ``` All quilts have the same form: * They are always 24 by 18. * The top line (line 1) and bottom line (line 18) are `=` all the way across. * Lines 2, 6, 13 and 17 are `-` all the way across. * Lines 4 and 15 are the same random **horizontally symmetric** pattern of `<` and `>`. * All other lines (3, 5, 7, 8, 9, 10, 11, 12, 14, 16) are filled with `/` and `\` in a completely random way such that the entire quilt remains **horizontally and vertically symmetric**. Notice that when folding the quilt exactly in half, either vertically or horizontally, the *shapes* of the characters exactly match up. Don't get this confused with the characters themselves matching up. e.g. line 3 and line 16 are **not** identical, they are vertical mirror images. # Challenge Write a program or function that will print or return a random ASCII art quilt. Due to the many hardcoded lines and the symmetry, the only real randomness comes from the first 12 characters on lines 3, 4, 5, 7, 8, 9: * The first 12 characters on line 4 should be able to be any length 12 string of the characters `<` and `>`. * The first 12 characters on lines 3, 5, 7, 8, 9 should be able to be any length 12 string of the characters `/` and `\` (independent of each other). * These random strings are then mirrored accordingly to make the entire quilt. **The shortest answer in bytes wins. Tiebreaker is earlier post.** You may use pseudorandom number generators. (No, you don't need to prove that *all* 12 char string of `<>` or `/\` can be generated with you language's PRNG.) The output may optionally contain a trailing newline, but no trailing spaces or other characters besides what's necessary for the quilt. [Answer] # CJam, ~~61~~ ~~60~~ ~~58~~ ~~55~~ ~~54~~ ~~52~~ 51 bytes Shortened a bit with some help from Sp3000 and Optimizer. ``` "=-/</-///"{C*1{"<\/>"%1$W%\_W%er}:F~+mrC<1FN}%s3F( ``` [Test it here.](http://cjam.aditsu.net/#code=%22%3D-%2F%3C%2F-%2F%2F%2F%22%7BC*1%7B%22%3C%5C%2F%3E%22%251%24W%25%5C_W%25er%7D%3AF~%2BmrC%3C1FN%7D%25s3F() ## Explanation As usual with these symmetric ASCII art challenges, I'm generating one quadrant and then expand it to the full thing by two appropriate mirroring operations. For this explanation I should start with the function `F`, which I'm defining somewhere along the way, because it's used in three places for three different things: ``` {"<\/>"%1$W%\_W%er}:F ``` This expects an integer on the top of the stack, and a string beneath that. Its purpose is to reverse the string and also swap some characters, to get the mirroring right. The integer is either `1` or `3` and indicates whether (`1`) both brackets and slashes should be swapped or (`3`) only brackets should be swapped. Here is how it works: ``` "<\/>" "Push a string with all four relevant characters."; % "% applied to a string and an integer N (in any order) selects every Nth character, starting from the first. So with N = 1 this just leaves the string unchanged, but with N = 3 it returns a string containing only < and >."; 1$ "Copy the string we want to mirror."; W% "% also takes negative arguments. Giving it -1 reverses the string."; \_ "Swap the two strings and duplicate the <\/> or <> string."; W% "Reverse that one. Due to the symmetry of this string, we'll now have the characters to be swapped at corresponding indices."; er "Perform element-wise transliteration on the reversed input string to complete the mirroring operation."; ``` Now for the rest of the code: ``` "=-/</-///" "This string encodes the 9 different line types. Note that for the /\ and <> lines we only use one of the characters. This idea is due to Sp3000. Thanks! :)"; { }% "Map this block onto the characters."; C* "Repeat the character 12 times, turning it into a string."; 1{...}:F~ "Define and call F on the resulting string. The reversal doesn't do anything, but the character swapping creates strings containing both \/ and <>."; +mr "Add the two halves together and shuffle them."; C< "Truncate to 12 characters. We've now got our random half-lines."; 1F "Call F again to mirror the half-line."; N "Push a newline."; s "Join all those separate strings together by converting the array to a string."; 3F "Perform one more mirroring operation on the half-quilt, but this time only swap < and >. This yields the correct full quilt, except there are two newlines in the centre."; ( "This slices the leading newline off the second half and pushes it onto the stack."; ``` The two halves and that single newline are then printed automatically at the end of the program. [Answer] # Python 3, ~~257~~ ~~229~~ ~~192~~ ~~185~~ ~~176~~ ~~149~~ 143 bytes ``` from random import* k,*L=80703, while k:s=eval("''"+".join(sample('--==<>\/'[k%4*2:][:2],2))"*12);L=[s]+L+[s[::(-1)**k]];k//=4 *_,=map(print,L) ``` With help from @xnor, we've finally caught up with JS! Sample output: ``` ======================== ------------------------ ///////////\/\\\\\\\\\\\ >><<<>><<<><><>>><<>>><< /\/\\/\/\\/\/\//\/\//\/\ ------------------------ //\\////\\/\/\//\\\\//\\ /////\\\/\/\/\/\///\\\\\ /\\//\\/////\\\\\//\\//\ \//\\//\\\\\/////\\//\\/ \\\\\///\/\/\/\/\\\///// \\//\\\\//\/\/\\////\\// ------------------------ \/\//\/\//\/\/\\/\/\\/\/ >><<<>><<<><><>>><<>>><< \\\\\\\\\\\/\/////////// ------------------------ ======================== ``` ## Explanation *(Slightly outdated, will update later)* `"444046402"` encodes the rows, with each digit referring to the starting index of the relevant 2-char substring of `'--==\/<>'`. Each individual row is built inside-out via repeated shuffling of the two chars (using `sample(...,2)`, since `random.shuffle` is unfortunately in-place) and string joining. A simplified example of what the expansion might look like for the fourth row is: ``` ''.join(['<','>']).join(['>','<']).join(['>','<']).join(['<','>']).join(['>','<']) ``` which would yield `><>><><<><`: ``` '' <> .join(['<','>']) > < .join(['>','<']) > < .join(['>','<']) < > .join(['<','>']) > < .join(['>','<']) ``` The overall quilt is also built inside-out, as construction begins with the 9th/10th rows, working outward. To do this we start with an empty list `L`, which we add rows to the front and back of as we go via ``` L=[s]+L+[[s,s[::-1]][n<"5"]] ``` The `n<"5"` condition is to check whether we have a row consisting of `><`, in which case we append an identical row to the back, otherwise its reverse. Finally, `*_,=` is to force the evaluation of `map` so printing occurs, and is just a shorter way to do `print("\n".join(L))`. For a long time I had the function ``` g=lambda s:s.translate({60:62,62:60,92:47,47:92}) ``` which takes a string and converts `/\><` to `\/<>` respectively, but I've finally managed to get rid of it :) [Answer] # Python 2, 300 bytes This program uses `join, lambda, replace, sample, import` and other verbose functions, so it will not be winning any golf awards. ``` from random import* f=lambda a,b,t:t.replace(a,'*').replace(b,a).replace('*',b) k=lambda a:''.join(sample(a*12,12)) c='-'*24 e=k('<>') h=e+f('<','>',e[::-1]) j=[d+f('/','\\',d[::-1])for d in[k('\\/')for i in'quilt']] g=['='*24,c,j[0],h,j[1],c]+j[2:] print'\n'.join(g+[f('/','\\',d)for d in g[::-1]]) ``` The code before the auto-golfer got hold of it: ``` from random import * change = lambda a,b,t: t.replace(a,'*').replace(b,a).replace('*',b) pick = lambda a: ''.join(sample(a*12, 12)) innerline = '-' * 24 line4h = pick('<>') line4 = line4h + change('<', '>', line4h[::-1]) diag = [d + change('/', '\\', d[::-1]) for d in [pick('\\/') for i in 'quilt']] quilt = ['='*24, innerline, diag[0], line4, diag[1], innerline] + diag[2:] print '\n'.join(quilt + [change('/', '\\', d) for d in quilt[::-1]]) ``` A sample output: ``` ======================== ------------------------ \\\\/\////\\//\\\\/\//// <><<>>>><><><><><<<<>><> /\\\\////\\\///\\\\////\ ------------------------ \\\\//\///\\//\\\/\\//// //\//\\\\/\/\/\////\\/\\ \/\\\\/\//\/\/\\/\////\/ /\////\/\\/\/\//\/\\\\/\ \\/\\////\/\/\/\\\\//\// ////\\/\\\//\\///\//\\\\ ------------------------ \////\\\\///\\\////\\\\/ <><<>>>><><><><><<<<>><> ////\/\\\\//\\////\/\\\\ ------------------------ ======================== ``` [Answer] # APL (~~53~~ 58) It's not *quite* as symmetrical as I thought it was, unfortunately. Fix cost me 5 characters and now I'm out of the running. ``` L←+,3-⌽⋄'==--/\<><'[↑(732451451260688⊤⍨18/8)+L{L?12⍴2}¨⍳9] ``` Explanation: * `L←+,3-⌽`: L is a function that returns its argument followed by 3 - the reverse of its argument * `L{L?12⍴2}¨⍳9`: generate 9 lines of 12 random values from [1,2] plus their reverse, then the reverse of those 9 lines * `732451451260688⊤⍨18/8`: generate the list `0 2 4 6 4 2 4 4 4 4 4 4 2 4 _7_ 4 2 0` (that's where the damn asymmetricality is) * `+`: for each line, add the corresponding number to each value * `↑`: format as matrix * `'==--/\<><'[`...`]`: for each of the numbers in the matrix, select the character from the string at that position Output: ``` ======================== ------------------------ ///////\\///\\\//\\\\\\\ <<><<><><<<<>>>><><>><>> \\\\\//\/\\\///\/\\///// ------------------------ /\///\\/\/\/\/\/\//\\\/\ \////////\//\\/\\\\\\\\/ \\/\\\//\///\\\/\\///\// //\///\\/\\\///\//\\\/\\ /\\\\\\\\/\\//\////////\ \/\\\//\/\/\/\/\/\\///\/ ------------------------ /////\\/\///\\\/\//\\\\\ <<><<><><<<<>>>><><>><>> \\\\\\\//\\\///\\/////// ------------------------ ======================== ``` [Answer] # PHP, 408, 407, 402, 387, 379 bytes I am not a good golfer, but this problem sounded fun so I gave it a try. ``` <?$a=str_replace;$b=str_repeat;function a($l,$a,$b){while(strlen($s)<$l){$s.=rand(0,1)?$a:$b;}return$s;}$c=[$b('=',12),$b('-',12),a(12,'/','\\'),a(12,'<','>'),a(12,'/','\\'),$b('-',12)];while(count($c)<9){$c[]=a(12,'/','\\');}for($d=9;$d--;){$c[$d].=strrev($a(['/','<','\\','>',1,2],[1,2,'/','<','\\','>'],$c[$d]));$c[]=$a(['/','\\',1],[1,'/','\\'],$c[$d]);}echo implode(" ",$c); ``` Ungolfed code ``` <?php function randomString($length, $a, $b) { $string = ''; while(strlen($string) < $length) { $string .= rand(0, 1) ? $a : $b; } return $string; } if(isset($argv[1])) { srand(intval($argv[1])); } $lines = [ str_repeat('=', 12), str_repeat('-', 12), randomString(12, '/', '\\'), randomString(12, '<', '>'), randomString(12, '/', '\\'), str_repeat('-', 12) ]; while(count($lines) < 9) { $lines[] = randomString(12, '/', '\\'); } for($index = count($lines); $index--;) { $lines[$index] .= strrev(str_replace(['/', '<', '\\', '>', 1, 2], [1, 2, '/', '<', '\\', '>'], $lines[$index])); $lines[] = str_replace(['/', '\\', 1], [1, '/', '\\'], $lines[$index]); } echo implode("\n", $lines) . "\n"; ?> ``` The ungolfed version has a little bonus: You can pass it an integer to seed `rand()` and get the same quilt each time for a seed: ``` php quilt.php 48937 ``` This results, for example, in this beautiful, hand woven quilt: ``` ======================== ------------------------ /\\\////\\\/\///\\\\///\ ><>><>><<<><><>>><<><<>< /\\\///\//\/\/\\/\\\///\ ------------------------ /\\/\\\/\\/\/\//\///\//\ /\\\\/\//\\/\//\\/\////\ \/\\/\/\////\\\\/\/\//\/ /\//\/\/\\\\////\/\/\\/\ \////\/\\//\/\\//\/\\\\/ \//\///\//\/\/\\/\\\/\\/ ------------------------ \///\\\/\\/\/\//\///\\\/ ><>><>><<<><><>>><<><<>< \///\\\\///\/\\\////\\\/ ------------------------ ======================== ``` **Edit**: Turns out my first version did not return a correct quilt. So I fixed it. Funny enough, the fix is even shorter. [Answer] # JavaScript (ES6) 169 ~~195 201~~ **Edit** 6 bytes saved thx @nderscore. Beware, the newline inside backquotes is significant and counted. **Edit2** simplified row building, no need of `reverse` and `concat` ``` F=(o='')=>[...z='/\\/-/<\\-='].map((c,i,_,y=[z,'\\/\\-\\>/-='],q=[for(_ of-z+z)Math.random(Q=k=>q.map(v=>r=y[v^!k][i]+r+y[v^k][i],r='')&&r+` `)*2])=>o=Q()+o+Q(i!=5))&&o ``` *Run snippet to test* (in Firefox) ``` F=(o='')=>[...z='/\\/-/<\\-='].map((c,i,_,y=[z,'\\/\\-\\>/-='],q=[for(_ of-z+z)Math.random(Q=k=>q.map(v=>r=y[v^!k][i]+r+y[v^k][i],r='')&&r+` `)*2])=>o=Q()+o+Q(i!=5))&&o Q.innerHTML=F() ``` ``` <pre id=Q style='font-size:9px;line-height:9px'> ``` [Answer] # Ruby, 162 155 I like this one because it made me learn to abuse backslashes in both string literals and `String#tr`. The code isn't terribly clever otherwise, just compact. ``` a='/\\' b='\\\/' t=Array.new(9){x='' 12.times{x+=a[rand(2)]} x+x.reverse.tr(a,b)} t[0]=?=*24 t[1]=t[5]=?-*24 t[3].tr!a,'<>' puts t,((t.reverse*' ').tr a,b) ``` [Answer] # Pyth, 57 ~~59 61~~ ``` J"\<>/"K"\/"L+b_mXdK_Kbjbym+d_XdJ_JmsmOk12[\=\-K-JKK\-KKK J"\<>/"K"\/"jbu++HGXHK_Km+d_XdJ_JmsmOk12[KKK\-K-JKK\-\=)Y ``` Thanks a lot to @Jakube for coming up with these 57 byte versions. Algorithm very similar to Martin's. (Revised) Explanation to come. [Try it online](https://pyth.herokuapp.com/?code=J%22%5C%3C%3E%2F%22K%22%5C%2F%22L%2Bb_mXdK_Kbjbym%2Bd_XdJ_JmsmOk12%5B%5C%3D%5C-K-JKK%5C-KKK&debug=0) Explanation: ``` =G"\<>/" : Set G to be the string "\<>/" K"\/" : Set K to be the string "\/" Jm+d_XdG_GmsmOk12[\=\-K"<>"K\-KKK; : Set J to be the top half of the carpet [\=\-K"<>"K\-KKK; : Make a list of possible chars for each row msmOk12 : for each element of that list, : make a list of 12 randomly chosen characters : from it, then join them Jm+d_XdG_G : for each element of that list, : make a new list with the old element, : and its horizontal reflection jb+J_mXdK_KJ : Print the whole carpet mXdK_KJ : For each element of J make its vertical reflection ``` [Answer] # J, ~~56~~ 54 bytes ``` '=/\<>--></\'{~(-,|.)0,(3(2})8$5,3#1)+(,1-|.)"1?8 12$2 ``` Usage: ``` '=/\<>--></\'{~(-,|.)0,(3(2})8$5,3#1)+(,1-|.)"1?8 12$2 ======================== ------------------------ ///\\\\/\///\\\/\////\\\ ><<><><>><>><<><<><><>>< \\/\//\\/\//\\/\//\\/\// ------------------------ \/\/\//////\/\\\\\\/\/\/ /\/\\//\//\\//\\/\\//\/\ //\\\\/////\/\\\\\////\\ \\////\\\\\/\/////\\\\// \/\//\\/\\//\\//\//\\/\/ /\/\/\\\\\\/\//////\/\/\ ------------------------ //\/\\//\/\\//\/\\//\/\\ ><<><><>><>><<><<><><>>< \\\////\/\\\///\/\\\\/// ------------------------ ======================== ``` 1 byte thanks to @FUZxxl. Explanation coming soon. [Try it online here.](http://tryj.tk/) [Answer] # Python 295 287 227 bytes Not that great but I'll post it anyway: ``` from random import* m,d=[],dict(zip("\/<>=-","/\><=-")) v=lambda w:[d[x]for x in w] for e in '=-/>/-///':f=[choice([e,d[e]])for x in[0]*12];t=''.join(f+v(f[::-1]));print t;m+=''.join(e=='/'and v(t)or t), print'\n'.join(m[::-1]) ``` If you want an explanation just ask me. [Answer] # Javascript (*ES7 Draft*) 174 168 146 Some inspiration taken from @edc65 Edit: Thanks to edc65 for some ideas to optimize building of rows. ``` F=(o='')=>[for(i of'555357531')(z=[for(_ of c='==--/\\<>golf')Math.random(r=x=>z.reduce((s,y)=>c[w=i^y^x]+s+c[w^1],'')+` `)*2],o=r()+o+r(i<7))]&&o ``` --- **Demonstration: (*Firefox only*)** ``` F=(o='')=>[for(i of'555357531')(z=[for(_ of c='==--/\\<>golf')Math.random(r=x=>z.reduce((s,y)=>c[w=i^y^x]+s+c[w^1],'')+` `)*2],o=r()+o+r(i<7))]&&o document.write('<pre>' + F() + '</pre>'); ``` --- **Commented:** ``` // define function, initialize output to '' F = (o = '') => // loop through character indexes of first 9 lines [ for (i of '555357531')( // build array of 12 random 0/1's, initialize character list z = [ for (_ of c = '==--/\\<>golf') Math.random( // define function for generating lines // if x is true, opposite line is generated r = x => z.reduce( (s, y) => c[w = i ^ y ^ x] + s + c[w ^ 1], '' ) + `\n` ) * 2 ], // build new lines and wrap output in them // x true in the second line for indexes < 7 (not character '>') o = r() + o + r(i < 7) ) ] // return output && o ``` [Answer] ## Pharo 4, 236 ``` |s i f v h|s:='====----/\/\/<><<>'.f:=[:c|s at:(s indexOf:c)+i].v:=#(),'=-/</-///'collect:[:c|h:=(String new:12)collect:[:x|i:=2atRandom.f value:c].i:=1.h,(h reverse collect:f)].i:=3.String cr join:v,(v reverse collect:[:k|k collect:f]) ``` or formatted normally: ``` |s i f v h| s:='====----/\/\/<><<>'. f:=[:c|s at:(s indexOf:c)+i]. v:=#() , '=-/</-///' collect:[:c| h:=(String new:12)collect:[:x|i:=2atRandom.f value:c]. i:=1. h,(h reverse collect:f)]. i:=3. String cr join:v,(v reverse collect:[:k|k collect:f]) ``` Explanation: The string `s:='====----/\/\/<><<>'` together with the block `f:=[:c|s at:(s indexOf:c)+i]` are here both for tossing the characters and for reversing the patterns... * For i=1, it performs horizontal reversion (`/` <-> `\` , `<` <-> `>` ). * For i=3, it performs vertical reversion (`/` <-> `\`) * For i=1 or 2 atRandom, it toss among `/` or `\`, `<` or `>` `'=-/</-///'` encodes the character type `c` that will feed the block `f` for the 9 first lines. `#() , '=-/</-///'` is a concatenation trick for transforming the String into an Array and thus collecting into an Array. The rest is simple concatenation after applying the horizontal/vertical symetry. ``` ======================== ------------------------ \\/\/\\\\/\/\/\////\/\// >>>><><><>><><<><><><<<< \/\/\//\///\/\\\/\\/\/\/ ------------------------ /\//\/\/////\\\\\/\/\\/\ \\//\//\\\/\/\///\\/\\// ////\\/\/\//\\/\/\//\\\\ \\\\//\/\/\\//\/\/\\//// //\\/\\///\/\/\\\//\//\\ \/\\/\/\\\\\/////\/\//\/ ------------------------ /\/\/\\/\\\/\///\//\/\/\ >>>><><><>><><<><><><<<< //\/\////\/\/\/\\\\/\/\\ ------------------------ ======================== ``` [Answer] ## Squeak 4.X, 247 ``` |r s h m n p|s:='==--/\<>'.r:=(1<<108)atRandom.h:=''.m:=0.(16to:0by:-2),(0to:16by:2)do:[:i|n:=3bitAnd:28266>>i.p:=0.(11to:0by:-1),(0to:11)do:[:j|h:=h,(s at:n*2+1+(r-1>>(6*i+j)+(101>>(3-n*4+m+p))bitAnd:1)).j=0and:[p:=1]].i=0and:[m:=2].h:=h,#[13]].h ``` Or formatted: ``` |r s h m n p| s:='==--/\<>'. r:=(1<<108)atRandom. h:=''. m:=0. (16to:0by:-2),(0to:16by:2) do:[:i| n:=3 bitAnd: 28266>>i. p:=0. (11to:0 by:-1),(0to:11) do:[:j| "h:=h,(s at:n*2+1+((r-1bitAt:6*i+j+1)bitXor:(101bitAt:3-n*4+m+p))). <- originally" h:=h,(s at:n*2+1+(r-1>>(6*i+j)+(101>>(3-n*4+m+p))bitAnd:1)). j=0and:[p:=1]]. i=0and:[m:=2]. h:=h,#[13]]. h ``` Explanations: `s:='==--/\<>'.` obviously encodes the four posible pairs. `r:=(1<<108)atRandom.` toss 108 bits (in a LargeInteger) for 9 rows\*12 columns (we toss the == and -- unecessarily but performance is not our problem). `h:=''`is the string where we will concatenate (Schlemiel painter because a Stream would be too costly in characters). `(16to:0by:-2),(0to:16by:2)do:[:i|` is iterating on the rows (\*2) `(11to:0by:-1),(0to:11) do:[:j|` is iterating on the columns `28266` is a magic number encoding the pair to be used on first 9 lines. It is the bit pattern `00 01 10 11 10 01 10 10 10`, where 00 encodes '==', 01 '--', 10 '/\' and 11 '<>'. `101` is a magic number encoding the horizontal and vertical reversion. It is the bit pattern `0000 0000 0110 1010`, encoding when to reverse (1) or not (0) the first (0) or second (1) character of each pair '==' '--' '/\' and '<>', for the vertical symetry and horizontal symetry. `n:=3 bitAnd: 28266>>i` gives the encoding of character pair for row i/2 (0 for '==', 1 for '--', 2 for '/\' and 3 for '<>'). `(r-1 bitAt: 6*i+j+1)` pick the random bit for row i/2 column j (1 is the rank of lowest bit thus we have a +1, k atRandom toss in interval [1,k] thus we have a -1). `(101 bitAt: 3-n*4+m+p)` pick the reversal bit: (3-n)\*4 is the offset for the group of 4 bits corresponding to the pair code n, m is the vertical reversion offset (0 for first 9, 2 for last 9 rows), p is the horizontal reversion offset (0 for first 12, 1 for last 12 columns)+1 because low bit rank is 1. `bitXor:` performs the reversion (it answer an offset 0 or 1), and `s at:2*n+1+bitXor_offset` pick the right character in s. But `(A>>a)+(B>>b) bitAnd: 1` costs less bytes than `(A bitAt:a+1)bitXor:(B bitAt:b+1)`thus the bitXor was rewritten and offset +1 on p is gone... `h,#[13]` is an ugly squeakism, we can concatenate a String with a ByteArray (containing code for carriage return). ``` ======================== ------------------------ /\/\\\/\//\/\/\\/\///\/\ ><>><<>>>><<>><<<<>><<>< ////\\////\\//\\\\//\\\\ ------------------------ /\\\/\\/\\//\\//\//\///\ \/\\/\//////\\\\\\/\//\/ \\\//\\\////\\\\///\\/// ///\\///\\\\////\\\//\\\ /\//\/\\\\\\//////\/\\/\ \///\//\//\\//\\/\\/\\\/ ------------------------ \\\\//\\\\//\\////\\//// ><>><<>>>><<>><<<<>><<>< \/\///\/\\/\/\//\/\\\/\/ ------------------------ ======================== ``` ]
[Question] [ ## Background *Note: This configuration was co-found by one of our fellow code golf enthusiasts, [Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb)* A [29 year old conjecture by John Conway](https://cp4space.hatsya.com/2022/01/14/conway-conjecture-settled/) about the Game of Life was recently solved. To quote Conway from the linked article: > > Indeed, is there a Godlike still-life, one that can only have existed > for all time (apart from things that don’t interfere with it)? > > > That is, a configuration in the game of life that could not have evolved but, if it exists, must have been part of the game's starting condition? The answer is yes, such still-lifes do exist, and the first one discovered looks like this: [![Primordial Still Life](https://i.stack.imgur.com/RNn7u.png)](https://i.stack.imgur.com/RNn7u.png) ## Task The challenge is simple: output this 22 by 28 primordial still-life as ascii text. Fewest bytes wins. Notes: * You can choose any characters you like to represent live and dead cells. * Trailing whitespace is allowed. * Allowed loophole: If you discover a *different* primordial still life, you may output that. Here it is with `x` for dead and for live: ``` xxxx xxxx xxxx x xx x xx x xx x xx x x xx x xx x xx x xx xxxx xxxx xxxx xxxx xxx x xx x xx x xx x xx x x xx x xx x xx x xx x xxxx xxxx xxxx xxxx xxxx x xx x xx x xx x xx x x x x xx x xx x xx x xx x xxxx xxxx xxxx xxxx xxxx x xx x xx x xx x xx x x xx x xx x xx x xx x xxxx xxxx xxxx xxxx xxxx x xx x xx x xx x xx x x x x xx x xx x xx x xx x xxxx xxxx xxxx xxxx xxxx x xx x xx x xx x xx x x xx x xx x xx x xx x xxx xxxx xxxx xxxx xxxx xx x xx x xx x xx x x xx x xx x xx x xx x xxxx xxxx xxxx ``` And here it is with `1` for dead and `0` for live: ``` 0000001111001111001111001000 0001101001101001101001101000 0001011001011001011001011000 1111001111001111001111001110 0010110010110010110010110010 0100110100110100110100110100 1111001111001111001111001111 1001101001101001101001101001 1001011001011001011001011001 1111001111001111001111001111 0010110010110010110010110010 0100110100110100110100110100 1111001111001111001111001111 1001101001101001101001101001 1001011001011001011001011001 1111001111001111001111001111 0010110010110010110010110010 0100110100110100110100110100 0111001111001111001111001111 0001101001101001101001101000 0001011001011001011001011000 0001001111001111001111000000 ``` [Answer] # [Nibbles](http://golfscript.com/nibbles), 37 33 bytes ``` ?, &" ";3 ! = $ `. ;~ `/ $ `D -2 :;!$ `' \@:.\$\$ `'<14>>^_$ `. 5 ~/$~ ~ >@$ @$ ~ 15a ``` That's 66 nibbles, each taking half a byte in the binary form. This could probably be improved, and will definitely be beaten by the things that specialize in ascii art as it uses rotate which nibbles doesn't have as a built in. BTW the trivially binary encoded way is 82 bytes in nibbles (use `D -2 and reverse the result to deal with 0 prefixes). Run it like this: ``` > nibbles life.nbl aaaa aaaa aaaa a aa a aa a aa a aa a a aa a aa a aa a aa aaaa aaaa aaaa aaaa aaa a aa a aa a aa a aa a a aa a aa a aa a aa a aaaa aaaa aaaa aaaa aaaa a aa a aa a aa a aa a a a a aa a aa a aa a aa a aaaa aaaa aaaa aaaa aaaa a aa a aa a aa a aa a a aa a aa a aa a aa a aaaa aaaa aaaa aaaa aaaa a aa a aa a aa a aa a a a a aa a aa a aa a aa a aaaa aaaa aaaa aaaa aaaa a aa a aa a aa a aa a a aa a aa a aa a aa a aaaa aaaa aaaa aaaa aaaa a aa a aa a aa a aa a a a a aa a aa a aa a aa a aaaa aaaa aaaa aaaa aaaa a aa a aa a aa a aa a a aa a aa a aa a aa a aaa aaaa aaaa aaaa aaaa aa a aa a aa a aa a a aa a aa a aa a aa a aaaa aaaa aaaa ``` ## How? It starts with the basic building block of ``` # # ## # ``` which concatenated as bits is 346 or 15a in hex. This is extracted to space and 'a' with ``D -2` and put into groups of 3 with ``/ 3` It then rotates this clockwise with transpose of the reverse ``'\` and appends the lines with `! <lhs> <rhs> :` Finally this is rotated 180 degrees by reversing it and each line. This constructs the basic square that you can see in the image with the hairs going out. ``` a a a aaaa a aa aa a aaaa a a a ``` This is then replicated 3 times x and y and truncated to the window (14). Then we remove 5,2,1 spaces (generated by iterating /2 starting from 5) from the front using a zip with a custom fn (drop). This is justified with `&" "` using a size of 3, but really any value <= 14 would work since it also checks the max size of any element. 3 is used because that value is saved and used in 3 other places (saving 1 nibble each in binary form). ``` aaaa aa aa a aa a a aa a aa aaaa aaaa aa a aa a aa a aa a aa a aaaa aaaa aa a aa a aa a a a aa a aa aaaa aaaa aa a aa a aa a aa a aa a aaaa aaaa aa a aa a aa a ``` The really cool thing is that the final product can also be constructed by a rotation of this. And so this rotation code is saved as a function using `;~`. It is a bit awkward to call as it needs to know the return type by calling it on some function before it is finished being defined. But here we want to call it on the result of calling it, which can't be done. So instead I take the result and put it into an if statement on a list `?,` it will be true and inside the true clause `$` will be the value we want to call the function on. The `<14>>^3` code was also repeated and had the same issue, but here I used iteration and took the 3rd element so that the code was applied twice. Edit: Zgarb confirmed that the 28x28 version is also a still life (it is fully rotationally symmetric). This saved 2 bytes by not having to do `<11` to trunctate during the final rotation. Thanks! [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 131 bytes ``` Uncompress@"1:eJxTTMoPCt7DxMBgAAaGQIBGAkVjDAyNwJIGhthIuLwBRAM6CZbHYjKMhOrHpR0qj9VqCEnAfEOwPG7tcHlcDiDG/JHufgOC5lOWfsDyWMwHAQA6Moq3" ``` [Try it online!](https://tio.run/##BcFtCoIwAADQq4QXqIiUgqC5yaa1plJKRT/WUKf57WR6enuv4komFVe54AtfnZZHLZqq7ZNhOBvbY@JN9zttfKgsNFE7A4DjwLUx@EUFAvNNey6WSrrjVdshoCZ8fcmzuFDJetKGm644RB10apA6TPvYUoKUAuUIrz0yphmD@5LF6YDmmGoCAmDSptsZi9/ntXrzz/IH "Wolfram Language (Mathematica) – Try It Online") Uses `1` for dead cells, `0` for living and background (grey) cells. A boring answer using Mathematica's [`Uncompress`](http://reference.wolfram.com/language/ref/Uncompress.html) built-in. --- # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/) + my [LifeFind](https://github.com/AlephAlpha/LifeFind) package, 147 bytes ``` <<Life` SeedRandom@1703 a=ArrayPad[SearchPattern[6,6,Agar->1>0][[1]],{{9,7},{9,13}},Periodic] Do[a[[i,1;;7-2i]]=1;a=Reverse@a,4,{i,3}] Print@@@a ``` Uses `0` for dead cells, `1` for living and background (grey) cells. Spent some time to find the correct random seed... I wrote this package to find interesting patterns in Conway's Game of Life and other cellular automata. `SearchPattern[6,6,Agar->1>0]` tries to find a 6x6 stable [agar](https://www.conwaylife.com/wiki/Agar). When the random seed is `1703`, it finds the following pattern: ``` ## # ## # # # ## # ## # ## ``` After that, the code pads the pattern periodically to a 22x28 array, and sets the background cells at the corners to `1` (this part takes so many bytes!), and then prints the result. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes ``` G↘³↓²↘²↓¹⁵↙³←²↙²←²¹↖³↑²↖²↑¹⁵↗³→²↗²”{“↧n⍘∨)¿UV·÷Σ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8gP6cyPT9Pw8olvzwvKDM9o0RHwVhHAczVUTCCsqASRnAJQ1Mo0yc1DaoDwjJCETdCiBsCmaEFCOWhBRBpmJgRVAxscmgBklOQLIeLAzlKFUAQk1ehoACjFEA0WBDMAdFgWSVN6////@uW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Works by defining a polygon that outlines the configuration and filling it with the 6×6 pattern. (The top left corner actually has coordinates `(0, -24)` but as the fill is 6×6 it comes to the same thing.) I also tried a number of other approaches. Simply printing a compressed string took [63 bytes](https://tio.run/##S85ILErOT8z5/z@gKDOvRENJAQwqgACNBIrG5IGlFCqwkVBZBYhidBIoi8VMGAnWi0srWLYCt8V4Ta4AyuLWCpXFZTEhk0eamxUImEx@2gDLYjEZBJQ0rf///69blgMA). Printing half of the string twice, rotating in between, took [61 bytes](https://tio.run/##S85ILErOT8z5/z8tv0hBw0hToZqLM6AoM69EQ0mhQkGhogI7GZNXAQQgHjYSKItbK1RWoQI7SchkPFqBrsLvZgUCJuPUqgCRxWExTBaLySCgpGnNxRmUX5JYkqphAmL75pelahjqKBgaAnm1////1y3LAQA). Filling an array with the pattern and then deleting the corners took [54 bytes](https://tio.run/##RU7BCsIwDL37FaGnFCrI8CDsNAaC4ECcRy9j1q1Q262dun19TXVqDi95L@G91G3lalvpEDLvVWMwn2ot89Z2WFQdlp1WA7KRCuBsCGj4dBipz/qbEof3ARPAzoZxAX8zJSDZcJKShKDn6eJqHeCaw5wb07JhZy5yxF7Aiq7KwSnTxMVRPqTzEntST9KZyk24l96jEbDV1jo82Kd0mAgolLn7OGjOYx4DeudrfPvJ8YMD2Q/kmYYQlg/9Ag). Drawing a rectangle with the pattern and then deleting the corners took [49 bytes](https://tio.run/##fY5NC8IwDIbP268IO6VQL0VU8Lpr9eLRyz7qLNRGunYMxN9e4@bZQPImIXmS7t6EjhqX87l15AdUBwlKSahmNoCr58DJqjCz/vpLyTUsA5U4ljcKgFsBr7LQyUX7DNZHrG0wXbTk8WSGJhqsKbXO9GiFEHwHYKWxfyGFpsmgtj6NqPYSLvZhRtxJ0NQnR2j5vWXxL5dB75zzZnIf). [Answer] # Excel, ~~137~~ 89 characters, 171 bytes Taylor Raine did their thing. ``` =BASE(UNICODE(MID("ó㏈ښᩨ֖ᙘ㳳㏎ବⲲፍഴ㳳㏏⚚ᩩ▖ᙙ㳳㏏ବⲲፍഴ㳳㏏⚚ᩩ▖ᙙ㳳㏏ବⲲፍഴᳳ㏏ښᩨ֖ᙘӳ㏀",SEQUENCE(22,2),1)),2,14) ``` There's a possibility the exact characters won't translate well from Excel to the browser, so here's the encoded string as list of Unicode codes instead (keeping in mind that some are two bytes wide): ``` 243, 13256, 1690, 6760, 1430, 5720, 15603, 13262, 2860, 11442, 4941, 3380, 15603, 13263, 9882, 6761, 9622, 5721, 15603, 13263, 2860, 11442, 4941, 3380, 15603, 13263, 9882, 6761, 9622, 5721, 15603, 13263, 2860, 11442, 4941, 3380, 7411, 13263, 1690, 6760, 1430, 5720, 1267, 13248 ``` The approach takes the (probably not optimized) approach of breaking the desired into chunks and storing those as Unicode characters. The function takes that string, converts each character to its binary equivalent, then breaks it into 2 columns of 14 bit chunks. --- Let's start by shortening the formula. We'll refer to this whole mess as `string`: ``` "ó㏈ښᩨ֖ᙘ㳳㏎ବⲲፍഴ㳳㏏⚚ᩩ▖ᙙ㳳㏏ବⲲፍഴ㳳㏏⚚ᩩ▖ᙙ㳳㏏ବⲲፍഴᳳ㏏ښᩨ֖ᙘӳ㏀" ``` Now the formula looks like this: ``` =BASE(UNICODE(MID(string,SEQUENCE(22,2),1)),2,14) ``` * `SEQUENCE(22,2)` creates an array 2 columns wide and 22 rows tall for 44 total items in the array. `string` is 44 characters long so that'll fit nicely. It counts over then down like this: > > > ``` > | 1 | 2 | > | 3 | 4 | > | 5 | 6 | > > ``` > > * `MID(string,SEQUENCE(~),1)` pulls out each character from `string` one at a time. * `UNICODE(MID(~))` converts those characters to their (decimal) unicode number. * `BASE(UNICODE(~),2,14)` converts those decimal numbers to their binary equivalent with each result padded with leading zeros so they're at least 14 bits long. The end result is two columns of data as shown in the screenshot below. I also split out the results into individual cells and added conditional formatting to show the results visually. The formula is only in cell `A1` and the output automatically spills into the range `A1:B22`. [![Result](https://i.stack.imgur.com/1wPCT.png)](https://i.stack.imgur.com/1wPCT.png) --- ~~I don't know what kind of ritual I need to perform to summon Taylor Raine but I'm sure they can improve upon this bloated answer. I already tried using chunks longer than 16 bits but it starts breaking in weird ways.~~ [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 87 bytes ``` »ƛUċ≬r¾□ƈ1K↵ẏǐṅȧꜝq6⟩λ∵†⇧↳∨¬ṫ«X¡„q∪[>±∩λxƒẊ[øȧẇ/hAh<∨T⅛⇧¥WnWU°⋎ƈ_S↳‡a∑⋏‡ø¨z≈cƛ÷a»₀Sτ22/⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCu8abVcSL4omscsK+4pahxogxS+KGteG6j8eQ4bmFyKfqnJ1xNuKfqc674oi14oCg4oen4oaz4oiowqzhuavCq1jCoeKAnnHiiKpbPsKx4oipzrt4xpLhuopbw7jIp+G6hy9oQWg84oioVOKFm+KHp8KlV25XVcKw4ouOxohfU+KGs+KAoWHiiJHii4/igKHDuMKoeuKJiGPGm8O3YcK74oKAU8+EMjIv4oGLIiwiIiwiIl0=) Naive base compression. ``` »...» # Base-255 compressed integer ₀Sτ # Decompress into base 22 with 1s and 0s 22/⁋ # Split into 22 pieces and join on newlines ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 85 bytes ``` “¦÷fİȷ⁻ƒỌU,ɠṘµINọþọ^°56ß~+Œ:ḟyṘdạʠȷẇḌẆ[ŻṁỤ°8zẉݬ{ḋzỵḣuṄ}Ṗj|ĠỌ½Ɲœiḥd⁷ɦȮʋḢ/iÇØ#¤œ’Bs28Y ``` [Try it online!](https://tio.run/##AawAU/9qZWxsef//4oCcwqbDt2bEsMi34oG7xpLhu4xVLMmg4bmYwrVJTuG7jcO@4buNXsKwNTbDn34rxZI64bifeeG5mGThuqHKoMi34bqH4biM4bqGW8W74bmB4bukwrA4euG6icSwwqx74biLeuG7teG4o3XhuYR94bmWanzEoOG7jMK9xp3Fk2nhuKVk4oG3yabIrsqL4biiL2nDh8OYI8KkxZPigJlCczI4Wf// "Jelly – Try It Online") Boring compression approach, but hey, it beats Vyxal. Outputs `1` for dead and `0` for live. ## How it works ``` “¦÷...#¤œ’Bs28Y - Main link. “¦÷...#¤œ’ - Compressed base-250 number; 267895893890769127503254177532545466822034310678965401690230443467397769491824224432265750760013635073235874891500166493638274198855494319824095093907255178782140555126842877012017876031 B - Binary s28 - Split into chunks of size 28 Y - Join by newlines ``` Fun fact, using base 2 is the [shortest](https://tio.run/##y0rNyan8///h7i1hj5rWAJHbwx2tjzauO7H94Y6uQ1sf7mg2MjV4uLv78AyvR43bdQwtjA4tqXy4u@dR475HDXMeNczM0vQ5POHhzqb///8bgoEBEKCRQFEusIyhATYSImkIUYpOGnJhMRBGgnTi0giSNMBtKT5jDbjwaIRI4rIUv7EjxbWG@I0lNyWAJbEYCwIA "Jelly – Try It Online") of all approaches in the form "large compressed number, to base, split" [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~46~~ 45 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Commands) ``` Ƶöb3ô4FDøí‚øJÂí«}¦22£€¦4F28£øíεN3‹i411NèFX0.; ``` Port of [*@DarrenSmith*'s Nibble answer](https://codegolf.stackexchange.com/a/241217/52210), so make sure to upvote him as well! Uses the legacy version of 05AB1E to save 2 bytes, since it can zip/transpose with lists of strings, whereas the new version requires a character-matrix instead. Outputs as a list of lines, with `1`/`0` for dead/alive respectively. [Try it online](https://tio.run/##AVoApf8wNWFiMWX//8a1w7ZiM8O0NEZEw7jDreKAmsO4SsOCw63Cq33CpjIywqPigqzCpjRGMjjCo8O4w63OtU4z4oC5aTQxMU7DqEZYMC47/13Cu1TigJ54IOKAof8) (feel free to remove the footer to see the actual output). **Explanation:** ``` Ƶö # Push compressed integer 346 b # Convert it to binary: 101011010 3ô # Split it into parts of size 3: ["101","011","010"] 4F # Loop 4 times: D # Duplicate the list of strings øí # Rotate it 90 degrees clockwise: ø # Zip/transpose; swapping rows/columns í # Reverse each inner string ‚ # Pair it together with the original list of strings ø # Zip/transpose to create pairs of lines J # Join those inner pairs together to a single line  # Bifurcate this list (short for Duplicate & Reverse copy) í # Reverse each line in the reversed copy « # Merge these lines to the list } # Close the loop # (we now have a grid of 48x48 characters) ¦ # Remove the first line 22£ # Then keep just the first 22 lines € # Map over each remaining line: ¦ # Remove the first character 4F # Loop 4 times again: 28£ # Keep just (up to) the first 28 characters øí # Rotate 90 degrees clockwise again ε # Map over each line: N3‹i # If this is one of the first three lines: 411Nè # Index the map-index into [4,1,1] F # Loop that many times: X0.; # Replace the first 1 with a 0 # (after which the list of lines is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ƶö` is `346`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 193 bytes ``` (x='xxxx ',y='xx x ',z='x xx ',h=` ${e=x+x+x}x ${g=' '+y+y+y+y} ${c=' '+z+z+z+z} ${b=e+x+'xxx'} ${c}x x${g} ${b}x x${g}x x${c}x ${b}x ${c}x `)=>h+` `+[...h].reverse().join`` ``` [Try it online!](https://tio.run/##LY1bDoMgEEX/WcV8mAChZQd0I00TLB1fMdKoMahh7XSEzv2YO2deQ73Vi5v773qf/AdTY5IIhgcKAH7bLwvZHmSh0M5YyFGdaIIiReLAqG4Npwm1F8XMXGFHEbHqfBuktesNz7WjAwwC7cerGwPLPifq/VmZs9I8OmWZVU@tdffSM244LyikHnw/WZucnxY/oh59KxohZfoB "JavaScript (Node.js) – Try It Online") Here we go... A lot of variables, dollar signs, curly braces, single quotes, pluses, and a tiny reverse at the end. [Answer] # Excel, 111 bytes ``` AO1 =IF(I1:AJ22,,INDEX(A1:F6,MOD(ROW(6:27),6)+1,MOD(COLUMN(F:AG),6)+1)) ``` [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJngYYXFl9HxhgwgPC?e=NbFKBB) `A1:F6` contains the repeating pattern. `I1:AJ22` contains a mask for blank cells. Takes advantage of the spreadsheet structure. The code is 67 bytes, pattern is 20 bytes, mask is 24 bytes for a total of 111 bytes. Not as clever as @EngineerToast 's answer but it gets the job done. [Answer] # JavaScript (ES6), ~~113~~ 106 bytes Outputs a string of `0`'s and `1`'s. ``` f=(n=616)=>--n&&((x=n>>8?615-n:n,y=x/28|0,x%=28)>=5>>y&x<24+y+!y&21703951>>x%6+y%6*45%71)+[` `[n%28]]+f(n) ``` [Try it online!](https://tio.run/##BcHRCsIgFADQ9/6iB0Vz1rTpLPL2IWOwsWYU4xotQqF/t3Oe43dcp/fj9ZEYb3MpwTP0VlnuQUqklLHkEcBdrTISz1hlnw7a/eoqEa8dB28AMk0X3Ygstplq1dbHk1EAiViRid01hrSKi27YDB0S7fpeBIa8TBHXuMz7Jd5ZYJyXPw "JavaScript (Node.js) – Try It Online") ### How? We use the following formula to get the state of the cell of the \$6\times6\$ pattern at \$(x,y)\$: ``` 21703951 >> x + y * 45 % 71 ``` The cell is alive if the result is odd or dead if it's even. Notes: * Because bitwise operations are limited to 32 bits, we cannot use a 36-bit bitmask. * The value of the shift is implicitly reduced modulo \$32\$ as per the ECMAScript specification. [Try it online!](https://tio.run/##Nc1RCoJAEAbgd0/xv9RqS@FWJrVpF@lFTKMSJ1wJI3zvBB2wi2yjJswwDP/HzDV5JCatLvd6XtIps7bIahAiCKGdnCq325@8@5rHHhseUnp4OUAXmT8FRtwMuBlwM@KB3zhcqtBfbQOFOGYl@ewM6wAThEr30EBGLKdQOEB8P28ugR0E0H9quakzDPsWx5KD1kmpNFRki4LOLgOQp639AQ "JavaScript (Node.js) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 108 bytes ``` j=4 28.times{|i|printf"%022b ","O)YO24"[i%6].ord%64*266305&2**(23-k=j.abs)-2**k>>1-(i-4)%24/23 i%23<4&&j-=1} ``` [Try it online!](https://tio.run/##DcdLDsIgEADQPccgGVKIYDuMxIX0Cl0b40KiJkPjJ7QujPXs6Nu98krvWnMkgVs38@0yfRZenoXv81VCi5iEXMlB7wckeWAIR/coZwhkMATfbhQa06C3Y8zulCZt/x/7vrMNW9KAtEYvGNDvSKlsY/et9Qc "Ruby – Try It Online") Prints the pattern rotated 90 degrees (which per comments from OP is allowed because it's still primordial.) The output is a binary matrix produced line by line as the bitwise `AND` of the following: ``` "O)YO24"[i%6].ord%64*266305 ``` Four copies of the repeating pattern (the character encodes the bitmap, the `%64` removes spurious bits to the left and the constant `266305` is `100000100000100001` in binary) ``` 2**(23-k=j.abs)-2**k>>1-(i-4)%24/23 ``` This is a mask consisting of a long string of `1`'s followed by a short string of `0`'s according to the formula `2**(23-k)-2**k`. As the pattern gets wider, `k` reduces from 4 to 0, stops reducing, then increases back to 4. This is done by varying `j` on the last line. To ensure the spurious output in the 23rd and 24th bits (those on the left) are deleted, the mask must be shifted one place to the right. But to get the pinwheel effect this should not occur on the 4th and 28th row. This is achieved by `>>1-(i-4)%24/23` [Answer] # [Perl 5](https://www.perl.org/) + `-p0513`, 95 bytes Outputs `0`s and `1`s, transliterated in the link. ``` $_=unpack"B*",'..<...h.Ye.<..'.',..$.M4..<...i.Ye.<..'x2 .',..$.M4s.<...h.Ye.<..';s/.{28}\K/./g ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiMDAwMDAwMDA6IDI0NWYgM2Q3NSA2ZTcwIDYxNjMgNmIyMiA0MjJhIDIyMmMgMjcwMyAgJF89dW5wYWNrXCJCKlwiLCcuXG4wMDAwMDAxMDogY2YzYyA4MWE2IDlhNjggMTY1OSA2NThmIDNjZjMgY2UyNyAyZTI3ICAuPC4uLmguWWUuPC4uJy4nXG4wMDAwMDAyMDogMmNiMiBjYjI0IGQzNGQgMzRmMyBjZjNjIGY5YTYgOWE2OSA5NjU5ICAsLi4kLk00Li48Li4uaS5ZXG4wMDAwMDAzMDogNjU5ZiAzY2YzIGNmMjcgNzgzMiAyMDJlIDI3MmMgYjJjYiAyNGQzICBlLjwuLid4MiAuJywuLiQuXG4wMDAwMDA0MDogNGQzNCA3M2NmIDNjZjEgYTY5YSA2ODE2IDU5NjUgODEzYyBmM2MwICBNNHMuPC4uLmguWWUuPC4uXG4wMDAwMDA1MDogMjczYiA3MzJmIDJlN2IgMzIzOCA3ZDVjIDRiMmYgMGEyZiA2NyAgICAnO3MvLnsyOH1cXEsvLi9nIiwiZm9vdGVyIjoiIyB0byBwcmV0dHkgcHJpbnQgdGhlIG91dHB1dFxuO3kvMDEvIHgvIiwiYXJncyI6Ii1wMDUxMyJ9) ## Explanation `unpack`s the binary representation from characters (repeating the duplicated section in the middle using string repetition - `x`) before inserting newlines every 28 characters. Probably not optimal but, was do-able on mobile! ]
[Question] [ You may know the game [*The Six Degrees of Kevin Bacon*](https://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon), based on the conjecture that every actor in Hollywood can be connected to Kevin Bacon by no more than 6 "co-star" relations, so Kevin Bacon is supposedly the "best-connected" node in that graph. Your task will be to find the Kevin Bacon of a graph. We will use positive integers to represent actors, and use a list of pairs which defines the relations of the graph (adjacency list). For example, `[(1, 2), (2, 3)]` defines that `1` has costarred with `2`, and `2` has costarred with `3`. We will measure "connectedness" using *average shortest path length*: * The shortest path length is the number of steps in the shortest path between two given nodes. In the example graph above, the shortest (and also only) path between `1` and `3` is `1 -> 2 -> 3`, which has path length 2 * The average shortest path length of a node `A` is the mean of the shortest path lengths between `A` and each other node in the network Your task is to, given an adjacency list, find the best-connected node in the graph. That is, find the node `A` such that this average is minimised, and output its number. If there are multiple nodes with the same average shortest path length, you may output any of them. ## Worked example Consider the small graph: ``` 1-----2 / \ | 3---4 5 ``` which would be represented by the adjacency list: ``` [(1, 2), (2, 5), (1, 3), (1, 4), (3, 4)] ``` Now we compute the shortest path length between each pair of nodes (ignoring the relations between nodes and themselves): ``` |1 2 3 4 5 --+--------- 1 | 1 1 1 2 2 |1 2 2 1 3 |1 2 1 3 4 |1 2 1 3 5 |2 1 3 3 ``` For each node we can then compute the average of its path lengths to all the other nodes: ``` 1 ~> 1.25 [ (1+1+1+2)/4 = 5/4 = 1.25 ] 2 ~> 1.5 3 ~> 1.75 4 ~> 1.75 5 ~> 2.25 ``` So node `1` has the smallest average shortest path length, so the output is `1`. ## Rules * You may assume the input is non-empty, contains no self-referential pairs (like `(3, 3)`), and no duplicate edges (like `[(3, 1), (1, 3)]`) * You may assume all nodes of the graph are connected somehow (for example, you don't have to handle `[(1, 2), (3, 4), (5, 3)]`) * You may assume the set of integers used for node IDs is `1` to `N` (inclusive) for some N. For example, you don't have to handle `[(1, 54), (54, 128)]` nor `[(2, 3), (2, 4)]` + You may alternately choose to assume this range is `0` to `N-1` * You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447) * [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 the shortest code in bytes wins ## Test cases ``` Input: [(1, 2), (2, 5), (1, 3), (1, 4), (3, 4)] Output: 1 Input: [(1, 2), (2, 3), (3, 4), (4, 5)] Output: 3 Input: [(1, 2), (2, 3), (3, 4), (4, 1), (2, 5)] Output: 2 Input: [(1, 2)] Output: 1 or 2 Input: [(6, 1), (5, 2), (2, 1), (1, 5), (6, 3), (6, 4), (3, 4), (6, 2), (3, 7)] Output: 6 ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/)\*, ~~53~~ 45 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` {1+⊑⍒+˝+´(∨∨∨˝∘×⎉1‿∞)⍟n˜∨⟜⍉∨˝𝕩≡⌜1+⋈⌜˜n←↕⌈´∾𝕩} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgezEr4oqR4o2SK8udK8K0KOKIqOKIqOKIqMud4oiYw5fijokx4oC/4oieKeKNn27LnOKIqOKfnOKNieKIqMud8J2VqeKJoeKMnDEr4ouI4oycy5xu4oaQ4oaV4oyIwrTiiL7wnZWpfQoKCj7ii4jin5xG4oiY4oCiSnPCqCDin6giW1sxLCAyXSwgWzIsIDVdLCBbMSwgM10sIFsxLCA0XSwgWzMsIDRdXSIKIltbMSwgMl0sIFsyLCAzXSwgWzMsIDRdLCBbNCwgNV1dIgoiW1sxLCAyXSwgWzIsIDNdLCBbMywgNF0sIFs0LCAxXSwgWzIsIDVdXSIKIltbMSwgMl1dIgoiW1s2LCAxXSwgWzUsIDJdLCBbMiwgMV0sIFsxLCA1XSwgWzYsIDNdLCBbNiwgNF0sIFszLCA0XSwgWzYsIDJdLCBbMywgN11dIuKfqQo=) **Theory:** Let \$k\$ be the maximum node id. Then the node IDs are \$\{1, 2, ..., k\}\$. For the given adjacency list we can construct an adjancency matrix \$A=(a\_{ij}) \in \{0,1\}^{k \times k}\$, where \$a\_{ij} = 1\$ iff \$i=j\$ or node \$i\$ and node \$j\$ are adjacent. The distance between two nodes in the graph is given by the smallest \$m\$, such \$A^m\$ has a non-zero entry at the position.† **Implementation:** [`∨⟜⍉∨˝𝕩≡⌜1+⋈⌜˜n←↕⌈´∾𝕩`](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge+KIqOKfnOKNieKIqMud8J2VqeKJoeKMnDEr4ouI4oycy5xu4oaQ4oaV4oyIwrTiiL7wnZWpfQoKRiAoMeKAvzIp4oC/KDLigL81KeKAvygx4oC/MynigL8oMeKAvzQp4oC/KDPigL80KQ==) Convert the adjacency list to a modified adjacency matrix \$A-I\_k\$ with zeros on the diagonals. This part is a bit lengthy, maybe `∊` can be used? [`(∨∨∨˝∘×⎉1‿∞)⍟n˜`](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeyjiiKjiiKjiiKjLneKImMOX4o6JMeKAv+KIninijZ9uy5ziiKjin5zijYniiKjLnfCdlaniiaHijJwxK+KLiOKMnMucbuKGkOKGleKMiMK04oi+8J2VqX0KCkYgKDHigL8yKeKAvygy4oC/NSnigL8oMeKAvzMp4oC/KDHigL80KeKAvygz4oC/NCk=) Calculate \$A-I\_k, \mathop{sign}(A^2), \mathop{sign}(A^3), \cdots, \mathop{sign}(A^{k-1})\$. In [normal matrix multiplication](https://mlochbaum.github.io/bqncrate/?q=matrix%20multiplication%20of#) you would use `+` instead of `∨`, but here we only care for zero / non-zero. [`+˝+´`](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeyvLnSvCtCjiiKjiiKjiiKjLneKImMOX4o6JMeKAv+KIninijZ9uy5ziiKjin5zijYniiKjLnfCdlaniiaHijJwxK+KLiOKMnMucbuKGkOKGleKMiMK04oi+8J2VqX0KCkYgKDHigL8yKeKAvygy4oC/NSnigL8oMeKAvzMp4oC/KDHigL80KeKAvygz4oC/NCk=) Sum the resulting \$k\$ matrices, then each row. This is some kind of *inverse summed shortest path length*. This could be converted to the *average shortest path length*, but that step is not necessary as the order is the same, but reversed. [`1+⊑⍒`](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgezEr4oqR4o2SK8udK8K0KOKIqOKIqOKIqMud4oiYw5fijokx4oC/4oieKeKNn27LnOKIqOKfnOKNieKIqMud8J2VqeKJoeKMnDEr4ouI4oycy5xu4oaQ4oaV4oyIwrTiiL7wnZWpfQoKCj7ii4jin5xG4oiY4oCiSnPCqCDin6giW1sxLCAyXSwgWzIsIDVdLCBbMSwgM10sIFsxLCA0XSwgWzMsIDRdXSIKIltbMSwgMl0sIFsyLCAzXSwgWzMsIDRdLCBbNCwgNV1dIgoiW1sxLCAyXSwgWzIsIDNdLCBbMywgNF0sIFs0LCAxXSwgWzIsIDVdXSIKIltbMSwgMl1dIgoiW1s2LCAxXSwgWzUsIDJdLCBbMiwgMV0sIFsxLCA1XSwgWzYsIDNdLCBbNiwgNF0sIFszLCA0XSwgWzYsIDJdLCBbMywgN11dIuKfqQo=) Get the 1-based index of the maximum value. Using 0-indexing for the node IDs would save two bytes. \*[According to the documentation, in this situation the name can be pronounced *bacon*](https://mlochbaum.github.io/BQN/#what-kind-of-name-is-bqn) †Slightly longer explanation can be found [on Wikipedia](https://en.wikipedia.org/wiki/Adjacency_matrix#Matrix_powers) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes -12 bytes thanks to @att. ``` g#&@@SortBy[##&@@@g,Tr[g~GraphDistance~#]&] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@z/9/aSFymoODsH5RSVOldHKILZDuk5IUXR6nXtRYkGGS2ZxSWJecmqdcqxa7P@Aosy8kmhlBV07hbRo5dhYBTUFfQeF6mpDBRugkJGOghGYYaqjABExhjFMdBSMIYxaHQV05cZwSR0FE4gBRKkyhNuHpBzENINJm6IaYQhzDtCBZjBDzdAcCBMxgomY19b@BwA "Wolfram Language (Mathematica) – Try It Online") Takes input as a list of `a <-> b`s, e.g. `{1 <-> 2, 2 <-> 5, 1 <-> 3, 1 <-> 4, 3 <-> 4}`. Sadly the `GraphCenter` built-in uses the *maximal* (instead of *average*) shortest path length. [Answer] # [J](http://jsoftware.com/), 72 71 73 bytes ``` 1+[:(i.<./)1#.[:+/@(*#\)2-~/\0,[:+./ .*^:a:~@(+[:=#\)[:+/](-{.1:)"1@,|."1 ``` [Try it online!](https://tio.run/##XY3LCsIwEEX3fsXQCk36mDRpEzFYKAiuXLltFUQs6sYPUPrrcZLiA8lrcubk5uYiTAZoLCSQQwmWVoGw3m03TmadZVdcoeAyxs5momVp3HNVjKIvcwIoANODPdqxZSQ31PTanhUPlJZHss2fGEnHZ@fT5Q4SGhhAg4I51QpoaqCq8lsNdNaTWAWx/oiKCDVp6ElQf0lfwd/073fyLU3QBLgM0BDW4bUMlaEMQxk@yYTMhXsB "J – Try It Online") **Input:** 1-indexed adjacency list. **Output:** 1-indexed answer. ## how Consider: ``` 1 2 2 5 1 3 1 4 3 4 ``` * `[:+/](-{.1:)"1@,|."1` - Converts the adjacency list to an adjacency matrix. This was the hardest part to golf, and it's still long. + `]...,|."1` First we concatenate the list with a copy of itself, with each row reversed: ``` 1 2 2 5 1 3 1 4 3 4 2 1 5 2 3 1 4 1 4 3 ``` + `(-{.1:)"1` - Then we create matrices of each of those sizes, with a `1` in the bottom right corner. I'll display them boxed, before the automatic 0 fill, for clarity: ``` ┌───┬─────────┬─────┬───────┬───────┬─┬───┬─┬─┬─────┐ │0 1│0 0 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 1│ │ │0 0 0 0│1│0 0│0│0│0 0 0│ │ │ │ │ │0 0 0 1│ │0 0│1│0│0 0 0│ │ │ │ │ │ │ │0 0│ │1│0 0 1│ │ │ │ │ │ │ │0 1│ │ │ │ └───┴─────────┴─────┴───────┴───────┴─┴───┴─┴─┴─────┘ ``` Once the fill is added it looks like: ``` 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . . . ``` + `[:+/` - Finally we sum the layers, giving us the adjacency matrix: ``` 0 1 1 1 0 1 0 0 0 1 1 0 0 1 0 1 0 1 0 0 0 1 0 0 0 ``` * `(+[:=#\)` Next we add the diagonal of ones (nodes are already connected to themselves). ``` 1 1 1 1 0 1 1 0 0 1 1 0 1 1 0 1 0 1 1 0 0 1 0 0 1 ``` * `+./ .*^:a:~` Matrix "or multiply" with self, until we reach a fixed point, saving intermediate values. The additional ones added in iteration `n` represent nodes that can be reached in `n` hops. * `2-~/\0,` We want to separate each iteration's contribution, so we take successive deltas, starting with a matrix of all zeros: ``` 1 1 1 1 0 1 1 0 0 1 1 0 1 1 0 1 0 1 1 0 0 1 0 0 1 0 0 0 0 1 0 0 1 1 0 0 1 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 1 0 0 0 0 1 0 0 1 1 0 ``` * `(*#\)` Multiply each of those values by its iteration number: ``` 1 1 1 1 0 1 1 0 0 1 1 0 1 1 0 1 0 1 1 0 0 1 0 0 1 0 0 0 0 2 0 0 2 2 0 0 2 0 0 0 0 2 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 3 0 0 3 3 0 ``` * `+/@` And sum the layers: ``` 1 1 1 1 2 1 1 2 2 1 1 2 1 1 3 1 2 1 1 3 2 1 3 3 1 ``` * `1#.` Then sum the rows: ``` 6 7 8 8 10 ``` * `1+[:(i.<./)` Finally return the minimum value's index, plus 1: ``` 1 ``` [Answer] # [Python 3](https://docs.python.org/3/), 234 bytes ``` def f(l): m=1+max(map(max,l));g=eval(str([[m]*m]*m)) for a,b in l:g[a][a]=g[b][b]=0;g[a][b]=g[b][a]=1 for x in range(m**3):k=x%m;x//=m;j=x%m;i=x//m;g[j][k]=min(g[j][k],g[j][i]+g[i][k]) return min((sum(g[i]),i)for i in range(m))[1] ``` [Try it online!](https://tio.run/##TU7NDoMgDL77FFyWUGfijDcNT0I4YKYMtWhQF/b0rDgPS762X3@/rp/9tbg6xmc/sIHP0GQMRXVHHTjqlSwUM0BrRP/WM992z6VElScAZGxYPNNFx6xjc2OkVgRhZKcI4tGele6qUKf6bYQ077UzPcc8r6GZRLhhG8pSYDue3ArKkA6MSk5KoHX84sUZrbobcpTTF77fD@9YGuLbgTx1oLCQtOyfFoCsVIxf "Python 3 – Try It Online") Implementing simple Floyd-Warshall. This is my first time here. Any tips are welcome! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ;©U;þ®ẎḢ⁼ṪƊƇƊLСŒṬ€ĖP€o/SİM ``` A monadic Link accepting the adjacency list specified that yields a list of all of the Kevin Bacons of that graph. **[Try it online!](https://tio.run/##y0rNyan8/9/60MpQ68P7Dq17uKvv4Y5Fjxr3PNy56ljXsfZjXT6HJxxaeHTSw51rHjWtOTItAEjm6wcf2eD7////aA1DHQUjTR0FDSMdBWMQbayjYAKiTXQUDKHippqxAA "Jelly – Try It Online")** How? We first produce lists of all pairs of nodes linked by `1, 2, 3, ...` steps (up to `2p+1` where `p` is the number of pairs in the input, just for golfing purposes) - including redundancies and self-linked pairs. Then we turn each of these into tables showing the number of steps taken, if possible, or zero if not - i.e. the first is `0` or `1` at each point, the second is `0` or `2` at each point, and so on. We then reduce these by logical OR, giving us the shortest length table shown in the question with a leading diagonal filled with `2`s (since we are guaranteed a fully-connected graph, we will always produce a `2` at this position in the second previous table by following a given pair and its reverse, and the logical OR will keep this value if we could do the same in more steps). Then we sum the columns, inverse and find maximal indices (aligning with the guaranteed `[1,n]` node numbering). ``` ;©U;þ®ẎḢ⁼ṪƊƇƊLСŒṬ€ĖP€o/SİM - Link: adjacency list, A U - reverse each pair in A ; - concatenate that to A © - copy this to the register for later С - collect up and repeat: L - ...times: length (of the new list) Ɗ - ...what: the last three links as a monad, f(current): ® - use the register as the right argument of: þ - (current) table (register) using: ; - concatenation (e.g. [2,5];[1,2] -> [2,5,1,2]) Ẏ - tighten (from a table to a row-major order list) Ƈ - filter keep those for which: Ɗ - last three links as a monad: Ḣ - pop and yield head Ṫ - pop and yield tail ⁼ - equal? (leaving the inner two e.g. [2,5,1,2] -> [5,1] which is kept since 2=2) € - for each: ŒṬ - make a table with 1s at the given coordinates) Ė - enumerate -> [[1,first],[2,second],...] P€ - product of each o/ - reduce by logical OR S - sum columns İ - inverse M - maximal indices (1-indexed) ``` [Answer] # [R](https://www.r-project.org/), ~~120~~ ~~113~~ ~~111~~ ~~107~~ ~~106~~ 102 bytes Or **[R](https://www.r-project.org/)>=4.1, 95 bytes** by replacing the word `function` with a `\`. *Edit: -7 bytes and -4 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe). -1 byte thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen). -4 bytes inpired by [@Dominic van Essen's answer to related challenge](https://codegolf.stackexchange.com/a/245389/55372).* ``` function(v){A=diag(m<-max(v)) A[v]=1 C=B=A=A|t(A) for(i in 2:m)B[(C=C%*%A)&!B]=i order(colSums(B))[1]} ``` [Try it online!](https://tio.run/##jY9BC4JAFITv@ys2wngv7LBrGUR7WP0BHTqKh9KMhXRjUwmq325ZLWl06DYMb755Y5pMNFlVJKXSBdR4kSJVmz3ky0m@OT8MJDKqY8FIKAIhhbyWIJFk2oCiqqB8kWMQQShCZ@xIHA2CWCiiTbozkOjDuspPECBGLL41GZitKlJIgLmUo0sT4C6dPcXD8ayYPoXXCkQ6XFXlsSoXlJHfAO9z3oppi@zmvL9z7PNTF8C/Ab2vqDa9C99yZp0uZre91vq23e@tfTvcOvNek9/cAQ "R – Try It Online") Straightforward approach: 1. Calculate adjacency matrix `A`. 2. Gradually increase powers of `A` (stored in `C`) to see when will appear the first non-zero entry for each pair of indices. *(Where's built-in matrix power when you need one?)* 3. Store the distances in `B`. 4. Find the column with the smallest sum. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~44~~ 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) [*I guess crossed out 44 is no longer a thing with the new font. ;)*](https://codegolf.stackexchange.com/questions/170188/crossed-out-44-is-still-regular-44) ``` ZL©ε®yKδ‚εU怜€`ʒнXнåyθXθåyüå€àPP}€gß]OWk> ``` Takes advantage of the rule "*You may assume the set of integers used for node IDs is positive and contiguous.*" to save some bytes, although it still feels pretty long.. [Try it online](https://tio.run/##yy9OTMpM/f8/yufQynNbD62r9D635VHDrHNbQw8ve9S05uhkIJFwatKFvREX9h5eWnluR8S5HUD68J7DS4EyhxcEBNQC6fTD82P9w7Pt/v@PjjbUMYrViTbSMQWShjrGYNIESBoDyVgA) or [verify almost all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVLmNL/KJ9DK89tPbSu0vvclkcNs85tDY08vOxR05qjk4FEwqlJF/ZGXNh7eGnluR0R53YA6cN7Di8FyhxeEBBQC6TTD8@P9Q/PtvuvpBem8z86OtpQxyhWJ9pIxxRIGuoYg0kTIGkMJGN1FBAKjKGCOtEmQMU4pQyhpsEVxMYCAA) (the largest/last test case times out and is omitted in the test suite). **Explanation:** ``` Z # Get the flattened maximum of the (implicit) input-list of pairs L # Pop and push a list in the range [1,max] © # Store it in variable `®` (without popping) ε # Map over each integer: ® # Push the [1,max] list from variable `®` again yK # Remove the current integer from it δ # Map over each remaining integer: ‚ # Pair it with the current integer ε # Map over each pair: U # Pop the current pair and store it in variable `X` æ # Get the powerset of the (implicit) input-list of pairs €œ # Get the permutations of each inner list €` # Flatten it one level down ʒ # Filter over this list of potential paths: н # Pop and push the first pair Xнå # Check if the first value of `X` is in this pair yθXθå # Do the same for the last pair and last value of `X` y # Then push the list of pairs again ü # For each overlapping pair of pairs: å # Check for both values in the second pair if it's in the first # (this will result in an empty list for single-pair lists) €à # Check for each overlapping check if either is truthy P # Check if all overlapping checks are truthy P # Check if all three checks are truthy }€g # After the filter: get the length of each valid path ß # Pop and push the minimum path-length ] # Close both the inner and outer maps O # Sum each inner list (shorter than the average) W # Push the minimum sum (without popping the list) k # Get the (first) 0-based index of this minimum > # Increase it by 1 to make it a 1-based index # (after which this is output implicitly as result) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~82~~ 81 bytes ``` ≔⊕⌈Eθ⌈ιη≔EηEη∨⁼ιλ∨№θ⟦ιλ⟧№θ⟦λι⟧η≔Eηιζ≔EηιεFη«UMζEκ⊙η∧§κπ§ξνUMεEκ⁺짧ζλν»UMεΣιI⌕ε⌈ε ``` [Try it online!](https://tio.run/##dZAxa8MwEIXn@lfcKIMKSZp08WRMAxlCAx2NBmGrtagkJ5JdXJf@dvVkyw2BVsvjvrv3JF3VcFu1XHmfOyffDDmYygotTCdqcuSD1L1GPZMLhaWUKR4KTZol0RQGmjAwybMlT5eeK0ckBZVOoGh704WQMjCG8EoUBcnS/0Il0vFPKpC@thZIk8JXcoedotWam5qM81veKeTmM4znCPPuYGoxBHpG91IOFMx0eXYTIX4jTqp3RF8Ni47z58zs/U5uzS/zorLkZCX@s@CuI3u5BM@LFJPV@7IsdxRWDHexpbAOuo71isI2KPY3UR@CbqLu4jzWj4wxf/@hfgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of ovs's "Bacon" answer. ``` ≔⊕⌈Eθ⌈ιη ``` Get the number of nodes. ``` ≔EηEη∨⁼ιλ∨№θ⟦ιλ⟧№θ⟦λι⟧η ``` Calculate the adjacency matrix. ``` ≔Eηιζ≔Eηιε ``` Create two shallow clones as we'll be mutating these. ``` Fη« ``` Repeat for each node, to ensure that all nodes are eventually reached. ``` UMζEκ⊙η∧§κπ§ξν ``` Update the first clone to the adjacency matrix at the next depth. ``` UMεEκ⁺짧ζλν ``` Add it to the second clone. ``` »UMεΣι ``` Sum the rows of the second clone. ``` I⌕ε⌈ε ``` Find the index of the largest sum. [Answer] # [Perl 5](https://www.perl.org/) List::Util, 174 bytes ``` sub{$S=99;sub D{$_[0]-$a?1+min map D(@$_),grep$_[0]==$$\_[1]&&!$b{$$_[0]}++,@g:0}for$a(@a=uniq map@$_,@g=map{$_,[@$_[1,0]]}@_){$S=$s,$A=$a if$S>($s=sum map{%b=();D($_)}@a)}$A} ``` [Try it online!](https://tio.run/##jVJNb5tAED2XXzFJxzZbb2uDY1cBbUIkbqmSQ9oTQdamXdCqARMWlFYO@evuLKCkSi/dy3vz8ebtV6Xq@/WhNQq@aNMEwbdG38PDo9uW@gEKXYJpCxY6tiGWjQyCuC0qVYcOZuJg2rs93ojT05AYxHvcJsv0I8pzb26lhawgdiPcMp7XquqrQiChl06nR0jiPtfN5zzKg2WX7WqUbiTF4C4r0lJFEKPZPImslC/TtIu2zDqj4XghUILO8ObMRSNou1a4n9wJl4WxS@ZdJFmHF90hdMjAdRKAhMaAn3JIfA5rixSvRjyxuLKYgjgDDyDl/4hWL02EJ3ZI37z6r2bvxbkX@W9Eoy01vd/V4A@VzShbv471xg33B9iMNpu/DzDE/hh/HiZveju2d4BW8dtFzVExQZcbjinMxRQzejnNhlRV67LJjieGuPpVqe@N@hEAKgrzXUMsJ6bLqiU@MbflMXfeoaK3zuEcZrufMwhgdnX9Fa4vZxyGL0S@TDybxacP4unWPIWLRU7fqjv8AQ "Perl 5 – Try It Online") [Answer] # Python3, 276 bytes: ``` lambda g:min(enumerate(n:=[*{i for k in g for i in k}]),key=lambda x:sum(min(p(g,x[1],j))for j in n[:x[0]]+n[x[0]+1:])/float(len(n)-1))[1] def p(g,s,e,c=[]): if s==e:yield len(c) else: for i in g: if s in i and(j:=[i[0],i[1]][s==i[0]])not in c:yield from p(g,j,e,c+[s]) ``` [Try it online!](https://tio.run/##jU/LToQwFN3zFXfZ69QoMIOmCV9Su8ChxfIoBJgEYvx27MVmRpNZuDo97Xl1WOeP3qWvw7iZ/G1ri@69LKASnXVMu0unx2LWzIlcPnxaMP0IDVgH1X60dGy@FPJGr3nwLmK6dIz8A6v4ImPFa0SS1yR3UizyWamDk4SHWCh8Mm1fzKzVjjl8jBG9KSq1AUqYuObnXCoUEVgDU55rsVrdlkD6M0ag20n7x9ukitguJmahcCWr/ResL@TWhyvpY4gpdP1MonPINGPf7bU11R7kpHAbRutmZphkMYcEObCEw4nQ8zTgkTAlVIjRXUt6lXg8UsS/pfG19Y7l71UW1KdbWhw27puzkJ793vzDk8BfKHL7Bg) ]
[Question] [ Some divisors of positive integers really hate each other and they don't like to share one or more common digits. Those integers are called *Hostile Divisor Numbers* (***HDN***) **Examples** Number `9566` has `4` divisors: `1, 2, 4783 and 9566` (as you can see, **no two of them share the same digit**). Thus, **9566** is a **H**ostile **D**ivisor **N**umber Number `9567` is **NOT *HDN*** because its divisors (`1, 3, 9, 1063, 3189, 9567`) share some common digits. Here are the first few ***HDN*** ``` 1,2,3,4,5,6,7,8,9,23,27,29,37,43,47,49,53,59,67,73,79,83,86,87,89,97,223,227,229,233,239,257,263,267,269,277,283,293,307,337... ``` **Task** The above list goes on and your task is to find the *nth* ***HDN*** **Input** A positive integer `n` from `1` to `4000` **Output** The `nth` ***HDN*** **Test Cases** here are some **1-indexed** test cases. Please state which indexing system you use in your answer to avoid confusion. ``` input -> output 1 1 10 23 101 853 1012 26053 3098 66686 4000 85009 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest score in bytes wins. **EDIT** Good news! I submitted my sequence to OEIS and... Hostile Divisor Numbers are now OEIS [A307636](https://oeis.org/A307636) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` µNNÑ€ÙSDÙQ ``` -2 bytes thanks to *@Emigna*. 1-indexed [Try it online](https://tio.run/##yy9OTMpM/f//0FY/v8MTHzWtOTwz2OXwzMD//w0NDAE) or [verify most test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/Q1v9/A5PfNS05vDMYJfDMwP/1@roHdr6P9pQx9AAiECUoVEsAA) (last two test cases are omitted, since they time out). **Explanation:** ``` µ # Loop while the counter_variable is not equal to the (implicit) input yet: N # Push the 0-based index of the loop to the stack NÑ # Get the divisors of the 0-based index as well # i.e. N=9566 → [1,2,4783,9566] # i.e. N=9567 → [1,3,9,1063,3189,9567] €Ù # Uniquify the digits of each divisor # → ["1","2","4783","956"] # → ["1","3","9","1063","3189","9567"] S # Convert it to a flattened list of digits # → ["1","2","4","7","8","3","9","5","6"] # → ["1","3","9","1","0","6","3","3","1","8","9","9","5","6","7"] D # Duplicate this list Ù # Unique the digits # → ["1","2","4","7","8","3","9","5","6"] # → ["1","3","9","0","6","8","5","7"] Q # And check if it is still equal to the duplicated list # → 1 (truthy) # → 0 (falsey) # And if it's truthy: implicitly increase the counter_variable by 1 # (After the loop: implicitly output the top of the stack, # which is the pushed index) ``` [Answer] # [Python 2](https://docs.python.org/2/), 104 bytes ``` n=input() x=1 while n: x=i=x+1;d={0};c=1 while i:m=set(`i`*(x%i<1));c*=d-m==d;d|=m;i-=1 n-=c print x ``` [Try it online!](https://tio.run/##JcpBCsIwEAXQfU6RjZBUAkZXdvx3KSSFDpgxaIoj6tmj4vq9@mjLRfa9C1jq2pw3imjuC59nK6M1VsHQbaSM5@5N6Yv2rzwW3ObmJp4Gpxs@Re8pDcihAJnyC4U4/L4EJFOvLM1q74fjBw "Python 2 – Try It Online") 0-indexed. [Answer] # JavaScript (ES6), 78 bytes 1-indexed. ``` n=>eval("for(k=0;n;n-=!d)for(s=d=++k+'';k%--d||d*!s.match(`[${s+=d,d}]`););k") ``` [Try it online!](https://tio.run/##ZcndCsIgGADQ@57CjWKauZ9GEMjXi0Qw8dtWaRpz7Kb17EZQN3V5OFc1qaCHy30UzmMbO4gODu2kLE07P1ADpXTSCUiQvR0AgXPDs0yalRA4z7hOQn5Toz7T5rh8BA64weepYZJJk7KovQvetrn1Pe1oRQhhjBQFqRY/U35nW/9V9an9ro4v "JavaScript (Node.js) – Try It Online") ### Faster version, 79 bytes ``` n=>{for(k=0;n;n-=!d)for(s=d=++k+'';k%--d||d*!s.match(`[${s+=d,d}]`););return k} ``` [Try it online!](https://tio.run/##bcvdCoIwAEDh@55iQuHWmk6lYYz1IhEoTvuZbbFZN@qzLyK7yS4PH@daPktX2cu9I9rI2jfCa7HvG2OhEpRrrokIJHq3E1JgrHAYcrUiRA6DXAcuupVddYbFYdk7LORGjscCccRt3T2sBmr0ldHOtHXUmhNsYAIAQAjEMUgWP0K/kmYzSibKt38snTZGZ5rRXf5RxljO/As "JavaScript (Node.js) – Try It Online") ### How? Given an integer \$k>0\$, we build the string \$s\$ as the concatenation of all divisors of \$k\$. Because \$k\$ is always a divisor of itself, \$s\$ is initialized to \$k\$ (coerced to a string) and the first divisor that we try is \$d=k-1\$. For each divisor \$d\$ of \$k\$, we test whether any digit of \$d\$ can be found in \$s\$ by turning \$d\$ into a character set in a regular expression. *Examples* * \$s=\text{"}956647832\text{"}\$, \$d=1\$ → `"956647832".match(/[1]/)` is falsy * \$s=\text{"}9567\text{"}\$, \$d=3189\$ → `"9567".match(/[3189]/)` is truthy ### Commented *This is the version without `eval()`, for readability* ``` n => { // n = input for( // for() loop: k = 0; // start with k = 0 n; // go on until n = 0 n -= !d // decrement n if the last iteration resulted in d = 0 ) // for( // for() loop: s = // start by incrementing k and d = ++k + ''; // setting both s and d to k, coerced to a string k % --d || // decrement d; always go on if d is not a divisor of k d * // stop if d = 0 !s.match( // stop if any digit of d can be found in s `[${s += d, d}]` // append d to s ); // ); // implicit end of inner for() loop // implicit end of outer for() loop return k // return k } // ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ÆDQ€FQƑµ#Ṫ ``` [Try it online!](https://tio.run/##y0rNyan8//9wm0vgo6Y1boHHJh7aqvxw56r//w0NDAE "Jelly – Try It Online") -1 byte thanks to ErikTheOutgolfer Takes input from STDIN, which is unusual for Jelly but normal where `nfind` is used. ``` ÆDQ€FQƑµ#Ṫ Main link Ṫ Get the last element of # The first <input> elements that pass the filter: ÆD Get the divisors Q€ Uniquify each (implicitly converts a number to its digits) F Flatten the list QƑ Does that list equal itself when deduplicated? ``` 2-indexed [Answer] # [Perl 6](http://perl6.org/), 53 bytes ``` {(grep {/(.).*$0/R!~~[~] grep $_%%*,1..$_},^∞)[$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiO9KLVAoVpfQ09TT0vFQD9Isa4uui5WASysEq@qqqVjqKenEl@rE/eoY55mtEp8bO3/4sRKBQ2gsJGppp2dnlrafwA "Perl 6 – Try It Online") 1-indexed. `/(.).*$0/` matches any number with a repeated digit. `grep $_ %% *, 1 .. $_` returns a list of all divisors of the number `$_` currently being checked for membership in the list. `[~]` concatenates all of those digits together, and then `R!~~` matches the string on the right against the pattern on the left. (`~~` is the usual match operator, `!~~` is the negation of that operator, and `R` is a metaoperator that swaps the arguments of `!~~`.) [Answer] # [Python 2 (PyPy)](http://pypy.org/), ~~117~~ 114 bytes Uses 1-indexing ``` k=input();n=0;r=range while k:n+=1;k-=1-any(set(`a`)&set(`b`)for a in r(1,n+1)for b in r(1,a)if n%a<1>n%b) print n ``` [Try it online!](https://tio.run/##NY5BC4JAFITv@yseguFigttR22527dIPcLVnLsZzea3U/npTKxiY4WNgxgXfj3TIXHBhbscbggaOomgetCU3@USWpPOSNRu6o3j19oEwFJRqVQ6ZVpmhkDzRJ7Wp5W4LTS27kcGAJeBE7SlVG2j@wEjbAcXmqE4UN1I4tuSB5mVW/BauPGEhADyH1QDwjS2s/8SaW3Qeqsu5Yh75W2gYzTArofJF6gM "Python 2 (PyPy) – Try It Online") [Answer] # Wolfram Language 103 bytes Uses 1-indexing. I'm surprised it required so much code. ``` (k=1;u=Union;n=2;l=Length;While[k<#,If[l[a=Join@@u/@IntegerDigits@Divisors@#]==l@u@a&@n,k++];n++];n-1)& ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 112 bytes ``` for($a=$args[0];$a-gt0){$z=,0*10;1..++$n|?{!($n%$_)}|%{"$_"|% t*y|sort -u|%{$z[+"$_"]++}};$a-=!($z|?{$_-ge2})}$n ``` [Try it online!](https://tio.run/##FYxLCsMgFACvkoYnxFiDdhukBwlBXFi7CFrUUOrn7NZsZ5j5uK/24a2Po7WX8xMoAcqbsLF9BUVNZDhDEnc2c7byZSEEbHnm2wQWgcS1oDyCHAsa4vwrwfk40LNDSBu5xE5IrddJ9CT1EiQ1@lFxBdta44z/AQ "PowerShell – Try It Online") Takes 1-indexed input `$args[0]`, stores that into `$a`, loops until that hits `0`. Each iteration, we zero-out a ten-element array `$z` (used to hold our digit counts). Then we construct our list of divisors with `1..++$n|?{!($n%$_)}`. For each divisor, we cast it to a string `"$_"`, cast it `t`oCharArra`y`, and `sort` those digits with the `-u`nique flag (because we don't care if a divisor itself has duplicate digits). We then increment the appropriate digit count in `$z`. Then, we decrement `$a` only if `$z` contains `0`s and `1`s (i.e., we've found an HDN). If we've finished our `for` loop, that means we found the appropriate number of HDNs, so we leave `$n` on the pipeline and output is implicit. [Answer] # [Python 3](https://docs.python.org/3/), 115 bytes 1-indexed ``` f=lambda n,x=1,s="",l="",d=1:n and(d>x+1and f(n-1,x+1)or{*s}&{*l}and f(n,x+1)or f(n,x,s+l,(1-x%d)*str(d),d+1))or~-x ``` [Try it online!](https://tio.run/##bU9BTsMwELznFatWILt1UF3EgUjhAgdOXHiBi53WkmNH3i1NVZWvh62aohywZO/szOxo3R1pl@LjMIdYwfvbBwIl2KZiDn0Fr/ucXaRwBHJIzkLctxuXWcQKPin7uIXUwNefDZ2LYP23x5S5bj0hm8PUfGUvKBgkYJ5zbyO@AU9wMAjmxilwbUccPSbQzuWDR8e59p8Nx6nCt13KBHjEgu8DOsqO90SfYvCtJ6FXfOTQ1MG0G2sgqr7WCuvZTIXLY2tdRTDRCvvSLzUDaEQsteJGpnxa4Pn@tAjnURjpK1S4DErosr@zcsGLCyuVZZ0NP2U/dPwTEo14lrK4Yb2aNnrSrJ@kHH4B "Python 3 – Try It Online") This uses a *lot* of recursion; even with increased recursion limit, it can't do `f(30)`. I think it might be golfable further, and I tried finding something to replace the `(1-x%d)` with, but couldn't come up with anything (`-~-x%d` has the wrong precedence). Any bytes that can be shaved off are greatly appreciated. # How it works ``` # n: HDNs to go # x: Currently tested number # s: String of currently seen divisor digits # l: String of digits of last tried divisor if it was a divisor, empty string otherwise # d: Currently tested divisor f=lambda n,x=1,s="",l="",d=1:n and( # If there are still numbers to go d>x+1and f(n-1,x+1)or # If the divisors have been # exhausted, a HDN has been found {*s}&{*l}and f(n,x+1)or # If there were illegal digits in # the last divisor, x isn't a HDN f(n,x,s+l,(1-x%d)*str(d),d+1) # Else, try the next divisor, and # check this divisor's digits (if # if is one) in the next call )or~-x # Else, return the answer ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 74 bytes ``` Nest[1+#//.a_/;!Unequal@@Join@@Union/@IntegerDigits@Divisors@a:>a+1&,0,#]& ``` [Try it online!](https://tio.run/##Fcc9C8IwEIDh3X8hgS6NJlEHP7Dc0EUHcelURA5J64G9YHK6iL89Vnjh4R1Q7n5AoRvmbp9PPknrSmXMHK9mN23YP1/4ADgGYoCGKbCBA4vvfaypJ0lQ05tSiAlwW2HpCm21uhT5HImlVbOqg3ENTD5OOzv2xy300m7WemWt/eYf "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (v2), 14 bytes ``` ;A{ℕfdᵐc≠&}ᶠ⁽t ``` [Try it online!](https://tio.run/##ASoA1f9icmFjaHlsb2cy//87QXvihJVmZOG1kGPiiaAmfeG2oOKBvXT//zUw/1o "Brachylog – Try It Online") Function submission; input from the left, output to the right. (The TIO link contains a command-line argument to run a function as though it were a full program.) ## Explanation "Is this a hostile divisor number?" [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") code: ``` ℕfdᵐc≠ ℕ number is ≥0 (required to match the question's definition of "nth solution") f list of all factors of the number ᵐ for each factor d deduplicate its digits c concatenate all the deduplications with each other ≠ the resulting number has no repeated digits ``` This turned out basically the same as @UnrelatedString's, although I wrote it independently. "nth solution to a [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'")" wrapper: ``` ;A{…&}ᶠ⁽t & output the successful input to { }ᶠ the first n solutions of the problem ⁽ taking <n, input> as a pair ;A form a pair of user input and a "no constraints" value t take the last solution (of those first n) ``` This is one of those cases where the wrapper required to produce the nth output is significantly longer than the code required to test each output in turn :-) I came up with this wrapper independently of @UnrelatedString's. It's the same length and works on the same principle, but somehow ends up being written rather differently. It does have more potential scope for improvement, as we could add constraints on what values we were looking at for free via replacing the `A` with some constraint variable, but none of the possible constraint variables save bytes. (If there were a "nonnegative integer" constraint variable, you could replace the `A` with it, and then save a byte via making the the `ℕ` unnecessary.) [Answer] # Java 10, ~~149~~ ~~139~~ ~~138~~ ~~126~~ ~~125~~ ~~120~~ 119 bytes ``` n->{int r=0,i,d;for(;n>0;n-=d){var s="1";for(r+=d=i=1;i++<r;)if(r%i<1){d=s.matches(".*["+i+"].*")?0:d;s+=i;}}return r;} ``` -10 bytes by using `.matches` instead of `.contains` per digit, inspired by [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/185110/52210). -5 bytes thanks to *@ValueInk* -1 byte thanks to *@ceilingcat* 1-indexed [Try it online.](https://tio.run/##ZZBBbsIwEEX3nGJkqZKNSeS0XbQY0xOUDUvKwsQJHZo4yDZIVZSzp06aBbQbS29mZL3/T/qqk5P56vNKew/vGm07A0AbClfqvIDNgABVY4@Q0zgHy2QcdbP4@KAD5rABCwp6m6zb4cApscCFkWXjqLRrIW2iDGuv2oFXJCPjwnFlFKpMIucrJxmW1D3gKmOtUT6tdcg/C09JOt8Rjpzs0zlhb2JppOcKZde5IlycBSe7Xg4q58uhiiqT0bVBA3UMQ7fBoT3u9qDZb5JQ@ECzMcMEj7eQiXvK/uDd8ZN4fbnlZyHEv3ZGl3E9lIOTxvbbh6JOm0tIz9EwVJbGmMuPQLhNY9Fs@qfrfwA) **Explanation:** ``` n->{ // Method with integer as both parameter and return-type int r=0, // Result-integer, starting at 0 i, // Index integer d; // Decrement integer for(;n>0; // Loop until the input `n` is 0: n-=d){ // After every iteration: decrease `n` by the decrement integer `d` var s="1"; // Create a String `s`, starting at "1" for(r+=d=i=1; // (Re)set the decrement and index integers to 1, // and increase the result by 1 as well i++<r;) // Inner loop `i` in the range [2, r]: if(r%i<1){ // If `r` is divisible by `i`: d=s.matches(".*["+i+"].*")? // If string `s` contains any digits also found in integer `i`: 0 // Set the decrement integer `d` to 0 :d; // Else: leave `d` unchanged s+=i;}} // And then append `i` to the String `s` return r;} // After the loops, return the result `r` ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes ``` g{∧0<.fdᵐc≠∧}ᵘ⁾t ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wP736UcdyAxu9tBQgL/lR5wIgFygx41HjvpL//6MNdQwNgAhEGRrpGBtYWuiYGBgYxAIA "Brachylog – Try It Online") Very slow, and twice as long as it would be if this was a [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'"). 1-indexed. ``` The output t is the last ᵘ⁾ of a number of unique outputs, g where that number is the input, { } from the predicate declaring that: . the output < which is greater than 0 zero ∧ (which is not the empty list) f factorized ᵐ with each factor individually d having duplicate digits removed ≠ has no duplicate digits in c the concatenation of the factors ∧ (which is not the output). ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, 17 bytes ``` _=â ®sâìUµZ¶â}f1 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=Xz3iIK5z4sOsVbVatuJ9ZjE&input=MTAx) Port of [this Brachylog answer](https://codegolf.stackexchange.com/a/185158/8340). Credit: 4 bytes savings total thanks to Shaggy who also suggested there was a better solution leading to many more bytes :) --- Original answer 28 byte approach: ``` Èâ¬rÈ«è"[{Y}]" ©X+Y}Xs)«U´Ãa ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=yOKscsir6CJbe1l9XSIgqVgrWX1YcymrVbTDYQ&input=WzEsMTAsMTAxXQ) Port of [this JavaScript answer](https://codegolf.stackexchange.com/a/185110/8340). [Answer] # [Perl 5](https://www.perl.org/) `-p`, 66 bytes ``` map{1while(join$",map{$\%$_==0&&$_}1..++$\)=~/(\d).* .*\1/}1..$_}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saDasDwjMydVIys/M09FSQckohKjqhJva2ugpqYSX2uop6etrRKjaVunrxGToqmnpaCnFWOoDxIHylb//29oYPgvv6AkMz@v@L9uAQA "Perl 5 – Try It Online") 1 indexed [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` !fȯS=uṁdḊN ``` [Try it online!](https://tio.run/##yygtzv7/XzHtxPpg29KHOxtTHu7o8vv//7@hAQA "Husk – Try It Online") Same method as Jelly. # [Husk](https://github.com/barbuz/Husk), 19 bytes ``` !f(Λo¬Fnfo¬Eπ2mdḊ)N ``` [Try it online!](https://tio.run/##yygtzv7/XzFN49zs/ENr3PLSgKTr@Qaj3JSHO7o0/f7//29oAAA "Husk – Try It Online") The more manual cehcker. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` λKvUfÞu;ȯt ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOu0t2VWbDnnU7yK90IiwiIiwiMTAxIl0=) [Answer] # [Icon](https://github.com/gtownsend/icon), 123 bytes ``` procedure f(n) k:=m:=0 while m<n do{ k+:=1 r:=0 s:="" every k%(i:=1 to k)=0&(upto(i,s)&r:=1)|s++:=i r=0&m+:=1} return k end ``` [Try it online!](https://tio.run/##TY7RCsIwDEXf8xWh4GjZHlbBl2I/RraKpbYdWecQ9dtn5hiYp8C5Obm@y2lZBsqd6ydyeJVJQTA2GtvCfPN3h/GcsM8vCLWxGmgFo7FCgHs4emI4SM8AS8agbFvJaShZ@mZUFWe1eo81H3ogZnFVfIBcmShhAJf6v9/x4pNUgDybevceT1wAZ/LFsRgFGhQNV/VqS29E6FbvhFeF6uf/Ag "Icon – Try It Online") 1-indexed. Really slow for big inputs. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 74 bytes ``` {(grep {!grep *>1,values [(+)] map *.comb.Set,grep $_%%*,1..$_},1..*)[$_]} ``` 0-indexed. Only the first three cases are listed on TIO since it's too slow to test the rest. [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiO9KLVAoVoRTGnZGeqUJeaUphYrRGtoa8Yq5CYCBfWS83OT9IJTS3TAilTiVVW1dAz19FTia0GUlma0Snxs7X9rrrT8IgUbAwVLBUMDAzuFai7O4sRKBSWVeAVdIC8NqLFWyZqr9j8A "Perl 6 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~110~~ ~~97~~ ~~92~~ 84 bytes -13 bytes by leveraging [@Arnauld's JavaScript regex check](https://codegolf.stackexchange.com/a/185110/52194). -5 bytes for swapping out the `times` loop for a decrementer and a `while`. -8 bytes by ditching `combination` for something more like the other answers. ``` ->n{x=0;n-=1if(s='';1..x+=1).all?{|a|x%a>0||(e=/[#{a}]/!~s;s+=a.to_s;e)}while n>0;x} ``` [Try it online!](https://tio.run/##FcrRCsIgFADQX1nE2MaY8/Yq1z5kjTAwE8Si65ih9utG5/m8t9unGrzUSfoUkQs/Idh7T9h1AhiLI8LAlHPnlFWOrZI8517jvByTKut8@JKgERULzysJPZT9YZ1uvOQilvraAjVmMTrQP9i1AofTDw "Ruby – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~87~~ 59 bytes *-28 bytes thanks to FrownFrog* ``` 0{(+1,1(-:~.)@;@(~.@":&.>@,i.#~0=i.|])@+{.)@]^:(>{:)^:_&0 0 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Dao1tA11DDV0rer0NB2sHTTq9ByUrNT07Bx0MvWU6wxsM/VqYjUdtKuBsrFxVhp21VaacVbxagYKBv81uVKTM/IVDBVsFdKAJIRnZAzhGkD5FqYwAbgKMwOEmJHCfwA "J – Try It Online") ## original # [J](http://jsoftware.com/), 87 bytes ``` [:{:({.@](>:@[,],([:(-:~.)[:-.&' '@,/~.@":"0)@((]#~0=|~)1+i.)@[#[)}.@])^:(#@]<1+[)^:_&1 ``` [Try it online!](https://tio.run/##RYvNCsIwEITvPsXSQpOl6ZpUFFmsBARPnrwuqQexqBcfoJpXj4H6c5hhvmHmngpSA3QMCgxY4KyGYHc87JPwyHokH/SWvZhgtLBuOBIKN1QpUN7MI/mCC4te61BG2z0juvpG6KUUfOUz9qxLHzaulhxPlUs4u5yvD3DQwZB9onYxof3wevktfouV/XctpDc "J – Try It Online") Yikes. This is atrociously long for J, but I'm not seeing great ways to bring it down. ## explanation It helps to introduce a couple helper verbs to see what's happening: ``` d=.(]#~0=|~)1+i. h=. [: (-:~.) [: -.&' '@,/ ~.@":"0 ``` * `d` returns a list of all divisors of its argument * `h` tells you such a list is hostile. It stringifies and deduplicates each number `~.@":"0`, which returns a square matrix where shorter numbers are padded with spaces. `-.&' '@,/` flattens the matrix and removes spaces, and finally `(-:~.)` tells you if *that* number has repeats or not. With those two helpers our overall, ungolfed verb becomes: ``` [: {: ({.@] (>:@[ , ] , h@d@[ # [) }.@])^:(#@] < 1 + [)^:_&1 ``` Here we maintain a list whose head is our "current candidate" (which starts at 1), and whose tail is all hostile numbers found so far. We increment the head of the list `>:@[` on each iteration, and only append the "current candidate" if it is hostile `h@d@[ # [`. We keep doing this until our list length reaches 1 + n: `^:(#@] < 1 + [)^:_`. Finally, when we're done, we return the last number of this list `[: {:` which is the nth hostile number. ]
[Question] [ Given an input of a list of positive integers with some replaced with `0`, output the list with the missing numbers that were changed to `0` replaced. Characteristics of the input list: * The list will always have a length of at least 2. * Let us define the input list as `a` and the "original list" (that is, the list before numbers were replaced with `0`s) as `b`. For any `n`, `a[n]` is either `b[n]` or `0`. * For any `n`, `b[n]` is either `b[n-1] + 1` or `b[n-1] - 1`. That is, the numbers in `b` will always change by `1` at each index from its previous. The first element is, of course, exempt from this rule. * For every run of zeroes in `a` (that is, consecutive elements replaced with `0`), with `x` representing the index of the start of the run and `y` representing the end, `a[x-1]` to `a[y+1]` will always be either solely increasing or solely decreasing. Therefore, there will only be one possible way to fill in the zeroes. + This also means that neither the first nor the last element of the array can be zeroes. In simpler terms, to fill in a run of zeroes, simply replace it with a range from the number before to the number following it. For example, an input of ``` 1 2 0 0 0 6 7 ``` must output ``` 1 2 3 4 5 6 7 ``` Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win. Test cases: ``` In Out ----------------------------------------------------- 1 0 0 0 5 6 0 4 0 0 1 | 1 2 3 4 5 6 5 4 3 2 1 7 6 0 0 3 0 0 0 7 0 5 | 7 6 5 4 3 4 5 6 7 6 5 1 0 3 0 5 0 3 0 5 0 7 | 1 2 3 4 5 4 3 4 5 6 7 14 0 0 0 0 0 0 0 0 23 | 14 15 16 17 18 19 20 21 22 23 ``` [Answer] # JavaScript (ES6), ~~72 66 64 54~~ 53 bytes *Saved 12 bytes thanks to @Neil!* *Saved 1 byte thanks to @IsmaelMiguel* ``` a=>a.map((l,i)=>l?b=l:b+=a.find((q,r)=>r>i&&q)>b||-1) ``` Pretty good for JavaScript. --- [Try it online](http://vihan.org/p/esfiddle/?code=f%3Da%3D%3Ea.map((l%2Ci)%3D%3El%3Fb%3Dl%3Ab%2B%3Da.find((q%2Cr)%3D%3Er%3Ei%26%26q)%3Eb%7C%7C-1)%0A%0Aalert(%20f(%20%5B1%2C%200%2C%200%2C%200%2C%205%2C%206%2C%200%2C%204%2C%200%2C%200%2C%201%5D%20)%20)%0Aalert(%20f(%20%5B7%2C%206%2C%200%2C%200%2C%203%2C%200%2C%200%2C%200%2C%207%2C%200%2C%205%5D%20)%20)%0Aalert(%20f(%20%5B1%2C%200%2C%203%2C%200%2C%205%2C%200%2C%203%2C%200%2C%205%2C%200%2C%207%5D%20)%20)%0Aalert(%20f(%20%5B14%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%2023%5D%20)%20)) (all browsers work) ## Explanation ``` a=> // Function with arg `a` a.map((l,i)=> // Loop through input l? // If nonzero b=l // Set `b` to current number :a.find((q,r)=>r>i&q) // Otherwise look for the next nonzero number >b? // If it's increased since nonzero last number ++b:--b) // Increasing? increase `b` (the previous nonzero number) // otherwise decrease `b` ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 11 ~~12~~ bytes ``` fGXzGn:3$Yn ``` Works with [current release (13.0.0)](https://github.com/lmendo/MATL/releases/tag/13.0.0) of the language/compiler. [**Try it online!**](http://matl.tryitonline.net/#code=ZkdYekduOjMkWW4&input=WzEgMCAzIDAgNSAwIDMgMCA1IDAgN10) ``` f % implicitly input array. Indices of nonzero elements (*) GXz % push input and get its nonzero elements (**) Gn: % vector [1,2,...,n], where n is input length (***) 3$Yn % interpolate at positions (***) from data (**) defined at positions (*) ``` [Answer] ## Haskell, ~~68~~ ~~61~~ 58 bytes ``` g(a:b:r)=[a..b-1]++[a,a-1..b+1]++g(b:r) g x=x g.filter(>0) ``` Usage example: `g.filter(>0) $ [7,6,0,0,3,0,0,0,7,0,5]`-> `[7,6,5,4,3,4,5,6,7,6,5]`. How it works: remove zeros from the input, then call `g`. Let `a` be the first and `b` then second element of the remaining list. Concatenate the lists from `a` upwards to `b-1` and from `a` downwards to `b+1` (one of them will be empty) and a recursive call with `a` dropped. Edit: @Zgarb saved 3 bytes. Thanks! [Answer] # Mathematica, 59 bytes ``` #//.{a___,x_,0..,y_,b___}:>{a,##&@@Range[x,y,Sign[y-x]],b}& ``` **Test case** ``` %[{1,0,3,0,5,0,3,0,5,0,7}] (* {1,2,3,4,5,4,3,4,5,6,7} *) ``` [Answer] # Perl, 47 45 44 39 37 bytes Includes +1 for `-p` ``` s%\S+%$p+=/\G(0 )+/?$'<=>$p:$&-$p%eg ``` Expects the list on stdin. Example: echo 1 0 3 0 1 | perl -p file.pl [Answer] # Jelly, ~~12~~ 11 bytes ``` ḢWW;ḟ0Ṫr¥\F ``` [Try it online!](http://jelly.tryitonline.net/#code=4biiV1c74bifMOG5qnLCpVxG&input=&args=WzcsIDYsIDAsIDAsIDMsIDAsIDAsIDAsIDcsIDAsIDVd) ### Alternative version, 8 bytes (non-competing) Unfortunately, Jelly's `pop` did not cast to iterable, in the latest version that predates this challenge. This has been fixed, and the following works in the current version. ``` ḟ0Ṫr¥\FḊ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bifMOG5qnLCpVxG4biK&input=&args=WzcsIDYsIDAsIDAsIDMsIDAsIDAsIDAsIDcsIDAsIDVd) ### How it works ``` ḢWW;ḟ0Ṫr¥\F Main link. Input: A (list) Ḣ Pop the first element of A. Let's call it a. WW Yield [[a]]. ; Concatenate with the popped A. This wraps the first element of A in an array. ḟ0 Filter; remove all zeroes. ¥ Create a dyadic chain: Ṫ Pop the last element of the left argument. r Call range on the popped element and the right argument. \ Reduce the modified A by this chain. F Flatten the resulting list of ranges. ``` In the alternate version, `ḢWW;` becomes unnecessary. However, since the first element is cast to iterable before popping, it is not actually modified. The final `Ḋ` removes the duplicate of the first element. [Answer] # Retina, ~~39~~ ~~34~~ 31 bytes *3 bytes saved thanks to @Martin.* ``` +`1(1*) (?= +((1)\1)?) $0$1$3$3 ``` Takes input and gives output in unary. The code iteratively fills every empty place (0's) with `previous_number - 1 + 2 * if_next_nonzero_number_bigger`. `previous_number - 1` is `$1` and `if_next_nonzero_number_bigger` is `$3`. With decimal I/O the code is 51 bytes long as you can see in the [online interpreter with all the test cases](http://retina.tryitonline.net/#code=XGQrCiQwJCoxCitgMSgxKikgKD89ICsxKCgxKVwxKT8pCiQwJDEkMyQzCigxKSsKJCMx&input=MSAwIDAgMCA1IDYgMCA0IDAgMCAxCjcgNiAwIDAgMyAwIDAgMCA3IDAgNQoxIDAgMyAwIDUgMCAzIDAgNSAwIDcKMTQgMCAwIDAgMCAwIDAgMCAwIDIz). [Answer] # GNU Sed (with `exec` extension using bash), 61 Score includes +1 for `-r` option to sed. ``` : s/( 0)+ /../ s/\w+..\w+/{&}/ s/.*/bash -c 'echo &'/e / 0/b ``` * Find runs of `0`s and replace them `..` * Put braces around the endpoint numbers to create a bash brace expansion like `{1..4}` for the local endpoints. The beauty of [bash brace expansions](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) here is that the generated sequence will always run in the right direction, regardless of whether the start or end is larger. * Use the `e` option to the `s` command to call out to bash to evaluate this brace expansion * If any more `0`s are found, jump back to the start. [Ideone.](https://ideone.com/q1MocR) [Answer] # Python 2, ~~195~~ 111 bytes (thanks [Alex](https://codegolf.stackexchange.com/users/20469/alex-a)!) ``` t=input() z=0 for i,e in enumerate(t): if e: while z:t[i-z]=e+z if l>e else e-z;z-=1 l=e else:z+=1 print t ``` Input: must be a `[list]` of ints Output: `[list]` of ints [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ḟ0rƝṖ€Fo ``` [Try it online!](https://tio.run/##y0rNyan8///hjvkGRcfmPtw57VHTGrf8/4fbgbT7///RhjoKBjBkqqNgBmaYwEQMY3UUos1hwkBkjKTcHKIJpMQQSdIUg20OVmKCpBUNGRnHAgA "Jelly – Try It Online") [Answer] # Perl, ~~85~~ 82 bytes *includes +1 for `-p`* ``` s/(\d+)(( 0)+) (\d+)/$s=$1;$e=$4;$_=$2;$c=$s;s!0!$c+=$e<=>$s!eg;"$s$_ $e"/e&&redo ``` Expects the list on stdin. Example: `echo 1 0 3 0 1 | perl -p file.pl`. This uses a nested regexp. Somewhat readable: ``` s/(\d+)(( 0)+) (\d+) # match number, sequence of 0, number / $s=$1; # start number $e=$4; # end number $_=$2; # sequence of ' 0' $c=$s; # initialize counter with start number s!0! $c += $s <=> $e !eg # replace all 0 with (in|de)cremented counter "$s$_ $e" # return replacement /e && redo # repeat until no more changes. ``` [Answer] # Python 2, ~~92~~ 88 bytes (Removed intermediate variable) ``` t=filter(bool,input()) print sum([range(o,p,cmp(p,o))for o,p in zip(t,t[1:])],[])+t[-1:] ``` [Answer] # Pyth, 17 bytes ``` u+G+treGHHfTtQ[hQ ``` The way it works: ``` u reduce [hQ seed: the first element of input, in a list iterable: tQ all except the first element of input fT remove if 0 lambda: G is the list to be returned, H is the current item +G append to return list reGH a range from the last element of the return list and the current item + concatenated with H the last item (this step forms a bidirectional inclusive list) ``` In other words: all zeroes are removed from input, then an exclusive range is inserted between every element. This range is zero length on elements only one apart. [Answer] # Vim: 231 Key Commands Note that any ^ preceding a character means you should hold control while typing that character ``` mbomayiwo^V^R"^V^V^V^X ^V^["sy0dd`a@f ^["bc0yiwo^V^V^V^X^V^R"^V^[0l@sa^V^V^V^A-^V^[0f-"ayhdd`a@i ^["dc0mbyiwo^V^R"Exe@b^V^[0fel"ty2ldd`b@t ^["ec0wmbyiwo@f @d^V^[@z ^["fc0"xyiwwmbyiwocw^V^V^V^Rx^V^V^V^[@a@i @e^V^[@z ^["ic0IB0 B^V^R" ^V^OWB0 ^V^OA B0^V^[0*w"tyiWdd`b@t ^["zd0dd`bAe^[0@e ``` ## Steps so you can run this too! 1. Copy the line into Vim 2. Type `:s/\^V/<Ctrl-V><Ctrl-V>/g` and press enter (the two s should give you a blue ^V) 3. Type `:s/\^R/<Ctrl-V><Ctrl-R>/g` and press enter (you should see blue ^Rs now) 4. Type `:s/\^X/<Ctrl-V><Ctrl-X>/g` and press enter (you should see blue ^Xs now) 5. Type `:s/\^O/<Ctrl-V><Ctrl-O>/g` and press enter 6. Type `:s/\^A/<Ctrl-V><Ctrl-A>/g` and press enter 7. Type `:s/\^\[/<Ctrl-V><Ctrl-[>/g` and press enter (this command is slightly different because I needed to escape the [) 8. Type `0"yy$`. The command is now stored in the y register 9. Set up input on a line, and run with `@y` If someone knows a better way to share the command, please let me know. I know this is lengthy, but it's the best I could come up with. ## Input/Output The input string should be alone on any line in the file. 1 0 0 4 3 0 0 0 7 The output will simply overwrite the input string 1 2 3 4 3 4 5 6 7 ## Explanation ### Algorithm 1. Start at a non-zero number, make sure it's not the last number 2. Find the next non-zero number 3. Take their difference. If the answer is negative, you should decrement to repair the range, otherwise, increment to repair the range. 4. Go back to the first character and replace each zero by incrementing/decrementing the previous number. 5. Repeat until you get to the last character ### Macros Used @e - Check for end. The last number will have an e appended to it. If the number under the cursor has an e at the end, delete the e and stop execution. Otherwise, start an interpolation cycle with @b. ``` mbyiwo^R"Exe@b^[0fel"ty2ldd`b@t ``` @b - Begin interpolation cycle. Save the number under the cursor for a subtraction operation (@s) and then find the next non-zero term (@f) ``` mayiwo^R"^V^X ^["sy0dd`a@f ``` @s - Stores the subtraction command to use in @d. It is simply `(val)^X` where `(val)` is the number at the start of the interpolation step. This is set by the @b command. @f - Find the next non-zero term. Write the current value to the unnamed register, then write `@f @d` on the next line, and then run @z. This will repeat this command if the number is a zero, and execute @d if it isn't. ``` wmbyiwo@f @d^[@z ``` @z - Conditional execute if unnamed register is 0. This command expects two commands on a new line in the format `command1 command2`. If the unnamed register is 0, `command1` is executed, otherwise `command2` is executed. Note that neither command can have any spaces in it. ``` IB0 B^R" ^OWB0 ^OA B0^[0*w"tyiWdd`b@t` ``` @t - Temporary command register. Stores various commands for a short time before executing them. Used primarily in if statements. @d - Determine interpolation direction. Subtracts the first number in the sequence from the number under the cursor (using @s). If the result is negative, the interpolation must decrement so ^X is saved to @a. Otherwise, we should increment so ^A is saved to @a. Once this is saved, move back to the beginning of this interpolate cycle and run @i to actually interpolate ``` yiwo^V^X^R"^[0l@sa^V^A-^[0f-"ayhdd`a@i ``` @a - Stores either `^A` or `^X` to increment or decrement during the interpolation step. This is set by the @d command. @i - Interpolate. Copy the number at the current location to @x and move to the next number. If that number is zero, replace it with @x and run @a to properly modify it up or down, then repeat this command. If the number isn't a zero, we have reached the end of this interpolation cycle. A new one should be started with this number as the beginning, so run @e to check for the end and run again. ``` "xyiwwmbyiwocw^V^Rx^V^[@a@i @e^[@z ``` @x - Temporary storage register. Used in the interpolate command (@i) ### Breaking Down the keystrokes ``` mbo :Set b mark to current position and open a new line below to write macros mayiwo^V^R"^V^V^V^X ^V^["sy0dd`a@f ^["bc0 :Write to @b and reset line yiwo^V^V^V^X^V^R"^V^[0l@sa^V^V^V^A-^V^[0f-"ayhdd`a@i ^["dc0 :Write to @d and reset line mbyiwo^V^R"Exe@b^V^[0fel"ty2ldd`b@t ^["ec0 :Write to @e and reset line wmbyiwo@f @d^V^[@z ^["fc0 :Write to @f and reset line "xyiwwmbyiwocw^V^V^V^Rx^V^V^V^[@a@i @e^V^[@z ^["ic0 :Write to @i and reset line IB0 B^V^R" ^V^OWB0 ^V^OA B0^V^[0*w"tyiWdd`b@t ^["zd0 :Write to @z and reset line dd`b :Delete this line and move cursor back to original line Ae^[ :Append an e to the last number 0@e :Move to the beginning of the line and run ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes This was a feature added after the challenge. Code: ``` 0KŸ ``` Explanation: ``` 0K # Remove all zeroes from the input list Ÿ # Rangify, [1, 4, 1] would result into [1, 2, 3, 4, 3, 2, 1] ``` [Try it online!](http://05ab1e.tryitonline.net/#code=MEvFuA&input=WzE0LCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAyM10) or [Verify all test cases!](http://05ab1e.tryitonline.net/#code=W0VExb0KCj8iIHJlc3VsdHMgaW4gIj8wS8W4LAoKXQ&input=WzEsIDAsIDAsIDAsIDUsIDYsIDAsIDQsIDAsIDAsIDFdCls3LCA2LCAwLCAwLCAzLCAwLCAwLCAwLCA3LCAwLCA1XQpbMSwgMCwgMywgMCwgNSwgMCwgMywgMCwgNSwgMCwgN10KWzE0LCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAyM10) [Answer] ## Python 3.5, 159 bytes a recursive solution ``` def f(s): h=s[0] g=lambda s,h,v:h*(h[-1]==s[0])if len(s)==1else(g(s[1:],h+[h[-1]-v],-v)+g(s[1:],h+[h[-1]+v],+v))*(s[0]==0 or h[-1]==s[0]) return g(s,[h],1) ``` ## Ungolfed ``` def f(s): h=s[0] def g(s,h,v): if len(s)==1: if h[-1]!=s[0]: r=[] else: r=h else: if s[0]==0: r=g(s[1:],h+[h[-1]+v],v) elif h[-1]!=s[0]: r=[] else: r=g(s[1:],h+[h[-1]-v],-v)+g(s[1:],h+[h[-1]+v],+v) return r return g(s,[h],1) ``` In the golfed solution, I replace conditions by using the fact that `h*True=h` and `h*False=[]` ## Result ``` >>> f([7, 6, 0, 0, 3, 0, 0, 0, 7, 0, 5]) [7, 6, 5, 4, 3, 4, 5, 6, 7, 6, 5] ``` [Answer] # [Perl 6](http://perl6.org/), 54 bytes ``` {$_=$^a;1 while s/:s(\d+) 0 + (\d+)/{+~$0...+~$1}/;$_} ``` [Answer] # **MATLAB, ~~39~~ ~~38~~ 37 bytes** ``` @(a)interp1(find(a),a(a>0),find(a/0)) ``` Anonymous function that linearly interpolates between the points in `a`. `find(a)` is an array of indices of non-zero elements in `a` and `a(a>0)` are the positive values. Saved 1 byte thanks to a friend's suggestion of `>` rather than `~=`. [Answer] # [J](http://jsoftware.com/), 32 bytes ``` {:,~[:;2<@({.+(i.@|**)@-~/)\-.&0 ``` [Try it online!](https://tio.run/##hY29DoJAEIR7nmJiIT9yJ3v8nJ6aEE2sjIWtdkaiNj4AhlfH5UAwNmRzt7uZ@Waf9US6BTYGLkJEMPyExO502NelCauzWal17pVy5j1k/g4CPxfV3L8IOY1q3zluJcZsjnO73l8oQJzdVIqM/8TOhFZ1hRBu5yQoxKw3vpR7zDtBmJEI3dtbtN0tpq09YqnFtY34v/aL9tdiax26/mIJKAVlIA1agJZQERSHKai4w5Pu3FAs1R8 "J – Try It Online") * `-.&0` Remove zeroes. * `2...\` For each infix of size 2... * `@-~/` Subtract the left from the right and... * `(i.@|**)` Create integers `0..<size of difference>`, multiplied by `*` the sign of the difference `*`. * `<@` And box (technical necessity for ragged arrays in J). * `[:;` Raise the result to remove the boxes. * `{:,~` And append the last element of the original array. [Answer] # [Husk](https://github.com/barbuz/Husk), 3 bytes ``` …fI ``` [Try it online!](https://tio.run/##yygtzv7//1HDsjTP////RxvqGIChqY4ZkDQBsw1jAQ "Husk – Try It Online") ]
[Question] [ In [Salesforce CRM](http://salesforce.com), every object has 15-character alphanumeric ID, which is case-sensitive. If anyone's curious, actually it's [base-62 number](https://help.salesforce.com/apex/HTViewSolution?id=000004383). However, tools used for data migration and integration may or may not support case sensitivity. To overcome that, IDs can be safely converted to 18-character case-insensitive alphanumeric IDs. In that process 3-character alphanumeric checksum is appended to the ID. The conversion algorithm is: **Example**: ``` a0RE000000IJmcN ``` 1. Split ID into three 5-character chunks. ``` a0RE0 00000 IJmcN ``` 2. Reverse each chunk. ``` 0ER0a 00000 NcmJI ``` 3. Replace each character in every chunk by `1` if it's uppercase or by `0` if otherwise. ``` 01100 00000 10011 ``` 4. For each 5-digit binary number `i`, get character at position `i` in concatenation of uppercase alphabet and digits 0-5 (`ABCDEFGHIJKLMNOPQRSTUVWXYZ012345`). ``` 00000 -> A, 00001 -> B, 00010 -> C, ..., 11010 -> Z, 11011 -> 0, ..., 11111 -> 5` ``` Yielding: ``` M A T ``` 5. Append these characters, the checksum, to the original ID. **Output**: ``` a0RE000000IJmcNMAT ``` Write program or function which takes 15-character alphanumeric (ASCII) string as input and returns 18-character ID. Input validation is out of scope of this question. Programs may return any value or crash on invalid input. Please, don't use Salesforce propretiary languages' features that make this challenge trivial (such as formula `CASESAFEID()`, converting `Id` to `String` in APEX &c). ### Test Cases ``` a01M00000062mPg -> a01M00000062mPgIAI 001M000000qfPyS -> 001M000000qfPySIAU a0FE000000D6r3F -> a0FE000000D6r3FMAR 0F9E000000092w2 -> 0F9E000000092w2KAA aaaaaaaaaaaaaaa -> aaaaaaaaaaaaaaaAAA AbCdEfGhIjKlMnO -> AbCdEfGhIjKlMnOVKV aBcDEfgHIJKLMNO -> aBcDEfgHIJKLMNO025 ``` [Answer] # Pyth, ~~23~~ 22 bytes *1 byte saved by [FryAmTheEggman](https://codegolf.stackexchange.com/questions/69127/convert-salesforce-15-character-id-to-18-character#comment168306_69131).* ``` sm@s+JrG1U6i}RJ_d2c3pz ``` [Try it online.](http://pyth.herokuapp.com/?code=sm%40s%2BJrG1U6i%7DRJ_d2c3pz&input=a0RE000000IJmcN&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=sm%40s%2BJrG1U6i%7DRJ_d2c3pz&test_suite=1&test_suite_input=a01M00000062mPg%0A001M000000qfPyS%0Aa0FE000000D6r3F%0A0F9E000000092w2%0Aaaaaaaaaaaaaaaa%0AAbCdEfGhIjKlMnO&debug=0) This might be the first time I've used the `p`rint instruction in golfing. ### Explanation ``` JrG1 save uppercase alphabet in J z input string p print it without newline c3 split into 3 parts m d for each part: _ reverse }R map characters to being in J uppercase alphabet (saved in J) i 2 parse list of bools as binary @ get correct item of J uppercase alphabet (saved in J) s+ U6 add nums 0-5 to it s concatenate and print ``` [Answer] ## Ruby, 97 bytes ``` ->s{s+s.scan(/.{5}/).map{|x|[*?A..?Z,*?0..?5][x.reverse.gsub(/./){|y|y=~/[^A-Z]/||1}.to_i 2]}*''} ``` ``` ->s{ # define an anonymous lambda s+ # the original string plus... s.scan(/.{5}/) # get every group of 5 chars .map{|x| # map over each group of 5 chars... [*?A..?Z,*?0..?5] # build the array of A-Z0-5 [ # index over it with... x.reverse # the 5-char group, reversed... .gsub(/./){|y| # ... with each character replaced with... y=~/[^A-Z]/||1 # ... whether it's uppercase (0/1)... }.to_i 2 # ... converted to binary ] # (end index) }*'' # end map, join into a string } # end lambda ``` This one's got some really neat tricks. My original instinct for splitting the string into groups of 5 chars was `each_slice`: ``` irb(main):001:0> [*1..20].each_slice(5).to_a => [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]] ``` Turns out that's waaay too long compared to a simple regex (`x.chars.each_slice(5)` vs. `x.scan(/.{5}/)`). This seems obvious in hindsight, but I never really thought about it... perhaps I can optimize some of my old Ruby answers here. The thing I'm most proud of in this answer, though, is this piece of code: ``` y=~/[^A-Z]/||1 ``` Alright, so here's some background for the non-Rubyists. Ruby completely separates booleans (`TrueClass`, `FalseClass`) from integers/numbers (`Numeric`)—that means there's no automatic conversion from true to 1 and false to 0 either. This is annoying while golfing (but a good thing... for all other purposes). The naïve approach to checking whether a single character is uppercase (and returning 1 or 0) is ``` y.upcase==y?1:0 ``` We can get this down a little further (again, with a regex): ``` y=~/[A-Z]/?1:0 ``` But then I really started thinking. Hmm... `=~` returns the index of a match (so, for our single character, always `0` if there's a match) or `nil` on failure to match, a falsy value (everything else except `FalseClass` is truthy in Ruby). The `||` operator takes its first operand if it's truthy, and its second operand otherwise. Therefore, we can golf this down to ``` y=~/[^A-Z]/||1 ``` Alright, let's look at what's happening here. If `y` is an uppercase letter, it will fail to match `[^A-Z]`, so the regex part will return `nil`. `nil || 1` is `1`, so uppercase letters become `1`. If `y` is anything but an uppercase letter, the regex part will return `0` (because there's a match at index `0`), and since `0` is truthy, `0 || 1` is `0`. ... and only after writing all of this out do I realize that this is actually the same length as `y=~/[A-Z]/?1:0`. Haha, oh well. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 24 bytes ``` j1Y24Y2hG5IePtk=~!XB1+)h ``` Uses [current version (9.1.0)](https://github.com/lmendo/MATL/releases/tag/9.1.0) of the language/compiler. ### Examples ``` >> matl > j1Y24Y2hG5IePtk=~!XB1+)h > > a0RE000000IJmcN a0RE000000IJmcNMAT >> matl > j1Y24Y2hG5IePtk=~!XB1+)h > > a01M00000062mPg a01M00000062mPgIAI ``` ### Explanation ``` j % input string 1Y2 % predefined literal: 'ABC...Z' 4Y2 % predefined literal; '012...9' h % concatenate into string 'ABC...Z012...9' G % push input string 5Ie % reshape into 5x3 matrix, column-major order P % flip vertically tk=~ % 1 if uppercase, 0 if lowercase !XB1+ % convert each column to binary number and add 1 ) % index 'ABC...Z012...9' with resulting numbers h % concatenate result with original string ``` [Answer] # JavaScript (ES6), 108 ``` x=>x.replace(/[A-Z]/g,(x,i)=>t|=1<<i,t=0)+[0,5,10].map(n=>x+='ABCDEFGHIJKLMNOPQRSTUVWXYZ012345'[t>>n&31])&&x ``` **Test** ``` f=x=>x.replace(/[A-Z]/g,(x,i)=>t|=1<<i,t=0)+[0,5,10].map(n=>x+='ABCDEFGHIJKLMNOPQRSTUVWXYZ012345'[t>>n&31])&&x // Less golfed U=x=>{ x.replace(/[A-Z]/g,(x,i)=>t|=1<<i,t=0); // build a 15 bit number (no need to explicit reverse) // convert 't' to 3 number of 5 bits each, then to the right char A..Z 0..5 [0,5,10].forEach(n=> // 3 value for shifting x += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345' // to convert value to char [ t>>n&31 ] // shift and mask ); return x } console.log=x=>O.innerHTML+=x+'\n'; ;[ ['a01M00000062mPg','a01M00000062mPgIAI'] , ['001M000000qfPyS','001M000000qfPySIAU'] , ['a0FE000000D6r3F','a0FE000000D6r3FMAR'] , ['0F9E000000092w2','0F9E000000092w2KAA'] , ['aaaaaaaaaaaaaaa','aaaaaaaaaaaaaaaAAA'] , ['AbCdEfGhIjKlMnO','AbCdEfGhIjKlMnOVKV'] , ['aBcDEfgHIJKLMNO','aBcDEfgHIJKLMNO025'] ].forEach(t=>{ var i=t[0],x=t[1],r=f(i); console.log(i+'->'+r+(r==x?' OK':' Fail (expected '+x+')')); }) ``` ``` <pre id=O></pre> ``` [Answer] ## CJam, 27 bytes ``` l_5/{W%{_el=!}%2bH+43%'0+}% ``` [Run all test cases.](http://cjam.aditsu.net/#code=qN%2F%7BS%2F0%3D%3AL%3B%0A%0AL_5%2F%7BW%25%7B_el%3D!%7D%252bH%2B43%25'0%2B%7D%25%0A%0A%5DoNo%7D%2F&input=a01M00000062mPg%20%20%20%20-%3E%20a01M00000062mPgIAI%0A001M000000qfPyS%20%20%20%20-%3E%20001M000000qfPySIAU%0Aa0FE000000D6r3F%20%20%20%20-%3E%20a0FE000000D6r3FMAR%0A0F9E000000092w2%20%20%20%20-%3E%200F9E000000092w2KAA%0Aaaaaaaaaaaaaaaa%20%20%20%20-%3E%20aaaaaaaaaaaaaaaAAA%0AAbCdEfGhIjKlMnO%20%20%20%20-%3E%20AbCdEfGhIjKlMnOVKV%0AaBcDEfgHIJKLMNO%20%20%20%20-%3E%20aBcDEfgHIJKLMNO025) A fairly straightforward implementation of the spec. The most interesting part is the conversion to characters in the checksum. We add 17 to the result of each chunk. Take that modulo 43 and add the result of that to the character `'0`. [Answer] # Japt, 46 bytes ``` U+U®f"[A-Z]" ?1:0} f'.p5)®w n2 +A %36 s36 u} q ``` Not too happy with the length, but I can't find a way to golf it down. [Try it online!](http://ethproductions.github.io/japt?v=master&code=VSuhWGYiW0EtWl0iID8xOjB9IGYnLnA1Ka53IG4yICtBICUzNiBzMzYgdX0gcQ==&input=ImEwUkUwMDAwMDBJSm1jTiI=) [Answer] # JavaScript (ES6), ~~137~~ 132 bytes ``` s=>s+s.replace(/./g,c=>c>"9"&c<"a").match(/.{5}/g).map(n=>"ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"[0|"0b"+[...n].reverse().join``]).join`` ``` *4 bytes saved thanks to [@ՊՓԼՃՐՊՃՈԲՍԼ](https://codegolf.stackexchange.com/users/41247/%d5%8a%d5%93%d4%bc%d5%83%d5%90%d5%8a%d5%83%d5%88%d4%b2%d5%8d%d4%bc)!* ## Explanation This challenge is not suited for JavaScript at all. There's no short way to reverse a string and it looks like the shortest way to convert the number to a character is to hard-code each possible character. ``` s=> s+ // prepend the original ID s.replace(/./g,c=>c>"9"&c<"a") // convert each upper-case character to 1 .match(/.{5}/g).map(n=> // for each group of 5 digits "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345" [0|"0b"+ // convert from binary [...n].reverse().join``] // reverse the string ).join`` ``` If the digits in the checksum were allowed to be lower-case it could be done in 124 bytes like this: ``` s=>s+s.replace(/./g,c=>c>"9"&c<"a").match(/.{5}/g).map(n=>((parseInt([...n].reverse().join``,2)+10)%36).toString(36)).join`` ``` ## Test ``` var solution = s=>s+s.replace(/./g,c=>c>"9"&c<"a").match(/.{5}/g).map(n=>"ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"[0|"0b"+[...n].reverse().join``]).join`` ``` ``` <input type="text" id="input" value="AbCdEfGhIjKlMnO" /> <button onclick="result.textContent=solution(input.value)">Go</button> <pre id="result"></pre> ``` [Answer] ## MATLAB, 100 98 bytes ``` s=input('');a=flip(reshape(s,5,3))';e=['A':'Z',48:53];disp([s,e(bin2dec(num2str(a~=lower(a)))+1)]) ``` A string will be requested as input and the output will be displayed on the screen. ## Explanation I'm probably using the most straight-forward approach here: * Request input * Reshape to 5 (rows) x 3 (columns) * Flip the row order * Transpose the matrix to prepare it for being read as binary * Allocate the ABC...XYZ012345 array * Compare the character indices of the transposed matrix to its lower-case equivalent and convert the booleans to strings, which are then read as binary and converted to decimal. * Interpret these decimals (incremented by 1) as indices of the allocated array. * Display the input with the additional 3 characters Now below 100 bytes thanks to Luis Mendo! [Answer] # C, ~~120~~ 118 bytes ``` n,j;main(c,v,s)char**v,*s;{for(printf(s=v[1]);*s;s+=5){for(n=0,j=5;j--;)n=n*2+!!isupper(s[j]);putchar(n+65-n/26*17);}} ``` Works for any input whose length is a multiple of 5 :) ## Ungolfed ``` n,j; main(c,v,s) char **v, *s; { for(printf(s = v[1]); *s; s+=5) { for(n=0, j=5; j--;) n=n*2+!!isupper(s[j]); putchar(n+65-n/26*17); } } ``` [Answer] ## PHP, ~~186~~ 181 bytes ``` <?$z=$argv[1];$x=str_split($z,5);$l="ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";foreach($x as$y){foreach(str_split(strrev($y))as$a=>$w)$y[$a]=ctype_upper($w)?1:0;$z.=$l[bindec($y)];}echo $z; ``` ## Unglofed ``` <?php $z = $argv[1]; $x = str_split($z,5); $l = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"; foreach($x as $y) { foreach( str_split( strrev($y) ) as $a => $w) { $y[$a] = ctype_upper($w) ? 1 : 0; } $z .= $l[bindec($y)]; } echo $z; ``` I started out thinking I could make it much shorter than this, but I ran out of ideas to make it shorter. [Answer] # [Japt](https://github.com/ETHproductions/japt), 21 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ;+ò5 ®Ô£BèXÃÍgB¬c6oì ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=OyvyNSCu1KNC6FjDzWdCrGM2b8Os&input=WwoiYTAxTTAwMDAwMDYybVBnIgoiMDAxTTAwMDAwMHFmUHlTIgoiYTBGRTAwMDAwMEQ2cjNGIgoiMEY5RTAwMDAwMDA5MncyIgoiYWFhYWFhYWFhYWFhYWFhIgoiQWJDZEVmR2hJaktsTW5PIgoiYUJjREVmZ0hJSktMTU5PIgpdLW1S) (includes all test cases) ``` ;+ò5 ®Ô£BèXÃÍgB¬c6oì :Implicit input of string + :Append ò5 :Partitions of length 5 ® :Map Ô : Reverse £ : Map each X ; B : Uppercase alphabet èX : Count occurrences of X à : End map Í : Convert from binary string to integer g : Index into ; B : Uppercase alphabet ¬ : Split c : Concatenate 6o : Range [0,6) à :End map ¬ :Join ``` [Answer] ## Perl, 80 bytes ``` $_.=join"",map{(A..Z,0..5)[oct"0b".join"",map{lc cmp$_}split//,reverse]}/.{5}/g ``` To be run as: ``` perl -ple '$_.=join"",map{(A..Z,0..5)[oct"0b".join"",map{lc cmp$_}split//,reverse]}/.{5}/g' ``` Pretty straightforward except `lc cmp $_` and `oct "0b" . $str` for binary conversion. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 18 17 bytes ``` Ȯe€ØAs5UḄ‘ịØA;ØD¤ ``` [Try it online!](https://tio.run/##y0rNyan8///EutRHTWsOz3AsNg19uKPlUcOMh7u7gVzrwzNcDi35//9/okGQqwEYeHrlJvsBAA "Jelly – Try It Online") ## Explanation ``` Ȯe€ØAs5UḄ‘ịØA;ØD¤ Main monadic link Ȯ Print (without newline) € Map: e is element of ØA the uppercase alphabet s Split into chunks of 5 five U Reverse [each] Ḅ Convert [each] from binary ‘ Add 1 [to each] ị Lookup [each] by 1-based index in ¤ ( ØA the uppercase alphabet ; join with ØD digits 0-9 ¤ ) ``` *-1 byte by inspiration from ovs' O5AB1E answer, printing the initial string directly instead of joining it at the end* *-1 byts because I'm a dumb and didn't realize that `U` vectorizes* [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), ~~18~~ 17 bytes ``` ƛꜝ;5ẇRvBkAkd+$İṅ+ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C6%9B%EA%9C%9D%3B5%E1%BA%87RvBkAkd%2B%24%C4%B0%E1%B9%85%2B&inputs=a0RE000000IJmcN&header=&footer=) My first attempt at golfing in Vyxal. ## Explanation ``` ƛꜝ;5ẇRvBkAkd+$İṅ+ ƛ ; Map ꜝ Is uppercase? 5ẇ Split into chunks of 5 R Reverse each v Vectorize B Convert from binary kAkd+ Push uppercase letters joined with digits $ Swap İ Index ṅ Join into a string + Append to the original string ``` [Answer] ## Python 2, 97 bytes ``` lambda i:i+''.join(chr(48+(17+sum((2**j)*i[x+j].isupper()for j in range(5)))%43)for x in[0,5,10]) ``` [Answer] ## PowerShell, 162 bytes ``` function f{param($f)-join([char[]](65..90)+(0..5))[[convert]::ToInt32(-join($f|%{+($_-cmatch'[A-Z]')}),2)]} ($a=$args[0])+(f $a[4..0])+(f $a[9..5])+(f $a[14..10]) ``` OK, a lot of neat stuff happening in this one. I'll start with the second line. We take input as a string via `$args[0]` and set it to `$a` for use later. This is encapsulated in `()` so it's executed and the result returned (i.e., `$a`) so we can immediately string-concatenate it with the results of three function calls `(f ...)`. Each function call passes as an argument the input string indexed in reverse order chunks as a char-array -- meaning, for the example input, `$a[4..0]` will equal `@('0','E','R','0','a')` with each entry as a char, not a string. Now to the function, where the real meat of the program is. We take input as `$f`, but it's only used way toward the end, so let's focus there, first. Since it's passed as a char-array (thanks to our previous indexing), we can immediately pipe it into a loop with `$f|%{...}`. Inside the loop, we take each character and perform a case-sensitive regex match with `-cmatch` which will result in true/false if it's uppercase/otherwise. We cast that as an integer with the encapsulating `+()`, then that array of 1's and 0's is `-join`ed to form a string. *That* is then passed as the first parameter in the .NET `[convert]::ToInt32()` call to change the binary (base `2`) into decimal. We use that resultant decimal number to index into a string (`-join(...)[...]`). The string is first formulated as a range `(65..90)` that's cast as a char-array, then concatenated with the range `(0..5)` (i.e., the string is `"ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"`). All of that is to return the appropriate character from the string. [Answer] # Jolf, 30 bytes Finally, a probably still-jolfable! [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=K2kgbVpjaTVkLnAxQ8-BQV9IcHUxIlteMV0nMCIy) ``` +i mZci5d.p1CρA_Hpu1"[^1]'0"2 Zci5 split input into groups of 5 _m map it d with this function _H reverse H A pu1 and replace in it all uppercase letters with 1 ρ "[^1]'0" replace all non-ones with zeroes C 2 parse as binary integer .p1 get the (^)th member of "A...Z0...9" ``` [Answer] # Python 3, ~~201 174~~ 138 bytes Big thanks to Trang Oul for pointing out a function declaration that no longer needed to exist. And Python ternary operators. And some incorrect output. Just...just give him the upvotes. ``` i=input();n='';c=l=15; while c:c-=1;n+=('0','1')[i[c].isupper()] while l:v=int(n[l-5:l],2);l-=5;i+=(chr(v+65),str(v-26))[v>25] print(i) ``` [Answer] # J, 36 bytes ``` ,_5(u:@+22+43*<&26)@#.@|.\]~:tolower ``` Usage: ``` (,_5(u:@+22+43*<&26)@#.@|.\]~:tolower) 'a0RE000000IJmcN' a0RE000000IJmcNMAT ``` [Try it online here.](http://tryj.tk/) [Answer] # C#, 171 bytes I'm not really well-practiced in golfing C#, but here's a shot. ``` s=>{for(var u=s;u.Length>0;u=u.Substring(5)){int p=0,n=u.Substring(0,5).Select(t=>char.IsUpper(t)?1:0).Sum(i=>(int)(i*Math.Pow(2,p++)));s+=(char)(n+65-n/26*17);}return s;} ``` [Answer] ## C# 334 ``` string g(string c){string[]b=new string[]{c.Substring(0,5),c.Substring(5, 5),c.Substring(10)};string o="",w="";for(int i=0,j=0;i<3;i++){char[]t=b[i].ToCharArray();Array.Reverse(t);b[i]=new string(t);o="";for(j=0;j<5;j++){o+=Char.IsUpper(b[i][j])?1:0;}int R=Convert.ToInt32(o,2);char U=R>26?(char)(R+22):(char)(R+65);w+=U;}return c+w;} ``` If requested, I'll reverse my code back to readable and post it. [Answer] # Python 3, 87 bytes ``` lambda s:s+bytes(48+(17+sum((~s[i+j]&32)>>(5-i)for i in range(5)))%43 for j in(0,5,10)) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 26 bytes ``` S+öm!+…'A'Zṁsŀ6mȯ→ḋ↔†o±DC5 ``` [Try it online!](https://tio.run/##yygtzv7/P1j78LZcRe1HDcvUHdWjHu5sLD7aYJZ7Yv2jtkkPd3Q/apvyqGFB/qGNLs6m////TzQIcjUAA0@v3GQ/AA "Husk – Try It Online") Getting the alphabets takes a lot of bytes. Otherwise, I think this qould be at par with the other languages. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` ?5ôvžKuÙyR€.uJCè? ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f3vTwlrKj@7xLD8@sDHrUtEav1Mv58Ar7//8TDQx9DcDAzCg3IB0A "05AB1E – Try It Online") **Commented**: ``` ? # print the input 5ô # split into groups of 5 ε # iterate over the groups: žK # push [a-zA-Z0-9] u # convert to uppercase Ù # deduplicate: [A-Z0-9] y # push the group R # reverse it € # for each char: .u # is it uppercase? J # join into a binary string C # convert from binary è # index into the string ? # print the char at index ``` [Answer] # [Raku](http://raku.org/), 63 bytes ``` {$_~S:g[((<:Lu>)||.)**5]=flat('A'..'Z',^6)[:2[?«$0[4…0;0]]]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiW@LtgqPVpDw8bKp9ROs6ZGT1NLyzTWNi0nsURD3VFdT089Sl0nzkwz2soo2v7QahWDaJNHDcsMrA1iY2Nr/xcnViooqcQr2NopVKcpqMTXKimk5Rcp2CQaGPoagIGZUW5AuoIBnF@YFlAZrJBo4OYK4buYFRm72f0HAA "Perl 6 – Try It Online") * `$_` is the single argument to this function, the Salesforce ID. * `$_ ~ S:g[regex] = expr` concatenates `$_` with the result of globally replacing the regular expression `regex` with `expr`. * `<:Lu>` matches any uppercase letter. `(<:Lu>) || .` matches an uppercase letter or any other character. An uppercase letter will be stored in a capture group; other characters won't. * `((<:Lu>) || .) ** 5` matches five such alternates. `$0` is the capture group for the outermost group. Since it is repeated, it will be a list of match objects. Each such match object will contain a capture group match object only if it's an uppercase letter. * As for the replacement text, `flat('A'..'Z', ^6)` evaluates to a list of all uppercase letters followed by the numbers zero through five. The following bracketed expression is an index into that list, providing the replacement character for each set of five ID characters. * `$0` is a list of match objects, one per character. * `$0[4…0;0]` is a list of the submatch objects, in reverse order. For uppercase letters, this is a match object; for other characters, it's `Nil`. * `?«` coerces that list of objects to boolean values. Match objects beome `True`, and `Nil` becomes `False`. * `:2[...]` combines those binary/boolean digits into a number. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~41~~ 37 bytes ``` {x,,/[`c$65+!26;$!6]@2/|+3 5#~"A["'x} ``` [Try it online!](https://ngn.bitbucket.io/k/#eJxdkF1LwzAUhu/Pr8hqwYtNGjMamIJ4XFvNauaYupshOOuyIdtAO3Dix2+3NGkh5718ePKS95iz70OvF82fi1DG3Y6Q52FHPl2K6KfbZ/HRX4Dz4PjwC2BYsODTlNdRo20xDiw71ZZJsZ2sasZb9m4mX/fOy9zbRH70M+tlA8f4QHwK6/mpGb4MX1NzvVZv+Ubv7qx3VSSpWd2oUX6rxxWDCPbLcs+KRbksgXyVVTm5YIRqfAAgA1rTowoVkFVOJFThI5CpbaNHNU6B7G8afZojAjlK0+gHK5FcyomEzvIZkPM1jT7lIoZ/Jn2Khw==) * `~"A["'x` generate a bit mask indicating which values of `x` (the input) are uppercase letters * `|+3 5#` chunk the input into five-length sections, transposing them and reversing the result to set up for... * `2/` converting each column from a list of base-two values to a single base-ten number * `,/[`c$65+!26;$!6]@` generate `"ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"` and index into it with the above * `x,` append the checksum to the input (and implicitly return) [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 40 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` {𝕩∾(u∾u-17)⊏˜2⊸×⊸+˜´¨(5/↕3)⊔𝕩∊u←'A'+↕26} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge/CdlaniiL4odeKIvnUtMTcp4oqPy5wy4oq4w5fiirgry5zCtMKoKDUv4oaVMyniipTwnZWp4oiKdeKGkCdBJyvihpUyNn0KCuKImOKAvzLigL8x4qWKPuKLiOKfnEbCqCDin6gKImEwMU0wMDAwMDA2Mm1QZyIKIjAwMU0wMDAwMDBxZlB5UyIKImEwRkUwMDAwMDBENnIzRiIKIjBGOUUwMDAwMDAwOTJ3MiIKImFhYWFhYWFhYWFhYWFhYSIKIkFiQ2RFZkdoSWpLbE1uTyIKImFCY0RFZmdISUpLTE1OTyIK4p+p) Or 31 bytes in [dzaima/BQN](https://github.com/dzaima/BQN): ``` {𝕩∾(2⊸×⊸+˜´¨(5/↕3)⊔𝕩∊•a)⊏•a∾•d} ``` [Answer] Dyalog APL, 23 bytes ``` {⍵,⎕A[1+2⊥⍉⎕A∊⍨⌽3 5⍴⍵]} ``` This is a straightforward mapping of the problem statement. ``` 3 5⍴⍵ ⍝ Reshape the vector into a matrix of ⍝ 3 rows by 5 columns. ⌽ ⍝ Reverse the rows. ⎕A∊⍨ ⍝ For each element, check whether they ⍝ are a member(∊) of the uppercase ⍝ alphabet, ⎕A. 2⊥⍉ ⍝ Decode, ⊥, the columns as a base 2 ⍝ number. The transpose, ⍉, is so the ⍝ rows becomes the columns. The result ⍝ is a three element vector. 1+ ⍝ Add one to each element so that they ⍝ map to the indexes of the letters on ⍝ the alphabet. This is because arrays ⍝ in APL are 1 indexed by default. ⎕A[] ⍝ Maps the indexes to their ⍝ corresponding uppercase letter. ⍵, ⍝ Finally concatenate the original ⍝ vector with the result. ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 31 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` 5n{±{┐Z{²≡]∑]2┴╵(Z◂[]6@)∑@]⤢╶;+ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjE1JXVGRjRFJXVGRjVCJUIxJXVGRjVCJXUyNTEwJXVGRjNBJXVGRjVCJUIyJXUyMjYxJXVGRjNEJXUyMjExJXVGRjNEJXVGRjEyJXUyNTM0JXUyNTc1JXVGRjA4JXVGRjNBJXUyNUMyJXVGRjNCJXVGRjNEJXVGRjE2JXVGRjIwJXVGRjA5JXUyMjExJXVGRjIwJXVGRjNEJXUyOTIyJXUyNTc2JXVGRjFCJXVGRjBC,i=YTBSRTAwMDAwMElKbWNO,v=8) [Answer] # [Perl 5](https://www.perl.org/) `-p`, 63 bytes ``` map{y/A-Z/0/c;y/A-Z/1/;$\.=(A..Z,0..5)[oct"0b".reverse]}/.{5}/g ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saC6Ut9RN0rfQD/ZGsIy1LdWidGz1XDU04vSMdDTM9WMzk8uUTJIUtIrSi1LLSpOja3V16s2rdVP//8/0SDI1QAMPL1yk/3@5ReUZObnFf/X9TXVMzA0@K9bAAA "Perl 5 – Try It Online") ]
[Question] [ You should write a program or function which receives a string representing an ascii-art polygon as input and outputs ot returns the area of the polygon. The input is a string consisting of the characters `_ / \ L V space` and `newline` defining a [simple polygon](http://en.wikipedia.org/wiki/Simple_polygon) (which means no extra segments, no self-touch and no self-intersect). The area of a single character cell is `2` * `_` splits the cell into sizes `0` and `2` * `\` splits the cell into sizes `1` and `1` * `/` splits the cell into sizes `1` and `1` * `L` splits the cell into sizes `0` and `2` * `V` splits the cell into sizes `1` and `1` (The two sides of the `V` will always be on the same side of the polygon so they are treated together in the listing.) Every character connects the two corners of its character cell which you expect (e.g. top left and top right in case of `V`). An example with area of 7 (`1+2+1` in the second row and `1+1+1` in the third one): ``` _ / \ V\/ ``` ## Input * Input will form a rectangle, i.e. there will be the same number of characters between newlines. * There can be extra whitespace on any side of the polygon. * Trailing newline is optional. ## Output * A single positive integer, the area of the polygon. ## Examples Outputs are after the last row of their inputs. ``` _ V 1 /L \/ 3 /VV\ L / L/ 14 ____/\ \ / /\/ / \____/ 32 /V\ / \__ \ / /\/ /V L____/ 45 ``` This is code-golf so the shortest entry wins. [Answer] # Pyth, 47 46 45 36 30 ``` FNs.zx=Z}N"\/L"aY|}N"\/V"yZ;sY ``` Explanation: ``` FNs.z For every character in input, except newlines... x=Z}N"\/L" Swap state if /, \, or L. aY|}N"\/V"yZ; Append 1 if /, \, or V, else 2 times the state to Y. sY Sum Y and print. ``` We have two states, "in the polygon", and "out of the polygon". The following characters each do the following when reading them from top-left to bottom-right: ``` / \ swap state, add one to area V add one to area _ space if in polygon, add two to area L swap state, if in polygon, add two to area ``` Note that "add one to area" and "if in polygon, add two to area" are mutually exclusive. [Answer] # [Retina](https://github.com/mbuettner/retina), 293 + 15 = 308 ~~314~~ ~~385~~ bytes ``` ;`\s _ ;`\\ / ;`.+ o$0iio ;+`(o(?=/.*(i)|L.*(ii)|V.*(io)|_)|i(?=/.*(io)|L.*(o)|_.*(ii)|V.*(i))). $1$2$3$4$5$6$7$8 ;`o <empty> ;`ii$ #:0123456789 ;+`^(?=i)(i*)\1{9}(?=#.*(0)|i#.*(1)|ii#.*(2)|iii#.*(3)|iiii#.*(4)|iiiii#.*(5)|iiiiii#.*(6)|iiiiiii#.*(7)|iiiiiiii#.*(8)|iiiiiiiii#.*(9)) $1#$2$3$4$5$6$7$8$9$10$11 :.*|\D <empty> ``` Each line goes in a separate file, so I've added 13 to the byte count. Alternatively, you can put that all in a single file as is and use the `-s` flag. The `<empty>` stand for actually empty files or lines. Unfortunately, I need 187 bytes just to convert the result from unary to decimal. I guess I really should [implement this some time soon](https://github.com/mbuettner/retina/issues/18). ## Explanation Retina is a regex-based language (which I wrote exactly for being able to do stuff like this with regex). Each pair of files/lines defines a replacement stage, with the first line being the pattern and the second line the replacement string. Patterns can be preceded by a ```-delimited configuration string, which may contain the usual regex modifiers, as well as some Retina-specific options. For the above program, the relevant options are `;`, which suppresses output of that stage and `+`, which applies the replacement in a loop until the result stops changing. The idea of the solution is to count each line separately, because we can always decide by the characters already encountered whether we're inside or outside the polygon. This also means I can join the entire thing into a single line, because going the beginning and end of a line are always outside the polygon. We can also note that `_` and space are completely identical for a line sweep algorithm, as well as `\` and `/`. So as a first step I replace all newlines and spaces by `_` and all `\` by `/` to simplify some code later on. I'm keeping track of the current inside/outside state with the characters `i` and `o`, while also using the `i`s to tally the area. To do so I start by prepending an `o` to the joined line to mark that we're outside the polygon. I'm also adding an `iio` to the very end of the input, which I'll use as a lookup to generate new characters. Then, the first large replacement simply replaces an `i` or `o` followed by one of `/V_L` with the next set of characters, thereby flooding and tallying the entire thing. The replacement table looks as follows, where the columns correspond to the last character in that line and the rows to the next character (where `S` is for space and `<>` for an empty string). I've included all characters of the input to show the equivalences I've already made use of: ``` i o / io i \ io i L o ii V i io _ ii <> S ii <> ``` Note that the final character then always indicates whether *after* the character we're inside or outside the polygon, while the number of `i`s corresponds to the area that needs to be added to the polygon. As an example here are the results of the first four iterations on the last example input (this was generated by an old version which actually flooded each line separately, but the principle is still the same): ``` o /V\ o / \___ o L _/ o/\/ /V oL__ _/ o V o /V\ o / \___ o L _/ oi\/ /V oii__ _/ o V o /V\ o/ \___ oL _/ oiio/ /V oiiii_ _/ o V o/V\ oi \___ oii _/ oiioi /V oiiiiii _/ oV oiV\ oiii \___ oiiii _/ oiioiii /V oiiiiiiii_/ oio ``` Lastly, I just get rid of all the `o`s and the line breaks by removing everything that matches `[^i]`, and the remainder is the decimal-to-unary conversion which is rather boring. [Answer] # CJam, ~~48 43~~ 29 bytes ``` qN-{i_9%2%U!^:U;J%D%1U2*?}%:+ ``` *Update*: Golfed a lot using maths and the state\*2 trick from orlp's answer. **How it works (Outdated, updating soon)** We split the input on newline and then for each part we maintain a counter of occurrences of boundary characters `L\/`. This counter % 2 will tell us which of the two partitions amounts to choose for all of the characters. Then we find the index of each character in the string `L _`. `\/V` will give `-1` referring to the last element in an array. After getting the index, we use `4558Zb2/` to create the array `[[2 0] [0 2] [0 2] [1 1]]` and then choose the correct of the count using the counter. ``` qN/0f{ } e# Split the input on newline and for each \{ }/ e# swap the 0 to back and for each char in e# the line, run this loop _"L _"# e# Copy the char and get index of it in e# this string "L _" 4558Zb e# This is basically 4558 3base e# which comes to be [2 0 0 2 0 2 1 1] 2/= e# Group into pairs of 2 and choose the e# correct one. 2$= e# Based on the counter, choose the correct e# partition amount @@"\/L"&,+ e# Increment the counter if the char is one e# of \, / and L ; e# Pop the counter after each line loop :+ e# Sum all the numbers to get area ``` [Try it online here](http://cjam.aditsu.net/#code=qN-%7Bi_9%252%25U!%5E%3AU%3BJ%25D%251U2*%3F%7D%25%3A%2B&input=%20%20%20%2FV%5C%0A%20%20%2F%20%20%20%5C__%20%0A%20%20%5C%20%20%20%20%20%2F%0A%2F%5C%2F%20%20%20%2FV%0AL____%2F) [Answer] # Perl, ~~65~~ 58 bytes ``` map{map{$b^=2*y,/\\L,,;$a+=y,/\\V,,||$b}split//}<>;print$a ``` * Toggle $b between 0 and 2 upon seeing / \ or L. * Add 1 to $a upon seeing / \ or V. * Add $b to $a upon seeing anything else. [Answer] # GNU sed, 290 + 1 The + 1 is to account for the `-r` switch passed to sed. Comments and additional whitespace not counted in the score. I haven't looked in great detail, but I think this is probably similar to [Martin's Retina answer](https://codegolf.stackexchange.com/a/49318/11259): ``` : # label to start processing next (or first) line s/[0-9]//g # remove the count of colons from previous lines H # append the current line to the hold space g # copy the hold space to the pattern space y^_\\^ /^ # Replace '_' with ' ' and replace '\' with '/' s/(\n| +$)//g # strip newlines and trailing space :o # start of "outside loop" s/(^|:) *V/\1:/ # replace leading spaces and "V" with ":" to # if the above matches, stay outside s/(^|:) *[|/]/\1:/ # replace leading spaces and "|" or "/" with ":" ti # if the above matches, go inside s/(^|:) *L/\1::/ # replace leading spaces and "L" with "::" :i # start of "inside" loop s/: /:::/ # replace space with "::" ti # if the above matches, stay inside s/:V/::/ # replace "V" with ":" ti # if the above matches, stay inside s/:[|/]/::/ # replace "|" or "/" with ":" to # if the above matches, go outside s/:L/:/ # remove "L" to # if the above matches, go outside h # copy current string of colons to hold buffer :b # start of colon count loop s/:{10}/</g # standard sed "arithmetic" to get string length s/<([0-9]*)$/<0\1/ s/:{9}/9/ s/:{8}/8/ s/:{7}/7/ s/:{6}/6/ s/:{5}/5/ s/::::/4/ s/:::/3/ s/::/2/ s/:/1/ s/</:/g tb # once arithmetic done, pattern buffer contains string length N # append newline and next line to pattern buffer b # loop back to process next line ``` ### Overview * Replace each unit of area with a colon `:` * Count the number of colons ### Notes * `sed` is line oriented so needs some work to process multiple lines at once. The `N` command does this by appending a newline then the next line to the current pattern space. The difficulty with `N` is that once it gets to the input stream EOF, it quits `sed` completely without any option to do further processing. To get around this, we count the current set of colons at the end of each line, just before reading in the next line. ### Output: ``` $ echo ' /V\ / \__ \ / /\/ /V L____/' |sed -rf polyarea.sed 45 $ ``` [Answer] # C, 93 ~~96 108~~ bytes *Edit:* Took into account suggestions in the comments, converted the while into a single-statement for loop, and removed the "i" variable entirely. ``` int s,t;main(c,v)char**v;{for(;c=*v[1]++;t+=s+(c>46^!(c%19)^s))s^=c>13^c%9>4;printf("%d",t);} ``` *Original post:* This looked like a fun and simple enough problem to finally get me to create an account here. ``` main(c,v)char**v;{int i,t,s;i=t=s=0;while(c=v[1][i++]){s^=c>13^c%9>4;t+=s+(c>46^!(c%19)^s);}printf("%d",t);} ``` The polygon text should be passed as the first command-line argument; this should work with or without any amount of newlines / whitespace. This just reads in the polygon one character at a time, s switches whether currently in or outside of the polygon on '/', 'L', or '\', and t increases by 1 on '/', 'V', and '\', or by 2 if inside / 0 if outside on 'L', '\_', space and newline. This is my first time trying my hand at any sort of "golfing" (or C, to the extent it differs from C++), so any criticisms are appreciated! [Answer] # POSIX sed, 245 244 POSIX sed, no extensions or extended regexps. Input is limited to the maximum hold space size of sed - POSIX mandates at least 8192; GNU manages more. This version assumes that there will be no blank lines before or after the shape; an extra 10 bytes of code, indicated in the expansion, can accommodate that if it's a requirement (original question doesn't specify). ``` H /^\([L\\]_*\/\|V\| \)*$/!d x s/[_ ]/ /g s/^/!/ s/$/!/ :g s/\([^V]\)V/V\1/ tg y/V/ / s/L/! /g s,[/\\], ! ,g s/![^!]*!//g :d / /{ s/ /v/g s/vv/x/g /[ v]/!s/\b/0/2 s/ /b/g s/bb/4/ s/b /3/ s/v /6/ s/vb/7/ s/v3/8/ s/v4/9/ y/ bvx/125 / td } ``` ## Expanded and annotated ``` #!/bin/sed -f # If leading blank lines may exist, then delete them # (and add 8 bytes to score) #/^ *$/d # Collect input into hold space until we reach the end of the figure # The end is where all pieces look like \___/ or V H /^\([L\\]_*\/\|V\| \)*$/!d x # Space and underscore each count as two units s/[_ ]/ /g # Add an edge at the beginning and end, so we can delete matching pairs s/^/!/ s/$/!/ # Move all the V's to the beginning and convert each # to a single unit of area :gather s/\([^V]\)V/V\1/ tgather y/V/ / # L is a boundary to left of cell; / and \ in middle s/L/! /g s,[/\\], ! ,g # Strip out all the bits of outer region s/![^!]*!//g # Now, we have a space for each unit of area, and no other characters # remaining (spaces are convenient because we will use \b to match # where they end). To count the spaces, we use roman numerals v and x # to match five and ten, respectively. We also match two (and call # that 'b'). At the end of the loop, tens are turned back into spaces # again. :digit / /{ s/ /v/g s/vv/x/g /[ v]/!s/\b/0/2 s/ /b/g s/bb/4/ s/b /3/ s/v /6/ s/vb/7/ s/v3/8/ s/v4/9/ y/ bvx/125 / tdigit } # If trailing blank lines may exist, then stop now # (and add 2 bytes to score) #q ``` [Answer] # C, 84 bytes ``` a;i;f(char*s){for(;*s;a+=strchr("\\/V",*s++)?1:i+i)i^=!strchr("\nV_ ",*s);return a;} ``` We switch sides whenever we see `\`, `/` or `L`; we always add one for `\\`, `/` or `V`, but add 2 (if inside) or 0 (if outside) for space, newline, `L` or `_`. The variables `a` and `i` are assumed to be zero on entry - they must be reset if the function is to be called more than once. ### Ungolfed: ``` int a; /* total area */ int i; /* which side; 0=outside */ int f(char*s) { while (*s) { i ^= !strchr("\nV_ ",*s); a += strchr("\\/V",*s++) ? 1 : i+i; } return a; } ``` ### Test program: ``` #include <stdio.h> int main() { char* s; s = " _ \n" " V \n"; printf("%s\n%d\n", s, f(s)); a=i=0; s = "/L\n" "\\/\n"; printf("%s\n%d\n", s, f(s)); a=i=0; s = " /VV\\\n" " L /\n" " L/"; printf("%s\n%d\n", s, f(s)); a=i=0; s = " ____/\\ \n" " \\ /\n" "/\\/ /\n" "\\____/"; printf("%s\n%d\n", s, f(s)); a=i=0; s = " /V\\\n" " / \\__ \n" " \\ /\n" "/\\/ /V\n" "L____/"; printf("%s\n%d\n", s, f(s)); a=i=0; return 0; } ``` ]
[Question] [ [Related](https://codegolf.stackexchange.com/questions/226292/g%C3%B6del-numbering-of-a-string) but different. [Part II](https://codegolf.stackexchange.com/questions/260178/g%C3%B6del-encoding-part-ii-decoding) Taken from the book: Marvin Minsky 1967 – Computation: Finite and Infinite Machines, chapter 14. ### Background As the Gödel proved, it is possible to encode with *a unique positive integer* not just any string but any *list structure*, with any level of nesting. Procedure of encoding \$G(x)\$ is defined inductively: 1. If \$x\$ is a number, \$G(x) = 2^x\$ 2. If \$x\$ is a list \$[n\_0, n\_1, n\_2, n\_3, …]\$, \$G(x) = 3^{G(n\_0)} \cdot 5^{G(n\_1)} \cdot 7^{G(n\_2)} \cdot 11^{G(n\_3)} \cdot...\$ Bases are *consecutive primes*. ### Examples: `[0] → 3` `[[0]] →` \$3^3 =\$ `27` `[1, 2, 3] →` \$3^{2^1} \cdot 5^{2^2} \cdot 7^{2^3} = \$ `32427005625` `[[0, 1], 1] →` \$3^{3^{2^0} \cdot 5^{2^1}} \cdot 5^{2^1} = \$ `15206669692833942727992099815471532675` ### Task Create a program that encoding (in this way) any given (possibly ragged) list to integer number. This is `code-golf`, so the shortest code in bytes wins. ### Input Valid non-empty list. **UPD** Some considerations regarding *empty lists* are given [here](https://codegolf.stackexchange.com/a/260088/114511). You may assume: * There are no empty sublists * Structure is not broken (all parentheses are paired) * List contains only non-negative integers ### Output Positive integer obtained by the specified algorithm ### Note Numbers can be very large, be careful! Your code *must be correct in principle*, but it is acceptable that it cannot print some number. However, all test cases are checked for TIO with Mathematica program and work correctly. ### Test cases ``` [0,0,0,0,0] → 15015 [1, 1, 1] → 11025 [[1], [1]] → 38443359375 [0, [[0]], 0] → 156462192535400390625 [[[0], 0], 0] → 128925668357571406980580744739545891609191243761536322527975268535 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11 10 9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)! (Use of a dyadic chain in place of a monadic compound link avoiding the need for argument manipulation with ```.) ``` ߀Żð%¡ÆẸ ``` A monadic Link that accepts a ragged list of non-negative integers and yields its Gödel encoding. **[Try it online!](https://tio.run/##y0rNyan8///w/EdNa47uPrxB9dDCw20Pd@34//9/dLSBjoJhLAgDAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///w/EdNa47uPrxB9dDCw20Pd@34f7gdKPL/f3S0QawOlwKIAtOGOgpGOgrGUDEdBcNYMIbIGMLY0SBhIAHmAFVBtCtAjQIZqQDFXLEA "Jelly – Try It Online"). ### How? ``` ߀Żð%¡ÆẸ - Link: non-empty list OR number, X ¡ - repeat... % - ...number of times: (X) modulo (X) positive ints -> 0 zero -> nan* non-empty lists -> non-empty lists* * truthy non-integers are treated by ¡ as 1 ð - ...action: the dyadic chain - f(X, X): € - for each E in X: ß - call this Link with X=E Ż - prefix with a zero (if X=zero we get [0]) ÆẸ - recompose from prime exponent list e.g.: [0,4,0,2] -> 3^4 × 7^2 = 3969 [0] -> 2^0 = 1 n -> 2^n (non-list n treated as [n]) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 24 bytes ``` ;2^₍|↰ᵐGl~lℕ₃ᵐṗᵐ≠≜;Gz^ᵐ× ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/39oo7lFTb82jtg0Pt05wz6nLedQy9VFTM5DzcOd0IPmoc8GjzjnW7lVxQM7h6f//R0dHG8TqgNH/KAA "Brachylog – Try It Online") Surely there are shorter ways to generate a list of primes… Brachylog is based on SWI-Prolog and can deal with [arbitrarily large integers](https://tio.run/##SypKTM6ozMlPN/r/39oo7lFTb82jtg0Pt05wz6nLedQy9VFTM5DzcOd0IPmoc8GjzjnW7lVxQM7h6f//R0dHG8bqGIDQ/ygA), but this will quickly run out of memory for even simple lists. ### Explanation ``` ;2^₍ Output = 2^Input | Or (if the input is not an integer) ↰ᵐG Recursive call of this predicate for all elements of the Input; call the result G Gl~l Take a list with as many elements as G ℕ₃ᵐṗᵐ≠≜ It must be a list of primes greater than 3 and all different (it always unifies with increasing magnitudes) ;Gz Zip with G ^ᵐ Map power × Multiply ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), `A` ~~23~~ ~~21~~ 11 bytes @AndrovT cool result: ``` Eλ-[żǎ$vxeΠ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiRc67LVvFvMeOJHZ4Zc6gIiwiIiwiWzEsIDEsIDFdXG5bWzFdLCBbMV1dXG5bMCwgW1swXV0sIDBdXG5bW1swXSwgMF0sIDBdIl0=) Unfortunately, can't explain in detail. Hope one of Vyxal' experts helps... My old version, maybe useful for beginners in Vyxal: ``` ƛIȧ[:L›ÞpŻ$vx¨£e|E]fΠ ``` Every input must be list of lists, so first test case should be `[[1, 1, 1]]` etc. -2 bytes thanks @emanresu (Vyxal chat) ``` ƛ #Begin lambda map Iȧ #Condition for If: is it list? [ #Begin If :L› #If list - get length and add 1 ÞpŻ #Get slice of given length from infinite list of primes $ #Swap vx #Recursively apply to list ¨£e #Zip and reduce pairs with exponentiation | #Else E #If number - two power ] #End If and lambda map, fΠ #Flatten and reduce by product ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwixptJyKdbOkzigLrDnnDFuyR2eMKowqNlfEVdZs6gIiwiIiwiW1sxLCAxLCAxXV1cbltbWzFdLCBbMV1dXVxuW1swLCBbWzBdXSwgMF1dXG5bW1tbMF0sIDBdLCAwXV0iXQ==) [Answer] # [R](https://www.r-project.org), ~~103~~ ~~102~~ 98 bytes *Edit: -1 byte, and then -4 more, both thanks to pajonk* ``` `?`=\(x,p=3)`if`(sum(!p%%1:p)>2,x?p+1,`if`(is.list(x),`if`(length(x),(x[-1]?p+1)*p^?el(x),1),2^x)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY_RasIwFIbvfQplCDkzjpwTkzSDrpd9CJ2Ugc5CN8JaIe-ymyrsfXbr22iSSjdykfN_5-RL8n366s9l_nPs9svs8lYVVb5hnrtcQlXvK9YeP9jMzef47OCFuC_cAnns1O1TU7cd85Bys_t87w4hMr9e4muYhEe3LXZNgAicth5guOm3ZAKmD1OclAxDQbci-gQXEDtqJBiJGUnM8h7vLHrMH1Fag06MRuTEZXLQiowQSpP6bwsPxuEkCa211ZYyKe1tnoy1JKzNUK0MKknaqPSvvk_7FQ) [Answer] # JavaScript (ES13), 82 bytes Expects a ragged list of Bigints. Returns a Bigint. ``` f=(a,k=2n,t=1n)=>a.at?a.map(a=v=>(g=d=>k%d--?g(d):d)(k++)?a(v):t*=k**f(v))&&t:k**a ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZJNTsMwEIUllqw4QjZUdn_tsWfsqeT2DmwRC4s0XaQkSIRehk0XcCg4DU6iVmoaSx558d43z6P5-q7qfHc6_Xw2xcL_PhVBxHkZoJo3QVcybOIyNtu4fIvvIoZj2Ih9yMOmfMwXi-1e5HKdS1HOZnIbxVGum2kop9MiPeVk0qzTO_bkv7uH17r6qA-75aHei0I8q-pFymx4VqvM3A-UrfRWm5TghlJdzbOUPTNX8BYKFpxSSIAj-Hmmq5euXFzJoxEUETExeGM4AcAxg2L2Gq3TaIDcDa6lXd8W2uGUvlHrrvd16765ViNRu5htHX7PW2sMshnP04_wnOXyPbIEmgENWqUMq7HhtM7OOHSDT04ib9Ch01YRe4VeOWudYbToWZNizRqscZSGRQYA0wQdAvnUs1-M8-r9Aw) Or [79 bytes](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWN_3TbDUSdbJtjXRKbA01be0S9RJL7BP1chMLNBJty2ztNNJtU2ztslVTdHXt0zVSNK1SNDWytbU17RM1yjStSrRss7W00oBMzZoSKyAzEWrsnOT8vOL8nFS9nPx0jTSNaINYTU0FZKCvr2DMhaYIqApVGVCRkTm6KgMdBQQCqQeqMjQ1MDRFV2ioowBCCCNBCg0NjEwhboQFAQA) without Bigints. [Answer] # [Arturo](https://arturo-lang.io), 66 bytes ``` f:$[x][(block? x)?[p:3∏map x=>[p^f&until->prime? p->'p+2]]->2^x] ``` [Try it](http://arturo-lang.io/playground?bPDONo) ``` f:$[x][ ; a function f taking an argument x (block? x)?[ ; is x a block? then... p:3 ; assign 3 to p ∏ ; product map x=>[ ; map over x, assign current elt to & p^f& ; p raised to the Gödel encoding of the current elt until->prime? p-> ; until p is prime... 'p+2 ; add 2 to p via in-place modification ] ; end map ] ; end the 'true' part of the ternary ->2^x ; ...otherwise, if x isn't a block, take 2^x ] ; end function ``` [Answer] # [Python](https://www.python.org), 103 bytes ``` g=lambda n,k=1,m=1:m%k>n or-~g(n,k+1,m*k) f=lambda l,p=3:l*0==0and 2**l or p**f(l[0])*f(l[1:]or 0,g(p)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY309NtcxJzk1ISFfJ0sm0NdXJtDa1yVbPt8hTyi3Tr0jWAotpAUa1sTa40mMocnQJbY6scLQNbW4PEvBQFIy2tHKByhQItrTSNnGiDWE0wbWgVCxQ00EnXKNDUhFrnXFCUmVeikaYBUqXJBecBuSh8Qx0jHWM0FTqGsUAEMwrmAwA) Method for calculating next prime is shamelessly adapted from [Dennis's answer](https://codegolf.stackexchange.com/a/108539/113573). [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr/), 118 bytes Modified from [@Dominic van Essen's answer](https://codegolf.stackexchange.com/a/260041/110802) --- Golfed version, [try it online!](https://tio.run/##Vc7PTsMwDAbwO08xbUKKmSfFzpIsh3BBqG/ApfsjhMaUw0ZUuqkI8ezF0K4UOaefP31Ofq7S4pDbtlAN5mggfqZX9X4@qhQJM6p8myBGDfeMv5E5AUqi/sh71chmWu@eHh@mPzaT9VZCJW3grlCX/Uv9VokuCBM2ZZqLdwXyeNsAfLW5SqdaFUoDTNbrCd1cgTrgAUqNetOn7FipVz/W3swfifXI/l9pN0O1HrcTMpprFy/Za20d23Gr3B@@QJa1cy64wCtjguTZh8A6hBXZpSdr2HnbfgM) ``` G(x,p=3)={if(sum(i=1,p,(p%i)==0)>2,G(x,p+1),if(type(x)=="t_VEC",if(#x,p^G(x[1])*G(vector(#x-1,i,x[i+1]),p+1),1),2^x))} ``` Ungolfed version ``` G(x, p = 3) = { if (sum(i = 1, p, (p % i) == 0) > 2, G(x, p + 1), if (type(x) == "t_VEC", if (#x, p^G(x[1]) * G(vector(#x - 1, i, x[i + 1]), p + 1), 1 ), 2^x ) ) } print(G(0)) \\ 1 print(G(1)) \\ 2 print(G([0,0])) \\ 15 print(G([0,1])) \\ 75 print(G([0])) \\ 3 print(G([[0]])) \\ 27 print(G([0,0,0,0,0])) \\ 15015 print(G([1,2,3])) \\ 32427005625 print(G([[0,1],1])) \\ 15206669692833942727992099815471532675 ``` [Answer] # [Julia](https://julialang.org), ~~68~~ 66 bytes ``` !x::Int=2^x !(x,p=2)=prod(i->(while(p+=1).%(2:p-1)∋0end;p^!i),x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TZHLSsNQEEBxm69IECHBtMzjzn1Urgt3fkOoILRipMTQphhwrQjduXXTTT9Kl_0Sb5O0lGEGZpg58_rZvawX5eN2u1s3TyP7e5e0k8l91Xh6aKMkbfPaU-br5essLUe36dtzuZin9bXHbHyV0qQeYbb_2sC8mt3UD0mZ5W3Wk_4u3pv5qlnFvogKmObx5f7zO-aoCM7JY08mKjCPKY_5FCXcbz6EKFhD7JkUGQDRJIfqPMZprwODoEvvi9CjEGitnXZkmV2oJeMcgXMWRRkUJm0CCfJBjiQUQOmmwTM-InR9D4FgTm2tUsziuEfFw1pnMK00oSNhUQDsoB-_O0WvQyLZkKS1ZTFiUIF2FsSCUcqwEyXWoQaHDkmx0WF8zUQSdjJC2gZ8NI3qZVk1i2qcjpPu6MMPjl_9Bw) -2 bytes by MarcMush. Doesn't use prime built-ins, which are not in Base anyway. Feels a bit weird to include a type annotation while golfing in a language that doesn't require it, but it looks like a decent way to disambiguate between numbers and lists. Note that this will only produce correct output within Int64. At the expense of 5 bytes, we can add a `big(...)` wrapper to get a version that processes all test cases as desired: ## [Julia](https://julialang.org), ~~73~~ 71 bytes ``` !x::Int=big(2)^x !(x,p=2)=prod(i->(while(p+=1).%(2:p-1)∋0end;p^!i),x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TZHLSsNQEEBxm69IECHBtMzjzn1UrlvxG0oLSqtGSgxtigHXitCdWzfd9KN02S_xNomlDDMww8yZ1_fueb0o7rbb3bp-GNifm6QZjW7L2t8Xjyll0yZK0iavPGW-Wr7M0mJwnb4-FYt5Wl16zIYXKY2qAWb7zw3My9lVNU2KLG-yDvd79lbPV_Uq9uNoDJM8Pt9_fMUcjYNz9NiTicaYx5THfIwS7jfvQhSsIfZMigyAaJJDdR7jpNOeQdCmd0XoUQi01k47sswu1JJxjsA5i6IMCpM2gQR5L_8kFEBpp8ETPiK0fQ-BYI5trVLM4rhDxf1aJzCtNKEjYVEA7KAbvz1Fp30i2ZCktWUxYlCBdhbEglHKsBMl1qEGhw5JsdFhfM1EEnYyQtoGfDSJqmVR1otymA6T9uj9D_5f-wc) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~23~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` o"Ddië®δ.VāØsmP"©.V ``` Also works for loose integer inputs, instead of just (ragged) lists. [Try it online](https://tio.run/##yy9OTMpM/f8/X8klJfPw6kPrzm3RCzvSeHhGcW6A0qGVemH//0dHG@gYxgIRAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/fCWXlMzDqw@tO7dFL@xI4@EZxbkBSodW6oX91/kfbaCjEG0QCySAJIgy1DHSMYbwdQxjQQgkZghhRANJIAYxDXQgOiB6QUaAUSwA). **Explanation:** Recursive functions are always so verbose in 05AB1E.. :/ ``` o # Take 2 to the power each inner-most integer of the (implicit) input "..." # Push the recursive string explained below © # Store it in variable `®` .V # Evaluate and execute it as 05AB1E code # (after which the result is output implicitly) D # Duplicate the current list di # If it's a single integer: # (do nothing, simply keep it as is) ë # Else (it's a list instead): δ # Map over each inner item: ® .V # Do a recursive call ā # Then push a list in the range [1,length] (without popping) Ø # Map index each to the 0-based prime: [3,5,7,...] s # Swap the two lists on the stack m # Take the primes to the power of the values P # Take the product of this list ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 67 bytes ``` ≔X²Aθ⊞υθFυFΦι⁺⟦⟧κ⊞υκF⮌υ«≔¹η≔²ζFι«≦⊕ζW¬⬤…²ζ﹪ζμ≦⊕ζ≧×Xζ⊟⁺⟦⁰⟧κη»⊞ιη»I⊟θ ``` [Try it online!](https://tio.run/##fZBNa8MwDIbPya/QUQYPtl57KoNBDy0h9FZ6MKkXmzp26o8WMvrbMzt2dpzBWELvI@l1J5jtDFPzvHNO9hob8@QWNxT2egweCaFwJ9u6CU5gyPG3sYCBwPJ@SeUjICk0Kjg8XyjcCCGwArcVaPmDW8cjSOCnrsq4DwoiKtY0zp1SuhByEVYHNpbqXneWD1x7fi266imk4oBH43GnFLZM9zx3oXAw16AMThQGklb6t9FfsZW98HiSA3fR0/IbUwpGzAbfi8Oy@KuuFqsy56@6sVJ7/GTOY4LuUbqd53M8icz3Mr891C8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔X²Aθ ``` Vectorised raise `2` to the power of the input. ``` ⊞υθFυFΦι⁺⟦⟧κ⊞υκF⮌υ« ``` Extract all of the sublists and loop over them in reverse. ``` ≔¹η≔²ζ ``` Start with a product of `1` and a last prime of `2`. ``` Fι« ``` Loop over the elements of the list. ``` ≦⊕ζW¬⬤…²ζ﹪ζμ≦⊕ζ ``` Get the next prime number by trial division (1 byte shorter than Wilson's theorem). ``` ≧×Xζ⊟⁺⟦⁰⟧κη» ``` Multiply the product by the prime power of the next list element (but if that's a list, then use its last element, as that's where we put the value on a previous loop iteration). ``` ⊞ιη ``` Save the resulting value to the sublist. ``` »I⊟θ ``` Output the resulting value of the original list. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 23 bytes ``` L?sIb^2b*F^V.fP_Zlb3yMb ``` [Try it online!](https://tio.run/##K6gsyfj/38e@2DMpzihJyy0uTC8tID4qJ8m40jfpf@X/6Ohog1gdBQgGAA "Pyth – Try It Online") Defines an encoding function `y(b)`. ### Explanation ``` L # define y(b) ?sIb # if b is invariant under s: (sums for list, int for int) ^2b # 2 ^ b # else: yMb # apply y to each element of b .fP_Zlb3 # generate a list of len(b) primes starting with 3 ^V # vectorized exponentiation *F # fold over multiplication ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 37 bytes ``` 1##&@@(i=1;Prime@++i^#&/@#)&//@(2^#)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b731BZWc3BQSPT1tA6oCgzN9VBWzszTllN30FZU01f30HDKA7I@A@UyiuJVta1S3NQjlWrC05OzKur5qo2qNXhqgaSIMpQx0jHGMLXMawFIS6gAh0ohKgwBAtXVwNJIAYxDXQg@iEmgQwEI67a/wA "Wolfram Language (Mathematica) – Try It Online") ``` (2^#) numbers: x -> 2^x //@ lists: 1##&@@( /@#) product of i=1;Prime@++i^#& prime(n+1)^x_n ``` [Answer] # [J](http://jsoftware.com/), 32 30 bytes ``` */@(p:@#\^$:&>)`(2^x:)@.(0=L.) ``` [Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tfQdNAqsHJRj4lSs1Ow0EzSM4iqsNB30NAxsffQ0/2typSZn5CukKdjYGMCYhtZG1sYwjoaBtaGmtSHXfwA "J – Try It Online") *-2 thanks to att* [Answer] # [Factor](https://factorcode.org/) + `math.primes.lists math.unicode`, 83 bytes ``` : g ( a -- n ) dup real? [ 2^ ] [ [ lprimes cdr lnth swap g ^ ] map-index Π ] if ; ``` [Try it online!](https://tio.run/##TY49DsIwDIV3TvFGGFoVRhgYEQsLYqpAilIXIlI3JKkAVdyFE3GlkjYgkCX/fO/Zcimkr2232643qznOZJk0KuFPcHRpiCW5YUwbVrIuCMaS93djFfsolA1Lr2r@@IJSkUu1ct4h5gXWmzmOtS67UDCGQJKAMUHRGFgSeokcswP2oeTQ8QRkYaG5/@QqTNjr9UqYRHFBN7yeYVQlFl2L6RCP4ElHLdqhj/nLMvQ8G0j254ws@9HuDQ "Factor – Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 147 bytes ``` $f={$r,$p=1,2 $args|%{do{$p++;for($u,$k=1,0;++$u-$p){$k+=!($p%$u)}}while($k)$r=$r*($b=[bigint])::Pow($p,(&($f,{$b::Pow(2,$_)})[$_-is[int]]@_))} $r} ``` [Try it online!](https://tio.run/##ZVJbb9owFH7nV3jotIqHI/kSO3GrSJnY9rCXVeveEEJATWFQnDnJ2JTmtzOHFAbDShzpfOe7HMe53RlXLM1mE86tM/s9LNIaHIE8ZYT3YOqei9eb@snWkA8G9wvrAqgIrD1K7wcDqELIcQ3rQfougPwGKtw0u@VqYwJYY3ApuPcBzNLRbPW82pZjfHf3YHe@kwS3ASxIDbOuwglMcINHMAlXxahtHWcTjJseuGafBT3kF0FZkAUUE9QXfXxWaneK2zqPLwBGECdIHBg84jGlUnF50eKZBDHcvX0mOVVKaaV5IoT2FB5rzanWCZNRzKTgKr4U8PR/T6dBmfw/BjsaMHoVoAXa/RAziSIhpBbXLmdzvvmoSHGmuRQyolRoej1bd1z0ROGJb1cqETKWMYuo0gmVCY2jKBZaRjLRTFHNNOORiJUfVwnOpT@DWHKVeCOvj9Er@mzdp@l8GX6d/TDzEtUHU39Z3PQPQWB@575qnlCKYNJBZ6XjXfA/fuoKf1GOWBcdnCmqTekbb2GBsoPmARg9PA6rorQvnek461zb9VjN56YoWr@TUWh@HrVOfR9aMf9N37L6SYZ2@8u48rsNvxR2i8KhfcldqxV@NHm5RIye2N@6YC37TLfpNfu/ "PowerShell Core – Try It Online") Fun challenge! Recursive function that expects the input list using splatting and returns a `[bigint]` Please ignore the inconsistent output of the array in the tests result as PowerShell has a tendency to flatten them sometime. ## Explanation This part updates `$p` to become the next prime after `$p` ``` do{$p++;for($u,$k=1,0;++$u-$p){$k+=!($p%$u)}}while($k) ``` This part checks whether the current list item `$_` is a number or not If it is a number, we take its power of two, otherwise, we do a recursive call. ``` $r=$r*($b=[bigint])::Pow($p,(&($f,{$b::Pow(2,$_)})[$_-is[int]]@_))} ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 71 bytes Of course, answering your own challenge is a bit ridiculous, but it is rather a supplement to not break the main post. Thanks @PaŭloEbermann for the idea! It seems we can account for *the empty lists*, naively but correctly, using the next encoding: 1. If \$x\$ is non-negative integer, \$G(x) = 2^{x+1}\$ 2. If \$x\$ is an empty list, `[ ]`, \$G(x) = 2^0 = 1\$ 3. If \$x\$ is a list, \$[n\_0, n\_1, n\_2, n\_3, …], G(x) = 3^{G(n\_0)} \cdot 5^{G(n\_1)} \cdot 7^{G(n\_2)} \cdot 11^{G(n\_3)} \cdot...\$ Of course, this is a purely intuitive idea without proof. But I do not see contradictions at the moment. So here is Mathematica program that encodes *any array-like structure* (with possible empty lists) with a unique positive integer. ``` Switch[#,{},1,{__},Times@@(Prime@Range[2,Length@#+1]^#0/@#),_,2^(#+1)]& ``` Some related test cases: ``` [] → 1 [[]] → 3 [[], 1, []] → 13125 [[], [0, []], 1] → 204721573027200065553188323974609375 ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7g8syQ5I1pZp7pWx1CnOj6@VickMze12MFBI6AIyHAISsxLT4020vFJzUsvyXBQ1jaMjVM20HdQ1tSJ1zGK0wAKaMaq/QcqzitxSHOoBpqjUG0AxLVAhmHtfwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 51 bytes ``` f(x)=if(x'===0,2^x,prod(i=1,#x,prime(i+1)^f(x[i]))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN43TNCo0bTOBpLqtra2BjlFchU5BUX6KRqatoY4yiJ2Zm6qRqW2oGQdUE50Zq6mpCdWaklhQkFOpkaiga6cAVJZXAmQqgThKCmkaiZqaOgrR0QY6UBgL5BnqKIAQiBkNJg1jQaQBWCGICVYFYkOYQDGoXTDnAgA) ]
[Question] [ Produce a program A such that running it in language A produces Program B, and running program A in language B produces program C. Program B, when run in language B produces Program A, and running program B in language A produces program C. Program C, when run in language *A* or language *B*, prints "Wrong language!". ``` Program | Language | Result --------|----------|---------- A | A | Program B B | B | Program A A | B | Program C B | A | Program C C | A | "Wrong language!" C | B | "Wrong language!" ``` Your answer should use this template: --- # Language A/Language B, {a bytes} + {b bytes} = {total bytes} bytes Program A: ``` a code ``` Program B: ``` b code ``` Program C: ``` c code ``` --- Source: ``` # Language A/Language B, <a bytes> + <b bytes> = <total bytes> bytes Program A: a code Program B: b code Program C: c code ``` --- * None of these programs should take input. * Different versions of the same language do count as different languages. (although this is discouraged because it leads to boring solutions) * Languages A and B must be distinct. * You must not read your own source code from a file. Programs may not be empty * Standard loopholes apply. # Hints * C++ and [Python/Bash/other `#` commented languages] are good combos because you can define macros that one language can ignore This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the smallest sum of the byte counts Program A and B wins. [Answer] # JavaScript (ES6) / Python 3, 264 + 258 = 522 bytes Program A: ``` a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''";b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))";c="1//2;alert=print\nalert('Wrong language!')";1//2;print(c);''' console.log(b,...[a,b,c].map(uneval))//''' ``` Program B: ``` a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''";b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))";c="1//2;alert=print\nalert('Wrong language!')";1//2;''' print=_=>console.log(c)//''' print(a%(a,b,c)) ``` Program C: ``` 1//2;alert=print alert('Wrong language!') ``` Probably golfable... ## JavaScript explanation Program A: ``` // Set a, b, and c to these strings: a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''"; b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))"; c="1//2;alert=print\nalert('Wrong language!')"; // Ignore this line: 1//2;print(c);''' // Print the Python program (b), replacing the "%s"s with the raw forms of a, b, and c: console.log(b,...[a,b,c].map(uneval))//''' ``` Program B: ``` // Set a, b, and c to these strings: a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''"; b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))"; c="1//2;alert=print\nalert('Wrong language!')"; // Ignore this line: 1//2;''' // Define a function `print` which prints `c` (the "Wrong language!" program): print=_=>console.log(c)//''' // Call `print`, ignoring the argument (which is NaN): print(a%(a,b,c)) ``` Program C: ``` // Ignore this line: 1//2;alert=print // Alert "Wrong language!": alert('Wrong language!') ``` ## Python explanation Program A: ``` # Set a, b, and c to these strings: a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''"; b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))"; c="1//2;alert=print\nalert('Wrong language!')"; # Print `c` (the "Wrong language!" program): 1//2;print(c); # Ignore this part: ''' console.log(b,...[a,b,c].map(uneval))//''' ``` Program B: ``` # Set a, b, and c to these strings: a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''"; b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))"; c="1//2;alert=print\nalert('Wrong language!')"; # Ignore this part: 1//2;''' print=_=>console.log(c)//''' # Print the JS program (a), replacing the "%r"s with the raw forms of a, b, and c: print(a%(a,b,c)) ``` Program C: ``` # Set `alert` to the function `print`: 1//2;alert=print # Call this function on "Wrong language!": alert('Wrong language!') ``` [Answer] # [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/)/[><>](https://esolangs.org/wiki/Fish), 123 + 123 = ~~266 250~~ 246 bytes Program A: ``` "81!#.#vp00g>:#,_j+4<.=1l5v!o#!g00 g00<<<<<>0!#[f8+1!#.48*k'Wrong language!<o>[f@,kep.#!0a'00g!#o# \!gff+k,@,k*8ba$$ #o#!a" ``` [Try it in Befunge-98!](https://tio.run/##HYxRCoMwEET/e4qsKwgmhggW0mJDb9EPCyVCstBIIgWFnj6NHRgY3jAzO79Fct1Fd@v3H3OudA8ocV@VInNF8XrzYZS3fjnvkBBIqVPxeMgowMlrfgwG3Ybm8UmR2GIjbZYcjMlM/i6CWyWCsk15BEzInkDe8yBK1erZ1jUrFGyV8w8), [Try it in ><>!](https://tio.run/##FYzBCoMwEETv/YqsKwgmhBUshBJD/6IHCyUFs20jRir199M4MJc3vAnv7ZVzZTpAjftKxO6C6vGRvdVDN593SAhMdCq1RxwBjsHIQ@hNG5vbNy0sZr/wz/MENrkxXFWcVo1AvimPgAnFHTgEGVWZWvP0dS0KBV/l/Ac) Program B: ``` "00g!#o!v5l1=.<4+j_,#:>g00pv#.#!18 g00<<<<<>0!#[f8+1!#.48*k'Wrong language!<o>[f@,kep.#!0a'00g!#o# \!gff+k,@,k*8ba$$ #o#!a" ``` [Try it in ><>!](https://tio.run/##JYzBCsIwEETvfkW2Wyg0IWygQpAY/AsPFSRCs2pKUxT7@zHinIY3vImP972UhogBM2z72Ry1G@TzqvDgmWjdUCMYu6vd/eIJcIxWGkA92D5151deWMxh4U/gCVz2YzypNK3Vo9D9n1FcgGOUSdWpt7fQtqJSCE0pXw), [Try it in Befunge-98!](https://tio.run/##JYxBCsIwFET3niK/v1Bo0pBAhSg1eAsXFSSF5IMtaRBa8PQx6qwe85iZfNgi@e5kuvT@Yc6VUgS4wn5c9EUOPX8@BJ4tKZV2lAjaHAoP31gFOAbDNaDsTTs3t9caiS0u0ubIw7DaMVzF7FPZKdf8n5HdgULgsyiqNZOra1ZacFXOHw) Program C: ``` "a0!#.pek,@f[>o<!egaugnal gnorW ``` [Try it in Befunge-98!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XSjRQVNYrSM3WcUiLtsu3UUxNTyxNz0vMUUjPyy8K//8fAA "Befunge-98 (PyFunge) – Try It Online") [Try it in ><>!](https://tio.run/##S8sszvj/XynRQFFZryA1W8chLdou30YxNT2xND0vMUchPS@/KPz/fwA "><> – Try It Online") ## How it Works: The second line in both programs is identical and serves the same function for both language. When entered leftwards from the `<<<<`, it prints the entire second line. When entering to the right of those, print program C. When the first line is run in the wrong language, it enters through the program C producing section. Otherwise, it prints the top line backwards with the `"` at the front and enters the second line producing section. ### First line Program A: ``` "81!#.#vp00g>:#,_j+4<.=1l5v!o#!g00 ><>: " Wrapping string literal over the first line 81!#. Jumps the pointer to the Program C producer Befunge-98: " Wrapping string literal 81!#. Pushes 8,0 (! inverts number, # skips over .) #v Skip over the exit p00g Pops the excess 8,0 and space and gets the " from 0,0 >:#,_ Classic print until stack is empty v j+4< Skips back to the exit and goes to the second line ``` Program B: ``` "00g!#o!v5l1=.<4+j_,#:>g00pv#.#!18 ><>: " Wrapping string literal 00g!# Gets the " from 0,0 o!v5l1=. Print until the stack is empty and jump to the second line Befunge-98: " Wrapping string literal 00g Gets the " from 0,0 !#o!v Skip the instruction o and go to Program C producer ``` ### Second Line: ``` g00<<<<<>0!#[f8+1!#.48*k'Wrong language!<o>[f@,kep.#!0a'00g!#o# $$00gff+k,@,k*9aa$$ #o#!a" ><>: Second line producer g00<<<<< Get the " from cell 0,0 ...... " Wrapping string literal over the stack #o#!a Print newline and the stack and exit Program C producer: >0!#[ Clear stack f8+1!#. Jump to cell 22,1 .....'...' Push program C to the stack 00g Get " from cell 0,0 !#o# Print stack until empty Befunge-98: Second line producer g00<<<<< Get the " from cell 0,0 ...... " Wrapping string literal #o#!a Skip over instruction o $$ Pop the excess characters 90a Push a newline and 90 @,k Execute , instruction (print) 90+1 times, printing second line Program C producer: >0!#[ Push 1 and skip [ f8+1!#. Push 22, 0 and skip . 48*k'...' Execute ' instruction 32 times, pushing program C ...'00g!#o# Push 0 and skip the instruction o \! Convert excess values to two 0s g Get " from cell 0,0 ff+ Push 30 k, Execute , 30+1 times, printing program C @ Exit program ``` ### Program C ``` "a0!#.pek,@f[>o<!egaugnal gnorW ><>: " Wrapping string literal a0!#. Jump to cell 10,0 f[ Create a new stack with only the top 15 elements >o< Print stack Befunge-98: " Wrapping string literal a0!#. Push 10,1 p Pop 10,1 and excess space ek,@ Push 14 and execute , 14+1 times and exit the program ``` [Answer] # Python 3 + JavaScript (Rhino), 171 + 171 = 342 bytes Program A (outputs program B in Python 3, program C in JavaScript; note trailing newline): ``` s="'";d='"';r=['print("s="+d+s+d+";d="+s+d+s+";r=["+s+r[1]+s+","+s+r[0]+s+"];eval(r[([11]+[0])[1]])")','print("print("+d+"Wrong language!"+d+")")'];eval(r[([11]+[0])[1]]) ``` Program B (outputs program A in JavaScript, program C in Python; note trailing newline): ``` s="'";d='"';r=['print("print("+d+"Wrong language!"+d+")")','print("s="+d+s+d+";d="+s+d+s+";r=["+s+r[1]+s+","+s+r[0]+s+"];eval(r[([11]+[0])[1]])")'];eval(r[([11]+[0])[1]]) ``` Program C (outputs "Wrong language!" in either language; also has a trailing newline, which doesn't count in the score): ``` print("Wrong language!") ``` Note that I'm using an unusual dialect of JavaScript here. People normally use browser implementations, but those have issues with output, doing it in a weird way (using `alert`). I'm using the Ubuntu package `rhino` which is an "offline" JavaScript implementation with a different set of libraries implemented to a typical browser (it's intended as an embeddable scripting language); this is notable in that it provides a `print` statement in the same style as, for example, Python 3. This is a "true polyglot" in the sense that both languages are running the same calculations, in the same order, giving them the same meaning. They both have the same AST (and it's fairly trivial to create a Python 3 + JavaScript polyglot quine via reducing this program). There's no code that's specific to one language, which helps me bring the length way down. Incidentally, you have to use Python 3 so that you can use semicolons to separate statements (if you used newlines you'd have to escape the newlines). The program starts by defining strings `s` and `d` which hold a single quote and double quote respectively. This makes it possible to output quotes without having to mention them later in the source code, avoiding issues with escaping (which frequently seem to be a problem with quines; the main reason I answer so many quine problems in Underload is that its strings nest). The heart of the program is the array `r` which holds the main body of the two programs used by the challenge; one of the programs (the one that comes first in program A, and second in program B) is an almost-quine that simply outputs the original program via concatenating together pieces (taken mostly from `r` itself, with a few string literals), and the other prints program C. In order to make the program not a true quine (which would make it impossible to detect that we were running in the wrong language), the elements of `r` are printed in reverse order; `r[0]` in program A is `r[1]` in program B, and vice versa. Finally, all that's necessary is to `eval`uate the correct element of `r`. This is accomplished using the expression `([11]+[0])[1]` that produces a different value in Python 3 and in JavaScript. Both languages parse it identically, but they have different ideas of what addition does to lists: * When Python 3 adds `[11]` to `[0]`, it gets `[11, 0]` (concatenating the lists), and then taking the second element of the list (`[1]`) gives us the integer 0. * When JavaScript adds `[11]` to `[0]`, it gets `"110"` (concatenating the *string representations of* the lists), and then taking the second character of the string (`[1]`) gives us the string `"1"`, which JavaScript is quite happy to use as an index into a list. Therefore, Python 3 runs the first element of `r` in both programs (producing the almost-a-quine when running program A, and printing program C when running program B); JavaScript runs the second element, and thus treats program A and program B the opposite way around. Incidentally, if you run program A in Ruby, it will print program B except without a trailing newline. If you run program B in Ruby, it will print program C except without a trailing newline. In other words, this solution very nearly works with a different set of languages, swapping Python 3 for Ruby (the only reason I don't just delete the newline from program B to get a score of 341 is that the newline inconsistency in program C would disqualify the submission). (I was working on a "true polyglot" like this for a different reason, which I've now posted as a challenge, and realised that the techniques could be adapted to this one as well.) [Answer] # C/Python, 733 bytes + 733 bytes = 1466 bytes Program A: ``` #define int char* int a1="#define print(X) main(){printf(d,13,13,34,a1,34,13,13,34,a2,34,13,13,34,b1,34,13,13,34,b2,34,13,13,34,c,34,13,13,34,d,34,13,b1,13,b2);}"; int a2="print(c%(13,34,34))"; int b1="#define print(X) main(){printf(c,13,34,34);};"; int b2="print(d%(13,13,34,a1,34,13,13,34,a2,34,13,13,34,b1,34,13,13,34,b2,34,13,13,34,c,34,13,13,34,d,34,13,a1,13,a2))"; int c="#define print(a) main(){puts(a);}%cprint(%cWrong language!%c)"; int d="#define int char*%cint%ca1=%c%s%c;%cint%ca2=%c%s%c;%cint%cb1=%c%s%c;%cint%cb2=%c%s%c;%cint%cc=%c%s%c;%cint%cd=%c%s%c;%c%s%c%s"; #define print(X) main(){printf(d,13,13,34,a1,34,13,13,34,a2,34,13,13,34,b1,34,13,13,34,b2,34,13,13,34,c,34,13,13,34,d,34,13,b1,13,b2);} print(c%(13,34,34)) ``` Program B: ``` #define int char* int a1="#define print(X) main(){printf(d,13,13,34,a1,34,13,13,34,a2,34,13,13,34,b1,34,13,13,34,b2,34,13,13,34,c,34,13,13,34,d,34,13,b1,13,b2);}"; int a2="print(c%(13,34,34))"; int b1="#define print(X) main(){printf(c,13,34,34);};"; int b2="print(d%(13,13,34,a1,34,13,13,34,a2,34,13,13,34,b1,34,13,13,34,b2,34,13,13,34,c,34,13,13,34,d,34,13,a1,13,a2))"; int c="#define print(a) main(){puts(a);}%cprint(%cWrong language!%c)"; int d="#define int char*%cint%ca1=%c%s%c;%cint%ca2=%c%s%c;%cint%cb1=%c%s%c;%cint%cb2=%c%s%c;%cint%cc=%c%s%c;%cint%cd=%c%s%c;%c%s%c%s"; #define print(X) main(){printf(c,13,34,34);}; print(d%(13,13,34,a1,34,13,13,34,a2,34,13,13,34,b1,34,13,13,34,b2,34,13,13,34,c,34,13,13,34,d,34,13,a1,13,a2)) ``` Program C: ``` #define print(a) main(){puts(a);} print("Wrong language!") ``` I used your hint of using C/C++ with Python. Not very concise, but still qualifying I suppose. [Answer] # Python 2 / Retina, 550 + 645 = ~~1373~~ ~~1254~~ ~~1221~~ 1195 bytes I'm not quite sure if the `unichr` and `replace` parts can be golfed more. I tried using Python 3, but a lot is lost by having to add parentheses and handle them. I tried setting `R=unicode.replace` and using that, but the output gets messed up. Note that Retina has a trailing newline in its output by default, and this is *not* included in the programs. If someone says I need to remove it, that can be done trivially. Also, the Python code works in repl.it, but is not guaranteed to work on Ideone.com. Also note that leading and trailing newlines are significant in the code below. **Program A (Python 2): ~~638~~ ~~587~~ ~~566~~ 550 bytes (UTF-8)** [**Python 2**](https://repl.it/Ekg5/3), [**Retina**](https://tio.run/nexus/retina#code=VT11bmljaHI7cz1VKDM5KSozO189dScnJ1xuI1U9dW5pY2hyO3M9VSgzOSkqMztfPXUlcy5yZXBsYWNlKFUoOSksVSg5NikpO3ByaW50IF8lJShzK18rcykucmVwbGFjZShVKDEwKSxVKDkyKSsnbicpLnJlcGxhY2UoVSg5NiksVSg5KSkucmVwbGFjZShVKDE3OCksVSgxNzkpKS5yZXBsYWNlKFUoMTgzKSxVKDE4NCkpLnJlcGxhY2UoVSgxODIpLFUoMTgzKSkjfMK2I8K3cHJpbnQiV3JvbmcgbGFuZ3VhZ2UhIsK3Iz8uKnR8IsK3wrYjezJ9fF4uwrZcbiMxCSNcblxuI1QJwrItwrkJX28JW17CuV1cbm49Y2hyKDEwKTtwcmludCBuK24uam9pbihbJ3ByaW50Ildyb25nIGxhbmd1YWdlISInLCcjPy4qdHwiJ10pK25cbicnJy5yZXBsYWNlKFUoOSksVSg5NikpO3ByaW50IF8lKHMrXytzKS5yZXBsYWNlKFUoMTApLFUoOTIpKyduJykucmVwbGFjZShVKDk2KSxVKDkpKS5yZXBsYWNlKFUoMTc4KSxVKDE3OSkpLnJlcGxhY2UoVSgxODMpLFUoMTg0KSkucmVwbGFjZShVKDE4MiksVSgxODMpKSN8CiPCtnByaW50Ildyb25nIGxhbmd1YWdlISLCtiM_Lip0fCLCtgojezJ9fF4uCg&input=) ``` U=unichr;s=U(39)*3;_=u'''\n#U=unichr;s=U(39)*3;_=u%s.replace(U(9),U(96));print _%%(s+_+s).replace(U(10),U(92)+'n').replace(U(96),U(9)).replace(U(178),U(179)).replace(U(183),U(184)).replace(U(182),U(183))#|¶#·print"Wrong language!"·#?.*t|"·¶#{2}|^.¶\n#1 #\n\n#T ²-¹ _o [^¹]\nn=chr(10);print n+n.join(['print"Wrong language!"','#?.*t|"'])+n\n'''.replace(U(9),U(96));print _%(s+_+s).replace(U(10),U(92)+'n').replace(U(96),U(9)).replace(U(178),U(179)).replace(U(183),U(184)).replace(U(182),U(183))#| #¶print"Wrong language!"¶#?.*t|"¶ #{2}|^. ``` **Program B (Retina): ~~735~~ ~~667~~ ~~655~~ 645 bytes (ISO 8859-1)** [**Retina**](https://tio.run/nexus/retina#code=CiNVPXVuaWNocjtzPVUoMzkpKjM7Xz11JycnXG4jVT11bmljaHI7cz1VKDM5KSozO189dSVzLnJlcGxhY2UoVSg5KSxVKDk2KSk7cHJpbnQgXyUlKHMrXytzKS5yZXBsYWNlKFUoMTApLFUoOTIpKyduJykucmVwbGFjZShVKDk2KSxVKDkpKS5yZXBsYWNlKFUoMTc4KSxVKDE3OSkpLnJlcGxhY2UoVSgxODMpLFUoMTg0KSkucmVwbGFjZShVKDE4MiksVSgxODMpKSN8wrcjwrhwcmludCJXcm9uZyBsYW5ndWFnZSEiwrgjPy4qdHwiwrjCtyN7Mn18Xi7Ct1xuIzEJI1xuXG4jVAnCsy3CuQlfbwlbXsK5XVxubj1jaHIoMTApO3ByaW50IG4rbi5qb2luKFsncHJpbnQiV3JvbmcgbGFuZ3VhZ2UhIicsJyM_Lip0fCInXSkrblxuJycnLnJlcGxhY2UoVSg5KSxVKDk2KSk7cHJpbnQgXyUocytfK3MpLnJlcGxhY2UoVSgxMCksVSg5MikrJ24nKS5yZXBsYWNlKFUoOTYpLFUoOSkpLnJlcGxhY2UoVSgxNzgpLFUoMTc5KSkucmVwbGFjZShVKDE4MyksVSgxODQpKS5yZXBsYWNlKFUoMTgyKSxVKDE4MykpI3zCtiPCt3ByaW50Ildyb25nIGxhbmd1YWdlISLCtyM_Lip0fCLCt8K2I3syfXxeLsK2CiMxYCMKCiNUYMKyLcK5YF9vYFtewrldCm49Y2hyKDEwKTtwcmludCBuK24uam9pbihbJ3ByaW50Ildyb25nIGxhbmd1YWdlISInLCcjPy4qdHwiJ10pK24K&input=), [**Python 2**](https://repl.it/EkhH/2) ``` #U=unichr;s=U(39)*3;_=u'''\n#U=unichr;s=U(39)*3;_=u%s.replace(U(9),U(96));print _%%(s+_+s).replace(U(10),U(92)+'n').replace(U(96),U(9)).replace(U(178),U(179)).replace(U(183),U(184)).replace(U(182),U(183))#|·#¸print"Wrong language!"¸#?.*t|"¸·#{2}|^.·\n#1 #\n\n#T ³-¹ _o [^¹]\nn=chr(10);print n+n.join(['print"Wrong language!"','#?.*t|"'])+n\n'''.replace(U(9),U(96));print _%(s+_+s).replace(U(10),U(92)+'n').replace(U(96),U(9)).replace(U(178),U(179)).replace(U(183),U(184)).replace(U(182),U(183))#|¶#·print"Wrong language!"·#?.*t|"·¶#{2}|^.¶ #1`# #T`²-¹`_o`[^¹] n=chr(10);print n+n.join(['print"Wrong language!"','#?.*t|"'])+n ``` **Program C:** [**Python 2**](https://repl.it/Ekgo/2), [**Retina**](https://tio.run/nexus/retina#code=CnByaW50Ildyb25nIGxhbmd1YWdlISIKIz8uKnR8Igo&input=) This can actually be made shorter using `#!`W.*!` instead of the last two lines, but this makes A and B longer, because having ``` in a line where there wasn't one means I need to handle it differently (because the first backtick in a line in Retina is a configuration delimiter). ``` print"Wrong language!" #?.*t|" ``` --- --- ## Explanation: **Program C:** ``` # Retina: replace nothing with the Python code string print"Wrong language!" # >> code is executed if run in Python #?.*t|" # Comment w/ '?' for Retina to skip, then replace up to the 't', # as well as any quotation marks, with nothing ``` I wrote Program C first during my first attempt and kept it mostly the same. In Python, it prints the string and ignores the comment. In Retina, it replaces nothing with `print"Wrong language!"` and then removes the parts around `Wrong language!`. To better understand the complex programs, let's look at simplified versions: **Program A (simplified):** ``` print"\n#PYTHON\n#1`#\n\n#T`²-¹`_o`[^¹]\nn=chr(10);print n+n.join(['print"Wrong language!"','#?.*t|"'])+n\n"#| #¶print"Wrong language!"¶#?.*t|"¶ #{2}|^. ``` When I started over from scratch, I used the `PYTHON` bit as a placeholder for the code that should print Program A. This simpler version made it easier to explain how both Program B and Program C would be printed. The `print` and everything inside is what prints Program B, but first, lets see how Program C is printed, because that's simple. After the `print"..."` is `#|`. This trick saved LOADS of difficulty that I experienced in my first attempt. This allows Retina to replace nothing with the 2nd line, which will be Program C, except there's a `#` in front. The last 2 lines remove that first `#`. I used `#{2}` to prevent the stage from removing *all* occurrences of `#`. I cannot use `#1`#` like I used in Program B, because it causes problems to have that backtick in the first line of Program A. Which brings me to my next task, printing Program B. You may have noticed another difference from the actual code. There aren't backticks in the actual code, since I replaced them with tabs. I had to substitute a character, because any backtick would make the earlier code a configuration string in Retina, causing the syntax to be invalid. I chose tabs because they're visible and the code point is a single digit (`9`). The code prints Program B as shown in the simplified version below. **Program B:** ``` #PYTHON #1`# #T`²-¹`_o`[^¹] n=chr(10);print n+n.join(['print"Wrong language!"','#?.*t|"'])+n ``` The first two lines will replace nothing with the Python code, but with a `#` in front and some characters slightly different. This part is omitted for clarity. The next stage removes that first `#`. Then, I use a Transliteration (T) stage `#T`²-¹`_o`[^¹]` to undo some of the `replace` operations seen in the complete Program A. Using this stage is a way to output a literal pilcrow `¶` in Retina, which might otherwise be impossible.¹ It replaces `·` with `¶`, and `³` with `²`. Occurrences of `¹` will stay the same due to them being ignored with `[^¹]`. **Program A:** Newlines and tabs have been added for readability. ``` U=unichr;s=U(39)*3; _=u''' \n#U=unichr;s=U(39)*3; _=u%s.replace(U(9),U(96)); print _%%(s+_+s) .replace(U(10),U(92)+'n').replace(U(96),U(9)).replace(U(178),U(179)) .replace(U(183),U(184)).replace(U(182),U(183))#| ¶#·print"Wrong language!"·#?.*t|"· ¶#{2}|^. ¶ \n#1 #\n\n#T ²-¹ _o [^¹]\nn=chr(10);print n+n.join(['print"Wrong language!"','#?.*t|"'])+n\n''' .replace(U(9),U(96)); print _%(s+_+s) .replace(U(10),U(92)+'n').replace(U(96),U(9)).replace(U(178),U(179)) .replace(U(183),U(184)).replace(U(182),U(183))#| #¶print"Wrong language!"¶#?.*t|"¶ #{2}|^. ``` This follows the general structure of the following Python quine: ``` _='_=%r;print _%%_';print _%_ ``` When you add things before or after, you have to put them in the string, too. ``` U=unichr;_='U=unichr;_=%r;print(_%%_).replace('','')';print(_%_).replace('','') ``` I wanted to use a triple-quoted string to make it easy to include quotation marks (avoiding the use of backslashes). `s=U(39)*3;` is the string `'''`. I also used `%s` instead of `%r`, in order to avoid some problems with newlines or other characters being escaped with backslashes. ``` U=unichr;s=U(39)*3;_='''U=unichr;s=U(39)*3;_=%s;print(s+_%%_+s).replace('','')''';print(s+_%_+s).replace('','') ``` So now, the replacements. The first replacement `.replace(U(9),U(96));` is there to replace tabs with the backticks that we see in Program B. This replacement is done *before* string formatting, because the tabs need to remain tabs in Program A. The other replacements are simply to avoid using certain characters in the 2nd line of Program B: ``` .replace(U(10),U(92)+'n') # Replace newlines with a backslash and 'n', for B to print A. .replace(U(96),U(9)) # Replace backticks with tabs for the first part of B. .replace(U(178),U(179)) # Replace '²' with '³', which will be undone with B's T stage .replace(U(183),U(184)) # Replace '·' with '¸', which will be undone with B's T stage .replace(U(182),U(183)) # Replace '¶' with '·', which will be undone with B's T stage ``` These last three replacements anticipate the Transliteration stage in Program B, in order to prevent those characters from being either removed or transliterated when they shouldn't be. The only other part of the code is the code from Program B that is essentially copied character-for-character, except for the changes due to the replacements. --- ¹ *Thanks to Martin for his tip on how to output a literal `¶` in Retina. It made everything so much easier.* [Answer] # Befunge/Python, ~~381+485~~ ~~259+345~~ 229+304 = 533 bytes Program A: [Try in Befunge](http://befunge.tryitonline.net/#code=Iz4yMWc6OjM1KjoqOjoiOiIlXD46IyQiOiIlI1wgXCMlIjoiLyM6OiQjLWcjMVxfIytcIzU6IzVfdgojdiI1MGciZzEyIic8OiM-ISMsX0A8J3RuaXJwImcxMiI-OiMsX0AiKzU1InByaW50ICI6OmcxMiQ8CiM-MjFnIldyb25nIGxhbmd1YWdlISIyMWciZzA1IjIxZyJbKzUrNTpdIjIxZyIrNTU-IyI-OiMsX0AKcHJpbnQnJydwcmludCc8QF8sIyE-Izo8JyJXcm9uZyBsYW5ndWFnZSEiWys1KzU6XScnJw&input=) | [Try in Python](http://python2.tryitonline.net/#code=Iz4yMWc6OjM1KjoqOjoiOiIlXD46IyQiOiIlI1wgXCMlIjoiLyM6OiQjLWcjMVxfIytcIzU6IzVfdgojdiI1MGciZzEyIic8OiM-ISMsX0A8J3RuaXJwImcxMiI-OiMsX0AiKzU1InByaW50ICI6OmcxMiQ8CiM-MjFnIldyb25nIGxhbmd1YWdlISIyMWciZzA1IjIxZyJbKzUrNTpdIjIxZyIrNTU-IyI-OiMsX0AKcHJpbnQnJydwcmludCc8QF8sIyE-Izo8JyJXcm9uZyBsYW5ndWFnZSEiWys1KzU6XScnJw&input=) ``` #>21g::35*:*::":"%\>:#$":"%#\ \#%":"/#::$#-g#1\_#+\#5:#5_v #v"50g"g12"'<:#>!#,_@<'tnirp"g12">:#,_@"+55"print "::g12$< #>21g"Wrong language!"21g"g05"21g"[+5+5:]"21g"+55>#">:#,_@ print'''print'<@_,#!>#:<'"Wrong language!"[+5+5:]''' ``` Program B: [Try in Python](http://python2.tryitonline.net/#code=Iz41NSsiXTo1KzUrWyI1MGciIWVnYXVnbmFsIGdub3JXIjUwZyInPDojPiEjLF9APCd0bmlycCI-OiMsX0AKcHJpbnQgIiIiIz4yMWc6OjM1KjoqOjoiOiIlXD46IyQiOiIlI1wgXCMlIjoiLyM6OiQjLWcjMVxfIytcIzU6IzVfdgojdiI1MGciZzEyIic8OiM-ISMsX0A8J3RuaXJwImcxMiI-OiMsX0AiKzU1InByaW50ICI6OmcxMiQ8CiM-MjFnIldyb25nIGxhbmd1YWdlISIyMWciZzA1IjIxZyJbKzUrNTpdIjIxZyIrNTU-IyI-OiMsX0AKcHJpbnQnJydwcmludCc8QF8sIyE-Izo8JyJXcm9uZyBsYW5ndWFnZSEiWys1KzU6XScnJyIiIg&input=) | [Try in Befunge](http://befunge.tryitonline.net/#code=Iz41NSsiXTo1KzUrWyI1MGciIWVnYXVnbmFsIGdub3JXIjUwZyInPDojPiEjLF9APCd0bmlycCI-OiMsX0AKcHJpbnQgIiIiIz4yMWc6OjM1KjoqOjoiOiIlXD46IyQiOiIlI1wgXCMlIjoiLyM6OiQjLWcjMVxfIytcIzU6IzVfdgojdiI1MGciZzEyIic8OiM-ISMsX0A8J3RuaXJwImcxMiI-OiMsX0AiKzU1InByaW50ICI6OmcxMiQ8CiM-MjFnIldyb25nIGxhbmd1YWdlISIyMWciZzA1IjIxZyJbKzUrNTpdIjIxZyIrNTU-IyI-OiMsX0AKcHJpbnQnJydwcmludCc8QF8sIyE-Izo8JyJXcm9uZyBsYW5ndWFnZSEiWys1KzU6XScnJyIiIg&input=) ``` #>55+"]:5+5+["50g"!egaugnal gnorW"50g"'<:#>!#,_@<'tnirp">:#,_@ print """#>21g::35*:*::":"%\>:#$":"%#\ \#%":"/#::$#-g#1\_#+\#5:#5_v #v"50g"g12"'<:#>!#,_@<'tnirp"g12">:#,_@"+55"print "::g12$< #>21g"Wrong language!"21g"g05"21g"[+5+5:]"21g"+55>#">:#,_@ print'''print'<@_,#!>#:<'"Wrong language!"[+5+5:]'''""" ``` Program C: [Try in Befunge](http://befunge.tryitonline.net/#code=cHJpbnQnPEBfLCMhPiM6PCciV3JvbmcgbGFuZ3VhZ2UhIlsrNSs1Ol0&input=) | [Try in Python](http://python2.tryitonline.net/#code=cHJpbnQnPEBfLCMhPiM6PCciV3JvbmcgbGFuZ3VhZ2UhIlsrNSs1Ol0&input=) ``` print'<@_,#!>#:<'"Wrong language!"[+5+5:] ``` **Explanation** *Program C:* This relies on the fact that Befunge-93 ignores unsupported instructions, so while the `p` harmlessly write a zero at 0;0, the rest of the `print` is ignored up until the `<` instruction which reverse the direction. Then flowing from right to left, the `+5+5` pushes a 10 (linefeed) on to the stack followed by the message string, and then a standard output sequence is executed to write out the string. In Python it's just printing two string literals that are concatenated together, but the first one (containing the Befunge code) is sliced off by the array reference at the end (`[+5+5:]`). *Program B:* The first line is a fairly basic Befunge sequence to print out Program C. The only interesting thing is the way it generates quote characters using `50g` (i.e. reading the character from memory) which is more efficient than calculating the ASCII code. The `#>` (a bridge over the direction instruction) is essentially a nop that prevents the code being seen by Python since `#` is the Python comment character. The Python interpretation starts on line two and is simply printing a multiline string containing the source code of Program A. *Program A:* In Python the first three lines are again ignored because they start with `#`, while the last line simply prints out Program C. The Befunge code snakes back and forth across the first three lines, building up the source for Program B on the stack in reverse order. It starts with three quotes, then a sequence that makes a copy of Program A's source, and finally what is essentially a hard coded string with the opening `print """` and the first line of Befunge code. It's then just a matter of writing it out with a standard output sequence. Some points of contention: 1. I've been told that a quine using the `g` command is not considered a proper quine as far as this community is concerned. I'm not sure if that rule would apply to this challenge as well, but if so, this answer might not be considered a proper solution either. 2. While I've said that Befunge-93 ignores unsupported instructions, that's not technically defined in the specification, and you'll need to use the `-q` (quiet) command line option in the reference interpreter to avoid warnings in Program C. Most other interpreters will be fine, though, but some of the flakier ones could potentially crash. Also note that Befunge-98 reflects on unsupported instructions, so a 98 interpreter will just loop indefinitely. [Answer] # Perl/JavaScript, 176 bytes + 176 bytes = 352 bytes Don't think I can share 52 bytes off the underlying mechanism for the bounty, but I enjoyed building this. I think what I've produced meets the criteria... Program A: ``` $P=1;$_='$L=eval("printf=console.log;J=``;q=_=>_+J;2")||1;$P?printf(q`$P=%s;$_=%s%s%s;eval($_)`,$P=$P==$L?J?2:1:0,$q=J?h^O:atob("Jw"),$_,$q):printf("Wrong language!")';eval($_) ``` Program B: ``` $P=2;$_='$L=eval("printf=console.log;J=``;q=_=>_+J;2")||1;$P?printf(q`$P=%s;$_=%s%s%s;eval($_)`,$P=$P==$L?J?2:1:0,$q=J?h^O:atob("Jw"),$_,$q):printf("Wrong language!")';eval($_) ``` Program C: ``` $P=0;$_='$L=eval("printf=console.log;J=``;q=_=>_+J;2")||1;$P?printf(q`$P=%s;$_=%s%s%s;eval($_)`,$P=$P==$L?J?2:1:0,$q=J?h^O:atob("Jw"),$_,$q):printf("Wrong language!")';eval($_) ``` ## Explanation Uses my [Perl/JavaScript polyquine as a basis](https://codegolf.stackexchange.com/a/155010/9365) but sets an additional variable `$P` which controls which program to generate. Uses the check that `+[]` is truthy in Perl, but falsy in JavaScript. ]
[Question] [ A [man from the stars](https://codegolf.stackexchange.com/users/12914/elendia-starman) has come to Earth! Luckily the president of the United States, Donald Trump, has an infinity-sided die. Using this die, he can conjure up a number which *you*, the mayor of [Podunk](http://earthbound.wikia.com/wiki/Podunk), must use to determine who should be sent to stop the invader! But be careful, you can only send a limited amount of bytes on the back of your [frog](http://earthbound.wikia.com/wiki/Save_Frog)! Given a user input (which will be a positive integer), you must return a string depending on what category the number is in. * If the number is a [**Fibonacci number**](https://en.wikipedia.org/wiki/Fibonacci_number), you must output [***Ness***](http://earthbound.wikia.com/wiki/Ness). * If the number is a [**Lucas number**](https://en.wikipedia.org/wiki/Lucas_number), you must output [***Lucas***](http://earthbound.wikia.com/wiki/Lucas). * If the number is *both* a **Lucas number** and a **Fibonacci number**, you must output [***Travis***](http://www.mother4game.com/). * If the number is *neither* a a **Lucas number** nor a **Fibonacci number**, you must output [***Pippi***](http://earthbound.wikia.com/wiki/Pippi). ## Examples Here are a bunch of test cases: ``` 1 => Travis 2 => Travis 3 => Travis 4 => Lucas 5 => Ness 6 => Pippi 7 => Lucas 8 => Ness 610 => Ness 722 => Pippi 843 => Lucas ``` ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins. * You program may be a full program or a(n anonymous) function. ## Bonuses There are a couple bonuses that you can use to help your frog get the data to President Trump faster: * **For `-15` bytes:** If the input number is `2016`, you must output `Trump`, as he is at the peak of his presidency. [Answer] # Julia, ~~146~~ ~~142~~ ~~121~~ 120 bytes ``` n->split("Pippi Lucas Ness Travis")[2any(isinteger,sqrt([5n^2+4,5n^2-4]))+(n∈[2;[(g=golden)^i+(-g)^-i for i=1:n]])+1] ``` This creates an unnamed function that returns a boolean. To call it, give it a name, e.g. `f=n->...`. Ungolfed: ``` function trump(n::Integer) # Determine if n is a Fibonacci number by checking whether # 5n^2 ± 4 is a perfect square F = any(isinteger, sqrt([5n^2 + 4, 5n^2 - 4])) # Determine if n is a Lucas number by generating Lucas # numbers and testing for membership # golden is a built-in constant containing the golden ratio L = n ∈ [2; [golden^i + (-golden)^-i for i = 1:n]] # Select the appropriate Earthbound charater using array # indexing on a string split into an array on spaces return split("Pippi Lucas Ness Travis")[2F+L+1] end ``` Fixed an issue and saved 7 bytes thanks to Glen O! [Answer] # Mathematica ~~143~~ 156 - 15 (bonus) = 141 bytes With 2 bytes saved thanks to LegionMammal978. ``` t_~g~l_:=(r=1<0;n=1;While[(z=l@n)<=t,If[z==t,r=1>0];n++];r);a=g[k=Input[],LucasL]; b=k~g~Fibonacci;Which[k==2016,Trump,a&&b,Travis,a,Lucas,b,Ness,2<3,Pippi] ``` [Answer] # Mathematica, ~~92~~ 87 bytes Inspired by [Sp3000's answer](https://codegolf.stackexchange.com/a/64484/9288). ``` Travis[Ness,Lucas,Pippi][[{2,1}.Product[Abs@Sign[{Fibonacci@n,LucasL@n}-#],{n,0,2#}]]]& ``` [Answer] # Pyth, 59 - 15 = 44 bytes *or 42 bytes after a bug was fixed* ``` &Qr@c."av�a�(s��kW�С��"\b?q2016Q4/hMst*2.uL,eNsNQ_BS2Q4 ``` Hexdump: ``` 0000000: 2651 7240 632e 2261 7601 c061 15dc 2873 &Qr@c."av..a..(s 0000010: fde0 6b57 8bd0 a1ed ed0f 225c 623f 7132 ..kW......"\b?q2 0000020: 3031 3651 342f 684d 7374 2a32 2e75 4c2c 016Q4/hMst*2.uL, 0000030: 654e 734e 515f 4253 3251 34 eNsNQ_BS2Q4 ``` The first two characters (`&Q`) are necessary because of a Pyth parsing bug that makes `Q` after `."` fail. Fix has been applied. If the post-bugfix interpreter is allowed, -2 bytes. --- Without unreadable string compression: # Pyth, 63 - 15 = 48 bytes *49 bytes without Trump* ``` @c"Pippi Ness Lucas Travis Trump")?nQ2016/hMst*2.uL,eNsNQ_BS2Q4 ``` [Test Suite](https://pyth.herokuapp.com/?code=%40c%22Pippi+Ness+Lucas+Travis+Trump%22%29%3FnQ2016%2FhMst%2a2.uL%2CeNsNQ_BS2Q4&input=843&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A610%0A722%0A843%0A2016&debug=0) Pretty straightforward, just generate the sequences, duplicate one and check for membership. Sequences are generated by starting with `[1, 2]` and `[2, 1]`, and then applying the fibonacci rule. [Answer] ## Python 2, 107 ``` f=lambda i,n=input():abs(5*n*n+i)**.5%1>0 print["Travis","Lucas","Ness","Pippi"][f(4)*f(-4)+2*f(20)*f(-20)] ``` The key is two purely arithmetical checks for Fibonacci and Lucas numbers: * `n` is a Fibonacci number exactly if `5*n*n+4` or `5*n*n-4` is a perfect square * `n` is a Lucas number exactly if `5*n*n+20` or `5*n*n-20` is a perfect square [This site has proof sketches](https://web.archive.org/web/20170303035519/http://hubpages.com/education/How-to-Tell-if-a-Number-is-a-Fibonacci-Number). So, the output depends on the values of `5*n*n+i` for `i` in `{4,-4,20,-20}`. The function `f` tests a value of `i`, by checking if the corresponding value *does not* have a whole-number square root The `abs` is there just to avoid an error of taking the root of a negative for `n=1, i=-20`. The function `f` takes the value of the number `n` to test from STDIN. Python only evaluates this once, not once per function call. Whether the number is not Fibonacci is evaluated as `f(4)*f(-4)` using the implicit boolean to number conversion and similarly for not Lucas, and the corresponding string is taken. If trailing spaces were allowed, string interleaving would be shorter. [Answer] ## Python 2, 117 bytes ``` F=[1] L=[2,1] n=input() exec 2*n*"F,L=L+[sum(L[-2:])],F;" print["Pippi","Lucas","Ness","Travis"][(n in F)*2+(n in L)] ``` For the string list, `"Pippi Lucas Ness Travis".split()` is the same length. [Answer] ## CJam, ~~58~~ ~~55~~ 54 bytes ``` ri5Zbe!f{1${_-2>:++}*&!}2b"Travis Ness Lucas Pippi"S/= ``` Naïve approach of generating the Fibonacci and Lucas numbers then counting occurences in both, converting to binary, and picking the appropriate string. [Try it online](http://cjam.aditsu.net/#code=ri5Zbe!f%7B1%24%7B_-2%3E%3A%2B%2B%7D*%26!%7D2b%22Travis%20Ness%20Lucas%20Pippi%22S%2F%3D&input=843). [Answer] ## Perl, ~~133~~ ~~(146-15=)131~~ ~~(144-15=)129~~ (136-15=)121 bytes +1 byte for the `-n` flag. ``` $a=$d=1;$b=$c=2;$f+=$_==$a,$l+=$_==$c,($a,$b,$c,$d)=($b,$a+$b,$d,$c+$d)while$a<$_*9;say$_-2016?(Pippi,Ness,Lucas,Travis)[$f+$l*2]:Trump ``` With newlines after semicolons, for readability: ``` $a=$d=1;$b=$c=2; $f+=$_==$a,$l+=$_==$c,($a,$b,$c,$d)=($b,$a+$b,$d,$c+$d)while$a<$_*9; say$_-2016?(Pippi,Ness,Lucas,Travis)[$f+$l*2]:Trump ``` Demo: ``` llama@llama:...code/perl/ppcg64476trump$ for x in 1 2 3 4 5 6 7 8 610 722 843 2016; do echo -n "$x => "; echo $x | perl -n trump.pl; done 1 => Travis 2 => Travis 3 => Travis 4 => Lucas 5 => Ness 6 => Pippi 7 => Lucas 8 => Ness 610 => Ness 722 => Pippi 843 => Lucas 2016 => Trump ``` Tricks: * ~~You might be wondering why my variables are named `$a`, `$b`, `$%`, and `$d`. That is an excellent question! In fact, it allows me to save a byte.~~ ``` (stuff) ... ,$l+=$_==$%while$a<$_ ``` is one byte shorter than ``` (stuff) ... ,$l+=$_==$c while $a<$_ ``` This no longer applies because I golfed my code by rearranging things, causing the variable name change to no longer save bytes. I changed it back so that variable names make sense again. * ~~`$_-2?$f+$l*2:3` is mildly interesting. Basically, I had to special-case `2` for Lucas numbers because my program checks whether a number is a Lucas number *after* "updating" the Fibonacci and Lucas numbers. So `2` was considered a not-Lucas number. `$_-2?foo:bar` is a char shorter than `$_==2?bar:foo`. Same thing is used for the `2016` test.~~ This is also no longer true because I was able to restructure the program to not require special-casing `2`. But I still use `$_-2016?stuff:Trump` instead of `$_==2016?Trump:stuff`, which is one byte longer. * Speaking of which, you may be wondering how I did this restructuring. I just made the program do 9 times more iterations than necessary, which only costs 2 bytes (`*9`) but allows me to make assumptions elsewhere that help golf stuff down. * Because variables default to zero, ``` $f+=$_==$a ``` is shorter than ``` $f=1if$_==$a ``` * Perl supports barewords, so I don't have to quote any of my strings (\o/). [Answer] # Seriously, 69 bytes ``` ,;;r`;F@2+F+`M2@q@#"%d="%£MΣ@f0≤2*+["Pippi","Lucas","Ness","Travis"]E ``` Before this challenge, Seriously had the builtin `f` (index in Fibonacci numbers, -1 if not a Fibonacci number)... but not index in a list or "is in list"! (It's since been added as `í`.) As a result, this is what I spend finding if the input is a Fibonacci number: ``` , f0≤ ``` This is what I spend generating a list of Lucas numbers: ``` ;r`;F@2+F+`M2@q ``` And this is what I spend finding if the input is in the list of Lucas numbers: ``` ; @#":%d:="%£MΣ ``` That's a string being formatted using Python's % notation into something like `:610:=`, and converted to a function, which is then mapped over the array and summed. (The Lucas numbers are unique, so the sum is always 0 or 1.) Thanks to @Mego for that last bit with the string formatting. [Answer] # Julia, ~~101~~ 100 bytes ``` n->split("Pippi Lucas Ness Travis")[[2;1]⋅(sum(i->[i[];trace(i)].==n,Any[[1 1;1 0]].^(0:n)).>0)+1] ``` Ungolfed: ``` function f(n) k=Any[[1 1;1 0]].^(0:n) # Produces characteristic matrices of Fibonacci # numbers from 0 to n F=sum(i->i[]==n,k) # Check if n is a Fibonacci number by checking # the first value in each matrix for n L=sum(i->trace(i)==n,k) # Check if n is a Lucas number by checking # the trace of each matrix for n I=[2;1]⋅[F;L]+1 # Calculate 2F+L+1, which is the index for the next step S=split("Pippi Lucas Ness Travis") # Creates array with four strings # saves a byte compared with directly creating array return S[I] # This uses the above calculations to determine which of the four to return end ``` [Answer] # Octave, 93 bytes ``` @(n){'Pippi','Lucas','Ness','Travis'}{(1:2)*any(~rem(real(sqrt(5*n^2+[-20,-4;20,4])),1)).'+1} ``` This approach is similar to [my MATLAB answer](https://codegolf.stackexchange.com/a/76849/51939) with the exception that Octave allows you to index directly into a fresh array: ``` {'a', 'b', 'c'}{2} %// b ``` [Answer] # MATL, ~~57~~ ~~55~~ ~~54~~ (67-15) = 52 bytes ``` 20Kht_vi2^5*+X^Xj1\~a2:*sG2016=-'Lucas Ness Travis Trump Pippi'Ybw) ``` [**Try it Online!**](http://matl.tryitonline.net/#code=MjBLaHRfdmkyXjUqK1heWGoxXH5hMjoqc0cyMDE2PS0nTHVjYXMgTmVzcyBUcmF2aXMgVHJ1bXAgUGlwcGknWWJ3KQ&input=MjAxNg) **Explanation** Again, similar logic to my other answers [here](https://codegolf.stackexchange.com/a/76851/51939) and [here](https://codegolf.stackexchange.com/a/76849/51939). ``` 20 % Number literal K % Retrieve the number 4 from the K clipboard (the default value) h % Horizontal concatenation to produce [20 4] t % Duplicate elements _v % Negate and vertically append elements (yields [20, 4; -20 -4]) i2^ % Explicitly grab the input and square it 5* % Multiply by 5 + % Add this to the matrix ([20, 4; -20 -4]) X^ % Take the square root Xj % Ensure that the result is a real number 1\ % Get the decimal component ~ % Create a logical arrays where we have TRUE when no remainder a % For each column determine if any element is TRUE 2: % Create the array 1:2 * % Perform element-wise multiplication with boolean s % Sum the result to yield an index G % Explicitly grab the input (again) 2016= % Check to see if it is 2016 (yields TRUE (1) if equal) - % Then subtract the boolean from the index. Since 2016 is NOT a % Fibonacci or Lucas number, the original index is 0. Subtracting % this boolean, will make this index now -1. For all other non-2016 % numbers this will have no effect on the index. 'Lucas Ness Travis Trump Pippi' % Create the possible strings values % Note: the 0 index wraps around to the end hence Pippi being at the end. % The next to last entry ('Trump') is ONLY accessible via a -1 index as % discussed above Yb % Split at the spaces to create a cell array w % Flip the top two stack elements ) % Retrieve the desired value from the cell array ``` [Answer] # C++11, 176 + 15 (#include) = 191 ``` #include<mutex> [](int n){std::function<int(int,int)>c=[&](int f,int s){return f-s>n?0:s-n?c(s,f+s):1;};int l=c(2,1),f=c(1,1);l&f?puts("Travis"):l?puts("Lucas"):f?puts("Ness"):puts("Pippi");} ``` Ungolfed with usage. I can add explanation if requested tomorrow, gtg to bed now! ``` #include <functional> #include <cstdio> int main() { auto r = [](int n) { std::function<int(int, int)> c = [&](int f, int s) { return f - s > n ? 0 : f - n ? c(s, f + s) : 1; }; int l = c(2, 1), f = c(1, 1); l & f ? puts("Travis") : l ? puts("Lucas") : f ? puts("Ness") : puts("Pippi"); }; for (int i : { 1, 2, 3, 4, 5, 6, 7, 8, 610, 722, 843 }) { printf("%i - ", i); r(i); } } ``` [Answer] # Javascript (ES6), 108 bytes ``` x=>(f=(a,x,y)=>a==y||a==x?1:a<y?0:f(a,y,x+y),b=f(x,0,1),c=f(x,2,1),b&&c?'Travis':b?'Ness':c?'Lucas':'Pippi') ``` Same function for Fibonnacci and Lucas. It's a recursive function that takes the first two values as init. [Answer] # Java, 151 bytes You could argue that Trump would never outsource this crucial decision, so we wouldn't have to make the method public, saving another 7 bytes. ``` public String t(int n){return"Pippi,Lucas,Ness,Travis".split(",")[2*f(n,1,1)+f(n,2,1)];}int f(int a,int x,int y){return a==x||a==y?1:a<y?0:f(a,y,x+y);} ``` Ungolfed including test-main invocation ``` public class Trump { //Test Invokation public static void main(String[] args) { int[] n = {1, 2, 3, 4, 5, 6, 7, 8, 610, 722, 843, 2016 }; for(int i = 0; i < n.length; ++i) { System.out.println(""+ n[i] + " => " + new Trump().t(n[i])); } } public String t(int n) { return "Pippi,Lucas,Ness,Travis".split(",")[2*f(n,1,1)+f(n,2,1)]; } int f(int a,int x,int y) { return a==x||a==y?1:a<y?0:f(a,y,x+y); } } ``` I found no way so far to test for 2016 and return "Trump" in code that's less than 15 bytes in code. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~39~~ 37 (52 - 15 bonus) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2016Qi.•ªb‚•ë>ÅG¹å_¹ÅF¹åi.•F_ïk|»9•ë.•?®B'5n•}2äsè}™ ``` [Try it online](https://tio.run/##yy9OTMpM/f/fyMDQLDBT71HDokOrkh41zAIyDq@2O9zqfmjn4aXxQKLVDcQCq3CLP7w@u@bQbkuwIpCI/aF1TuqmeUBWrdHhJcWHV9Q@alkEMdQAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn1l5X8jA0OzwEy9Rw2LDq1KetQwC8g4vNrucKt75eGl8ZWHW92ANFjaLf7w@uyaQ7stwSpAIvaH1jmpm@YBWbVGh5cUH15R@6hl0X@d/4ZcRlzGXCZcplxmXOZcFlxmhgZc5kZGXBYmxlwg6wA). **Explanation:** ``` 2016Qi # If the input equals 2016: .•ªb‚• # Push "trump" to the stack ë # Else: >ÅG # List of Lucas numbers up to and including the input+1 ¹å # Check if the input is in this list (1 if truthy; 0 if falsey) _ # Invert the boolean (0→1 and 1→0) ¹ÅF # List of Fibonacci numbers up to and including the input ¹åi # If the input is in this list: .•F_ïk|»9• # Push string "travisnessi" to the stack ë # Else: .•?®B'5n• # Push string "pippilucas" to the stack } # Close the inner if-else 2ä # Split the string into two parts # i.e. "travisnessi" → ["travis","nessi"] # i.e. "pippilucas" → ["pippi","lucas"] sè # Index the Lucas result into the list of two strings } # Close the outer if-else ™ # And output the top of the stack in title-case ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~128~~ ~~120~~ ~~116~~ 110 bytes ``` a;b;o;f(n){for(o=b=0,a=1;a<=n;b=a+b,a=b-a)o|=(b==n)+2*(2*a+b==n);n=o?o-1?o-2?"Travis":"Lucas":"Ness":"Pippi";} ``` [Try it online!](https://tio.run/##ZY7BbsIwDIbvfYooElICrUSzwtA8wwtMsANHLk6hUw4kVQtcoM/eJeIEPlj2//n/LdfFX12PI4GFAI3y@t6ETgW0OM8JS6Bv9GCRZjZKW5AOD1QW0euZmSozjYskwGPYhKKMZTZy39HN9fJL/lxrSn176lP7dW3rJAzjLbijaDvnL1s6n3aNipNwWtyfsFFyUh0FrsWkP3iZuzw6tAYxZFlynsl5Fd2ZeDlSangjhpEPRipGFowsGflkZMVT5ZznDP9pVaWvhvEf "C (gcc) – Try It Online") # Explanation Let's name `F(n)` the n-th Fibonacci number, and `L(n)` the n-th Lucas number. `a`, `b` are `F(n-1)`, `F(n)` respectively. Then we can calculate `L(n) == F(n-1)+F(n+1) == 2*F(n-1) + F(n) == 2*a+b` This function will successively calculate Fibonacci and Lucas numbers, up to `n`, and check if `n` is any of them. If `n` is a Fibonacci number, the 1st bit of `o` will be set to `1` If `n` is a Lucas number, the 2nd bit of `o` will be set to `1` `o` will then be used to determine which name to output # Edit * Saved 8 bytes by golfing the condition of the for-loop : starting at second iteration, we have `a<b<c` and `a<a+c=L(n)`, so `( b<=n || a+c<=n ) => a<n`. I actually needed `a<=n` to handle correctly `n=1` * Saved 4 bytes thanks to ceilingcat ! (also corrected a mistake, my code was outputting "2 => Ness") * Saved 6 bytes: + 2 thanks to ceilingcat again + 4 by removing the variable `c`, equal to `F(n+1)`, which was useless since we can already calculate `F(n+1)` with `a` and `b` [Answer] ## Perl 5.10, 119 - 15 (bonus) = 104 bytes ``` $_=<>;$j=1;($i,$j)=($j,$i+$j)while$_>$i;say$_-2016?(Pippi,Lucas,Ness,Travis)[($_==$i)*2|$_==3*$j-4*$i|$_-1>>1==0]:Trump ``` Ungolfed: ``` # Read line from stdin $_ = <>; # Find first Fibonacci number greater than or equal to input. # Store this number in $i and the next Fibonacci number in $j. $j = 1; ($i, $j) = ($j, $i + $j) while $_ > $i; say $_ - 2016 ? (Pippi,Lucas,Ness,Travis)[ ($_ == $i) * 2 | # Bitwise OR with 2 if Fibonacci number $_ == 3 * $j - 4 * $i | # Bitwise OR with 1 if Lucas number >= 3 $_ - 1 >> 1 == 0 # Bitwise OR with 1 if Lucas number <= 2 ] : Trump ``` This exploits the fact that ``` L(n-2) = 3 * F(n+1) - 4 * F(n) ``` is the greatest Lucas number lower to or equal than F(n). [Answer] # Groovy, 149 bytes ``` f={i->g={m,s->while(s[-2]<=m)s<<s[-2]+s[-1];s} println(["Pippi","Ness","Lucas","Travis"][(g(i,[1,1]).contains(i)?1:0)+(g(i,[2,1]).contains(i)?2:0)])} ``` Test code: ``` [1,2,3,4,5,6,7,8,610,722,843].each { print "$it => " f(it) } ``` `g` is a closure that generates a list of numbers based on a seed (`s`) and a max value (`m`). `(g(i,[1,1]).contains(i)?1:0)+(g(i,[2,1]).contains(i)?2:0)` finds the index to use based on the number being lucas or fibonacci. [Answer] # MATLAB, ~~122~~ 119 bytes ``` @(n)subsref({'Pippi','Lucas','Ness','Travis'},substruct('{}',{(1:2)*any(~rem(real(sqrt(5*n^2+[-20,-4;20,4])),1)).'+1})) ``` **Brief Explanation** We first create a cell array containing the values to print: `{'Pippi', 'Lucas', 'Ness', 'Travis'}`. Then to figure out which value to display, we check to see whether `n` is a Fibonacci or Lucas number. For Fibonnaci, we use the following formula: ``` any(~rem(sqrt(5*n^2 + [-4 4]), 1)) ``` This checks to see if either `5*n^2 + 4` or `5*n^2 - 4` are a perfect square. If `any` of them are, then it is a Fibonacci number. The formula for a Lucas number is *very* similar with the exception that we use +/- 20 instead of 4: ``` any(~rem(sqrt(5*n^2 + [-20 20]), 1)) ``` In this solution I combined these two cases into one by using the matrix: ``` M = [-20 -4 20 4] ``` By applying the same equation as those above, but force `any` to consider only the first dimension, I get a two element logical array where if the first element is `true`, then it is a Lucas number and if the second element is `true`, it is a fibonacci number. ``` any(~rem(sqrt(5*n^2 + [-20 -4;20 4]), 1)) ``` Then to compute the index into my initial cell array, I treat this as a binary sequence by performing element-wise multiplication of this boolean with `[2^0, 2^1]` or simply `[1,2]`. And sum the elements. Obviously I have to add 1 because of MATLAB's one-based indexing. ``` index = (1:2) * any(~rem(real(sqrt(5*n^2+[-20,-4;20,4])),1)).' + 1; ``` Then I have to use `subsref` and `substruct` to index into the initial cell array to obtain the final result. [Answer] ## JavaScript (ES6), 97 bytes ``` x=>[['Pippi','Lucas'],['Ness','Travis'],f=(a,x,y=1)=>a>x?f(a,y,x+y):a==x||a==1][+f(x,0)][+f(x,2)] ``` The `a==1` check is needed otherwise I don't notice that 1 is a Lucas number. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 47 bytes - 15 = 32 ``` +2ḶÆḞ⁸eð+ị“©ḤʠhMṂƁÞḄṭAƓ»Ḳ¤µ2+С-⁸eḤ “¡Ỵ¦»Ç⁼?⁽¥Ð ``` [Try it online!](https://tio.run/##AW8AkP9qZWxsef//KzLhuLbDhuG4nuKBuGXDsCvhu4vigJzCqeG4pMqgaE3huYLGgcOe4biE4bmtQcaTwrvhuLLCpMK1MivDkMKhLeKBuGXhuKQK4oCcwqHhu7TCpsK7w4figbw/4oG9wqXDkP///zIwMTY "Jelly – Try It Online") ]
[Question] [ The mean of a population \$(x\_1,\dots,x\_n)\$ is defined as \$\bar x=\frac1n\sum\_{i=1}^n x\_i\$. The (uncorrected) [standard deviation](https://en.wikipedia.org/wiki/Standard_deviation#Uncorrected_sample_standard_deviation) of the population is defined as \$\sqrt{\frac1n\sum (x\_i-\bar x)^2}\$. It measures how dispersed the population is: a large standard deviation indicates that the values are far apart; a low standard deviation indicates that they are close. If all values are identical, the standard deviation is 0. Write a program or function which takes as input a (non-empty) list of non-negative integers, and outputs its standard deviation. But check the scoring rule, as **this is not code golf**! ## Input/Output Input/Output is flexible. Your answer must be accurate to at least 2 decimal places (either rounding or truncating). The input is guaranteed to contain only integers between 0 and 255, and to not be empty. ## Scoring To compute your score, convert your code to integer code points (using ASCII or whatever code page is standard for your language) and compute the standard deviation. Your score is the number of bytes in your code multiplied by the standard deviation. Lower score is better. You should therefore aim for code which at the same time (a) is short and (b) uses characters with close codepoints. Here is an [online calculator](https://tio.run/##TY2xDsIwDET3fIXVyUaiAxMLH8DOwoJUpQ5liCPsRGqF@PaQdGK7906601rjNtoMFwhFfH4lwZU@DiA2FXnq2Mga2Vsz7grXY6THiXqjnIsKGrmvc@F/xwjEL5P2cID9BksO51u6Sm6SasDhnoqCTzPDM7HBwsrjQPUH "R – Try It Online") to compute your score (assuming you use ASCII). ## Test cases ``` Input | Output 77 67 77 67 | 5 82 | 0 73 73 73 | 0 83 116 97 116 115 | 13.336 ``` A word of caution about built-ins: if your language has a built-in, that's fine (and good for you if it only uses one character!). But make sure that it uses \$n\$ and [not](https://en.wikipedia.org/wiki/Bessel%27s_correction) \$n-1\$ as the denominator in the formula, or else your answer won't be valid. [Answer] # [MATL](https://github.com/lmendo/MATL), score 65.30697 ``` tYmhZs ``` [Try it online!](https://tio.run/##y00syfn/vyQyNyOq@P//aHNzBTNzBTAZCwA) Or [verify all test cases](https://tio.run/##y00syfmf8L8kMjcjqvi/S8j/aHNzBTNzBTAZyxVtYQQkzI0VwAjEN1YwNDRTULA0B9OGhqaxAA). ### How it works The built-in function `Zs` with its default arity (1 input, 1 output) computes the *corrected* standard deviation: \$\sqrt{\frac 1 {n-1}\sum (x\_i-\bar x)^2}\$ The uncorrected standard deviation can be obtained with the 2-input version of `Zs`: `1&Zs`, where `1` as second input means uncorrected. `l` or `T` could be used instead of `1` to reduce the score, but `&` is very far from the other characters. `2$` or `H$` could be used instead of `&`, but `$` is even farther. So it is better to use the default version of `Zs` (corrected standard deviation) on the input *with its mean appended*. This increases the input length by `1` and contributes `0` in the numerator, which causes the corrected standard deviation to become uncorrected. ``` t % Implicit input: numeric vector. Duplicate Ym % Mean h % Concatenate the input vector with its mean Zs % Corrected standard deviation ``` [Answer] # [J](http://jsoftware.com/), 19 bytes, [Score 119.8249](https://tio.run/##TY3BCsJADETv@xWhakkqreBJCn6Ad89CqV30sCluslARv33N9uRt3huYiTmHdyd3OINPPOpzZlzo4wCCqTANBY3ESF5RcVW4tIFuRypNnDRFRiH3dc7/7wgBj48hltDAeoNJ/ek6X1hNUvZY4f6w21Ld9U1fY2uwoYryDw) *-~1 thanks to Bubbler* Tries to have most characters between 0x23 and 0x2F `#$%&'()*+,-./`, with `:` being a bit further away. ``` (+/%$)&.:*:&(-+/%#) ``` [Try it online!](https://tio.run/##bY49DsIwFIP3nuIThSYpbSBE9JUndUJiYuIQGVgrzh8ilAWE5R/Zk595401iUQwDR7Ro9Fwf91u2@8Nu6zqvvXZ2LKV12eWECJNUr2gSw3ziF2WWWPm1zpEQJi7yiRDONLZdHT2JyEtZWbz5c8C8AQ "J – Try It Online") ### How it works ``` (+/%$)&.:*:&(-+/%#) (-+/%#) x - sum divided by length *:& and squared (+/%$)&.: mean of that &.:*: reverse square -> square root ``` [Answer] ## Google Sheets, Score 142.6885 ``` =STDEVP(F:F ``` Google Sheets automatically closes parentheses, and using `F` as the input column minimizes the standard deviation. This saves one byte over Excel's uncorrected standard deviation, since Excel uses `STDEV.P` instead of `STDEVP` [Answer] # [R](https://www.r-project.org/), ~~34 bytes~~ 24 bytes, [score](https://tio.run/##TY2xDsIwDAX3fIXVyQ9RBiYW2OncGakKjWBIKuJEalXx7cHJxOa7J51jKX47yZOu5HKw6b0EXrEbIq/Kz1NFJVGST0zcFK@9x@OMusQ55RhYYL7GuP@OgIJ9TbEeB2pvOCd3GZd7SCpRHHfqLIvVKPrbcGz5AUCH8gM) ~~789.5923~~ ~~723.4687~~ 722.6112 ``` sd(c(scan()->J,mean(J))) ``` [Try it online!](https://tio.run/##K/r/vzhFI1mjODkxT0NT185LJzcVyPLS1NT8b2bOZW7OBSH/AwA "R – Try It Online") *Edit: switched to a shorter formula to calculate the population sd (which I found [here](https://codegolf.stackexchange.com/questions/60901/calculate-standard-deviation/60908#60908)), which now only benefits from selecting the best variable name among the golfs outlined below for the previous version.* *Edit2: score reduced by 0.8575 thanks to Robin Ryder* The (previous) ungolfed code ~~is~~ was: `x=scan();sqrt(mean((x-mean(x))^2))` (which would have a score of 1104.484) From this, sequential score-improving golfs are: * `x=scan();`?`=mean;sqrt(?(x-?x)^2)` = re-define `mean()` as a single character unary operator (score 983.8933) * `x=scan();`?`=mean;(?(x-?x)^2)^.5` = exchange `sqrt()` for `()^.5` (score 918.6686) * `H=scan();`?`=mean;(?(H-?H)^2)^.5` = exchange `x` for `H` which is the closest codepoint value to the mean of the program, thereby reducing the standard deviation (score 801.4687) * `I=scan();`?`=mean;I=I-?I;(?I^2)^.5` = first calculate `x-mean(x)` separately, to reduce number of parentheses (which are at the far end of the ASCII range, and so increase the standard deviation), and re-adjust the variable name to `I`. Although this increases the code length by 2 characters, it reduces the score to 789.5923. --- # [R](https://www.r-project.org/) + multicon, 15 bytes, [score](https://tio.run/##TY3BCsIwEETv@Yqlp11BD56k4Ad49yyUtMGC2dTdDbSI3x6TnrzNewMzUkrcTjrCFUJmb3NiXOnjAGJVcRoaVtJK@hbDXeF6jPQ4U2tksiyMSu7rXPjfUQL2z0FaOMB@g9nC5Z5ubFVSCdjF/LLZJ@77JS06dlR@) 273.5032 ``` multicon::popsd ``` Trivial solution using built-in `popsd` function from `multicon` library. Not installed at TIO, but you can try it at [rdrr.io](https://rdrr.io/snippets/) by copy-pasting this code: ``` x=c(67,77,67,77) # data multicon::popsd(x) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), Score 537.0884 ``` A@((#-A@#)^2)^.5&;A=Mean ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n27739FBQ0NZ19FBWTPOSDNOz1TN2tHWNzUx739AUWZeiYKDn0N6dLW5uY6ZuQ6YrI3lQpaxMEITMDfWASN0dcY6CoaGZjoKluZQhqGhaW3s//8A "Wolfram Language (Mathematica) – Try It Online") @att saved 17.6142 points [Answer] # Python 3, Score 680.5175 Where the golfiest solution is not the best. I doubt any non-builtin could be better but I might be wrong. ``` import statistics;statistics.pstdev ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKG4JLEks7gkM7nYGsHUKyguSUkt@/8fAA "Python 3 – Try It Online") ### Python 3, Score 733.6818 ``` from statistics import*;pstdev ``` ### Python 3, Score 798.5587 ``` __import__('statistics').pstdev ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), Score: ~~[531.168](https://tio.run/##yy9OTMpM/f9fyTk/JbUgPzOvpNhKQcn@6L4jbZ7B2S62XErBpUnFJYl5KYlFKQopqWWZiSWZ@XkgNZ56YUDpgKL89KLEXIWc1Lz0kgyweDpQ2C0zLzFHoTg5vygVJKal8///4VbHvOI8XSClUQIA)~~ ~~[431.516](https://tio.run/##yy9OTMpM/f9fyTk/JbUgPzOvpNhKQcn@6L4jbZ7B2S62XErBpUnFJYl5KYlFKQopqWWZiSWZ@XkgNYdbHfOK83SBlEYJUF1AUX56UWKuQk5qXnpJBkiBZzpQ2C0zLzFHoTg5vygVJKal8/@/f3G6PkinC4ihUQIA)~~ [360.278](https://tio.run/##yy9OTMpM/f9fyTk/JbUgPzOvpNhKQcn@6L4jbZ7B2S62XErBpUnFJYl5KYlFKQopqWWZiSWZ@XkgNYdbHfOK83SBlEYJUF1AUX56UWKuQk5qXnpJBkiBZzpQ2C0zLzFHoTg5vygVJKal8/@/v2e6fp5nni6I1igBAA) (~~10~~ ~~15~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) ``` Osg/nsn-Osg/(t ``` Uses the [05AB1E coding page](https://github.com/Adriandmen/05AB1E/wiki/Codepage). The characters used have the codepoints `[79,73,103,47,110,73,110,45,68,79,73,103,47,40,116]`. [Try it online](https://tio.run/##yy9OTMpM/f/f3zNdP88zTxdEa5T8/x9tYaxjaGimY2kOpgwNTWMB) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf/9D61L1887tC5PF8zSKPmv8z862txcx8xcB0zG6kRbGAEJc2MdMALxjXUMDc10LM3BlKGhaWwsAA). **Explanation:** ``` # Get the arithmetic mean of the (implicit) input-list by: O # Summing the (implicit) input-list I # Push input-list again g # Pop and push its length / # Divide the sum by this length # (which gives a better score than the builtin `ÅA`) n # Square it I # Push the input again (better score than `s` or `¹`) n # Square each value in the input as well - # Subtract each from the squared mean # Take the arithmetic mean of that list again by: O # Summing it Ig # Push the input-list again, and pop and push its length / # Divide the sum by this length ( # Negate it t # And take its square-root # (after which the result is output implicitly) ``` [Answer] # JavaScript (ES7), Score ~~1359 1228~~ 1156.077 *Saved 72 points thanks to @edc65* ``` D=>D[F='map'](C=>B-=(C+E/A)**2/A,D[F](C=>E+=--A?C:9,A=B=E=0))&&B**.5 ``` [Try it online!](https://tio.run/##hVHLbsIwELzzFT5UYIfEvASUIlMFCNceOEIkXMe8caLEVG0h/XW6DqgEKrWWrLV2Z3Z3xmv@xhMRryLtqDCQpzk7DVlvOBmx0o5HJR8PWK/vMDwoexWXWFa94tpQzfJemTmO@zx46tgu6zOPVQkpFvuWRZsnEaok3Eq6DRd4jiftto1acM/RJ1SHo9W7DHCDkMId9rH@d73dgD7Z/acPYGq1lo067cujVmveUYATSMTQHLJjHa/UApNuIfmElKnQrVQLvewWAoPBE0qpSfsUvMECsR4SVCx5PICkqzEhQN4B9AqMZbAXEuPIRoIYQoTKdyQbVYGWX342VWMRxmaxh0PymSILYvCzeJOkWQXDnhYK8orSGbS66VWaKmSmUXTMJGVhr/RUOedTvglOyejXXMOEQ9rNKUnCGJa9KjegifAB53xd3kB9eV1LoelGfiTYZAmdh7HHxRJvMrvyKhECEZsUwtE8bkzJ/QeNeDDWHKaDPoM1tGzixge9v73bSa7OBu1QJf@PV6fqmVOnbw "JavaScript (Node.js) – Try It Online") ### Character breakdown ``` char. | code | count -------+------+------- 0 | 48 | 1 2 | 50 | 1 5 | 53 | 1 9 | 57 | 1 & | 38 | 2 ' | 39 | 2 ( | 40 | 3 ) | 41 | 3 * | 42 | 4 + | 43 | 2 , | 44 | 2 - | 45 | 3 . | 46 | 1 / | 47 | 2 : | 58 | 1 <-- mean ≈ 59.43 = | 61 | 9 > | 62 | 3 ? | 63 | 1 A | 65 | 4 B | 66 | 3 C | 67 | 4 D | 68 | 3 E | 69 | 3 F | 70 | 2 [ | 91 | 2 ] | 93 | 2 a | 97 | 1 m | 109 | 1 p | 112 | 1 ``` [Answer] # [Arn](https://github.com/ZippyMagician/Arn), score = ~~925.3172~~ ~~655.6836~~ ~~602.7985~~ 123.2274 ``` sdev:s ``` Uses the builtin standard deviation function. Go to the old answer for a more interesting one # Old Answer I don't compress it because Standard Deviation would be way higher. I have updated this answer, since I found a much shorter method (sitting at 14 bytes). Link [here](https://codegolf.stackexchange.com/questions/60901/calculate-standard-deviation/210065#210065) (this is the program the score refers to). I will leave the original program for posterity's sake ``` :/(+v{:*v-(:s.mean}\)/((:s)# ``` [Try it!](https://zippymagician.github.io/Arn?code=Oi8oK3Z7Oip2LSg6cy5tZWFufVwpLygoOnMpIw==&input=NjAgNzAgNjAgNzA=) # Explained $$\large\sqrt {\frac1n \sum(x\_i-\bar x)^2}$$ Just made use of the formula. `:/` is the sqrt prefix, `:*` is the square prefix, `+v{:*v-(:s.mean}\` Folds with `+` (addition) after mapping with the block `v{:*v-(:s.mean}`. `v` is current entry, `:s` splits on space (no variable is provided, so it assumes the variable `_`, which is STDIN). Then it just divides by the length (`#` suffix). [Answer] # [Io](http://iolanguage.org/), score = 1454.7164672196433912 -19.58295474318379 thanks to @ManishKundu ``` method(:,:map(Z,(Z- :average)squared)average sqrt) ``` [Try it online!](https://tio.run/##lU5BCsIwELznFaGnXVnBWGw04A98QfESbKqBtmmT6MHPRxt6EPQiLLvszszOWJdaro78nHoTb64BRarXI9QE9Zor/TBeXw2G6a69aXDZeZh8xNRCZ0MEKamSlDsiH70dYjewBdxvv2@ypFw/2CUJUdFB5iHE7oPCLq4xc9bi/6gFY9BCfqDD6e3EZ6Uly3WEDSKuMhbs0@Dil14 "Io – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), (14 [bytes](https://github.com/DennisMitchell/jelly)), score 218.314 (218.31399405443526) ``` +/÷LN+*2+/÷L*. ``` **[Try it online!](https://tio.run/##y0rNyan8/19b//B2Hz9tLSMwQ0vv////0YY6CuY6CpY6CoamsQA "Jelly – Try It Online")** Or see a [self-evaluation](https://tio.run/##y0rNyan8/19b//B2Hz9tLSMwQ0vv/@EZXpmPNq47tPXopIc7Z@gcbrc@3H54us@xrkNbHzXMSc5PSS3Iz8wrKbZSAHKLSxLzUhKLUhRSUssyE0sy8/Mgwsn5Rakg1tyje9wx7QAA "Jelly – Try It Online"). Bytecode: `2b 2f 1c 4c 4e 2b 2a 32 2b 2f 1c 4c 2a 2e` ### How? A naive program would be `_Æm²Æm½`for 348.47 (subtract the mean from each, square each, take the mean of that and then square root it). We know that to get rid of the two byte monad `Æm` whose code-points are quite far apart (`0x0d` and `0x6d`) we need to either: * divide using `÷` (`0x1c`), or * multiply, `×` (`0x11`), and invert, `İ` (`0xc6`) But the latter bytes are also fairly far apart, so this answer attempts to use bytes close to `÷` (`0x1c`). ``` +/÷LN+*2+/÷L*. - Link: list of numbers, A / - reduce (A) by: + - addition -> sum(A) L - length (A) ÷ - divide -> mean(A) N - negate + - add (to A, vectorised) -> [mean(A)-v for v in A] 2 - two * - exponentiate -> [(mean(A)-v)² for v in A] / - reduce by: + - addition -> sum((mean(A)-v)² for v in A) L - length (A) ÷ - divide -> sum((mean(A)-v)² for v in A)/n . - a half * - exponentiate -> √(sum((mean(A)-v)² for v in A)/n) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes, score [478.3451](https://tio.run/##TY0xDsIwEAR7v@KUyocUCiqaPICCBtJZBp1CLChsK@ezFIR4u7FT0e3MSrtcin/v0wMGcDlM8opBr/hRAL4qP1PDSqlSWlj0pvTae7wdsDU8S@agE6qvUu5/JyGE6Uncwg62G53FHcd4ClIlFqc7MnS3wyVGOdfl65KJZ0N9A0PWdlh@) ``` a[a_]=RootMeanSquare[a-Mean[a]] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z8xOjE@1jYoP7/ENzUxL7iwNLEoNTpRF8SJToyN/R9QlJlXEq2sa@fnkOigHKtWF5ycmFdXzVVtbq5jZq4DJmt1uKotjECkubEOGIFFjHUMDc10LM3BlKGhaS1X7X8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes, stddev 46.741654, score 701.12481 ``` I₂∕ΣX⁻θ∕ΣθLθ²Lθ ``` [Try it online!](https://tio.run/##VcoxD8IgEIbhv8J4JJgAwVrjqKMmjR2bDqQSS9JCoFB/Pp6D0W7Pe98No46D11MpTbQuwVkvCdqQdTR37xNc7GofBto8Q@NfJsLNurxAYORvCZSRq3HPNCIphqTbC6WnUrpOcsGIqCQ@SI5Se5SoUPURpcRm@KTg6qtD/cu@L7t1egM "Charcoal – Try It Online") Link is to verbose version of code. Link test case is the byte values in the Charcoal code page of the code. Explanation: ``` θ Input `x` Σ Summed ∕ Lθ Divided by `n` ⁻θ Vectorised subtracted from `x` X ² Squared Σ Summed ∕ Lθ Divided by `n` ₂ Square rooted I Cast to string Implicitly printed ``` Note that the alternative formula for the standard deviation, \$ \sqrt{\bar{x^2}-\bar x^2} \$, while having a slightly smaller standard deviation, takes 17 bytes, and therefore results in a higher score of 755.6. [Answer] ## [Setanta](https://try-setanta.ie/), score: 2728.508 ``` gniomh(g){f:=0h:=0e:=fad@g le i idir(0,e){d:=g[i]f+=d h+=d*d}toradh freamh@mata((h-f*f/e)/e)} ``` [Try it here!](https://try-setanta.ie/editor/EhEKBlNjcmlwdBCAgICgh9CGCg) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~107~~ ~~104~~ 99 bytes, stddev ~~25.25~~ \$\cdots\$~~25.32~~ 25.00, score ~~2702.01~~ \$\cdots\$ ~~2634.27~~ 2475.426270 Saved 3 bytes and 46.95288 points thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! Saved 5 bytes and 158.848632 points thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!! ``` E;float D,G,H;float F(F,C)int*C;{E=F;for(H=G=0;E>-F;0>E?G+=D*D:(H+=*C++))D=H/F-C[--E];G=sqrt(G/F);} ``` [Try it online!](https://tio.run/##VVDRjqJAEHyGr@gjMZmBQQc49XZncR8Q8B/UXIwLGwiLnsyDOcOvH9szAyZHbOypqqku@ux/ns/DkIqyuZwkbFnOdmOfkYwltGqlm4hHGmeivNzILs5jLtKNnwm@Sd9zL96621ey82I38TxKt/FukfnJ3vfTo8jj7s9NknyRUdEP6ARfp6ol1H7YeLAk3x8hhsd6zWCFZf57ZlsyMMyvUJ/CURehRpdGo1GDSBCsgMHLWnfqteyFGuGCLDrZGaHkDGSAFWJFRqD5360R/MSbDNBO3TY7gOJ@NeSSAde/IJpH0WpSWFBcO@T5nPNA2DbuCIgyrnBNUMEbdNXf4lISNKKLsXfVQYDnVRQetqWDNmhiwlZHoTGAdsQwoAanTAirXAabBtZqYI0DW@VcK2cwj2Vdb6goiQOzD8f7UTNo9vWRCluT/WSsviMjLbL0OeyjaOQJ8Q58KFSuEojB3oDTJ@3rBvnnJH8Ds3lYwqw7tA6DjsF0TS3sHZzDPQ0P95cEK3Lg9T9g6WCC3u6Hf@eyOX12g998fQM "C (gcc) – Try It Online") [Answer] # MATLAB/Octave, 12 bytes, score 336.32 *(changed according to guidance by Giuseppe to conform with rules)* ``` @(A)std(A,1) ``` Argument with name `A` provides the lowest deviation for score, output to standard output variable `Ans` and actually written to command window. [Try it online!](https://tio.run/##y08uSSxL/f/fQcNRs7gkRcNRx1Dzf2JesUa0hbGCoaGZgoKlOZg2NDSN1fwPAA "Octave – Try It Online") `std` is a built-in function. By default it uses \$N-1\$ as demoninator but by passing `1` as second argument it's changed to \$N\$. ]
[Question] [ ## Background [**Conway chained arrow notation**](https://en.wikipedia.org/wiki/Conway_chained_arrow_notation) is a notation to express very large numbers. It consists of zero or more positive integers separated by right arrows, e.g. \$2 \to 3 \to 4 \to 5 \to 6 \$. Assuming \$p, q, a\_1, \dots, a\_n\$ are positive integers and \$X\$ is an abbreviation for a nonempty chain \$a\_1 \to a\_2 \to \dots \to a\_n\$, the rules for evaluating such a notation are as follows: $$ \begin{align} (\text{empty chain}) &= 1 \\ (p) &= p \\ p \to q &= p^q \\ X \to 1 &= X \\ X \to 1 \to p &= X \\ X \to (p+1)\to (q+1) &= X \to (X \to p\to (q+1))\to q \end{align} $$ A length-3 chain has an equivalent up-arrow notation: \$ p \to q \to r = p \uparrow^r q\$. Note that the arrow notation cannot be treated as some kind of binary operator: $$ \begin{align} 2 \to 3 \to 2 &= 16 \\ 2 \to (3 \to 2) &= 512 \\ (2 \to 3) \to 2 &= 64 \end{align} $$ More examples can be found on the Wikipedia page linked above. ## Task Given a (possibly empty) list of positive integers, interpret it as Conway chained arrow notation and evaluate it into a single number. It is OK if your program gives wrong answers for large values due to the limits (bounds and/or precision) of your language's number type, as long as the underlying algorithm is correct. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` Input => Output [] => 1 [1] => 1 [99999999] => 99999999 [5, 5] => 3125 [4, 8] => 65536 [1, 2, 4] => 1 [2, 2, 4] => 4 [2, 3, 2] => 16 [2, 4, 2] => 65536 [4, 3, 2] => 4^256 = 1.34e154 [2, 2, 3, 2] => 4 ``` [Answer] # [Haskell](https://www.haskell.org/), ~~75~~ ~~68~~ 63 bytes ``` f(q:p:x)|p^q>p,x>[]=f$q-1:f(q:p-1:x):x|1<2=f$p^q:x f[x]=x f _=1 ``` [Try it online!](https://tio.run/##PYpNCsMgEEb3OUUWWUSwgtZAKzUXEVukVRJqrPkpdZG72yGkHZjvzbyZzsxP630eTB9kHxY7mftSvYPvg53JYGJZz93rQxyZrHkgsvns6lFEkdAar2MbcWqVlq4aD1RsF2BCIq30wkDDj0iFU0lLQHmTNGelC0Whz3vB2OAG8oQ5JMcM050MyPBxJ//v/OfBfAE "Haskell – Try It Online") Takes input as a list in reversed order, since in Haskell it's easier to deal with the beginning of a list than with the end of it. Now shorter and uglier! Rules 3,4,5,6 are combined in the first line. The most important trick is realizing that `p^q==p` *iff* `p==1||q==1` (where `^` is exponentiation and we're dealing with strictly positive numbers). We check the conditions to apply rule 6 (p and q greater than 1, at least three elements in the input) and if they are valid we do so recursively. If these conditions fail we know that either there is a 1 in the first two elements or there are just two elements in total: for both of this cases `f(p^q:x)` can solve the task. The last two lines deal with inputs with less than two elements. They could be rewritten as a single line `f x=last$1:x` but the score would not change. --- Below the original solution, no golfing tricks, just beautiful Haskell code: ``` f[]=1 f[p]=p f[q,p]=p^q f(1:x)=f x f(_:1:x)=f x f(q:p:x)=f$q-1:f(q:p-1:x):x ``` [Try it online!](https://tio.run/##TYnRCoMgFIbvfYouuigwwWawCT6JuCGbkqxMs7He3p2ijR045/u///Q6Pc0w5FE7L5xfzKzvS/nyg/MmkVGHokr99CaWzEY/arL32UolKLIyKBEAEW/hGpGtKF9rYYsV4o3/SeRhlzI2lO/abF@@5iwVkhT2cgzEDndwz5jBZbjF9GALbPHpIPs5@/bQfAA "Haskell – Try It Online") [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~112~~ 107 bytes ``` ?[dz0r^+q]sZ[rd3Rd_3R^q]sE[ilfx1rq]sA[iSplfx1rLprq]sB[z2>Zz2=Ed1=Ard1=B1-rlfx3RSpr1-lfx_3Rri1+Lp1+r3R]dsfxp ``` [Try it online!](https://tio.run/##HYyxCoAwDAV/xb0IpnVVUXBzqptBHQxCwSHGpfTna3R53MHx6Mi5Q0qVbOZenwWFnKfd@U1txHCdEUSxxzDzLxN/PmCy7ZJsMxI0vegMUIoGzs8sUCrpiQQwE4MR51d6zsg526Iu7As "dc – Try It Online") [Or verify all the test cases.](https://tio.run/##RY9Pa4NAEMXv@yke0puYdl0DLURLAvYUKJhbliRYd60LVrdjoUH63e0kETKHH@89hvnzUQ7NVJU/yOCp/6Tya2EqrFZB/v4WTK/ajE90DL8Pw16TUYU5qeLILteurc@SWK612/mr2fqL3@gxzvZjnOZGpmtibGRE3KCKnScZseIh5GS49TIkVRzMUJ/9xAuF@G1ca0G2NGhdZwVgegZgq6ZH1CF4uORIMwT3/BYG@APfHtVYPN5/uY7o7CSkeJlLLLEUCZ6FRIxExDMVYmbCTGZ9y/4B) The input is on stdin (a line with space-separated numbers), and the output is on stdout. --- **How it works:** dc is a stack-based language. The recursive macro `f` does the Conway chained-arrow calculation, but the stack is treated differently from what you usually see: 1. The input to `f` is the **entire stack** when the call is made. (So `f` essentially takes a variable number of arguments.) 2. If the stack at the time of call is $$a\_1 \; a\_2 \; \dots \; a\_n$$ (with the top of the stack on the right), `f` will compute the value of $$a\_1 \to a\_2 \to \dots \to a\_n$$ and push it on top of the stack, **but it leaves the arguments on the stack also.** So `f` turns the stack $$a\_1 \; a\_2 \; \dots \; a\_n$$ into $$a\_1 \; a\_2 \; \dots \; a\_n \; [\text{ArrowValue}(a\_1 \; a\_2 \; \dots \; a\_n)]$$ where I've written \$\;[\text{ArrowValue}(a\_1 \; a\_2 \; \dots \; a\_n)]\;\$ for the value of \$\;a\_1 \to a\_2 \to \dots \to a\_n.\$ There are several auxiliary macros as well. All the usual complex control structures other languages have (loops, conditionals, functions) are implemented in dc using macros. --- Note that dc produces a few error messages or warnings due to the golfing tricks used, but they don't interrupt program execution, and the messages are just written to stderr. Examples of these: duplicating when there's nothing on the stack, adding when there's only one item on the stack, or setting the input base to an illegal value. The code also makes use of the fact that we can distinguish positive numbers from \$0\$ by whether the power \$0^x\$ is \$0\$ or \$1.\$ --- Here's a detailed summary of the program's operation, updated for the revised, shorter answer. ``` ? Read a line of space-separated numbers, written in the usual Conway chained-arrow order, pushing them onto the stack in turn. (The chained arrow sequence will start at the bottom of the stack, since that's pushed first, and will end at the top of the stack, since that's pushed last.) MACRO Z Macro Z will only be called when the stack either is empty or has just one item p on it. We'll analyze both possibilities. [ Start macro. Stack: Empty or p d Duplicate. Stack: Empty or p p z Push the size of the stack. Stack: 0 or p p 2 0 Push 0. Stack: 0 0 or p p 2 0 r Swap. Stack: 0 0 or p p 0 2 ^ Exponentiate. Stack: 1 or p p 0 + Add top 2 items if they exist. Stack: 1 or p p q Exit this macro and the macro which called it. ]sZ End macro and name it Z. Summary of Z: Turn: Empty stack Into: 1 and Turn: p into: p p MACRO E [ Start a macro. Assume the stack is: ... p q (top on right). r Swap. Stack: ... q p d Duplicate. Stack: ... q p p 3R Rotate left the top 3 items. Stack: ... p p q d Duplicate. Stack: ... p p q q _3R Rotate right the top 3 items. Stack: ... p q p q ^ Exponentiate. Stack: ... p q p**q q Exit this macro and the macro which called it. ]sE End the macro and name it E. Summary of E: Turn: ... p q into: ... p q p**q MACRO A [ Start a macro. Assume the stack is: ... p (top on right). i Discard the top of stack. (Actually make it the new input radix just because dc wants a place to put it.) Stack: ... lfx Call f recursively. Stack: ... ArrowValue(...) 1 Push 1. Stack: ... ArrowValue(...) 1 r Swap. Stack: ... 1 ArrowValue(...) q Exit this macro and the macro which called it. ]sA End the macro and name it A. Summary of A: Turn: ... p into: ... 1 ArrowValue(...) MACRO B [ Start a macro. Assume the stack is: ... p q (top on right). i Discard top of stack (by storing it as the input radix). Stack: ... p Sp Pop p off the stack and push it onto stack p. Stack: ... lfx Call f recursively. Stack: ... ArrowValue(...) 1 Push 1. Stack: ... ArrowValue(...) 1 r Swap. Stack: ... 1 ArrowValue(...) Lp Pop the old value of p from stack p. Stack: ... 1 ArrowValue(...) p r Swap Stack: ... 1 p ArrowValue(...) q Exit this macro and the macro which called it. ]sB End the macro and name it B. Summary of B: Turn: ... p q into: ... 1 p ArrowValue(...) MACRO f [ Start a macro. z Push the stack size. 2> If the stack size was 0 or 1, O then call macro Z and return from f. In this case, we've turned ... into ... 1 or we've turned ... p into ... p p z2=E If the stack size was 2, then call macro E and return from f. In this case, we've turned ... p q into ... p q p**q If we get here, the stack size is at least 3. d1=A If the item at the top of the stack == 1, then call macro A and return from f. In this case, we've turned ... 1 into ... 1 ArrowValue(...) If we get here, the stack size is at least 3 and the item at the top of the stack isn't 1. Stack: ... p q r where r != 1. r Swap. Stack: ... p r q d1=B If the item at the top of the stack == 1, then call macro B and return from f. In this case, we've turned ... p 1 r into ... p 1 r ArrowValue(... p) If we get here, the stack size is at least 3, neither of the items at the top of the stack is 1, and we've already gone from Stack: ... p q r to Stack: ... p r q 1- Subtract 1. Stack: ... p r q-1 r Swap. Stack: ... p q-1 r lfx Call f recursively. Stack: ... p q-1 r [ArrowValue(... p q-1 r)] 3R Rotate left the top 3 items on the stack. Stack: ... p r [ArrowValue(... p q-1 r)] q-1 Sp Pop q-1 off the stack and push it onto stack p. Stack: ... p r [ArrowValue(... p q-1 r)] r Swap. Stack: ... p [ArrowValue(... p q-1 r)] r 1- Subtract 1. Stack: ... p [ArrowValue(... p q-1 r)] r-1 lfx Call f recursively. Stack: ... p [ArrowValue(... p q-1 r)] r-1 [ArrowValue(... p ArrowValue(... p q-1 r) r-1)] _3R Rotate right the top 3 items on the stack. Stack: ... p [ArrowValue(... p ArrowValue(... p q-1 r) r-1)] [ArrowValue(... p q-1 r)] r-1 r Swap: Stack: ... p [ArrowValue(... p ArrowValue(... p q-1 r) r-1)] r-1 [ArrowValue(... p q-1 r)] i Discard the top item. Stack: ... p [ArrowValue(... p ArrowValue(... p q-1 r) r-1)] r-1 1+ Add 1 Stack: ... p [ArrowValue(... p ArrowValue(... p q-1 r) r-1)] r Lp Load the old value of q-1 from stack p. Stack: ... p [ArrowValue(... p ArrowValue(... p q-1 r) r-1)] r q-1 1+ Add 1. Stack: ... p [ArrowValue(... p ArrowValue(... p q-1 r) r-1)] r q r Swap. Stack: ... p [ArrowValue(... p ArrowValue(... p q-1 r) r-1)] q r 3R Rotate left the top 3 items on the stack. Stack: ... p q r [ArrowValue(... p ArrowValue(... p q-1 r) r-1)] ] End the macro, dsf save it on the stack, and name it f. Summary of f: Turn: ... into: ... ArrowValue(...) x Execute f. p Print the desired value, which is now at the top of the stack. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/) -m32 -lm, ~~159~~ ~~150~~ ~~137~~ 136 bytes ``` f(a,b,u,t)int*a,*b;{t=a-b?b-a-1?*a-1?b-a-2?a[1]-1?t=a[1]--,a[1]=f(a,b),--*a,u=f(a,b),++*a,a[1]=t,u:f(a+2,b):pow(a[1],*a):f(a+1,b):*a:1;} ``` [Try the test cases online!](https://tio.run/##dc/daoMwGAbg817FR2Gg5stB1MKmSGnr/y10PYgWi9A/Nt0OSm99WaJrMbAIMXnf5CGkpoe6FqKxOFbYY2e3587h6FThrYs4rZYV5ZQtHfVTS3fJt2wng9xVC4pqigZvI6XS9o9EiEzDdod9IEviyjq4Xr4t1aLD7aFlqnV4wMK7kNfDibdn6@vS7u0ZwE0OUG0pSajC9UPGxpq/7N/Pc4TGKhFK2w5nj5Or7Q4iuLH7/8dXCCvCpmA9gre/z@DWCGvdbUa3QFgYzAZhQ9ypiUfziuAbTIwQ6yYZjY/gIpielSAkxJuydMpcA0sRUp1lI5PGM7MMIdNZ/mS@meUIuc4K7TazLBAK4isJcBc/dXPkh09BT54r6PH0Cw "C (gcc) – Try It Online") (except for `[4, 3, 2]`, which overflows). *9 bytes off thanks to ceilingcat!* *And saved 1 more byte thanks to ceilingcat too.* --- Input is taken as an array of ints in reverse order, and is passed as a [pointer to the beginning and a pointer to (the location immediately after) the end](https://codegolf.meta.stackexchange.com/a/14972/59825). --- **The following applies to the previous version of the program. The current version uses exponentiation from the C math library. The compilation flag `-m32` is now used so that the usual `#include <math.h>` line can be omitted.** C doesn't have exponentiation built in, so the previous version handled that by changing the 3rd and 4th rules of the recursive definition from $$ \begin{align} p \to q &= p^q \\ X \to 1 &= X \\ \end{align} $$ to $$ \begin{align} \quad\quad\quad\quad\quad X \to 1 &= X \\ p \to q &= (p \to q-1)\*p \\ \end{align} $$ [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~57~~ ~~49~~ ~~48~~ 46 [bytes](https://github.com/abrudz/SBCS) *Saved 8 bytes thanks to @[Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)!* ``` {3>≢w←⍵↓⍨⊃⍸1≠⍵:*/⌽w⋄(∇(⊃w-1),,∘(2↓w))⍣(1⊃w)⊢1} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OAZLWx3aPOReVA1qPerY/aJj/qXfGoq/lR7w7DR50LgEJWWvqPevaWP@pu0XjU0a4BlCvXNdTU0XnUMUPDCKi@XFPzUe9iDUOQhOajrkWGtSALgMalKTzqXcMFYxvDWaYKpnC2kYKxghEKz4TrUe9cBZiICVDM6D8A "APL (Dyalog Unicode) – Try It Online") A monadic function that must be given the input in reverse. Now also requires zero-indexing. This is slightly different from Conway's definition, but I *think* it's equivalent. If anyone can find a more math-y proof, that'd be great. This is how Conway described his chained arrow notation: > > Our own "chained arrow" notation names some even larger numbers. In this, a^^...^^b (with c arrows) is called a->b->c. > > > a->b-> ... ->x->y-> 1 is another name for a->b-> ... ->x->y > > > and a ... x->y->(z+1) is defined to be > > > a ... x if y = 1, > > > a ... x->(a...x)->z if y = 2, > > > a ... x->(a...x->(a...x)->z)->z if y = 3 > > > and so on. > > > No one likes ones (and \$X\to 1\$ evaluates to \$X\$), so we first remove leading ones using `⍵↓⍨⊃⍸1≠⍵`. `⊃⍸1≠⍵` is the first (`⊃`) index where (`⍸`) there isn't a 1 (`1≠⍵`), and we drop (`↓`) until that index. The result of that is assigned to `w` to reuse. We can replace the first rule from here with the first three rules from the question. So if `w` has 0, 1, or 2 elements (`3>≢w`), we can fold over it with exponentiation (`*/⌽w`), because according to APL's rules, `*/x` is `x` and `*/⍬` (`⍬` is an empty set) is 1. We do have to reverse (`⌽`) `w` again, though, because it was reversed in the first place. The second part of the function takes care of cases when `w` is in the form \$X \to y \to (z+1)\$. It's essentially \$y\$ applications of the function \$\lambda a. X \to a \to z\$, starting, with 1. If \$y\$ and \$z\$ are both 1, then this becomes \$X \to 1 \to 1\$. Next iteration, `w` will be just \$X\$. If only \$y\$ is 1, then it becomes \$X \to 1 \to z\$. After that, it becomes \$X \to 1 \to (z-1)\$, then \$X \to 1 \to (z-2)\$, and so on until it reaches \$X \to 1 \to 1\$, which gives us \$X\$. So this satisfies the fifth rule in the question (\$X \to 1 \to p = X\$). If \$y\$ is greater than 1, this becomes $$ X \to (X \to (... (X \to (X \to (1) \to z) \to z) ...) \to z) \to z\\ = X \to (X \to (... (X \to (X) \to z) ...) \to z) \text{ (by question's 5th rule)} $$ The second is Conway's definition (there are \$y\$ copies of \$X\$ and \$y-1\$ copies of \$z\$). In the first, there are \$y\$ copies of both \$X\$ and \$z\$. [Answer] # [J](http://jsoftware.com/), 90 79 75 bytes ``` (1:`]`(^~/)`(2&}.$:@,~<:@{.,[:$:]-2=#\)@.(3<.#))`($:@}.~1+i.&1)@.(1 e.2&{.) ``` [Try it online!](https://tio.run/##ZZDLSsRAEEX3/RWFGZJuzJRWP4IW0xAUXIkLt5oxIJlRN35AnPx67MfEZ0Mt7qnLKei3@QSrPXiGCmo4Bw6zRri@v72ZJXHf9XI7nale6vKAK27racPtiPUDr7hba188qhal2WChQikUDjjR6SuWFDnBgLocUc1K3F0h6CyMPimfFmU0cj1lZQhFtPZhn3RdEvnQHpcTnNHI6uu4EDuPsG8/UIjh@eUdCDzsoKp@Jsrh8vgSW0JeGdIuYQcuk8Y50yRk4eKXDDTYDGwC@htQcyQG9F9NKIXJNEpDBeLf2K12sUFo7EDunzqq5k8 "J – Try It Online") Takes input in reverse order. I suspect there's room for more golfing yet. I may return to it tomorrow. [Answer] # Rust, 161 bytes ``` fn f(s:&[u32])->u32{match s{[]=>1,[x]=>*x,[p,q]=>p.pow(*q),[x@..,1]=>f(x),[x@..,1,_]=>f(x),[x@..,p,q]=>f(&[x,&[f(&[x,&[p-1],&[*q]].concat())],&[q-1]].concat())}} ``` Uses Rusts pattern matching. The last case is a little verbose, because there's no spread operator. [Try it](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&code=fn%20f(s%3A%20%26%5Bu32%5D)%20-%3E%20u32%20%7B%0A%20%20%20%20match%20s%20%7B%0A%20%20%20%20%20%20%20%20%5B%5D%3D%3E1%2C%0A%20%20%20%20%20%20%20%20%5Bx%5D%3D%3E*x%2C%0A%20%20%20%20%20%20%20%20%5Bp%2Cq%5D%3D%3Ep.pow(*q)%2C%0A%20%20%20%20%20%20%20%20%5Bx%40..%2C1%5D%3D%3Ef(x)%2C%0A%20%20%20%20%20%20%20%20%5Bx%40..%2C1%2C_%5D%3D%3Ef(x)%2C%0A%20%20%20%20%20%20%20%20%5Bx%40..%2Cp%2Cq%5D%3D%3Ef(%26%5Bx%2C%20%26%5Bf(%26%5Bx%2C%26%5Bp-1%2C*q%5D%5D.concat())%5D%2C%20%26%5Bq-1%5D%5D.concat())%0A%20%20%20%20%7D%0A%7D%0Afn%20main()%20%7B%0A%20%20%20%20assert_eq!(1%2C%20f(%26%5B%5D))%3B%0A%20%20%20%20assert_eq!(1%2C%20f(%26%5B1%5D))%3B%0A%20%20%20%20assert_eq!(99999999%2C%20f(%26%5B99999999%5D))%3B%0A%20%20%20%20assert_eq!(3125%2C%20f(%26%5B5%2C%205%5D))%3B%0A%20%20%20%20assert_eq!(65536%2C%20f(%26%5B4%2C%208%5D))%3B%0A%20%20%20%20assert_eq!(1%2C%20f(%26%5B1%2C%202%2C%204%5D))%3B%0A%20%20%20%20assert_eq!(4%2C%20f(%26%5B2%2C%202%2C%204%5D))%3B%0A%20%20%20%20assert_eq!(16%2C%20f(%26%5B2%2C%203%2C%202%5D))%3B%0A%20%20%20%20assert_eq!(65536%2C%20f(%26%5B2%2C%204%2C%202%5D))%3B%0A%20%20%20%20%2F%2F%20assert_eq!(1%2C%20f(%26%5B4%2C%203%2C%202%5D))%3B%20%2F%2F%20panics%20because%20of%20overflow%0A%20%20%20%20assert_eq!(4%2C%20f(%26%5B2%2C%202%2C%203%2C%202%5D))%3B%0A%7D) on the rust playground. ## Readable version ``` fn f(s: &[u32]) -> u32 { match s { []=>1, [x]=>*x, [p,q]=>p.pow(*q), [x@..,1]=>f(x), [x@..,1,_]=>f(x), [x@..,p,q]=>f(&[x, &[f(&[x,&[p-1,*q]].concat())], &[q-1]].concat()) } } ``` [Answer] # JavaScript (ES7), ~~78~~ 77 bytes Takes the list in reverse order. ``` f=([q,p,...a])=>a+a?f(--q?--p?[q,f([++q,p,...a]),...a]:a:[p,...a]):p**q||q||1 ``` [Try it online!](https://tio.run/##Xc3dioMwEAXg@z7F3BlrTIkm0nWxXvUpgguDJt2WYvxZetV3d6PVKh0Cwe@cODd8YF921@YvrG2lh8FkRLW0oYwxLPzshAHmhoRhm4dhk7vIEBUEa@N1pZiqRdJmv2@fT3f48K12AKqgsM7hAHxEvtUFv@aZMofL95hJCvL9xmUxj@TogsJx64mUcTJtoBBREK9s2RB9oJgxdr42k1nFVt8/Fh918RPJBDLgLBaaS7HumWrznmLHjO3OWP4ShOwEpa17e9fsbi/EUx4EgOxmrzXxqOezBqtzXZGj79wrIIWxYAiyTj9012viuxn@AQ "JavaScript (Node.js) – Try It Online") ### With BigInt support (78 bytes) This version accepts either a list of *Numbers* or a list of *BigInts* and returns a value of the same type. ``` f=([q,p,...a])=>a+a?f(--q?--p?[q,f([++q,p,...a]),...a]:a:[p,...a]):p?p**q:q||1 ``` [Try it online!](https://tio.run/##Xc3BjoIwEAbgu08xN4qUmkJLXDZIsomHfYaGTSZQXIwLBYwn350tCGKcS9Pv/9s54w37vKvM1a@bQg9DmRDVUkMZY5i5yQE9TEvi@23q@ya1UUmU562NxxFjrBaJTWq22zZu73c@fKoNgMoorLPbAR@Rv@qCH/NMmcXlPmaSgny@sVnIAzm6oLB/9UjKMJo2UAgoiEe2bAjeUMwYWl@b0aziVZ8fi7e6@AlkBAlwFgrNpVj3TLV5T7ZhZdMdMf8lCMkB8qbum4tml@ZEHOWAB8jOTVUThzouM1gc64LsXetOBjGMhZIg@0NDvqrTd311Wadvuus1ce0M/w "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~117~~ ~~112~~ 111 bytes ``` f=lambda x:(len(x)<3)*reduce(lambda a,b:b**a,x,1)or f((1in x[:2])*x[1:]or[x[0]-1,f([x[0],x[1]-1]+x[2:])]+x[2:]) ``` [Try it online!](https://tio.run/##fY5RC4MgFIXf9yt8VHcHqRkk65eID7UVG2wV0cD9@nYNt1qDgaDnu@eeY/8cL10rp6kpbuW9OpfEG3qrW@rZUTE@1OfHqaZxVEJlKs5L8CBYN5CGUnFtibdGOsa9FcZ1g/U2cQcBDZ1fgBil23srjWPve/KFVaDdrh@u7UioDQ5m0cg5xcCwgYxhQrT8@Up0YKNjRSEWKTZaBi1XOk9mkicL0zC71MomQIIKMF@YQraNT4FIPIGmqxIgKlKRfeE04kxrlW0X0jmGc6l/Rp@S6QU "Python 2 – Try It Online") Takes input in reverse order. A recursive function that takes in a list of positive integers and returns a single number. In order to save bytes, we combine the 3 base cases into one expression: ``` (len(x)<3)*reduce(lambda a,b:b**a,x,1) ``` which returns either \$1\$, \$p\$, or \$p^q\$. --- The recursive cases are also mashed together via: ``` f((1in x[:2])*x[1:]or[x[0]-1,f([x[0],x[1]-1]+x[2:])]+x[2:]) ``` which becomes `f(x[1:])` when `x[0]` is \$1\$ or `x[1]` is \$1\$, and becomes `f([x[0]-1,f([x[0],x[1]-1]+x[2:])]+x[2:])` otherwise. [Answer] # [Erlang (escript)](http://erlang.org/doc/man/escript.html), 111 bytes Port of the Haskell answer. The last case seems to time out. ``` f([])->1;f([P])->P;f([1|X])->f(X);f([Q,P])->math:pow(P,Q);f([_,1|X])->f(X);f([Q,P|X])->f([Q-1,f([Q,P-1|X])|X]). ``` [Try it online!](https://tio.run/##ZY7NCoMwDIDvfQrxVCEd1FXYuuEz6E3oypChW4d/aMGL7@6abm6HBdp8/ZI2rcam7O6smm6jGexK1poqHbGUnxxkSBkSXwrkmhYRHnPwpba0Dzn0M80g9/4K/42bUDnj8FbMd@HarW1pOhwZsJQELhoz2Uk@e2fDSxeClxjK9HIeja2owtfd/aU4M0WUBqI4bsdPICeQYDqAwCQgBr5BjBDDfgPxM@Jbco5o7Ye7T74A "Erlang (escript) – Try It Online") [Answer] # [Factor](https://factorcode.org/), 144 bytes ``` :: g ( x -- y ) x llength 3 < [ x 1 [ swap ^ ] foldl ] [ x car 1 = [ x cdr g ] [ 1 x cadr [ x cdr cdr cons x car 1 - swons g ] times ] if ] if ; ``` [Try it online!](https://tio.run/##VVDBTsMwDL3nK94RDp3UrkjQAddpl10QJ1SkKEu3iCwtSSY2TXx7eSkZaLHy8uznWLY7qWLvx9eX1XrZ4EN7py2sCTHA9kragL2Muwlm3cGpaHoXMHgd42nwxkUR9OdBO6UDFmK1bhCUl1HtxqbBFjc4oihwwq04wlrttiw2xyPeKJTE8CUHvKNF19uNRSuSoKSn@DQlqY1nnRQvJ4XuJTzd1M7lR8FyyWc@otmzpRamEwmwGM8441uAWOb3IZ/s3tF@2T3qzGpUf@mJV5lXnOKf11fx@iqHCo2T5j09p@2yxRmb05KL@gE "Factor – Try It Online") Takes a linked list in reverse order. Uses the algorithm described in [user's APL answer](https://codegolf.stackexchange.com/a/215515/78410). Using linked lists is shorter than using arrays when the code involves a lot of dissection at the start (and you don't need sophisticated sequence operations): ``` first (5) > car (3) rest (4) > cdr (3) second (6) > 1 nth (5) > cadr (4) prefix (6) > cons (4) swap prefix (11) > swons (5) unclip (6) = uncons (6) unclip swap (11) > unswons (7) ``` ### How it works ``` :: g ( x -- y ) ! Takes a list `x` and returns a number x llength 3 < [ ! If x has 2 or fewer numbers... x 1 [ swap ^ ] foldl ! Reduce by ^ on reversed arguments ] [ ! Otherwise `x` is in the form of `X->y->z` x car 1 = [ ! If z is 1... x cdr g ! Remove z(=1) and recurse ] [ ! Otherwise... 1 ! Setup the initial value of 1 x cadr ! Setup the loop count of y [ x cdr cdr cons ! Build y':X x car 1 - swons g ] ! Build z-1:y':X times ! Iterate the above function y times to 1 ] if ] if ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~68~~ 66 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` "D©g2‹iPë`i)Y.Vëi)Y.Vë)\®`®g<imëX®šUs<s)Y.VXćsUDgÍsŠǝRć<šRY.V"DV.V ``` This was pretty hard in a stack-based language.. [Try it online](https://tio.run/##yy9OTMpM/f9fyeXQynSjRw07MwMOr07I1IzUCzu8Gkppxhxal3BoXbpNZu7h1RGH1h1dGFpsUwySizjSXhzqkn64t/joguNzg4602xxdGAQUV3IJ0wv7/z/aSMdIx1jHKBYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/JZdDK9ONHjXszAw4vDohUzNSL@zwaiilGXNoXcKhdek2mbmHV0ccWnd0YWixTTFILuJIe3GoS/rh3uKjC47PDTrSbnN0YRBQXMklTC/sv45mzP/o6FidaEMgtoQCINNUxxRImuhYgKR0jHRMgLQRnDbWMQLTJmDaBM6HyMQCAA). **Explanation:** ``` " "# Start a string we can execute as 05AB1E code # to mimic recursive calls: D # Duplicate the list at the top of the stack # (which will be the (implicit) input at the start) © # Store it in variable `®` (without popping) g2‹i # Pop one, and if its length is smaller than 2: P # Take the product # ([] → 1; [p] → p) ë # Else (the length is >= 2): ` # Dump the contents of the list onto the stack i # Pop the top value, and if it's a 1: ) # Wrap the remaining values into a list Y.V # And do a recursive call # (p=1 for [...,q,p] → recursive call to [...,q]) ë # Else: i # Pop the second top value, and if it's a 1: ) # Wrap the remaining values into a list Y.V # And do a recursive call # (q=1 for [...,q,p] → recursive call to [...]) ë # Else: )\ # Discard everything on the stack ®` # Dump the contents of `®` onto the stack again ®g<i # If the length of `®` is 2: m # Take the power of the two values # ([p,q] → p^q) ë # Else (the length is >= 3): X®šU # Prepend `®` to list `X` # (`X` is 1 by default, but that doesn't matter; # it'll become [[...,p,q],1] and the 1 is ignored) s<s) # Decrease the second value from the top by 1 Y.V # And do a recursive call # ([...,p,q] → recursive call to [...,p-1,q], # let's call its result `R` for the moment) Xć # Extract the first list from variable `X` again, sU # and pop and store the remaining values as new `X` DgÍ # Take its length - 2 (without popping by duplicating first) # (let's call this length-2 `I` for the moment) sŠ # Swap & triple-swap ([...,R,[...,p,q],I] → [...,[...,p,q],R,I]) ǝ # Insert value `R` into the list at (0-based) index `I` # ([...,[...,p,q]] → [...,[...,R,q]]) Rć<šR # And decrease the last value in the top list by 1 # ([...,[...,R,q]] → [...,[...,R,q-1]]) Y.V # And do a recursive call again " "# End the string of 05AB1E code DV # Store a copy of this string in variable `Y` .V # Execute it as 05AB1E code (`Y.V` is how we can do recursive calls) # (after which the result is output implicitly) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~40~~ 38 bytes ``` L?tJtby?}1<b2J+,thby+,hbthJtJttb|^F_b1 ``` [Try it online!](https://tio.run/##RYwxCsMwDEX3nkKrSYbYsgyGQrYMpjcopKDJYwtaDO3ZXTl200n//cfXs0iu9bZKEi7rx17ZpWmWzGWaM0tOKoTf@/ZgW19Q7gbspV37C86A6yEuGuNyAIH2OASQCuozcIAG4gGocP7xCrrxY4INbBjkGwUiDKf2Bnat6d/0ff0C "Pyth – Try It Online") Takes input in reverse order. `L` defines a recursive function named `y` that takes in a list `b` of positive integers and returns a single number. Similarly to my Python answer, the base cases are combined into one expression: ``` |^F_b1 ``` in which `^F_b` folds the exponentiation function `^` over `b` in reverse. If `b` has 2 elements \$(q,p)\$ this will return \$p^q\$, if `b` has 1 element \$(p)\$ it will return \$p\$, and if `b` is empty it will return 0 (`| .. 1` turns the 0 into 1, as needed) --- The recursive cases are handled by: ``` y?}1<b2J+,thby+,hbthJtJttb ``` This part is a pretty straightforward translation of the recursive rules. If either of the first two elements of `b` are 1 it calls `y` on `tb` (equivalent to `b[1:]` in Python)\*. Otherwise, the formula \$X \to (X \to p\to (q+1))\to q\$ is passed recusively to `y`. \*The rule \$X \to 1 \to p = X\$ thus takes two steps instead of one, but doing it this way saves a few bytes. [Answer] # Java, 282 chars ``` interface c{int n[]=new int[99];static void main(String[]a){int i=0,j=a.length;for(;i<j;)n[i]=new Integer(a[i++]);System.out.print(j<1?1:j<2?n[0]:c(j));}static int c(int j){j-=n[j-2]<2?2:n[j-1]<2?1:0;if(j<3)return(int)Math.pow(n[0],n[1]);n[j-2]--;n[j-2]=c(j);n[j-1]--;return c(j);}} ``` Readable version: ``` interface c{ int n[]=new int[99]; static void main(String[]a){ int i=0,j=a.length;for(;i<j;)n[i]=new Integer(a[i++]); System.out.print(j<1?1:j<2?n[0]:c(j)); } static int c(int j){ j-=n[j-2]<2?2:n[j-1]<2?1:0; if(j<3)return(int)Math.pow(n[0],n[1]); n[j-2]--; n[j-2]=c(j); n[j-1]--; return c(j); } } ``` [Answer] # [Clojure](https://clojure.org/), 117 bytes ``` (defn f([]1)([q]q)([q p](Math/pow p q))([q p & x](if(== p(f q p))(apply f p x)(apply f(dec q)(apply f q(dec p)x)x)))) ``` [Try it online!](https://tio.run/##TZDhCsIgFIX/7ynOr3AwCjcdRdgb9ARiEGtSMTZdRevp6zY32RXE853rkWvVdPdXX3@/7FLbFpZpw1OmvfH/Hc6w4/l53bjuDQefBogVBsNulikFxywIkXN2rvnAkj1EQakVXYueH4FLB1pU9Gr3qD30AJ1og706gCeax9NuqgBmlWiZQQZW8FwmWmTYBl1KWZQUkSHPIGJQvtRi1AWhyS9HICKYQsSySZxyWUKBrwtRcynmzLFjzjXM9bf22bSIP9D/BwzT/gA "Clojure – Try It Online") Handles all test cases, takes input arguments in reverse order. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~67~~ 66 bytes ``` f[x__,1,_:0]=f@x f[x___,p_:1,q_:1]=If[x<1,p^q,f[x,f[x,p-1,q],q-1]] ``` [Try it online!](https://tio.run/##RYnBCoMwEETv@Q2hpxEaG6GVWnLtrdCjbEOQSj0oSfEgBP31NIkFF3bmMW/Q0@c96KlvtfddMysFDlUdqe7kzNKgYFTFYUNQfQ/TlcO8LAKlN3mQBJtzIv/49uPUZPmtkzKjw/ps9bg65hYwx2Nc/he5RBlL4Jw0CogIxQ4nFBuIDcS@bJIt/gc "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Scala](https://www.scala-lang.org/), ~~156~~ 141 bytes ``` val f:Seq[Int]=>Int={case x if x.size<3=>(x:\1.0)(math.pow(_,_))toInt case 1::x=>f(x)case p::1::x=>f(x)case q::p::x=>f(q-1::f(q::p-1::x)::x)} ``` [Try it in Scastie](https://scastie.scala-lang.org/8Zz4FyQzS120VPE5CEkpYg) Note: Input must be a reversed `List`. If it's not reversed, the algorithm won't work correctly, and if it's not a `List`, there'll be a MatchError. I hate that `math.pow(_,_)` works but just `math.pow` would need the first argument to be a `Double`. ]
[Question] [ One day you awake only to find yourself caught in an array. You try to just walk out of there, taking one index at the time, but it seems there are other rules: The array is completely filled with natural numbers. * If you find yourself on an index `n`, you go to the index `array[n]`, except: * If you find yourself on an index `n` which is a prime number, you take `array[n]` steps back Example: You start on index `4`, in this array (start index is 0): ``` array = [1,4,5,6,8,10,14,15,2,2,4,5,7]; -----------------^ you are here ``` As the value of the field you are on is `8`, you go to the index `8` as the first step. The field you land on contains the value `2`. You then go to index `2` as your second step. As`2`is a prime number, you take 5 steps back, which is your third step. As there is no index `-3`, you successfully escaped the array in a total of 3 steps. **Your task is:** To write a program or function, which accepts an array and a start index as parameter, and outputs the amount of steps to escape the array. If you can't escape the array (e.g. `[2,0,2]` with start-index `2` => you constantly go from index `2` to `0`), output a falsy value. You may use one-based indexing or zero-based indexing, but please specify which you use. **Test cases** Input: `[2,5,6,8,1,2,3], 3` Output: `1` Input: `[2, 0, 2], 2` Output: `false` Input: `[14,1,2,5,1,3,51,5,12,3,4,41,15,4,12,243,51,2,14,51,12,11], 5`; Output: `6` The shortest answer wins. [Answer] # Python, ~~161~~ 138 bytes [Credits](https://codegolf.stackexchange.com/a/3133/48934) for factorial. ``` g=lambda x:0**x or x*g(x-1) f=lambda a,i,n=0,l=[]:(i<0)+(i>=len(a))and n or(0 if i in l else f(a,[a[i],i-a[i]][i and-g(i-1)%i],n+1,l+[i])) ``` [Ideone it!](http://ideone.com/EjAD8T) ### How it works [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem) is used for prime checking. Loop detection by storing seen indices to an array (`l`) and checking whether current index is in `l`. [Answer] # Python, 107 bytes ``` import sympy f=lambda a,i,n=0:0if n>len(a)else f(a,[a[i],i-a[i]][sympy.isprime(i)],n+1)if 0<=i<len(a)else n ``` Usage: `f(list, start)` ex: `f([2,5,6,8,1,2,3], 3)` Returns `0` for loops (detected when `n > len(a)`) [Answer] # Matlab, 138 bytes This a straighforward approach, using 1-based indices because Matlab uses 1-based indices by default. To count the number of steps we use a `for` loop counting from 1 to infinity(!). For the case were we cannot escape the array, we use a vector `v` to keep track of which entries we already visited. If we visit an entry twice, we know we are stuck in an unescapeable cycle. To see check whether we are outside of an array, we use the `try/catch` structure, which also catches out of bounds exceptions. ``` function r=f(a,i);v=a*0;v(i)=1;for k=1:Inf;if isprime(i);i=i-a(i);else;i=a(i);end;try;if v(i);r=0;break;end;v(i)=1;catch;r=k;break;end;end ``` [Answer] ## 05AB1E, 32 bytes ``` ï[U¯Xåi0,q}²gL<Xå_#X²XèXDˆpi-]¯g ``` **Explanation** ``` ï # explicitly convert input to int [ ] # infinite loop U # store current index in X ¯Xåi0,q} # if we've already been at this index, print 0 and exit ²gL<Xå_# # if we've escaped, break out of infinite loop X²XèXDˆpi- # else calculate new index ¯g # print nr of indices traversed ``` [Try it online](http://05ab1e.tryitonline.net/#code=w69bVcKvWMOlaTAscX3CsmdMPFjDpV8jWMKyWMOoWETLhnBpLV3Cr2c&input=NQpbMTQsMSwyLDUsMSwzLDUxLDUsMTIsMyw0LDQxLDE1LDQsMTIsMjQzLDUxLDIsMTQsNTEsMTIsMTFd) [Answer] ## Pyth, 31 Bytes ``` KlQ%tl-.u?}NUK?P_N-N@QN@QNKQEKK ``` [The test cases](http://pyth.herokuapp.com/?code=KlQ%25tl-.u%3F%7DNUK%3FP_N-N%40QN%40QNKQEKK&input=%5B2%2C5%2C6%2C8%2C1%2C2%2C3%5D%0A3&test_suite=1&test_suite_input=%5B2%2C5%2C6%2C8%2C1%2C2%2C3%5D%0A3%0A%5B2%2C+0%2C+2%5D%0A2%0A%5B14%2C1%2C2%2C5%2C1%2C3%2C51%2C5%2C12%2C3%2C4%2C41%2C15%2C4%2C12%2C243%2C51%2C2%2C14%2C51%2C12%2C11%5D%0A5&debug=1&input_size=2) It uses zero to indicate a false value, the number of hops otherwise. [Answer] # JavaScript (ES6), 100 Index base 0. Note: this function modifies the input array ``` (a,p)=>eval("for(s=0;1/(q=a[p]);++s,p=p>1&&p%i||p==2?p-q:q)for(a[p]=NaN,i=1;p%++i&&i*i<p;);q==q&&s") ``` *Less golfed* ``` (a,p)=> { for(s = 0; 1/ (q = a[p]); ++s) { a[p] = NaN; // mark visited position with NaN to detect loops for(i = 1; p % ++i && i*i < p;); // prime check p = p > 1 && p % i || p == 2 ? p-q : q; } return q==q && s // return false if landed on NaN as NaN != NaN } ``` **Test** ``` F= (a,p)=>eval("for(s=0;1/(q=a[p]);++s,p=p>1&&p%i||p==2?p-q:q)for(a[p]=NaN,i=1;p%++i&&i*i<p;);q==q&&s") ;[ [[2,5,6,8,1,2,3], 3, 1] ,[[2, 0, 2], 2, false] ,[[14,1,2,5,1,3,51,5,12,3,4,41,15,4,12,243,51,2,14,51,12,11], 5, 6] ].forEach(t=>{ var [a,b,k]=t, i=a+' '+b,r=F(a,b) console.log(r==k?'OK':'KO',i+' -> '+r) }) ``` [Answer] # JAVA, ~~229~~ 218 Bytes ``` Object e(int[]a,int b){Stack i=new Stack();int s=0;for(;!(a.length<b|b<0);s++){if(i.contains(b))return 1>2;i.add(b);b=p(b)>0?b-a[b]:a[b];}return s;}int p(int i){for(int j=2;j<i/2;j++)if(i%j<1)return 0;return i<2?0:1;} ``` Thanks to Kevin, 11 bytes bites the dust. [Answer] # CJam, 44 bytes Expects `index array` on the stack. ``` :G\{_G,,&{G=_L#)0{_L+:L;_mp3T?-F}?}L,?}:F~o@ ``` [Try it online!](http://cjam.tryitonline.net/#code=NFsxIDQgNSA2IDggMTAgMTQgMTUgMiAyIDQgNSA3XTpHXHtfRywsJntHPV9MIykwe19MKzpMO19tcDNUPy1GfT99TCw_fTpGfm9A) My first CJam answer, hence why it's so terrible and imperative... ``` :G\{_G,,&{G=_L#)0{_L+:L;_mp3T?-F}?}L,?}:F~o@ :G Store the array as G \ Put the index first { }:F~ The recursive F function G,, Generate a 0..length(G) sequence _ & ? Check that the index is contained { } If so, then... G= Get the value at the index _L#) ? If the value is in L (`-1)` gives `0` which is falsy) 0 Return 0 (infinite loop) { } Otherwise... _L+:L; Store the value we're accessing in L (infinite loop check) _mp3T?- Remove 3 if the number is prime F Then recursively call F L, We escaped! Return the size of "L" (number of steps) o Print the top value of the stack @ Tries to swap 3 elements, which will error out ``` (it is considered okay to crash after the correct output as printed, which is what the program here does) [Answer] ## C, 121 bytes Function `f` accepts array, starting index (0-based) and number of elements in the array, since there is no way how to test the end of an array in C (at least I don't know any). ``` p(n,i,z){return--i?p(n,i,z*i*i%n):z%n;}c;f(a,i,n)int*a;{return i<0||i/n?c:c++>n?0:i&&p(i,i,1)?f(a,i-a[i],n):f(a,a[i],n);} ``` Try it on [ideone!](http://ideone.com/77P4WW) **Note:** `function p(n)` tests if `n` is prime or not. Credit for this goes to @Lynn and his answer for [Is this number a prime?](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime) [Answer] ## JavaScript, ~~121~~ 132 bytes ``` p=n=>t=i=>n%i&&n>i?t(i+1):(0<n&&n<=i?1:0),c=-1,a=>r=s=>(++c,0<=s&&s<a.length?(p(s)(2)?r(s-a[s]):0||([a[s],s]=[0,a[s]])[1]?r(s):0):c) ``` ``` f=(p=n=>t=i=>n%i&&n>i?t(i+1):(0<n&&n<=i?1:0),c=-1,a=>r=s=>(++c,0<=s&&s<a.length?(p(s)(2)?r(s-a[s]):0||([a[s],s]=[0,a[s]])[1]?r(s):0):c)); let test_data = [[[1,4,5,6,8,10,14,15,2,2,4,5,7],4], [[2,5,6,8,1,2,3],3], [[2,0,2],2], [[14,1,2,5,1,3,51,5,12,3,4,41,15,4,12,243,51,2,14,51,12,11],5]]; for (test of test_data) { c = -1; console.log(f(test[0])(test[1])); } ``` edit 1: oops, missed the bit about returning number of steps. fix coming soonish. edit 2: fixed [Answer] # Racket, ~~183~~ 156 bytes Probably more bytes savable with further golfing, but that's it for me. :) ``` (require math)(define(e l i[v'()][g length])(cond[(memq i v)#f][(not(< -1 i(g l)))(g v)][else(e l((λ(a)(if(prime? i)(- i a)a))(list-ref l i))(cons i v))])) ``` Complete module with test suite with cleaner function: ``` #lang racket (require math) (define (e l i [v'()] [g length]) (cond [(memq i v) #f] [(not (< -1 i (g l))) (g v)] [else (e l ((λ (a) (if (prime? i) (- i a) a)) (list-ref l i)) (cons i v))])) (module+ test (require rackunit) (define escape-tests '((((2 5 6 8 1 2 3) 3) . 1) (((2 0 2) 2) . #f) (((14 1 2 5 1 3 51 5 12 3 4 41 15 4 12 243 51 2 14 51 12 11) 5) . 6))) (for ([t escape-tests]) (check-equal? (apply e (car t)) (cdr t) (~a t)))) ``` Run it like `raco test e.rkt` Major kudos for @cat [discovering the undocumented `prime?` function](https://codegolf.stackexchange.com/a/77255/16190). [Answer] ## Java, ~~163~~ 160 bytes ``` boolean p(int n){for(int i=2;i<n;)if(n%i++==0)return 0>1;return 1>0;} int f(int[]a,int n){return n<0||n>=a.length?1:p(n)?n<a[n]?1:1+f(a,a[n-a[n]]):1+f(a,a[n]);} ``` `p(n)` is for prime testing, `f(a,n)` is for the escape function. Usage: ``` public static void main(String[] args) { int[] array = {14,1,2,5,1,3,51,5,12,3,4,41,15,4,12,243,51,2,14,51,12,11}; System.out.println(f(array, 5)); } ``` Ungolfed version: ``` static boolean isPrime(int n) { for (int i = 2; i < n; i++) { if (n % i == 0) { return false; } } return true; } static int escape(int[] array, int n) { if (n < 0 || n >= array.length) { return 1; } else if (isPrime(n)) { if (n < array[n]) { return 1; } else { return 1 + escape(array, array[n - array[n]]); } } else { return 1 + escape(array, array[n]); } } ``` [Answer] # [Perl 6](http://perl6.org/), 85 bytes ``` ->\n,\a{{.[+a].defined??0!!+$_}(lazy n,{.is-prime??$_- a[$_]!!a[$_]}...^!(0 <=* <a))} ``` Explanation: ``` lazy n, { .is-prime ?? $_ - a[$_] !! a[$_] } ...^ !(0 <= * < a) ``` This is a lazy sequence of the indices traversed according to the rule. If the index eventually exceeds the input array bounds (the `!(0 <= * < a)` condition), the sequence is finite; otherwise, the indices cycle infinitely. That sequence is fed to the internal anonymous function: ``` { .[+a].defined ?? 0 !! +$_ } ``` If the sequence is defined at the index given by the size of the input array, it must have entered an infinite cycle, so `0` is returned. Otherwise, the size of the sequence `+$_` is returned. [Answer] # [Perl 5](https://www.perl.org/), 107 + 1 (`-a`) = 108 bytes ``` for($i=<>;!$k{$i}++&&$i>=0&&$i<@F;$s++){$f=0|sqrt$i||2;1while$i%$f--;$i=$f?$F[$i]:$i-$F[$i]}say$k{$i}<2&&$s ``` [Try it online!](https://tio.run/##JYzBDoIwDIbvPsVMKtGQmXWyiwP0xM0nMB44sNhIBBmJMcCrO4tc@n1/2/xt1dUmBNd0W6Asze0aHgPQFMdRBJRnakZ6Liz4ON4N4DI1@lfXA42jtvi@U10BbcBJabkA3AmKK9DtCCQXm3z5WTpTzWU@BEwECi0Mz4MwOItmS0SCAg2To07@Jy34mckbxJX5Nm1PzdMHeTF7hSrI8gc "Perl 5 – Try It Online") 0-based list. Returns false (blank) if the list is unescapable. ]
[Question] [ ## Task This one is simple. We want to compress a URL, but don't trust URL shorteners. Write a program that prints to stdout (or a 0-argument function that returns) the following, working URL: <http://a.b.c.d.e.f.g.h.i.j.k.l.m.n.oo.pp.qqq.rrrr.ssssss.tttttttt.uuuuuuuuuuu.vvvvvvvvvvvvvvv.wwwwwwwwwwwwwwwwwwwwww.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy.zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.me> Code golf, standard rules. You may output uppercase or lowercase. Leading or trailing whitespace is ok. ## Context Explanation taken from the website: > > The domain is created to reach the maximum number of allowed characters (255 (really 253)) with an exponential curve in the length of the letters as you proceed through the alphabet. The formula used is "1 + 62 \* (10/7)^(x-26)". To help illustrate this curve, reference the distribution on this spreadsheet. It's colorful because I like colors and wanted to do a progressive "rainbow" animation in CSS3. > > > [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ ~~24~~ ~~23~~ 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žXAS.7Ƶ-t∞-m>×….me¬ýJ ``` -1 byte thanks to [*@Neil*'s analysis](https://codegolf.stackexchange.com/questions/199002/print-this-maximally-long-url#comment472958_199005) that `*(10/7)**` is the same as `/.7**`. -3 bytes thanks to *@Grimmy* using a different formula and ingenious use of `ý`! [Try it online.](https://tio.run/##ASgA1/9vc2FiaWX//8W@WEFTLjfGtS104oieLW0@w5figKYubWXCrMO9Sv//) **Explanation:** The formula used to get the correct amount of characters of the alphabet, where \$n\$ is the 1-based index of the alphabetic letter: \$a(n) = \left\lfloor0.7^{(\sqrt{208}-n)}+1\right\rfloor\$ ``` žX # Push builtin "http://" Ƶ- # Push compressed 208 t # Take the square-root of that: 14.422... ∞ # Push an infinite list of positive integers: [1,2,3,...] - # Subtract each from the 14.422...: [13.442...,12.442...,...] .7 m # Take 0.7 to the power of each of these: [0.008...,0.011...,...] > # Increase each by 1: [1.008...,1.011...,...] AS # Push the lowercase alphabet as list of characters, × # and repeat each the calculated values amount of times as string # (which implicitly truncates the floats to integers, and ignores # the floats beyond the length of the alphabet) ….me # Push ".me" ¬ # Push its head (the "."), without popping the ".me" itself ý # Join with delimiter. Normally it will use the top value as # delimiter and joins the top-1'th list. In this case however, the # top-1'th item is a string, so instead it will join the entire stack # together. BUT, because the stack contains a list, it will instead # only join all lists on the stacks by the "." delimiter J # And finally join the three strings on the stack together # (after which this result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ƶ-` is `208`. [Answer] # [Python 3](https://docs.python.org/3/), ~~86~~ \$\cdots\$ ~~81~~ 77 bytes Saved 3 bytes thanks to [mypetlion](https://codegolf.stackexchange.com/users/65255/mypetlion)!!! Saved 4 bytes thanks to [Shieru Asakoto](https://codegolf.stackexchange.com/users/71546/shieru-asakoto)!!! ``` print(f"http://{'.'.join(chr(i+97)*int(1+.7**-i/120)for i in range(26))}.me") ``` [Try it online!](https://tio.run/##FcpBCoAgEADAr4gXXSVNg6J@E5G5QauIl4jebjTnyXeNiYbWckGqMvBYa16sfYQR5kxIcotFop4nUH9w2kxKdWid7yGkwpAhsbLSsUs/Arzm2jm09gE "Python 3 – Try It Online") Uses [Shieru Asakoto](https://codegolf.stackexchange.com/users/71546/shieru-asakoto)'s 0-based formula. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~41~~ 38 bytes *-3 bytes thanks to Bubbler* ``` 2⌽'mehttp://',∊'.',¨⍨⎕A⍴¨⍨⌊1+62×.7*⍒⎕A ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qn/6O2CQYgFpA2etSzVz03NaOkpMBKX19d51FHl7qeus6hFY96VwBVOD7q3QJh93QZapsZHZ6uZ671qHcSSOr/fwA "APL (Dyalog Classic) – Try It Online") Outputs the URL with the letters capitalised. Uses the 0 indexed formula \$ \lfloor 1 + 62 \times 0.7^{25-x} \rfloor \$, since \$ (\frac{10}{7})^{x-25} = ((\frac{7}{10})^{-1})^{x-25} = (\frac{7}{10})^{25-x}\$ ### Explanation: ``` 2⌽ ⍝ Rotate by two places (moving the 'me' to the end) 'mehttp://' ⍝ The start string , ⍝ Followed by ∊ ⍝ The flattened string of '.' ⍝ A period ,⍨¨ ⍝ Appended to the end of each of ⎕A ⍝ The uppercase alphabet ⍴¨⍨ ⍝ Where each letter is repeated by ⌊ ⍝ The floor of 1+ ⍝ 1 plus 62× ⍝ 62 times .7* ⍝ 0.7 to the power of ⍒⎕A ⍝ The range 26 to 1 ``` [Answer] # [Perl 5](https://www.perl.org/), ~~61~~ ~~57~~ 55 bytes *-4 bytes thanks to @Neil* ``` say"http://",(map{$_ x(1+62/.7**(++$p-26))."."}a..z),me ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIpo6SkwEpfX0lHIzexoFolXqFCw1DbzEhfz1xLS0NbW6VA18hMU1NPSU@pNlFPr0pTJzf1//9/@QUlmfl5xf91fU31DAwNAA "Perl 5 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 77 bytes Based on [@ShieruAsakoto's formula](https://codegolf.stackexchange.com/a/199008/58563). Builds the URL recursively. ``` f=n=>n>25?".me":(n?".".padEnd(2+.7**-n/120,Buffer([97+n])):"http://a")+f(-~n) ``` [Try it online!](https://tio.run/##DcZLCsIwEADQu8xqpjGJBqQYaAXBU4iL0GT8UCehjS69evSt3jN8wjotj1K15Jha40GGUUa3P4J5JfAo/4ApIZ4lolOm7zotdue2m9ObOS14OfRKrkQe7rUWb20AUoz6K9SmLGuek5nzDRmJ2g8 "JavaScript (Node.js) – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 108 bytes ``` v->{var s="HTTP://";for(char c=64,t;++c<91;s+=(""+c).repeat(t/=Math.pow(.7,c-90))+c+".")t=62;return s+"ME";} ``` [Try it online!](https://tio.run/##pdBBS8MwGAbg@35FyKm12zsVmcyuuyleBsLEi3jIsnZN16ZZ8rVzjv32GepABBXE5xLy5SW8fIVoxaBYro@qMrUlVvg7GlIlskZLUrXGWdwzzaJUkslSOMdmQmm27zF2mjoS5I@2VktW@bdgTlbp1fMLE3blwi7K2N3pu8mTz/U/IlOWJcd2MN23wjKX8PvHx4eb4ZDHWW0DmfuhTEZXfYqjSE7GF7GLkoDzSIawqUkFBTRMZoJymHob4LovB@PzMIxkxMFDSkaXsU2psZq5iM9ueXw4xl2X@c5RWqFuCMb3oFIHGYQx5S7QTVmG4Y8xnhMZX1FgAYklUmRYIYdCgTVKVNCoaxiDzWYD68F1QCdoPqH9Cttv4fV32P0B3v4HVcq7/Rx6h@M7 "Java (JDK) – Try It Online") ## Credits * -4 bytes thanks to Kevin Cruijssen [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` http://⭆β⁺×ι⊕×⁶²X·⁷⁻²⁵κ.¦me ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREMpo6SkwEpfX0nTmgsiElwCpNJ9Ews0knQUAnJKizVCMnNTizUydRQ885KLUnNT80pSU6CCZkZANfnlqUUaeuY6Cr6ZeUDlRqY6CtmaIKCjoKSnBKRhRivlpgLt@f//v25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` http:// Implicitly print literal string `http://` β Lowercase alphabet ⭆ Map over letters and join κ Current index ⁻²⁵ Subtract from 25 X·⁷ Raise 0.7 to that power ×⁶² Multiply by 62 ⊕ Increment ×ι Repeat letter that many times ⁺ . Concatenate literal string `.` ¦ Implicitly print me Implicitly print literal string `me` ``` [Answer] # Jelly, ~~[49](https://tio.run/##y0rNyan8/1/b0uzh7h6ueCMzFUM9E2Otw9PNjB41zHi4Y97h6YfbuYzMgg63Zz1qmKP3qGEuF5DOKCkpKLbS1wdyrQ8tsgbJ5KYCOf//AwA)~~ ~~[48](https://tio.run/##y0rNyan8/1/b0uzh7h6ueCMzFUM9E2Otw9PNjB41zHi4Y97h6YfbuYzMgg63Zz1qmKvH9ahhTkZJSUGxlb4@kG99aJE1UEQvNxXI@f8fAA)~~ ~~[46](https://tio.run/##y0rNyan8/1/b0uzh7h6ueCMzFUM9E2Otw9PNjB41zHi4Y97h6YfbuYzMgg63Zz1qmKvH9ahhTkZJSYGVvj6Qa31okTVQQC839f9/AA)~~ 31 bytes (send help) A niladic link printing the URL ``` 26RU.7*×89ĊØa×⁾meṭj”.“http://”; ``` -2 bytes thanks to Kevin -15 bytes thanks to Nick! I never wrote anything this complex in Jelly and the [*tacicity*](https://youtu.be/iywaBOMvYLI) isn't obvious to me yet... So this is very golfable (see 49 byte link). I would appreciate feedback and golfing tips in small chunks so that I can digest it! You can [try this online](https://tio.run/##y0rNyan8/9/ILChUz1zr8HQLyyNdh2ckHp7@qHFfburDnWuzHjXM1XvUMCejpKTASl8fyLP@/x8A). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 71 bytes ``` "http://"<>Array[Table[Alphabet[][[#]],1+1.43^(#-26)62]<>"."&,26]<>"me" ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/V8po6SkwEpfX8nGzrGoKLEyOiQxKSc12jGnICMxKbUkOjY6Wjk2VsdQ21DPxDhOQ1nXyEzTzCjWxk5JT0lNx8gMxMpNVfof@x8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 93 bytes ``` _=>`http://${[...Array(26)].map((x,i)=>Buffer(Array(1+.7**-i/120|0).fill(97+i))).join`.`}.me` ``` [Try it online!](https://tio.run/##JclBDoIwEADAz3jYBdkCB4kmJdFvGGMbbHVJaZuCRqO@vR6c64z6oechcVwqHy4mW5nPsle3ZYk7IVbvIxHtU9IvaDd4oklHgOeaUfaHu7UmwT@bkrqiqFg0bf2pkSw7B9uuZESkMbBXpL40GZWH4OfgDLlwBQuI@Qc "JavaScript (Node.js) – Try It Online") When turning the formula into 0-indexed, the formula becomes \$1+62\times(\frac{10}{7})^{x-25}=1+0.0083146\times0.7^{-x}\$, and then 0.0083146 is approximated by 1/120. [Answer] # [C (gcc)](https://gcc.gnu.org/), 99 bytes ``` n;f(i){for(i=printf("http://");i<33;)for(n=62/pow(.7,i++-32)+2;n--;)putchar(n?89+i:46);puts("me");} ``` *-3 or so bytes thanks to [Noodle9](https://codegolf.stackexchange.com/users/9481/noodle9)!* *-8 bytes thanks to [gastropner](https://codegolf.stackexchange.com/users/75886/gastropner)!* [Try it online!](https://tio.run/##FYxBDoIwEEX3nIKwmkmtJK1BZSSehVQLk9DSQNUF4erW@pb//TwjB2NS8mSBcbPzAtyFhX20UI0xhrauKyS@aU34t75rVB3mDxzPBxZCaoVCkZeSMLyiGft8uV@ugttTg5SnFSr3zIk95WjpevbwnvmBxVaUGQtIxZ6@xk79sCY5uR8 "C (gcc) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 29 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ;`http://{C®p.7**T´/#xÄ +'.}´ ``` Saved 2 bytes thanks to @Shaggy [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O2BodHRwOi8ve0OucC43KipUtC8jeMQgKycufbQ&footer=YHg) [Answer] # [Haskell](https://www.haskell.org/), 86 bytes ``` g(c,x)=replicate(floor$1+62*1.43**x)c++"." f="http://"++(zip['a'..][-25..0]>>=g)++"me" ``` [Try it online!](https://tio.run/##pdC9bsIwAATgPU9hWUgkcXv89GeoZJ6gGyNicIOduDi245gSePk0KhWoUoWE@LaT7parRLuVxvR9mRYPXcaD9EYXIspUGefCaMZe5/kMz0953mUFYxQ0UZxWMfq3yYQylh61X43FGFivHucvwHS9WPAyG6q1pL2w7V6G80DgAwU2kFAoUUHjE1sY1LBwDt6jaRqEAdofiL@wu8DXX9j/C911ONwAx/tgeCNJaqEt4WTjEjLwu7iM4d0SdYpB20hGRBHOyem4/hs "Haskell – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~124~~ ~~115~~ 63 bytes This is way better than my original approach. Thanks to @Giuseppe and @Grimmy ``` cat("http://");cat(strrep(letters,1+62*.7^(25:0)),"me",sep=".") ``` [Try it online!](https://tio.run/##K/r/PzmxREMpo6SkwEpfX0nTGsQtLikqSi3QyEktKUktKtYx1DYz0tIzj9MwMrUy0NTUUcpNVdIpTi2wVdJT0vz/HwA "R – Try It Online") [Answer] # [Keg](https://github.com/JonoCode9374/Keg), ~~46~~ 40 bytes ``` `3);://`0&(‡26 |⑻a+ⁿ⅍7 /⑻±Ëx/ℤ1+⑹*\.)`me ``` [Try it online!](https://tio.run/##y05N//8/wVjT2kpfP8FATeNRw0IjM86aRxN3J2o/atz/qLXXnEsfyDu08XB3hf6jliWG2o8m7tSK0dNMyE39/x8A "Keg – Try It Online") A port of the Python 3 answer by Noodle9. *-6 bytes due to using string compression and some other things* [Answer] # [PHP](https://php.net/), 94 bytes ``` for($c='a',$s='http://',$i=-26;$i++;$c++,$s.='.')for($l=62/.7**$i;$l-->=0;$s.=$c);echo$s.'me'; ``` [Try it online!](https://tio.run/##HYtRCoAgEEQvs7ClqeFHQdvWWUIMBSOp7m/WzzCPeZNDLvOaa@7n1YBj3LCDmzE8T56MqRBZ2YEgSkngpKyrZtTY/ofEgzV6FAIiQVJq4Z4@AVxL3oWzdjw8Uikv "PHP – Try It Online") Probably still golfable, uses the formula from the question and PHP's char incrementing EDIT: saved 3 bytes with code reorganization EDIT2: another byte less starting from `-26` and removing `($i-26)` [Answer] # [Ruby](https://www.ruby-lang.org/), 64 bytes Conveniently, when multiplying a string with a non-whole positive number, Ruby truncates the number to determine how many times to repeat the string. ``` puts"http://#{(?a..?z).map{|c|c*(1+62/0.7**(c.ord-122))}*?.}.me" ``` [Try it online!](https://tio.run/##KypNqvz/v6C0pFgpo6SkwEpfX7lawz5RT8@@SlMvN7Gguia5JllLw1DbzEjfQM9cS0sjWS@/KEXX0MhIU7NWy16vVi83Ven/fwA "Ruby – Try It Online") [Answer] # [MATLAB](https://www.mathworks.com/products/matlab.html) 92 bytes ``` b="";for i=1:26;b=b+repelem(char(96+i),floor(1+62*(10/7).^(i-26)))+".";end;"http://"+b+"me" ``` [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~126~~ 123 bytes -3 bytes thanks to [S.S. Anne](https://codegolf.stackexchange.com/users/89298/s-s-anne) Some acrobatics needed to avoid having to include `cmath`. ``` #import<map> using s=std::string;s f(){s r="http://";for(float i=26,p=7456;i--;p*=.7)r+=s(1+62/p,122-i)+'.';return r+"me";} ``` [Try it online!](https://tio.run/##HY1LDoMgFADX5RTELpTiJyWtJiLeheCnJPIJPFbGs1vb5UwmGeV9tSp13rVVW5pmPGgXIczSjJcz3gUYjPQjSlHbFUcRYer7q7iIR7wUZI84iOwD4PumyfjiQrFsTgLWgrWlF93r3XJdVdw/RN2RQEUsnrRljS@fjFWa0LzOeZghBYsDzcyc8ePUFrCR2hYE7ej2nyqXAA/D78nRcX4B "C++ (gcc) – Try It Online") [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), 809 bytes ``` {i}cc{{i}d}iiiic{i}iiccddddc{{d}iiiii}ddddc{d}dcc{{i}ddddd}c{{d}iiiii}dc{{i}ddddd}iic{{d}iiiii}ddc{{i}ddddd}iiic{{d}iiiii}dddc{{i}ddddd}iiiic{{d}iiiii}ddddc{{i}ddddd}iiiiic{{d}iiiii}dddddc{{i}ddddd}iiiiiic{{d}iiiii}ddddddc{{i}dddd}dddc{{d}iiii}iiic{{i}dddd}ddc{{d}iiii}iic{{i}dddd}dc{{d}iiii}ic{{i}dddd}c{{d}iiii}c{{i}dddd}ic{{d}iiii}dc{{i}dddd}iic{{d}iiii}ddc{{i}dddd}iiic{{d}iiii}dddc{{i}dddd}iiiic{{d}iiii}ddddc{{i}dddd}iiiiicc{{d}iiii}dddddc{{i}dddd}iiiiiicc{{d}iiii}ddddddc{{i}ddd}dddccc{{d}iii}iiic{{i}ddd}ddcccc{{d}iii}iic{{i}ddd}dcccccc{{d}iii}ic{{i}ddd}cccccccc{{d}iii}c{{i}ddd}i{c}c{{d}iii}dc{{i}ddd}ii{c}ccccc{{d}iii}ddc{{i}ddd}iii{c}{c}cc{{d}iii}dddc{{i}ddd}iiii{c}{c}{c}c{{d}iii}ddddc{{i}ddd}iiiii{c}{c}{c}{c}cccc{{d}iii}dddddc{{i}ddd}iiiiii{c}{c}{c}{c}{c}{c}ccc{{d}iii}ddddddc{{i}dddd}iiic{d}iic ``` [Try it online!](https://tio.run/##ZZFBDkMhCERP1EM10KasuzSc3aI1MIMszHfeIN9RX0992/fzmHOYi4xY1S1K4itW0aiQ/2LAvVXX413lyEFeh0AjEUaN2TWQaMcXvwzlcLzO@Y8kCEAHudQSS6u5kAPGgClQCJQBR8AJnACYdnzxNOw5SfH@vgGQAiJEEogwSWBDMp9KInZLxw5FuOg2FCV8OJ3dLeU5o9DZrOTNDmror7Ufc84f "Deadfish~ – Try It Online") E. ]
[Question] [ It's strange that I haven't seen this, as Excel seems to be a valid language for code golfing (despite its 'compiler' not being free). Excel is somewhat of a wildcard in golfing, being good at golfing challenges of medium complexity, and sometimes simpler challenges as well. More often than not, Excel is good at challenges with string manipulation and mixed string-number manipulation. What general tips do you have for golfing in Excel? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Excel (NOT VBA). Please, one tip per answer. [Answer] ## Vectorization with Arrays Whenever a function takes an array as an argument instead of a singleton, That function will also output an array with the result value to the corresponding indecies. Example: `=LEN(A1)+LEN(B2)+LEN(C3)` could be replaced with `=SUM(LEN({A1,B2,C3}))` [Answer] # Reference shorthand: If your program is required to take multiple inputs, you may want to be able to scoop them all up at once. to read multiple cells as an array, one could do such as the example: Example: `=len(A1)+Len(B1)+LEN(C1)` could be `=SUM(LEN(A1:C1))` `=SUM(LEN(A1:C1 A2:C2 A3:C3))` could be `=SUM(LEN(A1:C3))` `=SUM(LEN(A1:A1024))` could be `=SUM(LEN(A:A))` `=SUM(LEN(A:A B:B C:C))` could be `=SUM(LEN(A:C))` [Answer] ## Concatenate shorthand: The `CONCATENATE` function can be replaced with the `&` symbol 100% of the time, so long as the first argument is a string, or cell. example: ``` CONCATENATE(A1,B1) ``` could be shortened to ``` A1&B1 ``` In newer version of Excel (2016 or newer) the `CONCAT` function can be used for arrays and longer series of variables. ``` CONCAT(1:1) ``` [Answer] # Boolean Logic Shortcuts ## Universal Set of Operators `0` => `FALSE` and any other number => `TRUE`, so we can exploit this fact with some arithmetic operators | Standard | Hacky | # Saved | | --- | --- | --- | | `NOT(A1)` | `A1=0` | 3, 1 if parenthesized | | `XOR(A1,B1)` | `A1<>B1` | 4 | | `XOR(A1,B1,...)` | `A1=B1=...=0` | 3 | | `NOT(XOR(A1,B1,...))` | `A1=B1=...` | 6 (XNOR) | | `OR(A1,B1,...)` | `A1+B1+...` | 4 or 2 (see note) | | `AND(A1,B1,...)` | `A1*B1*...` | 5 | Note: This XOR only works if all argument values are the same nonzero number. You may have to "cast" a result (such as with `OR`) to a Boolean using `...>0` ## Operator precedence You may have to add parentheses, depending on precedence. 1. Reference (`:`//`,`) 2. Negation (Prefix `-`) 3. Percent (`%`) 4. Exponentiation (`^`) 5. Multiplication/Division (`*`/`/`) (AND) 6. Addition/Subtraction (`+`/`-`) (OR) 7. Concatenation (`&`) 8. Comparison (`=`, `<`, `>`, `<=`, `>=`, `<>`) (XOR/NOT) ## Other Things * A blank cell evaluates to `FALSE`. [Answer] # Converting a Number to Text: This is a very simple tip, but it may be useful to some nonetheless... * If you need to convert a number to text from within a formula, use the concatenation operator to join two parts of the number as a string (i.e. `1&23`). * If you need to convert a number to text for use by cell reference (i.e. `A1`), change the **Number Format** of the cell to **Text** to eliminate the need for extra bytes. * See the chart below for a comparison of number-to-text methods. **Quick Reference Chart:** ``` +-------------------------------------------------------------------------------------+ | | A | B | C | D | E | |-------------------------------------------------------------------------------------| | 1 | Formula | Bytes | Result | ISTEXT(cell)¹ | ISTEXT(formula)² | |-------------------------------------------------------------------------------------| | 2 | =TEXT(123,0) | 12 | 123 | TRUE | TRUE | | 3 | ="123" | 6 | 123 | TRUE | TRUE | | 4 | =1&23 | 5 | 123 | TRUE | TRUE | | 5 | '123 | 4 | 123 | TRUE | NOT VALID | | 6 | 123 | 3 | 123 | TRUE | FALSE | | 7 | 123 | 3 | 123 | FALSE | FALSE | +-------------------------------------------------------------------------------------+ Note: The result for cell C6 has been formatted as text, whereas the result for C7 has not. ¹ Denotes =ISTEXT(C2), =ISTEXT(C3), =ISTEXT(C4), etc. ² Denotes =ISTEXT(TEXT(123,0)), =ISTEXT("123"), =ISTEXT(1&23), etc. ``` [Answer] # Boolean Shorthand: Instead of using the `=TRUE()` and `=FALSE()` functions, use `=1=1` and `=1=2`. [Answer] # Vectorization of arrays of cells: The tip [Vectorization with arrays](https://codegolf.stackexchange.com/a/93923/56309) Shows how you can golf down a function with an array by using specific formatting within the array. It is possible to do the same thing with cells, and will save you many many bytes in the long run. Say you have the following sheet: [![example sheet](https://i.stack.imgur.com/Z9suy.png)](https://i.stack.imgur.com/Z9suy.png) And we want to find the highest shelf life of a fruit. Without Vectorization, one might use the two formulas like so: [![enter image description here](https://i.stack.imgur.com/gY8Ov.png)](https://i.stack.imgur.com/gY8Ov.png) And this does give a correct answer, but the Score for this golf is Unconventional, and will probably not be accepted as widely. On top of that, this uses a drag down function (Ew), which makes for a confusing answer. Instead, We can place the function in column D right on in with the formula in E2. To do this, you replace (in this case B2 and C2) your variables with arrays for the range you want to test. Thus, your formula becomes: [![enter image description here](https://i.stack.imgur.com/gPHx4.png)](https://i.stack.imgur.com/gPHx4.png) This saves you a few bytes as well as making your entry properly score-able. [Answer] # Converting Types ## To Number * Use a `--` prefix. + `--FALSE` = 0, `--TRUE` = 1 * Sometimes an arithmetic operator can be used to save steps later. + `"2"-2` = 0, which can be used as an equality check. ## To Boolean * Since numbers are implicitly Boolean-like, you may be able to avoid this. + 0 => `FALSE`, Any other number => `TRUE` + Blank cell => `FALSE` * If you need it, you can use comparison operators. + `A1<>0` => Non-zero to `TRUE`, `A1>0` => Positive to `TRUE`. ## To String * Concatenate either a blank cell or `""` using the `&` operator. ## Using `BASE()` and `DECIMAL()` `BASE` takes a decimal number and converts it to another base. For example, `=BASE(6873049,25)` becomes "HELLO". You can do the reverse of this with `=DECIMAL("HELLO",25)`. This is sometimes useful for restricted source problems, or can be used to compress a big number in a smaller base using a decimal number. [Answer] # LET Function LET allows you to define names within a function. For example, `=LET(x,1,y,2,x+y)` returns 3. This allow you to define longer expressions with one character and reuse them within a formula. For example, `LET(q,ROW(1:19),if(q>10,19-q,q))` lists the numbers from 1 to 10 and then back down to 1. This sounds like a simple function but it has allowed golfing answers that were not possible before this was added to Excel. There are functions like `OFFSET` and `SUMIF` that do not work entirely correctly on names that are not tied directly to cell references. [More info on LET](https://support.microsoft.com/en-us/office/let-function-34842dd8-b92b-4d3f-b325-b8b8f9908999) [Answer] # ISBLANK() Shorthand: Instead of using `=ISBLANK(A1)`, use `=A1=0` to determine if a cell (i.e. `A1`) is empty. ***Note:** This shortcut will not work if cell* `A1` *contains* `0`. *In that case, you will need to use* `=A1=""`. ]
[Question] [ Write a program that takes in a true-color RGB image *I*, the maximum number of lines to draw *L*, and the minimum *m* and maximum *M* length of each line. Output an image *O* that looks as much as possible like *I* and is drawn using *L* or fewer straight lines, all of which have Euclidean length between *m* and *M*. Each line must be one solid color, have both endpoints in the bounds of *O*, and be drawn using [Bresenham's line algorithm](http://en.wikipedia.org/wiki/Bresenham's_line_algorithm) (which most graphics libraries will already do for you). Individual lines can only be 1-pixel thick. All lines, even those of length 0, should take up at least one pixel. Lines may be drawn on top of one another. Before drawing any lines you may initialize the background of *O* to any solid color (that may depend on *I*). ## Details * *O* should have the same dimensions as *I*. * *L* will always be a nonnegative integer. It may be greater than the area of *I*. * *m* and *M* are nonnegative floating point numbers with *M* >= *m*. The distance between two pixels is the Euclidean distance between their centers. If this distance is less than *m* or greater than *M*, then a line between those pixels is not allowed. * The lines should not be antialiased. * Opacity and alpha should not be used. * Your program should not take more than an hour to run on a [decent modern computer](http://www.clarku.edu/offices/its/purchasing/recommendations.cfm) on images with less than a million pixels and *L* less than 10,000. ## Test Images You should of course show us your most accurate or interesting output images (which I expect will occur when *L* is between 5% and 25% of the number of pixels in *I*, and *m* and *M* are around one tenth of the diagonal size). Here are some test images (click for originals). You may also post your own. [![Mona Lisa](https://i.stack.imgur.com/sjWYq.jpg)](http://en.wikipedia.org/wiki/Mona_Lisa#mediaviewer/File:Mona_Lisa,_by_Leonardo_da_Vinci,_from_C2RMF_retouched.jpg) [![Waterfall](https://i.stack.imgur.com/wOurbm.jpg)](http://en.wikipedia.org/wiki/M._C._Escher#mediaviewer/File:Escher_Waterfall.jpg) [![Nighthawks](https://i.stack.imgur.com/owj3J.jpg)](http://en.wikipedia.org/wiki/Nighthawks#mediaviewer/File:Nighthawks_by_Edward_Hopper_1942.jpg) [![Starry Night](https://i.stack.imgur.com/nEzWz.jpg)](http://en.wikipedia.org/wiki/The_Starry_Night#mediaviewer/File:Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg) [![Golden Gate Bridge](https://i.stack.imgur.com/zm5VTm.jpg)](http://en.wikipedia.org/wiki/Golden_Gate_Bridge#mediaviewer/File:GoldenGateBridge-001.jpg) Simpler images: [![Penrose stairs](https://i.stack.imgur.com/XWoBv.png)](http://en.wikipedia.org/wiki/Impossible_object#mediaviewer/File:Impossible_staircase.svg)[![Mobius strip](https://i.stack.imgur.com/Blma9.png)](http://en.wikipedia.org/wiki/Mobius_strip#mediaviewer/File:Moebius_strip.svg) [![Hilbert curve](https://i.stack.imgur.com/pqlV1.png)](http://en.wikipedia.org/wiki/Hilbert_curve#mediaviewer/File:Hilbert_curve_3.svg) This is a popularity contest. The highest voted submission wins. ## Notes * It may be helpful to let *L* be derived from a percentage of total pixels in *I* as well as an absolute value. e.g. `>>> imageliner I=img.png L=50% m=10 M=20` would be the same thing as `>>> imageliner I=img.png L=32 m=10 M=20` if `img.png` were an 8 by 8 pixel image. Something similar could be done for *m* and *M*. This is not required. * Since lines cannot go out of bounds, the longest lines possible will be the diagonal length of *I*. Having *M* higher than this should not break anything though. * Naturally, if *m* is 0 and *L* is greater than or equal to the number of pixels in *I*, *O* could be identical to *I* by having length 0 "lines" at each pixel location. This behavior is not required. * Arguably, reproducing the shape of *I* is more important than reproducing the color. You may want to look into [edge detection](http://en.wikipedia.org/wiki/Edge_detection). [Answer] # C++ - somewhat random lines and then some ## First some random lines The first step of the algorithm randomly generates lines, takes for the target image an average of the pixels along this, and then calculates if the summed up square of rgb space distances of all pixels would be lower if we would paint the new line (and only paint it, if it is). The new lines color for this is chosen as the channel wise average of the rgb values, with a -15/+15 random addition. Things that I noticed and influenced the implementation: * The initial color is the average of the complete image. This is to counter funny effects like when making it white, and the area is black, then already something as a bright green line is seen better, as it is nearer to black than the already white one. * Taking the pure average color for the line is not so good as it turns out to be unable to generate highlights by being overwritten by later lines. Doing a little random deviation helps a bit, but if you look at starry night, it fails if the local contrast is high at many places. I was experimenting with some numbers, and chose `L=0.3*pixel_count(I)` and left `m=10` and `M=50`. It will produce nice results starting at around `0.25` to `0.26` for the number of lines, but I chose 0.3 to have more room for accurate details. For the full sized golden gate image, this resulted in 235929 lines to paint (for which it took a whopping 13 seconds here). Note that all images here are displayed in reduced size and you need to open them in a new tab/download them to view the full resolution. ![](https://i.stack.imgur.com/fwfUA.jpg) ## Erase the unworthy The next step is rather expensive (for the 235k lines it took about an hour, but that should be well within the "an hour for 10k lines on 1 megapixel" time requirement), but it is also a bit surprising. I go through all the previously painted lines, and remove those that do not make the image better. This leaves me in this run with only 97347 lines that produce the following image: ![](https://i.stack.imgur.com/JIbCc.jpg) You probably need to download and compare them in an appropriate image viewer to spot most differences. ## and start over again Now I have a lot of lines that I can paint again to have a total of 235929 again. Not much to say, so here is the image: ![enter image description here](https://i.stack.imgur.com/gPYV2.jpg) ## short analysis The whole procedure seems to work like a blurring filter that is sensitive to local contrast and object sizes. But it is also interesting to see where the lines are painted, so the program records these too (For each line, the pixel color will be made one step whiter, at the end the contrast is maximized). Here are the corresponding ones to the three colored above. ![](https://i.stack.imgur.com/SmcG3.png) ![](https://i.stack.imgur.com/P8FVo.png) ![](https://i.stack.imgur.com/h9CtG.png) ## animations And since we all love animations, here are some animated gifs of the whole process for the smaller golden gate image. Note that there is significant dithering due to gif format (and since creators of true color animation file formats and browser manufacturers are in war over their egos, there is no standard format for true color animations, otherwise I could have added an .mng or similar). [![](https://web.archive.org/web/20160927100305/http://plasmahh.projectiwear.org/color.gif)](https://web.archive.org/web/20160927100305/http://plasmahh.projectiwear.org/color.gif) [![](https://web.archive.org/web/20160927100702/http://plasmahh.projectiwear.org/layer.gif)](https://web.archive.org/web/20160927100702/http://plasmahh.projectiwear.org/layer.gif) ## Some more As requested, here are some results of the other images (again you might need to open them in a new tab to not have them downscaled) ![](https://i.stack.imgur.com/yzFHk.jpg) ![](https://i.stack.imgur.com/NNRCl.jpg) ![](https://i.stack.imgur.com/zM0HA.jpg) ![](https://i.stack.imgur.com/2QA4R.png) ## Future thoughts Playing around with the code can give some intresting variations. * Chose the color of the lines by random instead of being based on the average. You might need more than two cycles. * The code in the pastebin also contains some idea of a genetic algorithm, but the image is probably already so good that it would take too many generations, and this code is also too slow to fit into the "one hour" rule. * Do another round of erase/repaint, or even two... * Change the limit of where lines can be erased (e.g. "must make the image at lest N better") ## The code These are just the two main useful functions, the whole code doesn't fit in here and can be found at <http://ideone.com/Z2P6Ls> The `bmp` classes `raw` and `raw_line` function do access pixels and lines respectively in an object that can be written to bmp format (It was just some hack lying around and I thought that makes this somewhat independent from any library). The input file format is PPM ``` std::pair<bmp,std::vector<line>> paint_useful( const bmp& orig, bmp& clone, std::vector<line>& retlines, bmp& layer, const std::string& outprefix, size_t x, size_t y ) { const size_t pixels = (x*y); const size_t lines = 0.3*pixels; // const size_t lines = 10000; // const size_t start_accurate_color = lines/4; std::random_device rnd; std::uniform_int_distribution<size_t> distx(0,x-1); std::uniform_int_distribution<size_t> disty(0,y-1); std::uniform_int_distribution<size_t> col(-15,15); std::uniform_int_distribution<size_t> acol(0,255); const ssize_t m = 1*1; const ssize_t M = 50*50; retlines.reserve( lines ); for (size_t i = retlines.size(); i < lines; ++i) { size_t x0; size_t x1; size_t y0; size_t y1; size_t dist = 0; do { x0 = distx(rnd); x1 = distx(rnd); y0 = disty(rnd); y1 = disty(rnd); dist = distance(x0,x1,y0,y1); } while( dist > M || dist < m ); std::vector<std::pair<int32_t,int32_t>> points = clone.raw_line_pixels(x0,y0,x1,y1); ssize_t r = 0; ssize_t g = 0; ssize_t b = 0; for (size_t i = 0; i < points.size(); ++i) { r += orig.raw(points[i].first,points[i].second).r; g += orig.raw(points[i].first,points[i].second).g; b += orig.raw(points[i].first,points[i].second).b; } r += col(rnd); g += col(rnd); b += col(rnd); r /= points.size(); g /= points.size(); b /= points.size(); r %= 255; g %= 255; b %= 255; r = std::max(ssize_t(0),r); g = std::max(ssize_t(0),g); b = std::max(ssize_t(0),b); // r = acol(rnd); // g = acol(rnd); // b = acol(rnd); // if( i > start_accurate_color ) { ssize_t dp = 0; // accumulated distance of new color to original ssize_t dn = 0; // accumulated distance of current reproduced to original for (size_t i = 0; i < points.size(); ++i) { dp += rgb_distance( orig.raw(points[i].first,points[i].second).r,r, orig.raw(points[i].first,points[i].second).g,g, orig.raw(points[i].first,points[i].second).b,b ); dn += rgb_distance( clone.raw(points[i].first,points[i].second).r,orig.raw(points[i].first,points[i].second).r, clone.raw(points[i].first,points[i].second).g,orig.raw(points[i].first,points[i].second).g, clone.raw(points[i].first,points[i].second).b,orig.raw(points[i].first,points[i].second).b ); } if( dp > dn ) // the distance to original is bigger, use the new one { --i; continue; } // also abandon if already too bad // if( dp > 100000 ) // { // --i; // continue; // } } layer.raw_line_add(x0,y0,x1,y1,{1u,1u,1u}); clone.raw_line(x0,y0,x1,y1,{(uint32_t)r,(uint32_t)g,(uint32_t)b}); retlines.push_back({ (int)x0,(int)y0,(int)x1,(int)y1,(int)r,(int)g,(int)b}); static time_t last = 0; time_t now = time(0); if( i % (lines/100) == 0 ) { std::ostringstream fn; fn << outprefix + "perc_" << std::setw(3) << std::setfill('0') << (i/(lines/100)) << ".bmp"; clone.write(fn.str()); bmp lc(layer); lc.max_contrast_all(); lc.write(outprefix + "layer_" + fn.str()); } if( (now-last) > 10 ) { last = now; static int st = 0; std::ostringstream fn; fn << outprefix + "inter_" << std::setw(8) << std::setfill('0') << i << ".bmp"; clone.write(fn.str()); ++st; } } clone.write(outprefix + "clone.bmp"); return { clone, retlines }; } void erase_bad( std::vector<line>& lines, const bmp& orig ) { ssize_t current_score = evaluate(lines,orig); std::vector<line> newlines(lines); uint32_t deactivated = 0; std::cout << "current_score = " << current_score << "\n"; for (size_t i = 0; i < newlines.size(); ++i) { newlines[i].active = false; ssize_t score = evaluate(newlines,orig); if( score > current_score ) { newlines[i].active = true; } else { current_score = score; ++deactivated; } if( i % 1000 == 0 ) { std::ostringstream fn; fn << "erase_" << std::setw(6) << std::setfill('0') << i << ".bmp"; bmp tmp(orig); paint(newlines,tmp); tmp.write(fn.str()); paint_layers(newlines,tmp); tmp.max_contrast_all(); tmp.write("layers_" + fn.str()); std::cout << "\r i = " << i << std::flush; } } std::cout << "\n"; std::cout << "current_score = " << current_score << "\n"; std::cout << "deactivated = " << deactivated << "\n"; bmp tmp(orig); paint(newlines,tmp); tmp.write("newlines.bmp"); lines.clear(); for (size_t i = 0; i < newlines.size(); ++i) { if( newlines[i].is_active() ) { lines.push_back(newlines[i]); } } } ``` [Answer] ## Java - random lines A very basic solution that draws random lines and compute for them the source picture average color. The background color is set to the source average color. **L = 5000, m = 10, M = 50** ![enter image description here](https://i.stack.imgur.com/eUyXm.png) **L = 10000, m = 10, M = 50** ![enter image description here](https://i.stack.imgur.com/DVyPQ.png) **EDIT** I've added a genetic algorithm that handles a population of lines. At each generation, we keep only the 50% best lines, drop the others and generate randomly new ones. The criteria for keeping the lines are: * their distance to the source picture colors is small * the number of intersections with other lines (the smaller the better) * their length (the longer the better) * their angle with the nearest neighbour (the smaller the better) To my great disappointment, the algorithm does not really seems to improve the picture quality :-( just the lines are getting more parallel. **First generation (5000 lines)** ![enter image description here](https://i.stack.imgur.com/rCmRu.png) **Tenth generation (5000 lines)** ![enter image description here](https://i.stack.imgur.com/jrRoM.png) **Playing with parameters** ![enter image description here](https://i.stack.imgur.com/XSfU2.png)![enter image description here](https://i.stack.imgur.com/v8L6Q.png)![enter image description here](https://i.stack.imgur.com/cvKF5.png) ``` package line; import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.imageio.ImageIO; import snake.Image; public class Lines { private final static int NB_LINES = 5000; private final static int MIN_LENGTH = 10; private final static int MAX_LENGTH = 50; public static void main(String[] args) throws IOException { BufferedImage src = ImageIO.read(Image.class.getClassLoader().getResourceAsStream("joconde.png")); BufferedImage dest = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_RGB); int [] bgColor = {0, 0, 0}; int avgRed = 0, avgGreen = 0, avgBlue = 0, count = 0; for (int y = 0; y < src.getHeight(); y++) { for (int x = 0; x < src.getWidth(); x++) { int colsrc = src.getRGB(x, y); avgRed += colsrc & 255; avgGreen += (colsrc >> 8) & 255; avgBlue += (colsrc >> 16) & 255; count++; } } bgColor[0] = avgBlue/count; bgColor[1] = avgGreen/count; bgColor[2] = avgRed/count; for (int y = 0; y < src.getHeight(); y++) { for (int x = 0; x < src.getWidth(); x++) { dest.getRaster().setPixel(x, y, bgColor); } } List<List<Point>> lines = new ArrayList<List<Point>>(); Random rand = new Random(); for (int i = 0; i < NB_LINES; i++) { int length = rand.nextInt(MAX_LENGTH - MIN_LENGTH) + MIN_LENGTH; double ang = rand.nextDouble() * Math.PI; int lx = (int)(Math.cos(ang) * length); // can be negative or positive int ly = (int)(Math.sin(ang) * length); // positive only int sx = rand.nextInt(dest.getWidth() -1 - Math.abs(lx)); int sy = rand.nextInt(dest.getHeight() - 1- Math.abs(ly)); List<Point> line; if (lx > 0) { line = line(sx, sy, sx+lx, sy+ly); } else { line = line(sx+Math.abs(lx), sy, sx, sy+ly); } lines.add(line); } // render the picture int [] color = {0, 0, 0}; for (List<Point> line : lines) { avgRed = 0; avgGreen = 0; avgBlue = 0; count = 0; for (Point p : line) { int colsrc = src.getRGB(p.x, p.y); avgRed += colsrc & 255; avgGreen += (colsrc >> 8) & 255; avgBlue += (colsrc >> 16) & 255; count++; } avgRed /= count; avgGreen /= count; avgBlue /= count; color[0] = avgBlue; color[1] = avgGreen; color[2] = avgRed; for (Point p : line) { dest.getRaster().setPixel(p.x, p.y, color); } } ImageIO.write(dest, "png", new File("a0.png")); } private static List<Point> line(int x0, int y0, int x1, int y1) { List<Point> points = new ArrayList<Point>(); int deltax = x1 - x0; int deltay = y1 - y0; int tmp; double error = 0; double deltaerr = 0; if (Math.abs(deltax) >= Math.abs(deltay)) { if (x0 > x1) { // swap the 2 points tmp = x0; x0 = x1; x1 = tmp; tmp = y0; y0 = y1; y1 = tmp; deltax = - deltax; deltay = -deltay; } deltaerr = Math.abs (((double)deltay) / deltax); int y = y0; for (int x = x0; x <= x1; x++) { points.add(new Point(x, y)); error += deltaerr; if (error >= 0.5) { if (y0 < y1) y++; else y--; error -= 1.0; } } } else { if (y0 > y1) { // swap the 2 points tmp = x0; x0 = x1; x1 = tmp; tmp = y0; y0 = y1; y1 = tmp; deltax = - deltax; deltay = -deltay; } deltaerr = Math.abs (((double)deltax) / deltay); // Assume deltay != 0 (line is not horizontal), int x = x0; for (int y = y0; y <= y1; y++) { points.add(new Point(x, y)); error += deltaerr; if (error >= 0.5) { if (x0 < x1) x++; else x--; error -= 1.0; } } } return points; } } ``` [Answer] # C - straight lines A basic approach in C that operates on ppm files. The algorithm tries to place vertical lines with optimal line length to fill all pixels. The background color and the line colors are calculated as an average value of the original image (the median of each color channel): ``` #include <stdio.h> #include <stdlib.h> #include <assert.h> #define SIGN(x) ((x > 0) ? 1 : (x < 0) ? -1 : 0) #define MIN(x, y) ((x > y) ? y : x) #define MAX(x, y) ((x > y) ? x : y) typedef struct { size_t width; size_t height; unsigned char *r; unsigned char *g; unsigned char *b; } image; typedef struct { unsigned char r; unsigned char g; unsigned char b; } color; void init_image(image *data, size_t width, size_t height) { data->width = width; data->height = height; data->r = malloc(sizeof(data->r) * data->width * data->height); data->g = malloc(sizeof(data->g) * data->width * data->height); data->b = malloc(sizeof(data->b) * data->width * data->height); } #define BUFFER_LEN 1024 int load_image(const char *filename, image* data) { FILE *f = fopen(filename, "r"); char buffer[BUFFER_LEN]; /* read buffer */ size_t max_value; size_t i; fgets(buffer, BUFFER_LEN, f); if (strncmp(buffer, "P3", 2) != 0) { printf("File begins with %s instead of P3\n", buffer); return 0; } fscanf(f, "%u", &data->width); fscanf(f, "%u", &data->height); fscanf(f, "%u", &max_value); assert(max_value==255); init_image(data, data->width, data->height); for (i = 0; i < data->width * data->height; i++) { fscanf(f, "%hhu", &(data->r[i])); fscanf(f, "%hhu", &(data->g[i])); fscanf(f, "%hhu", &(data->b[i])); } fclose(f); printf("Read %zux%zu pixels from %s.\n", data->width, data->height, filename); } int write_image(const char *filename, image *data) { FILE *f = fopen(filename, "w"); size_t i; fprintf(f, "P3\n%zu %zu\n255\n", data->width, data->height); for (i = 0; i < data->width * data->height; i++) { fprintf(f, "%hhu %hhu %hhu ", data->r[i], data->g[i], data->b[i]); } fclose(f); } unsigned char average(unsigned char *data, size_t data_len) { size_t i; size_t j; size_t hist[256]; for (i = 0; i < 256; i++) hist[i] = 0; for (i = 0; i < data_len; i++) hist[data[i]]++; j = 0; for (i = 0; i < 256; i++) { j += hist[i]; if (j >= data_len / 2) return i; } return 255; } void set_pixel(image *data, size_t x, size_t y, unsigned char r, unsigned char g, unsigned char b) { data->r[x + data->width * y] = r; data->g[x + data->width * y] = g; data->b[x + data->width * y] = b; } color get_pixel(image *data, size_t x, size_t y) { color ret; ret.r = data->r[x + data->width * y]; ret.g = data->g[x + data->width * y]; ret.b = data->b[x + data->width * y]; return ret; } void fill(image *data, unsigned char r, unsigned char g, unsigned char b) { size_t i; for (i = 0; i < data->width * data->height; i++) { data->r[i] = r; data->g[i] = g; data->b[i] = b; } } void line(image *data, size_t x1, size_t y1, size_t x2, size_t y2, unsigned char r, unsigned char g, unsigned char b) { size_t x, y, t, pdx, pdy, ddx, ddy, es, el; int dx, dy, incx, incy, err; dx=x2-x1; dy=y2-y1; incx=SIGN(dx); incy=SIGN(dy); if(dx<0) dx=-dx; if(dy<0) dy=-dy; if (dx>dy) { pdx=incx; pdy=0; ddx=incx; ddy=incy; es=dy; el=dx; } else { pdx=0; pdy=incy; ddx=incx; ddy=incy; es=dx; el=dy; } x=x1; y=y1; err=el/2; set_pixel(data, x, y, r, g, b); for(t=0; t<el; t++) { err -= es; if(err<0) { err+=el; x+=ddx; y+=ddy; } else { x+=pdx; y+=pdy; } set_pixel(data, x, y, r, g, b); } } color average_line(image *data, size_t x1, size_t y1, size_t x2, size_t y2) { size_t x, y, t, pdx, pdy, ddx, ddy, es, el; int dx, dy, incx, incy, err; color ret; color px; size_t i; size_t j; size_t hist_r[256]; size_t hist_g[256]; size_t hist_b[256]; size_t data_len = 0; for (i = 0; i < 256; i++) { hist_r[i] = 0; hist_g[i] = 0; hist_b[i] = 0; } dx=x2-x1; dy=y2-y1; incx=SIGN(dx); incy=SIGN(dy); if(dx<0) dx=-dx; if(dy<0) dy=-dy; if (dx>dy) { pdx=incx; pdy=0; ddx=incx; ddy=incy; es=dy; el=dx; } else { pdx=0; pdy=incy; ddx=incx; ddy=incy; es=dx; el=dy; } x=x1; y=y1; err=el/2; px = get_pixel(data, x, y); hist_r[px.r]++; hist_g[px.g]++; hist_b[px.b]++; data_len++; for(t=0; t<el; t++) { err -= es; if(err<0) { err+=el; x+=ddx; y+=ddy; } else { x+=pdx; y+=pdy; } px = get_pixel(data, x, y); hist_r[px.r]++; hist_g[px.g]++; hist_b[px.b]++; data_len++; } j = 0; for (i = 0; i < 256; i++) { j += hist_r[i]; if (j >= data_len / 2) { ret.r = i; break; } } j = 0; for (i = 0; i < 256; i++) { j += hist_g[i]; if (j >= data_len / 2) { ret.g = i; break; } } j = 0; for (i = 0; i < 256; i++) { j += hist_b[i]; if (j >= data_len / 2) { ret.b = i; break; } } return ret; } void lines(image *source, image *dest, size_t L, float m, float M) { size_t i, j; float dx; float mx, my; float mm = MAX(MIN(source->width * source->height / L, M), m); unsigned char av_r = average(source->r, source->width * source->height); unsigned char av_g = average(source->g, source->width * source->height); unsigned char av_b = average(source->b, source->width * source->height); fill(dest, av_r, av_g, av_b); dx = (float)source->width / L; mx = 0; my = mm / 2; for (i = 0; i < L; i++) { color avg; mx += dx; my += (source->height - mm) / 8; if (my + mm / 2 > source->height) { my = mm / 2 + ((size_t)(my + mm / 2) % (size_t)(source->height - mm)); } avg = average_line(source, mx, my - mm / 2, mx, my + mm / 2); line(dest, mx, my - mm / 2, mx, my + mm / 2, avg.r, avg.g, avg.b); } } int main(int argc, char *argv[]) { image source; image dest; size_t L; float m; float M; load_image(argv[1], &source); L = atol(argv[2]); m = atof(argv[3]); M = atof(argv[4]); init_image(&dest, source.width, source.height); lines(&source, &dest, L, m, M); write_image(argv[5], &dest); } ``` ## L = 5000, m = 10, M = 50 ![L = 5000, m = 10, M = 50](https://i.stack.imgur.com/AHsd1.png) ## L = 5000, m = 10, M = 50 ![L = 5000, m = 10, M = 50](https://i.stack.imgur.com/EYqyz.png) ## L = 100000, m = 10, M = 50 ![enter image description here](https://i.stack.imgur.com/AN1fD.png) [Answer] ## Python 3 -based off of "somewhat random lines and then some", plus sobel edge detection. the code can theoretically run forever (so I can run it overnight for fun), but it records its progress, so all images are taken from the 1-10 min mark. It first reads the image, and then uses sobel edge detection to find the angle of all the edges, to make sure that the lines do not trespass on another color. Once a line of the random length within (lengthmin,lengthmax) is set, it then tests to see if it contributes to the overall image. While smaller lines are better, I set the line length from 10-50. ``` from random import randint, uniform import json from PIL import Image, ImageDraw, ImageFilter import math k=(-1,0,1,-2,0,2,-1,0,1) k1=(-1,-2,-1,0,0,0,1,2,1) population=[] lengthmin=10 lengthmax=50 number_lines=10**8 im=Image.open('0.png') [x1,y1]=im.size dx=0 class drawer(): def __init__(self,genome,score,filename): self.genome=genome self.score=score self.filename=filename def initpoint(self,g1): g2=self.genome im=Image.open('0.png') im1=im.filter(ImageFilter.Kernel((3,3),k,1,128)) im2=im.filter(ImageFilter.Kernel((3,3),k1,1,128)) im1=im1.filter(ImageFilter.GaussianBlur(radius=4)) im2=im2.filter(ImageFilter.GaussianBlur(radius=4)) for x in range(0,number_lines): if(x%10**4==0): print(x*100/number_lines) self.save() g1.save('1.png') (x,y)=(randint(0,x1-1),randint(0,y1-1)) w=im1.getpixel((x,y))[0]-128 z=im2.getpixel((x,y))[0]-128 w=int(w) z=int(z) W=(w**2+z**2)**0.5 if(W!=0): w=(w/W)*randint(lengthmin,lengthmax) z=(z/W)*randint(lengthmin,lengthmax) (w,z)=(z,w) (a,b)=(x+w,y+z) a=int(a) b=int(b) x=int(x) y=int(y) if(a>=x1): a=x1-1 if(b>=y1): b=y1-1 if(a<0): a=0 if(b<0): b=0 if(x>=x1): x=x1-1 if(y>=y1): y=y1-1 if(x<0): x=0 if(y<0): y=0 C=[0,0,0] D=0 E=0 F=0 G=0 W=((x-a)**2+(y-b)**2)**0.5 if(W!=0): for Z in range(0,int(W)): w=(Z/W) (c,d)=((w*x+(1-w)*a),(w*y+(1-w)*b)) c=int(c) d=int(d) C[0]+=im.getpixel((c,d))[0] C[1]+=im.getpixel((c,d))[1] C[2]+=im.getpixel((c,d))[2] C[0]/=W C[1]/=W C[2]/=W C[0]=int(C[0]) C[1]=int(C[1]) C[2]=int(C[2]) for Z in range(0,int(W)): w=(Z/W) (c,d)=((w*x+(1-w)*a),(w*y+(1-w)*b)) c=int(c) d=int(d) E=0 D=0 D+=(g1.getpixel((c,d))[0]-im.getpixel((c,d))[0])**2 D+=(g1.getpixel((c,d))[1]-im.getpixel((c,d))[1])**2 D+=(g1.getpixel((c,d))[2]-im.getpixel((c,d))[2])**2 F+=D**0.5 E+=(im.getpixel((c,d))[0]-C[0])**2 E+=(im.getpixel((c,d))[1]-C[1])**2 E+=(im.getpixel((c,d))[2]-C[2])**2 G+=E**0.5 #print((G/W,F/W)) if(G<F): for Z in range(0,int(W)): w=(Z/W) (c,d)=((w*x+(1-w)*a),(w*y+(1-w)*b)) c=int(c) d=int(d) g1.putpixel((c,d),(int(C[0]),int(C[1]),int(C[2]))) g2.append((x,y,a,b,int(C[0]%256),int(C[1]%256),int(C[2]%256))) return(g1) def import_file(self): with open(self.filename, 'r') as infile: self.genome=json.loads(infile.read()) print(len(self.genome)) def save(self): with open(self.filename, 'w') as outfile: data = json.dumps(self.genome) outfile.write(data) population.append(drawer([],0,'0.txt')) G=0 g1=Image.new('RGB',(x1,y1),'black') g1=population[0].initpoint(g1) g1.save('1.png') ``` [![American Gothic](https://i.stack.imgur.com/Pt7yl.png)](https://i.stack.imgur.com/Pt7yl.png) [![Escher](https://i.stack.imgur.com/Zoas8.png)](https://i.stack.imgur.com/Zoas8.png) ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/41522/edit). Closed 2 years ago. [Improve this question](/posts/41522/edit) This challenge's concept is pretty simple. All you have to do is write a program that will compile as both valid C and valid C++! Well, there are some catches. **The program must behave differently when compiled in each language.** The program must have different output for each language in order to be considered "behaving differently". ## Rules * The program must be both valid C and C++ * The program must have different outputs based on the language it was compiled in. * `#ifdef __cplusplus` or other "easy" preprocessor tricks are discouraged! (Other preprocessor operations are perfectly fine, though.) * Try not to make it look completely obvious that the program does something different. This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so whoever has the most interesting and surprising solution wins. Have fun! ## Example: I created my own program to see if this was even possible to do with out `#ifdef` tricks: ``` #include <stdio.h> #include <string.h> char *m="C++ rules!"; int t[11]={0,0,0,0,1,-1,-3,9,-8,82,0}; char tr(char c,int i) { return c+((sizeof('!')+1)&1)*t[i]; } int main() { int i = 0; for(;i<strlen(m);i++) { printf("%c",tr(m[i],i)); } printf("\n"); return 0; } ``` This program outputs `C++ rules!` when compiled in C++ and `C++ stinks` when compiled in C. **Explanation:** > > What causes the difference between languages is the `tr()` function. It takes advantage of one of the differences between C and C++, specifically, how char literals are treated. In C, they are treated as integers, so `sizeof('!')` returns 4, as opposed to 1 in C++. The `((...+1)&1)` part is just part of a simple bitwise operation that will return 1 if `sizeof('!')` returns 4, and 0 if it returns 1. That resulting number is multiplied by the ints in array `t` and then that product is finally added to the specific character being transformed. In C++ the product will always be zero, so the string `C++ rules!` remains unchanged. In C, the product will always be the value in `t`, and so the string changes to `C++ stinks`. > > > [Answer] # Is the cake a lie? As there has been much debate over whether the cake is or is not a lie, I wrote this program to answer this contentious question. ``` #include <stdio.h> // checks if two things are equal #define EQUALS(a,b) (sizeof(a)==sizeof(b)) struct Cake{int Pie;}; // the cake is a pie! typedef struct Cake Lie; main(){ struct CakeBox{ struct Cake{ // the cake contains lies! Lie Lies[2]; }; }; typedef struct Cake Cake; printf("The cake is "); if(EQUALS(Cake, Lie)){ printf("a LIE!\n"); }else{ printf("..not a lie?\n"); } return 0; } ``` What will the outcome be? C: > > `The cake is ..not a lie?` > > > C++: > > `The cake is a LIE!` > > > [Answer] ## Just some bools ``` #include <stdio.h> int test(bool) { return sizeof(bool) == sizeof(int); } int main(void) { puts(test(0) ? "C" : "C++"); return 0; } ``` <http://codepad.org/dPFou20W> <http://codepad.org/Ko6K2JBH> [Answer] I could have done this with a 3 line program but then it would be obvious why it produces different results for C and C++. So instead I started writing a bigger program with some stegonography which gets different results in C and C++... ``` #include <stdio.h> #include <stdlib.h> #include <string.h> struct product { int quantity; char name[20]; char desc[80]; }; struct _customer { char name[80]; struct product *products; } customer; int main(int argc, char *argv[]) { struct shipment { char tracking_number[40]; int quantity; struct product { int model; int serial; } sku; }; struct _supplier { char name[80]; struct shipment *shipments; } supplier; /* now read the command line and allocate all the space we need */ if(argc<5) { printf("Usage: %s <supplier name> <# of shipments> <customer name> <# of products> ",argv[0]); exit(1); } strcpy(supplier.name,argv[1]); int shipments_size = atoi(argv[2])*sizeof(struct shipment); printf("Allocating %d bytes for %s shipments\n", shipments_size,supplier.name); supplier.shipments=(struct shipment *)malloc(shipments_size); strcpy(customer.name,argv[3]); int products_size = atoi(argv[4])*sizeof(struct product); printf("Allocating %d bytes for %s products\n", products_size,customer.name); /* ... TODO ... finish the rest of this program later */ free(customer.products); free(supplier.shipments); return 0; } ``` You need to specify a command line. When I run it on my copy of gcc I get this output: ``` >g++ x.cpp >a.exe "Bob Supplier" 1 "Jane Customer" 1 Allocating 52 bytes for Bob Supplier shipments Allocating 104 bytes for Jane Customer products >gcc x.c >a.exe "Bob Supplier" 1 "Jane Customer" 1 Allocating 52 bytes for Bob Supplier shipments Allocating 8 bytes for Jane Customer products ``` How can things go so horribly wrong? [Answer] ``` #include <stdio.h> int c[1]; int main() { struct c { int cpp[2]; }; printf("%d\n", (int)sizeof(c)/4); } ``` [Answer] This one works with C++11 and newer and any C so far (before C11). ``` #include <stdio.h> int main() { auto a = 'a'; printf(sizeof(a) == sizeof(int) ? "C\n" : "C++\n"); return 0; } ``` See here: C++: <http://ideone.com/9Gkg75> and C: <http://ideone.com/eECSmr> It exploits the fact that in C++11 the auto keyword got a new meaning. So while a in C is of type int stored in an AUTOmatic location it is of type char in C++11. EDIT: As FUZxxl said the implicit int was removed in C11. [Answer] # Self-describing program This will print "This program is written in C!" if compiled using a C compiler; otherwise, it'll print "This program is written in C++!". It needs a C99 compiler. ``` #include <stdbool.h> #include <stdio.h> char str[] = "This program is written in C++ "; #define S (sizeof(str)-sizeof(true)-sizeof(true)%4) int main(){for(int i=S;i<=S+1;++i)str[i]=i==S?'!':'\0';puts(str);return 0;} ``` > > Most other posts take advantage of the difference of the size of a char in C vs C++; this one uses the fact that, in C99, `true` is defined to be a number. This inserts the exclamation point and null terminator based on the size of `true`. > > > [Answer] ``` #include <stdio.h> int main() { char arr[100]; printf("%zu",sizeof(0, arr)); // prints 8 in C and 100 in C++ } ``` In C the comma operator forces an [array-to-pointer conversion](https://port70.net/%7Ensz/c/c11/n1570.html#6.3.2.1p3) while in C++ the [result of the comma operator](http://eel.is/c++draft/expr.comma#1): > > The type and value of the result are the type and value of the right operand; the result is of the same value category as its right operand, > > > ]
[Question] [ [Minesweeper](https://en.wikipedia.org/wiki/Minesweeper_(video_game)) is a popular puzzle game where you must discover which tiles are "mines" without clicking on those tiles. Instead, you click on nearby tiles to reveal the number of adjacent mines. One downside about the game is that it is possible to end up in a scenario where there are multiple valid answers and you may only guess. For example, take the following board: ``` 1110 2*31 3*?? 2*4? 112? ``` In this format, a number represents the number of adjacent mines, an `*` represents a known mine, and a "?" represents a potential mine. The unfortunate thing about this particular puzzle is that there are four distinct and *valid* potential solutions: ``` 1110 1110 1110 1110 2*31 2*31 2*31 2*31 3*4* 3*5* 3**2 3**1 2*42 2*4* 2*4* 2*42 112* 1121 1121 112* ``` This means the board is *unsolvable*. Here is an example of a *solvable* board: ``` 1121 1??* 12?* 0122 ``` This board is solvable because there is only one possible valid solution: ``` 1121 1*4* 12** 0122 ``` Your task is to write either a program or function that takes a valid minesweeper board and determines if it is solvable or not. By "valid minesweeper board", I mean that the input will always be rectangular, have at least one solution, and not contain any invalid characters. Your input may be an array of characters, an array of strings, a string containing newlines, etc. The output must be a truthy value if it is solvable and a falsy value if it is not. I am not extremely worried about performance, but your solution must *theoretically* work for any size input. As usual, standard loopholes apply and the shortest solution in bytes wins! # Examples: The following examples are all solvable: ``` 1121 1??* 12?* 0122 1110 1??? 1110 0000 1110 3??? ??20 *310 **** **** **** **** 0000 0000 0000 0000 1100 *100 2321 ??*2 13*2 1221 1*10 1110 1121 2*?? 2*31 2220 1*10 ``` The following examples are all unsolvable: ``` 1110 2*31 3*?? 2*4? 112? 01??11*211 12??2323*1 1*33*2*210 12?2122321 13?3101**1 1***101221 1*** 3*52 2*31 12?? 02?? 01?? 00000111 000012*1 00001*21 22101110 **100111 ?31123*1 ?311**31 **113*20 ``` [Answer] # GNU Prolog, 493 bytes ``` z(_,[_,_]). z(F,[A,B,C|T]):-call(F,A,B,C),z(F,[B,C|T]). i([],[],[],[]). i([H|A],[I|B],[J|C],[H-I-J|T]):-i(A,B,C,T). c(A/_-B/_-C/_,D/_-_/T-E/_,F/_-G/_-H/_):-T#=A+B+C+D+E+F+G+H. r(A,B,C):-i(A,B,C,L),z(c,L). q(63,V):-var(V). q(42,1/_). q(X,0/Y):-Y#=X-48. l([],[0/_]). l([H|T],[E|U]):-q(H,E),l(T,U). p([],[[0/_,0/_]],0). p([],[[0/_|T]],N):-M#=N-1,p([],[T],M). p([H|T],[[0/_|E]|U],N):-p(T,U,N),l(H,E). m([H|A],B):-length(H,N),p([],[R],N),p([H|A],M,N),z(r,[R|M]),p(B,M,N). s(A):-setof(B,m(A,B),[_]). ``` An extra predicate that may be useful for testing (not part of the submission): ``` d([]). d([H|T]):-format("~s~n",[H]),d(T). ``` Prolog's definitely the right language for solving this task from the practical point of view. This program pretty much just states the rules of Minesweeper and lets GNU Prolog's constraint solver solve the problem from there. `z` and `i` are utility functions (`z` does a sort of fold-like operation but on sets of three adjacent elements rather than 2; `i` transposes 3 lists of *n* elements into a list of *n* 3-tuples). We internally store a cell as `*x*/*y*`, where *x* is 1 for a mine and 0 for a nonmine, and *y* is the number of adjacent mines; `c` expresses this constraint on the board. `r` applies `c` to every row of the board; and so `z(r,M)` checks to see if `M` is a valid board. Unfortunately, the input format required to make this work directly is unreasonable, so I also had to include a parser (which probably accounts for more code than the actual rules engine, and most of the time spent debugging; the Minesweeper rules engine pretty much worked first time, but the parser was full of thinkos). `q` converts a single cell between a character code and our `*x*/*y*` format. `l` converts one line of the board (leaving one cell that's known to be not a mine, but with an unknown number of neighbouring mines, at each edge of the line as a border); `p` converts the entire board (including the bottom border, but excluding the top one). All of these functions can be run either forwards or backwards, thus can both parse and pretty-print the board. (There's some annoying wiggling around with the third argument to `p`, which specifies the width of the board; this is because Prolog doesn't have a matrix type, and if I don't constrain the board to be rectangular, the program will go into an infinite loop trying progressively wider borders around the board.) `m` is the main Minesweeper solving function. It parses the input string, generating a board with a correct border (via using the recursive case of `p` to convert most of the board, then calling the base case directly to generate the top border, which has the same structure as the bottom border). Then it calls `z(r,[R|M])` to run the Minesweeper rules engine, which (with this call pattern) becomes a generator generating only valid boards. At this point, the board is still expressed as a set of constraints, which is potentially awkward for us; we could perhaps have a single set of constraints which could represent more than one board. Additionally, we haven't yet specified anywhere that each square contains at most one mine. As such, we need to explicitly "collapse the waveform" of each square, requiring it to be specifically either a (single) mine or a nonmine, and the easiest way to do this is to run it through the parser backwards (the `var(V)` on the `q(63,V)` case is designed to prevent the `?` case running backwards, and thus deparsing the board forces it to be fully known). Finally, we return the parsed board from `m`; `m` thus becomes a generator which takes a partially unknown board and generates all the known boards consistent with it. That's really enough to solve Minesweeper, but the question explicitly asks to check whether there's exactly one solution, rather than to find all solutions. As such, I wrote an extra predicate `s` which simply converts the generator `m` into a set, and then asserts that the set has exactly one element. This means that `s` will return truthy (`yes`) if there is indeed exactly one solution, or falsey (`no`) if there is more than one or less than one. `d` is not part of the solution, and not included in the bytecount; it's a function for printing a list of strings as though it were a matrix, which makes it possible to inspect the boards generated by `m` (by default, GNU Prolog prints strings as a list of ASCII codes, because it treats the two synonymously; this format is fairly hard to read). It's useful during testing, or if you want to use `m` as a practical Minesweeper solver (because it uses a constraint solver, it's highly efficient). [Answer] ## Haskell, ~~193~~ ~~169~~ 168 bytes ``` c '?'="*!" c x=[x] g x|t<-x>>" ",w<-length(words x!!0)+1=1==sum[1|p<-mapM c$t++x++t,and[sum[1|m<-[-1..1],n<-[j-w,j,j+w],p!!(m+n)=='*']==read[d]|(j,d)<-zip[0..]p,d>'/']] ``` Usage example: `g "1121 1??* 12?* 0122"` -> `True`. How it works: make list of all possible boards with the `?` replaced by either `*` or `!` (`!` means ignore later). This is done via `mapM c`, but before we prepend and append a bunch of spaces to the input string so that our indexing won't be out of range. For each such board check if it's a valid board by looping over all elements (index `j`) and if it's a number (`d>'/'`) also over its neighbors (index `n`, `m`), count the `*` and compare to the number. Finally check the length of the list of valid boards. [Answer] # Mathematica, ~~214~~ ~~192~~ ~~190~~ ~~180~~ ~~176~~ ~~174~~ ~~168~~ 165 bytes ``` 0&/@Cases[b="*";If[!FreeQ[#,q="?"],(x#0@MapAt[x&,#,#&@@#~Position~q])/@{b,0},BlockMap[If[#[[2,2]]==b,b,Count[#,b,2]]&,#~ArrayPad~1,{3,3},1]]&@#,#/.q->_,All]=={0}& ``` Contains U+F4A1 (Private use). This unnamed function finds all possible combinations for `"?"` (i.e. replacing all `"?"`s with `"*"` or `0`) and checks whether there is only one valid solution. # Explanation ``` b="*"; ``` Set `b` to `"*"`. ``` !FreeQ[#,q="?"] ``` Set `q` to the string `"?"`. Check whether there is `"?"` in the input. ``` If[ ..., (x#0 ... ,0}, BlockMap[ ... ]] ``` --- If `True`... ``` (x#0@MapAt[x&,#,#&@@#~Position~q])/@{b,0} ``` Replace the first occurrence of `q`(=`"?"`) with `b`(=`"*"`) or `0` (i.e. two outputs), and apply the entire function again. --- If `False`... ``` #~ArrayPad~1 ``` Pad the input with one layer of `0`. ``` BlockMap[If[#[[2,2]]==b,b,Count[#,b,2]]&, ... ,{3,3},1] ``` Partition the input into 3 x 3 matrices with offset 1. For each partition, apply a function such that if the middle value is `b`(=`"*"`), the output is the `b`(=`"*"`), and if the middle value is not `b`(=`"*"`), the output is the number of `b`(=`"*"`) in the input. This step re-evaluates all the number cells. --- ``` Cases[ ... ,#/.q->_,All] ``` From all of the results, find the ones that match the input ``` 0&/@ ... =={0} ``` Check whether the input is length 1. [Answer] ## Perl, 215 bytes 213 bytes of code + `-p0` flags (2 bytes). ``` /.*/;$c="@+";$_=A x$c." $_".A x$c;s/^|$/A/mg;sub t{my($_)=@_;if(/\?/){for$i(0..8,"*"){t(s/\?/$i/r)}}else{$r=1;for$i(/\d/g){$r&=!/(...)[^V]{$c}(.$i.)[^V]{$c}(...)(??{"$1$2$3"=~y%*%%!=$i?"":R})/}$e+=$r}}t$_;$_=$e==1 ``` The idea of the code is to test every possibility and see if there is one and only one that leads to a fully filled board that is valid. More readable, the code looks like: ``` /.*/;$c="@+"; # count the size of a line. $_=A x$c."\n$_".A x$c; # add a line of "A" at the begining and another at the end. s/^|$/A/mg; # add a "A" at the start and the end of each line. # The funcion that actually solves the problem sub t { my $_= pop; # Get the parameter, store it in $_ (default argument to regex). if (/\?/) { # if there is another unknown char. for $i(0..8,"*") { # try every possibility t(s/\?/$i/r) # reccursive call where the first unknown char has been replaced } } else { # no more unknown character, so here we check if the board is valid $r=1; # if r == 1 at the end, then the board is valid, otherwise it's not for $i (/\d/g) { # for each number present of the board # the following regex checks if there is a number is surrounded by either # too much or too little mines. # (how it works: magic!) $r&=!/(...)[^V]{$c}(.$i.)[^V]{$c}(...)(??{"$1$2$3"=~y%*%%!=$i?"":R})/ } $e+=$r # Increment the number of valid boards. } } t$_; # Call the previous function $_=$e==1 # Checks if there is only one valid board ($_ is implicitly printed thanks to -p flag). ``` About the regex in the middle : ``` /(...)[^V]{$c}(.$i.)[^V]{$c}(...)(??{"$1$2$3"=~y%*%%!=$i?"":R})/ ``` Note that `[^V]` just stands for "any character, including \n". So the idea is: 3 char on a line, then 3 on the next (with `$i` in the middle), then 3 on the next. those 3 groups of 3 numbers are aligned, thanks to `[^V]{$c}` and the number we're interested into is in the middle. And then, `"$1$2$3"=~y%*%%` counts the number of `*` (bombs) among those 9 characters: if it's different from `$i`, we add an empty string to match (`""` => instant matching, the regex returns true), otherwise, we force a fail by trying to match `R` (which can't be in the string). If the regex matches, then the board isn't valid, so we set `$r` to `0` with `$r&=!/.../`. And that's why we add some `A` everywhere around each line: so we don't have to worry about edges cases of numbers that are near the edges of the board: they'll have `A` as neighbors, which aren't mines (of course, roughly any char could have work, I chose `A`). You can run the program from the command line like that : ``` perl -p0E '/.*/;$c="@+";$_=A x$c."\n$_".A x$c;s/^|$/A/mg;sub t{my($_)=@_;if(/\?/){for$i(0..8,"*"){t(s/\?/$i/r)}}else{$r=1;for$i(/\d/g){$r&=!/(...)[^V]{$c}(.$i.)[^V]{$c}(...)(??{"$1$2$3"=~y%*%%!=$i?"":R})/}$e+=$r}}t$_;$_=$e==1' <<< "1121 1??* 12?* 0122" ``` The complexity couldn't be worst: it's `O(m*9^n)` where `n` is the number of `?` on the board, and `m` is the number of cells on the board (without counting the complexity of the regex in the middle, which is probably pretty bad). On my machine, it works pretty fast for up to 4 `?`, and starts to be slower 5, takes a few minutes for 6, and I didn't try for larger numbers. [Answer] # JavaScript (ES6), 221 ~~229~~ ``` g=>(a=>{for(s=i=1;~i;g.replace(x,c=>a[j++],z=j=0).replace(/\d/g,(c,p,g)=>([o=g.search` `,-o,++o,-o,++o,-o,1,-1].map(d=>c-=g[p+d]=='*'),z|=c)),s-=!z)for(i=a.length;a[--i]='*?'[+(c=a[i]<'?')],c;);})(g.match(x=/\?/g)||[])|!s ``` ~~If all input is expected to be valid - that is with at least 1 solution - then I can save a byte changing `s==1` with `s<2`~~ *Less golfed* ``` g=>{ a = g.match(/\?/g) || []; // array of '?' in a s = 1; // counter of solutions for(i=0; ~i;) // loop to find all configurations of ? and * { // get next configuration for(i = a.length; a[--i] = '*?'[+( c = a[i] < '?')], c; ); z = 0; // init at 0, must stay 0 if all cells count is ok g .replace(/\?/g,c=>a[j++],j=0) // put ? and * at right places .replace(/\d/g,(c,p,g)=>( // look for mines in all 8 directions // for each mine decrease c // if c ends at 0, then the count is ok [o=g.search`\n`,-o,++o,-o,++o,-o,1,-1].map(d=>c-=g[p+d]=='*'), z|=c // z stays at 0 if count is ok )) // check neighbour count s-=!z // if count ok for all cells, decrement number of solutions } return s==0 // true if exactly one solution found } ``` **Test** ``` F= g=>(a=>{for(s=i=1;~i;g.replace(x,c=>a[j++],z=j=0).replace(/\d/g,(c,p,g)=>([o=g.search` `,-o,++o,-o,++o,-o,1,-1].map(d=>c-=g[p+d]=='*'),z|=c)),s-=!z)for(i=a.length;a[--i]='*?'[+(c=a[i]<'?')],c;);})(g.match(x=/\?/g)||[])|!s out=x=>O.textContent+=x+'\n' Solvable=['1121\n1??*\n12?*\n0122' ,'1110\n1???\n1110\n0000' ,'1110\n3???\n??20\n*310' ,'****\n****\n****\n****' ,'0000\n0000\n0000\n0000' ,'1100\n*100\n2321\n??*2\n13*2\n1221\n1*10\n1110' ,'1121\n2*??\n2*31\n2220\n1*10'] Unsolvable=['1110\n2*31\n3*??\n2*4?\n112?' ,'01??11*211\n12??2323*1\n1*33*2*210\n12?2122321\n13?3101**1\n1***101221' ,'1***\n3*52\n2*31\n12??\n02??\n01??' ,'00000111\n000012*1\n00001*21\n22101110\n**100111\n?31123*1\n?311**31\n**113*20'] out('Solvable') Solvable.forEach(t=>out(t+'\n'+F(t)+'\n')) out('Unsolvable') Unsolvable.forEach(t=>out(t+'\n'+F(t)+'\n')) ``` ``` <pre id=O></pre> ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 167 bytes ``` s=>g=(r=c='',[p,...q]=s,w)=>w?0:p?(g(r+0,q,p=='*')+g(r+1,q,1/p),c==1):c-=-![...s].some((p,i)=>p>' '&&[-1,1,-q,-1-q,-2-q,q,q+1,q+2].map(j=>p-=~~r[i+j])|p,q=s.search` `) ``` [Try it online!](https://tio.run/##XZFBbsIwEEX3PkW7IbbjpJ5Ju6Ey3nGJEDUojWgQEBOjsqm4Op1xWOFIX@Px@L9vZb/93cZuGsKlOI3f/X3t7tGtdk5OrnNZZupgyrI8Ny6aq3Krq7fL4OVOTrk1ZxOcy3Smct4D7eEtKNM5B2rZFa54relubMo4HnspgxnIIayyl2yxqAswYIqzKYAFSehjkxyb8rgNck@zhbvdpnrI9436C@bsYhn77dT9tKJV90/RAiAI8F4LQBILiEIAgOWmnytL69GsuOk9WqEr2gpN61nm@Seh66SaBStCEhEFVCzICTQTmSBSItTEQWIIRIKl4/k8Nav5@J0DoicihQXQCMDP8ESoNJtWBKCu5S4SiMlQeYoOOg2Q2hQg1eT7gTOBbYRNQt7zmywFSAWgfhSasxIgRWOzNEMASAm40GxHR/xY25YxHIZLuzltTm36SV9u1Y2nOB768jDu5Fp@KamUuv8D "JavaScript (Node.js) – Try It Online") Though op say "input will always be rectangular, have at least one solution", false sample 3 doesn't match, so I still require 1 solution, not <2 solution ``` s=>( // p.s. Here "block" can also mean \n c=0, // possible mine count g=( // recursive r='', // mine states [p,...q]=s, // known info to check possible state for a block w // invert condition, stop if true )=> w?0: p?( // for each block g(r+0,q,p=='*')+ // possibly not bomb if doesn't say so g(r+1,q,1/p), // number/newline can't be bomb c==1 // only one bomb ): c-=-![...s].some( // no block doesn't satisfy (p,i)=> p>' '&& // \n don't mean number // other symbols turn into NaN when counting [-1,1,-q,-1-q,-2-q,q,q+1,q+2].map(j=>p-=~~r[i+j]) // subtract each neighbor, OOB = 0 |p, // difference between intended and actual q=s.search('\n') // how many blocks in a line ) ) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 78 bytesSBCS ``` {1=+/∧/∘,¨{⍵[1;1]∊' *',⍕+/'*'=,⍵}⌺3 3¨(⊂⍵){' *'[⍵]@c⊢⍺}¨,⍳2⊣¨c←⍸'?'=⍵}(⊢↑⍨2⌈⍴) ``` [Try it online!](https://tio.run/##jZJPaxNBGMbv@ynmNsk0NTsz9SRhlShYUARTD1J6mCSTZslmN@wGWim5KJQQukUPBS9e9ODePGhBctyPMl8kvu/Mrm2siAPJO7Pvn/k9z66aRbvDNypKjjfm8qr35N6r7vPHtJ@chvExSWJqVl90rPqR7j16dgAHKOq@ppmK5tSD/f4Lc/7e97IkgnhGiMk/we8aDtMw1tmJ1jOdkn6i0iFRGVFkMFapGszh4VTN0/DUI2SQJOkwgxaT/6QB7UC/G2QTYazmOiPJiEAOqqcqm2Bxy@TfBQCVhet3LbMky0Kghd5pH1vDJLbN/UjFE6LiIUEwmJPqWaQGGrEpYfTQ5OujhxXK6jMwLCqIVAMAkDsRJ@F8TDIdadDgZmUoYawHE1Sw/No2y4@tM@g/5A/4kVmucDrAXu20KaOdFk42F2tJJPTxzk7bCmrYCTVUsyzM6i1UeovNGdbUc8vivyaXRcP1N2tt16DNylovyuKWdVuuLxpYcv7B5IUwF0uT/2huRrbi0r3q1bvym8QC@FJeduH/4Ol@bwNN1huobECSci44JZQHAcMgbPC5ELRZ5bnv8gEGd/JhbeelyweBwBOTvM4zWPjkbmh6o7JwL8r7k8peQP4W6lvtE@aCkFYDSBDIKF0QThhz/Jzf9NqEYJZYACsGYcFt9W2wEeGEg7fwzjy6i4t6dy20V1STZD13zxkmgupeHzzknAnOndEBYEvmGCUwQ8Z3GQHsThKXAVjJWVUG0be6/uWdcB5Ldl/cUOF9aGEVAKWmwsUtk90J9nvLnE@AVSnE66tawOIVPW6ZuwUK0P0tC38B "APL (Dyalog Unicode) – Try It Online") A function that takes a 2-dimensional character matrix as its right argument, and gives 1 if the board is solvable (has unique solution) and 0 otherwise. ### How it works This is a straightforward implementation of the challenge description. Dimension extension is needed because the stencil operator isn't happy with too small arrays. Ungolfed version: ``` sol←{ coords←⍸'?'=⍵ masks←,⍳2⊣¨coords replace←{' *'[⍺]@coords⊢⍵} check←∧/∘,{⍵[1;1]∊' *',⍕+/'*'=,⍵}⌺3 3 1=+/masks(check replace)¨⊂⍵ }(⊢↑⍨2⌈⍴) ``` With comments: ``` sol←{ ⍝ ⍵←minesweeper board as a character matrix ⍝ 2D coordinates of '?' coords←⍸'?'=⍵ ⍝ possible combinations of blank as 0 and mine as 1 masks←,⍳2⊣¨coords 2⊣¨coords ⍝ (≢coords) copies of 2 ,⍳ ⍝ cartesian product of 0..n-1 for each n in the above ⍝ create a board with selected mines replace←{' *'[⍺]@coords⊢⍵} { } ⍝ a function ⊢⍵ ⍝ take the array ⍵ @coords ⍝ replace the items at given coords ' *'[⍺] ⍝ ... into blanks and mines as specified ⍝ by boolean array ⍺ ⍝ test if the complete board is valid check←∧/∘,{⍵[1;1]∊' *',⍕+/'*'=,⍵}⌺3 3 { }⌺3 3 ⍝ for each 3x3 subarray (including ones centered at the edges) ⍕+/'*'=,⍵ ⍝ s←count the mines and cast to string ⍵[1;1]∊' *', ⍝ check if the center is one of blank, mine, or s ∧/∘, ⍝ reduce by AND for all subarrays ⍝ for all combinations, check if the board has unique solution 1=+/masks(check replace)¨⊂⍵ masks( replace)¨⊂⍵ ⍝ generate all possible boards check ⍝ check each board if it is a valid solution 1=+/ ⍝ check that there's exactly one valid solution in total }(⊢↑⍨2⌈⍴) ⍝ extend each dimension to have at least length 2 before calling main function ⍴ ⍝ dimensions 2⌈ ⍝ max(n,2) for each dimension ⊢↑⍨ ⍝ extend the input to have ^ dimension; fill extended cells with blank ``` ]
[Question] [ [Tab completion](https://en.wikipedia.org/wiki/Command-line_completion) is a useful feature that auto-completes partially written commands. You're going to be implementing it. For example, if the available commands were `['apply','apple','apple pie','eat']`, then `a` would complete to `appl`, as all of the commands that start with `a` also start with `appl`. # Input/Output You need to input a string, A, and a set of strings, B. You need to output the longest common prefix of all B that starts with A. * If none of the options starts with A, then return A * You can assume that B is nonempty, and that all strings are nonempty * You cannot assume that any of the options start with A, nor that the common prefix will be longer than A * You can be case sensitive or case insensitive. * You only need to handle printable ASCII * Built-ins that explicitly do this task are allowed # Test cases: ``` 'a' ['apply','apple','apple pie','eat'] => 'appl' 'a' ['apple pie'] => 'apple pie' 'apple' ['eat','dine'] => 'apple' 'program' ['programa','programb'] => 'program' '*%a(' ['*%a()-T>','*%a()-T<','@Da^n&'] => '*%a()-T' 'a' ['abs','absolute','answer'] => 'a' 'a' ['a','abs'] => 'a' 'one to' ['one to one','one to many'] => 'one to ' ``` Note the trailing space on the last test case This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your answers as short as possible! [Answer] ## JavaScript (ES6), 75 bytes ``` (s,a)=>/^(.*).*(\n\1.*)*$/.exec(a.filter(e=>e.startsWith(s)).join` `)[1]||s ``` Explanation: Filters on all matching prefixes, then joins with newlines and matches against a regex that finds the longest common prefix of all lines. If there are no prefixes then the regex returns an empty string in which case we simply return the original string. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḣJ$€ċÐff\ṪṪȯ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bijSiTigqzEi8OQZmZc4bmq4bmqyK8&input=&args=WydhcHBseScsJ2FwcGxlJywnYXBwbGUgcGllJywnZWF0J10+J2En) or [verify all test cases](http://jelly.tryitonline.net/#code=4bijSiTigqzEi8OQZmZc4bmq4bmqyK8Kw6dAMi9Z&input=&args=J2EnLCBbJ2FwcGx5JywnYXBwbGUnLCdhcHBsZSBwaWUnLCdlYXQnXSAsICdhJywgWydhcHBsZSBwaWUnXSAsICdhcHBsZScsIFsnZWF0JywnZGluZSddICwgJ3Byb2dyYW0nLCBbJ3Byb2dyYW1hJywncHJvZ3JhbWInXSAsICcqJWEoJywgWycqJWEoKS1UPicsJyolYSgpLVQ8JywnQERhXm4mJ10gLCAnYScsIFsnYWJzJywnYWJzb2x1dGUnLCdhbnN3ZXInXSAsICdvbmUgdG8nLCBbJ29uZSB0byBvbmUnLCdvbmUgdG8gbWFueSdd). ### How it works ``` ḣJ$€ċÐff\ṪṪȯ Main link. Left argument: B. Right argument: A $€ Convert the two links to the left into a monadic chain and apply it to each string s in B. J Generate the indices of s, i.e., [1, ..., len(s)]. ḣ Head; for each index i, take the first i characters of s. This generates the prefixes of all strings in B. Ðf Filter; keep prefixes for which the link to the left returns 1. ċ Count the number of times A appears in the prefixes of that string. f\ Do a cumulative (i.e., keeping all intermediate values) reduce by filter, keeping only common prefixes. f/ is a more obvious choice, but it errors on an empty array, i.e., when A isn't a prefix of any string in B. Ṫ Tail; take the last prefix array (if any) or return 0. Ṫ Tail; take the last common prefix (if any) or return 0. ȯ Logical OR (flat); replace 0 with A, leave strings untouched. ``` [Answer] # Pyth, ~~14~~ 13 bytes *Thanks to @isaacg for -1 byte* ``` .xe@F/#z._MQz ``` A program that takes the list of strings, and then the string, on STDIN and prints the result. [Verify all test cases](https://pyth.herokuapp.com/?code=.xe%40F%2F%23z._MQz&test_suite=1&test_suite_input=%5B%27apply%27%2C%27apple%27%2C%27apple+pie%27%2C%27eat%27%5D%0Aa%0A%5B%27apple+pie%27%5D%0Aa%0A%5B%27eat%27%2C+%27dine%27%5D%0Aapple%0A%5B%27programa%27%2C+%27programb%27%5D%0Aprogram%0A%5B%27%2a%25a%28%29-T%3E%27%2C+%27%2a%25a%28%29-T%3C%27%2C+%27%40Da%5En%26%27%5D%0A%2a%25a%28%0A%5B%27one+to+one%27%2C+%27one+to+many%27%5D%0Aone+to&debug=0&input_size=2) **How it works** ``` .xe@F/#z._MQz Program. Inputs: Q, z ._MQ Map prefixes over Q /#z Filter that by count(z)>0, removing the prefixes corresponding to elements in Q that do not start with z @F Fold intersection over that. This yields all the common prefixes e Yield the last element of that, giving the longest common prefix, since the prefixes are already sorted by length .x But if that throws an exception since no elements of Q start with z: z Yield z instead Implicitly print ``` [Answer] ## PowerShell v3+, 112 bytes ``` param($a,$b)if($c=@($b-like"$a*")){([char[]]$c[0]|%{($i+="$_")}|?{($c-like"$_*").count-eq$c.count})[-1]}else{$a} ``` Takes input as a string `$a` and an array of strings `$b`. Uses the `-like` operator to pull out those elements from `$b` that (case-insensitive) starts with `$a`, explicitly cast those as an array `@(...)` (since the result could be one match as a scalar, in which case indexing later fails), and store that array into `$c`. That forms the `if` clause. If there's nothing in `$c` (i.e., nothing starts with `$a`, so the array is empty), then output `$a` with the `else`. Otherwise ... We cast the first element of `$c` as a `char`-array and loop through each element, string-concatenating with the previous `$i` and placing the strings on the pipeline via encapsulating parens. Those are filtered through `|?{...}` (the `Where-Object` clause) to verify that the `.count` of `$c` is `-eq`ual to the `.count` of things in `$c` that are `-like` the substring (i.e., the substring matches everything in $c). Since we're building our substrings in order shortest to longest, we need the last `[-1]` of the resultant strings. ### Test Cases ``` PS C:\Tools\Scripts\golfing> $tests=@('a',@('apply','apple','apple pie','eat')),@('a',@('apple pie')),@('apple',@('eat','dine')),@('program',@('programa','programb')),@('one to',@('one to one','one to many')),@('*%a(',@('*%a()-T>', '*%a()-T<', '@Da^n&')) PS C:\Tools\Scripts\golfing> $tests|%{""+$_[0]+" ("+($_[1]-join',')+") -> "+(.\implement-tab-completion.ps1 $_[0] $_[1])} a (apply,apple,apple pie,eat) -> appl a (apple pie) -> apple pie apple (eat,dine) -> apple program (programa,programb) -> program one to (one to one,one to many) -> one to *%a( (*%a()-T>,*%a()-T<,@Da^n&) -> *%a()-T ``` [Answer] ## Python 2, 122 bytes ``` s=input();l=[x for x in input()if x[:len(s)]==s]or[s];i=len(l[0]) while len(l)>1:i-=1;l=set(x[:i]for x in l) print l.pop() ``` Full program; takes string and list from stdin exactly as given in the examples, except the inputs must be on separate lines. [Verify all test cases](http://ideone.com/winJs0) [Answer] # Perl, 54 bytes Includes +2 for `-Xp` (can be combined with `-e`) and +3 for `-i` (cannot be combined) Give dictionary on STDIN and the word after the `-i` option, e.g.: ``` perl -ia -Xpe '/^\Q$^I\E.*?(?{$F[$a{$&}++]=$&})^/}{$_=pop@F||$^I' apply apple apple pie eat ^D ``` Just the code: ``` /^\Q$^I\E.*?(?{$F[$a{$&}++]=$&})^/}{$_=pop@F||$^I ``` [Answer] # Perl, 61 bytes Includes +2 for `-0p` Run with the first word followed by the dictionary words on STDIN: ``` tabcompletion.pl a apply apple apple pie eat ^D ``` `tabcompletion.pl`: ``` #!/usr/bin/perl -0p /^(.+) ((?!\1).* )*(\1.*).* ((?!\1).* |\3.* )*$| /;$_=$3||$` ``` [Answer] # Python 2, 112 bytes ``` lambda n,h:[a.pop()for a in[{s[:-i]for s in h if s.find(n)==0}for i in range(-len(`h`),0)]+[{n}]if len(a)==1][0] ``` [Answer] ## Haskell, 67 bytes ``` (a:b)?(c:d)|a==c=a:(b?d) _?_="" s%l=foldr1(?)$max[s][x|x<-l,x?s==s] ``` The auxiliary function `?` finds the longest common prefix of two strings by recursively taking the first character as long as it's the same for both strings and the strings are non-empty. The main function `%` first keeps only the strings in the list that start with the given one `s`, checked by the longest common prefix with `s` being `s`. To handle there being no valid competitions, it adds `s` to an empty result via `max`. Then, it finds the longest common prefix of those by folding the binary function `?`. [Answer] # Python 2, 75 bytes ``` import os lambda s,x:os.path.commonprefix([t for t in x if s<=t<s+'ÿ'])or s ``` *Thanks to @xnor for suggesting the built-in, originally used by @BetaDecay in [this answer](https://codegolf.stackexchange.com/a/62800/12012).* For scoring purposes, `ÿ` can be replaced with a DEL byte. Test it on [Ideone](http://ideone.com/5OCJjn). [Answer] ## D, 88 bytes ``` S f(S)(S p,S[]q){try p=q.filter!(a=>a.startsWith(p)).fold!commonPrefix;catch{}return p;} ``` **Usage:** ``` assert(f("a", ["apply","apple","apple pie","eat"]) == "appl"); ``` The code simply removes all elements from `q` that don't start with `p`, then computes the largest common initial subsequence of the remaining elements. The templated parameters save us two repetitions of `string` and one of `auto`. The exception misuse lets us avoid the temporary variable and conditional that would otherwise be necessary to handle the case where no elements of `q` start with `p`. [Answer] # Python 2, ~~107~~ 102 bytes ``` s,x=input();r='';q=1 for c in zip(*[t for t in x if s<=t<s+'ÿ']):q/=len(set(c));r+=c[0]*q print r or s ``` For scoring purposes, `ÿ` can be replaced with a DEL byte. Test it on [Ideone](http://ideone.com/HhyJFs). *Thanks to @xnor for saving 5 bytes!* [Answer] # PHP, ~~167~~ ~~160~~ ~~157~~ 152 bytes ``` <?for($r=preg_grep("$^".preg_quote($s=$_GET[s])."$",$a=$_GET[a]);$r[0]>$s&&preg_grep("$^".preg_quote($t=$s.$r[0][strlen($s)])."$",$a)==$r;)$s=$t;echo$s; ``` I could save 3 more bytes by assigning variables with `preg_grep` and `preg_quote`, but eh. **breakdown** ``` for( // find items in $a that start with $s $r=preg_grep("$^".preg_quote($s=$_GET[s])."$",$a=$_GET[a]); // while the first match is longer than $s $r[0]>$s // and appending the next character of the first match &&preg_grep("$^".preg_quote($t=$s.$r[0][strlen($s)])."$",$a) // does not change the matches ==$r ;) // keep appending $s=$t; return$s; ``` [Answer] # PHP, 156 Bytes with much Help from Titus Thank You ``` <?foreach($_GET[t]as$v)if(strstr($v,$s=$_GET[s])==$v)$r[]=$z=$v;for(;$i++<strlen($z);){$s=substr($z,0,$i);foreach($r as$x)if($x[$i]!=$z[$i])break 2;}echo$s; ``` # PHP, 199 Bytes 32 Bytes saves by Titus with array\_unique ``` <?foreach($_GET[t]as$v)if(strstr($v,$s=$_GET[s])==$v)$r[]=$v;for(;$i++<strlen($r[0]);$a=[]){foreach($r as$x)$a[]=substr($x,0,$i);if(count($r)==count($a)&count(array_unique($a))<2)$s=$a[0];}echo$s; ``` I know that the Regex Solution by Titus was shorter till Titus help me to improve my way. Maybe the way I found is interesting for you [Answer] ## Retina, 60 bytes ``` ^(.*)(\n(?!\1).*)*(\n(\1.*)).*(\n((?!\1)|\4).*)*$ $4 s`\n.* ``` The trailing new line is significant. Takes input as the string on a line and then each word on a separate line (but no trailing newline!). Works in a similar way to my JavaScript answer by matching the longest common prefix of all lines that begin with the string on the first line. If it doesn't find one then it simply deletes all the words. [Answer] # Scala, 119 bytes ``` def f(s:String,a:Seq[Char]*)=a filter(_ startsWith s)reduceOption(_ zip _ takeWhile(t=>t._1==t._2)map(_._1))getOrElse s ``` Ungolfed: ``` def tabComplete(input: String, options: Seq[Char]*) = { options. filter((x: String) => x.startsWith(input)). reduceOption((x: Seq[Char], y: Seq[Char]) => x.zip(y). takeWhile((t: (Char, Char)) => t._1 == t._2). map((t: (Char, Char)) => t._1) ).getOrElse(input) } ``` Explanation: ``` def g(s:String,a:Seq[Char]*)= //define a method g with a string and a vararg array of strings as parameter a filter(_ startsWith s) //filter the options to contains only elements starting with the input reduceOption( //if the filtered array is nonempty, reduce it: _ zip _ //zip two elements together takeWhile(t=>t._1==t._2) //take the tuples while they contain the same char map(_._1) //take the first element from each tuple )getOrElse s //else return the input ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 101 bytes *Based on [Nail's awesome regexp](https://codegolf.stackexchange.com/a/94420/80745)*. ``` if($args-join' '-cmatch'^(.*)(\n(?!\1).*)*(\n(\1.*)).*(\n((?!\1)|\4).*)*$'){$Matches.4}else{$args[0]} ``` [Try it online!](https://tio.run/##jVLLboMwELzzFW7kZG0EUSPlVPXBodfeeitN5SSbhAoMwkRtRPh2umAe6eNQH@yZnZnVYpylH5ibA8ZxzXfsjpV1tBNc5Xvjv6eRBgf8TaKKzQFWYu5KEWrxcBUuJGG3IeGCELEGW@UcLluVgyz5UxNFM19WGBss28Yv169VXTlOIBxGyxOgsiwG1i0PFIyQlBN4gAoswf5kWYRWkJdtbP2vNlb5bv7hsDlUBTXeRvrCneXpPlcJdO6BDrCZr4PrMeZOlZD@cx9rKIyQlHsY4C3B4FGt9OxiyOFWfn3R2kC7p/GxaC9FG/qT/4ra4GhNNbIiZf2UlsIIGR0wkETpE2UlO7MpK9seHD8z3BS49RhX9Ij4my3naI5xQYUZva1AtcUJF13dj/QQlDe9e@JU9Rc "PowerShell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ʒIÅ?}€ηøʒË}‚˜θ ``` [Try it online](https://tio.run/##yy9OTMpM/f//1CTPw632tY@a1pzbfnjHqUmHu2sfNcw6Pefcjv//o5USCwpyKpV0wHQqjFYoyASxUxNLlGK5EgE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeWHv4Qku9qFKCol5KQpK9pXndrjYKyk8apsE5Pw/NSnicKt97aOmNee2H95xatLh7tpHDbNOzzm347/O/@hopUQlHQUgWVCQU6mkA6ZTYbRCQSaInZpYohQbC1alpBONJAUVhGiJBqvTUUrJzIPJFBTlpxcl5oLkoEygATBmElSRlmqiBkgFiNbUDbEDqoAybYBMB5fEuDw1FOuTikHuSyrOzyktATs1r7g8tQhFCVhBMlQoPy9VoSQfJA5hKQApoAIoJzcxrxKqMBmkJjk/JbUCKJ2UAzIFxEvPz0kDqogFAA). **Explanation:** ``` ʒ } # Filter the (implicit) input-list IÅ? # Does it start with the (second) input-string # i.e. ["codex","bla","codegolf"] and "c" → ["codex","codegolf"] €η # Then take the prefixes of every remaining string # → [["c","co","cod","code","codex"], # ["c","co","cod","code","codeg","codego","codegol","codegolf"]] ø # Zip/transpose; swapping rows/columns # → [["c","c"],["co","co"],["cod","cod"],["code","code"],["codex","codeg"]] ʒ } # Filter: Ë # Only keep sublists which only contain the same substrings # → [["c","c"],["co","co"],["cod","cod"],["code","code"]] ‚ # Pair it with the (second implicit) input # → ["c",["c","c"],["co","co"],["cod","cod"],["code","code"]] # (workaround if nothing in the input-list starts with the input-string) ˜ # Flatten this list # → ["c","c","c","co","co","cod","cod","code","code"] θ # And only leave the last item (which is output implicitly as result) # → "code" ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), 12 bytes ``` e…¦&⊢…Ė⁇_+ₔ) ``` [Try it online!](https://tio.run/##S0/MTPz/P/VRw7JDy9QedS0CMo5Me9TYHq/9qGmK5v//0Y8a5iQWFOQAVcyFMiuBzFiuAgA "Gaia – Try It Online") Takes input as B, then A. ``` e | eval B as list of strings …¦ | take prefixes of each string &⊢ | reduce by set intersection … | take list prefixes of each. Ė⁇ | Keep only those with A as an element _ | flatten +ₔ | add A to the beginning of the list ) | take the last element ``` ]
[Question] [ Each cell in a [life-like cellular automaton](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) only needs one bit to represent it since it can only be alive or dead. That means there are only two colors; pretty boring. Normal images have 24 bits per pixel (8 in each of R G B). This means in a normal image with pixels as cells you could simulate 24 life-like games at once! # Challenge Your task is to write a program that will apply one generation of the rules of a life-like cellular automaton to a 24-bit depth image (in any well known format you like), and output the resulting image. Each of the 24 layers will use the same life-like ruleset, strictly within it's own layer. **The 24 layers do not interact with each other.** **Also** * Zeros are dead cells and ones are live cells. * Boundary conditions are periodic (forming a torus). * Any image dimensions should work. # Input/Output Your program needs to take in 3 arguments, via stdin or command line (or your language's closest equivalent): 1. The name of the input image file. 2. A string of the digits 0 to 8 in increasing order that denotes when new cells are born: * If the digit *d* is in the string then dead cells come alive when they have *d* living neighbors. * Example: `3` is normal [Life](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) - Dead cells with exactly 3 living neighbors come to life. 3. A string of the digits 0 to 8 in increasing order that denotes when existing cells survive: * If the digit *d* is in the string then living cells with *d* living neighbors survive to the next generation, otherwise they die. * Example: `23` is normal Life - Only cells with exactly 2 or 3 neighbors survive to the next round. *Note that the [Moore neighborhood](http://en.wikipedia.org/wiki/Moore_neighborhood) is always used. Read [this](http://en.wikipedia.org/wiki/Life-like_cellular_automaton) or [this](http://www.conwaylife.com/wiki/Cellular_automaton) for more info on what precisely defines a life-like automaton and many interesting rulesets.* The 1-generation-later output image should either be displayed or saved as `out.png` (or `bmp` or whatever). # Submission The shortest code in bytes wins. You are **required** to include at least one test image and its three immediate subsequent generations for some non-trivial ruleset. Use your avatar and the normal Life rules if you can't think of anything better. If you like you may use this [Gosper Glider Gun](http://www.conwaylife.com/wiki/Gosper_glider_gun) where the only living bits are in the green 128 layer (it's only sure to work in normal Life): ![glider gun](https://i.stack.imgur.com/DiHi7.png) Posting interesting sequences or even animations is highly encouraged. [Answer] # MATLAB: 275 My favorite of the parameters I tried is `45678`, `568` which following a gradual disintegration results in a sky of twinkling stars. This image depicts, "the disintegration of the persistence of memory." ![](https://i.stack.imgur.com/3bQp2.gif) Ungolfed gif-producing code (accepts PNG without extension): ``` B = input('B', 's') - 48; S = input('S', 's') - 48; f0 = input('file: ', 's'); frames = 60; f = sprintf('%s.png',f0); fout = sprintf('%s.gif',f0); first = 1; img = imread(f); for i = 1:60 out = img * 0; [r, c, turd] = size(img); for b=0:7 bimg = ~~bitand(img,2^b); pimg = [bimg,bimg,bimg;bimg,bimg,bimg;bimg,bimg,bimg]; fun = @(ro,co) pimg(r+ro:r+r+ro-1,c+co:c+c+co-1,:); sum = fun(0,0)+fun(0,1)+fun(0,2)+fun(1,0)+fun(1,2)+fun(2,0)+fun(2,1)+fun(2,2); bnew = uint8(bimg & ismember(sum,S) | ~bimg & ismember(sum, B)); out = out + 2^b * bnew; end %imwrite(out,'out.png'); if first [img1,img2] = rgb2ind(img,256); imwrite(img1,img2,fout,'gif','Loop',Inf); imwrite(img1,img2,fout,'gif','WriteMode','append'); first = 0; end img = out; [img1,img2] = rgb2ind(img,256); imwrite(img1,img2,fout,'gif','WriteMode','append');%,'DelayTime', 2*delay); end ``` Golfed code that accepts a full filename (which can be GIF, JPEG, and perhaps other stuff) and writes to `out.png`: ``` I=@()input('','s');B=I();S=I();i=imread(I());o=0;[r,c,t]=size(i);for b=0:7 g=~~bitand(i,2^b);p=repmat(g,3);F=@(z,Z)p(r+z:r+r+z-1,c+Z:c+c+Z-1,:);M=@(A)ismember(F(0,0)+F(0,1)+F(0,2)+F(1,0)+F(1,2)+F(2,0)+F(2,1)+F(2,2),A-48);o=o+2^b*uint8(g&M(S)|~g&M(B));end imwrite(o,'out.png') ``` A previously discovered fact is that parameters `12`, `1` can be used to generate a Sierpinski carpet-like fractal. Here is one with a randomly placed seed point in each bit: ![](https://i.stack.imgur.com/bbgU7.gif) [Answer] ## Mathematica, 359 ``` i=InputString;f=Transpose;b=(p=FromDigits/@Characters@#&)@i[];s=p@i[];Map[FromDigits[#,2]&/@#~ArrayReshape~{3,8}&,f[(g=#;{#,Total[g~RotateRight~#&/@Drop[Join@@Table[{i,j},{i,-1,1},{j,-1,1}],{5}],1]}~f~{3,1,2}/.{l_,n_}:>Boole[l<1&&!b~FreeQ~n||l>0&&!s~FreeQ~n])&/@Apply[Join,IntegerDigits[ImageData[Import@i[],y="byte"],2,8],{2}]~f~{2,3,1},{3,1,2}],{2}]~Image~y ``` I'm taking input from string prompts in the order (1) birth rules, (2) survival rules, (3) file name, and I'm displaying the result right in Mathematica. This should be able to deal with most popular formats, as long as the file actually has 24-bit depth. Here is a somewhat ungolfed version: ``` i = InputString; f = Transpose; b = (p = FromDigits /@ Characters@# &)@i[]; s = p@i[]; Map[ FromDigits[#,2] & /@ #~ArrayReshape~{3, 8} &, f[ ( g = #; {#, Total[g~RotateRight~# & /@ Drop[Join @@ Table[{i, j}, {i, -1, 1}, {j, -1, 1}], {5}], 1]}~f~{3, 1, 2} /. {l_, n_} :> Boole[l < 1 && ! b~FreeQ~n || l > 0 && ! s~FreeQ~n] ) & /@ Apply[Join, IntegerDigits[ImageData[Import@i[], y = "byte"], 2, 8], {2}]~ f~{2, 3, 1}, {3, 1, 2} ], {2} ]~Image~y ``` Here are two examples using [Rainbolt](https://codegolf.stackexchange.com/users/18487/rainbolt)'s avatar: ![Rainbolt](https://i.stack.imgur.com/Rc1kv.jpg?s=128&g=1) 20 generations using the standard Game of Life `[3,23]`: ![enter image description here](https://i.stack.imgur.com/XvFKr.png) 20 generations using `[456,34567]`: ![enter image description here](https://i.stack.imgur.com/JmOmP.png) And here is a GIF of the first 200 generations of the latter rule. The GIF skips every third frame, because I couldn't compress it below 2MB otherwise: ![enter image description here](https://i.stack.imgur.com/OBHdZ.gif) [Answer] # Python 2, 427 For those who don't have Mathematica ;) ``` import Image as I t=raw_input r=range A=I.open(t()) G=map(int,t()) S=map(int,t()) w,h=A.size B=I.new('RGB',(w,h)) A=[[map(int,("{:08b}"*3).format(*A.load()[x,y]))for y in r(h)]for x in r(w)] for x in r(w): for y in r(h): p='' for i in r(24): c=A[x][y][i] n=sum(A[(x+k-1)%w][(y+j-1)%h][i]for j in r(3)for k in r(3))-c p+=str(~~[n in G,n in S][c]) B.load()[x,y]=tuple(int(p[i*8:i*8+8],2)for i in r(3)) B.save('out.bmp') ``` It prompts for the filename, then the birth cases, then the survival cases. So for normal life rules you might input `test.bmp`, then `3`, then `23` (no quotes or anything needed). I used string formatting to index into and recombine the color bits, though I fear that's probably not optimal. Note that's it's pretty slow. # Example [High life](http://en.wikipedia.org/wiki/HighLife) and great art mix right? (Rule `36` / `23`.) ![Mona Lisa Original](https://i.stack.imgur.com/3Zlt4.png) ![generation 1](https://i.stack.imgur.com/N1TKf.png) Original / Generation 1 ![generation 2](https://i.stack.imgur.com/HUbuZ.png) ![generation 3](https://i.stack.imgur.com/1tSDD.png) Generation 2 / Generation 3 [Answer] # Java, 1085 bytes ``` import java.awt.image.*;import java.io.*;import javax.imageio.*;class F{static int n(boolean[][][]a,int x,int y,int z){int k=0;for(X=Math.max(x-1,0);X<Math.min(x+2,w);X++)for(Y=Math.max(y-1,0);Y<Math.min(y+2,h);Y++)if(a[X][Y][z])k++;return k-(a[x][y][z]?1:0);}static int p(String k){return Integer.parseInt(k,2);}static int w,h,x,y,z,X,Y;public static void main(String[]a)throws Exception{BufferedImage i=ImageIO.read(new File(a[0]));w=i.getWidth();h=i.getHeight();boolean[][][]G=new boolean[w][h][24];for(x=0;x<w;x++)for(y=0;y<h;y++){String k="".format("%24s",Integer.toBinaryString(0xFFFFFF&i.getRGB(x,y)));for(z=0;z<24;z++){G[x][y][z]=k.charAt(z)>48;}}for(x=0;x<w;x++)for(y=0;y<h;y++){String r="",g="",b="",k;for(z=0;z<8;){k=""+n(G,x,y,z);r+=(-1!=(G[x][y][z++]?a[1].indexOf(k):a[2].indexOf(k)))?1:0;}for(;z<16;){k=""+n(G,x,y,z);g+=(-1!=(G[x][y][z++]?a[1].indexOf(k):a[2].indexOf(k)))?1:0;}for(;z<24;){k=""+n(G,x,y,z);b+=(-1!=(G[x][y][z++]?a[1].indexOf(k):a[2].indexOf(k)))?1:0;}i.setRGB(x,y,new java.awt.Color(p(r),p(g),p(b)).getRGB());}ImageIO.write(i,"png",new File("out.png"));}} ``` Examples (rule 368/245): Gen 0: ![enter image description here](https://i.stack.imgur.com/gzrWZ.png) Gen 1: ![enter image description here](https://i.stack.imgur.com/33P1L.png) Gen 2: ![enter image description here](https://i.stack.imgur.com/wSAGV.png) Gen 3: ![enter image description here](https://i.stack.imgur.com/Um3gH.png) Gen 4: ![enter image description here](https://i.stack.imgur.com/66M5Y.png) ]
[Question] [ When translating DNA into proteins, the ribosomes read the sequence of DNA nucleotides 3 by 3. Each set of 3 nucleotides is called a codon, and each codon encodes for an amino acid, with some redundancies. Here's the conversion table used by most organisms (table is read left, top, right): [![Codon to Amino Acid conversion table](https://i.stack.imgur.com/xFLGg.png)](https://i.stack.imgur.com/xFLGg.png) Humans and most other organisms use just a single amino acid as a "start" codon: Methionine, a.k.a. Met, M, or ATG. This means that any DNA sequence coding for a protein starts with ATG, which will be recognised by the translation machinery. However, three different codons are used to stop the translation: TAA, TAG and TGA. If the replication machinery encounters any of these, it will stop, and the translated protein will be released into the cell. Therefore, one of the most dangerous mutations that can occur is one that will cause an **early termination** of protein translation. For example, if we take this DNA sequence: `ATGGCCTTCATATCGGCGGACAGCGAATCTGGTGATTAA` Split into codons: `ATG GCC TTC ATA TCG GCG GAC AGC GAA TCT GGT GAT TAA` Once translated, will give: `met ala phe ile ser ala asp ser glu ser gly asp STOP` But if we replace C at 14th position into an A, then the protein sequence will be `met ala phe ile STOP` This **substitution** would be written in genomics as `14C>A`. I could also perform other substitutions (25G>T for example) that would cause early termination, but 14C>A is the first one in the sequence, and so would produce the shortest protein after translation. ## Challenge Given a string of nucleotides coding for a protein (first codon is ATG, last is a STOP), find the first substitution that would cause an early termination of protein translation, resulting in the shortest possible protein. This is code golf, so fewest bytes wins! ## Rules and specifications (these will be updated if anyone asks relevant questions about what's allowed) * DNA sequence is stored in a character string as consecutive block capitals, no spaces or punctuation in it, and contains only ACGT. If you want to store it into binary (A:00/C:01/G:10/T:11) or as integers (A:1/C:2/G:3/T:4), that's fine (you don't need to follow these encodings). * Declaration of the codon to amino acid conversion table is part of the golfing challenge. You must choose which parts you deem relevant. Most softwares use hashes / dictionaries to store it. * Code should return the substitution formatted under the preferred nomenclature: 14C>A (position, original nucleotide, ">", new nucleotide), but any format that includes those three elements is accepted. * If there are no possible early termination sites, function should return any easily recognisable error value (raise an error, FALSE, -1, etc) or return nothing. ## Test cases ``` ATGCACTGTTGGGGAGGCAGCTGTAACTCAAAGCCTTAG -> 9T>A ATGGTAGAACGGAGCAGCTGGTCATGTGTGGGCCCACCGGCCCCAGGCTCCTGTCTCCCCCCAGGTGTGTGGTCATGCCAGGCATGCCCTTAG -> 7G>T ATGGAACATCAATCTCAGGCACCTGGCCCAGGTCATTAA -> 4G>T ATGTGCCAAGTGCATTCTTGTGTGCTTGCATCTCATGGAACGCCATTTCCCCAGACATCCCTGTGGCTGGCTCCTGATGCCCGAGGCCCATGA -> 6C>A ATGCTTTTCCATGTTCTTTGGCCGCAGCAAGGCCGCTCTCACTGCAAAGTTAACTCTGATGCGTGA -> 20G>A ATGGTAGAGTAA -> 7G>T ATGGTTCCACGGTAA -> ERROR ``` [Answer] # JavaScript (ES6), ~~124 ... 93~~ 92 bytes Output format: `XiY`, with `X` = original nucleotide, `i` = position, `Y` = new nucleotide. ``` s=>s[i=([,,x,y]=s.match(/(.A[AG]|.GA|T(.[AG]|(A|G).))(...)*$/)).index+!!x+!!y]+-~i+'AT'[+!x] ``` [Try it online!](https://tio.run/##fZBNaoRAEIX3uYUQsDs6PScwUNSiLlA7cSGOkxgmOsQhOCC5uqkfd/kRpLrb97737Lf2s527j@F6O4zTqd/O1TZXz3M9VKEuy6W8N9Wc3ttb9xqOIUEN1KyJYOWQbB1gpZhiDCml@PR4jDEN46lfiizT994Uh6@hyIHzusiWZuumcZ4ufbpML@Ec5JwQkImZ5AGSHekW5BABZIPMQHmMDz@dIiMRqs9tJB4xk8IQBYw2UbmMytWxn@xCs7jEFv/lSRhoLcWYQZm04@ST1P7daQmgQ0SSYNE60VnOVhEzez@Lss5kv@Y/4BXtolRMf@QJWjmarHFW0u4IwJeWipqvtfy6nU4O3b4B "JavaScript (Node.js) – Try It Online") ### Regular expression ``` r = /(.A[AG]|.GA|T(.[AG]|(A|G).))(...)*$/ ( | ) // 1st capturing group .A[AG]|.GA // match ★AA, ★AG or ★GA T(.[AG]|(A|G).) // 'T' + 2nd & 3rd capturing groups: // match T★A, T★G, TA★ or TG★ (...)*$ // make sure that the number of trailing // nucleotides is a multiple of 3 ``` To summarize, this will match 21 codons that can be mutated to generate a *STOP*. By testing the 2nd and 3rd capturing groups, we can classify them into 3 categories describing the position of the nucleotide that needs to be altered. ``` 2nd group | 3rd group | position | matching codons -----------+-----------+----------+------------------------------------------------------- not set | not set | 1st | (TAA) (TAG) (TGA) CAA CAG CGA AAA AAG AGA GAA GAG GGA set | not set | 2nd | TTA TTG TCA TCG TGG set | set | 3rd | TAT TAC TGT TGC ``` ### Commented ``` s => // s = input DNA sequence s[ // append the original nucleotide ... i = // ... which is at position i (0-based) ( [,, x, y] = // x = 2nd capturing group, y = 3rd capturing group s.match(r) // apply the regular expression to s ).index // get the position of the matching codon + !!x + !!y // add 2 if x and y are set, 1 if only x is set, 0 if x is not set ] // + -~i // append the 1-indexed position + 'AT'[+!x] // append the new nucleotide: 'T' if x is not set, 'A' otherwise ``` [Answer] # [Perl 5](https://www.perl.org/), ~~73~~ 72 bytes -1 byte using anchor at the end instead of the start ``` /(?|(.)(A[AG]|GA)|T(.)[AG]|T[AG](.))(...)*$/;$_="$+[1]$1>".($-[1]%3?A:T) ``` [TIO](https://tio.run/##RZCxagNBDER7f4bZwG6C1xiTJiYxQoV@QJ0xqVIYTHzYKe/bs5mRDnLFaaWbeaO96et@fR1jW49z7a3KSew8m7TZ0UbjfKNptffensv2UD7f1@XltDuX3ce617LB8Wl/lDdvY4ibirq5Gx4xdMZWMFQRNOoutoIOQ8OYqhQZFJAararAaFQlxZUUlmWyCMOSkjj804EWRtIUn0mwxYxPWGkVcZgIC0ZwB5ZV05kkitw9swMc@1isnctlfFyZYgs6QHQxh/BYIG4rksfIUKZxifxNyQJdfm/Tz@X2/Rib6/QH) ``` /^(...)*?(?|(.)(A[AG]|GA)|T(.)[AG]|T[AG](.))/;$_="$+[2]$2>".($-[2]%3?A:T) ``` [Try it online!](https://tio.run/##RZDBasNADETv@YzgwG5DNpDSS0tqhA76Ad1C2lMPhdCYJkd/ezczkqE@WCt55o3W09fv5aX3/UdprdWnsYxzabXISew8m9TZ0UbjfKOp@7fh87getqfDeTi8r1sZdjhunkd59dq7uKmom7vhEUNnbAVDFUGj7mIr6DA0jKlKkUEBqdGqCoxGVVJcSWFZJoswLCmJwz8daGEkTfGZBFvM@ISVVhGHibBgBHdgWTWdSaLI3TM7wLGPxdq5XMbHlSm2oANEF3MIjwXitiJ5jAxlGpfI35Qs0OXvOt2/rz@3vrtMDw "Perl 5 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` os3ḅ4f“EGM‘Ḋ JṬ€×Ɱ4ZẎçƇ⁸ḢĖżW€Ṁ ``` A monadic Link accepting a list of integers (in `[1,2,3,4]` mapping to `ACGT` respectively) which yields a list of lists of integers, `[[position, new nucleotide], original nucleotide]`. (A valid sequence with start, and stop but no possible substitution that would cause early termination will output `[[4]]`) **[Try it online!](https://tio.run/##y0rNyan8/z@/2PjhjlaTtEcNc1zdfR81zHi4o4vL6@HONY@a1hye/mjjOpOoh7v6Di8/1v6occfDHYuOTDu6Jxwo93Bnw////6MNdRRMdBSMdRSMwAw4MgIjuCxcEK7AGKbLCMYwRGIYYlNggkQawtjIWgyR7DJEUgNXiexaY7hgLAA "Jelly – Try It Online")** ...Or see [this version](https://tio.run/##y0rNyan8/z@/2PjhjlaTtEcNc1zdfR81zHi4o4vL6@HONY@a1hye/mjjOpOoh7v6Di8/1v6occfDHYuOTDu6Jxwo93Bnw3@gHkdn95BHDXMzgQqB8ofbQ6Me7pwV@nB3t9GhZQjpLKAGIGX3/79jiLtzCBA4OwNZQArIdHd3dnZ3dgQiRwgTKOrs6BwCEnAEqnF0BIm4g3S6AykA "Jelly – Try It Online") which performs both a translation from the `ACGT` input format, and a translation to the `{position}{original nucleotide}>{new nucleotide}` output format. ### How? ``` os3ḅ4f“EGM‘Ḋ - helper Link: [0,...,0,new nucleotide], N; DNA integer list, A o - (N) logical OR (A) (vectorises) s3 - split into chunks of three ḅ4 - convert from base four to integer “EGM‘ - code-page index list = [69,71,77] f - filter keep (i.e. only keep stops) Ḋ - dequeue (so if only a single stop was found and hence no early stops we'll have an empty list which is falsey) JṬ€×Ɱ4ZẎçƇ⁸ḢĖżW€Ṁ - Main Link: DNA integer list, A J - range of length (of A) -> [1,2,...] Ṭ€ - untruth each -> [[1],[0,1],[0,0,1],...] ×Ɱ4 - map across [1,2,3,4[ performing multiplication Z - transpose Ẏ - tighten -> [[1],[2],[3],[4],[0,1],[0,2],[0,3],[0,4],[0,0,1],...] - (call that X) ⁸ - use chain's left argument, A, as the right argument Ƈ - filter keep those (x in X) for which this is truthy: ç - call the helper link as a dyad f(x, A) Ḣ - head (which will be the shortest) Ė - enumerate (that) W€ - wrap each (integer a in A) in a list ż - zip left and right together Ṁ - get the maximum ``` [Answer] # [Python 3](https://docs.python.org/3/), 88 bytes ``` f=lambda i,j,k,*l,n=1:(j+k<4)*(n,i,5)+(i-k>2)*(n+1,j,1)or(i-j>2)*(n+2,k,1)or f(*l,n=n+3) ``` [Try it online!](https://tio.run/##bZJBj9owEIXv/ApfkOMlXRXocojKSpal@tZWlW8oQgmYxRAc6jhtUdXfTmfGQQWpuUzsfO/Nm1HOl7hv/fx63S2b6lRvK@byQ37Mn5rcL6dFdpgcP34QT5nPXf4iJpl7d3yd4XkyBW4q2gBXh@FqBkK8YruM9H4yF9et3bFou5h19rsoRgyeeh3btWdsyX5zyYtpzrjmxQyK4sUciuHFyx9CPaI1oXVRsR2YV3nNnB9Mnl20py4Tid60vY8Mac6fD63zGR8vOj52JHQoC5V/s9kib6ynRDDHQghSO3/GAupVMl9t9lUoSYtvKAdJSXCw3QDDsKAcLHYMjeGjYMslm6d5UzT/Y40iyDbuxt3rGHIhuHpf5sOYKzxOy8fzrCyTt206@3@/zy2zVWgusOdwcr6KroWksBmI3vstJ9E5OB8z/s12bttb5vtTbQNjBeNskhYn7rkvwb2BVYNb6eONw43dU1@DPVfBbh@p2/JP1TnrYshxPeJB96n3G0oJE/RNvLnHQKt7QBUMakOEHom9BU7j36NiNPq5d41lJvTDpmK4FFTxB6SM2eBuf23sGczqYKvjVRqtpDLaGA2P1HDSeJRwqaSEgzJG6hFwcAmAQipBGghANUqVAhtFVaGLUeiCZbgZQJIkhF7@uUNHiS1RRJ/RQQ9i@ASRRtQObiQWuAI12WJVSZmcEDLGpN5kTHk0xU7hUnsaGWFN7mCEKuyD5hSAppUyvVIPhd0wRFpT8tKDhSYDheuSfwE "Python 3 – Try It Online") Solution without regex. Uses `1235` for `AGCT`, respectively. Takes each base as a separate argument. Will suggest `A` for any instance of `T*A, T*G, TA*, TG*`. Outputs as `(position, original base, new base)`. Returns an (invalid) 6-element tuple when there is no early termination site. ### Explanation ``` f=lambda i,j,k,*l,n=1: (j+k<4) # If the last two bases are 1+1 (AA), 1+2 (AG) or 2+1 (AG) *(n,i,5) # Return (position, 1st base, 5 (T)) +(i-k>2) # If the 1st base is 5 (T) and the 3rd base 1 (A) or 2 (G) *(n+1,j,1) # Return (position, 2nd base, 1 (A)) or(i-j>2) # If the 1st base is 5 (T) and the 2nd base 1 (A) or 2 (G) *(n+2,k,1) # Return (position, 3rd base, 1 (A)) or f(*l,n=n+3) # Else process the next three bases ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 138 bytes ``` x=>{for(int i=0;;i++)foreach(var k in"AGT")if("TAG TAA TGA".Contains(x.Remove(i,1).Insert(i,k+"").Substring(i-i%3,3)))return(i+1,x[i],k);} ``` [Try it online!](https://tio.run/##fZBBS8QwEIXv/opSEBLaLS57rF0YAg6CJw14EA@1ZN1hMQtpd1kQf3udmfTmYg@dJH3ve68ZxtUw0vxwisP9OCWKn7WhONXDvk/6sttdN1@67ffumORLQd1d21JVWT4I/bA35z4Vh4JiCehLSztTesDCAxQeoWzcMU49xdFcmufwdTwHQ/XaNo9xDGni9aEqS9u8nD5yvKEV3W7qjbU2hemUoqFqXV/e6L0@2PZnbm9eE03hiWIwHAUeHTiP3iM/gLxD2QIfOgDeOM91Smv/GlmFrBNbdiFb2IvCco65TqcTrHeClbGcLEK1ZIku/onjLJBSQlG9IHGh8ScufdWofJDBGuZrsEyXURktIu99bqdJ2hj1x3L9XFBvScR4PY7JgpFgSdOKekEAeamhTuKlVb7qDMeFOf8C "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~29~~ 27 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` vNU4E¨NXǝ3ô•`|Ž•₅вåàiX>yN)q ``` Input as `2341` for `ACGT` respectively. Output in the format and order `[position, original nucleotide, new nucleotide]`. Will output the input itself if there are no possible early termination sites. (Could be 1 byte less by removing the `>` if 0-based positions were allowed.) [Try it online](https://tio.run/##yy9OTMpM/f@/zC/UxPXQCr@I43OND2951LAooeboXiD1qKn1wqbDSw8vyIywq/TTLPz/38jQxMTQyMTIyNjExMjEGIhAAsZAYRA0MTE2NjYyNgbTQEmgrDFQgSGIgopAFYK1QJSAGcaGQFMB) or [verify all test cases](https://tio.run/##RZAxawJBEIV7f4VcF0iTaK0MQ5juqjFoZwIprFIEBMEDCeRqsRc0ELATgq3NHSGFjb/h/shl3sxCtpnd2fe@N7uvb0/Ps5d2OV9kSizZ3X2v36z29fpxmHWbctPNhu08H/UfJtUhH/9ue/WpWX1Olz9nK837x/W7/qp3s/Fgkd9cyrYoismlrI7Xc3W6bUmFiVVUxRaJnQRHsiYT2YFVSTqms6ZYG6oQiSlMKrAyG4a9MijKoKCkThK6JSS@@acbmhAJk1@DIMlsVzZSx@OsQyjWMrdjUTmcQYJIVSPbwT6P@NgxXMT7kyEWpxsILuQA7gP4a4li6xmMNAwR3xQsSQj/JknTitMYTfoD) or [verify all test cases with a conversion back to `ACGT`](https://tio.run/##RZAxSwNBEIX7/IqwXcBCTeqEYRKmu2qU2KkgcpVFIHCQgyCYIqW9oIIQsAhILNPcIhaC5DfcHznfzB64zezOvve92b2bXV3nN81iXoxHoVuvHrthFJRYwslpf1AvX8bnzTw7G0wuqk02/X7qx129fL1cfO1R6vuHw0d8i8/5dFhkvZ9VU5Zltb0d5kV8r7aH/e9ndhzXeRAQwyxucH1U7RpSYWIVVcEiwUnsSGgyEQ6sStKBDk1B21RJJFBAKmZlBoa9slGUjWKl7bRCtySJb/7pQJNFmsmvjSCtGVcYqeNx6JAVtOB2rFVOzkQykaqmbAf7POJjp@FSvD/ZxOJ0gMxlOQb3Afy1RGnrGWxpNkT6psSSFuHfJO204jS2Jv0B). **Explanation:** ``` v # Loop over each of the digits of the (implicit) input-string NU # Store the current loop-index in variable `X` 4E # Inner loop in the range [1,4]: ¨ # Remove the last digit of the (implicit) input-string # (this is to ensure it doesn't find the trailing STOP all inputs will have) NXǝ # Insert the current digit of the inner loop at position `X` in the string 3ô # Split the string into parts of size 3 •`|Ž• # Push compressed integer 7964812 ₅ # Push builtin integer 255 в # Convert the larger integer to base-255 as list: [122,124,142] å # Check for each of these three values if it's in the list ài # If any is truthy: X # Push the current index of the outer loop we stored in `X` > # And increase it by 1 to make the 0-based index 1-based y # Push the current digit of the outer loop N # Push the current digit of the inner loop ) # Wrap all three values into a list q # And terminate the program # (after which this list is output implicitly as result) # (and if no value is found after the nested loop, # output the (implicit) input as output implicitly instead) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•`|Ž•` is `7964812` and `•`|Ž•₅в` is `[122,124,142]`. [Answer] # [Python 2](https://docs.python.org/2/), ~~138~~ ~~133~~ ~~144~~ 142 bytes ``` f=lambda s,i=0:next((`i-~j`+s[j]+'TAA'[j]for j in[0,1,2]if re.match('.TTA.[[[AAAGGG]]].'[j::3]+'|.GA',s[:3])),s[6:]and f(s[3:],i+3)) import re ``` [Try it online!](https://tio.run/##LVHNasMwDD43T2HYwQnxQtdCDxk9CB/0AroZQ7O1oS5rWpIcNhh79UySc4ks@fuz8vyZr49htyz98au7f5w7M7l03LbD5Xsuy1N6/bud6incYm0JwPKhf4zmZtIQtu7N7WLqzXhp7t38eS1tQwRNCAEAEDHG2DCjbffM/m0QrJsCN1XF9dDGbjibvpzCvo0u1fuqKtL9@RhnFlzEZWIXEywQAgIBWldsNtJ68IREbME33KG0wEMvxt6Tgo1AeY58I8CMQwYxGoXtPSt5rV6EyIuQlHWyApWSIXpYDdY0og9iLUzFiAyuCnwli3NWXXkGUnjIIqou1Wdu1hIQEeUIKq2xUNPnjDmFPl7AslkOk3dDyhU3sdAg@nSAfFQnL54SJa8tK6IIxbbYPMc0zGZ6z5V/UVUUxYthrOMPGvlxjF3@AQ "Python 2 – Try It Online") Returns `nXY` instead of `nX>Y`, or the empty string if there is no valid substitution. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 91 bytes ``` {,/(1+t),(x@t:(&u)+3*-3!p),(u:r@p)#'t@3!p:*&1=+/'r:0N 3#,//~(t:3 3#"TAATAGTGA")=\:/:0N 3#x} ``` [Try it online!](https://tio.run/##JYqxCoAgFEV/pQxMU3mF24PAN72tybG5paEIgyDq101ou@ecu7ptzXnB24IaTNJWXSGhkqc2vnO@3os58Qi7btoUCmMnh9FAe2A/Vb6xAK9K6MsUkSgSRyahxxnhP1xPXipBkbk0YpE/ "K (oK) – Try It Online") I'm sure my solution can be significally golfed (I used too many named varialbes) [Answer] # Brainf\*\*\*, ~~696~~ ~~624~~ 397 Bytes ``` >>>>>>,,,++>>>+[-<<,<<+<<+<<+>,>>,>>>[>+<<<<<<<<+>>>>>>>-]>[-<+>]<<<<<<<<-[-[-[->->-[-[-[->->[-]>->+++>>>+<<<<<]>[->-[-[[-]>->+++>>+<<<<<]]>[->+>->+<<<]]<]>[->-[-[-[->->++>>+<<<<]>[->++>->+<<<]<]>[->+>-->+<<<]<]>[-]]<]>[->-[-[-[->->++>>+<<<<]>[->++>->+<<<]<]]>[-]]<]]]>[->-[-[>->[-]>->+++>>>+<<<<<]>[->-[[-]>->+++>>>+<<<<<]>[->>>++++<<<]]<]>[->-[-[[-]>->+++>>>+<<<<<]]>[->>>++++<<<]]]>>>>]<<<.>.>. ``` Uses the actual bytes 1, 2, 3, 4 to code for A, G, C, T respectively and outputs the position as a byte as well, so you only get the position modulo 256. Outputs position + two zero bytes if there is no possible mutation. [Try it online!](https://tio.run/##lZBdCgIxDISx2duk9QRhLlL6oIIggg@C56/5sXVZVDApNOl8U0KO98Pldn6crr3DI@fMrDfXIpJFOA4y7KBCuwgOA0qDsow2hFI9oTmrqlQBx9dOmcuBlfRSXGJ79O6Nxl@TDG6CMnzr/h/74Nt0/Jr8iwB72g7@gd3CzXZpO9xDs/fdkmjRINJKLy1TSkRP "brainfuck – Try It Online") # How? ``` # X 1 Y 1 Z 1 C L L F >>>>>>,,, #first codon is always ATG ++>>>+[ - #zero exit flag <<,<<+<<+<<+> #input X into L1 for a trick later|set switch flags|seek to Y ,>>, #memory is now 0 1 Y 1 Z 1 4 X 0 0 >>>[>+<<<<<<<<+>>>>>>>-]>[-<+>] #copy L1 onto cell0 #memory is now X 1 Y 1 Z 1 4 X 0 0 <<<<<<<< #begin switch on X -[-[-[- #case T: >- > #begin switch on Y -[-[-[- #case TT: >->[-]>->+++>>>+<<<<<] #TT not possible|zero out switch flags|inc exit flag|increase counter #case TC: >[- > #switch Z -[-[[-]>->+++>>+<<<<<] #cases TCT TCC not possible ] #TCG ~ TAG (fall through) >[- >+>->+<<<] #TCA ~ TAA ]<] #case TG: >[- > -[-[-[- >->++>>+<<<<] #TGT ~ TGA >[- >++>->+<<<]<] #TGC ~ TGA >[- >+>-->+<<<]<] #TGG ~ TAG >[-] #TGA is correct STOP ]<] #case TA: >[- > -[-[-[- >->++>>+<<<<] #TAT ~ TAA >[- >++>->+<<<]<] #TAC~TAA ] #TAG is correct STOP (fall through) >[-] #TAA is correct STOP ] <] #case C: ] (fall through) #we can fall through because we already put the letter into L1 #case G: ] (fall through) #case A: >[- > -[-[ #cases _C & _T not possible >->[-]>->+++>>>+<<<<<] #case _G: >[- > -[[-]>->+++>>>+<<<<<] #cases _GC/_GT/_GG are not possible >[->>>++++<<<] #_GA ~ TGA ]<] #case _A: >[- > -[-[[-]>->+++>>>+<<<<<] #cases _AC/_AT not possible ] #AAG ~ TAG (fall through) >[->>>++++<<<] #_AA ~ TAA ] ] #pointer is on cell5 #if exit flag is zero then exit loop: >>>> ] <<<.>.>. #print position and letters ``` It loads one codon at a time and uses a series of switch statements to look for all the possible codons that could mutate into a STOP. Further golfing ideas I have are: * ~~For C\_\_, G\_\_, A\_\_ codons, the switch statements are almost identical. There has to be a way to collapse them~~ Done. * ~~Is there a way to fall through cases in BF? Some of the cases are identical~~ There is! Just replace the entire case with `]`. * There's probly a more optimal arrangement of the memory cells The last bullet won't save too much; I'm happy with shaving 300 bytes for now. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 68 bytes ``` ((...)*?((.)(?=AA|AG|GA)|T(.(?=G)|G.)))(?<=(.)).* $.1$6>$#4$*T$#5$*A ``` [Try it online!](https://tio.run/##RZCxbsMwDER3/0YUQPIgoEDbKWlAcLgf4AekQ4csGYqM/nf3jjRQLxSpu3eUf39ej@f3fu64773POcd6Yx39djXbDBtsbNEne4wNcwxeXa5UjLkubb61z692em9rtNNHW23fLeDmgQjwM7CDWuPQzdh4hGGhjkNwLFWJQAWlkNWdGM/qooSLonJMDmFaSpKHfzrRpkiZ8loEHGZecaUl4zgxFY7oTqyql7NIEkVEZSc490GuXctVfD5ZYiSdILmUI3gukK81q2NmuNK0RP2mYpFufw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ( ``` Capture the string up to and including the mutation so that we can take the length. ``` (...)*? ``` Capture as few codons as necessary. ``` ( ``` Choose either: ``` (.)(?=AA|AG|GA) ``` a nucleotide followed by `AA`, `AG` or `GA` (using the count of captures of capture group 4 to identify the necessary mutation) ``` | ``` or ``` T(.(?=G)|G.) ``` a nucleotide either side of a `G`, both following a `T` (using the count of captures of capture group 5 to identify the necessary mutation) ``` ) ``` End of choice. ``` ) ``` End the first capture at the nucleotide to be mutated. ``` (?<=(.)) ``` Look behind to see the nucleotide to be mutated (trying to capture it inside the group turns out to be nontrivial). ``` .* ``` Also delete the rest of the input. ``` $.1 ``` Output the position of the nucleotide to be mutated. ``` $6> ``` Output the nucleotide to be mutated plus a `>`. ``` $#4$*T ``` If the first alternative matched then mutate the nucleotide to a `T`. ``` $#5$*A ``` If the second alternative matched then mutate the nucleotide to an `A`. [Answer] # [Red](http://www.red-lang.org), 187 bytes Thanks to @Jitse for finding a bug! ``` func[s][k: 0 until[v: take/part s 3 foreach t["TAA""TAG""TGA"][u: collect[repeat i 3[if(m: v/:i)<> n: t/:i[keep/only reduce[k + i m">"n]]] ]if 1 = length? u[print u exit]]k: k + 3 s =""]] ``` [Try it online!](https://tio.run/##VZA/T8MwEMX3foqTJxBDQd0iWmR5uB15szxE6QWspG6UOhV8@nB3jhB48PnPu9979kzn9Z3OIe76Zu2X3IVbDEMDz7DkksZwb6C0A@2ndi5wgwP015na7hNKMN5awxPyhNbEsDTQXceRuhJmmqgtkOAQUv9waeC@b9Lj6wky83gZBqJpf83jN8x0XjoKAzyx/GJOJscYdzH18AJHGCl/lM83WMI0p1xgAfpKJUaOKB0HznQ0Jsa1B2M9Ous8eo88LPIOZWv50FnLG@cl7q5q@QL5SpRViKxiOUq7c4xyWp2QvBOSlO1kE2pLlejivwPjrVhLo0qEghuAr@QHN61SrBQ@ZoripbraXWki8t7XDArXXKjxa8gaQ58vYvx1YJh0ipcYaBB9ubV1qT5OHCVI/bbKwz8Y/TY06w8 "Red – Try It Online") Using [Red](http://www.red-lang.org)'s `parse`: # [Red](http://www.red-lang.org), 211 bytes ``` func[s][u: func[c][print[index? p p/1">"c]]t:"T"a:"A"c:"C"g:"G"parse s[any[[[p:[a | g | c]"AA"|"AG"|"GA"](u"T")|[t p:[t | c | g][a | g]](u"A")|[t p:[a | t | c]a](u"G")|["TG"p:[g | t | c]](u"A")](exit)| 3 skip]]] ``` [Try it online!](https://tio.run/##VVA7a8QwDN7zK4ymu6mUbh5ahAftRZvREPIiFELIA@4g/z2V5PSggUS2v6ezdO353bVZqj6Gs9@nJq@S9xh82Uiel3Ha8ji13eMrzGF@e4dPaES2CAx1BIQmQoIhAsFcL2tXrbmenjnnOeY6HGHQtxFAhAOQ9EMIcttVfT/yFpS1GcOYUgRiMDpcXSZOkdoAMgBY02IeXtAlkVv3GLf7ET7C@jPOInL2AZApYWJiJn2QdEe2RT1MiLpJzNqtKlwFSCFjFiIpS@lk8pTUKvlM5sTJnGxcJxfRJYXii/8Jao8WbUKnmAtdBgpptT@uu6ANPVYXt7eZirq4GYmZSwc3917k9UvJUsOvb2R6JaiZKS3LAryI3xyxLD0nWaIVKb@t@JHZnL8 "Red – Try It Online") [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 56 bytes ``` {(1+;x;a)@'*<(*&~^5 6 9?4/+0N 3#)'i@[x;;:;]'a:1&3!i:!#x} ``` [Try it online!](https://tio.run/##bZBPa8JAEMXvfoq4FpMopUm1FncLusxhbj3tLaQYAhaxWBAPEdGvns6fBEprDpnd5L33m5n94@Hz0LZbe0nyqWtcla7jyVsyGd8@XqJFtFzNn6bZezQbpfFuXTTOWVfGlc3Hs@HODkfNtT3Zy0Nxvh3tNmrc5nvvks222n1R1tkd0/I6qK0JHsGsBqeiNj4geAgYAtLjkW7IV08fwXu6QCC5ccnS1SYYenmTlr2XhEhSdqoRyUV25DgAigapwMkBOJlL96UTikUlcuiJrwRDI9hfRMJ5bo2DxMKp2AXSL2qdvPN7XqF4LiQjiuC5gqZpOotCCNqjwKRvlPF0CG1T1sViZOKCYPB3PxTOScxmoDQqm/Jej8IF7oAb07VrPmrsc9ZP8m/vqKPeX5NgAVWTR3mUle0P "K (ngn/k) – Try It Online") encodes `"TAGC"` as `0 1 2 3` respectively returns `1 1 0` on error important observation: there's no point trying to replace a nucleotide with anything other than `T` (when first in the codon) or `A` (when second or third) `{` `}` function with argument `x` `i:!#x` the list `0 1` ... `length(x)-1`, assigned to `i` `a:1&3!i` mod 3 and min with 1: `0 1 1 0 1 1` ... `0 1 1`, assigned to `a` `@[x;;:;]` a projection - tetradic `@` (a.k.a. "amend") with 2 missing arguments. this is a function that when given args `u` and `v`, creates a copy of `x` and replaces its `u`-th element with `v` `i@[x;;:;]'a` call the projection with corresponding elements from `i` and `a` `(` `)'` each `0N 3#` reshape to a 3 columns wide matrix `4/+` decode from base 4. for a codon `u v w` this is `(16*u)+(4*v)+w` `*&~^5 6 9?` find the index of the first codon that decodes to 5 (`TAA`) or 6 (`TAG`) or 9 (`TGA`) `*<` from the length(`x`) such possible first codons, find the index `p` of the one that terminates earliest `(1+;x;a)@'` make a list of `(1+p;x[p];a[p])` ]
[Question] [ Write a program or function that takes in an eight byte string containing one of each of the characters `()[]{}<>` arranged in any way such that the four respective bracket types match. For example, `]<([){}>` is invalid input because the square brackets don't match (though all the others do). Print or return an integer from `0` to `6` that denotes how many of the six possible pairings of the four bracket types are interlocked. Bracket type pairs are considered interlocked if exactly one bracket of one type occurs between the brackets of the other type. So `([)]` and `[(])` are interlocked but `()[]`, `[]()`, `([])`, and `[()]` are not. The shortest code in bytes wins. **Input/Output Examples** ``` ()[]{}<> : 0 ([{<>}]) : 0 <>{[]}() : 0 {<>([])} : 0 <(>)[{}] : 1 <[({)}]> : 1 [{<}]>() : 2 {<>([}]) : 2 <{(>})[] : 3 [(]<){>} : 3 <([>{)}] : 4 (<{[>})] : 4 (<[{)>}] : 5 <{[(>})] : 5 [{<(]}>) : 6 (<{[)>}] : 6 ``` [Answer] # CJam, 18 ``` l7~f&_f{\/~;&}s,2/ ``` Thanks isaacg for some golfing ideas :) [Try it online](http://cjam.aditsu.net/#code=l7~f%26_f%7B%5C%2F~%3B%26%7Ds%2C2%2F&input=(%3C%7B%5B)%3E%7D%5D) or [try all examples](http://cjam.aditsu.net/#code=qN%2F%7B%0A%207~f%26_f%7B%5C%2F~%3B%26%7Ds%2C2%2F%0AN%7D%2F&input=()%5B%5D%7B%7D%3C%3E%0A(%5B%7B%3C%3E%7D%5D)%0A%3C%3E%7B%5B%5D%7D()%0A%7B%3C%3E(%5B%5D)%7D%0A%3C(%3E)%5B%7B%7D%5D%0A%3C%5B(%7B)%7D%5D%3E%0A%5B%7B%3C%7D%5D%3E()%0A%7B%3C%3E(%5B%7D%5D)%0A%3C%7B(%3E%7D)%5B%5D%0A%5B(%5D%3C)%7B%3E%7D%0A%3C(%5B%3E%7B)%7D%5D%0A(%3C%7B%5B%3E%7D)%5D%0A(%3C%5B%7B)%3E%7D%5D%0A%3C%7B%5B(%3E%7D)%5D%0A%5B%7B%3C(%5D%7D%3E)%0A(%3C%7B%5B)%3E%7D%5D) **Explanation:** ``` l read a line of input 7~f& clear the lowest 3 bits of each character the goal is to convert brackets of the same type to the same char _ duplicate the resulting string, let's call it S f{…} for each character in S, and S (the char and S are pushed every time) \ swap the character with S / split S around that character, resulting in 3 pieces: before, between, after ~ dump the pieces on the stack ; pop the last piece & intersect the first 2 pieces after the loop, we have an array of strings containing the chars interlocking to the left with each char of S s join all the string into one string , get the string length 2/ divide by 2, because S has duplicated characters ``` [Answer] # Python 2, 163 bytes ``` def f(b,e='([{<)]}>',q=range(4)): b=[b[b.index(e[j])+1:b.index(e[j+4])]for j in q] print sum(sum(abs(b[k].count(e[j])-b[k].count(e[j+4]))for j in q)for k in q)/2 ``` This looks at the stuff between each pair of matching brackets and counts the number of individual left or right brackets present. The sum of these divided by two is the output. I'm sure it could be golfed a lot more by better golfers than me. [Answer] # GNU sed -r, 147 Output is in unary as per [this meta-answer](http://meta.codegolf.stackexchange.com/a/5349/11259). ``` y/([{</)]}>/ s/.*/\t& & & & / :b y/)]}>/]}>)/ s/\S*>(\S*)>\S* /\1\t/ t s/\S* // : s/(\t\S*)(\S)(\S*)\2(\S*\t)/\1\3\4/ t s/\S *$/&/ tb s/\s//g s/../1/g ``` Note: Replace `\t` with actual `tab` characters to get the correct score. However, the program will work either way with GNU sed. [Try it online](https://tio.run/##NY9LisMwDIbX0SmyGIoUmIo@VsXoErOUvSlTSjdtabIJwlevKyUUo@f/SbbHy39rM6NaYipVGEbeDtxt@vUwnM4wr5IbhZ7/BkF3JO56zruOYVr7PfuAp5inAJyihcz7CB05nA/5@OX74Yc3XpyjGpmvcfuWd3xtDUmL1SQQb5NaCJKYlooEXqMWqpBQSK0WSIpGtQg46@HLLFOGUn0XKJZEJjGlEjRgMnUtEjWS2GOKS8f3YPx3YUJ6P57T7XEf2@/rAw). [Answer] # Perl, 77 bytes 76 code + 1 switch ``` perl -pe 'y/)]}>/([{</;for$x(/./g){$h{$x="\\$x"}++&&s!$x(.*)$x!$z+=length$1,$1!e}$_=$z' ``` Takes input from STDIN and the program must be started fresh for every input. **Explanation** 1. Replace all closing brackets with their open counterparts (`y/.../.../`). 2. Then, for every character in the input string (`for$x...`), increment a counter for the character (`$h{$x}++`). 3. If this is the second time we're seeing the character, get the distance between the two occurances (`length $1`) and remove both occurances of this character from the string. For example, if the string was `([{([{<<`, there are two characters `[` and `{` between the two `(`s. After the `(`s are processed, the string becomes `[{[{<<` and we add 2 to the total number (`$z`) of interlocking brackets. 4. The result is taken from `$z` (`$_=$z`) [Answer] # Pyth, 20 bytes ``` JmC/CdTzlsm@FPcsJd{J ``` [Test suite](https://pyth.herokuapp.com/?code=JmC%2FCdTzlsm%40FPcsJd%7BJ&input=%28%29%5B%5D%7B%7D%3C%3E%0A%28%5B%7B%3C%3E%7D%5D%29%0A%3C%3E%7B%5B%5D%7D%28%29%0A%7B%3C%3E%28%5B%5D%29%7D%0A%3C%28%3E%29%5B%7B%7D%5D%0A%3C%5B%28%7B%29%7D%5D%3E%0A%5B%7B%3C%7D%5D%3E%28%29%0A%7B%3C%3E%28%5B%7D%5D%29%0A%3C%7B%28%3E%7D%29%5B%5D%0A%5B%28%5D%3C%29%7B%3E%7D%0A%3C%28%5B%3E%7B%29%7D%5D%0A%28%3C%7B%5B%3E%7D%29%5D%0A%28%3C%5B%7B%29%3E%7D%5D%0A%3C%7B%5B%28%3E%7D%29%5D%0A%5B%7B%3C%28%5D%7D%3E%29%0A%28%3C%7B%5B%29%3E%7D%5D&test_suite=1&test_suite_input=%28%29%5B%5D%7B%7D%3C%3E%0A%28%5B%7B%3C%3E%7D%5D%29%0A%3C%3E%7B%5B%5D%7D%28%29%0A%7B%3C%3E%28%5B%5D%29%7D%0A%3C%28%3E%29%5B%7B%7D%5D%0A%3C%5B%28%7B%29%7D%5D%3E%0A%5B%7B%3C%7D%5D%3E%28%29%0A%7B%3C%3E%28%5B%7D%5D%29%0A%3C%7B%28%3E%7D%29%5B%5D%0A%5B%28%5D%3C%29%7B%3E%7D%0A%3C%28%5B%3E%7B%29%7D%5D%0A%28%3C%7B%5B%3E%7D%29%5D%0A%28%3C%5B%7B%29%3E%7D%5D%0A%3C%7B%5B%28%3E%7D%29%5D%0A%5B%7B%3C%28%5D%7D%3E%29%0A%28%3C%7B%5B%29%3E%7D%5D&debug=0) `JmC/CdTz`: First, this converts each symbol pair to a single character by map each input character to its character code (`Cd`) divided by 10 (`/ T`), which is the same for each pair but different between all pairs. The resultant number is converted back into a character for purposes to be revealed later (`C`). The resultant list of characters is saved to `J`. `lsm@FPcsJd{J`: Now, we map over the unique characters in `J` (`{J`). We start by chopping the string formed by concatenating `J` using the current character as the delimeter (`csJd`). A pair of brackets overlaps the current pair if it appears in the second group and either the first or third group. To avoid double counting, we'll just count the first and second group case. So, we remove the third group (`P`) and take the intersection of the remaining groups (`@F`). Finally, we concatenate the overlap characters (`s`) and print the length of the resut (`l`). [Answer] # Python 3, 107 ``` t=0 s="" for x in input():s+=chr(ord(x)&~7) for x in s:a=s.split(x);t+=len(set(a[0])&set(a[1])) print(t//2) ``` Loosely based on my CJam solution. [Answer] # [Retina](https://github.com/mbuettner/retina), ~~128~~ ~~108~~ ~~64~~ ~~62~~ 55 bytes ``` (T`)]>}`([<{ (\D)(.*)\1(.*) \n$2\n$3 (?=(\D).*\n.*\1) 1 \n <empty> ``` Where `<empty>` represents an empty trailing line. For counting purposes, put each line in a separate file, and replace the `\n` with actual linefeed characters. For convenience, you can use this equivalent code with the `-s` flag from a single file: ``` (T`)]>}`([<{ (\D)(.*)\1(.*) #$2#$3 (?=(\D)[^#]*#[^#]*\1) 1 # <empty> ``` Output is [unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary). ## Explanation The first `(` tells Retina to execute the entire code in a loop until an iteration stops changing the string. In this case, it will always iterate four times, once for each bracket type. ``` T`)]>}`([<{ ``` This simply turns each closing bracket into the corresponding opening bracket, so that we can match corresponding brackets with a simple backreference later on. (This stage becomes a no-op after the first iteration. It's only included in the loop, because the `T` already required a backtick, so adding `(` cost only one instead of two bytes.) ``` (\D)(.*)\1(.*) \n$2\n$3 ``` This replaces the left-most pair of brackets with newlines. We use `\D` to distinguish brackets from the `1`s we add later in the loop for counting. The `(.*)` at the end ensures that only one pair is replaced (because matches cannot overlap). ``` (?=(\D).*\n.*\1) 1 ``` The entire regex is in a lookahead, so this matches a *position*. More specifically it matches one position for each pair of brackets which has been separated by the other brackets we just turned into newlines. A `1` is inserted into each of these positions. We can just leave the `1`s there, because they don't affect any of the other regexes (because the `\D`s ensure that we don't match them accidentally). ``` \n <empty> ``` Finally, we remove the newlines (i.e. the placeholders for the current type of brackets) - this means that we've reduced the remaining problem to a string of length 6 containing only 3 types of brackets, but otherwise it works exactly the same. At the end, only the `1`s we inserted will be left, and their amount corresponds exactly to the number of interlocking brackets. [Answer] # JavaScript (ES7), ~~121~~ 117 bytes ``` x=>(a=b=0,[for(c of x)for(d of'1234')(e=c.charCodeAt()/26|0)==d?a^=1<<d:b^=(a>>d&1)<<d*4+e],f=y=>y&&y%2+f(y>>1))(b)/2 ``` Wow. That was fun. I sketched out an answer idea when this challenge first came out, but it was over 150 bytes long and I didn't want to put in the effort to golf it. I ran across this idea in my notebook yesterday and decided I wouldn't stop thinking about it until I had fully golfed it. I ended up writing out two entirely new algorithms, the first of which ended up several bytes shorter after golfing off around 25 bytes with tons of bit-hacking. ### How it works First we set variables `a` and `b` to `0`. `a` is a 4-bit binary array of which bracket pairs we are currently inside, and `b` is a 16-bit binary array of which bracket pairs are linked together. Next, we loop through each character `c` in `x`, and each char `d` in `'0123'`. First we determine what type of bracket `c` is with `e=c.charCodeAt()/26-1|0`. The decimal char codes of each bracket type are as follows: ``` () => 40,41 <> => 60,62 [] => 91,93 {} => 123,125 ``` By dividing by 26, subtracting 1, and flooring, we map these to 0, 1, 2, and 3, respectively. Next we check if this number is equal to the current value of `d`. If it is, we are either entering or exiting the `d`th bracket type, so we flip the `d`th bit in `a` with `a^=1<<d`. If it's not, but we *are* inside the `d`th bracket type, we need to flip the `e`th bit in the `d`th 4-bit section of `b`. This is done like so: ``` b^=(a>>d&1)<<d*4+e ``` `(a>>d&1)` Returns the `d`th bit in `a`. If we are inside the `d`th bracket type, this returns 1; otherwise, it returns 0. Next, we shift this left by `d*4+e` bits, and XOR `b` by the result. If we are inside the `d`th bracket type, this XORs the `d*4+e`th bit of `b`; otherwise, it does nothing. At the end of all the looping, `b` will contain a number of 1-bits equal to twice the desired return value. But we still need to figure out how many bits this is. That's where the sub-function `f` comes in: ``` f=y=>y&&y%2+f(y>>1) ``` If `y` is 0, this simply returns 0. Otherwise, it takes the last bit of `y` with `y%2`, then adds the result of running all but the last bit `y` through the function again. For example: ``` f(y) => y && y%2 + f(y>>1) f(0b1001101) => 1 + f(0b100110) = 4 f(0b100110) => 0 + f(0b10011) = 3 f(0b10011) => 1 + f(0b1001) = 3 f(0b1001) => 1 + f(0b100) = 2 f(0b100) => 0 + f(0b10) = 1 f(0b10) => 0 + f(0b1) = 1 f(0b1) => 1 + f(0b0) = 1 f(0b0) => 0 = 0 ``` We run `b` through this function and divide the result by 2, and there is our answer. [Answer] # Oracle SQL 11.2, 206 bytes ``` WITH v AS(SELECT b,MIN(p)i,MAX(p)a FROM(SELECT SUBSTR(TRANSLATE(:1,'])>}','[(<{'),LEVEL,1)b,LEVEL p FROM DUAL CONNECT BY LEVEL<9)GROUP BY b)SELECT COUNT(*)FROM v x,v y WHERE x.i<y.i AND x.a<y.a AND y.i<x.a; ``` Un-golfed : ``` WITH v AS( -- Compute min and max pos for each bracket type SELECT b,MIN(p)i,MAX(p)a FROM ( -- replace ending brackets by opening brakets and split the string SELECT SUBSTR(TRANSLATE(:1,'])>}','[(<{'),LEVEL,1)b,LEVEL p FROM DUAL CONNECT BY LEVEL<9 ) GROUP BY b ) SELECT COUNT(*) FROM v x,v y WHERE x.i<y.i AND x.a<y.a AND y.i<x.a -- Apply restrictions for interlocking brackets ``` ]
[Question] [ Write the shortest code that will take any real number greater than 1 as input and will output its positive inverse factorial. In other words, it answers the question "what number factorial is equal to this number?". Use the Gamma function to extend the definition for factorial to any real number as described [here](http://en.wikipedia.org/wiki/Factorial#The_Gamma_and_Pi_functions). For example: ``` input=6 output=3 input=10 output=3.390077654 ``` because `3! = 6` and `3.390077654! = 10` **Rules** * It is forbidden to use built in factorial functions or gamma functions, or functions that rely on these functions. * The program should be able to calculate it to 5 decimal digits, with the theoretical ability to calculate it to any precision (It should contain a number that can be made arbitrary big or small to get arbitrary precision) * Any language is allowed, shortest code in characters wins. I made a working example [here](http://jensrenders.site88.net/inversefactorial.htm). Have a look. [Answer] ## Javascript (116) Black magics here ! Gives a result in **few milliseconds**. Only elementary math functions used : `ln`, `pow`, `exponential` ``` x=9;n=prompt(M=Math);for(i=1e4;i--;)x+=(n/M.exp(-x)/M.pow(x,x-.5)/2.5066/(1+1/12/x+1/288/x/x)-1)/M.log(x);alert(x-1) ``` Too bad LaTeX is not supported on codegolf but basically, I coded a [newton solver](http://en.wikipedia.org/wiki/Newton%27s_method) for `f(y)=gamma(y)-n=0` and `x=y-1` (because `x!` is `gamma(x+1)`) and approximations for gamma and digamma functions. Gamma approximation is [Stirling approximation](http://en.wikipedia.org/wiki/Stirling%27s_approximation) Digamma approximation use [Euler Maclaurin formula](http://en.wikipedia.org/wiki/Digamma_function#Computation_and_approximation) The digamma function is the derivative of gamma function divided by gamma function : `f'(y)=gamma(y)*digamma(y)` Ungolfed : ``` n = parseInt(prompt()); x = 9; //first guess, whatever but not too high (<500 seems good) //10000 iterations for(i=0;i<10000;i++) { //approximation for digamma d=Math.log(x); //approximation for gamma g=Math.exp(-x)*Math.pow(x,x-0.5)*Math.sqrt(Math.PI*2)*(1+1/12/x+1/288/x/x); //uncomment if more precision is needed //d=Math.log(x)-1/2/x-1/12/x/x+120/x/x/x/x; //g=Math.exp(-x)*Math.pow(x,x-0.5)*Math.sqrt(Math.PI*2)*(1+1/12/x+1/288/x/x-139/51840/x/x/x); //classic newton, gamma derivative is gamma*digamma x-=(g-n)/(g*d); } alert(x-1); ``` Test cases : ``` 10 => 3.390062988090518 120 => 4.99999939151027 720 => 6.00000187248195 40320 => 8.000003557030217 3628800 => 10.000003941731514 ``` [Answer] ## Mathematica - ~~74~~ ~~54~~ 49 The proper way will be ``` f[x_?NumberQ]:=NIntegrate[t^x E^-t,{t,0,∞}] x/.FindRoot[f@x-Input[],{x,1}] ``` If we just drop the test `?NumberQ` it would still work, but throw some nasty warnings, which would go away if we switch to symbolic integration `Integrate`, but this would be illegal (I suppose), because the function would automatically be converted to `Gamma` function. Also we can get rid of external function that way. Anyway ``` x/.FindRoot[Integrate[t^x E^-t,{t,0,∞}]-Input[],{x,1}] ``` To heck with proper input, just function definition (can't let MatLab win) ``` x/.FindRoot[Integrate[t^x E^-t,{t,0,∞}]-#,{x,1}]& ``` If built-in factorial were allowed ``` N@InverseFunction[#!&]@Input[] ``` The above does not give an integer (which is the argument for a true factorial function). The following does: ``` Floor[InverseFunction[Gamma][n]-1] ``` [Answer] # ised: ~~72~~ 46 characters This is almost a perfect fit... there is a "language" out there that seems to be meant precisely for math golf: [ised](http://ised.sourceforge.net/). Its obfuscated syntax makes for a very short code (no named variables, just integer memory slots and a lot of versatile single char operators). Defining the gamma function using an integral, I got it to 80 seemingly random characters ``` @4{:.1*@+{@3[.,.1,99]^x:*exp-$3}:}@6{:@{$4::@5avg${0,1}>$2}$5:}@0,0@1,99;$6:::. ``` Here, memory slot $4 is a factorial function, memory slot $6 bisection function and memory slot $2 is expected to be set to input (given before sourcing this code). Slots $0 and $1 are the bisection boundaries. Call example (assuming above code is in file `inversefactorial.ised`) ``` bash> ised '@2{556}' --f inversefactorial.ised 556 5.86118 ``` Of course, you could use the builtin ! operator, in which case you get down to 45 characters ``` @6{:@{{@5avg${0,1}}!>$2}$5:}@0,0@1,99;$6:::. ``` Careful, operator precendence is weird sometimes. Edit: remembered to inline the functions instead of saving them. Beat Mathematica with 72 characters! ``` @0,0@1,99;{:@{{:.1*@+{@3[.,.1,99]^x:*exp-$3}:}::@5avg${0,1}>$2}$5:}:::. ``` And using the ! builtin you get 41. --- An year overdue update: I just realized this was highly inefficient. Golfed-down to 60 characters: ``` @0#@1,99;{:@{.1*@3[.,.1,99]^@5avg${0,1}@:exp-$3>$2}$5:}:::. ``` If utf-8 is used (Mathematica does it too), we get to 57: ``` @0#@1,99;{:@{.1*@3[.,.1,99]^@5avg${0,1}·exp-$3>$2}$5:}∙. ``` A bit different rewrite can cut it down to 46 (or 27 if using builtin !): ``` {:x_S{.5@3[.,.1,99]^avgx·exp-$3*.1<$2}:}∙∓99_0 ``` The last two characters can be removed if you are ok with having the answer printed twice. [Answer] ## MATLAB ~~54~~ 47 If I pick the right challenges MATLAB is really nice for golfing :). In my code I find the solution to the equation (u-x!)=0 in which u is the user input, and x the variable to solve. This means that u=6 will lead to x=3, etc... ``` @(x)fsolve(@(y)u-quad(@(x)x.^y./exp(x),0,99),1) ``` The accuracy can be changed by altering the upper limit of the integral, which is set at 99. Lowering this will change the accuracy of the output as follows. For example for an input of 10: ``` upper limit = 99; answer = 3.390077650833145; upper limit = 20; answer = 3.390082293675363; upper limit = 10; answer = 3.402035336604546; upper limit = 05; answer = 3.747303578099607; ``` etc. [Answer] # Python - 199 chars Ok, so you'll need a lot of stack space and a lot of time, but hey, it'll get there! ``` from random import * from math import e def f(x,n): q=randint(0,x)+random() z=0 d=0.1**n y=d while y<100: z+=y**q*e**(-y)*d y+=d return q if round(z,n)==x else f(x,n) ``` Here's another approach with even more recursion. ``` from random import * from math import e def f(x,n): q=randint(0,x)+random() return q if round(h(q,0,0.1**n,0),n)==x else f(x,n) def h(q,z,d,y): if y>100:return z else:return h(q,z+y**q*e**(-y)*d,d,y+d) ``` Both of these can be tested with `>>>f(10,1)` provided you set the recursion limit around 10000. More than one decimal place of accuracy will likely not complete with any realistic recursion limit. Incorporating the comments and a few modifications, down to 199 chars. ``` from random import* from math import* def f(x,n): q=random()*x+random() z=y=0 while y<100: z+=y**q*e**-y*0.1**n y+=0.1**n return q if round(z,n)==x else f(x,n) ``` [Answer] # Python 2.7 - ~~215~~ [189 characters](http://www.javascriptkit.com/script/script2/charcount.shtml) ``` f=lambda t:sum((x*.1)**t*2.71828**-(x*.1)*.1for x in range(999)) n=float(raw_input());x=1.;F=0;C=99 while 1: if abs(n-f(x))<1e-5:print x;break F,C,x=f(x)<n and(x,C,(x+C)/2)or(F,x,(x+F)/2) ``` Usage: ``` # echo 6 | python invfact_golf.py 2.99999904633 # echo 10 | python invfact_golf.py 3.39007514715 # echo 3628800 | python invfact_golf.py 9.99999685376 ``` To change precision: change `1e-5` to a smaller number for greater precision, larger number for worse precision. For better precision you probably want to give a better value for `e`. This just implements the factorial function as `f`, and then does a binary search to hone in on the most accurate value of the inverse of the input. **Assumes the answer is less than or equal to 99** (it wouldn't work for an answer of 365 for sure, I get a math overflow error). Very reasonable space and time usage, always terminates. Alternatively, replace `if abs(n-f(x))<=10**-5: print x;break` with `print x` to shave off **50 characters**. It'll loop forever, giving you a more and more accurate estimate. Not sure if this would fit with the rules though. [Answer] # [dg](http://pyos.github.io/dg/) - 131 133 bytes ``` o,d,n=0,0.1,float$input! for w in(-2..9)=>while(sum$map(i->d*(i*d)**(o+ 10**(-w))/(2.718281**(i*d)))(0..999))<n=>o+=10**(-w) print o ``` Since dg produces CPython bytecode this should count for Python as well, but oh... Some examples: ``` $ dg gam.dg 10 3.3900766499999984 $ dg gam.dg 24 3.9999989799999995 $ dg gam.dg 100 4.892517629999997 $ dg gam.dg 12637326743 13.27087070999999 $ dg gam.dg # i'm not really sure about this one :P it's instantaneous though 28492739842739428347929842398472934929234239432948923 42.800660880000066 $ dg gam.dg # a float example 284253.232359 8.891269689999989 ``` EDIT: Added two bytes because I didn't remember that it should accept floats as well! [Answer] # [R](https://www.r-project.org/), 92 bytes A function, `g`, which takes input `z` and outputs the inverse factorial of that number *There is almost certainly more to be golfed out of this, so if you see something that I can improve, please let me know.* ``` library(pryr) g=f(z,uniroot(f(a,integrate(f(x,x^a*exp(-x)),0,Inf)$v-z),c(0,z+1),tol=1e-9)$r) ``` [Try it online!](https://tio.run/##jVBBasMwELz7FULksJuuwQpJoAVdAzn1AyWgGNkYjCxWcpH8eUcBE0JPndvMMLuzy@s6Dnc2nMFzZqx63cFCsxt4miJ0YGhw0fZsoi0sUbqZvU0e6oRIDV1dh7vfekFqoaHlQyHFadTK1p@4Y1yTbkHRgY50JtXQ4YhV1sF4P@YyrMeqNRHk1YkvIcT3HMVfXEwbJx7MCMVF8ePkltH/xivjTShXhPkeIm8kkRQSqVREkqWDpM3ORVPnIr5p3atLfkbUqbwgWK/lc8P6AA "R – Try It Online") ## Ungolfed and Commented ``` library(pryr) # Add pryr to workspace inv.factorial = f(z, # Declare function which uniroot( # Finds the root of f(a, integrate( # The integral of f(x, x^a*exp(-x)) # The gamma function ,0 ,Inf # From 0 to Infinity )$value-z # Minus the input value, `z` ), c(0, z+1), # On the bound of 0 to z+1 tol = 1e-323 # With a specified tolerance )$root # And outputs the root ) # End function ``` [Try it online!](https://tio.run/##jZLNbtswEITveoqB3APZrgvLSXMooEOANkAORS4FeimC0BQVE5VJgSITyS/vkors/lhBuzftzKcdcukOh0ZvnHADa93gOOZqgeuqQtLhLZ6t@9G1QqpMm6f3tZDeOi0alKjZnv4mPynZCKdQByO9tgbPWy23QAYEo521nuGVWuBGm6qD3yokI2ydpX7NBEEbrx6d8IqdUV@jf5KbyCB7EWrWE/p78Vb1LVv2nJ9Bj2K3E6ek2VGkFejW1PMJnd1hla4lOrTRfpgw/uZJNEEt97PYF23Cy8G0aYPH6CU87B9GnBMkWxH27wpOM/idGdmNDaZKJxwDRPMIe5t2UajlxfpibvY37bcQ6Folda1VlQDlhIkLTbHHm8brO7lOI4OPqX9tJuP4Vy3wOYLHuz30pWQFremSrqhY0fqSZ0PZibZthrimPx4Wz6TwLL81@Bj/cxfO090crSyqHN9NPjHlf9eJaUUX31QXNp1300dPOXJOMS6nPGbIaZKH2CuuYvO33ik2GxJSfOCcOtWWeZpw@Ak "R – Try It Online") [Answer] # Javascript (without using loops!) To do this, I used a well-known [numerical approximation of the inverse of the Stirling Factorial approximation](https://math.stackexchange.com/questions/430167/is-there-an-inverse-to-stirlings-approximation), (and also got inspiration by this ..cough.. cough.. [code of someone else](http://forums.xkcd.com/viewtopic.php?t=38065&p=1514897#p1521506)...) ``` function f(n){ if(n==1) return 1; else if(n==2) return 2; else if(n==6) return 3; else if(n==24) return 4; else{ return Math.round((((Math.log(n)/Math.LN10 * Math.log(10.) - .5 * Math.log(2.*3.141592))+(((Math.log(n)/Math.LN10 * Math.log(10.) - .5 * Math.log(2.*3.141592))+(((Math.log(n)/Math.LN10 * Math.log(10.) - .5 * Math.log(2.*3.141592))+(Math.log(n)/Math.LN10 * Math.log(10.) - .5 * Math.log(2.*3.141592)))/Math.log((Math.log(n)/Math.LN10 * Math.log(10.) - .5 * Math.log(2.*3.141592)))))/Math.log((((Math.log(n)/Math.LN10 * Math.log(10.) - .5 * Math.log(2.*3.141592))+(Math.log(n)/Math.LN10 * Math.log(10.) - .5 * Math.log(2.*3.141592)))/Math.log((Math.log(n)/Math.LN10 * Math.log(10.) - .5 * Math.log(2.*3.141592)))))))/Math.log((((Math.log(n)/Math.LN10 * Math.log(10.) - .5 * Math.log(2.*3.141592))+(((Math.log(n)/Math.LN10 * Math.log(10.) - .5 * Math.log(2.*3.141592))+(Math.log(n)/Math.LN10 * Math.log(10.) - .5 * Math.log(2.*3.141592)))/Math.log((Math.log(n)/Math.LN10 * Math.log(10.) - .5 * Math.log(2.*3.141592)))))/Math.log((((Math.log(n)/Math.LN10 * Math.log(10.) - .5 * Math.log(2.*3.141592))+(Math.log(n)/Math.LN10 * Math.log(10.) - .5 * Math.log(2.*3.141592)))/Math.log((Math.log(n)/Math.LN10 * Math.log(10.) - .5 * Math.log(2.*3.141592))))))))) } } ``` ]
[Question] [ ## Description Your task is to output a 'depthmap' - that is, a heightmap of an object but not seen from its top but from its front. For example, consider the following object as shown on the image. The height map is shown on the left. The corresponding depth map would be (as seen from standing at the arrow): ``` 010 211 <- Depthmap 322 ``` If you stand at the arrow, there are 3 cubes behind each other at the bottom left-hand point, 2 behind each other on the middle left-hand point, 0 at the top left-hand point etc. ![example](https://i.stack.imgur.com/xFc72.png) ## Input Input is a two dimensional array of any sizes (not necessarily square). ## Output Output is another two dimensional array which represents the depthmap. As you can deduce, its sizes are `(height x width)`. In the image, it would be `(3 x 3)`. Note that if the highest tower of cubes was 5, the depthmap would be an array of `(5 x 3)`. ## Winning condition The shortest code wins. ## Disallowed All languages allowed, no explicit restrictions. (I don't know what you can come up with, but play fair please.) ## Examples ``` Input: Ouput: 5321 0001 1456 1012 2105 1112 1212 2222 3323 Input: Output: 22 01 13 12 00 22 Input: Output: (of the sample image) 232 010 210 211 101 322 ``` [Answer] ### Golfscript, 42 chars ``` n%{n*~]}%zip:|[]*$),{:);n|{{)>},,}%}%-1%\; ``` results ``` $ golfscript 2657.gs < 2657-1.txt 0001 1012 1112 1212 2222 3323 $ golfscript 2657.gs < 2657-2.txt 01 12 22 $ golfscript 2657.gs < 2657-3.txt 010 211 322 ``` [Answer] ## Ruby 1.9, 102 characters ``` f=$<.map{|g|[*g.chop.bytes]} f.flatten.max.downto(49){|j|puts f.transpose.map{|n|n.count{|r|r>=j}}*""} ``` Passes all testcases. [Answer] ## Windows PowerShell, 108 ~~111~~ ~~114~~ ``` (($i=@($input))-split''|sort)[-1]..1|%{$h=$_ -join(1..$i[0].Length|%{$x=$_-1 @($i|?{"$h"-le$_[$x]}).count})} ``` Passes all test cases. [Answer] ## Haskell, 118 characters ``` import List p h=map(\c->transpose(lines h)>>=show.length.filter(>=c))['1'..maximum h] main=interact$unlines.reverse.p ``` --- * Edit (122 → 118): avoid filtering by only iterating to maximal height [Answer] ## Scala 236 characters ``` object D extends App{var(l,m,z)=(io.Source.stdin.getLines.toList,0,0);val a=Array.ofDim[Int](l.head.size,10);for(i<-l;(j,q)<-i.zipWithIndex;x<-1 to j-48){a(q)(x-1)+=1;m=List(m,j-48).max};for(i<-1 to m){for(j<-a){print(j(m-i))};println}} ``` With some formatting: ``` object Depthmap extends App { var(l,m,z)=(io.Source.stdin.getLines.toList,0,0) val a=Array.ofDim[Int](l.head.size,10) for(i<-l;(j,q)<-i.zipWithIndex;x<-1 to j-48) { a(q)(x-1)+=1 m=List(m,j-48).max } for(i<-1 to m) { for(j<-a) { print(j(m-i)) } println } } ``` I'm sure a better facility with for comprehensions would mean I could cut some characters from this. [Answer] ## JavaScript, ~~235~~ ~~208~~ 195 bytes ``` function _(b){for(e=Math.max.apply(0,b.join().split(",")),f=[],c=i=0;i<e;i++){for( c=[],a=0;a<b[0].length;a++)for(d=c[a]=0;d<b.length;d++)b[d][a]>i&&c[a]++;f[e-i-1] =c.join("")}return f.join("\n")} ``` Just for the record, this is the code I made up before posting the question. (Smallened now) [Answer] Haskell Version (Now optimized) ``` import Data.List import Text.Parsec import Text.Parsec.String main= readFile"in.txt">>=(\t->either print(putStrLn.intercalate"\n".map(concatMap show).(\j->map (\n->(map(length.(filter(>=n)))(transpose$reverse j))) (reverse [1..(maximum$map maximum j)])))(parse(many1$many1 digit>>=(\x->newline>>(return$map(read.return)x)))""t)) ``` Ungolfed version ``` import Data.List (foldl', transpose, intercalate) import Text.Parsec import Text.Parsec.String -- Source: http://codegolf.stackexchange.com/questions/2657/swapping-heightmaps-to-depthmaps digitArray :: Parser [[Int]] digitArray = many1 $ do xs <- many1 digit optional newline return $ map (read . return) xs maxHeight :: Ord c => [[c]] -> c maxHeight = maximum . (map maximum) heightToDepth :: [[Int]] -> [[Int]] heightToDepth ins = level (maxHeight ins) where level 0 = [] level n = (map (length . (filter (>=n))) xs) : level (n-1) xs = transpose $ reverse ins lookNice xs = intercalate ['\n'] $ map (concatMap show) xs main = do inText <- readFile "in.txt" case parse digitArray "" inText of Left err -> print err Right xs -> putStrLn $ lookNice $ heightToDepth xs ``` [Answer] ## Python, 117 chars ``` import sys a=zip(*sys.stdin)[:-1] n=int(max(map(max,a))) while n:print''.join(`sum(e>=`n`for e in r)`for r in a);n-=1 ``` Similar to Ventero's Ruby solution. [Answer] # [Uiua](https://www.uiua.org), 10 bytes ``` ⇌⍉/+⬚0∵↯∶1 ``` [Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4oeM4o2JLyvirJow4oi14oav4oi2MQoKZiBbWzEgNF1bMiAyXVswIDBdXQpmIFtbNSAzIDIgMV1bMSA0IDUgNl1bMiAxIDAgNV1d) ``` ⇌⍉/+⬚0∵↯∶1 input: a matrix of numbers ∵↯∶1 replace each number with that many 1s repeated... ⬚0 ...filling the remaining space in the 3D array with zeros /+ sum layers element-wise ⇌⍉ transpose and reverse to put the result in correct orientation ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 14 bytes ``` {⊖⍉+⌿⍵≥⍀⍳⌈/,⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR17RHvZ3aj3r2P@rd@qhz6aPehke9mx/1dOjrAAVq/6c9apvwqLfvUd9UT/9HXc2H1hs/apsI5AUHOQPJEA/P4P@VQCXGCiaPereYKhgrGCkYAqGJgqmCGZhtoGDKxVXJ9ah3DVeaQiUA "APL (Dyalog Extended) – Try It Online") ``` {⊖⍉+⌿⍵≥⍀⍳⌈/,⍵} Monadic function: ⍵ Start with a 2D array ⍵. ⌈/, Find the overall maximum value h. ⍳ Make the list 1...h ≥⍀ Make a ≥ table between that list and ⍵. Now we have a 3D matrix where position [a,b,c] represents whether ⍵[a,b] is at least c. +⌿ We sum along the outermost (first) dimension, since that corresponds to a column of ⍵. Now we have a 2D matrix where position [b,c] represents how many values in column b of ⍵ are at least c. ⍉ Transpose so the heights are rows. ⊖ Flip vertically. ``` [Answer] ## Clojure, 102 bytes ``` #(for[h(range(apply max(flatten %))0 -1)](map(fn[w _](count(for[r % :when(>=(r w)h)]_)))(range)(% 0))) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 bytes ``` c rÔÆÕËè>X w ``` [Try all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=YyBy1MbVy+g+WAp3&input=W1tbNSAzIDIgMV0KWzEgNCA1IDZdClsyIDEgMCA1XV0sCgpbWzIgMl0KWzEgM10KWzAgMF1dLAoKW1syIDMgMl0KWzIgMSAwXQpbMSAwIDFdXV0KLVFt) Outputting the rows in reversed order would save [2 bytes](https://ethproductions.github.io/japt/?v=1.4.6&code=YyBy1MbVy+g+WA==&input=W1s1IDMgMiAxXQpbMSA0IDUgNl0KWzIgMSAwIDVdXQotUQ==), taking input in column-major order would save [1 byte](https://ethproductions.github.io/japt/?v=1.4.6&code=YyBy1MbL6D5YCnc=&input=W1s1IDEgMl0KWzMgNCAxXQpbMiA1IDBdClsxIDYgNV1dCi1R), doing both would (naturally) save [3 bytes](https://ethproductions.github.io/japt/?v=1.4.6&code=YyBy1MbL6D5Y&input=W1s1IDEgMl0KWzMgNCAxXQpbMiA1IDBdClsxIDYgNV1dCi1R) Explanation: ``` c rÔ #Find the maximum height Æ #For each number X in the range [0...max_height]: Õ # Get the columns of the input Ë # For each column: è>X # Count how many items are greater than X w #Reverse the output ``` [Answer] # [Julia](https://julialang.org), 55 bytes ``` !a=[sum(a[:,j].>m-i) for i=1:(m=max(a...)),j=axes(a,2)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVG7boMwFFVXvuKSyZYIwqa0FZGztAxd2g6JVMliMApIRkBRAImO_Y4uWfJR7dfUNg6htmzfxznn-trf53KopDidzkNfrB9-7l3BeDfUSPDYK1N_W68lhuLjCJKRGNWsFiMSvu9j7JVMjHmHhEdxOtF_b776vOs7YMAdHkEIFAhs1LqFCO6Upf0AohTYFngAek4AfVJjkdmi1qJ2bpSglgxTh1OLCdWuVC6CxBINycBC6-kSttAVHNgUMdqGkjq6W9UV5GOLQTZgWnJAjfYomx6tnl9iWGETOciurcQnEngJeN3vZkSmHsMV_8DZlJGFLgEug8z4C4Hk_S153CVPs8qSru9lgnlzuFatGoQdFZl-4vKhfw) ]
[Question] [ Given a rectangle, a start point, and an end point, find any path from start to finish that avoids the rectangle. ## Example Suppose you were at \$(1.5, -1.5)\$ and you needed to get to \$(2, 4)\$. However, there is a rectangle with upper left corner \$(1, 3)\$ and bottom right corner \$(4, 1)\$ in your way. It would look like this:                              [![](https://i.stack.imgur.com/pXmiS.png)](https://i.stack.imgur.com/pXmiS.png) There are lots of paths you could take to get from the (green) start to the (red) end: * You could go via \$(-3, 3)\$. * You could go to \$(-1.5, -0.5)\$ and then to \$(-1, 4)\$. * Since you're infinitely thin (having perfected your workout routine), you could go via \$(4, 1)\$ and \$(4, 3)\$. * Among many others. Here's what those three options look like (click for full size): [![](https://i.stack.imgur.com/0B94X.png)](https://i.stack.imgur.com/0B94X.png)[![](https://i.stack.imgur.com/vsso8.png)](https://i.stack.imgur.com/vsso8.png)[![](https://i.stack.imgur.com/JqgKW.png)](https://i.stack.imgur.com/JqgKW.png) ## Challenge Given a starting point \$S\$, an end point \$E\$, and the coordinates for the upper left and bottom right corners of a rectangle (in any format reasonable for your language, including complex numbers if you wish), output a series of points \$A\_1, A\_2, \ldots, A\_n\$ of any length such that the piecewise linear path \$S \rightarrow A\_1 \rightarrow A\_2 \rightarrow \ldots \rightarrow A\_n \rightarrow E\$ does not intersect the interior of the rectangle. Note that: * The start point and end point will not be inside the rectangle, nor on the edge or corner of the rectangle. * Your path may touch the corners and edges of the rectangle, but must not intersect the rectangle's interior. * You may output nothing, an empty list or similar if you wish to traverse \$S \rightarrow E\$ directly. * You may assume that the rectangle has a strictly positive width and height. * Your approach need not use the same number of points for all testcases. * The path may have duplicate points, and may intersect itself, if you so wish. ## Testcases Here, `(sx,sy)` is the start point, `(ex,ey)` is the end point, `(tlx,tly)` is the top left corner of the rectangle and `(brx,bry)` is the bottom right corner. Note that from the spec we will always have `tlx < brx` and `tly > bry`. ``` Input -> Sample output (one of infinite valid answers) (sx,sy), (ex,ey), (tlx,tly), (brx,bry) -> ... (1.5,-1.5), (2,4), (1,3), (4,1) -> (-3,3) or (-1.5,0.5),(-1,4) or (4,1),(4,3) (-5,0), (5,0), (-1,1), (2,-2) -> (0,5) or (-5,1),(5,1) (0.5,-2), (0.5,1), (2,2), (4,-3) -> [] or (0.5,-0.5) or (-1,-0.5) ``` ## Scoring The shortest code in bytes wins. [Answer] # JavaScript (ES6), ~~66~~ 57 bytes Expects `(Sx,Sy,Ex,Ey,[Tx,Ty],[Bx,By])`. Returns 3 points. ``` (S,s,E,e,T,B,[x,y]=T)=>[S>x&s<y?B:T,[B[0],y],E>x&e<y?B:T] ``` [Try it online!](https://tio.run/##ZYzBCsIwGIPvPoiskI622y7iJgz2BOvtp4cxO1HGKlZke/ra6kk8JIHkI7fhNfjxcb0/@eLONkx1yHp4dLDQaEErNlNrVjfUN@veH7dTe9CgloSJC7pY2m9pwugW72abz@6STZnMK/BkCiVIojCgEtIwtvsFeQWBJOIy7iAFrv4xkf4UUsjEqM8fLyIZ3g "JavaScript (Node.js) – Try It Online") ### Method The first point is \$(Bx,By)\$ if the start point is in the gray area or \$(Tx,Ty)\$ otherwise. The second point is always \$(Bx,Ty)\$. The third point is \$(Bx,By)\$ if the end point is in the gray area or \$(Tx,Ty)\$ otherwise. [![schema](https://i.stack.imgur.com/VgiKC.png)](https://i.stack.imgur.com/VgiKC.png) [Answer] # [Python 2](https://docs.python.org/2/), 49 bytes ``` lambda S,E,T,B:[(T*(L<B)+L+T)[::3]for L in S,T,E] ``` [Try it online!](https://tio.run/##PU6xDoIwEJ3lK25s4WpogaWRhYSNzW5IDEaJJFoIdPHra0@Iy727917eu/njnpNVfigv/tW/b/cezlijwUq3zMSsOVU8aRLDW62zbpgWaGC0wWOw7rx7rO462nmFElomjwWKMDgCU5gTSMwIcpS8w2ARBaZE7CBkEH5uoTZDShmKONp2UW0ZIuMdQERPhE5649@vo8O8jNbBwOJwc/8F "Python 2 – Try It Online") **53 bytes** ``` def f(S,E,T,B): for L in S,T,E:L[L>B]=T[L>B];print L ``` [Try it online!](https://tio.run/##PU6xDoMgFJzrV7wRmkcjqIuNHUzc2HQzpEslJWmQKEu/ngKaLu9e7i53577@vVoRwmvRoMmIA07Y07YAvW4gwVgYIzO0cpaPXnVThrvbjPUgg192/zTW7dDBTPitQRYPRSAC6wQcqwQ1cqowWliDZSJOYDwK2c3EYShThkhc@k5RHBmsogqgSMtiZ9r272@LiybX@WN2TxzN47MhaooWl7w3/AA "Python 2 – Try It Online") We make a path out of only horizontal or vertical segments, which means that each step changes one coordinate [word-ladder](https://en.wikipedia.org/wiki/Word_ladder)-style. Our path `S->E` always goes through the rectangle's top left vertex `T`. ``` S ? T ? E ``` We go from `S` to `T` via a pit stop that's a hybrid between them, changing either the first or second coordinate of `S` to that of `T`: ``` S0, S1 S0, S1 S0, T1 or T0, S1 T0, T1 T0, T1 ``` That is, we go from `S` to `T` by stepping vertical-then-horizontal or horizontal-then-vertical. We pick one of them to avoid crossing the rectangle's interior, though in many cases either would work. Changing the first coordinate can only fail if we're directly right of the rectangle, and changing the second can only fail if we're directly above it. We can separate those two cases by checking whether we're left or right of `B`. We similarly hybridize the end point `E` to connect it to `T`. In the code, each of the three points S,T,E is hybridized with T and printed. For T, the hybridization leaves it unchanged. The 53-byte version of the code uses list mutation, which necessitates a non-`lambda` function. The 49-byte version above does it with list-slicing trickery `(T*(L<B)+L+T)[::3]`, equivalent to `[L+T,T+L][L<B][::3]`. **49 bytes** ``` def f(B,*R): for L in R:L[L>B]=R[1][L>B];print L ``` [Try it online!](https://tio.run/##PU8xCoNAEKz1FVt6YS94pzYGUwh2V2k6kRCIkoNED70mrze7Kml2hp1hZ9Z9/Wsa9bo@@wGGqMRTLfIQhmkGA3aEOjetuZZdUbeq29jFzXb0YFbfL/5uR7dAAW2kzhlKGgIh0pgyKEwYUlSiQ7LIDGNeHCAVCZtb6t0Q8w3NO2aHqPcbMhEdQMjFKJOr/fPzMGiwwhuW1OTzcNHbLh5JEWHALzUkVcS34usP "Python 2 – Try It Online") Takes inputs in order `B,S,T,E` as two-element lists. [Answer] # [R](https://www.r-project.org/), ~~86~~ ~~82~~ ~~94~~ ~~81~~ 79 bytes *Edits: -4 bytes by not outputting the start & end points, and then ~~+12~~ -1 byte to fix bug (see below)* ``` function(p,q,r,s=.5:-1)list(r[1+all(p*s>(z=r[1,]*s)),],r[2:3],r[1+all(q*s>z),]) ``` [Try it online!](https://tio.run/##XY7LDoMgEEX3fAljRxNQNyb4Fd0Z01BrGxIKCvTlz1Oou27mZk5O7oyL8mnV5eTmKUhz07OI14eZgrKGLriiQy@qtisZaOUDdQM7SK3pUviebiKtOBYeAEd0A@/qHLuxJmNLHOJilQlMTJRVLZZpAPkhnhDHBki@Le4yOPWmycIaG2SAxtmX4Hj@5DwCIX@f0r0Y9zLMHOIX "R – Try It Online") Goes directly from starting point to one of the reachable specified rectangle corners\*. Then goes to any of the non-specified corners (along the edge of the rectangle), and from there to a specified corner (this might or might not be a backtrack), from which it can go directly to the end point. A slightly-modified version of the program can avoid any detours if the rectangle isn't actually in the way, for [90 bytes](https://tio.run/##nY7BTsMwEETv@QpLHPCWTYWd9lLJfAW3qkImcVtLru3aGyj9@WCnCKEeuexoZ0ajlyb9EezwlkxP2h@cUdN@9D3Z4HnEMybMarnetAJJaed4XOQXflVpK3C3yABg95zampxLcgVwNhMv8RPhDtNWbrpZ2vLCFIP1JFTPxXKNbTnQzJYslsQVNBVDnTQle@GlhR2uUAD6FD6VxPevqq/QNHfQ/DaMtzGsfik9MHPRp@gM@y0yOmpiQzDZPxLzxgxsnrL@wLgPLIwUR/qhqqDPFVT@wayGuAeVWOix7f5JOn0D). (\* The bug fix: I initially assumed that the *closest* specified corner was always reachable, but this isn't necessarily the case if the rectangle is very wide & flat, and the starting-point is below it but close to the left-hand end, for instance). [Answer] # C 125 bytes ``` z(a,b){printf("%d:%d|",a,b);}d(m,n,p,q,r,s,u,v){(p-m)*(s-n)>(r-m)*(q-n)?z(m,s):z(r,n);(u-m)*(n-s)>(r-m)*(v-s)?z(r,s):z(m,n);} ``` [try it online](https://tio.run/##hVBhb8IgEP0sv4K4mMBCZ0uWbJGhf2RfaMtckxYrUFN0/nZ3VFxm9mFN6L073nHvXZVtq@pyORLFSnrqbWP8B5kv6tWi/pqzWBTnmnTMsJ7tmWWODexAT6TPOvpIXGbomtgJ7wFvjkB1dHUklhkqyDDdmMz9sA6AN/F6YnWRdb48NKZqh1rjN@frZvf0uUZ3pbYpYw0tl147j6tdrQGDVNyT@FcMx3Bn4N3DMTcLiV5N9DG/8kOKY5HyFEee8hQ9PXlJxiIbc3AQeBZympGRp7yIOYxAnWoMoRg@dEKz6SXFxpIFxUIpMF4ulXReWVAqtamBJyXu8R4P@JD4BYPhoCNw4EOD1ZVXZttqMG2Nti62dNhgix1Cs7GQXIRCPgvAXL6IwGURsYJSUPI14jLiUmZcQEcNPuIAUAay4jA@SYQloRma/d4wJLd1HlQ7aHldKCzx7xM5pQL/05EGJYfXDmS1H6zBuUBnNG3u8g0) code explanation ``` z(a,b){printf("%d:%d|",a,b);} // print routine d(m,n,p,q,r,s,u,v) // function take x0 y0 xa ya x1 y1 xb yb // x0 y0 - top left corner of rectangle // xa ya - start point a // x1 y1 - bottom right corner of rectangle // xa ya - end point b {(p-m)*(s-n)>(r-m)*(q-n)?z(m,s):z(r,n); // 1st cross product to decide P1 (see below) (u-m)*(n-s)>(r-m)*(v-s)?z(r,s):z(m,n);} // 2nd cross product to decide P2 (see below) ``` method if we go from **a** to **b** below then we can first choose one point on the rectangle that will definitely connect with a without crossing by looking to see which side of the diagonal **a** is on - below we choose **P1**. Similarly, by comparing the position of **b** with the other diagonal we can choose a second point **P2** that will connect with **b** without crossing the rectangle - as indicated in the diagram. Now **P1** and **P2** will always connect without crossing the rectangle and we are done. The list is > > **P1** > > > **P2** > > > (note to find which side of the diagonal we are we can use the cross product - if positive one side - if negative the other.) [![enter image description here](https://i.stack.imgur.com/HjFse.png)](https://i.stack.imgur.com/HjFse.png) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` IE⟦θζη⟧Eι⎇⁼μ›ιε§ζμλ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQCO6UEehSkchI1ZHAcTN1FEISS3KSyyq1HAtLE3MKdbI1VFwL0pNLEktAkmmamrqKDiWeOalpFZoAPXlArk5miBg/f9/dLSuqY4B0KRoKKVrqGMIoo10dI1iY//rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. I wanted to do this using at most two points but I couldn't come up with an easy way of deciding which direction to jump. I then tried adding a third point, but this quickly simplified into a port of @xnor's algorithm. Takes input as 4 tuples. Explanation: ``` ⟦θζη⟧ List of points S, T, E E Map over list ι Current point E Map over coordinates ›ιε Is the current point to the right of B ⁼μ If this is the appropriate coordinate §ζμ Take the relevant coordinate from T λ Otherwise keep the coordinate I Cast to string Implicitly print ``` [Answer] # [Scala](https://www.scala-lang.org/), 126 bytes Modified from [@Arnauld's answer](https://codegolf.stackexchange.com/a/210879/110802). --- Golfed version. [Try it online!](https://tio.run/##ZY5BS8QwEIXv/RVzWhKYLJuuXqIRLNmjh9J6EpHsmi6V2F2bKFtKf3udth5EA2/ykvfNJOFgvR1P@zd3iPBg6wb6MXZnB0ab0@feu2Q@5ZoZNDx5dRVUrFAGA2lHcqRS5ZipnOv@y3p2wY7r8qZwH6wm9u6yWoXbjmfgfHBQIsvWL5IYpHQ3pe5XyocRYHrlnf7CbHsMCu7b1nZPRWzr5vjMFTw2dQQNfQK0znQbfcMqJtfXCGKuKcIVApMIW047eck5/8MLAjcIS2VCThAZ6hXpf3ozT6dwNnIB05/pYrs0DMkwfgM) ``` type D=Double type Q=(D,D) def f(S:D,s:D,E:D,e:D,T:Q,B:Q)={val(x,y)=T;Seq(if(S>x&&s<y)B else T,(B._1,y),if(E>x&&e<y)B else T)} ``` Ungolfed version. [Try it online!](https://tio.run/##ZZAxb4MwEIV3fsWbIlsyUSDtgppKRWRrJ9IpiioHTOqKQoTdKqjit9PDQIZEsp7vzt89@2wyWcq@r49fKrN4k7rCnwfY9qyQbJL651gqymnlqkDB0giJgHG6daqc7iIw2hIuEM8hj/Cqjd2P2QEbZw38yhLsItByKu28a63QjbFU0gVYimdcsFjA4GkAY6jSKKJn2KisrnKiWbz8CAaz65H91E0@@WxnH3Xj4@jhecxdKyZDMXYPZp03Tf1Nv8Jkc6KpX5pGtvvUNro6HWi@90rb61xnqtqyYgULlo8CvtNQ4EGA0QvX9DeM4oBzfsP7BK4ERmV@MEAUUK8f3tMr506HLghGMJzc/fXY0Hmd1/f/) ``` object Main { type D=Double def f(S: D, s: D, E: D, e: D, T: (D, D), B: (D, D)): List[(D, D)] = { val (x, y) = T val first = if (S > x && s < y) B else T val second = (B._1, y) val third = if (E > x && e < y) B else T List(first, second, third) } def main(args: Array[String]): Unit = { println(f(1.5, -1.5, 2, 4, (1, 3), (4, 1))) println(f(-5, 0, 5, 0, (-1, 1), (2, -2))) println(f(0.5, -2, 0.5, 1, (2, 2), (4, -3))) } } ``` ]
[Question] [ The [mid-autumn festival](https://en.wikipedia.org/wiki/Mid-Autumn_Festival) has begun! Unfortunately, all my mooncakes were stolen -- they're getting too expensive for small folk such as myself, and I fear I won't be able to eat any this year! So I turn to you for help. Would you be able to make me some? For those unaware, let me educate you on what a mooncake looks like. --- Mooncakes come in many different sizes! So I'm gonna give you my **input**, *n*, when I want one. Here are some examples of the **output** I want: Mooncake of size n = 3: ``` (@@@@@) (@MAF@) (@@@@@) ``` Mooncake of size n = 6: ``` (@@@@@@@@@@@) (@ @) (@ M @) (@ F @) (@ @) (@@@@@@@@@@@) ``` That is to say, a mooncake of size *n* is: * *n* lines high * *2n - 1* @s long * *2n + 1* characters long (@s and brackets) And you better not throw me your too-tiny practice mooncakes! **Assume input will always be n >= 3**. Mooncakes also **contain one of the following decorations**: * MF * MAF * HMF * JCJ * TTT * ZJ * LF * RF * CF Which one, it doesn't matter - as long as it is **vertically and horizontally centered**. It can be written vertically or horizontally too! I want variety! If you're really going to make me two of the same mooncake, the decoration better be different! That is, **multiple executions of your program with the exact same input must not always yield the same decoration**. I can't wait to eat your moon cakes, so the sooner I can receive them (**the shorter your code**) the better! Good Luck! --- For those wondering about the decorations: They are the initials of all alternative names for the Mid-Autumn Festival. A list can be found in the Wikipedia page linked at the top of this post. --- **Clarifications:** *There are no rules regarding leading and trailing whitespace*. Have as much or as little as you like! *The decorations must be in the very center of your mooncake!* On horizontal decorations, this means it must be on the middle line of your cake, and the number of characters to the left and right of the decoration string must be equal. On vertical decorations, this means it must reside in the middle column of your cake, and the number of characters above and below the decoration must be equal. ***Not all decorations must be used!*** The only requirement is that there must be more than one possibility for any given input *n*. The possibilities also do not need to be even. *Functions are acceptable.* [Answer] # Pyth, ~~71~~ ~~65~~ ~~59~~ 58 bytes *Saved 1 byte thanks to @StevenH.* ``` jjRc"(@@)"2++J*KtytQ\@m.[Kd;.[ttQ@,,O"MC"\F]Oc"MAFHMF"3QkJ ``` [Try it online.](http://pyth.herokuapp.com/?code=jjRc%22(%40%40)%222%2B%2BJ*KtytQ%5C%40m.%5BKd%3B.%5BttQ%40%2C%2CO%22MC%22%5CF%5DOc%22MAFHMF%223QkJ&input=4&test_suite_input=3%0A4%0A5%0A6&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=jjRc%22(%40%40)%222%2B%2BJ*KtytQ%5C%40m.%5BKd%3B.%5BttQ%40%2C%2CO%22MC%22%5CF%5DOc%22MAFHMF%223QkJ&input=4&test_suite=1&test_suite_input=3%0A4%0A5%0A6&debug=0) So much padding. [Answer] ## JavaScript ES6, ~~206~~ ~~196~~ ~~192~~ ~~188~~ ~~187~~ ~~180~~ ~~176~~ ~~169~~ ~~165~~ 156 bytes ``` g=(n,r=new Date%2,a=(s,x,b=' @'[+!s].repeat(n-3+!x))=>`(@${b+(s||'@')+b}@) `,l=a` `.repeat(n/2-2+n%2))=>a()+l+(n%2?a(r?'MAF':'HMF',1):a('RC'[r])+a`F`)+l+a() ``` ### Breakdown ``` r=new Date%2 // Sometimes 0, sometimes 1 // Function to create lines of the cake of the form `(@@@@@@@@@)` or `(@ ${s} @)` a=(s,x,b=' @'[+!s].repeat(n-3+!x))=>`(@${b+(s||'@')+b}@) ` // Cake parts a() // Top of the cake. l=a` `.repeat(n/2-2+n%2) // Undecorated inner part. a(r?'MAF':'HMF',1) // Decoration for uneven sized cakes. a('RC'[r])+a`F` // Decoration for even sized cakes. l // Undecorated inner part. a() // Bottom part. ``` My first attempt at code-golf. This can probably be golfed more. *saved 4 bytes thanks to @ETHProductions* **Edit** I took the liberty of using ~~`Date.now()%2`~~ `new Date%2` to satisfy: > > multiple executions of your program with the exact same input must not always yield the same decoration > > > this allows me to save another 7 bytes over `+Math.random()>.5` *saved another 4 bytes thanks to @Arnauld* [Answer] # Pyth, ~~99~~ ~~79~~ ~~71~~ ~~68~~ 64 bytes Pyth is ~~very bad~~ all right at making strings. Or maybe I'm just ~~bad~~ getting better at golfing them. ``` jmj.[-yQ3@,k@,@,O"MC"\FgydQOc"MAFHMF"3Q>2ahydQ@" @"sIcdtQc2"(@@) ``` Can create the decorations `MAF` and `HMF` horizontally, and the decorations `MF` and `CF` vertically. [Try it online!](http://pyth.herokuapp.com/?code=jmj.%5B-yQ3%40%2Ck%40%2C%40%2CO%22MC%22%5CFgydQOc%22MAFHMF%223Q%3E2ahydQ%40%22+%40%22sIcdtQc2%22%28%40%40%29&input=6&debug=0) [Answer] # Vim, 118 bytes Takes input as a buffer (e.g. a file with the number *n* as its contents). ``` "aDi()<Esc>@ai@<Esc>.xY@apddll<C-v>G$k3hr @=@a/2-1 j@=@a-2-@a%2 l:let r=abs(reltime()[1])%2 @=@a%2?r?"RJCJ":"3rT":"rFkr"."ML"[r] <Esc> ``` Here it is with the unprintable control characters in xxd format: ``` 0000000: 2261 4469 2829 1b40 6169 401b 2e78 5940 "aDi().@[[email protected]](/cdn-cgi/l/email-protection)@ 0000010: 6170 6464 6c6c 1647 246b 3368 7220 403d apddll.G$k3hr @= 0000020: 4061 2f32 2d31 0a6a 403d 4061 2d32 2d40 @a/2-1.j@=@a-2-@ 0000030: 6125 320a 6c3a 6c65 7420 723d 6162 7328 a%2.l:let r=abs( 0000040: 7265 6c74 696d 6528 295b 315d 2925 320a reltime()[1])%2. 0000050: 403d 4061 2532 3f72 3f22 524a 434a 223a @=@a%2?r?"RJCJ": 0000060: 2233 7254 223a 2272 466b 7222 2e22 4d4c "3rT":"rFkr"."ML 0000070: 225b 725d 0a1b "[r].. ``` [Try it online!](http://v.tryitonline.net/#code=ImFEaSgpG0BhaUAbLnhZQGFwZGRsbBZHJGszaHIgQD1AYS8yLTEKakA9QGEtMi1AYSUyCmw6bGV0IHI9YWJzKHJlbHRpbWUoKVsxXSklMgpAPUBhJTI_cj8iUkpDSiI6IjNyVCI6InJGa3IiLiJNTCJbcl0KGw&input=&args=OQ) (As it turns out, the V interpreter works fine for normal Vim code, too.) # Explanation ``` "aD " Delete the number and store it in @a i()<Esc> " Insert empty parentheses @ai@<Esc>.x " Insert @a '@' characters between the parentheses twice; delete 1 Y@apdd " Copy the line and paste it @a times; delete 1 ll<C-v>G$k3hr<Space> " Replace the inner area with spaces @=@a/2-1<CR>j " Go down @a/2-1 lines @=@a-2-@a%2<CR>l " Go right @a-2-@a%2 columns :let r=reltime()[1]%2<CR> " Get a random 1 or 0 based on the time (this may be OS-dependent) @=@a%2? r?"RJCJ":"3rT" " For odd @a, replace the next 3 characters with "JCJ" or "TTT" :"rFkr"."ML"[r] " For even @a, replace this character with "F" and the above with "M" or "L" <CR><Esc> ``` [Answer] # PHP, ~~342~~ ~~292~~ ~~249~~ ~~185~~ ~~178~~ 176 bytes ``` for(;$i<$n=$argv[1];)$o.=str_pad("(@",2*$n-1," @"[$i++%($n-1)<1])."@) ";$p=F.[M,AM,R,MH][rand()&2|$d=$n&1];$f=$n*($n+$d)-2;for($i=2+$d;$i--;$f+=$d?:2*$n+2)$o[$f]=$p[$i];echo$o; ``` Call with `php -r '<code>' <size>` **history** Rev 1: initial version; all sizes (including tiny cakes), all decorations, all possible directions Rev. 2: removed tiny cakes (-36 bytes), restructured decoration options, removed one decoration item (-21) and a single byte golf (-1). Rev. 3: Down to four decorations; (-17), only horizontal for odd sizes (-18) plus minor golfing (-8). Rev. 4: Thanks to Jörg for golfing down the "paint cake" part; he took off an amazing (-31). Another -6 with my additional golfing, and -27 for using a single string instead of an array of strings. Rev. 5: -7 bytes mostly thanks to Christallkeks **breakdown** This is getting slimmer by the hour. :) ``` // paint cake for(;$i<$n=$argv[1];)$o.=str_pad("(@",2*$n-1," @"[$i++%($n-1)<1])."@)\n"; // add deco $p=F.[M,AM,R,MH][rand()&2|$d=$n&1]; $f=$n*($n+$d)-2; for($i=2+$d;$i--;$f+=$d?:2*$n+2)$o[$f]=$p[$i]; // output echo$o; ``` [Answer] # Java 7, ~~399~~ 349 bytes Updated version with help from @Dodge and @Kevin Cruijssen: ``` void m(int n){int i=2,r=n%2,x=2*n,u=r+2,y=r*4+(int)(Math.random()*2)*u,z=y+u;String t="MFZJMAFHMF".substring(y,z);char[][]c=new char[n][x+1];while(i<x-1)c[0][i]=c[n-1][i++]=64;for(i=0;i<u;)c[(n-1)/2+(1-r)*i][r*(i-1)+n]=t.charAt(i++);for(i=0;i<n;){c[i][0]=40;c[i][1]=c[i][x-1]=64;c[i][x]=41;System.out.println(new String(c[i++]).replace('\0',' '));}} ``` ``` void m(int n){String[]s={"MF","MAF","ZJ","HMF","LF","JCJ","RF","TTT","CF","MAF"};char[]d=s[((int)(Math.random()*5))*2+(n%2)].toCharArray(),c[]=new char[n][2*n+1];int i=2;while(i<2*n-1)c[0][i]=c[n-1][i++]='@';i=0;while(i<d.length)c[(n-1)/2+(1-(n%2))*i][(n%2)*(-1+i)+n]=d[i++];i=0;while(i<n){c[i][0]='(';c[i][1]=c[i][2*n-1]='@';c[i][2*n]=')';System.out.println(new String(c[i++]).replace('\0',' '));}} ``` [Try it here!](https://ideone.com/yQ1fgg) The new version is much more optimized and got rid of the `String` array handling. Also as suggested, there are only 4 decorations now: 2 for even inputs (`MF`,`ZJ`) and 2 for odd inputs (`MAF`,`HMF`) which are combined into a single `String`. **Ungolfed:** ``` void m(int n){ int i=2, r=n%2, x=2*n, u=r+2, // length of the decoration string y=r*4+(int)(Math.random()*2)*u, // random starting index of string (0, 2, 4, 7) z=y+u; // exclusive end index of string (2, 4, 7, 10) String t="MFZJMAFHMF".substring(y,z); char[][]c=new char[n][x+1]; while(i < x-1) { c[0][i]=c[n-1][i++]=64; // '@' } for(i=0; i<u;) { c[(n-1)/2+(1-r)*i][r*(i-1)+n]=t.charAt(i++); // Depending on even/odd, fills the center column/row respectively with the decoration } for(i=0; i<n;) { c[i][0]=40; // '(' c[i][1]=c[i][x-1]=64; // '@' c[i][x]=41; // ')' System.out.println(new String(c[i++]).replace('\0',' ')); // Print all } } ``` [Answer] ## Batch, 386 bytes ``` @echo off set/pn= set f=HMAC set/ao=n%%2,u=n/2,l=h=u+1,d=%random%%%2*2+1 if %o%==1 set/al=u=0,d/=2 set c= for /l %%i in (4,1,%n%) do call set c= %%c%% call:l %n% for /l %%i in (2,1,%n%) do call:l %%i exit/b :l set s= if %1==%h% call set s=%%f:~%d%,2%%F if %1==%u% call set s= %%f:~%d%,1%% if %1==%l% set s= F set s=(@%c%%s%%c%@) if %1==%n% set s=%s: =@% echo %s% ``` Will only output HMF, MAF, MF or CF as appropriate. Note: certain lines end in white space. Variables: * `n` Input parameter (read from STDIN) * `f` Decoration prefixes (suffix `F` is implied) * `o` Oddness of `n` (only used once, but `if` statements don't accept expressions) * `l` Row of the upper vertical character, or `0` for a horizontal decoration * `u` Row of the lower vertical character, or `0` for a horizontal decoration * `h` Row of the horizontal decoration (gets overwritten by a vertical decoration) * `d` Index of decoration in decoration prefix (0/1 for horizontal or 1/3 for vertical) * `c` String of `n-3` spaces * `s` Output string for each row * `%1` Row number, but set to `n` for the first row too, so that both first and last rows use `@`s instead of spaces. [Answer] # C, 233 Bytes Should be able to golf this down a bit from here... ``` A="HMFMAFCF";i,j,k,t;f(n){t=time();char*S=n&1?t&1?A:A+3:t&1?A+1:A+6;for(;i<n;i++,puts(")"))for(j=0,k=2*n-1,putchar(40);j<k;putchar(0==i*j|i==n-1|j==k-1?64:n&1&i==n/2&j>n-3&j<n+1?*S++:n&1?32:(i==n/2-1|i==n/2)&j>n-2&j<n?*S++:32),j++);} ``` Great challenge, this was difficult and ugly to code. Run with this main func; ``` main(c,v)char**v; { f(atoi(v[1])); } ``` [Answer] # Ruby 2.3.1, ~~449~~ ~~265~~ ~~245~~ ~~233~~ 230 characters Seems like there should be a ruby answer, so here is a ruby answer. It's really not that clever, Hopefully someone else here will be more clever ;) Golfed version: ``` def m(n) d,s=n.odd?? [[%w{MAF HMF}.sample],n/2]:[%w{RF LF}.sample.chars,(n-2)/2] r=->f{l=f.size;q=($i-l)/2;($c=' '*$i)[q...l+q]=f;puts "(@#$c@)"} $i=2*n-1;a='@'*$i r[a] (1..n-2).map{|x|(s...s+d.size)===x ?r[d[x-s]]:r['']} r[a] end ``` Golfing tricks: * replace method declaration with a stabby string interpolation of * $globals doesn't need #{global}, only #$global * === for ranges is shorter than .covers? Readable version ``` def row(inner_width, fillchar='') padding = ( inner_width - fillchar.size) / 2 (center =(' ' * inner_width))[padding...fillchar.size+padding]=fillchar puts "(@"+center+"@)" end def mooncake(n) decoration = n.odd?? [%w{ MAF HMF JCJ TTT }.sample] : %w{ ZJ LF RF CF }.sample.chars start_row = n.odd?? (n/2) : (n - 2) / 2 inner_width = 2 * n - 1 row(inner_width,'@'*inner_width) (1...(n-1)).each do |row| if (start_row ... start_row + decoration.size).include? row row(inner_width,decoration[row - start_row]) else row(inner_width) end end row(inner_width,'@'*inner_width) end ``` Testing ``` mooncake(3) mooncake(4) mooncake(5) mooncake(6) ``` [Answer] I was bored ... here are two more versions: # PHP, 193 bytes ``` function p($s){global$n;return"(@".str_pad($s,2*$n-3,$s?" ":"@",2)."@) ";}$p=[M,MA,R,HM][rand()&2|1&$n=$argv[1]];echo p(""),$e=str_repeat(p(" "),($n+$n%2)/2-2),$n&1?p($p.F):p($p).p(F),$e,p(""); ``` a port of [Lmis´ answer](https://codegolf.stackexchange.com/q/93348#93348) # PHP, 191 bytes ``` for($p=[M,MA,R,HM][rand()&2|1&$n=$argv[1]].F;$i<$n*$w=2*$n+1;$i++)echo($x=$i%$w)?$w-1-$x?($y=$i/$w|0)%($n-1)&&1-$x&&$w-2-$x?$p[$n&1?$n>>1!=$y?9:$x-$n+1:($n-$x?9:$y-$n/2+1)]?:" ":"@":") ":"("; ``` printing the cake character by character in a single loop **breakdown** ``` for( $p=[M,MA,R,HM][rand()&2|1&$n=$argv[1]].F; // pick decoration $i<$n*$w=2*$n+1;$i++) // loop $i from 0 to $n*width-1: echo // print ... $w-1-($x=$i%$w) // 1. not last column ?$x // 2. not first column ? ($y=$i/$w|0)%($n-1) // 3. not first or last line && 1-$x%($w-3) // and not second or (width-2)th column ?$p[$n&1 ?$n>>1!=$y?3:1+$x-$n :($n-$x?3:1+$y-$n/2) ] ? // 4. decoration character :" " // 4. else: blank :"@" // 3. else: "@" :"(" // 2. else: "(" :")\n" // 1. else: ")"+newline ; ``` [Answer] # Python 3, ~~318~~ ~~301~~ ~~297~~ ~~285~~ 272 bytes **Knocked off 17 bytes with the help of DJMcMayhem** **Knocked off 4 bytes thanks to mbomb007** **Knocked off another 12 bytes thanks to DJMcMayhem** **Knocked off another 13 bytes thanks to mbomb007** My first golf ever, so it's not all that great. I used: aliasing math.ceil as y and str.format as z, nesting formats, single line imports, lambda, and bitwise operation plus some other things to get this like it is. ``` def f(n):import random,math;y=math.ceil;z=str.format;i=y(2*n-5>>1);j=y(n-3>>1);return z("{a}{}{a}",z("{d}(@{}{b}F{c}@)\n{e}"," "*i,b=random.sample(["L","R"],1)[0],c=" "*(2*n-5-i),d=z("(@{}@)\n"," "*(2*n-3))*j,e=z("(@{}@)\n"," "*(2*n-3))*(n-3-j)),a=z("({})\n","@"*(2*n-1))) ``` Ungolfed version (separated imports, no aliases, and no bitwise operation): ``` def f(n): import random; import math; return "{a}{}{a}".format( "{d}(@{}{b}F{c}@)\n{e}".format( " "*(math.ceil((2*n-5)/2)), b=random.sample(["L","R"],1)[0], c=" "*((2*n)-(5+math.ceil((2*n-5)/2))), d="(@{}@)\n".format(" "*(2*n-3))*math.ceil((n-3)/2), e="(@{}@)\n".format(" "*(2*n-3))*(n-(3+(math.ceil((n-3)/2))))), a="({})\n".format("@"*(2*n-1))) ``` Interestingly, using the non-bitwise version of this still produces correct output, however, the output is different: Non-Bitwise: ``` (@@@@@@@) (@ @) (@ LF @) (@@@@@@@) ``` Bitwise: ``` (@@@@@@@) (@ LF @) (@ @) (@@@@@@@) ``` [Answer] # C# 448 bytes Golfed: ``` var v=n%2==0;int l=n+n-3,h=n-2,e=v?0:1,c=e+2;var c2=v?"MFZJLFRFCF":"MAFHMFJCJTTT";var r=new Random().Next(3+e);var f=new String(c2.Skip(c*r).Take(c).ToArray());var mc="";for (var i=0;i < h;i++) {var x="";if (!v && i==((h / 2))) { x=f;} else if (v && ((i==h / 2) || (i==(h/2)-1))) { x +=f[i%2==1?0:1];} var es=x.PadLeft((l/2)+1+e,' ').PadRight(l,' ');mc +="(@"+es+"@)\n";}var b="("+"".PadLeft(l+2, '@')+")";mc=b+"\n"+mc+ b; Console.WriteLine(mc); ``` Test it [here](http://rextester.com/EQOSI4698) Ungolfed: ``` var v = n % 2 == 0; int l = n + n - 3, h = n - 2, e = v ? 0 : 1, c = e + 2; var c2 = v ? "MFZJLFRFCF" : "MAFHMFJCJTTT"; var r = new Random().Next(3 + e); var f = new String(c2.Skip(c * r).Take(c).ToArray()); var mc = ""; for (var i = 0; i < h; i++) { var x = ""; if (!v && i == ((h / 2))) { x = f; } else if (v && ((i == h / 2) || (i == (h / 2) - 1))) { x += f[i % 2 == 1 ? 0 : 1]; } var emptySpace = x.PadLeft((l / 2) + 1 + e, ' ').PadRight(l, ' '); mc += "(@" + emptySpace + "@)\n"; } var b = "(" + "".PadLeft(l + 2, '@') + ")"; mc = b + "\n" + mc + b; Console.WriteLine(mc); ``` ]