text
stringlengths
180
608k
[Question] [ Draw this Ascii coffee cup: ``` o o o __________ / \__ | J | \ | A | | | V | | | A |__/ \__________/ ``` Brownie points for coffee-script or java :) Shortest code in bytes, function or program, trailing newline or white space is acceptable, drink up! [Answer] ## JavaScript (ES6), ~~110~~ 104 bytes *Saved 4 bytes thanks to edc65* ``` let f = _=>`1o 6o 3o 9 /44\\__ |2J5|1\\ |3A4|1| |4V3|1| |5A2|__/ \\9/`.replace(/\d/g,n=>' _'[n>>3].repeat(++n)) console.log(f()) ``` ### How it works The compression of the original ASCII art is achieved by replacing all sequences of 2 to 10 consecutive spaces and the two sequences of 10 consecutive underscores with a single digit: * Each sequence of `N` consecutive spaces is encoded with the digit `N-1`. * The underscore sequences are encoded with a `9`. We use `N-1` rather than `N` so that we never have to use more than one digit. Hence the need for `++n` when decoding. The expression `n>>3` (bitwise shift to the right) equals 0 for `n = 1` to `n = 7` and equals 1 for `n = 8` (not used) and `n = 9`. Therefore, `' _'[n>>3]` gives an underscore for `9`, and a space for all other encountered values. The only special case is the sequence of 10 consecutive spaces just above "JAVA". Encoding it with a `9` would conflict with the underscore sequences. So we need to split it into two sequences of 5 spaces, encoded as `44`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~67~~ 64 bytes -2 bytes thanks to Dennis (1. remove redundant `”`, and 2. replace transpose and run-length decode, `ZŒṙ`, with reduce by element repetition, `x/`.) ``` “Ñṁ{xGgṭḷVỤɲ8ṿfƬT9Ɱ¹=qṀS“$<(ƇỤ08ØÑḌṃṘX6~cuc8HṗḞ2’Dx/ị“ ¶_/\|JAVo ``` **[Try it online!](https://tio.run/nexus/jelly#AXUAiv//4oCcw5HhuYF7eEdn4bmt4bi3VuG7pMmyOOG5v2bGrFQ54rGuwrk9ceG5gFPigJwkPCjGh@G7pDA4w5jDkeG4jOG5g@G5mFg2fmN1YzhI4bmX4bieMuKAmURaxZLhuZnhu4vigJwgCl8vXHxKQVZv4oCd//8)** ### How? `“...“...’` is a list of two base-250 compressed numbers: ``` [1021021021332411532617161526181616261916162618163425334, 2117114111551155121131612111415121115141211161312111551] ``` `D` converts to decimal to yield two lists of digits: ``` [[1, 0, 2, 1, 0, 2, 1, 0, 2, 1, 3, 3, 2, 4, 1, 1, 5, 3, 2, 6, 1, 7, 1, 6, 1, 5, 2, 6, 1, 8, 1, 6, 1, 6, 2, 6, 1, 9, 1, 6, 1, 6, 2, 6, 1, 8, 1, 6, 3, 4, 2, 5, 3, 3, 4], [2, 1, 1, 7, 1, 1, 4, 1, 1, 1, 5, 5, 1, 1, 5, 5, 1, 2, 1, 1, 3, 1, 6, 1, 2, 1, 1, 1, 4, 1, 5, 1, 2, 1, 1, 1, 5, 1, 4, 1, 2, 1, 1, 1, 6, 1, 3, 1, 2, 1, 1, 1, 5, 5, 1]] ``` `x/` reduces by element repetition to give one list of digits (repeating the number from the first list by the corresponding value of the other): ``` [1, 1, 0, 2, 1, 1, 1, 1, 1, 1, 1, 0, 2, 1, 1, 1, 1, 0, 2, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 3, 3, 2, 6, 1, 1, 1, 7, 1, 1, 1, 1, 1, 1, 6, 1, 1, 5, 2, 6, 1, 1, 1, 1, 8, 1, 1, 1, 1, 1, 6, 1, 1, 6, 2, 6, 1, 1, 1, 1, 1, 9, 1, 1, 1, 1, 6, 1, 1, 6, 2, 6, 1, 1, 1, 1, 1, 1, 8, 1, 1, 1, 6, 3, 3, 4, 2, 5, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4] ``` `ị` instructs to index into the list of the right, one based and modularly (0 indexes into the rightmost item). The list on the right, `¶_/\|JAVo`, is simply the character used in the required order where the pilcrow, `¶`, is the same code-point as a linefeed. The closing partner of `“` is not required as this is the end of the program: ``` [' ', ' ', 'o', '\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'o', '\n', ' ', ' ', ' ', ' ', 'o', '\n', ' ', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '\n', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', '_', '_', '\n', '|', ' ', ' ', ' ', 'J', ' ', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', '\\', '\n', '|', ' ', ' ', ' ', ' ', 'A', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', '|', '\n', '|', ' ', ' ', ' ', ' ', ' ', 'V', ' ', ' ', ' ', ' ', '|', ' ', ' ', '|', '\n', '|', ' ', ' ', ' ', ' ', ' ', ' ', 'A', ' ', ' ', ' ', '|', '_', '_', '/', '\n', '\\', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '/'] ``` Jelly performs an implicit print of this list, which, since it contains characters, prints as if it were a string: ``` o o o __________ / \__ | J | \ | A | | | V | | | A |__/ \__________/ ``` [Answer] # CoffeeScript ES6, 214 180 bytes ``` r="replace";" 1o0n0 6o0n0 3o0n0 _9n0/0 9b0_1n0|0 2J0 5|0 1b0n0|0 3A 4|0 1|0n0|0 4V0 3|0 1|0n0|0 5A0 2|0_1/0n0b0_9/0"[r](/\d/g,(a,b,c)->c[b-1].repeat(a))[r](/n/g,"\n")[r](/b/g,"\\") ``` # CoffeeScript, 135 bytes with hardcoding ``` f=()->""" o o o __________ / \__ | J | \\ | A | | | V | | | A |__/ \__________/""" ``` [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), ~~136~~ ~~124~~ ~~123~~ 105 bytes ``` """2o 7o 4o $(($a='_'*10)) /55\__ |3J6|2\ |4A5|2| |5V4|2| |6A3|__/ \$a/"""-replace'(\d)','$(" "*$1)'|iex ``` [Try it online!](https://tio.run/nexus/powershell#@6@kpGSUz2Wez2WSz6WgoqGhkmirHq@uZWigqcmlb2oaEx/PVWPsZVZjFMNVY@JoWmNUw1VjGmYCps0cjWvi4/W5YlQS9YHm6BalFuQkJqeqa8SkaKrrqKtoKCkoaakYaqrXZKZW/P8PAA "PowerShell – TIO Nexus") *Thanks to @briantist for finding the shorter `-replace` method that I knew was there somewhere.* This takes the string with numbers in place of the requisite number of spaces. We then regex `-replace` the digits with a script expression `$(" "*$1)`. So, for example, the first line of the string will be `$(" "*2)o`, the second will be `$(" "*7)o` and so on. Because of the triple-quoting, this is left as a string on the pipeline. We dump that to `iex` (short for `Invoke-Expression` and similar to `eval`), which processes the script expressions and leaves the resulting multi-line string on the pipeline. Output is implicit. [Answer] # Python 2, ~~174~~ ~~172~~ ~~171~~ 167 bytes No hard-coding. No Base-64 encoding. No Regex. ``` k=' ' q='_'*10 print'\n'.join([k*i+'o'for i in 2,7,4]+[k+q]+['/'+k*10+'\\__']+['|'+k*s+'JAVA'[s-3]+k*(9-s)+'|'+' _'[s==6]*2+'\\||/'[s-3]for s in 3,4,5,6]+['\\'+q+'/']) ``` Saved 2 bytes by externalizing `'_'*10` and by exploiting Python's conversion of `True -> 1` and `False -> 0`. Saved 1 byte by removing unnecessary whitespace. Saved 4 bytes thanks to @TuukkaX! [Answer] ## [GNU sed](https://en.wikipedia.org/wiki/Sed), ~~113~~ 112 bytes ``` s:$: o@SS o@S o@ UU@/SSS \\__@|SJSS| \\@|S AS | |@|S VS | |@|SSAS|__/@\\UU/: s:S: :g y:@:\n: s:U:_____:g ``` Basic encoding, it stores 3 spaces as `S`, `\n` as `@` and 5 underlines as `U`. I'll keep trying combinations to find something shorter. [**Try it online!**](https://tio.run/nexus/sed#NYyhDoBADEM9X1GBP181LLYZaskkDgSK5P792AmWtHmvYuPhSuA2aVYF7tZUGpFpXbvUUVKITUBJn4xDP2tTz2wW4d64PFS9BM/lpTGuuThzHs8xPg) The trivial solution of printing the string directly is given below. It has 136 bytes, resulting in a compression of 18 %, using the encoding scheme above. ``` c\ o\ o\ o\ __________\ / \\__\ | J | \\\ | A | |\ | V | |\ | A |__/\ \\__________/ ``` [**Try it online!**](https://tio.run/nexus/sed#@58co6CQH8OlAAFQFoiKh4MYLn0FOIiJAQnUAFleEIEakBhERMERJlIDFVAIQxcAq6mJj9eP4QIZBQP6//8DAA) [Answer] # [Python 2](https://docs.python.org/2/), ~~128~~ 127 bytes -1 byte thanks to Rod (use multiplication of tuple `('_'*10,)` to avoid a declaration). ``` print''.join('0'<c<':'and' '*int(c)or c for c in'''2o 7o 4o %s / 9\__ |3J6|2\\ |4A5|2| |5V4|2| |6A3|__/ \%s/'''%(('_'*10,)*2)) ``` **[Try it online!](https://tio.run/nexus/python2#HYuxCsMgGAb3/ylc5FMpNTUmpSVL1j5AJ0GKpWAGLUnH/91tyHI3HNe@ay4/4LzUXBQ6TGnCHa/yhoDZk0q6riKJz8FcALhK10q@kpAbWXELMRL3j5FdCMR@Htgx8fD0h8e55xgtBbnZfZZKIcJcupM2TuvW/g)** *Note:* that double backslash *is* needed before the line feed. Everything between the `'''` and `'''` is a single string, the two `%s` are formatters which get replaced by the content of the trailing `%(...)` tuple, which in turn contains two copies of `'_'*10` via the tuple multiplication `(...)*2`. The `'_'*10` performs string multiplication to yield `'__________'`. The code traverses the characters, `c`, of that whole string using `for c in '''...` and creates a new string by joining (`join(...)`) *either* the number of spaces identified by `c`, `int(c)`, if `c` is a digit *or* `c` itself - being a digit is identified by `'0'<c<':'` to save over `c.isdigit()`. [Answer] # Java 8, 294 289 248 bytes Golfed: ``` ()->{String s="";for(char c:"\u026F\n\u076F\n\u046F\n __________\n/\u0A5C__\n|\u034A\u067C\u025C\n|\u0441\u057C\u027C\n|\u0556\u047C\u027C\n|\u0641\u037C__/\n\\__________/".toCharArray()){for(int i=0;i<c>>8;++i)s+=' ';s+=(char)(c&255);}return s;} ``` In the spirit of [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'"), this does not hard-code the string to output. Instead, it makes use of the fact that there are many cases of multiple spaces followed by a printable character. It encodes the number of spaces that precede a character in the high-order byte of the character, with the actual ASCII character in the low-order byte. Ungolfed: ``` import java.util.function.*; public class DrinkYourMorningCoffee { public static void main(String[] args) { System.out.println(f( () -> { String s = ""; for (char c : "\u026F\n\u076F\n\u046F\n __________\n/\u0A5C__\n|\u034A\u067C\u025C\n|\u0441\u057C\u027C\n|\u0556\u047C\u027C\n|\u0641\u037C__/\n\\__________/".toCharArray()) { for (int i = 0; i < c >> 8; ++i) { s += ' '; } s += (char) (c & 255); } return s; } )); } private static String f(Supplier<String> s) { return s.get(); } } ``` [Answer] # MATL, ~~87~~ ~~86~~ ~~83~~ ~~82~~ 78 bytes ``` [TIH][IAC]111Z?c'(ty!(OWM4J4gW{lm> >bw8ch|.FU2W"@\#2Dj!NQDeIMZ'F'_ /|\JAV'Za7e ``` This solution breaks the coffee into two pieces: the "bubbles" and the mug. To create the bubbles, we create a sparse matrix with 111 located at three locations and convert it to a character array ``` [TIH][IAC]111Z?c ``` For the mug component, we rely upon string compression ``` '(ty!(OWM4J4gW{lm> >bw8ch|.FU2W"@\#2Dj!NQDeIMZ'F'_ /|\JAV'Za7e ``` Both components are printed to the output and a newline is automatically placed between the components Try it at [**MATL Online**](https://matl.io/?code=%5BTIH%5D%5BIAC%5D111Z%3Fc%27%28ty%21%28OWM4J4gW%7Blm%3E+%3Ebw8ch%7C.FU2W%22%40%5C%232Dj%21NQDeIMZ%27F%27_+%2F%7C%5CJAV%27Za7e&inputs=&version=19.8.0) [Answer] # [SOGL](https://github.com/dzaima/SOGL), 48 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` mγmλ⁶…Jcēņ▒&↓¡℮štΥ{ιE‽▼⅛÷εγ╝Ξ∫$■⌡πθ&χF׀▼ΡQ7L↓F¶‘ ``` Explanation: SOGL has built-in string compression and one of the things it has is a char dictionary compression. Even better, it has a boxstring compression type where the only chars available are " /\|\_-\n". So the whole program is a string encased in "‘ (the " is implicit). The string I gave the compressor are (escaped): ``` " o\n o\n o\n ", "__________", "\n/ \\__\n| ", "J", " | \\\n| ", "A", " | |\n| ", "V", " | |\n| ", "A", " |__/\n\\", "__________", "/" ``` [Answer] # Befunge, ~~158~~ ~~105~~ 101 bytes ``` <v"XaXXXNYXNY77777'XXXXX2_TXQXX0XZTXDXX0X^TXXRX0X^TXXDX07]27777#"p29+55 :<_@#:,g2/+55,g2%+55 \JV/|_Ao ``` [Try it online!](http://befunge.tryitonline.net/#code=PHYiWGFYWFhOWVhOWTc3Nzc3J1hYWFhYMl9UWFFYWDBYWlRYRFhYMFheVFhYUlgwWF5UWFhEWDA3XTI3Nzc3IyJwMjkrNTUKOjxfQCM6LGcyLys1NSxnMiUrNTUKXEpWL3xfQW8&input=) The characters in the string are first encoded as indices into a lookup table of the ten possible values. The indices are then grouped into pairs, each pair being combined into a single number (i1 + i2\*10) in the range 0 to 99. By carefully choosing the order of the lookup table, we can guarantee that those values will always be valid ASCII characters which can be represented in a string literal. This is a breakdown of the code itself: ![Source code with execution paths highlighted](https://i.stack.imgur.com/nm8j5.png) ![*](https://i.stack.imgur.com/jmV4j.png) We start by initialising the last element of the lookup table with a newline character (ASCII 10). ![*](https://i.stack.imgur.com/z4eIY.png) We then use a string literal to push the encoded content onto the stack. ![*](https://i.stack.imgur.com/RFUim.png) Finally we loop over the values of the stack, decoding and outputting two characters at a time. ![*](https://i.stack.imgur.com/BX1CZ.png) The last line hold the lookup table: the 9th element is an implied space, and the 10th (newline) is set manually, as explained earlier. [Answer] # [Retina](https://github.com/m-ender/retina), 71 bytes Differently from [my other answer](https://codegolf.stackexchange.com/a/111344/62393), this one was written by hand. ``` 2o¶6o¶3o¶1=¶/55\__¶|3J6|2\¶|4A5|2|¶|5V4|2|¶|6A3|__/¶\=/ = 10$*_ \d $* ``` (there's a trailing space at the end) [Try it online!](https://tio.run/nexus/retina#@89llH9omxkQGwOxoe2hbfqmpjHx8Ye21Rh7mdUYxQAZJo6mNUY1QIZpmAmEYeZoXBMfr39oW4ytPpctl6GBilY8V0wKl4qWwv//AA "Retina – TIO Nexus") The principle is still having a "compressed" string from which the cup of coffee can be reconstructed by substitutions. Trying different substitutions it turned out that the only ones worth doing are: * `=` turns into `__________` (10 underscores) * any digit turns into that number of spaces [Answer] # Common Lisp, ~~125~~ ~~123~~ ~~122~~ ~~120~~ 114 bytes ``` (format t"~3@{~vto ~} ~10@{_~} /~11t\\__ | J~11t| \\ ~2@{|~5t~a~11t| | ~}|~7tA |__/ \\~10{_~}/"2 7 4'A" V"1) ``` I saved 6 bytes, using idea of just putting enters in string instead of `~&`s. Ideas for improvement welcomed. [Answer] # Python3, 206 bytes ``` print(' o\n'+7*' '+'o\n'+4*' '+'o\n'+' '+10*'_'+'\n'+'/'+10*' '+'\__\n'+'|'+3*' '+'J'+6*' '+'| \\\n'+'|'+4*' '+'A'+5*' '+'| |\n'+'|'+5*' '+'V'+4*' '+'| |\n'+'|'+6*' '+'A'+3*' '+'|__/\n'+'\\'+10*'_'+'/') ``` [Answer] # Pyth, 80 bytes ``` r" o 7 o 4 o 10_ /10 \__ |3 J6 | \\ |4 A5 | | |5 V4 | | |6 A3 |__/ \\10_/"9 ``` [Online interpreter available here.](http://pyth.herokuapp.com/?code=r%22++o%0A7+o%0A4+o%0A+10_%0A%2F10+%5C__%0A%7C3+J6+%7C++%5C%5C%0A%7C4+A5+%7C++%7C%0A%7C5+V4+%7C++%7C%0A%7C6+A3+%7C__%2F%0A%5C%5C10_%2F%229&debug=0) Simple run-length decoding. [Answer] # C - 179 Solution with extensive use of format string: ``` void f(){printf("%1$3c\n%1$8c\n%1$5c\n%2$11s\n/%3$13s\n|%4$4c%5$7c%6$3c\n|%7$5c%5$6c%5$3c\n|%8$6c%5$5c%5$3c\n|%7$7c%5$4c__/\n\\%2$s/\n",'o',"__________","\\__",74,'|',92,65,86);} ``` Here is a more readable version: ``` void f() { printf("%1$3c\n" "%1$8c\n" "%1$5c\n" "%2$11s\n" "/%3$13s\n" "|%4$4c%5$7c%6$3c\n" "|%7$5c%5$6c%5$3c\n" "|%8$6c%5$5c%5$3c\n" "|%7$7c%5$4c__/\n" "\\%2$s/\n" 'o',"__________","\\__",'J','|','\','A','V'); } ``` [Answer] # [Retina](https://github.com/m-ender/retina), 99 bytes This solution was generated automatically using [this](https://codegolf.stackexchange.com/a/108853/62393) script. ``` 0 0o¶ 1¶/32\__¶4 J24\¶|3A 34|¶| 3V34|¶|2A |__/¶\1/ 4 |   3   2   1 __________ 0 o¶ ``` (there are trailing spaces on many lines) This works by using numbers 1,2,3,4 in place of some character sequences that are repeated in the target string and then substituting them back. I know it could be golfed more by tweaking this code or completely changing approach, but since the kolmogorov meta-golf challenge had quite a disappointing outcome I wanted to try using my script on a real challenge. [Try it online!](https://tio.run/nexus/retina#PYyxDcAwCAR7pvgNbAMLuM0AqSwxQhZgLgZgMYckUq750xW/qaNfGRgZTXiZZSgO1pXhMiHqJZDzE54A3KxlrNFIyQESqgjid0oG2Q/1qs9/sfcN "Retina – TIO Nexus") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 96 bytes ``` "2o 7o 4o 0 /55\__ |3J6|2\ |4A5|2| |5V4|2| |6A3|__/ \0/"-replace'\d',{' '*"$_"+(,'_')["$_"]*10} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X8kon8s8n8skn0vBgEvf1DQmPp6rxtjLrMYohqvGxNG0xqiGq8Y0zARMmzka18TH63PFGOgr6RalFuQkJqeqx6So61SrK6hrKanEK2lr6KjHq2tGg9ixWoYGtf//AwA "PowerShell – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 62 bytes ``` ≔\||||α”{“‽!⭆hi¿ü” ×_¹⁰↓× ⁵¦ __↑/||\← __↓α←”|⁻⎚}”↑⁺α/M⁴¦²↘JAVA ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9R55SYGiA4t/FRw9zqRw1zHjXsVXy0ti0j89D@w3uAYgqHp8cf2vmoccOjtsmHpys8atx6aJlCfPyjton6NTUxj9omgDmTgfrbJgCV1zxq3P2ob1YtkAlU8qhx17mN@u/3rH3UuOXQskObHrXN8HIMc/z/HwA "Charcoal – Try It Online") # Pure `”~”` compression, 62 bytes ``` ”~∨]S⁶G⌈↖L⌈LTFJS‖j∕⍘c⊗l⁶D⍘2S∧⦃﹪�⎚º}ερKM✳AV³α;≕~FY|◧:¶d⮌rt;↶≕Xê ``` [Try it online!](https://tio.run/##FcpNCoJQGIXhPTVsFkQbCKJJA7FBhBBIwwolkFtYMzX6G2rYD4QlGJ8ENrc9nA18S7heJ4cXnqOPNFOfaIaUsE4LiMugCztliuAKOD7TTYVaphdTyBQzJbD8MYSHzU7HOjDUv626UYuIEC45i/mbY7svPvPy/beZrkx3HJNWr0jKJ9MBK4/zc4cpmyGImkU6xMM1p7U4qcL@L5ayAg "Charcoal – Try It Online") [Answer] ## Python 3.6 *(non-competing)* Here's my attempt at Huffman encoding. It's definitely golfable further if anyone wants to take up the idea. ``` from bitarray import bitarray as b a=b() a.frombytes(bytes.fromhex('ca7fca7e53b6db6db664ffc6d9ae1fd6335e2fad1af83d68d7e2e9b218db6db6db20')) print(''.join(a.decode({k:b(v)for k,v in zip(" _|\no/\\AJV","1 011 010 0011 00101 00100 00011 00010 00001 00000".split())}))) ``` The literal could be compressed further still by converting to base64 or other, and the Huffman tree could be optimized to yield a shorter bitarray still. [Answer] # GameMaker Language, 138 bytes ``` show_message(" o# o# o# __________#/ \__#| J | \#| A | |#| V | |#| A |__/#\__________/") ``` [Answer] # C, 141 Bytes ``` f(){printf(" o\n%7co\n o\n __________\n/%11c__\n| J%6c| \\\n| A | |\n|%6c | |\n|%7c |__/\n\\__________/",0,92,0,86,65);} ``` ### Usage ``` main(){f();} ``` ## Easy Solution, 148 Bytes: ``` w(){puts(" o\n o\n o\n __________\n/ \\__\n| J | \\\n| A | |\n| V | |\n| A |__/\n\\__________/");} ``` [Answer] # PHP, 116 bytes ``` for(;$c="1o 6o 3o 9 /44\\__ |2J5|1\\ |3A4|1| |4V3|1| |5A2|__/ \\9/"[$i++];)echo$c>0?str_repeat(" _"[$c>8],$c+1):$c; ``` This looks a lot like [Arnauld´s answer](https://codegolf.stackexchange.com/a/111154/55735) - and does pretty much the same. Run with `-r`. [Answer] # zsh, 86 bytes ``` printf "^_<8b>^H^@^@^@^@^@^B^CSPÈçR^@^A^P^CJÆÃ^A<97>¾^B^\Ä^@¹5@Ú^KÂ^E2cÀ|^EG^X¿^FÂW^HCæÃTÔÄÇësÅÀ^L^Fq^@<92>}ý^?{^@^@^@"|zcat ``` Explanation: that string is the gzip-compressed java cup ascii art. I use `printf`, because with `echo`, `zcat` prints a warning, and `echo -e` is one character longer. It doesn't work with `bash` or `sh`, because they think it's a binary file. Since you can't effectively paste that output from the browser, [here](https://0x0.st/JSy.sh)'s a usable file. [Answer] # Java 9 / JShell, 299 bytes ``` ()->{String s="";BigInteger b=new BigInteger("43ljxwxunmd9l9jcb3w0rylqzbs62sy1zk7gak5836c2lv5t36ej6682n2pyucm7gkm9bkfbn4ttn0gltbscvbttifvtdfetxorj6mmy3mt6r3",36);while(!b.equals(BigInteger.ZERO)){int x=b.intValue()&0x3ff;for(int i=0;i<x>>7;i++)s+=' ';s+=(char)(x&0x7f);b=b.shiftRight(10);}return s;} ``` Ungolfed: ``` () -> { String s = ""; BigInteger b = new BigInteger( "43ljxwxunmd9l9jcb3w0rylqzbs62sy1zk7gak5836c2lv5t36ej6682n2pyucm7gkm9bkfbn4ttn0gltbscvbttifvtdfetxorj6mmy3mt6r3", 36); while (!b.equals(BigInteger.ZERO)) { int x = b.intValue() & 0x3ff; for (int i = 0; i < x >> 7; i++) s+=' '; s += (char)(x&0x7f); b = b.shiftRight(10); } return s; } ``` Usage in JShell: ``` Supplier<String> golf = <lambda expression> System.out.println(golf.get()) ``` Encodes each character as ten bits consisting of a count of the number of spaces before the character in the high three bits following by the code point in the low seven bits. (Since there are only three bits for the count it can't represent more than seven consecutive spaces, and there are ten spaces at one point in the string. These are encoded as a count of six, followed by a space, and then a count of three followed by the next character.) Sadly, it loses to this trivial 140-byte Java solution: ``` ()->" o\n o\n o\n __________\n/ \\__\n| J | \\\n| A | |\n| V | |\n| A |__/\n\\__________/" ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 85 bytes ``` •1d'uì[_ÍpH»Ð]jŠ$ÿ{ɘß|ªpå±W¾Ö:ÞjÇ&@è$´Öàˆå]Á¢šBg¦ï&-ã¥ønØ7Ñà'?•9B8ÝJ"o _/\|JAV"‡15ô» ``` [Try it online!](https://tio.run/nexus/05ab1e#AYIAff//4oCiMWQndcOsW1/DjXBIwrvDkF1qxaAkw797w4nLnMOffMKqcMOlwrFXwr7DljrDnmrDhyZAw6gkwrTDlsOgy4bDpV3DgcKixaFCZ8Kmw68mLcOjwqXDuG7DmDfDkcOgJz/igKI5QjjDnUoibyBfL1x8SkFWIuKAoTE1w7TCu/// "05AB1E – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~67~~ 65 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 'oƵ®Sú»•BÇÉι!т³ÂSˆtTóV”PHAëdÀāåΘý”å.@=Ø₂)øUqrÖ½ñ*•“_ | \/AVJ“ÅвJ» ``` Pretty straight-forward approach which most likely has room for improvement. [Try it online.](https://tio.run/##AXQAi/9vc2FiaWX//ydvxrXCrlPDusK74oCiQsOHw4nOuSHRgsKzw4JTy4Z0VMOzVuKAnVBIQcOrZMOAxIHDpc6Yw73igJ3DpS5APcOY4oKCKcO4VXFyw5bCvcOxKuKAouKAnF8gfApcL0FWSuKAnMOF0LJKwrv//w) **Explanation:** ``` 'o '# Push an "o" Ƶ® # Push compressed integer 274 S # Convert it to a list of digits: [2,7,4] ú # Prepend that many leading spaces to the "o": [" o"," o"," o"] » # Join them by newlines: " o\n o\n o" •BÇÉι!т³ÂSˆtTóV”PHAëdÀāåΘý”å.@=Ø₂)øUqrÖ½ñ*• # Push compressed integer 21514733101393053622421734761651860518184887728386739717403046550918945532453802933506348033205129 “_ |\n\/AVJ“ # Push string "_ |\n\/AVJ" Åв # Convert the integer to base-"_ |\n\/AVJ" # (builtin for converting to base string-length, and index those into the string) J # Join the characters to a single string » # And join the two strings on the stack by a newline # (after which the result is output implicitly as result) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ƶ®` is `274` and `•BÇÉι!т³ÂSˆtTóV”PHAëdÀāåΘý”å.@=Ø₂)øUqrÖ½ñ*•` is `21514733101393053622421734761651860518184887728386739717403046550918945532453802933506348033205129`. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 108 bytes ``` `274`ƛI\o꘍,;_ð\_₀*+,\/₀꘍`\__`+,\|3꘍\J6꘍\|ðd\\Wṅ,\|4꘍\A5꘍`| `m++,\|5꘍\V4꘍`| `m++,\|6꘍\A3꘍`|__/`++,\\\_₀*\/++, ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60274%60%C6%9BI%5Co%EA%98%8D%2C%3B_%C3%B0%5C_%E2%82%80*%2B%2C%5C%2F%E2%82%80%EA%98%8D%60%5C__%60%2B%2C%5C%7C3%EA%98%8D%5CJ6%EA%98%8D%5C%7C%C3%B0d%5C%5CW%E1%B9%85%2C%5C%7C4%EA%98%8D%5CA5%EA%98%8D%60%7C%20%60m%2B%2B%2C%5C%7C5%EA%98%8D%5CV4%EA%98%8D%60%7C%20%60m%2B%2B%2C%5C%7C6%EA%98%8D%5CA3%EA%98%8D%60%7C__%2F%60%2B%2B%2C%5C%5C%5C_%E2%82%80*%5C%2F%2B%2B%2C&inputs=&header=&footer=) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 65 bytes ``` 'oƵ®Sú»•BÇÉι₆₅8á·ŸˆE©/LнDË9Ï0³†₃þC¤ā¸·Í¨z©´Kˆι₃BÄ•"_ /\|JAV"ÅвJ» ``` [Try it online!](https://tio.run/##AXgAh/9vc2FiaWX//ydvxrXCrlPDusK74oCiQsOHw4nOueKChuKChTjDocK3xbjLhkXCqS9M0L1Ew4s5w48wwrPigKDigoPDvkPCpMSBwrjCt8ONwqh6wqnCtEvLhs654oKDQsOE4oCiIl8gCi9cfEpBViLDhdCySsK7//8 "05AB1E – Try It Online") # Pure `Åв` compression (compressing the bubbles too), 67 bytes ``` •5m™ÔćtвÃÔηŒćõ»θpøàÄqŠZ₂rÓ¢γβÞĆ?úËÄÌUöÉн%Cñí₄‡±ÁkÆùi•"o _/\|JAV"Åв ``` [Try it online!](https://tio.run/##AX0Agv9vc2FiaWX//@KAojVt4oSiw5TEh3TQssODw5TOt8WSxIfDtcK7zrhww7jDoMOEccWgWuKCgnLDk8KizrPOssOexIY/w7rDi8OEw4xVw7bDidC9JUPDscOt4oKE4oChwrHDgWvDhsO5aeKAoiJvIApfL1x8SkFWIsOF0LL//w "05AB1E – Try It Online") Outputs as a list of characters. # `Λ` canvas, 109 bytes ``` 'oƵ®Sú»6…/||º4Λ12„\_`5׫º2Λ2„/|0Λ4„|_º2Λ4„/|º0Λ4„\ º6Λ4'|4Λ5'|0Λ4ð2Λ4„ _º6Λ2'\0Λ2ð6ΛT'_6Λ3…_ 4Λ4ð2Λ4'îáu3.Λ» ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fPf/Y1kPrgg/vOrTb7FHDMv2amkO7TM7NNjR61DAvJj7B9PD0Q6sP7TI6NxskoF9jcG62CZBREw8WMwGLHdoFFY1ROLTLDMhUrwGaYKoOVnx4A1SdQjxY0kg9BihsdHgDkB2iHg8kjYHWxisomMAVqx9ed3hhqbHeudmHdv//DwA "05AB1E – Try It Online") [Answer] # [Canvas](https://github.com/dzaima/Canvas), 59 bytes ``` ?Eα)⁶^↑^jo↕jα◂9S⁷YNU>AgX↷UE╬q\d7f²t}MøQ#║M<Y52dpc3I‰0C5G9-‟ ``` [Try it online!](https://dzaima.github.io/Canvas/?u=JXVGRjFGRSV1MDNCMSUyOSV1MjA3NiU1RSV1MjE5MSU1RWpvJXUyMTk1JXVGRjRBJXUwM0IxJXUyNUMyOSV1RkYzMyV1MjA3N1lOJXVGRjM1JTNFQSV1RkY0NyV1RkYzOCV1MjFCNyV1RkYzNSV1RkYyNSV1MjU2QyV1RkY1MSU1QyV1RkY0NDcldUZGNDYlQjIldUZGNTQlN0QldUZGMkQlRjgldUZGMzEldUZGMDMldTI1NTEldUZGMkQlM0NZNSV1RkYxMiV1RkY0NCV1RkY1MGMldUZGMTMldUZGMjkldTIwMzAldUZGMTAldUZGMjM1JXVGRjI3JXVGRjE5JXVGRjBEJXUyMDFG) ]
[Question] [ A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers). Given a number print whether it is happy or unhappy. ``` Sample Inputs 7 4 13 Sample Outputs Happy Unhappy Happy ``` Note: Your program should not take more than 10 secs for any number below 1,000,000,000. [Answer] ## Ruby, 77 characters ``` a=gets.to_i;a=eval"#{a}".gsub /./,'+\&**2'until a<5 puts a<2?:Happy: :Unhappy ``` [Answer] ## C - 115 ``` char b[1<<30];a;main(n){for(scanf("%d",&n);b[n]^=1;n=a)for (a=0;a+=n%10*(n%10),n/=10;);puts(n-1?"Unhappy":"Happy");} ``` This uses a 230-byte (1GB) array as a bitmap to keep track of which numbers have been encountered in the cycle. On Linux, this actually works, and efficiently so, provided [memory overcommitting](http://opsmonkey.blogspot.com/2007/01/linux-memory-overcommit.html) is enabled (which it usually is by default). With overcommitting, pages of the array are allocated and zeroed on demand. Note that compiling this program on Linux uses a gigabyte of RAM. [Answer] ## Golfscript - 34 chars ``` ~{0\`{48-.*+}/}9*1="UnhH"3/="appy" ``` Basically the same as [this](https://stackoverflow.com/questions/3543811/code-golf-happy-primes/3556849#3556849) and [these](http://golf.shinh.org/p.rb?happy%20number#GolfScript). The reason for 9 iterations is described in [these comments](https://stackoverflow.com/questions/3543811/code-golf-happy-primes/3544162#3544162) (this theoretically returns correct values up to about `10^10^10^974` ([A001273](http://oeis.org/A001273))). [Answer] ## Haskell - 77 ``` f 1="Happy" f 4="Unhappy" f n=f$sum[read[c]^2|c<-show n] main=interact$f.read ``` [Answer] ### Golfscript, 49 43 41 40 39 chars ``` ~{0\10base{.*+}/.4>}do(!"UnhH"3/="appy" ``` Every happy number converges to 1; every unhappy number converges to a cycle containing 4. Other than exploiting that fact, this is barely golfed at all. (Thanks to Ventero, from whose Ruby solution I've nicked a trick and saved 6 chars). [Answer] ## Python - 81 chars ``` n=input() while n>4:n=sum((ord(c)-48)**2for c in`n`) print("H","Unh")[n>1]+"appy" ``` Some inspiration taken from Ventero and Peter Taylor. [Answer] **eTeX, 153** ``` \let~\def~\E#1{\else{\fi\if1#1H\else Unh\fi appy}\end}~\r#1?{\ifnum#1<5 \E#1\fi~\s#1{0?}}~\s#1{+#1*#1\s}~~{\expandafter\r\the\numexpr}\message{~\noexpand ``` Called as `etex filename.tex 34*23 + 32/2 ?` (including the question mark at the end). Spaces in the expression don't matter. EDIT: I got down to **123**, but now the output is dvi (if compiled with `etex`) or pdf (if compiled with `pdfetex`). Since TeX is a typesetting language, I guess that's fair. ``` \def~{\expandafter\r\the\numexpr}\def\r#1?{\ifnum#1<5 \if1#1H\else Unh\fi appy\end\fi~\s#1{0?}}\def\s#1{+#1*#1\s}~\noexpand ``` [Answer] ## Javascript (~~94~~ ~~92~~ ~~87~~ 86) ``` do{n=0;for(i in a){n+=a[i]*a[i]|0}a=n+''}while(n>4);alert(['H','Unh'][n>1?1:0]+'appy') ``` Input is provided by setting a to the number desired. Credits to mellamokb. [Answer] ## Python (98, but too messed up not to share) ``` f=lambda n:eval({1:'"H"',4:'"Unh"'}.get(n,'f(sum(int(x)**2for x in`n`))')) print f(input())+"appy" ``` Way, way too long to be competitive, but perhaps good for a laugh. It does "lazy" evaluation in Python. Really quite similar to the Haskell entry now that I think about it, just without any of the charm. [Answer] ## dc - 47 chars ``` [Unh]?[[I~d*rd0<H+]dsHxd4<h]dshx72so1=oP[appy]p ``` Brief description: `I~`: Get the quotient and remainder when dividing by 10. `d*`: Square the remainder. `0<H`: If the quotient is greater than 0, repeat recursively. `+`: Sum the values when shrinking the recursive stack. `4<h`: Repeat the sum-of-squares bit while the value is greater than 4. [Answer] ## Befunge, 109 Returns correct values for 1<=n<=109-1. ``` v v < @,,,,,"Happy"< >"yppahnU",,,,,,,@ >&>:25*%:*\25*/:#^_$+++++++++:1-!#^_:4-!#^_10g11p ``` [Answer] # J, 56 ``` 'Happy'"_`('Unhappy'"_)`([:$:[:+/*:@:"."0@":)@.(1&<+4&<) ``` A verb rather than a standalone script since the question is ambiguous. Usage: ``` happy =: 'Happy'"_`('Unhappy'"_)`([:$:[:+/*:@:"."0@":)@.(1&<+4&<) happy =: 'Happy'"_`('Unhappy'"_)`([:$:[:+/*:@:"."0@":)@.(1&<+4&<) happy"0 (7 4 13) happy"0 (7 4 13) Happy Unhappy Happy ``` [Answer] ## Scala, 145 chars ``` def d(n:Int):Int=if(n<10)n*n else d(n%10)+d(n/10) def h(n:Int):Unit=n match{ case 1=>println("happy") case 4=>println("unhappy") case x=>h(d(x))} ``` [Answer] # J (50) ``` 'appy',~>('Unh';'H'){~=&1`$:@.(>&6)@(+/@:*:@:("."0)@":) ``` I'm sure a more competent J-er than I can make this even shorter. I'm a relative newb. New and improved: ``` ('Unhappy';'Happy'){~=&1`$:@.(>&6)@(+/@:*:@:("."0)@":) ``` Newer and even more improved, thanks to ɐɔıʇǝɥʇuʎs: ``` (Unhappy`Happy){~=&1`$:@.(>&6)@(+/@:*:@:("."0)@":) ``` [Answer] # Python (91 characters) ``` a=lambda b:b-1and(b-4and a(sum(int(c)**2for c in`b`))or"Unh")or"H";print a(input())+"appy" ``` [Answer] # Common Lisp 138 ``` (format t"~Aappy~%"(do((i(read)(loop for c across(prin1-to-string i)sum(let((y(digit-char-p c)))(* y y)))))((< i 5)(if(= i 1)"H""Unh")))) ``` More readable: ``` (format t "~Aappy~%" (do ((i (read) (loop for c across (prin1-to-string i) sum (let ((y (digit-char-p c))) (* y y))))) ((< i 5) (if (= i 1) "H" "Unh")))) ``` Would be shorter to just return "Happy" or "Unhappy" right from the `(do)`, but arguably that wouldn't count as a whole program [Answer] # K, 43 ``` {{$[4=d:+/a*a:"I"$'$x;unhappy;d]}/x;`happy} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` D²SµÐLỊị“¢*X“<@Ḥ» ``` **[Try it online!](https://tio.run/nexus/jelly#@@9yaFPwoa2HJ/g83N31cHf3o4Y5hxZpRQApG4eHO5Yc2v3//39LKDAFAA "Jelly – TIO Nexus")** ### How? ``` D²SµÐLỊị“¢*X“<@Ḥ» - Main link: n µÐL - loop while the accumulated unique set of results change: D - cast to a decimal list ² - square (vectorises) S - sum - (yields the ultimate result, e.g. n=89 yields 58 since it enters the - "unhappy circle" at 145, loops around to 58 which would yield 145.) Ị - insignificant? (abs(v)<=1 - in this case, 1 for 1, 0 otherwise) “¢*X“<@Ḥ» - dictionary lookup of ["Happy", "Unhappy"] (the central “ makes a list) ị - index into - implicit print ``` [Answer] # [Perl 5](https://www.perl.org/), 62 + 1 (`-p`) = 63 bytes ``` $_=eval s/./+$&**2/gr while$_>1&&!$k{$_}++;$_=un x($_>1).happy ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3ja1LDFHoVhfT19bRU1Ly0g/vUihPCMzJ1Ul3s5QTU1RJbtaJb5WW9saqLQ0T6FCAySuqZeRWFBQ@R8oqGerom@tmm2roWn934TL0JjL/F9@QUlmfl7xf11fUz0DQ4P/ugUA "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 'ŽØs[SnOD5‹#}≠i„unì}™ ``` [Try it online](https://tio.run/##ASsA1P9vc2FiaWX//yfFvcOYc1tTbk9ENeKAuSN94omgaeKAnnVuw6x94oSi//83) or [verify the first 100 test cases](https://tio.run/##ATsAxP9vc2FiaWX/0YJFTsOQVj8iIOKGkiAiP/8nxb3DmHNbU25PRDXigLkjfeKJoGnigJ51bsOsfeKEov8s/w). **Explanation:** Each number will eventually result in either `1` or `4`, so we loop indefinitely, and stop as soon as the number is below 5. ``` 'ŽØ '# Push string "happy" s # Swap to take the (implicit) input [ } # Loop indefinitely S # Convert the integer to a list of digits n # Square each O # Take the sum D5‹# # If this sum is smaller than 5: stop the infinite loop ≠i } # If the result after the loop is NOT 1: „unì # Prepend string "un" to string "happy" ™ # Convert the string to titlecase (and output implicitly) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `'ŽØ` is `"happy"`. [Answer] # [Python 2](https://docs.python.org/2/), 71 bytes ``` f=lambda n:n>4and f(sum(int(d)**2for d in`n`))or("H","Unh")[n>1]+"appy" ``` [Try it online!](https://tio.run/##FcyxCoMwFAXQuX7F4015NotWKAh17g90EsFICAbqTUjt4NfHuB9OPPY1oM3Zvb5mW6wh9Bg6A0tO/f6b8tiVlbpuXUhkyWPGLBKS4jdr/mBlGTE0051NjAfni/nCaHxq6jQ1j6mvbjGVp4xe8gk "Python 2 – Try It Online") ...or, for the same byte count: ``` f=lambda n:n>4and f(eval('**2+'.join(`n*10`)))or("H","Unh")[n>1]+"appy" ``` [Try it online!](https://tio.run/##DcxBCsIwEADAs75i2UuzaRBTC0LBnv2Ap1LoSg1dqZsQitDXR@cBk/ZtidqUEm4rf54zg3bat6wzBPP68moqa5u6Or2jqJnU@vNERDEbvKPDhy5Ig/Z@rJFT2rGEmEFAFIarg9aBv4zd8ZCy6PYfhcoP "Python 2 – Try It Online") [Answer] # Perl 5 - 77 Bytes ``` {$n=$_*$_ for split//,$u{$n}=$n;exit warn$/.'un'[$n==1].'happy'if$u{$n};redo} ``` $n is the input value [Answer] # C++ 135 , 2 Lines ``` #include<iostream> int n,i,j;int main(){for(std::cin>>n;n>1;n=++j&999?n*n+i:0)for(i=0;n/10;n/=10)i+=n%10*(n%10);std::cout<<(n?"H":"Unh")<<"appy";} ``` This is a modified version of the one I did here: <https://stackoverflow.com/questions/3543811/code-golf-happy-primes/3545056#3545056> [Answer] Yes, this challenge has three years; yes, it already has a winner answer; but since I was bored and done this for another challenge, thought I might put it up here. Surprise surprise, its long - and in... # Java - ~~280~~ 264 bytes ``` import java.util.*;class H{public static void main(String[]a){int n=Integer.parseInt(new Scanner(System.in).nextLine()),t;while((t=h(n))/10!=0)n=t;System.out.print(t==1?"":"");}static int h(int n){if(n/10==0)return n*n;else return(int)Math.pow(n%10,2)+h(n/10);}} ``` Ungolfed: ``` import java.util.*; class H { public static void main(String[] a) { int n = Integer.parseInt(new Scanner(System.in).nextLine()), t; while ((t = h(n)) / 10 != 0) { n = t; } System.out.print(t == 1 ? "" : ""); } static int h(int n) { if (n / 10 == 0) { return n * n; } else { return (int) Math.pow(n % 10, 2) + h(n / 10); } } } ``` [Answer] # C# 94 bytes ``` int d(int n)=>n<10?n*n:(d(n%10)+d(n/10));string h(int n)=>n==1?"happy":n==4?"unhappy":h(d(n)); ``` For any given number (as `int`), `h()` will return the correct value. You can try the code on [.NetFiddle](https://dotnetfiddle.net/piCL9v). Kudos to [user unknown](https://codegolf.stackexchange.com/users/373/user-unknown) for the original [algorithm](https://codegolf.stackexchange.com/a/2286/15214). [Answer] ## Clojure, ~~107~~ 97 bytes Update: Removed unnecessary `let` binding. ``` #(loop[v %](case v 1"Happy"4"Unhappy"(recur(apply +(for[i(for[c(str v)](-(int c)48))](* i i)))))) ``` Original: ``` #(loop[v %](let[r(apply +(for[i(for[c(str v)](-(int c)48))](* i i)))](case r 1"Happy"4"Unhappy"(recur r)))) ``` First time using a nested `for` :o [Answer] # R, ~~117~~ 91 bytes -16 bytes thanks to Giuseppe ``` a=scan();while(!a%in%c(1,4))a=sum((a%/%10^(0:nchar(a))%%10)^2);`if`(a-1,'unhappy','happy') ``` [Answer] # Julia 1.5 , 188 bytes (without indent) ``` f(s)=sum([parse(Int64,i)^2 for i in string(s)]) function g(s) a=[f(s)] while true;h=f(last(a)) if h in a println("unhappy") break elseif h==1 println("Happy") break end append!(a,h) end end ``` [Try it online!](https://tio.run/##XY5BDsIgEEXXzimwK0i6EG10hXvP0NRkVJBRpA3QqKdH2oUmLiaT@fPy8m@jI5SvnA2PQsXxwdsBQ9T84NO2qUkc18z0gREjz2IK5K8F7ASY0Z8T9Z5NN6BqJ0EHT0tOM7lfgVWGO4yJoxBAhtnJgDAURXKeV6O3OAzvSsApaLyDdlFPmFLyB/0h/gIlKGvJsbZiDsrkb8O2qXe13HSwuHKa//kD) ]
[Question] [ [Related](https://codegolf.stackexchange.com/questions/246025/average-ignorant-sets-of-integers). Given a list of 3 or more positive integers, remove every number X for which there is another number Y in the list and the average of X and Y is also in the list. In other words, if X, Y, and the average of X and Y are all in the input, neither X nor Y should appear in the output. Note: Pairs of numbers are not successively removed from the list, rather all at once. This avoids ambiguity. A pair of numbers whose average is in the list will be removed even if one or both of the numbers are already part of another such pair. The average of two numbers is their sum divided by two. Examples: ``` input => output explanation [1, 2, 3] => [2] 1 and 3 are removed because their average (2) is in the list. [1, 2, 3, 4] => [] 1 and 3 are removed because their average (2) is in the list, 2 and 4 are removed because their average (3) is in the list. [1, 3, 4, 5] => [4] 1 and 5 are removed because their average (3) is in the list, 3 and 5 are removed because their average (4) is in the list. [1, 5, 10, 20, 40] => [1, 5, 10, 20, 40] No numbers are removed; No pair of numbers also has their average in the list. [1, 5, 6, 10] => [1, 5, 6, 10] [1, 2, 3, 4, 10, 52, 100, 200] => [10, 52, 200] [1, 2, 3, 5, 8, 13, 21, 34] => [] ``` You may assume numbers are given in ascending order with no duplicates. [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") Shortest code wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 7 bytes ``` +HfḊʋÐḟ ``` [Try it online!](https://tio.run/##y0rNyan8/1/bI@3hjq5T3YcnPNwx///hdm/NyP//ow11FIx0FIxjdRRgTB0FEygPxNRRMIXyTHUUDA2ASoDYxAAhZgYSRtUOUWhqBKLBOlDlgZosgFJAlhHIEpNYAA "Jelly – Try It Online") ``` Ðḟ Remove elements for which + that element plus each element of the list H halved Ḋ has more than one element f ʋ after being filtered to only elements of the original list. ``` [Answer] # [J](http://jsoftware.com/), 27 22 15 14 bytes ``` -.&,~:/~*+:-/] ``` [Try it online!](https://tio.run/##XY5BCsIwFET3PcWg0FqbpEmaiKQUioIrceG@K2kRNx5AyNXrb9IKdfFJ8v7MZF7jRmQDGocMDBKOhguc79fLyEXKvCv9vnC87MY8uZ0ELT9t7et261PW9cIHAXdtUfqkfzzfGKBQwcAm8a3RBKZRRZBl4G5BMBHuFINlUJJB0xiZz6I/vFIfps1KGEjUKAmrySV/e81QUUaMs3o6Q@5sMHPRWH5ddTHTF0fy0U0Tq8z4BQ "J – Try It Online") Consider `1 3 4 5`. * `+:-/]` We note that if `c = (a + b)/2`, then `2c - a = b`. So we can double the input, and create a subtraction table between that doubled input and the original input: ``` 1 _1 _2 _3 5 3 2 1 7 5 4 3 9 7 6 5 ``` Now any element in that table not on the diagonal is the `a` or `b` giving rise to a `c` in the original list, and thus invalid. * `~:/~*` So zero out the diagonal: ``` 0 _1 _2 _3 5 0 2 1 7 5 0 3 9 7 6 0 ``` * `-.&,` Flatten, and then remove all the table elements from the original list: ``` 4 ``` [Answer] # [R](https://www.r-project.org), ~~48~~ 46 bytes ``` \(v)v[!v%in%combn(v,2)[,combn(v,2,mean)%in%v]] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY39WI0yjTLohXLVDPzVJPzc5PyNMp0jDSjdeBsndzUxDxNkHRZbCxU15c0jWQNQx0FIx0FY01NZQVbO4Voo1guJFEdBROYBFwcJKijYAoTN4FLmOooGBoA9QGxiQFMGl0cWbUZSAJVIVgI3QkQ_aZGIBpsEEITVBwohKYJaJYFUD2QZQRyM8IbEL8vWAChAQ) [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 17 bytes ``` {x^/x+(x-\:x)^'0} ``` [Try it online!](https://ngn.codeberg.page/k#eJx1kd1uwyAMhe95CkeREsiPDDSZJrZMfY+mVLnJM3jK0mevoWnSrJuEMJzPHIwZ3UQeqZRU946Uz/UsxOim6Qdx6NDZYnDMvpXXM7oTnS80R24+08EPPnDGOyal6WpMc98baQvVU61ylf5mZW/Taod2pFbRcmF0zExXIuZD17v8fim6lb2aRpQl+GoaogvnMkr+OcdVFl8en2tcnsa9ktcuJVXUoQBbbPJD4B5uogzC0tlVpZKVE33QObZ7/PMLwICFwyNCE1ccoY2rFowGq6HRy/aNhS070NbyHJI2vYV3MAew7NQ8JbPlsTICRWVFokXViN0Fq/3dNBgmYdwA8bGKRg==) Dang, [Jonah's solution](https://codegolf.stackexchange.com/a/248996/78410) translates very well to K. ``` {x^/x+(x-\:x)^'0} (x-\:x) self difference table ^'0 remove zeros from each row x+ add i-th item of x to i-th row of matrix above x^/ seeded reduce: remove all numbers that appear in the matrix from x ``` --- # [K (ngn/k)](https://codeberg.org/ngn/k), 22 bytes ``` {((*>^/^\+\2#,x-)')_x} ``` [Try it online!](https://ngn.codeberg.page/k#eJx1kF0OwiAMgN85RZclG8wtBRzGEGe8h4jhZWfATO8uxZ85jQmhpV/7NWG0E+fN3qN3K6fLNnaiFud4Y2y003RFDANa3QTLY3cRXt7QHuOJGoirXRl88MQTXjDO1dBhWXunuG6Ey+Lym807X2hBOpGVTxYPlRpWiHUYnK0fS9G+2a80o6rAXylFS3NVLP7M/f0XUKBh/YrQ5yxFMDkzoCRoCb18PjepMHcTNTrd1DTXDWxBrUEnU//RbBiyVrNCsrZnC/fb/PCRq6BzB9ykakw=) I think this idea is not touched well yet (or at least not explained well in other answers). The idea here is: given an element E of list X, E is to be removed from the result if: * there exists two other elements E2 and E3 of X such that E2 = (E + E3)/2 * ⇔ E, E2, E3 forms an arithmetic progression * ⇔ E2 = E + k, E3 = E + 2k for some nonzero k * ⇔ X-E (elementwise) contains k and 2k for some nonzero k ``` {((*>^/^\+\2#,x-)')_x} {(( )')_x} apply to each element E and keep those that gives 0 x- L = X-E +\2#, (L, 2L) ^/^\ set intersection of L and 2L *> first of grade down (index of max) all k's (including zero) are found in increasing order; index of max is nonzero iff there exist some nonzero k's ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ʒ+;Ãg ``` Byte-count halved thanks to *@Steffan* by porting [*@UnrelatedString*'s Jelly answer](https://codegolf.stackexchange.com/a/249019/52210). [Try it online](https://tio.run/##yy9OTMpM/f//1CRt68PN6f//RxvqKBjpKBjrKJjoKBga6CiYGoFoIMPIwCAWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLoZX/T006tM6lSNv6cHP6/1qd/9HRhjpGOsaxOhBaxwTMAtI6pmCWqY6hgY6RgY6JAZRrBhRAqAbJmhoCSZAihLipjoWOobGOEdAkk9hYAA). **Explanation:** ``` ʒ # Filter the (implicit) input-list by: + # Add the current value to each in the (implicit) input-list ; # Halve each à # Only keep those values from the (implicit) input-list g # Pop and push the length to get the amount of remaining values # (only 1 is truthy in 05AB1E) # (after which the filtered result is output implicitly) ``` [Answer] # [Haskell](https://www.haskell.org), 39 bytes ``` f a=[x|x<-a,[1]==[1|z<-a,elem(2*z-x)a]] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN9XTFBJtoytqKmx0E3WiDWNtbaMNa6pAnNSc1FwNI60q3QrNxNhYqPLO3MTMPAVbhZR8LgWFgqLMvBIFFYU0hWhDHWMdEx3TWHRRUx0zHUMDDGEFIx0FYx0FEx0FQwMdBVMjEA1kGBngVGqqo2ABVAVkGQHFjE2gDoL5AwA) ovs and Wheat Wizard each saved a byte. Thanks! [Answer] # JavaScript (ES6), 50 bytes ``` a=>a.filter(x=>!a.some(y=>x-y&&a.includes(y*2-x))) ``` [Try it online!](https://tio.run/##fY5BDsIgEEX3ngI3DRhKWizGDVzEuJi01NQgmFINnB5Bt7WLyUzyXv78O7zB9/P0XGrrBp1GmUAqYONkFj3jINUemHcPjaNUoY5VBWyyvXkN2uN44HUghKTeWe@MZsbd8IgvLUWcouOVkN06oahbh4VQJNahoKhtckCervmrnIq1@foXI3jZ37xNPUees5kvXgqW4ukD "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input a.filter(x => // for each value x in a[]: !a.some(y => // test whether there is a value y in a[]: x - y && // which is not equal to x a.includes( // and is the average of x and y * 2 - x // another value 2y - x that exists in a[] ) // ) // end of some() ) // end of filter() ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 20 bytes ``` {x^/a*~=#a:-x-\:2*x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6quiNNP1KqzVU600q3QjbEy0qqo5eJKUzBUMFIwhtEKJmAWkFYwBbNMFQwNFIwMFEwMoFwzoABCNUjW1AhIghQhxE0VLBQMjRWMgCaZAABf3xgV) Switched to @Jonah's approach. -1 byte thanks to @ovs! ## Explanation Input is *x*. * `a:-x-\:2*x` subtraction table of 2*x* - *x* stored as `a` * `a*~=#` multiply *a* by inverse of eye of *a* (i.e. zero out *a*'s diagonals) * `x^/` remove table elements from *x* [Answer] # [Scala](http://www.scala-lang.org/), 52 bytes ``` s=>s.filter(i=>s.forall(j=>i==j|s.forall(_*2!=i+j))) ``` [Try it online!](https://tio.run/##dZHBTsMwDIbvewpv2qEBD21di9BEKnHggDhMGuKEEMq2FKUKXWmyCQn27MVJuzLKuESO/8@/LdushBbVZpnJlYXHXOxkKV6lWGppQH5Yma8N3BQFfPZ6AGuZQjqDB/n@dJfbZ@DJUVwZnpiLVGkry0D5eFMKrYOMJ4rz7KtNvJyFfa7OM8ZYBbATmjqJt8K15M4woFYAgYsmGOIUY4Y@HzKGHe1/BaNG60gktIZRR4txMsZwjNG4AX6luuwlSUec/54YwxnEIb3Ohwq85FPu@7cgxiucTDGkUaOaZowY5i5AG6RT@AKVF1uLtLqCTifXDK5H7R49sdlaImilac06k31TXZQqtzqvNw2gUggOOP@xbFQAM5jfwwyG3gdGCQxretAQUht5BN8uFvPFKR76HIYH@7rYT9XbV98 "Scala – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~12~~ 10 bytes ``` f(εn¹Mo½+¹ ``` [Try it online!](https://tio.run/##yygtzv7/P03j3Na8Qzt98w/t1T608////9GGOkY6xjomOoYGOqZGQNJAx8jAIBYA "Husk – Try It Online") ``` f( ) # filter the input to keep only elements that satisfy: ½+ # half the sum Mo ¹ # with each other element of the input ε # has only 1 element n¹ # shared with any elements of the input ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~9~~ 7 bytes ``` '?+½?↔₃ ``` [Try it Online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCInPyvCvT/ihpTigoMiLCIiLCJbMSwgMiwgMywgNCwgMTAsIDUyLCAxMDAsIDIwMF0iXQ==) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJhUGoiLCJ2aMabwqMiLCInwqUrwr3CpeKGlOKCgyIsIjs7wqhad0o7Osabw7figbxg4p2M4pyFYGk7wqhaJMO3JF9cImAgPT4gYGpcXCBKcCIsIlsxLCAyLCAzXSwgWzJdXG5bMSwgMiwgMywgNF0sIFtdXG5bMSwgMywgNCwgNV0sIFs0XVxuWzEsIDUsIDEwLCAyMCwgNDBdLCBbMSwgNSwgMTAsIDIwLCA0MF1cblsxLCA1LCA2LCAxMF0sIFsxLCA1LCA2LCAxMF1cblsxLCAyLCAzLCA0LCAxMCwgNTIsIDEwMCwgMjAwXSwgWzEwLCA1MiwgMjAwXVxuWzEsIDIsIDMsIDUsIDgsIDEzLCAyMSwgMzRdLCBbXSJd). *-2 bytes by porting Unrelated String's Jelly answer* ## How? ``` '?+½?↔₃ ' # Filter for: ?+ # Add the input (vectorizes) ½ # Halve each ?↔ # Remove elements that are not in the input ₃ # Is the length equal to 1? ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 39 bytes ``` ->l{l-l.permutation(2).map{|a,b|a*2-b}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOkc3R68gtSi3tCSxJDM/T8NIUy83saC6JlEnqSZRy0g3qbb2f4FCWnS0oY6RjnFsLBeUo2Cko2Cso2Cio2BooKNgagSigQwjAwOgmv8A "Ruby – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/) ## 58 bytes with unordered sets *Thanx to [Jitse](https://codegolf.stackexchange.com/users/87681/jitse)!* ``` lambda l:{*l}-{a for a in l for b in{*l}-{a}if(a+b)/2in l} ``` [Try it online!](https://tio.run/##VY3RCsIgFIav6ynOpZbR5jRi0JMsL5SQBHNjeBPDZzfPMmIX4nfO9/@c6R2fY@iyvd2z1y/z0OD75eDTadFgxxk0uAB@RVOwquQs0UdDzxxtyqgjJoehZcAZdIrBDxmIOiEykHWSDNqmRMoTzX93wfW2/g1Kjv/a2PpSuhZViOMRoVS/302zC5FYEinNHw "Python 3 – Try It Online") ## ~~62~~ 61 bytes with ordered lists ``` lambda l:[a for a in l if{(a+b)/2in l for b in{*l}-{a}}=={0}] ``` [Try it online!](https://tio.run/##VY3NCsMgEITP7VPsUVtLjfmhBHwS60Ep0oBNQvBSxGe3bppSclh2Zr4ddn6H5zTW2cl79uZlHwZ8rwy4aQEDwwgeBheJOVt6FatFYguJJ58u0aQkZeRJZ8wDNpSqGAgGtWbwkwyazaFk0G6uZVDxclKm4f@sw3hf/x62Avfa2PNSuhVUlMAnjdb98TAvwxiII4HS/AE "Python 3 – Try It Online") [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 7 bytes (14 nibbles) ``` |$~<<`&*2@+@_ ``` ``` |$~<<`&*2@+@_ | # filter $ # input list ~ # keeping only elements that are falsy for << # discard first element of `& # common elements of *2@ # twice the input list # and +@_ # sum of this element and the input list ``` [![enter image description here](https://i.stack.imgur.com/D5Mig.png)](https://i.stack.imgur.com/D5Mig.png) --- Works on the basis that if the average of X and Y is Z, then X+Y=2\*Z. So we just remove all Xs whenever there's a Y that when added to it gives twice one of the other elements of the input. Step-by-step for input of `[1, 2, 3, 4, 10, 52, 100, 200]`: ``` |$ # for each element x in input=[1, 2, 3, 4, 10, 52, 100, 200] ~ # keep it if the following function returns an empty list (falsy): `& # find elements in common between: *2@ # double the input: [2, 4, 6, 8, 20, 104, 200, 400] # and: +@_ # input + x: # so, when x=1 => [2, 3, 4, 5, 11, 53, 101, 201] # common elements = [2, 4] # when x=10 => [11, 12, 13, 14, 20, 62, 110, 210] # common elements = [20] << # and remove the first element: # so, when x=1 => [4] => so won't keep it # when x=10 => [] => so we'll keep it ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒcSe¥ƇḤFḟ@ ``` A monadic Link that accepts a list of positive integers and yields the filtered list. **[Try it online!](https://tio.run/##y0rNyan8///opOTg1ENLj7U/3LHE7eGO@Q7///@PNtRRMNJRMNZRMNFRMDTQUTA1AtFAhpGBQSwA "Jelly – Try It Online")** ### How? ``` ŒcSe¥ƇḤFḟ@ - Link: list L Œc - ordered pairs (L) Ḥ - double (L) (vectorises) Ƈ - filter the pairs keeping those for which: ¥ - last two links as a dyad - f(pair, doubled L) S - sum (pair) e - exists in (doubled L)? F - flatten (this list of pairs whose sum is in the doubled L) @ - with swapped arguments: ḟ - filter discard (take L and remove the pair elements) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~12~~ 10 bytes ``` -Qs-L-LydQ ``` [Try it online!](https://tio.run/##K6gsyfj/XzewWNdH16cyJfD//2hDHQVjHQUTHQXTWAA "Pyth – Try It Online") or [Verify all test cases](https://tio.run/##K6gsyfiv/F83sFjXR9enMiUwUMHW9f//aEMdBSMdBeNYLhhLR8EEwgGxdBRMIRxTHQVDA6ACIDYxgAuZgURRtEKUmRqBaLB6FGmgFgugDJBlBLLAJBYA "Pyth – Try It Online") ``` -Qs-L-LydQ L (Q) # Left map over the implicit input with variable `d`: L Q # Left map over the input with variable `k`: - yd # d*2 - k - # Remove d from the resulting list s # Flatten -Q # Remove elements of the resulting list from the input ``` ### 12-byte solutions ``` fqFf}-yYTQQQ ``` ``` -Qsf}.OT-QT* ``` [Answer] # [Factor](https://factorcode.org) + `math.unicode`, ~~57~~ ~~51~~ 50 bytes ``` [| s | s [ s n+v 2 v/n s ∩ length 1 > ] reject ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XU-7bsJAEOz9FdNHEPvACAUpbURDE6VCFCezJkb22dydLfHq-QcaN0TKJ9Gm5CvYixvbK-1jZnd2tdefWEY21_X98fU5X3y8IZP2e1iqJMrXhEKTtftCJ8rC0K4kFZFBrPfNWEVOa7AhRVqmyUHaJFfmv4k0j2RqMPO8owe2IwIIjHDuoHELOxS2cIjAh_Ax9jvkxNH9LUyFgqMT9LshpghGEHzBnTvfShsPpnexPMHA-ZJdvVQ8XL0qrv8uv0hJbfiLAO9YQdOWX8WqUd4yWWDY1HXd5Cc) [Answer] # [Desmos](https://desmos.com/calculator), ~~80~~ 76 bytes ``` f(l)=l[[[(.5k-l)^2.minfork=l[m]+l[(L-m)^2>0]].minform=L]>0] L=[1...l.length] ``` This is probably a terrible way of doing it, but whatever. Also, the "words" `minfork` and `minform` that appear in the code are very much intentional, though you will quickly see what they actually parse as in the graph links :P. [Try It On Desmos!](https://www.desmos.com/calculator/xhboevghmj) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/hflewhjjth) [Answer] # [T-SQL] 111 bytes ``` DELETE FROM T WHERE EXISTS(Select*From T Y Join T Z ON T.ID NOT IN(Y.ID,Z.ID)And Y.ID<>Z.ID And T.N+Y.N=2*Z.ID) ``` Formatted: ``` DELETE FROM T WHERE EXISTS( Select * From T as Y Join T as Z ON T.ID NOT IN(Y.ID, Z.ID) And Y.ID <> Z.ID And T.N+Y.N = 2*Z.ID) ``` I *could* save one more byte by using the excremental SQL-89 joins, but my soul is worth more than one byte. [Answer] # [Arturo](https://arturo-lang.io), 41 bytes ``` $[a][a--map permutate.by:2a'p[-p\0*2p\1]] ``` [Try it](http://arturo-lang.io/playground?I0bU8I) Port of G B's [Ruby answer](https://codegolf.stackexchange.com/a/249099/97916). [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 14\log\_{256}(96)\approx \$ 11.52 bytes ``` gz0+2/z0sAqS2< ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhbr0qsMtI30qwyKHQuDjWwgglC5BWuiDXUUjHUUTHQUTGMhYgA) #### Explanation ``` g # Filter: z0+ # Add input 2/ # Halve each z0 # Push input again sAq # Each is in the input? S2< # Sum is less than 2? ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 16 bytes ``` ĐĐ2*⇹ɐ-ĐŁřĐɐ≠*Ƒ\ ``` [Try it online!](https://tio.run/##AS0A0v9weXT//8SQxJAyKuKHucmQLcSQxYHFmcSQyZDiiaAqxpFc//9bMSwyLDMsNF0 "Pyt – Try It Online") Port of [Jonah's J answer](https://codegolf.stackexchange.com/a/248996/116013) [Answer] # [Julia 1.0](http://julialang.org/), 32 bytes ``` !l=l[l.|>i->sum(i.+l.∈[2l])<2] ``` [Try it online!](https://tio.run/##ZY5RCsIwDED/d4rsr8M6XN3EDze8gCcY@wisQiVWaaf44QE8pxeZrXEwsFCavLykOd3IYPEYx5Rqail/NmbZ@NtZmHxB@fv1ahV12U514/HiwICx4DT2ZKz2IksgHJQaatB3JHHQA@ZXdF4Lk3H16owdyAqEuoEUGe7Re@2GkEMdWhNt@7EtJCgJ6y6KreqSCUgomTGKuYSKUcmsklCsgh1uueLKH53ETaRzh8H8O@6rVHy/Ayb/RyOY@WHGNqghUnG/adsP "Julia 1.0 – Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 68 bytes ``` ($a=$args)|?{$_-notin($a|%{$a-ne($c=$_)|%{$_,$c*(($_+$c)/2-in$a)}})} ``` [Try it online!](https://tio.run/##lU/RSsMwFH3vV1zGVRJNcKub@FIsFH3wRXF7Eyk1Zm6yNbPJVGj77TVJtyLbHmagNPece07OWalvWeiZXCy4UIVscBqVDcEswqx417S6KTHluTLz3ILVSYkZzyVBEWFK3ZgyFGeEYHqOgl6EfJ5jRuua1k0dBDEJwB4GMYnJgEHI4JK6KaR0n2Ew9OQu5wgGI88Nd8kRg0Hf6u037PuVPXBfceX4P8vtfDhSazUK3d97boQb0M0Hhdb22mrsLXQdumoUKrhTxW0mZvzh9UMKA6XXo5HaMED5s7KgfIMIMG2ZQur1wljgFKcQuz2PPz@Ok7U2atn6vMStkTvjtRBSa3@PgGwdKhirwmzfrSBR@ZcszETxe61y4IlaruyqpsDlp5V1WY4Wdgl6ExsTkkzLnmviQh/t0pk8tbE3Nf7bwtvUQd38Ag "PowerShell Core – Try It Online") [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 26 bytes ``` Js12CB:U_f{avg1j~[}g1jFL\\ ``` [Try it online!](https://tio.run/##SyotykktLixN/V@tZGunZG2tG1uUqFmS8t@r2NDI2ckqND6tOrEs3TCrLroWSLr5xMT8rw3P@R9tqKNgpKNgHKtga6cQbRTLBRPQUTCBiMUqgMVAAjoKphAxE4g6Ux0FQwOgciA2MYDIYIjCFJqBRJHVQASQ7YPoMzUC0WADYOqhoiABJPVAMyyASoEsI5D7YM4FAA "Burlesque – Try It Online") Takes input as block of doubles ``` J # Duplicate s1 # Store as 1 2CB # Combinations of length 2 :U_ # Filter for unique (guaranteed safe by no dups) f{avg1j~[} # Filter for average contained in original list (1) g1 # Get 1 j # Reorder stack FL # Flatten \\ # Remove elements contained in (1) also in averages ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` IΦθ¬⊙θ∧⁻κμ№⊗θ⁺ιλ ``` [Try it online!](https://tio.run/##LYvBCoMwEER/ZY8rbCGm9tSTWLy1eBcPqQoN3SYYk4Jfv0ZwLvN4w4wfE0ZvWKQL1kVszBqxtRzngAvBy0es3XZg7SZ8WpdW/BL8CoLGp3x4@PTmecIlm47zagm4OHMX6fuSQBNcCSqCUhHc9NEZtFLDIJc/7w "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input list Φ Filtered where θ Input list ¬⊙ No elements satisfy ⁻κμ Indices differ ∧ Logical And θ Input list ⊗ Doubled № Does not contain ⁺ιλ Sum of current elements I Cast to string Implicitly print ``` [Answer] # [Haskell](https://www.haskell.org), 67 bytes ``` f a=[z|z<-a,not$elem z[x|x<-a,y<-a,x/=y,even$x+y,div(x+y)2`elem`a]] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN53TFBJto6tqqmx0E3Xy8ktUUnNScxWqoitqKkAilSCiQt-2Uie1LDVPpUK7Uicls0wDSGsaJYCUJiTGxkKMgpoIMxkA) [Answer] # [Zsh](https://www.zsh.org/), 75 bytes ``` for x;for y;((s=x+y,s%2||x==y))||a+=(${=${(M)@:#$[s/2]}:+$x $y}) <<<${@:|a} ``` [Try it online!](https://tio.run/##bZDBbsIwEETv/oqpcNUEkAoBpAqIxKGH9tBjTxVSXLIBqyRGsQNJCd@e2gGKVPXitXbXM/P8rTdN4vlek6gc5cyd1czzdFj2qr6@D@q6DMPK9@ta9EKPH0N@9N78xbTDP/RjsDxNe7wEr04@m8/n/LiY1uLU@IwlGCLA@FJH13rp2IpJe5tgOEAwwHhwW3GtSWBPN7n1J3jCcITAPh8zRqU0jHXwrEhnDwYHlX/1IbIYZkPISWiV4bCpsFLFNsYnodCUFFs4xLXaJjJbT9l/1GloyW7sdX3HFx/eq8/T5e8/OGbf2b9QToh4GkFqULmzASiGtXYpuruc9lIVuou92BYElYCnNos1JMTKRmj3RC7NJiUjV2cJLVVmtd@1WziLZ9qQiJ1AtItazKi/C@3kL55MUKkCGdkYRkGLPbUe1yiQhnJhrEPzAw "Zsh – Try It Online") Not as compact as I was expecting... ``` for x;for y # for $x, $y in the Cartesian product of the list with itself ((s=x+y,s%2||x==y)) || # test if the sum is odd or x == y. If not, a+=(${=${(M)@:#$[s/2]}:+$x $y}) # ${(M)@:#$[s/2]} # substitute the average if found in $@ # ${ :+$x $y} # if non-empty, substitute "$x $y" # a+=(${= }) # split on spaces and add it to $a <<<${@:|a} # set difference ``` [Answer] # [Python](https://www.python.org) + NumPy, 50 bytes ``` lambda a:a[((a+[[a]]).T==a+a[:,1>0]).sum((0,1))<2] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY5BCsIwEEX3PcUsExxLkrZSivUU7mIWI1Is2DTEFuxZ3BRE8Urexth24-q9_z8Dc3-5oTu3dnxU5eHZd9U6_6gLNccTARWkGaOV1mQMj_dlSSvSBcqdCPHaN4wJlJxvlVku33XjWt-B7Rs3AF3BuqhqPdwAagtaosLE4ExMJwvEbLIMpUAlMBVThAxhgyCXpBAShPRXhEn9GESJvzmc5GEJpkKXpKaIwPnadqxi1sXkPQ3sxjmf_x3HmV8) Straightforward masking with a few tricks to shorten the required indexing operations without having to explicitly import numpy. #### How? Construct 3d table of *z,y,x* each running through the input list *a*. Each cell is True if *2z=y+x* and False otherwise. Fixing *x=a* count solutions *z,y*. If *a* is not part of an averaging pair there is only solution *z=a,y=a*, otherwise there are more. Use boolean indexing to filter *a* accordingly. `(a+[[a]]).T` is a shorter surrogate for `2*a[:,None,None]` and `a[:,1>0]` is shorter than the more natural `a[:,None]`. ]
[Question] [ This one comes from a real life problem. We solved it, of course, but it keeps feeling like it could have be done better, that it's too lengthy and roundabout solution. However none of my colleagues can think of a more succinct way of writing it. Hence I present it as code-golf. The goal is to convert a nonnegative integer into a string the same way Excel presents its column headers. Thus: ``` 0 -> A 1 -> B ... 25 -> Z 26 -> AA 27 -> AB ... 51 -> AZ 52 -> BA ... 16,383 -> XFD ``` It has to work **at least** up to 16,383, but beyond is acceptable too (no bonus points though). I'm looking forward most to the C# solution, but, as per traditions of code-golf, any real programming language is welcome. [Answer] ## Excel Formula:), 36 chars ``` =SUBSTITUTE(ADDRESS(1,A1,4),"1","") ``` Usage: ![enter image description here](https://i.stack.imgur.com/wvNSN.png) Sorry, couldn't resist ... [Answer] ## Perl, 17 characters ``` say[A..XFD]->[<>] ``` The `..` operator does the same thing as the magical auto-increment, but without the need for the temporary variable and loop. Unless `strict subs` is in scope, the barewords `A` and `XFD` are interpreted as strings. (*This answer was [suggested](https://codegolf.stackexchange.com/review/suggested-edits/1786) by an anonymous user as an edit to [an existing answer](https://codegolf.stackexchange.com/questions/3971/generate-excel-column-name-from-index/3979#3979). I felt it deserves to be a separate answer, and have made it one. Since it wouldn't be fair for me to gain rep from it, I've made it Community Wiki.*) [Answer] ## Haskell, 48 ``` f=(!!)(sequence=<<(tail$iterate(['A'..'Z']:)[])) ``` Less golfed: ``` f n = (concatMap sequence $ tail $ iterate (['A'..'Z'] :) []) !! n ``` ### Explanation Haskell's [`sequence`](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v%3asequence) combinator takes a list of actions and performs them, returning the result of each action in a list. For example: ``` sequence [getChar, getChar, getChar] ``` is equivalent to: ``` do a <- getChar b <- getChar c <- getChar return [a,b,c] ``` In Haskell, actions are treated like values, and are glued together using the `>>=` (bind) and `return` primitives. Any type can be an "action" if it implements these operators by having a [Monad](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#t%3aMonad) instance. Incidentally, the list type has a monad instance. For example: ``` do a <- [1,2,3] b <- [4,5,6] return (a,b) ``` This equals `[(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)]` . Notice how the list comprehension is strikingly similar: ``` [(a,b) | a <- [1,2,3], b <- [4,5,6]] ``` Because lists are a type of "action", we can use `sequence` with lists. The above can be expressed as: ``` sequence [[1,2,3],[4,5,6]] ``` Thus, `sequence` gives us combinations for free! Thus, to build the list: ``` ["A","B"..."Z","AA","AB"] ``` I just need to build lists to pass to `sequence` ``` [['A'..'Z'],['A'..'Z','A'..'Z'],...] ``` Then use [`concatMap`](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v%3aconcatMap) to both apply `sequence` to the lists, and concatenate the resulting lists. Coincidentally, `concatMap` is the `=<<` function for lists, so the list monad lets me shave a few characters here, too. [Answer] ## C, 53 characters It's like playing golf with a hammer... ``` char b[4],*p=b+3;f(i){i<0||(*--p=i%26+65,f(i/26-1));} ``` Normal version: ``` char b[4]; char *p = b+3; void f(int i) { if (i >= 0) { --p; *p = i%26 + 65; f(i/26-1); } } ``` And the usage is like that: ``` int main(int argc, char *argv[]) { f(atoi(argv[1])); printf("%s\n", p); return 0; } ``` [Answer] # Perl, 26 characters ``` $x='A';map$x++,1..<>;say$x ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~16~~ 14 bytes ``` {("A"..*)[$_]} ``` Works even beyond XFD. Thanks to infinite lists in Perl 6, this doesn't take forever (and a half) to execute. [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPu/WkPJUUlPT0szWiU@tva/NVdafpGCgY6CoY6CkSkQmwGxuY6CKZBvagQUNjO2MFbQtVNQqVCo5lIAguJEkEkaKhWa1ly1/wE "Perl 6 – Try It Online") [Answer] ### Ruby, 35 characters ``` e=->n{a=?A;n.times{a.next!};a} ``` Usage: ``` puts e[16383] # XFD ``` Note: There is also a shorter version (30 characters) using recursion. ``` e=->n{n<1??A:e[n-1].next} ``` But using this function you might have to increase the stack size for large numbers depending on your ruby interpreter. [Answer] # Groovy, 47 ``` m={it<0?'':m(((int)it/26)-1)+('A'..'Z')[it%26]} [0:'A',1:'B',25:'Z', 26:'AA', 27:'AB', 51:'AZ', 52:'BA', 16383:'XFD'].collect {k,v-> assert v == m(k);m(k) } ``` [Answer] # Python 45 ~~51~~ ``` f=lambda i:i>=0and f(i/26-1)+chr(65+i%26)or'' ``` [Answer] # PHP, 30 bytes ``` for($c=A;$argn--;)$c++;echo$c; ``` Run as pipe with `-nr' or [try it online](http://sandbox.onlinephpfunctions.com/code/c14b95165411e7e3da7e79e05f1c08c9dd82f0f8). [Answer] ## Excel (MS365), 32 bytes. ``` =TEXTBEFORE(ADDRESS(1,A1,4),"1") ``` [![enter image description here](https://i.stack.imgur.com/ghA8k.png)](https://i.stack.imgur.com/ghA8k.png) [Answer] ## Scala, 62 characters ``` def f(i:Int):String=if(i<0)""else f((i/26)-1)+(i%26+65).toChar ``` Usage: ``` println(f(16383)) ``` returns: ``` XFD ``` You can try this on [Simply scala](http://www.simplyscala.com/). Copy and paste the function and use `f(some integer)` to see the result. [Answer] # Excel VBA, 31 Bytes Anonymous VBE immediate window function that takes input from cell `[A1]` and outputs to the VBE immediate window ``` ?Replace([Address(1,A1,4)],1,"") ``` [Answer] # Java, 57 bytes (recursive) ``` String f(int n){return n<0?"":f(n/26-1)+(char)(n%26+65);} ``` [Try it online.](https://tio.run/##RY/BisJADIbvfYpQEGYYrLXFslhln2BPHtXDWNvduG0qM6kg0mev4zjgJZDk5/uSi77p@eX8P1WtthZ@NNIjArCsGSuYdmyQfqERSAwkH6bmwRDQJv2O43UjaJEV86VUovrTRgqaZYUqVrIcpzJymOtwah0m0G49nqFzBvHG7o9avmQAXFsWqSx90/TG63CbpSVutrmrSkm/C1EMUd8si/wr94Mx@pzuZe/wixVEu7vlukv6gZOrO4FbEqji9YFj5X6UgTJOTw) **Explanation:** ``` String f(int n){ // Recursive method with integer parameter and String return-type return n<0? // If `n` is negative: "" // Return an empty String : // Else: f(n/26-1) // Recursive call with `n` integer-divided by 26, minus 1 +(char)(n%26+65);} // And append `n%26+65` as character ``` --- # Java 10, 62 bytes (iterative) ``` n->{var r="";for(;n>=0;n=n/26-1)r=(char)(n%26+65)+r;return r;} ``` [Try it online.](https://tio.run/##ZZDBasMwDIbvfQoRGNiYZGnCwpjnvsF66XHbwUvTzl2qFFkJjJJnz5zEt10Ekn7@/5MudrDp5fgz1a31Ht6sw/sGwCE3dLJ1A/u5BTgwOTxDLcIGUOowHDeheLbsatgDgoEJ0919sARkkkSfOhIadybXaPCxqNKtJCPqb0tS4ENRqepJKtLUcE8IpMdJz463/qsNjtF46NwRroFKrATvn1auRNx4FvlCAjBnzWTOFLl2r6YMVSm57KLURenSbKvyufx3xRK2imevGHT49dxcs67n7BYQuEXhVPLywYnCLDxERp9x@gM) **Explanation:** ``` n->{ // Method with integer parameter and String return-type var r=""; // Result-String, starting empty for(;n>=0; // Loop as long as `n` is not negative n=n/26-1) // After every iteration: divide `n` by 26, and subtract 1 r=(char)(n%26+65)+r; // Prepend `n%26+65` as character to the result-String return r;} // Return the result-String ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 50 bytes ``` f=_=>_<0?'':f(_/26-1)+String.fromCharCode(_%26+65) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbe1i7exsBeXd0qTSNe38hM11BTO7ikKDMvXS@tKD/XOSOxyBmoVCNe1chM28xU839yfl5xfk6qXk5@ukaahqGm5n8A "JavaScript (Node.js) – Try It Online") Seeing that a lot of people started answering this I answered too. # Note : This is basically a rip off of @kevinCruijssen's answer in Java shortened thanks to this being JS. [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), 71 bytes ``` [range(1;4)as$l|[65+range(26)]|implode/""|combinations($l)]|map(add)[N] ``` Expects input in `N`. e.g. ``` def N:16383; ``` Expanded: ``` [ # create array with range(1;4) as $l # for each length 1,2,3 | [65+range(26)] # list of ordinal values A-Z | implode/"" # converted to list of strings ["A", "B", ...] | combinations($l) # generate combinations of length $l ] | map(add)[N] # return specified element as a string ``` [Try it online!](https://tio.run/##JcnRDoIgGEDhV2HmhS5YicFavoMvwLz4C2o4BBKoG549cnX5nTM/i1R3NF7QEVOGKceM4o73535AOxRViOgFJqlQxAr2oZpuOLUQapMFZ/t/orydsl68cVIdqirf3HLVFqJ2NjS12eYCvgEpWzFOpXyc/61CiE3GEG19ihtWeBOX4oYv "jq – Try It Online") [Answer] # VBA/VB6/VBScript (non-Excel), 73 bytes ``` Function s(i):While i:i=i-1:s=Chr(i Mod 26+65)&s:i=i\26:Wend:End Function ``` Calling `s(16383)` will return `XFC`. [Answer] # Javascript, 147 bytes I had a similar problem. This is the golf of the solution. Excel columns are [bijective base-26](https://en.wikipedia.org/wiki/Bijective_numeration#The_bijective_base-26_system). ``` n=>{f=Math.floor;m=Math.max;x=m(0,f((n-24)/676));y=m(0,f(n/26-x*26));return String.fromCharCode(...[x,y,n+1-x*676-y*26].filter(d=>d).map(d=>d+64))} ``` Expanded, except using 1-indices: ``` function getColName(colNum){ // example: 16384 => "XFD" let mostSig = Math.max(0, Math.floor((colNum - 26 - 1)/26**2)); let midSig = Math.max(0, Math.floor((colNum - mostSig*26**2 - 1)/26)); let leastSig = colNum - mostSig*26**2 - midSig*26; return String.fromCharCode(...[mostSig,midSig,leastSig].filter(d=>d).map(d=>d+64)); } ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 59 bytes ``` : f dup 0< if drop else 26 /mod 1- recurse 65 + emit then ; ``` [Try it online!](https://tio.run/##hczRCsIwDAXQ937FZa@yGgdOcfsZaVNX2GzJuu@vqc@CEEi4nNyQpCz9K7RV6wMB/sigGVEvSRm87oxhxHlLHpcewu4QjcYrTuAtFpSF35j0tzRH8AlRe/b8dIw1acdkCpzomIZuNDT4j92JvvSnM7aDtbarHw "Forth (gforth) – Try It Online") ## Explanation ``` dup 0< \ duplicate the top of the stack and check if negative if drop \ if negative, drop the top of the stack else \ otherwise 26 /mod \ divide by 26 and get the quotient and remainder 1- recurse \ subtract one from quotient and recurse on result 65 + emit \ add 65 to remainder and output ascii char then \ exit if statement ``` [Answer] # [R](https://www.r-project.org/), 65 bytes Recursive answer as are many previous answers. ``` function(n,u=LETTERS[n%%26+1])"if"(n<=25,u,paste0(g(n%/%26-1),u)) ``` [Try it online!](https://tio.run/##DcuxCoMwEIDhVxEhcEdPak4SO@jo1ql1Kx2KNHLLKWny/Gnm//9i2aeuhKxbkkNBKc/3ZV2Xx/OlxrC/2De2ElrQaWZHmc7PL3172EHNtfbOImXEEo4I0og2G/Rkqa7siUdylhyT9cNtQDyjaKpUKvgD "R – Try It Online") [Answer] # Powershell, 68 bytes ``` param($n)for(;$n-ge0;$n=($n-$r)/26-1){$s=[char](($r=$n%26)+65)+$s}$s ``` Alternative recursive version, 68 bytes: ``` filter g{if($_-ge0){(($_-($r=$_%26))/26-1|f)+[char]($r+65)}else{''}} ``` Test script: ``` $f = { param($n)for(;$n-ge0;$n=($n-$r)/26-1){$s=[char](($r=$n%26)+65)+$s}$s } filter g{if($_-ge0){(($_-($r=$_%26))/26-1|f)+[char]($r+65)}else{''}} @( ,(0 , "A") ,(1 , "B") ,(25 , "Z") ,(26 , "AA") ,(27 , "AB") ,(51 , "AZ") ,(52 , "BA") ,(676 , "ZA") ,(702 , "AAA") ,(16383 , "XFD") ) | % { $n, $expected = $_ $result = &$f $n # $result = $n|g # Alternative "$($result-eq$expected): $result" } ``` Output: ``` True: A True: B True: Z True: AA True: AB True: AZ True: BA True: ZA True: AAA True: XFD ``` Note: Powershell does not provide a `div` operator. [Answer] # [Ruby](https://www.ruby-lang.org/), 26 bytes ``` ->n{(?A..).take(n+1).last} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuha7dO3yqjXsHfX0NPVKErNTNfK0DTX1chKLS2ohClYVKLhFG5oZWxjHQgQWLIDQAA) [Answer] # Excel, 30 bytes ``` =@TEXTSPLIT(ADDRESS(1,A1,4),1) ``` [Answer] # Haskell, 48 I really thought that I would be able beat the other Haskell entry, but alas... ``` f(-1)="" f n=f(div n 26-1)++[toEnum$mod n 26+65] ``` I am certain it is possible to shave a couple of characters off this, but I haven't coded in Haskell for nearly a year, so I am quite rusty. It's not exactly what you would call elegant. [Answer] # [><>](https://esolangs.org/wiki/Fish), 29 bytes ``` !v:2d*%:"A"+@-2d*,1-:0(?! $<o ``` [Try it online!](https://tio.run/##S8sszvj/X7HMyihFS9VKyVFJ20EXyNQx1LUy0LBX5FKxyf///79umYKhmbGFMQA "><> – Try It Online") [Answer] # [Icon](https://github.com/gtownsend/icon), 58 bytes ``` procedure f(n);return(n<0&"")|f(n/26-1)||char(65+n%26);end ``` [Try it online!](https://tio.run/##Xc5BCoNADAXQfU8hQktCKdWRSQt6GRkjzsJYguJm7m6nu5rs/oOfJIZFjuOjS@BhUy5GEGyV100FpKtuZYkp29PRo8aUwtQrkL/L1RG2LMNfde6jAF6KPLvGlWGECs@5Ntl5C2ThZcDbHd7ZI9S8m2y/774 "Icon – Try It Online") [Answer] # [Factor](https://factorcode.org) + `successor`, 27 bytes ``` [ "A"[ successor ] repeat ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70sLTG5JL9owc3LocGefu5WCumpealFiTmZVYklmfl5xQoFRaklJZUFRZl5JQrFqYWlqXnJqcUKxaXJQKo4v0jBmourmksBCAwUwEBRQddOwREsYogk4gQWMTJFiERBRMyQdEG0GZkjCUH0mRoiCUE0mhohGQ61z0zH2MIYIhTh5sJVu7S0JE3XYne0gpKjUjSSm2MVilILUhNLFGIhKlblJhYoFJckJmfrQQQWLIDQAA) Yup, Factor has a vocab for this. [Answer] # C (GCC), 39 bytes ``` f(i){i>25&&f(i/26-1);putchar(65+i%26);} ``` [Try It Online!](https://tio.run/##jc7BCsIwDAbge58iDDZau2E32A5WfRH1UCqdOThHmV5Gn722ojiQDXPJT/IFootWa@8NRTbivqqzLMR11RQlk/190BdlaVNzTKuGSeexG@CqsKMxKNvqHCKBVciPw4mRkcC7zM3CiyHsQMjQtlCKEDhHBl/3qd4GbGiSnjeQ5IBM/pD4pZw9PHbJZOsIWQaGhm/EZLDE/nbz0Pkn) Explanation: ``` f(i) { // If i cannot be represented as a single letter i>25 && // Print the next letter f(i/26-1); // Print the current letter putchar(65+i%26); } ``` I thought using 0-based indexing was a little strange, so here's 1-based indexing in the same number of bytes: ``` f(i){i-->26&&f(i/26);putchar(65+i%26);} ``` [Try It Online!](https://tio.run/##jc69CsIwEADgPU9xFFoS02AtmMGoL6IOIZJ6g7GE6lL67DERxYK0eMv9fQdnRGNMCJYi61GIfS2LIjbLWjLV3jtz0Z7KNcc8DYaAroOrRkdToX1jSkgEFrF@HE6M9ATeYW8eXgxhBysV0zbmqlLAOTL4wk@0PmpLs/y8gawEZOqHpDfV5OHRZaPtQMg8sDR@U40Gc@xvNw0HEp4) ]
[Question] [ **Input:** A positive integer `n=p^q` where `p` and `q` are [prime](https://www.mathopenref.com/prime-number.html). **Output:** Output the result of `q^p` **Test cases (in, out):** ``` 4, 4 8, 9 25, 32 27, 27 49, 128 121, 2048 125, 243 343, 2187 1331, 177147 3125, 3125, 16807, 78125, 823543, 823543 161051, 48828125 19487171, 1977326743 ``` **Scoring:** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code in bytes win! Input and output maybe in any reasonable format suitable to your language. Related: [Recover the power from the prime power](https://codegolf.stackexchange.com/questions/167199/recover-the-power-from-the-prime-power) [Recover the prime from the prime power](https://codegolf.stackexchange.com/questions/167106/recover-the-prime-from-the-prime-power) [Answer] # [Python 2](https://docs.python.org/2/), 56 bytes ``` n=input() p=2 while n%p:p+=1 P=p**n-1 print(n**n/P%P)**p ``` [Try it online!](https://tio.run/##JYtbCoMwEEX/ZxVBEDSl1MmjiUJ@ugK3UCTUQI1DHWm7eqv04144HA59eZyz2t5jekaBXfzEoSiKLYeUaeWqBgoK/jaX1NEpIPSBpMxnBHqlzFXe4dKXfS0lbUdswIOyoByYFlDhPgvaaECtEfRBePWN2x8bi1Dd0kNwXFgM9yUugtMUxbxyDV5pe3St8Q4d/gA "Python 2 – Try It Online") We first find the prime \$p\$ for which \$n=p^q\$ by incrementing \$p\$ until we get a divisor on \$n\$. After that, we find the exponent \$q\$ with a mathematical trick first discovered by Sp3000 and used in [Perfect power logarithms](http://golf.shinh.org/p.rb?Perfect%20power%20logarithms) on Anarchy Golf. We note that $$ \frac{n-1}{p-1} = \frac{p^q-1}{p-1} = 1 + p + p^2 \dots+p^{q-2}+p^{q-1}$$ Working modulo \$p-1\$, we have \$p \equiv 1\$, so each of \$q\$ the summands on the right hand side equals 1, and so: $$ \frac{n-1}{p-1} \equiv q \space \bmod (p-1)$$ We'd now like to extract \$q\$. We'd like to get there by applying the modulus operator `%(p-1)` to the left hand side. But this requires that \$q<p-1\$, which is not guaranteed, or we'll get a different value of `q%(p-1)`. Fortunately, we can get around this with one more trick. We can replace \$n\$ with \$n^c\$ and \$p\$ with \$p^c\$ for some positive number \$c\$, and still have \$n^c=(p^c)^q\$. Since the exponent \$q\$ relating them is unchanged, we can extract it as above, but make it so that \$q<p^c-1\$. For this, \$c=n\$ more than suffices and is short for golfing, though it makes larger test cases time out. [Answer] # [Bash](https://www.gnu.org/software/bash/) + Linux utils, 17 ``` factor|dc -e?zr^p ``` * `factor` takes a number as input and factorizes it. The output is the input number, followed by a colon, followed by a spaced-separated list of all the prime factors. * This list is piped to `dc` which evaluates the following `e`xpression: + `?` reads the whole line as input. dc cannot parse the input number followed by the colon, so it ignores it. Then it parses all the space-separated prime factors and pushes them to the stack. + `z` takes the number of items on the stack (number of prime factors) and pushes that to the stack + `r` reverses the top two items on the stack + `^` exponentiates, giving the required answer + `p` prints it. [Try it online!](https://tio.run/##FYoxC8IwFAb371e8wVXoy0uaFAenbg7iJogQk0gEMZIKgvS/x3a44Y67@Sm3b348E9Xk445iQQq50OY0Hg9nmunS7j58Sp1joG3a/@r13WJ5pabhoAyUhR7AihcMRAtYhCGrce86C6fErLnnzizXoJ1ly/gD "Bash – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~8~~ 5 bytes -3 bytes thanks to @LuisMendo ``` &YFw^ ``` [Try it online!](https://tio.run/##y00syfn/Xy3SrTzu/38LAA "MATL – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` ÓOsfm ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8GT/4rTc//@NTAE "05AB1E – Try It Online") **Commented:** ``` # implicit input 25 Ó # prime factor exponents [0, 0, 2] O # sum 2 s # swap (with input) 25, 2 f # unique prime factors [5], 2 m # power [32] ``` [Answer] # [J](http://jsoftware.com/), 9 8 bytes ``` 2^~/@p:] ``` [Try it online!](https://tio.run/##VY69CsJAEIT7PMViEwMasz/J7gUCgmBlZa@NGMRGn8BXP3MXuYvFcjsfM7P39Ku6HGHooYQNNNBPs63hcD4dPV0/u/27v/iqKO63xwvWI0gFA0iSFqRLktqgmTLQAEhz3gWAZIkgYfQ0smSxiIQTYuGI0HIZMscsqqJkzL94eLO3syZ@Rm2Jjbidm@dt4cemje1iRn8ZdGKKOp92qkydTkn/BQ "J – Try It Online") * `2 p: ]` returns a list of primes and their exponents. * `^~/@` then swap the arguments and exponentiate [Answer] # [Python 2](https://docs.python.org/2/), 62 bytes ``` n=input() p=2 q=-1 while n%p:p+=1 while n:n/=p;q+=1 print q**p ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERDk6vA1oir0FbXkKs8IzMnVSFPtcCqQNsWzrXK07ctsC4EiRQUZeaVKBRqaRX8/29oZmhgaggA "Python 2 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/) `-lm`, 47 bytes ``` p;f(n){for(p=1;n%++p;);p=pow(log(n)/log(p),p);} ``` [Try it online!](https://tio.run/##dVLtaoMwFP3fp7gUCmojNh9tIln3Z@wp1jI6q05wMVRhsuKrz92ktttgE3JvPOd@nJski8ssG0eri8CE56I5BXZLtVksl1aH2m5t8x7UTYlk4pwNiQ31MFamg7dDZYJwdp4Bfg7o8rZ7Nk972CJwFgQUAbbGJQmIlABQRr1FjAvutpw7BLjH6EatMFQxvnYs3dDVmg4a@SSCrmmgbkwJqBE4i1@qzjclNBVKUukDo@QmJu9t3nf50ctxYlAAZxcxlDllK@Gs68SocqiUVKC/iJHKu6sYoRRzCHb5XwzWSKXkbCMFH3SUgFeTvR5OEZwuQua7/pHt@vQB13pO4Oc/nw965lNc2cBNUZlj3mPeSk/bO2irj7wpgut8YTIB0Q3RsFz66BAul3M9E4OVpkvy/F7/onOkb8f2V0CLAe6dfKP2hHgRzBdHiO8B7aLdGRzLEGgJzowlt9Dup4xhNoyfWVEfynaM67cv "C (gcc) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` ḋ⟨l^h⟩ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/w93dD@avyInLuPR/JX//0eb6ChY6CgYmQKxuY6CiaWOgqGRIYgAihibGANZxsZAvjFYwNDMwgCoysLI2BQsZWZoYApSbGliYW5obhj7PwoA "Brachylog – Try It Online") On the prime decomposition `ḋ` (like `[5, 5]`), length `l` `^` first element `h`. A nicer and more Brachylog-y solution, that is one byte longer: ``` ~^ṗᵐ↔≜^ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/3VxD3dOBzIetU151Dkn7v//aBMdBQsdBSNTIDbXUTCx1FEwNDIEEUARYxNjIMvYGMg3BgsYmlkYAFVZGBmbgqXMDA1MQYotTSzMDc0NY/9HAQA) Reverse `~^` to get two Numbers `[A,B]` so that `Input = A^B`, while both are prime `ṗᵐ`. Flip `↔` the list to `[B,A]`, actually find the numbers `≜` and output `B^A`. [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` k ÊpUg ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=awrKcFVn&input=MTMzMQ) ``` k\nÊpUg :Implicit input of integer U k :Prime factors \n :Reassign to U Ê :Length p :Raised to the power of Ug :First element of U ``` [Answer] # [R](https://www.r-project.org/), 37 bytes ``` log(n<-scan(),p<-(b=2:n)[!n%%b][1])^p ``` [Try it online!](https://tio.run/##K/r/Pyc/XSPPRrc4OTFPQ1OnwEZXI8nWyCpPM1oxT1U1KTbaMFYzruC/oZHhfwA "R – Try It Online") My best effort, sadly 1-byte longer than the [Xi'an's much-cleverer R answer](https://codegolf.stackexchange.com/questions/210437/prime-power-switch/210466#210466), but posting anyway in the competitive spirit. Uses the straightforward approach of finding the prime factor (`p<-(b=2:n)[!n%%b][1]`), then the exponent (`log(n,p)`) and finally raising the exponent to the power of the factor (`log(n,p)^p`). [Answer] # JavaScript (ES7), ~~47 46~~ 44 bytes Uses a recursive function that first looks for the smallest divisor \$k\ge2\$ of \$n\$ and then counts how many times \$n\$ can be divided by \$k\$. The result is raised to the power of \$k\$. ``` n=>(k=2,g=_=>n%k?n>1&&g(k++):1+g(n/=k))()**k ``` [Try it online!](https://tio.run/##bZHLbsIwEEX3fEU2IJsUknmEmVRy@BSEKETUyEGA@vtpUSJknHo3OsfXd@Tv/c/@fridr49V6L6O/cn1wTXGO/xo3c41Ye63oYHFojU@z@0n5K0JhfPWGrtc@v7QhXt3Oa4vXWtOhrPhWJsVRcazd6pvtE4oVjElTLHEGCXBXMcYUBMOCPH1kqdCFQtMCSemmIOmDYAIogYiwKlC4yPjin9TmrHRUl6C6NRQpOrZZDCGaRICZQWvT1DFf3KgZhUQGNvWIoQbYep/AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` n => ( // main function taking n k = 2, // start with k = 2 g = _ => // g is a recursive function ignoring its input n % k ? // if k is not a divisor of n: // this point of the code is reached during the first step // of the algorithm; but it's also reached on the last // iteration when n = 1, which is why ... n > 1 && // ... we test whether n is greater than 1 ... g(k++) // ... in which case we do a recursive call with k + 1 : // else (k has been found): 1 + // add 1 to the final result g(n /= k) // and do a recursive call with n / k )() // initial call to g ** k // raise the result to the power of k ``` [Answer] # [R](http://cran.r-project.org) ~~36~~ ~~28~~ ~~1~~ 36 bytes Using the fact that exactly `p` powers of `n` are factors of `n^p`: ``` sum(a<-!max(b<-2:scan())%%b)^b[a][1] ``` [Try it online!](https://tio.run/##K/r/v7g0VyPRRlcxN7FCI8lG18iqODkxT0NTU1U1STMuKToxNtow9r/FfwA "R – Try It Online") but using a function definition does better (by moving `function(m)` to the header part!) ``` f=function(m) sum(a<-!m%%(b<-2:m))^b[a][1] ``` [Try it online!](https://tio.run/##K/qfZptWmpdckpmfp5Gr@b@4NFcj0UZXMVdVVSPJRtfIKldTMy4pOjE22jD2f5pGmoZJnLGmJheIZQ5i/QcA "R – Try It Online") with the ultimate improvement in length (1 byte!) produced by defining everything as the function argument (in the header of Try It Online). ``` f=function(m,b=2:m,a=!m%%b,d=sum(a)^b[a][1]) d ``` but this is not keeping with the code golf spirit! [Answer] # [Haskell](https://www.haskell.org/), ~~42~~, 39 bytes ``` f x|r<-[2..x]=[z^w|z<-r,w<-r,w^z==x]!!0 ``` [Try it online!](https://tio.run/##PZBfC4IwFMXf@xQniFCY4f7UJrhe@hhm4INRZBIqOKXvbtcmvtz9zt2557I9ivZVVtXUlW13KdqyhUUWKAYVsg0QGIbEkzgySLGwZhDas0oYuDBecMHpJlarpCGhpFdSSVLcLINcSjJzrblaOvLvn@viOJmYNmmzdoyQxznFn2E@3eG@TRpl4nBwuc3GW/8d06hh/b/cRmtdvt3G07t41vS0T/OsO@woqqgqBNfAMQwhojMoCNZiwH5PPMzsQqzfMv0A "Haskell – Try It Online") * 3 bytes saved by @xnor [Answer] # [Ruby](https://www.ruby-lang.org/), 56 bytes ``` n=gets.to_i p=2 p+=1while n%p>0 w=p**n-1 p (n**n/w%w)**p ``` Port of xnor's Python 3 answer. [Try it online!](https://tio.run/##JY3NDoIwEITv@xR7IdEaleXH9kC9qGcfwfCzUSIpTQEbn76CXCbfTGYybqq@oe4bRo1Fcblfb8HoJ4/DYewfLVidgN1p8q@2YzSRPcfgtRXC7AksbsxMRx/5rRA2LGuAtTq6ibHpAZE/ZYf/B8dDPaeV4/INbJpAaUpAUlImIaUkX4VOKpYg1coU5wSZUsnifw) (headers and footers courtesy of ovs. :D) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` ǐ₌Lhe ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLGmyIsIseQ4oKMTGhlIiwiO1rGm2AgPT4gYGo74oGLIiwiWzQsIDgsIDI1LCAyNywgNDksIDEyMSwgMTI1LCAzNDMsIDEzMzEsIDMxMjUsIDE2ODA3LCA4MjM1NDMsIDE2MTA1MSwgMTk0ODcxNzFdIl0=) ## How? ``` ǐ₌Lhe ǐ # Prime factors with duplicates ₌ # Apply both of next two elements and push both results to the stack: L # Length h # First item e # Exponentiate these two (length ^ first item) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes ``` #2^#&@@@FactorInteger@#& ``` [Try it online!](https://tio.run/##FYqxCsIwEED3/kYg0wm9XNKkg3KT4CY4isIRUu3QCCGb2F@P7fCG93iL1HdapM5R2nRsyjyVZuazxPopl1zTKxVWul3LnOtdHU4Tq4deb1Hy@u0sBDAOjAc7AhrccECWAIkQaDccQu8hGHJ7HrB32zXa4NFj92t/ "Wolfram Language (Mathematica) – Try It Online") Returns `{q^p}`, a singleton list. ``` FactorInteger@# (* {{p,q}} *) #2^#&@@@ (* { q^p } *) ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 59 bytes ``` .+ * ~`(?=(__+?)\1*$)((?=(_+)(\3+)$)\4)+ _+¶$$.($.1*$($#2$* ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8F9Pm0uLqy5Bw95WIz5e214zxlBLRVMDzNXW1Igx1tZU0Ywx0dTmitc@tE1FRU9DRQ@oQkNF2UhF6/9/Ey4LLiNTLiNzLhNLLkMjQyA25TI2MeYyNDY25DIG8QzNLAzMAQ "Retina – Try It Online") Link includes faster test cases. Explanation: ``` .+ * ``` Convert the input to unary. ``` (?=(__+?)\1*$)((?=(_+)(\3+)$)\4)+ ``` First, find the smallest nontrivial factor, which will necessarily be `p`. Secondly, count the number of times `q` that `n` can be replaced with its largest proper factor. (The proper factor will be `n/p` on the first pass and eventually decrease to `1` which is left unmatched but this doesn't affect the result.) ``` _+¶$$.($.1*$($#2$* ``` Generate a Retina stage which takes `n` as input and calculates (in decimal) the result of multiplying `1` by `q` `p` times, thus calculating `q^p`. ``` ~` ``` Evaluate the resulting code, thus calculating the desired result. [Answer] # [Scala](http://www.scala-lang.org/), 63 bytes ``` n=>2 to n find(n%_<1)map{p=>import math._;pow(log(n)/log(p),p)} ``` [Try it online!](https://tio.run/##NVHbasMwDH33VwjTQQxeVl9aO9sSKOxlD2MfsI3ipm6bkdom8W6Ufntnt5sM1pF1jrCksTW9OfnVu20jPJnOgf2O1q1HWIQAB/RpetjcwqOLUDfwHGLn3cuD/1j19g3qk6sbDtGDg03n1oW7Wt4zsjfhEOqm2wc/RNibuCuXd8F/Fb3fFo7cZBcIDeR4whhLChJpChXiMwqCI64ocIVkRYFxjRhnKZ7KjBKBS4GEFAkwrRATImWZUkwqJM6EfCM219NURukcaC5mWXHxKcems6SSWvNznlVSK6ZyoUopwedKivSxcgx9Fwv86jApc09j3SCA8f@dAia5u3aX5gTJWjNaWAyD@SkcHciZnS3PcLAj1LApXBl9GiYptzZe4B8pDJ2LvStGPHFw3cAkKWhaRkiLset6MmCSmEeUzukX "Scala – Try It Online") Finds the first factor of `n`, which must be `p` because `n` is a prime power, then finds \$\log\_p(n)^p\$. Returns an `Option[Double]` that's a `Some[Double]` if the input is valid. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ÆFẎṪ*$ ``` [Try it online!](https://tio.run/##y0rNyan8//9wm9vDXX0Pd67SUvl/uP1R05rI//9NdBQsdBSMTIHYXEfBxFJHwdDIEEQARYxNjIEsY2Mg3xgsYGhmYQBUZWFkbAqWMjM0MAUptjSxMDc0NwQA "Jelly – Try It Online") # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ÆFẎ*@Ɲ ``` [Try it online!](https://tio.run/##y0rNyan8//9wm9vDXX1aDsfm/j/c/qhpTeT//yY6ChY6CkamQGyuo2BiqaNgaGQIIoAixibGQJaxMZBvDBYwNLMwAKqyMDI2BUuZGRqYghRbmliYG5obAgA "Jelly – Try It Online") # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ÆfL*ḢƊ ``` [Try it online!](https://tio.run/##y0rNyan8//9wW5qP1sMdi451/T/c/qhpTeT//yY6ChY6CkamQGyuo2BiqaNgaGQIIoAixibGQJaxMZBvDBYwNLMwAKqyMDI2BUuZGRqYghRbmliYG5obAgA "Jelly – Try It Online") A 5-byter feels possible... [Answer] # [J](http://jsoftware.com/), 8 bytes ``` 2^~/@p:] ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/jeLq9B0KrGL/K/g56SlwRVsB@UZqBVZcEL5hnL5DjR6SQI2emp4GiK8JFdCo1lNW1lTTK0RREW@oVghUovk/TcHQyJQLSFqaWJgbmhtWAAA "J – Try It Online") J has a built-in that gives the prime factorization of a given integer in prime-exponent form. Then it's just a matter of applying exponentiation in reverse (`^~`) between the two numbers. (Happens to be the same as [Jonah's answer](https://codegolf.stackexchange.com/a/210439/91267); somehow didn't notice before I submitted the answer...) --- Because it is also solvable using `f&.g` ("Under"; do action g, do action f, then undo action g), here are some interesting ones: ### 10 bytes ``` |.&.(2&p:) 2&p: Prime factorization into prime-exponent form |. Swap the prime and exponent &. Undo `2&p:`; evaluate the "prime" raised to "exponent" ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/a/TU9DSM1AqsNP8r@DnpKXBFW8XV6YMEuCB8wzh9hxo9JAGEDqiARrWesrKmml4hiop4Q7VCoBLN/2kKhkamXEDS0sTC3NDcsAIA "J – Try It Online") ### 10 bytes ``` ({.##)&.q: q: Prime factorization into plain list of primes {. Head (prime) # Copies of # Length (exponent) {.## Essentially swap the role of prime and exponent &. Undo `q:`; product of all "primes" ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/Nar1lJU11fQKrf4r@DnpKXBFW8XV6RupFVhxQfiGcfoONXpIAjV6anoaIL4mVABhBLKKeEO1QqASzf9pCoZGplxA0tLEwtzQ3LACAA "J – Try It Online") [Answer] # [Alice](https://github.com/m-ender/alice), 13 bytes ``` / \f~#oE/ i@ ``` [Try it online!](https://tio.run/##S8zJTE79/19fISatTjnfVZ9LIdPh/38jUzMA) **Explanation:** ``` / Switch to Ordinal mode i Push the input as a string \ Switch to Cardinal mode f Pop n, implicitly convert n to an integer, and push the prime factors of n as pairs of prime and exponent ~ Swap the top two elements of the stack # Skip the next command E Pop y, pop x. If y is non-negative, push x ^ y / Switch to Ordinal mode o Pop s, then output s as a string. ~ Swap the top two elements of the stack. \ Switch to Cardinal mode @ Terminate the program ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 85 bytes ``` : f dup 2 do dup i mod 0= if i leave then loop tuck swap s>f fln s>f fln f/ s>f f** ; ``` [Try it online!](https://tio.run/##RczNDkQwGIXhvas4awmjMkllhHsR7YcoX0Nx@fUXY/U@Z3OIJ9dGDZ3x/geCWixSKL7QYWCFpEBHh42uVg3X6hGG2cItdY95qyzmkkBm/Jc@N8MQuc@OV4pRT4FIxWspxVc@0@8 "Forth (gforth) – Try It Online") Works like [Noodle9's C answer](https://codegolf.stackexchange.com/a/210455/78410). Takes an integer and returns a floating-point number on the FP stack. ### How it works ``` : f ( n -- float ) dup 2 do \ loop from i = 2..n-1 dup i mod 0= if \ if n % i == 0 i leave \ ( n p ) we found p; leave the loop then \ end if loop \ end loop tuck swap \ ( p p n ) s>f fln s>f fln \ ( p F:ln(n) F:ln(p) ) f/ \ ( p F:q ) q = ln(n)/ln(p) s>f f** \ ( F:q**p ) ; ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~7~~ 6 bytes -1 byte thanks to @FryAmTheEggman ``` ^lPQhP ``` [Try it online!](https://tio.run/##FYo7DoAgEAX7dwx6DcvyvYA1XMDKAhMjJtp4eVcoppjJXO9TZSlzkfXIpWYRpWARYRxMgE0gQx0HtgxiJvAw8lEHRMNuZE/a9SvZGCjQ165nb@ct0/YD "Pyth – Try It Online") ## Explanation ``` ^lPQhP l # length of PQ # prime factors of input ^ # raised to power of hP # first element in prime factors of input ``` [Answer] # [Io](http://iolanguage.org/), ~~57~~ 55 bytes Fixed a bug kindly pointed out by @DominicvanEssen ``` method(i,p :=2;while(i%p>0,p=p+1);i log(p)floor pow(p)) ``` [Try it online!](https://tio.run/##FY5BCoMwFET3/xQfoZBQF/5ETazYI/QEbizVGojmoxaPn8aBgXnDLMaFOOGjwz4u4zGHj3A5J1btOTs/CnfjZ5Fzx3eSrUMfvoLl5EPYkMOZsoxZCRZUBcpA2QApSq5AlxpIawJ9EdW2MGCVrq66pqJKq6a0hgxluLN3h8j6NZO4DJwuACZNwuGwv37Le9wk8ubWw68g4x8 "Io – Try It Online") [Answer] **APL (NARS2000 0.5.14), 9 characters 8 characters (thanks to gurus in APL Orchard):** ``` (⍴*1∘↑)π ``` **How it works:** Take input 8 as example. `π` breaks down 8 into vector of prime factors `2 2 2`. The [fork](http://help.dyalog.com/17.0/Content/Language/Introduction/Trains.htm) `⍴*1∘↑` takes one element from `2 2 2` as exponent, applies this to length of vector `2 2 2` which is `3`, giving `3^2 = 9`. [Answer] # [Factor](https://factorcode.org/) + `math.primes.factors`, 34 bytes ``` [ factors dup length swap last ^ ] ``` [Try it online!](https://tio.run/##NY5NDoIwEIX3PcWcgFDKT9EDGDdujCujSVOLEKBgO8QY49lr08Is5s3ke28yjZA4GXc5H0@HHYwC22Q23ahs0gRiwarXorRUFnpltBqiqVm0xG7SFmajED8@pBH2hHwJ@MpD56FnRZQqkjoIzeiqkbKcxZ2xCNhGaMnTGOUZKzZbSdNivVDnvKIVJT/irrB9/VhmGJR@Ygv2LfwsLMIdbm70i0Uh@8T9AQ "Factor – Try It Online") [Answer] # [Desmos](https://desmos.com/calculator), ~~61~~ 10+38=48 bytes ``` l=log_m(n) \sum_{m=2}^{n-1}(sign(l-ceil(l))+1)l^m ``` [View it online](https://www.desmos.com/calculator/ym7ev8es6e) (note that large values may fail because Desmos doesn't handle large numbers well) I decided to revisit this because I felt like outgolfing myself, and I remember this having potential inefficiencies. I could only find one improvement, but it seemed substantial enough for the edit. Input is via the variable `n`, output via the second calculation. If taking input via a variable feels wrong, feel free to add two bytes for a `n=`. Not horribly efficiently golfed. About 70% of the code is just dedicated to finding one factor, and there's surely a more efficient way to factor numbers in Desmos, but I haven't found one yet, and Desmos is lacking in built-ins relating to factorization or prime numbers. Instead, we simply observe that since \$p\$ and \$q\$ are prime, then \$p\*p...\*p\$ must be the only factorization of \$n\$ which can be represented with integer values, because the list of \$p\$s cannot be split into any other even groups. Therefore, we can just interate through all integers \$m \in 2,3,...,n-1\$ and find the value satisfying \$log\_mn \in \mathbb{Z}\$ (the set of integers). We do this in the code using `sign(log_m(n)-ceil(log_m(n)))+1`, which gives us a nice 1 when integeral and 0 when not. We multiply by `log_m(n)^m` to give us our new value, and add up the results for all values 2 through n-1 to single out the answer. [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` §^←Lp ``` [Try it online!](https://tio.run/##yygtzv7//9DyuEdtE3wK/v//b2hsbAgA "Husk – Try It Online") ]
[Question] [ For an integer `n` that satisfies `n > 0`, write its value as a right-descending path based on its binary representation. # Rules * The first (most significant) set bit is always in the top-left corner. * When the next bit is set (a `1`), draw a character ("filled") on the next line in the same column as the previous character drawn. Try to use spaces ("empty") to fill, but any character will do as long as it's always the same. * When the next bit is unset (a `0`), draw a character ("filled") on the same line immediately to the the right of the previous character drawn. * Your code must support numbers with at least 20 significant bits. * Write a full program, a function, a lambda, etc. but no snippet. * No leading spaces (or "empty" char) / lines allowed * Any number of trailing spaces (or "empty" char) / lines allowed * Any kind of 1D input is accepted: number, string, array of booleans, etc. Keep the order of bits untouched though. * Any kind of visual 2D output is accepted: on stdout, a string (with any two distinct values representing "filled" and "empty"), you can even output a matrix if you want. A list of numbers seems hard to reconcile with the "no heading spaces" rule, but I'm open to it if you find a way to use it. Note: if you chose to print or return a string, the characters used must be ASCII characters in the codepoints range [32-126]. * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/16236) are banned. * This is codegolf so the shortest code wins. # Examples Input: 1 ``` * ``` Input: 2 ``` ** ``` Input: 3 ``` * * ``` Input: 4 ``` *** ``` Input: 5 ``` ** * ``` Input: 6 ``` * ** ``` Input: 7 ``` * * * ``` Input: 25 ``` * *** * ``` Input: 699050 ``` ** ** ** ** ** ** ** ** ** ** ``` Input: 1047552 ``` * * * * * * * * * *********** ``` Input: 525311 ``` ********** * * * * * * * * * * ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 14 bytes ``` J_iB^YsJ+'o-'&XG ``` Produces graphical output as a path starting at coordinates (0,0). Try it at [**MATL Online!**](https://matl.io/?code=J_iB%5EYsJ%2B%27o-%27%26XG&inputs=699050&version=20.8.1) Or see some offline examples below: * Input `7`: [![enter image description here](https://i.stack.imgur.com/4rHll.png)](https://i.stack.imgur.com/4rHll.png) Output: [![enter image description here](https://i.stack.imgur.com/KV0Ta.png)](https://i.stack.imgur.com/KV0Ta.png) * Input `699050`: [![enter image description here](https://i.stack.imgur.com/VUaYg.png)](https://i.stack.imgur.com/VUaYg.png) Output: [![enter image description here](https://i.stack.imgur.com/bfa5b.png)](https://i.stack.imgur.com/bfa5b.png) If you prefer, you can see the path as complex coordinates for **9 bytes**: ``` J_iB^YsJ+ ``` [**Try it online!**](https://tio.run/##y00syfn/3ys@0ykusthL@/9/cwA) ###Explanation ``` J_ % Push -1j (minus imaginary unit) i % Push input number B % Convert to binary. Gives an array of 0 and 1 digits ^ % Power, element-wise. A 0 digit gives 1, a 1 digit gives -1j Ys % Cumulative sum. Produces the path in the complex plane J+ % Add 1j, element-wise. This makes the complex path start at 0 'o-' % Push this string, which defines plot makers &XG % Plot ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ¬¨≈ì·πó+\·π¨z0 ``` A monadic link accepting a number as a list of ones and zeros (e.g. `13` is `[1,1,0,1]`) returning a list of lists of ones and zeros where the first list is the first row. **[Try it online!](https://tio.run/##y0rNyan8///QmqOTH@6crh3zcOeaKoP///9HG@ooAJEBEoJwDWMB "Jelly ‚Äì Try It Online")** or see a formatted [test-suite](https://tio.run/##y0rNyan8///QmqOTH@6crh3zcOeaKoP/R/c4HW5XedS0JhKIgSgLRDXuszq0LQtIHdp2aNv//4Y6RjrGOiY6pjpmOuY6RkDK0tLA1EDH0MDE3NTUSMfUyNTY0BAA "Jelly ‚Äì Try It Online") ### How? ``` ¬¨≈ì·πó+\·π¨z0 - Link: list L e.g. [1,1,0,0,1,1,0,1] (i.e. 205) ¬¨ - logical NOT L [0,0,1,1,0,0,1,0] \ - cumulative reduce L by: + - addition [1,2,2,2,3,4,4,5] ≈ì·πó - partition @ truthy indices [[1,2],[2],[2,3,4],[4,5]] ·π¨ - un-truth (vectorises) [[1,1],[0,1],[0,1,1,1],[0,0,0,1,1]] z0 - transpose with filler 0 [[1,0,0,0],[1,1,1,0],[0,0,1,0],[0,0,1,1],[0,0,0,1]] - i.e. 1000 1110 0010 0011 0001 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` YsG~YsQ1Z? ``` Inputs an array of binary digits. Outputs a matrix. [Try it online!](https://tio.run/##y00syfn/P7LYvS6yONAwyv7//2hDBUMFAyA0jAUA "MATL ‚Äì Try It Online") ### Explanation ``` Ys % Implicit input: array of binary digits. Cumulative sum. This gives the % row coordinates G % Push input again ~ % Negate: change 0 to 1 and 1 to 0 Ys % Cumulative sum Q % Add 1. This gives the column coordinates 1Z? % Matrix containing 1 at those row and column coordinates and 0 otherwise. % Implicit display ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ ~~17~~ 14 bytes ``` Œ≥‚Ǩgƒá¬∏s>¬´1I√î¬∑√åŒõ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3OZHTWvSj7Qf2lFsd2i1oefhKYe2H@45N/v//2hDHQUgMgAjw1gA "05AB1E ‚Äì Try It Online") **Explanation** ``` Œ≥‚Ǩg # Push the input as the array as chuncks of consecutive elements, map with length ƒá¬∏s>¬´ # Increment each value except the first one 1I # Push 1 and the input √î # Push connected uniquified input (first elements of each chunck of consecutive elements in the input) ¬∑√å # Map each with 2 * a + 2 Œõ # Draw canvas :-) ``` * 3 bytes thanks to @Emigna [05AB1E canvas's explanation](https://codegolf.stackexchange.com/a/160031/76822) [Answer] # [Python 2](https://docs.python.org/2/), ~~100~~ ~~99~~ ~~81~~ ~~78~~ ~~73~~ 66 bytes ``` a='';x=0 for c in input():a+=('\n'+' '*x)*c+'*';x+=1-c print a[1:] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9FWXd26wtaAKy2/SCFZITMPiApKSzQ0rRK1bTXUY/LUtdUV1LUqNLWStdW1gEq1bQ11k7kKijLzShQSow2tYv//jzbUUTDQUSCHjAUA "Python 2 ‚Äì Try It Online") Recursive version: # [Python 2](https://docs.python.org/2/), ~~71~~ ~~69~~ 67 bytes ``` f=lambda n,x=0:n and('\n'[:x]+' '*x)*n[0]+'*'+f(n[1:],x+1-n[0])or'' ``` [Try it online!](https://tio.run/##VclBCoMwEEDRvaeY3WQ0haitxYAnSV0kaKigo6QppKdP7bK7z/vHJz53bnL2w2o3N1lgmQalGSxPAh@MRqexQsAyUclGnV1i5QWbWo8yVfXlh7QHxDzNHpxg0gWEOb4Dw7q8otjsIRaO0i18TtPokagojnAaeOFE1/fqpv6tvd67lih/AQ "Python 2 ‚Äì Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~22~~ ~~20~~ ~~19~~ ~~11~~ 10 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page) ``` Ôº¶‚ÆåÔº≥¬øÔº©Œπ‚Üë*‚Üê* ``` Only my second Charcoal answer thus far. Takes the input as binary-String (i.e. `699050` as `10101010101010101010`). -9 bytes thanks to *@Neil* suggesting to loop backwards. [Try it online.](https://tio.run/##S85ILErOT8z5/98tv0gjKLUstag4VcMzr6C0JLikKDMvXUNTU5NLQcEzTcM5sbhEI1NTUyEAKF6iYRVaoKOkpaRpreCaU5wKE/RJTSuBCP//b2iACf/rluUAAA) **Explanation:** Read STDIN as string in reversed order: ``` Reverse(InputString()) ‚ÆåÔº≥ ``` Loop over its binary digits as strings `Œπ`: ``` For(Reverse(InputString())) Ôº¶‚ÆåÔº≥ ``` If `Œπ` casted back to a number is 1, print the `*` upwards, else print the `*` towards the left. ``` If(Cast(i)) Print(:Up,"*"); Else Print(:Left,"*"); ¬øÔº©Œπ‚Üë*‚Üê* ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~155~~ ~~123~~ ~~120~~ ~~113~~ 101 bytes Saved 32 bytes due to input being able to be received as an array of bits. Saved 7 bytes thanks to @auhmaan. Saved 10 bytes thanks to @KevinCruijssen. ``` n=>{var m="";for(int i=0,c=1;i<n.Length;)m+=n[i++]<1?c++%1+"":(i>1?"\n":"")+"0".PadLeft(c);return m;} ``` [Try it online!](https://tio.run/##RZBNawIxEIbP7q8YAoWE2GW30ILGrJRCTxYECx62HmLMbgNuQidZQcTfvo0ftMcZnvdjRodH7dEMfbCuhdUxRNPlC@t@RJbpvQoBluhbVB2cslGIKloNB2938KGsoyFiktUbUNgGlpDs7vDeOz2zLtabMdygChqQg5PV6aAQOkmIaDzSxICVxVjLUtiZyxfGtfFbsI5LV1vON7Nyrjl/KDkhU2qrck6@HJkSwjgpSL5Uu4VpItVMoIk9OujEeUjdL76u77YGQcLLZFI8FyK7FoKtjSEt703fvDsYjPmnX1170ptqDE8sX5m90clcVkmZsjAYqv9JxlgaXhHVkTLxd3tyDH5v8jXaaNIrDW3oJZNdmNE5Ow@/ "C# (.NET Core) ‚Äì Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 65 bytes ``` f(a:b)|a="*":f b|(x:y)<-f b=('*':x):map(' ':)y f[]=["*"] f.tail ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00j0SpJsybRVklLySpNIalGo8KqUtNGF8i01VDXUreq0LTKTSzQUFdQt9Ks5EqLjrWNBiqN5Uq3TdMrSczM@Z@bmJlnW1BaElxSpFKal5OZl1qskh4dUlSaquOWmFOcqgNmIgiwYOx/AA "Haskell ‚Äì Try It Online") Takes input as a list of booleans. # Curry PAKCS, 70 bytes ``` u(a:b)=('*':a):map(' ':)b f(a:b)|a="*":f b|1>0=u$f b f[]=["*"] f .tail ``` Port of the Haskell answer, but because `<-` doesn't work in Curry we need to make a helper function `u`. We also need to add a space between `f` and `.` so that Curry parses it as a compose rather than a dot. This also works in MCC Curry, but doesn't work in Sloth Curry (which is the only one supported by TIO). [Answer] # [Python 2](https://docs.python.org/2/), 59 bytes ``` s=p='\n' for x in input():s+=p*x+'*';p+=' '[x:] print s[2:] ``` [Try it online!](https://tio.run/##PcZBCoAgEEDRfaeY3ZS2UJeGJzG3kRsd1MBOP0lQ8Ph8utuZk2GujhzuCacjF@gQ00BXmxdbpSPRJQrcSDoE9N2GiUpMDao3NjB7vcKg3v6jPjo8 "Python 2 ‚Äì Try It Online") Based off [TFeld's solution](https://codegolf.stackexchange.com/a/161449/20260). [Answer] # [Haskell](https://www.haskell.org/), ~~74~~ ~~70~~ ~~67~~ 62 bytes ``` tail.("\n"%) s%(x:r)=([1..x]>>s)++'*':(s++[' '|x<1])%r s%[]="" ``` [Try it online!](https://tio.run/##FY4xC8IwFIT3/opHoCQxGGzdiuniqlBwEdIM0WoNprE0VTr4243J8Ljv4Lh3D@2fN2vDxTjYgACpsoQuYlLSmU80JQXGQA6vLhmVZb1ow6yN5QS1DuU08zlZqokKIgvOF1XXnjKGV7ginjGJAX@XXaFoPsWkVAKhMGiTvgx6PAIZ3/Npng4OOBDGUieN2MdLKyik1m2pwu96t7r3YX3eN80f "Haskell ‚Äì Try It Online") Takes a list of zeros and ones as input and returns a newline separated string. Inspired by [xnor's answer](https://codegolf.stackexchange.com/a/161507/56433). [Answer] # [Emojicode](http://www.emojicode.org/), 251 bytes ``` üêñüéÖüèøüçáüç¶büî°üêï2üç¶cüî§*üî§üçÆeüî§üî§üçÆyüî§üî§üç¶küç°büîÇi küçáüçäüòõüî°iüî§1üî§üçáüçäüòõy eüçáüçâüçìüçáüòÄyüçâüçÆyüî§üî§üçÆyüç™e cüç™üçâüçìüçáüçÆyüç™y cüç™üçÆeüç™üî§ üî§ eüç™üçâüçâüòÄyüçâ ``` [Try it online!](https://tio.run/##S83Nz8pMzk9J/f9h/oRuhQ/zZzUBid52EHfah/l9rR/m9@8HCQDxsqQP86csBEpMNQLxkoG8JVogAshblwphQDiVSJxl2UBiIUhrU6ZCNtSorg/zZ8wGmZYJUmUIVQqXqVRIhXI7gXgyhD2joRIqgGI@iNO7KlUhGUSh6oDKVcLlQK4EMaYsUQATqUh6OuE2/AcRXECPN4KM4VKABYOCmaWlgakBkoChgYm5qakRF1gXAA "Emojicode ‚Äì Try It Online") This is definitly not a golfed solution, but there isn't a person alive that would consider Emoji-code a golfing language. However, in the process of subjecting myself to the horrors that are emoji-code's syntax in an effore to teach myself this monstrosity of a language, I've been pleasantly surprised by just how powerful and efficient it can be üòÄ **Explaination:** ``` üêã üöÇ üçá üë¥ Define Class üêñüéÖüèøüçá üë¥ Define Method üç¶büî°üêï2 üë¥Convert Input integer to binary string üç¶cüî§*üî§ üë¥ asterisk string üçÆeüî§üî§ üë¥ Spacing string üçÆyüî§üî§ üë¥ output string üç¶küç°b üë¥ translate to iteratable üîÇi küçá üë¥ for-in loop to iterate over each digit üçäüòõüî°iüî§1üî§üçá üë¥ if digit is 1: üçäüòõy eüçáüçâ üë¥ don't print initial newline üçìüçáüòÄyüçâ üë¥ print spaces + asterisks üçÆyüî§üî§ üë¥ reset output string üçÆyüç™e cüç™üçâ üë¥ add correct number of spaces and one asterisk üçìüçá üë¥ if digit is 0: üçÆyüç™y cüç™ üë¥ add an asterisk to the output string üçÆeüç™üî§ üî§ eüç™ üë¥ add another space to the space string üçâüçâ üòÄy üë¥ print one last output string üçâüçâ üèÅüçá üë¥ Start Program üéÖüèø 699050 üë¥ Call Method üçâ ``` [Answer] # JavaScript (ES6), 48 bytes Same I/O format and same logic as the recursive version below. ``` a=>a.map((n,i)=>n?i&&p+0:+(p+=' '),p=` `).join`` ``` [Try it online!](https://tio.run/##HY69DoIwFEZ3n@JOtA3Xhh8rUVOcXF0ckYSKoDVy2wD6@ggOX3Ly5QznZb5mqHvrxzW5ezO1ejI6N7IznnNCK3RORxsEPoz2IfehZsAEel2tKiFfzlJVTYciRkgQUoQNgkLYImTzs9BuF6kIIY42mVKzoxKVxnG5kq3rT6Z@cgKdQ@1ocO9Gvt2Ds4JBCDSPlVdauOWFlJLk6C5jb@nBE1H@A8@f7tb0QizurAox/QA "JavaScript (Node.js) ‚Äì Try It Online") Or **42 bytes** if [this format](https://tio.run/##HY6xDoIwFEV3v@JNtg3PhqKVoClOri6OSGJFQAy8NoD@PoLDTU5uznDe9muHom/8uCH3LKfKTNakVnbWc07YCJPSqVmvfRAeAu4DwwCYQG/uq7uYjplCiBC2CDsEjbBHiOdnoSQJdYigwl2s9ezoSG@Vyleycv3ZFi9OYFIoHA2uLWXras4yBgHQPJbfaOGKZ1JKkqO7jn1DNY9E/k@7fLpH2QuxuLMqxPQD) is acceptable. --- # Recursive version, 56 bytes Takes input as an array of integers (0 or 1). Uses `0` for filled and space for empty. ``` f=([n,...a],p=` `,x=0)=>1/n?(n?x+0:+(p+=' '))+f(a,p,p):a ``` [Try it online!](https://tio.run/##FY4xb8IwEEZ3fsVtvpOvrh1wESDD1LVLxzQSJk0oCM5WSCv@feoMn/T06Q3vGv/iox0ueXyR9N1NUx@wFjbGxIZzOC6O/AyWwt69ygHl8NR2qzHroEAR6R4jZ860jdOudgwVw5JhxeAZ3hjW5Zlps7HeMji7WntfHF/5pXPNwvRpeI/tDwqEPbRJHunWmVs6o6oVaJAy1XzJzD3WpUrMmD7H4SJnrKgx95jx4/d@6gai2S0q0fQP "JavaScript (Node.js) ‚Äì Try It Online") ### Commented ``` f = ( // f = recursive function taking: [n, ...a], // n = current bit; a[] = remaining bits p = `\n`, // p = padding string, initialized to a linefeed x = 0 // x = 0 on the 1st iteration / equal to p after that ) => // 1 / n ? // if n is defined: ( n ? // if n = 1: x + 0 // append x + 0 --> either the integer 0 on the first iteration // or the padding string followed by a '0' : // else: +( // append the integer 0 (whitespace coerced to a number) p += ' ' // and append a space to the padding string ) // ) + f(a, p, p) // append the result of a recursive call with x = p : // else: a // append the empty array a[], forcing coercion to a string ``` [Answer] # Bash + GNU utilities, 38 ``` dc -e?2op|sed 's/\B1/^K^H*/g;s/[10]/*/g' ``` Here `^K` and `^H` are literal vertical-tab and backspace control characters. These don't render well on browsers, so this script may be recreated as follows: ``` base64 -d <<< ZGMgLWU/Mm9wfHNlZCAncy9cQjEvCwgqL2c7cy9bMTBdLyovZyc= > binpath.sh ``` Run in a terminal. Input is via STDIN. This answer may stretch the specifications too far - there are in fact no leading characters on each line of output - all positioning is done with control characters. If this is too much of a stretch, then the output may be piped to `|col -x|tac` for an extra 11 bytes. [Answer] ## Batch, 113 bytes ``` @set s= :l @shift @if %1.==0. set s=%s%+&goto l @echo %s%+ @if not %s%.==. set s=%s:+= % @if %1.==1. goto l ``` Takes a list of bits as command-line arguments. Uses `+` instead of `*` because `*` has a special meaning inside `%s:...=...%` expansions. [Answer] # Java 10, ~~100~~ 106 bytes ``` b->{var s="";int i=0,j;for(var c:b){if(c)for(s+="\n",j=i;j-->0;)s+=0;else++i;s+=1;}return s.substring(1);} ``` Takes an array of booleans and returns a String (`0`s are empty, `1`s are filled). Try it online [here](https://tio.run/##lVLLboMwEDw7X2FxCRYBQVoapS6R2lsPPeWY5mCIQ0yJiWxDFUV8O10eeSin5rRivTM77EzGKuZmm5/mUMa5SHCSM63xFxMSn0ZISMPVliUcfwjJ1LHtoaVRQqb4wMzOjosi50yu1liW@5grQkeoHqGBTBtmoFSF2OA9UNo9FKaZSjXp2AbiuC8RbmJ3caqYwjqyLAoCsIj8SUa3hbLbdvIak5PY2glpO9qJrG9pTbJI0Mx1Fz4l0PIpzzV3HEHhI6C14qZUEmtPl7HuJNgBoXWDEMhFLU@3B7YHFMpbhGdQHYfAK1oeteF7ryiNdwCoyaXdi/W6C2xEKoy2BSFOq6Q9wD8h0/BxzMt87of@47jAf56F4fRxYDgNn4LgBte6q0TFDD/be83A@RZwzCEOt4G5WPwJqUq58kzRm9@/29cEoXtKAEn@e9k06My5TEEpWd@76HcuDthh7Gpo316JNUwOTMmOqXcDJuIowuNg3BIOoemnux@vmz8). Thanks to [Olivier Gr√©goire](https://codegolf.stackexchange.com/users/16236/olivier-gr%C3%A9goire) for helping me golf it a bit more and alerting me to the fact that my output format was not up to the spec. Ungolfed version: ``` b -> { // lambda taking an array of booleans as argument var s = ""; // the output String int i = 0, // the number of "empty" characters to output j; // iterator variable for outputting the "empty" characters for(var c : b) { // iterate over the boolean array (the binary digits) if(c) // if it's a '1' for(s += "\n", // output a newline j = i; j-- > 0;) s += 0; // output the "empty" characters else // if it's a '0' ++i; // move one to the right on the next line s += 1; // output the "filled" character } return s.substring(1); // output the constructed String, minus the leading newline } ``` [Answer] # [Java (JDK 10)](http://jdk.java.net/), 83 bytes ``` a->{int m[][]=new int[20][20],r=0,i=0;for(int b:a)m[r+=i<1?0:b][i++-r]=1;return m;} ``` [Try it online!](https://tio.run/##jZDBb4IwFMbv/BUvJktASgMoc4K47LJkh508Eg4FwdVBIW1xIYa/3RVUZrK47NA2fd/3fl9f9@RArP3280TLuuIS9uqOG0kLnDcslbRieBpoaUGEgHdCGRw1gLpJCpqCkESq41DRLZRK0zeSU7aLYiB8J4zBCvB64awok1GMhj2K15BDeCLW@qgKUPalkGVf0MuuHfcL8dBGNLSDvOJ670p8YpQRN0O6cp5tP4kjapoWj0Mn4JlsOIMy6E7BkDrEgMyEFBDC0UEumqE58tAjWiBXHcul7dnIsecLz3OR53ozx@kCbWhWgTAk9v3@mXId54pOKCO8Vew3JrNdxrGszuPrvR2Ba@D0g3ChG7gktZ5a69SaPxnK9sI5aXUjuMUpIM9EU0gFzDGp66LVzwmjb9MKmZW4aiSuVY4s2JD0lz5qlx/sU/xL0M88owxUibf139BcnzykE0Snjm3O3JEP0Gn3Wm7f0f3jrfe1vrvTutM3 "Java (JDK 10) ‚Äì Try It Online") * Supports at most 20 bits. * Input as `int[]` * Output as `int[][]` [Answer] # [Haskell](https://www.haskell.org/), 126 bytes ``` (#)n=maximum.map(!!n) f l|s<-scanl1(zipWith(+))$(\a->[1-a,a])<$>l=unlines[[last$' ':['#'|elem[x,y]s]|x<-[0..0#s]]|y<-[1..1#s]] ``` Input as a list of zeroes and ones. Transforms number into offset by `x‚ܶ[1-x,x]` and calculates the partial sums. Final output is done with two nested list comprehensions. [Try it online!](https://tio.run/##FY5BDoIwEADvvmINJLRBGmvixYCf8OCh9rBqCY3bldhi0PB3lNtM5jIdxocjmq@egRvfAtcaUucYjAVH0cFSxN2/gWEny9KE531BO4tMchNw9GEIKmAv1muWqxZoinUVb8ikxdf3Z586UUqZiwtWR6Mr3KCVdX6kZmDy7KIxhDHlBRQHU2TF5MgFM24@NtpprCuzVWqbRWunz1@0UnqROaDnRvRDOqWXatV/U8JuP/8A "Haskell ‚Äì Try It Online") [Answer] # [R](https://www.r-project.org/), 59 bytes ``` function(n,x=sum(n|1))matrix(1:x^2%in%cumsum((n-1)%%x+1),x) ``` [Try it online!](https://tio.run/##XY3RCoIwGIXvfQoZDP4/J7WRBFKv4AtEgonWwP3C2mhRPfvSbqTuDt/hO8dG8kadNTX2ke7ztPfUOj0SED6Jr7mqAWAYL2oCmcSJSCxlPiWu3kk/K3FxRDjcvAF6SUTTOKsDyDLUimvirTdzB/SVwzQmAsYeln8oEJNqnpSb7a4oVHK32nXQAkuZYCuGR5k5@FEqRDwJKYaOLu761wjBGMYP "R ‚Äì Try It Online") Takes input as an array of bits. Returns a boolean matrix of `TRUE` and `FALSE` representing a `*` and a , respectively. Also has some stuff in the footer to print a matrix corresponding to the specs above, for ease of testing. [Answer] # APL+WIN, 65 or 46 bytes Prompts for input of the integer ``` n‚Üê+/i‚Üê((1+‚åä2‚çün)‚ç¥2)‚ä§n‚Üê‚éï‚ãÑm‚Üê(n,n)‚ç¥' '‚ãÑm[‚äÇ[2](+\i),[1.1]1++\~i]‚Üê'*'‚ãÑm ``` or for numerical vector of the binary representation of the integer ``` m‚Üê(2‚ç¥+/n‚Üê‚éï)‚ç¥' '‚ãÑm[‚äÇ[2](+\i),[1.1]1++\~i]‚Üê'*'‚ãÑm ``` assuming I have read the comments to certain answers correctly and the latter input is allowed. [Answer] # Pyth, 23 bytes ``` p\*VtQINp+b*Zd.?=hZ)p\* ``` [Try it here](http://pyth.herokuapp.com/?code=p%5C%2AVtQINp%2Bb%2AZd.%3F%3DhZ%29p%5C%2A&input=%5B1%2C0%2C1%2C0%2C1%2C0%2C1%2C0%2C1%2C0%2C1%2C0%2C1%2C0%2C1%2C0%2C1%2C0%2C1%2C0%5D&debug=0) ### Explanation ``` p\*VtQINp+b*Zd.?=hZ)p\* p\* Print the leading *. VtQ For each bit (excluding the leading 1)... IN .? ) ... If the bit is set... p+b*Zd ... Print a newline and a bunch of spaces... =hZ ... Otherwise, increase the count of spaces... p\* ... Then print the next *. ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~54~~ 36 bytes ``` s/./$&?" ".$"x$i.1:++$i&&1/ge;s/.//s ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX09fRc1eiUtJT0WpQiVTz9BKW1slU03NUD891Rokq1/8/7@hoYGB4b/8gpLM/Lzi/7q@pnoGhgb/dQsA "Perl 5 ‚Äì Try It Online") Cut it way down after I realized that the input could be a bit string. [Answer] # SmileBASIC, ~~64~~ ~~59~~ 57 bytes ``` INPUT N@L GPSET X,Y B=N<0X=X+B Y=Y+(X>B)N=N<<1ON!N GOTO@L ``` The highest bit (sign bit) is checked, and if it's 1, the X position increases. If the sign bit is less than the X position (that is, the sign bit is 0 and X is not 0) the Y position increases. The first movement will always be horizontally, so Y movement is blocked until after the first X movement. This ensures that the Y position doesn't increase during the leading 0 bits. Then N is shifted left, and this repeats until N reaches 0. [Answer] # [Ruby](https://www.ruby-lang.org/), 63 bytes ``` ->n{s="" n.to_s(2).gsub(/./){$&==?1?" "+s+?*:(s+=" ";?*)}[1,n]} ``` [Try it online!](https://tio.run/##FYpBDoIwEADvvGKzGEOhFgpUAqb2IUCMGNFTNbYcTOnbK55mMpnPMn3DLMPhrJ2RiJFm9nUxSUnYwyxTkrOcuN1eSsUVRpiZTKVdYjKJgCeVEt9zqkcfNkBJoaJQUxAUjhSarfytbQtRUOBF3QixPaIUFecju19vT3CrXeG9WAMYO@u7Qcdu7u3oB40@/AA "Ruby ‚Äì Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~19~~ 17 bytes ``` √ã?R+T√Æ +Q:¬∞T¬©Q√ɬ¨x √ã? // Map over the input and if the current value is 1: R+ // Return a new line and T√Æ + // a space repeated T (with initial value 0) times and Q // a \". : // If the current value is 0: ¬∞T // Increment T ¬©Q // and return \". √É // When all of that is done, ¬¨ // turn the array into a string x // and trim it, removing the excess new line at the start. ``` Takes input as an array of bits, for example `[1,0,1]`, outputs `"` instead of `*`. Shaved two bytes off thanks to [Oliver](https://codegolf.stackexchange.com/users/61613/oliver). [Try it online!](https://tio.run/##y0osKPn//3C3fZB2yOF1CtqBVoc2hBxaGXi4@dCaiv//ow11DHUMgBBCAulYAA) [Answer] # Python 2, 113 Bytes ``` def f(a): o='*';r=[o] for i in bin(a)[3:]: if'0'<i:r+=[' '*len(r[-1][1:])] r[-1]+=o print'\n'.join(r) ``` Not sure if this one counts (it outputs an array of each of the lines), but if so then I'll change my byte count to 103: ``` def f(a): o='*';r=[o] for i in bin(a)[3:]: if'0'<i:r+=[' '*len(r[-1][1:])] r[-1]+=o print r ``` [Answer] # TI-Basic (TI-84 Plus CE), 85 bytes ``` Prompt L 1→X 1→Y DelVar [A] sum(LL {Ans,1-Ans+dim(LL→dim([A] 1→[A](Y,X For(I,2,dim(LL Y+LL(I→Y X+not(LL(I→X 1→[A](Y,X End [A] ``` Prompts for a boolean list, returns a matrix of 0 and 1. Goes through the list, incrementing X if the next 'bit' is 0, changing Y otherwise, then adding a 1 to the matrix at that location, and returns the matrix at the end. TI-Basic is a [tokenized lanugage](http://tibasicdev.wikidot.com/one-byte-tokens). * 1 byte: `Prompt` , `L`\*6, (newline)\*12, `1`\*5, `‚Üí`\*7, `X`\*5, `Y`\*5, `sum(`, `L`\*5, `{`, `Ans`\*2, `,`\*5, `-`, `+`\*3, `dim(`\*3, `(`\*4, `For(`, `I`\*3, `2`, `not(`, `End` = 73 bytes * 2 bytes: `Delvar` , `[A]`\*5 = 12 bytes * Total: 85 bytes --- # TI-Basic (TI-84 Plus CE), 56 bytes ``` Prompt L 1→X 1→Y Output(Y,X,"* For(I,2,dim(LL Y+LL(I→Y X+not(LL(I→X Output(Y,X,"* End ``` Same processs as above, but using graphical output (limited by screen size: 10 rows, 26 columns, so max 10 1s and 25 0s) as it goes, instead of adding to a matrix. [Answer] ## Pyth, 30 bytes ``` JZFG.BQIsGIJk)p+*ZdN.?pN=hZ)=J ``` [Try it online!](https://tio.run/##K6gsyfj/3yvKzV3PKdCz2N3TK1uzQFsrKsVPz77AzzYjStPW6/9/M0tLA1MDAA) Uses `"` instead of `*`. Python 3 translation: ``` Q=eval(input()) Z=0 J=Z for G in "{0:b}".format(Q): if int(G): if J: print() print(Z*' '+'"',end='') else: print('"',end='') Z+=1 J=Q ``` [Answer] # x86 .COM, 32 bytes ``` 00h: 66 D1 E6 66 0F BD CE BF 24 AD 8E DF 41 66 0F A3 10h: CE 19 DB 81 E3 9E 00 8D 79 02 C6 05 2A E2 EE C3 fun: shl esi, 1 bsr ecx, esi mov di, $ad24 mov ds, di inc cx lab2: bt esi, ecx sbb bx,bx and bx,158 lea di,[di+2+bx] mov [di],byte '*' lab1:loop lab2 ret ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 18 bytes ``` +‚åø‚Üë1‚Ü묮‚ç®-+\,¬®‚àò~‚ç®0,‚éï ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/5rP@rZ/6htoiEQH1rxqHeFrnaMDpDRMaMOyDHQAar@D1T3Pwmow@hR19JHvYsPrTd81LWIiyuNK0nBkEtdHcwwgjGMYQwTGMMUxjCDMczhuhBylpYGpgYwnqGBibmpKdxMUyNTY0NDAA "APL (Dyalog Classic) ‚Äì Try It Online") ]
[Question] [ Write a function that takes as input a set of integers (can be a list, array or any other container with distinct numbers), and outputs the list of all its permutations. **Python (95 chars)**: ``` p=lambda s:s and sum(map(lambda e:map(lambda p:[e]+p,p(filter(lambda x:x!=e,s))),s),[]) or [[]] ``` It'd be nice to be beaten in the same language, but implementations in other languages are more than welcome! [Answer] # Python, 52 Input is a set. Output is a list of lists. ``` f=lambda a:[p+[x]for x in a for p in f(a-{x})]or[[]] ``` This is shorter than the [answer that does all the work with a builtin](https://codegolf.stackexchange.com/a/5057/30688). [Answer] ## Python - 76 chars Longer than gnibbler's, but implements things from scratch. ``` p=lambda x:x and[[a]+b for a in x for b in p([c for c in x if c!=a])]or[[]] ``` [Answer] ## J, 11 characters ``` (i.@!@#A.[) ``` Usage: ``` (i.@!@#A.[) 1 3 5 1 3 5 1 5 3 3 1 5 3 5 1 5 1 3 5 3 1 ``` Explanation: `i.@!@#` uses three verbs to return a list from 0 to (!n)-1 where n is the number of items in the given list. `[` returns the list itself. In the example shown that gives `0 1 2 3 4 5 A. 1 3 5`. `A.` returns one possible permutation of the second list for each item in the first list (kind of - the proper explanation is given [here](http://www.jsoftware.com/help/dictionary/dacapdot.htm)). [Answer] ## Python - 55 chars ``` from itertools import* p=lambda x:list(permutations(x)) ``` [Answer] ## Haskell, 44 43 ``` p[]=[[]] p l=[e:r|e<-l,r<-p$filter(/=e)l] ``` Essentially the same as ugoren's solution, but Haskell is better at list comprehensions! --- Of course, it can also do ## 30 ``` import Data.List p=permutations ``` --- More efficient approach, that doesn't require an equality comparison: ## 92 ``` import Data.List p[]=[[]] p l=(\(l,(e:r))->map(e:)$p(l++r))=<<(init$zip(inits l)(tails l)) ``` As a consequece, this one also works when there are duplicate elements in the list. [Answer] # C, ~~270~~ ~~243~~ 239 characters ``` #define S t=*a;*a=a[i];a[i]=t; #define R o=p(n,r-1,a+1,o,r-2,0) int*p(n,r,a,o,i,t)int*a,*o;{if(!r)for(;n;--n)*o++=*--a;else{R;for(;i;--i){S R;S}}return o;} P(n,a)int*a;{int N=1,i=n;for(;i;N*=i--);return p(n,n,a,malloc(N*n*8),n-1,0)-N*n;} ``` The function P(n,a) returns a pointer to the n! permutations of a, packed one after another in one giant array. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 33 bytes ``` X-Y:-bagof(A,permutation(X,A),Y). ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P0I30ko3KTE9P03DUacgtSi3tCSxJDM/TyNCx1FTJ1JT77@9rkK0oY6RjnGsbqSOQnlRZklqTp4GSAYA "Prolog (SWI) – Try It Online") -2 from steffan [Answer] ## in Q (48) ``` g:{$[x=1;y;raze .z.s[x-1;y]{x,/:y except x}\:y]} ``` Sample usage: ``` q)g[3;1 2 3] 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 ``` [Answer] # Ruby - 23 chars ``` f=->x{p *x.permutation} ``` for example `f[[1,2,3]]` [outputs this](http://pastebin.com/sx9aNEVk). but using `[].permutation` feels like cheating, so: # Ruby - 59 chars ``` f=->a{a.size<2?[a]:a.flat_map{|x|f[(a-x=[x])].map{|y|x+y}}} ``` tested with ``` 100.times.all?{arr=(1..99).to_a.sample(rand(5)); arr.permutation.to_a==f[arr]} => true ``` [Answer] ### Scala 30: ``` def p(s:Seq[_])=s.permutations ``` ### Scala 195, quick'n'dirty, without *permutations* from library: ``` def c(x:Int,t:List[_]):List[_]={val l=t.size val o=x%l if(l>1){val r=c(x/l,t.tail) r.take(o):::(t.head::r.drop(o))}else t} def p(y:List[_])=(0 to(1 to y.size).product).foreach(z=>println(c(z,y))) val y=List(0,1,2,3) p(y) ``` ### Scala 293, full grown, type safe iterator: ``` class P[A](val l:Seq[A])extends Iterator[Seq[A]]{ var c=0 val s=(1 to l.size).product def g(c:Int,t:List[A]):List[A]={ val n=t.size val o=c%n if(n>1){val r=g(c/n,t.tail) r.take(o):::(t.head::r.drop(o)) }else t} def hasNext=c!=s def next={c+=1 g(c-1,l.toList)} } for(e<-new P("golf"))println(e) ``` [Answer] **Python - 58 chars** Slightly shorter than ugoren's, by taking a set as input: ``` p=lambda x:x and[[y]+l for y in x for l in p(x-{y})]or[[]] ``` [Answer] # K, 30 bytes ``` {x@v@&((#x;1)~^=:)'v:!(#x)##x} ``` No builtins! [Answer] ## JS - ~~154~~ 146 chars `function f(x){var a=[],m;(m=x.length)>1?f(x.slice(1)).map(function(y){for(l=m;l--;a.push(y.slice(0,l).concat(x[0],y.slice(l))));}):a=[x];return a}` Test : `f([1,2,3,4,5]).map(function(a){return a.join('')}).join('\n')` returns [this](http://pastebin.com/8Wu0q7r3). [Answer] ## R Since we are talking about permutations let me show at least one solution in R: ``` library(gtools);v=c(3,4,5);permutations(length(v),length(v),v) ``` [Answer] ## Perl 188 No library routines, no recursion ``` sub p{$l=(@_=sort split'',shift)-1;while(print@_){$k=$j=$l;--$k while($_[$k-1]cmp$_[$k])>=0;$k||last;--$j while($_[$k-1]cmp$_[$j])>=0;@_[$j,$k-1]=@_[$k-1,$j];@_[$k..$l]=reverse@_[$k..$l]}} ``` [Answer] ## Python - 50 chars ``` import itertools list(itertools.permutations("123")) ``` [Answer] # Pyth, 4 bytes ``` L.pb ``` Yeah, Pyth was created after this challenge was posted and all. This is still really cool. :D [Live demo.](https://pyth.herokuapp.com/?code=L.pb%0Ay%5B1+2+3%29&debug=1) Reading from stdin is a byte shorter: ``` .pQ ``` [Answer] # JavaScript ~~143~~ ~~136~~ ~~134~~ 123 ``` function p(s,a="",c="",i,z=[]){a+=c,i=s.length !i?z.push(a):0 for(;i--;s.splice(i,0,c))p(s,a,c=s.splice(i,1),0,z);return z} var perms = p([1,2,3]); document.getElementById('output').innerHTML = perms.join("\n"); ``` ``` <pre id="output"></pre> ``` [Answer] # 05AB1E - 2 1 bytes `œ` The input must be an array/list. Explanation: ``` œ //Takes all the permutations of the elements in the top of the stack (the input is a list, so it would work) ``` Saved a byte thanks to Erik the Outgolfer [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes ``` pᵘ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh1snlP8veLh1xv//0dGGOkY6xjomOqaxOtFmOiZGQMpAx9BIJ97YODYWAA "Brachylog – Try It Online") ``` ᵘ Find every unique p permutation of the input. ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 2 bytes ``` ṖU ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E1%B9%96U&inputs=%5B1%2C1%2C3%5D&header=&footer=) ``` Ṗ # All permutations of input U # Filtered by unique ``` [Answer] # JavaScript (ES6), ~~91~~ 78 bytes *-5 thanks to @Neil* ``` f=a=>a.length<2?[a]:a.flatMap((x,i)=>f(a.filter((_,j)=>i-j)).map(t=>[x,...t])) ``` Pretty normal recursive approach, and my first time using `copyWithin` :p Okay, `copyWithin` modifies the array, so that doesn't work. Used a different approach, which now saves more bytes. [Answer] # Curry, ~~41~~ 26 bytes *15 bytes saved by alephalpha* *Tested in [PAKCS](https://www.informatik.uni-kiel.de/%7Epakcs/)* ``` p[]=[] p(x++a:y)=a:p(x++y) ``` [Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/78gOtY2OparQKNCWzvRqlLTNtEKzK7U/J@bmJmnYKtQoBBtrGOiY6hjFPsfAA "Curry (PAKCS) – Try It Online") Uses non-determinism to output all the permutations. This same code is used in my answer [here](https://codegolf.stackexchange.com/a/246041/) for which I originally wrote it. [Answer] # [Knight](https://github.com/knight-lang/knight-lang), 180 bytes ``` ;=i=jF;W=pP E++"=x"=i+1i" p";=s"";W>i-=j+1jT=s+++++++s";=y"j"F W>i-=y"j"+1y"j"T"E+s';=z=bF;W>i-=z+1zT;=aF W>i-=a+1aT|?z a=b|b?E+"y"zE+"y"a|b;=rF;=s"";W>z=r+1r=s++sE+"x"E+"y"r" "Os' ``` [Try it online!](https://knight-lang.netlify.app/#WyI7PWk9akY7Vz1wUCBFKytcIj14XCI9aSsxaVwiIHBcIjs9c1wiXCI7Vz5pLT1qKzFqVD1zKysrKysrK3NcIjs9eVwialwiRiBXPmktPXlcImpcIisxeVwialwiVFwiRStzJzs9ej1iRjtXPmktPXorMXpUOz1hRiBXPmktPWErMWFUfD96IGE9YnxiP0UrXCJ5XCJ6RStcInlcImF8Yjs9ckY7PXNcIlwiO1c+ej1yKzFyPXMrK3NFK1wieFwiRStcInlcInJcIiBcIk9zJyIsIjJcbjRcbjZcbjgiXQ==) This was a *pain*. Nested evals and stuff. Since recursion doesn't really work, I had to literally compose a string of nested while loops, and then eval it. Extremely inefficient, \$O(n^{n+1})\$ where \$n\$ is the length of the input. My browser started to freeze up with \$n=6\$. -2 bytes thanks to Aiden Chow. [Answer] # Python, 53 bytes ``` from itertools import*;lambda x:list(permutations(x)) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` Œ! ``` [Try it online!](https://tio.run/##y0rNyan8///oJMX/h9sj//9XKkktLlECAA "Jelly – Try It Online") Yay for builtins! [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 3 bytes **Solution** ``` prm ``` [Try it online!](https://tio.run/##y9bNz/7/v6AoV8FQwUjBWMHk/38A "K (oK) – Try It Online") **Explanation:** It's a 3 byte **built-in** shortcut to the following **built-in** 47 byte function: ``` {[x]{[x]$[x;,/x ,''o'x ^/:x;,x]}@$[-8>@x;!x;x]} ``` ... which can be shortened to 23 bytes if we know we're getting a list of ints as input: ``` {$[x;,/x,''o'x^/:x;,x]} / golfed built in { } / lambda function with implicit input x $[ ; ; ] / if[condition;true;false] x / if x is not null... x^/:x / x except (^) each-right (/:) x; create length-x combinations o' / call self (o) with each of these x,'' / x concatenated with each-each of these results (this is kinda magic to me) ,/ / flatten list ,x / otherwise enlist x (enlisted empty list) ``` [Answer] # Axiom, 160 bytes ``` p(a)==(#a=0=>[[]];r:=[[a.1]];r:=delete(r,1);n:=#a;m:=factorial n;m>1.E7=>r;b:=permutations n;for j in 1..m repeat(x:=b.j;r:=concat([a.(x.i)for i in 1..n],r));r) ``` ungolfed ``` --Permutation of a pmt(a)== #a=0=>[[]] r:=[[a.1]]; r:=delete(r,1) -- r has the type List List typeof(a) n:=#a m:=factorial n m>1.E7=>r b:=permutations(n) --one built in for permutation indices for j in 1..m repeat x:=b.j r:=concat([a.(x.i) for i in 1..n],r) r ``` All this call one library function that give permutation on index (only integers as permutation as permutations on [1], permutations on [1,2], permutations on[1,2,3] etc).So it is enough get these set of indices and build the lists; One has to note that this seems to be compiled good for every List of type X ``` (4) -> p([1,2,3]) Compiling function p with type List PositiveInteger -> List List PositiveInteger (4) [[1,2,3],[1,3,2],[3,1,2],[2,1,3],[2,3,1],[3,2,1]] Type: List List PositiveInteger (5) -> p([x^2,y*x,y^2]) Compiling function p with type List Polynomial Integer -> List List Polynomial Integer (5) 2 2 2 2 2 2 2 2 2 2 2 2 [[x ,x y,y ],[x ,y ,x y],[y ,x ,x y],[x y,x ,y ],[x y,y ,x ],[y ,x y,x ]] Type: List List Polynomial Integer (6) -> p([sin(x),log(y)]) Compiling function p with type List Expression Integer -> List List Expression Integer (6) [[sin(x),log(y)],[log(y),sin(x)]] Type: List List Expression Integer (7) -> m:=p("abc")::List List Character Compiling function p with type String -> Any (7) [[a,b,c],[a,c,b],[c,a,b],[b,a,c],[b,c,a],[c,b,a]] Type: List List Character (8) -> [concat(map(x+->x::String, m.j)) for j in 1..#m] (8) ["abc","acb","cab","bac","bca","cba"] Type: List String ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 1 byte ``` á ``` [Japt interpreter](https://ethproductions.github.io/japt/?v=1.4.6&code=4Q==&input=WzAsMSwyLDMsNF0KLVI=) This got bumped and didn't have a Japt answer, so I figured I'd go ahead and add one. `á` when applied to an array and without any arguments is the builtin for "get all permutations". The `-R` flag used in the interpreter link only modifies how the result is printed. [Answer] # APL(NARS), 39 chars, 78 bytes ``` {1≥k←≢w←,⍵:⊂w⋄↑,/{w[⍵],¨q w[a∼⍵]}¨a←⍳k} ``` test: ``` q←{1≥k←≢w←,⍵:⊂w⋄↑,/{w[⍵],¨q w[a∼⍵]}¨a←⍳k} q 1 2 3 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 q 'abcd' abcd abdc acbd acdb adbc adcb bacd badc bcad bcda bdac bdca cabd cadb cbad cbda cdab cdba dabc dacb dbac dbca dcab dcba ``` ]
[Question] [ Your task is to write a program, function or snippet (yes, snippets are allowed) that simply outputs an integer. *However*, you must be able to separate your submission into prefixes that *also* produce distinct integers. You cannot use any bytes that have appeared in previous prefixes. For example, we can have the prefixes: ``` 1 # 1 (Now we can't use 1) 1-6 # -5 (Now we can't use - or 6) 1-6/3 # -1 (Now we can't use / or 3) 1-6/3+0xA # 9 Final submission ``` ## Rules * Your goal is to create to try and create the most unique integers, while keeping them close to zero. + The scoring system is `((number of unique integers)**3)/(sum of absolute values)`, where the higher your score, the better. The above example scores \$(4^3)/(1+\lvert-5\rvert+\lvert-1\rvert+9) = 64/16 = 4\$. * There should be at least two unique integers (no dividing by zero!) * Please format your answer similar to: ``` # Language, \$(4^{3})/16 = 4\$ 1-6/3+0xA (the full program) ``` * Mention if your submission is composed of snippets that evaluate to a value, functions or full programs. * List each of the prefixes and (optionally) an explanation for how they work. [Answer] # TI-BASIC (TI-84+ CE), \$238^3/14161 = 952.0\$ ``` 118-length("+×/ABCDEFGHIJK... ``` The 256 bytes in TI-BASIC break down thusly: * 240 bytes are one-byte tokens that can be quoted * 11 are the start of two-byte tokens * 2 are unused * The remaining 3 are the `"`,`→`, and newline characters which break strings. The string contains all 237 allowable bytes in the first category not already in `118-length(`. The program calculates 238 distinct integers, ranging from 118 down to -119. The score is therefore $$ \frac{238^3}{\sum\_{n = -119}^{118} |n|} = 952.$$ [Answer] ## vim, 14³ / 53 = 51.77 ``` i10<esc>X<c-x>r2hx<c-a>Pa<del>4<c-c>d^s5<c-o>I-<c-o>$<c-o>C6<c-h>7 ``` [Try it online!](https://tio.run/##PYxLD4IwEITv/RWbpkk1BAFfcBBj4smbRxMfSREaSKBEitjE@NuxWOxl59udmU2YzPuexRMEQGgR0J/6Ri4qSE4WI0PN3Giu/o4/to5G2EWFfGnNRXozLFf2xg/uMMkwzHG/tmYUUjRFSMaUIl43oKAQgMmbnXfXD0ZprYNNBS4HNmtVqzcZYyKJwhq7ogLsiFoHiMTgvB4mBRsvzTpPPMsSthZ14c7a8U9ai6zvvw) (all prefixes) Breakdown: ``` i1 1 0 10 <esc>X 0 <c-x> -1 <c-x> decrements r2 -2 hx 2 hx is X, but we've already used that <c-a> 3 <c-a> increments P -3 paste the - from two steps ago a<del>4 -4 <c-c>d^ 4 <c-c> is an <esc> alternative s5 5 <c-o>I-<c-o>$<c-o> -5 <c-o> allows a single normal mode input C6 -6 trailing <c-o> from previous line used here <c-h>7 -7 <c-h> = backspace ``` [Answer] ## [Lenguage](https://esolangs.org/wiki/lenguage), 256³ / 16384 = 1024 The source code of the solution can be described as follows: ``` 183662808731984092 0x00 bytes 4775233027031586288 0x01 bytes 27 0x02 bytes 81 0x03 bytes 128931291729852829668 0x04 bytes 108 0x05 bytes 648 0x06 bytes 81 0x07 bytes 2079 0x08 bytes 27 0x09 bytes 3481144876706026401009 0x0A bytes 108 0x0B bytes 2808 0x0C bytes 27 0x0D bytes 17496 0x0E bytes 81 0x0F bytes 2079 0x10 bytes 27 0x11 bytes 56106 0x12 bytes 756 0x13 bytes 93990911671062712827216 0x14 bytes 108 0x15 bytes 2808 0x16 bytes 27 0x17 bytes 75789 0x18 bytes 756 0x19 bytes 474552 0x1A bytes 27 0x1B bytes 81 0x1C bytes 56025 0x1D bytes 756 0x1E bytes 1514835 0x1F bytes 20439 0x20 bytes 2537754615118693246334805 0x21 bytes 108 0x22 bytes 2808 0x23 bytes 27 0x24 bytes 75789 0x25 bytes 756 0x26 bytes 2046276 0x27 bytes 20439 0x28 bytes 12812877 0x29 bytes 108 0x2A bytes 729 0x2B bytes 2079 0x2C bytes 27 0x2D bytes 1512648 0x2E bytes 40920957 0x2F bytes 1689866867948183303767857 0x30 bytes 66829507740256534347823839 0x31 bytes 2808 0x32 bytes 27 0x33 bytes 75789 0x34 bytes 756 0x35 bytes 2046276 0x36 bytes 20439 0x37 bytes 55249425 0x38 bytes 551880 0x39 bytes 345947652 0x3A bytes 2916 0x3B bytes 27 0x3C bytes 19656 0x3D bytes 56133 0x3E bytes 40842225 0x3F bytes 1104865839 0x40 bytes 45626405434600949201732247 0x41 bytes 1804396708986926427391243545 0x42 bytes 27 0x43 bytes 75789 0x44 bytes 756 0x45 bytes 2046276 0x46 bytes 20439 0x47 bytes 55249425 0x48 bytes 551880 0x49 bytes 1491734448 0x4A bytes 9355487364 0x4B bytes 78732 0x4C bytes 756 0x4D bytes 530685 0x4E bytes 1515591 0x4F bytes 1102740075 0x50 bytes 29831377653 0x51 bytes 1231912946734225628446770696 0x52 bytes 48718711142647013539563576444 0x53 bytes 2066715 0x54 bytes 55801305 0x55 bytes 1506635235 0x56 bytes 292874988897 0x57 bytes 2125764 0x58 bytes 14348907 0x59 bytes 40920957 0x5A bytes 29773982025 0x5B bytes 33261649561824092773510005450 0x5C bytes 1315405200851469365568216563988 0x5D bytes 55801305 0x5E bytes 1506635235 0x5F bytes 7948303851537 0x60 bytes 57395628 0x61 bytes 387420489 0x62 bytes 1104865839 0x63 bytes 803897514675 0x64 bytes 898064538169250504884770147177 0x65 bytes 35515940422989672870341847227676 0x66 bytes 1506635235 0x67 bytes 40679151345 0x68 bytes 214604203991472 0x69 bytes 1549681956 0x6A bytes 10460353203 0x6B bytes 29831377653 0x6C bytes 24001245795414021635055080475036 0x6D bytes 246496735155742018538946394995 0x6E bytes 958930391420721167499229875147252 0x6F bytes 40679151345 0x70 bytes 5795411844856032 0x71 bytes 41841412812 0x72 bytes 282429536481 0x73 bytes 805447196631 0x74 bytes 648033636476178584146487172825972 0x75 bytes 108 0x76 bytes 6655411849205034500551552664784 0x77 bytes 25891120568359471522479206628975804 0x78 bytes 1098337086315 0x79 bytes 156484875126743748 0x7A bytes 21747074309037 0x7B bytes 17496908184856821771955153666301244 0x7C bytes 108 0x7D bytes 2808 0x7E bytes 27 0x7F bytes 81 0x80 bytes 179696119928535931514891921949087 0x81 bytes 699060255345705731106938578982346708 0x82 bytes 4225121283523411674 0x83 bytes 472416520991134187843376319996477587 0x84 bytes 108 0x85 bytes 2808 0x86 bytes 27 0x87 bytes 75789 0x88 bytes 108 0x89 bytes 729 0x8A bytes 2079 0x8B bytes 27 0x8C bytes 4851795238070470150902081892625349 0x8D bytes 18874626894334054739887341632523361116 0x8E bytes 114078274655132115171 0x8F bytes 12755246066760623071771160639904894849 0x90 bytes 108 0x91 bytes 2808 0x92 bytes 27 0x93 bytes 75789 0x94 bytes 756 0x95 bytes 2046276 0x96 bytes 2916 0x97 bytes 27 0x98 bytes 19656 0x99 bytes 56133 0x9A bytes 130998471427902694074356211100885179 0x9B bytes 854006569949556303994892977044130020645 0x9C bytes 108 0x9D bytes 2808 0x9E bytes 27 0x9F bytes 75789 0xA0 bytes 756 0xA1 bytes 2046276 0xA2 bytes 55269864 0xA3 bytes 78732 0xA4 bytes 756 0xA5 bytes 530685 0xA6 bytes 1515591 0xA7 bytes 3536958728553372740007617699723899860 0xA8 bytes 23058177388638020207862110380191510557388 0xA9 bytes 108 0xAA bytes 2808 0xAB bytes 27 0xAC bytes 75789 0xAD bytes 756 0xAE bytes 2046276 0xAF bytes 20439 0xB0 bytes 55249425 0xB1 bytes 1492286328 0xB2 bytes 2125764 0xB3 bytes 14348907 0xB4 bytes 40920957 0xB5 bytes 622666287378897486676257185943063330345696 0xB6 bytes 108 0xB7 bytes 2808 0xB8 bytes 27 0xB9 bytes 75789 0xBA bytes 756 0xBB bytes 2046276 0xBC bytes 20439 0xBD bytes 55249425 0xBE bytes 1492286328 0xBF bytes 40291730856 0xC0 bytes 57395628 0xC1 bytes 387420489 0xC2 bytes 1104865839 0xC3 bytes 16811989759230232140258944020462709919333792 0xC4 bytes 108 0xC5 bytes 2808 0xC6 bytes 27 0xC7 bytes 75789 0xC8 bytes 756 0xC9 bytes 2046276 0xCA bytes 20439 0xCB bytes 55249425 0xCC bytes 551880 0xCD bytes 1491734448 0xCE bytes 40291730856 0xCF bytes 1087876733112 0xD0 bytes 1549681956 0xD1 bytes 10460353203 0xD2 bytes 29831377653 0xD3 bytes 453923723499216267786991488552493167822012492 0xD4 bytes 2808 0xD5 bytes 27 0xD6 bytes 75789 0xD7 bytes 756 0xD8 bytes 2046276 0xD9 bytes 20439 0xDA bytes 55249425 0xDB bytes 551880 0xDC bytes 1491734448 0xDD bytes 40291730856 0xDE bytes 1087876733112 0xDF bytes 29372671794024 0xE0 bytes 324270949293 0xE1 bytes 805447196631 0xE2 bytes 12255940534478839230248770190917315531194337311 0xE3 bytes 76545 0xE4 bytes 2066715 0xE5 bytes 55801305 0xE6 bytes 1506635235 0xE7 bytes 832318279426764 0xE8 bytes 21747074309037 0xE9 bytes 330910394430928659216716795154767519342247107424 0xEA bytes 2066715 0xEB bytes 55801305 0xEC bytes 1506635235 0xED bytes 22472634223673946 0xEE bytes 8934580649635073798851353469178723609411678244474 0xEF bytes 55801305 0xF0 bytes 1506635235 0xF1 bytes 40679151345 0xF2 bytes 606761124039196515 0xF3 bytes 241233677540146992568986543667825537454115312600825 0xF4 bytes 1506635235 0xF5 bytes 40679151345 0xF6 bytes 6513309293583968799362636679031305893812560835614495 0xF7 bytes 40679151345 0xF8 bytes 1098337086315 0xF9 bytes 175859350926767157582791190333845259132939142561591365 0xFA bytes 1098337086315 0xFB bytes 4748202475022713254735362139013821996589386504264297360 0xFC bytes 29655101330505 0xFD bytes 128201466825613257877854777753373193907913435615136028720 0xFE bytes 3461439604291557962702078999341076235513663562296408699075 0xFF bytes ``` Each run of identical bytes combined with the previous runs constitutes a prefix, and the full program is all the strings described above concatenated. This is an optimal score. (The programs print all numbers from -127 to 128 inclusive.) To create this answer, first, I copied [the Java answer here](https://codegolf.stackexchange.com/a/5440/3808) for generating brainfuck programs to print a string. I ran it with this `main` function: ``` public static void main(String[] args) { for (int i = -127; i <= 128; ++i) generate(""+i); } ``` Then, I ran this Ruby script to generate the human-readable text shown here: ``` #!/usr/bin/ruby nums = File.open('f').map do |line| line.chomp.sub(/^\+/, '>+').chars.map{|ch| '+-><.,[]'.index(ch).to_s(3).rjust(3,?0) }.join.to_i 3 end puts ([0]+nums.sort).each_cons(2).map.with_index{|x,i|"#{x[1]-x[0]} 0x#{i.to_s(16).rjust(2,?0).upcase} bytes"}*"\n" ``` The largest program is 3594571896764310192036774345469579167648804468538578264427 bytes long (and prints `-90`). [Answer] # Javascript, \$(111^{3})/2530 = 540.5656126482213\$ ``` [][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(+(!+[]+!+[]+!+[]+[!+[]+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]])+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+(!+[]+!+[]+!+[]+!+[]+!+[]+[+[]])+[])+(!![]+[])[+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+(+!+[]+[+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]])[+!+[]]+(+[![]]+[+(+!+[]+(!+[]+[])[!+[]+!+[]+!+[]]+[+!+[]]+[+[]]+[+[]]+[+[]])])[+!+[]+[+[]]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+!+[]]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+([][[]]+[])[!+[]+!+[]])+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+!+[]]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(![]+[+![]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]]+[+[]]+(![]+[+![]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]])()[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()+[])[!+[]+!+[]+!+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(![]+[])[+!+[]]+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+(+(+!+[]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+[+[]])+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+([][[]]+[])[+!+[]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[+!+[]]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(!![]+[])[+[]]+(+(+!+[]+[+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+[+!+[]])[+!+[]]+(+(+!+[]+(!+[]+[])[!+[]+!+[]+!+[]]+[+!+[]]+[+[]]+[+[]])+[])[!+[]+!+[]]+[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[+!+[]]]+([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[!+[]+!+[]]+([][[]]+[])[+!+[]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+[!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(![]+[+![]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]]+[+[]]+(![]+[+![]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]])()[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()+[])[!+[]+!+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+((+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+[+[]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+!+[]]])+[])[!+[]+!+[]]+[+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(![]+[+![]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]]+[!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(![]+[+![]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]]+[+[]]+(![]+[+![]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]])()[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()+[])[!+[]+!+[]+!+[]]+(+((+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+[+[]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+!+[]]])+[])[!+[]+!+[]]+([][[]]+[])[+!+[]]+(![]+[+![]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]]+[!+[]+!+[]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+([][[]]+[])[!+[]+!+[]])+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]])().$0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyzÀāłƃDŽȅɆʇˈ̉͊βόЍюҏӐԑՒ֓הٖؕڗۘܙݚޛߜరᡡⱱ㣣䤤奥榦秧訨驩ꪪ뫫쬬흝ﯯ&''|""**"",~{} ``` (Credit to [this interesting utility](http://www.jsfuck.com/) for the conversion.) The above effectively evaluates into the following code: ``` (new Proxy({},{get:(a,p,b,n=p.length+3)=>n%2?(n-1)/2:-n/2})).$0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyzÀāłƃDŽȅɆʇˈ̉͊βόЍюҏӐԑՒ֓הٖؕڗۘܙݚޛߜరᡡⱱ㣣䤤奥榦秧訨驩ꪪ뫫쬬흝ﯯ&''|""**"",~{} ``` ...which creates a proxy that converts the length of a property name into a number. The first prefix ends one character after the `.`, and uses only 6 unique characters, excluding the `.$`. The next 63 slices append 63 other single-byte characters which are valid in JS object property names. The next 44 slices append two-byte valid characters made up of unused bytes. The final slices append `&''`, `|""**""`, and `,~{}`. The first slice returns `-2`, the second `2`, then `-3`, then `3`, `-4`, `4`, `-5`, etc. up to the last three slices which are `0`, `1`, and `-1`. [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), \$4^3/4=16\$ For this one we use brain-flak snippets so we are concerned with the value not what they do. Complete program: ``` <>(())[[][][]]{} ``` Prefixes and output ``` 0 : <> 1 : <>(()) -2 : <>(())[[][][]] -1 : <>(())[[][][]]{} ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v9fg8vGjktDQ1OTKzo6FgRjuapruTT//wcA "Brain-Flak (BrainHack) – Try It Online") ## Explanation This is probably the best a brain-flak answer can get since we've used up all the character Brain-flak cares about, and we can't cluster the numbers closer to zero. The first snippet is `<>`, `<>` changes the stack but otherwise evaluates to zero, so we start with zero. From here we add `(())` this makes one. We could have just done `()`, because that is also one, but if we push a one now we will be able to recall it later with `{}` and `[]`. This is pretty much the only way `{}` and `[]` can create value so we do that. Since there is one thing on the stack `[]` counts as a 1 so we subtract 3 from the total with `[[][][]]` bringing us to -2. Lastly we use `{}` to pop the one we pushed earlier bringing us up to -1. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 984 ``` LNḂ¡:2µ}“¢¢¢£¤¥¦©¬®½¿€ÆÇÐÑרŒÞßæçðıȷñ÷øœþ !"#$%&'()*+,-./013456789;<=>?@ABCDEFGHIJKMOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|~¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭ§Äẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż”‘ ``` [Try it online!](https://tio.run/##HY33UlpBGEdfJb333nvvvffEFEN6NW1YRDCgSYQZwSQqUicJEkGF/fYizuxedu7lLX77IoTJnH/PnNPe5vF0NJtHjoH75MimVXLyo/H@lMn/pGRaZmRW/pJ5WZBTctr48iqgguqb6lMxFa9H1JAaVlmVU2N20amooqooXo@q2oyZs2bPmTtv/oKFixYvWbps@YqVq9esXbd@w8bNW7Zu275j567de/bu23/g4KHDR4@fOHnq9Jmz585fuHjp8pWr167fuHnr9p22u/fuP2h/6Hn0@MnTZ89fvHz1@s3bjnfvP3ySZTkmSZbkuGEThk0aVjasYhg3jAwThlmGVQ2bMqymmQ7qkO7TUR03xYIe1Gmd1yUn7UZ1txvTETfhZvWAW3RLOtNIuNWGT482wk4GIgHuB@@B4OBpWCHwEngZ5AMFYPWAvoOSoDysNKgG0Q1rAiLiZO2WGrL7wYfsViNpj9nTIC/I7xRA/aA4KAH6DRGACEF8qVsQI@Bd4L0QBJ6BFQYfB6@AOkFBWL2gH6AUaFTmlB/iM6xJiKiTA@@0W27YjoEP261Iqt4aMVCX8xcUAw2ARkB/IIIQYYiv9arxDhpvvNn8Bw "Jelly – Try It Online") You can see the prefixes (separated by a double newline) [here](https://tio.run/##HZF3U1NBFMW/ir23INhi72LvXWxYIvaKbfICJJiACpkhQQWSkIRRA5JQsncfZWb3Zec9vsXZLxJX594/75xzz@8EGpuamqtVQSpbDzbg84FFzfpr6mpFFnZMlQLamhGTYlJb3F@tVo8cAwuJ9JYaMfFBB3@IzP8ZFFmRE3nxUxTEiJgWszpUkGEZkV9ll0zIZKVb9ssBmZdDctQpumVZlGXJKnE5M2/@goWLFi9Zumz5ipWrVq9Zu863vrZuw8ZNm/1bt23fsXPX7j179@0/cPBQ/eGjx0@cPHX6zNlz5y9cvHT5ytVrDddv3Lx1u/HO3Xv3Aw@aHj56/OTps@cvXr56/ab57bv3H83To4JESYxpa1xbE9oyGcraYtoiE0ZbtramtDVt8ilLRVRUdam4SuriiOpTWVVQJTfrxVW7l1DdXsrLq16v6JVUbi7lTc2F1PBczM2Bp8BawTrAGZgBZuCVwCZBIVAYdgfoGygDKsDOgmbA22GPg3e7eecfZ6cHrN8xGhln1JkFBUGt7gioB5QEpUC/wMPgUfDPFRs8DdYG1glOYDnTDtgYWBnUAorA7gR9Bw2ChsWQbAX/BHsCPO4OgbU45jbmJEzFjhEZrBgjC9Tm/gElQL2gNOg3eAQ8Bv6lMqWDfTqY/As). The numbers printed are, in order: ``` 0 1 -1 -2 2 -3 3 -4 4 -5 5 -6 6 -7 7 -8 8 -9 9 -10 10 -11 11 -12 12 -13 13 -14 14 -15 15 -16 16 -17 17 -18 18 -19 19 -20 20 -21 21 -22 22 -23 23 -24 24 -25 25 -26 26 -27 27 -28 28 -29 29 -30 30 -31 31 -32 32 -33 33 -34 34 -35 35 -36 36 -37 37 -38 38 -39 39 -40 40 -41 41 -42 42 -43 43 -44 44 -45 45 -46 46 -47 47 -48 48 -49 49 -50 50 -51 51 -52 52 -53 53 -54 54 -55 55 -56 56 -57 57 -58 58 -59 59 -60 60 -61 61 -62 62 -63 63 -64 64 -65 65 -66 66 -67 67 -68 68 -69 69 -70 70 -71 71 -72 72 -73 73 -74 74 -75 75 -76 76 -77 77 -78 78 -79 79 -80 80 -81 81 -82 82 -83 83 -84 84 -85 85 -86 86 -87 87 -88 88 -89 89 -90 90 -91 91 -92 92 -93 93 -94 94 -95 95 -96 96 -97 97 -98 98 -99 99 -100 100 -101 101 -102 102 -103 103 -104 104 -105 105 -106 106 -107 107 -108 108 -109 109 -110 110 -111 111 -112 112 -113 113 -114 114 -115 115 -116 116 -117 117 -118 118 -119 119 -120 120 -121 121 -122 122 123 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~32~~ ~~34.7~~ ~~40~~ \$(11^{3})/32 = 41.59375\$ After two hours of trial and error I finally got all integers from `-4` to `+5` (and `7`). ``` 0^cmp('','_')&3+1/~9*2-[-[-[[]==[]][[]==[[]]]][[]==[[]]]-[-[[]==[]][[]==[[]]]][[]==[[]]]-[-[[]==[]][[]==[[]]]][[]==[[]]]-[-[[]==[]][[]==[[]]]][[]==[[]]]-[-[[]==[]][[]==[[]]]][[]==[[]]]][[]==[[]]]|6<<7<<7>>8>>8and 5 ``` This is a snippet with the following prefix snippets: ``` # -1 cmp(cmp,()) # +3 = (-1) & 3 cmp(cmp,())&3 # +7 = 3 + 4 cmp(cmp,())&3+4 # +2 = 3 + (-1) = 3 + floor(4/-10) cmp(cmp,())&3+4/~9 # +1 = 3 + (-2) = 3 + 2*floor(4/-10) cmp(cmp,())&3+4/~9*2 # -4 = 1 - 5 cmp(cmp,())&3+4/~9*2-1-1-1-1-1 # -2 = (-4) | 6 cmp(cmp,())&3+4/~9*2-1-1-1-1-1|6 # -3 = (-4) | 1 = (-4) | floor(6/4) = (-4) | (6>>2) cmp(cmp,())&3+4/~9*2-1-1-1-1-1|6<<7<<7>>8>>8 # 0 = -3 and 0 cmp(cmp,())&3+4/~9*2-1-1-1-1-1|6<<7<<7>>8>>8and 0 # +5 = -3 and 05 cmp(cmp,())&3+4/~9*2-1-1-1-1-1|6<<7<<7>>8>>8and 05 # +4 = 5 ^ 1 cmp(cmp,())&3+4/~9*2-1-1-1-1-1|6<<7<<7>>8>>8and 05^True ``` [Try it online!](https://tio.run/##nVRtb9owEP68/IoblYoNCeAk0C1q@bg/sH1DdDLgqN6CE8XOVLRuf53d5YWSCgl1SqKc757n8fl05@LgnnITHncqBbvNS8WKUqX6WVmeeAClslXmLDzAb/VLZm2QQ5qX0NigDXSUPzXDVaWBNMulY5kyrJXgo1HEYQq22jO5sQzVKtUI1SbpdFDPo3S0/Y4RvetntH2qzE9KqPOukjW6SUf7BakoU@1VKZ1iDbamNYiD/3wJsdJjkax9wB@CP7TOwxp3OdmTzLpSF6zgqKaNU6VVW6dzQ7msrHJMcrgFMjbNsSRt1aZL683ZWqcgPz5sKHM0Te5AmgPrybZpt/X8VlYK1yqzquf/ItHjw3A4@ZFrw/ayYK3t99WwqF3FMOHBYHC8gUB4233B8PMZAm5gHGGMBYJOEp3HbiOK3mE0gjHE/dA4pmDYBmt6Y2IT5CWLp4GY8beU6d/PxBInVtixwtEV3ihEZhAjXEAA84uIQHQPYcP6WDGHF1hcgb8siBC9EsSr2eS1mNaptj62WC5DflX0/v4O3@XyE764AcxQAXeRZgezd5EbBlZufqYwf7/EnDSohnN4BPEf/EdqySM20qQZDD6xRaZdpo2yjK9EkoRr6jlsQxh@zbOK@hCHGuqhTob@hQE/wekmIsibK6nV87zL9w9NRqNwflkd/wE "Python 2 – Try It Online") [Answer] ## Batch, 176³/7744 = 704 ``` @cmd/cset/a%~z0-110 : !"#$&'()*+,.23456789;<=>?ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`bfghijklnopqruvwxy{|} ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ ``` The first prefix includes the colon and outputs the number -88. Subsequent prefixes output ascending numbers and the final program outputs 87. [Answer] # Pyth, \$(249^{3})/15500 = 996.0\$ ``` -C\|l"\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !#$%&\'()*+,./0123456789:;<=>?@ABDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijkmnopqrstuvwxyz{}~\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0¡¢£¤¥¦§¨©ª«¬\xad®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ ``` All of the escaped characters are single bytes - I've presented the program in this form for ease of copying and pasting. [This link](https://pyth.herokuapp.com/?code=-C%5C%7Cl%22%01%02%03%04%05%06%07%08%09%0A%0B%0C%0A%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20%21%23%24%25%26%27%28%29%2A%2B%2C.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABDEFGHIJKLMNOPQRSTUVWXYZ%5B%5D%5E_%60abcdefghijkmnopqrstuvwxyz%7B%7D~%C2%80%C2%81%C2%82%C2%83%C2%84%C2%85%C2%86%C2%87%C2%88%C2%89%C2%8A%C2%8B%C2%8C%C2%8D%C2%8E%C2%8F%C2%90%C2%91%C2%92%C2%93%C2%94%C2%95%C2%96%C2%97%C2%98%C2%99%C2%9A%C2%9B%C2%9C%C2%9D%C2%9E%C2%9F%20%C2%A1%C2%A2%C2%A3%C2%A4%C2%A5%C2%A6%C2%A7%C2%A8%C2%A9%C2%AA%C2%AB%C2%AC%C2%AD%C2%AE%C2%AF%C2%B0%C2%B1%C2%B2%C2%B3%C2%B4%C2%B5%C2%B6%C2%B7%C2%B8%C2%B9%C2%BA%C2%BB%C2%BC%C2%BD%C2%BE%C2%BF%C3%80%C3%81%C3%82%C3%83%C3%84%C3%85%C3%86%C3%87%C3%88%C3%89%C3%8A%C3%8B%C3%8C%C3%8D%C3%8E%C3%8F%C3%90%C3%91%C3%92%C3%93%C3%94%C3%95%C3%96%C3%97%C3%98%C3%99%C3%9A%C3%9B%C3%9C%C3%9D%C3%9E%C3%9F%C3%A0%C3%A1%C3%A2%C3%A3%C3%A4%C3%A5%C3%A6%C3%A7%C3%A8%C3%A9%C3%AA%C3%AB%C3%AC%C3%AD%C3%AE%C3%AF%C3%B0%C3%B1%C3%B2%C3%B3%C3%B4%C3%B5%C3%B6%C3%B7%C3%B8%C3%B9%C3%BA%C3%BB%C3%BC%C3%BD%C3%BE%C3%BF&debug=0) is to the full program without escaped characters; as can be seen there are a lot of placeholders for the unprintable characters used. The approach used is similar to [lirtosiast's TI-BASIC answer](https://codegolf.stackexchange.com/a/179757/41020), though I wrote my answer before browsing the other entries. The cord works as follows: ``` -C\|l"... \| "|" C Character code of the above, i.e. 124 - Subtract from the above... l"... ... the length of the trailing string - the closing quote is inferred ``` The string is made of every single-byte character other than 0 (NULL), 127 (backspace), and the boilerplate characters (`-C\|l"`). That way, each character of the string can be removed one at a time to produce strings of lengths 248 down to 0. These programs yield results in the range [-124 - 124], with sum of absolute values of 15500. The code was generated using [this program](https://pyth.herokuapp.com/?code=%2BJ%22-C%5C%5C%7Cl%5C%22%22sCM-U256%2BCMJ%2CZ127&debug=0): ``` +J"-C\\|l\""sCM-U256+CMJ,Z127 J"-C\\|l\"" Assign the boilerplate code to J CMJ Get the character code of each character in J + ,Z127 Append 0 and 127 -U256 Get values in range [0-256) which are not in the above CM Get each character with code points in the above s Concatenate into string +J Prepend boilerplate ``` And the sum of the numbers generated from each of the truncated programs was found with [this program](https://pyth.herokuapp.com/?code=sm.a.vd%3E._%2BJ%22-C%5C%5C%7Cl%5C%22%22sCM-U256%2BCMJ%2CZ127%205&debug=0): ``` sm.a.vd>._+J"-C\\|l\""sCM-U256+CMJ,Z127 5 +J"-C\\|l\""sCM-U256+CMJ,Z127 The full program string, as above ._ Get the prefixes of the above > 5 Discard the first 5 (those prefixes which don't include all the boilerplate code) m Map each of the above to: .vd Evaluate as Pyth code .a Take the absolute value of the above s Take the sum ``` [Answer] ## Python 2, \$11^3/53 = 25.1132075472\$ ``` 015-8*2+6/3&9%7if[]else 4^ord('\b') ``` Prefixes: ``` 0 # 0 01 # 1 015 # 13 (octal) 015-8 # 5 015-8*2 # -3 015-8*2+6 # 3 015-8*2+6/3 # -1 015-8*2+6/3&9 # 9 (-1 bitwise-AND 9 = 9) 015-8*2+6/3&9%7 # 2 015-8*2+6/3&9%7if[]else 4 # 4 015-8*2+6/3&9%7if[]else 4^ord('\b') # 12 (4 bitwise-XOR 8 -- OR would also work) ``` Not optimal, but the best I could personally find with this particular structure. [Answer] # Python 2 \$6^3/9 = 24\$ ``` False-False**0&1+[[]<[[]]][[]<[]]^~3>>2 ``` Here are the prefixes and what they output ``` 0 : False-False -1 : False-False**0 1 : False-False**0&1 2 : False-False**0&1+[[]<[[]]][[]<[]] -2 : False-False**0&1+[[]<[[]]][[]<[]]^~3 -3 : False-False**0&1+[[]<[[]]][[]<[]]^~3>>2 ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 40\$^3\$/400 = 160 ``` import StdEnv,Data.GenDefault,Gast.GenLibTest derive genShow G derive gDefault G n = sum[(bitnot o bitnot) one \\ n <-: s]-one-one-one-one-one-one-one-one-one-one-one-one-one-one-one-one-one-one-one-one-one s = (hd o show o d) undef d :: G -> G d g = gDefault{|*|} g :: G = GABCFHIJKMNOPQRUVWXYZcjkqxyz_0123456789` ``` [Try it online!](https://tio.run/##rZDbTsMwDIbv@xS@3NCKymEcKooEFMpgwKCcGYKsSduwxoEmHQzGqxPSDXgCLiz5@23r/@WkYASNkLQqGAjC0XDxLEsNsaa7OGqFRJP5iGHIUlIVuhURpWvu8sE5U9qhrOQjBhnDOJevEP0JPwdWQQhAVeKuMeAapQYJs6YJEhn0@4Cw4fqg7l3L/12Osu6NnFpXVQeUQJtQIWWpQ8H3IQJ3s04Nmd37Df0xmZt8QuZM5wFEW9s7e/udg8Oj45Pe6dnF5dX1zW3yNHx5G78/eAuLS8vtldW19UcTa2I/FwCaryQtSKaM2@macIxE8GQGvYLoVJZiCvUzjZubtueJbw "Clean – Try It Online") Defines `n` which produces `-20, -19, ..., 18, 19` depending on the length of the type `G`. The smallest prefix of `G` looks like `:: G = G`, preceded by the assorted imports and definitions. The largest prefix of `G` looks like `:: G = GABCFHIJKMNOPQRUVWXYZcjkqxyz_0123456789``, similarly preceded. [Answer] # [Japt](https://github.com/ETHproductions/japt), \$245^3/15006=980.0163268026123\$ ``` _Ê-122}$($"   !#%&')*+,./03456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^`abcdefghijklmnopqrstuvwxyz|~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ ``` [Try it online!](https://tio.run/##BcEDbgQAAATA1Ext27Zt27bt1LZt23aT3YddZ6oKG1oEgnxO2jo6OfWYWJgYCQmLiIqJS0hKScvIyskrKCopq6iqqWtoamnr6OrpGxgam5qZW1pZ29jZOzi7uLq5e3h6efv4@vkHBAYFh4SGhUdERkXHxMbFJyQmJaekpqVnZGZl5@Tk5hUUFhWXlJaVV1RWVdfU1tU3NDY1t7S2tXd0dnX39qEfAxjEEIYxglGMYRwTmMQUpjGDWcxhHgtYxBKWsYJVrGEdG9jEFraxg13sYR8HOMQRjnGCU5zhHBe4xBWucYNb3OEeD3jEE57xgle84R0f@MQXvvGDX/yxnwMc5BCHOcJRjnGcE5ziNGc4yznOc4GLXOIyV7jKNa5zg5vc4jZ3uMs97vOAhzziMU94yjOe84KXvOI1b3jLO97zgY984jNf@Mo3vvODn/ziN3/4yz@B4B8 "Japt – Try It Online") Like the other entries, uses the length of a string. Characters in the starting snippet, as well as `\r` (textareas don't play nice with this) and `{` (string interpolation character) are excluded from the string. First program is `_Ê-122}$($"`, each program is one character longer with the exception of when you add `\\`. [Answer] # Python 3, \$(6^{3})/12 = 18\$ ``` 0x1-2+3|True*~4 ``` This is a snippet. The individual prefix snippets are: ``` 0 # gives 0 0x1 # gives 1 (hex syntax) 0x1-2 # gives -1 (1 minus 2) 0x1-2+3 # gives 2 (-1 plus 3) 0x1-2+3|True # gives 3 (True == 1; 2 bitwise-OR 1 == 3) 0x1-2+3|True*~4 # gives -5 (~4 == -5; True*~4 == -5; 2|-5 == -5) ``` Python's bitwise operators treat negative integers as two's complement with unlimited `1`s to the right, so `-5` is treated as `...11111011`, which when ORed with `...000010` gives `...11111011` unchanged. [Answer] ## Excel, \$(6^{3})/12 = 18\$ ``` =0 0 =01 1 =01*2 2 =01*2-5 -3 =01*2-5+8 5 =01*2-5+8/4 -1 ``` `Prefix` challenge does not gel well with Excel's formula structure [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 1173/3422 = 468.034 ``` >"ul'B-$;   !#%&()*+,.:0123456789@<=?ACDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijkmnopqrstvwxyz{|}~€ ``` [Try it online!](https://tio.run/##KyrNy0z@/99OqTRH3UlXxZqRiZmFlY2dg5Obh49fQFBIWERUTFxCUkpaRlZOXkFRWVVNQ1NLW0fPysDQyNjE1MzcwtLBxtbe0dnF1c3dw9PL28fXzz8gMCg4JDQsPCIyKjomNi4@ITEpOSU1LT0jMys7Ny@/oLCouKSsvKKyqrqmtq7@UMP//wA "Runic Enchantments – Try It Online") [And the prefix](https://tio.run/##KyrNy0z@/99OqTRH3UlXxfr/fwA). Prints [-58,58] inclusive. Uses a similar tactic as other entries, using a progressively longer string, getting its length, subtracts `B` (decimal value of `66`), and prints the result. Uses a non-printing character (shown in the code block as `€` because apparently that's what `&#128;` evaluates to in HTML) in order to utilize byte value `0x80` (and consuming an otherwise unusable `0x00`) and score one more value. Only byte values up to 127 that can't be represented in any fashion are `10` and `13`, because they would cause the program to be two lines tall and not be read correctly by the instruction pointer. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~95³/2256 = 380.04211~~ 96³/2304 = 384 ``` I⁻⁴⁸L´´ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` The first prefix is the first 7 bytes and outputs the number `47`. [Try it online!](https://tio.run/##AR8A4P9jaGFyY29hbP//77yp4oG74oG04oG477yswrTCtP// "Charcoal – Try It Online") Subsequent prefixes output descending numbers and the final program outputs `-48`. [Try it online!](https://tio.run/##AX4Agf9jaGFyY29hbP//77yp4oG74oG04oG477yswrTCtCAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1@//8 "Charcoal – Try It Online") Edit: Increased score by 3.95789 thanks to @ASCII-only. ]
[Question] [ Given an integer `N` as input, output the `N`th permutapalindromic number. A permutapalindromic number is a strictly positive integer such that there is at least one permutation of its digits that results in a palindrome (i.e. a number that is its own reverse). For example, `117` is a permutapalindromic number since its digits can be permuted into `171`, which is a palindrome. We consider that numbers like `10` are not permutapalindromic numbers, even though `01 = 1` is a palindrome. We impose that the palindromic permutation must not have a leading zero (as such, `0` itself is not permutapalindromic). Numbers that are already palindromes are also permutapalindromic, since permuting nothing is valid. ### Inputs and outputs * `N` may be either 0-indexed or 1-indexed. Please indicate which of the two your answer uses. * The input can be taken through `STDIN`, as a function argument, or anything similar in your language of choice. The output can be written to `STDOUT`, returned from a function, or anything similar in your language of choice. * The input and output must be in the decimal base. ### Test cases The following test cases are 1-indexed. Your program must be able to pass any of the test cases presented here in at most 1 minute. ``` N Output 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 11 42 181 100 404 128 511 256 994 270 1166 ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~15~~ ~~14~~ 13 bytes Saved a byte thanks to **Emigna**! Code: ``` µNœvyJÂïÊP}_½ ``` Explanation: ``` µ # c = 0, when c is equal to the input, print N. N # Push N, the iteration variable. œ # Push all permutations of N. vyJ } # For each permutation...  # Bifurcate, which is short for duplicate and reverse. ï # Convert the seconds one to int, removing leading zeros. Q # Check if they are not equal. P # Product of the stack. _ # Logical not. ½ # Pop a value, if 1 then increase c by 1. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=wrVOxZN2eUrDgsOvw4pQfV_CvQ&input=MTI4). [Answer] # Brachylog, 19 bytes ``` ~l<:1at. .=pPrPl~l? ``` [Try it online!](http://brachylog.tryitonline.net/#code=fmw8OjFhdC4KLj1wUHJQbH5sPw&input=NDI&args=Wg) Takes about 17 seconds for `N = 270`. ### Explanation * Main predicate: ``` ~l Create a list whose length is Input. < The list is strictly increasing. :1a Apply predicate 1 to each element of the list. t. Output is the last element of the list. ``` * Predicate 1: ``` .= Input = Output = an integer pPrP A permutation P of the Output is its own reverse l~l? The length of P is equal to the length of the Input ``` [Answer] ## Pyth, 14 ``` e.ff&_ITshT.p` ``` [Try it here](http://pyth.herokuapp.com/?code=e.ff%26_ITshT.p%60&input=270&debug=0) or run a [Test Suite](http://pyth.herokuapp.com/?code=e.ff%26_ITshT.p%60&input=270&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A42%0A100%0A128%0A256%0A270&debug=0) ### Expansion: ``` e.ff&_ITshT.p`ZQ # Auto-fill variables .f Q # Find the first input number of numbers that give truthy on ... .p`Z # Take all the permutations of the current number f& # Keep those that give a truthy value for both: _IT # Invariance on reversing (is a palindrome) shT # The integer value of the first digit (doesn't start with zero) # A list with any values in it it truthy, so if any permutation matches # these conditions, the number was a permutapalindrome e # Take only the last number ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~21~~ 20 bytes **1 byte thanks to Fatalize.** Did you design the challenge for Brachylog? ``` :1yt. 0<.={@epcPrP!} ``` [Try it online!](http://brachylog.tryitonline.net/#code=OjF5dC4KMDwuPXtAZXBjUHJQIX0&input=Mjcw&args=Wg&debug=on) 270 takes about half a minute here. ``` Z = 1166 real 0m27.066s user 0m26.983s sys 0m0.030s Exit code: 0 ``` ### Predicate 0 (main predicate) ``` :1yt. :1y find the first Input solutions to predicate 1 t. unify the output with the last element ``` ### Predicate 1 (auxiliary predicate) ``` 0<.={@epcPrP!} 0<. 0 < Output .= Assign a value to Output (choice point) { } Inline predicate: @e Digits of the Output p A permutation (choice point) c Concatenate (fails if leading zero present) P store as P rP assert that P reversed is still P ! remove the choice point in this predicate, so that it will not return twice for the same number. ``` [Answer] ## JavaScript (ES6), 99 bytes ``` f=(n,i=1)=>(n-=/^.0+$/.test(i)</^((.),\2,)*(.)(,\3)?(,(.),\6)*$/.test([...i+''].sort()))?f(n,i+1):i ``` Explanation: ``` f=(n,i=1)=> look for n numbers starting at 1 (n-= test whether current guess is /^.0+$/.test(i)< not a round number and /^((.),\2,)* pairs of comma-separated digits (.)(,\3)? possible single digit (,(.),\6)*$/ pairs of comma-separated digits .test( matches the comma-joined [...i+''].sort())) digits in ascending order ?f(n,i+1) if not n numbers found try next number :i found it! ``` [Answer] # R, 145 bytes ``` g=function(n){d=b=0 while(d<n){b=b+1 if(sum(a<-table(strsplit(n<-as.character(b),""))%%2)==nchar(n)%%2&(!names(a)[1]==0|a[1]|sum(!a)>1))d=d+1} b} ``` ungolfed ``` f=function(b){ a<-table(strsplit(n<-as.character(b),""))%%2 sum(a)==nchar(n)%%2&(!names(a)[1]==0|a[1]|sum(!a)>1) } g=function(n){ d=b=0 while(d<n){ b=b+a if(f(b)) d=d+1 } b } ``` Essentially -- a function checking membership in permutapalindromic set, and a while loop incrementing until it finds the nth member. [Answer] # Python 2.7, ~~163~~ 154 bytes: ``` from itertools import*;I,F,Q=input(),[],2 while len(F)<I:F=[g for g in range(1,Q)if any(i==i[::-1]*(i[0]>'0')for i in permutations(`g`))];Q+=1 print F[-1] ``` Simple enough. Basically uses a `while` loop to repeatedly create arrays containing permutapalindromic numbers the the range `[1,Q)` until `Q` is large enough such that the array contains `Input` number of items. It then outputs the last element in that array. [Try It Online! (Ideone)](http://ideone.com/wOkRhR) [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 51 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) One-indexed. ``` {⍵⊃{⍵/⍨{(⍵≤9)∨(1<≢c~'0')∧1≥+/2|+⌿c∘.=∪c←⍕⍵}¨⍵}⍳5×⍵} ``` > > `{` a function where ⍵ represents the argument > > > > > > > `⍵⊃{` use the argument to pick from the result of the function > > > > > > > > > > > > `⍵/⍨{` filter the argument with the result of the function > > > > > > > > > > > > > > > > > `(⍵≤9)∨` the argument is less or equal to 9, OR > > > > > > > > > > > > `(1<≢c~'0')∧` there remains more than one digit when zeros are removed AND > > > > > > > > > > > > `1≥+/` 0 or 1 is the sum of > > > > > > > > > > > > `2|` the oddnesses of > > > > > > > > > > > > `+⌿` of the column sums of > > > > > > > > > > > > `c∘.=∪c` the comparison table of *c* and the unique elements of *c*, where *c*... > > > > > > > > > > > > `←⍕⍵` is the string representation of the argument > > > > > > > > > > > > > > > > > > > > > `}¨⍵` applied to each of the arguments > > > > > > > > > > > > > > > `}⍳5×⍵` applied to {1, 2, 3, ..., 5 times the argument} > > > > > > > > > `}` [end of function] > > > Finishes all the test cases instantly on [TryAPL](http://tryapl.org/?a=%7B%u2375%u2283%7B%u2375/%u2368%7B%28%u2375%u22649%29%u2228%281%3C%u2262c%7E%270%27%29%u22271%u2265+/2%7C+%u233Fc%u2218.%3D%u222Ac%u2190%u2355%u2375%7D%A8%u2375%7D%u23735%D7%u2375%7D%A81%202%203%204%205%206%207%208%209%2010%2042%20100%20128%20256%20270&run) [Answer] # JavaScript (ES6), 92 ``` n=>eval("for(a=0;n-=(a++<9||(b=[...a+``].sort().join``)>9&!b.replace(/(.)\\1/g,``)[1]););a") ``` *Less golfed* ``` n=>{ for( a = 0; n -= // decrement n (and exit when 0) if the check below is true == a is permutapalindromic (a ++ < 9 // single digit (meanwhile, increment a) || // or... ( b=[...a+``].sort().join`` )// build a string with the digits sorted > 9 // required at least 2 non zero digits & ! b.replace(/(.)\1/g,``)[1] // removed all digits pair, there must be just 1 or no single digits remaining ); ); return a; } ``` **Test** ``` f=n=>eval("for(a=0;n-=(a++<9||(b=[...a+``].sort().join``)>9&!b.replace(/(.)\\1/g,``)[1]););a") function update() { O.textContent=f(+I.value) } update() ``` ``` <input id=I oninput=update() type=number value=100> <pre id=O></pre> ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` _ì á fÎdêQ}iU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X%2bwg4SBmzmTqUX1pVQ&input=WwowCjEKMgozCjQKNQo2CjcKOAo5CjQxCjk5CjEyNwoyNTUKMjY5Cl0tbVI) 0-indexed ``` _ì á fÎdêQ}iU _ }iU # Find the N-th number that meets this condition: ì # Get the digits as an array á # Get all permutations of that array f # Keep only permutations where: Î # The first digit is not zero d # Return true if any remaining permutation: êQ # Is a palindrome ``` [Answer] # [Perl 6](http://perl6.org), 66 bytes ``` {(1..*).grep(*.comb.permutations.grep({+.join.flip eq.join}))[$_]} ``` 0 based ## Explanation: ``` # bare block lambda which takes an implicit parameter 「$_」 { # all numbers greater than 0 (1..*)\ # remove any which aren't permutapalindromic .grep( # 「*」 here starts a Whatever lambda *\ # split into list of digits .comb\ # get all of the permutations of the digits .permutations\ # find out if there are any palindromes .grep( # another bare block lambda taking 「$_」 as implicit parameter { # compare the current permutation with its reverse stringwise # numify only one side to get rid of leading 「0」 +$_.join.flip eq $_.join } ) # get the value at the index )[$_] } ``` ## Test: ``` #! /usr/bin/env perl6 use v6.c; use Test; my &permutapalindromic = {(1..*).grep(*.comb.permutations.grep({+.join.flip eq.join}))[$_]} my @tests = ( 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 7, 8 => 8, 9 => 9, 10 => 11, 42 => 181, 100 => 404, 128 => 511, 256 => 994, 270 => 1166, ); plan +@tests + 1; my $start-time = now; for @tests -> $_ ( :key($input), :value($expected) ) { # zero based instead of one based, so subtract 1 is-deeply permutapalindromic( $input - 1 ), $expected, .gist; } my $finish-time = now; my $total-time = $finish-time - $start-time; cmp-ok $total-time, &[<], 60, 'Less than 60 seconds for the tests'; diag "$total-time seconds"; ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) v2, 16 bytes ``` <~l<₁{≜.pX↔Xp}ᵐt ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w36Yux@ZRU2P1o845egURj9qmRBSAxEv@/4821DHSMdYx0THVMdMx17HQsdQxNNAxMQKSBjqGRhY6RqZmOkbmBrEA "Brachylog – Try It Online") Borrows Fatalize's `~l` trick because my attempt at a `ᵘ`-based solution is a bit too slow... ``` < The input is less than ~l the length of some list <₁ which is strictly increasing { }ᵐ where each element: ≜. is an integer chosen such that pX some permutation X ↔X is X reversed, p a permutation of which is the element. t Output the final element of that list. ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~10~~ 9 bytes ``` SṖ'Ṙ⌊=)ȯt ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBQiIsIiIsIlPhuZYn4bmY4oyKPSnIr3QiLCIiLCIxICBcbjIgIFxuMyAgXG40ICBcbjUgIFxuNiAgXG43ICBcbjggIFxuOSAgXG4xMCBcbjQyIFxuMTAwXG4xMjhcbjI1NlxuMjcwIl0=) You say any test case presented in the challenge should pass in under a minute? *All* test cases presented in the challenge pass in under 30 seconds. That's what I call gaming (no doubt the other answers do too though lol). ## Explained ``` SṖ'Ṙ⌊=)ȯt )ȯ # Starting at 1, get the first (input)th numbers where: SṖ # From the permutation of the digits of the number, ' # There exists at least 1 such that: Ṙ⌊ # The reverse (cast to int) = # Equals that permutation t # Print the tail of the list ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), 15 bytes ``` :vdṙ= ṙf↑¦Σ ↑#) ``` [Try it online!](https://tio.run/##S0/MTPz/36os5eHOmbZcQCLtUdvEQ8vOLeYC0sqa//@bGAEA "Gaia – Try It Online") First ever code golf, so please tell me if I'm doing anything wrong. ## Explained ``` :vdṙ= # Helper function 2 (hf2) : # Push two copies of the function argument vdṙ # str(int(argument[::-1])) = # does that equal the original function argument? ----- ṙf↑¦Σ # Helper function 1 (hf1) ṙf # Get all permutations of the string representation of the function argument ↑¦ # Map hf2 to each item Σ # and summate the result ----- ↑#) # Main function ↑# # First (input) items where hf1 is true ) # get the last item of that ``` [Answer] # Javascript (using external library - Enumerable) (142 bytes) ``` n=>_.Sequence(n,i=>{l=i+"";p=_.Permutations(_.From(l),l.length).Any(y=>y.First()!="0"&&y.SequenceEqual(y.Reverse()));if(p){return i;}}).Last() ``` Link to lib:<https://github.com/mvegh1/Enumerable/> Code explanation: \_.Sequence creates an enumerable for a count of "n" elements, based on the predicate of signature ("i"teration~~,"a"ccumulated array~~). Cast the current iteration to a string, and create an enumerable of all permutations from it. Test if any of the permutations satisfy the test of not starting with "0" and that the reversal of the permutation equals the permutation. Return the last element in the sequence because that is the desired output as per OP [![enter image description here](https://i.stack.imgur.com/qs3nr.png)](https://i.stack.imgur.com/qs3nr.png) [Answer] ## Python 2, 93 bytes ``` S=sorted f=lambda n,i=1:n and-~f(n-(S(`i`)in[S(`k`)for k in range(9*i)if`k`==`k`[::-1]]),i+1) ``` 1-indexed. Depending on your system, the last test case may exceed the allowed recursion depth. Does not compute permutations. Instead, uses the fact that two strings are permutations if they are equal when sorted. To test if a number is permutapalindromic, checks if its sorted digits equal the sorted digits of any palindrome up to a bound. --- **96 bytes:** ``` f=lambda n,i=1:n and-~f(n-(sum(`i`.count(`d`)%2for d in range(10))<2*(set(`i`[1:])!={'0'})),i+1) ``` 1-indexed. Depending on your system, the last test case may exceed the allowed recursion depth. This doesn't look at permutations and instead uses the following characterization: > > A number is *permutapalindromic* exactly when > > > * At most one of its digits appears an odd number of times, and > * It does not have the form d00...00 with one or more zeroes. > > > This is true because a palindrome must pair off digits from the start and end, except for a possible center digit. The exception comes from the requirement that the leading digit be nonzero, and so some nonzero digit must appear twice unless the number is single-digit. [Answer] # Haskell, ~~89~~ 87 bytes ``` import Data.List (filter(any(show.floor.read.reverse>>=(==)).permutations.show)[0..]!!) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` 1DŒ!ŒḂ×ḢƊ€ẸƲ#Ṫ ``` [Try it online!](https://tio.run/##ASoA1f9qZWxsef//MUTFkiHFkuG4gsOX4biixorigqzhurjGsiPhuar///8yNzA "Jelly – Try It Online") ## How it works ``` 1DŒ!ŒḂ×ḢƊ€ẸƲ#Ṫ - Main link. Takes an argument n on the left Ʋ - Group the previous 4 links into a monad f(k): D - Convert k to digits Œ! - Permutations of k's digits Ɗ€ - Over each permutation p: ŒḂ - Is p a palindrome? ×Ḣ - And is the first digit non-zero? Ẹ - Is that true for any permutation? 1 # - Count up k = 1, 2, 3, ... until n k return true under f(k) Return those k Ṫ - Return the n'th k ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 69 bytes ``` 1while$_-=(join'',sort++$\=~/./g)=~s/(.)\1//gr=~y///c<2*$\!~/^.0+$/}{ ``` [Try it online!](https://tio.run/##BcHdCkAwGAbga1ErP2MvSk7sThYHEpNsbStJduk@z2MXd3REzbXpY2FTJbPd6DNNS29c4JwpGSGw5jJ6ZCJXDbA6GW8A89AWTCURo6g5w/sQtX39GRu0OT1V9gc "Perl 5 – Try It Online") [Answer] # [Python](https://python.org) + [`golfing-shortcuts`](https://github.com/nayakrujul/golfing-shortcuts), 128 bytes A port of [R. Kap's answer](https://codegolf.stackexchange.com/a/90122/114446). ``` from s import* I,F,Q=e(i()),[],2 while l(F)<I:F=[G for G in r(1,Q)if a(I==I[::-1]*(I[0]>'0')for I in Im(repr(G)))];Q+=1 p(F[-1]) ``` [Answer] **C, 254 bytes** ``` #define W while #define R return f(j){int c=0,a[16]={0};do++a[j%10],++c;W(j/=10);if(c>1&&a[0]>=c-1)R 0;c%=2;W(j<10)if(a[j++]%2&&(!c||++c>2))R 0;R 1;}g(n){int k=0,i=1;W(k<n)if(f(i++))++k;R i-1;}main(a){printf("N>");scanf("%d",&a);printf("%d\n",g(a));} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` Dœ^/LỊaṢ-ịø#Ṫ ``` [Try it online!](https://tio.run/##ASQA2/9qZWxsef//RMWTXi9M4buKYeG5oi3hu4vDuCPhuar///8yNzA "Jelly – Try It Online") Out of curiosity, I decided to see how far I could get without actually computing permutations, and two hours of head bashing later it ties caird's existing answer (modulo a golf to use `ø`). The logic boils down to checking two conditions: * At most one digit occurs an odd number of times. * There must be multiple nonzero digits if at least one digit is zero. and stuck in a blender for five minutes on high, that's: ``` # Count up collecting the first n integers ø starting from 0 which satisfy: D Do the digits œ^/ reduced by symmetric multiset difference LỊ have length ≤ 1? Ṣ Sort the digits, a replace them all with 0 if the previous condition is not met, -ị and take the second to last element (wrapping around if length 1), # succeeding if it's nonzero. Ṫ Return the last result. ``` ]
[Question] [ Given a string as input, output the US state whose capital it is if it is a state capital, the capital of the state if it is a state, or `Arstotzka` if it is neither. Examples: ``` Austin -> Texas Alaska -> Juneau The Nineteenth Byte -> Arstotzka ``` All the capitals and their respective states: ``` Baton Rouge, Louisiana Indianapolis, Indiana Columbus, Ohio Montgomery, Alabama Helena, Montana Denver, Colorado Boise, Idaho Austin, Texas Boston, Massachusetts Albany, New York Tallahassee, Florida Santa Fe, New Mexico Nashville, Tennessee Trenton, New Jersey Jefferson, Missouri Richmond, Virginia Pierre, South Dakota Harrisburg, Pennsylvania Augusta, Maine Providence, Rhode Island Dover, Delaware Concord, New Hampshire Montpelier, Vermont Hartford, Connecticut Topeka, Kansas Saint Paul, Minnesota Juneau, Alaska Lincoln, Nebraska Raleigh, North Carolina Madison, Wisconsin Olympia, Washington Phoenix, Arizona Lansing, Michigan Honolulu, Hawaii Jackson, Mississippi Springfield, Illinois Columbia, South Carolina Annapolis, Maryland Cheyenne, Wyoming Salt Lake City, Utah Atlanta, Georgia Bismarck, North Dakota Frankfort, Kentucky Salem, Oregon Little Rock, Arkansas Des Moines, Iowa Sacramento, California Oklahoma City, Oklahoma Charleston, West Virginia Carson City, Nevada ``` ### Rules * No built-ins or libraries/modules that provide a mapping from states to capitals or capitals to states, or lists of capitals and/or states (for example, Mathematica's `CityData` built-in) * Standard loopholes apply * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! # Leaderboard The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 64254; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] # Python3, 997 bytes ``` i=input() s="Baton Rouge,Louisiana,Indianapolis,Indiana,Columbus,Ohio,Montgomery,Alabama,Helena,Montana,Denver,Colorado,Boise,Idaho,Austin,Texas,Boston,Massachusetts,Albany,New York,Tallahassee,Florida,Santa Fe,New Mexico,Nashville,Tennessee,Trenton,New Jersey,Jefferson,Missouri,Richmond,Virginia,Pierre,South Dakota,Harrisburg,Pennsylvania,Augusta,Maine,Providence,Rhode Island,Dover,Delaware,Concord,New Hampshire,Montpelier,Vermont,Hartford,Connecticut,Topeka,Kansas,Saint Paul,Minnesota,Juneau,Alaska,Lincoln,Nebraska,Raleigh,North Carolina,Madison,Wisconsin,Olympia,Washington,Phoenix,Arizona,Lansing,Michigan,Honolulu,Hawaii,Jackson,Mississippi,Springfield,Illinois,Columbia,South Carolina,Annapolis,Maryland,Cheyenne,Wyoming,Salt Lake City,Utah,Atlanta,Georgia,Bismarck,North Dakota,Frankfort,Kentucky,Salem,Oregon,Little Rock,Arkansas,Des Moines,Iowa,Sacramento,California,Oklahoma City,Oklahoma,Charleston,West Virginia,Carson City,Nevada,Arstotzka".split(",")+[i] print(s[1^s.index(i)]) ``` I can not be bothered to do the base-conversion or binary packing that the winning version will undoubtly do, but I do want to post this to show a really cool trick. XOR'ing a number by 1 is equivalent to adding 1 if the number is even, or subtracting 1 if the number is odd. You can make really easy and golfy bi-directional maps using this trick. [Answer] # CJam, ~~625~~ ~~609~~ ~~603~~ 599 bytes ``` 00000000: 22 05 77 c6 fa 94 29 be 77 9b 88 35 9b e0 86 05 86 ".w...).w..5..... 00000011: 8a d3 cd 53 e6 97 c1 20 f4 bd b5 76 f3 f7 14 ab 4b ...S... ...v....K 00000022: fa 8e 4d 2c be 71 4d 13 ca 9c 67 3e 35 21 76 6b 74 ..M,.qM...g>5!vkt 00000033: f8 88 8b c1 bc 2a ab da 6b ba 1f 2b a3 2c 12 bc d1 .....*..k..+.,... 00000044: b8 c3 b6 7c b0 4d 0f 11 a2 dc 15 a2 94 45 39 1c 20 ...|.M.......E9. 00000055: 12 08 03 a3 5c 71 d9 11 1c 56 f5 c2 2d cb 63 64 b3 ....\q...V..-.cd. 00000066: c0 d8 e7 e3 9b 82 28 85 57 2b e4 28 ea 8f 17 02 1d ......(.W+.(..... 00000077: a8 8f f3 0e 31 5f 8e c4 2b b3 8f 7e b2 64 fc d2 99 ....1_..+..~.d... 00000088: dc 9d 98 e5 3a b3 8b 59 52 5f 63 5a ae c9 3d 8a 7a ....:..YR_cZ..=.z 00000099: b6 a2 0a 8a 2f 4c 43 78 fa 56 9b 07 ce 21 3a 2f 50 ..../LCx.V...!:/P 000000aa: 5e d3 f3 a9 90 ad 21 85 75 cd 9e 07 29 a3 3d b7 c2 ^.....!.u...).=.. 000000bb: cd f4 b8 5f 60 b4 72 cd 47 93 17 14 28 3e da b1 65 ..._`.r.G...(>..e 000000cc: 90 ec 5f 35 4d c6 0e b1 66 40 af 8a 67 95 47 f8 8f [[email protected]](/cdn-cgi/l/email-protection).. 000000dd: fd 38 66 c8 df fd 51 6c 5f 06 06 35 a1 77 ae 93 84 .8f...Ql_..5.w... 000000ee: 73 33 63 be 98 3e 1c f3 43 de ca 0a 13 6d e9 64 52 s3c..>..C....m.dR 000000ff: 96 b8 41 e8 db 23 a6 01 c5 60 38 db 63 9c 2a d9 5d ..A..#...`8.c.*.] 00000110: 03 fc 38 c8 94 1e 2f 70 8e 4d 0f 93 44 4a 6c 57 e8 ..8.../p.M..DJlW. 00000121: af cc e7 e2 70 82 84 a3 06 d3 2a 4f cd 8b b6 68 a5 ....p.....*O...h. 00000132: 80 98 9e 49 4f bc fd 91 20 55 a6 66 12 1d c0 49 f2 ...IO... U.f...I. 00000143: 3e 9e ef 5d 89 bc b3 30 ef dd cc ca 93 70 27 2c 14 >..]...0.....p',. 00000154: 03 6a 53 32 ef af e1 b5 d3 5a cc 3e fd 1d 78 a5 b3 .jS2.....Z.>..x.. 00000165: 06 ae 67 58 ec e4 7a 99 16 f5 da a7 1e 51 0a 94 fc ..gX..z......Q... 00000176: cd e9 e8 fe 5a d1 bc 0f bb 24 9d 45 9a ac 97 58 a7 ....Z....$.E...X. 00000187: 9b ea f0 77 89 e8 a1 fa e7 83 2c b9 ea 5c a7 f1 b3 ...w......,..\... 00000198: 76 ba 97 fb 41 b7 74 9a 09 2d 96 97 73 80 13 17 7a v...A.t..-..s...z 000001a9: fe 15 5f c6 cf 89 3d 7f df 54 cd 16 fe 8a ea d7 0a .._...=..T....... 000001ba: 91 84 54 61 4f 03 87 a6 d2 1c c8 a9 b8 0f 52 2e 39 ..TaO.........R.9 000001cb: 13 2e 48 8b 04 ce 2d 35 5e 02 96 63 11 a7 f8 75 6d ..H...-5^..c...um 000001dc: 8a e2 13 e2 d6 1b f9 43 07 3e 99 29 a9 69 7f f5 6a .......C.>.).i..j 000001ed: 72 15 7b 92 5b 26 cb 74 48 1b c0 fc fb 64 45 05 2d r.{.[&.tH....dE.- 000001fe: 37 d6 21 6a d9 83 88 13 fb e7 e8 f2 17 c7 54 de 48 7.!j..........T.H 0000020f: f6 23 1e bf b0 34 f5 4f 63 ce 46 40 a9 16 e7 4a 60 .#[[email protected]](/cdn-cgi/l/email-protection)` 00000220: 71 ce a3 d3 6a 15 4c 8b 52 d6 3f cb 53 dd 96 97 10 q...j.L.R.?.S.... 00000231: f6 e5 22 32 35 36 62 32 37 62 27 60 66 2b 27 60 2f .."256b27b'`f+'`/ 00000242: 7b 27 71 2f 33 32 61 66 2e 5e 53 2a 7d 25 5f 71 61 {'q/32af.^S*}%_qa 00000253: 23 7e 28 3d #~(= ``` The above hexdump can be reversed with `xxd -r -c 17`. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%22%05w%C3%86%C3%BA%C2%94)%C2%BEw%C2%9B%C2%885%C2%9B%C3%A0%C2%86%05%C2%86%C2%8A%C3%93%C3%8DS%C3%A6%C2%97%C3%81%20%C3%B4%C2%BD%C2%B5v%C3%B3%C3%B7%14%C2%ABK%C3%BA%C2%8EM%2C%C2%BEqM%13%C3%8A%C2%9Cg%3E5!vkt%C3%B8%C2%88%C2%8B%C3%81%C2%BC*%C2%AB%C3%9Ak%C2%BA%1F%2B%C2%A3%2C%12%C2%BC%C3%91%C2%B8%C3%83%C2%B6%7C%C2%B0M%0F%11%C2%A2%C3%9C%15%C2%A2%C2%94E9%1C%20%12%08%03%C2%A3%5Cq%C3%99%11%1CV%C3%B5%C3%82-%C3%8Bcd%C2%B3%C3%80%C3%98%C3%A7%C3%A3%C2%9B%C2%82(%C2%85W%2B%C3%A4(%C3%AA%C2%8F%17%02%1D%C2%A8%C2%8F%C3%B3%0E1_%C2%8E%C3%84%2B%C2%B3%C2%8F~%C2%B2d%C3%BC%C3%92%C2%99%C3%9C%C2%9D%C2%98%C3%A5%3A%C2%B3%C2%8BYR_cZ%C2%AE%C3%89%3D%C2%8Az%C2%B6%C2%A2%0A%C2%8A%2FLCx%C3%BAV%C2%9B%07%C3%8E!%3A%2FP%5E%C3%93%C3%B3%C2%A9%C2%90%C2%AD!%C2%85u%C3%8D%C2%9E%07)%C2%A3%3D%C2%B7%C3%82%C3%8D%C3%B4%C2%B8_%60%C2%B4r%C3%8DG%C2%93%17%14(%3E%C3%9A%C2%B1e%C2%90%C3%AC_5M%C3%86%0E%C2%B1f%40%C2%AF%C2%8Ag%C2%95G%C3%B8%C2%8F%C3%BD8f%C3%88%C3%9F%C3%BDQl_%06%065%C2%A1w%C2%AE%C2%93%C2%84s3c%C2%BE%C2%98%3E%1C%C3%B3C%C3%9E%C3%8A%0A%13m%C3%A9dR%C2%96%C2%B8A%C3%A8%C3%9B%23%C2%A6%01%C3%85%608%C3%9Bc%C2%9C*%C3%99%5D%03%C3%BC8%C3%88%C2%94%1E%2Fp%C2%8EM%0F%C2%93DJlW%C3%A8%C2%AF%C3%8C%C3%A7%C3%A2p%C2%82%C2%84%C2%A3%06%C3%93*O%C3%8D%C2%8B%C2%B6h%C2%A5%C2%80%C2%98%C2%9EIO%C2%BC%C3%BD%C2%91%20U%C2%A6f%12%1D%C3%80I%C3%B2%3E%C2%9E%C3%AF%5D%C2%89%C2%BC%C2%B30%C3%AF%C3%9D%C3%8C%C3%8A%C2%93p'%2C%14%03jS2%C3%AF%C2%AF%C3%A1%C2%B5%C3%93Z%C3%8C%3E%C3%BD%1Dx%C2%A5%C2%B3%06%C2%AEgX%C3%AC%C3%A4z%C2%99%16%C3%B5%C3%9A%C2%A7%1EQ%0A%C2%94%C3%BC%C3%8D%C3%A9%C3%A8%C3%BEZ%C3%91%C2%BC%0F%C2%BB%24%C2%9DE%C2%9A%C2%AC%C2%97X%C2%A7%C2%9B%C3%AA%C3%B0w%C2%89%C3%A8%C2%A1%C3%BA%C3%A7%C2%83%2C%C2%B9%C3%AA%5C%C2%A7%C3%B1%C2%B3v%C2%BA%C2%97%C3%BBA%C2%B7t%C2%9A%09-%C2%96%C2%97s%C2%80%13%17z%C3%BE%15_%C3%86%C3%8F%C2%89%3D%7F%C3%9FT%C3%8D%16%C3%BE%C2%8A%C3%AA%C3%97%0A%C2%91%C2%84TaO%03%C2%87%C2%A6%C3%92%1C%C3%88%C2%A9%C2%B8%0FR.9%13.H%C2%8B%04%C3%8E-5%5E%02%C2%96c%11%C2%A7%C3%B8um%C2%8A%C3%A2%13%C3%A2%C3%96%1B%C3%B9C%07%3E%C2%99)%C2%A9i%7F%C3%B5jr%15%7B%C2%92%5B%26%C3%8BtH%1B%C3%80%C3%BC%C3%BBdE%05-7%C3%96!j%C3%99%C2%83%C2%88%13%C3%BB%C3%A7%C3%A8%C3%B2%17%C3%87T%C3%9EH%C3%B6%23%1E%C2%BF%C2%B04%C3%B5Oc%C3%8EF%40%C2%A9%16%C3%A7J%60q%C3%8E%C2%A3%C3%93j%15L%C2%8BR%C3%96%3F%C3%8BS%C3%9D%C2%96%C2%97%10%C3%B6%C3%A5%22256b27b'%60f%2B'%60%2F%7B'q%2F32af.%5ES*%7D%25_qa%23)~%3D&input=Indiana). ### Idea We encode the required information as follows: ``` columbia`columbus`frankfort`olympia`desqmoines`jefferson`springfield`carsonqcity`topeka`sacramento`littleqrock`saltqlakeqcity`boston`trenton`batonqrouge`indianapolis`madison`charleston`austin`denver`hartford`santaqfe`atlanta`augusta`boise`oklahomaqcity`dover`helena`tallahassee`richmond`lansing`honolulu`saintqpaul`salem`providence`raleigh`cheyenne`nashville`concord`albany`bismarck`phoenix`jackson`montpelier`montgomery`harrisburg`juneau`pierre`annapolis`lincoln`nebraska`maryland`southqdakota`alaska`pennsylvania`alabama`vermont`mississippi`arizona`northqdakota`newqyork`newqhampshire`tennessee`wyoming`northqcarolina`rhodeqisland`oregon`minnesota`hawaii`michigan`virginia`florida`montana`delaware`oklahoma`idaho`maine`georgia`newqmexico`connecticut`colorado`texas`westqvirginia`wisconsin`indiana`louisiana`newqjersey`massachusetts`utah`arkansas`california`kansas`nevada`illinois`missouri`iowa`washington`kentucky`ohio`southqcarolina`arstotzka ``` All the names have been cast to lowercase, spaces have been replaced with q's, and names are separated by backticks. All capitals are listed first (in an order that managed to minimize the byte count). Then the corresponding states are listed in reverse order. Finally, *Arstotzka* is appended. This way, the capital/state at index **i** corresponds to the state/capital at index **-(x+2)**. Also, an invalid input will either have index **100** (*Arstotzka*) or **-1** (not found), and **-(100+2) ≡ -1 ≡ -(-1+2) mod 101**. This layout prevents *Arstotzka* from being a special case, without prepending or appending anything to the list. To compress the information, we subtract 97 (code point of ```) from each character in the string and convert the result from base 27 to base 256. Decoding is straightforward: we go back from base 256 to base 27, add the resulting base-27 digits to the backtick character, replace q's with spaces, and capitalize the first letter of each resulting word. ### Code ``` "…" e# Push a string of 562 characters. 256b27b e# Convert it from base 256 to base 27. '`f+ e# Add each base-27 digit to the character '`'. '`/ e# Split at occurrences of '`'. { e# For each resulting chunk: 'q/ e# Split at occurrences of 'q'. 32a e# Push [32]. f.^ e# For each chunk, perform vectorized XOR with 32. e# This capitalizes the first character of the chunk. S* e# Join the chunks, separating by spaces. }% e# _ e# Push a copy of the resulting array. qa e# Read all user input and wrap it in an array. # e# Find its index (i) in the copy. ~( e# Apply bitwise NOT and decrements to calculate e# ~i - 1 = -(i + 1) - 1 = -(i + 2). = e# Retrieve element at the corresponding index. ``` [Answer] # Pyth, ~~597~~ ~~596~~ 590 ``` 00000000: 40 4a 63 72 58 73 40 4c 2b 62 47 6a 43 22 05 77 c6 @JcrXs@L+bGjC".w. 00000011: fa 94 29 be 77 9b 88 35 9b e0 86 05 86 8a d3 cd 53 ..).w..5........S 00000022: e6 97 c1 20 f4 bd b5 76 f3 f7 14 ab 4b fa 8e 4d 2c ... ...v....K..M, 00000033: be 71 4d 13 ca 9c 67 3e 35 21 76 6b 74 f8 88 8b c1 .qM...g>5!vkt.... 00000044: bc 2a ab da 6b ba 1f 2b a3 2c 12 bc d1 b8 c3 b6 7c .*..k..+.,......| 00000055: b0 4d 0f 11 a2 dc 15 a2 94 45 39 1c 20 12 08 03 a3 .M.......E9. .... 00000066: 5c 71 d9 11 1c 56 f5 c2 2d cb 63 64 b3 c0 d8 e7 e3 \q...V..-.cd..... 00000077: 9b 82 28 85 57 2b e4 28 ea 8f 17 02 1d a8 8f f3 0e ..(.W+.(......... 00000088: 31 5f 8e c4 2b b3 8f 7e b2 64 fc d2 99 dc 9d 98 e5 1_..+..~.d....... 00000099: 3a b3 8b 59 52 5f 63 5a ae c9 3d 8a 7a b6 a2 0a 8a :..YR_cZ..=.z.... 000000aa: 2f 4c 43 78 fa 56 9b 07 ce 21 3a 2f 50 5e d3 f3 a9 /LCx.V...!:/P^... 000000bb: 90 ad 21 85 75 cd 9e 07 29 a3 3d b7 c2 cd f4 b8 5f ..!.u...).=....._ 000000cc: 60 b4 72 cd 47 93 17 14 28 3e da b1 65 90 ec 5f 35 `.r.G...(>..e.._5 000000dd: 4d c6 0e b1 66 40 af 8a 67 95 47 f8 8f fd 38 66 c8 [[email protected]](/cdn-cgi/l/email-protection). 000000ee: df fd 51 6c 5f 06 06 35 a1 77 ae 93 84 73 33 63 be ..Ql_..5.w...s3c. 000000ff: 98 3e 1c f3 43 de ca 0a 13 6d e9 64 52 96 b8 41 e8 .>..C....m.dR..A. 00000110: db 23 a6 01 c5 60 38 db 63 9c 2a d9 5d 03 fc 38 c8 .#...`8.c.*.]..8. 00000121: 94 1e 2f 70 8e 4d 0f 93 44 4a 6c 57 e8 af cc e7 e2 ../p.M..DJlW..... 00000132: 70 82 84 a3 06 d3 2a 4f cd 8b b6 68 a5 80 98 9e 49 p.....*O...h....I 00000143: 4f bc fd 91 20 55 a6 66 12 1d c0 49 f2 3e 9e ef 5d O... U.f...I.>..] 00000154: 89 bc b3 30 ef dd cc ca 93 70 27 2c 14 03 6a 53 32 ...0.....p',..jS2 00000165: ef af e1 b5 d3 5a cc 3e fd 1d 78 a5 b3 06 ae 67 58 .....Z.>..x....gX 00000176: ec e4 7a 99 16 f5 da a7 1e 51 0a 94 fc cd e9 e8 fe ..z......Q....... 00000187: 5a d1 bc 0f bb 24 9d 45 9a ac 97 58 a7 9b ea f0 77 Z....$.E...X....w 00000198: 89 e8 a1 fa e7 83 2c b9 ea 5c a7 f1 b3 76 ba 97 fb ......,..\...v... 000001a9: 41 b7 74 9a 09 2d 96 97 73 80 13 17 7a fe 15 5f c6 A.t..-..s...z.._. 000001ba: cf 89 3d 7f df 54 cd 16 fe 8a ea d7 0a 91 84 54 61 ..=..T.........Ta 000001cb: 4f 03 87 a6 d2 1c c8 a9 b8 0f 52 2e 39 13 2e 48 8b O.........R.9..H. 000001dc: 04 ce 2d 35 5e 02 96 63 11 a7 f8 75 6d 8a e2 13 e2 ..-5^..c...um.... 000001ed: d6 1b f9 43 07 3e 99 29 a9 69 7f f5 6a 72 15 7b 92 ...C.>.).i..jr.{. 000001fe: 5b 26 cb 74 48 1b c0 fc fb 64 45 05 2d 37 d6 21 6a [&.tH....dE.-7.!j 0000020f: d9 83 88 13 fb e7 e8 f2 17 c7 54 de 48 f6 23 1e bf ..........T.H.#.. 00000220: b0 34 f5 4f 63 ce 46 40 a9 16 e7 4a 60 71 ce a3 d3 [[email protected]](/cdn-cgi/l/email-protection)`q... 00000231: 6a 15 4c 8b 52 d6 3f cb 53 dd 96 97 10 f6 e5 22 32 j.L.R.?.S......"2 00000242: 37 5c 71 64 33 62 5f 68 68 78 4a 7a 7\qd3b_hhxJz ``` The above hexdump can be reversed with `xxd -r -c 17`. Try it online in the [Pyth Compiler](https://pyth.herokuapp.com/?code=%40JcrXs%40L%2BbGjC%22%05w%C3%86%C3%BA%C2%94%29%C2%BEw%C2%9B%C2%885%C2%9B%C3%A0%C2%86%05%C2%86%C2%8A%C3%93%C3%8DS%C3%A6%C2%97%C3%81+%C3%B4%C2%BD%C2%B5v%C3%B3%C3%B7%14%C2%ABK%C3%BA%C2%8EM%2C%C2%BEqM%13%C3%8A%C2%9Cg%3E5%21vkt%C3%B8%C2%88%C2%8B%C3%81%C2%BC%2a%C2%AB%C3%9Ak%C2%BA%1F%2B%C2%A3%2C%12%C2%BC%C3%91%C2%B8%C3%83%C2%B6%7C%C2%B0M%0F%11%C2%A2%C3%9C%15%C2%A2%C2%94E9%1C+%12%08%03%C2%A3%5Cq%C3%99%11%1CV%C3%B5%C3%82-%C3%8Bcd%C2%B3%C3%80%C3%98%C3%A7%C3%A3%C2%9B%C2%82%28%C2%85W%2B%C3%A4%28%C3%AA%C2%8F%17%02%1D%C2%A8%C2%8F%C3%B3%0E1_%C2%8E%C3%84%2B%C2%B3%C2%8F~%C2%B2d%C3%BC%C3%92%C2%99%C3%9C%C2%9D%C2%98%C3%A5%3A%C2%B3%C2%8BYR_cZ%C2%AE%C3%89%3D%C2%8Az%C2%B6%C2%A2%0A%C2%8A%2FLCx%C3%BAV%C2%9B%07%C3%8E%21%3A%2FP%5E%C3%93%C3%B3%C2%A9%C2%90%C2%AD%21%C2%85u%C3%8D%C2%9E%07%29%C2%A3%3D%C2%B7%C3%82%C3%8D%C3%B4%C2%B8_%60%C2%B4r%C3%8DG%C2%93%17%14%28%3E%C3%9A%C2%B1e%C2%90%C3%AC_5M%C3%86%0E%C2%B1f%40%C2%AF%C2%8Ag%C2%95G%C3%B8%C2%8F%C3%BD8f%C3%88%C3%9F%C3%BDQl_%06%065%C2%A1w%C2%AE%C2%93%C2%84s3c%C2%BE%C2%98%3E%1C%C3%B3C%C3%9E%C3%8A%0A%13m%C3%A9dR%C2%96%C2%B8A%C3%A8%C3%9B%23%C2%A6%01%C3%85%608%C3%9Bc%C2%9C%2a%C3%99%5D%03%C3%BC8%C3%88%C2%94%1E%2Fp%C2%8EM%0F%C2%93DJlW%C3%A8%C2%AF%C3%8C%C3%A7%C3%A2p%C2%82%C2%84%C2%A3%06%C3%93%2aO%C3%8D%C2%8B%C2%B6h%C2%A5%C2%80%C2%98%C2%9EIO%C2%BC%C3%BD%C2%91+U%C2%A6f%12%1D%C3%80I%C3%B2%3E%C2%9E%C3%AF%5D%C2%89%C2%BC%C2%B30%C3%AF%C3%9D%C3%8C%C3%8A%C2%93p%27%2C%14%03jS2%C3%AF%C2%AF%C3%A1%C2%B5%C3%93Z%C3%8C%3E%C3%BD%1Dx%C2%A5%C2%B3%06%C2%AEgX%C3%AC%C3%A4z%C2%99%16%C3%B5%C3%9A%C2%A7%1EQ%0A%C2%94%C3%BC%C3%8D%C3%A9%C3%A8%C3%BEZ%C3%91%C2%BC%0F%C2%BB%24%C2%9DE%C2%9A%C2%AC%C2%97X%C2%A7%C2%9B%C3%AA%C3%B0w%C2%89%C3%A8%C2%A1%C3%BA%C3%A7%C2%83%2C%C2%B9%C3%AA%5C%C2%A7%C3%B1%C2%B3v%C2%BA%C2%97%C3%BBA%C2%B7t%C2%9A%09-%C2%96%C2%97s%C2%80%13%17z%C3%BE%15_%C3%86%C3%8F%C2%89%3D%7F%C3%9FT%C3%8D%16%C3%BE%C2%8A%C3%AA%C3%97%0A%C2%91%C2%84TaO%03%C2%87%C2%A6%C3%92%1C%C3%88%C2%A9%C2%B8%0FR.9%13.H%C2%8B%04%C3%8E-5%5E%02%C2%96c%11%C2%A7%C3%B8um%C2%8A%C3%A2%13%C3%A2%C3%96%1B%C3%B9C%07%3E%C2%99%29%C2%A9i%7F%C3%B5jr%15%7B%C2%92%5B%26%C3%8BtH%1B%C3%80%C3%BC%C3%BBdE%05-7%C3%96%21j%C3%99%C2%83%C2%88%13%C3%BB%C3%A7%C3%A8%C3%B2%17%C3%87T%C3%9EH%C3%B6%23%1E%C2%BF%C2%B04%C3%B5Oc%C3%8EF%40%C2%A9%16%C3%A7J%60q%C3%8E%C2%A3%C3%93j%15L%C2%8BR%C3%96%3F%C3%8BS%C3%9D%C2%96%C2%97%10%C3%B6%C3%A5%2227%5Cqd3b_hhxJz&input=Indiana). ### Idea We encode the required information as follows: ``` columbia columbus frankfort ⋮ kentucky ohio southqcarolina arstotzka ``` All the names have been cast to lowercase, spaces have been replaced with q's, and names are separated by linefeeds. All capitals are listed first (in an order that managed to minimize the byte count). Then the corresponding states are listed in reverse order. Finally, *Arstotzka* is appended. This way, the capital/state at index **i** corresponds to the state/capital at index **-(x+2)**. Also, an invalid input will either have index **100** (*Arstotzka*) or **-1** (not found), and **-(100+2) ≡ -1 ≡ -(-1+2) mod 101**. This layout prevents *Arstotzka* from being a special case, without prepending or appending anything to the list. To compress the information, we find each character's index in `"\nabc...xyz"` and convert the result from base 27 to base 256. Decoding is straightforward: we go back from base 256 to base 27, retrieve the corresponding elements from `"\nabc…xyz"`, replace q's with spaces, and capitalize the first letter of each resulting word. ### Code ``` @JcrXs@L+bGjC"…"27\qd3b_hhxJz C"…" Convert the 562-character from base 256 to integer. j 27 Convert the result from integer to base 27. +bG Compute "\n" + "abc…xyz". @L Retrieve the corresponding characters. s Flatten the resulting array of strings. X \qd Replace each q with a space. r 3 Apply title casing. Jc b Split at linefeeds and save in J. xJz Compute the index of the input (z) in J. _hh Increment twice and negate. @ Retrieve the element at that index from J. ``` [Answer] # JavaScript (ES6), ~~821~~ 806 bytes Uses Base64 decode to compress strings. [Live demo](https://jsfiddle.net/intrepidcoder/sub4gqhL/) ``` s=>(S=(r=x=>btoa(x).replace(/\+/g," ").split`/`)`.¢²&§kò'v&§kó¡À¦Ú¯Ì¢{Z¯Â¢Z+iÚ?!Ö¡£ôÞÅ«?1«,iÈn±ëm³ó^Ãæ(®OÅâu¯Í{{£ôÞw¬±ç¿5ì>%êì{/ÌË(º¸¿V*àxý*.¶jJ-kóÞ{2ö§¯Ìj)Þýhuï²V§wðÞ¬­ïÍ{jjl*ÞýW«íü*'ç-Ë­ü¦§±«?2)çzÊ-kð%jÉü×­«$kóh®Ø~ ªè)Úýh¬rìÖjÈbhð+:'kó"r jÇk¢ó"²È¬²*iò%)èÏÒ¢ëaø&«¢X§kó¯)ZßÖÊ¢Ôµ¨ê+&¿6íàÚZü§§¶ç$Ëó«z 'ü äj{³ò(Á¯ÂjX¢¹âkó¤¨h¯ÖzË~V*àxüׯiÖ¿`,C=r`«hähº¿"wbjv©¢X¬ü*%ºfî³ó(Ø(êòüw¥zv¿ éïz¿Á¢+ü¬¶)ÿ-¢À¶§ËôÚV¡jË{ôÖ¾ïÍjÈoY^ý:ÞÚ'ü}êì¢ÑÈf¢w>'«­ïÇjºâ±»«ð.ë-kóë¢øzwü:/z¿Â¢w(­ßÌ¢{izX¯ñÚ®×è­ßÓ¢¤kô{~=«¥ü§y«¿.)Ü¢YÿE©^1§b²ÿ:\\¦¦&¿>,-©ìx?èénüÊ'ý*kxé]ü*%ºfâkð'ªh+? ²zyÞý&¥·âÚïÜ¿ÙZÖ¿+&j·$üZÚGè®ßÒjW¦ü¸­¶W¾F$ü7¬øÊ"ë?I§+jg§¶ÎV¡¢f¾ +rü(Z®W¬¶ÿ ªì¢Ü¿`,S[C.indexOf(s)]||C[S.indexOf(s)]||"Arstotzka") ``` Here is a hexdump; use `xxd -r filename` to reverse. ``` 00000000: 733d 3e28 533d 2872 3d78 3d3e 6274 6f61 s=>(S=(r=x=>btoa 00000010: 2878 292e 7265 706c 6163 6528 2f5c 2b2f (x).replace(/\+/ 00000020: 672c 2220 2229 2e73 706c 6974 602f 6029 g," ").split`/`) 00000030: 602e 3fa2 b226 a76b f227 7626 a76b f3a1 `.?..&.k.'v&.k.. 00000040: 3f8f c03f a6da 3faf cca2 7b5a 9daf c2a2 ?..?..?...{Z.... 00000050: 5a2b 69da 3f21 d6a1 a3f4 dec5 ab3f 31ab Z+i.?!.......?1. 00000060: 2c69 c86e b1eb 6db3 f35e c3e6 28ae 4fc5 ,i.n..m..^..(.O. 00000070: 3f3f e275 afcd 7b0f 3f7b 183f a3f4 de3f ??.u..{.?{.?...? 00000080: 77ac b1e7 bf35 ec3e 25ea ec7b 2fcc 3fcb w....5.>%..{/.?. 00000090: 28ba b8bf 562a e03f 783f fd2a 2eb6 1f3f (...V*.?x?.*...? 000000a0: 6a4a 2d6b f3de 3f7b 323f f6a7 3faf cc6a jJ-k..?{2?..?..j 000000b0: 29de fd18 6875 ef3f b256 a777 f0de 3fac )...hu.?.V.w..?. 000000c0: 1aad efcd 7b0f 3f6a 6a6c 3f2a defd 57ab ....{.?jjl?*..W. 000000d0: 3f3f edfc 2a27 9de7 2d3f cbad fca6 a7b1 ??..*'..-?...... 000000e0: ab3f 3229 e77a ca2d 6bf0 256a c91a fcd7 .?2).z.-k.%j.... 000000f0: 3fad ab24 6bf3 68ae d87e 09aa e83f 29da ?..$k.h..~...?). 00000100: fd68 ac72 3fec 3f7f d66a c862 3f0b 683f .h.r?.?..j.b?.h? 00000110: f02b 3f3a 276b f322 7218 206a 7fc7 6b06 .+?:'k."r. j..k. 00000120: a23f f322 b2c8 acb2 2a69 3ff2 253f 29e8 .?."....*i?.%?). 00000130: 3fcf d2a2 eb61 f826 aba2 58a7 6bf3 1aaf ?....a.&..X.k... 00000140: 295a 9ddf d6ca 3fa2 3f0f d4b5 a87f 19ea )Z....?.?....... 00000150: 2b3f 26bf 363f ed3f e0da 3f3f 5afc a7a7 +?&.6?.?..??Z... 00000160: b6e7 24cb f3ab 7a0a 27fc 0ae4 6a7b 1ab3 ..$...z.'...j{.. 00000170: f228 c1af c26a 583f a2b9 e26b f3a4 3fa8 .(...jX?...k..?. 00000180: 683f afd6 7acb 7e56 2ae0 3f78 3ffc d7af h?..z.~V*.?x?... 00000190: 69d6 bf60 2c43 3d72 6005 ab68 3fe4 68ba i..`,C=r`..h?.h. 000001a0: 07bf 2277 626a 76a9 a258 acfc 2a25 ba66 .."wbjv..X..*%.f 000001b0: eeb3 f328 3fd8 283f eaf2 fc77 a57a 76bf ...(?.(?...w.zv. 000001c0: 0ae9 ef7a bfc1 a22b 1efc 0bac b629 ff06 ...z...+.....).. 000001d0: 3f2d a27f c03f b6a7 cbf4 da3f 56a1 6acb ?-...?.....?V.j. 000001e0: 1e7b f43f 3fd6 be15 efcd 6ac8 6f3f 595e .{.??.....j.o?Y^ 000001f0: fd3a de3f da27 fc3f 3f7d eaec a27f d13f .:.?.'.??}.....? 00000200: c866 a277 7f3e 27ab adef c76a bae2 b1bb .f.w.>'....j.... 00000210: ab3f f02e 3feb 2d6b f3eb a2f8 9d7a 771e .?..?.-k.....zw. 00000220: fc3a 2f7a bfc2 a277 28ad dfcc a27b 697a .:/z...w(....{iz 00000230: 583f aff1 daae d7e8 addf d3a2 3fa4 6bf4 X?..........?.k. 00000240: 3f3f 7b7e 3dab a5fc 3fa7 79ab bf2e 29dc ??{~=...?.y...). 00000250: a259 ff45 a95e 3f08 7f31 a762 b23f ff3a .Y.E.^?..1.b.?.: 00000260: 5c5c a6a6 26bf 3e1a 1e3f 2c7f 2da9 ec3f \\..&.>..?,.-..? 00000270: 783f 1e3f e83f e96e fc3f 3f3f ca27 fd2a x?.?.?.n.???.'.* 00000280: 6b3f 781f 3fe9 5dfc 2a25 ba66 e26b f027 k?x.?.].*%.f.k.' 00000290: 9daa 683f 2b3f 0a17 b27a 79de fd26 a5b7 ..h?+?...zy..&.. 000002a0: e2da 3fef 3f3f dcbf 02d9 5a3f d6bf 062b ..?.??....Z?...+ 000002b0: 266a b724 fc5a da3f 47e8 aedf d26a 57a6 &j.$.Z.?G....jW. 000002c0: fcb8 adb6 57be 463f 24fc 37ac f8ca 229d ....W.F?$.7...". 000002d0: eb3f 49a7 2b6a 67a7 b68f ce3f 56a1 a266 .?I.+jg....?V..f 000002e0: be0a 2b72 fc28 5aae 57ac b63f ff09 aaec ..+r.(Z.W..?.... 000002f0: a27f 3f3f dcbf 602c 535b 432e 696e 6465 ..??..`,S[C.inde 00000300: 784f 6628 7329 5d7c 7c43 5b53 2e69 6e64 xOf(s)]||C[S.ind 00000310: 6578 4f66 2873 295d 7c7c 2241 7273 746f exOf(s)]||"Arsto 00000320: 747a 6b61 2229 tzka") ``` [Answer] ## PHP, ~~1272~~ 1239 bytes Make sure you have enabled short\_open\_tag in php.ini: This code uses argv[1] as the input. ``` <?$c=json_decode('{"Baton Rouge":"Louisiana","Indianapolis":"Indiana","Columbus":"Ohio","Montgomery":"Alabama","Helena":"Montana","Denver":"Colorado","Boise":"Idaho","Austin":"Texas","Boston":"Massachusetts","Albany":"New York","Tallahassee":"Florida","Santa Fe":"New Mexico","Nashville":"Tennessee","Trenton":"New Jersey","Jefferson":"Missouri","Richmond":"Virginia","Pierre":"South Dakota","Harrisburg":"Pennsylvania","Augusta":"Maine","Providence":"Rhode Island","Dover":"Delaware","Concord":"New Hampshire","Montpelier":"Vermont","Hartford":"Connecticut","Topeka":"Kansas","Saint Paul":"Minnesota","Juneau":"Alaska","Lincoln":"Nebraska","Raleigh":"North Carolina","Madison":"Wisconsin","Olympia":"Washington","Phoenix":"Arizona","Lansing":"Michigan","Honolulu":"Hawaii","Jackson":"Mississippi","Springfield":"Illinois","Columbia":"South Carolina","Annapolis":"Maryland","Cheyenne":"Wyoming","Salt Lake City":"Utah","Atlanta":"Georgia","Bismarck":"North Dakota","Frankfort":"Kentucky","Salem":"Oregon","Little Rock":"Arkansas","Des Moines":"Iowa","Sacramento":"California","Oklahoma City":"Oklahoma","Charleston":"West Virginia","Carson City":"Nevada"}',1);$s=array_flip($c);$z=$argv[1];echo @$c[$z]?$c[$z]:(@$s[$z]?$s[$z]:'Arstotzka'); ``` [Answer] # Java, ~~1062~~ 964 bytes ``` s->{String t="Arstotzka",a[]="AlabamaMontgomeryAlaskaJuneauArizonaPhoenixArkansasLittle RockCaliforniaSacrementoColoradoDenverConecticutHartfordDelawareDoverFloridaTallahasseeGeorgiaAtlantaHawaiiHonoluluIdahoBoiseIllinoisSpringfieldIndianaIndianapolisIowaDes MoinesKansasTopekaKentuckyFrankfortLouisianaBaton RougeMaineAugustaMarylandAnnapolisMassachusettsBostonMichiganLansingMinnesotaSaint PaulMississippiJacksonMissouriJefferson CityMontanaHelenaNebraskaLincolnNevadaCarson CityNew HampshireConcordNew JerseyTrentonNew MexicoSanta FeNew YorkAlbanyNorth CarolinaRaleighNorth DakotaBismarckOhioColumbusOklahomaOklahoma CityOregonSalemPennsylvaniaHarrisburgRhode IslandProvidenceSouth CarolinaColumbiaSouth DakotaPierreTennesseeNashvilleTexasAustinUtahSalt Lake CityVermontMontpelierVirginiaRichmondWashingtonOlympiaWest VirginiaCharlestonWisconsinMadisonWyomingCheyenne".split("(?<=[a-z])(?=[A-Z])");for(int k=-1;k++<99;t=s.equals(a[k])?a[k%2*-2-~k]:t);return t;} ``` *-17 bytes thanks to @KevinCruijssen.* [Try it online!](https://tio.run/##jVRNb@JIEL3Pr2ghrQQ7A9LObZYwEQFlIQMEhexEs4hDYRe44naVtz9InFH2r2erQxLNMZbltqtfVb9@r9q3cICu1Mi3efmUWfDezIHY/Pxg9Krj1lJmfICgw0EoN5XOtlfBEe/XGwNu7zsv4HTdarleDGR7u8hZIOHe@cvLyTHpkzmOX83ODJ589@vP47cJg9bQ@SDhoYTWJ1hv9NvCFiqYC4e9VOgaDfgSLiIjxKGjB2FYFoJM90NXAnvwMwrBormSrByBpZ04JlhB5rBCDjISKw5yGSMf0I2EUbllMUzABcXmY7RwBw7HotPniqUcrsFaKFQZxL9Q3J5gGCxwgIlCiSbCYqON0xwKORPyOLWWWF9WddrYjtDmU84JGF6GWiz5qdzBGFVuIUb/7Zn9tTpRwjdlGrOyOXfApbIKM4nkU@IZBGHdXNxjcgmHcR/VnDm4RhnlQ36pPVe2kBXRYwj@TFRVnlNW0B54pgspqzmxripBtSEOZgnRzsn7dNc1XUBW@pTjvURHF7jbodOAGVFokh3KZYIWGRa4dcmTGXEmlhd4gBxG8AZe4J2ZQFX7ghyq3pmKnGIXWg@ba5dM4RSY4z1lskq6mnNMkR/iyqHdAjcL1aAwWlX3xnAFFmlfHINjKHUTZ@QrcFl5WVCyOFbb6C9LdU0qeB2f6Vw63AuvtEK1RGbf2ANog6j9jvw2uv1VITmaqU9yLp0cKEfOcCXxFwLHFbStnqNHBktC5/Aak6raKAvwxYGs1cg9@KGaRPx3gEJXDmYGJT6z@Y6uUjGToDVarfCdtL2Uz5WapTP5jZZRs1SiS9tUNcEN@mBeUaMCnMVk7g35TJKvc8hJpb9ppNK8UYFNYtTq@dpSaLfapyeDNXQfNp326WA97P6z6bQ6fW2xdmqCctD9o19@/Hjy5Us/DHwP/41gfRvW5aZzqs/fPv/e/dz9r9z8GTp9hyE6NqH/@PR6@Ptvv4FV4wNWPdWnl85AsNze9aCubdNuJRlanc77wM/yvRv92j3vTjj@Sd4N34lswW3h4S3j8cPj0/8 "Java (OpenJDK 8) – Try It Online") Pretty straightforward; if a match is found, then add to or subtract from the current index of the array depending on whether it is even or odd. Otherwise print "Arstotzka". The majority of bytes saved was due to removing the 99 `:`s and splitting the string based on the regex `(?<=[a-z])(?=[A-Z])`, which uses a positive lookbehind and lookahead to check for a difference in casing. [Answer] # [R](https://www.r-project.org/), ~~1023~~ 985 bytes ``` function(s){g=strsplit y="Bat9 Rouge,Indi2apol3,Columbus,M9tgomery,Hel6a,D6ver,Bo3e,Aust1,Bost9,Alb2y,Tallah5s4,S2ta Fe,N5hville,Tr6t9,Jeffers9,Richm9d,Pierre,H7r3burg,Augusta,Provid6ce,Dover,C9c0d,M9tpelier,H7tf0d,Topeka,Sa1t Paul,Juneau,L1coln,Raleigh,Mad39,Olympia,Pho6ix,L2s1g,H9olulu,Jacks9,Spr1gfield,Columbia,Annapol3,Chey6ne,Salt Lake8,Atl2ta,B3m7ck,Fr2kf0t,Salem,Little Rock,Des Mo1es,Sacram6to,Oklahoma8,Ch7lest9,C7s98,Nevada,West Virg1ia,Oklahoma,Calif0nia,Iowa,Ark2s5,Oreg9,K6tucky,N0th Dakota,Ge0gia,Utah,Wyom1g,M7yl2d,South C7ol1a,Ill1o3,M3s3sippi,Hawaii,Michig2,Ariz9a,W5h1gt9,W3c9s1,N0th C7ol1a,Nebr5ka,Al5ka,M1nesota,K2s5,C9necticut,Verm9t,New Hampshire,Delaw7e,Rhode Isl2d,Ma1e,P6nsylv2ia,South Dakota,Virg1ia,M3souri,New Jersey,T6ness4,New Mexico,Fl0ida,New Y0k,M5sachusetts,Tex5,Idaho,Col0ado,M9t2a,Alabama,Ohio,Indi2a,Lou3i2a" for(i in 0:9)y=gsub(i,g("or,in,an,is,ee,as,en,ar, City,on",",")[[1]][i+1],y) x=g(y,",")[[1]] 'if'({y=match(s,x,0)},x[101-y],'Arstotzka')} ``` [Try it online!](https://tio.run/##VVNdT9tKEH3Pr7DyQqJOJX80Dq6Uh5CIG2gMCGjRFZeHiT22V157rf0Icav@djqmgStka@2ZPTtz5sysfikWL4VrMytUOzHTX@XCWG06KeyoX4zP0CberXIlwUWbixA7JSNYKemanTOQJrZUDekeNiRjhHW8Jw1nKiJYOmMD/jU2gaXchT3co5RYzcwXuAsteucEV7NqL6QkuNcxwy6pKEibBG5FVjVJDjeCtCbYzHW0c7rkmCVHRbjRai/yOCNYqyHhKsn8fCDTkeQjfMAW7LhXHdUIdxhY7wadhEvXEjrYBpmSLdyiJFFWkGIeJXAt@6YTHLtSsTjANjRBCZuEK5UOLjGrmdddp4OyECTzowSMX7btUZSK@rglTiett8WaTmFpJVcKZ1Ezz2o412Fd@HYAUANbYa0k1pZ31mS8VAVkeC/T2MRWwXXNYqkGTznwXNIg42puklO4oj3mCA/s8n4IXQZM4g0MK5Si8Ft2XahnJqfr0MzgWlOZwLfYuqzu4cq3lbfGWjG1f8gvGfzdYgUPvWq45nTeyzCHO@UYtporGXAwKQMVQRqZyIiuE7DBZxQCUm6UKEPOI34mzGlWBSUTfYiyxAR/Ex0jXNFOz7gZSzmsadCSGfJ/G@itkpZ4/jJn4QfpJrGMfvY22HSmEtz/NUl8nhPcVion78IM9FIMCG7i1vRyH3IFf@keq3qThfkqp8VruEueLOIh5BYZHsHBldJBZArOpS9yfPX869eQzgxmlTNkrYF7OszgImdxh477mKthzMKhDtwhC35dCXW8GrBVLuLveFQoPRGeaD3/azLtF6Vxu4mAcjJWGkQL2IIwQATIK5savJWwPah2DPxMHx@Dp6dH8Sl4gn46OizKSf@/f3QiipPJr37RoM2qiYED@NPfcHgM/OBz/wQnS22ssj9rPJn@fsnQTsbDJVTtV28MxZsxnsL4P15Hr4D3WRI8OUfcB99H@Nl2ye9bvFfjI@CdwhHzbr/DXv4A "R – Try It Online") Different from the other R submission. The code puts the capitals and states in the same vector. The states are in reverse order so that, given the index of either the state or the capital, the matching entry's index is `length(data)-index+1`, where `length(data)=100`, 50 (states) + 50 (capitals) Also, the input data is packed as a single string and then split. The string could be compressed to golf it further. Edit: added some unoptimized substitution of pairs of characters. [Answer] ## Javascript, ~~1057~~ 1042 bytes Answer 1: 1042 ``` (()=>{for(i=0,b=prompt(),c='Baton Rouge,Louisiana,Indianapolis,Indiana,Columbus,Ohio,Montgomery,Alabama,Helena,Montana,Denver,Colorado,Boise,Idaho,Austin,Texas,Boston,Massachusetts,Albany,New York,Tallahassee,Florida,Santa Fe,New Mexico,Nashville,Tennessee,Trenton,New Jersey,Jefferson,Missouri,Richmond,Virginia,Pierre,South Dakota,Harrisburg,Pennsylvania,Augusta,Maine,Providence,Rhode Island,Dover,Delaware,Concord,New Hampshire,Montpelier,Vermont,Hartford,Connecticut,Topeka,Kansas,Saint Paul,Minnesota,Juneau,Alaska,Lincoln,Nebraska,Raleigh,North Carolina,Madison,Wisconsin,Olympia,Washington,Phoenix,Arizona,Lansing,Michigan,Honolulu,Hawaii,Jackson,Mississippi,Springfield,Illinois,Columbia,South Carolina,Annapolis,Maryland,Cheyenne,Wyoming,Salt Lake City,Utah,Atlanta,Georgia,Bismarck,North Dakota,Frankfort,Kentucky,Salem,Oregon,Little Rock,Arkansas,Des Moines,Iowa,Sacramento,California,Oklahoma City,Oklahoma,Charleston,West Virginia,Carson City,Nevada'.split(","),q="Arstotzka";i<100;i++){if(c[i]==b)q=c[i%2?i-1:i+1];}return q})() ``` Updated Answer 1 missed a zero :S, Also fixed general incorrectness Updated Answer 1 + 2 re-arranged structure a bit. *Answer 1 is recommended to be run in a Javascript console (your browser's, for example) an unnamed function that returns to the console. You can also test it [here](https://repl.it/B11V).* Answer 2 1049 ``` alert((()=>{for(i=0,b=prompt(),c='Baton Rouge,Louisiana,Indianapolis,Indiana,Columbus,Ohio,Montgomery,Alabama,Helena,Montana,Denver,Colorado,Boise,Idaho,Austin,Texas,Boston,Massachusetts,Albany,New York,Tallahassee,Florida,Santa Fe,New Mexico,Nashville,Tennessee,Trenton,New Jersey,Jefferson,Missouri,Richmond,Virginia,Pierre,South Dakota,Harrisburg,Pennsylvania,Augusta,Maine,Providence,Rhode Island,Dover,Delaware,Concord,New Hampshire,Montpelier,Vermont,Hartford,Connecticut,Topeka,Kansas,Saint Paul,Minnesota,Juneau,Alaska,Lincoln,Nebraska,Raleigh,North Carolina,Madison,Wisconsin,Olympia,Washington,Phoenix,Arizona,Lansing,Michigan,Honolulu,Hawaii,Jackson,Mississippi,Springfield,Illinois,Columbia,South Carolina,Annapolis,Maryland,Cheyenne,Wyoming,Salt Lake City,Utah,Atlanta,Georgia,Bismarck,North Dakota,Frankfort,Kentucky,Salem,Oregon,Little Rock,Arkansas,Des Moines,Iowa,Sacramento,California,Oklahoma City,Oklahoma,Charleston,West Virginia,Carson City,Nevada'.split(","),q="Arstotzka";i<100;i++){if(c[i]==b)q=c[i%2?i-1:i+1];}return q})()) ``` Answer 2 will work with the code snippet button [Answer] # PHP, 674 bytes ``` <?php $a=explode("\n",gzinflate('=SÛŽê0.|÷WôWº =Àr.p..GÓšÆj.WN.ÛýúãÀ²R¥ÞÆžñxRkL’¾{„7L.ªƒäŽ`-™#c@X†¶ÜGñ._/0.Ÿ‡Kްs,°‘.:.H\'¨=^p@X.\'Õ?.?§p#-e¢Ø.¼.G‚e‹N Î1q€.}a´.¦&À.cÄÆåH)EkzÁ0Á–îÕ?Ñ.Nè=:ƒ.Á»uä.áˆÆT½Ó.µ¡/n.¶.Ý.½\'k..=ð\'¥P..lE.i‚.]¯öTh9FÉÊpàÆ..Zødí80žI•à(9¹j޽$..U9^²v°7‚8ù..l.;›É¦G..{•.·..‚ƒ“–ªeôh.çR,™“Ç;Z癄F´}.[à0FÇöµ.8’7rø$5I©°¦kAZE &q“.œd$[á.†h...8U{ÌÞF*“.µ«..sÙP4äš.Î...úøp@OÜ9ØŠÚ„3T[xÙ ¶\¬9sl$D[ÔÎOÃhSžÍ].]1sï„..A.ü-V´Æ‚쌼qÜa€….KŒÏ&þŽÌ°Â¦..^®qd8Žj5W&ßÂÒ.¹eä\'hÆö4þWV.^‘Ü N.?gަ²f8O2.ö#úT.±§jÆi‚¿..ÔÉ— À..[¬ežã€Úô?cÿ,ö]1ôæq‚.KKnú©4£.vJ.É^sJžì¨Xa.ýÓô9Åj#¶q;&r/‰l.‡’6˜¡gkW²±ë-º2àSÓëÍÄ£zzdÿl·ê7w6±.õDoé†-þ.'));$b=array_search($argv[1],$a);echo $a[$b?$b%2?$b+1:$b-1:0]; ``` Hex: ``` 00000000: 3C 3F 70 68 70 20 24 61 - 3D 65 78 70 6C 6F 64 65 |<?php $a=explode| 00000010: 28 22 5C 6E 22 2C 67 7A - 69 6E 66 6C 61 74 65 28 |("\n",gzinflate(| 00000020: 27 3D 53 DB 8E EA 30 0C - 7C F7 57 F4 57 BA A0 3D |'=S 0 | W W =| 00000030: C0 72 13 70 16 9D 47 D3 - 9A C6 6A 1A 57 4E 02 DB | r p G j WN | 00000040: FD FA E3 C0 B2 52 A5 DE - C6 9E F1 78 52 6B 4C 92 | R xRkL | 00000050: BE 7B 84 37 4C 12 AA 83 - E4 8E 60 2D 99 23 63 40 | { 7L `- #c@| 00000060: 58 86 B6 DC 47 F1 1C 5F - 2F 30 13 9F 87 4B 8E B0 |X G _/0 K | 00000070: 73 2C B0 91 90 3A 19 48 - 5C 27 A8 3D 5E 70 40 58 |s, : H\' =^p@X| 00000080: 90 5C 27 C3 95 3F 05 3F - A7 70 23 2D 65 A2 D8 0A | \' ? ? p#-e | 00000090: BC 09 47 82 65 8B 4E A0 - CE 31 71 80 13 7D 61 B4 | G e N 1q }a | 000000a0: 1F A6 26 C0 06 63 C4 C6 - E5 48 29 45 6B 7A C1 30 | & c H)Ekz 0| 000000b0: C1 96 EE D5 3F D1 1E 4E - E8 3D 3A 83 10 C1 BB 75 | ? N =: u| 000000c0: E4 16 E1 88 C6 54 BD D3 - 03 B5 A1 2F 6E 04 B6 18 | T /n | 000000d0: DD 8D BD 5C 27 6B 1E 02 - 3D F0 5C 27 A5 50 18 0A | \'k = \' P | 000000e0: 6C 45 1A 69 82 15 5D AF - F6 54 68 39 46 C9 CA 70 |lE i ] Th9F p| 000000f0: E0 C6 0D 12 5A F8 64 ED - 38 30 C2 9E 49 95 E0 28 | Z d 80 I (| 00000100: 39 B9 6A 8E BD 24 1B 12 - 55 39 5E B2 76 B0 37 82 |9 j $ U9^ v 7 | 00000110: 38 F9 1B 16 6C 9D 3B 9B - C9 A6 47 0E 04 7B 95 1B |8 l ; G { | 00000120: B7 14 1A 82 83 93 96 AA - 65 F4 68 AD E7 52 2C 99 | e h R, | 00000130: 93 C7 3B 5A E7 99 84 46 - B4 7D 08 5B E0 30 46 C7 | ;Z F } [ 0F | 00000140: F6 B5 18 38 92 37 72 F8 - 24 35 49 A9 B0 A6 6B 41 | 8 7r $5I kA| 00000150: 5A 45 A0 26 71 93 13 9C - 64 24 5B E1 07 86 68 2E |ZE &q d$[ h.| 00000160: 1E 8D 38 55 7B CC DE 46 - 2A 93 17 B5 AB 1C 08 73 | 8U{ F* s| 00000170: D9 50 34 E4 9A 8D CE 17 - 1F 2E FA F8 70 40 4F DC | P4 . p@O | 00000180: 39 D8 8A DA 84 33 54 5B - 78 D9 20 B6 5C AC 39 73 |9 3T[x \ 9s| 00000190: 6C 24 44 5B D4 CE 4F C3 - 68 53 9E CD 5D 0E 5D 31 |l$D[ O hS ] ]1| 000001a0: 73 EF 84 02 7F 41 AD FC - 2D 56 B4 C6 82 EC 8C BC |s A -V | 000001b0: 71 DC 61 80 85 04 4B 8C - CF 26 FE 8E CC B0 C2 A6 |q a K & | 000001c0: 7F 19 5E AE 71 64 38 8E - 6A 35 57 26 DF C2 D2 1B | ^ qd8 j5W& | 000001d0: B9 65 E4 5C 27 68 C6 F6 - 34 FE 57 56 1D 5E 91 DC | e \'h 4 WV ^ | 000001e0: A0 4E 0F 3F 67 8E A6 B2 - 66 38 4F 32 14 F6 23 FA | N ?g f8O2 # | 000001f0: 54 AD B1 A7 6A C6 69 82 - BF 09 1D D4 C9 97 A0 C0 |T j i | 00000200: 1F 12 5B AC 65 9E E3 80 - DA F4 3F 63 FF 2C F6 5D | [ e ?c , ]| 00000210: 31 F4 E6 71 82 0F 4B 4B - 6E FA A9 34 A3 01 76 4A |1 q KKn 4 vJ| 00000220: 9D C9 5E 73 4A 9E EC A8 - 58 61 AD FD D3 F4 39 C5 | ^sJ Xa 9 | 00000230: 6A 23 B6 71 3B 26 72 2F - 89 6C 14 87 92 36 98 A1 |j# q;&r/ l 6 | 00000240: 67 6B 57 B2 B1 EB 2D BA - 32 E0 53 D3 EB CD C4 A3 |gkW - 2 S | 00000250: 7A 7A 64 FF 6C B7 EA 37 - 77 36 B1 19 F5 44 6F E9 |zzd l 7w6 Do | 00000260: 86 2D FE 07 27 29 29 3B - 24 62 3D 61 72 72 61 79 | - '));$b=array| 00000270: 5F 73 65 61 72 63 68 28 - 24 61 72 67 76 5B 31 5D |_search($argv[1]| 00000280: 2C 24 61 29 3B 65 63 68 - 6F 20 24 61 5B 24 62 3F |,$a);echo $a[$b?| 00000290: 24 62 25 32 3F 24 62 2B - 31 3A 24 62 2D 31 3A 30 |$b%2?$b+1:$b-1:0| 000002a0: 5D 3B - |];| 000002a2; ``` Explanation ``` <?php // create array of capitals and states $a = explode("\n", gzinflate(/* Arstotzka Baton Rouge Louisiana Indianapolis Indiana ... */)); $b = array_search($argv[1], $a); // find user input in list echo $a[ $b // if $b is nonzero, the match succeded ?$b % 2 // checks if $b is odd, indicating a capital ?$b + 1 // $b points to capital; return the next item, the state :$b - 1 // $b points to state; return the previous item, the capital :0 // select "Arstotzka" otherwise ]; ``` [Answer] # Ruby, 989 bytes ``` ->s{a="Baton Rouge|Louisiana|Indianapolis|Indiana|Columbus|Ohio|Montgomery|Alabama|Helena|Montana|Denver|Colorado|Boise|Idaho|Austin|Texas|Boston|Massachusetts|Albany|New York|Tallahassee|Florida|Santa Fe|New Mexico|Nashville|Tennessee|Trenton|New Jersey|Jefferson|Missouri|Richmond|Virginia|Pierre|South Dakota|Harrisburg|Pennsylvania|Augusta|Maine|Providence|Rhode Island|Dover|Delaware|Concord|New Hampshire|Montpelier|Vermont|Hartford|Connecticut|Topeka|Kansas|Saint Paul|Minnesota|Juneau|Alaska|Lincoln|Nebraska|Raleigh|North Carolina|Madison|Wisconsin|Olympia|Washington|Phoenix|Arizona|Lansing|Michigan|Honolulu|Hawaii|Jackson|Mississippi|Springfield|Illinois|Columbia|South Carolina|Annapolis|Maryland|Cheyenne|Wyoming|Salt Lake City|Utah|Atlanta|Georgia|Bismarck|North Dakota|Frankfort|Kentucky|Salem|Oregon|Little Rock|Arkansas|Des Moines|Iowa|Sacramento|California|Oklahoma City|Oklahoma|Charleston|West Virginia|Carson City|Nevada".split(?|) i=a.index(s) i ?a[i^1]:"Arstotzka"} ``` Split the data into a single array. Find the index of the input in the array (`index` returns a falsy value of `nil` if the input is not there) If falsy, return "Arstotzka" otherwise XOR the index with 1 to find the other member of the pair **In test program:** ``` f=->s{a="Baton Rouge|Louisiana|Indianapolis|Indiana|Columbus|Ohio|Montgomery|Alabama|Helena|Montana|Denver|Colorado|Boise|Idaho|Austin|Texas|Boston|Massachusetts|Albany|New York|Tallahassee|Florida|Santa Fe|New Mexico|Nashville|Tennessee|Trenton|New Jersey|Jefferson|Missouri|Richmond|Virginia|Pierre|South Dakota|Harrisburg|Pennsylvania|Augusta|Maine|Providence|Rhode Island|Dover|Delaware|Concord|New Hampshire|Montpelier|Vermont|Hartford|Connecticut|Topeka|Kansas|Saint Paul|Minnesota|Juneau|Alaska|Lincoln|Nebraska|Raleigh|North Carolina|Madison|Wisconsin|Olympia|Washington|Phoenix|Arizona|Lansing|Michigan|Honolulu|Hawaii|Jackson|Mississippi|Springfield|Illinois|Columbia|South Carolina|Annapolis|Maryland|Cheyenne|Wyoming|Salt Lake City|Utah|Atlanta|Georgia|Bismarck|North Dakota|Frankfort|Kentucky|Salem|Oregon|Little Rock|Arkansas|Des Moines|Iowa|Sacramento|California|Oklahoma City|Oklahoma|Charleston|West Virginia|Carson City|Nevada".split(?|) i=a.index(s) i ?a[i^1]:"Arstotzka"} puts f[gets.chop] ``` [Answer] ## Python 2.7, ~~1271~~ ~~1232~~ 1054 bytes ``` y='Little Rock,Boise,Richmond,Denver,Olympia,Sacramento,Springfield,Baton Rouge,Tallahassee,Austin,Trenton,Lansing,Annapolis,Dover,Phoenix,Pierre,Charleston,Salt Lake City,Montpelier,Indianapolis,Concord,Providence,Madison,Oklahoma City,Santa Fe,Frankfort,Columbia,Atlanta,Boston,Salem,Juneau,Bismarck,Helena,Montgomery,Des Moines,Saint Paul,Jefferson,Lincoln,Hartford,Augusta,Carson City,Albany,Cheyenne,Columbus,Harrisburg,Honolulu,Raleigh,Nashville,Jackson,Topeka'.split(',') z='Arkansas,Idaho,Virginia,Colorado,Washington,California,Illinois,Louisiana,Florida,Texas,New Jersey,Michigan,Maryland,Delaware,Arizona,South Dakota,West Virginia,Utah,Vermont,Indiana,New Hampshire,Rhode Island,Wisconsin,Oklahoma,New Mexico,Kentucky,South Carolina,Georgia,Massachusetts,Oregon,Alaska,North Dakota,Montana,Alabama,Iowa,Minnesota,Missouri,Nebraska,Connecticut,Maine,Nevada,New York,Wyoming,Ohio,Pennsylvania,Hawaii,North Carolina,Tennessee,Mississippi,Kansas'.split(',') def a(b): m='Arstotzka' if b in y:m=z[y.index(b)] if b in z:m=y[z.index(b)] print m ``` Example I/O: ``` >>> a('Baton Rouge') Louisiana >>> a('Montana') Helena >>> a('asdfghjkl;') Arstotzka ``` *Edit: way improved* [Answer] ## Perl 5 , 1029 bytes ``` $h{$h{$_}}=$_ for keys{%h=(Indianapolis,Indiana,Columbus,Ohio,Montgomery,Alabama,Helena,Montana,Denver,Colorado,Boise,Idaho,Austin,Texas,Boston,Massachusetts,Tallahassee,Florida,Nashville,Tennessee,Jefferson,Missouri,Richmond,Virginia,Harrisburg,Pennsylvania,Augusta,Maine,Dover,Delaware,Montpelier,Vermont,Hartford,Connecticut,Topeka,Kansas,Juneau,Alaska,Lincoln,Nebraska,Madison,Wisconsin,Olympia,Washington,Phoenix,Arizona,Lansing,Michigan,Honolulu,Hawaii,Jackson,Mississippi,Springfield,Illinois,Annapolis,Maryland,Cheyenne,Wyoming,Atlanta,Georgia,Frankfort,Kentucky,Salem,Oregon,Sacramento,California,Charleston,'West Virginia','Carson City',Nevada,'Baton Rouge',Louisiana,Albany,'New York','Santa Fe','New Mexico','Trenton','New Jersey',Pierre,'South Dakota',Providence,'Rhode Island',Concord,'New Hampshire','Saint Paul',Minnesota,Raleigh,'North Carolina',Columbia,'South Carolina','Salt Lake City',Utah,Bismarck,'North Dakota','Little Rock',Arkansas,'Des Moines',Iowa,'Oklahoma City',Oklahoma)};say$h{$ARGV[0]}//Arstotzka ``` [Answer] ## Perl 5, 999 bytes My first post in codegolf. ``` %m;@r=qw/la ol ia nt en or is an in on/;map{$x=$_;$x=~s/$_/$r[$_]/eg for(0..9);$x=~s/\b(\w)/\U$1/g;($c,$s)=split'\|',$x;$m{$c}=$s;$m{$s}=$c}qw(bat9_rouge|lou62na 8d2nap16|8d2na c1umbus|ohio mo3gomery|a0bama hel4a|mo37a d4ver|c15ado bo6e|idaho aust8|texas bost9|massachusetts alb7y|new_y5k tal0hassee|fl5ida sa3a_fe|new_mexico nashville|t4nessee tre39|new_jersey jeffers9|m6souri richm9d|virg82 pierre|south_dakota harr6burg|p4nsylv72 augusta|ma8e provid4ce|rhode_60nd dover|de0ware c9c5d|new_hampshire mo3pelier|vermo3 hartf5d|c9necticut topeka|k7sas sai3_paul|m8nesota juneau|a0ska l8c1n|nebraska raleigh|n5th_car18a mad69|w6c9s8 1ymp2|wash8gt9 pho4ix|ariz9a 0ns8g|michig7 h91ulu|hawaii jacks9|m6s6sippi spr8gfield|ill8o6 c1umb2|south_car18a 7nap16|mary0nd chey4ne|wyom8g salt_0ke_city|utah at03a|ge5g2 b6marck|n5th_dakota fr7kf5t|ke3ucky salem|5eg9 little_rock|ark7sas des_mo8es|iowa sacrame3o|calif5n2 ok0homa_city|ok0homa charlest9|west_virg82 cars9_city|nevada);print $m{$ARGV[0]}||"Arstotzka" ``` Ungolfed: ``` %m; @r=qw/la ol ia nt en or is an in on/; # Top 10 bigrams map{ $x=$_; $x=~s/$_/$r[$_]/eg for(0..9); # Resolve bigram placeholders $x=~s/\b(\w)/\U$1/g; # ucfirst each word ($c,$s)=split'\|',$x; # split city and state $m{$c}=$s; # key on both city and state $m{$s}=$c } qw( bat9_rouge|lou62na 8d2nap16|8d2na c1umbus|ohio mo3gomery|a0bama hel4a|mo37a d4ver|c15ado bo6e|idaho aust8|texas bost9|massachusetts alb7y|new_y5k tal0hassee|fl5ida sa3a_fe|new_mexico nashville|t4nessee tre39|new_jersey jeffers9|m6souri richm9d|virg82 pierre|south_dakota harr6burg|p4nsylv72 augusta|ma8e provid4ce|rhode_60nd dover|de0ware c9c5d|new_hampshire mo3pelier|vermo3 hartf5d|c9necticut topeka|k7sas sai3_paul|m8nesota juneau|a0ska l8c1n|nebraska raleigh|n5th_car18a mad69|w6c9s8 1ymp2|wash8gt9 pho4ix|ariz9a 0ns8g|michig7 h91ulu|hawaii jacks9|m6s6sippi spr8gfield|ill8o6 c1umb2|south_car18a 7nap16|mary0nd chey4ne|wyom8g salt_0ke_city|utah at03a|ge5g2 b6marck|n5th_dakota fr7kf5t|ke3ucky salem|5eg9 little_rock|ark7sas des_mo8es|iowa sacrame3o|calif5n2 ok0homa_city|ok0homa charlest9|west_virg82 cars9_city|nevada ); print $m{$ARGV[0]}||"Arstotzka" ``` [Answer] # [Haskell](https://www.haskell.org/), ~~1077~~ ~~1069~~ ~~1068~~ 1063 bytes ``` z s=last$"Arstotzka":[last$l:[r|s==l]|(l,_:r)<-span(<'~')<$>lines"Baton Rouge~Louisiana\nIndianapolis~Indiana\nColumbus~Ohio\nMontgomery~Alabama\nHelena~Montana\nDenver~Colorado\nBoise~Idaho\nAustin~Texas\nBoston~Massachusetts\nAlbany~New York\nTallahassee~Florida\nSanta Fe~New Mexico\nNashville~Tennessee\nTrenton~New Jersey\nJefferson~Missouri\nRichmond~Virginia\nPierre~South Dakota\nHarrisburg~Pennsylvania\nAugusta~Maine\nProvidence~Rhode Island\nDover~Delaware\nConcord~New Hampshire\nMontpelier~Vermont\nHartford~Connecticut\nTopeka~Kansas\nSaint Paul~Minnesota\nJuneau~Alaska\nLincoln~Nebraska\nRaleigh~North Carolina\nMadison~Wisconsin\nOlympia~Washington\nPhoenix~Arizona\nLansing~Michigan\nHonolulu~Hawaii\nJackson~Mississippi\nSpringfield~Illinois\nColumbia~South Carolina\nAnnapolis~Maryland\nCheyenne~Wyoming\nSalt Lake City~Utah\nAtlanta~Georgia\nBismarck~North Dakota\nFrankfort~Kentucky\nSalem~Oregon\nLittle Rock~Arkansas\nDes Moines~Iowa\nSacramento~California\nOklahoma City~Oklahoma\nCharleston~West Virginia\nCarson City~Nevada",s==l||s==r] ``` [Try it online!](https://tio.run/##RVQNS@NAEP0roQgq3P0BsQe14tnaD2k95bByTJNpMmQzG2Z3qxHZv@7Nphah0OxkZt68N29TgavRmM/P98wNDTh/MhiJ89a/1zC4eO4j5uJZPtxwaF4@zsyPfxdyfvnTtcBnl6fx9Pzy5JchRje4Am85W9lQYpzZQI6AYcMTLtJDaw25@HXY8Nia0GyDi8uK7Ibnln1pG5QujgxsodGUWzTIENOrvuQaeY8StdIKFFp0ZclhnBRQ6WEUnCeOD/gGLr1SDhzn4BzkVXDovUZHZgvcxQW@Zn@t1Bt@AGOg0iTEeKNtqVCcNShgdoN93hzfKNf2C3DVnoxBRWBlqxVaLsgJJiVOURx2G57ibqePCZycs0FowyvKq8ZyER9JSmJSkHtCEYxrG3yVXUNtfWIMIuS2Qcp4ryiuM3vos0ehVHqqBajSWix2TwVyjnFV2QKziTPAhUpkk0LXaOAVBJPKnFsp@gFvoWldRSmcJG3R6AjxEUUn8z2236VcrWHMPeVBow@2xRriHbBLsq4V32f3EIyySzL0Y08DI4S0OFfrcUYKapIqWzlEVmCQyiourCjbMYh6IW10DgUlpZ7I5ZYd8YaXpmtagvikehOXqq7SrSwyvcWR0LtNdTNIyaXOkFdUgqbcWlZDmRBvlTmp5FPI6@MS0q9tNbhuRct2hKaIE6MzqIGOVlTMwzK@xxvx0bZzkO6g8LjCLhkgPnW20WZJE@OzGdSYjcl38Y@HSku9SS6Kv9HqxrXXFbkGJK@/NDhu/EaAa5Xdxzu1Usjrrm@ITVwKlon8jLw3qNdKa0dSfy3iGl02t@naxYl97U2bCzTJjnEMhrRlb5xlrf62DRxmO54SDRCD/R150r/s25hKX3U75C9wDwUMfqS7/5G@APLy2agFsmHWBr/2MuPsJHvPBv2tG3z@Bw "Haskell – Try It Online") After wasting a lot of time trying to golf an implementation of Huffman coding I realized the straightforward approach is probably shorter. Ah, well. EDIT: Thanks to @Laikoni for taking off 8 bytes! EDIT: Thanks again Laikoni for that additional byte. Good idea to use '~' EDIT: Thanks to Laikoni for taking off those 5 bytes! [Answer] ## T-SQL, 1402 bytes (counting size of .sql file) ``` create table t(s varchar(99),c varchar(99))insert into t values('Baton Rouge','Louisiana'),('Indianapolis','Indiana'),('Columbus','Ohio'),('Montgomery','Alabama'),('Helena','Montana'),('Denver','Colorado'),('Boise','Idaho'),('Austin','Texas'),('Boston','Massachusetts'),('Albany','New York'),('Tallahassee','Florida'),('Santa Fe','New Mexico'),('Nashville','Tennessee'),('Trenton','New Jersey'),('Jefferson','Missouri'),('Richmond','Virginia'),('Pierre','South Dakota'),('Harrisburg','Pennsylvania'),('Augusta','Maine'),('Providence','Rhode Island'),('Dover','Delaware'),('Concord','New Hampshire'),('Montpelier','Vermont'),('Hartford','Connecticut'),('Topeka','Kansas'),('Saint Paul','Minnesota'),('Juneau','Alaska'),('Lincoln','Nebraska'),('Raleigh','North Carolina'),('Madison','Wisconsin'),('Olympia','Washington'),('Phoenix','Arizona'),('Lansing','Michigan'),('Honolulu','Hawaii'),('Jackson','Mississippi'),('Springfield','Illinois'),('Columbia','South Carolina'),('Annapolis','Maryland'),('Cheyenne','Wyoming'),('Salt Lake City','Utah'),('Atlanta','Georgia'),('Bismarck','North Dakota'),('Frankfort','Kentucky'),('Salem','Oregon'),('Little Rock','Arkansas'),('Des Moines','Iowa'),('Sacramento','California'),('Oklahoma City','Oklahoma'),('Charleston','West Virginia'),('Carson City','Nevada') declare @i varchar(99) = 'Austin' select coalesce((select s from t where c = @i union select c from t where s = @i),(select 'Arstotzka')) ``` Fort this kind of task set logic trumps procedural logic making easy and fast to solve it on a relational DB. Below the ungolfed code. Note we can just run the create/populate part once in a separate batch ``` create table t ( s varchar(99) ,c varchar(99) ) insert into t values ('Baton Rouge','Louisiana') ,('Indianapolis','Indiana') ,('Columbus','Ohio') ,('Montgomery','Alabama') ,('Helena','Montana') ,('Denver','Colorado') ,('Boise','Idaho') ,('Austin','Texas') ,('Boston','Massachusetts') ,('Albany','New York') ,('Tallahassee','Florida') ,('Santa Fe','New Mexico') ,('Nashville','Tennessee') ,('Trenton','New Jersey') ,('Jefferson','Missouri') ,('Richmond','Virginia') ,('Pierre','South Dakota') ,('Harrisburg','Pennsylvania') ,('Augusta','Maine') ,('Providence','Rhode Island') ,('Dover','Delaware') ,('Concord','New Hampshire') ,('Montpelier','Vermont') ,('Hartford','Connecticut') ,('Topeka','Kansas') ,('Saint Paul','Minnesota') ,('Juneau','Alaska') ,('Lincoln','Nebraska') ,('Raleigh','North Carolina') ,('Madison','Wisconsin') ,('Olympia','Washington') ,('Phoenix','Arizona') ,('Lansing','Michigan') ,('Honolulu','Hawaii') ,('Jackson','Mississippi') ,('Springfield','Illinois') ,('Columbia','South Carolina') ,('Annapolis','Maryland') ,('Cheyenne','Wyoming') ,('Salt Lake City','Utah') ,('Atlanta','Georgia') ,('Bismarck','North Dakota') ,('Frankfort','Kentucky') ,('Salem','Oregon') ,('Little Rock','Arkansas') ,('Des Moines','Iowa') ,('Sacramento','California') ,('Oklahoma City','Oklahoma') ,('Charleston','West Virginia') ,('Carson City','Nevada') ``` And with that data persisted only use this query ``` declare @i varchar(99) = 'Austin' select coalesce( ( select s from t where c = @i union select c from t where s = @i ), (select 'Arstotzka') ) ``` The variable declaration is not mandatory, of course you can just put the input directly in the query and spare 10 bytes but I prefer my queries parametized. [Answer] # [Zsh](https://www.zsh.org/), ~~993 928~~ 924 bytes ***-4 bytes** thanks to @spuck's Bash answer, replacing `th Dakota` and `th Carolina`* ``` a=(_ Bat4\ Rouge Lou7i5a Indi5apol7 Indi5a Columbus Ohio M4tgomery Alabama Hel8a M4t5a D8ver Col9ado Bo7e Idaho Aust6 Texas Bost4 Massachusetts Alb5y New\ Y9k Tallahassee Fl9ida S5ta\ Fe New\ Mexico Nashville T8nessee Tr8t4 New\ Jersey Jeffers4 M7souri Richm4d Virg6ia Pierre Sou3 Harr7burg P8nsylv5ia Augusta Ma6e Provid8ce Rhode\ 7l5d Dover Delaware C4c9d New\ Hampshire M4tpelier Verm4t Hartf9d C4necticut Topeka K5sas Sa6t\ Paul M6nesota Juneau Alaska L6coln Nebraska Raleigh N92 Mad74 W7c4s6 Olympia Wash6gt4 Pho8ix Ariz4a L5s6g Michig5 H4olulu Hawaii Jacks4 M7s7sippi Spr6gfield Ill6o7 Columbia Sou2 5napol7 Maryl5d Chey8ne Wyom6g Salt\ Lake1 Utah Atl5ta Ge9gia B7marck N93 Fr5kf9t K8tucky Salem 9eg4 Little\ Rock Ark5sas Des\ Mo6es Iowa Sacram8to Calif9nia 01 0 Charlest4 West\ Virg6ia Cars41 Nevada) for w (Oklahoma \ City th\ Carol6a th\ Dakota on an in is en or)a=(${a//$[i++]/$w}) <<<${a[$a[(ie)$1]^1]:-Arstotzka} ``` ~~[Try it online!](https://tio.run/##RVNNb9swDL33V/BQoMmAHXoduoOboGvafCHJGgzNVjA2YxOWRUOSk7rDfntGOckGGJZkP/KRj08fvjjuev3eEb/23uAeg9gNLKTJCcbSsGe0CCObxbUWw/5ygIGYpto2HmYFC0zEhlwqci0kBrdYITySIcXFPxE/JLsnF8PEYSZwL@wJRhkWAknjA1tY0Tt6/eG1Cpig95gWjacQvCbdom1hSocN/BBXwgqNwUIxRPCgKTlDWKJSbeCBTrgJvXMqMEVf7NkY0vzWUhexcmQjSYd7Iuep1WW3012kZu@lcQwLTotKbAYv7HK2jDBnco5gKU0oNjDEUoJ2is6x3zYuh7lS@NbsMYKTJtfGVAJkSzB3sueMbEqwKCSjDYy8QU0@lCjMkAweUHMPxKbislNtj1jVvmD9HHWsySg/vJDTqkLkDbsI1RBLaeC0CbCSmkqEZ7RexVwqddjAHBujbcX2Y8FPjSVs4qS8QseshCaKsXXdhwUa4ryAqbjY5QCdTj6OEjOO@qzZp2K9Tmxm2qrWTteqMds8SjovhCy/Q@L4QzRojBGZK3tacI4WHsWqdUyj5R@QGZ4wLS@qx6euGZa105gdk8lgZJRczXJ2nLKd1f9XV2Iv5pygaztNBwW1cdqwbqWK9Es0qsMYS9V9wKGF7wELSIKJnoFvJDpghHv2Fbq0vLR@HvCDQ1uq0gGe1TdNWrYxH1Uwc5Rr6WMOwVC8OBqauPKk/ZC8mlB09npr5BD9mTqsovO0dsOaMLpkVqqRpcJzXZejtoDOUHcX1rps/ptQG/fxnnb4Ke0xw/7V3d3d9W98vcbXHlP/@vbnr9ufXz4nThOEjxL/HPtXVzu4OcV2oTfxHGU4bz51a/d6uzn@BQ "Zsh – Try It Online") [Try it online!](https://tio.run/##PVPbTttAEH3nK@YhEklRBaG@VvQhJKJcEoiSFFQRiib22F557bV21wmm4tvTsYMqWXsZnZ0zc@b43WT7pD/o7/FH/xUu0TprWKg6JZiq2hcuwk0Z81Yp6X8eYaxkXWxqAw@ZUDBzbKoK0g2MJG6wQLgmGWAbZ@wk2JJuX4QYK7hUPsFNjJmCUW2sByt6Q8NhYx2YoTEYZbUhaw0n27gN3NNuDb/DHFYoJWaMIIIrGYoYYelaXMMVHUAzehORgns02VZISbAKSurgKx1w9g50S9pQw1uS8IkpfaNqLWAhoqxwYngUOvUEwlyQ1gRLVdvsG1yj1v6m1inMg9I0cusyZFSn3AG3iR7BXKutiIOIYJGpmNbgSzeGiWp7n5DEHXK2sROF8aGOaywqkwkOskoVSaaDR9KFY1symzBu7JQUWRHVFlaqohzhzjWs1RI9u4Y51hJmHneouIbbuiSsW/0N46ZepGTJRBvd3RcoSaQZ3Ic2O@d6Y9@BJz9yjAcPsikqbuaJVfNSVmmeqUC8wUiLd4czucZLYcbiiNSFa4fnLmuucIdCwC1G@UFC34iqErCstJcmgmQMN1J6yv80CufvhDwHtzz4aIa6aQUaZ9TwlOCpUQUTLVFya1PMaQi/LGYwspJnDD8pTDnJpV@gjvKuj29wpd08CS3cBbaO8qZ9TAWElDowFdZKan3M6JHOO90mZNgkyiMDN2rHJWGksQisgjFKkYQlM5wN4YyLQi2pNeQTr@v/nhgjO2bIsm4xxsFRojTsoP@Qsy0Vm34NY2GbdkOtpNcGJpi301ElYAmCPwNUgtID/td6f/H0tPcsTk5eTnu7j8HRxcUFx557@NwXNOgNX/4MX75/HWljlX3P8WM/ODpK4LitghO2XMftvVP2k6kLtMJ9Hr50e7e8Hu//AQ "Zsh – Try It Online")~~ [Try it online!](https://tio.run/##PVNdb@M2EHzPr5gHA7F7KHK@04dVpA@OjTTJxYkRuxcUcXpYSyuJECUaJGVHOdxvT1dOUEAgl4vh7O5w9OrKt3w4Gr7Rn8MfuCAfbPBg2oJxa9pYhYTrJpNtZ3T8EWJmdFtvW4f7UhksAl@Ymm2HqaYt1YQr1hPq84KdT/Zs@xsJZQYXJmZcZ1QaTFvnI6z5hZyknQ@wIOcoLVvH3jsh24Yd7viwwT9JhTVpTaUgmHGpE5URVqGnDS75HbTgF5Ua3JEr90prxnrS8BG@thNhP4Ju2DruZMtziaRk7ExrFR5UWtZBhu/KFpEiLBVby1iZ9iuuyNp429oCy0njOr0PBTBtC@lfhqSIsbRmr7JJyngoTcYbxDrMMDf95HPWdCDhmgVpkr13cUX1zpVKkqLRjrUUw3e2deD7Yj4X3CxoOPUqbT3WZscV4VvoRKkVRX6DJbUai0jmM9LDTdswtb36TnC3UWp0I4W29nh@IM2qKHGXfJFuszjAY5wGLsK97uqdjPIoikWFKLQszUS9YGrVayA8oYsKLEQYVYS4CuTNdSv9HUgp3FBavcsXO7XbKax2NipyxTrDtdaRiT9MIvwi4heEzbuDFmS7XpxZyZ28Dx47U0uZFWkZ65YqHuNvTyWmXsvr4i9OCqG4iGuyaSUzfMWlDas88fg28W1adf1VrpFwEeBWea@5969gp7Y6KjZnJ@YwETtcm4O0Q6mleuINZqRVnjTC/3mMz9ISWc29ER9l3fzvhRmJU8Yi6J4yGp3kxuKA4X0ldjRi9g1mynfw5aZHGh3RMZ5T1b@NaUANlHwO3MDYkfxng590djZ4Up8@PZ8NDr9GJ@fn55J7GtDTUPFoMH7@d/z8x@9T67zxrxX9ehudnOQ47TsRwr7eaX8WZX35UemY6KX7CH477sflx@nbfw "Zsh – Try It Online") Manual compression by replacing numbers 0..9 in the array. Because Zsh uses 1-indexed arrays, we have to add a dummy element at the start. `$a[(i)$1]` gets the index of the matching array element. Adding the `(e)` flag disables pattern matching and uses plain string matching. If we don't do this, `Ut*` matches `Utah` and we will print `Carson City`. If the element is not found, this returns an index beyond the end of the array. We then xor with 1 and get the corresponding paired element. If our dummy element at index 1 was matched, this will be `$a[0]`, which substitutes the empty string. In any case, if this is empty, `${ :-Arstotzka}` will substitute Arstotzka instead. [Answer] # [Bash](https://www.gnu.org/software/bash/), 927 ~~978~~ ~~1003~~ ~~1051~~ ~~976~~ bytes One more edit, reducing bytes taken by spaces and newlines in $T. Also re-ordered the substitution for 0..9, fixing a problem handling "Carol1a", since the substitution of 1->"in" would have already been accomplished before that point. Editing my answer after @GammaFuntion's comment below; I was not meeting the original rules to handle all input; a string that partially matched a state or capital would give wrong output. His/Her Zsh answer inspired me to also use the XOR rather than the modulo 100 indexing and to do some manual compression using numerals 0..9. I wrote a script to do some quick and dirty calculations on the input list to decide which ten strings would give the best byte reduction. Then used that script iteratively to reduce the strings. Check it out here: [Try it online!](https://tio.run/##TVNtT9tIEP4@v2LVRlUoiuWX2mkaOAmCWkITQCQtqjg@TOyJvcnam9tdJ/igv50bB3qtZMue2dEzz4u9QFs8P1NaaNEj8WauHSpxLEa6rpwQYuaMrHLRVVQdvBnuCqlIGMJMVMIOMy3uRKcSvdyJQNy/e/c/TOeuet95fGt/3v/tOhXfVnT3NYNkuqKjo6NO9w@0PdZSm253dRzEw87qr2C46vUODh5fuvLYH3bu5OHq/uh4jzOUh4ft6X5j59F@kp9WP4dif7ULnqw27qmu5D@il@4L0WOi5kA8id/V8/MpOt@70XVOMK4yGeJGqwhGWtXlorYw9V2uy0ED56QShLNkO4BTHRGc1NYF/GqdDydqETYwR6Ww6FsimIUOvc8El/1iK5UimJuE5y5ouRxYH25kWpR@BtdyYAjO0ZhoUZucMXNGRbg2eiuzJCU407xv5Kdx1jLZkJKDdt4tuTHXG1ojzDBw3jXWCi7qirCGSZBqVcENKpJ5AVPMIh@uVFNuJEMXOpEPMAltkMO5zzJVDReYrpnWbGOCfClJZa/6ef6kql4dKahJKpaGynkTXJM3kq6BE6dYK5xGJZp0DZ9NuF7Grp2iEibSOUXsLp@ckfWmOiDLZ6nBMnEartZsmC7xBWpUoFHU@jlCY/2X5kTXEYfymg1cFVKz3bjAEltHuMVUY8w0jDPGgjk99GHat5gWtSXnLFzSzvsRMzUVywz35ZQeZMqzrMe2cbW9i4GlBqaR1bWR8F2aPGD5M11/hOukso3ahlxPMSC4KXRG3tiqMGNZCndoXjDOsdzYQnL1fVD6joOrKHUyrR18DS3zCngh/1@soL9uqSzM/hl/gNso9W0At/0iyNsvysh/fV7HH4rMQ458h1K27CIrNxsJY6UCHbX0PjAn07RUbhtdcqjfHBbwheJctsgf4Wvi6nTdwJWhvAVet0zGesfOoZLLuOK5X0HALfvv/RJ/SVvM8D8 "Bash – Try It Online") ``` T="Bat8.RougeLou3i2aIndi2apol3Indi2aColumbusOhioM8tgom9yAlabamaHel6aM8t2aD6v9Col5adoBo3eIdahoAust4Tex7Bost8M7sachusettsAlb2yNew.Y5kTallah7seeFl5idaS2ta.FeNew.MexicoN7hvilleT6nesseeTr6t8New.J9seyJeff9s8M3souriRichm8dVirg4iaPi9reSou0Harr3burgP6nsylv2iaAugustaMa4eProvid6ceRhode.Isl2dDov9DelawareC8c5dNew.HampshireM8tpeli9V9m8tHartf5dC8necticutTopekaK2s7Sa4t.PaulM4nesotaJuneauAl7kaL4colnNebr7kaRaleighN51Mad38W3c8s4OlympiaW7h4gt8Pho6ixAriz8aL2s4gMichig2H8oluluHawaiiJacks8M3s3sippiSpr4gfieldIll4o3ColumbiaSou1Annapol3Maryl2dChey6neWyom4gSalt.Lake.CityUtahAtl2taGe5giaB3marckN50Fr2kf5tK6tuckySalemOreg8Little.RockArk2s7Des.Mo4esIowaSacram6toCalif5niaOklahoma.CityOklahomaCharlest8West.Virg4iaCars8.CityNevada" for t in th.Dakota th.Carol4a an is in or en as on er;{ T=${T//$[j++]/$t};} for t in {A..Z};{ T=${T//$t/ $t};} S=${T//. /.} U=($S) for s in $S;{ [ "${s//./ }" = "$1" ]&&echo ${U[i^1]//./ }&&exit;i=$[i+1];} echo Arstotzka ``` [Try it online!](https://tio.run/##TVLbbtpAEH3PV1gIRa0imeAbRhEPDiiFBBMUk0RtlEqDPXinXnvR7prgIL6dLtCqfVntzJy5nTNLUOxwWAxat6BD@0nUOU5F7ZIDkyoz71pw9/wbCl6Xy1o9MhJxqHNR9puIwxJKGCMPwPgcGAWbvgH6kIlb4eIkAyaiWmlvgdverVA6jHsKUlYr1FpFfOk0M/ywv/vFAjgH1lOId9ynDBJHg32Hx2iMW0rFrMc2xDkuggqVgS1koMNj@L6vsLnH1aqvwthVopb0RCkrw@yFZO4RzKkvMRH19RikdJe1zOdBpRq@cQiiOjfjQQwezqXYUBak@MREhvZEcScbiU1/hBw@QOIwTP3s2HAM5VoxkmhWXiOn/ku/DLUprld@NgwrTDWltV6INRbw4KheAp6251Dz2DOzCw33dYVQR7xXwNRLBa9muJTGeAKOlLOZ340hc8NXNw2V98ibck3w2mNersM5EwFtI0mfIUwd5eWx2ZVyZxwafXg9NqMS3UNanMhwFa3XlKyll68IeTbh3BPuWUoCw0k3qqqTyDHIxiw8ZNgYgl8bUXp5AlzbUyjQHpJunjWwSHOjyzf0c4JbtwSZFjP/@k46xcrXD4Gu06IxWVg@SszDKWnN0VxVWkSyMESMUNmx8FBNxAckkEooAy2GwGnlVwSPhTkBUcKp3V9jyEByNJfzah77j6RDkCo8wWa4gQxaFyshLW1RZWlmj6AwJB9/Bie4BxZUFqlj1KCwskBZorJQ3uysxaC9W3Q67bdfV1fvnbbe3@z/1dpFtv1j/x9Kd6wzJDk7bKtj7y@eB1/ayddT2qlJOzEpb1arvVMG0rH2LWtgrG7Ler@8xJQJq717fqOf3fdz2Di3pG9o0H6jq@67KX8CRVJpoT8LOBwO5zV/Aw "Bash – Try It Online") ~~[Try it online!](https://tio.run/##NVLRbtpKEH3frxghVLWKZGxcTFHEgwNKIQ0JikmjKkqlwR7srddetLsmcaN8O3cMty9j78zZMztnzhZtcTwm094VOt970E1OcKubUA5RLOuMP3utQjj/iplWTbVtLNwXUouV73JdTVqIFW6xQrEgFSFwmqHz6DABxo8w0@JKhwTLDAst4sa6ADb0NuasdT6sxhbTorHknBWx2g5buKNX79eoFBtUCouxJYJrNZIZimTo0LumE2JFbzLV4m5cHKRSBJuoJstYsTER83aQm4mlVtzQbjex3Cm0ujFSPMi0qPwMfkqTBxLFWk4MQaKbb2KBxoTbxuSwjmrbqsOQ63GT86N5MAxIrI0@yCxKCR4KnZG3tGqYibnmaeek8BUNiZmfjrLTAxZY7W0hOceq7EnJCfycVL7rGrkdg2Z@TamTaePERu@pRPgxtGORYOC8NTYKVgFPpR2Km6YmbFjrcYniNki1qrnF1nTHB1Qk8wLuRl/FCrPQh6cw9W0g7lVb7SXC07gIcueLdaEj@QaxkX99ZhnaIIcVyyHzoVj4vF3VwIKHkFLcYFqeRQut3O@lSPYmyHeSVAZLpQId/m8Hpmftvoq4rs9mWaFpO1FmBbW8E3hqdRXkPJNy3i2W5M2ka@HRYSFip3ij8J1GOQt9FVZo0pLH@CauzbDcjRz8iFyTlm13myq4N5T74lY6p4jdytjYlJ1gc7LeSgdkYalf2SeYGqwip2GGSu5GNbPfl2wmXeG5/b8TvxKNos6JTxy9f6aYobH@GXpHB8ywJ3bagANZg667iBwtuMJjqFYBApeJ06fcHEteGpC5fIdk2n9PBoP@85@Li5dB331cfojH6ed@8uVEaTuyfsLAZ@j13@1g4A3gowdTPgU9ePn0idJCQ//98Vn@Dl7OZU6@SXcpp/1neRG8MOMJFBvrtPtb4vF47AT@Dw "Bash – Try It Online")~~ ~~[Try it online!](https://tio.run/##NVNdb@I6EH33rxghtGpVKSRkgUVcHlJQL3RLixq61VXVKw3JkJg4MbIdShb1t3OHcvfFyYzPfJ05XqPNT6fV@EpXICtAPi243Jug0SpA0AaI3V@@KRbaIZC5FvG4dYvO9551nRE86DqUXRTzKuXPTqsQLr9iolVdrmsLT7nUYuG7TJfDBiKFayxRzEj1EdjN0Gl/PwTG9zDV4laHBPMUcy2i2roAVnQYsNc6HxYDi0leW3LOikituw080of3T68QK1QK84ElgjvVkymKuOvQu6MvxIIOMtHicZDvpVIEq35FlrFiZfqc9wy5H1pqxD1tNkPLlUKrayPFs0zy0k/hlzRZIFEs5dAQxLr@IWZoTLiuTQbLfmUbte/yfVRn3DQPhgGJpdF7mfYTgudcp@TNreqmYqp52ikp/EBDYuInvfSrgRmWO5tL9jErO1JyCL@Gpe/OhdyGQRO/osTJpHZipXdUIPzs2oGIMXDeEmsFi4Cn4j2J@7oirJnrQYHiIUi0qrjE2pzNZ1Qksxwee9/FAtPQh9cw8W0gnlRT7iTC6yAPMueLZa778gCRkb99ztK1QQYLpkNmXTHzebuqhhkPIaW4x6S4kBZaudtJEe9MkG0kqRTmSgU6/F8OnJ65@y6iqrqIZYGmOZMyyanhncBro8sg45mU8x6wIG8iXQMvDnMROcUbhb@plzHRt2GJJil4jB/iznSLTc/Bz76rk6I5R1MJT4YyXzxI5xSxWhkbmeJM2JSst9ABWZjrD9YJJgbLvtMwQSU3vYqzPxUsJl3ipfwfi7tEo@isxFc@vT@i4Bdj/Qv0kfaYYktstLm62o79UXv7V@CPtjc319dHiMftY9zptLed9nH1tn3//BzBp3gZX7XjayHH/jkM7Pk1tuNRquENWu2j7XS8Dny2YMxW0IL3b98oyTW0jy9v8t/g/XLNzoN0Izluv8mb4J2jKxJfuMhYp93vAk@nE@@UKnn4Dw "Bash – Try It Online")~~ ~~[Try it online!](https://tio.run/##PVPBTttAEL3PV1jIRaWVDBx6Qj6EIJoACRGhoApxmNgTe@T1TrS7TjCIb09nnbaSD7szszNv3nteoa/3@yIfc@ihzK@wkYBA@RidGLYINp@LCzVIft8YrKVF8PlSOg1t8yd2FVtGWOZfLzGIzR6kqwimtmS0uNEWHsZiunbVeZiJDZW05HqYkCFtfkV2Sw4uhT3BqPOBrV68NoKRWaHt4RGNTkXviWCJNmB2TTBX0Fs2huDRkY3VN7Rek/N6euCibsWWsGByjmCCzrFfda7SAZWOQFg42XJJtiC4kjh/LLYQVw4AN2T0YXwW1jH2KBtqdEFkG7IFdgZuOkvYwR3rI6MD0RBXNcyw5Ajg3vTtRilZ1EKW3@AOrWdbwUSsEmE6uMGiiYXLjdP4msmUfznSVyP7n7aaerI2rm1CdocNZWkBo2AiC3DJvkVXNHDt0DaKNMQ6ahVWCIZUB81dkc9mwpa8JguHbSQLUomNxjU6QwPVqrXiicE76dhH5f4pCPc1i2qBK1ThIz8xqGjFYSkwLdUR8EhvqOqqSFjUnacQPMxpl/0Wp/i0lEscAjN64yLW61qDojF4o7pRDzP2XjrHkG4h9VmqAmqZ780Wo8Fmyj/BQy0lZVOvHJS6ncEdukOXCbYbX7Pensip/iGKaqkIXHQBblWDCJHj4Ghw3cg3EdTKDYdU1yd4Zl9IVAue1WEqzmBEx@@iS8/UWFyhVWvskHkAHL/NhmFq9F9REw/IScG6foD43Esbtf8VsIafJPq3HGaVcKtadEXTw72jahjTHEBOZacMo2EVNW6eCjyrTpnyMqctlngCnP84A00nPmGbpB/Ll2@vnxelJC/JUfrhT0@z0@TzKMn1dn6UvB4fU1HLUJfy6yGrsTcOF5ynL1/5@/nJl/Ozs1dtoSQPxSOn1gjvDe73@4OlkmipPw "Bash – Try It Online")~~ ~~[Try it online!](https://tio.run/##LVNLb@JADL77V4yqqD1WPVc5pKAutLwEbNGq24NJ3MTKZIxmJpR0tfvXWU@LhCCZsf35e7DH0JzPZT7iOECVj7GViED5CL1YdgguX4iPDUi@bC020iGEfCO9Hh3zF/Y1O0bY5FcPGMWZtfQ1zaTnwKjdU1el34POCpdnGIntu30flg0LzMXFWjryQ2Fxjzp9QpYcpvNUPCZ3JK8t4rESeBAONK10Dyj6ENlt6YRBj4OCzzEELJs@UIwBCrtHNyzow/wS38IWra6vFUSPOowrXRoVwzxSqpnTiUuBhcpxZGtpS85RKoatJ6fDU9ET@UADPNH7uz4pIIcgvWdYc9l04qrsCCsm7ykLJqtggt5z2Pe@Xum4MNgjJrGKvtbdcY7sCFZejlyRK2ndSEVmGiy6CsaitMdk8QM9qWSuFF@lHSbYHULDepgkOpBVvBfyih4TXnzXOi13VEYu@whbOVCLz@iC6rRRyGhW2Ns5J37J66feEfaqfmgRZqxAVsnu/df7Gi1x3WTOZAqIFSvrHYdSXGAHSzt0B8adisauVpFg1Qg5PhWeP0Xdm2Gqq@cqD9foYCJOzbf9RGkxwxOW7UXG9DkcGDYHrw3vTLaaWg2g@n0JDGMSlaBwlzzN0Q9fWo0aGpJdu0E6bVaWNpoZtmSy0vyM2EARbfL6B4nmFeGBQ4e@bBOtCh49ulZli89qdF@2QxpA3dJTrYxmHKMlzXXZFr79lnFMwcxF3QtT@Ug5Kj12KSUjtKyTksmZJPRMdDv0llI@d/ptNCL631LW6XpBR6zwCqaPmzy7@e1uQLtNMKy3m/tKzOurUdb5P5Pdmbe362sqG537J9zeZnd/9fXEUcsc3X9dFF5h4meL5/P52/f/ "Bash – Try It Online")~~ [Answer] # Prolog, 1221 bytes ``` p(X):-L=['Baton Rouge','Louisiana','Indianapolis','Indiana','Columbus','Ohio','Montgomery','Alabama','Helena','Montana','Denver','Colorado','Boise','Idaho','Austin','Texas','Boston','Massachusetts','Albany','New York','Tallahassee','Florida','Santa Fe','New Mexico','Nashville','Tennessee','Trenton','New Jersey','Jefferson','Missouri','Richmond','Virginia','Pierre','South Dakota','Harrisburg','Pennsylvania','Augusta','Maine','Providence','Rhode Island','Dover','Delaware','Concord','New Hampshire','Montpelier','Vermont','Hartford','Connecticut','Topeka','Kansas','Saint Paul','Minnesota','Juneau','Alaska','Lincoln','Nebraska','Raleigh','North Carolina','Madison','Wisconsin','Olympia','Washington','Phoenix','Arizona','Lansing','Michigan','Honolulu','Hawaii','Jackson','Mississippi','Springfield','Illinois','Columbia','South Carolina','Annapolis','Maryland','Cheyenne','Wyoming','Salt Lake City','Utah','Atlanta','Georgia','Bismarck','North Dakota','Frankfort','Kentucky','Salem','Oregon','Little Rock','Arkansas','Des Moines','Iowa','Sacramento','California','Oklahoma City','Oklahoma','Charleston','West Virginia','Carson City','Nevada'],nth0(I,L,X),J is I xor 1,nth0(J,L,E),write(E),!. p(X):-write('Arstotzka'). ``` Most of the byte count comes from the list of states and capitals. All names of states and capitals need to be quoted atoms since they begin with upper case letters, costing us 202 bytes in 's alone. **How it works** ``` nth0(I,L,X) ``` Gets index **I** of element **X** in list **L**. ``` J is I xor 1 ``` Xor index with 1 to get index of return value. ``` nth0(J,L,E) ``` Gets element **E** at index **J** of list **L**. If any rule fails, print Arstotzka **Example** ``` >p('Austin'). Texas >p('Texas'). Austin ``` [Answer] ## R, 1294 bytes ``` d=data.frame(a=c("Baton Rouge","Indianapolis","Columbus","Montgomery","Helena","Denver","Boise","Austin","Boston","Albany","Tallahassee","Santa Fe","Nashville","Trenton","Jefferson","Richmond","Pierre","Harrisburg","Augusta","Providence","Dover","Concord","Montpelier","Hartford","Topeka","Saint Paul","Juneau","Lincoln","Raleigh","Madison","Olympia","Phoenix","Lansing","Honolulu","Jackson","Springfield","Columbia","Annapolis","Cheyenne","Salt Lake City","Atlanta","Bismarck","Frankfort","Salem","Little Rock","Des Moines","Sacramento","Oklahoma City","Charleston","Carson City"),b=c("Louisiana","Indiana","Ohio","Alabama","Montana","Colorado","Idaho","Texas","Massachusetts","New York","Florida","New Mexico","Tennessee","New Jersey","Missouri","Virginia","South Dakota","Pennsylvania","Maine","Rhode Island","Delaware","New Hampshire","Vermont","Connecticut","Kansas","Minnesota","Alaska","Nebraska","North Carolina","Wisconsin","Washington","Arizona","Michigan","Hawaii","Mississippi","Illinois","South Carolina","Maryland","Wyoming","Utah","Georgia","North Dakota","Kentucky","Oregon","Arkansas","Iowa","California","Oklahoma","West Virginia","Nevada"),stringsAsFactors=F) print(ifelse(any(e<-d[,1]%in%(n<-scan("","raw",sep='$'))),d[e,2],ifelse(any(f<-d[,2]%in%n),d[f,1],'Arstotzka'))) ``` It is case senstive according to the input shown as example. Ungolfed code (slightly different in the position of scan): ``` n<-scan("","raw",sep='$') print( ifelse( any(e<-d[,1]%in%n), # test city d[e,2], # if yes return the state ifelse( any(f<-d[,2]%in%n), # test state d[f,1], # return city 'Arstotzka' ) ) ) ``` [Answer] # Java, 1312 ``` public class a{public static void main(String[]x){List<String>a=Arrays.asList("Baton Rouge","Louisiana","Indianapolis", "Indiana","Columbus","Ohio", "Montgomery","Alabama","Helena","Montana","Denver","Colorado","Boise","Idaho","Austin","Texas","Boston","Massachusetts","Albany","New York","Tallahassee","Florida","Santa Fe","New Mexico","Nashville","Tennessee","Trenton","New Jersey","Jefferson","Missouri","Richmond","Virginia","Pierre","South Dakota","Harrisburg","Pennsylvania","Augusta","Maine","Providence","Rhode Island","Dover","Delaware","Concord","New Hampshire","Montpelier","Vermont","Hartford","Connecticut","Topeka","Kansas","Saint Paul","Minnesota","Juneau","Alaska","Lincoln","Nebraska","Raleigh","North Carolina","Madison","Wisconsin","Olympia","Washington","Phoenix","Arizona","Lansing","Michigan","Honolulu","Hawaii","Jackson","Mississippi","Springfield","Illinois","Columbia","South Carolina","Annapolis","Maryland","Cheyenne","Wyoming","Salt Lake City","Utah","Atlanta","Georgia","Bismarck","North Dakota","Frankfort","Kentucky","Salem","Oregon","Little Rock","Arkansas","Des Moines","Iowa","Sacramento","California","Oklahoma City","Oklahoma","Charleston","West Virginia","Carson City","Nevada");int b=a.indexOf(x[0]);String s=b<0?s="Arstotzka":a.get(b/2*2+((b+1)%2));System.out.print(s);}} ``` [Answer] # Javascript, 1042 ``` var x=prompt(),a="Baton Rouge,Louisiana,Indianapolis,Indiana,Columbus,Ohio,Montgomery,Alabama,Helena,Montana,Denver,Colorado,Boise,Idaho,Austin,Texas,Boston,Massachusetts,Albany,New York,Tallahassee,Florida,Santa Fe,New Mexico,Nashville,Tennessee,Trenton,New Jersey,Jefferson,Missouri,Richmond,Virginia,Pierre,South Dakota,Harrisburg,Pennsylvania,Augusta,Maine,Providence,Rhode Island,Dover,Delaware,Concord,New Hampshire,Montpelier,Vermont,Hartford,Connecticut,Topeka,Kansas,Saint Paul,Minnesota,Juneau,Alaska,Lincoln,Nebraska,Raleigh,North Carolina,Madison,Wisconsin,Olympia,Washington,Phoenix,Arizona,Lansing,Michigan,Honolulu,Hawaii,Jackson,Mississippi,Springfield,Illinois,Columbia,South Carolina,Annapolis,Maryland,Cheyenne,Wyoming,Salt Lake City,Utah,Atlanta,Georgia,Bismarck,North Dakota,Frankfort,Kentucky,Salem,Oregon,Little Rock,Arkansas,Des Moines,Iowa,Sacramento,California,Oklahoma City,Oklahoma,Charleston,West Virginia,Carson City,Nevada".split(","),b=a.indexOf(x),s=b<0?s="Arstotzka":a[Math.floor(b/2)*2+((b+1)%2)];alert(s); ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 1009 bytes ``` {split("Baton Rouge,Louisiana,Indianapolis,Indiana,Columbus,Ohio,Montgomery,Alabama,Helena,Montana,Denver,Colorado,Boise,Idaho,Austin,Texas,Boston,Massachusetts,Albany,New York,Tallahassee,Florida,Santa Fe,New Mexico,Nashville,Tennessee,Trenton,New Jersey,Jefferson,Missouri,Richmond,Virginia,Pierre,South Dakota,Harrisburg,Pennsylvania,Augusta,Maine,Providence,Rhode Island,Dover,Delaware,Concord,New Hampshire,Montpelier,Vermont,Hartford,Connecticut,Topeka,Kansas,Saint Paul,Minnesota,Juneau,Alaska,Lincoln,Nebraska,Raleigh,North Carolina,Madison,Wisconsin,Olympia,Washington,Phoenix,Arizona,Lansing,Michigan,Honolulu,Hawaii,Jackson,Mississippi,Springfield,Illinois,Columbia,South Carolina,Annapolis,Maryland,Cheyenne,Wyoming,Salt Lake City,Utah,Atlanta,Georgia,Bismarck,North Dakota,Frankfort,Kentucky,Salem,Oregon,Little Rock,Arkansas,Des Moines,Iowa,Sacramento,California,Oklahoma City,Oklahoma,Charleston,West Virginia,Carson City,Nevada,Arstotzka,",S,",") for(x in S)if(S[x]==$0)break $0=S[x-1+x%2*2]}1 ``` [Try it online!](https://tio.run/##VVPLbttADLzrK4QgBZKWBZLcc3BspHnYsRG5CYoiB1qiJVarpbC7sq0U/XaX60eKAjb0muUMh0Nc19vtb98aDmcnNxjEps/SlQRj6dgzWoR7W8RrK4b98QGGYrpm0XmYViwwERtKacj1MDC4wAbhjgwpLn6J@BHZFbl4TBwWAjfCnuC@wEpg0PnAFua0Qa8fvIqACXqPedV5CsFr0QXaHp5onf4QV8McjcFKIURwqxW5QMhQmdJb2qEmtOFc4Al9tWJjSItbSzv83JGNDBH2QM5TDw@0XOpdpGXvpXMMz5xXjdgCXtiVbBlhxuQcQSZdqNIR1hK0SXSO/aJzJcyUwPdmhRE76ErtSbtHtgQzJysuyOYEz5UUlN57g1p6JNGSERlco1Yeis3FFTthd9i0vmJ9Gw1sySg5vJBTSSGyhmVE6glLeeC8CzCXlmqER7ReXcyUOKQz7Iy2FDuPah86S9jFCXlFjlnpTPRh4XYvntEQlxU8idMOh@h04HGCWHC05pV9LtbroKamb1rt8lXdZVtGM2eVkOUNDBy/ix4aY0SWSp5XXKKFO7GaGNOp@DUywwPm9dHw@Gtbhqx1embJZAq4N0quGTkETdn2xn/IGthjJCfo@p2fw4r6OGZ47aWJ7BmakI6xpnTIoYfvASsYBBODAt9IdLAIN@wbdHl9aPsw2FuHtlaPAzxqWrq87mMxamDqqFTZYw7BkK6KHhy4em/6iHw6EZ24romsYyJzh01MGwzRsJaL2ZjWGl1pcK/p@KTi0RnaZf9VL@lH7rRjNWqPfqIVatQHTnHhXWd2Apn@T84TLX62Sdmm2Tkvz7Kfm7fr69OL84UjrJPTi2t98/Xyy@bT1eertz@X2@0voeSwqsl@VZPDqib7VU2OypJ/ypL/lCV/AQ "AWK – Try It Online") If there's a way to shrink this, I'd be happy to hear about it. :) [Answer] # [J](http://jsoftware.com/), ~~843~~ 829 bytes ``` -&.((<;._1'-rstotzk7Bat> Roug/Ind6?p@;[[email protected]](/cdn-cgi/l/email-protection),Hel97D9v4,Bo;e-ust=,Bost>-lb<y,Tal1h2se/Sa8a F/N2hvill/Tre8>,Jeff4s>,Richm>d,Pi4r/H3r;burg-ugust7Provid9c/Dov45>c:d.o8peli4,H3tf:d,Topek7Sai8 Paul,Juneau,L=c@n,Raleigh.ad;>,Olymp6,Pho9ix,L<s=g,H>@ulu,Jacks>Apr=gfield5@umb6-n?p@;5hey9n/Salt Lake City-t187B;m3ck,Fr<kf:tAalem,Little Rock,Des Mo=esAacrame8o,Ok1homa City5h3lest>53s> City0evad7West Virg=6,Ok1homa5alif:n6,Iowa-rk<s2,Oreg>,Ke8ucky0:th Dakot7Ge:g6,Utah,Wyom=g.3y1ndAouth C3@=7Ill=o;.;s;sippi,Hawaii.ichig<-riz>7W2h=gt>,W;c>s=0:th C3@=a0ebr2ka-1ska.=nesot7K<s25>necticut,V4mo80ew Hampshir/De1w3/Rhode Is1nd.a=/P9nsylv<6Aouth Dakot7Virg=6.;souri0ew J4sey,T9nesse/New Mexico,Fl:ida0ew Y:k.2sachusetts,Tex2,Idaho5@:ado.o8<a-1bam7Ohio,Ind6n7Lou;6?'rplc(45{21;/\a.),._2<\',A,Me,,Nlaasarer,Ciaa,ntenorisaninonnaol,S')i.<) ``` [Try it online!](https://tio.run/##TVJdb@I6EH3fX5GnpZUmSQkfgXwtFNSFLm1R29vqSiuthmRIfOPYyHZo6f74rqFa9b7ZZ8Zzzhmf/97ft6nnuF@9s7Mk9n51O67SRpq3OrxEkzn3si39pSiG33aTeDBpm02rPTkqZdM/wIL4OJyP9324lDG5rTapPWmTuXyTHOARebcKNPkPOELnyr8Nqj3j3H9UNMrgmrbbvs7gnuVVkxWwZn3lL3oq3rSqdNvSTgvXSu5ZMc79udz3B1keFZZ7R5z1YdEz26iAR7mjOnxANnLW2HK4bgVhC6s0nwi4R06srDws4gzu@KHZDWFdyTF7hVWi0xIW2aTlLVxjXutsulNpuWXEi5PPoStOnis6jIW1wI2zwpqcGTMH13RH4WXc9PIarlRSbyMztVwNrJgxnOzWbGFO2rmRKekp5gobGkm4q7uVbPA0Y1D1ONldDXo6OwEXtMcifLaY88RUmQ7/tg@Qs20khrCUL@iqOtEB3CkqM/hBozavDxeRqZw51tKE3ykqh/CPwQqeD7JJS6936IpiKlvbMutN0nDJeSpjL9axZrsdgwW@IGOe/QVWJq5ib1n4HFRpaTJ4jvNMp6fpx6d4QRsV1Oh2dY1eKkhbwh9WzSATlBuWtwae@o0cXdCLs8Bmpyum/Dl1X3r@fSULcpbaavEw9ddjoQ98nww/hH1o/3BtlclWseOM674mG6OxZbIpurXIDb2yXMIVj1iBx5Z/o9oLNOZVq8kYDY/0GsCywEoOJhEW0uYlsYI32IR3FZNwjLIIV7KNh986asfzs/7gd9CN/Z/onYP3K0h@dmAKNwRwyxE1KlIwY4ggDAmpmEbBhBQCJYeHzjnzkvN3yivpbJ3Oce2dL39vT6QaKcwnMFU1Co36E5mT2JP6vM9QvP2/PrPhIyGo8/4H) ]
[Question] [ Given two positive numbers `N >= 2` and `N <= 100` create a matrix which follows the following rules: * First Number starts at position `[0,0]` * Second Number starts at position `[0,1]` * Third number goes below First Number (position `[1,0]`) * Following numbers goes in "slash" direction * Range of numbers used is `[1, N1 * N2]`. So, numbers goes from starting 1 to the result of the multiplication of both inputs. **Input** * Two numbers `N >= 2` and `N <= 100`. First number is the amount of rows, Second number the amount of columns. **Output** * Matrix. (Can be outputted as a multidimensional array or a string with line breaks) **Example:** Given numbers `3 and 5` output: ``` 1 2 4 7 10 3 5 8 11 13 6 9 12 14 15 ``` Given numbers `2 and 2` ``` 1 2 3 4 ``` Given Numbers `5 and 5` ``` 1 2 4 7 11 3 5 8 12 16 6 9 13 17 20 10 14 18 21 23 15 19 22 24 25 ``` The shortest code in bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 bytes ``` pS√û·ª§s ``` [Try it online!](https://tio.run/##y0rNyan8/78g@PC8h7uXFP8/vNxI3/1R05qsR437Dm07tO3/f2MdBVMdBSMwAjJMAQ "Jelly ‚Äì Try It Online") ### How it works ``` pS√û·ª§s Main link. Left argument: n. Right argument: k p Take the Cartesian product of [1, ..., n] and [1, ..., k], yielding [[1, 1], [1, 2], ..., [n, k-1], [n, k]]. S√û Sort the pairs by their sums. Note that index sums are constant on antidiagonals. ·ª§ Grade up, sorting the indices of the sorted array of pairs by their values. s Split the result into chunks of length k. ``` [Answer] # [Python 3](https://docs.python.org/3/), 91 bytes ``` def f(n,k):M=[(t//k+t%k,t)for t in range(n*k)];return zip(*k*[map([M,*sorted(M)].index,M)]) ``` [Try it online!](https://tio.run/##LYxNCoMwEIXXeorZiDNpqKB0Y@kRPIG4EExaCZ2EdKQ/l08N7WrevPfxhbfcPHcpLcaCRdaO@uEyojSNO0jltJD1EQRWhjjz1SArR9M5Gtkiw2cNqJwa73PAcdDq4aOYBQeajisv5qX3RCkbdjU4yhrsNJxIA7Ya2nxP@e/LImPRPzNjf/heFiGuLFhX7QY1KHBQZYjK/0DpCw "Python 3 ‚Äì Try It Online") [Answer] # [R](https://www.r-project.org/), ~~101~~ ~~60~~ 54 bytes ``` function(M,N)matrix(rank(outer(1:M,1:N,"+"),,"l"),M,N) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NXx08zN7GkKLNCoygxL1sjv7QktUjD0MpXx9DKT0dJW0lTR0cpB0iCFP5P0zDWMdXkStMwBVL/AQ "R ‚Äì Try It Online") *Thanks to @nwellnhof for the suggestion of `rank`* Ports [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/163275/67312). Old answer, 101 bytes: ``` function(M,N)matrix(unsplit(lapply(split(1:(M*N),unlist(split(x,x))),rev),x<-outer(1:M,1:N,"+")),M,N) ``` [Try it online!](https://tio.run/##LYxBCoAgEEX3nSJazdS0iGgTXUHvIJEgmImNYac3o1af//7jh6zrpc86upXN4UCQxF1xMAmiO701DFZ5b2/4yjCDaCVSdNac/MNECREpbBdSWvoj8haKKWiYJTVdU7b3N2sYacJKw1QiPw "R ‚Äì Try It Online") `split` is doing most of the work here; possibly there's a golfier algorithm but this definitely works. Explanation: ``` function(M,N){ x <- outer(1:M,1:N,"+") # create matrix with distinct indices for the antidiagonals idx <- split(x,x) # split into factor groups items <- split(1:(M*N),unlist(idx)) # now split 1:(M*N) into factor groups using the groupings from idx items <- lapply(items,rev) # except that the factor groups are # $`2`:1, $`3`:2,3, (etc.) but we need # $`2`:1, $`3`:3,2, so we reverse each sublist matrix(unsplit(items,x),M,N) # now unsplit to rearrange the vector to the right order # and construct a matrix, returning the value } ``` [Try it online!](https://tio.run/##jZHBTsMwDIbP7VNYg0MCAWmbdql4he0ZlrVuF6lLKsfZihDPPtysEwJxoJfIbv4v/n/TtYW3l2ubfM0ueLU1O/1RjtKDkBhJLautWVY7s3he6KIoHqAmtIxwskxuhIvjIzQushMAON@4GiO0gYCPCNaza5ztgrd9LF2TuXHoHavRjDdeLkXJAVpbsyg7CmmQ64yn@C1YVmr7tNMm@V6eUwLTWuQ@XGbEfOEPFKTofJcnyg0pZEYKJxDK9zu9HYb@XeXaEJ71NB6ONQ4sWssZ8BNsCcuiyD4e96t9tTRyrvfVyqwNKOT6VcMhMVwQPGJTwj@/X7i1WRmIYcLIXEgRAW19hJgOUxjlbRkq@VtUNwejNtM2izmk@SdIOLJBIus7zI7OmB1Jf6rIdUeGQA3S3Zn1DdTBR6YkO7bz6o1gOJG/J3u2fcLy89qqtdnoslUbOa5f "R ‚Äì Try It Online") -- you can use wrap a `print` around any of the right-hand sides of the assignments `<-` to see the intermediate results without changing the final outcome, as `print` returns its input. [Answer] # Java 10, ~~121~~ ~~120~~ ~~109~~ 105 bytes ``` m->n->{var R=new int[m][n];for(int i=0,j,v=0;i<m+n;)for(j=++i<n?0:i-n;j<i&j<m;)R[j][i-++j]=++v;return R;} ``` -11 bytes thanks to *@OlivierGr√©goire*. -4 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##jZExa8MwEIX3/oqbioVlYRKyRLZLl0KHLsloNKiOE6RaZyPLLiHkt7tyIkhSOhSEuMd7h96HtBxlondfU9XIvocPqfD0BNA76VQF2rtscKph@wErp1pkb2HI3tHVh9rS/4UUulKUoiigghwmkxSYFKdRWtjkWH9ffCNKFHzf2sgrUHlKNR3zlKvMxMjJbOg8jlWGL@laJch1pp51ZjjZlFqUKoljLXxg5LZ2g0XY8PPEPY0/3fDZeKDANbZqB8azRltnFR5KIcmMDeDq3kVLuiL8Jld0eS8XdPHorh7dX7vX8Pla4/79iz@TIp1vExoEfl9pXTHZdc0xQhIGQ8glA7A99q42rB0c6zyBazC6/cOrtfLYM9de6SJJQqU/tkK78/QD) **Explanation:** ``` m->n->{ // Method with two integer parameters and integer-matrix return-type var R=new int[m][n]; // Result-matrix of size `m` by `n` for(int i=0,j, // Index integers, starting at 0 v=0; // Count integer, starting at 0 i<m+n;) // Loop as long as `i` is smaller than `m+n` for(j=++i<n?0 // Set `j` to 0 if `i+1` is smaller than `n` :i-n; // or to the difference between `i` and `n` otherwise j<i&j<m;) // Inner loop `j` until it's equal to either `i` or `m`, // so basically check if it's still within bounds: R[j][i-++j]=++v; // Add the current number to cell `j, i-(j+1)` return R;} // Return the result-matrix ``` [Answer] # [J](http://jsoftware.com/), 15 bytes ``` $1(+/:@;)</.@i. ``` -4 more bytes for this solution by miles. Thanks! [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F/FUENb38rBWtNGX88hU@@/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqCsYIpjGmkYARjmgJF/wMA "J ‚Äì Try It Online") # [J](http://jsoftware.com/), 22 19 bytes -3 bytes thanks to FrownyFrog! ``` ,$[:>:@/:@/:@,+/&i. ``` [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F9HJdrKzspBH4x0tPXVMvX@a3Ip6Smop9nqqSvoKNRaKaQVc3GlJmfkKxgrpCmYQphGQKYRhGkKFv0PAA "J ‚Äì Try It Online") An implementation of Dennis' fantastic Jelly solution in J. ## Explanation: Dyadic verb, takes left and right argument (m f n) `+/&i.` creates lists 0..m-1 and 0..n-1 and makes an addition table for them: ``` 3 +/&i. 5 0 1 2 3 4 1 2 3 4 5 2 3 4 5 6 ``` `[:>:@/:@/:@,` flattens the table and grades the list twice and adds 1 to it: ``` 3 ([:>:@/:@/:@,+/&i.) 5 1 2 4 7 10 3 5 8 11 13 6 9 12 14 15 ``` `,$` reshapes the list back into mxn table: ``` 3 (-@],\[:>:@/:@/:@,+/&i.) 5 1 2 4 7 10 3 5 8 11 13 6 9 12 14 15 ``` [Answer] # APL+WIN, 38 or 22 bytes Prompts for integer input column then row: ``` m[‚çã+‚åø1+(r,c)‚ä§m-1]‚Üêm‚Üê‚ç≥(c‚Üê‚éï)√ór‚Üê‚éï‚ãÑ(r,c)‚ç¥m ``` or: ``` (r,c)‚祂çã‚çã,(‚ç≥r‚Üê‚éï)‚àò.+‚ç≥c‚Üê‚éï ``` based on Dennis's double application of grade up. Missed that :( [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~73~~ 67 bytes Count elements in rows above: `Min[j+k,#2]~Sum~{k,i-1}` Count elements on the current row and below: `Max[j-k+i-1,0]~Sum~{k,i,#}` Put into a table and add 1. Voila: ``` 1+Table[Min[j+k,#2]~Sum~{k,i-1}+Max[j-k+i-1,0]~Sum~{k,i,#},{i,#},{j,#2}]& ``` Update: I realized there is a shorter way to count all the positions ahead of a normally specified position in the matrix with just one sum over two dimensions: ``` Table[1+Sum[Boole[s-i<j-t||s-i==j-t<0],{s,#},{t,#2}],{i,#},{j,#2}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyQxKSc12lA7uDQ32ik/H8gu1s20ydItqakBMmxtgSwbg1id6mId5Vqd6hIdZaNaIC8TzMsC89T@BxRl5pVEp0Ub65jGxv4HAA "Wolfram Language (Mathematica) ‚Äì Try It Online") [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b731A7JDEpJzXaNzMvOks7W0fZKLYuuDS3rjpbJ1PXsFbbN7EiOks3WxvI0TFASOko1@pUQ8gsoJ7aWLX/AUWZeSXRadHGOqaxsf8B "Wolfram Language (Mathematica) ‚Äì Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~14~~ 12 bytes ``` {‚終祂çã‚çã‚àä+/‚Üë‚ç≥‚çµ} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR79ZHvVse9XaDUEeXtv6jtomPejcDhWv//3/UO1fBNzEzTyGtNC@5JDM/T0GjuDQpN7O4GMjW5OJKU3jUNkEBnxlcXCAzQlKLSxSSE4tTi4EGpBYkFiWWpCqUZ5ZkKCQq5GTmpSok5@eVAO3JzEtX0HjUNxVo6qPeNZpgG4wVTLngQkC@kYIRCt9UwRQA "APL (Dyalog Unicode) ‚Äì Try It Online") -2 thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn), due to his clever usage of `‚Üë‚ç≥`. Based off of Dennis's 5-byte Jelly solution. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 23 bytes ``` *L<DŒ£¬πLIL√¢Os√®}UŒ£Xs√®}√Å>√¥ ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fy8fG5dziQzt9PH0OL/IvPryiNvTc4ggQfbjR7vCW//@NuUwB "05AB1E ‚Äì Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 164 bytes ``` from numpy import* r=range def h(x,y): a,i,k,j=-array([i//y+i%y for i in r(x*y)]),1,2,0 while j<x+y:a[a==-j],i,k,j=r(i,k),k,k+sum(a==~j),j+1 a.shape=x,y;return a ``` [Try it online!](https://tio.run/##TY07DsIwEER7n2IbJC9Z/qIBfBJEYQkHryGOtTgibrh6MBIFzXw00rxUsu/jbppa6TuIQ5cKcJd6yXMlRmy8OXV1LXg9UsGDAktMdwpmYUVs0WderUrDswJtL8DAEUSP84IXpA1taa3g5fnhIJzGphzs2RqzCJffiejqWOO9eQ6drts7IIVmUznLp7fJmYo9isuDRLBTEo5Ze/1VjmnIGpHgvwHitFf7Dw "Python 3 ‚Äì Try It Online") This is definitely not the shortest solution, but I thought it was a fun one. [Answer] # [Python 2](https://docs.python.org/2/), 93 bytes ``` def f(b,a):i=1;o=[];exec"if b:o+=[],;b-=1\nfor l in o:k=len(l)<a;l+=[i]*k;i+=k\n"*a*b;print o ``` [Try it online!](https://tio.run/##FYtBDsIgEADP@opNT9Cuh2J6AXmJ7QEU4gayNE0P@nqE02SSmf13fgqrWt8hQhQendRkZ1PsczPhG14DRfC6TM3R@JudV47lgAzEUHSyObDI8uFMbgltYzI02bTyMLrRm/0gPqHUvghGSLJ/4o6wSAShEFTn0l1fL7E1SdY/ "Python 2 ‚Äì Try It Online") Semi-Ungolfed version: ``` def f(b,a): i=1 o=[] for _ in range(a*b) if b: o+=[[]] b-=1 for l in o: if len(l)<a: l+=[i] i+=1 print o ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~25~~ 24 bytes Hardly elegant, but gets the job done. Working with 2D data in Japt is tricky. ``` ;N√ó√á<U¬©Ap[] A¬Æ√ä<V¬©Zp¬∞T A ; // Set alternative default vars where A is an empty array. N√ó√á // Multiply the inputs and map the range [0..U*V). <U // If the current item is less than the second input, ¬©Ap[] // add a new empty subarray into A. A¬Æ // Then, for each item in A, √ä<V // if its length is less than the first input, ¬©Zp¬∞T // Add the next number in the sequence to it. A // Output the results, stored in A. ``` I added the `-Q` flag in TIO for easier visualization of the results, it doesn't affect the solution. Bit off one byte thanks to [Oliver](https://codegolf.stackexchange.com/users/61613/oliver). [Try it online!](https://tio.run/##AS0A0v9qYXB0//87TsOXw4c8VcKpQXBbXSBBwq7DijxWwqlacMKwVApB//8zIDUKLVE) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 103 bytes ``` (a,b,e=[...Array(b)].map(_=>[]))=>f=(x=0,y=i=0)=>(x<a&y<b&&(e[y][x]=++i),x?f(--x,++y):y>a+b?e:f(++y,0)) ``` [Try it online!](https://tio.run/##DcpNCoMwEEDh28gM@UEo3Vgn0o2XCKFMbCwWaySWkpzeZvk@3pt/fExp2b9qi89wjnQyGU8GAlmt9T0lLuDR6Q/v8CBjHcqZIFMrCy3UYl1zz03pfdNAsMXZ7EiIBWUeZlAqSyEKdsWw8EPoZqgpW0Q8b1PcjrgGvcYXjHBFuCBU/wM "JavaScript (Node.js) ‚Äì Try It Online") [Answer] # TI-Basic, 76 bytes ``` Prompt A,B {A,Bü°ídim([A] 1ü°íX For(E,1,B+A For(D,1,E If D≤A and E-D<B Then Xü°í[A](D,E-D+1 X+1ü°íX End End End [A] ``` Prompts for user input and returns the matrix in `Ans` and prints it. TI-Basic is a [tokenized language](http://tibasicdev.wikidot.com/tokens); all tokens used here are one byte, other than `[A]` which is 2 bytes. Note: TI-Basic (at least on the TI-84 Plus CE) only supports matrices up to 99x99, and so does this program. Explanation: ``` Prompt A,B # 5 bytes, prompt for user input {A,Bü°ídim([A] # 9 bytes, make the matrix the right size 1ü°íX # 4 bytes, counter variable starts at 1 For(E,1,B+A # 9 bytes, Diagonal counter, 1 to A+B-1, but we can over-estimate since we have to check later anyway. For(D,1,E # 7 bytes, Row counter, 1 to diagonal count If D≤A and E-D<B # 10 bytes, Check if we are currently on a valid point in the matrix Then # 2 bytes, If so, Xü°í[A](D,E-D+1 # 13 bytes, Store the current number in the current point in the matrix X+1ü°íX # 6 bytes, Increment counter End # 2 bytes, End dimension check if statement End # 2 bytes, End row for loop End # 2 bytes, End dimension for loop [A] # 2 bytes, Implicitly return the matrix in Ans and print it ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~61~~ 59 bytes ``` {($!={sort($_ Z=>1..*)>>.{*}})($!([X+] ^<<$_)).rotor(.[1])} ``` [Try it online!](https://tio.run/##FYtBCsIwEEWvMpYgMzUMtFI3NjmHWGtxYUDRRqbdlJCzx2T1@O/zfk/5nNJ3g70DkwKqnQmLlxXVBFdjG@aarOVQx0j5xOFyGOHe92oiYvGrF@ShGSmm5bGByxnx279mrG5zRRoKwHkBPGrossBWQ1vYlX1Ofw "Perl 6 ‚Äì Try It Online") Another port of Dennis' Jelly solution. [Answer] # [Java (JDK 10)](http://jdk.java.net/), ~~142~~ 131 bytes ``` X->Y->{var A=new int[X][Y];int E=1;for(int y=0;y<Y+X-1;y++)for(int x=0;x<X;x++){if(y-x<0|y-x>Y-1)continue;A[x][y-x]=E++;}return A;} ``` [Try it online!](https://tio.run/##jVE9b4MwEN37K260xYfy0Sw1IDGkUodOWUDIg0tJ5JQYZI4UK@W3U0OokkodKlmnu/fOfvfOR3EW3vH9Y8hL0TTwKqS6PAA0KFDmcLSs36Is/X2rcpSV8p/nJHhRWBwK7f6vSSrMeMajCHIIYUi8KPWiy1loiENVfE58wrOUM5vBNlyyfaXJmJtwwUyQOom3ZMZx6A/eWbwLEtZZ7CL3xHhdsPiy0b68pHmlUKq2YHHW8cyiPNw6Dut1ga1WELN@YNanPXX7Vlqrs@NzJd/hZLdAdqilOmRc0HEhAFg0SNbuI2W3cuOu78uVu/rNbqayvwrdK0z86CJ1x5jMGrM3K/qU@6KuS0NSOicJpVMPwM40WJz8qkW/tjNiqcjtD2KthWl8rK7zE0Hnkf64NU/XD98 "Java (JDK 10) ‚Äì Try It Online") **Explanation:** ``` X->Y->{ // Method with two integer parameters and integer-matrix return-type var A=new int[X][Y]; // The Matrix with the size of X and Y int E=1; // It's a counter for(int y=0;y<Y+X-1;y++) // For each column plus the number of rows minus one so it will run as long as the bottom right corner will be reached for(int x=0;x<X;x++){ // For each row if(y-x<0|y-x>Y-1) // If the cell does not exist becouse it's out of range continue; // Skip this loop cycle A[x][y-x]=E++; // Set the cell to the counter plus 1 } return A; // Return the filled Array } ``` *Big thank to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) because I didn't know how to run my code on [tio](https://tio.run/). Some code like the header and footer are stolen from him. [-> His answer](https://codegolf.stackexchange.com/a/163276/75908)* [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` ·π†CoŒ∑√ñ¬§√ó,·∏£ ``` [Try it online!](https://tio.run/##AR0A4v9odXNr///huaBDb863w5bCpMOXLOG4o////zP/NQ "Husk ‚Äì Try It Online") Most of the heavy lifting is done by `√ó`, which creates pairs in the desired order so that it can support infinite lists. ### Explanation ``` CŒ∑√ñ√ó,·∏£¬≤·∏£‚Å∞‚Å∞ (Expanded; let N and K denote the arguments.) Œ∑√ñ Take the list of indices of the sorted values of √ó, the list of all pairs taken from ·∏£¬≤ the range from 1 to N and ·∏£‚Å∞ the range from 1 to K, and C ‚Å∞ cut it into lengths of K. ``` [Answer] # PHP, 115 bytes a pretty lazy approach; probably not the shortest possible. ``` function($w,$h){for(;$i++<$h*$w;$r[+$y][+$x]=$i,$x--&&++$y<$h||$x=++$d+$y=0)while($x>=$w|$y<0)$y+=!!$x--;return$r;} ``` anonymous function, takes width and height as parameters, returns 2d matrix [try it online](http://sandbox.onlinephpfunctions.com/code/67d5f8de325e9267933c5eeb634f3d8f07cece55) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 108 105 101 100 bytes ``` n=>(l=>{for(r=[];i<n*n;n*~-n/2+2>i?l++:l--*y++)for(T=y,t=l;t--;)r[T]=[...r[T++]||[],++i]})(y=i=0)||r ``` [Try it online!](https://tio.run/##FcoxDsIgFADQ3ZMAv6Dp4CB@vEQ3wtDUYjDkYygxIaJXR93e8O7zc96WHB5FUrqu3WMnNCyiefmUWUbrdDiTIE3iI2k/wmjCJQKcopSiAvB/m7AOBaMuUmqe7eTQKqV@AHCtWTcABPfmrGLAA28t9yXRluKqYroxz46c7/oX "JavaScript (Node.js) ‚Äì Try It Online") [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 45 bytes ``` {Chop[Grade//2<|Flat!Table[`+,1:_2,1:_],_]+1} ``` [Try it online!](https://tio.run/##SywpSUzOSP2fZmX7v9o5I78g2r0oMSVVX9/IpsYtJ7FEMSQxKSc1OkFbx9Aq3ghExOrEx2ob1v73S01NKY5WKShITo/lqlYIKMrMK4mOj9dRUNK1U4q1VnDJLC7ISayMTnNwiAdyIfKxCrUKtnYK0VwKQBBtrGMaqwNhGukYwZimQFGu2P8A "Attache ‚Äì Try It Online") Anonymous lambda, where paramaters are switched. This can be fixed for +1 byte, by prepending `~` to the program. The test suite does this already. ## Explanation This approach is similar to the [J answer](https://codegolf.stackexchange.com/a/163281/31957) and the [Jelly answer](https://codegolf.stackexchange.com/a/163275/31957). The first idea is to generate a table of values: ``` Table[`+,1:_2,1:_] ``` This generates an addition table using ranges of both input parameters. For input `[5, 3]`, this gives: ``` A> Table[`+,1:3,1:5] 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 ``` Then, we flatten this with `Flat!`: ``` A> Flat!Table[`+,1:3,1:5] [2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8] ``` Using the approach in the J answer, we can grade the array (that is, return indices of sorted values) twice, with `Grade//2`: ``` A> Grade//2<|Flat!Table[`+,1:3,1:5] [0, 1, 3, 6, 9, 2, 4, 7, 10, 12, 5, 8, 11, 13, 14] ``` Then, we need to chop the values up correctly, as in the Jelly answer. We can cut every `_` elements to do this: ``` A> Chop[Grade//2<|Flat!Table[`+,1:3,1:5],5] 0 1 3 6 9 2 4 7 10 12 5 8 11 13 14 ``` Then, we just need to compensate for the 0-indexing of Attache with `+1`: ``` A> Chop[Grade//2<|Flat!Table[`+,1:3,1:5],5]+1 1 2 4 7 10 3 5 8 11 13 6 9 12 14 15 ``` And thus we have the result. [Answer] # [Python 3](https://docs.python.org/3/), 259 bytes So I did this a weird way. I noticed that there were two patterns in the way the array forms. **The first** is how the top rows pattern has the difference between each term increasing from 1 -> h where h is the height and l is the length. So I construct the top row based on that pattern For a matrix of dim(3,4) giving a `max RoC = 3` We will see the top row of the form ``` 1, (1+1), (2+2), (4+3) = 1, 2, 4, 7 ``` Suppose instead that the dim(3,9) giving a `max RoC = 3` we will instead see a top row of ``` `1, (1+1), (2+2), (4+3), (7+3), (10+3), (13+3), (16+3), (19+3) = 1, 2, 4, 7, 10, 13, 16, 19, 22 ``` **The second** pattern is how the rows change from one another. If we consider the matrix: ``` 1 2 4 7 11 3 5 8 12 16 6 9 13 17 20 10 14 18 21 23 15 19 22 24 25 ``` and subtract each row from the row below (ignoring the extra row) we get ``` 2 3 4 5 5 3 4 5 5 4 4 5 5 4 3 5 5 4 3 2 ``` Upon seeing this matrix we can notice this matrix is the sequence `2 3 4 5 5 4 3 2` where by each row is 5 terms of this pattern shifted by 1 for each row. See below for visual. ``` |2 3 4 5 5| 4 3 2 2 |3 4 5 5 4| 3 2 2 3 |4 5 5 4 3| 2 2 3 4 |5 5 4 3 2| ``` So to get the final matrix we take our first row we created and output that row added with the 5 needed terms of this pattern. This pattern will always have the characteristics of beginning `2-> max value` and ending `max value -> 2` where the `max value = min(h+1, l)` and the number of times that the max value will appear is `appearances of max = h + l -2*c -2` where `c = min(h+1, l) - 2` So in whole my method of creating new rows looks like ``` 1 2 3 7 11 + |2 3 4 5 5|4 3 2 = 3 5 8 12 16 3 5 8 12 16 + 2|3 4 5 5 4|3 4 2 = 6 9 13 17 20 6 9 13 17 20 + 2 3|4 5 5 4 3|4 2 = 10 14 18 21 23 10 14 18 21 23 + 2 3 4|5 5 4 3 2| = 15 19 22 24 25 ``` Relevant code below. It didn't end up being short but I still like the method. ``` o,r=len,range def m(l,h): a,t=[1+sum(([0]+[x for x in r(1,h)]+[h]*(l-h))[:x+1]) for x in r(l)],min(l,h+1);s,c=[x for x in r(2,t)],[a[:]] for i in r(h-1): for j in r(o(a)): a[j]+=(s+[t]*(l+h-2*(t-2)-2)+s[::-1])[0+i:l+i][j] c+=[a[:]] for l in c:print(l) ``` [Try it online!](https://tio.run/##VY7BbsMgEETvfAVHNguSTdsLEV@COCDHKUQYR5hK7tc7a7uHVEJa7dthZp6/Lc7lY9tmWW0ei6yhfI/sNt75JLKMYBgPslnX4/IzCeE6j27l97nylafCq@hJRCz6i8gqAjizYu/hXZLByymVw@@6yMH@d9CykcAFZ7xnxyGdh6j6Pf9AjxPNIsDBeHAPj1Ys6NoejVHpi2hKAz1cnDGKWrgOk8mYPInp04D2PSbvnoN51lQaldwmqqKBnTtwNolP@UXzD9CuO6k72F4 "Python 3 ‚Äì Try It Online") [Answer] # Japt, 20 bytes ``` √µ √ØV√µ)√±x ¬£bYgU√±¬π√Ñ√É√≤V ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=9SDvVvUp8XgKo2JZZ1XxucTD8lY=&input=Myw1Ci1S) [Answer] # [Haskell](https://www.haskell.org/), 92 bytes ``` r=[1..] (#)=take n!k=[[sum$lookup(i,j)$zip[(i,j)|s<-r,i<-n#r,j<-k#r,i+j==s]r|j<-k#r]|i<-n#r] ``` [Try it online!](https://tio.run/##bY5BCsMgEEX3OcWEuFBqhBK6096gJxApQgM1JkY02ZTc3ZrYQhddzf/z33zmqaPtxzGlIOSZMVXhhohF275ytRVSxnVC4zzb1WNDB4JexstDbZG3gRreuibQgbc2D3MahIgqbMWrrcQqTdo4EPCYK4BJ@9sdfDBuAQRdfcm7r5Of7ny/f3NRR8UuO6V@uVyCMSWGFOw/hVFJCcs4yzhH10KlNw "Haskell ‚Äì Try It Online") ]
[Question] [ ## Definition and Rules A *golfy array* is an array of integers, where each element is *higher than or equal to* the arithmetic mean of all the previous elements. Your task is to determine whether an array of positive integers given as input is golfy or not. * You do not need to handle the empty list. * [Default loopholes apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). * [Standard Input and Output methods apply](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). * You can choose any two distinct non-empty values. They **must** be consistent, and must comply with all other [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") rules. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in each language wins! ## Test Cases & Example For example the following array: ``` [1, 4, 3, 8, 6] ``` Is a golfy array, because each term is higher than the arithmetic mean of those preceding it. Let's work it out step-by-step: ``` Number -> Preceding elements -> Average -> Follows the rule? 1 -> [] -> 0.0 -> 1 ≥ 0.0 (True) 4 -> [1] -> 1.0 -> 4 ≥ 1.0 (True) 3 -> [1, 4] -> 2.5 -> 3 ≥ 2.5 (True) 8 -> [1, 4, 3] -> 2.(6) -> 8 ≥ 2.(6) (True) 6 -> [1, 4, 3, 8] -> 4.0 -> 6 ≥ 4.0 (True) ``` All the elements respect the condition, thus this is a golfy array. Note that for the purpose of this challenge, we will assume that the average of an empty list (`[]`) is `0`. More test cases: ``` Input -> Output [3] -> True [2, 12] -> True [1, 4, 3, 8, 6] -> True [1, 2, 3, 4, 5] -> True [6, 6, 6, 6, 6] -> True [3, 2] -> False [4, 5, 6, 4] -> False [4, 2, 1, 5, 7] -> False [45, 45, 46, 43] -> False [32, 9, 15, 19, 10] -> False ``` --- **Note that this is *[Puzzle 1](https://github.com/Mr-Xcoder/CodeGolf-Hackathon/blob/master/Puzzle%201/Puzzle%201.md)* from *[CodeGolf-Hackathon](https://github.com/Mr-Xcoder/CodeGolf-Hackathon)* and is also posted on [Anarchy Golf](http://golf.shinh.org/p.rb?Golfy+ARrays) (that one is broken) - *[Reposted](http://golf.shinh.org/p.rb?Golfy+Arrays+with+test+cases)* by [histocrat](https://codegolf.stackexchange.com/users/6828/histocrat), but I am the original author on both sites, and thus allowed to repost them here.** [Answer] # [Python 2](https://docs.python.org/2/), 37 bytes ``` def g(a):sum(a)>len(a)*a.pop()or g(a) ``` [Try it online!](https://tio.run/##hdHPa8IwFAfwe/@Kh6dGgtjWuVnobhsMxk7eJIduPl2hS8JLCvrXdy8pqBM7Q8I7vE@/@VF79N9G532/xR3s01qUrvvh8tyi5jKtZ9bYVBiKzah26bsoEwBPxxIIfUcaPo1p0z03BDfw8IXWw5ve4uGFyNCJranDJKmdQ/KcsykUXA0BVTWws8olZLm6pzIJCwmFhCcJS/WPyqNi@zCqlhxxmqOKU/4ea1CvdesuWdgpJi3UHRYuGvGjGmfcjisExve7yQrOWnEcyyzUubpglhrtYfJhYPigMRow/Cg3m/S/ "Python 2 – Try It Online") Outputs via exit code: crashes (exit code 1) for golfy arrays, just exits with exit code 0 for non-golfy arrays. ovs and Jonathan Frech saved 3 bytes. ### [Python 2](https://docs.python.org/2/), 44 bytes ``` f=lambda a:a and sum(a)<=len(a)*a.pop()*f(a) ``` [Try it online!](https://tio.run/##hdBND4IgGAfwe5/imSd1zCWavSyuHTt1axxo6nJTcKCHPr094FbWMhnsGePHn5f20d2VpMNQslo0t1yAOOCQOZi@8UVwZHUhsYYialXrB2GJk0EYU@gOSv@acPhqATAGF90Xq7eiBGLKl1RMICWQENgRyPgfRZ1Cu5lVGUa8@qzClM9rjeokajNl9iSXlPIFZh/q8JbPM1x2wwa6//vJEszaYxzK2NY1n7BWV7ID76xg3FApCYXWSpvIG54 "Python 2 – Try It Online") A more traditional variant, which returns `True` for golfy arrays, else `False`. Jonathan Frech saved 2 bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 bytes ``` <ÆmƤE ``` [Try it online!](https://tio.run/##y0rNyan8/9/mcFvusSWu/w@3P2paA0Tu//9HR0cbx@pwKShEG@koGBpBmIY6CiY6CsY6ChY6CmZwISOwEFDCFCJkBpSEo1iQGNAsoDKILEgdWMoEzgfZABY1hwoBmWAMUgV1hTFQkSVQHVDYEEQbxMbGAgA "Jelly – Try It Online") ### How it works ``` <ÆmƤE Main link. Argument: A (integer array) ÆmƤ Compute the arithmetic means (Æm) of all prefixes (Ƥ) of A. < Perform element-wise comparison. Note that the leftmost comparison always yields 0, as n is equal to the arithmetic mean of [n]. E Test if all elements of the resulting array are equal, which is true if and only if all comparisons yielded 0. ``` [Answer] ## JavaScript (ES6), ~~33~~ 32 bytes ``` a=>a.some(e=>e*++i<(s+=e),s=i=0) ``` Code also works on negative values such as`[-3, -2]`. Returns `false` for a golfy array, `true` for other arrays. Edit: Saved 1 byte thanks to @JustinMariner. [Answer] ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes ``` Max[Accumulate@#-Range@Tr[1^#]#]>0& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zexItoxObk0tzQnsSTVQVk3KDEvPdUhpCjaME45VjnWzkDtf0BRZl6Jg5ZCmoK@g0I1l4JCtXGtjgKINtJRMDSCsg11FEx0FIx1FCx0FMwQYkZgMaCMKVTMDCgNR1AxoAqYMSCVYDkThADIGrCwOUwMyAZjkDqYY4yByiyBKoHihiDaoJar9j8A "Wolfram Language (Mathematica) – Try It Online") Outputs `False` for golfy arrays and `True` otherwise. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~9~~ 8 bytes ``` tYstf/<a ``` Outputs `0` for golfy arrays, `1` otherwise. [**Try it online!**](https://tio.run/##y00syfmf8L8ksrgkTd8m8b9LyP9o41iuaCMdBUMjIG2oo2Cio2Cso2Cho2AG4RuB@UBRUyDfDCgMR0A@UAakDSQLFjOBcEDGgYXMQXwgDcYgeZBlxkBpS6AKoJghiDaIBQA "MATL – Try It Online") ### Explanation Consider input `[1, 4, 3, 8, 6]`. ``` t % Implicit input. Duplicate % STACK: [1, 4, 3, 8, 6], [1, 4, 3, 8, 6] Ys % Cumulative sum % STACK: [1, 4, 3, 8, 6], [1, 5, 8, 16, 22] t % Duplicate % STACK: [1, 4, 3, 8, 6], [1, 5, 8, 16, 22], [1, 5, 8, 16, 22] f % Find: indices of nonzeros. Gives [1, 2, ..., n], where n is input size % STACK: [1, 4, 3, 8, 6], [1, 5, 8, 16, 22], [1, 2, 3, 4, 5] / % Divide, element-wise % STACK: [1, 4, 3, 8, 6], [1, 2.5, 2.6667, 4, 4.4] < % Less than?, element-wise % STACK: [0, 0, 0, 0, 0] a % Any: true if and only there is some nonzero. Implicit display % STACK: 0 ``` [Answer] # [Haskell](https://www.haskell.org/), ~~53~~ ~~50~~ 48 bytes ``` and.(z(<=).scanl1(+)<*>z(*)[1..].tail) z=zipWith ``` [Try it online!](https://tio.run/##bY6xDsIgEIb3PsWlEygSaWvVpPUJdHJwqAyk1UpEJC0ufXgRiHEygfDfd/9/x02M94tSrocazk7ojqIJVTWmYyu0YmiOq9luQjPcMEo5tUIqnEz1JM1J2pt7CKl9snsm8BDmAMgMUlug0GNompwTaDICLAuCESgI5AQ2BMovyCLweBVA6Ru/w3kC5mWPdtjrNP0/3w8IuZCPoeJbhZ2RrSPwIt7giH/KvWHrPR6y8C45d@/2qkQ/ukVrzAc "Haskell – Try It Online") *Edit:* -3 bytes thanks to Zgarb! **Explanation** The above point-free version is equivalent to the following program: ``` f s = and $ zipWith(<=) (scanl1(+)s) (zipWith(*)[1..](tail s)) ``` Given an input `s=[1,4,3,8,6]`, `scanl1(+)s` computes the prefix sums `[1,5,8,16,22]` and `zipWith(*)[1..](tail s)` drops the first element and multiplies all other elements with their index: `[4,6,24,24]`. The list is now *golfy* if pairwise the prefix sums are smaller or equal to the elements times index, which can be checked by zipping both lists with `(<=)` and checking that all results are `True` with `and`. [Answer] # [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 71 + 18 = 89 bytes ``` x=>x.Select((n,i)=>new{n,i}).Skip(1).All(y=>x.Take(y.i).Average()<=y.n) ``` additional 18 bytes for `using System.Linq;` [Try it online!](https://tio.run/##jdFBa4MwGAbgc/MrvmMCWZjWdRtWYQx22mDgYAfxkGWphNq4JWlXEX@7ix5KaUGUhMSQ580XFfZGWNHvrdIlZI11chej8zf2qvRvjETFrYV3U5eG76BFC@u4UwIOtfqGN640ts54lRfATWkJtPCy12KttMsL@lXXVQobSAD1xyQ9skxWUjiMNVUkSbX8a/2sIyzbqh8cEPZUVbgZNn7wrcQNU37pIA0vJSbrpGGa9DF6rrWtK8k@jXLSlynxBvuovGiXHSExXD4TIKQQhFdoAgQUIgpLCg8UVic4DcIReHY3B6x88KnNAT77@gpTYKhkjI/O2TQYPtTI7ueUFPmNYx8OOf2UqTv4/Ed/hDfBMN6OBqFFh7r@Hw "C# (Visual C# Compiler) – Try It Online\"(n,i)=>new{n,i}).Skip(1).All(y=>x.Take(y.i).Average()<=y.n") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 10 bytes This is an anonymous tacit prefix function (called a monadic train in APL terms). ``` ∧/⊢≥+\÷⍳∘≢ ``` [Try all the test cases on TIO!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHHcv1H3UtetS5VDvm8PZHvZsfdcx41LkIKKlgzJWmYKRgaASkDBVMFIwVLBTMwGwjINtEwRTINoNBINtYAaQSKA7km4BZQM1AnjmIbQpGQAmQocZGCpYKhqYKhkDSAAA "APL (Dyalog Unicode) – Try It Online") *Is it*  `∧/` all-true that  `⊢` the elements  `≥` are greater than or equal to  `+\` the cumulative sums  `÷` divided by   `⍳` the integers 1 through   `∘` the   `≢` number of elements *?* [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~62~~ ~~60~~ 62 bytes * Removed two superfluous parentheses. * Added two bytes to fix function's reusability (`b=`). ``` f(A,S,k,b)int*A;{for(S=k=b=0;*A;S+=*A++)b+=!(S<=*A*k++);b=!b;} ``` [Try it online!](https://tio.run/##fZDNasMwEITPzVNsAgXJ3oLttm6DooPzn1x9bHKoXByCiVtCb8bP7q4lV@iQCGTEzjeDtVM8nYqi60qWYY4VKn6uf4NMNOX3leWykkpGguY8lEEWhlyFcszyGQ1BRaNQcqxE210@zzXjzeiB0pB9HEFC84wQtcJIcyMlCHHiyAsjxwgvCOR/R0gdvLQ40ZhMrw5eGZzqkD0a/1zJULLJ4xdICfGhniDQipzfZXMPW3jY0sNWmpnHrm0pbgEbo5rFUr2hZVvL@tq0483BuwGTrL8@7Va@H35I4SnlyRL3d3SzoWh48frGNv9s42FbD9t52L5no7b7Aw "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` ηÅA÷W ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3PbDrY6Ht4f//x9tpgOFsQA "05AB1E – Try It Online") Extensive help from Dennis and Adnan got to this reduced version. Also a bug was fixed to make this possible, thanks again you guys. I take little credit for this answer. --- # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` ηεÅA}ü.S_P ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3PZzWw@3OtYe3qMXHB/w/3@0mQ4UxgIA "05AB1E – Try It Online") --- ~~Long because `DgsO/` is the equivalent of "mean" in 05AB1E.~~ Apparently `ÅA` is arithmetic mean. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 15 bytes ``` ∧/⊢≥((+/÷≢)¨,\) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHHcv1H3UtetS5VENDW//w9kedizQPrdCJ0QRKKxhzpSkYKRgaASlDBRMFYwULBTMw2wjINlEwBbLNYBDINlYAqQSKA/kmYBZQM5BnDmKbghFQAmSosZGCpYKhqYIhkDQAAA "APL (Dyalog Unicode) – Try It Online") **How?** ``` ,\ all prefixes ¨ for each +/÷≢ calculate arithmetic mean ⊢≥ element wise comparison ∧/ logically and the result ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 60 bytes ``` param($a)$o=1;$a|%{$o*=$_-ge($a[0..$i++]-join'+'|iex)/$i};$o ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRUyXf1tBaJbFGtVolX8tWJV43PRUoHG2gp6eSqa0dq5uVn5mnrq1ek5laoamvkllrrZL///9/Bw1DHQUTHQVjHQULHQUzTQA "PowerShell – Try It Online") Takes input as a literal array (e.g., `@(1, 4, 3, 8, 6)`) into `$a`. Sets our `$o`utput variable to be `1`. Then loops through `$a`. Each iteration, we're (ab)using PowerShell's implicit casting to `*=` the result of a Boolean comparison against our `$o`utput. The Boolean is whether the current value `$_` is `-g`reater-than-or-`e`qual to the previous terms `$a[0..$i++]` added together (`-join'+'|iex`) divided by how many terms we've already seen `$i`. So, if any step along the way is false, then `$o` will get multiplied by `0`. Otherwise, it will remain `1` throughout. We then simply place `$o` onto the pipeline and output is implicit. `1` for truthy and `0` for falsey. [Answer] # Perl 5, 27 +2 (-ap) bytes ``` $_=!grep$_*++$n<($s+=$_),@F ``` [Try It Online](https://tio.run/##K0gtyjH9/18l3lYxvSi1QCVeS1tbJc9GQ6VY21YlXlPHwe3/fzMFCDT9l19QkpmfV/xfN7EAAA) [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 74 bytes ``` x=>{for(int i=1,s=0;i<x.Count;)if(x[i]<(s+=x[i-1])/i++)return 0;return 1;} ``` [Try it online!](https://tio.run/##nZJPa4MwGMbvfor3GGnaadt1G9FeCtulg7Eddig9SBrlBZtAEjeH@NldkpXSwy4ajObf73memHAz50qLoTEoK/j4MVacWXTbW@xUXQtuUUmzeBFSaOQsinhdGANvWlW6OEddBK4YW1jk8KXwBK8FSmKsdkKHIxS6MnFY87fSl@dG8myPxmYo7ZaCf0MJ@dDm265UmrgBwDylJk8YZq0L0kjLYixJe8BjRswsd415eozvcDaLtbCNlpCwSyNl/cCubjsXX9Vi8anRij1KQUoixTdcA0AHK@jjeByypJAux2MphTWFFYVHCptJ@DLgTuR@PL6hN8943PlO2LKPGhzXk1j/o4PCwwTcYaF69xGHDJm/lBD27PyfXASnkvpv8r/KuyhOQeQy10f98As "C# (.NET Core) – Try It Online") Returns 0 for false and 1 for true. 3 Bytes longer than core of [chryslovelaces](https://codegolf.stackexchange.com/users/75118/chryslovelace) [answer](https://codegolf.stackexchange.com/a/145706/42502). But in total several Bytes shorter because my variant doesn't need any `using` statements. [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 35 bytes ``` /I?/\+psu0^.\)*sqs;-\;;U;O1.....?@^ ``` [Try it online!](https://tio.run/##Sy5Nyqz4/1/f014/RruguNQgTi9GU6u4sNhaN8baOtTa31APBOwd4v7/N1YwAgA "Cubix – Try It Online") Not the most efficient use of space (6 no-ops in the code) Produces no output for a golfy array, `1` for a not-golfy array. Expands to the following cube: ``` / I ? / \ + p s u 0 ^ . \ ) * s q s ; - \ ; ; U ; O 1 . . . . . ? @ ^ . . . . . . . . . . . . . . . . . . . ``` Explanation forthcoming, but it basically ports something like Luis Mendo's [MATL answer](https://codegolf.stackexchange.com/a/145715/67312) or Dennis' [Julia answer](https://codegolf.stackexchange.com/a/145818/67312). [Watch it run!](http://ethproductions.github.io/cubix/?code=ICAgICAgLyBJID8KICAgICAgLyBcICsKICAgICAgcCBzIHUKMCBeIC4gXCApICogcyBxIHMgOyAtIFwKOyA7IFUgOyBPIDEgLiAuIC4gLiAuID8KQCBeIC4gLiAuIC4gLiAuIC4gLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4K&input=MyAy&speed=5) [Answer] # Matlab and Octave, ~~41~~ 36 bytes *5 bytes saved thx to Luis Mendo* ``` all([a inf]>=[0 cumsum(a)./find(a)]) ``` [Try it online!](http://rextester.com/AAM39974) [Answer] # SQL (MySQL), 68 bytes ``` select min(n>=(select ifnull(avg(n),1)from t s where s.i<t.i))from t ``` [Try it online!](http://sqlfiddle.com/#!9/91466a/1) Returns **1** for golfy arrays, and **0** otherwise. Takes input from a [named table](https://codegolf.meta.stackexchange.com/a/5341), `t`. In order to create `t`, run: ``` CREATE TABLE t(i SERIAL,n INT) ``` and to load the values: ``` truncate table t;insert into t(n)values(3),(2); ``` [Answer] # [Factor](https://factorcode.org/), 26 bytes ``` [ dup cum-mean v>= vall? ] ``` [Try it online!](https://tio.run/##PY3NDoIwEITvPsW8gERA8C/q0XjxYjwZD01dlVhKbQuJGp4dV2pMm8l8nZ3tRUhf2e6w3@42c9zJalIohb9FzgtfOF9IF7ih76SDo0dNWpKDseT909hCe1xJkxWqeHGp0g6LweCNFC1rgjjpTYwxP02R/yhhGiPrKf@fti@GxjfNWYPnRcyTQFl/OQyfpAlmiDPErCO03RHn2kDW5bAkodGslmiEUmucOs61MEY9ETlIRcJ2Hw "Factor – Try It Online") ## Explanation Factor has some pretty great words for this. ``` ! { 1 4 3 8 6 } dup ! { 1 4 3 8 6 } { 1 4 3 8 6 } cum-mean ! { 1 4 3 8 6 } { 1 2+1/2 2+2/3 4 4+2/5 } v>= ! { t t t t t } vall? ! t ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` Λ<mAḣ ``` [Try it online!](https://tio.run/##yygtzv7//9xsm1zHhzsW////P9pQx0THWMdCxywWAA "Husk – Try It Online") Modification of Mr. Xcoder's solution from the linked repository. -1, a sweet victory using `all2`! # [Husk](https://github.com/barbuz/Husk), ~~8~~ 7 bytes ``` ΛΓ·<Aṫ↔ ``` [Try it online!](https://tio.run/##ASIA3f9odXNr///Om86Twrc8QeG5q@KGlP///1sxLDQsMyw4LDZd "Husk – Try It Online") Took me long enough to use `Γ` here.(more than a year!) [Answer] # [Ruby](https://www.ruby-lang.org/), 30 bytes ``` ->a{0until a.pop*a.size<a.sum} ``` [Try it online!](https://tio.run/##VY1LDsIwDET3nMKCHQoV/fCToDuWcIEqi7QNUAmSKm0WUHr2YhsEworl8ZtJ4nx@H067YZaqbu5NW11BBbWtpypoqofe4vC3fsiyWArIIgFhRCIUkAiIBawFLD8gYoB4QWCJxvcQQI@vUoBp8tnoUWYrBii4KcGfxhjYYAZhSHMuZaBVcYHSwlM9R4CV63NlWFHVrjItjCed6mGXwvhn@LaBU6YkE6ebwms42oNuL7bcO2cd5fV//r1qU46whxc "Ruby – Try It Online") Inspired by [Lynn's answer](https://codegolf.stackexchange.com/a/145705/73819). Throws `NoMethodError` for golfy, returns `nil` otherwise. [Answer] # [Python 2](https://docs.python.org/2/), 52 bytes ``` lambda A:all(k*j>=sum(A[:j])for j,k in enumerate(A)) ``` [Try it online!](https://tio.run/##hdG7DoIwFAbg3ac4YQLTGLmISlITFkcnN@xQY4lcS1oYfHpsS6JoRJo2Hfr1P700j/bOa69P8aUvaXW9UYgjWpZ2scwPWHaVHSdRTpyUC8hRAVkNrO4qJmjL7NhxeiolEy2kduIT@GoOYAxn0bHFW3kIXI/MKRdBgMBHsEMQkj/KM0rZzaQKVcSrTyqV8nmsQR1pKcdMVzJJAZlh@qIGb8k0U8tm6EDzfj@Zr7L2Kk5JV89rMmKNyOoWrBOHYUPG1RcJwYVcWf0T "Python 2 – Try It Online") # [Python 2](https://docs.python.org/2/), ~~50~~ ~~48~~ ~~44~~ 42 bytes * Saved two bytes by inlining and using `and`. * Saved two bytes thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) by chaining assignment `S=k=0`. * Saved two bytes by using `or` and the comparison's boolean value as `k`'s increment value. * Saved two bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs); raising a `NameError` by using an undefined variable instead of a `ZeroDivisionError`. ``` S=k=0 for j in input():k+=S<=j*k or J;S+=j ``` [Try it online!](https://tio.run/##TY6xbsIwEIbn@Cl@eWqLVZGEUprWUwRIHeiQblGHCBmRhMaRY1R4@vRsEkA6y7r/@87n9mz3uon6VHLO@0zWcsp22qBC2VC1R/vwmNQTmX3I6qkGkc/3bCKrnnRmzTlh@NuXB4U0YcEaEt/mqFjgCNRJbZGyQJ22qrXYFL9qaYw2CZy4Kg4dmUXXKWPHVZASazYMLL9Wg9@asrHgG42LXuoGyqHumfd5/MP81jwSCKOxCQVmArHAQmB@F0Y@JPQyhnMSrjWG5NBTl0/mzvZ4dh@5dR683lLq/HFufI1jUt/IJhK6ezqQfw "Python 2 – Try It Online") [Answer] # [q/kdb+](http://kx.com/download/), 14 bytes **Solution:** ``` min x>=avgs x: ``` **Examples:** ``` q)min x>=avgs x:1 4 3 8 6 1b / truthy q)min x>=avgs x:4 2 1 5 7 0b / falsey ``` **Explanation:** Fairly simple with the `avgs` built-in: ``` min x>=avgs x: / solution x: / store input in variable x avgs / calculate running averages x>= / array comparison, x greater than running average min / take minimum of list of booleans ``` [Answer] # [Julia 0.6](http://julialang.org/), 29 bytes ``` !x=any(find(x).*x.<cumsum(x)) ``` Returns *false* or *true*. [Try it online!](https://tio.run/##PY5hC4JADIa/@yumINzFlO7OLKGi/1F@kEy4yCs04fr11@4UYWPb875se04v3ZTOxfbUmB/rtGmZ5fnG5sf71I9TTxN33XsAC9oAiwCuqkZfJIKQcysQCgSFcEAoVyQDImE3o5LENWZE@rLC24JSrLM/EOh@QdSG9K7lCUWminyEha/bOuLEL59Bm2/HkjQT1QjZGdLxZhIEixBbHj1M6/4 "Julia 0.6 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~38~~ 34 bytes ``` function(x)any(cumsum(x)/seq(x)>x) ``` [Try it online!](https://tio.run/##bY7bCsIwDIbvfYpdJvCD9jTdhb7LKBYGW512he3pawQvxC4JCcmX06uEawk5@mV4RFq5jxv5PKU8SXJM96eE28ol9fM8bjQOaSGDQ/MjnjSU5v@igoXBBe0O0UIsXEVafLUiBvUF2SC9dqcuDwk718ThYzJk6gsaHZSDEn9iRhO4vAE "R – Try It Online") [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 54 bytes ``` D,g,@@#,BFB D,k,@,¦+AbL/ D,f,@,dbLR$€g€k0b]$+ABcB]£>ª! ``` [Try it online!](https://tio.run/##bZA7CsJAEIbr3VOsMZ0DmsT3i7hIqlRiJykSY4JvUbQRG68iWIinyFG8SJxZUYkIOyzzf/PPLr8fhptNmvYhBtvOg3Qk78McbEiuhV7gFrGLsAsDd6A/zvcYa14KPL3Qk2PpJZducsuhe7aermhBEzjTRLvTFdqMo3fpo07ayPK0A2OsJYbb/YQEE4RhKvGrGSDKICwQdRBVYhlkKoQDlSyq4vDnZBHOv99w/MVOabRAzZb/EPqV4rXXoi9DTRUZrR9ooa2BTuQG3aUMl17IGQZ3jE7YqNiOFNiJc50CSp8 "Add++ – Try It Online") ### Unoriginal version, 30 bytes ``` D,f,@,¬+AbLRBcB/@0@B]ABcB]£>ª! ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ03HQefQGm3HJJ8gp2QnfQcDB6dYRyAr9tBiu0OrFIEqsvIz83QcHJStdLg4lRRsbO0UlLK4uFx0chOB4iCxaONYpTJOTk5rhZCi0lSQgJGOgqERWBAhZqijYKKjYKyjYKGjYAaSQ5EyAksBFZiiSpkBFcMRqhRQPcwOt8ScYrAYyACwWhMsMiBXgeXNIQYh5IBiYAzSaIwmaQzUZgnUCZQ3BNEGKPJOsSlcnI@a1lSn1QI54GCrBgVYLReXCiiA/gMA "Add++ – Try It Online") Both output **1** for golfy arrays and **0** otherwise ## How they work The first version was created by me, without checking any other solutions. The second was inspired by Dennis' [comment](https://codegolf.stackexchange.com/questions/145699/am-i-a-golfy-array/145762#comment356541_145719), so I'm less happy with it. ### The first version Here, we define our main function \$f\$ that computes the *golfiness* of our input array, \$A\$. First, we need to yield the suffixes of \$A\$, which is done by first generating the range \$B := [1, ... \vert{A}\vert]\$, where \$\vert{A}\vert\$ denotes the length of \$A\$. This is done with the code `dbLR$`, which leaves \$[B, A]\$ as the stack. We then iterate the dyadic function \$g\$ over these two lists. Being dyadic, the function binds its left argument as \$A\$ for each iterated element. It then iterates over the range \$B\$, which each element from \$B\$ being the right argument provided to \$g\$. \$g\$ is defined as ``` D,g,@@#,BFB ``` which is a dyadic function (i.e. takes \$2\$ arguments), and pushes its arguments to the stack in reversed order (`#`) before execution. `BF` then flattens the two arguments. We'll assume that the arguments are \$A\$ and \$e \in x\$. This leaves the stack as \$[...A, e]\$, where \$...\$ represents an [array splat](https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists). Finally, `B` takes the first \$e\$ elements of \$A\$ and returns a list containing those elements. *Note* : The function names \$g\$ and \$k\$ aren't chosen randomly. If the commands given to an operator (such as `€`) doesn't currently have a function (which [`g` and `k` don't](https://github.com/cairdcoinheringaahing/AddPlusPlus/blob/master/add%2B%2B.py#L1082)), then the named functions are searched for a matching function. This saves \$2\$ bytes, as normally the function would have to wrapped in `{...}` to be recognised as a user-defined function. At the time of writing, the currently unused single byte commands are `I`, `K`, `U`, `Y`, `Z`, `g`, `k`, `l`, `u` and `w`. When \$g\$ is applied over the elements of a range \$x\$, this returns a list of prefixes for \$A\$. We then map our second helper function \$k\$ over each of these prefixes. \$k\$ is defined as ``` D,k,@,¦+AbL/ ``` which is the standard implementation of the [arithmetic mean](https://en.wikipedia.org/wiki/Arithmetic_mean). `¦+` calculates the sum of the argument, `AbL` calculates its length, then `/` divides the sum by the length. This calculates the arithmetic mean of each prefix, yielding a new array, \$C\$. Unfortunately, \$C\$ contains the mean of \$A\$ as its final element, and does not include the mean of the empty list, \$0\$. Therefore, we would have to remove the final element, and prepend a \$0\$, but popping can be skipped, saving two bytes, for reasons explained in a second. Instead, we push \$[0]\$ underneath \$C\$ with `0b]$`, then concatenate the two arrays forming a new array, \$C^+\$. Now, we need to check each element as being less than its corresponding element in \$A\$. We push \$A\$ once again and zip the two arrays together with `ABcB]`. This is the reason we don't need to pop the final element: `Bc` is implemented with Python's [`zip`](https://docs.python.org/3/library/functions.html#zip) function, which truncates the longer arrays to fit the length of the shortest array. Here, this removes the final element of \$C^+\$ when creating the pairs. Finally, we [starmap](https://docs.python.org/3/library/itertools.html#itertools.starmap) \$p \in A, q \in C^+; p < q \equiv \neg(p \ge q)\$ over each pair \$p, q\$ to obtain an array of all \$0\$s if the array is golfy, and array containing at least a single \$1\$ if otherwise. We then check that all elements are falsey i.e. are equal to \$0\$ with `ª!` and return that value. ### The second version This takes advantage of Dennis' approach to remove \$24\$ bytes, by eliminating the helper functions. Given our input array of \$A\$, we first compute the cumulative sums with `¬+`, i.e the array created from \$[A\_0, A\_0+A\_1, A\_0+A\_1+A\_2, ..., A\_0+...+A\_i]\$. We then generate Jelly's equivalent of `J` (*indicies*), by calculating the range \$B := [1 ... \vert{A}\vert]\$ where \$\vert{A}\vert\$ once again means the length of the array. Next, we divide each element in \$A\$ by the corresponding index in \$B\$ with `BcB/` and prepend \$0\$ with `@0@B]`. This results in a new array, \$C^+\$, defined as $$C^+ := [0, A\_0, \frac{A\_0+A\_1}{2}, \frac{A\_0+A\_1+A\_2}{3}, ..., \frac{A\_0+...+A\_i}{i+1}]$$ The final part is identical to the first version: we push and zip \$A\$ with \$C^+\$, then starmap inequality over each pair before asserting that all elements in the resulting array were falsy. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` Kvṁ<≈ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJLduG5gTziiYgiLCIiLCJbMSwgNCwgMywgOCwgNl0iXQ==) Porting jelly got me feeling like yeet. ## Explained ``` Kvṁ<≈ K # prefixes of the input vṁ # the mean of each of those prefixes < # is the input less than each of those means? ≈ # and is everything the same? ``` [Answer] # [Desmos](https://desmos.com/calculator), 55 bytes ``` f(l)=\sum_{n=2}^{l.\length}\{l[1...n-1].\mean>l[n],0\} ``` Outputs `0` for golfy array, and a positive integer otherwise. [Try It On Desmos!](https://www.desmos.com/calculator/qpyjlv6fxf) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/nctchn5mvi) [Answer] # [Scala](http://www.scala-lang.org/), 109 bytes Golfed version, [try it online!](https://tio.run/##hZHPS8MwFIDv@yseOyWjlLWdU6sZ6E3QXcTTEHnWtIukqSTZQUr/9voShpeNNeQn@fK9l8RVqHHsPr9l5eEFlYF@/JI11AzLZ@X87sn4d14@dp2WaESP0KKv9n2FTsJWabHx9iDv4vJDbDB1h/ZeMEy1NI3fL2iCzi@YqhkpU2WU5zwDqYlfcj4MI0CI11JohrZxJTxYi7@7V2@VaSg0vNEZENDPgAo6J60nV0iOFZyDEBBS4Ge28wSy/DKSJbBKoEjgJoH1JJpHlA5cXUbXJPuvl1HyHVOskR7lHBLiRdVqGgxXjvj1FEtMbMFbTMAFaW/JTHwWxuUJH7sf@jKvDZtvu6NAdQaktZ116TyAw2wY/wA) ``` def f(a:List[Int]):Boolean={a match{case Nil=>true;case _=>a.sum<=(a.length*a.last*(if(f(a.init))1 else 0))}} ``` Ungolfed version ``` object Main { def f(a: List[Int]): Boolean = { a match { case Nil => true case _ => a.sum <= (a.length * a.last * (if(f(a.init)) 1 else 0)) } } def main(args: Array[String]): Unit = { assert(f(List(3)) == true) assert(f(List(2, 12)) == true) assert(f(List(1, 4, 3, 8, 6)) == true) assert(f(List(1, 2, 3, 4, 5)) == true) assert(f(List(6, 6, 6, 6, 6)) == true) assert(f(List(3, 2)) == false) assert(f(List(4, 5, 6, 4)) == false) assert(f(List(4, 2, 1, 5, 7)) == false) assert(f(List(45, 45, 46, 43)) == false) assert(f(List(32, 9, 15, 19, 10)) == false) println("No assertion errors.") } } ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 11 10 bytes -1 byte thanks to Mr. Xcoder ``` .A.egb.O<Q ``` [Try it online!](https://tio.run/##K6gsyfj/X89RLzU9Sc/fJvD//2gTHQUIMjQyjgUA "Pyth – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 96 bytes I know it's not a good golfing language, but I still gave it a go! Input array as first argument of comma separated ints to test. Returns 1 for true, 0 for false. ``` a->{int i=1,j,r=1,s=0;for(;i<a.length;i++,s=0){for(j=0;j<i;s+=a[j++]);r=s/i>a[i]?0:r;}return r;} ``` [Try it online!](https://tio.run/##TZAxb4MwEIVn8ytOmUAkhK51SOcOjSp1RAzXxHFMwKCzSRUhfjs9o0Ttcvb53nv@dDXecNP1ytan63xs0Dn4QGPHKBLGekVnPCo4jBGI0IOOuZYVJjISE2v64bsxR3AePR@3zpygZXv85clYXVaAyRgJsd3CJ5JTDvxFwdmQ84Ckh1Zxpu8gRCMR3uHcESh0dxgcasXWvyTSDgrAMq8y1zfGx6v1KnCIBenhL8Cqn5BXBn3WKKv9pQoqTg7wYFiTSzC7fwJu03QhFUtMaSpWvfMCtKKsD@jcxMHBo4yR2jhZ/p4C4t151Wbd4LOeYX1sMx0vOclzT48FHcBy7oyb/bigFC/rek1cXZHLACgZ68nESOE9GcOgZkG9M9KlBZZ1mlaJpMJtzR4Z6C1/JTmR8gNZ4NssZDTNvw "Java (OpenJDK 8) – Try It Online") ]
[Question] [ ### Introduction Let's observe the following sequence (non-negative integers): ``` 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ... ``` For example, let's take the first **three** numbers. These are `0, 1, 2`. The numbers used in this sequence can be ordered in **six** different ways: ``` 012 120 021 201 102 210 ``` So, let's say that **F(3) = 6**. Another example is **F(12)**. This contains the numbers: ``` 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ``` Or the concatenated version: ``` 01234567891011 ``` To find the number of ways to rearrange this, we first need to look at the length of this string. The length of this string is `14`. So we compute **14!**. However, for example the ones can exchange places without disrupting the final string. There are 2 zeroes, so there are **2!** ways to exhange the **zeroes** without disrupting the order. There are also 4 ones, so there are **4!** ways to switch the ones. We divide the total by these two numbers: This has **14! / (4! × 2!)** = 1816214400 ways to arrange the string `01234567891011`. So we can conclude that **F(12) = 1816214400**. ### The task Given **N**, output **F(N)**. For the ones who don't need the introduction. To compute F(N), we first concatenate the first N non-negative integers (e.g. for N = 12, the concatenated string would be `01234567891011`) and calculate the number of ways to arrange this string. ### Test cases ``` Input: Output: 0 1 1 1 2 2 3 6 4 24 5 120 6 720 7 5040 8 40320 9 362880 10 3628800 11 119750400 12 1816214400 13 43589145600 14 1111523212800 15 30169915776000 ``` ### Note Computing the answer must be computed within a **time limit of 10 seconds**, **brute-forcing** is **disallowed**. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! [Answer] ## ES6, ~~118~~ ~~81~~ 78 bytes ``` n=>[...[...Array(n).keys()].join``].map(c=>r/=(o[c]=-~o[c])/i++,o=[],i=r=1)&&r ``` Someone's bound to tell me there's a shorter way of concatenating the numbers up to `n`. Saved a cool 37 bytes by taking @edc65's idea and running it on steroids. (Save an extra byte by using '|' instead of `&&` but that limits the result to 31 bits.) Edit: Saved 3 further bytes again thanks to @edc65. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 13 bytes ``` ×/2!/+\⎕D⍧⍕⍳⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXECWWxCQZWhkYQ7iBAQAOcYmXI862tP@H56ub6Sorx0DFHd51Lv8Ue/UR72bgZz/QNn/aVwGXGlchkBsBMTGQGwCxKZAbAbE5kBsAcSWIDVghSCVhiClhiC1hiDFhqYA "APL (Dyalog Extended) – Try It Online") A full program. Uses `⎕IO←0`. ### How it works ``` ×/2!/+\⎕D⍧⍕⍳⎕ ⎕ ⍝ Take input from stdin (N) ⍳ ⍝ Generate range 0..N-1 ⍕ ⍝ Stringify the entire array (S) ⍝ (The result has spaces between items) ⎕D ⍝ The character array '0123456789' ⍧ ⍝ Count occurrences of each digit in S ×/2!/+\ ⍝ Calculate multinomial: +\ ⍝ Cumulative sum 2!/ ⍝ Binomial of consecutive pairs ×/ ⍝ Product ``` The multinomial calculation comes from the following fact: $$ \frac{(a\_1 + a\_2 + \cdots + a\_n)!}{a\_1! a\_2! \cdots a\_n!} = \frac{(a\_1 + a\_2)!}{a\_1! a\_2!} \times \frac{(a\_1 + a\_2 + \cdots + a\_n)!}{(a\_1 + a\_2)! a\_3! \cdots a\_n!} $$ $$ = \frac{(a\_1 + a\_2)!}{a\_1! a\_2!} \times \frac{(a\_1 + a\_2 + a\_3)!}{(a\_1 + a\_2)! a\_3!} \times \frac{(a\_1 + a\_2 + \cdots + a\_n)!}{(a\_1 + a\_2 + a\_3)! \cdots a\_n!} $$ $$ = \cdots = \binom{a\_1 + a\_2}{a\_1} \binom{a\_1 + a\_2 + a\_3}{a\_1 + a\_2} \cdots \binom{a\_1 + \cdots + a\_n}{a\_1 + \cdots + a\_{n-1}} $$ [Answer] # Jelly, ~~17~~ 15 bytes ``` R’DFµ=€QS;@L!:/ ``` [Try it online!](http://jelly.tryitonline.net/#code=UuKAmURGwrU94oKsUVM7QEwhOi8&input=&args=MTU) or [verify all test cases at once](http://jelly.tryitonline.net/#code=UuKAmURGwrU94oKsUVM7QEwhOi8KMHIxNcOH4oKs&input=). ### How it works ``` R’DFµ=€QS;@L!:/ Main link. Input: n R Yield [1, ..., n] for n > 0 or [0] for n = 0. ’ Decrement. Yields [0, ..., n - 1] or [-1]. D Convert each integer into the list of its decimal digits. F Flatten the resulting list of lists. µ Begin a new, monadic chain. Argument: A (list of digits) Q Obtain the unique elements of A. =€ Compare each element of A with the result of Q. For example, 1,2,1 =€ Q -> 1,2,1 =€ 1,2 -> [[1, 0], [0, 1], [1, 0]] S Sum across columns. This yields the occurrences of each unique digit. ;@L Prepend the length of A. ! Apply factorial to each. :/ Reduce by divison. This divides the first factorial by all remaining ones. ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 21 bytes ``` :qV0h!4Y2=sts:pw"@:p/ ``` [**Try it online!**](http://matl.tryitonline.net/#code=OnFWMGghNFkyPXN0czpwdyJAOnAv&input=MTU) ### Explanation ``` :q % implicitly input N, and generate vector [0, 1, ..., N-1] V % convert to string representation of numbers. Contains spaces, % but no matter. Only characters '0', ..., '9' will be counted 0h % append 0 character (not '0'), so that string is never empty ! % convert string to column char array 4Y2 % string '0123456789' (row char array) = % test all pairs for equality s % sum each column. For N = 12 this gives [2, 4, 1, 1, ..., 1] t % duplicate s % compute sum. For N = 12 this gives 14 :p % factorial w % swap. Now vector [2, 4, 1, 1, ..., 1] is on top " % for each number in that vector @:p % factorial / % divide % implicitly end loop % implicitly display ``` [Answer] # Python 2, ~~142~~ ~~137~~ ~~101~~ 97 bytes (Thanks @adnan for the suggestion about `input`) (Applied the incremental calculation from the [C version](https://codegolf.stackexchange.com/a/71208/25319)) ``` f=1;v=10*[0] for i in range(input()): for h in str(i):k=int(h);v[k]+=1;f=f*sum(v)/v[k] print f ``` ### Original version using factorial ``` import math F=math.factorial v=10*[0] for i in range(input()): for h in str(i):v[int(h)]+=1 print reduce(lambda a,x:a/F(x),v,F(sum(v))) ``` Really, the only golfing in the above is calling `math.factorial` `F` and leaving out some spaces, so there is probably a shorter python solution. If explanation is needed, `v` maintains a count of the frequency of each digit; the count is updated for each digit in each number in the indicated range. In the original version, we compute the number of permutations using the standard formula (Σfi)!/π(fi!). For the current version, this computation is done incrementally by distributing the multiplies and divides as we see the digits. It might not be obvious that the integer divide will always be exact, but it is easy to prove based on the observation that each division by `k` must follow `k` multiplies of consecutive integers, so one of those multiplies must be divisible by `k`. (That's an intuition, not a proof.) The original version is faster for large arguments because it does only 10 bignum divides. Although dividing a bignum by a small integer is faster than dividing a bignum by a bignum, when you have thousands of bignum divides, it gets a bit sluggish. [Answer] # Python 2, 197 Bytes (edit: saved 4 bytes, thanks Thomas Kwa!) ``` import math l,g,f,p,r,s=[],[],math.factorial,1,range,str for x in r(int(input())):l.append(s(x)) l="".join(l) for y in r(10):b=s(l).count(s(y));g.append(f(b)); for c in g:p*=y print f(int(len(l)))/p ``` Ungolfed: ``` import math l=[] #list of the numbers from 0 to n exchange_list=[] #numbers that can be exchanged with each other, ie repeats multiplied = 1 #for multiplying the digits by each other n = int(input()) for x in range(n): #put all the numbers from 0-n into the list l.append(str(x)) l = "".join(l) #put all the digits in a string to remove repeats for x in range(10): #look at all the digits and check how many are in the list/string count = str(l).count(str(x)) if count > 1: #if there is more than 1 of the digit, put the factorial of the amount of - exchange_list.append(math.factorial(count)) # - appearances into the exchange list. for x in exchange_list: #multiply all the values in the list by each other multiplied*=x print math.factorial(int(len(l)))/multiplied #print the factorial of the length of the string #divided by the exchanges multiplied ``` [Answer] ## CJam, ~~21~~ 19 bytes ``` ri,s_,A,s@fe=+:m!:/ ``` [Test it here.](http://cjam.aditsu.net/#code=ri%2Cs_%2CA%2Cs%40fe%3D%2B%3Am!%3A%2F&input=15) ### Explanation ``` ri e# Read input and convert to integer N. , e# Get a range [0 1 ... N-1]. s e# Convert to string, flattening the range. _, e# Duplicate and get its length. A,s e# Push "012345789". @fe= e# Pull up the other copy of the string and count the occurrences of each digit. + e# Prepend the string length. :m! e# Compute the factorial of each of them. :/ e# Fold division over the list, dividing the factorial of the length by all the other e# factorials. ``` [Answer] # JavaScript (ES6), 100 ``` n=>(f=[...[...Array(n).keys()].join``].map(c=>(k[c]=~-k[c],p*=i++),i=p=1,k=[]),k.map(v=>p/=f[~v]),p) ``` **Test** ``` F=n=>(f=[...[...Array(n).keys()].join``].map(c=>(k[c]=~-k[c],p*=i++),i=p=1,k=[]),k.map((v,i)=>p/=f[~v]),p) // Less golfed U=n=>( // STEP 1, count digits, compute factorials f= // will contain the value of factorials 1 to len of digits string [...[...Array(n).keys()].join``] // array of cancatenated digits .map(c=> // execute the following for each digit ( k[c]=~-k[c], // put in k[c] the repeat count for digit c, negated p*=i++ // evaluate factorial, will be stored in f ),i=p=1,k=[]),// initialisations // at the end of step 1 we have all factorials if f and max factorial in p // STEP 2, divide the result taking into account the repeated digits k.map(v=>p/=f[~v]), // for each digit, divide p by the right factorial (~v === -v-1) p // return result in p ) // Test console.log=x=>O.textContent+=x+'\n' for(j=0;j<=15;j++) console.log(j+' '+F(j)) ``` ``` <pre id=O></pre> ``` [Answer] # Pyth, 18 bytes ``` /F.!M+lJ.njRTQ/LJT ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=%2FF.!M%2BlJ.njRTQ%2FLJT&input=15&debug=0) ``` /F.!M+lJ.njRTQ/LJT implicit: Q = input number jRTQ convert each number in [0, ..., Q-1] to their digits .n flatten to a single list J store this list in J /LJT for each digit count the number of appearances in J +lJ prepend the length of J .!M compute the factorial for each number /F fold by division ``` [Answer] ## Haskell, 92 bytes ``` import Data.List h n|l<-sort$show=<<[0..n-1]=foldl1 div$product.map fst.zip[1..]<$>l:group l ``` Usage example: `h 12` -> `1816214400`. How it works ``` l<-sort$show=<<[0..n-1] -- bind l to the sorted concatenated string -- representations of the numbers from 0 to n-1 -- e.g. n=12 -> "00111123456789" l: group l -- group the chars in l and put l itself in front -- e.g. ["00111123456789","00","1111","2",..."9"] <$> -- map over this list product.map fst.zip[1..] -- the faculty the length of the sublist (see below) -- e.g. [87178291200,2,24,1,1,1,..,1] foldl1 div -- fold integer division from the left into this list -- e.g. 87178291200 / 2 / 24 / 1 -- Faculty of the length of a list: zip[1..] -- make pairs with the natural numbers -- e.g. "1111" -> [(1,'1'),(2,'1'),(3,'1'),(4,'1')] map fst -- drop 2nd element form the pairs -- e.g. [1,2,3,4] product -- calculate product of the list ``` [Answer] # C, ~~236~~ ~~174~~ ~~138~~ 121 bytes Much credit to rici, for massive reduction of bytes. ``` long long d,f=1;j,s=1,n,b[10]={1};main(d){for(scanf("%d",&n);n--;)for(j=n;j;j/=10,f*=++s)d*=++b[j%10];printf("%Ld",f/d);} ``` ## Ungolfed ``` long long d,f=1; j,s=1,n,b[10]={1}; main(d) { scanf("%d",&n); /* get input */ for(;n--;) /* iterate through numbers... */ for(j=n;j;j/=10,f*=++s) /* iterate through digits, sum up and factorial */ d*=++b[j%10]; /* count and factorial duplicates */ printf("%Ld",f/d); /* print out result */ } ``` Try it [here](http://ideone.com/BpA81a). [Answer] # C/bc, ~~233~~ ~~121~~ 112 bytes (assuming 3 byte penalty for `|bc`) 1. Inspired by Cole Cameron, removed the hacky character manipulation and just do arithmetic on the argument value. 2. Changed to scanf from using arg vector. ``` C[10]={1},n=1,k,t;main(){for(scanf("%d",&k);k--;)for(t=k;t;t/=10)printf("%d/%d*",++n,++C[t%10]);puts("1");} ``` Needs `bc` to actually do the arbitrary precision computation. Ungolfed and warning free: ``` #include <stdio.h> int main() { int C[10]={1},n=1,k,t; /* 0 is special-cased */ for(scanf("%d",&k);k--;) /* For each integer less than k */ for(int t=k;t;t/=10) /* For each digit in t */ printf("%d/%d*",++n,++C[t%10]); /* Incremental choice computation */ puts("1"); /* Finish the expression */ } ``` Illustrated (which I trust shows the algorithm): ``` $ for i in {0..15} 100 ; do printf %4d\ $i;./cg70892g<<<$i;done 0 1 1 1 2 2/1*1 3 2/1*3/1*1 4 2/1*3/1*4/1*1 5 2/1*3/1*4/1*5/1*1 6 2/1*3/1*4/1*5/1*6/1*1 7 2/1*3/1*4/1*5/1*6/1*7/1*1 8 2/1*3/1*4/1*5/1*6/1*7/1*8/1*1 9 2/1*3/1*4/1*5/1*6/1*7/1*8/1*9/1*1 10 2/1*3/1*4/1*5/1*6/1*7/1*8/1*9/1*10/1*1 11 2/1*3/2*4/1*5/1*6/1*7/1*8/1*9/1*10/1*11/1*12/2*1 12 2/1*3/2*4/3*5/2*6/1*7/1*8/1*9/1*10/1*11/1*12/1*13/1*14/4*1 13 2/1*3/1*4/2*5/3*6/4*7/2*8/1*9/1*10/1*11/1*12/1*13/1*14/1*15/2*16/5*1 14 2/1*3/1*4/2*5/1*6/3*7/4*8/5*9/2*10/1*11/1*12/1*13/1*14/1*15/1*16/2*17/2*18/6*1 15 2/1*3/1*4/2*5/1*6/3*7/1*8/4*9/5*10/6*11/2*12/1*13/1*14/1*15/1*16/1*17/2*18/2*19/2*20/7*1 100 2/1*3/2*4/3*5/1*6/4*7/1*8/5*9/1*10/6*11/1*12/7*13/1*14/8*15/1*16/9*17/1*18/10*19/1*20/11*21/2*22/2*23/12*24/3*25/4*26/5*27/2*28/6*29/2*30/7*31/2*32/8*33/2*34/9*35/2*36/10*37/2*38/11*39/2*40/12*41/3*42/3*43/13*44/4*45/13*46/5*47/6*48/7*49/3*50/8*51/3*52/9*53/3*54/10*55/3*56/11*57/3*58/12*59/3*60/13*61/4*62/4*63/14*64/5*65/14*66/6*67/14*68/7*69/8*70/9*71/4*72/10*73/4*74/11*75/4*76/12*77/4*78/13*79/4*80/14*81/5*82/5*83/15*84/6*85/15*86/7*87/15*88/8*89/15*90/9*91/10*92/11*93/5*94/12*95/5*96/13*97/5*98/14*99/5*100/15*101/6*102/6*103/16*104/7*105/16*106/8*107/16*108/9*109/16*110/10*111/16*112/11*113/12*114/13*115/6*116/14*117/6*118/15*119/6*120/16*121/7*122/7*123/17*124/8*125/17*126/9*127/17*128/10*129/17*130/11*131/17*132/12*133/17*134/13*135/14*136/15*137/7*138/16*139/7*140/17*141/8*142/8*143/18*144/9*145/18*146/10*147/18*148/11*149/18*150/12*151/18*152/13*153/18*154/14*155/18*156/15*157/16*158/17*159/8*160/18*161/9*162/9*163/19*164/10*165/19*166/11*167/19*168/12*169/19*170/13*171/19*172/14*173/19*174/15*175/19*176/16*177/19*178/17*179/18*180/19*181/10*182/20*183/20*184/20*185/20*186/20*187/20*188/20*189/20*190/20*1 ``` And, with the pipe through bc (and adding the computation of F(1000): ``` $ time for i in {0..15} 100 1000; do printf "%4d " $i;./cg70892g<<<$i|bc;done 0 1 1 1 2 2 3 6 4 24 5 120 6 720 7 5040 8 40320 9 362880 10 3628800 11 119750400 12 1816214400 13 43589145600 14 1111523212800 15 30169915776000 100 89331628085599251432057142025907698637261121628839475101631496666431\ 15835656928284205265561741805657733401084399630568002336920697364324\ 98970890135552420133438596044287494400000000 1000 45200893173828954313462564749564394748293201305047605660842814405721\ 30092686078003307269244907986874394907789568742409099103180981532605\ 76231293886961761709984429587680151617686667512237878219659252822955\ 55855915137324368886659115209005785474446635212359968384367827713791\ 69355041534558858979596889046036904489098979549000982849236697235269\ 84664448178907805505235469406005706911668121136625035542732996808166\ 71752374116504390483133390439301402722573240794966940354106575288336\ 39766175522867371509169655132556575711715087379432371430586196966835\ 43089966265752333684689143889508566769950374797319794056104571082582\ 53644590587856607528082987941397113655371589938050447115717559753757\ 79446152023767716192400610266474748572681254153493484293955143895453\ 81280908664541776100187003079567924365036116757255349569574010994259\ 42252682660514007543791061446917037576087844330206560326832409035999\ 90672829766080114799705907407587600120545365651997858351981479835689\ 62520355320273524791310387643586826781881487448984068291616884371091\ 27306575532308329716263827084514072165421099632713760304738427510918\ 71188533274405854336233290053390700237606793599783757546507331350892\ 88552594944038125624374807070741486495868374775574664206439929587630\ 93667017165594552704187212379733964347029984154761167646334095514093\ 41014074159155080290000223139198934433986437329522583470244030479680\ 80866686589020270883335109556978058400711868633837851169536982150682\ 22082858700246313728903459417761162785473029666917398283159071647546\ 25844593629926674983035063831472139097788160483618679674924756797415\ 01543820568689780263752397467403353950193326283322603869951030951143\ 12095550653333416019778941123095611302340896001090093514839997456409\ 66516109033654275890898159131736630979339211437991724524614375616264\ 98121300206207564613016310794402755159986115141240217861695468584757\ 07607748055900145922743960221362021598547253896628914921068009536934\ 53398462709898222067305585598129104976359039062330308062337203828230\ 98091897165418693363718603034176658552809115848560316073473467386230\ 73804128409097707239681863089355678037027073808304307450440838875460\ 15170489461680451649825579772944318869172793737462142676823872348291\ 29912605105826175323042543434860948610529385778083808434502476018689\ 05150440954486767102167489188484011917026321182516566110873814183716\ 30563399848922002627453188732598763510259863554716922484424965400444\ 85477201353937599094224594031100637903407963255597853004241634993708\ 88946719656130076918366596377038503741692563720593324564994191848547\ 42253991635763101712362557282161765775758580627861922528934708371322\ 38741942406807912441719473787691540334781785897367428903185049347013\ 44010772740694376407991152539070804262207515449370191345071234566501\ 33117923283207435702471401696679650483057129117719401161591349048379\ 16542686360084412816741479754504459158308795445295721744444794851033\ 08800000000 real 0m0.246s user 0m0.213s sys 0m0.055s ``` This computed F(5000) -- an 18,592-digit number -- in under 10 seconds. ``` $ time ./cg70892g3<<<5000|BC_LINE_LENGTH=0 bc|wc -c 18593 real 0m9.274s user 0m9.273s sys 0m0.005s ``` [Answer] # Perl 6, 117 bytes ``` say $_ <2??1!!permutations(+[(my@n=^$_ .join.comb)]).elems÷[*] ([*] 2..$_ for @n.classify(&unique).values)for lines ``` and in a more readable fasion ``` for (lines) -> $number { say 1 and next if $number < 2; my @digits = (^$number).join.comb; my @duplicates = @digits.classify(&unique).values; my $unique_permutations = permutations(+@digits).elems ÷ [*] ([*] 2..$_ for @duplicates); say $unique_permutations; } ``` [Answer] # Perl 5, 108 bytes ``` sub f{eval join"*",@_,1}push@a,/./g for 0..<>-1;for$i(0..9){$b[$i]=grep/$i/,@a}say f(1..@a)/f map{f 1..$_}@b ``` Many thanks to [dev-null](/users/48657/dev-null) for saving me 17 bytes, and to [japhy](http://www.perlmonks.org/?node_id=82445) for the factorial idea. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ ~~12~~ 11 bytes ``` ÝD¨SāPr¢!P÷ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8FyXQyuCjzQGFB1apBhwePv//4amAA "05AB1E – Try It Online") ``` Ý # range [0..input] D # duplicate ¨ # drop the last element S # split into digits ā # length range: [1..number of digits] P # product (effectively a factorial) r # reverse the stack ¢ # count occurences of each number in the list of digits ! # factorial of each count P # product of those ÷ # divide the initial factorial by this product ``` [Answer] # [Python 2](https://docs.python.org/2/), 123 bytes ``` import math i,b,F="".join(map(str,range(input()))),1,math.factorial for x in range(10):b*=F(i.count(`x`)) print F(len(i))/b ``` [Try it online!](https://tio.run/##JcrBCsIwDADQe7@i7JRIqVbwIuza71g7NhfZ0hIzmF9fFd/51bcuha@t0VaLqN2SLoZcdrHvOv8sxLClCi8VJ4kfExDXXQG/XHC/7ec0ahFKq5mL2MMS238NF7znUx@B/Fh2VhiOAdFUIVYbYZ0YCPGcWwu3Dw "Python 2 – Try It Online") 1. Convert the `range` of the input to a single string 2. Check how many times each of the numbers from 0 to 9 appears in the string and get the factorial for each then multiply them together 3. Divide the factorial of the length of the string by the number calculated in step 2 [Answer] ## PowerShell, 125 bytes ``` (1..(($b=0..($args[0]-1)-join'').Length)-join'*'|iex)/((0..9|%{$c=[regex]::Matches($b,$_).count;1..($c,1)[!$c]})-join'*'|iex) ``` Takes input `$args[0]`, subtracts `1`, builds a range of integers from `0..` that number, `-join`s that together into a string, and saves it as `$b`. We take the `.Length` of that string, build another range from `1..` that length, `-join` those integers together with `*`, then pipe that to `Invoke-Expression` (similar to `eval`). In other words, we've constructed the factorial of the length of the number sequence based on the input. That's our numerator. We divide that `/` by ... Our denominator, which is constructed by taking a range `0..9` and sending it through a for-loop `|%{...}`. Each iteration, we set a helper variable `$c` equal to the number of times the current digit `$_` appears within `$b` thanks to the [.NET `[regex]::matches` call](https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.matches(v=vs.110).aspx) coupled with the `.count` attribute. We then construct a new range from `1..` up to that value, so long as it's non-zero. Yes, in many instances, this will result in a range `1..1`, which evaluates to just `1`. We take all of those and `-join` them together with `*`, then pipe that to `Invoke-Expression` again. In other words, we've constructed the product of the factorials of the number of occurrences of each digit. --- ### NB Handles input up to `90` without issue and in significantly less than a second. ``` PS C:\Tools\Scripts\golfing> .\rearranging-the-sequence.ps1 90 1.14947348910454E+159 PS C:\Tools\Scripts\golfing> Measure-Command {.\rearranging-the-sequence.ps1 90} | FL TotalMilliseconds TotalMilliseconds : 282.587 ``` ... beyond that results in `Infinity` as output, since the length of the permutable string results in `170!` which fits in the `double` datatype (`7.25741561530799E+306`), but `171!` doesn't. PowerShell has a ... quirk ... that automatically up-casts from `[int]` to `[double]` in the case of overflow (provided you didn't explicitly cast the variable to start with). No, I don't know why it doesn't go to `[long]` for integer values. If we did some explicit casting and manipulation (e.g., using `[uint64]`, for unsigned 64-bit integers), we could get that higher, but it would significantly bloat the code as we would need to range up to 170-length with conditionals and then recast each multiplication from there onward. As the challenge doesn't specify an upper range, I'm presuming this to be adequate. [Answer] # Perl6 ``` perl6 -e 'sub p ($a) { my $x = $a.join.comb.classify(+*).values.map(*.elems).classify(+*).values.flatmap(*.list).flatmap((2..+*).list); my $y = 2..$a[*-1]; [/] $x.list * [*] $y.list }; p([1..11]).say' ``` Rather ungolfed at the moment - need sleep now. [Answer] # Groovy, 156 bytes ``` def f(n){def s=(0..n-1).join('') 0==n?1:g(s.size())/s.inject([:]){a,i->a[i]=a[i]?a[i]+1:1;a}*.value.inject(1){a,i->a*g(i)}} BigInteger g(n){n<=1?1:n*g(n-1)} ``` My humble first Code Golf solution. [You can test it here.](https://groovyconsole.appspot.com/script/5126972522889216) And here's a more readable version: ``` def f(n) { def s = (0..n - 1).join('') // Store our concatented range, s 0 == n ? 1 : // Handle annoying case where n = 0 fact(s.size()) / s.inject([:]) { // Divide s.size()! by the product of the values we calculate by... a, i -> // ...reducing into a map... a[i] = a[i] ? a[i] + 1 : 1 // ...the frequency of each digit a // Our Groovy return statement }*.value.inject(1) { a, i -> a * fact(i) } // Finally, take the product of the factorial of each frequency value } BigInteger fact(n) { n <= 1 ? 1 : n * fact(n - 1) } // No built-in factorial function... ``` Quite straightforward, but there were a couple highlights for me: * Performing an inject/reduce from an array of `chars` to a `Map<Character, Integer>`. This was still a little complicated by the lack of a default value for the map values. This doubt this is possible, but if the map defaulted all values to 0, I could avoid the ternary which is necessary to avoid an NPE. * The Groovy spread operator (e.g. `}*.value`) is always fun to use On annoying feature, however, was the necessity to declare the factorial function with the return type `BigInteger`. I was under the impression that Groovy wrapped all numerics in `BigInteger` or `BigDecimal`, but this might not be the case when it comes to return types. I'll have to experiment more. Without this return type explicitly stated, we get incorrect factorial values very quickly. [Answer] # J, 33 bytes ``` (#(%*/)&:!&x:#/.~)@([:;<@":"0)@i. ``` Converts the range into a string of digits, counts each digits, and applies the multinomial coefficient to compute the result. ## Usage ``` f =: (#(%*/)&:!&x:#/.~)@([:;<@":"0)@i. (,.f"0) i. 16 0 1 1 1 2 2 3 6 4 24 5 120 6 720 7 5040 8 40320 9 362880 10 3628800 11 119750400 12 1816214400 13 43589145600 14 1111523212800 15 30169915776000 ``` [Answer] # R, 118 bytes About 8 months late to the party but thought I'd give it a go because it looked like an interesting challenge. ``` function(n,x=as.numeric(el(strsplit(paste(1:n-1,collapse=""),""))),F=factorial)`if`(n,F(sum(1|x))/prod(F(table(x))),1) ``` [Try it on R-fiddle](http://www.r-fiddle.org/#/fiddle?id=X6OLdOa8&version=1) **Explained** 1. Generate vector `0 ... n-1` and collapse it to a string: `paste(1:n-1,collapse="")` 2. Split string into its digits and convert to numeric(store as `x`): `x=as.numeric(el(strsplit(...,"")))` 3. To calculate the numerator we simply do `factorial(sum(1|x))` which is just `#digits!` 4. To calculate the denominator we make use of `table` to construct a contingency table that list the frequencies. In the case of F(12) the table generated is: ``` 0 1 2 3 4 5 6 7 8 9 2 4 1 1 1 1 1 1 1 1 ``` 5. Which means we can take the use `factorial()` (which by the way is vectorized) on the count and simply take the product: `prod(factorial(table(x)))` Note: step 4 and 5 are only carried through if `n>0` otherwise return `1`. [Answer] # Mathematica, 65 bytes ``` (Tr@IntegerLength[a=Range@#-1]+1)!/Times@@(Total[DigitCount@a]!)& ``` Could probably be golfed further. [Answer] # [Ruby](https://www.ruby-lang.org/), 64 bytes ``` ->n,*w{a=1;[*0...n].join.chars{|d|a=a*(w<<d).size/w.count(d)};a} ``` [Try it online!](https://tio.run/##BcFLDoMgFAXQrXQIxF5Lp0o3Qhg8pUZNisZPQIG103O2s7vKoMrz4yrhIynZaPEC4AzmZXLoR9r2mGwiRYL5trUc@3R/a49@Od3BLM8N5cIkIN8cP1pjCml96FANOhiTyx8 "Ruby – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` éÄ\↑≈g→FP○░→ ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=828e5c18f7671a465009b01a&i=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15&a=1&m=2) ### Unpacked (14 bytes) and explanation: ``` r$c%|Fso:GF|F/ r Range [0..input) $ Stringify each and concat c Copy atop the stack %|F Factorial of length s Swap original back to top o Sort :G Run lengths F For each: |F Factorial / Divide running quotient by this factorial Implicit print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wii/Code-page) Golfed [Dennis' 15 byte Jelly answer](https://codegolf.stackexchange.com/a/70992/53748)... ``` ḶDFµW;ĠẈ!:/ ``` A monadic Link accepting a non-negative integer which yields a positive integer. **[Try it online!](https://tio.run/##y0rNyan8///hjm0uboe2hlsfWfBwV4eilf7///8NTQE "Jelly – Try It Online")** Or see the [test suite](https://tio.run/##y0rNyan8///hjm0uboe2hlsfWfBwV4eilf7/o3sOtz9qWuP@/3@0gY6CoY6CkY6CsY6CiY6CqY6CmY6CuY6ChY6CJVAKJA2UNwQqMASqMAQqMTSNBQA "Jelly – Try It Online"). ### How? ``` ḶDFµW;ĠẈ!:/ - Link: non-negative integer, N e.g. 12 Ḷ - lowered range [0,1,2,3,4,5,6,7,8,9,10,11] D - to decimal (vectorises) [[0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[1,0],[1,1]] F - flatten [0,1,2,3,4,5,6,7,8,9,1,0,1,1] µ - start a new monadic chain - i.e. f(that) W - wrap in a list [[0,1,2,3,4,5,6,7,8,9,1,0,1,1]] Ġ - group indices by values [[1,12],[2,11,13,14],3,4,5,6,7,8,9,10] ; - concatenate [[0,1,2,3,4,5,6,7,8,9,1,0,1,1],[1,12],[2,11,13,14],3,4,5,6,7,8,9,10] Ẉ - length of each [14,2,4,1,1,1,1,1,1,1,1] ! - factorial (vectorises) [87178291200,2,24,1,1,1,1,1,1,1,1] / - reduce by: : - integer division 1816214400 ``` [Answer] # [Python 2](https://docs.python.org/2/), 190 bytes ``` from collections import* g,n=range,int(input()) p=lambda r:reduce(lambda x,y:x*y,r,1) f=lambda n:p(g(1,n+1)) s=''.join(str(i)for i in g(n)) c=Counter(s) print(f(len(s))/p(f(c[i])for i in c)) ``` [Try it online!](https://tio.run/##RY3BCsIwEETv/YrcuqlBieCl0JOfIR5qmsSVdhM2KbRfHyMo3maY95i452egcymOwyJMmGdrMgZKApcYOHeNVzTwSN4qpAxIcc0gZROHeVwe0yi4ZzutxsK3b2rvt25XrLRs3I@iPoIHreigq5yGtj2@AhKkzIDSBRYokIQHqrMZrmGlbBlSPeLPr4PZVlrKU6zZ3PD@l4yUpejLGw "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 134 bytes ``` s="".join(map(str,range(input()))) n=d=1 for i in range(1,len(s)+1):n*=i;d*=i**len([c for c in range(10)if s.count(`c`)>=i]) print n/d ``` [Try it online!](https://tio.run/##TY4/T8MwFMTn3qewPNmhKn1py58is5WVhQ0hNXVcaijP0Ysj6KcPjli44XT63Q3XXfIpcT361AYnWuuxd1ovPlJk89V0ps8yl4bfg4ncDdnYIrBrHeGYREUVWf31ND8HNr29IrvlysWHtlhVTfDVq2ns/42XNh5Vv/Bp4Gz2fm8fXXyz6CRyVnzdjuUKvk/xHNSLDGGLWZZL8Vn4CV5Nb1GiD11Wu@ennUiSqT1IaD4xLkGoscIaG9zgFne4BxVIoBq0Aq1Bm18 "Python 2 – Try It Online") An alternate approach... ]
[Question] [ Given an integer \$N\$, you must print a \$N\times N\$ integer involute with the numbers increasing in a clockwise rotation. You can start with either 0 or 1 at the top left, increasing as you move towards the centre. ## Examples ``` Input => 1 Output => 0 Input => 2 Output => 0 1 3 2 Input => 5 Output => 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 20 7 12 11 10 9 8 Input => 10 Output => 0 1 2 3 4 5 6 7 8 9 35 36 37 38 39 40 41 42 43 10 34 63 64 65 66 67 68 69 44 11 33 62 83 84 85 86 87 70 45 12 32 61 82 95 96 97 88 71 46 13 31 60 81 94 99 98 89 72 47 14 30 59 80 93 92 91 90 73 48 15 29 58 79 78 77 76 75 74 49 16 28 57 56 55 54 53 52 51 50 17 27 26 25 24 23 22 21 20 19 18 ``` You may output a 2 dimensional array, or a grid of numbers. Challenge inspired by [Article by Eugene McDonnell](https://www.jsoftware.com/papers/play132.htm) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize your source code with answers being scored in bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` ⁸JW;ṚZ+LƲƲ2¡¡ ``` [Try it online!](https://tio.run/##ASMA3P9qZWxsef//4oG4Slc74bmaWitMxrLGsjLCocKh/8KiR/8xMA "Jelly – Try It Online") A nilad function or full program that takes a number from stdin and returns the 1-based involute of size n × n. ### How it works ``` ⁸JW;ṚZ+LƲƲ2¡¡ ⁸ Empty list ([]) 2¡¡ Take n from stdin and repeat 2n times starting from the above: Given previous matrix m, ṚZ+LƲ Rotate m and add the number of rows of m JW; Ʋ Prepend a row of 1..(number of rows of m) ``` The involute can be constructed iteratively as follows: ``` Start with m = [] (think of it as 0-row, 0-col matrix) Repeat 2n times: If m has r rows, add r to every cell of m Rotate m 90deg clockwise Attach 0..r-1 (or 1..r) as a new row at the top of m ``` After every step, the matrix `m` is always an involute for some rectangular size (square at even steps). For example, using 1-based indexing, doing a single step on ``` 1 2 3 8 9 4 7 6 5 ``` gives ``` 1 2 3 10 11 4 9 12 5 8 7 6 ``` and then ``` 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~12~~ 11 bytes ``` UG1YL-GoQ&P ``` [Try it online!](https://tio.run/##y00syfn/P9TdMNJH1z0/UC3g/39TAA "MATL – Try It Online") MATL (like MATLAB) has a `spiral` matrix which spirals clockwise from the center, so this performs the necessary flips and subtracts the matrix from `N^2`. ~~Probably Luis Mendo knows how to golf this...~~ Thanks to Luis Mendo for −1 byte. ``` % Implicit input N U % Square G1YL % Push the N×N spiral matrix (S) % clockwise from the center, starting at 1 - % N^2 - S, element-wise GoQ % Push mod(N,2)+1 &P % Flip along that dimension: % for odd N, flips the rows; for even N, flips the columns % Implicit output ``` [Answer] # [Python](https://www.python.org), 73 bytes (@ovs) ``` f=lambda n,m=0,p=-1:n*[n]and((*range(m,n),),*zip(*f(2*n-m+p,n,~p)[::-1])) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3PdNscxJzk1ISFfJ0cm0NdApsdQ2t8rSi82IT81I0NLSKEvPSUzVydfI0dTR1tKoyCzS00jSMtPJ0c7ULdPJ06go0o62sdA1jNTWhBqqnFeXnKhQUFGXmlShk5hbkF5VAeVwQSiNNw9AAphzmDgA) #### Old [Python](https://www.python.org), 74 bytes (@DialFrost) ``` f=lambda n,m=0,p=-1:n and((*range(m,n),),*zip(*f(2*n-m+p,n,~p)[::-1]))or() ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3vdJscxJzk1ISFfJ0cm0NdApsdQ2t8hQS81I0NLSKEvPSUzVydfI0dTR1tKoyCzS00jSMtPJ0c7ULdPJ06go0o62sdA1jNTXzizQ0oSaqpxXl5yoUFBRl5pUoZOYW5BeVQHlcEEojTcPQQBOqHOYQAA) #### Old [Python](https://www.python.org), 76 bytes ``` f=lambda n,m=0,p=-1:n>m and((*range(m,n),),*zip(*f(2*n-m+p,n,~p)[::-1]))or() ``` -15 by reversing order of recursion. [Attempt This Online!](https://ato.pxeger.com/run?1=LYwxCgIxEAB7X5HO3biBOys5yL3AH6hF5IweuJslxEILP2ITEP2Tv7G4q4aBYV5fvZdLkvqOfv-5leg2v23018DHIRgh9g2pd20nPZsgA4DNQc4nYBIkJPsYFWyEtRXHKyWhp-Ku61x7QEwZcH4uY05sVPMoxYysKZfZFhMgQtvgnNc68Q8) #### Old [Python](https://www.python.org), 91 bytes ``` lambda n:g((n*n-1,)) g=lambda*s:(l:=s[0][0])and g((*range(l-len(s),l),),*zip(*s[::-1]))or s ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY1BCsMgFET3OYW7_i8KcVeEnCTNwpJoA-YrahftVboRSnun3qYBAwOPGR7M6xsf5Raovu1w-dyLleff6M12nQ0j7QCIk1QCsXNDm3nW4PWQx37ag4Zmtms8GXILeOkXgozCo0DBn2sEnketpZoQQ2L5uDjZFDYWY1qpsHWLIZWjdQ1gQfWITa-18Q8) Builds the spiral from inside to out by recursively rotating 90° and adding a row on the top. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~18~~ ~~17~~ 16 bytes ``` (⍉⍳⍨,⊖+≢)⍣2⍣⎕⊤⍨⍬ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/@f9qhtQvV/jUe9nY96Nz/qXaHzqGua9qPORZqPehcbAfGj3q2PupYAJR71rvlf@z/tEJCx2QIA "APL (Dyalog Unicode) – Try It Online") Full program. TIO uses `⍵` instead of `⎕` for easier test case demonstration. For the core algorithm, refer to my [Jelly answer](https://codegolf.stackexchange.com/a/241837/78410). The only additional trick here is the `⊤⍨⍬`, which is [one of the shortest expressions that give a 0-by-0 matrix (`0 0⍴0`)](https://www.dyalog.com/blog/2021/07/code-golf-generating-empty-arrays/). This one in particular is handy because it doesn't mess up by stranding with the input value. -1 byte using `⍳∘≢ → ⍳⍨`; the rows are guaranteed to be distinct, so finding indices of items in itself gives the vector of indices for the leading axis. Also -1 byte by moving `⍉` to the end of the train to save a `∘`. Add first row to a transposed matrix == Add first column and then transpose it. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 29 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` {⍉⌽∘⍉∘∾´≍¨⌽(/«⥊2↕↕𝕩+1)⊔⌽↕𝕩⋆2} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge+KNieKMveKImOKNieKImOKIvsK04omNwqjijL0oL8Kr4qWKMuKGleKGlfCdlakrMSniipTijL3ihpXwnZWp4ouGMn0KCuKImOKAvzHipYpGwqjijL0xK+KGlTEw) A port of [Bubbler's Jelly answer](https://codegolf.stackexchange.com/a/241837/64121) comes in at 20 bytes: ``` {(⊒˜∾⍉∘⌽+≠)⍟2⍟𝕩↕0‿0} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeyjiipLLnOKIvuKNieKImOKMvSviiaAp4o2fMuKNn/CdlanihpUw4oC/MH0KCuKImOKAvzHipYpGwqjijL0xK+KGlTEw) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~48~~ ~~41~~ 40 bytes ``` F⊗N≔⁺⟦Eυλ⟧E∧υ⌊υ⁺LυE⮌υ§μλυEυ⪫Eι◧IλL⌈Eυ⌈ν ``` [Try it online!](https://tio.run/##NY29DoMwDIT3PkXE5Eh07MSE2oWqVKhr1SGAgUiJg/KDePs0UOrFd9b5u24StjNCxTgYy@BmQquwh4rm4J9Bt2iBc85K5@RI0Kjg4F2LGULOFP/kbNMl9ZuvJUkdNATOc7YnH0ijn9Lhl3vhgtbh7ktfUY8r6I2zTc4CL06NleThKLgbSbuWiSf6Bw4ersJ5UCl9sGux7qXHy98SP6AZy9IuYrzE86K@ "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 4 bytes by porting @Bubbler's observation that you can vectorised add the current length of the array to all of its elements on each iteration, 3 bytes by special-casing an empty array to avoid having to perform the first step manually, and 1 byte by golfing my rotation code. Explanation: ``` F⊗N ``` Repeat `2n` times. ``` ≔⁺⟦Eυλ⟧E∧υ⌊υ⁺LυE⮌υ§μλυ ``` Rotate the spiral while adding its length to it values and prefix an additional row of numbers from `0` up to its length. (Unfortunately Charcoal won't let me vectorised add the length to the whole matrix at once but fortunately I can at least do it a row at a time as part of the rotation.) Also handle the edge case of the initially empty spiral which produces a zero-length array. ``` Eυ⪫Eι◧IλL⌈Eυ⌈ν ``` Display the final spiral as a grid. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 35 bytes ``` {(⍵*2)-⌽{⍉⌽⍵,(⌈/,⍵)+⍳≢⍵}⍣(2×⍵-1)⍪0} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1rjUe9WLSNN3Uc9e6sf9XYCKaCAjsajng59HSBLU/tR7@ZHnYuAzNpHvYs1jA5PBzJ1DTUf9a4yqP2f9qhtwqPevkddzY961zzq3XJovfGjtomP@qYGBzkDyRAPz@D/aYdWAM2wAAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 91 bytes ``` f=(n,s=[[n*n-1]],[l]=t=s[0])=>l?f(n,[0,...t].map((_,i)=>s.map(r=>r[i-1]||--l).reverse())):s ``` [Try it online!](https://tio.run/##VY7BasMwEETv@Yq5WVvbwm5OTSLnI3IUpphELgqqZCQ1YJJ8u7tNaKGwMKPZfas9D5chHaOdcu3DySyj4hK@Skpr/@Lrtu8r7XqVVdJNT6pz@5HbuqmklLmXn8MkxHtluZMej6i6qC1zt1tdO5LRXExMRhDRJi1jiBDOZFgotFuWHWvDpiwJ1xVwDD5lhK/MA6OwtOXsj5o55OEZO1iWX@ZJBWekCx@CWT0/L/NQHURRoIQnOQ2nQx5iFhYd3rDHGhv8@DX7V/YtkTwH60WBgh4/31f/d3N4X74B "JavaScript (Node.js) – Try It Online") A port of [loopy walt](https://codegolf.stackexchange.com/users/107561/loopy-walt)'s [Python answer](https://codegolf.stackexchange.com/a/241833/44718). Although I don't really understand what happening. [Answer] # [R](https://www.r-project.org/), 78 bytes ``` function(n)matrix(order(cumsum(rep(rep(c(n,1,-n,-1),,x<-2*n-1),n-1:x%/%2))),n) ``` [Try it online!](https://tio.run/##HcdBCoAgEIXhffcQZmIkFGoRdZgwBReOMSV4e8sW7@P90sLeQmH3xMzAmI5HYoUspxdwJd0lgfjrnwMmQ5pJGySqm7Yj9/uxVjUpi/gFtgAGhwC2M3cWbC8 "R – Try It Online") Direct construction of the matrix, no rotations required. [Answer] # [R](https://www.r-project.org/), ~~84~~ ~~81~~ 67 bytes Or **[R](https://www.r-project.org/)>=4.1, 60 bytes** by replacing the word `function` with a `\`. *Edit: -14 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) inspired by [@Bubbler's Jelly answer](https://codegolf.stackexchange.com/a/241837/55372).* ``` function(n){m=t(1) while(T<n)m=rbind(1:n,(T=nrow(m))+t(m[T:1,])) m} ``` [Try it online!](https://tio.run/##Fcs7CoAwDADQvSdJsIMVXIq5RTdx8RMsmBRKxUE8e6XL216uTJVv3UpMCoqvUAGH5jnjdUCYFIXyGnUH59VCIM3pAUHsCsgcvLMLopGvclsMQ2NsuB7rDw "R – Try It Online") Uses the common "rotate and add a row on top" approach. See also [@Giuseppe's direct construction of the matrix](https://codegolf.stackexchange.com/a/241927/55372). [Answer] # JavaScript (ES7), ~~ 111 ~~ 101 bytes *Saved 9 bytes thanks to @tsh* Returns a matrix. The results are 1-indexed. ``` n=>[...Array(n)].map((x=-n/2,y,a)=>a.map(_=>n*n-(i=4*(++x*x>y*y?x:y)**2)+(x>y||-1)*(i**.5+x+y),y+=x)) ``` [Try it online!](https://tio.run/##PY7BbsIwEETvfMXesms7bpPCpciueugXcKSosgKhRrCOjBXZKv32FHLoad7MHGZObnTXLvoh1Rz2h6k3Exu71Vq/x@gKMu30xQ2I2dT81KqiHBnr5uzLWBZcozdLgVJmkW0R5S2/FhKiJYl3f7vVDQn0QuiVzLKQKtJkomm9bRS0ClYKmued7kP8cN03MhgLPwuALvA1nA/6HI7Y32/Mi/HRxhnHB446hU2Kno9IenD7TXIx4QuRPgXPWEH1j59cEUiYdfFL0x8 "JavaScript (Node.js) – Try It Online") [Answer] # [Julia](http://julialang.org/), 46 bytes ``` m\n=[1:n n.+rotl90(m')]' !n=[n<2||!~-n\~-n\n;] ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/Pzcmzzba0CpPIU9Puyi/JMfSQCNXXTNWnUsRKJ5nY1RTo1inmxcDwnnWsf/T8osUMhUy8xQMrQwNuBSAICWzuCAnsVJDMVMTzC8oyswrycnT0ORKzUv5DwA "Julia 1.0 – Try It Online") the simple rotate and add row, with some trickery with `'` (transpose) starts with 1 [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ 34 33 ~~ 32 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) I would have thought Jelly would be better at this, maybe a more mathematical approach will triumph? ``` ŒMḢḢ +þ`¬ZṚ$ṛ¬Ç$¦€Ç¦‘ɼ$ḣÇȦƊ?ƬȦƇṂ ``` A monadic Link accepting a positive integer that yields a list of lists of positive integers (top-left `1` option). **[Try it online!](https://tio.run/##y0rNyan8///oJN@HOxYBEZf24X0Jh9ZEPdw5S@XhztmH1hxuVzm07FETkAZSDTNO7lF5uGPx4fYTy4512R9bA6TaH@5s@n@43f3/f0MDAA "Jelly – Try It Online")** ### How? Start with an \$N\times N\$ table of zeros, then repeatedly either fill in the next number in the first zero of the first row that contains a maximal value, unless that row is filled in which case rotate. This process terminates with a full table but rotated further than we want, so we collect all the states along the way then pick the one we need out (using `ȦƇṂ`). ``` ŒMḢḢ - Helper Link: list of list of integers (current state) ŒM - multidimensional indices of maximal elements Ḣ - head Ḣ - head -> row index containing the maximum value +þ`¬ZṚ$ṛ¬Ç$¦€Ç¦‘ɼ$ḣÇȦƊ?ƬȦƇṂ - Link: positive integer, N +þ` - [1..N] addition table with [1..N] ¬ - logical NOT -> N×N table of zeros Ƭ - collect inputs while distinct applying: ? - if... Ɗ - ...condition: last three links as a monad: Ç - call our helper link ḣ - head (the current state) to that index Ȧ - all truthy when flattened? $ - ...then: last two links as a monad: Z - transpose Ṛ - reverse - this rotates when we've finished a row $ - ...else: last two links as a monad: ɼ - apply to the register (initially 0) & yield: ‘ - increment ¦ - sparse application... Ç - ...to indices: call our helper link € - ...apply: for each: ¦ - sparse application... $ - ...to indices: last two links as a monad: ¬ - logical NOT (vectorises) Ç - call our helper link ṛ - ...apply: the incremented register value Ƈ - filter keep those for which: Ȧ - all truthy when flattened? Ṃ - minimum (of the rotate tables we have left) ``` --- Another approach, but even more lengthy at 39: ``` RµṚĖm€0F;Ɱ"ḊṚ’$ṖṚ4ƭ³’Ḥ¤Ð¡UÐeẎIƇŒṬ€×"J$S ``` [Try this one](https://tio.run/##y0rNyan8/z/o0NaHO2cdmZb7qGmNgZv1o43rlB7u6AIKPWqYqfJw5zQgy@TY2kObgdyHO5YcWnJ4wqGFoYcnpD7c1ed5rP3opIc71wB1Hp6u5KUS/P9wu/v//4YGAA "Jelly – Try It Online") This one works by building a list of the two-dimensional indices ordered by their final value then composing the table by adding up tables that are all zeros except the bottom-rightmost entry which is the number we want there in the end. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¯I·FāUøí¬g+Xš ``` 1-based. Port of [*@Bubbler*'s Jelly answer](https://codegolf.stackexchange.com/a/241837/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##AR8A4P9vc2FiaWX//8KvScK3RsSBVcO4w63CrGcrWMWh//81) or [verify all test cases](https://tio.run/##yy9OTMpM/R/ipuSZV1BaYqWgZO@n8//Qer9D292ONIYe3nF47aE16doRRxf@r@VSckwuKU3MUcgvLYGqteVSCihKLSmp1C0oyswrSU1ByOlwRaXbhZ3bem5r5OFdQZGPOnqDar0OLas9tFuH69A2@/8A). **Explanation:** ``` ¯ # Start with an empty list [] I· # Push the input and double it F # Pop and loop that many times: ā # Push a list in the range [1,length] (without popping the matrix) U # Pop and store this list in variable `X` øí # Rotate the matrix 90 degrees clockwise: ø # Zip/transpose; swapping rows/columns í # Reverse each row ¬ # Push the first row (without popping the matrix) g # Pop and push its length + # Add that to each value in the matrix Xš # Prepend `X` as first row # (after the loop, the resulting matrix is output implicitly) ``` [Answer] # [R](https://www.r-project.org/), ~~187~~ ~~183~~ 151 bytes ``` function(n){w=which X=diag(0,n) X[n,]=m=n:1 while(!min(X)){i=w(!X)[1] j=w(!!X[-1:-i]) X[i-1+1:j]=max(X)+j:1 X=t(X)[m,]} `if`(n%%2,t(t(X)[m,])[m,],X)-1} ``` [Try it online!](https://tio.run/##NYxNCoMwEIX3cwsXwgQTaIR2Icw9AiGg2KaO1BGKxULx7GlS6Obj8f6eKVKKLxk3XgVFfWCnfeJxAkdXHu540qLAedGBFpLOQk4fN6wWFnQq95l2rJzyNsBcZOW8sZ3hUGZsbGO7OW@Hd643cz5wtGXpFx0O6Dn2KHXd6g3/7g/aKWOPFNEqiNgWnAsuKn0B "R – Try It Online") A clumsier version of rotate and fill! [Answer] # [JavaScript (Node.js)](https://nodejs.org), 108 bytes ``` n=>[...Array(n)].map((_,Y,a)=>a.map(g=(y=Y,x,_,s=n)=>y?--s-x?s-y?x?s*4+g(y-1,x-1,_,s-1):4*s-y:3*s-x:s+y:x)); ``` [Try it online!](https://tio.run/##VU/BasMwDL33K3SL1NhmWXtpUifsG3YqZRTTJsEls0PsjZjRb8@0lg12sN7T83sSuppPE86THaN0/tIunV6cro9KqZdpMgkdval3MyKexEEY0rW5t73GpA9iFicRtGM5NVIGOTdBpobrepv3mGQhZn7skQWV2zV/lhuucxnyVM5E1dL5CXBoI1jQUFQMe8YnJnlO8LUCOHsXIviPyIYOLVWs/aUSi2xOsAfL8Jt5pPzQqsH3yNljepzhQNeAWQY5OFKjubxGM0W0UMMOGthACT98w/yZeUGkrt46zCCj@@bb6v9sFm/LNw "JavaScript (Node.js) – Try It Online") [Answer] # [Factor](https://factorcode.org/) + `math.matrices`, ~~82~~ 79 bytes ``` [ 2 * { } [ dup length [ m+n flip [ reverse ] map ] keep iota prefix ] repeat ] ``` [Try it online!](https://tio.run/##HY07DsIwFAR7TrE1iAgo4QCIhgZRRSlM2AQrjmOeXxAfcXbj0IxGW8w2ptZB0vl0OO636I3e0FE83d@LDLE1IyLvI/1kLT3FOPs2agcfEYSqryDWK3az2XqVSmwwxwdflLiOAY6@zd0S/cKjcTZkFT4okajyT8jsyAA7qJl6jX3mSRhoFFWqjXOItg@OSzUXxyL9AA "Factor – Try It Online") Port of @Bubbler's excellent [Jelly answer](https://codegolf.stackexchange.com/a/241837/97916). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes -8 bytes thanks to @att. ``` Nest[Join[{l=0;l++&/@#},Reverse@#+l]&,{{}},2#-1]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@98vtbgk2is/My@6OsfWwDpHW1tN30G5VicotSy1qDjVQfl9f7t2TqyaTnV1ba2OkbKuYaza/4CizLySaGUFXTuFtGjl2FgFNQV9B4VqQx0FIx0FUx0FQ4Pa/wA "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ Given an array of integers. Find out its longest sub-array (contiguous subsequence) whose sum is 0. The sub-array for output *may* be an empty array. ## Input Input an array of integers. ## Output Output the longest zero sum sub-array. If there are multiple such arrays, output any one of them. ## Output Format You may output in one of following acceptable format: 1. Output an array of integers; 2. Output the index of first (inclusive) and last (inclusive) element of sub-array; * Output (last = first - 1) for empty sub-array 3. Output the index of first (inclusive) and last (exclusive) element of sub-array; 4. Output the index of first (inclusive) element and length of sub-array; You may choose 0-indexed or 1-indexed value for 2~4 options. But your choices should be consistent for both first and last element. ## Rules * This is code golf, shortest codes win. * As usual, [standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/) are forbidden. * Your program *may* fail due to integer overflow (as long as this not trivialize this challenge, [which is a standard loophole](https://codegolf.meta.stackexchange.com/a/8245/44718)). * This is code golf. We don't care the performance of your algorithm / implementation. ## Testcases ``` Input -> Output [] -> [] [0] -> [0] [1] -> [] [-1,1] -> [-1,1] [-1,1,2] -> [-1,1] [-2,-1,1,2] -> [-2,-1,1,2] [1,2,3,4,5] -> [] [1,0,2,0,3,0] -> [0] [1,2,-2,3,-4,5] -> [1,2,-2,3,-4] [1,2,3,4,5,-4,-3,-2,-1,0] -> [4,5,-4,-3,-2] [0,1,0,0,0,1] -> [0,0,0] [0,0,0,1,0,0,1] -> [0,0,0] [0,0,0,1,0,0,-1] -> [0,0,0,1,0,0,-1] [-86,14,-36,21,26,-2,-51,-11,38,28] -> [26,-2,-51,-11,38] [0,70,65,-47,-98,-61,-14,85,-85,92] -> [0,70,65,-47,-98,-61,-14,85] [4,-4,2,0,4,-2,-2,1,0,1,-4,0,-2,2,2,-4,0,-1,2,1,-4,-2,3,4,3,0,3,2,-4,2,3,3,1,2,3,-3,-4,3,-4,4,0,-3,-1,-5,-4,1,-3,4,-4,2,-1,-4,0,2,-5,-5,2,1,-4,0,-1,4,3,3,-5,-4,-5,3,-3,-1,-5,1,-2,3,0,3,-4,1,-5,-1,4,-5,2,1,-3,4,4,1,-1,-5,-5,-2,4,0,-3,4,1,-3,0,-3] -> [4,-4,2,0,4,-2,-2,1,0,1,-4,0,-2,2,2,-4,0,-1,2,1,-4,-2,3,4,3,0,3,2,-4,2,3,3,1,2,3,-3,-4,3,-4,4,0,-3,-1,-5,-4,1,-3,4,-4] ``` [Answer] # [Python 3](https://docs.python.org/3/), 47 bytes ``` f=lambda x,*a:f(*a,x[1:],x[:-1])if sum(x)else x ``` [Try it online!](https://tio.run/##dY/BboMwEETvfMXeYkfjCkNCCBL9EcTBVUFBAmIVaOnX0zVQSiJVlq3dN@sZ2373t3sbTlOZ1qZ5ezc04miSUhwNxkwnOZ@J0rmsSuqGRoyyqLuCxunrVtUF6cSjqrWg@9BbSqkxVhSfpoajQy/kS2frqhcHUq90kNIj@1G1vSgF65LSdL4opyx3A1nuZf5S@VzqDSqNtZmrBSB4RAEe6NayEQKEOOG8GWr4zHym@zxGyk2qbXSH9j5uQoVYMlaHPXb/gFt6OdcM1zxJaq/9Mf5OHEE7uwgB50Zz2FmzqBHGCOLl3rMw2198RO4xF6hrDBU58YSYEe9r8Jv431j@Aw "Python 3 – Try It Online") It's simple breadth-first search, implemented recursively. The `if...else` is slightly bothering me; it feels like there is an improvement somewhere... [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` ŒéʒO_}θ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6KTDK09N8o@vPbfj//9oXQszHUMTHV1jMx0jQx0jMx1dIx1dU0MdXUNDHWMLHSOLWAA "05AB1E – Try It Online") ``` Œ # sublists of the input é # sort by length ʒ } # keep those where: O_ # the sum equals 0 θ # take the last one ``` The output of `Œ` doesn't contain the empty list, but if the result of the filter is empty, `θ` fails and leaves the empty list on the stack. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~24~~ ~~22~~ 21 bytes ``` {t@'*<-/t:&x=/:x}0,+\ ``` [Try it online!](https://ngn.bitbucket.io/k#eJzlUstqwzAQvOsrQigNpLtYD8dxTF//4ZoGAoH07ENKyL93dyTbiqG0p16KkL07uzMroTk2l/51tX7kom/uz09Fc75aengzpj80+9Pd/uNl2bYdtVa2k82Ohh95DTyNsXwpUEkbxFYyK7kyLWmuy6U+1lYeehNPAQ4UNSMPnJGZ54xz1BU5JVXkRaYCd+Ok6CjU5GuQtpYqFd8S72riSusl1QLJ3unRSx2t5y2h4DHDKWg10xVjPStwjmcOuKOP9CArXoZxOXxAC8pkXNBpluZxGuFR2wzamFNCLnLkGyYRF4fbqB91tX8QUHngLslKezpFGq9x1y2NOa76gzz1Zf35fr6ukJnCtN2CnxdtZ+TZEVkJ3QjCA0gQmcENN9Doi4iOqclsMgjmZhnn5Z6JoCaJP9kHpQzKB8z8hNYcxpTcYTdzZmabahNmfmFA8OYFyP9kyzTxuzbR+I+2Ta/49xfvvgBV2gdM) *-1 byte thanks to coltim and Traws* Unfortunately(?), I found a 2-byte golf that bumps the time complexity to \$\mathcal{O}(n^2 \log n)\$ (and space complexity to \$\mathcal{O}(n^2)\$). This one utilizes "equality table" `=/:` and "deep where" `&` to extract *all* pairs of indices that represent zero-sum subarrays. Finding the pair that represents the longest such subarray is algorithmically the same. --- # [K (ngn/k)](https://codeberg.org/ngn/k), 24 bytes ``` *<!/1-/'\(*'1|:\)'.=0,+\ ``` [Try it online!](https://ngn.bitbucket.io/k#eJzlUstOwzAQvPsrSoUUCLvUjyRNIx4fkkZUqlQJzj2AgH9nd+wkbiUEJy7IcrI7uzNry3PoyruLleNVsb0qC/fRba+L23tLN1tjjvtu93y5e3lc9v1AvZXtZLOj8UdeA09TLF8KVFGN2EpmJVemJc11udTH2spjb+IpwIGiZuSBMzHznHGOtiGnpIa8yDTg1k6KjkJLvgVpbalR8TXxpiVutF5RK5DsjR690tF63goKHjOcglYzXTHWswLneOaAO/pID7LiZRiXwwe0oEzGBZ1maR6nER61etTGnApykSPfMIu4ONxG/air/aOAygN3SVba0ynSeI2HYWnMoTju5anfy7en188CmVmZfljww6IfjDw7Iiuhm0B4AAkiM7rhBJp8EdEpNZlNRsHcLNO83DMR1CTxZ/uglEH5gDM/oTWHMSV32MmcM7PNtRkzvzAgeOcFyP9kyzTxuzbR+I+2Ta/49xcfvgB5AwaK) Runs in \$\mathcal{O}(n \log n)\$ time and \$\mathcal{O}(n)\$ space. A monadic function train that takes a list of integers and returns `[start index (inclusive), end index (exclusive)]`. (For reading test case output, `!0` and `()` are notations for empty lists, and `,0` is a notation for the singleton list `[0]`.) ``` *<!/1-/'\(*'1|:\)'.=0,+\ monadic train; x: integer list 0,+\ prepend 0 to the cumulative sum of x = group; gives a dict of {value:indices} . extract values of the dict any ordered pair inside each row forms a valid (start,end) pair with subarray sum of zero (*'1|:\)' for each list, extract (first,last) <!/1-/'\ sort this list by ascending order of (first-last) * extract the first pair ``` It is actually shorter than a function that generates all contiguous subsequences and operates on them (which is \$\mathcal{O}(n^3)\$ time and space): # [K (ngn/k)](https://codeberg.org/ngn/k), 26 bytes ``` {*(0=+/)#,/x{y'x}/:|!1+#x} ``` [Try it online!](https://ngn.bitbucket.io/k#eJzlUstqwzAQvOsr0qSQtllhPWzHCbT9EGMIBALtOQeXNP/e3dHDiqG0p16KkL07uzMjoT3tL08P5nlTPa6oGi8f6/Fa7T/v7GY1XpU6H/eHt/vD++uy7wfqDW/LW1tKP3ISOMoxf8lTTQ1iw5nhXJiGJJdlY5+WVp16I08A7SloBh44mVnmGufoWrJCasmxTAtuY7loyXfkOpC2hloR35LedaRbqdfUMcR7J0evxVrOW0PBwcMKaCSTFWI5K3AdzuxxRxfonle4jMbl8AHNC1Pjglay6KejhUOtSdrwqSEXOPz1k4gN5iboB13pTwIiD9xGWW6Pp4j2Eg/DUqnT+nxUqlL9sNAvi35Q/NCIDIc2g3h1JIhUev8bKE9CQHOqisFIguV4ZL9ySgIoSeRPA4NSAZUGswlCawnDpZypG5/ZeE21CVO/GDnw5gXI/zSI0fG7Ntb4j4MaX/HvLz58AUzsA8k=) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ã k_x ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=4yBrX3g&input=WzAsNzAsNjUsLTQ3LC05OCwtNjEsLTE0LDg1LC04NSw5Ml0) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4yBrX3g&footer=zA&input=WwpbXQpbMF0KWzFdClstMSwxXQpbLTEsMSwyXQpbLTIsLTEsMSwyXQpbMSwyLDMsNCw1XQpbMSwwLDIsMCwzLDBdClsxLDIsLTIsMywtNCw1XQpbMSwyLDMsNCw1LC00LC0zLC0yLC0xLDBdClswLDAsMCwxLDAsMCwxXQpbMCwwLDAsMSwwLDAsLTFdClstODYsMTQsLTM2LDIxLDI2LC0yLC01MSwtMTEsMzgsMjhdClswLDcwLDY1LC00NywtOTgsLTYxLC0xNCw4NSwtODUsOTJdCls0LC00LDIsMCw0LC0yLC0yLDEsMCwxLC00LDAsLTIsMiwyLC00LDAsLTEsMiwxLC00LC0yLDMsNCwzLDAsMywyLC00LDIsMywzLDEsMiwzLC0zLC00LDMsLTQsNCwwLC0zLC0xLC01LC00LDEsLTMsNCwtNCwyLC0xLC00LDAsMiwtNSwtNSwyLDEsLTQsMCwtMSw0LDMsMywtNSwtNCwtNSwzLC0zLC0xLC01LDEsLTIsMywwLDMsLTQsMSwtNSwtMSw0LC01LDIsMSwtMyw0LDQsMSwtMSwtNSwtNSwtMiw0LDAsLTMsNCwxLC0zLDAsLTNdCl0tbVI) ``` ã k_x :Implicit input of array ã :Sub-arrays k :Remove elements that return truthy (not 0) _ :When passed through the following function x : Reduce by addition :Implicit output of last element of resulting array (or undefined if empty) ``` [Answer] # JavaScript (ES6), 60 bytes ``` f=(b,...a)=>eval(b.join`+`)?f(...a,b.slice(1),b.pop()?b:b):b ``` [Try it online!](https://tio.run/##dY/PToNAEMbvPsXEC7txdgNUEWtoT3rwoIceaxMXulQaBARsNMY3MPHiUd/D5/EFfIQ6C/1DTQxhM/Obb75vd64WqorKpKhFlk/1chkHLEQppeLBQC9UykI5z5Ps5uCGD2NmBhjKKk0izRxOZZEXjA/Dfsj74bLU9w9JqZkVVxaXpVbT8yTVo6csYjaXdT6qyySbMS6rIk1qtn@d7XMZ5@WZim5ZBcEAnvcAxqAQ9GOho1pPYQIBVOsFEAOglTtVMHM5fkryUtMmxEw1XZRnVZ5qmeYzdjG6upRVk5nET4yEHBv5AVgWBME2ZAjWz9fb98c7nRb0wfr@fLXI74UvxxMTOp7sje22sql0NlA4uGqaqgXo7iIXd@imJSN0sYeHeLQxdNAmZhPt5hESRik20g7q@hiF6GGbsXLoYvMONJ/TnqsM0/wZie5sy@g5voeOsfPQpVyvCTtyaOhgz0fXb/f@Dhr7Yxs9c5ljFCc@Cs8MD9EnRP@Ju078Tzb5BQ "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: b, // b[] = next array ...a // a[] = list of all other arrays ) => // eval(b.join`+`) ? // if the sum of b[] is not zero: f( // do a recursive call: ...a, // first try with the other arrays that were // already passed to this iteration b.slice(1), // then try with b[] without the leading term b.pop() ? b : b // and finally with b[] without the trailing term // NB: we don't mind modifying b[] at this point, // and this is shorter than b.slice(0, -1) ) // end of recursive call : // else: b // success: return b[] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 7 bytes ``` ẆSÐḟṪȯ$ ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLhuoZTw5DhuJ/huarIryQiLCLDh+KCrMWS4bmY4oKsWSIsIiIsWyJbMCw3MCw2NSwtNDcsLTk4LC02MSwtMTQsODUsLTg1LDkyXSwgWzEsMiwzXSwgWzAsMSwyLDNdIl1d) Converted from a full program to a link for the same byte-count thanks to Jonathan Allan. ``` ẆSÐḟṪȯ$ Main Link Ẇ Get all sublists (unfortunately excludes the empty sublist) Ðḟ Filter to remove elements with a non-falsy/non-zero S sum $ Apply monadically to the resulting list of sublists: Ṫ - take the last one (returns zero if the list is empty) ȯ - logical OR; if 0 was returned, instead return the list of sublists, which is the empty list ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ÞS'∑¬;t # main program ``` ``` ÞS # sublists '∑¬; # filter ∑¬ # by the negated sum t # take the tail ``` Similar to @hyper-neutrino's answer. [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C3%9ES%27%E2%88%91%C2%AC%3Bt&inputs=%5B-86%2C14%2C-36%2C21%2C26%2C-2%2C-51%2C-11%2C38%2C28%5D&header=&footer=) [Answer] # [J](http://jsoftware.com/), 28 bytes ``` <\\.;@{.@(\:#&>)@#~&,0=+/\\. ``` [Try it online!](https://tio.run/##xVFNT8MwDL3zKywmrUxsJU7SrisUVULitBPnSj6gTRMXfgASf734I1lXDc4oSmI/2@85zsd4WxZH6FooYA0OWt6bEl7e9q/j0zCUj/1X2d8N7WL5vOoX38u16@4fGB9XN4f30ycUBWxaOPJtvoOOPTcPormEgAaI9RsGPqE@uSnkZ9EzLccDRKgupZFvzzvkJiSLJJHiVJaBVMqGeBQkMOeecG7BZSVZmmcm2nkZNYjwOo1Snq@VtUJGEEKT3trUgCJZg8frHN9kka2DWrrbAu0aoFpSIjRVFvwzTrx3Pj@cnyfjiqrjtUUU0Ikny2yZh@Jkcwk6Ym/lgZcNjHSqemhZkErSIaJ48fwL/6Ksn6i0XmNV5ladqHRWw2eYSNDEnfEbr@RnAqFXHBMtp6cukrzY4w8 "J – Try It Online") * `<\\....#~&,0=+/\\.` All boxed sublists `<\\.` filtered by those with 0 sum `#~ 0=+/\\.` after flattening both `&,`. * `(\:#&>)@` Sort down by length * `;@{.@` And open the first element. [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 64 bytes ``` [ [ "1"] when-empty all-subseqs [ Σ 0 = ] filter ?last >array ] ``` [Try it online!](https://tio.run/##xVRLboMwFNxzimn2RtgmhLRquqy66abqKsqCUkeJSoCCozaKcprep1dK/SM4IlkXC8ue997M@FmwzHJZNcfXl6fnx1tkTZPtWnyIphQFNplchdtynVfvAnUjpNzVzbqUaMXnVpS5aPtVKL5lk7W4C4J9APXsgQNuQGZm5aCox6ITSC8kEurDdueH2LUgG8Z76CTIwBFjfEGYKmNMvfyaV6YJOchZuQ8PVRRIuPPhsZ6F@g7pQd3sOYg8F34SGWT1eNeUNAHVQgmYcpUYK2OqUih4Cpb2DINgLzmJkGjDE5BpCpLolBipgtQ7Zb6Lq6kdW6wPrtscGzlmPFMNRnqnh13rJhqc2GZyczXMlnM1bJeJ6byZTBnXlcS0l@qd0yNOgpnYuOM2OrGhszVq5j0JteKR5be8Or8j0PQGp45WpTsXTt6svXv/h8MfgsNxjjlGdLTA10qURGxquUNWFKTdvqnvuFXR3x9FcI8FlutCigYPRdZKzMxvAQtFEIahiubVpq5aAZHlq@Mf "Factor – Try It Online") * `[ "1"] when-empty` Unfortunately necessary to handle the empty sequence. `all-subseqs` blows up otherwise. `"1"` is simply the shortest thing you can stick in there that ultimately produces the empty sequence. * `all-subseqs` Get every subsequence of a sequence. * `[ Σ 0 = ] filter` Select the ones that sum to 0. * `?last >array` Take the last (also longest) element (or `f` if the sequence is empty) and then convert it to a sequence. Necessary because the `filter` can return an empty sequence. [Answer] # Wolfram Language (Mathematica), ~~37~~ 36 bytes ``` Last@*Select[Tr@#==0&]@*Subsequences ``` -1 byte from att using function composition [Try it online!](https://tio.run/##fVDBasMwDL33KwyDHYYNsp2k6SGQD@ihsN1KDlkwXWEtrHFPo9@e2ZbsxG0ZOI70nvT0rFNvv8ypt8ehnw7NtO1H2769m28z2P3HpX1pGnjtHHL9HM3P1ZwHM067y/Fs28P@99atUgzLRC4TITl7BDhTGaY4e4b7nDPNWcFZeUdA4CDQ8NgksFE86ZwlkRcay72DTAmCPgRfFPxPi/yldeW4MMAFyk@uaFIpfbG7dO3Q@k517b4qmFu7a@NKRBUanFbtcX9tsk0V@BTcSEFTVLQmkQXE8ETAcSvGmEpVIu1Hx/2qpK7DSUsUtGKvQCHJapQWtGOJ0GxTzJ4UlZXcyyyckL0ijo1i/q/zGTL5hsxNtIAyPlRLM1Qhk4OgQg@CVEYNAbh10x8) `Subsequences` generates all contiguous subsequences, sorted by length; `Select[Tr@#==0&]` selects those whose trace (total) is 0; `Last` selects the last, and thus longest, of these subsequences. att also shows, in the comments, a different approach from mine that is 35 bytes: ``` Last@Pick[#,Tr/@#,0]&@*Subsequences ``` [Answer] # [Risky](https://github.com/Radvylf/risky), 12 bytes ``` {_*_1?+?:_0{_-+_0+_0+_0 ``` [Try it online!](https://radvylf.github.io/risky?p=WyJ7XypfMT8rPzpfMHtfLStfMCtfMCtfMCIsIlswLDIsLTEsMSwzXSIsMF0) ### Explanation Here's a rough tree diagram of how the program parses: ``` { ? + * : + + { _ + _ _ _ _ _ _ 1 ? 0 - 0 0 0 ``` The left half generates a list of all sublists that sum to zero: ``` {_ List of sublists of the input (ordered shortest to longest) *_1 Repeat 1 time (no-op) ? Filter by this function: +? The sum of the input : Equals _0 Zero ``` The right half, using a ton of no-ops to balance the parse tree, evaluates to -1. Finally, `{` gets the element of (left half's result) at index (right half's result): i.e. the last and therefore longest sublist. [Answer] # [Python 3](https://docs.python.org/3/), 85 bytes ``` lambda a:[(s,l)for l in range(len(a))for s in range(len(a)-l)if 0==sum(a[s:s+l])][-1] ``` [Try it online!](https://tio.run/##XchLDsIgEADQq7Bk4kwCWvtLOAmyGGPRJlPaQF14emxcunibt33215ouNbpbFV7uD1Y8el1QIK5ZiZqTypyek5YpaYbflv8lgTkq41x5L5p9GctJAgRPNtQtz2nXUXuDncH2itR0SEOP1Fok22B/1GE4B4D6BQ "Python 3 – Try It Online") -5 bytes thanks to totallyhuman [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~13~~ 9 bytes *-4 bytes thanks to a [clever trick](https://codegolf.stackexchange.com/a/231602/16766) from [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)* ``` ⊇.+0&s.∨Ė ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FXu562gVqx3qOOFUem/f8fbaBjpBNvqGMY@z8CAA "Brachylog – Try It Online") (Note that negative numbers in the input must be indicated with underscores rather than minus signs.) ### Explanation It would have been nice to use this 6-byte solution: ``` s.+0∨Ė s. A contiguous sublist of the input is the output +0 and its sum is zero ∨ Or, if it is impossible to satisfy those conditions... Ė the output is the empty list ``` Unfortunately, the order in which the `s` predicate tries sublists is [ordered by start index](https://tio.run/##SypKTM6ozMlPN/r/v/jhrs5HXUv//4820DHSiTfUMYwFAA), not by length. However, the `⊇` predicate, which gives not-necessarily-contiguous sublists, *is* [ordered by length](https://tio.run/##SypKTM6ozMlPN/r//1FX@8NdnY@6lv7/H22gY6QTb6hjGAsA). So we can start by getting the longest sublist and then afterwards check that it's contiguous: ``` ⊇.+0&s.∨Ė ⊇. A sublist of the input is the output +0 and its sum is zero & and furthermore s. the output is a contiguous sublist of the input ∨ Or, if it is impossible to satisfy those conditions... Ė the output is the empty list ``` [Answer] # [Haskell](https://www.haskell.org/), 64 bytes ``` k=length f l|sum l==0=l|h:t<-l=f t#(f.init)l a#b|k a>k b=a|1>0=b ``` [Try it online!](https://tio.run/##ZY3RisIwEEXf8xUD7oPCzDJJNUYx/oFfIH1IwW5L0yIa3/rvNbFZtrCEzNw5uXPTuGd3836aOutvw09oRA1@fL568Nay9WNzDCfytoawWtff7dCGjRduVY0duHMHlXWjPLOtpt61A1jo3f0C90c7BPhKA6zrzRUEwLXEVHlucm4kcaFQZa1wOUaBBW5x9ztyBBwR/71TstDCk1cSowLnxOxnTEfO9T@izICMRpnWNaoYqD8pOxkNEguDymQf455Rp6/2SAeDpJNniyaieA@qhFKI6Q0 "Haskell – Try It Online") * `f` return longest sublist by checking if list sum is 0 or choosing the best result coming from recursively inspecting tail and init * a`#` b used by `f` to choose longest result [Answer] # [Haskell](https://www.haskell.org/), ~~75~~ 73 bytes *-2 bytes thanks to [Joseph Sible](https://codegolf.stackexchange.com/users/81540).* ``` f i|e<-length i=last[(s,l)|l<-[0..e],s<-[0..e-l],0==sum(take l$drop s i)] ``` [Try it online!](https://tio.run/##dVBBjsMgDLznFT7sIZHsCEibUql5Ql@AOCCVblFJGhX21r9noc0lyS4IC8@Mx@CbCXfr/TRdwb3sibwdvuMNXOdNiKoM6KuXP5FidW01hvlGXiPruvDTl9HcLfivy/MxQgBX6SnaEAN0oEDpAuaFoNgi44uMOG4BFEtI4B9oyrHBHe5XKEs4SwzbqCkX0LZi9skUNfjptqxmmDf/xH8ZWv1EtsizZYsiNWnfznueZBwbiUKujA4M2/yIA9JRIrVZuUOZoHSOQoMuit64IU24N@MZyvHphgg1XCt4j376BQ "Haskell – Try It Online") [Answer] ## Clojure, 98 bytes ``` #(or(first(for[n[(count %)]i(range n)j(range n i -1):when(=(apply +(subvec % i j))0)][i j]))[1 0]) ``` Returns an exclusive range, or `[1 0]` if no such range is found. For example: ``` [1,2,3,4,5,-4,-3,-2,-1,0] -> [3 8] ``` [Answer] # [Perl 5](https://www.perl.org/), 73 bytes ``` sub{(sort{@$b-@$a}grep!sum(@$_),map[@_?@_[$_/@_..$_%@_]:()],0..@_**2)[0]} ``` [Try it online!](https://tio.run/##nVRNb9swDD3Pv0INtMU2qMySE9eN4VX3DetlO7mG0RZu6y4fXuxgK4L89kyk1HwBuzRKBPKRfI@irbT1ajbZ8cd8163vN363XPUbze@F5nfbp1XdXnTrua95FcD8ri10da2rglefdTUa8eqjrsqpH5QQjUa6CkMVFFG53WXe/JXpvu763PeKkuVfWFGCZ2JkRmjLAywkOI8sh4A6wxScwHsXyUBBDGOYHEglRAaMDHyiajCBuWKffASdUGGKiMHqOI5jmA4EuKTdnQw65zFxHDxgeKo0AYmMCSgjnZDeRJqohDgFldrC84AVuIwgwYYuQVylIBKMjiE1kPldqTfN/6UhyRjPg3Mak4Ci5iSCEXq4rI1zIVzY@cQ0W48pSxCbZUcnaLi0UWGMtYLmJtFzisKJEMMEv2qvK4k/dlVmjw800jYQWQVp6jELK94oUIK0pCM2Ba4T1wLapcfMxz7Ud4/A@4B9vGsEZZB5f56bWe3TRQk21M/81efNogVe/22DvGtnzUNNcXybM5fC@NOyzz/xR3MvTXJg8XbVLHr2smwW/hCGoDEpYPXvYwhZ2TUbLH8xit8uBmzKBmEYsu83P9jN1wuDZN7WW3c1@9Z0/XT6s29mbGj@BIbZ7h8 "Perl 5 – Try It Online") [Answer] # [Desmos](https://desmos.com/calculator), ~~154~~ ~~139~~ 137 bytes *Thanks [@fireflame241](https://codegolf.stackexchange.com/users/68261/fireflame241) for helping me golf a couple of bytes (on Discord)* ``` A=length(l) B=[1...A-f] Z=[0...A] h(a,b)=\{\sum_{C=a}^bl[C]=0,0\} f=\max((Z+1)\sign(\sum_{n=1+Z}^Ah(n-Z,n))) g(l)=[f,\max(Bh(B,[f...A]))] ``` Uses Output Format #4. The first element in the outputted list is the length of the subarray, while the second element is the starting index of the subarray in respect to the inputted array. [Try It On Desmos!](https://www.desmos.com/calculator/w3h6rp5vpz) [Try It On Desmos! - Prettified(and a more verbose version)](https://www.desmos.com/calculator/s5savobsr4) [Answer] # [PHP](https://www.php.net/), 101, 99, 90 ``` for(;$argc>$j=++$i;)for(;$j;)array_sum(array_slice($argv,$j--,$l=$argc-$i))||die("$j,$l"); ``` [Try It Online](https://tio.run/##K8go@G9jXwAk0/KLNKxVEovSk@1Usmy1tVUyrTUhYlnWmolFRYmV8cWluRpQVk5mcqoGSHWZjkqWrq6OSo4tWK@uSqamZk1NSmaqhpJKFlBYSdP6////Zv8N/xv91zX@b/Jf1@S/AQA) Input is array elements as the command line argument list. Outputs the zero based start position and length of sub array. Does not output anything for the null case. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` F⊕LθF⊕⁻Lθι⊞υ✂θκ⁺κι¹I⊟Φυ¬Σι ``` [Try it online!](https://tio.run/##ZcyxCsIwGATg3afI@Af@DEm1FBwFQVAJdCwdSow2NE1smvj6sZkcvPW@OzUOQfnB5vz0gcDFqaBn7aJ@wFW7VxxhoZSSv/JmXFp/BIkpTKZ1hISktUZpWJBMSKTd4FQAEk7pcSeDcRFOwxpB@jecjY06lNXdR2jTDOVqyzHnrmNNjXyPrKpRcBQ1MoHswJFxjlWDoun7zD72Cw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⊕LθF⊕⁻Lθι⊞υ✂θκ⁺κι¹ ``` Carefully list the subsequences of the input in ascending order of length. ``` I⊟Φυ¬Σι ``` Get those with a zero sum (or no sum at all, in the case of the empty subsequences) and output the last i.e. the longest. [Answer] # [Haskell](https://www.haskell.org/), 88 bytes ``` f=head.filter((0==).sum).concat.iterate(concat.zipWith map[tail,init].replicate 2).(:[]) ``` [Try it online!](https://tio.run/##LYxBCoMwEEWvMgsXCabB6k7IAXqCLkIWox3J0JhKnFLo5W2ELv9/vBdxf1JKxw7oisfwiVQIisJx0o4X2N9rJa6TSBkQKO2VNlPbes4sgEaQE2A4FhcJH3bhJFSU6pzTtsrazq88o1iuNwqp//zydmeJsOLmz4Q5c8EW2hJXTtBrq0Yf9LEiZ7cVztIsfjBX05vLMI63LOH4AQ "Haskell – Try It Online") [Answer] # [jq](https://stedolan.github.io/jq/), 53 bytes ``` [.[keys[]:keys[]+1]|select(add==0)]|max_by(length)//. ``` [Try it online!](https://tio.run/##bU/bbsIwDH3fl4CwIU7aUJD4kiqaGFTbGINN7cOQ@PZ1Pk66vUyWE9/OOfbpcxzbZfvW3fo2bfO3kHTvu3N3GGb743G3c/N0f99/PT7dZufu8jy8zFerpcLSQ@vURZ2Fpo88Ak@/sb4UqKLaYqeZ09yVDqPJU7dMosCBMgsmHQEJE8ss@jdn26OJJKCI5JU0GlMt2hQKDfnGQGtHEVJr4k1DHNGvqNGS@garV1gE@1bG4E1DUHTIYDnG5lbnfEGwG32GB7V8Gtup9hgsAMl2riArelwkvPXqidt0KqPLGH3DH4lkcZf5My/mJwLQW10KrY6XLYo84vR9/Rher5d@5MMP "jq – Try It Online") **Explanation:** ``` [ .[keys[]:keys[]+1] #calculates all subarrays |select(add==0) #selects these which add up to 0 ] |max_by(length) #picks the longest one //. #if there is no such subarray returns an empty array ``` ]
[Question] [ So this is my first challenge on this site. The challenge is to take in an input integer \$n\$, which will be positive, and print, in ascending order (\$1\$ to \$n\$, **including n**), the output of \$i^{(n-i)}\$ (where \$i\$ is the current integer). # Example Given the input 5, the program will print: ``` 1 8 9 4 1 ``` \$1^4\$ is 1 and \$1+4=5\$ \$2^3\$ is 8 and \$2+3=5\$ \$3^2\$ is 9 and \$3+2=5\$ \$4^1\$ is 4 and \$4+1=5\$ \$5^0\$ is 1 and \$5+0=5\$ # Input and Output Input will be in the form of a positive integer. Output will be a list of numbers, delimited by either commas or new lines. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~8~~ 5 bytes ``` ⍳*⊢-⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/@v8ahvql/wo941mnogZrCrXqizr4t6Un6FQn6egm6abX6e@qOuxal5iUk5qcGOPiFADlCdc6R6cWJOibomF5Dj6f@obYLB/0c9ex91zHjUu1nrUe8KQ20g438aUOJRbx9ETVfzofXGj9omgqwJcgaSIR6ewf8f9a5KOwRRbmgAAA "APL (Dyalog Unicode) – Try It Online") Anonymous prefix tacit function. TIO tests for the range [1..10]. Thanks @lirtosiast for 3 bytes. ### How: ``` ⍳*⊢-⍳ ⍝ Tacit function ⍳ ⍝ Range. ⍳n generates the vector [1..n]. ⊢- ⍝ Subtracted from the argument. The vector is now [n-1,n-2,...,0] ⍳* ⍝ Exponentiate using the range [1..n] as base. The result is the vector ⍝ [1^(n-1), 2^(n-2), 3^(n-3),...] ``` [Answer] ## Haskell, 23 bytes ``` f i=[x^(i-x)|x<-[1..i]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00h0za6Ik4jU7dCs6bCRjfaUE8vMzb2f25iZp6CrUJBUWZeiYKKQpqC6X8A "Haskell – Try It Online") Alternative version, also 23 bytes: ``` f i=(^)<*>(i-)<$>[1..i] ``` [Answer] # Japt, 5 bytes ``` õ_p´U ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=9V9wtFU=&input=OA==) ``` õ :Range [1,input] _ :Map p : Raise to the power of ´U : Input decremented ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 19 bytes ``` {^$_+1 Z**[R,] ^$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzpOJV7bUCFKSys6SCdWAcir/Z@WX6RgqmOpY2isUM3FWZxYqaCnlsZV@x8A "Perl 6 – Try It Online") Anonymous code block that takes a number and returns a list. Zip exponents the range `1 to input` and the range `input-1 to 0` [Answer] # [Aheui (esotope)](https://github.com/aheui/pyaheui), ~~193~~ 164 bytes (56 chars) ``` 방빠싹받분샥퍼붇바파쟈뿌차샦히망맣여 타빠바푸투반또분뽀뿌서썪삯타삯받반타 석차샦져쌲볼어타토싻삭빠쏛ㅇ또섞썪뻐 ``` [Try it online!](https://tio.run/##JY7BCoJAFEX3/k8f1CKoD2gvOqXQSAZRgmlClBVGQ4UoGn1My/vmG6Y3tHlcePcc7nA8mk6MgbqgLWjRQqWoBflHHfWoA6i1lpL2IT6S1Jn8k85DlBnKA20rR/suY7a0anRYQSVIYubxdi0gdhRdybtzja9Vq4SzQyL7y6hoSD7w7Gnz4oee84SOvJvdsky/s4B1JHK2oIuNGfwA "Aheui (esotope) – Try It Online") [Try it on AVIS](https://aheui.github.io/avis/)(**Korean**); just copy and paste code above, press start button, input a number, see how it moves. To see output, press the **>\_** icon on left side. --- It's not golfed much, but I give it a shot. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` _m^-Q ``` [Try it online!](https://tio.run/##K6gsyfj/Pz43Tjfw/39TAA "Pyth – Try It Online") Optimally encoded this would be 4.106 bytes. ``` _ reverse of the following list: m map the following lambda d: ^ (N-d)**d -Qd d Q over [0,...,N-1] ``` [Answer] # [J](http://jsoftware.com/), 10 bytes ``` (>:^|.)@i. ``` [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F/DziquRk/TIVPvvyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKagimMYQJjGBr8BwA "J – Try It Online") ## If we really need to separate the numbers by a newline: # [J](http://jsoftware.com/), 13 bytes ``` ,.@(>:^|.)@i. ``` [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F9Hz0HDziquRk/TIVPvvyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKagimEoa6rq6sOEzPBImZo8B8A "J – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` R*ḶU$ ``` [Try it online!](https://tio.run/##y0rNyan8/z9I6@GObaEq////NwUA "Jelly – Try It Online") ``` R [1,...,n] * to the power of ḶU$ [0,...,n-1] reversed ``` [Answer] # PHP, 32 bytes ``` while($argn)echo++$i**--$argn,_; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/0c987739bbeb6317fc43a8a63bcbabdf4ce0f4e8). [Answer] # [Octave](https://www.gnu.org/software/octave/), 18 bytes ``` @(n)(t=1:n).^(n-t) ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQSNPU6PE1tAqT1MvTiNPt0Tzf5ptYl4xV5qGqeZ/AA "Octave – Try It Online") Thanks [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo), using internal variable saves 3 bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` *ạ¥€ ``` [Try it online!](https://tio.run/##y0rNyan8/1/r4a6Fh5Y@alrz//9/UwA "Jelly – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~24~~ ~~20~~ 18 bytes ``` (x=Range@#)^(#-x)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE7872Zl@1@jwjYoMS891UFZM05DWbdCU@1/QFFmXkm0W7RpbOx/AA "Wolfram Language (Mathematica) – Try It Online") -4 thanks @lirtosiast. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 6 bytes ``` rx\╒m# ``` [Try it online!](https://tio.run/##y00syUjPz0n7/7@oIubR1Em5yv//m3JZchkaAwA "MathGolf – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 40 bytes ``` lambda n:[i**(n-i)for i in range(1,n+1)] #Outputs a list ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKjpTS0sjTzdTMy2/SCFTITNPoSgxLz1Vw1AnT9tQM/Z/QVFmXolCmoapJheMaYJgGiIxDTT/AwA "Python 2 – Try It Online") # [Python 2](https://docs.python.org/2/), 41 bytes ``` n,i=input(),0 exec"print(n-i)**i;i+=1;"*n #Prints in reversed order ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P08n0zYzr6C0RENTx4ArtSI1WamgKDOvRCNPN1NTSyvTOlPb1tBaSSvv/39TAA "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 27 bytes ``` ->n{(1..n).map{|r|r**n-=1}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNQTy9PUy83saC6pqimSEsrT9fWsLb2f4FCWrRpLBeIMjSM/Q8A "Ruby – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 35 bytes ``` .+ * _ $$.($.'*$($.>`$*)_¶ %~`^ .+¶ ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4srnktFRU9DRU9dSwVI2iWoaGnGH9rGpVqXEMelp31o2///pgA "Retina – Try It Online") Explanation: ``` .+ * ``` Convert the input to unary. ``` _ ``` Match each position. This then sets several replacement variables. `$`` becomes the left of the match; `$>`` modifies this to be the left and match; `$.>`` modifies this to take the length, i.e. the current index. `$'` meanwhile is the right of the match, so `$.'` is the length i.e. the current exponent. ``` $$.($.'*$($.>`$*)_¶ ``` Create a string `$.(` plus `$.'` repetitions of `$.>`*` plus `_`. For an example, for an index of 2 in an original input of 5, `$.'` is 3 and `$.>`` is 2 so the resulting string is `$.(2*2*2*_`. This conveniently is a Retina replacement expression that caluclates 2³. Each string is output on its own line. ``` %~`^ .+¶ ``` For each line generated by the previous stage, prefix a line `.+` to it, turning it into a replacement stage, and evaluate that stage, thereby calculating the expression. [Answer] ## QBasic, ~~35~~33 bytes Thank you @Neil for 2 bytes! ``` INPUT a FOR b=1TO a ?b^(a-b) NEXT ``` Slightly expanded version on [REPL.IT](https://repl.it/@pimsteenbergh/MasculineDarksalmonApplicationpackage) because the interpreter in't entirely up-to-spec. **Output** ``` QBasic (qb.js) Copyright (c) 2010 Steve Hanov 5 1 8 9 4 1 ``` [Answer] # [F# (.NET Core)](https://www.microsoft.com/net/core/platform), 42 bytes ``` let f x=Seq.map(fun y->pown y (x-y))[1..x] ``` [Try it online!](https://tio.run/##SyvWTc4vSv3/Pye1RCFNocI2OLVQLzexQCOtNE@hUteuIL8cSCtoVOhWampGG@rpVcT@LyjKzCtJy1NQUnVUUtAAaSjJ98ksLtFIUzDV1PwPAA "F# (.NET Core) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~33~~ 32 bytes ``` n=>(g=i=>--n?++i**n+[,g(i)]:1)`` ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k4j3TbT1k5XN89eWztTSytPO1onXSNTM9bKUDMh4b91cn5ecX5Oql5OfrpGmoappuZ/AA "JavaScript (Node.js) – Try It Online") -3 bytes with credits to @Shaggy, and -1 byte by @l4m2! # [JavaScript (Node.js)](https://nodejs.org), 36 bytes ``` f=(n,i=1)=>n--?[i++**n,...f(n,i)]:[] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjTyfT1lDT1i5PV9c@OlNbW0srT0dPTy8NJKEZaxUd@986OT@vOD8nVS8nP10jTcNUU/M/AA "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 37 bytes ``` n=>[...Array(n)].map(x=>++i**--n,i=0) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i5aT0/PsagosVIjTzNWLzexQKPC1k5bO1NLS1c3TyfT1kDzv3Vyfl5xfk6qXk5@ukaahqmm5n8A "JavaScript (Node.js) – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 46 bytes ``` x=>new int[x].Select((_,i)=>Math.Pow(i+1,--x)) ``` [Try it online!](https://tio.run/##DcqxCsIwEADQvV9xdEowCTg4tc2moCgIHRxEpMarHtQLpAnN38dOb3lu1m6mckjsWuKo4Ljn9MMwvCZs3z6tWAsjdFByZxkXWNc9P0yPE7ooxFOR7OxliF9z9YugzVZpnaUsTVXdAkU8E6PoYyD@mJMnFjXUCkaxk1I25Q8 "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` :Gy-^ ``` [Try it online!](https://tio.run/##y00syfn/38q9Ujfu/39TAA "MATL – Try It Online") ### Explanation Consider input `5` as an example. ``` : % Implicit input. Range % STACK: [1 2 3 4 5] G % Push input again % STACK: [1 2 3 4 5], 5 y % Duplicate from below % STACK: [1 2 3 4 5], 5, [1 2 3 4 5] - % Subtract, element-wise % STACK: [1 2 3 4 5], [4 3 2 1 0] ^ % Power, element-wise. Implicit display % STACK: [1 8 9 4 1] ``` [Answer] # Java, 59 Bytes ``` for(int i=1;a+1>i;i++)System.out.println(Math.pow(i,a-i)); ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 37 bytes ``` import StdEnv $n=[i^(n-i)\\i<-[1..n]] ``` [Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4xLJc82OjNOI083UzMmJtNGN9pQTy8vNvZ/cEkiUJGtgoqC6f9/yWk5ienF/3U9ff67VOYl5mYmFwMA "Clean – Try It Online") Defines `$ :: Int -> [Int]` taking an integer and returning the list of results. ``` $ n // function $ of n = [i ^ (n-i) // i to the power of n minus i \\ i <- [1..n] // for each i in 1 to n ] ``` [Answer] # [R](https://www.r-project.org/), 34 bytes ``` x=1:scan();cat(x^rev(x-1),sep=',') ``` [Try it online!](https://tio.run/##K/r/v8LW0Ko4OTFPQ9M6ObFEoyKuKLVMo0LXUFOnOLXAVl1HXfO/6X8A "R – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LD<Rm ``` Port of [*@lirtosiast*'s Jelly answer](https://codegolf.stackexchange.com/a/176669/52210). [Try it online.](https://tio.run/##yy9OTMpM/f/fx8UmKPf/f1MA) **Explanation:** ``` L # List in the range [1, (implicit) input integer] # i.e. 5 → [1,2,3,4,5] D< # Duplicate this list, and subtract 1 to make the range [0, input) # i.e. [1,2,3,4,5] → [0,1,2,3,4] R # Reverse it to make the range (input, 0] # i.e. [0,1,2,3,4] → [4,3,2,1,0] m # Take the power of the numbers in the lists (at the same indices) # (and output implicitly) # i.e. [1,2,3,4,5] and [4,3,2,1,0] → [1,8,9,4,1] ``` [Answer] # [Lua](https://www.lua.org), 43 41 bytes -2 bytes thanks to *@Shaggy* ``` s=io.read()for i=1,s do print(i^(s-i))end ``` [Try it online!](https://tio.run/##yylN/P@/2DYzX68oNTFFQzMtv0gh09ZQp1jbQCElX6GgKDOvRCMzTqNYN1NTMzUv5f9/UwA "Lua – Try It Online") [Answer] # R, 22 bytes ``` n=scan();(1:n)^(n:1-1) ``` Fairly self-explanatory; note that the `:` operator is higher precendence than the `-` operator so that `n:1-1` is shorter than `(n-1):0` If we are allowed to start at 0, then we can lose two bytes by using `(0:n)^(n:0)` avoiding the need for a -1. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes ``` I⮌ENX⁻θιι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyi1LLWoOFXDN7FAwzOvoLTErzQ3KbVIQ1NHISC/HMjwzcwrLdYo1FHI1ARhELD@/9/0v25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input as a number E Map over implicit range ι Current value ⁻ Subtracted from θ First input X Raised to power ι Current value ⮌ Reverse list I Cast to string Implicitly print on separate lines ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 55 bytes ``` v=>Enumerable.Range(0,v--).Select(i=>Math.Pow(i+1,v--)) ``` [Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpds45lXYmyko@Dpmleam1qUmJSTauOSXwqk7OwU0oAKFGwV/pfZ2iGk9YIS89JTNQx0ynR1NfWCU3NSk0s0Mm3tfBNLMvQC8ss1MrUNwXKa/625uMKLMktSfTLzUjUUgkuKMvPS9bzyM/M0FJR0QAhkgYaCqYImCFr/BwA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-n`, 21 bytes ``` say++$\**--$_ while$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJbWyVGS0tXVyVeoTwjMydVJf7/f9N/@QUlmfl5xf91fU31DAwN/uvmAQA "Perl 5 – Try It Online") ]
[Question] [ # Challenge Your task is to encode an integer as a string of [ASCII](https://codegolf.meta.stackexchange.com/a/5869/82619) characters, then successfully decode it after said string has been randomly shuffled. You will write two [programs/functions](https://codegolf.meta.stackexchange.com/q/2419/82619), which will be referred to as *Encoder* and *Decoder*. ### *Encoder* * **Input:** an integer \$n\$ in the range \$[0,2^{31}-1]\$. * **Output:** a string \$s\$ of [ASCII](https://codegolf.meta.stackexchange.com/a/5869/82619) characters (not necessarily printable). ### *Decoder* * **Input:** a random permutation \$s'\$ of the string \$s\$. * **Output:** the integer \$n\$. # Scoring Let \$A\$ be the **maximum length** of \$s\$ across all possible values of \$n\$. If the *Encoder* acts non-deterministically (which is allowed, see below), then the \$A\$ will be the maximum length of \$s\$ that may occur (possibly \$\infty\$). Let \$L\_E\$ be the **length of the *Encoder*** in bytes and \$L\_D\$ the **length of the *Decoder*** in bytes. Then your score is \$A\cdot(L\_E+L\_D)\$. Victory is awarded to the submission the **lowest score**. # Time limit There is a somewhat arbitrary **time limit of 1 minute** on the execution time of both the *Encoder* and the *Decoder* for a single testcase (i.e. a single value of \$n\$). The goal is to avoid solution that find that brute-force the encoding by enumerating all sequences with certain properties. If your solution does something more clever than that, it will most likely fit the time constraint and will be considered valid. Likewise, if it works on [TIO](https://tio.run/#) for some randomly selected values of \$n\$ it will be considered valid. Otherwise I will test it on my machine, but note that if your solution is pure brute-force it will almost certainly fail. # Rules * The *Encoder* and the *Decoder* must be written in the **same language**. * The *Decoder* must output the **correct** integer \$n\$ for every possible permutation \$s'\$ of the string \$s\$ returned by the *Encoder*. * The *Encoder* and the *Decoder* are **not** allowed to **share information** in any way (e.g. by means of global variables or files). * The output of the *Encoder* need **not** be **deterministic** (that is, the same input \$n\$ may produce different output strings if the *Encoder* is run multiple times), but the *Decoder* must always guess the correct integer \$n\$. * The *Encoder* and the *Decoder* may take and return the integer \$n\$ in **any convenient way** (e.g. if \$n=14\$ it is fine for the input to be `14`, `"14"` or `[1,4]`). * The *Encoder* may output the string \$s\$ either by **printing** it on `stdout` **or** by **returning** a string, a list/array of characters or a list/array of integers in the range \$[0,127]\$; note that the *Decoder* will receive as input a permutation of \$s\$ as returned by the *Encoder*, so it should accept the string \$s'\$ in the **same format** as \$s\$. * [**Standard loopholes**](https://codegolf.meta.stackexchange.com/q/1061/82619) are forbidden. * If possible, **explain** how your code works and why the score you claim is correct. # Example > > Assume \$n=14\$. > > > * The *Encoder* receives `14` as input. It may output `"qwerty"`. > * The *Decoder* receives a permutation of `"qwerty"` as input, for instance `"tweyqr"`. It must output `14` (in any convenient format). > > > The *Encoder* could have returned `[113,119,101,114,116,121]` as well, in which case the *Decoder* would have received (for instance) `[116,119,101,121,113,114]`. Note that the string returned by the *Encoder* may also include non-printable ASCII characters (but always in the range `[0x00, ..., 0x7F]`). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), (17 bytes + 18 bytes) × length 6 = 210 points ``` b36µỤỤ+×3µŒ¿b3U+Ṣ ``` ``` Ṣ:3_J Ṣ%3Uḅ3œ?Çḅ36 ``` [Try it online!](https://tio.run/##y0rNyan8/z/J2OzQ1oe7lwCR9uHpxoe2Hp10aH@Scaj2w52LuLiAhJVxvBeIVjUOfbij1fjoZPvD7SCG2X/DI/sf7mx5uKsLSJoc2f//v7GhkZmlpaGZOQA "Jelly – Try It Online") [(or with extra debug info)](https://tio.run/##y0rNyan8/z/J2OzhzpZDWx/uXgJCO1u0geydLYenG4OFj046tB/ISALxQrUf7lzExQUkrIzjvYACIKaqcSiQ9XBHK0jF0cn2h9uhXLP/hkdAWh/u6gKSJkf2//9vbGhkZmlpaGYOAA "Jelly – Try It Online") Having had a go at solving this challenge aiming at the stated victory condition, I thought it'd be interesting to go for a hypothetical alternative victory condition: [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") given a minimum possible maximum length for the output. ## Explanation ### Encoding The first step in the encoding is to represent the input as base 36 (`b36`). 366 = 2176782336 > 2147483647, so there will be at most 6 digits in the result, each of which is in the range 0–35. Next, we transform this into a representation that contains 6 *different* digits. There are multiple possible algorithms for this, but the one used here is to add 1 to the smallest digit, 2 to the second-smallest, 3 to the third-smallest, and so on. This means that if two digits were the same, one of them will be arbitrarily considered smaller, and thus they'll become different; and obviously, this algorithm can't cause two different digits to become the same. In order to represent this in Jelly, we use `Ụ` ("sort indexes by values") to get a list of the indexes in sorted order; `Ụ` again to invert that, effectively mapping each element of the original to its position in sorted order; and `µ…+` to add the original to the new list. The result is a representation of the input number as six *different* digits in the 1–41 range (minimum 0+1, maximum 35+6). We then split this into yet another form: a *sorted* list of digits in the 1–41 range, alongside a number from 1 to 720 that represents which of the 720 possible permutations the digits were in. (The `Œ¿` and `Ṣ` extract the permutation number and sorted list respectively.) Finally, we convert the number from 1 to 720 into base 3 (`b3`), reverse it (`U`), and encode the six base 3 digits and six 1–41 digits via packing them each into a single ASCII character using reverse divmod (the value of the character mod 3 is the base 3 digit, the value divided by 3 is the 1–41 digit). The possible range of results is (1×3)+0=3 at minimum, and (41×3)+2=125 at maximum, fitting within our ASCII range. The packing is done via `×3` and `+`, together with an additional `µ` to make sure that every command operates on the right bit of data. (There's a bit of a golfing trick here, in that we do the multiplication by 3 *before* extracting the permutation; that saves the need to spend a byte on a grouping character.) Incidentally, the reason to reverse the base 3 number is because it may have fewer digits than the 1–41 number. (It can't have more; the smallest number for which *n*! > 3*n* is slightly above 6.) Jelly effectively inserts trailing zeros when adding together two numbers of different lengths, in order to make them match up; trailing zeroes would affect the interpretation of the number, but *leading* zeroes wouldn't, so the reverse is used to ensure that the extra zeroes end up somewhere that won't mess up our answer. ### Decoding The first step in decoding is to extract the two numbers (the base 3 number and the 1–41 number). We can get their digits easily enough with division (`:3`) and modulo (`%3`) respectively, but how to know which order they were in? Well, the 1–41 number had its digits in sorted order, and digits in corresponding positions of the two numbers were stored in the same characters; thus, we can work out which order the 1–41 number's digits were shuffled into (by looking at their relative values) and know that the base-3 number's digits must have been shuffled the same way. In fact, because characters of our ASCII encoding sort the same way as the 1–41 number's digits (these were all distinct and they're more significant than the base 3 number's), we can simply put the characters of the encoding back into order with a sort `Ṣ`. So both extractions start with `Ṣ`, followed by `%3` or `:3` as appropriate. While the 1–41 number's digits are still in sorted order, we have a very convenient/terse way to go back to the 0–35 digits of base 36; just subtract 1 from the first, 2 from the second, 3 from the third, and so on. In Jelly, we can do that with `_J` ("subtract index"). Meanwhile, in the other branch of the decode, we reverse the base 3 number's digits back into order (`U`), and convert it from base 3 back into a permutation index with `ḅ3`. We can then combine the two branches with `œ?Ç`; `œ?` means "permute given this permutation index", and `Ç` means "the result of applying the line above", i.e. it's what tells Jelly to run both lines separately on the same input. What we have now is the digits of the original number, in base 36 (due to the `_J`), and in the original order (due to the `œ?`), so we can simply do a `ḅ36` to convert back from base 36 into a single integer. ## Commentary The TIO! link above uses 312699167 as the number to encode. This number in base 36 is `[5, 6, 6, 8, 7, 35]`, and thus shows off all aspects of the encoding: the 35 tests the limit of the 0–127 range we have; the duplicate 6s test the resolution of identical digits in the original base 36; and the fact that the digits are almost (but not quite) sorted means that the permutation number is very small, giving it many fewer digits than the base 36 number, and thus showing the need to reverse it before adding it to the original. It's really convenient how all the constants here fit together. 366 is only *just* high enough to fit 231, 36 is only *just* high enough to fit 6!, and (36+6)×3 is only *just* high enough to fit within the 128 possibilities we have. (The last constraint here is the least tight, because we could use 0-indexing rather than 1-indexing to make use of characters in the 0-2 range. Still, that'd only give enough room to use 37 as the base rather than 36.) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), (~~4~~ 3 bytes + ~~6~~ 5 bytes) × length 8 = ~~80~~ 64 points ``` b⁴Ä ``` ``` ṢŻIḅ⁴ ``` [Try it online!](https://tio.run/##y0rNyan8/z/pUeOWwy1cD3cuOrrb8@GOViD3v@GR/Q93tjzc1QUkjY7s///fyNDE3MTC2MzEHAA "Jelly – Try It Online") # [Jelly](https://github.com/DennisMitchell/jelly), (~~2~~ 1 byte + ~~4~~ 3 bytes) × length 10 = ~~60~~ 40 points ``` Ä ``` ``` ṢŻI ``` [Try it online!](https://tio.run/##y0rNyan8//9wC9fDnYuO7vb8b3hk/8OdLQ93dQFJoyP7//@PNtIx1DHRMQdiCx1jHTMQOxYA "Jelly – Try It Online") ## Explanation ### Solution 1 This is using a different algorithm from most of the other answers. We start by encoding the value in hexadecimal (`b⁴`), as with the other answers, then take a cumulative sum (`Ä`). Each input will clearly give a different output (as both these operations are reversible), and given that the hexadecimal encoding will contain at most 8 digits whose maximums are 7 (for the 8th-last digit) and 15 (for the last to 7th-last digits), the maximum number in the output list will be 7+(7×15) = 112, less than the 127 required by the question. Additionally, the output will necessarily be in sorted order, allowing us to reverse the shuffle. For the decoder, we first reverse the shuffle with a sort (`Ṣ`); then reverse the cumulative sum, by prepending a zero (`Ż`) and taking the difference of consecutive pairs (`I`); then convert back from hexadecimal (`ḅ⁴`). ### Solution 2 The question actually allows us to take the input as a list of (presumably decimal) digits, so we can "cheat" by simply removing the base conversion; the maximum number used in the output will then be 2 + (9×9) = 83 (actually 82 because 2999999999 is out of range, so the worst possible input is 1999999999). The resulting encoding is pretty terrible as encodings for this problem go, but it has the advantage of being very terse to generate, which outweighs the verbosity of the encoding. This answer feels so much like cheating that it's not my primary solution for this problem, but it seems like it's worth adding because it technically complies with the rules and produces a better score. ## Commentary I have some algorithms in mind for getting below length 8, but it seems unlikely you could implement a length-7 algorithm in ≤9 bytes (non-cheating) or ≤5 bytes (cheating), so by the scoring in the question, this is likely the best way to do it. (I might have a go at a solution for the alternative "minimize the length of the encoding" challenge anyway, though, just for fun.) Unlike some of the solutions, the use of 16 as the base here isn't critical; there are plenty of other numbers that would work for a length 8 solution (e.g. 18). I picked 16 for the first solution simply because Jelly has a 1-byte way to represent that, and other viable bases would need to use up multiple bytes from the program. Of course, the second solution needs to use 10 as the base in order to exploit the loophole. Thanks to @Dennis for pointing out some newer Jelly commands that made this algorithm even terser to write. [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 10 \* (264 + 494) = ~~8650 7910~~ 7580 ### Encoder: 264 bytes ``` ,.Ajax,.Ford,.Act I:.Scene I:.[Exeunt][Enter Ajax and Ford]Ajax:Open mind.Be you nicer zero?You be the sum ofyou the product ofthe sum ofI a big big pig the sum ofa big big big big cat a big big pig.If soSpeak thy.Ford:You are the sum ofyou a cat.If soLet usAct I. ``` [Try it online!](https://tio.run/##XY/NCsIwEIRfZR@gBMRitRdRUCgIHnqS0kOabLVqk5AfaH35mFSk6GFgZ@dbhjXq6X1Cdnc6JOQoNQ8zs1DkpGQoMA7VYUAnbF0dhEUNEQUqOES6ji4/KxTQd4KTPcIoHYiOBfKFWm4vwTYI9oZgXA@yjXl0SkvuQpVs56wACk13naSC5mTef8Wo/aVJ0YKRpUL6CIfj9E0e66n@76fx@sOf0IIz08/E@8UmzdL1cpVmbw "Shakespeare Programming Language – Try It Online") ### Decoder: 494 ``` ,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Exeunt][Enter Ajax and Ford]Ajax:Open mind.Is you nicer a pig?If soRemember you.If soLet usAct I.Scene V:.Ford:Remember I.Ajax:Recall.Is you worse the sum ofPage twice the sum ofa big big cat a cat?If soYou be the difference betweenyou Page.If soOpen heart.If notlet usScene V.Scene X:.Ford:Recall.Ajax:Be I nicer zero?If soRemember I.If soLet usScene X.[Exit Ajax][Enter Page]Ford:You be the sum ofyou twice twice the sum ofa big big cat a pig.Let usAct I. ``` [Try it online!](https://tio.run/##hZBBS8RADIXxR3jzkLtlTp6KIAorFAVFQdRlD9M27Y60M2Umpat/vibT2aV48dDSpMnL914YunnO1O2XPmTq3vk6U8@6Re5UBEWuXiu0KB/bzQFHS7vtxhJ6kAXQtgbZ2UmVPw1ooTe2VkWAbzeCNRVPahhMe1M0ENwL9tiX3OO/KnYekWAM8VY69ZZHjPw0W0Q4rivddUfpyfmAQHuEMPbgGmEGmvjgqqmhNG18Kk3Mwe@F44MVymWyNk2DHi0vlkgTohV5kVsAo6k9ak9SW0ddJE6sifn9xBwZI@8dp5YS@EHv/gRQrO0nEYnYUEz2mLJw7KL0CnkxJ5jJ8D@2OX61znmez84vLq@uHz7r8As "Shakespeare Programming Language – Try It Online") This was a thing. The encoder encodes each digit as the digit plus the index of the digit times twelve. The decoder stores all the input in the Ford's memory and then loops over a counter, outputting then deleting each digit lower than the counter\*12 + 10. ## Explanation: ### Encoder ``` ,.Ajax,.Ford,.Act I:.Scene I:. Boilerplate introducing the two characters [Exeunt][Enter Ajax and Ford] Enter the two characters Ajax and Ford Ford will be handling the input Ajax will be the counter Ajax:Open mind. Set Ford to the next character of input Be you nicer zero? Check if it is EOF You be the sum of Set Ford to the sum of you His original value (48 to 58) the product of the sum of I Ajax's value a big big pig Minus 4 (this handles the offset of 48) the sum of Multiplied by a big big big big cat 2^4 a big big pig. + -2^2 = 12 This essentially sets Ford to (F+12*(A-4)) If soSpeak thy. If not EOF, print Ford's value Ford:You are the sum ofyou a cat. Increment Ajax's value If soLet usAct I. If not EOF, Repeat again. ``` ### Decoder ``` ,.Ajax,.Ford,.Page,.Act I:.Scene I:. Boilerplate introducing three characters Ajax is the spare stack Ford is the storage stack Puck is the counter, increasing by 12 [Exeunt][Enter Ajax and Ford] Enter Ajax and Ford onto the stage Ajax:Open mind. Get the next character of input Is you nicer a pig? If not EOF If soRemember you. Store the value in Ford's memory If soLet usAct I. And repeat the loop Scene V:. Otherwise move to the next scene Ford:Remember I. Store Ford's value (initially -1 from EOF) in Ajax's memory Ajax:Recall. Get the next value from Ford's memory Is you worse the sum of Is the value smaller than Puck Puck's value twice the sum ofa big big cat a cat? + 10 ? i.e. is it the next digit? If soYou be the difference betweenyou Puck. If so, subtract Puck's value from Ford If soOpen heart. And print Ford's value If notlet usScene V. If that was not the digit, repeat Scene X:. Ford:Recall. Get the next value from Ajax's memory Ajax:Be I nicer zero? Until the -1 If soRemember I. Returning the values to Ford's memory If soLet us Scene X. Repeat until Ajax's memory is exhausted [Exit Ajax][Enter Page] Swap Ajax and Page Ford:You be the sum of Set Puck's value to you Puck + twice twice the sum of 2*2*( a big big cat 4 a pig. -1) = 12 Let usAct I. And start from the beginning again, having removed one number ``` [Answer] # Python 2.7, 31 \* (52 + 37) = 2759 **Encoder (~~69~~ 52 bytes):** ``` lambda n:[chr(i)if n&(1<<i)else""for i in range(32)] ``` **Decoder (~~41~~ 37 bytes):** ``` lambda s:sum([1<<(ord(c))for c in s]) ``` Stores the all the non-zero bits in the input number as ascii values. The value of the ascii character stores the position of the set bit. For example the value 'a' would mean that the 97th bit is set. A few improvements, thanks to @Delfad0r [Try it online!](https://tio.run/##RY9LbsMwDET3OgXhRUMCQdHIKFIYSS8SZOFaVK1CogzKXrSXd@SmnxWH5JsBOX3OYxa7rl5zAu3F1RLSlHWG0qcpsnHsoYyL95G/sFAHyvOiArvd40cOgncMyz5ybYjIGIYzxD69uR6ka5o7dxlGxUDBozzg4XQK9PpEHAs3jc8KAYJsB7wzHuyRrmTcf0rpypLwUl2Y1eFAtFmGzVIqaaSitrXt87G1L2bSIDMK/Qiu8lc7/Hvle1wX63oD "Python 2 – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), score 8 × (10+9) = 152 ### Encoder, 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç·MÉJ'♀τ│½ ``` [Run and debug it](https://staxlang.xyz/#p=80fa4d904a270ce7b3ab&i=16%0A2147483647%0A1823792&a=1&m=2) ``` 16|E{i16*+m Full program, implicit input 16|E Get hexadecimal digits { m Map: i16*+ Add 16 * loop index Implicit output as string ``` The encoder outputs the string in an increasing order. ### Decoder, 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` üL∟n╫k∞‼9 ``` [Run and debug it](https://staxlang.xyz/#p=814c1c6ed76bec1339&i=%01%10%0A%0A%10%01%0A%0A%07%1F%2F%3FO_o%7F%0A%0A_%3F%7F%1F%2FoO%07%0A%0A%3F%07o%1FO%2F_%7F%0A%0A%01%1B-4CP%0A%0A-C%01P4%1B&m=1) ``` o{16%m16|E Full program, implicit input o Sort string {16%m Module each element by 16 16|E Interpret as array of hex digits ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 maximum length \* (8 + 7) bytes = 120 ### Encoder (8) ``` hεHN16*+ ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/49xWDz9DMy3t//@NDE3MTSyMzUzMAQ "05AB1E – Try It Online") ### Decoder (7) ``` {16%hJH ``` [Try it online!](https://tio.run/##yy9OTMpM/f@/2tBMNcPL4///aHMdBWNDHQUTIG1mrKNgbqmjYGmqo2BoCBQ0NDKPBQA "05AB1E – Try It Online") Uses the same technique as [wastl](https://codegolf.stackexchange.com/a/172696/59487) and [Jonathan](https://codegolf.stackexchange.com/a/172697/59487). [Answer] # [Python 3](https://docs.python.org/3/), 8 \* (45 + 38) = 664 ### Encoder (45 bytes): ``` lambda n:[16*i+(n>>4*i)%16 for i in range(8)] ``` ### Decoder (38 bytes): ``` lambda l:sum(x%16<<x//16*4 for x in l) ``` [Try it online!](https://tio.run/##VY3djoIwEEbv@xRzY2wRfyqVdYlypU9hvCgC2oQOpELCZrPPzhaLqDdzzmS@yVf91LcSg6477gupk1QCRiceempGMY6Fp9iEh5CXBhQoBCPxmtEtO5PDM19E90bT1sZ2u3a5tL/ikW/7fME6pavS1P1nWmpC0iwH0yBFFhEACXs4WreaWJWn6GzVZRf3W5PnRUaT/nyx54PTyiis6fT3D@YxfM7pwlZrWVP0QfqQ@HBhjJC@cMUe4A5rh/DJYKAYuBkYOorVtxhtM9rr@jXadijwvIDPg/dl/b5w1v0D "Python 3 – Try It Online") [Answer] # JavaScript (ES6), 8 \* (40 + 32) = 576 The encoder outputs an array of \$0\$ to \$8\$ integers. The decoder takes the same format as input. ## Encoder (40 bytes) ``` E=(n,k=0)=>n?[k|n&15,...E(n>>4,k+16)]:[] ``` ## Decoder (32 bytes) ``` s=>s.map(c=>s|=c%16<<(c/4&~3))|s ``` ## Demo [Try it online!](https://tio.run/##dU@xTsMwEN39FbfQ@prE1E1bJKjN0ixIhIGxqpBJQxqS2lVsIVUEfj04oTAgsdx7757u3t2relM2a8qji7TZ5V2XCKrDSkxRSH27qVo94ouQMZZQLeU8rAK@xO31ZkvIWhArpGUHdaSZJ63ILvhytaLZ5Xz0GSO2tnO5dSAgBSHhnQA0ufUyoSneeJUZbU2ds9oUNIUAxhBF0tcA7h4fUmZdU@qifDlRP4aDT3vTK1bnunD7ofd88ik4xt/1vW9N4@hTH3uv3J41Su/MgSJEwBb4J/q/sJ9j1kMLyQch/T90it94dUY@i89sNpnEPOLYfQE "JavaScript (Node.js) – Try It Online") ## How? The input is divided into 8 blocks of 4 bits and each block is encoded with 1 among 16 possible characters. The most significant bit of the last block is never set. ``` 3222222222211111111110000000000 bit: 0987654321098765432109876543210 \_/\__/\__/\__/\__/\__/\__/\__/ block: 7 6 5 4 3 2 1 0 block #0 is encoded with char. 00 to 0F (NUL to SI) block #1 is encoded with char. 10 to 1F (DLE to ES) block #2 is encoded with char. 20 to 2F (' ' to '/') block #3 is encoded with char. 30 to 3F ('0' to '?') block #4 is encoded with char. 40 to 4F ('@' to 'O') block #5 is encoded with char. 50 to 5F ('P' to '_') block #6 is encoded with char. 60 to 6F ('`' to 'o') block #7 is encoded with char. 70 to 77 ('p' to 'w') ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), (8 + 9) [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) \* 8 max-length = 136 ``` b⁴+J’Ɗ⁴¡ ``` **[Encoder](https://tio.run/##y0rNyan8/z/pUeMWba9HDTOPdQFZhxb@P9x@dNLDnTP@/7e0MDczNTE2MgQA "Jelly – Try It Online")** (footer formats the list as Python would for clarity) ``` Ṣ_J‘Ɗ⁴¡ḅ⁴ ``` **[Decoder](https://tio.run/##y0rNyan8///hzkXxXo8aZhzretS45dDChztagfT///@jDQ3MdRSMzHQUTEx1FAwNjXUUgMjcQEfBzEhHwcIiFgA "Jelly – Try It Online")** It's theoretically possible to have a max-length of six, can that be done in 22 bytes or fewer? It's impossible with a max-length of five since \$\sum\_{i=0}^{i=5}\binom{127+i}{127}=321402081< 2^{31}-1\$ ### How? Since \$2^{31}-1\$ is encodable as 8 hexadecimal digits (`7fffffff` or `[7,15,15,15,15,15,15,15]`) we may then add the zero-based index of each hex-digit multiplied by 16 to ensure such a conversion is always in sorted order while keeping even the rightmost value in-bounds (i.e. `[7,15,15,15,15,15,15,15] + [0,16,32,48,64,80,96,112] = [7,31,47,63,79,95,111,127]`). Decoding is then reversing this same process. **Encoder**: ``` b⁴+J’Ɗ⁴¡ - Link: integer, n e.g. 1234 ⁴ - literal 16 16 b - convert to base [4,13,2] ¡ - repeat... ⁴ - ...16 times: Ɗ - last 3 links as a monad: J - range of length [1,2,3] iter 2 iter 3 ... iter 16 + - add [5,15,5] [5,16,7] [5,17,9] ... [5,30,35] ’ - decrement [4,14,4] [4,15,6] [4,16,8] ... [4,29,34] - [4,29,34] ``` **Decoder**: ``` Ṣ_J‘Ɗ⁴¡ḅ⁴ - Link: list of integers e.g. [29,34,4] Ṣ - sort [4,29,34] ¡ - repeat... ⁴ - ...16 times: Ɗ - last 3 links as a monad: J - range of length [1,2,3] _ - subtract [3,27,31] [3,26,29] [3,25,27] ... [3,12,1] ‘ - increment [4,28,32] [4,27,30] [4,26,28] ... [4,13,2] ⁴ - literal 16 16 ḅ - from base 1234 ``` [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 31 \* (472 + ~~383~~ ~~379~~ 344) = ~~26505~~ ~~26381~~ 25296 Previous score: 16909322 \* (246 + 217) = **7829016086** This is still very high, but it's the lowest I can think of right about now. Encoder: ``` ,.Ajax,.Ford,.Act I:.Scene I:.[Enter Ajax and Ford]Ajax:Remember a pig.Ford:Listen tothy.Scene V:.Ajax:Remember the remainder of the quotient betweenI a big cat.Ford:You be the quotient betweenyou a big cat.Be you nicer zero?If solet usScene V.Remember a pig.Scene X:.Ajax:Recall.Ford:Am I worse zero?If notremember I.If notlet usScene X.Ajax:You zero.Scene L:.Ford:Recall.Ajax:You be the sum ofyou a cat.Am I nicer zero?If sospeak thy.Am I worse zero?If notlet usScene L. ``` [Try it online!](https://tio.run/##bZDPbsIwDMZfxQ@AIrHtlAti0iZF6mmTJtDEIU0NhDVJSVwxePkuabKOIW7@8/nnzw5dOwwztjzI7xl7db6JsSIQnL0rtJiCzxdL6CFJQNoGkmqTMv6GBk0dexI6vRvHeaUDoQVytD8Xxgdn/@W0R/BopLZNzNx2LBx7RxotQY10QrQiUmu9AyUpk9euj7272nNs/amfEVLBahXpF/RuIbYQXIsEfSiW2I33XF5NTpVs27x2aUDAyfmAE8s68r/jguXCNX2VKclwGinwimdggU@SclPoTXxFviRdMe69vSF0KL8gvfa@rWsXFRuG@cPj0w8 "Shakespeare Programming Language – Try It Online") Decoder: ``` ,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Exeunt][Enter Ajax and Ford]Ajax:You cat.Ford:Open mind.Remember the sum ofyou I.Scene V:.Ajax:Am I nicer a cat?If soyou be twice you.Ford:If soyou be the sum ofyou a pig.If solet usScene V.[Exit Ford][Enter Page]Page:Recall.Ajax:Am I worse a cat?If notyou be the sum ofyou Ford.If notlet usAct I.Open heart ``` [Try it online!](https://tio.run/##bVBLCsIwEAVBFLzEHKDkANmIC4WulAqCSBcxHbXSJKWZ0nr6mkkLKrgJmbw37xNfV8OQiM1T9YnYuaZIxEHdMbxoglSKo0aLfLlse2wt5ZetJWyAF0DZAngn50meXQtaUVSR@xotmNIWIkOD5hpW6IHgWwPu9grMdJI@yWguNwZSsKUORMUy6/QG3jHzikBdACAMo/gP9KOqoC7vIuIVErR@MuH4JY1hpwZcM@dDZqhVVX3F6Fzj8RPDOvprxmpixEez@GciVn@gamgYlrPFav4G "Shakespeare Programming Language – Try It Online") Basically, if the string contains a character with the ASCII code (n+1), the nth binary digit is set. [Answer] # Python 3, (208 bytes + 200 bytes) \* 6 length = 2448 [Try it online!](https://tio.run/##nZHPbsIwDMbP7VP4RkpTIO0QCCmc2Bv0hjh0SroGBZc1raZd9urMLn/GruvBib/6c/xLzl9902JxuRhbw6tA2WiVr5NNHJXaV6c3UwFKs8FpKTBV0mQqmc8NuBrMVlkfLBio0ABC24GKI6O9XsRR0PtDHH02zlvArS5FIw03jTC7JbQ3qSZHTUYHDqGr8N2Ka9mzM/PSpN9u1G/@u8SKH7tEIdV7T2d2th86hBAz0E6E/6OEWWi7XtAhIxKRWaR@cYQ6DCdRCroouUt4/t3z/MkTU@ChOTv@Vnh5Z0n12CQ7jsOQ5LXje8mY6AaCF3c60xxsNu1pxCpt6AVyk2A/QPO7kfvcOSRZAomUhmaoH/@u5hlrtbeC14eDEwkWjZ7AhNR26Mm3@1tEYhI/sPYLCUpCTjFfcVhTsnzhsJSwLtbFGElQC/5oLdRiRfX5dFrkmTrwqzCFSy4/ "Python 3 – Try It Online") (contains both, the extra byte is the newline between them). -4 bytes (-24 score) by utilizing the empty list (which allowed more things to start at 0) ### Encoder (208 bytes) ``` def E(n,h=128): T=lambda n,d:n*T(n+1,d-1)//d if d>1else d and n or 1 d=l=0 s=[] while n>=T(h,d): n-=T(h,d) d+=1 for i in range(d): while n>=T(h-l,d+~i): n-=T(h-l,d+~i) l+=1 s+=[l] return s ``` ### Decoder (200 bytes) ``` def D(s): T=lambda n,d:n*T(n+1,d-1)//d if d>1else d and n or 1 s.sort() l=0 d=len(s) n=sum(T(128,D)for D in range(d)) for i in s: for j in range(l,i): n+=T(128-j,d-1) l=i d-=1 return n ``` Observations: * Shuffling can be losslessly reversed for strictly non-increasing (i.e. sorted) lists. * Strictly non-increasing numerical lists of the same length can be [totally ordered](https://en.wikipedia.org/wiki/Total_order) (as they are in Python). * We can define that lists are ordered by length first to form a total order of all sorted lists. * We can form an indexable sequence of these lists if we define that the only valid values in a list are integers from `0` to `127` inclusive (i.e. there exist a finite number of valid lists with length `L`). Strategy: * Encoder: Given a number `N`, find the `N`th valid strictly non-increasing list. * Decoder: Given a (shuffled) valid list, sort it and return its index in the sequence of valid lists. Common code explanation: * `T=lambda n,d:n*T(n+1,d-1)//d if d>1else d and n or 1` * Compute the `n`th [`d`-simplex number](https://en.wikipedia.org/wiki/Figurate_number#Triangular_numbers) + For `d=0`, always `1` + For `d=1`, `n` (the number of dots in a line of dots with length `n`) + For `d=2`, \$\sum\_{i=1}^{n} i\$, (the number of dots in a triangle of dots with side length `n`) + For `d=3`, \$\sum\_{j=1}^n \sum\_{i=1}^{j} i\$, (the number of dots in a tetrahedron of dots with side length `n`) Encoder explanation: * `def E(n,h=128):` `d=l=0`, `s=[]` * `n` is the input number, `h` is the "high value" (i.e. the highest number allowed + 1), `d` is the length the output will be, `s` is the output, `l` is the "low value" (starting at 0, explained more later) * `while n>=T(h,d):`, `n-=T(h,d)`, `d+=1` * There are `T(h,d)` valid length-`d` lists, and our calculation is easier if `n` is an index relative to the list `[0]*d` (at index `0`) instead of an actual index, so decrement `n` accordingly. This also adjusts `d` (the length) to be correct for the given `n`. * `for i in range(d):` * Effectively: "for the `i+1`th number in the list" + This is where I will explain `l`, the "low value" + After a number has been put into the list, no number less than it can be put in the list (to keep it sorted), so `l` is the last number that was added to the list. + `while n>=T(h-l,d+~i):`, `n-=T(h-l,d+~i)`, `i+=1` + If `n` is too big to be encoded with an `l` at this "digit", then adjust `n` accordingly and increment `l` + `s+=[l]` + Encode `n` with an `l` at this "digit". + At first, we have `h` options for what "digit" to put in next, but once we put in a "digit" (which is assigned to `l`), we are limited to `h-l` options for the next "digit". + At first there were `T(h,d)` valid lists, but we have added a "digit" `l`, decreasing the number of "digits" left to `d-1` and the number of valid next "digits" to `h-l`, so the number of valid lists after this is `T(h-l,d-1)` Decoder explanation: * `def D(s):`, `s.sort()`, `l=0`, `d=len(s)` * `s` is the (shuffled) input list, so `s.sort()` it; `l` is the "low value" (`h` the "high value" is just literal `128`s in the code to save bytes), `n` is the output number, `d` is the length. * `n=sum(T(128,D)for D in range(d))` * Adjust `n` to the point in the sequence of `[0]*length` * `for i in s:` * For each digit: + `for j in range(l,i):`, `n+=T(128-j,d-1)` + Adjust `n` to the point in the sequence of `[...prevdigits, thisdigit, 0...]` - `l=i`: Set the "low value" to the most recent digit - `d-=1`: Decrement the length since we used a digit * `return n`: After `n` has been adjusted for all of the digits, it is the right number; return it. Sorry if this isn't clear, but here's my original [nongolfed debug version Try it online!](https://tio.run/##jZTBjoIwEIbvPEUTPRQtKruXjdn6FN4IMZhWKcLAUozZp2cLaClQdcuFZqZ///k6bfFbxTl81nUszjH1P76cPU2j7MgiBIRtYbHHsPQJ83x3vWZInBDb@TyVHEE7Qe2/7zB@QnDNjrw8VPlB8h8M7tZB98Gor/8lDUI9SfMb3ejZLRapEt7RPW7sEGZIPAZ4fXQSZEtjo1NeIoEEoDKCM8c2sdGGnrKjShWq2GnuxICR/TRZpZiWNINVVBQcGFbxfnFRCqgwI5IAGQRKXl1LQLKlrNg2iDvYWBpO5UrmZYX7dWCwNY@gKzvloJbvmIXx8r@Mh@enicupZhNL@tNo2IlXlB8WvKRtPsdCloqpOc8wN@uAqj4mcgITau020LFFA5AzHIhw3D7qargusWSSJBwX1@Ta1jc3RnzTROnMLDrk0ildLErv1edPNEnaqaYWhXc7PdckWaeaWRRe7zTXDIMNuX/9gxBuR9dBkGHDC3d8YYbPziTbdeo/ "Python 3 – Try It Online"), which doesn't use the empty list, so is 1 off from all numbers used in this version [Answer] # [Ruby](https://www.ruby-lang.org/), (36+29 bytes)\*8, score 520 Encode: ``` ->n{(0..7).map{|x|(n>>x*=4)%16+x*4}} ``` [Try it online!](https://tio.run/##KypNqvyfZmj7X9cur1rDQE/PXFMvN7GguqaiRiPPzq5Cy9ZEU9XQTLtCy6S29n@BQpphtImlhbG5kWHsfwA "Ruby – Try It Online") Decode: ``` ->a{a.sum{|x|x%16<<(x/4&28)}} ``` [Try it online!](https://tio.run/##PYxNCoMwEIX3nsJNq6Yk7YyhWjC5iLiw0NCFisQGUjRnT0dou3jwfj6edfd3NKC4ntb8IkRViLGf181v@aS1Z0oWB7iePJMhJAZV5Lpfe7G4cWc8bU2T@7M8Yl2EEOfUgjLQyltdVghdQgUqC2J5OmOGx55LZbC1SJt7LWkmOOd/ZQQgYyVwIEccfX1z9/vo4gc "Ruby – Try It Online") ### How it works: The number is encoded using 4-bit chunks and a 3-bit index. Decoder takes the input array and puts every nibble into its place again. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), score 10 \* (10 + 15) = 250. Uses decimal; previous base 16-based solution scored ~~328~~ ~~296~~ 264. May output nonprintable characters. In particular, character 10 is tricky to input to Charcoal. Encoder, 10 bytes: ``` ⭆⮌S℅⁺Iι×χκ ``` [Try it online!](https://tio.run/##JYu7CoAwDAB/pWMKFezs6OQgiPoDoQQt1gdt7O/HqrccHJxbMboTg8gQ/cEwcdHS4wUjZYqJoDuum/8MWhvVlgMdU4Qh3AlaTAy@9NnvlMDWRm36oxGx9YtUOTw "Charcoal – Try It Online") Link is to verbose version of code. Decoder, 15 bytes: ``` IΣES×﹪℅ιχXχ÷℅ιχ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUDDM6@gtCS4BCiRrqGpoxCSmZtarOGbn1Kak6/hX5SSmZeYo5EJlDA0ABIB@eWpRRqGBjoKnnklLpllmSmp6IrAwPr/f@P/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Version using a list of integers scores ~~360~~ 296 (base 16; decimal would score 310): Encoder, 19 bytes: ``` NθIE⁸⁺﹪÷θX¹⁶ι¹⁶×¹⁶ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMM3sUDDQkchIKe0WMM3P6U0J1/DM6/EJbMsMyVVoxAokV8O1GRopqOQqampo2BoBiRCMnNTi2FiQGD9/7/Bf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Decoder, 18 bytes: ``` IΣEE⁸N×﹪ι¹⁶X¹⁶÷ι¹⁶ ``` [Try it online!](https://tio.run/##LYrLCsMgEEX38xWznICFmAaxdNluukgItD9gE6GCxmA0/XxjHxfO5pw7vlQYvbI5D8HMkS5qjXRPjjq1fJEMb/OSYp/cUweqKoYP4/RKnZ@S9WQYclHk4N8lc/G5x6vZzKT/7bdzzjUicIFwbBBaiSBaBFkjnIrjvMmHze4 "Charcoal – Try It Online") Link is to verbose version of code. Version using printable characters scores 360 (was ~~416~~ ~~384~~ 368 in base 16): Encoder, 19 bytes: ``` ⭆⮌S℅⁺Iι×χ⁺κ×⁵⊕׳÷κ⁵ ``` [Try it online!](https://tio.run/##PcvBCsIwEATQX8lxAxFapCeP9dKDUNQfWNJFF9NYkm1@P01adC4Djxn7xmC/6HIeA3uBh5R63XCBOyUKkWDwyyoHg9ZG9eWBVijA6NYIPUYBLv7kmSK0jVG7f37SGTV4G2gmLzTBgeeKcuXEE9Vpp/@55Nw2NfmU3AY "Charcoal – Try It Online") Link is to verbose version of code. Decoder, 17 bytes: ``` Fθ⊞υ⌈Φθ¬№υκ⭆υ﹪℅ιχ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBo1BTIaC0OEOjVEfBN7EiM7c0V8MtM6cktUijUEfBL79Ewzm/NK8EJJ2tCQLWXAFFmUCB4BIgle6bWADWmZ9SmpOv4V@UkpmXmKORqamjYGgAUvz/v5GNW0DU4d3/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 17+18 bytes \* 8 length = 280 ## Encoder: ``` ḃ₁₆I∧7⟧₁;Iz₁~ḃ₁₆ᵐ ``` ## Decoder: ``` ḃ₁₆I∧7⟧₁;Iz₁~ḃ₁₆ᵐp ``` A p can be added to the end of the encoder with no effect. The decoder is run by putting the (shuffled) result as the output and getting the original number in the input. If there would be a (properly implemented) cumulative sum predicate the score could drop down to 20 [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO5kdNjY@a2jwfdSw3fzR/OZBn7VkFJOvgUg@3Tij4/9/IAAb@RwEA "Brachylog – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: (2 + 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) \* 11 maximum length = 44 **Encoder (2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)):** ``` .¥ ``` [Try it online.](https://tio.run/##yy9OTMpM/f9f79DS//@jjXUMdEx0zHUsdIyALEMdy1gA) **Decoder (2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)):** ``` {¥ ``` [Try it online.](https://tio.run/##yy9OTMpM/f@/@tDS//@jDU10zHWMjHSMTHWMTHSMdQzAFBDFAgA) Input of the encoder and output of the decoder are a list of digits. Port of [*@ais523*'s 2nd Jelly answer](https://codegolf.stackexchange.com/a/172706/52210). **Explanation:** ``` .¥ # Undelta (automatically prepends a 0) # i.e. [3,0,4,7,8,2,0,1,9] → [0,3,3,7,14,22,24,24,25,34] { # Sort # i.e. [14,7,22,25,24,3,0,24,34,3] → [0,3,3,7,14,22,24,24,25,34] ¥ # Deltas # i.e. [0,3,3,7,14,22,24,24,25,34] → [3,0,4,7,8,2,0,1,9] ``` Because `.¥` prepends a zero to the output, the length of the output is the length of the input + 1. Since \$2^{31}-1\$ has a length of 10 digits, the maximum length of the output is 11. [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 8 \* (14 + 13) = 216 Encoder [Try it online!](https://tio.run/##S8/PScsszvj/39PCLS0g2MVCy0c7v8b6//9HDWuByNDI2MTUzNzC0gAA "Gol><> – Try It Online"), 14 bytes: ``` I8FfPSD8*L+o|; ``` Decoder [Try it online!](https://tio.run/##S8/PScsszvj/P9M1wyLYxUTLSCVCS/v/f4FMIT9mE191AA "Gol><> – Try It Online"), 13 bytes: ``` iEh8SD4*2$X*+ ``` Since this can output unprintable ascii characters, thus messing with the decoder, there is now a version using numbers in the output / input: Encoder [Try it online!](https://tio.run/##S8/PScsszvj/39PCLS0g2MVCy0fbr8b6//9HDWuByNDI2MTUzBwA "Gol><> – Try It Online"), 14 bytes: ``` I8FfPSD8*L+N|; ``` Decoder [Try it online!](https://tio.run/##S8/PScsszvj/P9M1wyLYxUTLSCVCS/v/f4FMIT9mE191AA "Gol><> – Try It Online"), 13 bytes: ``` IEh8SD4*2$X*+ ``` ## Encoding: The encoding works by breaking the given number into 8 x 4bit chunks. These chunks are then shifted right by 3 bit and the original location of the chunk is appended on the end as a number between 0 and 7. Thus the encoding looks like this: ``` 0AAAABBB |__| -> the original part of the number |_| -> the position of the chunk inside the original number 0 = LSB and 7 = MSB ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 10 \* (10 + 12) = ~~340~~ 220 Encoder: ``` {^@_ Z~@_} ``` Decoder: ``` {.sort X%10} ``` [Try it online!](https://tio.run/##K0gtyjH7n1up4JBo@786ziFeIarOIb5Wh6tarzi/qEQhQtXQoBYkr5aqYAtUFG0Qa80F4qZAuIYQrkoekJuTmZdaDFOgUgEUSdVQydNLzs9N0rTmKk4ECVpzgSVUKvQKMpOzNbSQJEB0ioZKhab1fyNDE3MTC2MzE3MA) The encoder function zips each digit with the 0-index of the number. Then the encoder sorts the list of numbers and gets the modulo by 10, in other words the second digit of the number. The total is 10, since that's the maximum length of 231-1. [Answer] # [Haskell](https://www.haskell.org/), 10\*(23+51) = 740 Here's a program that encodes, shuffles, decodes and validates values: [Try it online!](https://tio.run/##ZVPBjtowEL3nK0YIqUkBQ1rUbREgrXZVCQmEtBx6oGjXwgMxBDuyDez25@k4DqGouTiZN2@e38wk43aPeX6Rh0IbB09aOaNzNtOKi6gKPnPH2aMx/INN5nfBqbTuGlh8WIcH9sKV0Ico6nTA8T0q2Bh9gMy5wg663bPcS5YFTabNthvSX2123GxyjKoTBgNY8hV0xjCZ@7caeLcwAqEjqB5uYNgBhefyfqAoocY22sxgmTKmVtCE39KX@4fqn51nm/IOL6QUy7ZK7hJOssxALoIA6cn7hN1/Cbu7hLORDm8YVbyDDbqjUVSGoucMDZaoIpc5qq3LroZqi9SaiXLey61D8WQeQI/w5J6gQtN8wM8rBOOUnBJwQbUm8I8sfkmXxXErYXHa@5wkyx5jq0igRw@8AKsEszTnOU3UOkah@E3I00yLt7SXXA5cqpA5e4WtBgYOrSPd4RC26PxeoaLvYJEuWMEQL3vttP2jndKRttP@ClqthOhe03eVXnOp0HoO1VWfbvOnFaO6J6TlcxnCiedHBKdBUmEht/6gyQI51AIpWpJydGV3q9rF0SAMm2OwmT5T9Xo2SDm@Nyq6ai2qFfRaoaYImmWCRb8H1zXFmvWMpbonVaCAhnVGqm2jvpDwpqjV9sZ7ynC9B7mBM8KGS0/zZgoiBrv0txVhNainCmIB3RHQTJvkyS2cgcbPx8l0AEElxKaKLFMBNGuec4fQ8AvUIM6y8t8OjcDqtPQiYDwelZ@rS1o/0Ze0/9D//vVb/@Ev "Haskell – Try It Online") ## Encoder, 23 bytes ``` zipWith((+).(10*))[0..] ``` [Try it online!](https://tio.run/##JYwxDsIwDAD3vsJjAiIqiLVdygO6gQQMVjBNRJJGjll4PKHAdiedzmF5UAjVxzyzwAEFzeCQQYF1DLppKFno4FJfPh@9OKXW2qhtu9L63BpzrRF9WoKJZJiTUJICfd9BZp8EDETMv5OB7@jviglvC@cnk6773dveA06lbk7DOH4A "Haskell – Try It Online") ## Decoder, 51 bytes ``` map snd.sortOn fst.map(`divMod`10) import Data.List ``` [Try it online!](https://tio.run/##TY6xCsIwGAb3PsWHLoliqGuhLtVBUHRwcOjQ0CQ1mCYl@fHxje3megfHvWR6a@fyWmljvYbSPdo8ygnJK5FCpJuHSSRmxDplP9egun3JCztOs8RRkhQXmyj/g@YlIxhCVOBFMUrrUWPQ1ARP2lPC4VBjitYTBExwyoGxLRdsX244BytRVTh74rNejgSWoyUnELVUedWebo/WrL69cXJIefds7vcf "Haskell – Try It Online") ### Explanation Since we're allowed to use input as decimal digits, we'll use that.. The encoder maps each digit that occurs to `10*index + digit`, note that all `digit`s will be in `[0..9]` so we can reverse the above by using `divMod`. After restoring the indices and the digits it's only a matter of sorting by the indices and getting rid of them. The solution is expected to work for values up to \$2^{31} - 1 = 2147483647\$ which is 10 digits long, so the maximum code-point we get will be \$9 \cdot 9 = 81 < 128\$. Also each digit will be converted to a "character", so we'll end up with a maximal length of 10. [Answer] # [Husk](https://github.com/barbuz/Husk), 10\*(7+8) = 150 Straight port of my Haskell solution only with the observation that \$10 \cdot 9 = 90 < 128\$ (Husk's `N` is 1-based): ## Encoder, 7 bytes ``` zo+*10N ``` [Try it online!](https://tio.run/##yygtzv7/vypfW8vQwO/////RpjomOkaxAA "Husk – Try It Online") ## Decoder, 8 bytes ``` m→Ö←m‰10 ``` [Try it online!](https://tio.run/##yygtzv7/P/dR26TD0x61Tch91LDB0OD////RhqY6xkY6RiaxAA "Husk – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), \$L\_E+L\_D=36; A=8 \rightarrow 288\$. ``` d←{16⊥n-16×⍳≢n←⍵[⍋⍵]} e←(⊢+16×⍳∘≢)16⊥⍣¯1⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/1OAZLWh2aOupXm6hmaHpz/q3fyoc1EeUPRR79boR73dQCq2lisVKKDxqGuRNkxNxwygMk2wxke9iw@tNwRK/v@fqmBoZGzClaJgomBkqQBmAWkTCMvYBCwMljUGsQA "APL (Dyalog Unicode) – Try It Online") (contains 5 extra bytes for the assignments and the newline). Uses `⎕IO←0` ### How: ``` (⊢+16×⍳∘≢)16⊥⍣¯1⊢ ⍝ Encoder; input 1234 16⊥⍣¯1⊢ ⍝ Convert input to base 16 → 4 13 2 ⍳∘≢ ⍝ [0..length of the list-1] → 0 1 2 16× ⍝ times 16 → 0 16 32 ⊢+ ⍝ plus the original list → 4 29 34 ``` --- ``` {16⊥n-16×⍳≢n←⍵[⍋⍵]} ⍝ Decoder; input ⍵ → 34 4 29 [⍋⍵] ⍝ Grade ⍵ up → 2 0 1 ⍵ ⍝ Index ⍵ with that list → 4 29 34 n← ⍝ assign that to n 16×⍳≢ ⍝ 16×[0..length(n)-1] → 0 16 32 n- ⍝ subtract that from n → 4 13 2 16⊥ ⍝ Decode from base 16 → 1234 ``` [Answer] # PHP, 8\*(44+53) = 776 ## encoder, 44 bytes: ``` for(;$n=&$argn;$n>>=4)echo$n&15|16*$i++," "; ``` prints space separated list of integers. Run as pipe with `-nR`. maximum 8 bytes with 4 data bits (lower nibble) and 3 weight bits (upper nibble). Simply put: Put each hex digit in an own character and use the upper half of the byte to store the digit´s position. ## example: `1457893891` (`0x56e5b203`) will turn into `0x03`, `0x10`, `0x22`, `0x3b`, `0x45`, `0x5e`, `0x66`, `0x75` → `3 16 34 59 69 94 102 117` ## decoder, 53 bytes: ``` while($i++<8)$n+=(15&$x=$argv[$i])<<($x>>4)*4;echo$n; ``` or ``` while($i++<8)$n+=(15&$x=$argv[$i])<<($x/4&~3);echo$n; ``` or ``` for(;$i<9;$x=$argv[++$i])$n+=$x%16<<($x/4&~3);echo$n; ``` take integers from command line arguments. Run with `-nr`. --- [Try them online](http://sandbox.onlinephpfunctions.com/code/d2366ed2c91a18dc9531ec1893193b048f65a0b7). [Answer] # [Python 2](https://docs.python.org/2/), 10\*(68+54) = 1220 ``` e=lambda n:"".join(chr(int(`i`+j))for i,j in enumerate(`n`)if j<'L') d=lambda s:int("".join(`ord(c)%10`for c in sorted(s))) ``` [Try it online!](https://tio.run/##NZDLbsMgEEX3fMUoVWVIkZXHzmq2XfUjIPZQY9kDgvHCX5@C7LBBiHvOcIkbj4FuL7/EkBiSpSEsQnzAiHPEBG6lnn2gFn5CAsbMnv40UGCItgDBwXNj7MNK3BYsj6tzM2awkDmV7KGct1YM6N73MqtOQFkJeU0ETdNOwZPcw222S6whPSOVqFIvfMx2eQ4WqDud9mw/JumJpfHma1LKlfd5PYEnQFoXTJZRGjLKO5i@m99GieEtyV0F3yIT0iB79Xm9mCrpqyKX38Bhn03wOFq0davoRd/O5/tVCRFLSQbSgJKUhoIcDeu5wP8 "Python 2 – Try It Online") EDIT: Thanks to Jo King for the pointers - not sure why I was offsetting by 32, in retrospect. Encodes the position and value of each place as a single character, starting with ~~[space] (position 0, value 0)~~ the NUL byte 0x0. Decodes by: * sorting the string (Python will sort characters by their ordinal value) * converts each character into its ordinal value * takes the last digit of each ordinal integer * joins the integers into a string * converts the joined string back into an int [Answer] # [C (gcc)](https://gcc.gnu.org/), 10\*112 = 1120 ``` c,i;e(i,s)char*s;{for(c=1;i;c+=10,i/=10)*s++=c+i%10;*s=0;} d(char*s){for(i=0;c=*s++;i+=--c%10*pow(10,c/10));s=i;} ``` [Try it online!](https://tio.run/##vZbNbqMwEMfvfopRK1Y2HxtIyEfl0ieo9ranbFaiBoIjQiMM6qHi1ZcdmzjbSHv2HwmG8cz87AEsRHQUYppEKHlJZaiYqPPOV/yzeu@oyBIuuQiyJA7lAs/MV0GQiUB6Scx9lcV8JAWdU5hJkegTmQ7jMsiiSGCkf3n/oFhCLLAC4yqTfJweZSuaoSjhWfVFI9@@1y/kn6@X51J7iPrILwYAvgphNnoGn2S2RQ0ZjnCCJ2312urREjUnIyFk4Yu6zC@g6qGqmtJfkKtli5pasu1BYlbMZ/uEtuq7pmypYugbWiWPbVmYQVWikQGlPqV3Az5TjMFv@M8A/ab26YGhsJopEGSgF0l//Hx9Nc4ubwuqh/SdrOjJzEz3lOPcnmEZ4zUIjBfA9AWLmizmnQ4hfL3TNUYymhYQoudwzmVLTfLd1OyqTTfUPkkOnJCbV78SYDpw6TC6og/eANEL7D110NeHEGyAbetd9NVZfM3xhl8t5uHTxOXqfsy4xDFvGTsGruKVY2Iax3HqFrk2csvcJOZwC91u1ul6s3UL3V3ljErsx7lc6dXunpy9wWB3BSvX4Js4uN2XkuVVjsHJyso1OLVyDV5buQZvrFyDt1auwbvb3uUY/GTlDtyV/dC1@gdK/35Nf0TV5Ec1Rc35Lw "C (gcc) – Try It Online") I have global variables, but they are not actually passing any info between two functions. Variable declaration for `c` is used in both functions saving me 2 bytes in code length. A version that uses printable ASCII only for a ~~3~~ 5 byte penalty is here: ``` c,i;e(i,s)char*s;{for(c=32;i;c+=10,i/=10)*s++=c+i%10;*s=0;} d(char*s){for(i=0;c=*s++;i+=(c-=32)%10*pow(10,c/10));s=i;} ``` Thanks @ceilingcat for 70 points improvements. ]
[Question] [ Consider, for a given positive integer \$k\$, the sequence \$(a, a+1, a+2, ..., a+k)\$, where \$a\$ is some positive integer. Is there ever a pair \$a, k\$ such that for each element \$a+i\$ in the sequence, either \$\gcd(a, a+i)\$ or \$\gcd(a+i, a+k)\$ are greater than 1? This was investigated by [Alan R. Woods](https://www.mathgenealogy.org/id.php?id=1477) as part of his PhD thesis, and it turns out that the answer is not only "yes", but also, that there are an infinite number of such pairs. For example, choose \$k = 16\$ and \$a = 2184\$, to get the sequence $$2184, 2185, 2186, 2187, 2188, 2189, 2190, 2191, 2192, 2193, 2194, 2195, 2196, 2197, 2198, 2199, 2200$$ For each element \$x\$ in this sequence, calculate \$\gcd(2184, x)\$ and \$\gcd(2200, x)\$ to get the pairs $$[8, 2184], [5, 1], [2, 2], [1, 3], [4, 4], [11, 1], [10, 6], [1, 7], [8, 8], [1, 3], [2, 2], [5, 1], [4, 12], [1, 13], [2, 14], [1, 3], [2200, 8]$$ None of these are \$[1,1]\$, therefore the pair \$16, 2184\$ accomplishes the proposed question. However, not every choice of \$k\$ produces a valid \$a\$. For example, no such \$a\$ exists for \$k = 2\$ (i.e. it is impossible to choose a consecutive triple of positive integers such that the middle is not coprime with either the first or last). The values of \$k\$ for which \$a\$ exists are the [Erdős–Woods numbers](https://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93Woods_number), which begin $$16, 22, 34, 36, 46, 56, 64, 66, ...$$ [A059756](https://oeis.org/A059756) is the list of Erdős–Woods numbers, and [A059757](https://oeis.org/A059757) is the list of corresponding \$a\$'s --- Given an Erdős–Woods number \$k\$, output a positive integer \$a\$ for which no element of \$(a,a+1,a+2,...,a+k)\$ is coprime to both \$a\$ and \$a+k\$. The output **does not** have to be the smallest such integer, so long as the output is always correct. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. ## Test Cases ``` k a 16 2184 22 3521210 34 47563752566 36 12913165320 46 3180417880379694 56 2212091405535117414 64 3843095117044776029646 66 3615758618744894508744 70 13151117479433859435440 ``` --- ## Bounty I have awarded a +100 bounty (minimum) to [Nick Kennedy's C++ answer](https://codegolf.stackexchange.com/a/230797/66833), which can handle \$k = 538\$ on [Try it online!](https://tio.run) without timing out. This has completely blown the scale for the other offered bounty (+500 for producing output for \$k = 76\$ or higher), so instead, I've decided to award +500 to [xash's J answer](https://codegolf.stackexchange.com/a/230542/66833), which was the first to find the more efficient method that other quick answers relied on, as well as notice that the values listed on OEIS were wrong. [Answer] # [J](http://jsoftware.com/), 213 bytes Computes the lowest solution for each \$n \leq 162\$ on TIO. Also found out that the OEIS lowest values is apparently wrong, as you don't need to put every prime in a partition. Big thanks to @Neil for reminding me about modular arithmetic, otherwise I would have sit at \$n=36\$. :-) ``` 3 :'N-~<./(0{[*|.(]-[*<.@%~)N*0}.@{_2{[:(]\:~@,:[-]*<.@%&{.)/^:a:,.&(=i.2))"1*/&x:&>>,&.>/@(<@((|.@[(;~"1&>&{.,;"1&>&{:)[,"1 0&.>(-.&.>|.)~)`(,:@[)@.(1 e.[:,e.&>))"1&>~)/(<,:a:,~<2),~<"1\:~(,.|.)<@~.@q:i.&.<:N=:y' ``` [Try it online!](https://tio.run/##JVDLbtswELz7KxYCKpM2RfEh0RIjCQQK5BT4kCurPmA4idtD0VsCu/p1d0eFwMHsznKGq5/3Qm9faIy0JUWGIp9K0@fnp8e7p7g9Vsuga2GueXfTYq7ybtDp0yKPO/NXp@s3d81RzF/iklTM1byq5VXL@mv8EZUuxXjRTsrC7uryPZbTpEo91UkMSYibTlk8LIUtJ76iHv6TKLMqLBmeE5VmvGm5yO9CxZRl0sLSWeeozrqc4FtOi6zFoBC3DE4yFJbfI5Tmi0NadPoTL@wzxOMYP7Z3uTm9nU@/xmjGHPe6JstfFTkyx1skMau8nyVBueg0cSrtad688i86n95@J6Eyz6we8kVuNq@FMJJsIOfIN@QDNYHaQKGhEOhg6MDYUReo66h31DfUB7LG8AmKrHWAlXUMzgAaBg/mwRqMNCvDXAsWoAYIHXo9yp6ZM6w6awAoYepg6hwPO78CerByDVgLtUUJUwdTFyAc0OvQ61aGXg91Deq59MYAHIB7HrkeuR6RHnt4t5YYxkbeo2zAsJbHM3wb7v8A "J – Try It Online") ### How it works ~~Partition the primes \$\leq n\$ into two sets \$p\_0, p\_1\$~~ … this approach doesn't necessarily finds the lowest value, as sometimes not all primes are needed. Find \$p\_0, p\_1 \subseteq primes\_{\leq n}\$ with \$p\_0 \cap p\_1 = \emptyset\$, so that every number \$i\$ in \$0 \dots n\$ is a multiples of a prime in \$p\_0\$ or \$n - i\$ is a multiple of a prime in \$p\_1\$ – so the numbers get sieved. I got the idea from [Bertram Felgenhauer's implementation](http://www.int-e.eu/oeis/a059756.cc) to get the Erdös-Woods numbers. For example, for \$n = 16\$ the sets \$2,3,7,13\$ and \$5,11\$ do this. With \$P\_0 = \prod p\_0\$ and \$P\_1 = \prod p\_1\$ we need some \$a, b\$ so that \$aP\_0 + n = bP\_1\$. With some shifting around this is equal to \$aP\_0 \equiv n \bmod P\_1\$, which can be solved with \$a = n P\_0^{\phi(P\_1)} - tP\_1\$. Luckely, J has `m&|@^` already efficiently implemented, thus we can easily get a solution with \$t=0\$ and then adjust \$t\$ so \$aP\_0\$ will be the lowest over 0. At the end we just find the lowest overall \$aP\_0\$ of all partitions. Another method that is slightly faster (but also quite longer) is to solve the equation with the extended Euclidean Algorithm. \$aP\_0 + n = bP\_1\$ is \$a(-P\_0) + bP\_1 = n\$, and with the algorithm we get a solution for \$a(-P\_0) + bP\_1 = 1\$. We multiply \$a, b\$ by \$n\$ to get a solution for the original formula. To get the smallest positive number, we can increase \$a\$ by \$P\_1\$ and decrease \$b\$ by \$-P\_0\$ (though in the end we don't care only about one of them, so we can ignore \$b\$). To get the sets we compute for each \$i \in 1\dots n - 1\$ the primes that would sieve \$i\$ on both side. So with \$n = 16, i = 3\$ would get sieved if \$3 \in p\_0\$ or \$13 \in p\_1\$. We sort this list so lower numbers that occur more often will already be sieved when construction the sets. Folding these results, starting with the pair \$(\{2\}, \{\})\$, either a pair already sieves that number (then we pass it unaltered to the next iteration), or it doesn't – in which case new sets are generated, so that for example \$(\{2, 3\},\{\})\$ and \$(\{2\}, \{13\})\$ occur next step. We need to make sure that no prime occurs in both sets, otherwise \$gcd(P\_0, P\_1) \neq 1\$. ### Ungolfed (old) ``` f =: 3 : 0 N=:y NB. needed primes to sieve number ps=:(,.|.)<@~.@q:i.&.<: N NB. initial partitioning of 2;'' i=:(<,:(<2),a:),~<"1 ps NB. fold and expand each partition to all possibilities NB. to sieve out the next number ugh=:([:,&.>/<@(([:(#~*/@~:@;"1)({:@[;~"1&>[:{.n),{.@[;"1&>[:{:n=:,"1 0/&.>/@,:)`(,:@[)@.(1 e.[:,e.&>))"1&>~)/ i NB. helper function for the mod-calculation t=:4 :'x-@*y(]-[*>.@%~)N*x y&|@^_1+(-~:)&.q:y' NB. get each partition's solution and pick the lowest of them <./t/"1 */&x:&>> ugh ) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ,gþr’§Ạð+¥1# ``` [Try it online!](https://tio.run/##ASAA3/9qZWxsef//LGfDvnLigJnCp@G6oMOwK8KlMSP///8xNg "Jelly – Try It Online") -3 bytes thanks to caird coinheringaahing yeah this isn't gonna finish for `22` on TIO. --- You can find a more in-depth explanation and step-by-step process for solving and golfing a Jelly solution for this challenge in my [YouTube video here](https://www.youtube.com/watch?v=QsYz4DRxJK0). --- ``` ,gþr’§Ạð+¥1# Main Link; accept `k` 1# nfind; find the first 1 element `a` where all of [a, a + 1, ..., a + k] are not coprime with both [a, a + k] ¥ last two links as a dyad: -------ð - this link accepts `a` on the left and `a + k` on the right + - this link adds `a` and `k` therefore, by the 2,2 chaining rule, this applies the left link to `a` and `a + k` ,gþr - by the special-case 2,2,2 chaining rule, this applies `gþ` to `(a) , (a+k)` on the left and `(a) r (a+k)` on the right gþ - product table: compute the GCD between all pairs between , - pair; [a, a+k] r - inclusive range; [a, a + 1, a + 2, ..., a + k] ’ - decrement each GCD § - vectorized sum: sum each pair Ạ - are all truthy? ``` Essentially, for each number, we compute the GCD between all elements of `[a, a + k]` and `[a, a + 1, a + 2, ..., a + k]`. Then, we get a list of pairs (though each in reverse order to what was presented in the challenge). Then, we subtract 1 from each. Since GCD gives a minimum of 1, this gives a minimum of 0. Therefore, when we sum each pair, and `[1, 1]` GCD pairs become `0` and everything else remains positive. Therefore, we check if all elements are truthy, and find the first `a` for which it is. --- [![enter image description here](https://i.stack.imgur.com/gn4KN.jpg)](https://i.stack.imgur.com/gn4KN.jpg) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 168 bytes ``` ṫ-;Ṛ×+ƭ/⁸; %@’п/:ƝṖṚçƒØ.ṫ-××%P{ ’ÆfQ$€m2Ṛż$©f/ÐḟFḢWḟ"Ṛ¥€FḊ$ÐḟZ;FQɗ"ʋ@ƬƲṪF®ḟ€ƑƇẈ⁼Ø1ƊƇƲF€fƇFQɗⱮ`ÐLQƲ,@$ŒPżṚ$F€€;"€ʋ@/;"Ɱ®f"Ẹ¥ÐḟFQɗḟF}ɗŒPżṚ$Ʋ$€Ẏf"ⱮẸ€ẠɗƇ®P€ḤżUƊ$€ẎNÞ祀⁸FṂ ``` [Try it online!](https://tio.run/##PVBPi9NAFL/3U4SSPe3sJpmZTlMD0lNOIu1BRE9ejLCsF28iQncRI12Qugezin8WsRR1LWxPaS0uZOxA/RaTLxLfbxShffn9m/fmzcH9w8PHzaNg3/44eaB/mnE9elPN7Oq8sctve4ldvtXFrvke1Edl0trpk6sn1VVwzby3y9dwZ@ZUn@0jrAtd7AyetJB5ng39@vjiIafIZu1XX7JAT2z5MbXlp9v0bZNeTSlBwth31t0kHW6L9u@TvrkwC7v8mlZzkiljXpncrl7UR2t9Fpmxyc0iJTkzOU7Ul/N7enJjaBas729OB5s19fYRoF/SpkItAwKX82qete2qrKZ/70KH8Xm6Lf4fMwtc265eZshT1rHzbWHyaj4AKT9v1rfM@F/spv6gZ24ReqDULo@bROcJ241@XW2Lauof1KN33t51rx7Rez1r6ZySd5omUoxzJiQTiknFOoopyZRi3ZB1qcYsViyOWY8zryfpr5gXhSEKUMRRHIqpcBicYpEAEkASEekQch0gBVfBiKH1QNGZh@TyKEQBRVOOppzu6HHhCjS04hKoA7cDiqYcTbmC0YUWQ4sdgoYtuBvUIyqwhwg5CmkCcwXmCowU2ENwRxHGRkKASiCsJXANgeFCoXShdRGOgfBeAtMkBknsJkNHKSIjUEyTGCS5QzBE@Ac "Jelly – Try It Online") A full program taking an integer argument and returning an integer. Works on TIO to solve a for all values of n between 16 and 118 inclusive within 60 seconds. Individually it manages every n up to 130 within 60 seconds. I’ll post a full explanation later, but crudely it works like this: 1. Partition primes <n such that all \$i\$ or \$n-i\$ for \$i\$ from \$1\$ to \$n-1\$ have gcd > 1 for one of the two partitions. This is done initially y working out which primes must go together and then trying all combinations of the rest. 2. Solve the Diophantine equation of the form \$Ax - By = c\$ to work out the final end points. 3. Find the minimal such solution. [Here’s a minimally golfed Python 3.8 version of this solution](https://tio.run/##dVTdcqJKEL7nKebs1m4xZtyFGYLEqjlPce4oL1BGxSggghs8Oc@e01@DMbF2U5W2//vrnm7qvt1WpUnq5u1t3VQHUbSuaatqfxLFoa6aVtRNlXer1mPrIWu3Hw2DdlXV/VWbO1dD9nK3Fmv/Rc49Udv05FpfrqtGFKIoRZOVG@e/TEO58MSdViuOEcValFUr9q7067SYhgvWsvfu5h0qTvPzZ/EQDg6CvCc78v@R5blfSE@0Nr1w3AVxl6KmhPM5eahajmV8zaY0WADR8VNAe4UC8/dLGi7IpbHpv6V7aX3Myz@SBbHyP8WNkkNuQ0/82hZ7J3Lgym1ANLMp2Th3j9xHhnyyaU/h04aI6qkAcVyFp4AJnJDd2lBkZT4qQiiCoWW4v1o4sci1hXD7z9HBfXR4jQ44OryLPrl59kDQWH20mSfONBg4Ywi3AR2vKC/3KC9jHcpQoX@ehw/LWf5lK36w8jYSznZmUG4A8T6ocoBKhfrvl4EX/au9DJzj4dLfsnHZ8zg3Ny8J/YXRV3YoCv5sS09suer76o1L7k/SNFA0@sngPgK87rTfyBGpv1PPEoGu7A6uyVpHm8awyvSZhnlOd6jbWV6HMYgrtfMRHrauwEaVRGClWRGPPe9eLZteoZNTOEzL4Xk6uy9Ord/Jj1v0W/QdoReotbzhL@V1qL9poB/vZ0kd8O101IS8e4zitrXXJlCMG1ni@clnUIRQEPwx65/eiHVbeqgUXfjLtFjIia@n/s7aQt5/MrRc3H0ANI5t9fk1t/z9@HGi7xEPv7cFXyAv2nCT/zSdGxctL84Hqoy7UzhDbrm3qcMNPvQenwRJAUn5FTfZcD/XXjaWJ/9xj/nqxQYrONmk9LV5IKr5qjfQvdxcYZiz5WB5CvhqiRWFbqjqBLP8dlAb@plg0N8O@AC5tmtKcShKfyXf3lt352zvF2XdUecynZtgge9vU5S0bOrL9O8vak3Z1XrfnbYWQ5De18G89p@0lG9pGCutlYmUiVUUq8dYxZGKYzUL1IxoopJYJYl60ko8RfQfKxEGAQi4UIMwlxDRMGhyCw04Ay6CS8Qc/B7BxbDGMCTQPUFEZh2QVYcBCEQk1UiqCaPQhgl0SKUjcI@wPkJEUo2kOoZhBl0CXcIcdOhCc6EnEg36MIEGIZ1BXYO6BiUN@jCaRTijI2MgRuDQlgEMg@ImBplBN4NzAg7zMqgWoVCE3qKARXKJQoioFqFQpJmDgR7xfw) that gets from 16 to 144 within 60 seconds. Thanks to @ovs for pointing out a bug that meant the minimum \$a(n)\$ was not always obtained. Following @xash’s insightful observation, now doesn’t assume that the prime partition will always include every prime. For example, the value for \$a(46)\$ in the question and the linked OEIS sequence is wrong. I’ve now got a [faster, slightly shorter version](https://tio.run/##LVBNa9tAEL37VwijnryJpJ31So6gJBcfQ1Poob301BRCoNBbDwUnhxqsi8mhSkvThBZj@pFAc5LS0oC2WbD/xeqPqPO2BevxZt7sezM@eHZ4@Kp7GW26n8Vz89vO2sm7ZuluLjpXf9vIXf3elAN7GbVHVd67t82qmTe30ZY9c/VbqEt7Yk43d838BR6Ysj2qB0/tZb/9cbWz1U5OXT25O3loZ6wcf18Xj143i6Y25bpgxx7s3uzvhSyxV/Pl7le4H5m5q87byQf/O2uuxBhydR656nPyrymEndnrvM@CvWapj9cLrsaumoXe4Ek@3luV/XWxbdn7q1f/e/MMludnML6pPF6EGJ266lOzWBf@zQMWds1Hs1zxVdV4x9XHXW6muRgkf25XZbMID3idYON@wCv1zJTHH3ddooWUgpQgLZQWQy20ElqLNBYpYyYyLbJMjKQIRoo/LYIkjgFgiQR4ljFICJLHEgIjMIUR5RnmhmAaqoaQoTdCCWcZsyqTGIASphKmkncMJHlAD1ZSgQ2hDlHCVMJUaggpehl6mWfo4Qrpg0ZcEu6gWAK4R8gl5BIiCXeQ9CWGcRERSgWGswhrEMJJA1L0UgxnYPi/CGkKQQq3qdiXPKISlEhTCFLSMwgU/wU) which doesn’t guarantee a minimum value of \$a(n)\$ but generates values of \$a(n)\$ for all \$n\$ between 16 and 430 in about 50 seconds on TIO. This represents all of the values of \$n\$ listed in [A059756](https://oeis.org/A059756) at the time of writing. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 4344 bytes ``` #include<iostream> #include<set> #include<vector> #include<array> #include<chrono> #include<map> #include<boost/multiprecision/cpp_int.hpp> #include<thread> #include<future> using namespace boost::multiprecision;using namespace std;int S(set<int>&x){return x.size()?*x.begin(): 0;}void M(vector<array<int1024_t,2>>*f,vector<int>*nr,vector<array<int1024_t,2>>*q,int x,int ct,int nt,promise<int1024_t>*pr){int1024_t m=0;for(size_t i=0;i<f->size();i++){if(i%nt==ct){array<int1024_t,2>h={1,1};for(int j=0;j<2;j++){int1024_t c=(*f)[i][j];int k=0;while(c>0){if(c%2){h[j]*=(*nr)[k];}c>>=1;k++;}}for(auto j=q->begin();j!=q->end();j++){int1024_t g0,g1,f0,f1;int64_t f2,f3;g0=h[0]*(*j)[0];g1=h[1]*(*j)[1];vector<int1024_t>d;vector<int64_t>e;if(g0>g1){swap(g0,g1);}f0=g0;f1=g1;while(f0>1&&(f0>=INT32_MAX/2||f1>=INT32_MAX/2)){int1024_t n=f0;d.push_back(f1/f0);f0=f1%f0;f1=n;}if(f0>1){f2=(int64_t)f0;f3=(int64_t)f1;while(f2>1){int64_t n2=f2;e.push_back(f3/f2);f2=f3%f2;f3=n2;}}f2=0;f3=1;for(auto k=e.rbegin();k!=e.rend();k++){int64_t n2=f3;f3=*k*f3+f2;f2=n2;}f0=f2;f1=f3;for(auto k=d.rbegin();k!=d.rend();k++){int1024_t n=f1;f1=*k*f1+f0;f0=n;}int1024_t K=(x*f0+g0/2)/g0;int1024_t o=min(abs(f1*x-g1*K)*g0,abs(f0*x-g0*K)*g1);if(!m||o<m){m=o;}}}}pr->set_value(m);}int main(){int nt=8;double tt=0;int x;while(cin>>x){auto start=chrono::system_clock::now();vector<array<set<int>,2>>v(x-1),nv;vector<pair<array<int1024_t,2>,int>>r,s;vector<array<int1024_t,2>>f;map<int,int>c;set<int>y;int1024_t t=1;int mp=0;for(int i=2;i<x;i++){if(!v[i-1][0].size()){for(int j=1;j<(x-1)/i+1;j++){v[i*j-1][0].insert(i);v[x-i*j-1][1].insert(i);}if(x%i==0){t*=i;}else if(!mp){mp=i;}}}if(v[0][1].size()==1){continue;}for(auto i=v.begin();i!=v.end();i++){bool e=0;if((*i)[0].size()){for(auto j=(*i)[0].begin();j!=(*i)[0].end();j++){if(t%*j==0){e=1;break;}}}if(e){continue;}if(S((*i)[0])!=mp){nv.push_back(*i);}for(int j=0;j<2;j++){for(auto k=(*i)[j].begin();k!=(*i)[j].end();k++){auto ci=c.find(*k);if(ci==c.end()){c.insert(make_pair(*k,1));}else{ci->second++;}}}}v=nv;map<int,int>ns;vector<int>nr;vector<array<pair<int1024_t,vector<int1024_t>>,2>>bs;int cn=0;for(auto i=v.begin();i!=v.end();i++){if(((*i)[0].size()==1&&(*i)[0].size()==1&&c[*((*i)[0].begin())]<3&&c[*((*i)[1].begin())]<3)){int z=*((*i)[0].begin());if(z!=*((*i)[1].begin())){z*=*((*i)[1].begin());};if(!y.count(z)){y.insert(z);}}else{array<pair<int1024_t,vector<int1024_t>>,2>b;for(int j=0;j<2;j++){b[j].first=0;for(auto k=(*i)[j].begin();k!=(*i)[j].end();k++){auto ni=ns.find(*k);int1024_t c;if(ni==ns.end()){ns.insert(make_pair(*k,cn));nr.push_back(*k);c=((int1024_t)1)<<cn;cn++;}else{c=((int1024_t)1)<<ni->second;}b[j].second.push_back(c);b[j].first|=c;}}bs.push_back(b);}}sort(bs.begin(),bs.end(),[](array<pair<int1024_t,vector<int1024_t>>,2>&x,array<pair<int1024_t,vector<int1024_t>>,2>&y){return min(x[0].first,x[1].first)<min(y[0].first,y[1].first);});r.push_back(make_pair(array<int1024_t,2>{((int1024_t)1)<<ns[mp],0},0));bool D=false,D2=false;while(!D&&r.size()>0){if(D&&!D2){D2=true;}s.clear();for(auto i=r.begin();i!=r.end();i++){for(;i->second<bs.size();i->second++){bool e=0;if(!((i->first[0]&bs[i->second][0].first)||(i->first[1]&bs[i->second][1].first))){break;}}if(i->second==bs.size()){D=true;f.push_back(i->first);}else{for(int j=0;j<2;j++){for(auto k=bs[i->second][j].second.begin();k!=bs[i->second][j].second.end();k++){if(!(i->first[0]&*k||i->first[1]&*k)){array<int1024_t,2>b{i->first[0],i->first[1]};b[j]|=*k;bool e=true;if(D2){for(auto l=f.begin();l!=f.end();l++){if((*l)[0]&b[0]==(*l)[0]&&(*l)[0]&b[1]==(*l)[0]){e=false;break;}}}if(e){s.push_back(make_pair(b,i->second+1));}}}}}}sort(s.begin(),s.end());s.erase(unique(s.begin(),s.end()),s.end());r=s;}if(!D){continue;}size_t w=y.size();vector<array<int1024_t,2>>q(((size_t)1)<<w);for(int j=0;j<(int)(1<<w);j++){q[j]={1,1};auto l=y.begin();for(int k=0;k<w;k++,l++){q[j][(j&(1<<k))/(1<<k)]*=*l;}q[j][0]*=t;}vector<thread>ts(min(f.size(),(size_t)nt));vector<promise<int1024_t>>ps(ts.size());for(size_t i=0;i<ts.size();i++){ts[i]=thread(&M,&f,&nr,&q,x,i,nt,&ps[i]);}int1024_t m=0;for(size_t i=0;i<ts.size();i++){ts[i].join();int1024_t o=ps[i].get_future().get();if(!m||o<m){m=o;}}double rt=(double)((chrono::duration<double>)(std::chrono::system_clock::now()-start)).count();tt+=rt;cout<<x<<"->"<<m<<" : "<<rt<<" secs;total "<<tt<<" secs"<<endl;}} ``` [Try it online!](https://tio.run/##lVdbb@o6Fn7Pr4AzKorT0OYGm93gjEbqy@hozzyceRgJoSqEhIZLkiaGQiF/fTqfnZtbus@lErXXxZ/XzSt2kGXDVRC8v/8tToLtfhlO47RgeejvPKVlFSGTqEMYsDSXGH6e@yeJDp7zNEklxs7PJGqRYof73X7L4iwPg7iI0@Q@yLKnOGF3z5msyp5hyVJiRHu2z0NP2Rdxsuol/i4sMj8IewLz4eEjqPtZq2BLF5v0flPh0RQzb3Ak5zwEZtI73hXxW6iSv2vHu0W4ihOVPPQMtzyk8bL3Q628rnzlS03Dcp6YbnmeFum1kCNqSa7/ju6Lzg04iv8BE0PC9CxPd3ERdrqeluXk3JK9HTXcKM1VbiLIGGQ8jYZeZbIb395CO1Ljm4RRGjByvt77mZ5N3SwFDN92DYz11HLXYm27U0BVLSKzeD5bz0WwNtB7fY63oRp4htgluLHI@RlyDbpJTmabuVsGnkdNd3N765Yl38LfsxR7vAy9Opjuus@pMFny@cdNV4a@MvXI0COT7znmvMjSI9tdGfR5Zsw1VVsTjO7KBG3WtDl3u8jXgVtKLI7jhS5MXhneyiTn4tXPVLEZccvIoCtE1aQrs3YwMjxzMOAD/ee//mNbTz/@8d9763KJzA8MIpue0Mhwl3fZvnh@WvjBRo3M@8ggLtAj8yYSGyRuCRs4OjlHFlVr0wiX2hLZ2mFxzSYQiUUjyw3lLez7yMIWENg3kAEksXjcLSoQTbfNwIaGd3mTgU2fU1UGNnUG2i1svlLbaJF9yyEtAcm9sLgLXNxhLj9gLj9jdqEx@VoOat5yZw0RilbhV6oetci4XRkI6j2S0YlSugO8vygQT@04XJnar0RD5gTH4BxDcJBIhLa/u1zS6Y6cdzRFHMoyy3E2QvZ08Lf7UN0RsWtv53OTz9WhoxN3me4X27DHGBVb945NoceJ56EzCG8L5ueMVj3t4aE4FSzcPQXbNNg8PCTpK9z@cNybzsJP@0E9Dk2iJ4dGJfPjr9oCbwOel@uF@/POEbnoopwllAO32eckBY1RcXx6u6xuF5yIqYVecWx7RP8wi4fmHIepbnioybYlmGgJwuj7@NasTinUtXW9IE6KMGdqDJ9nx2HNN2U@L/TjTUwpWgXTaOyW4bYIeyJHGfKTcVbJtQ4A5GsrIyhFxQdpwuJkH7pdB4npoenGbtwHUVWacAZNf9sLee4iVdVi8tmlugU1IqkPNSy5GUUqu9HWwvAQcVjgy7OpTQ1l00D/1mxH@pR7lRykw6nxKHzZZKUDJNavO5s2/ZYlHSWhHMQ0uIticLWNKHYwwBFqsKuJ/c7fhE@8vqCmm4RUgT8HMT8IsH4pOnNZHijKUS6lpJA6ppfkH2tQVGxXiFftVtT5ohBlFyR12f1h5njCPmYM@UfnvWYFM039lEAyn9qSwPwgqHpz741eL@Oxe@vT62Xk/KZ9wXZL0VpOd0G6T5j6Br1TE@03SKsA//kwLb7@9C540qM4L5gcvb9UIklMk0Kqke5jzj2AlIvrgsHsq4oJEjic5HIdAwmXAbVFIyaZToPEDRJeSlV1XcmTtt7cUnhWERJuQNzO5QsNEMhFIckXPLRFCgPBrp3XF7X9@myu/vmID476X1A@tVdB/uk58tIRNupHXhViSqZcdOpEp07klsSV49eF97qbn6/CVsx22Vw3St1AHkRje6SRjxjrj1Y1qb9N/cfBIK9PSH0fA6f/iCsZNFnOW1RxF2xDP0eNSKcxl09jLp9GruS2eZsi1s21susdH7ttH/YPPeE3YjFYFLNWdd4Gh1wunZb5WauNG2qy6bX8BttoUNraAc8qxyIpvA1y0@j@qON@3L0rTOl4/UxFvtxw32XXtc3lIjuJU/PV5Xtxlhbp0oJSHIYL7khuHWDhKc@qJdm/pVFr6bYPorJp2zRTbUtEIvCP0oYadGyzY/PPW1VQnz5xxZfFu9C7KhCfFfEnzmd3PJvu4mKS@0Wo7pP4BReva41ONaeF@Jj2H@Wva/3AeaWnpgh/fiV6wUek0hdn6JV8arB8SlRTSEQ5vCDU9SuojuqpjWqzlD93NtNXnm592yyaqesBB0Jy76sRbx9t65ZCiOcJZXgoVobWb1ZWqLxXRLUbemMpTGp9un72eVmhsrbur598rDub3DaGip3Takd18EMfRPoA78/Bi44Xpo4P/CDjGkS@dH/5lPwK926dVu1CupQLuLsVbtbVS1wlnFC/uoTXl2vcndVqSlS1uUUv97nP8EKfVhKPqHiaPzz8ziV7KK7hhNQfY@Iydktz5oJk0@lxOv1l6P0yne4w6T30MMsZn6JwC5elzN9yHmt5IFCGSGD5/m6OFctSbEexx4ozVkZjZewo47HyzVC@4f9EmYyVyUT5binfHeX7WDENAz@MpoUfHyeKaYFnOYppYwSU6UDm8BHyEcYx@GPwgGV@xxw4luEolmnghzkwLGBYsMSy@Q801loOxhH4sMoChgUMawweLLMmoCd8BA3rLI75faLYsM824BFstIFvA98Gtg37bIvPoQM7bfhrOxgd7j3m2MOG3/Y30HDbnmCEyzZwHWA6sNcx@HyiOCbmwHWA6Vh8BA@YDux2gOXAZ2fE44kfAukA0/kGHux2Jhhht4M4OMB3YPMIsRwBb4Q4jGDrCJgjYI4QixHiOYKtI3vyvyDa@qviffjvyC/Y@zCrSv// "C++ (gcc) – Try It Online") This C++ version is primarily written to maximise the speed of generating results. It is loosely based on the approach of my Jelly solution, but includes further optimisations. The version on TIO can produce the minimal \$a(n)\$ for all Erdős–Woods numbers <= 538 within about 30 seconds in total, not including the compilation time. It initially assumed that all Erdos-Woods numbers were even, but they're not - the smallest non-even one is 903 ([OEIS A111042](https://oeis.org/A111042)). The code posted should handle odd Erdos-Woods numbers too. Below is a slightly expanded version that will also generate the Erdos-Woods numbers themselves from scratch (i.e. doesn't use a presupplied list). Here's some more results (from an older version for now): ``` 16 -> 2184 : 0.0023778 secs; total 0.0023778 secs 22 -> 3521210 : 0.0007892 secs; total 0.003167 secs 34 -> 47563752566 : 0.0007036 secs; total 0.0038706 secs 36 -> 12913165320 : 0.0008207 secs; total 0.0046913 secs 46 -> 21653939146794 : 0.0011214 secs; total 0.0058127 secs 56 -> 172481165966593120 : 0.0013218 secs; total 0.0071345 secs 64 -> 808852298577787631376 : 0.0011176 secs; total 0.0082521 secs 66 -> 91307018384081053554 : 0.0006865 secs; total 0.0089386 secs 70 -> 1172783000213391981960 : 0.0009034 secs; total 0.009842 secs 76 -> 26214699169906862478864 : 0.001472 secs; total 0.011314 secs 78 -> 27070317575988954996883440 : 0.0016488 secs; total 0.0129628 secs 86 -> 92274830076590427944007586984 : 0.0032485 secs; total 0.0162113 secs 88 -> 3061406404565905778785058155412 : 0.0008836 secs; total 0.0170949 secs 92 -> 549490357654372954691289040 : 0.001961 secs; total 0.0190559 secs 94 -> 38646299993451631575358983576 : 0.0012295 secs; total 0.0202854 secs 96 -> 50130345826827726114787486830 : 0.007897 secs; total 0.0281824 secs 100 -> 35631233179526020414978681410 : 0.0255103 secs; total 0.0536927 secs 106 -> 200414275126007376521127533663324 : 0.0011955 secs; total 0.0548882 secs 112 -> 1022681262163316216977769066573892020 : 0.0016636 secs; total 0.0565518 secs 116 -> 199354011780827861571272685278371171794 : 0.0068985 secs; total 0.0634503 secs 118 -> 5084808394825008411597027854612265320 : 0.0140484 secs; total 0.0774987 secs 120 -> 33088145229978950006171841905081799893430 : 0.0282395 secs; total 0.105738 secs 124 -> 9132534211053896168120244510786592061314796 : 0.0119749 secs; total 0.117713 secs 130 -> 1010223786859974709684811231603116447862010 : 0.0085169 secs; total 0.12623 secs 134 -> 918536092326116746940802093225005168208856 : 0.0080068 secs; total 0.134237 secs 142 -> 326415290503067481481262636553276300760538971418633970 : 0.0097704 secs; total 0.144007 secs 144 -> 12519236270374172120152530393181563366703899726 : 0.0104701 secs; total 0.154477 secs 146 -> 30102196727419035397352263664971701624550 : 0.001873 secs; total 0.15635 secs 154 -> 250086121511153463601017992836053431027953173230156 : 0.0128302 secs; total 0.169181 secs 160 -> 16823726350582448550419008635093980344211195490 : 0.0121503 secs; total 0.181331 secs 162 -> 971838598937769539765770921839883750903640741790 : 0.0048932 secs; total 0.186224 secs 186 -> 1794082996332254346315702546582790195234663527026144577149550 : 0.0059784 secs; total 0.192202 secs 190 -> 100043328863825836942691086460363243931180087197722910850 : 0.0080825 secs; total 0.200285 secs 196 -> 17018920629980040075969105511895180448985253900154238700 : 0.0085788 secs; total 0.208864 secs 204 -> 481578279081960788203960306279407682980396228758026204933056959715840 : 0.0472954 secs; total 0.256159 secs 210 -> 29225782603870300544827882241040291898185518589118372486421537923611871170 : 5.60295 secs; total 5.85911 secs 216 -> 440200183843647241078327939248364204862519711650712622914040841410 : 0.0077262 secs; total 5.86683 secs 218 -> 67518017451793349875086631136663331002689144202850547609381398525979202451060 : 0.0092965 secs; total 5.87613 secs 220 -> 1459104994350090197385240721881419804872579186868731078959002070 : 0.0179516 secs; total 5.89408 secs 222 -> 398425392772309365488991662748906112633693445300311983234641390568 : 0.0085589 secs; total 5.90264 secs 232 -> 907378346149256277304071914319955007121813704909147483268086111540 : 0.0361636 secs; total 5.9388 secs 238 -> 45894107313965996638570818463974089099761314947922544200331971462236682 : 0.0174366 secs; total 5.95624 secs 246 -> 127209574731840814488699664382213489925455290327133090193663688070010069772464 : 0.14518 secs; total 6.10142 secs 248 -> 87349027419299768189875606566564845285333219860920999198422625577318053831430260 : 0.0417115 secs; total 6.14313 secs 250 -> 1274769952223858733770020211602403840979999894289407226855668118167657960120 : 0.0177074 secs; total 6.16084 secs 256 -> 211337714604794757725712768305031523837613606852887423808080138155983960657486438548840080 : 0.0095592 secs; total 6.1704 secs 260 -> 611379532364397862318258986724238889055579879595343134082300581949384481717350 : 0.0143897 secs; total 6.18479 secs 262 -> 457385261010485284248495193082983704923527433029112880026848488309914263938871758209640697245248 : 0.0057613 secs; total 6.19055 secs 268 -> 3837924875435446453632171348188362753950788432477364059540845274930576542794383781497646020913032 : 0.0041049 secs; total 6.19466 secs 276 -> 690516469573823892560050501225021813072395907134207867385994632898243111919015752071367994 : 0.133966 secs; total 6.32862 secs 280 -> 47182555594339904819679927877406287035566782878354969819901299764693418800067961552340 : 0.0912517 secs; total 6.41987 secs 286 -> 120610684017694120228701154065517023464640987099534560151170016560718941441263176114 : 0.0114873 secs; total 6.43136 secs 288 -> 138971473108541248222606578801479253148138919955516661540809691054255010511185699956086224052870 : 0.0775585 secs; total 6.50892 secs 292 -> 185675662432708092090998266897578702332183677920758773231493308055529123987258619622978284717475820 : 0.012051 secs; total 6.52097 secs 296 -> 528072426832989018489058277937146939019285808979376200830352699489792774867918795228285244 : 0.0120736 secs; total 6.53304 secs 298 -> 7925959560314994619176238662647274773767908511981401648794904625493728870549039264807892534696970055800 : 0.0128203 secs; total 6.54586 secs 300 -> 3830358397632282878932144419312617888493673029003334276706856317887318564286779642788172700903966820 : 2.7098 secs; total 9.25566 secs 302 -> 40657328466375053173917761727511056770288784946750010931930738501228836738754637506437259099070010911712995558 : 0.0027574 secs; total 9.25842 secs 306 -> 40577677425253871035899827941839786555247037625668392197716461967627850030740187779049330460230 : 0.413231 secs; total 9.67165 secs 310 -> 538488606541428281546338121909778865003615807576612791533987823960965825028425066849096657000 : 0.0080856 secs; total 9.67973 secs 316 -> 7872867140686218605593823674909333997835782911606331664298338788801081063003828117779226595689776787167680 : 0.0036166 secs; total 9.68335 secs 320 -> 151976414541647699016758460810943108138612297987590453341893209833547476537041052081981397479713129600 : 0.0557666 secs; total 9.73912 secs 324 -> 26361986955675918481699797183223411546429483863365717815976219805637972415698978214362140147547701812766 : 0.0969804 secs; total 9.8361 secs 326 -> 3789841018118926364678300055227311891347014053695801630069508088470681947289010244266304599643061195254304 : 0.002667 secs; total 9.83877 secs 328 -> 10928038824030068766469302266515597858847366735722411591364684152289531562139922070667848114860 : 0.0040279 secs; total 9.84279 secs 330 -> 32164328124314699652501607056033487951959073966795652571372554775412926044029553406890067889637692284566807340 : 93.6157 secs; total 103.458 secs 336 -> 3106020225275080429219264134875355687747745764370605877192451827687782320288332577944406977489148953164 : 0.246205 secs; total 103.705 secs 340 -> 29825269805686870505819604699502725220723406983445751308008620959839573168190344914196554174050824118754330 : 0.0289699 secs; total 103.734 secs 342 -> 240212844654937042612584799122424026485025869333251741199943878938676548397965251130234996068893280600 : 0.22941 secs; total 103.963 secs 346 -> 543096578713377998688537214746167217275303559738471072780629061333582537465383342959631810586241474719593516160 : 0.0062745 secs; total 103.969 secs 356 -> 16954869911528757517125591203874504442168457692764697546479952706970406480165191259262577720757385141714267796770657531340 : 0.002579 secs; total 103.972 secs 366 -> 4389659730095193754318655326327264752833785100279687859257349610267590708369010442448055310835588452360330889210894 : 0.0927121 secs; total 104.065 secs 372 -> 7377842100032579096970847665137405200105289987277245889432100309989104285888041825332110324561692968177624974176800 : 0.336335 secs; total 104.401 secs 378 -> 973134143857711984548808752932685151707551919556522506881076061012440046791171659775408389749625215164909147269668871280 : 2.50325 secs; total 106.904 secs 382 -> 672269870455295752749941691733331442902745781790421727886817450524410833032155123359740686629763506140323192428376385310 : 0.0025048 secs; total 106.907 secs 394 -> 221289329584737900269172059924096886744337194160035374991996053169800056881835752028310810922527670054056514781556013120958243152651198947795931415976 : 0.0032405 secs; total 106.91 secs 396 -> 1962986156270498590837428040271644141937106717996208244700227775952029989686778918949868920441390965913892352842577184164989322280 : 0.357485 secs; total 107.267 secs 400 -> 7487622941447424114189400327301794212912996211997720849199184913543025205738725722282996789897024593595594873848452690 : 0.0106362 secs; total 107.278 secs 404 -> 104988944031640566696876252223159702218634054291721114053942362103943547825159449331266825026341053836613626131254908908390059949340029727927290 : 0.0068556 secs; total 107.285 secs 406 -> 3140483434894111885957811121301682079786715171339614782737909232797671719266043287171188825464389608552117061317022641877667150 : 0.0183488 secs; total 107.303 secs 408 -> 211579081971284319753516661852997477765586890005276537318680476829494942508856533853247237516980759776245938593513888662281476762 : 0.484314 secs; total 107.788 secs 414 -> 184227830045234549016502848638570064283232747405972675492625247428967117610127137967793024207389649680803110124047199844886032416070 : 1.70146 secs; total 109.489 secs 416 -> 89716593469689252073694377593991599925396252252128033061971555378192612549403678662751600278716749636229262016871937541224901670587864 : 0.0045737 secs; total 109.494 secs 424 -> 190621313082002759082457531048983736857933425199317500309526460260480903992578039696090385642014886318893763859405914277246805656256382726421852130 : 0.0129013 secs; total 109.507 secs 426 -> 93728800773978265556429683027376173974950491906681697895736778157191134689503042887570278926594182170446133332560163856227637704274 : 0.160621 secs; total 109.667 secs 428 -> 2931848991408268124639635840008496586773506309953806810487482744551349578602533515984624684883631658704332317293256288264488948110946767780308172 : 0.0070358 secs; total 109.674 secs 430 -> 27478709895719298365755297812017619883221248788103553267387547041210617817326144730386583943696714770371394850963566107511565760 : 0.183163 secs; total 109.857 secs 438 -> 10912133713738946485738976131261562575408798493640821012109929982555297357336779342832390534219583446609310610201415309129133752660304392 : 0.447402 secs; total 110.305 secs 446 -> 1140646211956922665110130943268802509462711871461936692317977656567336777075905111559102852981167574234825226618883638636541407433356327827292857571679143420 : 0.0030787 secs; total 110.308 secs 454 -> 32778488604746971516107026989471786134873496259639072415065379151165026246089617762655468453355618291470712565631400415148976402188426870828927155076332524667888122690930 : 0.0045086 secs; total 110.312 secs 456 -> 151096680791287555145708840203295091586008659656829222140415372024546189048930084841422098326639382479146980605530110525787281920838306339978674 : 30.045 secs; total 140.357 secs 466 -> 1567036107936517776618947389958745525432586256910736346537512869766866036596967674195302350096711059648145953613686739267169651942922997304140534784421838930674 : 0.0076627 secs; total 140.365 secs 470 -> 442636529132068806081734237157206434836968006423546114466573521440524351421895912515760783653974315127885405849361383716546069303602606144594769938590 : 0.039894 secs; total 140.405 secs 472 -> 10184617044462151138890133863697369948628720643109450174383206953743306700307307177810890693876133203419020147232151560327552759086619074348 : 0.0036374 secs; total 140.409 secs 474 -> 1617367866042184847828111911826113198686256982420665156527057977530672664118556420609597651648637558677521232503264167513016194613324137370193144481380920 : 2.84999 secs; total 143.259 secs 476 -> 236014456526751889817622944694390965881058524509721339611383876800307554765688174182401020296857582255254583552096165354006185460487674653777209920 : 0.0580355 secs; total 143.317 secs 484 -> 141976867395758552861787541457927126724538937293609458854032925303046910754958179365387268701118922730055897358394006290803374658100681262033519449099698126678176542426356 : 0.0118532 secs; total 143.328 secs 486 -> 356334501749931789484943782741090710258398678714033932161852193144903024991207070454724045209936833184480106332413355129475649065855116232678542708710 : 0.331206 secs; total 143.66 secs 490 -> 61142856427699216317652651451852676228906233471655696309019956924256750472168114478752815319180103091541437573463446889733710647242210167431263330 : 0.500067 secs; total 144.16 secs 494 -> 13360851385477005746836609396303165290377765108365352964375482734646350283757930339054998760291263161974941451315337859589050340422814787615218791854992672068532376 : 0.0281845 secs; total 144.188 secs 498 -> 37136456756237928456333082900289626867300753740238089774205977596971973140622723718171174705485552866608478552058362711323479010006038966108413071907792830 : 1.73238 secs; total 145.92 secs 512 -> 3056747870887228098274237048029194850161865139074924724362956728582114272246014987352232242442837952089404728413292444253101127040775837013188315154874080676006495913028031281141819149290683720 : 0.0070583 secs; total 145.927 secs 516 -> 1131555242873749534137274770219505280389897328648902629475343634265231956226997190950103242905773228961039181493470861979226757872075973587099786609188514377605334 : 7.83639 secs; total 153.764 secs 518 -> 477900440773544256479262259016273308559590588598496935263961967987794124526804855066381826565156468459813846151185097284888144391947088957185250310387800 : 0.0518673 secs; total 153.816 secs 520 -> 53295397262268776453849317832027361287530404818968588036673281812052585944521470485678375302855137955202286016365201707282088250452598123166205568775120 : 0.531242 secs; total 154.347 secs 526 -> 19424119374445642412403413515452767870220141285947188050541538624609193256956205716630247444614560168795810201142653834560712410450343710094164276418543086083594 : 0.005264 secs; total 154.352 secs 528 -> 30694089378160770896860118764822753631340537417762572149219922646503153282141487639750918973387074051444909686447639044669850144084746728440401948616591058733242 : 4.03965 secs; total 158.392 secs 532 -> 13459822155848911563783687954011789407239432497812485476640425254665924231709912955546596483553340050690865588404870256974711800204194799241717025037756572273760675620938682735309504734045828 : 0.0423439 secs; total 158.434 secs 534 -> 117525677123012146851504206773256702574127049792880307128940336050833225345490730514792535209749918559665667573312048870436744825997262807901807331654750578881556 : 2.11484 secs; total 160.549 secs 536 -> 37953035901675033874082777749737339776908186726114170955384846260192326022205601462847134971612903086043582609431025333685948238062884527557649582702731422543516117121509592615405126096626578954525664 : 0.0192415 secs; total 160.568 secs 538 -> 16196651398204425343126936097310356120271733322915212745417863402087632834855106079328035191739382581211211313371102200810776477533999356496876819775145135505886294417405826796677815167202187231226380 : 0.042992 secs; total 160.611 secs 540 -> 7457024203430025045000252745986378288257798055712938914631895114617942193302064491548616645193114952485328586549524995017851549385933748399627674884768699761301176072240176523890 : 2386.21 secs; total 2546.82 secs 546 -> 906090109321101729491726881541053979178972487361799219712590335175522483559909203865941393722108527136430394867372834736293604286304634557871670431017044124429073624820 : 420.93 secs; total 2967.75 secs 550 -> 197490094160544395396549305368226880292622861915466587917449780781018793491009064512769135161880021395235171684350281153672504648514849424450310672780491899440 : 0.067318 secs; total 2967.82 secs 552 -> 38282359610231628282831498788938209861245275810769012526965243452818895402093285406329236081174607890226405739681916179312332654073751190321978668248231301342117758090838 : 5.12497 secs; total 2972.94 secs 554 -> 23771229990533688222255135237644396999826197982957529226466440286239303888103093086197321252728038657983679097634246530566372011748924965172231144135340117582179405787427960559356 : 0.0090439 secs; total 2972.95 secs 556 -> 4857603802034637317375127547951669382523516071838990950169026514282756467102928060519727335056584226078970170169997806868256439476020543753338168433279838045467101152377717213736949622910183068526164222761690 : 0.0185084 secs; total 2972.97 secs 560 -> 272208909506156925953839876645187050133348076516401932496369349850650627386265629609139875758757383483902068443401226921109116925430747778344298173444558100717973475040 : 4.8772 secs; total 2977.85 secs 574 -> 1275435375517115512897300542185833966066491035597727224272604123011644504993482909778354167419041389947805448830560987552251025577696795933590399032890985110764978616637169064008224056 : 0.247191 secs; total 2978.1 secs 576 -> 298179859257470177908263364628436856057468391489349634019593712133109176917547027197861721857175410707099262876487528771785466600654551807115456199471239220370627625375591985253094 : 5.12889 secs; total 2983.22 secs 580 -> 21873582157258215963234358946291447731672986994580045624239305366301962394860230998609841412492534091851025222512678649387067473981514527023124860468541170665880381031035147283606967668817905144610277505238789780220 : 0.102718 secs; total 2983.33 secs 582 -> 4016161829994147748845913407152041076046399031071578083952592814719712711657040785664701106746617570126732355008201518684816875880016705765815939547243584178063162124164510986182282668 : 30.3593 secs; total 3013.69 secs 584 -> 45236247400020666480545468726212341723354946922526038432436575755942047488070730224099526255539687116442535538297431957422886242989193405914582974720765434432095661188486323999254703593523324436166436 : 0.0333996 secs; total 3013.72 secs 590 -> 6889383848839915217298949398094374036081630617210157374425520209355276133085552242919621853522810182287592498800627273029020556556839621250456907629276436543675881587810593393893172922948383090 : 0.220044 secs; total 3013.94 secs 604 -> 184620358713498811801944896187295122445956608695311712336954912905293602586260534536882742021739645300399687912768638069331331947240622029962453788103384878521654162484119512065511477948572693795158016 : 0.0051752 secs; total 3013.94 secs 606 -> 89109072215348433817469024454151710803903802285944117425044464435650940985590337051487256308784368328494208624852157573845648189779542064325949845825271360650274235846701393496355129321994 : 162.689 secs; total 3176.63 secs 612 -> 1321055404144574513003582655172280650647793869743403412906828920247108131151252250102075322103991976505400372137998390669329045466134906760071523081549148156083653841941857156040536507968 : 38.5042 secs; total 3215.14 secs 616 -> 9666621445450430777433009930239370627075507536582044785966540594215112757983327047885354306763860678983983146559225232690773501091711583869809931872697919620408682024744046390333114740 : 0.56366 secs; total 3215.7 secs 624 -> 5787931117691527449382170368040556978905353865643472593867302507531631417320117806460428790429845594369595233599226031846058723763606389486025690470528950041577838749110533253673486411705923136 : 111.509 secs; total 3327.21 secs ``` ``` #include<iostream> #include<set> #include<vector> #include<array> #include<chrono> #include<map> #include<boost/multiprecision/cpp_int.hpp> #include<thread> #include<future> using namespace boost::multiprecision; using namespace std; int S(set<int> &x) { return x.size() ? *x.begin() : 0; } void M(vector<array<int1024_t, 2>> * f, vector<int> * nr, vector<array<int1024_t, 2>> * q, int x, int ct, int nt, promise<int1024_t> * pr) { int1024_t m = 0; for (size_t i = 0; i < f->size(); i++) { if (i % nt == ct) { array<int1024_t, 2> h = { 1,1 }; for (int j = 0; j < 2; j++) { int1024_t c = (*f)[i][j]; // cout << "c: " << c << endl; int k = 0; while(c > 0) { if (c % 2) { h[j] *= (*nr)[k]; } //cout << k << " " << c << " " << (*nr)[k] << " " << c % 2 << " " << h[j] << endl; c >>= 1; k++; } //cout << "h: " << h[j] << endl; // cout<< "-"; } // cout<<endl; for (auto j = q->begin(); j != q->end(); j++) { int1024_t g0, g1, f0, f1; int64_t f2, f3; g0 = h[0] * (*j)[0]; g1 = h[1] * (*j)[1]; //cout << g0 << " " << g1 << " " << h[0] << " " << h[1] << " " << (*j)[0] << " " << (*j)[1] << endl; vector<int1024_t>d; vector<int64_t>e; if (g0 > g1) { swap(g0, g1); } f0 = g0; f1 = g1; while (f0 > 1 && (f0 >= INT32_MAX / 2 || f1 >= INT32_MAX / 2)) { int1024_t n = f0; d.push_back(f1 / f0); f0 = f1 % f0; f1 = n; } if (f0 > 1) { f2 = (int64_t)f0; f3 = (int64_t)f1; while (f2 > 1) { int64_t n2 = f2; e.push_back(f3 / f2); f2 = f3 % f2; f3 = n2; } } f2 = 0; f3 = 1; for (auto k = e.rbegin(); k != e.rend(); k++) { int64_t n2 = f3; f3 = *k * f3 + f2; f2 = n2; } f0 = f2; f1 = f3; for (auto k = d.rbegin(); k != d.rend(); k++) { //cout<<f[0]<<" "<<f[1]<<" "<<(*j)<<endl; int1024_t n = f1; f1 = *k * f1 + f0; f0 = n; } int1024_t K = (x * f0 + g0 / 2) / g0; int1024_t o = min(abs(f1 * x - g1 * K) * g0, abs(f0 * x - g0 * K) * g1); //cout << x << " " << f0 << " " << f1 << " " << g0 << " " << g1 << " " << K << " " << o << endl; //cout<<o<<" m "<<m<<endl; if (!m || o < m) { m = o; } } } //cout<<endl; } pr->set_value(m); } int main() { int nt = 8; double tt = 0; for (int x = 36; x < 1000; x++) { auto start = chrono::system_clock::now(); vector<array<set<int>, 2>>v(x - 1), nv; vector<pair<array<int1024_t, 2>, int>>r, s; vector<array<int1024_t, 2>>f; map<int, int>c; set<int>y; int1024_t t = 1; int mp = 0; for (int i = 2; i < x; i ++) { if (!v[i - 1][0].size()) { for (int j = 1; j < (x - 1) / i + 1; j++) { v[i * j - 1][0].insert(i); v[x - i * j - 1][1].insert(i); } if (x % i == 0) { t *= i; } else if (!mp) { mp = i; } } } if (v[0][1].size() == 1) { continue; } for (auto i = v.begin(); i != v.end(); i++) { bool e = 0; if ((*i)[0].size()) { for (auto j = (*i)[0].begin(); j != (*i)[0].end(); j++) { if (t % *j == 0) { e = 1; break; } } } if (e) { continue; } if (S((*i)[0]) != mp) { nv.push_back(*i); } for (int j = 0; j < 2; j++) { for (auto k = (*i)[j].begin(); k != (*i)[j].end(); k++) { auto ci = c.find(*k); if (ci == c.end()) { c.insert(make_pair(*k, 1)); } else { ci->second++; } //cout << *k << " "; } //cout << "-"; } //cout << endl; } v = nv; map<int, int>ns; vector<int>nr; vector<array<pair<int1024_t,vector<int1024_t>>,2>>bs; int cn = 0; for (auto i = v.begin(); i != v.end(); i++) { if (((*i)[0].size() == 1 && (*i)[0].size() == 1 && c[*((*i)[0].begin())] < 3 && c[*((*i)[1].begin())] < 3)) { int z = *((*i)[0].begin()); if (z != *((*i)[1].begin())) { z *= *((*i)[1].begin()); }; if (!y.count(z)) { y.insert(z); //cout<<z<<endl; } } else { array<pair<int1024_t,vector<int1024_t>>,2>b; for (int j = 0; j < 2; j++) { b[j].first = 0; for (auto k = (*i)[j].begin(); k != (*i)[j].end(); k++) { auto ni = ns.find(*k); int1024_t c; if (ni == ns.end()) { ns.insert(make_pair(*k, cn)); nr.push_back(*k); c = ((int1024_t)1) << cn; cn++; } else { c = ((int1024_t)1) << ni->second; } b[j].second.push_back(c); b[j].first |= c; } } bs.push_back(b); } } sort(bs.begin(), bs.end(), [](array<pair<int1024_t, vector<int1024_t>>, 2>&x, array<pair<int1024_t, vector<int1024_t>>, 2>&y) { return min(x[0].first, x[1].first) < min(y[0].first, y[1].first); }); //cout << "bs size: " << bs.size() << endl; //for (auto i = bs.begin(); i != bs.end(); i++) { // for (auto j = 0; j < 2; j++) { // int k = 0; // int1024_t c = (*i)[j].first; // while (c > 0) { // if (c % 2) { // cout << nr[k] << " "; // } // c >>= 1; // k++; // } // cout << "-"; // } // cout << endl; //} //cout << endl; //for (auto i = v.begin(); i != v.end(); i++) { // for (auto j = 0; j < 2; j++) { // for (auto k = (*i)[j].begin(); k != (*i)[j].end(); k++) { // cout << *k << " "; // } // cout << " - "; // } // cout << endl; //} r.push_back(make_pair(array<int1024_t, 2>{((int1024_t)1) << ns[mp], 0}, 0)); // cout << "v size: " << v.size(); //int ii = 0; bool D = false, D2 = false; while (!D && r.size() > 0 && r.size() < 40000000) { // memory issues above this //cout << "ii: " << ii << endl; //for (auto j = 0; j < 2; j++) { // for (auto k = (*i)[j].begin(); k != (*i)[j].end(); k++) { // cout << *k << " "; // } // cout << " - "; //} //cout << endl; if (D && !D2) { D2 = true; } s.clear(); for (auto i = r.begin(); i != r.end(); i++) { // for (auto j = 0; j < 2; j++) { // int k = 0; // int1024_t c = (*i).first[j]; // while (c > 0) { // if (c % 2) { // cout << nr[k] << " "; // } // c >>= 1; // k++; // } // cout << "-"; // } // cout << endl; for (; i->second < bs.size(); i->second++) { bool e = 0; // Check bitmap for left or right set of primes if (!((i->first[0] & bs[i->second][0].first) || (i->first[1] & bs[i->second][1].first))) { break; } } if (i->second == bs.size()) { // Reached the end for this path D = true; f.push_back(i->first); } else if (!D) { for (int j = 0; j < 2; j++) { for (auto k = bs[i->second][j].second.begin(); k != bs[i->second][j].second.end(); k++) { //cout<<k<<" "<<*l<<endl; if (!(i->first[0] & *k || i->first[1] & *k)) { array<int1024_t, 2>b{ i->first[0], i->first[1] }; b[j] |= *k; bool e = true; if (D2) { for (auto l = f.begin(); l != f.end(); l++) { if ((*l)[0] & b[0] == (*l)[0] && (*l)[0] & b[1] == (*l)[0]) { e = false; break; } } } if (e) { s.push_back(make_pair(b, i->second + 1)); } } } } } //cout << endl; } //cout<<"s size: "<<s.size()<<endl; if (!D) { sort(s.begin(), s.end()); s.erase(unique(s.begin(), s.end()), s.end()); r = s; //cout << x << ": " << "r size: " << r.size() << endl; } //map<size_t, int>rs; //for (auto j = r.begin(); j != r.end(); j++) { // size_t js = j->first[0].size() + j->first[1].size(); // auto k = rs.find(js); // if (k == rs.end()) { // rs.insert(make_pair(js, 1)); // } // else { // k->second++; // } //} //for (auto k = rs.begin(); k != rs.end(); k++) { // cout << k->first << ": " << k->second << endl; //} } if (!D && r.size() <= 40000000) { continue; } //size_t ms = 0; //for (auto i = r.begin(); i != r.end(); i++) { // size_t cs = i->first[0].size() + i->first[1].size(); // if (cs < ms || !ms) { ms = cs; } //} size_t w = y.size(); cout << x << " -> " << f.size() << " " << w << " " << (f.size() * ((size_t)1 << w)) << endl; if (D && w <= 25 && (f.size() * ((size_t)1 << w)) < (1 << 30)) { vector<array<int1024_t, 2>>q(((size_t)1) << w); //for (auto j = t.begin(); j != t.end(); j++) { // cout << "t:" << *j << endl; //} for (int j = 0; j < (int)(1 << w); j++) { q[j] = { 1,1 }; auto l = y.begin(); for (int k = 0; k < w; k++, l++) { q[j][(j & (1 << k)) / (1 << k)] *= *l; } q[j][0] *= t; //cout << j << ": " << q[j][0] << " " << q[j][1] << endl; } vector<thread> ts(min(f.size(), (size_t)nt)); vector<promise<int1024_t>> ps(ts.size()); for (size_t i = 0; i < ts.size(); i++) { ts[i] = thread(&M, &f, &nr, &q, x, i, nt, &ps[i]); } int1024_t m = 0; for (size_t i = 0; i < ts.size(); i++) { ts[i].join(); int1024_t o = ps[i].get_future().get(); if (!m || o < m) { m = o; } } double rt = (double)((chrono::duration<double>)(std::chrono::system_clock::now() - start)).count(); tt += rt; cout << x << " -> " << m << " : " << rt << " secs; total " << tt << " secs" << endl; } else if (D) { double rt = (double)((chrono::duration<double>)(std::chrono::system_clock::now() - start)).count(); tt += rt; cout << x << " skipping because too many to check : " << rt << " secs; total " << tt << " secs" << endl; } else { double rt = (double)((chrono::duration<double>)(std::chrono::system_clock::now() - start)).count(); tt += rt; cout << x << " skipping because search got too broad : " << rt << " secs; total " << tt << " secs" << endl; } } } ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~263~~ ~~407~~ ~~544~~ 536 bytes A port of [xash's J answer](https://codegolf.stackexchange.com/a/230542/64121), if this ends up getting the most terms, the bounty should definitely go to them. Uses functionality added to `pow` in 3.8 to compute modular inverses. Using the bits of integers to store sets of primes resulted in a quite large improvement, this gets to 204 on TIO. ``` n=int(input()) Q=[] P=k=r=1 while k<n:Q+=P%k*[k];P*=k*k;k+=1 D=[int(''.join(str(+(a%p<1))for p in Q)[::-1],2)for a in range(n)] R=[(0,0,-1)] for i in sorted(range(1,n),key=lambda x:-((P:=D[x]|D[n-x])&-P)): N=[];F=D[i];O=D[n-i] for p in R: A,B,c=p if F&A or O&B:N+=p,;continue d=F&c;w=1 while d: if d%2:N+=(A^w,B,c^w), d>>=1;w*=2 d=O&c;w=1 while d: if d%2:N+=(A,B^w,c^w), d>>=1;w<<=1 R=N for v,w,_ in R: x=y=1 for p in Q: if v%2:x*=p if w%2:y*=p v>>=1;w>>=1 r=min([n*pow(x,-1,y)%y*x-n,r][:r]) print(r) ``` [Try it online!](https://tio.run/##hVHPa8IwFL73r8hFTdp0WAdjpD5BEY9avYY4OltnVk1DrLaF/e8usbjBLruEvPf94L3v6bY6lOr5VZvbTYFUFZZKXypMiLcGLrwECjAQefVBHnNUjBVbB5D0Cp8XIk58KPwiLgJLmAN36sHg6bOUCp8rgwOc9vQ4ImRfGqSRVGhNOGNhJOjo3ktdz6TqI8eKCG8DHA/pkIaRLRwuHX4uTZVnuKNFVBFa5C0c09N7lqKGhRgnDOa8EV9zrsJGkH6YEMI8tLTzxwsLSRGvwIFSeOhnlo2loCmd0R1o@5N7tOhPkUVX/RlbBqBpvCtVJdUlt3AGi/4uru2iCHVZZE7vZFlv5Ph4uq2d27Ym1CHZZAJRXPswustX/8rpzBr8lY/HTrOB5T2QK63p22P4BlqH/YbLujWu1rDxH0vVtmq76tpZutdDBk72TFz5uqxxYzOnLem1fhMqagRnRhBPG3dRQ2636GX0DQ "Python 3.8 (pre-release) – Try It Online") A bit more readable: ``` def f(n): primes = [] P = k = 1 while k<n: if P%k: primes.append(k) P *= k*k k += 1 divs = [ int(''.join(str(+(a%p==0))for p in primes)[::-1], 2) for a in range(n) ] np = len(primes) partitions = [(0, 0, 2**np-1)] for i in sorted( range(1,n), key=lambda x:bin(divs[x]|divs[n-x])[::-1].index('1'), reverse=True ): new_partitions = [] factors = divs[i] other_factors = divs[n-i] for p in partitions: set_a, set_b, r_primes = p if factors & set_a or other_factors & set_b: new_partitions += p, continue for i, v in enumerate(bin(factors & r_primes)[2:][::-1]): if v=='1': w = 1 << i new_partitions += (set_a^w, set_b, r_primes^w), for i, v in enumerate(bin(other_factors & r_primes)[2:][::-1]): if v=='1': w = 1 << i new_partitions += (set_a, set_b^w, r_primes^w), partitions = new_partitions result = float('inf') for px, py, _ in partitions: x = y = 1 for p in primes: if px % 2: x *= p if py % 2: y *= p px //= 2 py //= 2 result = min(result, n*pow(x,-1,y)%y*x-n) return result ``` [Try it online!](https://tio.run/##xVVNc6JAEL37K@biCqZNYGZCkIr7G3LYm2UsjOPKqgOFqFDZ/Hb3DRgI4lbtbamMPdMfr/s1zSQpsnWshZ@k5/NSrdjK0nbQY3iSNNqpPZuw6aw8v2C7wXLL02kdbRXbPOvK2TzRir30N8El8D5MEqWX1sauHV7YEBDDTa3YsLtPvGV0LHM1aDqzBoP7X3GkrX2WWndW2E8mE8e2V3HKEtgviexpEIzcGTHeZDIuoXFJQ/1TgVJpqXjoBHm2SluX8IpsmGZRFsW6LMJyiOGPD4c6Gbl2FWcwI4O5j9NMLa06WZXDJW1Tw0wVk224WyxDlgcLUDD8pvnsdyn1KJ9dyr6P9FLl1sAdfIlO1VGlezX5kR5UqbSbLmt1mrernTW0w7csTo2yTBM1ljhbq3R@ZdejLx5NV2vwJql59iqbh1SKBbF0Xs9H0nLDFHym@VbFMCC381eGRRv/BjlMR0Idp7dYZ5G@dOZr@RGxo2Gg9GGn0jBTlul8k/SzZnvKg1nVfrtbAwgcJxO8kK6pHHzzCbDnZxbdNHcZWGUTXk@d1r2ebPpHDtft@59MLjwMoZtMWsPZBulVw70/bDPYVts4xDce6dXArr@wJCeWFMTmfxvFHJFFfQ21J7csJrgexyRnfca7PcjNddQZ3qS47V10vQH88DBhvK0srpQ13x1eZHUgpodJfLJyGrlU2P1imI8ud1SqskOqL0FnddKGqkeck5AkPJIePXrkSfI8enLoCb8@@R75Po05jSWNPXIdBwvS5VhG@uRy6LgkV0ACypWwSSNhf4T0oPegA5Y7xh443JHEXQcLe2BwYHBUwoVZOCOWS8hH6FEVBwYHBvegQ2Xcx9k3EmdUxw3m2CeB@oQDRqhRAF8AXwBboD7BzR4@qFOAr5CQ0rDHHjkEeIsnnEFb@JCgLIArgSlRr3TM3ifpYg9cCUzJjYROOL1efY2jt@YtY2jwn2Y1eI8C8cFG39n7yorsjwFhPg/7dXkH2@c/ "Python 3.8 (pre-release) – Try It Online") After letting this run *a bit* longer than 60 seconds locally, here are some more results: ``` 16 -> 2184 22 -> 3521210 34 -> 47563752566 36 -> 12913165320 46 -> 21653939146794 56 -> 172481165966593120 64 -> 808852298577787631376 66 -> 91307018384081053554 70 -> 1172783000213391981960 76 -> 26214699169906862478864 78 -> 27070317575988954996883440 86 -> 92274830076590427944007586984 88 -> 3061406404565905778785058155412 92 -> 549490357654372954691289040 94 -> 38646299993451631575358983576 96 -> 50130345826827726114787486830 100 -> 35631233179526020414978681410 106 -> 200414275126007376521127533663324 112 -> 1022681262163316216977769066573892020 116 -> 199354011780827861571272685278371171794 118 -> 5084808394825008411597027854612265320 120 -> 33088145229978950006171841905081799893430 124 -> 9132534211053896168120244510786592061314796 130 -> 1010223786859974709684811231603116447862010 134 -> 918536092326116746940802093225005168208856 142 -> 326415290503067481481262636553276300760538971418633970 144 -> 12519236270374172120152530393181563366703899726 146 -> 30102196727419035397352263664971701624550 154 -> 250086121511153463601017992836053431027953173230156 160 -> 16823726350582448550419008635093980344211195490 162 -> 971838598937769539765770921839883750903640741790 186 -> 1794082996332254346315702546582790195234663527026144577149550 190 -> 100043328863825836942691086460363243931180087197722910850 196 -> 17018920629980040075969105511895180448985253900154238700 204 -> 481578279081960788203960306279407682980396228758026204933056959715840 210 -> 29225782603870300544827882241040291898185518589118372486421537923611871170 216 -> 440200183843647241078327939248364204862519711650712622914040841410 218 -> 67518017451793349875086631136663331002689144202850547609381398525979202451060 220 -> 1459104994350090197385240721881419804872579186868731078959002070 222 -> 398425392772309365488991662748906112633693445300311983234641390568 232 -> 907378346149256277304071914319955007121813704909147483268086111540 238 -> 45894107313965996638570818463974089099761314947922544200331971462236682 246 -> 127209574731840814488699664382213489925455290327133090193663688070010069772464 248 -> 87349027419299768189875606566564845285333219860920999198422625577318053831430260 250 -> 1274769952223858733770020211602403840979999894289407226855668118167657960120 256 -> 211337714604794757725712768305031523837613606852887423808080138155983960657486438548840080 260 -> 611379532364397862318258986724238889055579879595343134082300581949384481717350 262 -> 457385261010485284248495193082983704923527433029112880026848488309914263938871758209640697245248 268 -> 3837924875435446453632171348188362753950788432477364059540845274930576542794383781497646020913032 276 -> 690516469573823892560050501225021813072395907134207867385994632898243111919015752071367994 280 -> 47182555594339904819679927877406287035566782878354969819901299764693418800067961552340 286 -> 120610684017694120228701154065517023464640987099534560151170016560718941441263176114 288 -> 138971473108541248222606578801479253148138919955516661540809691054255010511185699956086224052870 292 -> 185675662432708092090998266897578702332183677920758773231493308055529123987258619622978284717475820 296 -> 528072426832989018489058277937146939019285808979376200830352699489792774867918795228285244 298 -> 7925959560314994619176238662647274773767908511981401648794904625493728870549039264807892534696970055800 300 -> 3830358397632282878932144419312617888493673029003334276706856317887318564286779642788172700903966820 302 -> 40657328466375053173917761727511056770288784946750010931930738501228836738754637506437259099070010911712995558 ``` [Answer] # [Python 3](https://docs.python.org/3/), 97 bytes ``` f=lambda k,a=1:all(gcd(a,x)+gcd(a+k,x)>2for x in range(a,a+k))and a or f(k,a+1) from math import* ``` [Try it online!](https://tio.run/##JY7bCoMwEETf/Yp9zFYpTQt9KOi/bE2iwVxkk4J@fbq0AwMHDgOzn3XN6dF83DNXKGfppNdiK9v5w8XnFHz0VembBJsbA8W3IdgGGvWLQlDLbBQNB/Y/6DfB6e4ywwE@AVNarHgRiJQMEIhySva9xs5xjhCprvB/cGk7@1SVU/qJ2L4 "Python 3 – Try It Online") Might reach the recursion limit, so adjust it with `sys.setrecursionlimit`. In TIO link it is set to 10000 in Header section. [Answer] # [Ruby](https://www.ruby-lang.org/), 60 bytes ``` ->k{1.step.find{|x|(x..x+k).all?{|y|y.gcd(k+x)+y.gcd(x)>2}}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y672lCvuCS1QC8tMy@luqaiRqNCT69CO1tTLzEnx766prKmUi89OUUjW7tCUxvCrNC0M6qtrf1foJAWbWgWywWijYwgtLFJrIKyQmKxQmbafwA "Ruby – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 17 bytes ``` λ?+₌ṡ"Ẋvġ2ẇ‹v∑Π;ṅ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%CE%BB%3F%2B%E2%82%8C%E1%B9%A1%22%E1%BA%8Av%C4%A12%E1%BA%87%E2%80%B9v%E2%88%91%CE%A0%3B%E1%B9%85&inputs=16&header=&footer=) -3 bytes thanks to lyxal Using the same approach as my Jelly answer. --- You can find a more in-depth walk-through and explanation of my solution on my YouTube channel [here](https://www.youtube.com/watch?v=ipuMUs0IOmg). However, the explanation there is outdated. --- ``` λ?+₌ṡ"Ẋvġ2ẇ‹v∑Π;ṅ Full Program; start with `k` on the stack and as the input λ?+₌ṡ"Ẋvġ2ẇ‹v∑Π;ṅ Function: given `a`: ? Push the input, `k` + Sum with `a`: `a + k` ₌ṡ" In parallel, apply inclusive range and pair The TOS is now [a, a + k] The second element is [a, a + 1, a + 2, ..., a + k] Ẋ Cartesian Product vġ GCD of each pair 2ẇ Slice into blocks of length 2 ‹ Decrement v∑ Sum of each pair Π Product ṅ Find the first integer satisfying this ``` [Answer] # [R](https://www.r-project.org/), ~~106~~ ~~102~~ ~~100~~ 93 bytes ``` function(k,`^`=function(x,y)ifelse(r<-x%%y,y^r,y)){while({b=0:k+T;sd(T^b*(T+k)^b<2)})T=T+1;T} ``` [Try it online!](https://tio.run/##K/qfWp5v@z@tNC@5JDM/TyNbJyEuwRbOrdCp1MxMS80pTtUostGtUFWt1KmMKwIKalaXZ2TmpGpUJ9kaWGVrh1gXp2iExCVpaYRoZ2vGJdkYadZqhtiGaBtah9SCrNAwNNP8DwA "R – Try It Online") This won't win any fastest-code bounties, but at least runs happily on TIO for the first test-case. A lot of the code is used-up writing a `gcd` function (here assigned to the `^` operator for golfing motives), since 'greatest common divisor' isn't a built-in function in base [R](https://www.r-project.org/). [Answer] # [Julia 1.0](http://julialang.org/), ~~60~~ ~~59~~ 51 bytes ``` k->(a=1;while any(gcd.((a+k)a,a:a+k).<2) a+=1end;a) ``` [Try it online!](https://tio.run/##yyrNyUw0rPifZvs/W9dOI9HW0Lo8IzMnVSExr1IjPTlFT0MjUTtbM1En0QpE69kYaSokatsapualWCdq/i8oyswrycnTSNMwNNPU5EJwjYw0Nf8DAA "Julia 1.0 – Try It Online") Thanks to MarcMush for a saved byte and to Glen O for further -8. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~101~~ ~~95~~ 90 bytes ``` f=(k,a=0)=>[...Array(k+1)].some((_,i)=>(g=(x,y=a+i)=>y?g(y,x%y):x)(a)*g(a+k)<2)?f(k,++a):a ``` [Try it online!](https://tio.run/##FcxBCsIwEEbh0wj/ODFYFy6KsXgOERlqEmpqI4lIcvpYl48P3lO@ksc0vT@7JT5sa84gKDF7Muer1vqSklQE7uimc3xZ4K6m1eANiqpG@F918KiqbCr1hSC09RAOdDrQ4NYds1AvbYxLjrPVc/Rw6I5E7Qc "JavaScript (Node.js) – Try It Online") -5 thanks to Arnauld # Explanation ``` f = ( // Define a function f k, // Taking a parameter k a = 0 // And initialise a to 0 ) => [ ...Array(k + 1) ].some( // If any value i in the range 0 to k satisfies the following: (_ , i) => // Taking a useless variable _ and the iteration i (g = ( // Define a helper gcd function g x, // Taking a parameter x y = a + i // And initialising y to a + i ) => y ? // If y is nonzero g(y,x%y) // Take the gcd of y and x modulo y : x // Otherwise yield x )(a) // And call that on a * // Multiplied by g(a + k) // That called on a+k < 2 // Is less than 2? ) ? f(k,++a) // If so (at least one is invalid), then increment a and try again : a // Otherwise (all are valid) yield a. ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 23 bytes ``` λD→a?+:£ṡƛ¥ġn←aġ+2>;A;ṅ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%CE%BBD%E2%86%92a%3F%2B%3A%C2%A3%E1%B9%A1%C6%9B%C2%A5%C4%A1n%E2%86%90a%C4%A1%2B2%3E%3BA%3B%E1%B9%85&inputs=16&header=&footer=) -1 byte thanks to @cairdcoinheringaahing [Answer] # Julia 1.6, 941 bytes **As it turns out, the numbers provided in the question aren't the "optimal" ones. The code provided below makes no attempt to be golfed (although I may make a pass at golfing it down soon), but rather seeks to find the smallest possible \$a\$ for any given \$k\$, as efficiently as possible.** The code here begins with the approach noted by [Xash](https://codegolf.stackexchange.com/a/230542/21439) (obviously, converted to Julia), but makes some tweaks to improve the optimisation. ``` using Primes function g(k) p=primes(k) Q=p[gcd.(p,k).>1] q=big(prod(Q)) p=setdiff(p,Q) p2=big.(p) l=falses(k-1) L=copy(l) for i=Q l[i:i:end].=true end r=p.>0 ~p=prod(p) n=(q*~p2)^2 while any(r) L.=l for i=1:length(p) if r[i] L[p[i]:p[i]:end].=true else L[k%p[i]:p[i]:end].=true end end if all(L) L1=copy(l) for i=1:length(p) if r[i] L1[p[i]:p[i]:end].=true end end L2=copy(L1) pn=p[.!r]; r2=pn.>0 while any(r2) L2.=L1 for i=1:length(pn) if r2[i] L2[k%pn[i]:pn[i]:end].=true end end if all(L2) P0=q*~p2[r] P1=~big.(pn[r2]) m=(k*invmod(-P0,P1)%P1)*P0 if m<n n=m end end r2.chunks.-=1 end end r.chunks.-=1 end n==(q*~p2)^2 ? Inf : n end ``` [Try it online!](https://tio.run/##jVRNj9owEL3vr3BXWslBJopNyAdd03OlHMI5SiUKCbgJxmug7V7463TGWZak1aJGGs@85/HMs2P5x6lVS/77cqlPenVUe002tPEeCDGyEIxMGJkyEjPCORggjnHKiIBYgJ8APwEuBB8CF0I8xVUwFwEXAY7Bx8DFwCXgE/Ap1gmwaIBVAwdT7INQIJy4li7CiRCHKXJT5CLMw@o8drJwNsHZ1A3IuR5pWrrdmML4zw3GC4g3q7VPDWs8f86Re5Hf1YYau1/Thddt/1Ad16quIWvhCIEpsAhBK@tle6gOtBlzxJlc7c0rbTGu95YouYAI8go1U7NKr0tfHu2pAhIAjFYafx5AcAZl2NWV1ZK@jM5GeN8EoF9b1VZkqV@p9Vy1zJetC7oWfNZWenPcdmvxUzWxhSrfECwoDMCZGwYi8KtgA73M5ulerhN989Bo2bY0uzbOeO8A7in8VyMuvifz1rQfZaJrmPFrZaPht/qfbPn5jbBCGt0dMn690xQ3NZnwZcbf4d@ytdfTicrFUDoWwJPTTr/@YAN94cP4eo6i3ycPpLsFhe23yrk8dxdQF1aU/QU7SZuR0j93cI/GecBy7j2BjfJgqH73rAfatdz9h0Yr/NX2pJuDP5b8g/tghykdreXtOpMv5KuuyYzoB5i84Dk3suARPCL4yoRgEIdgU7AIcAQ@DsAiFicsiViSsFSwNGRpxHgQlMRYpY@tpg17JOM5eWT4cnlY/g8 "Julia 1.0 – Try It Online") - note that, because the Primes package cannot be loaded on TIO, I have hardcoded the primes up to 200; this does not provide any substantive speed boost, as most of the time is spent in the loops. Here are the smallest \$a\$ values for given \$k\$ values... ``` 16 -> 2184 22 -> 3521210 34 -> 47563752566 36 -> 12913165320 46 -> 21653939146794 56 -> 172481165966593120 64 -> 808852298577787631376 66 -> 91307018384081053554 70 -> 1172783000213391981960 76 -> 26214699169906862478864 78 -> 27070317575988954996883440 86 -> 92274830076590427944007586984 88 -> 3061406404565905778785058155412 92 -> 549490357654372954691289040 94 -> 38646299993451631575358983576 96 -> 50130345826827726114787486830 100 -> 35631233179526020414978681410 ``` TIO was able to complete this set in 57 seconds - The time required grows rapidly (indeed, exponentially) with \$k\$, though, so the next Erdos-Woods number, 106, takes more than 60 seconds on TIO on its own. [Answer] # [Husk](https://github.com/barbuz/Husk), 17 bytes ``` ḟSμΛo←§Y⌋¹⌋³…)+⁰N ``` [Try it online!](https://tio.run/##yygtzv7//@GO@cHn9pybnf@obcKh5ZGPeroP7QQRmx81LNPUftS4we////@GZgA "Husk – Try It Online") ``` ḟ # find the first x N # in the infinite list of integers # that satisfies: Sμ )+⁰ # hook: apply lambda function with args x and x+input Λ # are all results truthy … # in range arg1 to arg2 (so from x to x+input): o← # one less than §Y # maximum of ⌋¹ # GCD of each element and arg1 ⌋³ # and GCD of each element and arg2 ``` ]
[Question] [ # Introduction A while ago a lost SO user posted a question here and its now been deleted but I think it would make a good challenge so here it goes... # Challenge Write a full program or function that takes two strings and checks whether any permutation of the first string is a sub-string of the second string. # Input Two strings, a string and a sub-string to test for (you may choose the order). # Output: A truthy value if the string contains any permutation of the sub-string. A falsey value if the string does not contain any permutations of the the sub-string. The test is case sensitive. # Examples/Test cases ``` sub-string string input d!rl Hello World! output truthy input Pog Programming Puzzles & Code Golf output falsey input ghjuyt asdfhytgju1234 output truthy ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes ``` sp ``` [Try it online!](https://tio.run/nexus/brachylog2#@19c8P@/UmJxSlpGZUl6VqmhkbGJ0n@l9Iys0soSJQA "Brachylog – TIO Nexus") ### Explanation ``` Input variable = "Hello World!", Output variable = "d!rl" (?)s Take a substring of the Input variable p(.) It is a permutation of the Output variable ``` [Answer] # JavaScript (ES6), 77 bytes ``` (s,t)=>t&&[...t.slice(0,s.length)].sort()+''==[...s].sort()|f(s,t.slice(1)) ``` Returns 1 or 0. **Snippet** ``` f= (s,t)=>t&&[...t.slice(0,s.length)].sort()+''==[...s].sort()|f(s,t.slice(1)) console.log(f('d!rl','Hello World!')) //1 console.log(f('Pog','Programming Puzzles & Code Golf')) //0 console.log(f('ghjuyt','asdfhytgju1234')) //1 ``` [Answer] ## Python 2, ~~67~~ 66 bytes Takes input as two strings, substring first. ``` a=sorted lambda s,S:a(s)in[a(S[n:n+len(s)])for n in range(len(S))] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` œåZ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6OTDS6P@/09RLMrh8kjNycnXUQjPL8pJUQQA "05AB1E – Try It Online") -1 byte thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna). Explanation: ``` œåZ 2 inputs œ permutations of the first input å Is each of the in the second input? Z Take the maximum of the resulting boolean list ``` [Answer] # Japt, ~~10~~ ~~7~~ 6 bytes ``` á d!øV ``` [Try it online](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4SBkIfhW&input=ImQhcmwiCiJIZWxsbyBXb3JsZCEi) ``` á d!øV :Implicit input of sub-string U & string V á :Permutations of U d :Any !øV : Contained in V ``` [Answer] # Java 8, ~~266~~ 244 bytes ``` import java.util.*;Set l=new HashSet();s->p->{p("",p);for(Object x:l)if(s.contains(x+""))return 1>0;return 0>1;}void p(String p,String q){int n=q.length(),i=0;if(n<1)l.add(p);else for(;i<n;)p(p+q.charAt(i),q.substring(0,i)+q.substring(++i,n));} ``` **Explanation:** [Try it here.](https://tio.run/nexus/java-openjdk#jZBBj9owEIXv/IrZHCqbBANtTw1Eaiu1e0FFolIPVQ8mcRIjxzb2eNks4rdTh7LaarnswfbM0/jz8ztPp/CzFWC5Qw8HiS1Mp@Ntj2JSmqBxDNwJwNb4Yed4aYdhMHUUBHDtD8KNRrKzJqo7/sBZQKnYOH9Fuh2pgy5RGs2@XYt8VCruPayOI4CNQFBLLQ5wz30bO0JvkADPVxcbdFI32ev@izFKcF0U5TJOA/hJYSfF0ZIkySzNa@PIj@1OlAiPnxSVNfGsNBq51J48pklCqRMYnIZ5Mcuv5ayY56dbK3lcD0ZWYMm/x8Fm12JPj1Ij6OWeKaEbbAnN5HKWx/f0Yk4V41VFoh2hYs6Dp1wudE4tsemelS13n5FImu2ZD1t/QZJZJmn6v5CmMtOU3jqLtmzYKlmCR47xuJjs4hevPn//AU6Pl3hW0MEShtBXMe6LtOk9io6ZgMzGaVSadKxk3FrVk@ReKGXgl3Gqukvos1rdORWjewtg7UzjeNcNMa3D05MSHt7BV1MJ@G5U/cJcm@aNSO6ruu2x2YX5@w8fXwhNuws9XiGn0el8/gs) ``` java.util.*; // Required import for Set and HashSet Set l=new HashSet(); // Class-level Set s->p->{ // Method (1) with two String parameters and boolean return-type p("",p); // Put all permutations in the class-level Set for(Object x:l) // Loop over the permutations: if(s.contains(x+"")) // If the input String contains one of the permutations: return 1>0;//true // Return true // End of loop (implicit / single-line body) return 0>1;//false // Return false } // End of method (1) void p(String p,String q){ // Method (2) with two String parameters and no return-type int n=q.length(),i=0; // Two temp integers if(n<1) // If `n` is zero: l.add(p); // Add this permutation of the String to the Set else // Else: for(;i<n; // Loop over `n` p(p+q.charAt(i),q.substring(0,i)+q.substring(++i,n)) // Recursive-call with permutation parts ); // End of loop (no body) } // End of method (2) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Œ!ẇ€Ṁ ``` [Try it online!](https://tio.run/##y0rNyan8///oJMWHu9ofNa15uLPh////SimKRTlK/5U8gLL5Ogrh@UU5KYpKAA "Jelly – Try It Online") -1 thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) for encouraging me to retry golfing. Explanation: ``` Œ!ẇ€Ṁ Main link, dyadic Œ! the permutations of the left argument ẇ€ Is each of in the right argument? Ṁ Maximum of boolean values ``` [Answer] # [Python](https://docs.python.org/), 60 bytes An altered form of [TFeld's answer](https://codegolf.stackexchange.com/a/122945/53748) - go give some credit! ``` s=sorted f=lambda u,t:s(u)==s(t[:len(u)])or t and f(u,t[1:]) ``` Recursive function returning the boolean `True` (truthy) or an empty string (falsy). **[Try it online!](https://tio.run/nexus/python3#HY67DoIwGEZneYqfDtKaOqBOTerioCObA2Go6QVIaU0vA7w8guP5cpLzrZFHH5KSheZWTB8pINPEIs6E84hTy6xyG3TEB0ggnASNN6OtWUdWvY8qJhgcYIxkGSyigF7KWg9vH6wsEaEYNd4giprgTRDTNDgDTV4WqyIc4eGlgqe3@m@afsxz2mQRpe7nZMZcX643RAgrDt8wuIT3IIXqfK/o9uW0IyHrDw "Python 3 – TIO Nexus")** sorts the substring, `u`, and the same length of the front of the string, `t`, (using a slice `t[:len(u)]`) if they are the same then `True` is returned, otherwise if `t` is still truthy (not empty) recurses with a dequeued `t` (using a slice, `t[1:]`). If `t` does become empty the `and` is not executed and this empty `t` is returned. [Answer] # Pyth, ~~9~~ 8 bytes ``` sm}dQ.pE ``` *-1 byte thanks to @Erik\_the\_Outgolfer* Takes two quoted strings, the second of which is the substring. [Try it!](https://pyth.herokuapp.com/?code=sm%7DdQ.pE&input=%22Hello+World!%22%0A%22d!rl%22) [Answer] ## Mathematica, ~~55~~ 50 bytes -5 bytes from user202729 ``` StringFreeQ[#2,""<>#&/@Permutations@Characters@#]& ``` Returns `False` if a permutation of the first input is in the second string. Returns `True` if a permutation of the first input is not in the second string. Explanation: ``` Characters@# - split first string into array of characters Permutations@ - make all permutations ""<>#&/@ - join each array of characters together to form a single string StringFreeQ[#2, ]& - Check if any of these string is in the second input string ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~13~~ 12 bytes ``` le!lf{\#)}:+ ``` [Try it online!](https://tio.run/##S85KzP3/PydVMSetOkZZs9ZK@///9Iys0soSrsTilLSMypL0rFJDI2MTAA "CJam – Try It Online") I feel like CJam is really limited compared to other golfing languages, but maybe it's just me being bad... I'm thinking about moving to another. 05AB1E seems fun. *Fixed small bug thanks to Erik the Outgolfer* *Cut one bite because non-zero numbers are truthy* Explanation: ``` l Read substring e! Generate all permutations l Read string f{ For each permutation \# Check if it is in the string (returns -1 if not found) ) Add one } End for :+ Sum the whole found/not found array ``` [Answer] # [Java 9 JShell](http://jdk.java.net/9/), 160 bytes ``` p->q->IntStream.range(0,q.length()-p.length()+1).anyMatch( i->Arrays.equals( q.substring(i,i+p.length()).chars().sorted().toArray(), p.chars().sorted().toArray())) ``` (newlines inserted for readability) [Try it online!](https://tio.run/nexus/java-openjdk9#hVBNb9swDL3rV7CXQVoTYd12S2NgGLAPYB0C5LDDsANr07YyWXIkqp079LdncuxmRVFsPEgE@d4jH03X@8CwwxvUiY3VL1fCPK3VyZVsvHu2GTkQdmNL9OnamhJKizHCFRoHvwXkmOuRkfN3400FXe7KLQfjmu8/AEMT1Qwe48M88HJCLGATqDIlMs2VooAa1od@WeyXxWfH22mJgK4h@Wqx15Zcw61Uy/6Unl8ojW64Qi5baZbFuxBwiJr2CW2Uex3TdTyKS7Mw5395SpcthiiVjtk5VTlhfyRLtej/0VTq8GBotS3ROQoQ8w9rcHQLc0luh8jUaePU6nSA29ZYAjmidYvxK/3iL8ZR1nx0pTGmc2Q9qjJhfdTX7gRfPQdus23G8ud/4dNiPrHuM5Gtk7XGvreDnOZlrxRZPuipR/x7Mb33h@osWPGJrPXwzQdbnYmNb8Qm@CZg1437bNLdnaUIL@C9rwg@eluLpt2lgQXGqm4Hbnbp4vWbt38A "Java (OpenJDK 9) – TIO Nexus") Note: JShell includes a number of imports by default. As a Java 8 or Java 9 solution, it would be necessary to import: ``` import java.util.*;import java.util.stream.*; ``` For an extra 45 bytes, or 205 bytes total. The TIO link above is to a Java 9 program since TIO doesn't currently have JShell (and it's not clear to me how JShell would work on TIO). [Answer] # C#, 320 bytes ``` using System.Linq;s=>u=>p(u.ToArray(),0,u.Length-1).Any(p=>s.Contains(p));w=(c,a,b)=>{if (a!=b)(var t=c[a];c[a]=c[b];c[b]=t;)};System.Collections.Generic.IEnumerable<string>p(char[]l,int k,int m){if(k==m)yield return new string(l);else for(int i=k;i<=m;){w(l,k,i);foreach(var c in p(l,k+1,m))yield return c;w(l,k,i++);}} ``` I'm sure calculating the permutations can be a lot shorter but I can't see how at the moment. Formatted/Full version: ``` void test() { Func<string, Func<string, bool>> f = s => u => p(u.ToArray(), 0, u.Length - 1).Any(p => s.Contains(p)); Console.WriteLine(f("Hello World!")("d!rl")); Console.WriteLine(f("Programming Puzzles & Code Golf")("Pog")); Console.WriteLine(f("asdfhytgju1234")("ghjuyt")); } System.Collections.Generic.IEnumerable<string>p(char[] l, int k, int m) { Action<char[], int, int> w = (c, a, b) => { if (a != b) { var t = c[a]; c[a] = c[b]; c[b] = t; } }; if (k == m) yield return new string(l); else for (int i = k; i <= m;) { w(l, k, i); foreach (var c in p(l, k + 1, m)) yield return c; w(l, k, i++); } } ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 69 bytes ``` ->a,b{r=nil;a.chars.each_cons(b.size){|q|r||=q.sort==b.chars.sort};r} ``` [Try it online!](https://tio.run/nexus/ruby#RYu7DoIwFEB3v6J2EE2wiY@N1MVBRzYHQ0yhpUAKV25pwvPbURON48k5p@Xz9iT8eEBe5SYQLMkEWqZEkj0SqOw6Zjbv1WYY6xHHkdfMAjacx9/wQ1OA0/x0jSXt3bsqY4DcAI1cer4nl2i8aPGzIYJGUZZ5pUno@t4oS1bkDFKRC5j0PYSg/z0VVqZZ1@jC7faHI/WpzgrXNTSaXw "Ruby – TIO Nexus") [Answer] # [Perl 6](http://perl6.org/), 48 bytes ``` {$^a.contains(any $^b.comb.permutations».join)} ``` Returns an or-junction of each permutation's presence as a substring. For example, with arguments `"Hello World!"` and `"d!l"`, returns: ``` any(False, False, False, False, True, False) ``` ...which "collapses" to `True` in a boolean context. That is, junctions are truthy values. [Answer] # PHP>=7.1, 91 Bytes ``` for([,$x,$y]=$argv;~$p=substr($y,$i++,strlen($x));)$t|=($c=count_chars)($x)==$c($p);echo$t; ``` [Testcases](http://sandbox.onlinephpfunctions.com/code/5593a150bb9b96c6d8bc13ee03c2ffcd0d7ca2a8) [Answer] # Haskell, 54 bytes ``` import Data.List s#t=any(`isInfixOf`s)$permutations t ``` Using the power of Data.List for both `isInfixOf` as well as `permutations`. [Answer] # [R](https://www.r-project.org/), 103 bytes ``` function(w,x,y=u(w),z=u(x)){for(i in 1:n(w)){F=F|!sum(setdiff(y[1:n(x)+i-1],z))};F} u=utf8ToInt n=nchar ``` [Try it online!](https://tio.run/##JcqxbsIwFIXhPU9x4wHZwgwpHSogE1KALUOlDoghwrmOkeMrObZI0vLsaSKmI53v9xPCYQMTRncPhhx/yl4OeeRPIcd5eiF@kTw3YBxku9nno8iLv7SLLe/qoAwiH64L9WJtNtlNjkK89sUriXkM@PVNFxcSl7t7U/kJOTvX1hL8kLcqZRKYSr1lIpml9KR91bbGaSjjONq6gxUcSdVwIotLXJJ@t1WnsBmCfsTsY/u5kG4ecQhMTP8 "R – Try It Online") Returns `TRUE` for truthy and `NA` for falsey. [Answer] # MATL, 10 bytes ``` Y@Z{w&Xfma ``` [Try it on MATL Online](https://matl.io/?code=Y%40Z%7Bw%26Xfma&inputs=%27d%21rl%27%0A%27Hello+World%21%27&version=20.9.1) [Answer] # [Ruby](https://www.ruby-lang.org/), 43 bytes ``` ->a,b{b.chars.permutation.any?{|c|a[c*""]}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3tXXtEnWSqpP0kjMSi4r1ClKLcktLEksy8_P0EvMq7atrkmsSo5O1lJRia2uhWjoKFNyilTxSc3LyFcLzi3JSFJV0FJRSFItylGIVlBVs7RRKikpTucCqAory04sSc3Mz89IVAkqrqnJSixXUFJzzU1IV3PNz0kAaA_LTYfrSEnOKoRoTi1PSMipL0rNKDY2MTUDq0jOySitLkK2AuGfBAggNAA) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 18 bytes ``` {∨/(∧/⍺∊⊢)¨⍵,/⍨⍴⍺} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/FR24TqRx0r9DUedSzXf9S761FH16OuRZqHVjzq3aoDFADSW4DCtf//q6coFuWoO6p7pObk5CuE5xflpCiqc6kH5KcDBQOK8tOLEnNzM/PSFQJKq6pyUosV1BSc81NSFdzzc9KA6tIzskorS4BKE4tT0jIqS9KzSg2NjE3UAQ "APL (Dyalog Unicode) – Try It Online") [Answer] # [Factor](https://factorcode.org/) + `math.combinatorics`, 35 bytes ``` [ '[ _ subseq? ] find-permutation ] ``` [Try it online!](https://tio.run/##TY@7TgMxEEX7/YqbLUJFpBAqkKCgCGnQShGiiCLk@LUOtmdjj4tNlG9fjBASU845dzTXCMmUpvft5m39AJEzyQyTRgTB/UJSOLgoquHqekiaeRySi4ysT0VHqTMem@bSoM4FrZol36J91d4TPih5NWtx/aMd2Qq7RDaJEFy06Mr57OuNOV5IaazJm3@@7Y9l5BoRWZl@ZHssy7vV/Y9xnXa42eETuRzqK8/Yw7iobgedQmHBjiL2k/kt9BTEgMxCfi2mbw "Factor – Try It Online") Outputs the matching subsequence (which behaves as boolean true in Factor) for truthy and `f` for falsey. ]
[Question] [ Write a program or function with no input that prints or returns this string of [24-hour](https://en.wikipedia.org/wiki/24-hour_clock) and [12-hour](https://en.wikipedia.org/wiki/12-hour_clock) times: ``` 00:00 12:00am 01:00 1:00am 02:00 2:00am 03:00 3:00am 04:00 4:00am 05:00 5:00am 06:00 6:00am 07:00 7:00am 08:00 8:00am 09:00 9:00am 10:00 10:00am 11:00 11:00am 12:00 12:00pm 13:00 1:00pm 14:00 2:00pm 15:00 3:00pm 16:00 4:00pm 17:00 5:00pm 18:00 6:00pm 19:00 7:00pm 20:00 8:00pm 21:00 9:00pm 22:00 10:00pm 23:00 11:00pm ``` **The string must be output *exactly* as it appears here.** The only exception is that it may optionally have a single trailing newline. So the [MD5 hash](http://www.miraclesalad.com/webtools/md5.php) of your output should be ``` 827ae6e2dbb1df494930baedb3ee2653 ``` if you do not have a trailing newline and ``` cd4c3d18abee9bafb495f390a919a13f ``` if you do. (Your hash could be different if your system uses another type of [newline](https://en.wikipedia.org/wiki/Newline#Representations) but that's OK.) **The shortest code in bytes wins. Tiebreaker is earlier answer.** [Answer] # Bash + coreutils, 43 30 * Saved 7 bytes thanks to @Yossarian * Saved 3 bytes thanks to @AndersKaseorg ``` seq 0 23|date -f- +%R\ %l:00%P ``` * `seq` generates integers 0-23, one per line. * `date` interprets each line as a datetime. Bare integers appear to be sufficient to be recognised as hours of the day by `date`. `date` then outputs each time with the required formatting using the available [time format specifiers](https://www.gnu.org/software/coreutils/manual/html_node/Time-conversion-specifiers.html#Time-conversion-specifiers). Assumes `LANG=C` locale, as per [this meta answer](http://meta.codegolf.stackexchange.com/a/276/11259). [Ideone.](https://ideone.com/AY5OKU) [Answer] # Python 2, 66 bytes ``` for i in range(24):print'%02d:00%3d:00%sm'%(i,12+i%-12,'ap'[i>11]) ``` [Answer] # C, 73 bytes ``` m(i){for(i=25;--i;)printf("%02d:00%3d:00%cm\n",24-i,12-i%12,"pa"[i/13]);} ``` [mIllIbyte](https://codegolf.stackexchange.com/users/52554/millibyte) found a particularly neat way to rewrite this answer. Thanks! [Answer] # MATL, ~~46~~ ~~42~~ 34 bytes ``` 12tEt:qy/t15XObZ"!b16XOhhkw14:X~Z) ``` Previously, 42 bytes, `12tEt:q2M/736330+t15XObZ"!b16XOhhkw14:X~Z)`, and 46 bytes, `736330 24t:qw/+t15XO' '24TX"b16XOhhk14: 12X~Z)`. Of course the 736330 wasn't needed, that was crazy! Note: Doesn't work with TryItOnline, I think there is a compatibility issue between Matlab and Octaves implementation of `datestr`. `datestr` takes the number representation of a date and converts it to the string representation of that date. The time of the day is the fractional part of the number, so 0.0 corrsponds to January 0, 0000, at time 00:00:00, and 1.0 corresponds to January 1, 0000, at 00:00:00. 1/24 is 1am, 2/24 2am etc. Explanation ``` 12t % push a 12 onto the stack and duplicate Et % double the 12 and duplicate the 24 (stack now has 12, 24, 24, bottom to top) :q % make vector 1:24 and decrement by 1, stack has 12, 24, 0:23 y % duplicate second element on stack (24) / % divide, for (0:23)/24 t % duplicate elements 15XO % string representation of date, 15 specifies format b % bubble up element in stack (gets a 24 on top of the stack) Z"! % makes a column of 24 spaces, to put between columns of times b % bubble up another (0:23)/24 16XO % string representation of date, 16 for a different format hh % concatenate two time vectors and the column of spaces k % convert string to lowercase, because CO gives AM/PM not am/pm w % swap elements in stack, that first 12 is now on top 14: % vector of equally spaced values 1:14 X~ % set exclusive-or, returns [1 2 3 4 5 6 7 8 9 10 11 13 14] Z) % get the right columns of the string array to remove extra column of blanks % implicit display ``` To show it works in Matlab, here is a screenshot [![enter image description here](https://i.stack.imgur.com/21Wnl.png)](https://i.stack.imgur.com/21Wnl.png) [Answer] # [///](https://esolangs.org/wiki////), 160 bytes ``` /Z/:00 //S/Z //A/:00am //P/:00pm /00Z12A01S1A02S2A03S3A04S4A05S5A06S6A07S7A08S8A09S9A10Z10A11Z11A12Z12P13S1P14S2P15S3P16S4P17S5P18S6P19S7P20S8P21S9P22Z10P23Z11P ``` [Try it online!](//slashes.tryitonline.net#code=L1ovOjAwIC8vUy9aIC8vQS86MDBhbQovL1AvOjAwcG0KLzAwWjEyQTAxUzFBMDJTMkEwM1MzQTA0UzRBMDVTNUEwNlM2QTA3UzdBMDhTOEEwOVM5QTEwWjEwQTExWjExQTEyWjEyUDEzUzFQMTRTMlAxNVMzUDE2UzRQMTdTNVAxOFM2UDE5UzdQMjBTOFAyMVM5UDIyWjEwUDIzWjExUA) **Ungolfed** ``` 00:00 12:00am 01:00 1:00am 02:00 2:00am 03:00 3:00am 04:00 4:00am 05:00 5:00am 06:00 6:00am 07:00 7:00am 08:00 8:00am 09:00 9:00am 10:00 10:00am 11:00 11:00am 12:00 12:00pm 13:00 1:00pm 14:00 2:00pm 15:00 3:00pm 16:00 4:00pm 17:00 5:00pm 18:00 6:00pm 19:00 7:00pm 20:00 8:00pm 21:00 9:00pm 22:00 10:00pm 23:00 11:00pm ``` [Answer] # MarioLANG, ~~965~~ 834 bytes [**Try it online**](http://mariolang.tryitonline.net/#code=Kys8PikgKysrQCsrKys-ICAgWyEpID4pPigoKCg6OiguKTo6KCguKSkrOis6LS0oLik6OikpLikuKS4pKysrKysrKysrCisrIiIrICsiPT09PT0iIj09PT0jKSAiKyI9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PQorKyspKyArPj4rKysrKy0gPCs8KS0-KysrICFbLSkuKS4pLikpKDo6KSkuKDooOikpKS4uKCgoOjopKS4oOisoOigoKCg8Cis-KysrICsrIj09PT08KCAiKSIpLSIhKysrIz09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PSIKKygrKys-KyshKyspPCsoICsrKystKysrKys-CiAtKSkrKT0oIz09PSIrKCArKysrKSsrKysrIj09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PSEKIFshISstWyEoKysrISEhICErITwrISsrIT4oKCgoKCs6KC4pKTo6KCgoLgo9PSMjPT09Iz09PT0jIyM9Iz0jIj0jIz0jIj09PT09PT09PT09PT09PT09PAorKysrKSkpKysrKysrKysrKysrKysrKCgoIVstKS4pLikuKTo6KSkuKDopKSAgID4KPj09PT09PT09PT09PT09PT09PT09PT09PSM9PT09PT09PT09PT09PT09PT0gICAiCis-KyA-CisiKyAiPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09WyAgID09PT09PT09PT09PT09PT09PT09PSM9PT09PT09PT09PT09PT1bCishPiAhIC0pLikuKS4pKSg6OikpLikpOisoLi4oKCg6OikpLig6KygoKCgoPCsrIS0pLikuKS4pKSg6OikpLikpOisoLigoKDo6KSkuKDorKCgoKCg8Cj0jPT0jPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09Ij09Iz09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09&input=) well this was ridiculously complicated. Technically the output is valid but in practice the Tio for MarioLANG output "n " instead of "n" when we print a number with ':' if I find the time i'll guess i'll try to do a (probably much longer) version of the program that output correctly on Tio ``` ++<>) +++@++++> [!) >)>((((::(.)::((.))+:+:--(.)::)).).).)+++++++++ ++""+ +"=====""====#) "+"============================================ +++)+ +>>+++++- <+<)->+++ ![-).).).))(::)).(:(:)))..(((::)).(:+(:((((< +>+++ ++"====<( ")")-"!+++#==========================================" +(+++>++!++)<+( ++++-+++++> -))+)=(#==="+( ++++)+++++"==========================================! [!!+-[!(+++!!! !+!<+!++!>(((((+:(.))::(((. ==##===#====###=#=#"=##=#"=================< ++++)))+++++++++++++++(((![-).).).)::)).(:)) > >========================#================== " +>+ > +"+ "=======================================[ =====================#===============[ +!> ! -).).).))(::)).)):+(..(((::)).(:+(((((<++!-).).).))(::)).)):+(.(((::)).(:+(((((< =#==#======================================="==#====================================== ``` **Explanation :** our main problem here is the fact that we have 6 NaN char (newLine, Space, :, a, p, m) in marioLANG, in order to print character, we need their ascii value: * **newLine** is 10 * **Space** is 32 * **:** is 58 * **a** is 97 * **p** is 112 * **m** is 109 So the first thing to do is to set the memory : ``` ++<>) +++@++++> [!) >)> ! ++""+ +"=====""====#) "+"== +++)+ +>>+++++- <+<)->+++ +>+++ ++"====<( ")")-"!+++ +(+++>++!++)<+( ++++-+++++ -))+)=(#==="+( ++++)+++++ [!!+-[!(+++!!! !+!<+!++!> ==##===#====###=#=#"=##=#" ``` with this, the memory look like : ``` v 32 58 0 0 97 109 10 0 _ : a m \n ``` we will transform **a** into **p** during the rest of the program then we do the actual output : ``` ++<>) +++@++++> [!) >)>((((::(.)::((.))+:+:--(.)::)).).).)+++++++++ ++""+ +"=====""====#) "+"============================================ +++)+ +>>+++++- <+<)->+++ ![-).).).))(::)).(:(:)))..(((::)).(:+(:((((< +>+++ ++"====<( ")")-"!+++#==========================================" +(+++>++!++)<+( ++++-+++++> -))+)=(#==="+( ++++)+++++"==========================================! [!!+-[!(+++!!! !+!<+!++!>(((((+:(.))::(((. ==##===#====###=#=#"=##=#"=================< ++++)))+++++++++++++++(((![-).).).)::)).(:)) > >========================#================== " +>+ > +"+ "=======================================[ =====================#===============[ +!> ! -).).).))(::)).)):+(..(((::)).(:+(((((<++!-).).).))(::)).)):+(.(((::)).(:+(((((< =#==#======================================="==#====================================== ``` [Answer] # Julia, ~~88~~ ~~71~~ ~~66~~ 64 bytes ``` [@printf "%02d:00%3d:00%cm " i-11 i%12+1 i>22?112:97for i=11:34] ``` This is a full program that prints the string with a single trailing newline. [Try it online!](http://julia.tryitonline.net/#code=W0BwcmludGYgIiUwMmQ6MDAlM2Q6MDAlY20KIiBpLTExIGklMTIrMSBpPjIyPzExMjo5N2ZvciBpPTExOjM0XQ&input=) Saved 5 bytes thanks to Sp3000 and 2 thanks to Dennis! [Answer] ## C# function, 100 bytes ``` void F(){for(int i=0;i<24;i++){Console.Write($"{i:00}:00 {(i+11)%12+1,2}:00 {(i>11?"p":"a")}m\n");}} ``` **Ungolfed version:** ``` void F() { for (int i = 0; i < 24; i++) { Console.Write($"{i:00}:00 {(i + 11)%12 + 1,2}:00 {(i > 11 ? "p" : "a")}m\n"); } } ``` `Console.Write()` takes too many characters! [Answer] ## JavaScript (ES2015), ~~147~~ ~~138~~ ~~137~~ ~~134~~ 133 bytes ``` ((o,x,r)=>{for(i=0;i<24;)b=i%12,c=b||12,o+='0'[r](i<10)+i+++x+' '[r]((c<10)+1)+c+x+(i<13?'a':'p')+"m\n";return o})('',':00','repeat') ``` In this version I took advantage of String.repeat() method to get rid of lengthy .slice() and .join() and moved incrementation inside loop. Previous version: ``` ((o,x,i)=>{for(;i<24;i++){b=i%12;o+=[`0${i+x}`.slice(-5),(b||12)+x+(i<12?'a':'p')+'m'].join(' '.repeat((b>0&&b<10)+1))+"\n"}return o})('',':00',0) ``` Gives output with trailing newline. Tested in Firefox Scratchpad. Not sure if passing arguments to IIFE is OK with "no input" rule. It's my first submission, so hello to everyone! :) [Answer] # TSQL(SQLServer 2012) ~~146~~ ~~124~~ 121 ``` DECLARE @ DATETIME=0WHILE @<1BEGIN PRINT CONVERT(char(5),@,108)+' '+LOWER(RIGHT(FORMAT(@,'g'),8))SET @=dateadd(hh,1,@)END ``` [Try it online!](https://data.stackexchange.com/stackoverflow/query/499873/24-and-12-hour-times) First attempt, a bit longer, but a one-liner: ``` SELECT CONVERT(char(5),n,108)+' '+LOWER(RIGHT(FORMAT(n,'g'),8))FROM(SELECT top 24 dateadd(hh,Number,0)n FROM master..spt_values WHERE'P'=type)x ``` [Try it online!](https://data.stackexchange.com/stackoverflow/query/492778/24-and-12-hour-times) [Answer] # Perl 5, 58 ``` map{printf"%02u:00%3u:00%sm ",$_,$_%12||12,$_>11?p:a}0..23 ``` [Answer] # Javascript, 122 Bytes, 120 Bytes ``` f=j=>j>12?j-12:j;for(i=0;i<24;i++)console.log('%s:00 %s:00%s',i<10?'0'+i:i,i==0?12:f(i)<10?' '+f(i):f(i),i>11?'pm':'am') ``` Edit: Small bug fixed + output: ``` 00:00 12:00am 01:00 1:00am 02:00 2:00am 03:00 3:00am 04:00 4:00am 05:00 5:00am 06:00 6:00am 07:00 7:00am 08:00 8:00am 09:00 9:00am 10:00 10:00am 11:00 11:00am 12:00 12:00pm 13:00 1:00pm 14:00 2:00pm 15:00 3:00pm 16:00 4:00pm 17:00 5:00pm 18:00 6:00pm 19:00 7:00pm 20:00 8:00pm 21:00 9:00pm 22:00 10:00pm 23:00 11:00pm ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~56~~ 53 bytes ``` i00:00 23ñYpñH12G$yP13G$pgvó $/am í/pm í 0/ í/12 ``` [Try it online!](http://v.tryitonline.net/#code=aTAwOjAwIBsyM8OxWXABw7FIFjEyRyR5UDEzRyRwZ3bDsyAkL2FtCsOtL3BtCsOtIDAvICAKw60vMTI&input=) Since this can be hard to enter, here is a reversible hexdump: ``` 00000000: 6930 303a 3030 201b 3233 f159 7001 f148 i00:00 .23.Yp..H 00000010: 1631 3247 2479 5031 3347 2470 6776 f320 .12G$yP13G$pgv. 00000020: 242f 616d 0aed 2f70 6d0a ed20 302f 2020 $/am../pm.. 0/ 00000030: 0aed 2f31 320a ../12. ``` A [noncompeting version](http://v.tryitonline.net/#code=aTAwOjAwIBsyM8OxWXABw7FIFjEyTHlQMTNMcGd2w7MgJC9hbQrDrS9wbQrDrSAwLyAgCsOtLzEy&input=) is trivially 2 bytes shorter if you replace both occurrences of `G$` with `L`, which was supposed to be the same but had a bug. Explanation: ``` i00:00<esc> #Enter the starting text. 23ñYp<C-a>ñ #Duplicate and increment 23 times H #Move back to the beginning <C-v>12G$y #Select 12 lines horizontally P #Horizontally paste 13G$p #Move to line 13 and Horizontally paste again gv #Reselect the top 12 lines ó $/am #Replace a space at the end of the line with 'am' ``` --- ``` í/pm #Replace the previous search with 'pm' í 0/ #Replace "Space+0" with 2 spaces í/12 #Replace the previous search with "12" ``` [Answer] ## [05AB1E](https://github.com/Adriandmen/05AB1E), ~~51~~ ~~50~~ ~~48~~ ~~44~~ 42 bytes Saved two bytes thanks to *carusocomputing* **Code:** ``` 24FNgi0}N…:00©ðN12(%12+Dgiðs}®„paN12‹è'mJ, ``` [Try it online!](https://tio.run/nexus/05ab1e#@29k4uaXnmlQ6/eoYZmVgcGhlYc3@BkaaagaGmm7pGce3lBce2jdo4Z5BYlA0UcNOw@vUM/10vn/HwA "05AB1E – TIO Nexus") **Explanation** ``` 24F # for N in [0...23] Ngi0} # if len(N)=1, push 0 N # push N …:00© # push ":00" and store a copy in register ð # push " " N12(%12+D # push 2 copies of N%(-12)+12 giðs} # if the length of that number is 1, # push " " and swap with the number ® # push ":00" again „pa # push "pa" N12‹è # index into that with N<12 'm # push "m" J, # join everything and print with newline ``` [Answer] ## PowerShell v2+, 76 bytes ``` 0..23|%{"{0:D2}:00{1,3}:00"-f$_,(($_%12),12)[!($_%12)]+('am','pm')[$_-ge12]} ``` Loops from `0..23` and each loop sets a string with the `-f` operator. The first `{0:D2}` ensures we have prepended zeros, the second `{1,3}` ensures we have padded spaces for the middle column. The `{0}` one corresponds to the `$_` of the `-f` operator, while the `{1}` corresponds to the pseudo-ternary that chooses between `$_%12` or `12` based on whether `$_%12` is non-zero or not (i.e., if we're at `$_=13`, this will choose `1` for 1:00pm). We then concatenate that with another pseudo-ternary that chooses the appropriate `am`/`pm`. --- As opposed to my answer on [List all times in the day at a half hour rate](https://codegolf.stackexchange.com/a/63176/42963), it's actually shorter *here* to brute-force the numbers since we get significantly cheaper padding. Here's the answer using date functions, at **78 bytes** ``` 0..23|%{(Date -h $_ -f 'HH:00')+(Date -h $_ -f "h:00tt").ToLower().PadLeft(8)} ``` [Answer] # C++, ~~81~~ 79 bytes ``` []{for(time_t t=0,y;t<24;cout<<put_time(gmtime(&y),"%R %l:00%P\n"))y=t++*3600;} ``` This code requires `using namespace std` somewhere preceding it. It does a loop on the values 0...23. It multiplies each value by 3600, converts to a `tm` struct and prints it. The print format `%R` outputs the 24-hour and minute; the print formats `%l` and `%P` output the proper 12-hour parts; they require [GNU](http://www.gnu.org/software/libc/manual/html_node/Formatting-Calendar-Time.html). A working online version is [here](https://ideone.com/xq5x2B). [Answer] # Ruby, 66 62 bytes ``` 0.upto(23){|i| puts "%02d:00%3d:00#{'ap'[i/12]}m"%[i,(i-1)%12+1]} ``` New version ``` 24.times{|i|puts"%02d:00%3d:00#{'ap'[i/12]}m"%[i,(i-1)%12+1]} ``` [Answer] # JavaScript (ES6), ~~119~~ 116 bytes ``` _=>Array(24).fill().map((_,i)=>`${`0${i}`.slice(-2)}:00 ${` ${(i+11)%12+1}`.slice(-2)}:00${'ap'[+(i>11)]}m`).join` ` ``` [Answer] # Sclipting, 76 bytes The program assumes that the input is empty (or `'0'` or anything that converts to the integer `0`). The byte count assumes UTF-16 encoding. ``` 군上❶겠小꼀虛嗎❷꾣갰글❷결加곀剩增❶겠小글虛嗎댆밁⓷꾣갰⓷⓼곀小掘닐밊終 ``` Ungolfed: ``` 군 // 23 上 // for loop (goes from 0 to 23 if input is 0) ❶겠小꼀虛嗎 // n < 10 ? "0" : "" ❷ // n 꾣갰글 // ":00 " ❷결加곀剩增 // k = (n+11) % 12 + 1 ❶겠小글虛嗎 // k < 10 ? " " : "" 댆밁 // "pa" ⓷ // Pull n to top of stack 꾣갰 // ":00" ⓷ // Pull "pa" to top of stack ⓼ // Pull k to top of stack 곀小掘 // "pa"[k < 10 ? 1 : 0] 닐밊 // "m\n" 終 // end of for loop ``` Each iteration of the loop leaves lots of small strings on the stack; at the end they are all automatically concatenated. [Answer] # JavaScript, ~~97~~ 95 bytes This is based off of [starcorder’s answer](https://codegolf.stackexchange.com/a/81007/668). Thanks to [George Reith](https://codegolf.stackexchange.com/users/11182/george-reith) for a 2 byte improvement. ``` for(i=0,k=12;i<24;k=i++%12+1)console.log('%s:00 %s:00%sm',i>9?i:'0'+i,k>9?k:' '+k,i>11?'p':'a') ``` Ungolfed: ``` for (i=0, k=12; i < 24; k = (i++) % 12 + 1) console.log('%s:00 %s:00%sm', i > 9 ? i : '0' + i, k > 9 ? k : ' ' + k, i > 11 ? 'p' : 'a') ``` [Answer] ## Batch, 167 bytes ``` @echo off set h=11 set p=a for /l %%a in (0,1,23)do call:e %%a exit/b :e set a=0%1 set/ah=h%%12+1 set h= %h% if %1==12 set p=p echo %a:~-2:00 %h:~-2%:00%p%m ``` [Answer] # [Kotlin](https://kotlinlang.org), 95 bytes It can be improved for sure. ``` fun p(){for(i in 0..23)println("%02d:00 ${(i+11)%12+1}:00${if(i>12)"p" else "a"}m".format(i))} ``` [Answer] # PHP, ~~110~~ 107 bytes ``` for($h=0;$h<24;){$m=($h+11)%12+1;echo($h<10?0:"")."$h:00 ".($m<10?" ":"")."$m:00".($h++<12?"a":"p")."m\n";} ``` **exploded view** ``` for ($h=0; $h<24; ) { $m = ($h+11) % 12 + 1; echo ($h < 10 ? 0 : "") . "$h:00 " . ($m < 10 ? " " : "") . "$m:00" . ($h++ < 12 ? "a" : "p") . "m\n"; } ``` Somewhat surprised, tried to turn the `($i < 10 ? $s : "") . "$i:00"` bit into a function, but it wound up *adding* ~25 characters. No go there. [Answer] ## Swift, 85 bytes ``` for x in 0...23{print(String(format:"%02d:00 %2d:00\(x<12 ?"a":"p")m",x,12+x % -12))} ``` [Answer] # C Function, 82 bytes ``` m(i){for(;i<24;printf("%02d:00 %2d:00%cm\n",i,i%12==0?12:i%12,i>11?'p':'a'),i++);} ``` **Usage, 94 Byte** ``` m(i){for(;i<24;printf("%02d:00 %2d:00%cm\n",i,i%12==0?12:i%12,i>11?'p':'a'),i++);}main(){m();} ``` **Ungolfed, 337 Bytes** ``` #include <stdio.h> void m(){ int i,a; char c; for(i=0;i<24;i++){ if (i%12==0){ a = 12; } else{ a = i%12; } if (i>11){ c = 'p'; } else{ c = 'a'; } printf("%02d:00 %2d:00%cm\n",i,a,c); } } int main(){ m(); } ``` it works on Windows: [![in the warning you can find the whole program ](https://i.stack.imgur.com/y00oQ.png)](https://i.stack.imgur.com/y00oQ.png) # C Program, 85 bytes ``` main(i){for(;i<24;printf("%02d:00 %2d:00%cm\n",i,i%12==0?12:i%12,i>11?'p':'a'),i++);} ``` [Answer] # Foo, 163 bytes Pretty brute-force approach; nothing clever here (I tried in a couple spots but it ended up being shorter not to), just wanted to give Foo a shot. Foo automatically prints anything within quotes. `$c10` prints a line break. `(## ... )` loops until the current cell equals `##`. ``` "00:00 12:00am"$c10+1(10"0"$i":00 "$i":00am"$c10+1)(12$i":00 "$i":00am"$c10+1)"12:00 12:00pm"$c10+1(22$i":00 ">+1$i<":00pm"$c10+1)(24$i":00 ">+1$i<":00pm"$c10+1) ``` Ungolfed a bit: ``` "00:00 12:00am"$c10+1 (10"0"$i":00 "$i":00am"$c10+1) (12$i":00 "$i":00am"$c10+1) "12:00 12:00pm"$c10+1 (22$i":00 ">+1$i<":00pm"$c10+1) (24$i":00 ">+1$i<":00pm"$c10+1) ``` [Try it online](http://foo.tryitonline.net/#code=IjAwOjAwIDEyOjAwYW0iJGMxMAooMTAiMCIkaSI6MDAgICIkaSI6MDBhbSIkYzEwKzEpCigxMiRpIjowMCAiJGkiOjAwYW0iJGMxMCsxKQoiMTI6MDAgMTI6MDBwbSIkYzEwKzEKKDIyJGkiOjAwICAiPisxJGk8IjowMHBtIiRjMTArMSkKKDI0JGkiOjAwICI-KzEkaTwiOjAwcG0iJGMxMCsxKQ&input=) [Answer] # Javascript (using external library - Enumerable) (107 bytes) ``` _.Range(0,24).WriteLine(x=>((x<10?"0"+x:x)+":00 "+(((h=((x+11)%12)+1))<10?" "+h:h)+":00"+(x<12?"am":"pm"))) ``` Link to library: <https://github.com/mvegh1/Enumerable/> Code explanation: Create array of integers from 0 to 23, for each write a line according to the predicate. That predicate checks if current val is less than 10, and pads it with 0, else uses the current val as is. Then adds the minutes string to it. Then basically does a little trickery to convert military to am/pm time, and handles padding for am/pm times less than 10. [![enter image description here](https://i.stack.imgur.com/BPOlz.png)](https://i.stack.imgur.com/BPOlz.png) [Answer] # SmileBASIC, 73 bytes ``` FOR H=0TO 23?FORMAT$(%02D:00 %2D:00%Sm",H,(H+11)MOD 12+1,"ap"[H>11])NEXT ``` Someone found a better 24->12 hour formula than my old one, which saves 3 bytes, and 5 bytes in another program [Answer] # PHP, ~~67~~ ~~65~~ 64 bytes This uses IBM-850 encoding. ``` for(;$i<24;)printf(~┌¤═ø┼¤¤┌╠ø┼¤¤┌îÆ§,$i,$i%12?:12,$i++>11?p:a); ``` With the unencoded string (66 bytes): ``` for(;$i<24;)printf("%02d:00%3d:00%sm\n",$i,$i%12?:12,$i++>11?p:a); ``` Run like this: ``` php -n -r 'for(;$i<24;)printf(~┌¤═ø┼¤¤┌╠ø┼¤¤┌îÆ§,$i,$i%12?:12,$i++>11?p:a);' ``` ## Tweaks * Saved 2 bytes by improving sprintf format * Saved a byte by getting rid of unnecessary space (thx @Titus) [Answer] # tcl, 93 ``` set i 0;time {puts [format %02d:00%3d:00[expr $i<12?"a":"p"]m $i [expr $i%-12+12]];incr i} 24 ``` [demo](http://www.tutorialspoint.com/execute_tcl_online.php?PID=0Bw_CjBb95KQMd09RT0M2SktUM1U) ]
[Question] [ Given an image, output the [width in pixels of a full vertical section]1 (if one exists). If no vertical section exists, output `0`. Input may be provided as a local file or a nested array. If you choose to take input as a nested array, white pixels should be represented by a truthy value while non-white pixels should be represented by a falsey value. 1. the number of contiguous, all-white columns --- You can assume that * no image will be larger than 1000 square pixels * there will be no more than one full vertical section per image --- ## Examples Inputs: ![](https://i.stack.imgur.com/AmXiR.jpg) ![](https://i.stack.imgur.com/vb2Yt.jpg) ![](https://i.stack.imgur.com/1V7QD.jpg) Outputs: ``` 50 57 0 0 ``` Here are the first two examples, highlighted (in yellow) to show their sections: ![](https://i.stack.imgur.com/iJAgn.jpg) ![](https://i.stack.imgur.com/aN6gC.jpg) [Answer] # Jelly, 2 bytes ``` PS ``` [Try it here!](http://jelly.tryitonline.net/#code=UFM&input=&args=W1swLDAsMCwwLDEsMSwxLDEsMSwxLDEsMSwxLDEsMCwwLDAsMCwwXSxbMCwwLDAsMCwwLDAsMCwxLDEsMSwxLDEsMSwxLDEsMSwwLDAsMF0sWzAsMCwwLDAsMCwwLDAsMCwwLDEsMSwxLDEsMSwwLDAsMCwwLDBdLFswLDAsMCwwLDAsMCwwLDAsMSwxLDEsMSwxLDAsMCwwLDAsMCwwXSxbMCwwLDAsMSwxLDEsMSwxLDEsMSwxLDEsMSwxLDEsMSwxLDAsMF0sWzAsMCwwLDAsMCwwLDEsMSwxLDEsMSwxLDAsMCwwLDAsMCwwLDBdLFswLDAsMCwwLDAsMCwwLDEsMSwxLDEsMSwxLDEsMSwwLDAsMCwwXSxbMCwwLDAsMCwxLDEsMSwxLDEsMSwxLDEsMSwxLDAsMCwwLDAsMF1d) If I encode an image like so: ``` 0000111111111100000 0000000111111111000 0000000001111100000 0000000011111000000 0001111111111111100 0000001111110000000 0000000111111110000 0000111111111100000 ``` Into a nested array like this: ``` [[0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0],...] ``` Then `P` takes the element-wise product of all of the row vectors, and `S` sums all of the ones in the result, yielding the length of the vertical slice. (This works only because there’s guaranteed to be only one contiguous slice.) In our case, the answer is `3`. [Answer] # APL, 4 bytes ``` +/×⌿ ``` `[Try it here.](http://ngn.github.io/apl/web/index.html#code=%28+/%D7%u233F%298%2019%u23740%200%200%200%201%201%201%201%201%201%201%201%201%201%200%200%200%200%200%200%200%200%200%200%200%200%201%201%201%201%201%201%201%201%201%200%200%200%200%200%200%200%200%200%200%200%200%201%201%201%201%201%200%200%200%200%200%200%200%200%200%200%200%200%200%201%201%201%201%201%200%200%200%200%200%200%200%200%200%201%201%201%201%201%201%201%201%201%201%201%201%201%201%200%200%200%200%200%200%200%200%201%201%201%201%201%201%200%200%200%200%200%200%200%200%200%200%200%200%200%200%201%201%201%201%201%201%201%201%200%200%200%200%200%200%200%200%201%201%201%201%201%201%201%201%201%201%200%200%200%200%200)` This is my first APL answer! Thanks to @jimmy23013 and @NBZ for saving bytes! [Answer] # Bash + common utilities, 17 ``` rs -Tc|grep -vc 0 ``` If you're not using `grep` for [image-processing](/questions/tagged/image-processing "show questions tagged 'image-processing'"), then you're doing it wrong ;-). This uses the `rs` utility to do transposition. `rs` is [bundled in OSX](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/rs.1.html), but will need installing in most linux with something like `sudo apt-get install rs`. Input columns are `TAB` separated, and rows are newline separated: ``` 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 ``` If you like, you can preprocess the example input images into this format with imagemagick and (GNU) sed. E.g: ``` $ for img in "AmXiR.jpg" "vb2Yt.jpg" "1V7QD.jpg" "MqcDJ.jpg" ; do > convert -depth 1 "$img" xpm:- | \ > sed -nr '/pixels/{:l;n;/}/q;s/^"(.*)",?$/\1/;y/ ./01/;s/./&\t/g;p;bl}' | \ > rs -Tc|grep -vc 0 > done 50 57 0 0 $ ``` [Answer] # Perl, ~~21~~ 22 bytes ## Fixed version Includes +2 for `-lp` (`-l` can be omitted and would still be a valid solution, but it's ugly without the final newline) Give sequences of 1's and 0's on 0 or more lines on STDIN. You can add spaces or commas or whatever between the digits if you want as long as the usage is.consistent on all lines. ``` $a|=~$_}{$_=$a=~y;\xce; ``` This works as shown, but replace `\xce` by the literal byte value to get the claimed score If there are multiple vertical sections this returns the sum of all section widths. If you want the width of **a** vertical section use ``` $a|=~$_}{$a=~/\xce+/;$_="@+"-"@-" ``` ## Old version I originally misunderstood the challenge and implemented a program that gives true or false based on if a vertical line exists at all. Code and explanation here are for this old version ``` $a|=~$_}{$_|=~$a=~1 ``` If only I could add 1=~ at the left for almost perfect symmetry... I suppose the closest would be ``` 1=>$a|=~$_}{$_|=~$a=~1 ``` ## Explanation ``` $a|=~$_ The bitwise operators in perl (&, |, ^, ~) also work on strings by working on the sequence of byte values. The digits "0" and "1" happen to have the same ASCII value differing only in the last bit which is 0 for "0" and 1 for "1". So I would really like to do an "&" here. Unfortunately "&" of two different length strings shortens the result to the shortest of the strings and my accumulator starts as an empty string. The "|" of two strings however extends to the longest string. So instead I will apply De Morgan's law and use "|" on the complemented byte string }{ Standard perl golf trick. "-p code" transforms to (simplified) "while (<>) { code; print }". So if code is "code1 } { code2" this becomes "while (<>) { code1 } {code2; print }". So you can use code1 for the loop operation, use code2 for the final calculation and get a free print by assigning to $_ $_|=~$a=~1 I would like to match the accumulator with the bit complement of "1", but $a=~~1 doesn't work because the 1 is not a string but a number. $a=~~"1" would work but is too long. Next up is complementing $a back and matching with 1, so $_=~$a=~1. That also doesn't work since the first =~ will be interpreted as a string match insteads of equals followed by complement. Easily solved by writing it as $_= ~a=~1. But if I am going to give up a byte I can at least have some fun with it. Using $_|= also makes the parse work and has the advantage that the failure case will give 0 instead of an empty string, which looks nicer. It also makes the code look very symmetric. I can also bring out the symmetry more by putting 1=> in front (which evaluates 1 before the assignment and then immediately discards it) ``` [Answer] # Python 2, 30 bytes There is a surprisingly elegant solution using many of my favourite built-in functions chained together. ``` lambda c:sum(map(all,zip(*c))) ``` Using the test image from @Lynn: ``` >>> image = [[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]] >>> func = lambda c:sum(map(all,zip(*c))) >>> func(image) 3 ``` [Answer] # Pyth, 5 ``` s*VFQ ``` [Try it here](http://pyth.herokuapp.com/?code=s%2AVFQ&input=%5B%5B0%2C%200%2C%200%2C%200%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%201%2C%201%2C%201%2C%201%2C%201%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%201%2C%201%2C%201%2C%201%2C%201%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%200%2C%200%2C%200%2C%200%2C%200%5D%5D&debug=0) This uses Lynn's algorithm, but I decided to post it just to show how to golf vector operations in Pyth. The trick here is to chain the "sugar" syntax helpers `V` and `F` so that the fold is applied as a vector operation. The operator that is folded is of course multiplication, and then the result is summed to get the final answer. [Answer] ## JavaScript (ES6), ~~54~~ ~~45~~ 43 bytes ``` a=>a[s=0].map((_,i)=>s+=a.every(b=>b[i]))|s a=>a[s=0].map((_,i)=>s+=!a.some(b=>b[i]))|s ``` Based on @Lynn's Jelly answer, though since golfed by using `every` or `some` instead of `reduce`. The first version encodes black = 0 while the second encodes black = 1. Edit: Saved 2 further bytes thanks to @edc65. [Answer] # [J](http://jsoftware.com/), ~~5~~ 6 bytes Takes Boolean matrix as argument. ``` [:+/*/ ``` This is my first J answer! (was wrong for 1½ years…) `*/` columnwise product `+/` sum `[:` cap (serves as placeholder since `+/` should not take a left argument) [Try it online!](https://tio.run/##y/r/P83WKtpKW19L/39qcka@QoGtlbGCmYqBgiEYGgAhmIJxwSIQpiEXWEeaQsF/AA "J – Try It Online") [Answer] # CJam, 7 bytes ``` q~:.*:+ ``` [**Try it online!**](http://cjam.tryitonline.net/#code=cX46Lio6Kw&input=W1swIDAgMCAwIDEgMSAxIDEgMSAxIDEgMSAxIDEgMCAwIDAgMCAwXSBbMCAwIDAgMCAwIDAgMCAxIDEgMSAxIDEgMSAxIDEgMSAwIDAgMF0gWzAgMCAwIDAgMCAwIDAgMCAwIDEgMSAxIDEgMSAwIDAgMCAwIDBdIFswIDAgMCAwIDAgMCAwIDAgMSAxIDEgMSAxIDAgMCAwIDAgMCAwXSBbMCAwIDAgMSAxIDEgMSAxIDEgMSAxIDEgMSAxIDEgMSAxIDAgMF0gWzAgMCAwIDAgMCAwIDEgMSAxIDEgMSAxIDAgMCAwIDAgMCAwIDBdIFswIDAgMCAwIDAgMCAwIDEgMSAxIDEgMSAxIDEgMSAwIDAgMCAwXSBbMCAwIDAgMCAxIDEgMSAxIDEgMSAxIDEgMSAxIDAgMCAwIDAgMF1d) ``` q~ e# read input and evaluate: push nested array :.* e# fold vectorized product over nested array: element-wise product of rows :+ e# fold addition over array: compute its sum ``` [Answer] ## Mathematica 24 ``` Length@Cases[Total@#,0]& ``` Takes an array in the following form: ``` {{1, 0, 0, 0, 1, 0}, {1, 0, 0, 1, 1, 1}, {1, 1, 0, 0, 0, 0}, {1, 1, 0, 0, 1, 1}, {1, 0, 0, 1, 1, 1}} ``` And in this case outputs: ``` 1 ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟, 7 chars / 9 bytes ``` ⨭МƟïⓜ⨴$ ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=%5B%5B0%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%2C0%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C0%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C1%2C0%2C0%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C1%2C0%2C0%2C0%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%2C0%5D%2C%5B0%2C0%2C0%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C0%2C0%2C0%2C0%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C0%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%2C0%2C0%2C0%2C0%5D%5D&code=%E2%A8%AD%D0%9C%C6%9F%C3%AF%E2%93%9C%E2%A8%B4%24)` This is @Lynn's great algorithm, but I found it independently. (I thought there was a builtin for this somewhere, still looking :P) # Explanation `МƟï` transposes the input array, `ⓜ⨴$` turns each inner vector into its product, and `⨭` sums the resulting array. [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~6~~ 4 bytes Takes input as an array of rows, with `1` being white and `0` being black. ``` y xe ``` * 2 bytes saved thanks to [ETH](https://codegolf.stackexchange.com/users/42545/ethproductions). [Test it](http://ethproductions.github.io/japt/?v=1.4.5&code=eSCu18N4&input=W1swLDAsMCwwLDEsMSwxLDEsMSwxLDEsMSwxLDEsMCwwLDAsMCwwXSxbMCwwLDAsMCwwLDAsMCwxLDEsMSwxLDEsMSwxLDEsMSwwLDAsMF0sWzAsMCwwLDAsMCwwLDAsMCwwLDEsMSwxLDEsMSwwLDAsMCwwLDBdLFswLDAsMCwwLDAsMCwwLDAsMSwxLDEsMSwxLDAsMCwwLDAsMCwwXSxbMCwwLDAsMSwxLDEsMSwxLDEsMSwxLDEsMSwxLDEsMSwxLDAsMF0sWzAsMCwwLDAsMCwwLDEsMSwxLDEsMSwxLDAsMCwwLDAsMCwwLDBdLFswLDAsMCwwLDAsMCwwLDEsMSwxLDEsMSwxLDEsMSwwLDAsMCwwXSxbMCwwLDAsMCwxLDEsMSwxLDEsMSwxLDEsMSwxLDAsMCwwLDAsMF1d) --- ## Explanation ``` y xe :Implicit input of array U. y :Transpose. e :Map over each sub-array, checking if every element is truthy. x :Reduce by summing, converting booleans to 1 or 0. :Implicit output of resulting integer. ``` ]
[Question] [ Given a string containing some parentheses and some other ASCII printable characters, like this: `(abc((123))(k))` your task is to remove any sets of parentheses that are redundant. A set of parentheses is redundant if: 1. It encloses another set of matching parentheses, like `ab((123))`, or 2. It encloses the entire string, like `(abc123)` Parentheses are guaranteed to be matched in the input. Also there will never be an empty pair. ## Test cases ``` { "(alpha)": "alpha", "(((([))))": "[", " beta(gamma)": " beta(gamma)", "@lpha((lambda))": "@lpha(lambda)", "(phi((theta)pi))": "phi((theta)pi)", "(sigma)(omega)": "(sigma)(omega)", "(sig(ma)(om)e;a)": "sig(ma)(om)e;a", "(((((a)))b))": "(a)b", "((b(((a)))))": "b(a)", "b((a$c)(def))": "b((a$c)(def))", "x(((y)(z)))": "x((y)(z))", "(foo(bar))baz": "(foo(bar))baz", "foo((bar)baz)": "foo((bar)baz)", "(((((a)(b)))c))": "((a)(b))c", "((c(((b)(a)))))": "c((b)(a))", "(((a))b)c": "((a)b)c", "c(b((a)))": "c(b(a))", "((\"))": "\"", "(('))": "'" "XYZ!\"#$%&\'(*)+,-./": "XYZ!\"#$%&\'(*)+,-./", ":;<=>?@[\\]^_`{|}~'" : ":;<=>?@[\\]^_`{|}~'", "a((foo(bar))baz)z": "a((foo(bar))baz)z", "a(foo((bar)baz))z": "a(foo((bar)baz))z", } ``` [Answer] # Regex (Perl / PCRE / Boost / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), ~~45~~ ~~44~~ ~~45~~ ~~44~~ 43 bytes ``` s/(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$)/$3/ ``` [Try it online!](https://tio.run/##VY7bToNAEIbveQrEFWbqAavxRkrpvS@gsqXuUgokUDaURKW0r46zgInOxc5@/z8nldTFU89a/977zPIigcUSj3FWlcqbm4PSH1zg0EXIXyhTBA/YhRHgGmfIESHwOXYMXfbo9h5rbVvV@b6x@N4i8ueeOTDbnHoQhcoEGnpKiBSGKZNGQCrKkuSVdgEKUcqtIBNUlgM0GZWgyrVwyFMqhKpMUjEijIyJN80F6kSpi0FOREBfwWKEbbIj@iLjG6HVDuyqCqSoqUm0hoaBCNCgY/662JLyr4KUaSfQSoyHtTEJEn83jzdIjI1YHyRGjVtDcuh9fXu/sC7Zlc0dmOH1ze2dazx7C38ZrELO19Hm49idzs4P "Perl 5 – Try It Online") - Perl v5.28.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=VZBNTsMwEIXFNqcowbQzLSUUNogkbfdcAKibYqf5k5ImaoOANOUibLqAW8BB4DSM4yCBF7a_9954Rn59K4J1uv9glXtmP8ZJGoAzxq0f51lhjzqN8v5QhsPLr8HGAg61h_yaTlqTc6xnHuAc-8gRYeJyrBla7MLSJZ82q7rdYp2sSpOvTCJ3ZHcaZoudzuy_DxwQaRELNNSjM6RldGRQCohElpE8VS5AKjK5FGRCEScAZUwRLBIlbJKIgpBnQSQ0gmYM7PZdoEqUKgyyJQK6CuYjLIOQ6ImMZ4RKORDmOUixpiJRGQoaIkCDhvnrYkXKvwQpbU-glug3bX0SJP521jNI9A1fDSS0xs3m6NF-c3t3aB6x4y7vQR8HJ8NTy7iyHXc8mc44n3uL-229e-npX_wB "Perl - Attempt This Online") - Perl v5.36+ [Try it online!](https://tio.run/##lVRrk9s0FP3uX6E1ZqW79SNp@QKON@3QMLM8CpNSKMRZI8vyg/o1ktMN2aR/fbmytwPboczUM4l0H7rn3KNHynV5pyTPiKcyQilRiwVNPvGj1mLZlz1xFIlIr2SRKNnXXEhGA/9imSQlr4dEdE1f1VLFLIYwXgeaugjokhydSSFNQjvIdtAsSb65@n6VJOCSOYRWlRPmqM1sexZRTYEMpepuSCtvyGovZD9UXcvoD5XWVVsQW9sU1zgZUsFF821IxvXZJX1HyfE48Wv4IEpkt5l5Xz7z4i33Tg6Di0f@4nJ5vQ2o62Tw30D2VfuW11VGMllXTTVIZRs407nc93WXScRyERomYNHt2gHpw1n0xUcq/qo6JN7umlQq0uX/VNZjaT118hg7cfJp/sTMDSS26U9tmjFDb4HenNdahlbe4cZim3pQie7rCmnkQLgmjoDbURRBzs8JhvtOM7uoGr1/9vzV6293tospURSNhT4i@KtWSdEVbXWQGclrjtJT3xE@NfpPmosoogUFp4gGtZMhkVjN8PaRuAhPVn6jsE328ufnq/XatX/6er0ib7Hnh348FnrgKCI1Cckvq/XLqx9fUPgwz45bo1fVVomWA7N7oaSfcvFmUPiXjJraLrG9uW0IPkjDVnZKY1//n/bnFJoZHFSXOYdoFjp1lOPx1YbH1QsI4Ra7Z069QWFr2eIMvPk2ikZ@mKx3KUbQ7c5cbz5qhYVAirIzKbiHh2geWoQYhBDLOX304FI5Cs@Xxl/tEm/umu0ci5zhJMUtf4MlanM4@vBETFliO7Udnj64hwzCOx2wmB2vIf4OR/yWj@G4uWawhQuIAdgyiuHoQOA8Ce4@9VWwRmivRXRlXwq8GT4@EqHcS0GCnVZBWrWBeTbeh@4Yr/uSg2WYbAA/i6Ry4KzgTYPupybKWM2bNOMYZH1ZMTaUmAJ9ZRy6KjCRdY0s@GSyyQYZ3tdluBJSk8zSewsNnHJUj2UyR2uPgb@AHUyE5V3HUq5wET9YxhgtNMBCMv@OwgE9DzLQc4/JEBLECCvQkcJ75IlDCsIShhCffLE9DnjIrde//X5mf@Z8fh5TdgGPXM8PrK/CRXS5fLqJ4@118sft8fSO/g0 "Bash – Try It Online") - PCRE1 [Try it online!](https://tio.run/##fVNrc9w0FP3uX6EYEemm3lfKF3CcbaddZsKjMFsKhfXGyLL8oH5oJG8TNrv96@HKDgPpUDxjW/feo3vOuZZ1qe8vlrrUhBoSEW1UkRilayEVZ7Pp2TJJSlH3iewaXdXKxDyGMF7PLAsIwzvHZFIoB2h71faWJ8nXV9@tkgQCsoDQq3LCqdnMtycRswxIX5ruhrTqhqxupdJ91bWcfV9ZW7UF8a3PcA/NUApuWmxDMuzPLtkHRg6HUV8jelmius188uXzSbwVkyPlcPZkenG5vN7OWEAz@G8i/6p9L@oqI5mqq6bqlfEdnXOubnXdZQq5AqSGkVh2u7ZH@XASffGJjr@YDoW3uyZVhnT5P53t0NqOTs7RCc3H9VO3dpRoczradO8MswVmc1FbFXp5Z5RAm7Y3idV1hTJyIMISKuFuGIokp6cEy7qz3C@qxt4@f/nm7Tc7P0BIFEVDo08M/E1rlOyKttqrjOS1wNGzKZVT5uY/zlxGESsY0CLqzU6FRGE3p3uKwmV49PIbgzb5659ertbrwP/xxXp1Tt6j6ccFPBe2FzhF5hDJz6v166sfXjH4GOfHrRtY1VaJVT33tTRqmgr5rjf4SIah@gHxJwvfKXwEQy87Y9HY/8P@GEtzx4Pj5XQfzUNaRzmeX@t0XL2CEO7QPqf1BidbqxZXMFlso2jQh2C7S7GC6WAeTBbDsLARKFl2DoIfcR8tQo8QxxBiO6qjR38VNXjALN51QCaLwH3PockJLlL85u@wRe1Ohw6PxLUlPq398PjRj8ghvLczHvPDNcTf4huv5TkcNtcctnAGMQBfRjEcKMzo09n9PRe1LgV4DrgBvDySql7wQjQNpp@5Kue1aNJMYJHrsuK8LxECunIJWxUI5F2jCjGGfIxBhQ99Oe6E1IF5@hBhgEuB5nimcoxusfAn8L2r8LzreCoMbhJ7zwVDhAF4KObfVdhj5hECMw@cHClBDrQSEyn8zTxqSEF60gkSYy72hxeeQe/tr7@d@J/Rz09jxs/gSTCZzryvwovocvlsE8fb6@T3u8PxA/sL "PHP – Try It Online") - PCRE2 v10.33 [Try it online!](https://tio.run/##fVXbcts2EH3nV0CMGgISbfnStC4h2pnM9CGTTB96mUlq2ixIgRQmvA1B1ZJM5dOrLgBKptSoGI2ovZzdg93lKq6qszSOt69EEWeLGUfTqCxlM6l5ypfn86q6teI5q1FY3T8gH/1qv3t6@hJdLz6vVp9@n//wNMdbOcEBbh9J8AGecO6uSHv/iMkDGZGAEHznB6QdksnwerIlx3DbRaPKDytqvTAQQKDmLL@1RNGgqobvkNd1WeO4LGSDNKFRzqVkKSfPspl5XgwOaDpFnVb91HpezDKKat4s6gJd0g1SIeWqaNiyi0meO2s/kf2bdkFasgndmCrMeCZy/4IiKFIGoWpWpBxrU@HqBzOPaB91AUFvwgYXZ4ygqb@XI5B3YUeJKGahDm6CjSRBzxaCk5Q1wpTK8XinUUckCA@UU5fklz8@fqR7K88k1y4j6ftOEDgANYjx@Aiz@TZIU9l7ShN6Y210Q3ImCrxjoxHjcTXwHem07QCbEikVeQlwUG@qQdpvetG2uypqhfv9jfvmhhxp2@sr96cf3curN2CB2Yjn0KEhJqPx@fT27tF2Dd99voNOvi/@ZpmYmd6Jhqt2IqBnLtWVG0a714Oq4ziQJ68wgo5AbS@cfpjkMIzchUlOh0kOwqjhuL4KG1RCJP0iep5@Ez2vKMO8nIU5RWzRlEj2PGBGctaEiahlE5ZFtkLtkYllGe2NE6SFfgWFQ1GiBks@iSaeQyOTXVtjBtPgCMdDQKX10REZoezUDE4Er@oX2kPJUyjFX55CLf8PtTyFyg3qtY@@nirXN1ApoOQB6j8lpH3UjCdskTUeOlg19s@qix7aDViSsRTZygKDcGr/GBZ6jfUJgweuXFTCSGgYDLkoUtgw1aLpdU69fmu1f7RTyptMFBwbVqJwjT@hx6tiTRDo1Yxi1XVIsvYvX/ZFt2P6KHX6RMpFczSRYc2rjMUc65wuXMBFEj5whYMoKr9G@x27fmH3TsoCCcrdbc2@OWASqyhQ1l5NjEdX3AtqbbaYZdWcEUv9D90TOBaKeMNwyvIc1G@VFeOM5dGMgRFXc4FxMwcXUgmlkCIFR1zmPGVGxEYmnHZxMSBJpJxx1EkgwE82jAksrASkJRhWBAqv3JKyxBGrAcTWlhK0BAKxgEzfStagOfAATZcTQ0oS67QxKCKyy2w4RCS2YkWIGV1g64cD358@/zmwXw2/ex04eETG7tn5xPLo1L@9e3sfBA@P4V/P7ear80@sJlhuzzLd51C3@V8 "C++ (gcc) – Try It Online") - Boost [Try it online!](https://tio.run/##bVJrU9pAFP2eX7GmtNmLkYdoq2BE2zIdpqgzap8JtBuyCTvdPGY3tIDYv05vEhnrjPmQ5Jz7OOfu3WyZz9KksxFxlqqc6KW2FY/4okeUo0zT3Ogm9eh6At5H/OLT34e1O6Ewhjp4ALTveLCuQdPrNDeY77a7e@2xIUKi3NZ4x7G01SWKCc3JzTLJ2WKgVKqodSG0FklETG1aYASOcquqVAU0ACISonnemCciTSj@UcWSiNODI/vwCMB@ZI7f2O39wyfU60P7uIPMXT1mGcWGtlmjUN9tnJz2Jybcw7OGhslvJkVAAi5FLHKu0JYiDlENnUmRo6nCnuQJVbDjHDzb44tKcaRkHvtckTR87KWxWShZpJ1Wj0zTeZI7bSNMFQmLSZXbGXcNgu1Dx7EiPLAqpWUQLjXvkrKUrB1yZwmrW@6nMfxweXU9eHd@M7CJFW/Zi0@j2@FoeFmQeku@v7o9H42QWWyZz4Prt1c3g3s3HBsaz35/XO4bd9AjK9QtrMlyCUvd0HkgkspfMb4EwpKASBf3jHa9BP1KR7qtcvHkz0xITtqYT@Li@Eo9Pffx3GyibSLtajq7mgp6KOSQGC8LVqBE7BZtW13iK85@laqrLsmUSHIKBrpr9x4QTwJHwoYymc0YGMXldAEfg/g8ZzRicYz0WRGlVLLYDxgGaTYTlOYzTIFMFIQWESbSNOYRqyCtMPDeQ1@KleAXydR/QAjwl9WmQAMeIlpgYAl0VURomKbUZwqL2MooQIkQgIFm/o/CCpknGcg8aFKUhGkpO0XCh61y5cGHqTEtDLGK88zyY@H767fvO@aL2stXnkXrsGvvNZpGt3finPbPXM8bT378vFvf/7X@AQ "Python 3 – Try It Online") - Python `import regex` This is a single regex substitution to be repeatedly applied until it has nothing to match. However in Boost, it is applied until there is no change (since its substitution interface apparently doesn't allow detecting whether any replacements were done). This golf down from the 45 byte version is similar to [Neil's .NET regex](https://codegolf.stackexchange.com/a/250664/17216), in that it is flanked with `(?<=\(|^)` and `(?=\)|$)` (or equivalent). When initially writing a PCRE regex answer to this challenge, the thought occurred to me to do this, but I dismissed the idea, assuming that empty capture groups would need to be used to XNOR the flanking conditions (i.e. force them to only match if they agree on `^` and `$` or `\(` and `\)`), by doing `(?<=\(()|^)`...`(?=(?(1)\)|$))` or at least `(?<=\(()|^)`...`(?=\1\)|$)`. Then later on, after Neil posted his answer, I tried porting that approach to mine anyway. I found it to indeed return some incorrect results unless forced to agree using an empty capture group, but at that point I'd already gone with the (as it turned out incorrect) golf of `[^)]` in my regex. As it turns out, with `[^()]`, the flanking approach is fully robust in recursive versions of the regex, without requiring any additional XNORing logic or atomic grouping. ``` s/ # Begin substitution - match the following: (\(|^) # Assert either we're at the start of the string, or there # is a (redundant) left-adjacent opening parenthesis. \K # Keep everything matched up to this point out of the match. # This is a more efficient way of doing the same thing as # lookbehind in many situations. ( # Define recursive subroutine (?2) \( # Match an opening parenthesis ( # At the outermost level, $3 = the following capture, i.e. # with the parentheses matched outside it discarded. ( (?2) # Call (?2) recursively | # or [^()] # Match any character other than a parenthesis. # It's not safe to reduce this to "[^)]" because if, # after popping out to the top level and exiting this # loop, the "\)" fails to match because there's more # inside the top-level parentheses pair matched in this # regex, it will backtrack and can incorrectly match an # opening parenthesis here. )* # Iterate the above as many times as possible, min 0 ) \) # Match a closing parenthesis ) (?=\)|$) # Assert that either we're at the end of the string, or # there is a redundant right-adjacent closing parenthesis. / # Substitution - replace with the following: $3 / # End substitution - no flags used ``` I also intend to write a single-use `s/`...`//g` substitution that will erase all the parentheses in one go, but that will be significantly more complicated and less efficient (as it will need to emulate variable-length lookbehind to erase the closing parentheses). As such, it would be demonstrable in [regex101](https://regex101.com/r/UsM7Nv/1), which can only apply a substitution once. (I've done this for .NET, but intend to for PCRE2 as well.) # Regex (PCRE / Ruby), ~~48~~ ~~49~~ ~~45~~ 44 bytes ``` s/(\(|^)\K(\(((\g<2>|[^()])*)\))(?=\)|$)/\3/ ``` [Try it online!](https://tio.run/##lVRpj9s2EP2uX8FV1CVno8NO@iWVZSdoXGB7pIWTtGktr0pR1NHIkkDKWddr569vh9IG6QZNgQiwyTk4783jkXJd3irJM@KpjFBK1GxGky/8qDVbdGVHHEUi0ilZJEp2NReS0cC/WCRJyes@Ee22q2qpYhZDGK8CTV0EdEmOzqSQJqHpZdNrliTfXf64TBJwyRRCq8oJc9R6sjmLqKZA@lK116SR12S5F7Lrq7Zh9KdK66opiK1timucDKngoukmJMP6bE7fU3I8jvy2vBclsltPvCfPvHjDvZPD4OKhP5svrjYBdZ0M/hvIvmze8brKSCbralv1UtkGznQu913dZhKxXISGEVi0u6ZH@nAWff2Zir@pFok3u20qFWnzj5X1UFqPnTzCTpx8nD82cwOJbfpjm2bM0FugN@e1lqGVt7ix2KbuVaK7ukIaORCuiSPgZhBFkPNzguGu1cwuqq3eP3v@@s33O9vFlCiKhkKfEfx1o6Roi6Y6yIzkNUfpqe8Inxr9R81FFNGCglNEvdrJkEisZnj7SFyEJyu/Vtgme/nq@XK1cu1fvl0tyTvs@b4fj4XuOYpITULy63L18vLnFxQ@zbPjxuhVNVWiZc/sTijpp1y87RX@JYOmtktsb2obgvfSsJWd0tjX/6f9NYYmBgfVZc4hmoROHeV4fLXhcfkCQrjB7plTr1HYWjY4A2@6iaKBHybrXYoRdLsT15sOWmEhkKJsTQru4SGahhYhBiHEck4X3btUjsLzpfFXu8SbumY7hyJnOElxy99iidocji48EVOW2E5th6dP7iGD8FYHLGbHK4h/wJGxuJg9mh/XVww2cAExAFtEMRwdCOLHwe2XPgvWgO01CK/sucCr4eMrEcq9FCTYaRWkVROYd@ND6Jbxuis5WEiFrQE/i6Sy56zg2y26n5ooYzXfphnHIOvKirG@xBToKuPQVYGJrN3Kgo8mG22Q4V1dhishNcksvbPQwClH@Vgmc7T2GPgb2MFEWN62LOUKF/GDZYzBQgMsJPPvKBzQcy8DPXeYDCFBDLACHSl8QB45pCAsYQjx0Rfbw4Cn3Hrz@x9n9gPnq/OYsgt46Hp@YH0TzqL54uk6jjdXyZ83x9N7@g8 "Bash – Try It Online") - PCRE1 [Try it online!](https://tio.run/##fVPbcts2EH3nV8Asa@w61M3pS0vTSiZRZ9xL2lGaNq0osyAIXhreBqBiV5by6@6CdKd1pqlmKGJ3D/acswC7oru/WHZFxzzNQtZplcdadZWQCvhseraM40JUfSzbuisrpSOIMIjWM8N9xunJKBnnygKaXjW9gTj@@uq7VRyjzxYYOGXGwNOb@fYk5IYj6wvd3rBG3bDVrVRdX7YN8O9LY8omZ65xOe3xUpJCmxbbgA3700v@gbPDYdRXi14WpG4zn3z5fBJtxeToAZ49mV5cLq@3M@57Kf43kXvVvBdVmbJUVWVd9kq7ls46V7dd1aaKuHyixpFYtrumJ/l4En7xiY6/6JaEN7s6UZq12T@dzdDajE7OyYmXjeundm0pyeZ0tGnfKWVzymaiMipwslYrQTZNr2PTVSXJyJAJwzyJd8NQJDs9ZVTuWgNuXtbm9vnLN2@/2bk@QcIwHBp9YuBvGq1kmzflXqUsqwSNnk89OeV2/uPMZRjynKOXh73eqYAp6mZ1T0m4DI5OdqPJJrz@6eVqvfbdH1@sV@fsPZl@XKB7YXpBU@QWEf@8Wr@@@uEVx49xbtTYgZVNGRvVg9tJraaJkO96TX/xMFTXZ@5k4VqFj2DkZacNGft/2B9jaW55aLzg7cN54FVhRvfXWB1XrzDAO7IPXrWhyVaqoRVOFtswHPQR2OwSqlDan/uTxTAsaoRKFq2F0CHuw0XgMGYZAmrndeGjr8rTdMEMPZXPJgvfnufQ5IQWCZ35O2pR2dvRBUdm2zLXq9zg@NGHCBjcmxlEcLjG6Ft6A0T5xfnlYXMNuMUzjBBhGUZ48HAWPZ3d34OoukKgQ0jYIP0clqheQC7qmtLPbBWgEnWSCipCV5QAfUEQ7EqbMGVOQGhrlYsxhDFGFTz0BdqJiQVD8hBRQEtB7iBVGUW3VPgTYW8rkLUtJELTJrF3bDBEFKBDYv5dxT1lHiEo88AJRIlyoJWUSPBv5lFDgtKRVpAYc5E7vOgSOm9//e3E/cz7/DTicIZP/Ml05nwVXISXy2ebKNpex7/fHY4f@F8 "PHP – Try It Online") - PCRE2 **[Try it online!](https://tio.run/##bVFtc5pAEP7Or1iNLXcJokn6pRo0TuN0nCZpx6TTtID2gONlBpDeYX3D/HW7qLFJJnzg7nn22Wf3dsXUWWwEGHDVu@/pgjPvRAW1DZEPwmzaFUOViASLJIe7RZqzeV@IidBAvYmkjNIAqrKKCp56ioc2wjy1t9leR31UoSjAMx4bZrP@sVe3bFZf1wg9PtEvOt2R3XjbeJD@ZXHkgcfjKIlyLvb2ZZdCl1kc5cSjuxb1mKdBHkLFgA9vu/0QE2wynSYOFzDx/7vKva2Pts02BBLPekdq2UrqcuqQTBPmmU3XaGue2zpnbjh2QyZgBYVbgMuwlKsAzEKeAs7scI3Q2IfCgCEP@DxrtQafb78O@596d/2DZv5a03@4799e9a8OiuS14ub79f3genDbBzgCyRIOTMI3LmJVAi4J/JgFQIa4TyT4n2mEU@RpXr75SZWoEElg8YwtJExSeigWqM8HoAkcQfByBjiptTKEp3b0lM@2u9b8ss0ykWCm0aSrzDAkdEFCC3wzkKbUYGhrIG10WRo46VkYxRxiI@C5xA5wjctKyWfTXG4LlbrTXSQ266e2YVSttNrGlNhs6nr9zN5tDiATEb7QN@M9Mx7jEMfjjWwQixQjan3BkxAruDjrFOaIUJseU4tS0jUsWtRowzpvbDaExVnIqIJKYlL8FHB4zkjAkgTpyzJKSMwSx2MYJFkYEZKHKKFZVBIyClBIJgkP2A6SHaa8vfclmEmdUkycPUKAV1ZzKfG4j2iOgQUlyzJC/MmEOExgElsqJdgiBFTBZp5H6RKZFwpk9jUJlqTutqyLhEOfKu96cKiruGVDbMdZ1e2h4v/h569K9aj27r2lkmN6otX1htJqXxid7qVpWfZo/HtVrB/Vfw "Ruby – Try It Online") - Ruby** As of 45 bytes and smaller, this is an absolutely straight port of the regex above. Previously, it needed to work around the difference in Ruby subroutine capture group behavior. ## \$\large\textit{Functions}\$ # [Ruby](https://www.ruby-lang.org/), ~~75~~ ~~76~~ ~~74~~ ~~72~~ ~~71~~ ~~66~~ 62 bytes *-5 bytes thanks to Steffan* *-4 bytes [thanks to Dingus](https://codegolf.stackexchange.com/questions/250861/add-parentheses-to-polish-notation/250875#comment559072_250875)* ``` ->s{0while s[/(\(|^)\K(\(((\g<2>|[^()])*)\))(?=\)|$)/]&&=$3;s} ``` [Try it online!](https://tio.run/##VY7dUoMwEIXveYoUsd2t0j/vTNP23hdQCdWE8jcTWqbQ0VL01XGBOqO5yOZ852x2jyd9biLRuKviMvtIUhOywpuChHqL8okqgIyXi1XtbQF9HKNEhLWQWDs49YdD4Tzw4qupxIyzvt2IOCwLztKIVQPC@YlUuN/xSsw7ajx37gthy73NjTDebDJxF34XYfkx3Zcs8ozPGYEGlMkThRatAR7SsZgOSwWxyjLCm9YFMCrTO0Um5EkKUCYUwTxtQZHGFIRDFsaql9BrDPn1X6BO1G0Y9FWRoKdyAoRdGJH6JOOMULUORIcDaHWkJlVZregUCbRomb8uVkT@JYhcZwKNxKAbGxDQ@Du530FjYAXtQqpn0u7KiO7nl9eBfePcDuUIxnh3706m1iNfitV640npb9/eL/XX9@gH "Ruby – Try It Online") # [Julia](http://julialang.org/) v1.6.1+, ~~84~~ ~~85~~ ~~84~~ 83 bytes [Attempt This Online!](https://ato.pxeger.com/run?1=PVBLTsMwEBXbnIClCYXOlBYQbFCD2-5ZIiSgbsFJ7NTI-ShJJQiBi7DppoeC0zBJCrOY8fvMs-Wv7cvaGrnZbNelHl1932oohhk_R15wnrEpK9iYachVZmWgSMtdEFAvUdzQpJpeYD1fAi5wgAIRplxg3UOXTwpXXLo4LHAXfVdxLW2hPKbTnFlmEpYrGVqTqALQYSyyqS8tqzyjqWW5SUqbAHoqCT1W8TJfK3K1PGiwiA4pXfjmZ28fpM1WEp3mVXOkcpivSgmRjGOiZ40KYGXsh5JEyFYGoFyRBTPTEIWJyAhprCLZQegwKm-XC7SJfmMGf4cI0FH2AoRQaUKvJLwhVI0COk3BlzktycppQIsI_OcBxWHQRgZE-PiX2uX7GDhBc5nsOOG2o0_9_uHxwD3sHR2LPgzwZDg6PXPG3jWfTGdzIRbLp-f3-uOz3_3QLw "Julia - Attempt This Online") (now the same as below) # [Julia](http://julialang.org/) v0.7+, ~~86~~ ~~87~~ ~~84~~ 83 bytes ``` f(s,p=0)=s==p ? s : f(replace(s,r"(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$)"=>s"\3"),s) ``` [Try it online!](https://tio.run/##PY7dUoMwEIXveYqI1e7W@n9XTOm9L6A2rSaQ0DjhZ0g7UxF9dVxAzcVuvnN2T/J@cFbeHrvOgJ9X/Aa557xiMfNswQzUunIy0eTVIQhotygeqdOJ77BdbwE3OEOBCDEX2E4w5EsfivsQ5x67hhvpvI6YKWvmmC1YrWXqbKE9YMBY5kolHWsia6hUtS32rgCMdJFGrOH7@qBpatDBgEMMyOlAumonMeh/sUY6AVN6LyGTeU7yqncBnMxVKsmEamcB9jsawcr2grcZDUKZ60yOCCOjjn5zgTZR9cOgfomArnKSIKTaEB3J@EBoegdMWYKSNS3JJuhhIIL/PKA4TIbIhASFf6ljvsIkSPrH5KiJcGhTqk/PLyfh6eTsXExhhhfzy6vrYBE98GW8Wgux2b6@fbZf39Mf "Julia 1.0 – Try It Online") Julia's implementation of PCRE substitution appears to be deficient, not actually using `pcre2_substitute()` (the giveaway is that `$1` `$2` etc. capture group syntax is not supported). This is a shame, because PCRE2 has some advanced conditional replacement features (enabled by `PCRE2_SUBSTITUTE_EXTENDED` in its C interface). The explanation, though, is that it was originally integrated with PCRE1, which has no built-in substitution API – so presumably when they switched to PCRE2, they kept the substitution code they'd already written for use with PCRE1. # [R](https://www.r-project.org/) v4.1.0+, ~~90~~ ~~91~~ ~~89~~ 88 bytes ``` f=\(s,p=0)if(p==s)s else f(sub(r'{(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$)}','\\3',s,,1),s) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVBNc9MwFByu_hVuCNXb4kILFwZXpHdypxA1IDuSoxnH9vg5M5CP_hEu4cCPgl_DcxxmWh0k7b59b1f6-as9HH6vO3_57s-d14Y4afQVgqdGawbHrmQXe-J1Rq3akqHdHOajnLImb7CbzQn3uIABaKINdmPsVaKMeasSTpJrJIzT_IL1VRpvtA-loxF3i1CNkMa-bmkahyrmddO0jvmTbatQFUyts4tpqBzTBsBWQjFy25EylULK-jqNe-hpCuzlXtbsRDrYHf4-uyFbNkuLqA87kxGI4sx1lgq7Wgl921eJSrvKFlaK1CwDUbcUCZrQExwKEVK9coUdIA0YLj3NJelE1ospOyEBcrXjHLRwXtB3KfzA8RUR-bqmzLbSZDdRD45IACIJ87iKjTBPFMKcPEkskR9tcyEy_HceMmTIo7wPZAfOjI6Hkv3u85ez0fPxi3Oj6AIvk8tXr6P36Y3-MLmdGXM___ptu9s_qOEX_wE "R - Attempt This Online") R is apparently also not using PCRE2's built-in substitution engine, otherwise `$2` would work as the replacement argument. # [Python](https://docs.python.org/) (with [`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), ~~123~~ ~~108~~ ~~107~~ ~~106~~ ~~107~~ ~~106~~ 105 bytes *-15 bytes thanks to Steffan* ``` import regex f=lambda s,p=0:s==p and s or f(regex.sub('(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$)',r'\3',s),s) ``` [Try it online!](https://tio.run/##VU/bUsIwEH3PV0REs4sFQd5aI7z7A2oDmt4709s0dQYq@uu4vTCjmUySc9k9m@rYJGWxPp/TvCrrhtdhHB5YJDOde4Hmxqrk0jZSVlwXATe8rHkEvWlhPj0QoOC0R/VMN63NA57cPeAOZ6gQYSMVnqYorFqotbAM0r4kmaNxeCuXLKKeGU@LjlmYJkgLm/E04llYQIZ9bubOVzsphSqEzTOZuUubiN7V2ryq06IBZNRt5YwoLAIZUTmeQWdVopF187lIi3EvbDTEOs@J3nYqwPBfEqFKUoAmIQtWaUeYNCYjlHkY6wHCgDF0xr5Aleh1ZvBGRICeeuojBGFE6EDCEaHtFIjKEjxdU5FuWQd6RAAZDfNXxZaYfw5ixkygSPT7WJ8IDy/Jwwwe@szvBtIDpyb9Jeh8eX27mlxPb26VgBneWfPFPbOdR/m02bpK7fbvH1@n7x/xCw "Python 3 – Try It Online") For golf reasons, this continues substituting until the string is unchanged, not until there are no matches (with this regex either of those two methods will work). Alternative 105 bytes, using essentially the same technique as [suggested by VisualMelon](https://codegolf.stackexchange.com/questions/250596/remove-redundant-parentheses/250617#comment558588_250617): ``` import regex def f(s): for i in s:s=regex.sub('(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$)',r'\3',s) return s ``` [Try it online!](https://tio.run/##VVDbUsIwEH3PV0REs4uIIG/FCO/@gNqAplcy06adpsxARX8dty3MaB6yOZfds5PyUG8LOz@dTF4WVc2rOI33LIoTnoBDj/GkqLjhxnLnOdmpE7cLQICC4wbVC1U6y0c8@hvANY5QIcJSKjwOUYwroeZi7JDR5HpX0ZhLkju4BW/klLUJWZdwcBNXR8ZSrEl4FlvIkGsb8cy/n62lFMoKj2cy86ceEZ2r8XhZGVsDRTRytjij2EYyoXY8gc7KrUbWrukjHcaDuNaQ6jwnetWqAJnOg0iTCOXWANRbsmBpWsKZlIxQ5HGqewg9xnhxngvUiUFrhuCMCNBTD0ME@k1CexIOCE2rQFIUEOiKmnTDWtAhAshomb8qNsT8cxBzzgSKxLCLDYkI8JLc7xBgyMJ2Id1zatAVQffr2/vV4Hp4c6sEjPBufD95YN7iST4vV75S683H59fx@0f8Ag "Python 3 – Try It Online") # [Python 3.8+](https://docs.python.org/3.8/) (with [`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), ~~100~~ ~~101~~ ~~100~~ 99 bytes ``` lambda s:[s:=regex.sub('(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$)',r'\3',s)for i in s][-1] import regex ``` Can't [Try it online!](https://tio.run/##VY/dUsIwEIXv8xQR0ewiIMiNU4xw7wuoDWj6B5np3zR1Bir66rhp64zmosl39uzZbXms90W@uC@rcyLVOdVZEGluPd96sop38WFqPwIQoOC0RfVEN53VHZ78LeAGR6gQYSUVnoYoxpVQCzG2mBQVN9zk3G78yXzDTFYWVc3bwHMP9miXvJEz5sxpaz7aqa0jk3uMm4SncQ4pcp1HPHUpUgqVC4@nMvVnnot1rsbjZWXyGpBR2nzZU5xHMqF2PINOy71G5hb3kQ7jQVxr2OksI3ntqgDdj1MRyr0BqPdkwdI4wZodGaHI4p3uEDrGeNnnAnVi4MwQ9ERATz0MEaI4ITpQ4YjQuAokRQGBrqhJN8xBSwTIaJm/VWxI@ecgpZ8JNBLDdmxIQoC/k7sdAgxZ6BbSnaYG7SXo@/zyejG4HF5dKwEjvBlPprfMWz7Ix9XaV2qzfXv/PH19ix8 "Python 3.8 (pre-release) – Try It Online") - Confirmed to work on my machine, but `regex` is not installed on TIO or ATO. Uses essentially the same technique as [suggested by VisualMelon](https://codegolf.stackexchange.com/questions/250596/remove-redundant-parentheses/250617#comment558588_250617). # [PHP](https://php.net/), ~~108~~ ~~109~~ ~~108~~ ~~107~~ ~~106~~ 104 bytes *-1 bytes (→ 106) [thanks to Steffan](https://codegolf.stackexchange.com/questions/250861/add-parentheses-to-polish-notation/250873?noredirect=1#comment559241_250875) with the added bonus of now being an anonymous function* *-2 bytes (→ 104) with no "Undefined variable" warning* ``` function($s){while($p!=$s=preg_replace('/(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$)/','$3',$p=$s));return$s;} ``` [Try it online!](https://tio.run/##VU/LjtMwFN3nK9JgyL1DSqewq8dkFlRohDSDCgugboOTcR6S21hOKqDt8OvlOi0SeGH7PHzPsa3t6Sa1tQ1ZKU7lblv0TbsF1uHhR90YDcyOBOuEdbrKnLZGFRriCUg4rlF@oJNW@hqPyzXgCq9QIkIqJB4ZTuIkZm/ihFmagMid7nduyzr@dOJl64A14pozI8pK9x18@vzu7h45HsKmBGaWXe@MpiYGx9OVEJHcRkjmbpeTQnRynYynyAd3g7qoW2/hIU2d8tDjcChtVNdn2jkKxJH4uJi/z@4fsvli8bBIo7nnZ2E0Yz4TqRkoY2uFgf/XEmkFYa57BZXabIi@9SqAUZv8UZEItm4A@posaBtPdE1FRmg3ulJnCGeMml/mAr3E3JshvyACdFWsQHjUJaGfJPxC2HsFyraFXDl6pPaBBwMigAGV@VfFPTH/OYi5ZAJFYjHEFkTk@Df53CHHIih8IXXmZDQcMe1fvn4bRc/Y8xcyhit8mYxfTYIZvxFv09ullKt19v1wfPod/wE "PHP – Try It Online") ## \$\large\textit{Full programs}\$ # [Perl](https://www.perl.org/) `-p`, ~~52~~ ~~51~~ ~~50~~ ~~51~~ ~~50~~ 49 bytes *-1 byte thanks to dingledooper and [Sisyphus](https://codegolf.stackexchange.com/questions/250556/transform-characters-of-your-choice-into-hello-world#comment558485_250565)* ``` 1while s;(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$);$3 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVDNToNAEI7XfYqKKDNVNNWLkVZ69wVUFnSXLj8JBNJiVMS-iJcetO9kn8ZZFhOdw85-fzuT_fis1bLYBpZbW-Hm66lJ3MvvyeQ5yws1WnnAoYuQ31Cn8s-xCyLAEMfIEcGfcexs9OwLExzym93eFERRZwKZjgVIxUZSNQJSUZZEz7UKUIhSLgSJUGc5QJORBetcE6s8JSNUpUqFgWAwKm94FyiJUptBDogAXYUdIyxUQuiFhFeEViuQVBVIsaSQaJkGPSKAjJb5q2JLzD8HMcNMoJEY92NjIiT-TjY7SIxZrBcShuNW3xw6b-_u960D-_CIOzDG4xP39IxdedPZtT8POA-jh8e37n3tmF_8AQ "Perl - Attempt This Online") # [PHP](https://php.net/) `-F`, ~~103~~ ~~104~~ ~~103~~ ~~102~~ ~~100~~ 98 bytes *-2 bytes (→ 100) [thanks to Steffan](https://codegolf.stackexchange.com/questions/250861/add-parentheses-to-polish-notation/250873?noredirect=1#comment559241_250875)* *-2 bytes (→ 98) with the added bonus of getting rid of the "Undefined variable" warning* ``` <?for($s=$argn;$p!=$s=preg_replace('/(\(|^)\K(\((((?2)|[^()])*)\))(?=\)|$)/','$3',$p=$s););echo$s; ``` [Try it online!](https://tio.run/##VVBNj5swED2XXzFL6XpmG4ra3GoIe1op6mEPvbQNSWrAASSCLUBqy7L96@k4yUrdOTB@H543OFdDfeq1KiHsSxAC@jgW@2uJU5weTI/BkASqrzoZ2JuEge11te@1bVWhUUSY4byj7At3rvQTzZsd0pbuKCPCNMloDigSCxEsxSKwPIEkSV3UJhjk6SXMcwSEHfhx@pSugt4Xz47ys86XAlZQmFJLwEKNEpxAzK0lDHqE0IBtrD6oppUQGTtGtrZR3nSuQ1hApMcCwhKG2vTj3ljd7UdVJY8dhA/nwRDDGmb4VTethvXD1wSujwJKQmm8NxsIJwgm2M6zC5dT8lG@NrYQ3y4vq51/I1C@V5pOw5Jnn1C1tlbkuSfaEJcHuR4VVup4ZPreqYitOualYhFt3SCONVvINo4YmoqNaI66UheIF0xaXuci36TcmTG/IgZ8VEFBWOoDo98s/CGcnIIHYzBXPV9Sk@fAGTEgj5f5X6WJmVcOZq6ZyJFUnGMLJnJ6Sb7skFPhFW4hdeEy/9wEf799/3Hjvw3e3WYC7@j9IvwQeZ9lnKzS@02WbXf7n0/z81/xDw "Bash – Try It Online") [Answer] # [sed 4.2.2](https://www.gnu.org/software/sed/), 98 bytes ``` :a s/(\(([^()]*)\))/\1/ ta s/\(.\)(\([^()]*\))\(.\)/\1\t\2\n\3/ ta s/^(\([^()]*\))$/\1/ y/\t\n/()/ ``` [Try it online!](https://tio.run/##TY3NUoNAEITv@xQaUXqiZku9Jf7kMdRM0FkgQFUIlHAw8efVcRbQcg672/319DZp0nVzMY0FA6sItJ4SE1m@sqb1PmPGpHBginpDObd8zTu@GXPR/0zQ7@@tZnYWZLsOsq1zIQOdFemYI5e2gkzKUu2lp8BWSpeIQtR5AbS5RqguvNEUmQZRlWkmg8SgKV2MvdBNcj4MNyoV@pQgJiTpRtW7gj3h4Ak2VQUnb7okB@NFr1T89UHrKO4rYzUc/bYO/Y5iE/vPZPB40l@hno9Pz8c8OQlOzzjElM4vLmfWzBe3d/cPyxXzOnp5/fj8@g5/AA "sed 4.2.2 – Try It Online") *-a handful of bytes thanks to Jiří for reminding me to use `y`.* *+4 bytes thanks to Deadcode for noting that any printable ascii could be in the input string* ## how ``` :a s/(\(([^()]*)\))/\1/ # remove a layer of any double parens # not enclosing parens ta # loop back to a if we changed anything s/\(.\)(\([^()]*\))\(.\)/\1\t\2\n\3/ # convert (no-parens) to \tno-parens\n # but only if they occur in the middle. ta # loop back to a if we changed anything s/^(\([^()]*\))$/\1/ # Remove global parens if they # don't enclose any parens y/<>/()/ # convert all our \t\n back to () ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~33 30 29~~ 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ø(jẹⱮØ(Œ!ż€¥/ṢƑ€ÞṪ_Ø-fƊF’œP ``` A full program that accepts a string and prints the result. **[Try it online!](https://tio.run/##y0rNyan8///wDI2sh7t2Ptq4Dsg6Oknx6J5HTWsOLdV/uHPRsYlA5uF5D3euij88QzftWJfbo4aZRycH/D/cDpSI/P8/WkkjMacgI1FTiUtHSQMIojWBAMRRSEotSdRIT8zNhUg6gJRpaOQk5ialJEKUaBRkZGpolGQAFWoWZELFijPTgTo08nNT0xPhIhoQIc1Ua4RNGkBTNJOgujSSoAIQPpCXqJKsqZGSmgYRqABKV2pqVEHlNdLy8zWSEouABiRWgQRAfLAAkA9UEQsA "Jelly – Try It Online")** ### How? Partitions the input string at its redundant parentheses and prints the characters that remain. The redundant parentheses are found by first finding the indices of all pairs of matching parentheses in a copy of the input string that has been wrapped in parentheses, and then filtering these to those which are bounded by any other (i.e. rule 1, but removing the inner pair). For that, the list of indices of all pairs of matching parentheses are effectively found by pairing each closing index with the opening index that is closest to its left that has not been consumed by any previous closing index. This is actually achieved by constructing all lists of pairs of opening and closing indices and finding the one that (a) has no reversed pairs and (b) has the maximal list of opening indices when ordered by their respective closing indices. ``` Ø(jẹⱮØ(Œ!ż€¥/ṢƑ€ÞṪ_Ø-fƊF’œP - Link: list of characters, S Ø( - "()" j - join with S -> parenthesised S Ø( - "()" Ɱ - map with: ẹ - all indices -> [open_indices, close_indices] / - reduce this pair of lists by: ¥ - last two links as a dyad - f(open_indices, close_indices): Œ! - all permutations of open_indices ż€ - zip each with close_indixes Þ - sort by: € - for each pair: Ƒ - is invariant under?: Ṣ - sort Ṫ - tail -> X = list of open indices that pair ascending close indices Ɗ - last three links as a monad - f(X) Ø- - [-1,1] _ - subtract [-1,1] from each index-pair f - X filter keep those -> redundant parentheses index pairs F - flatten ’ - decrement (from indices in parenthesised S to indices in S) œP - partition S at those indices, discarding borders - implicit, smashing print ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~53~~ ~~52~~ ~~51~~ 55 bytes *-2 bytes by assuming balanced parentheses in the input* *+4 bytes to fix a bug* ``` .+ ($&) +`\((\((?>(\(()|[^)]|(?<-3>.))*)\))\) $1 ^.|.$ ``` [Try it online!](https://tio.run/##VU7bToNAEH3fr9BKy5liMY1vtkLf/AUVisxSCiRFSOVBEf11nAVMdDLZ3XOZPXNOm@KV1/0cD3HvOgrWgpQTh4C075mTuiCifQd/u7r1XKIlhSStrLWK3M61VN@DT3XOpCAVkJS60GnDyLgshd4ZFThxqQ8sIuq8AJpcLFQXhngrMjGiKtOMR4gRU7qZ/oVMkjZm6AkJkCdbCeGQHgW9i/BBaI2CY1VB81mGuFUGDEgAKVnmr0qtMP8cwkyZkEhKhthECE2/yeMOmhKVmIV45MLZcNlyPj49X86urPkitLEk53rl3qi7zfbe83dBGO6jl/iz@/q2fwA "Retina – Try It Online") **Step 1:** ``` .+ ($&) ``` Surround the string with parentheses (in addition to whatever parentheses it may already have). An alternative way to do this for the same number of bytes would have been: ``` ^ ( $ ) ``` **Step 2:** ``` +`\((\((?>(\(()|[^)]|(?<-3>.))*)\))\) $1 ``` Remove redundant parentheses, assuming that all parentheses are balanced in the input string. ``` + # Loop substitution until its result is equal to the input ` # Delimiter between Retina flags and regex \( # Opening parenthesis (redundant one) ( # $1 = the following: \( # Opening parenthesis (?> # Atomic group – once the following finishes matching, lock # in the match and prevent backtracking into it. ( \( # Match an opening parenthesis () # Push a capture onto the \3 stack | # or [^)] # Match any character other than a closing parenthesis. | # or (?<-3>.) # By process of elimination, this character must be a # closing parenthesis, but only allow removing it if it # corresponds to popping a capture from the \3 stack. )* # Iterate the above as many times as possible, minimum zero. ) \) # Closing parenthesis ) \) # Closing parenthesis (redundant one) # (newline) - delimiter between regex and substitution $1 # Replace with $1 ``` **Step 3:** ``` ^.|.$ ``` Remove the pair of parentheses that surround the entire string, which are guaranteed to still be there. # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~112~~ ~~101~~ ~~95~~ 99 bytes *-6 bytes thanks to VisualMelon* ``` [char[]]($p="($args)")|%{$p=$p-replace'\((\((?>(\(()|[^)]|(?<-3>.))*)\))\)','$1'};$p-replace'^.|.$' ``` [Try it online!](https://tio.run/##VY7rUoMwEIX/8xSIadmtBe34T0rbx1CBakjDZSZcBnCqXHz1upQ61kwmyXfO2eyWxVFWdSKVOrHI7U6eSHjlBQGw0jWA8Squ0cB@1hGz0qpkqbiQpg9Ae7sZT@y9PQY9bNfW48ZGXKCPtM2lyVbm4FxV7e3eZuaJtNZ9cKKiklwkwJSe5jpL8/KjwS6NgLXYHau0kVZS1M1A4ZWj/wm6lRe5PKo0l7rBYM4inSk0hhNwVSYcNaDlIS1ND2XDIeZZRvJudAEUz8IDJxPKJAVoEopgmY5CncYUhCKTMZ8QJkbpXP4FqsRwDEN4IQJ6ciYQDjIi@iTjC6EdHYiKAkJeURFvtRHORIAaDXPtYkvKvwQpl55ALVGc2woSQvztPM0QotDEOBCfNN84Xyadzy@vN8Ytm819ExZ4t7Tse@3JWbub7c7z/WD/9t71w7f5Aw "PowerShell – Try It Online") Uses the same regex and algorithm as my Retina answer, so I figured it'd make sense to group into the same post. Ungolfed: ``` $p = "($args)" $c = [char[]]$p # $c = $p converted to an array of characters $c | ForEach { # Iterate the following the same number of times as $c's length $p = $p -replace'\((\((?>(\(()|[^)]|(?<-3>.))*)\))\)', '$1' } $p -replace '^.|.$', '' ``` # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 94 bytes Using [Neil's regex](https://codegolf.stackexchange.com/a/250642/17216), with a -1 byte golf from me: ``` [char[]]($p="$args")|%{$p=$p-replace'(^|\()\(((?>((\()|[^)]|(?<-4>.))*))\)(?=\)|$)','$1$2'};$p ``` [Try it online!](https://tio.run/##VY7dUoMwEIXveQrEtOzWUq3jlZTSx1CBakjDzww/GcCpAvXVcSl11Fwk@51zNruqPMqqTmSWDSxyusETCa@8IACmHIPxKq4N7GcdEVNWJVXGhTRh3/uAPgC4WwAqe2@PQQ/uxnrYrhAXiD6C6/jYMzSXJluze/NkMzXQ1Tp3dlRWkosEWKanhc7SQr032KURsBa7Y5U20krKujlReG3rv4JuFWUhj1laSN1gMGeRzjI0TgPwTCUcNVoJPKSj6aFsOMQ8z0nejS5AxvPwwMkElaQATUIRVOko1GlMQShzGfMJYWKU9uVfoE4MxzCEFyKgkjOBcJAR0QcZnwjt6EBUlhDyipp4q41wJgLUaJm/Lrak/EuQcpkJNBLFeawgIcSfydMOIQpNjAvxSfON82PS/fT8cmVcs9ncN2GBN0trdas92htn6@483w/2r29df/oyvwE "PowerShell – Try It Online") [Answer] # Python3, 275 bytes: ``` lambda x:P(f(x)[1]) P=lambda x,l=0:[]==x*0and'('*l+''.join(P(i,1)for i in x)+l*')'or x def f(s): r,*t=0,'' while s: h,*R=s if'('==h:s,T=f(R);t+=T,'' elif')'==h:r=1;break else:t[-1]+=h;s=R return s[r:],(lambda x:len(x)<2and[]==x[0]*0and x[0]or x)([*filter(None,t)]) ``` [Try it online!](https://tio.run/##XZLLbtswEEXX9VcQQgDNyGxgt5tCDoF8QWAY2alakBFlsaEeIBlUadFvd0cPK1a44tw5uDOXYPceqrb5/qNzl0L8vFhZq0KyPj1CCT1m@xw3R3FVuRW7NMuF6JOdbIoY4sRu4/j@V2saOILheyxbxwwzDetxa5MYY6r7TaFLVoLHdMMcT4LY8TjesN@VsZp5ElnFk5PwdDEluQpRpZ4/ixJOeAhb8TziTFvq4th1Yn9QTsvXUfY6DdnXfb4V1cGLEw3R4c01zGcuzTksoaxuKNTDN9p9TJHt8jEIG27DoghZUhobtIOnttE8YI6XIZLkTA2p/tI8FoG0XSUxStnqRKMc8YmhkyGdNRVlc58pHSScZV2vjNb6hD4OtjDH@DCc9Vm@ju0qAxAqMsHOLHC0lq@wN2caA22tzzdbfNY/YJhU1IcFj9byTXqgXVGtHoBeDtWCqJlZIwqWkQTIuxcE@j63zCd9Ynsye0f4M7kN5VRR@9@9Cbr2QN/vi/Reu8AKGiKEuvwH) [Answer] # Regex (.NET), 200 bytes `s/(?<=()^\(*|)(?=\(((\()|[^)]|(?<-3>.))*(?=\)+$()|)(\).*)).(?=\1\4|\(((\()|[^)]|(?<-7>.))*\)\5$)|\)(?=\)*$()|)(?<=(.*\()(?<=^\(+()|)((\))|[^(]|(?<-12>.))*.)(?<=\8\10|^\9\(((\))|[^(]|(?<-14>.))*\).)//g` [Try it on regex101!](https://regex101.com/r/xRyPIS/1) This is a single regex substitution, to be applied once. It's one and done, erasing all the required parentheses in a single pass. This is the only kind of substitution that can be easily used on regex101; ones requiring multiple passes need to have their output manually fed back as input each time. ``` (?<= () # \1 = set if to the left is a continuous stack of # opening parentheses ^\(* | ) (?= \( # Match an opening parenthesis. ( (\() # Push an opening parenthesis onto the \3 stack. | # or [^)] # Match any character other than a closing parenthesis. | # or (?<-3>.) # Match what must, by process of elimination (with the # assumption that the input is balanced) be a closing # parenthesis, while popping a capture off the \3 stack. )* (?= \)+$ () # \4 = set if to the right is a continuous stack of # closing parentheses | ) (\).*) # \5 = mark spot by capturing everything to the right ) . (?= # Assert \1 and \4 are both set \1\4 | # or # Assert that the next deeper set of parentheses is adjacent on both # sides to the pair we just processed. # First, match balanced parentheses the same way we did above, but one # level deeper, starting by asserting that the next opening parenthesis # is immediately adjacent. \( ( (\() | [^)] | (?<-7>.) )* \) # Assert that this brings us exactly to the spot we marked with \5. \5$ ) | # Do the same thing as above, but exactly in reverse. Note that lookbehinds # are tokenwise evaluated from right to left (bottom to top in this view # here). That means alternatives are still evaluated left to right within a # group, but the matching of groups/characters/backreferences is done from # right to left. \) (?= \)*$ () # \8 | ) (?<= (.*\() # \9 (?<= ^\(+ () # \10 | ) ( (\)) # \12 | [^(] | (?<-12>.) )* . ) (?<= \8\10 | ^\9 \( ( (\)) # \14 | [^(] | (?<-14>.) )* \) . ) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~31~~ 29 bytes ``` Ø(j ẆṚẹⱮØ(>/SƊÐḟÇ€¹œṣÇ}jʋƒÇḊṖ ``` [Try it online!](https://tio.run/##y0rNyan8///wDI0sroe72h7unPVw185HG9cBBez0g491HZ7wcMf8w@2PmtYc2nl08sOdiw@312ad6j426XD7wx1dD3dO@///v5IGCCQmaWoma2pqpKRqVgC5lZoaVZpAoAQA "Jelly – Try It Online") If Jelly had a builtin for "is a balanced string", this would have been much shorter. A "replace substring" builtin could also have helped, as would better chaining rules for dyads. (My recommendation for dyad chains is to start with the left argument, then mostly use the monad chaining rules with the right argument, keeping the special case for `+×` but discarding the other dyad chaining rules. That would have saved two bytes in this program, compared to Jelly's current chaining rules, and would also be much more intuitive.) Larger-scale problems like this one can be good at exposing some of Jelly's shortcomings. Thanks to @Unrelated String for pointing out that I'd missed a builtin – using `ẹ` rather than implementing it manually saved two bytes. ## Explanation ### Helper function `1Ŀ` The helper function encloses a string in parentheses, and is called using the shortcut `Ç` (which calls the other function, when only one function is available, thus there's no need to state its name explicitly). ``` Ø(j Ø( ["(", ")"] j join this list by {the function argument} ``` ### Main program Outputs a string with redundant parentheses removed. ``` ẆṚẹⱮØ(>/SƊÐḟÇ€¹œṣÇ}jʋƒÇḊṖ ẹⱮØ(>/S check if a string is unbalanced Ɱ for each of Ø( ["(", ")"] ẹ find the indexes at which it occurs / compare these two lists with each other > by greater than of corresponding elements S sum (i.e. true if there are any nonzeros) Ɗ parse the entire check as a single group Ẇ find each substring of {the input} Ṛ ordered from longest to shortest Ðḟ keep only those that are not ẹⱮØ(>/SƊ unbalanced Ç€ call `1Ŀ` on each of them ƒ iterating over this list, using an accumulator Ç initialised to `1Ŀ` of {the input} ʋ do all of the following, parsed as a group: œṣ split {the accumulator} on Ç `1Ŀ` } of the current list element j and join on {the current list element} {to produce the new accumulator} ¹ (fix for parser ambiguity) ḊṖ delete the first and last elements ``` There's an interesting subtlety in the check for unbalanced strings. The main idea is to check the indexes of the opening parentheses and of the close parentheses, and try to find an *n* for which the *n*th opening parenthesis appears after the *n*th closing parenthesis (thus, we're comparing the two lists with an element-wise `>` that compares corresponding elements of the two lists). However, if the number of opening parentheses differs from the number of closing parentheses, the element-wise `>` will be trying to compare two lists of different lengths. In this case, it ends up just outputting the extra elements literally (so, e.g., comparing [4,3,2]>[1,2,3,4] outputs [true, true, false, 4]). This doesn't make much sense mathematically, but means that (because Jelly uses 1-indexing) the result will contain a truthy element if the two lists are different lengths, so the string will be seen as unbalanced (which is correct – if the number of opening and closing parentheses differ, it can't be balanced). It took me a while to find a check for string balance that could handle both the equal-parenthesis-count and unequal-parenthesis-count cases without needing a separate check, but I'm happy with this one. Once we have a list of all the balanced strings (say *`x`*), the algorithm is to replace `((*x*))` with `(*x*)`. As long as this is done in order from longest to shortest, all the internal redundant parentheses will be removed. To remove redundant parentheses around the string as a whole, the idea is to enclose the string in parentheses to start with, and remove them at the end, so that the same redundant parenthesis removal algorithm works to remove both internal and external redundant parentheses. This fits in rather nicely with the `ƒÇ` construction, allowing the loop to start with a parenthesis-enclosed input without requiring any extra plumbing (if attempting to use the input directly rather than a function of it, it might well require spending another byte on parser ambiguity fixes). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~50~~ ~~47~~ 46 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ®1‚„()ISkkƶ0KvyDdi‚ˆ]¯.Æʒ`αP}€¨¯ʒ®Ig‚Q}«˜Ä<õsǝ ``` [Try it online](https://tio.run/##AWEAnv9vc2FiaWX//8KuMeKAmuKAnigpSVNra8a2MEt2eURkaeKAmsuGXcKvLsOGypJgzrFQfeKCrMKowq/KksKuSWfigJpRfcKry5zDhDzDtXPHnf//KGFiYygoMTIzKSkoaykp) or [verify all test cases](https://tio.run/##TZDBSsNAFEV/JQwu3oNSrC4V6sKdG0WUQin4JkmT0IYUW4opFIpI15KlqGtBaSmoHzABhRb8iPxIfDMTi2HI3HPvnTcwyZBk5JfjtCmcYp45opnm9xeiVItGMXsoZs@ArfNe7@tz92ScHnsRm5t5Ry3r@XydXf2sTqfF7Zt6Uct1phatgOOzqXrdPOZ3h/nH8PupFPXLmnov2wJIugCNvX1E6CGKmiBZMWudam1kfxCSUfy1EU3Bkf6IIKA4NtGR7gD0KZYe2QmDMAIYhVzDQWStYRRwHZLYD@jPAOugf7C9A3gCSnsEZMUGGWjHRfD8ruEbDlOEiU2hmyQg6ZoP04RZo2HGf7OBR6Nbjec3YN7e4IiG/oGRxIlrEIy0BQbihXpHJKpchCrVir3OLw). **Original (completely different) 50 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach:** ``` ŒʒÁÁ4ôć„()©º{RQiJ®Ã®õ:õQ]vyD¦¨:}Ð'(Å?i¦¨‚¤®Ã®õ:õQè ``` [Try it online](https://tio.run/##yy9OTMpM/f//6KRTkw43Hm40ObzlSPujhnkamodWHtpVHRSY6XVo3eFmIN5qdXhrYGxZpcuhZYdWWNUenqCucbjVPhPEe9Qw69ASZGWHV/z/r5GYlKyhYWhkrKmpka2pCQA) or [verify all test cases](https://tio.run/##TZCxS8NAFMb/lXAIvgdFqDrVIQ5ObhV0KR3epWkSbEiwpZiK0CLqWjI6OInUxaldHO908c/IPxLf3cXScEm@3/d99w4uG5NMwnpa@MKrnkpP@IVeXor6p/wt9UIvjvX6@7mavwKqD/V1d9FNztWnfuB309Gbbn9anKl3terc6@U@6Ec/MVTNX9Tbbk2vanFw1VLruieAZADQPjxChGtE0RIkG2ZtUqOtHOUxWcVPD9EWPBlOCCJKUxudmg7AiFI5IDchjxOAScw1zBNnjZOI65ClYUT/BjgHw5PtGcATULotIBu2yEB7AcIgHFq@5bBAmLkUhlkGkm54M82YDVpm3JkNPBqDZjzfAfP2BE@0zQesJE4Ci2ClKzAQLzR/RKLGRWhSo9jr/wE). Both can most likely be golfed quite a bit more, but these kind of challenges aren't really 05AB1E's (nor my..) strong suit, especially with all these edge-cases. **Explanation 1:** Step 1: Get a list of all index-pairs for the balanced parenthesis: ``` ®1, # Push pair [-1,1] „() # Push string "()" I # Push the input-string Sk # Get the index 0-based index of each character in string "()", # or -1 if it's neither k # Use that to index into the [-1,1] (basically replacing -1s with 0s and # vice-versa, without changing the 1s) ƶ # Multiply each value by its 1-based index 0K # Remove all 0s v # Loop over each index: y # Push the current index to the stack Ddi # Duplicate it, and if it's a positive index: ‚ # Pair it with the top negative index of the stack ˆ # Pop and add this pair to the global array ] # Close the if-statement and loop ¯ # Push the global array ``` [Try just step 1 online.](https://tio.run/##TZC9SsRAFIVfJQwW58IiRkuLtbCzFEVYtriTzCZDNiS4y2K22mprsbTwEbQRHyCCjW@RF4l3fnYxDJnznXPmDkyzYm3NuOmmKhn2L4madt/Pd2rs39Nh9zrs3kAPt1X183V2s@mucyvm737ef4zq9H7Sf44zBdYZkJ5fEKEiUhPFOrJolzrt5bIt2Sv5ZkS@kGizZhRc1z66ch1gybXOOUxoSwusS6lRa4O1soXU0dSm4IOB4JC5PN4BmUA6HIGO7FGATzJCbhaenyTsCNuQYtE00Pwoh3kr7NCz4L/ZkNGUxfHyBsLHGxKVuh@8ZEkyj/AyFARYFrmdiDm6hJg6Jd78Dw) Step 2a: Keep all the pairs which has a neighboring pair available: ``` .Æ # Get all unique pairs of this list of index-pairs ʒ # Filter it by: ` # Pop and push both pairs separated to the stack α # Get the absolute difference at the same positions P # Product to check if both differences are 1 }€ # After the filter: map over each pair of pairs: ¨ # Remove the last one ``` [Try steps 1 and 2a online.](https://tio.run/##TZDBSsNAFEV/JQwu7oNSjC5d1IU7N4IoQin4JkmbkIYEW4opCMVF1tKlC9cuRBHED0jBhQU/Ij8S38zEYhgy99x75w1MPmOdRO2iHCivqdaeGpSbhwvV1q9@s3psVk@gq/M0/frcP12UJ2Ei5rYa1W/9TfW9vv55P7tr7l/q51b1L3v1RztUYB0A/sEhEVIi1VOsOxZtUqOtnBYxWyXfkMgWPB3NGRPOMhsdmw4w5UyH7CYUcQLMY6lRkThrlkykjjyLJvxnwDkUHe3ugEwg7Y5Ad2xRgPcCQhiNLd9KWBKWLsU4z6H5Rg7zUtigZcF/syGjKejGyxsI727wlG9@sJIlCSzCSlcQYFlkdiLmziV0qVHijX4B) Step 2b: If the input is surrounded by a pair of parenthesis, add its index-pair as well: ``` ¯ # Push the global array of pairs again ʒ # Filter it by: ‚ # Pair ® # -1 Ig # with the length of the input-string Q # And check if the current pair is equal to this }« # After the filter: merge the two lists of step 2a and 2b together ``` [Try steps 1 and 2 online.](https://tio.run/##TZDBSsNAFEV/JQwu3oNSGl26qAt3biyiFErBN0mahDQk2FJMoVBcZC1ZunAtKC2C@AFTcFHBj8iPxDczsRiGzD333nkDk81IxkGzKPrCqcvKEf1i93gtGrVx6/VTvX4GHF4lyddn72JRnPsxm9/lWG27u3Jf3f68X67qhzf1orb7Sm2GIceDlXptRPemoz6akQCSHoB7fIIICaLoCJIts9ap1kZO84iM4m@EaAqODOYEIaWpic50B2BKqfTJTsijGGAecQ3z2FqzOOQ6ZGkQ0p8B1sHg9HAH8ASU9gjIlg0y0JGH4AcTw/ccFghLm8Iky0DSHR@mJbNGw4z/ZgOPRq8dz2/AfLjBEa7@gZHEiWcQjLQFBuKFekckal2ENtWKvfEv) Step 3: Remove all characters at those indices, and output the result: ``` ˜ # Flatten the list of index-pairs Ä # Get their absolute values, to make the negative indices positive < # Subtract 1, to make the 1-based indices 0-based õ # Push an empty string "" s # Swap so the list of indices as at the top ǝ # Insert the empty string at those indices in the (implicit) # input-string, basically removing them # (after which the result is output implicitly) ``` **Explanation 2:** Step 1: Get all substrings of the input, and filter it to only keep those with double leading/trailing parenthesis-pairs: ``` Œ # Get all substrings of the (implicit) input-string ʒ # Filter it by: ÁÁ # Rotate the substring twice to the right 4ô # Split the string into parts of size 4 ć # Extract the first item „() # Push string "()" © # Store it in variable `®` (without popping) º # Mirror it to "()()" { # Sort it to "(())" R # Reverse it to "))((" Qi # If the extracted head is equal to this: J # Join the remainder-list together ®Ã # Only keep all "()" ®õ:õQ # Check if these parenthesis are well-balanced: ®õ: # Keep replacing all "()" with "" until it is no longer possible õQ # Check if the result is "" ] # Close both the if-statement and filter ``` [Try just step 1 online.](https://tio.run/##TZCxTsMwFEV/JbIY7pMqpAITDGVmayVYqg7PaZpYNErUVoiUhQoJVpQPYGdhahfGGBY@oz8Snu1QETnJPfc@X0sulqxN0t5VAxXtn@tIDSr7eq3a7/qnthu7ObPbr5f94xuoeW8@H0ZDc9V82Cd5d@d2N5y06vim12zbsQLrGOifnBLhlkj1FOuORbvUaS/nZcZeyTMm8gORTlaMlPPcR5duBphzrqccGsrMAKtMxqg0wVqaVMZR5EnKfwaCQ8nF4QxIA@mwBbpjjwJ8FBOmyczzvYQVYR1SzIoCmheymdfCDj0L/uuGVFPc1csdCB9OiFTffeAlSxJ7hJdhQIBlkfsTMXcuoUudEm/yCw) Step 2: Replace all these filtered substrings with it's leading/trailing parenthesis removed in the input-string: ``` v # Loop over each of these filtered substrings: y # Push the current substring D # Duplicate it ¦¨ # Remove the first and last characters (the "(" and ")") : # Replace it in the (implicit) input-string } # Close the loop ``` [Try steps 1 and 2 online.](https://tio.run/##TZAxS8NAGIb/Sjgc3g@KUHWqQx2c3CroUjp8l6ZJsCHBlmIqgkXQVfIDHEUXp3ZxvNPFn9E/Er@7xGK4JO/zvt@9B5fPWKdRvSj7Ktg@VoHql/b5QtXf1U9lV3Z1ZNdfT9v7F5B5N5@354P0zHzYB3k3PbsZjBblqXk1b727Wu1fdsy6HiqwDoHuwSERrohUR7FuWbRLnfZyWiTslTxDIj8Q6GjOiDnLfHTiZoApZ3rMTUORpMA8kTEq0saapbGMI8@imP8MNA5Fx7szIA2kmy3QLXsU4L2QMI4mnm8kLAnLJsUkz6H5WjbzUtihZ8F/3ZBqCtt6uQPh3QmB6roPvGRJQo/wshkQYFnk/kTMrUtoU6fEG/0C) Step 3: Remove a potential leading/trailing parenthesis-pair, if everything else in the string is still well-balanced without it, and output the result: ``` Ð # Triplicate the current string '(Å?i '# Pop one copy, and if it starts with a "(": ¦¨ # Remove the first and last character from another copy ‚ # Pair it with the string ¤ # Push the string with first/last characters removed (without # popping the pair) ®Ã®õ:õQ # Same as in step 1 to check if its parenthesis are well-balanced, # resulting in 1 or 0 for truthy/falsey respectively è # Use that to index into the pair # (after which the result is output implicitly) ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~215~~ ~~204~~ ~~195~~ ~~214~~ 205 bytes *-11 bytes [thanks to Unrelated String](https://chat.stackexchange.com/transcript/message/61726656#61726656)* *-9 bytes thanks to att* *~~+19~~ +10 bytes to properly handle input containing single quotes and/or backslashes* ``` lambda x:P(Q(eval(repr('"\''+x)[3:].translate({40:"',['",41:"'],'"}))))[1:-1] P=lambda x:[]==x*0and'(%s)'%''.join(map(P,x))or x Q=lambda x:(x:=[Q(y)if[]==y*0else y for y in x if y])==[[*x[0]]]and Q(*x)or x ``` [Try it online!](https://tio.run/##bZTNjpswEMfPy1OMrEYepzRKtHtYEVmq1FNvyZlwMMQkrPgS0Aqy2msfoI/YF0nHfAWS9cn85s9/ZoyHvKnOWfr8mhfXUB6usUr8o4La2eEe9W8VY6HzAjk7cP61Fu6z462qQqVlrCqN7y9rh3Hb5cx@2dDOszn7ELTcjfNt41k7Ofq5npT1cq3SI8dFKfiC89VbFqWYqBx3di1EVkBt7W9vYO1Id4@NiELzcrNc67jU0EBIygaiFGqIQmg8IaXrLmt37Xke@cMel3Xrdq10WZUg4d0CAIYqzs9KMAdmi7WY2Z2Glms6mKuY28fB15XCk0qSmdGcd9Lvxhax6@dm2PMeD2nzc4RYnclE5NEoZnM8iMvoRGkwS/RpUsU9v4mxo0JvRzmb40n3SLUKf3YAdHLCHyV@r5lLfBxTkkB9CQQedTjV3PFOW5NZI/Byd@KGd3hIG2YZ@qqg0tRl4jnnndaglhGa5p/zWcdIDYtg8pEGGIy6gIS@uOucBQO8@SlzfMHd/THYH90Cc4jq8ZYZPvU6MPFwXYEd2Cjgn8SB8ZvB4RMFI0qKD@si11uIs/REY2K2br8HR0KiauwfbYh12v0HTM3t/CnbNxPYDtgqqnRSovCsLgKPIcd6olG9OJAXUVqhsJ4ucrOFgGYzJNNtz/mPrCh0UFHB3Mx2IKUP7dTzn2nQx7gNOj1Kvijh35@/sCg5LGAobxW//SqroXJhQ8vpy4rrfw "Python 3.8 (pre-release) – Try It Online") This was inspired by [Ajax1234's **275 byte** answer](https://codegolf.stackexchange.com/a/250615/17216), which had already had 48 bytes knocked off it (starting at 323 bytes) by okie, Unrelated String, and Steffan. The `P()` lambda here is based directly on its `P()`. The rest is completely refactored to be functional rather than imperative, but follows a similar approach: 1. Convert the string into a ragged list. 2. Do the parentheses removal on the ragged list. 3. Convert it back into a string. This will be surrounded by outermost parentheses whether or not the original was. 4. Remove the outermost pair of parentheses. In more detail: `repr('"\''+x)[3:]` - backslash-escape single quotes and backslashes, and surround with single quotes (forces `repr` to use single quotes even if they're in the input, by putting a double quote in it) `.translate({40:"',['",41:"'],'"})` - replace `(` with `',['` and `)` with `'],'` At this point, e.g. `"(sig(ma)(om)ega)"` will have become `"'',['sig',['ma'],'',['om'],'ega'],''"`. When we then `eval()` it as Python code, it becomes a ragged list that is a `tuple` on the topmost level, containing lots of empty strings, `''`, mixed in with the strings/lists we want. The job of `Q()` is to recursively remove the empty strings (which results in the original string converted to a ragged list), and unnest lists whose only element is another list. `[]==y*0` is true iff `y` is a list – golfed down from `type(y)==list`. `x:=[Q(y)if[]==y*0else y for y in x if y]` recursively applies `Q()` to `x`'s list elements, and removes its empty string elements. `x==[[*x[0]]]` is true iff `x` is a list whose only element is another list – golfed down from `type(x)==list and len(x)<2`. `Q(*x)` recursively applies `Q()` to the result of dropping one pair of surrounding brackets from `x` (unnesting it by one level). `'(((((a)(b)))c))'` will have become `[[['a'], ['b']], 'c']`. `' beta(gamma)'` will have become `[' beta', ['gamma']]`. `'(alpha)'` will have become `['alpha']`. `'epsilon'` will have become `['e', 'p', 's', 'i', 'l', 'o', 'n']`. `P()` then converts the resulting ragged list back into a string, surrounding lists' contents with parentheses and joining the strings. `[1:-1]` removes the outermost pair of parentheses, which will be there even if the original input didn't have them. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~53~~ 52 bytes ``` +`(^|\()\(((?>((\()|[^)]|(?<-4>.))*))\)(\)|$) $1$2$5 ``` [Try it online!](https://tio.run/##VY7NUoNAEITv@xQaN9KTmFhaejERcvMVVDbILCFAVRAqclBEXx2HH6t0D7vzdffszDGusldup3gI23mIoDEgA8BzASkbP6BtA2@9uHGXRDMiQzDUaFL6Sl/r27YFH8qUSUkTfJKjTmxcMRLOc5E3nQscOLc7FhNlmgFVKhEqs054yxIJosjjhAfEwBSvxn8hnWS7MOxIAlKyjgi7eC/0LsYHoe4c7IsClo/SxLXqoCcBUrLMX5dqUf4lRBlnQkZS1I@NRLD0O3nYwVKkom4hHjQz6R9H7sen59PJmZ6eGwczml8slpfqbrW@d72Nb8w2eAk/m69v5wc "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Works by removing all inner sets of balanced parentheses that are contained by parentheses or match the whole string. Uses the assumption that all parentheses are balanced meaning that the input can't be something like `(@))((@)`. Edit: Saved 1 byte thanks to @Deadcode pointing out that I didn't need to use lookarounds. [Answer] # [Python 3.10](https://www.python.org),~~194~~ ~~193~~ ~~183~~ ~~177~~ ~~174~~ ~~173~~ ~~165~~ 163 bytes * -1 byte since one string didn't need to be raw * -10 byes by using a recursive function to re-assemble the output rather than regex * -6 bytes thanks to @deadcode by using `map()` instead of a comprehension * -3 bytes by copying string comparison logic from dead code's answer * -8 bytes thanks to @deadcode and @steffan * -2 bytes by using old-style string formatting instead of modern f-strings Since it's a slightly different approach than the other python answers I think this deserved it's own answer. Probably further golfable. ``` lambda x:u(eval(s('\)\(','),(',s('(?<![^(]),','',s('[^()]+',lambda i:",%r,"%i[0],x)))))[1:-1] u=lambda g:g if''==g*0else"(%s)"%"".join(map(u,g)) import re;s=re.sub ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZNNcpswGEAX3XEKRQ3Vp0R2k10HhybHaAskFURgtcYwCDp20vQSXXbjmUxzp_Q0FRZgxFgLQE-P70egPy_ltl4W691z6od_mzqdfXh9XvE8vudo4zUgfvAVKCAhDYEwQpm-6ilcX50EtxBRpuGe6BmNzgnr3pUeZm7FsCuDi4htaDuCS292GTmN3zmZlyGZEuL72dmFWCmBwVUUuxjPvxVyDTkvoWEZpY7My6KqUSUWyq_EXDWxKfXfm9-1UPVdwpVQyEcIPWLgq3LJKfaQNfAeY-a0z6BH0JZkWzjo1lEsag4Zz3MrkM2NetOGBTAtHQJ2vMN92nIpAeqlDkJLOcjYxr2sZKbTQJGLbFTFlB9kMJSKxaBjG4-6B10rja0N0DtH40GJO8dWYhhSaoGfJhTuRTp2Jty4Gx1sS-FhsuMtN7hPmxYFxLzSpfGHUUybG7dFe6bROL_NrY5BN0yT0UfqYTJ4iRZjOukcJz0cvBBPf56Wh3gQyJF1hMmwrjeHIYBs8gnSlmZ9nk-fv5yE-O2p-y4kcEbP2Wz-XuvHuXnFW1z5H69vgjCMbu--Pv58-kUw8o5z58lx0qJC38WW6XPeCCTX6HCg5rIWuQLqtYFRWcl1DSlomRqbmYnvm5kSpU_CmlBzNnc7c_8P) ## Explanation 1. Extract all sequences that don't contain parenthesis and surround them by quotes and commas. ``` a = re.sub('[^()]+',lambda i:",%r,"%i[0],x) ``` 2. Remove commas at the start of the string and right after opening parenthesis ``` b = re.sub('(?<![^(]),','',a) ``` 3. Eval the string then repr it again, this part actualy does the parenthesis removing ``` c = eval(b) ``` 4. Basically a custom repr function that ignores strings ``` u=lambda g:g if g*0==''else"(%s)"%"".join(map(u,g)) d=u(c) ``` 5. Remove the first and last character ``` f=e[1:-1] ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 112 bytes ``` a=>a.map((c,i)=>c=='('?a[a.push(!i|a[i-1]==c?[c]:c)-1]:c==')'&&(a[p=a.pop(),i+1]||c)==c?(p[0]='')+p&&c:c).join`` ``` [Try it online!](https://tio.run/##XZHBcoIwEIbvPkXKdGB3xEx7lYn20nMfIMOMSwwQC5IR2qmtPjsNgijuLV@@/JtsdvRNtToY2yz21Va3qWhJrIiXZAFUaFCslBABBGuSxO1XncOTOZE0i9dYCLWWKl4qdItlp2Hg@0DSCqdWFjA089f4dFLYqWDlSyyCAOfW95U7xXeV2W82baPrRlGtaybY34wx5gEVNif0lmxS3gV7Ye@4kuhqanly2GeJbggyKstJ0JT36lsXC1BQmWzpFjjwAV/b2twANLkLQWtG2Zviq1ybzLWBqtTZ3S0e@U2GnqKORt2b4rvXg7srJpMBuMlhMirJ4EyVBMaWTqBnhbDV6b3zwHv3x4UdEX4fJt7xHjvvHM0@kp1WDf/UxxrGj0WeVod3UjkYJlaXT1bVvq4KzYsqgxQk59zEyIRg4yFp4pCNWxjNzhi1/w "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~32~~ ~~30~~ ~~28~~ 27 bytes ``` =þØ(_/µJṁ"Äo¹ṁɗ\ḟ"JċⱮ`HnAɓx ``` [Try it online!](https://tio.run/##y0rNyan8/9/28L7DMzTi9Q9t9Xq4s1HpcEv@oZ1AxsnpMQ93zFfyOtL9aOO6BI88x5OTK/4fbn/UtCby//9oJY3EnIKMRE0lLh0lDSCI1gQCEEchKbUkUSM9MTcXIukAUqahkZOYm5SSCFGiUZCRqaFRkgFUqFmQCRUrzkwH6tDIz01NT4SLaECENFOtETZpAE3RTILq0kiCCkD4QF6iSrKmRkpqGkSgAihdqalRBZXXSMvP10hKLAIakFgFEgDxwQJAPrINGkALNJNhliQDxZI04fbEAgA "Jelly – Try It Online") Removes every pair of parentheses which is the only thing contained by either an outer pair or the entire string. ``` =þØ( Table equality with "()" _/ and subtract the close parens from the open parens. Ä Cumulative sum, to get depths, µJṁ" repeat each index by its depth, \ and scan by: o overlay the element on the accumulator ¹ ɗ then ṁ trim the accumulator to the element's length. ḟ"J For each result, filter out its index. =þØ(_/µJṁ"Äo¹ṁɗ\ḟ"J This results in a list of lists where each list uniquely represents the deepest pair of parentheses containing the corresponding element. ċⱮ` Count how many times each list appears. H Is each count halved n not equal to =þØ(_/µ A if the corresponding element is a paren? ɓx Replicate the input by that result. ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), 190 Bytes ``` def f(s,r="",o="("): while o in s:a,b=s.split(o,1);i=[b.count(o,0,i+1)-b.count(")",0,i+1) for i in range(len(b))].index(-1);s=b[i+1:];r=r+a+o+f(b[:i])+")" if r+a+s else f(b[:i]) return r+s ``` No regex library! This works by going through each open paren, finding the matching close paren, and recursing on the contents. If, at any recursion level, the parens identified enclose the whole string being considered, they are redundant and discarded (as they either enclose the whole string or enclose a substring that is immediately surrounded by another pair of parens). Un-golfed Version: ``` def f(unparsed_string): ret = "" while "(" in unparsed_string: # Split on first open paren first, rest = unparsed_string.split("(", 1) # Find index of matching close paren; it's the first index in `rest` # where the number of close parens is one more than the # number of open parens. # This will error if the parens are unmatched close_paren_index = [ rest[:i+1].count("(") - rest[:i+1].count(")") for i in range(len(rest)) ].index(-1) unparsed_string = rest[close_paren_index+1:] if (ret + first) or unparsed_string: # Recurse on the contents of the identified parens ret += first + "(" + f(rest[:close_paren_index]) + ")" else: # If the identified parens are the beginning and end of # the string, they are redundant; return just the recursed payload ret = f(rest[:close_paren_index]) return ret + unparsed_string ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 206 bytes ``` s=>eval(`[${s[[].__proto__.toString=function(){return this[1]?this.map(e=>Array.isArray(e)?`(${e})`:e).join``:this[0]+''},r='replace'](/[^()]+/g,m=>JSON.stringify(m)+',')[r](/\(/g,'[')[r](/\)/g,'],')}]`)+'' ``` [Try it online!](https://tio.run/##XZLBbqMwEIbv@xQWisSMQmn3mop099pDe@jRZYNxDHEKGBk3ahrl2bODA0moL8jf/3nGY7EVO9FJq1t315i1OhXJqUuWaicqyPjs0HGexqtVa40zq1XszJuzuimT4rORTpsG8GCV@7QNcxvd8d/pU/@Na9GCSpZ/rRX7WHf@CwqfMpgd1BGzhcJ4a3STZQt/7iGdh@ExskloVVsJqcIU7vk/wHR@X0Z1snx@e32JO99bF3uocR5GIXJL2juQEvJxh/0upfCYZmSFp8JYBtI0nWP8I2K7lJmCveZbJV2sGiqpOjj8YiwAUbUbgcGCXVbgURD5mBZHWlch4OeI5coJKEVdX45Pmbf@9LUAKlHna3EuM7ABDX3ajQZwGzqOrfZeMEWD1@mSaoOpVTm0/ckuHpwhqkdvBlN0nQ/oXphfRqQnwXxM8yG@pjmMPSgTM4mwVsUY/2Be@6ISe4Tvm0fs2RkNfQpjIBeWriG@h0pT5rWeeERkbDhltzMBjYRyePIRyFGR5OR4M1sgR0DKEZH1f4@pVFyZEgr4QJYkCdtFjH6nfouPp/8 "JavaScript (Node.js) – Try It Online") [Answer] # [Rust](https://www.rust-lang.org), ~~408~~ 396 bytes I made this problem way to hard for myself ``` let f=|b:&[u8]|->Vec<u8>{let v=(0..).zip(b).scan(vec![],|a,(b,c)|Some(match c{40=>{a.push(b);None}41=>{Some((a.pop()?,b))}_=>None})).flatten().collect::<Vec<_>>();for k in &v{if k.0==0&&k.1==b.len()-1{return b[1..b.len()-1].to_vec();}for l in &v{if l.0==k.0+1&&l.1==k.1-1{return [&b[..k.0],&b[l.0..k.1],&b[k.1+1..]].concat();}}}return b.to_vec();};let g=|mut b:Vec<u8>|{while f(&b)!=b{b=f(&b)}b}; ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVFLjpwwEFW2fQo3ilBZQ1uNNIsWDExOkE2kbBBq2bT5qM1HYHoyDdwgN8hmFskqBxolp0kZyPR4g9-nXhXlHz_bvtMvv9OKlLyogJLhV6_T3eHvh-9KapIGo_DsqD_E4y78KpOH_hAORrgEsGeMsmvRgKCsS3gFF5lso9gZuQPCSej4pS4llFwnOUmG-30QDpw1fZdjgf-5ruR07yI3uwCVugH66AhKp2MQzjqlLFVca4mDsaRWSiba8x7MHMcwBOqndUvOpKiIfRmKlJzZPgj2tn1mbhAIpkzdzh1aqfu2IiJyGXtjY6brI06MKZOJUbcYZWIw6861bWWiMO8WE9kiYgzl2MEbeg1wZ4DfO-wRxzhslXBtsqfpf_t3DX2zwiwYy14T4a17HYenvFCSpGALug3EIIL5OonJXx7lT2Mm5W1mZu30yfNkdfE8JDqgw4asp2mLSqtqC9YwWc7s63TreWlbl0cMOoCdARYx8axld1stUFx4Xz21HF-C-ptpM619XyMLuGpyTi2HWIAnQu8MiJCaQ8bLchE_GRuA4qU48cUCTV4A6ByNtClWrisyrAB8_Iy_MbBQVPq3ToApVKxVIFZiwYj4x4TCSaYL8Q3lZwrXVYe0rkHwFgP41RAGzwRiasUvy__9Aw) ## Expanded version: ``` // Single iteration let f = |b: &[u8]| -> Vec<u8> { // Find all pairs of parenthesis and store them in v let v = (0..) .zip(b) .scan(vec![], |a, (b, c)| { Some(match c { 40 => { a.push(b); None } 41 => Some((a.pop()?, b)), _ => None, }) }) .flatten() .collect::<Vec<_>>(); // For ever pair for k in &v { // If it's the first and last, return everything except the first and last character if k.0 == 0 && k.1 == b.len() - 1 { return b[1..b.len() - 1].to_vec(); } for l in &v { //else if a second pair touches it if l.0 == k.0 + 1 && l.1 == k.1 - 1 { // combine 3 sections to crate the whole string again without 2 parenthesis return [&b[..k.0], &b[l.0..k.1], &b[k.1 + 1..]].concat(); } } } return b.to_vec(); }; let g = |mut b: Vec<u8>| { //while f(x) does something while f(&b) != b { b = f(&b) } b }; ``` ]
[Question] [ **Explanation:** Last year in math class, on homework we would occasionally get these extremely simple, although equally annoying questions called diamond puzzles. These were basically questions where we would be given a sum, and a product then were asked to find the two numbers which when multiplied give the product, and when added give the sum. These drove me crazy, since the only way I knew how to solve them (in Algebra I) was to just list the factors of the product then see which ones added to make the sum. (Since I didn't know how to use Quadratics at the time) Not to mention, they weren't exactly challenging math. However, It just occured to me that I should have just written a program. So that is your challenge today! Write a program that can solve a diamond puzzle. **Examples** [![enter image description here](https://i.stack.imgur.com/bbHkK.png)](https://i.stack.imgur.com/bbHkK.png) Apologies for the blurry image, its the best I could find. Also, ignore the numbers in bubbles.The top of the diamond is the product, the bottom is the sum, the right and left are the two numbers. Answers are as follows: (These are also your test cases) 1. 9, -7 2. -2, -1 3. 5, 8 4. -9, -9 **Rules:** * You may not use any pre-defined functions or classes which accomplish this for you. * Your code must be a complete program, or function which either returns or prints the answers once it finds them * The input is the sum and product, which are inputted as a function parameters or user input **Specifications:** * Assume that the two numbers, the sum, and the product will always be an integer. * The two answers will both be between -127 to 127. * Your input will be two integers (Sum and Product). Remember this is code-golf, so shortest byte count wins. Please title your answer with the standard ##Language Name, Byte Count Edit: Also, Doorknob pointed out that this is essentially "factor a quadratic of form x^2 + bx + c,". That is another way to think about and approach this challenge. :D [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~15~~ ~~11~~ 10 bytes ``` Hð+,_ðH²_½ ``` [Try it online!](http://jelly.tryitonline.net/#code=SMOwKyxfw7BIwrJfwr0&input=&args=MTM+NDA) The following binary code works with [this version](https://github.com/DennisMitchell/jelly/tree/7ee6838e9979ef33cab5085f413b3b6855e1ba46) of the Jelly interpreter. ``` 0000000: 48 98 2b 2c 5f 98 48 8a 5f 90 H.+,_.H._. ``` ### Idea This is based on the fact that ![formula](https://i.stack.imgur.com/OIyER.png) ### Code ``` Hð+,_ðH²_½ Left input: s -- Right input: p ð ð This is a link fork. We define three links, call the left and right link with the input as arguments, then the middle link with the results as arguments. H Left link, dyadic. Arguments: s p H Halve the left input. ðH²_½ Right link, dyadic. Arguments: s p H Halve the left input. ² Square the result. _ Hook; subtract the right input from the result. ½ Apply square root to the difference. ð+,_ Middle link, dyadic. Arguments: (results of the previous links) + Compute the sum of the results. _ Compute the difference of the results. , Pair. ``` [Answer] # [Unicorn](https://github.com/vihanb/Unicorn), ~~4650~~ ~~2982~~ ~~1874~~ 1546 ``` [ ✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨ 🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄 ( 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 ✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨ 🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤 🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 ( ) ) 🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄 2 🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄 🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄 🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐 🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄 🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄 ✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨ 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 ( 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 ✨✨✨✨✨✨✨ 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄 4 🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 ✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨ 🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤 🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 ( ) ) 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤 ✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨ ] ``` Now with goats, rainbows, and sparkles! Hopefully shorter than Java. --- Uses a custom [encoding](https://github.com/vihanb/Unicorn/blob/master/encoding.txt) which can be applied with `ApplyEncoding` ## Explanation How does this work??? With the magic of unicorns (and a little code). Unicorn is compiled into JavaScript Each section is separated by a space, and each section represents a character in the JavaScript code. If the section contains unicorns, the section's character is the section's length, converted to a char code (e.g. 32 unicorns would be a space) If the section contains goats, the section's length is doubled and then converted to a char code. --- If the program's special chars don't show, here's a picture: [![enter image description here](https://i.stack.imgur.com/frQ8h.png)](https://i.stack.imgur.com/frQ8h.png) --- This is non competing because Unicorn was made after this challenge was posted. [Answer] # JavaScript ES6, ~~45~~ ~~39~~ 37\* bytes ``` (q,p)=>[x=p/2+Math.sqrt(p*p/4-q),p-x] ``` \* Thanks to Dennis! [Answer] # dc, 16 ``` ?ddd*?4*-v+2/p-p ``` Reads sum then product from separate lines of STDIN. -ve numbers must be entered with an underscore instead of a minus sign. e.g. ``` $ { echo 2; echo _63; } | dc -e'?ddd*?4*-v+2/p-p' 9 -7 $ ``` ### Explanation: Same basic quadratic solution for `sum = a + b` and `product = a * b`. This calculates solution `a` as: ``` a = [ sum + √( sum² - 4 * product ) ] / 2 ``` And calculates solution `b` as: ``` b = sum - a ``` ### Expanded: ``` ? # push sum to stack ddd # duplicate 3 times (total 4 copies) * # sum squared ? # push product to stack 4* # multiply by 4 - # subtract (4 * product) from (sum squared) v # take square root of (sum squared) - (4 * product) + # add sum to square root of (sum squared) - (4 * product) 2/ # divide by 2 to give solution a p # print with newline and without pop - # subtract solution a from sum to give solution b p # print with newline and without pop ``` Dividing by 2 is done late to prevent loss precision. It is possible to divide by 2 earlier, but this requires fractional precision which needs more characters. [Answer] # TeaScript, 22 bytes ~~30 31~~ ``` [d=y/2+$s(y*y/4-x),y-d ``` Not *that* bad. Would be much shorter if I could of gotten some golfing features finished earlier such as ~~unicorn~~ unicode shortcuts [Try it online](http://vihan.org/p/TeaScript/#?code=%22%5B(y%2B(d%3D$s(y*y-4*x)))%2F2,(y-d)%2F2%5D%22&inputs=%5B%22-63%22,%222%22%5D&opts=%7B%22int%22:true,%22ar%22:false,%22debug%22:false%7D) [Answer] # [MATL](https://esolangs.org/wiki/MATL), 33 bytes ``` -100:100t!2$t+i=bb*i=&2#2$1fv101- ``` Outputs the two numbers in two different lines. If no solution exists it produces no output. If several solutions exist it produces only the pair of numbers corresponding to one solution. ### Example The following was run in Octave with the [current GitHub commit](https://github.com/lmendo/MATL/commit/77a5eba228ccedec8ac0d58d0f1842aba03858cc) of the compiler. ``` >> matl -r '-100:100t!2$t+i=bb*i=&2#2$1fv101-' > 2 > -63 9 -7 ``` ### Explanation ``` -100:100 % row vector -100, -99, ..., 100 t! % duplicate and transpose into column vector 2$t % duplicate the two vectors + % sum with singleton expansion (all combinations) i= % does it equal input? Produces logical matrix bb % move the two vectors to top * % multiply with singleton expansion (all combinations) i= % does it equal input? Produces logical matrix & % logical "and" 2#2$1f % find row and column of the first "true" value in logical matrix v101- % concatenate vertically and subtract 101 ``` [Answer] # Julia, ~~46~~ ~~44~~ 32 bytes ``` f(b,c)=(x=b+√(b^2-4c))/2,b-x/2 ``` An function f that takes the sum and then the product. My first Julia answer. @AlexA., you should be proud of me. Thanks @Dennis and @Alex A. for all the help. I got to cross out the 44. :P [Answer] # Pyth, ~~21~~ 18 bytes *Saved 3 bytes thanks to @Dennis* ``` ,J/+@-^Q2*4E2Q2-QJ ``` [Test suite](http://pyth.herokuapp.com/?code=%2CJ%2F%2B%40-%5EQ2*4E2Q2-QJ&input=2%2C+3&test_suite=1&test_suite_input=2%0A-63%0A-3%0A2%0A13%0A40%0A-18%0A81&debug=0&input_size=2) My second Pyth program ever, so it can probably be golfed with built-ins. Suggestions are welcome! ### How it works ``` ,J/+@-^Q2*4E2Q2-QJ Implicit: Q = first line of input , Create and output a list of these items: J Set variable J to the result of these operations: ^Q2 Square Q. - *4E Subtract 4*(next line of input). @ 2 Take the square root. + Q Add Q. / 2 Divide by 2. The list is currently [J]. -QJ Push Q-J; the list is now [J, Q-J]. EOF; list is sent to output. ``` (This explanation may not be 100% correct; I'm not very familiar with Pyth.) Note that `/` is integer division. By replacing it with `c`, we could make this work with non-integer inputs as well. [Answer] # Python 3, ~~49~~ 44 bytes There are probably some ways to golf this down even further, but this looks pretty good as is. ``` def f(s,p):s/=2;d=(s*s-p)**.5;return s+d,s-d ``` [Answer] # Java , 82 (69 λ) bytes with quadratic formula (127 (114 λ) bytes brute-force) *Brute-Force: (Vanilla, Java 7)* ``` int[] n(int s,int p){for(int a=-100;a<=100;a++)for(int b=-100;b<=100;b++) if(a+b==s&&a*b==p)return new int[]{a,b};return null;} ``` *λ-enhanced: (Java 8)* ``` (s,p)->{for(int a=-100;a<=100;a++)for(int b=-100;b<=100;b++) if(a+b==s&&a*b==p)return new int[]{a,b};return null;} ``` Assign lambda to `java.util.function.BiFunction<Integer, Integer, int[]>` and call `apply()`. Plain old brute-force approach. Just the working function is here, and since Java can't return multiple values, we return a 2-element `int` array with the required numbers. The full brute-force approach based program can be found [here on ideone.com](http://ideone.com/7WcQwq), with λ version here. Golfing this involved removing all unnecessary braces. *Ungolfed:* ``` int[] n(int s,int p){//sum and product as function parameters,in that order for(int a=-100;a<=100;a++){//iterate first no. from -100 to 100 for(int b=-100;b<=100;b++){//iterate second no. from -100 to 100 //if the 2 nos. satisfy the diamond-puzzle condition, //pack them in an int array and return them if(a+b==s&&a*b==p)return new int[]{a,b};} }//if no such pair exists, return null return null;} ``` *Quadratic Approach: (Vanilla, Java 7)* ``` int[] n(int s,int p){int x=s+(int)Math.sqrt(s*s-4*p);return new int[]{x/2,s-x/2};} ``` *λ-enhanced: (Java 8)* (s,p)->{int x=s+(int)Math.sqrt(s\*s-4\*p);return new int[]{x/2,s-x/2};} (Usage as for brute-force λ above). Parameters and return criteria are the same as the brute-force solution above. Uses the good old quadratic formula used by almost all other answers here, and cannot be golfed down much further unless someone helps me out here. It's pretty clear so I'm not including an ungolfed version. The full quadratic approach based program is here on [ideone.com](http://ideone.com/8bXCr0), with λ version here. [Answer] # [convey](http://xn--wxa.land/convey/), 52 bytes ``` {?~1 4*"v v*#2 `-.v *%2v .10-` v0 v" "-v,< >,+ 2%} ``` [Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiez9+MVxuNCpcInZcbiB2KiMyXG5gLS52XG4qJTJ2XG4uMTAtYFxudjAgdlwiXG5cIi12LDxcbj4sK1xuIDIlfSIsInYiOjEsImkiOiIyIC0xNSJ9) Golfed version of [this answer](https://codegolf.stackexchange.com/a/221123/56656). [![Running on 2 -15](https://i.stack.imgur.com/nIVkI.gif)](https://i.stack.imgur.com/nIVkI.gif) [Answer] ## [Japt](http://ethproductions.github.io/japt/), ~~28~~ ~~22~~ ~~21~~ 20 bytes ``` [X=V/2+(V²/4-U ¬V-X] ``` Input is made in the form of `-63 2`. Explanation: * `U` and `V` are the two inputs (`-63` and `2` in the first case) * `²` squares the number * `q` extracts the square root [Answer] # APL, ~~27~~ 21 bytes ``` h(+,-).5*⍨⊣-⍨h×h←.5×⊢ ``` This is a dyadic function train that accepts integers on the right and left and returns an array. To call it, assign it to a variable. Ungolfed: ``` h←.5×⊢ ⍝ Define a train h for halving the input h× ⍝ b^2/4 ⊣-⍨ ⍝ b^2/4 - c .5*⍨ ⍝ sqrt(b^2/4 - c) h(+,-) ⍝ Return the halved pair ``` [Try it online](http://tryapl.org/?a=f%u2190h%28+%2C-%29.5*%u2368%u22A3-%u2368h%D7h%u2190.5%D7%u22A2%20%u22C4%20%AF63%20f%202%20%u22C4%202%20f%20%AF3%20%u22C4%2040%20f%2013%20%u22C4%2081%20f%20%AF18&run) Saved 6 bytes thanks to Dennis! [Answer] # CJam, 18 bytes ``` q~2d/_2#@-mq_2$+p- ``` [Try it online!](http://cjam.tryitonline.net/#code=cX4yZC9fMiNALW1xXzIkK3At&input=NDAgMTM) ### How it works ``` q~ e# Read an evaluate all input. STACK: product sum 2d/ e# Divide the sum by 2.0. _ e# Push a copy of the result. 2# e# Square the copy. @- e# Rotate the product on top and subtract it from the square. mq e# Apply square root. _2$ e# Push copies of the root and the halved sum. +p e# Add and print. - e# Subtract the originals. ``` [Answer] **MathCAD 15. 38 Bytes** [![enter image description here](https://i.stack.imgur.com/nREAG.png)](https://i.stack.imgur.com/nREAG.png) With a mathematical formula, programming in MathCAD is easy. The language is even designed to handle complex numbers with ease. However there are shorter languages that can solve the problem. [Answer] # 𝔼𝕊𝕄𝕚𝕟, 21 chars / 30 bytes ``` [x=í/2+√ í²/4-î⦆,í-x] ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=%5B-63%2C2%5D&code=%5Bx%3D%C3%AD%2F2%2B%E2%88%9A%20%C3%AD%C2%B2%2F4-%C3%AE%E2%A6%86%2C%C3%AD-x%5D)` Meh. This should be visual enough for y'all to get the idea; however, if you must, `î = input1, í = input2`. [Answer] # [J](http://jsoftware.com/), 12 bytes ``` 1-@>@{p.@,&1 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DXUd7ByqC/QcdNQM/2typSZn5CtYKsSbK@haKaQpxJsZKxhBBOONFOINIaJAljFE0ELBFCJkYqBgCBWLtwQhsKiFIVCPxX8A "J – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 bytesSBCS ``` ⊣(⊢,-)(⊢×-)⍣¯1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HXYo1HXYt0dDVB1OHpupqPehcfWm/4P@1R24RHvX2P@qZ6@j/qaj603vhR20QgLzjIGUiGeHgG/3/UO1ehuDRXIU2hoCg/hcsYyDDiOrTeCEgfWm9mzGVoZA5kGgAA "APL (Dyalog Unicode) – Try It Online") A tacit function whose left arg is the sum and the right is the product. Finds one solution to the quadratic equation using the built-in numerical solver, and then gives both solutions based on the result. The "power operator" `f⍣n` runs the function `f` `n` times, but if `n` is negative, runs the *inverse* of `f` `-n` times. The inverse of `f` is, in the numerical point of view, equivalent to solving the equation `f x = y` with a given value of `y`. Dyadic form `a(f⍣n)y` solves `(a f x) = y`. ### How it works ``` ⊣(⊢,-)(⊢×-)⍣¯1 ⍝ left: sum s, right: product p (⊢×-) ⍝ A function that, when left-bound with s, computes x*(s-x) ⍣¯1 ⍝ Find one solution to x*(s-x)=p, i.e. x^2-sx+p=0 ⊣( ) ⍝ With s as left and x as right arg, ⊢,- ⍝ Give (x,s-x) ``` [Answer] ## [wx](https://github.com/w-golflang/w) `d`, ~~14~~ 12 bytes Just [W](https://github.com/a-ee/w) with a few instructions added. ``` ○Äπ√akû▀╧Θ°v ``` Decompressed: ``` a*S4*-Q+2/:aS- ``` [Answer] ## PHP, 62 bytes ``` <?=($x=($p=$_GET[p])/2+sqrt($p*$p/4-$q=$_GET[q]))." ".($p-$x); ``` This could be pretty long but being full-featured PHP web-"program". Accepts the arguments via the "get" request. [Demo](http://justachat.freevar.com/diamonds.php?q=-63&p=2). [Answer] # TI-BASIC, 20 bytes Takes `Q` from `Ans`, and `P` from `Prompt`. Call like `P:prgmNAME`. ``` Prompt P P/2+√(P²/4-Ans {Ans,P-Ans ``` ]
[Question] [ The Binary Sierpinski Triangle sequence is the sequence of numbers whose binary representations give the rows of the Binary Sierpinski Triangle, which is given by starting with a 1 in an infinite row of zeroes, then repeatedly replacing every pair of bits with the xor of those bits, like so: ``` f(0)= 1 =1 f(1)= 1 1 =3 f(2)= 1 0 1 =5 f(3)= 1 1 1 1 =15 f(4)= 1 0 0 0 1 =17 ``` More digits are given at OEIS: <https://oeis.org/A001317> Input: A non-negative integer n in any format you like. (Must work for all n up to 30.) Output: The nth term (0-indexed) of the sequence as a decimal number. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so try give the shortest answer in bytes of which your language is capable. No answer will be accepted. Standard loopholes apply (e.g. no hard-coding the sequence), except that you *may* use a language created/modified after this challenge was posted. (Do avoid posting another solution in a language that has already been used unless your solution is shorter.) ## Leaderboard The Stack Snippet at the bottom of this post generates the catalogue 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 = 67497; // 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 = 47050; // 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] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5~~ 4 bytes I proudly present to you, 05AB1E. Although it is very short, it is probably very bad at long challenges. Thanks to ETHproductions for shaving off 1 byte :) ``` $Fx^ ``` Explanation: ``` $ # Pushes 1 and input F # Pops x, creates a for-loop in range(0, x) x # Pops x, pushes x and 2x ^ # Bitwise XOR on the last two elements # Implicit, ends the for-loop # Implicit, nothing has printed so the last element is printed automatically ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 27 bytes ``` n->lift(Mod(x+1,2)^n)%(x-2) ``` The function takes the \$n\$-th power of the polynomial \$x+1\$ in the ring \$\mathbb{F}\_2[X]\$, lifts it to \$\mathbb{Z}[X]\$, and then evaluates it at \$x=2\$. [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1y4nM61Ewzc/RaNC21DHSDMuT1NVo0LXSPN/Wn6RRh5QkYGOgiEQFxRl5pUABZQUdO2ARJpGnqam5n8A "Pari/GP – Try It Online") [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 6 bytes ``` 1Ḥ^$³¡ ``` [Try it online!](http://jelly.tryitonline.net/#code=MeG4pF4kwrPCoQ&input=&args=NA) The binary version that works with [this revision](https://github.com/DennisMitchell/jelly/commit/c282f46eac85e15e2ca789b2cb11ad0abd454ac8) of the Jelly interpreter has the xxd dump ``` 0000000: 31 a8 5e 24 8b 80 1.^$.. ``` ### How it works ``` 1Ḥ^$³¡ Input: n 1 Set the left argument to 1. Ḥ Multiple the left argument by two. ^ Hook; XOR it with its initial value. $ Create a monadic chain from the last two insructions. ³¡ Call the chain n times, updating the left argument after each call. ``` [Answer] # Haskell, 44 bytes ``` import Data.Bits f n=iterate((2*)>>=xor)1!!n ``` In the `((->) r)` monad, `(f >>= g) x` equals `g (f x) x`. [Answer] ## Matlab, 45 bytes Solution: ``` @(i)2.^[0:i]*diag(mod(fliplr(pascal(i+1)),2)) ``` Test: ``` ans(10) ans = 1285 ``` Explanation: `pascal` constructs Pascal triangle, but it starts from 1, so input should be `i+1`. `fliplr` flips array from left to right. `mod(_,2)` takes remainder after division by 2. `diag` extracts main diagonal.Multiplication using `2.^[0:i]` converts vector to decimal I'm glad, @flawr that I found Matlab competitor here :) [Answer] # JavaScript (ES6), 23 bytes ``` f=x=>x?(y=f(x-1))^y*2:1 ``` Based on the first formula on the OEIS page. If you don't mind the code taking almost forever to finish for an input of 30, we can shave off a byte: ``` f=x=>x?f(--x)^f(x)*2:1 ``` Here's a non-recursive version, using a `for` loop in an `eval`: (32 bytes) ``` x=>eval("for(a=1;x--;a^=a*2);a") ``` [Answer] # Matlab, ~~77~~ 70 bytes This function calculates the n-th row of the Pascal triangle via repeated convolution with `[1,1]` (a.k.a. binomial expansion or repeated multiplication with a binomial), and calculates the number from that. ``` function r=c(n);k=1;for i=1:n;k=conv(k,[1,1]);end;r=2.^(0:n)*mod(k,2)' ``` [Answer] ## CJam, 10 bytes ``` 1ri{_2*^}* ``` [Test it here.](http://cjam.aditsu.net/#code=1ri%7B_2*%5E%7D*&input=4) Simple iterative solution using bitwise XOR. [Answer] # Ruby, 26 bytes anonymous function with iteration. ``` ->n{a=1;n.times{a^=a*2};a} ``` this recursive function is one byte shorter, but as it needs to be named to be able to refer to itself, it ends up one byte longer. ``` f=->n{n<1?1:(s=f[n-1])^s*2} ``` [Answer] # Ruby, 25 bytes ``` ->n{eval"n^=2*"*n+?1*n=1} ``` Shorter than the other answers on here so far. It constructs this string: ``` n^=2*n^=2*n^=2*n^=2*1 ``` Then it sets `n=1` (this actually happens while the string is being made) and evaluates the above string, returning the result. [Answer] # [Samau](https://github.com/AlephAlpha/Samau/tree/master/OldSamau), 4 bytes Now Samau has built-in functions for [XOR multiplication](https://codegolf.stackexchange.com/questions/50240/xor-multiplication) and XOR power. ``` ▌3$ⁿ ``` Hex dump (Samau uses CP737 encoding): ``` dd 33 24 fc ``` Explanation: ``` ▌ read a number 3 push 3 $ swap ⁿ take the XOR power ``` [Answer] # Pure Bash (no external utilities), 37 Bash integers are 64-bit signed, so this works for inputs up to and including 62: ``` for((x=1;i++<$1;x^=x*2)){ : } echo $x ``` [Answer] ## Python 2.7.6, 38 33 bytes Thanks to Dennis for shaving off a few bytes! ``` x=1 exec'x^=x*2;'*input() print x ``` [Answer] # Pyth, 7 bytes ``` uxyGGQ1 ``` Try it online: [Demonstration](https://pyth.herokuapp.com/?code=uxyGGQ1&input=4&debug=0) ### Explanation: ``` u Q1 apply the following statement input-times to G=1: xyGG update G with (2*G xor G) ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 15 bytes Similar to [@flawr's answer](https://codegolf.stackexchange.com/a/67500/36398): ``` i:1w"TToX+]2\XB ``` *EDIT (May 20, 2016) [Try it online!](http://matl.tryitonline.net/#code=aToxdyJUVG9ZK10yXFhC&input=NQ) with `X+` replaced by `Y+` to conform to version 18.0.0 of the language.* ### Example ``` >> matl i:1w"TToX+]2\XB > 5 51 ``` ### Explanation ``` i % input : % vector of values 1, 2, ... to previous input 1 % number literal w % swap elements in stack " % for TTo % vector [1 1] X+ % convolution ] % end 2\ % modulo 2 XB % convert from binary to decimal ``` [Answer] # [Perl 5](https://www.perl.org/), 23 bytes ``` $.^=2*$.for 1..<>;say$. ``` [Try it online!](https://tio.run/##K0gtyjH9/19FL87WSEtFLy2/SMFQT8/Gzro4sVJF7/9/k3/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online") [Answer] # MIPS, 28 bytes Input in `$a0`, output in `$v0`. ``` 0x00400004 0x24020001 li $v0, 1 0x00400008 0x10800005 loop: beqz $a0, exit 0x0040000c 0x00024021 move $t0, $v0 0x00400010 0x00021040 sll $v0, $v0, 1 0x00400014 0x00481026 xor $v0, $v0, $t0 0x00400018 0x2084ffff addi $a0, $a0, -1 0x0040001c 0x08100002 j loop ``` [Answer] # Mathematica, ~~40~~ 24 bytes ``` Nest[BitXor[#,2#]&,1,#]& ``` [Answer] ## k4, 26 bytes ``` {x{2/:~(=). 0b\:'1 2*x}/1} ``` `0b\:` converts a number to a boolean vector (i.e. bitstring), XOR is implemented as "not equal", `2/:` converts a bitstring back to a number by treating it as a polynomial to evaluate, and `x f/y` with `x` an integer is `f` applied to `y` first, and then to its successive outputs `x` times. Sample run: ``` {x{2/:~(=). 0b\:'1 2*x}/1}'!5 1 3 5 15 17 ``` [Answer] # Ruby, ~~31~~ 26 bytes **EDIT:** Changed to a different language entirely! All golfing suggestions welcome! This program bitwise XORs the previous element of the sequence with twice itself, i.e. `f(n) = f(n-1) ^ 2*f(n-1)`. ``` ->n{v=1;n.times{v^=2*v};v} ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 87 bytes ``` ,[>>[>]++<[[->+>+<<]>-->[-<<+>>]<[>+<-[>-<-]]>+<<<]>>>[[-<+>]>]<<[<]<-]>>[<[->++<]>>]<+ ``` [Try it online!](https://tio.run/##bY87DsJADER7TrG9MSew5iKWixAFFBEFlM/5l/FCJAq28crPM2Nfl26cb3v/qPXsgCNEzF0hELOAKlzNBAhzttShphFJiakgFgSxuQURW5Z6SRwm9blvr31bSz9MU@nWMs7bcB@WE@NaSNNQ1FKgkdWNufQ4XjoyOteAyzeyLWVtD9c4lXJMu30qzdJX8PvJ8Ug//BknuNCLh9Q3 "brainfuck – Try It Online") Assumes infinite sized cells (otherwise it can’t get past 7, which is conveniently 255). The Pascal’s triangle mod 2 method is actually much longer because of the costly mod 2 operation, while XOR is much easier to implement. [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ±s┤ε─ ``` [Run and debug online!](https://staxlang.xyz/#p=925b5dde17&i=%5B1+0+10+0+-127+0+-460+0+576%5D%0A%5B1+0+-4+0%5D%0A%5B1%5D&a=1&m=2) Port of the Jelly answer. Uses ASCII representation to explain: ``` ODcH|^ O Put 1 under top of stack D Repeat for times specified by input cH|^ Xor the number with itself doubled Implicit output ``` [Answer] ## APL, 31 bytes ``` {({2⊥⊃~1 2=.{(64⍴2)⊤⍺×⍵}⍵}⍣⍵)1} ``` This is almost certainly awful code, but I'm a complete APL newb. I expect anyone with any skill could get rid of all the D-functions and shorten it considerably. The logic is more or less the same as my `k4` answer -- multiply by `1` or `2`, convert to bits with `⊤`, XOR using not equals, convert back to a number with `⊥`, wrap the whole thing in a function and ask for a specific number of iterations using `⍣`. I have no idea why the result coming out of the inner product is enclosed, but `⊃` cleans that up. [Answer] ## Seriously, 12 bytes ``` 2,╣`2@%`Mεj¿ ``` Hex Dump: ``` 322cb960324025604dee6aa8 ``` [Try it online](http://seriouslylang.herokuapp.com/link/code=322cb960324025604dee6aa8&input=5) Since Seriously does not include any means of doing a bitwise xor, this solution takes the challenge completely literally, directly computing the given row of the triangle. This method gives correct answers up to n=1029 (after which there is not enough memory to compute the given row of Pascal's triangle). Explanation: ``` , get input ╣ push the nth row of pascal's triangle `2@%`M take each element of the row mod 2 εj join all the binary digits into a string 2 ¿ interpret it as a base 2 number ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), ~~40~~ 10 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage) ``` Đ0⇹Řć2%ǰ2Ĩ ``` Explanation: Observing that the Binary Sierpinski Triangle is equivalent to Pascal's Triangle mod 2, ``` Implicit input Đ Duplicate input 0⇹Ř Push [0,1,2,...,input] ć2% Calculate the input-th row of Pascal's Triangle mod 2 ǰ Join elements of the array into a string 2Ĩ Interpret as a binary number Implicit print ``` [Try it online!](https://tio.run/##ARoA5f9weXT//8SQMOKHucWYxIcyJcewMsSo//8zMA) ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 3 years ago. [Improve this question](/posts/184951/edit) Upside-Down Pyramid Addition is the process of taking a list of numbers and consecutively adding them together until you reach one number. When given the numbers `2, 1, 1` the following process occurs: ``` 2 1 1 3 2 5 ``` This ends in the number `5`. --- ### YOUR TASK Given the right side of an Upside-Down Pyramid (Ascending), write a program or function that will return the original list. **New Extra Challenge**: Try doing this in less than O(n^2) ### EXAMPLE ``` f([5, 2, 1]) => [2, 1, 1] f([84,42,21,10,2]) => [4,7,3,8,2] ``` NOTE: The Upside-Down Pyramid will never be empty and will always consist of positive integers ONLY. [Answer] # JavaScript (ES6), ~~62 58 49~~ 46 bytes *Saved 3 bytes thanks to @Oliver* Returns the list as a comma-separated string. ``` f=a=>+a||f(a.map(n=>a-(a=n),a=a.shift()))+[,a] ``` [Try it online!](https://tio.run/##XYuxDoIwFEV3v4LxvXApUmtkKT9CGF6QKgZbYokT/17r4OIdzzn3IW@J42tet8qH65SSs2K7UvbdkainrORtJxWJ9QyxouJ9dhsxc9lDhjQGH8MyqSXcyFF/hkYzMBe/1XWRCZrDX9gaGA2dzRH6e8ihwQUntNDpAw "JavaScript (Node.js) – Try It Online") ### Commented ``` f = a => // f = recursive function taking the input list a[] +a // if a[] consists of a single positive integer: // stop recursion and return this integer || // else: f( // do a recursive call to f: a.map(n => // for each value n in a[]: a - (a = n), // yield the difference between the previous value and n // and update a to n a = a.shift() // start by removing the first element and saving it in a // (because of the recursion, it's important here to reuse // a variable which is defined in the scope of f) ) // end of map() ) // end of recursive call + [, a] // append the last entry from a[] ``` [Answer] # [Haskell](https://www.haskell.org/), 22 bytes ``` foldl(flip$scanr(-))[] ``` [Try it online!](https://tio.run/##VcixDkAwEADQ3VfcYKjkJNqQWHwJHZpyNE41re93Zm98hyvnxiw0LUI3r6yIQ6qLdzGrtmlmK5cLESZY7wog5RAfqIFgHtCgtv8be@wNGo26Q2Pl9cRuL9L6lD4 "Haskell – Try It Online") [Answer] ## Haskell, 42 bytes ``` f[]=[] f a=f(zipWith(-)a$tail a)++[last a] ``` [Try it online!](https://tio.run/##Vcg7CoAwEAXA3lO8wkJxBRMUbHIOi7DFggYX4wdN5eVj7ZSzyrMtMeYcPDvPRYC4UL16TZrWqq2lTKIRUjeNj/IkCOdd9IDDfBbAdeuRUCLAD2TJ8P/GnnpL1pDpyHL@AA "Haskell – Try It Online") [Answer] # TI-BASIC, 54 bytes ``` Ans→L₁:dim(L₁→dim(L₂:While 1-Ans:L₁(Ans→L₂(Ans:-ΔList(L₁→L₁:dim(Ans:End:L₁(Ans→L₂(Ans:L₂ ``` Input is the list of the right side of the triangle in `Ans`, as is described in the challenge. Output is the top row of said triangle. **Examples:** ``` {5,2,1 {5 2 1} prgmCDGF19 {2 1 1} {84,42,21,10,2 {84 42 21 10 2} prgmCDGF19 {4 7 3 8 2} ``` **Explanation:** This solution abuses the fact that the triangle formed using the right side of the triangle as the start ends up being the change in each element. In other words, ``` 2 1 1 3 2 5 ``` becomes: ``` 5 2 1 3 1 2 ``` Thus, the resulting list is the right side of this new triangle, which can be formed by setting the last element to the index of its parent list's length in the resulting list. ``` Ans→L₁ ;store the input list in L₁ dim(L₁→dim(L₂ ;set the length of L₂ to the length of L₁ While 1-Ans ;while the L₁'s length is not 1 L₁(Ans→L₂(Ans ;set the last element of L₁ to the corresponding index in L₂ -ΔList(L₁→L₁ ;get the change in each element, then negate ; (elements are in descending order so the change in each ; element will be negative) ; and store the resulting list in L₁ dim(Ans ;leave the length of L₁ in "Ans" End L₁(Ans→L₂(Ans ;set the element again ; (needed for final step) L₂ ;leave L₂ in "Ans" ;implicit print of "Ans" ``` --- **Note:** TI-BASIC is a tokenized language. Character count does ***not*** equal byte count. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṚIƬZḢṚ ``` A monadic Link accepting a list of integers which yields a list of integers. **[Try it online!](https://tio.run/##y0rNyan8///hzlmex9ZEPdyxCMj6//9/tIWxjoKRuY6CpY4CkDSLBQA "Jelly – Try It Online")** ### How? Builds the whole triangle then extracts the required elements. ``` ṚIƬZḢṚ - Link: list of integers e.g. [84,42,21,10,2] Ṛ - reverse [2,10,21,42,84] Ƭ - collect & apply until a fixed point: I - incremental differences [[2,10,21,42,84],[8,11,21,42],[3,10,21],[7,11],[4],[]] Z - transpose [[2,8,3,7,4],[10,11,10,11],[21,21,21],[42,42],[84]] Ḣ - head [2,8,3,7,4] Ṛ - reverse [4,7,3,8,2] ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), ~~14~~ 11 bytes ``` xÆ‼├│?;∟;]x ``` [Try it online!](https://tio.run/##ATgAx/9tYXRoZ29sZv//eMOG4oC84pSc4pSCPzviiJ87XXj//1s1IDIgMV0KWzg0IDQyIDIxIDEwIDJd/w "MathGolf – Try It Online") ## Explanation ``` x reverse int/array/string Æ ∟ do while true without popping using 5 operators ‼ apply next 2 operators to TOS ├ pop from left of list │ get differences of list ? rot3 ; discard TOS (removes rest from ├ command) loop ends here ; discard TOS (removes empty array from stack) ] wrap stack in array x reverse array ``` [Answer] # [Python 2](https://docs.python.org/2/), 56 bytes ``` f=lambda a:a and f([l-r for l,r in zip(a,a[1:])])+a[-1:] ``` A recursive function accepting a list of positive integers which returns a list of non-negative integers. **[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIdEKiPNSFNI0onN0ixTS8osUcnSKFDLzFKoyCzQSdRKjDa1iNWM1tROjdYGs/wVFmXklINUWJjomRjpGhjqGBjpGsZr/AQ "Python 2 – Try It Online")** [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` _ƝƬa/ ``` [Try it online!](https://tio.run/##y0rNyan8/z/@2NxjaxL1/x9uPzrp4c4Z//9HW5joKJgY6SgYGeooGBoA6VgA "Jelly – Try It Online") We can assume the whole pyramid is positive, so we can use a && operation instead of a "right" operation. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 36 bytes Based on [@Lynn](https://codegolf.stackexchange.com/users/3852/lynn)'s comment: > > Free insight that I can't find a language it's shorter in: > $$f([a,b,c,d,e]) = \begin{bmatrix} 1&-4&6&-4&1 \\ 0&1&-3&3&-1 \\ 0&0&1&-2&1 \\ 0&0&0&1&-1 \\ 0&0&0&0&1 \end{bmatrix} \cdot \begin{bmatrix}a\\b\\c\\d\\e\end{bmatrix}$$ > > > Pari/GP has a built-in for the Pascal matrix, and its inverse is exactly the matrix we need: $$\begin{bmatrix} 1&0&0&0&0 \\ 1&1&0&0&0 \\ 1&2&1&0&0 \\ 1&3&3&1&0 \\ 1&4&6&4&1 \end{bmatrix}^{-1} = \begin{bmatrix} 1&0&0&0&0 \\ -1&1&0&0&0 \\ 1&-2&1&0&0 \\ -1&3&-3&1&0 \\ 1&-4&6&-4&1 \end{bmatrix}$$ ``` a->r=Vecrev;r(r(a)/matpascal(#a-1)~) ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P1HXrsg2LDW5KLXMukijSCNRUz83saQgsTg5MUdDOVHXULNO839iQUFOpUaigq6dQkFRZl4JkKkE4igppAE1aOooREeb6hjpGMYCWRYmOiZGOkaGOoYGOkaxsZr/AQ "Pari/GP – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~69~~ 67 bytes ``` function(n,x=sum(n|1):1-1,`[`=outer)(x[x,choose]*(-1)^x[x,"+"])%*%n ``` [Try it online!](https://tio.run/##FchBCoMwEAXQvacogjCjP@AEhVLqSUQRgqFddALGQBbePcXd4x3FP96m@KTu/AYlRZ5i@pFewi8xgm3eppDO/WDKc4b7hBD3pSUjvN5Rd/XCTdto8eRohIUwV7efAwYLK5Aelrn8AQ "R – Try It Online") Returns a column vector. -2 bytes thanks to [Kirill L.](https://codegolf.stackexchange.com/users/78274/kirill-l) Also based on [Lynn](https://codegolf.stackexchange.com/users/3852/lynn)'s comment: > > Free insight that I can't find a language it's shorter in: > $$f([a,b,c,d,e]) = \begin{bmatrix} 1&-4&6&-4&1 \\ 0&1&-3&3&-1 \\ 0&0&1&-2&1 \\ 0&0&0&1&-1 \\ 0&0&0&0&1 \end{bmatrix} \cdot \begin{bmatrix}a\\b\\c\\d\\e\end{bmatrix}$$ > > > It's longer than the other R answer, but it was an interesting approach to take and try to golf. [Answer] # Javascript (ES6), 127 bytes ``` f=a=>{for(e=[a],a=[a[l=a.length-1]],i=0;i<l;i++){for(e.push(g=[]),j=-1;j<l;)g.push(e[i][j]-e[i][++j]);r.unshift(g[j])}return r} ``` Original code ``` function f(a){ var e=[a]; var r=[a[a.length-1]]; for (var i=1;i<a.length;i++){ var g=[]; for (var j=0;j<a.length;j++){ g.push(e[i-1][j-1]-e[i-1][j]); } e.push(g); r.unshift(g[j-1]); } return r; } ``` Oh, I lost like... a lot... to the previous answer... [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 57 bytes ``` (r=Reverse)[#&@@@Most@NestList[Differences,r@#,Tr[1^#]]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X6PINii1LLWoOFUzWlnNwcHBN7@4xMEvtbjEJ7O4JNolMy0ttSg1Lzm1WKfIQVknpCjaME45NjZW7X9AUWZeiYJDenS1qY6RjmFtLBdYJDpWgQshZWGiY2KkY2SoY2igY1Qb@/8/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` R.¥.Γ¥}¨ζнR ``` Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/184958/52210), although I'm *jelly* about Jelly's more convenient builtins in this case. ;) -1 byte thanks to *@Emigna*. [Try it online](https://tio.run/##ASoA1f9vc2FiaWX//1IuwqUuzpPCpX3CqM620L1S//9bODQsNDIsMjEsMTAsMl0) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/IL1DS/XOTT60tPbQinPbLuwN@q/zPzraVMdIxzBWRyHawkTHxEjHyFDH0EDHCCRgaKZjrmOiYxwbCwA). **Explanation:** ``` R # Reverse the (implicit) input-list # i.e. [16,7,4,3] → [3,4,7,16] .¥ # Undelta it (with leading 0) # → [0,3,7,14,30] .Γ } # Continue until the result no longer changes, and collect all steps: ¥ # Get the deltas / forward differences of the current list # → [[3,4,7,16],[1,3,9],[2,6],[4],[]] ¨ # Remove the trailing empty list # → [[3,4,7,16],[1,3,9],[2,6],[4]] ζ # Zip/transpose; swapping rows/column (with space as default filler) # → [[3,1,2,4],[4,3,6," "],[7,9," "," "],[16," "," "," "]] н # Only leave the first inner list # → [3,1,2,4] R # Revert it back # → [4,2,1,3] # (after which it's output implicitly as result) ``` [Answer] # [R](https://www.r-project.org/), ~~55~~ ~~63~~ ~~55~~ 53 bytes ``` x=scan();for(i in sum(1|x):1){F[i]=x[i];x=-diff(x)};F ``` [Try it online!](https://tio.run/##K/r/v8K2ODkxT0PTOi2/SCNTITNPobg0V8OwpkLTylCz2i06M9a2AkhYV9jqpmSmpWlUaNZau/23MFEwMVIwMlQwNFAw@g8A "R – Try It Online") -2 bytes thanks to Giuseppe. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 37 bytes ``` {[R,]($_,{@(.[]Z-.skip)}...1)[*;*-1]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OjpIJ1ZDJV6n2kFDLzo2SlevODuzQLNWT0/PUDNay1pL1zC29n9afpGCRk5mXmqxpkI1l4JCcWKlgp5rmKOPnloaV@1/DVMdBSMdBUNNAA "Perl 6 – Try It Online") Repeatedly reduces by elementwise subtraction, and then returns the last number of each list in reverse. ### Explanation: ``` { } # Anonymous code block $_, ... # Create a sequence starting from the input { } # Where each element is .[]Z-.skip # Each element minus the next element @( ) # Arrayified 1 # Until the list has one element left [R,] # Reverse the sequence ( )[*; ] # For every list *-1 # Take the last element ``` [Answer] # [Python 2](https://docs.python.org/2/), 78 bytes ``` lambda n,*a:R(lambda r,v:R(lambda x,w:x+[w-x[-1]],r,[v]),a,[n])[::-1] R=reduce ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFPRyvRKkgDyivSKUNwKnTKrSq0o8t1K6J1DWNjdYp0ostiNXUSdaLzYjWjrayAglxBtkWpKaXJqf8LijLzShTSNEx1jHQMNf8DAA "Python 2 – Try It Online") [Answer] ## [C# (Visual C# Interactive Compiler)](https://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 164 bytes ``` a=>{int x=a.Length;var l=new int[x][];for(int i=0;i<x;i++){l[i]=new int[x];l[i][0]=a[i];for(int j=0;j<i;j++)l[i][j+1]=l[i-1][j]-l[i][j];}return l.Last().Reverse();} ``` [Try it online!](https://tio.run/##lY5PS8QwEMXvforBU0L/0C4rCGl6EQWlJy8eSg6xTNcpNYUkXQtLP3uduiBehYE37/F@w3Qh6wJtT7PrKnKxNenzo5s/0dv3EfekrqHXm9X1hQ0s2uYNulP8UGfrYdQOv2DnFtMa1U9e7C3ShaJqUZQk8jK2ZP7U1O7bwmjL@ksMTAwVqYGJn8KQlEbzlpW8m@yaGbV6jLN3MOaNDVHI/BXP6AMKqdZN3TxMLkwj5m@eIjbkUIToyZ3yl4mcuE2Bpxf8TGvgAncpHFIoYZVS/pe9P6ZwZPpQ8oWCFa5ntm8) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` Fθ«PI§θ±¹↑UMθ⁻§θ⊖λκ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBo1BToZqL07c0pySzoCgzr0TDObG4RMOxxDMvJbVCo1BHwS81PbEkVcNQEwisgSrzy1I1rEILwOzEAuf83NzEvBSQQt/MvNJiZJ0uqclFqbmpeSWpKRo5mpo6CtkgE2r//4@ONtVRMNJRMIyN/a9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Fθ« ``` Loop once for each term in the original list. ``` PI§θ±¹↑ ``` Print the last term in the list, but move the cursor to the beginning of the previous line, so that the terms are output in reverse order. ``` UMθ⁻§θ⊖λκ ``` Compute the deltas, inserting a dummy value at the beginning so that we can use an operation that doesn't change the length of the list. [Answer] # APL+WIN, 34 or 28 bytes ``` v←⊂⌽⎕⋄1↓⌽↑¨⍎∊'v',(∊⍴¨v)⍴⊂',-2-/¨v' ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/6XAZmPupoe9ewFSjzqbjF81DYZxGmbeGjFo96@Rx1d6mXqOhpA@lHvlkMryjSBFFC9uo6uka4@kK/@H2jM/zQuCxMFEyMFI0MFQwMFIwA "APL (Dyalog Classic) – Try It Online") Prompts for right side vector. or implementing @Lynn's approach: ``` 0⍕⌽(⌹⍉n∘.!n←0,⍳¯1+⍴n)+.×⌽n←⎕ ``` [Try it online!Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4bPOqd@qhnr8ajnp2PejvzHnXM0FPMA0ob6Dzq3XxovaH2o94teZraeoenA1WBJID6/wN1/k/jsjBRMDFSMDJUMDRQMAIA "APL (Dyalog Classic) – Try It Online") Prompts for right side vector. [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 29 bytes ``` {y.=Delta@-_If[_,$@y'_@-1,y]} ``` [Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@7@6Us/WJTWnJNFBN94zLTpeR8WhUj3eQddQpzK29r9fampKcbRKQUFyeixXQFFmXklIanGJc2JxanF0mo5CtKW6qY6CqbqRuqGOgoWJuomRupGhuqGBulFs7H8A "Attache – Try It Online") Simply iterates the `Delta` function until its empty. Much shorter than the very verbose `PeriodicSteps` solution... [Answer] # C, 76 bytes ``` i=0;int*f(int*a,int n){for(;i<n;a[i++]=a[i]-a[i+1]);if(!n)return a;f(a,n-1);} ``` **input** : `(*a = pointer to array, n = last element's index of that array)` **output** : `return int* = output` **Explanation** going from right side to up, as the last elements are same in both input and output the loop inside function simply finds next higher numbers in the triangle gradually reaching to the top leaving the answer intact in the end. **ungolfed(from C++)** ``` #include <iostream> #define SIZE_F 5 int*recFind(int*a, int n) { int i = 0; while (i < n) a[i++] = a[i] - a[i+1]; if (!n) return a; recFind(a, n - 1); } int main() { int first[SIZE_F],*n; for (int i = 0; i < SIZE_F; i++) std::cin >> first[i]; n = recFind(first, SIZE_F - 1);//size - 1 for (int i = 0; i < SIZE_F; i++) std::cout << n[i]; } ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~11~~ 9 bytes ``` Nc¡=äa yÌ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=TmOhPeRhCnnM&input=Wzg0LDQyLDIxLDEwLDJd) 2 bytes saved thanks to Oliver. ## ~~12~~ 11 bytes ``` _äa}hUÊN yÌ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X%2bRhfWhVyk4gecw&input=Wzg0LDQyLDIxLDEwLDJd) 1 byte saved thanks to Oliver. [Answer] # [Julia 0.6](http://julialang.org/), 44 bytes ``` x->reverse([(j=x[end];x=-diff(x);j)for i=x]) ``` [Try it online!](https://tio.run/##Xck9CoAwDEDh3VM4JoNgi4oQ6kVKB8EGWqRK/SG3r47i@L4XrzXMQ2FTpJmyv30@PFiIRqxPiyMxzRKYQZAi8pbrYMRh2XNI55qAwSqHWH26J01/GzvqNGlFqiX9vvIA "Julia 0.6 – Try It Online") Same iterative principle as my R answer. # [Julia 0.6](http://julialang.org/), 55 bytes ``` x->inv([binomial(i,j)for i=(l=length(x)-1:-1:0),j=l])*x ``` [Try it online!](https://tio.run/##XYlBCoMwEADvfYXHXVEwwYp0ST8iHhRM3bCuIrbk96lHEeYyM@ErPDTJuxTLN@sPupF1XXgQ4CKgX/eMHYiTST/HDBFL8zqpsAhOesxj2nbWQxQ8dKZHfFz8SZbura2ptmQNmYrs@dIf "Julia 0.6 – Try It Online") @Lynn's algorithm (inverse of Pascal matrix multiplied by input). ]
[Question] [ Now that I'm thoroughly addicted to Code Golf, it's probably about time that I try to pick up a few golfing languages. Given that I play almost exclusively in JavaScript, [Japt](https://github.com/ETHproductions/japt) seems like the logical language to start with. I'll be diving into the documentation at the next opportunity I get but, in the meantime, please post any tips you have for Japt in the answers below. As I'm a beginner in Japt and golfing languages in general, if you could "translate" your tips to JavaScript, where possible, that would be a big help in helping me get to grips with things. [Answer] ## Moving from JavaScript to Japt As you may know, Japt is simply a shortened, extended version of JavaScript. I created Japt because I was tired of long property names, like `String.fromCharCode(x)` and `Math.floor(x)`, and the tediousness of doing things such as creating a range. Here's the bare minimum you need to know when going from JavaScript to Japt: * Japt is a *transpiled* language; Japt code is *transpiled* to JavaScript and then run as JS. (I guess you could say *compiled*, but transpiled sounds more hipster. Disclaimer: I know absolutely nothing about being hipster) * All entries are full programs by default. The input is implicitly parsed, and the first six inputs are put into the variables `U`, `V`, `W`, `X`, `Y`, and `Z`; the full array is stored in `N`. The result of the last expression is automatically printed. * All uppercase letters are variables, and stay the same when transpiled. Most have preset values, which you can find in the "Variables" section of the Japt docs (at the [interpreter](http://ethproductions.github.io/japt)). * All lowercase letters are prototype functions, or *methods*. Japt adds the methods `a`-`z` (and `à`-`ÿ`) on numbers, strings, and arrays. When you use one of these letters, Japt fills in the `.` and `(`; `Uc` in Japt is equivalent to `U.c(` in JavaScript, which could mean ceil, charCodeAt, or concat, depending on the type of `U`. This is where most of Japt's power comes from; you can find full lists of these methods under the "\_\_\_\_\_ functions" sections of the Japt docs (at the [interpreter](http://ethproductions.github.io/japt)). * A space represents `)`, and `)` represents `))`. This is because when I first designed Japt, I wanted to save as many bytes as possible, and that's how I first thought of doing this. (Though `Us w n` does look better than `Us)w)n)`, IMHO.) * A function is denoted as `ABC{...}`, where the `ABC` can be any string of variables. Functions work for the most part as they do in JS, the main difference being the last expression is automatically returned (rather than having to use `return` or fancy ES6 parentheses). * `'` denotes a single char string (i.e. `'a` is the same as `"a"`), and `#` takes the next char-code and becomes that number (`#e` is the same as `101`). * Anything between dollar signs `$` stays the same during the transpilation process. You can use this to implement `for` loops, for example, since Japt doesn't have those, but I would suggest using other methods (such as `m` on strings and arrays, or `o` on numbers). * Most other chars commonly used in JS — `""`, `0-9`, `(`, `+`, `=`, etc. — stay the same when transpiled (for the most part, anyway). And that is all you need to know to write basic Japt code. Achieving maximum golf power in Japt requires more knowledge, but that can be found in other answers. --- Here's a basic example. Say you have want to take a string of ASCII characters and replace each with its hexadecimal char code. Here's how you might do that in JavaScript: ``` U.split("").map(x=>x.charCodeAt(0).toString(16)).join("") ``` Now to convert to Japt. `.split("")` in JS is equivalent to `q""` in Japt, or even shorter, just `q`. `.join("")` is also just `q`, the difference being that the object is an array instead of a string. `.map(` is `m`, `.charCodeAt(` is `c`, and `.toString(` is `s`. So our Japt code might look like: ``` Uq mX{Xc0 s16} q ``` In Japt, though, `m` works as well on strings as it does on arrays, so we can remove both `q`s: ``` UmX{Xc0 s16} ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=VW1Ye1hjMCBzMTZ9&input=IkhlbGxvLCBXb3JsZCEi) As you can see in the "JS code" box, this directly transpiles to: ``` U.m(function(X){return X.c(0).s(16)}) ``` As you learn to work with Japt, you'll become less and less focused on converting back and forth from JavaScript and be able to code in Japt as its own language. Here's an explanation leaving out the JavaScript portion entirely: ``` UmX{Xc0 s16} // Implicit: U = input string UmX{ } // Take U, and replace each character X with the result of this function: Xc0 // Take the char-code at index 0 in X (the first and only one). s16 // Convert this to a hexadecimal string. // Implicit: output result of last expression ``` [Answer] # Compressing String Arrays > > **UPDATE:** The tools featured in this tip have since be rewritten, improved and integrated into [my Japt interpreter](https://petershaggynoble.github.io/Japt-Interpreter/). For the best results it is recommended that you use that compressor over any of those linked below. I'll revisit this tip when I have some more time and rewrite it with the new compressor in mind. > > > ## Introduction If you have an array of strings in your code, the most obvious way to compress it would be to [run each string through `Oc`](https://codegolf.stackexchange.com/a/121267/58974) individually. For the purposes of this tip, we'll be working with the array [`["lollipop","marshmallow","nougat","oreo"]`](https://ethproductions.github.io/japt/?v=1.4.5&code=WyJsb2xsaXBvcCIsIm1hcnNobWFsbG93Iiwibm91Z2F0Iiwib3JlbyJd&input=), which weighs in at 42 bytes initially. Running each string through `Oc` gives us: [``` [`lo¥ipop`,`Ú\hÚaow`,`Í`,`eo`] ```](https://ethproductions.github.io/japt/?v=1.4.5&code=W2Bsb6VpcG9wYCxg2lxo2mFvd2AsYM0FhWAsYI5lb2Bd&input=) That's now 33 bytes, a decent saving. --- ## Step 1 **But**, we can do better. If we join the array to a newline separated string, we can get rid of the brackets, commas, and extraneous backticks and split on newline to get our array. Applying that to our example array gives us the following: [``` `lo¥ipop Ú\hÚaow Í eo`· ```](https://ethproductions.github.io/japt/?v=1.4.5&code=YGxvpWlwb3AK2lxo2mFvdwrNBYUKjmVvYLc=&input=) Down to 26 bytes now. --- [Answer] ## Compressing strings Japt (currently) uses the [shoco](http://ed-von-schleck.github.io/shoco) library for string compression. You can compress an arbitrary string using `Oc`, as long as it contains runs of lowercase letters: ``` Oc"Hello, World!" ``` [This outputs](http://ethproductions.github.io/japt/?v=1.4.4&code=T2MiSGVsbG8sIFdvcmxkISI=&input=) `HÁM, WŽld!` (well, the `Ž` is technically an unprintable character). You can decompress this by wrapping it in backticks: ``` `HÁM, WŽld!` ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=YEjBTSwgV45sZCFg&input=) Alternatively, you can use the `Od` function to decompress an arbitrary string. This isn't usually useful, but [it has its purposes](https://codegolf.stackexchange.com/a/109518/42545)... [Answer] ## Shortening Numbers With Char-Codes In Japt, you can use `#`, followed by a character to create a char-code. This comes in handy when shortening longer numbers. As @ETHproductions mentioned, this only works on three-digit runs in the range 100-255, unless you are willing to switch to UTF-8. ### Examples: `123` can be shortened to `#{` `101` can be shortened to `#e` **You can even chain these together:** `123101` can be shortened to `#{#e` You can use `String.fromCharCode(123)` in JavaScript, or `123d` in Japt to find the appropriate character. `String.fromCharCode(123)` returns `{` [Answer] # Quick tip: Empty array `[]` Japt has a constant for an empty array: `A`. But, in order to access it, you must prepend a semicolon `;` to your programme to use Japt's alternative constants, otherwise `A` will be `10`. So using `;A` actually offers a 0 byte saving over `[]`, but *will* save you bytes if you need to assign your array to a variable (e.g., `A=[]`). However, if (and only if) your programme is not taking any input, you can access the empty array with just 1 byte by using the `N` variable, which is the array of inputs - with no inputs, it would be empty. [Try it out here](http://ethproductions.github.io/japt/?v=1.4.4&code=Tg==&input=LVE=). This has also has the added benefit of allowing you to use the default constant values in your programme and, in some cases, can still save you bytes over using `;A` even when your programme is taking input thanks to the shortcuts for `s1` and `s2`. [Answer] ## Evaluating JavaScript Japt allows you to execute raw JavaScript by wrapping it around `$...$`. For example, `$alert("hello world")$` This can be shortened by taking advantage of Japt's auto-closing `$` and `)`. `$alert("hello world")$` can be shortened to `$alert("hello world"` ### Compressing JavaScript You can also compress JavaScript using `Ox`. If there is a JavaScript function that you want to use, say `screen.width`, you can compress the string [`"screen.width"` using `Oc`](http://ethproductions.github.io/japt/?v=1.4.4&code=T2Mic2NyZWVuLndpZHRoIg==&input=), then [inserting the result in between Ox`...`](http://ethproductions.github.io/japt/?v=1.4.4&code=T3hgc9fHbi6xZJA=&input=) Note that you do not need closing quotes in Japt when it is not followed by anything else. [Answer] # Know the flags As per [the latest meta consensus (Dec 2017)](https://codegolf.meta.stackexchange.com/a/14339/78410), command-line flags are no longer counted towards bytes. It's really a great news for Japt since it has many flags for extra treatment on input/output. All available flags in Japt are described below, **in the order of evaluation**. The flags in the same group are exclusive to each other. Note that the flags in different groups can be used in combination, resulting in something like [this](https://codegolf.stackexchange.com/a/165894/78410) :) ## `mdefæ` The whole program is mapped over the first argument (`U`). If more arguments are present, they are passed as-is (i.e. *not* pairwise mapped). Otherwise, the second argument is the index, and the third is the whole array, just like `U.m`. If `U` is a number, it is converted to range; if string, it's converted to array of chars and the results are joined together. * `-m`: Applies the above and nothing else. * `-d`: Returns `true` if some result is truthy, `false` otherwise. * `-e`: Returns `true` if all results are truthy, `false` otherwise. * `-f`: Returns the array of elements of `U` whose results are truthy. * `-æ`: Applies `-f` and returns its first element. ## `gh` Takes an element at the specified index. * `-g`: Takes first element (index 0). * `-gX`: Takes the element at index `X` (can be any positive integer). * `-h`: Takes last element. ## `!¡` Convert the result to boolean. * `-!`: Apply boolean not. * `-¡`: Apply boolean not twice (returns the truthiness). ## `N` Convert the result to number. The unary plus is used. ## `PRSQ` Convert to string of some sort. * `-P`: Join the array with `""`. * `-R`: Join the array with `"\n"`. * `-S`: Join the array with `" "`. * `-Q`: Apply `JSON.stringify` (can be any object, not only an array). [Example](https://codegolf.stackexchange.com/a/165497/78410). ## `x` Applies the function `x` to the output. (It's literally `x`, not "any single lowercase alphabet function".) * Array: Sum. * String: Trim from both ends. * Number: Round to integer. [Answer] ## Take advantage of preset variables Variables `A`-`S` are preset to common values that take more than one byte to represent in Japt: * `A`-`G` are `10`-`16`. * `H` is `32`, `I` is `64`, `J` is `-1`, `L` is `100`. * `K` is defined as `new Date()`, which you can manipulate in various ways. * `M` and `O` are objects with various useful functions. You can learn more in the docs. * `P` is the empty string, `Q` is a quote mark, `R` is a newlines, and `S` is a space. * `T` is set to `0`, so you can use it as an accumulator if necessary. --- If the first character in the program is a semicolon `;`, `A-L` are reset as follows: * `A` is the empty array `[]`. * `B` is `"ABCDEFGHIJKLMNOPQRSTUVWXYZ"`. * `C` is `"abcdefghijklmnopqrstuvwxyz"`. * `D` is `"QWERTYUIOP\nASDFGHJKL\nZXCVBNM"`. * `E` is `"[a-z]"`, and `F` is `"[A-Za-z]"` (useful before I added these as regex features) * `G` is `36`, `H` is `65`, and `I` is `91` (useful for alphabet ranges). * `J` is a single comma; `L`, a single period. Nowadays only `A`, `B`, `C`, and `D` from this list are really useful. I'm planning to add a better system which allows up to 256 two-byte variables, which will be preset to these values and a whole lot more. [Answer] ## Unicode shortcuts There are many common structures in Japt that just can't be stored in a single ASCII char, such as `qS`, `p2`, `mX{`, `}`, etc. So to get around this, Japt has "Unicode shortcuts", which are characters in the range `\xA1`-`\xDE` (`¡`-`Þ`) which expand to these common structures. You can find a full list of these in the [interpreter docs](http://ethproductions.github.io/japt). Additionally, `@` stands for `XYZ{`, and `_` stands for `Z{Z`, to help build functions. So let's golf our example program from [another answer](https://codegolf.stackexchange.com/a/121286/42545): ``` UmX{Xc0 s16} ``` Firstly, we can replace `X{X` with `_`, which gives us: ``` Um_c0 s16} ``` Then we can replace `m_` with `®` saving another byte: ``` U®c0 s16} ``` Or we could replace `X{` with `@`, which gives us: ``` Um@Xc0 s16} ``` This then allows us to use the `¡` shortcut to save two bytes: ``` ¡Xc0 s16} ``` One of these two paths can be shortened 1 byte more than the other. Can you figure out which? [Answer] # Use auto-functions You most likely already know that `@` and `_` are shortcuts for `XYZ{` and `Z{Z`, respectively (covered in the [Unicode shortcuts](https://codegolf.stackexchange.com/a/121378/42545) answer). But sometimes you can make functions even shorter. Suppose you had an array of characters and you wanted to map each character to its char-code. You could do this with either of these: ``` mX{Xc} m_c} ``` But there's a better way. If a method or operator is the first item after another method or a `(`, it gets turned into a string. So these two lines are equivalent: ``` r'a'b // Replace all "a"s with "b"s; transpiles to .r("a","b") ra'b // Does the same thing, 1 byte less; transpiles to the same thing ``` But how does that help with our functions? Well, most methods that accept functions, if given a string representing a method or operator, will interpret it as a function. Which means you can also do this: ``` m_c} // Map each item to its char code m'c // Does the same thing, 1 byte less mc // Also does the same thing, 2 bytes less ``` I call these "auto-functions". There are several different varieties: * `m@Xc}` → `mc` * `m@Xc1}` → `mc1` * `m@X+1}` → `m+1` * `m@1+X}` → `m!+1` * `m@2pX}` → `m!p2` Hopefully you get the idea. To swap the arguments, just prefix the method or operator with `!`. [Answer] # Implicit Variable Assignment Whenever you start a new line in Japt the result of the previous line is automatically assigned to one of the input variables (`U`-`Z`), with the first line being `U`, the second `V`, and so on. Let's take an example: say you wanted to create 2 arrays to work with, one containing the numbers 1-10 and the other containing their squares. The long way to do this would be like so: ``` U=Aõ V=Um² [do something with the arrays] ``` Using automatic variable assignment, though, that can be shortened to: ``` Aõ Um² [do something with the arrays] ``` We've saved 4 bytes there. But, in this instance, we can save one more byte because the array of 1-10 is assigned to `U` and [`U` can be omitted in certain scenarios](https://codegolf.stackexchange.com/a/121417/58974): ``` Aõ m² [do something with the arrays] ``` ## Caution One thing to be careful of with this tip is that you don't overwrite any input variables you might need later on in your programme. This can be avoided by leaving one or more empty lines at the start of it. In the following example, the 2 arrays will be assigned to the variables `V` & `W`, instead of `U` & `V`: ``` Aõ Vm² [do something with the arrays] ``` [Answer] # Know the Javascript Since any Japt code runs as transpiled JS, good understanding of JS operators and built-in methods helps a lot in golfing pieces of Japt code. ### Relevant JS tips * [Implicit casting, increment/decrement operators](https://codegolf.stackexchange.com/a/2714/78410) * [Some arithmetic/bitwise operator recipes](https://codegolf.stackexchange.com/a/126112/78410) + This doesn't necessarily save bytes in Japt (due to shortcuts), but it's always good to keep in mind how the operators work. * [Know the comma and assignment-anywhere](https://codegolf.stackexchange.com/a/60969/78410) + The comma (usually implicitly inserted in Japt) is especially useful when you want to initialize a variable and then do some work on it. The following code assigns empty array to `U` and then evaluates `V.m`. (Having a newline activates implicit assignment to `U` on the first line.) ``` []Vm@... ... ``` * [Short-circuiting](https://codegolf.stackexchange.com/a/2788/78410) * [Splitting with numbers](https://codegolf.stackexchange.com/a/11699/78410) + This can be generalized to any method that accepts strings but not numbers. A number passed there will implicitly cast to a string, often saving a byte (e.g. `0` over `'0`). ### Relevant JS built-in functions Closely look at what parameters are passed to function arguments. * [`Array.prototype.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) + Related Japt methods: `Array.a/b/m/x/y/í`, `Number.o/õ`, `String.m/y/í` * [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) + Related Japt methods: `Array.r/å`, `String.å`; for `å`, 4th argument is not passed. * [`Array.prototype.some`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) + Related Japt method: `Array.d` * [`Array.prototype.every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) + Related Japt method: `Array.e` For string methods, it's good to know how the behaviors differ between passing a string or regex with or without `g` flag. * [`String.prototype.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) + Related Japt methods: `String.f/o` * [`String.prototype.search`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search) + Related Japt method: `String.â` * [`String.prototype.replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) + Related Japt methods: `String.e/k/r` + For `e/r`, passing functions as 2nd argument is OK, and understanding the function parameters is highly encouraged. [Answer] # Use multiple lines when necessary For most not-too-hard challenges, you can express the solution in just one line of Japt, as a sequence of applying built-in functions. But more complex ones will require to use looping constructs, recursion, or reusing large chunks of code. This is where multi-line programming comes in. ## Remove closing parens **Task**: Given an array of numbers, pair each element with the index squared, and sort it by the sum. `[5,1,17,9,3] => [[5,0],[1,1],[17,4],[9,9],[3,16]] => [[1,1],[5,0],[9,9],[3,16],[17,4]]` One-line solution is `íUm@Yp2})ñx`, but `})` costs two bytes (and there is no one-byte shortcut). You can remove `})` by simply moving the trailing `ñx` to the next line, so the code looks like this: ``` íUm@Yp2 ñx ``` and the transpiled JS becomes: ``` U = U.í(U.m(function(X, Y, Z) { return Y.p(2) })); U.ñ("x") ``` You can clearly see this does the same thing as the one-line solution, just assigning the intermediate result back to `U`. ## Recurse with implicit arguments The recursion function `ß` takes all of `UVWXYZ` as implicit parameter, if not specified. `U` is obviously the main input, but you can use any of `VWXYZ` to keep track of other values you need. For example, you can do something like the following: ``` (modify input and implicit assign to U) (modify V and implicit assign to V) (test something and call ß without arguments; U and V are passed automatically) ``` Alternatively, if all you want is a temporary variable, you can use inline assignment, like `(T=...)`, as the variable `T` (0) is rarely used as-is. ## Reuse a long function For this, I don't think I can come up with a good example task, so I'll reference [the only solution this tip was used](https://codegolf.stackexchange.com/a/165790/78410), and just outline some general ideas. * In order to reuse a function, you need to store it in a variable. Starting a line with the function-opener `{`, `@` or `_` does the job. Alternatively, you can also do something like `(T=@...})` to embed the function assignment inside a more complex line. * It's actually not trivial to call the stored function. Suppose `V` is a function and we want to call `V(U)` in JS. `VU` does not work since it simply means `V,U`. `V(U` doesn't either; it's `V,(U)`. Even the function methods aren't helpful very much. The best way we found is: + `[U]xV` (map and sum) if the result is number + `UmV` if `U` is a single char and `V` returns a string, or + `$V($U` or `[U]mV g` in general. * However, mapping or looping with it is rather easy. To map over an array, use `UmV`. To find the first integer that satisfies `V`, use `Va`. [Answer] # Fun with Auto-Functions As a follow-up to [ETH's general tip on auto-functions](https://codegolf.stackexchange.com/a/124037/58974), this tip will provide a few specific examples of byte saving tricks you can achieve with them, which I'll add to as I think of more. --- ## Get the largest integer in an array. Assume we have the array `[3,1,4,2]` assigned to variable `U` and we ant to retrieve the largest number from it. We *could* do it in 4 bytes by sorting the array and then popping the last element: ``` Un o ``` The downside to that is that we've modified the original array; `U` is now `[1,2,3]` which may not always be desirable. Luckily, there's a way of doing it without modifying the array that's also one byte shorter: ``` Urw ``` What we've done there is reduced the array using the `w` method, which, when used on an integer returns the larger of the integer and the method's argument (e.g., `2w5` returns `5`). So the above is the equivalent of `UrÈwY` or `UrXY{XwY}`. Note, though, that this tip won't work in the case of *all* the integers in the array being negative. [Answer] ## When *not* to use `í` `í` is a useful built-in that pairs (or `zip`s) two arrays or strings, and optionally maps each pair through a function. However, it currently has a few minor issues when given uneven arrays or strings: * If the first array has more items than the second, the non-existent items in the second will be given as `undefined`. * If the second array has more items than the first, it will stop processing at the end of the first array. This can make it difficult to, say, compare two uneven strings and take the char with the higher code point from each pair. Even if you know that `U` is going to be the longer one, it still takes far to many bytes to solve this simple task: ``` UíUç hV @[XY]n o ``` What you could do instead would be to take input as an array of two strings, *transpose* the array with `y`, and then map each row to the correct result: ``` Uy m_q n o ``` This has the advantage of always padding the shorter string with spaces, making it a piece of cake to go through the entirety of both strings. Real-life examples: [1](https://codegolf.stackexchange.com/a/125485/42545), [2](https://codegolf.stackexchange.com/a/138546/42545) [Answer] # Generate the ASCII Range > > Update: Japt now has a constant for the ASCII range; the alternative value for `E`, accessible with `;`. See [this tip](https://codegolf.stackexchange.com/a/121380/58974) for more on Japt's constants. > > > While Japt doesn't (yet) have a built-in for the ASCII range, you can generate an array of characters in just 5 bytes: ``` 95odH ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=OTVvZEg=&input=) --- ## How It Works `95o` creates the range `[0,95)` with each element being passed through the [auto-function](https://ethproductions.github.io/japt/?v=1.4.5&code=OTVvZEg=&input=) `d` which, when used on a number, returns the character at that codepoint. Pass a number as an argument to the `d` method, in this case `H`, the Japt constant for 32, and it will be added to the original number before being converted. An equivalent solution in JavaScript would be: ``` [...Array(95)].map((_,x)=>String.fromCharCode(x+32)) ``` --- ## Random Characters To get a random character in the ASCII range, use `ö` instead, which returns a random number from the range `[0,X)`, where `X` is the number it is run on. ``` 95ö dH ``` Or, to get an array of multiple random characters, pass the number of characters you need as an argument of `ö`. The following will return 10 characters: ``` 95öA mdH ``` [Answer] ## Remove unnecessary structural chars By structural chars, I mean `{}`, `()`, `$`, even `"` and ```. You can typically remove these chars whenever they occur right at the end of a program (e.g. `UmX{Xc +"; "} -> UmX{Xc +";` ). Additionally, you can remove parens or spaces whenever they appear in the following places: * Up against a semicolon `;` (or the end of the program); * To the right of `{` (and by extension, `@`) or `[`, or the left of `]` or `}`. Also, commas are very rarely needed to separate arguments. If you write `AB`, for example, Japt knows you mean `A` and `B` separately. You only really need a comma to separate two numerical literals, such as `Us2,5`. Finally, if there's a `U` at the start of a program or after a `{` or `;`, followed by a method call (lowercase letter or related Unicode shortcut) or any binary operator excluding `+` and `-` (`*`, `&`, `==`, etc.), you can remove the `U` to save a byte and Japt will insert it for you. [Answer] # Modify the Last Element in An Array Sometimes you may need to modify the last element in an array so here's an explanation of a short way of doing that. We'll be working with the array `[2,4,8,32]` assigned to input variable `U` and dividing the last integer (`32`) by 2. The obvious way to achieve this would be with this 9 byte solution ([Demo](http://ethproductions.github.io/japt/?v=1.4.5&code=VWgzVWczIC8y&input=WzIsNCw4LDMyXQ==)): ``` UhJUgJ /2 ``` * `hnx` sets the element at index `n` to `x`. * `gn` returns the the element at index `n`. * `J` is the Japt constant for `-1`, which, thanks to Japt's support for negative index, allows us to work with the last element in an array; handy when you don't know the size of the array. * And `/2` is simply division by 2. So the above sets the element at index `-1` in the array to the element at index `-1` in the array divided by 2. Or in JavaScript: `U[3]=U[3]/2`. When you write it out like that, it seems a far too long-winded way of going about it. Luckily, there *is* a shorter way; we could pop the last element from the array, modify it and push it back to the array. Performing each of those operations individually would take more than 9 bytes but we can do them all at once for just 7 bytes, a 2 bytes saving ([Demo](http://ethproductions.github.io/japt/?v=1.4.5&code=VXBVbyAvMg==&input=WzIsNCw4LDMyXQ==)) ``` UpUo /2 ``` Translated to JS, it's the equivalent of: ``` U.push(U.pop()/2)&&U ``` ]
[Question] [ [Related](https://codegolf.stackexchange.com/q/257458/119451). Given a positive integer \$n\$, output all integers \$b\$ (such that \$1<b<n-1\$) where \$n\$ can be written as the sum of any number of consecutive powers of \$b\$. **Example:** Let's say \$n=39\$. \$3^1+3^2+3^3\$ \$= 3 + 9 + 27\$ \$= 39\$ This does not work for any other \$b\$, so our output is `[3]`. **Test cases up to \$n=50\$:** ``` 1: [] 2: [] 3: [] 4: [2] 5: [] 6: [2] 7: [2] 8: [2] 9: [3] 10: [] 11: [] 12: [2,3] 13: [3] 14: [2] 15: [2] 16: [2,4] 17: [] 18: [] 19: [] 20: [4] 21: [4] 22: [] 23: [] 24: [2] 25: [5] 26: [] 27: [3] 28: [2] 29: [] 30: [2,5] 31: [2,5] 32: [2] 33: [] 34: [] 35: [] 36: [3,6] 37: [] 38: [] 39: [3] 40: [3] 41: [] 42: [6] 43: [6] 44: [] 45: [] 46: [] 47: [] 48: [2] 49: [7] 50: [] ``` **Clarifications:** * You can use [this Python script](https://tio.run/##VY/BDoIwEETvfMUcW4IH5SQJX0I42FB0SV0JLQn9@tqiAs71zezMjt49XlyGTvewszJknRVGVhmi@tcEAjGmG9@1MJoj@rIfH3ZOB5TkSZsOphkqagOjjk4niMfZCSmzFFZ7@FKAT@dDsU1sm9TkHxvL9tDi49FGIc@xrJllzbQbp/TUU3iJugb/rxunNEcV8DKE8voG) to generate your own test cases. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins! [Answer] # [JavaScript (V8)](https://v8.dev/), 62 bytes Prints the results. ``` n=>{for(b=1;i=++b<n-1;k||print(b))for(k=n;k%b?i--:k/=b;)k-=!i} ``` [Try it online!](https://tio.run/##FcrRCsIgFMbx@57iJASKWHkRRO7Ug0QXc2xhynE42c22Zzd39f/g9/3auZ265Mas5nsZsBA@lyEmblEbh1LahpQ2fl3H5ChzK8SuHsn4k305pR7@gtYIr/DotrJj6DMQIGhT0yDcrnVIKWA5AHSRphj6c4hfzt6EDGR9SWAfJkz1gVPtVv4 "JavaScript (V8) – Try It Online") ### Algorithm Given the input \$n\$ and for each \$b\in[2,n-2]\$: 1. we do \$n\gets n/b\$ as long as \$n\equiv 0\pmod b\$ 2. we do \$n\gets (n-1)/b\$ as long as \$n-1\equiv 0\pmod b\$ If we end up with \$n=0\$, then \$b\$ is a solution. ### Explanation If \$n\$ is of the form \$b^p+b^{p+1}+\dots+b^{p+q}\$, the first step will normalize it to: $$b^0+b^1+\dots+b^q$$ and each iteration of the second step will remove the most significant term ... $$b^0+b^1+\dots+b^{q-1}$$ ... until it's eventually reduced to \$0\$. --- ### [C (gcc)](https://gcc.gnu.org/), 79 bytes Essentially the same code. ``` b,i,k;f(n){for(b=1;i=++b<n-1;k||printf("%d ",b))for(k=n;k%b?i--:(k/=b);)k-=!i;} ``` [Try it online!](https://tio.run/##NY7LDoIwEEX3fMVIQtKmNNKFG4bGb6ElxaY6EERdAL9u5RF3J/eRe61srY3R5D4P6BjxyXUDM1qh10KYiqTCMM/94Gl0LM0aSHPD@RYKmjBk5uqlLFk4a8ORB6lPHpf47nwDj9oT4zAlAGsbCFfYigQaFAJBpeFSrCDEkQL475DOmnKdAuK4G9u1g/rXaG/1wFSxC0uyxK9197p9Rvn5AQ "C (gcc) – Try It Online") I wish it could be rearranged to get rid of `:(k/=b)`. The obvious way is `k%b<1?k/=b:i--`, but that's just as long. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 73 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 9.125 bytes ``` ⇩Ḣ'?ʀeÞSṠ?c ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBPSIsIiIsIuKHqeG4oic/yoBlw55T4bmgP2MiLCIiLCIxXG4yXG4zXG40XG41XG42XG43XG44XG45XG4xMFxuMTFcbjEyXG4xM1xuMTRcbjE1XG4xNlxuMTdcbjE4XG4xOVxuMjAiXQ==) Formulas? No we do things brute force around here. ## Explained ``` ⇩Ḣ'?ʀeÞSṠ?c­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌­ ⇩Ḣ' # ‎⁡Keep all from the range [2, n - 2] where: ÞSṠ # ‎⁢ Sums of sublists of ?ʀe # ‎⁣ The number raised to each number in the range [0, input] ?c # ‎⁤ Contains the input 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~24~~ 20 bytes ``` NθIΦ…²⊖θ¬⊙⪪⍘θι0⁻λI¬μ ``` [Try it online!](https://tio.run/##LYzNCsIwEITvPkXoaQMRtNee/EHwYBH7BGtcaiDZtslG8OljFOcwh5n5xj4x2gl9KWees/Q53CnCorvVNToWOGASODkvNb0hjwStUUeykQKx0KNOtVH9JLDjNwyzdwJ7TDRIxUdYjHK1bzZN9YvjnMAb9Tv9MkH/1ZWybcv65T8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: When converted to base `b`, `n` has to have the form `1+0*`, thus when split on `0` the first part can only contain `1`s and the other parts must be empty, although the code "permits" `0`s. ``` Nθ Input `n` as a number … Range from ² Literal integer `2` to θ Input `n` ⊖ Decremented Φ Filtered where θ Input `n` ⍘ Converted to base ι Current value ⪪ Split on 0 Literal string `0` ¬⊙ All parts satisfy λ Current part ⁻ Only contains occurrences of μ Inner index ¬ Logical Not I Cast to string Implicitly print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ½Ḋbt0ỊƑɗ@Ƈ ``` A monadic Link that accepts a positive integer and yields a list of all valid integer bases. **[Try it online!](https://tio.run/##ASYA2f9qZWxsef//wr3huIpidDDhu4rGkcmXQMaH/8OHxZLhuZj//zE1Ng "Jelly – Try It Online")** ### How? A base, \$b\$, works for \$n\$ when \$n\$ converted to base \$b\$ is a run of ones optionally followed by a run of zeros. No \$b > \sqrt{n}\$ can work since the \$b^2\$ term breaks the bank on its own and the \$b^1\$ and \$b^0+b^1\$ solutions are the excluded cases \$b\ge n-1\$. ``` ½Ḋbt0ỊƑɗ@Ƈ - Link: positive integer, n ½ - square-root {n} Ḋ - dequeue -> B = [2,3,4,...,floor(sqrt(n))] Ƈ - keep those {b in B} for which: ɗ@ - last three links as a dyad with swapped arguments - f(n, b): b - convert {n} to base {b} t0 - trim zeros (e.g. [4,0,1,0,0,0] -> [4,0,1]) Ƒ - is invariant under?: Ị - insignificant? (abs(digit)<=1 vectorised) ``` [Answer] # [Python](https://www.python.org), 82 bytes *-1 byte, thanks to xnor* *-1 byte, thanks to Arnauld* ``` lambda n:[b for b in range(2,n-1)for i in range(n*n)if~-b*n==b**(i%n+1)-b**(i//n)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3g3ISc5NSEhXyrKKTFNLyixSSFDLzFIoS89JTNYx08nQNNUGCmQjBPK08zcy0Ot0krTxb2yQtLY1M1TxtQ01dMFNfP08zFmqyMppGUwNNKy4FhYKizLwSjUydNI1MTU2I0gULIDQA) Uses the equation \$\sum\_{k=i}^{j}b^k = \frac{b^{j+1}-b^i}{b-1}\$ [Answer] # [Haskell](https://www.haskell.org/), 54 bytes ``` f n|r<-[0..n]=[i|i<-[2..n-2],a<-r,b<-r,n*i-n==i^a-i^b] ``` [Try it online!](https://tio.run/##XZLRboMgFIbvfYpzsYt2gUYOqG0iT2JoYjeXkXZkUS99dwdtIv7zgvgB5@Tjh@9@ug@Px7p@UVjGVnbl6RSc7fziI3AEyU70rRzFLQ3h3ctgrb/20l9vbv3pfSBLv6MPM71RHz6pi63IWhppoUMQNB6plTQP0/zRT8PkimL7j5VdQfE7KEGdO4oX8B70HkwE3qjaL9Ww1ACdgS6R9Eaq3HdRIKKSCYvdZo216KMqxKeSMHmigeZnoAskkKRyIStECIghIUYlTkpVxhr2NnAaxpgYjHT5PExupdX/CYZyDVraAMHN6SSlRZ0nICcNOWm8PVMiwvWZZJTbGo0ISgaUDORkwMdgTCYJNflNvp6TK9Y/ "Haskell – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~55~~ 56 bytes ``` ->n{(2..n-2).select{|x|/^[0_]*(1_)+1$/=~n.digits(x)*?_}} ``` [Try it online!](https://tio.run/##FcvdCkAwGADQVxEuNvIx5XI8iFj@UyzZ1DSfV5@c@3Ne/e1m7pJSWpIDyCSnoKZtGrR9zJO2dSaaiDBBYxam/JUwrsuqFTE0qgSiOy6tPMIAiozC3h3/8gNr0AvsXJsGfXQf "Ruby – Try It Online") If a number `n` is the sum of consecutive powers of `x`, then its representation is base `x` is a sequence of `1`s followed by any number of zeroes. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~28~~ 26 bytes ``` {2+&x{i~!#i:&y\x}'-1_2_!x} ``` -2 thanks to @coltim [Try it online!](https://ngn.codeberg.page/k#eJxLs6o20larqM6sU1TOtFKrjKmoVdc1jDeKV6yo5eJKUzfUVjQ14AIA4QwKaA==) [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 9 bytes ``` ←ᶠ{ᵈqEů∑= ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FpsetU14uG1B9cOtHYWuR9c_6phou6Q4KbkYKr3gpqMhlxGXMZcJlymXGZc5lwWXJZehAZehIZehEZehMZehCZehKZehGZehOZehBZehJZeRAZcRUI8Rl5Exl5EJl5EpxCQA) ``` ←ᶠ{ᵈqEů∑= ← Decrement ᶠ{ Filter the range [0, n) by: ᵈq Find any subsequence of the range [0, input) E Power ů Check that it does not contain duplicates so that the base is not 1 ∑ Sum = Check that it is equal to the input ``` --- # [Nekomata](https://github.com/AlephAlpha/Nekomata), 10 bytes ``` ←ᶠ{1>B:o±= ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY4rbgJRGEb9Wcb4Se7_uC-SIthGg4CmNWRAMFX1VQh8zQggOIJhAeyisl1JJyn6yznn-zqvX1ebbtEvTs9N2zXz4fjev7Xl8vu5_7kNHzKdTTb369Nhu3zZPrbheycohhNJZAoVCYggihjiSEQSkpGCVDSgI6OooY5GNKEZLWjFAibYqDTMsYglLGMFq3jABVd8LDoe8YRnvOCVGP5P_QE) A port of [@Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/264952/9288). ``` ←ᶠ{1>B:o±= ← Decrement ᶠ{ Filter the range [0, n) by: 1> Check that it is greater than 1 B Convert the input to that base : = Check that it is invariant under: o Sort ± Sign ``` Now I regret supporting converting to base 1, otherwise that `1>` could be omitted. [Answer] # [Haskell](https://www.haskell.org), 74 bytes ``` 0#i=[] n#i=mod n i:div n i#i f n=[i|i<-[2..n-2],all(==1)$snd$span(<1)$n#i] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZM9boMwGIaHbhyh0yclA0gmwj9AUsUX6BUQAypEtUrcKNBOuUmXLFXP1J6mdlAxb1nMY_N9evzafHw9N8NL1_fX6-fbeEi334_Zyuiqjqwbjq8tWTIPrXn348pEB7K6MhezTyux2dhU1Kzp-1hrnqwH266HU2PjvQNXXk8df-7uj42xpOl0NnakNTW2pcp1Iq3pTBeKLaNzQvuUxm4Yn5qhG-oomt9dZRWRe2LOqKoTNoFYglyCciBmypdLBSyVQFugnSM5E8-WXTiIcG8i2OJjibXow3PEmxJTYaKE5lugHSTgpUKh4IgQkICEBCoJr5QHLODbEnYjMCYBRjK7bSa0kvz_hIByCVpSAcHJSS8lWREmICcJOUk8PZUhwvEpbxTaKokISgqUFOSkwEdhTMoLleFOTtepjqZf5O_n-wU) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` tL¦ʒIÝmŒOIå ``` -1 byte thanks to *@MTN* by porting `tL¦` from [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/264952/52210). [Try it online](https://tio.run/##yy9OTMpM/f@/xOfQslOTPA/PzT06yd/z8NL//40tAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/W9q4Opnr6TwqG2SgpK936GV/0t8Di07NenQusNzc49O8gfSS//X6vwHAA). **Explanation:** ``` t # Get the square-root of the (implicit) input-integer L # Pop and push a list in the range [1,floor(sqrt(input))] ¦ # Remove the leading 1 to make the range [2,floor(sqrt(input))] ʒ # Filter this list by: IÝ # Push a list in the range [0,input] m # Take the current integer to the power of each of these values Œ # Get all sublists of this list O # Sum each inner sublist Iå # Check whether the input is in this list of sums # (after which the filtered list is output implicitly as result) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes ``` Select[r=Range[0,#-2],Tr/@Subsequences[#^r]&/*MemberQ[#]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277Pzg1JzW5JLrINigxLz012kBHWdcoViekSN8huDSpOLWwNDUvObU4WjmuKFZNX8s3NTcptSgwWjk2Vu1/QFFmXom@Q2BpZmqJg1a6voMCxAxDHVOD2P8A "Wolfram Language (Mathematica) – Try It Online") -2 bytes from @att [Answer] # [Perl 5](https://www.perl.org/), 88 bytes ``` sub{grep{$x=$_;join('+',map$x**$_,0..$n)=~/\b.+\b(??{$n-eval$&?$;:""})/}2..sqrt($n=pop)} ``` [Try it online!](https://tio.run/##bZFNc5swEIbP1a/YqGowMeFDkj8CYZx7Z5pLb8GTsWvw0DqCAGnc8bh/3V2xmpzKYd/VavXsK9GW3WF2MQ28bzpTm30PfLvpyvem2/GMiSq/9G/b074r25M45uI5@9nUZuJNveBl04rjzY14DuIwFMbP/0bFNpwW28lqdRLmtvy9OYjrlchSzs9@dJZh2L92w0SYvG1a/3zJWNV0E@jbQz1EhYmC@3vOwWdJCk9rJseoxqgxyjWbjYs5LRYkS5I7FLVmSTy2JIRILEMGtq7cviMlM6cjLNCYLejIkuSOPFgcbsrEKZmS5Eo6mLSwGeqcyguaJZ01SSwVj6OwTyUfmaQWRUClSeieyuJUMMeMvCnyptxddeyULqstC5u1ckowTTBN3jSRtLOmLWqBD0vPxk4M8Hv5g/8oeCiPrZ9HxW4a7bOx/tmUxwHqCoS5ylX8n6JeZo7wsG@G/FpUSPKp1na1GSr@5XbeA5gU@7GIM8ofQ7lLwY7DAh7DHGNheMA@cZtyKF@B2wYOK/CaXx6k4H17/A6PX72MnS//AA "Perl 5 – Try It Online") [Answer] # [Scala 3](https://www.scala-lang.org/), 85 bytes ``` n=>for{b<-2 to n-2;i<-0 to n*n-1;if(b-1)*n==math.pow(b,i%n+1)-math.pow(b,i/n)}yield b ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TU2xTsMwEN37FU9ISHGDISlCQmlciZGBqepUdbDbuBxyL8V1QVWVz2BiCQP8U_8GN2FAp7v37t67u8-f3VI7fduePmrzUi0DnjQxjgNgVVlsYpNov94VePBeH-bT4InXC1FgxhSgOidga4-EUEpk2HMgh7tM_GnANu4Ex9GQ4iJGCpuQEJ3aDM4Zy5t2sAUeOajJtHqdR7KA-t4HK-9PM1aT-ONoSjlCqMFyNKZSZh0fsszHZBMjczFkpTY6PF9v6_fEXNElp7mQ_yc3LJoDVW4F0x__anps2x5_AQ) --- Uses the equation \$\sum\limits\_{k=i}^{j}b^k = \frac{b^{j+1}-b^i}{b-1}\$ ]
[Question] [ You are to write a program which outputs a single positive integer \$n\$. The integer may have leading zeros and whitespace, and/or trailing whitespace. Then, choose a positive integer \$m > 1\$. When the program is repeated exactly \$m\$ times, it should output \$m \times n\$ (and only \$m\times n\$). When repeated any number of times other than \$m\$, it should output \$n\$ (and only \$n\$). You may choose the value of \$m\$, so long as it is a positive integer greater than 1. In this context, "repeated \$m\$ times" means that the whole program is repeated \$m\$ times, rather than each character. For example, repeating `abcde` \$4\$ times yields `abcdeabcdeabcdeabcde`. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code (not repeated \$m\$ times) in bytes wins. --- For example, if your program is `print 5` which outputs 5, and you choose \$m = 3\$, then: * `print 5` should output 5 * `print 5print 5` should output 5 * `print 5print 5print 5` should output 15 * `print 5print 5print 5print 5` should output 5 * `print 5print 5print 5print 5print 5` should output 5 * etc. [Answer] # [R](https://www.r-project.org/), 16 bytes ``` T=a=1+!T;T=T-1;a ``` [Try it online!](https://tio.run/##K/r/P8Q20dZQWzHEOsQ2RNfQOvF/Ua5GiCaXskJQakFqYklqikJJeWZyKhe6OnQ@F4Y@Y4WSzNzUYoI6CZtkQqZJGH4DAA "R – Try It Online") Works with \$n=1\$ and \$m=2\$. --- Previous version: ## [R](https://www.r-project.org/), ~~24~~ ~~23~~ ~~21~~ 19 bytes -4 bytes thanks to Dominic van Essen ``` T=a=1+0^T^2;T=T-1;a ``` [Try it online!](https://tio.run/##K/r/P8Q20dZQ2yAuJM7IOsQ2RNfQOvF/Ua5GiCaXskJQakFqYklqikJJeWZyKhcWpViEuDB0GyuUZOamFhOpnygjTSg1Epu3AQ "R – Try It Online") Works with \$n=1\$ and \$m=2\$. This uses the fact that \$0^k = \begin{cases} 1 & \text{ if } k=0\\0& \text { otherwise.}\end{cases}\$ Therefore, when the code is repeated \$k\$ times, we output \$1+0^{(2-k)^2}\$, which is worth \$2\$ when \$k=2\$, and \$1\$ otherwise. [Answer] # [R](https://www.r-project.org/), ~~27~~ ~~20~~ 18 bytes *Edit: -2 bytes thanks to Robin Ryder, and -2 bytes thanks to pajonk* ``` b=a=3^!(F=F+1)-3;a ``` [Try it online!](https://tio.run/##K/qvrJCfl6qQnF9QqZBfWlJQWlKsYPg/yTbR1jhOUcPN1k3bUFPX2DoRqK6kPB@kLjO1GKpSwZCrKFfDTZMLUzmmCBcX0ISMotRUNDOMSTADu6lp@aVF6A5TgJiqQKaxOCzKLEuluUXYrc7LzBsIq6kl8h8A "R – Try It Online") n=1, m=3 (or trivially for any m up to 9 for same bytes...) [Answer] # [Bash](https://www.gnu.org/software/bash/), 26 n=3, m=2 ``` trap echo\ $[++a-2?3:6] 0 ``` [Try it online!](https://tio.run/##S0oszvj/v6QosUAhNTkjP0ZBJVpbO1HXyN7YyixWwYDr/38A "Bash – Try It Online") [Try it online!Try it online!](https://tio.run/##S0oszvj/v6QosUAhNTkjP0ZBJVpbO1HXyN7YyixWwYALt8z//wA "Bash – Try It Online") [Try it online!Try it online!Try it online!](https://tio.run/##S0oszvj/v6QosUAhNTkjP0ZBJVpbO1HXyN7YyixWwYCLHJn//wE "Bash – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~77~~ ~~50~~ ~~46~~ ~~43~~ ~~39~~ 37 bytes ``` input(1+(len([*open(__file__)])==2)) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzOvoLREw1BbIyc1TyNaK78ASMXHp2XmpMbHa8Zq2toaaWpy/f8PAA "Python 3 – Try It Online") Simply counts the number of lines of the code and returns 2 if it is 2 and one otherwise. The `x` is not defined and causes a runtime error immediately after and ends the program. $$n=1, m=2$$ Thanks to *ChartZ Belatedly* for -27 bytes, *FryAmTheEggman* for -3 bytes, *pxeger* for -4 bytes and *dingledooper* for -2 bytes. [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 bytes ``` |d1=^ ``` [Run and debug it](https://staxlang.xyz/#c=%7Cd1%3D%5E&i=) [Run and debug itRun and debug it](https://staxlang.xyz/#c=%7Cd1%3D%5E%7Cd1%3D%5E&i=) [Run and debug itRun and debug itRun and debug it](https://staxlang.xyz/#c=%7Cd1%3D%5E%7Cd1%3D%5E%7Cd1%3D%5E&i=) This works for `m = 2, n = 1`. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 22 bytes, \$n=1\$, \$m=2\$ ``` +!$x+!(++$x-2)-!($x-3) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X1tRpUJbUUNbW6VC10hTV1EDSBtr/v8PAA "PowerShell – Try It Online") [Try it online!Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X1tRpUJbUUNbW6VC10hTV1EDSBtrYhf9/x8A "PowerShell – Try It Online") [Try it online!Try it online!Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X1tRpUJbUUNbW6VC10hTV1EDSBtrkiL6/z8A "PowerShell – Try It Online") # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 39 bytes, \$n=1\$, \$m=2\$ ``` 1+((gc $PSCommandPath).Count-eq2);exit ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31BbQyM9WUElINg5Pzc3MS8lILEkQ1PPOb80r0Q3tdBI0zq1IrOE6/9/AA "PowerShell – Try It Online") # PowerShell 7, 39 bytes, \$n=1\$, \$m=2\$ ``` (gc $PSCommandPath).Count-eq2?2:1;exit ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes ``` ⎚⊞υω×1⁼³Lυ5 ``` \$n=5\$, \$m=3\$. [Try it online!](https://tio.run/##ASQA2/9jaGFyY29hbP//4o6a4oqez4XPicOXMeKBvMKz77ysz4U1//8 "Charcoal – Try It Online") [Try it online!Try it online!](https://tio.run/##ASQA2/9jaGFyY29hbP//4o6a4oqez4XPicOXMeKBvMKz77ysz4U1//8 "Charcoal – Try It Online") [Try it online!Try it online!Try it online!](https://tio.run/##S85ILErOT8z5//9R36xHXfPOt57vPDzd8FHjnkOb3@9Zc77VlFTx//8B "Charcoal – Try It Online") [Try it online!Try it online!Try it online!Try it online!](https://tio.run/##S85ILErOT8z5//9R36xHXfPOt57vPDzd8FHjnkOb3@9Zc77VlFri//8DAA "Charcoal – Try It Online") Explanation: ``` ⎚ ``` Clear the canvas of output from the previous copy. ``` ⊞υω ``` Track the number of copies. ``` ×1⁼³Lυ ``` If that's 3 then print a `1`. ``` 5 ``` Always print a `5`. [Answer] # [Zsh](https://www.zsh.org/) `-F`, 21 bytes, \$n=1\$, \$m=4\$ ``` bye `wc -l<$0`-5?1:4 ``` [Try it online!](https://tio.run/##qyrO@G9jo@6qbpf2P6kyVSGhPFlBN8dGxSBB19Te0MqE678rV1VxhoKum0Ial42NjYr9fwA "Zsh – Try It Online") [Try it online!Try it online!Try it online!Try it online!](https://tio.run/##qyrO@G9jo@6qbpf2P6kyVSGhPFlBN8dGxSBB19Te0MqEi0LB/65cVcUZCrpuCmlcNjY2Kvb/AQ "Zsh – Try It Online") Note the trailing newline. Outputs via exit code. [Answer] # JavaScript, ~~65~~ ~~60~~ ~~57~~ ~~46~~ 45 bytes, \$n = 1, m = 5\$ ``` var i=-~i;setTimeout(_=>i=i&&alert(i^5?1:5)); ``` *Saved 3 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563).* *Saved 11 bytes thanks to [user81655](https://codegolf.stackexchange.com/users/46855)* *Saved 1 byte thanks to [Neil](https://codegolf.stackexchange.com/users/17602)* By itself: ``` var i=-~i;setTimeout(_=>i=i&&alert(i^5?1:5)); ``` Repeated 5 times: ``` var i=-~i;setTimeout(_=>i=i&&alert(i^5?1:5));var i=-~i;setTimeout(_=>i=i&&alert(i^5?1:5));var i=-~i;setTimeout(_=>i=i&&alert(i^5?1:5));var i=-~i;setTimeout(_=>i=i&&alert(i^5?1:5));var i=-~i;setTimeout(_=>i=i&&alert(i^5?1:5)); ``` [Answer] # Factor, 172 bytes, n = 2, m = 4 Let's see some love for the [language of the month](https://codegolf.meta.stackexchange.com/questions/20824/language-of-the-month-for-march-2021-factor?cb=1). ``` USING: prettyprint namespaces init math io kernel ; IN: main 0 1 set-global 1 get-global 1 + 1 set-global [ 1 get-global 4 = [ 8 ] [ 2 ] if . flush ] 2 add-shutdown-hook ! ``` (The leading space before `USING:` is significant, and so is the lack of newline at the end) We store a simple counter in a global variable (global variables in Factor are, by convention, symbols, but there's no actual requirement, so our global variable is named the integer `1`). Then the part of our code that "repeats" simply increments this global. We register a shutdown hook that does the final checks for us. The fact that we register the hook several times is irrelevant, because we give it the same name each time (this name, incidentally, is the integer `2`; once again, Factor is happy to accept a very loose definition of "name"). [Try it online!](https://tio.run/##VYmxCsIwGAZ3n@JzlootDlJxli5dipM4/DZJE5omIfmL@PQxk9Dl4O4UjexjzngMXX9vEaJk/oZoHMPRIlOgUSYYZxgLsYbxmGV00uKKrm9LNA4n1EiSq8n6N9ldjekv5Rw2F09s/hm3ki54FTaFRuEIZdekizQgIaqkVxb@4yrt/Yx9zj8 "Factor – Try It Online") [Try it online!Try it online!](https://tio.run/##1Y6xCsIwFEV3v@I6S8QWB6k4S5cu4iQOsUmb0PQlJK@IXx8zCf0ElwP3nOUOsmcfc8b91nbXBiFq5k@IlhgkZ52C7HWCJcuYJRtYj0lH0g5ntF1TpCUcUCFpFqPzL@k2FcbfKGW3qnhg1Y@4FHXCs7AutAP2GNySTBk1pFIimYWVf5Mw3k/Y/tPXnL8 "Factor – Try It Online") [Try it online!Try it online!Try it online!](https://tio.run/##7Y6xCsIwFEV3v@I6S8QWB6k4S5cuxUkcYpM0oWkSklfEr4@ZhH6Am8uFc85yFR/Ix5xx69vu2iBESfQO0TiC47NMgQ8ywThDmDlpGI9JRictzmi7pkjjcECFJImN1j@53VQYv1DKblVxx6ofcSnqhEfZuqxR2EPZJekCNbgQLOmFhH85pr2fsP1//c3XnD8 "Factor – Try It Online") [Try it online!Try it online!Try it online!Try it online!](https://tio.run/##7Y6xCsIwFEV3v@I6S8QWB6k4S5cuxUkcYpM0oWkSklfEr4@ZhP5DlwvnnOUqPpCPOePRt929QYiS6BuicQTHZ5kCH2SCcYYwc9IwHpOMTlpc0XZNkcbhhApJEhutf3O7qzD@oZTDquKJVT/jVtQFr7J1WaNwhLJL0gVqcCFY0gsJ/3FMez9hv33dvub8Aw "Factor – Try It Online") [Answer] # Java 6, ~~120~~ 77 bytes, \$n=1, m=2\$ ``` enum A{A;{System.out.print(new java.io.File("A.java").length()==154?2:1);}}// ``` *Saved 43 bytes thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236).* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ ~~5~~ 4 bytes, \$ n=1, m=2 \$ -1 thanks to @Kevin Cruijssen ``` .gΘ> ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fL/3cDLv//wE "05AB1E – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~8~~ 6 bytes, \$n=1\$, \$m=2\$ Works because Javascript numbers [don't overflow from positive to negative](https://stackoverflow.com/questions/19054891/does-javascript-handle-integer-overflow-and-underflow-if-yes-how). Essentially J is incremented to infinity, 2 is output only on the case of two repetitions. ``` J°?1:2 // J is a builtin variable that equals -1 at first. J° // If J++ is truthy (-1, 1, 2, etc) ?1:2 // output 1, otherwise 2. ``` [Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=SrA/MToy&input=) [Answer] # [JavaScript (V8)](https://v8.dev/), 40 bytes ``` 0;i=-~this.i,{get x(){print(i-3?1:3)}}.x ``` [Try it online!](https://tio.run/##FY3BCoMwEETvfsUeE6xB8VKaBn/FELftitUQlyAE@@tpPM2DGd7MNtrdBfLcxHt227ozuG1CMDDmVpNpfvyhXdEtvZHhEDL5QCsLavqhe/TyPNWRR8WBvkLq6rUFEEtZzsXQ6hJPA90FdS0hVQATlhqBdGGMdhHXnQro0bKYZXGc@Q8 "JavaScript (V8) – Try It Online") Uses the same trick as [my solution the other day](https://codegolf.stackexchange.com/a/220447/46855). The core idea is putting the `print()` behind a getter function. If the `.x` property is accessed it will print the result. This is placed at the end of the generated code so that it accesses `.x` on the last iteration but when concatenated it becomes `.x0` (does not access `.x`). [Answer] # [JavaScript (Node.js)](https://nodejs.org), 26 bytes, \$n=1\$, \$m=2\$ ``` (x=>x?y=>y?g=z=>z?g:1:2:1) ``` [Try it online!](https://tio.run/##JcxBDsIgEEDRPaeY5UwaibhEgauUIBIMlgawaWs8OzZx9Tcv/2kXW12JcztN@e57ze/iPCgYO65Kr2ZTejNB7UrvJkghL1JQH3kr8YXE2CMXwHh4cYUINxDno8NA8GEALk81J89TDugXm/B/58XP3jaMREjEvqz/AA "JavaScript (Node.js) – Try It Online") Is this valid? I'm not quite sure... --- # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 28 bytes, \$n=1\$, \$m=2\$ ``` f=x=>((f+'').length==54)+1// ``` [Try it online!](https://tio.run/##JcxBDsIgEEDRPaeYXWdCpJLoSvEsJTitKC0EsNEYz45NXP3V@3e72uKyT3VXkr9ynuPy4Hcr8Zkdg4GhjeZlLoij7DpSgZep3ow5Hkjqvm@DqtnPSEKMMQP6TegTeDiD3m@VkuAjAFxcSgysQpyQVxvw/1eZE9uKngiJxLf9AA "JavaScript (SpiderMonkey) – Try It Online") Another similar answer [(requires Firefox 86**-**)](https://bugzilla.mozilla.org/show_bug.cgi?id=1579792) [Answer] # [Julia](http://julialang.org/), 20 bytes, \$n=1\$, \$m=2\$ ``` a=b=1;a+=1;b+=a==3;b ``` [Try it online!](https://tio.run/##yyrNyUw0rPhfrGCroKSk9D/RNsnW0DpRG0gkadsm2toaWyf9B0pEG1ql5qXoGsZycaXlFylkKmTmKRhamXIpgEBBUWZeSU6eRqYmKr84Dl0ktSwxR8M3tSRRryCxqDgVrEITTY0mF9Cm/wA "Julia 1.0 – Try It Online") [Answer] # [PHP](https://php.net/), ~~38~~ 34 bytes \$n=1\$ \$m=2\$ ``` <?=count(file(__FILE__))!=3?:2; // ``` [Try it online!](https://tio.run/##K8go@P/fxt42Ob80r0QjLTMnVSM@3s3TxzU@XlNT0dbY3srImktf//9/AA "PHP – Try It Online") This hacky solution relies on getting the current code's first line and testing the length is 76 (38 \* 2). Works as a standalone but needs the `//` to comment any repetitions of the program so that only one output is displayed. Also in ternary conditions `a?b:c`, if `b` is missing, the value of `a` is used, and in PHP `true` is displayed as `1`. EDIT: saved 4 bytes by counting the lines of code instead of length of the first line. Notice the newline *before* the comment [Answer] # Brainfuck, 268264 characters / 10199 bytes, n=1, m=2 ``` ++>+ Init [->+>+<<]>>[-<<+>>]< Copy second into third [-<<->>]<< Check if equal [ If not equal [-] Reset first +++++++++++++++++++++++++++++++++++++++++++++++++ . ------------------------------------------------- Output 1 >>>-<<< Set a flag saying that this cycle was passed ] >>>+ Change the flag [ If the flag is nonzero (meaning the previous cycle was not passed) [-] Reset the flag ++++++++++++++++++++++++++++++++++++++++++++++++++ . -------------------------------------------------- Output 2 ] <[-]<<[-] Reset first and third ``` [Try it online!](https://fatiherikli.github.io/brainfuck-visualizer/#Kys+KyBJbml0ClstPis+Kzw8XT4+Wy08PCs+Pl08IENvcHkgc2Vjb25kIGludG8gdGhpcmQKWy08PC0+Pl08PCBDaGVjayBpZiBlcXVhbAogICAgWyBJZiBub3QgZXF1YWwKICAgICAgICBbLV0gUmVzZXQgZmlyc3QKICAgICAgICArKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrCiAgICAgICAgLgogICAgICAgIC0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0gT3V0cHV0IDEKICAgICAgICA+Pj4tPDw8IFNldCBhIGZsYWcgc2F5aW5nIHRoYXQgdGhpcyBjeWNsZSB3YXMgcGFzc2VkCiAgICBdCiAgICA+Pj4rIENoYW5nZSB0aGUgZmxhZwogICAgWyBJZiB0aGUgZmxhZyBpcyBub256ZXJvIChtZWFuaW5nIHRoZSBwcmV2aW91cyBjeWNsZSB3YXMgbm90IHBhc3NlZCkKICAgICAgICBbLV0gUmVzZXQgdGhlIGZsYWcKICAgICAgICArKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKwogICAgICAgIC4KICAgICAgICAtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSBPdXRwdXQgMgogICAgXQo8PDwgUmV0dXJuIHRvIGZpcnN0ClstXSBSZXNldCBmaXJzdAo+PlstXTw8IFJlc2V0IHRoaXJkCg==) This can take a while to run, so set the delay to minimum if you want to test it. Definitely not a good golfing language, but it was interesting to write just for the sake of it. (This challenge is impossible to complete in BF as it's stated because repeated code will always produce a multiple-char output, so in this solution the answer is the last output char) Edit: I'm completely brain dead and forgot this is code golf, so I wrote the last lines in a really weird way. Corrected, saved 4 chars. [Answer] # [Grok](https://github.com/AMiller42/Grok-Language), 31 bytes, n=1, m=2 ``` ` j ljq 11z +=1 {k j2`h `lzq ``` Note the single trailing newline. Program was multiplied with `cat odd1out >> odd2out`. At first I thought I would have to rework my solution because of how programs need to be multiplied, but then I realized I could just turn it on its side. ]
[Question] [ You are given a list of at least two positive integers as input. The challenge is to find such a position of a cut that minimizes the absolute difference between the sums of the two parts (to the left and to the right of it). The position should be given as the index of the first element after the cut. This is tagged [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins! ## Test cases These are 0-indexed. ``` [1, 2, 3] -> 2 [3, 2, 1] -> 1 [1, 5, 3, 2, 4] -> 2 or 3 [1, 2, 4, 8, 16] -> 4 [1, 1, 1, 1, 1] -> 2 or 3 [1, 2, 4, 8, 14] -> 4 ``` For example, for the first test case, if the cut is placed before the second element, the sums of the parts will be 1 and 5 and the absolute difference will be 4, and if the cut is placed before the third element, the sums will be equal and the absolute difference will be 0. Therefore, the correct output is 2 (assuming 0-indexing). If multiple correct outputs exist, you must output one of them. ## Explained examples Input: `[1, 2, 3]` ``` Cut at 0: [] vs [1, 2, 3] -> 0 vs 1+2+3=6, difference is 6 Cut at 1: [1] vs [2, 3] -> 1 vs 2+3=5, difference is 4 Cut at 2: [1, 2] vs [3] -> 1+2=3 vs 3, difference is 0 (minimum) Cut at 3: [1, 2, 3] vs [] -> 1+2+3=6 vs 0, difference is 6 ``` Input: `[1, 2, 4, 8, 14]` ``` Cut at 0: [] vs [1, 2, 4, 8, 14] -> 0 vs 1+2+4+8+14=29, difference is 29 Cut at 1: [1] vs [2, 4, 8, 14] -> 1 vs 2+4+8+14=28, difference is 27 Cut at 2: [1, 2] vs [4, 8, 14] -> 1+2=3 vs 4+8+14=26, difference is 23 Cut at 3: [1, 2, 4] vs [8, 14] -> 1+2+4=7 vs 8+14=22, difference is 15 Cut at 4: [1, 2, 4, 8] vs [14] -> 1+2+4+8=15 vs 14, difference is 1 (minimum) Cut at 5: [1, 2, 4, 8, 14] vs [] -> 1+2+4+8+14=29 vs 0, difference is 29 ``` Input: `[1, 1, 1, 1, 1]` ``` Cut at 0: [] vs [1, 1, 1, 1, 1] -> 0 vs 1+1+1+1+1=5, difference is 5 Cut at 1: [1] vs [1, 1, 1, 1] -> 1 vs 1+1+1+1=4, difference is 3 Cut at 2: [1, 1] vs [1, 1, 1] -> 1+1=2 vs 1+1+1=3, difference is 1 (minimum) Cut at 3: [1, 1, 1] vs [1, 1] -> 1+1+1=3 vs 1+1=2, difference is 1 (minimum) Cut at 4: [1, 1, 1, 1] vs [1] -> 1+1+1+1=4 vs 1, difference is 3 Cut at 5: [1, 1, 1, 1, 1] vs [] -> 1+1+1+1+1=5 vs 0, difference is 5 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~50~~ 35 bytes ``` f=lambda a,*l:sum(l)>0and-~f(*l,-a) ``` [Try it online!](https://tio.run/##XZDNCoMwEITveYq9aSSC1h9aQV9EPKTYUCFGMemhiH11u1GIrRAI38zssMn4Ns9BJesqSsn7e8uBs0AW@tX7klYRV234EX4gWcjpah7aaCihJgB1zODCIGmYhWSDeAd0MnQ2KXWSBQZXTOVOO46riaPfHltypKNT/Bj/G8rdUHpqQCfbARe8ITekIUQME9inQae2WxeYGKdOGV94s1UWCCuY8R8s0MWj6xc "Python 3 – Try It Online") ### Explanation *If the sum of elements on the left of `a` is smaller than the sum of elements right of `a`, then the cut must be after `a`* - explanation by [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum). How I arrived here: In each recursive call we compare `abs(sum(x[:i]) - sum(x[i:]))` to `abs(sum(x[:i+1]) - sum(x[i+1:]))`. If the first distance is larger, we continue with the next recursive call, if not the program is stopped: ``` f=lambda x,i=0:abs(sum(x[:i])-sum(x[i:]))>abs(sum(x[:i+1])-sum(x[i+1:]))and f(x,i+1) ``` This can be shortened by modifying the list to make the distance calculation simpler: ``` f=lambda x:abs(sum(x))>abs(sum(x[1:])-x[0])and 1+f(x[1:]+[-x[0]]) ``` Even shorter if we take the input as single arguments: ``` f=lambda a,*l:abs(sum(x)+a)>abs(sum(x)-a)and 1+f(*x,-a) ``` By rearranging the formula ... $$ |(\sum\_{k \in x}k) + a| > |(\sum\_{k \in x}k) - a| \\ \iff ((\sum\_{k \in x}k) + a)^2 > ((\sum\_{k \in x}k) - a)^2 \\ \iff ((\sum\_{k \in x}k) + a)^2 - ((\sum\_{k \in x}k) - a)^2 > 0 \\ \iff 4 \cdot (\sum\_{k \in x}k) \cdot a > 0 \\ \overset{a>0}\iff \sum\_{k \in x}k > 0 $$ ... we arrive at the final solution: ``` f=lambda a,*x:sum(x)>0and-~f(*x,-a) ``` [Answer] # [K4](https://www.kx.com/download/) / [K (oK)](https://github.com/JohnEarnest/ok), ~~22~~ ~~18~~ 14 bytes **Solution:** ``` *&(+\x)>|+\|x: ``` [Try it online!](https://tio.run/##y9bNz/7/X0tNQzumQtOuRjumpsLKUMFIwUTBQsHQ5P9/AA "K (oK) – Try It Online") **Explanation:** Compare cumulative sum against reverse of the reverse cumulative sum. ``` *&(+\x)>|+\|x: / the solution x: / save input as x |x / reverse +\ / cumulative sum | / reverse > / greater than? (+\x) / cumulative sum x & / indices where true * / take first ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 13 bytes ``` t&+gREqY*|&X< ``` The output is 0-indexed. [Try it online!](https://tio.run/##y00syfn/v0RNOz3ItTBSq0Ytwub//2hDBSMFEwULBUOzWAUA) Or [verify all test cases](https://tio.run/##y00syfmf8L9ETTs9yLUwUqtGLcLmv0vI/2hDHQUjHQXjWK5oYzDLEMgCipkCxcB8EwgfxNJRsADKm0EEECgWAA). ### Explanation Consider input `[1 2 4 8 16]` as an example. ``` t % Implicit input. Duplicate % STACK: [1 2 4 8 16], [1 2 4 8 16] &+g % All pair-wise additions, then convert to logical. Gives square matrix of ones % STACK: [1 2 4 8 16], [1 1 1 1 1; 1 1 1 1 1; 1 1 1 1 1; 1 1 1 1 1; 1 1 1 1 1] R % Upper triangular matrix. Sets elements below the diagonal to zero % STACK: [1 2 4 8 16], [1 1 1 1 1; 0 1 1 1 1; 0 0 1 1 1; 0 0 0 1 1; 0 0 0 0 1] Eq % Times 2, minus 1, element-wise % STACK: [1 2 4 8 16], [ 1 1 1 1 1; -1 1 1 1 1; -1 -1 1 1 1; -1 -1 -1 1 1; -1 -1 -1 -1 1] Y* % Matrix multiplication % STACK: [-29 -25 -17 -1 31] | % Absolute value, element-wise % STACK: [29 25 17 1 31] &X< % Index of minimum entry % STACK: 4 % Implicit display ``` [Answer] # [Haskell](https://www.haskell.org/), ~~65~~ 36 bytes ``` (0%) a%(b:c)|a<sum c=1+(a+b)%c a%_=0 ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX8NAVZMrUVUjySpZsybRprg0VyHZ1lBbI1E7SVM1GSgTb2vwPzcxM0/BViE3scA3XkGjoCgzr0RBTyFNk0tBQSFaIdpQx0jHOBbE0VGINgZyDGEcQx1THZCACaqAIbqAMbIAULmOhY6hGUIECsECsf//JaflJKYX/9eNcA4IAAA "Haskell – Try It Online") This answer really just uses one trick. Instead of caluclating $$ \left|a-b\right| $$ and taking the minimum, go until the left hand side is greater than the right hand side. To see why this works we will show that: $$ \left|a-(b+c)\right| < \left|(a+b)-c\right| \implies a > c $$ Here is the proof: $$ \begin{matrix} \left|(a-c)-b \right| < \left|(a-c)+b \right| &\implies \\ a - c > 0 &\implies \\ a > c \end{matrix} $$ [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~14~~ ~~12~~ 11 bytes -1 byte thanks to @isaacg ``` lhoaysNsQ._ ``` [Try it online!](https://tio.run/##K6gsyfj/PycjP7Gy2K84UC/@//9oQx0FIx0FEx0FCx0FQ5NYAA "Pyth – Try It Online") ``` lhoaysNsQ._ ._ All prefixes of input list o Sort, using the following function as the key: a Absolute difference of sN - the sum of the prefix y times 2 sQ - the sum of the input list h First such prefix l Take its length (which gives the index of the element immediately after the prefix) ``` This is based on the following identity: \$ \left|\sum\_{b \in R} b - (\sum\_{q \in Q} q - \sum\_{b \in R} b) \right| = \left|2\sum\_{b \in R} b - \sum\_{q \in Q} q \right|\$ where \$R\$ is the current prefix and \$Q\$ is the input list. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÄḤạSỤḢ ``` A monadic Link accepting a list which yields the first available cut index. **[Try it online!](https://tio.run/##ASQA2/9qZWxsef//w4ThuKThuqFT4buk4bii////WzcsOCw0LDIsMV0 "Jelly – Try It Online")** ### How? ``` ÄḤạSỤḢ - Link: list, X e.g. [ 7, 1, 1, 1, 1, 1, 1, 6] Ä - cumulative sums (X) [ 7, 8, 9, 10, 11, 12, 13, 19] Ḥ - double [14, 16, 18, 20, 22, 24, 26, 38] S - sum (X) 19 ạ - difference (vectorises) [ 5, 3, 1, 1, 3, 5, 7, 19] Ụ - grade [3, 4, 2, 5, 1, 6, 7, 8] Ḣ - head 3 ``` [Answer] # [Python 3](https://docs.python.org/3/), 67 bytes ``` lambda l:min([abs(sum(l)-2*sum(l[:i])),i]for i in range(len(l)))[1] ``` [Try it online!](https://tio.run/##RYzdasQgEEbvfYohV1rMQn5aSiD7ItYLl03aAZ2I2sIS8uypupTCXMx3vjPjH@lro@Fc54/TGne7G7CTQ@LK3CKP345b0fYvdVETaiEk6nULgIAEwdDnwu1C2RJCdfpE57eQID4iY0WzSEsxM7jEdEeaGFgJhiLM4Izny4/JuWiX6C0m3rTXRggGIQtr/svAB6TE12a3B7RX2MMBag/znJ8cuhGn6iT0EgZd2p6pocauxo6V9jW3FY5/zvNklPCezbdKx0r/56n@Ag "Python 3 – Try It Online") Straightforward implementation, can probably be golfed more. Output the 0-indexed cut. [Answer] # [J](http://jsoftware.com/), ~~16~~ 13 bytes -3 bytes thanks to Jonah ``` 1 i.~+/\>+/\. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRUy9eq09WPsgFjvvyaXAldqcka@QpqCoYKRgjGMYwzkGCJkTMECJshKTRQsFAzNECJQ@B8A "J – Try It Online") [Answer] # JavaScript (ES6), ~~64~~ 48 bytes Now very similar to [ovs' answer](https://codegolf.stackexchange.com/a/204215/58563), but we keep track of the left sum in \$s\$ rather than re-injecting the opposite values in the list. ``` f=([v,...a],s=0)=>s<=eval(a.join`+`)&&1+f(a,s+v) ``` [Try it online!](https://tio.run/##bc3RCoIwFMbx@z3FuZKNrdnUoovWi8jAYRrK2AkXe/0lSoTl4bv88T@jjTa00/B8HTzeu5R6TesopJTWiKCPTN/CVXfROmrliINveMOyTPGeWhF4ZKlFH9B10uGD9rRWAgoBpYH1GIM8h4L8qHJRaqsU@W@d5tZiK/NpAU5Qkt23lYDLnD2blVY76rttML0B "JavaScript (Node.js) – Try It Online") NB: `eval(a.join('+'))` is *undefined* if \$a[\:]\$ is empty, so `s<=eval(a.join('+'))` is always *false* in that case. [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` η◄Ṁ≠½Σ¹∫ ``` [Try it online!](https://tio.run/##yygtzv6fq1H8qKmxSPPQtv/ntj@a3vJwZ8OjzgWH9p5bfGjno47V////jzbUMdIxjuWKNgbShkDaUMdUB8Q2AbOBtI6FjqEZmAOFyBImsQA "Husk – Try It Online") ## Explanation ``` η◄Ṁ≠½Σ¹∫ Implicit input, say x = [5,2,2,3,6,2,6] ∫ Prefix sums: p = [5,7,9,12,18,20,26] Σ¹ Sum of x: 26 ½ Halve: 13 Ṁ≠ Absolute differences with elements of p: [8,6,4,1,5,7,13] η◄ 1-based index of minimal element: 4 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 20 [SBCS](https://en.wikipedia.org/wiki/SBCS) bytes ``` (⊃∘⍸((+\⌽)≥(⌽+\))∘⌽) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X@NRV/OjjhmPendoaGjHPOrZq/moc6kGkNaO0dQESQBF/qcpPGqboECMUi6uR31TQYrTFAwVjBSMEVxjINcQWdYULGSCqsFEwULB0AxZDAr/AwA "APL (Dyalog Unicode) – Try It Online") Port of [streetster's answer](https://codegolf.stackexchange.com/a/204219/75323) so be sure to upvote that one as well. This one is 1-indexed and returns the first option available. # [APL (Dyalog Unicode)](https://www.dyalog.com/), 29 [SBCS](https://en.wikipedia.org/wiki/SBCS) bytes ``` {0>+/1↓⍵:0⋄1+∇((-1∘↑),⍨1∘↓)⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9rATlvf8FHb5Ee9W60MHnW3GGo/6mjX0NA1fNQx41HbRE2dR70rIOzJmkA1tf/TFB61TVAgWR8X16O@qSCdaQqGCkYKxgiuMZBriCxrChYyQdVgomChYGiGLAaF/wE "APL (Dyalog Unicode) – Try It Online") This is 0-indexed and returns the second option, when available. Fairly direct port of [ovs's answer](https://codegolf.stackexchange.com/a/204215/75323) so be sure to upvote that answer as well! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` IΣEθ‹Σ…θ⊕κΣ✂θκ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUCjUEfBJ7W4GMx3rkzOSXXOyAeLeuYlF6XmpuaVpKZoZGtqauoogJQE52Qmp4KkQUIgYP3/f3S0oY6CqY6CsY6CkY6CSWzsf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Port of @ovs's solution, except that I include the current element in each sum as the sum of an empty list is `None`. Explanation: ``` θ Input aray E Map over elements κ Current index ⊕ Incremented θ Input array … Sliced to that index Σ Take the sum ‹ Is less than κ Current index θ Input array ✂ Sliced starting at that index Σ Take the sum Σ Take the sum I Cast to string Implicitly print ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~25~~ 24 bytes ``` {(⊢⍳⌊/)|⍵+.×∘.(≤->)⍨⍳⍴⍵} ``` or ``` (|⍳⌊/∘|)∘.(≤->)⍨∘⍳∘⍴+.×⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqjUddix71bn7U06WvWfOod6u23uHpjzpm6Gk86lyia6f5qHcFSLZ3C1CqFqhFwVDBSMGYK03BGEgbcoH4pmC2CRdEzkTBQsHQDMyBQgA "APL (Dyalog Unicode) – Try It Online") Using a variation on [*@LuisMendo*'s method](https://codegolf.stackexchange.com/a/204224/65326). **How?** `⍳⍴⍵` gives the range `1 .. n` where `n` is the array size. `∘.(≤->)⍨⎕` performs an outer product with `x≤y - x>y` (`1` for upper triangular, `-1` for lower) `⍵+.×⎕` matrix-multiplies with the array `|⎕` does absolute value, and `⎕⍳⌊/⎕` searches the minimum index of the result [Answer] # [Racket](https://racket-lang.org/), 71 bytes ``` (define(f a[s 0][n 0])(if(<(apply + a)s)n(f(cdr a)(+(car a)s)(+ n 1)))) ``` [Try it online!](https://tio.run/##bc6xCgIxDAbg3af4wcGULtZTcfBNDofQa6VYQmld7uk1d@ckTSAk@SCksn@F92efWZ6o20BTiEkCRfDYcHyMosVQinQnLiXPsGDTjFAkP1XtyZLnui7JQuCMht5JrWSes0BvHcjhhEFh9w@DguuBwwULnvuogBvcta@/XD75Ag "Racket – Try It Online") 1-indexed [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ḣJ§ạSH$iṂ$ ``` [Try it online!](https://tio.run/##ASsA1P9qZWxsef//4bijSsKn4bqhU0gkaeG5giT///9bMSwgMiwgNCwgOCwgMTZd "Jelly – Try It Online") ### How? ``` ḣJ§ạSH$iṂ$ - Main link (with input l, e.g. l = [1, 2, 4, 8, 16]) iṂ$ - Get the index of the smallest element of ạ - the absolute difference between SH$ - sum of elements in l divided by 2 and ḣJ§ - for n in range(1, len(l)), get sum of the first n elements of l, e.g. [1, 3, 7, 15, 31] ``` [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 8 bytes Port of Zgarb's Husk answer. The index is 0-based. ``` ηOsO;αWk ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3Hb/Yn/rcxvDs///jzbVMQJCYx0zIGkWCwA "05AB1E (legacy) – Try It Online") # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 12 bytes ``` āΣôćs˜OsOα}¬ ``` [Try it online!](https://tio.run/##ASkA1v8wNWFiMWX//8SBzqPDtMSHc8ucT3NPzrF9wqz//1szLCAxLCAyLCAzXQ "05AB1E (legacy) – Try It Online") # Explanation ``` ā Length-range with the input. Σ Sort by this: ô Split input into chunks of current item. ć Head extract, s Put head in the back, ˜ Flatten. OsO Sum head & tail. α} Absolute difference between these parts. ¬ Take the first item of this sorting. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 55 bytes ``` Abs@ReplaceList[#,{x__,y__}:>Plus@x-Plus@y]~Ordering~1& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zGp2CEotSAnMTnVJ7O4JFpZp7oiPl6nMj6@1souIKe02KFCF0xVxtb5F6WkFmXmpdcZqv0PADJKFBzSo6sNdRSMdBSMa2O5EGLGYDFDFDGgOlOgOrCMCboMSExHwQKoxwxdCoFqY///BwA "Wolfram Language (Mathematica) – Try It Online") 24 bytes saved @Kyle Miller 2 byte from my @pronoun is monicareinstate [Answer] # [Red](http://www.red-lang.org), 60 bytes ``` func[a][s: 0 i: 1 while[(s: s + take a)<= sum a][i: i + 1]i] ``` [Try it online!](https://tio.run/##RYzLCsIwEEX3@YpLV4oIxlaRoH6E22EWoU1osC@aFj8/jtbHzObcw@WOrko3VxErb5D83JVkmaLBDsFAq0cdGkcrEREbTPbuYNfnC@LcQorSCeI1B06@H50ta0wuTiAFOdLYI@eFc2HNX3/AKxf87xU4QR9/4vOsmIYxdDLZ9k21rGfba@bfyIz0BA "Red – Try It Online") 1-indexed [Answer] # [Perl 5](https://www.perl.org/) -aple, 39 bytes ``` my$i;@F=map{(++$i)x$_}@F;$_=$F[$#F/2-1] ``` [Try it online!](https://tio.run/##K0gtyjH9/z@3UiXT2sHNNjexoFpDW1slU7NCJb7Wwc1aJd5WxS1aRdlN30jXMPb/f0MFIwVjLmMgachlqGCqAGKZcIFETRQsFAzNgEwo/JdfUJKZn1f8XzexIAcA "Perl 5 – Try It Online") ...or 42 bytes: ``` sub f{my$i;@_=map{(++$i)x$_}@_;$_[@_/2-1]} ``` [Try it online!](https://tio.run/##RYzNCoMwEITvPsVScogYKf6Voih5gd56kxBaiCVQqxgFRXx2u41iQ0hmv5nZVnXvZF3N8IRqrieiMy7z@tHO1POIdkciFy4zIksuz6EfiGUdjIK7Mn2a3ppOQY/S5EWSOVXTUQfwlCGDMmCAXyQE2xjOZWRZcLBoyyWYs058OPGxAdUVO5fD2pf/rxCOO1uvnihRY8uI/rRuzonMdgzk1fR5Rbl1NqoN/VFmG3BCmdoYWkhQ44vaVsAv7HzC7rJ@AQ "Perl 5 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~101~~ 85 bytes ``` f x=snd$minimum$(`zip`[0..])$(\(a,b)->abs$sum a-sum b).(`splitAt`x)<$>[0..length x-1] ``` [Try it online!](https://tio.run/##Xc9NCsIwEAXgvaeYRRYJpMVYFRe2IK57gjbYlFYN5qckKRQvX1N1ozMwi48Hj7kL/@iVmqUerAtwtiY4q9LSGtEBvlpXXsh8hSn3pkNaGqlHjXDzlENTrdOUE4RrLGhLkkK0HvlRg0iW25IUN35QMpxCM5EjKpa86s0t3GFKGJ@1kAZy6OwK4F0EVcXohmacRvlOlUVhP8Loji66/dMo9EDZ/o@/yzkgqCcPSfGpBBicNCFqfM9HcH0YnQFM5hc "Haskell – Try It Online") Less golfed: ``` minIndex f=snd.minimum.(`zip`[0..]).map f f x = minIndex inner [0..length x-1] where inner = (\(a, b)->abs$ sum a - sum b) . (`splitAt` x) ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~58~~ 49 bytes Uses a variable declaration via `is` to avoid declaring a proper body and having to type the excessively long word `return`. For some reason List has the method `FindIndex`, but other `IEnumerable`s don't seem to. ``` a=>0is var s?a.FindIndex(e=>(s+=e)>a.Sum()-s+e):0 ``` [Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpds45NZXGKTmVdip6MAIhXcFGz/J9raGWQWK5QlFikU2yfquWXmpXjmpaRWaKTa2mkUa9umatol6gWX5mpo6hZrp2paGfy35uIKKALq13DTyEstj46tNtRRMNJRMK7VC8kH2aChqalpjabEGKzEEJ8SoCmmQFPACk0IKAQp0VGwAJpoRkAlAhFtJPGWm6Oo/A8A "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 112 bytes ``` l;r;f(int n,char**m){char*i=*(m+1),*j=i;while(*j++);for(j-=2,r=l=0;i<=j;)l<r?l+=*i++:(r+=*j--);return i-*(m+1);} ``` [Try it online!](https://tio.run/##JY7LDoIwFET3fEWjMenTCO68VH@EDRaQ25RirhBJjN9eUXcnk8mZcebmXEoBCDqOcWJRu74mKQfx@gFayQeVCy29RXj2GFouvVICupG4N7bQZIM9AJbWgwglXYKyEpU6cVrBGyOA2mmmyND8XfBOW4wuzE3LysfU4Ljvz9lQY/xdqDX7TjMpr@KVMXanNe34ZtdUcaNZx9fCVQjI3ilVS14tRbUcPw "C (gcc) – Try It Online") Unfortunately I did not figure out how to input hex characters as arguments into the program with the online view. Basically the input consists of a single "argument" which is the array of numbers. [Answer] # [Desmos](https://desmos.com/calculator), ~~69~~ 66 bytes ``` f(l)=L[∑_{n=1}^Ll[n]>=∑_{k=L}^{L.max}l[k]][1] L=[1...l.length] ``` Returns 1-based indices. Uses the same strategy as ovs's [Python answer](https://codegolf.stackexchange.com/a/204215/96039) [Try It On Desmos!](https://www.desmos.com/calculator/f3rgr4ssrl) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/lcdrfv9u9a) [Answer] # Scala, 117 bytes ``` def g(l:List[Int],s:Int,i:Int):Int={val h::t=l;if(t==Nil)i else if(s+h>t.sum)if(s<l.sum)i+1 else i else g(t,s+h,i+1)} ``` [Answer] This question deserved a lengthy suboptimal PHP answer, that has to cope with the fact that the arguments array starts with the script name, forcing me to add the `$i>1` test that leads to extra brackets, and such oddities.. # [PHP](https://php.net/), 124 bytes ``` $f=array_sum;$g=array_slice;for($a=$argv;$a[++$i];$s=$r)if(($s<$r=abs($f($g($a,$i))-$f($g($a,0,$i))))&$i>1)break;echo($i-2); ``` [Try it online!](https://tio.run/##PcpRCsIwEEXRzTwkQy2Y0g8hTV2IiExLkgaVhgkKrn4sgv5cOHDLUnQ4la2InkX4fa3Ph0P64Z7n4OIqBuzBkl4OfG4a5ItD9RDK0RjUAeJ5qgbRIG3vHpmo/evwNdEOebQ0SeCbC/OyGuS2I6eqVjvt9ai2/wA "PHP – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 84 bytes ``` a->{int i=0,j=a.length-1,l=0,r=0,t;for(;i<j;)t=l<r?l+=a[i++]:(r+=a[j--]);return-~i;} ``` [Try it online!](https://tio.run/##bZAxa8MwEIX3/IojYLAbWTRthhLFKVkKHTqlW/BwTWxXriwZ6RwIwf3rrmynLaQFHdK9d@J7XIlHjMvDRyer2liC0ve8Ian4jZj80fJG70ka/a/pyGZY9dZeoXPwglLDeQJQN29K7sERkr@ORh6g8l64JSt1sUsBbeGiYRTg1TxrerpwVlLTLl1DnnQYr8@@A5ncsjJBrjJd0Hs8Z8oL1heJ3NhQyFUpIkrUyj6qWYI7OZuly9D2zzKO00jYjBqr408p2k4MyAHiY1DmyEFyCQJwhjmDOwb30LIracHggcF8ceX8nm@jHRF9tCPaAbEcQdEPZ3tylFXcNMRrvxHKw2nglhAcAj1lsLEWT46TGdcV9p8jBjnHulanjfPrGrVoRLWTvtruCw "Java (JDK) – Try It Online") ## Credits * -1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) ]
[Question] [ [Inspiration](https://codegolf.stackexchange.com/q/59299/43319). ### Task Reverse runs of odd numbers in a given list of 2 to 215 non-negative integers. ### Examples `0 1` → `0 1` `1 3` → `3 1` `1 2 3` → `1 2 3` `1 3 2` → `3 1 2` `10 7 9 6 8 9` → `10 9 7 6 8 9` `23 12 32 23 25 27` → `23 12 32 27 25 23` `123 123 345 0 1 9` → `345 123 123 0 9 1` [Answer] # Python 2, ~~75~~ ~~68~~ 63 bytes 5 bytes thanks to Dennis. And I have [outgolfed Dennis](https://codegolf.stackexchange.com/a/84352/48934). Credits to [Byeonggon Lee](https://codegolf.stackexchange.com/a/84350/48934) for the core of the algorithm. ``` o=t=[] for i in input():o+=~i%2*(t+[i]);t=i%2*([i]+t) print o+t ``` [Ideone it!](http://ideone.com/YOj0Hk) Old version: [75 bytes](http://ideone.com/6POOe6) [Answer] # APL, ~~21~~ 20 bytes ``` {∊⌽¨⍵⊂⍨e⍲¯1↓0,e←2|⍵} ``` [Try it](http://tryapl.org/?a=%7B%u220A%u233D%A8%u2375%u2282%u2368e%u2372%AF1%u21930%2Ce%u21902%7C%u2375%7D2%201%203%205%202%204%206%207%205%201&run) || [All test cases](http://tryapl.org/?a=%u236A%20%7B%u220A%u233D%A8%u2375%u2282%u2368e%u2372%AF1%u21930%2Ce%u21902%7C%u2375%7D%A8%280%201%29%281%203%29%281%202%203%29%281%203%202%29%2810%207%209%206%208%209%29%2823%2012%2032%2023%2025%2027%29%28123%20123%20345%200%201%209%29&run) Explanation: ``` 2|⍵ Select all the odd numbers e← Save that to e 0, Append a 0 ¯1↓ Delete the last element e⍲ NAND it with the original list of odd numbers ⍵⊂⍨ Partition the list: (even)(even)(odd odd odd)(even) ⌽¨ Reverse each partition ∊ Flatten the list ``` *Edit: Saved a `~` thanks to De Morgan's laws* [Answer] # Haskell, ~~46~~ 44 bytes ``` h%p|(l,r)<-span(odd.(h*))p=l++h:r foldr(%)[] ``` Thanks to @xnor for recognizing a fold and saving two bytes. [Answer] # Python 2, ~~79~~ ~~75~~ 73 bytes ``` def f(x): i=j=0 for n in x+[0]: if~n%2:x[i:j]=x[i:j][::-1];i=j+1 j+=1 ``` This is a function that modifies its argument in place. Second indentation level is a tabulator. Test it on [Ideone](http://ideone.com/wsu6KO). [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḃ¬ðœpUżx@F ``` [Try it online!](http://jelly.tryitonline.net/#code=4biCwqzDsMWTcFXFvHhARg&input=&args=WzEyMywgMTIzLCAzNDUsIDAsIDEsIDld) or [verify all test cases](http://jelly.tryitonline.net/#code=4biCwqzDsMWTcFXFvHhARgrDh-KCrEc&input=&args=WzAsIDFdLCBbMSwgM10sIFsxLCAyLCAzXSwgWzEsIDMsIDJdLCBbMTAsIDcsIDksIDYsIDgsIDldLCBbMjMsIDEyLCAzMiwgMjMsIDI1LCAyN10sIFsxMjMsIDEyMywgMzQ1LCAwLCAxLCA5XQ). ### How it works ``` Ḃ¬ðœpUżx@F Main link. Argument: A (array) Ḃ Bit; return the parity bit of each integer in A. ¬ Logical NOT; turn even integers into 1's, odds into 0's. ð Begin a new, dyadic link. Left argument: B (array of Booleans). Right argument: A œp Partition; split A at 1's in B. U Upend; reverse each resulting chunk of odd numbers. x@ Repeat (swapped); keep only numbers in A that correspond to a 1 in B. ż Zipwith; interleave the reversed runs of odd integers (result to the left) and the flat array of even integers (result to the right). F Flatten the resulting array of pairs. ``` [Answer] # Python 2, 78 75 bytes ``` def r(l): def k(n):o=~n%2<<99;k.i+=o*2-1;return k.i-o k.i=0;l.sort(key=k) ``` Super hacky :) [Answer] ## Python3, 96 bytes Saved a lot of bytes thanks to Leaky Nun! ``` o=l=[] for c in input().split(): if int(c)%2:l=[c]+l else:o+=l+[c];l=[] print(" ".join(o+l)) ``` [Answer] # C, 107 bytes ``` i;b[65536];f(){for(;i;)printf("%d ",b[--i]);}main(n){for(;~scanf("%d",&n);)n%2||f(),b[i++]=n,n%2||f();f();} ``` [Answer] # Pyth, 14 bytes ``` s_McQshMBx0%R2 %R2Q Take all elements of the input list modulo 2 x0 Get the indices of all 0s hMB Make a list of these indices and a list of these indices plus 1 s Concatenate them cQ Chop the input list at all those positions _M Reverse all resulting sublists s Concatenate them ``` [Test cases](https://pyth.herokuapp.com/?code=s_McQshMBx0%25R2&input=%5B10%2C7%2C9%2C6%2C8%2C9%5D&test_suite=1&test_suite_input=%5B0%2C1%5D%0A%5B1%2C3%5D%0A%5B1%2C2%2C3%5D%0A%5B1%2C3%2C2%5D%0A%5B10%2C7%2C9%2C6%2C8%2C9%5D%0A%5B23%2C12%2C32%2C23%2C25%2C27%5D%0A%5B123%2C123%2C345%2C0%2C1%2C9%5D) [Answer] # [MATL](https://github.com/lmendo/MATL), 20 bytes ``` TiodgvYsG8XQ!"@gto?P ``` Input is a column array, using `;` as separator. [**Try it online!**](http://matl.tryitonline.net/#code=VGlvZGd2WXNHOFhRISJAZ3RvP1A&input=WzEyMzsxMjM7MzQ1OzA7MTs5XQ) ### Explanation Consider as an example the input array `[1;2;3;5;7;4;6;7;9]`. The first part of the code, `Tiodgv`, converts this array into `[1;1;1;0;0;1;0;1;0]`, where `1` indicates a *change of parity*. (Specifically, the code obtains the parity of each entry of the input array, computes consecutive differences, converts nonzero values to `1`, and prepends a `1`.) Then `Ys` computes the *cumulative sum*, giving `[1;2;3;3;3;4;4;5;5]`. Each of these numbers will be used as a *label*, based on which the elements of the input will be *grouped*. This is done by `G8XQ!`, which splits the input array into a cell array containing the groups. In this case it gives `{[1] [2] [3;5;7] [4;6] [7;9]}`. The rest of the code *iterates* (`"`) on the cell array. Each constituent numeric array is pushed with `@g`. `to` makes a copy and *computes its parity*. If (`?`) the result is truthy, i.e. the array contents are odd, the array is *flipped* (`P`). The stack is *implicitly displayed* at the end. Each numeric vertical array is displayed, giving a list of numbers separated by newlines. [Answer] # [Desmos](https://desmos.com/calculator), 167 bytes ``` k=mod(l,2) K=l.length a=[K...1] L=a[k[a]=1] g(q)=∑_{n=1}^{[1...q.length]}q[n] A=g(join(1,sign(L-L[2...]-1))) f(l)=l[\{k>0:\sort(L,A.\max+1-A)[g(k)],k\}+[1...K](1-k)] ``` Hooooly crap, this was pretty challenging to do in Desmos given its limited list functionalities, but after lots of puzzling and scratched ideas, I finally managed to pull together something that actually works. [Try It On Desmos!](https://www.desmos.com/calculator/lcifzpsj5w) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/ouholqommb) [Answer] # [Desmos](https://desmos.com/calculator), ~~94~~ 93 bytes ``` g(M,j)=j-max([1...j]0^{mod(M,2)}) f(L)=L[[i+g(L[n...1],n+1-i)-g(L,i)fori=[1...n]]] n=L.length ``` [Try it on Desmos!](https://www.desmos.com/calculator/qhrwpidzr0) \*-1 byte thanks to [@AidenChow](https://codegolf.stackexchange.com/users/96039/aiden-chow) (remove space after `for`) ## How it works `g(M,j)` gives the difference between `j` and the greatest index less than (or equal to) `j` of an even entry in `M`. For example, `g([0,2,4,1,3,5,7,6,8],6) = 3` because the 6th element in the list is 5, and the last even entry before it is 4, which is 3 elements earlier. `f(L)` is the solution to the challenge. It's of the form `L[[h(i)for i=[1...n]]]`, which is a list indexing: `h(i)` gives the index of the value in `L` that should be at index `i` in the result list. The main difficulty lies in `h(i)`, defined as `h(i) = i+g(L[n...1],n+1-i)-g(L,i)`. Note that `g(M,j) = 0` whenever `M[j]` is even, so `h(i)=i` if `L[i]` is even (this corresponds to even entries not moving) since `L[n...1][n+1-i]=L[i]=even` If `L[i]` is odd then we have a more complicated story: `g(L,i)` gives the distance to the element before the start of the odd run, and `g(L[n...1],n+1-i)` gives the distance to the element after the end of the odd run. Then `g(L[n...1],n+1-i)-g(L,i)` says how much closer the element is to the end of the run than the start of the run. For example, for `L=[0,2,4,1,3,5,7,6,8]` and `i=6`, this difference is `-1`, so `L[6]` has to move 1 element to the left, to where the `3` is currently. In general regarding the difference `g(L[n...1],n+1-i)-g(L,i)`: * if the difference is positive, then the element is closer to the left than the right, and it needs to move right by the value of the difference * if the difference is negative, then the element is closer to the right than the left, and it needs to move left by the negative of the difference * if the difference is zero, then the element is at the center of an odd-length run, so it doesn't need to move at all. [Answer] # Clojure, 86 bytes ``` #(flatten(reduce(fn[a b](if(odd? b)(conj(pop a)(conj[b](last a)))(conj a b[])))[[]]%)) ``` Here is the ungolfed version ``` #(flatten ; removes all empty vectors and flattens odd sequences (reduce (fn[a b] (if(odd? b) ; if we encounter odd number in the seq (conj(pop a)(conj[b](last a))) ; return all elements but last and the element we encountered plus the last element of current result (conj a b[])) ; else just add the even number and the empty vector ) [[]] ; starting vector, we need to have vector inside of vector if the sequence starts with odd number % ; anonymous function arg ) ) ``` Basically it goes through the input sequence and if it encounters even number it adds the number and the empty vector otherwise if it's an odd number it replaces the last element with this number plus what was in the last element. For example for this seq `2 4 6 1 3 7 2` it goes like this: * `[]<=2` * `[2 []]<=4` * `[2 [] 4 []]<=6` * `[2 [] 4 [] 6 []]<=1` * `[2 [] 4 [] 6 [1 []]]<=3` * `[2 [] 4 [] 6 [3 [1 []]]]<=7` * `[2 [] 4 [] 6 [7 [3 [1 []]]]]<=2` * `[2 [] 4 [] 6 [7 [3 [1 []]]] 2 []]` And then flattening this vector gives the correct output. You can see it online here: <https://ideone.com/d2LLEC> [Answer] # [J](http://jsoftware.com), ~~33~~ ~~31~~ 30 bytes ``` [:;]<@(A.~2-@|{.);.1~1,2|2-/\] ``` ## Usage ``` f =: [:;]<@(A.~2-@|{.);.1~1,2|2-/\] f 0 1 0 1 f 1 3 3 1 f 1 2 3 1 2 3 f 1 3 2 3 1 2 f 10 7 9 6 8 9 10 9 7 6 8 9 f 23 12 32 23 25 27 23 12 32 27 25 23 f 123 123 345 0 1 9 345 123 123 0 9 1 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` ṁ↔ġ¤&%2 ``` [Try it online!](https://tio.run/##yygtzv7//@HOxkdtU44sPLRETdXo////0YYGOuY6ljpmOhZA0hTINtYxNIgFAA "Husk – Try It Online") ## Explanation ``` ṁ↔ġ¤&%2 Implicit input, a list of integers. ġ Group by equality predicate: ¤ %2 Arguments modulo 2 & are both truthy. ṁ Map and concatenate ↔ reversing. ``` [Answer] # C#, ~~179~~ ~~178~~ 177 bytes ``` s=>{var o=new List<int>();var l=new Stack<int>();foreach(var n in s.Split(' ').Select(int.Parse)){if(n%2>0)l.Push(n);else{o.AddRange(l);o.Add(n);l.Clear();}}return o.Concat(l);} ``` I use a C# lambda. You can try it on [.NETFiddle](https://dotnetfiddle.net/rCdWDK). The code less minify: ``` s => { var o=new List<int>();var l=new Stack<int>(); foreach (var n in s.Split(' ').Select(int.Parse)) { if (n%2>0) l.Push(n); else { o.AddRange(l); o.Add(n); l.Clear(); } } return o.Concat(l); }; ``` Kudos to [Byeonggon Lee](https://codegolf.stackexchange.com/a/84350/15214) for the original algorithm. [Answer] # JavaScript (ES6) ~~70~~ 66 bytes **Edit** 4 bytes saved thx @Neil ``` a=>[...a,[]].map(x=>x&1?o=[x,...o]:r=r.concat(o,x,o=[]),r=o=[])&&r ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 51 bytes ``` ->l{l.chunk(&:odd?).flat_map{|i,j|i ?j.reverse: j}} ``` [Try it online!](https://tio.run/##jZHdToNAEIXv9ynGmIAmK2mhipJgX8I7JIbCCrviQvhpNKXPjrMslBJ7UZKFyTfnnBmgane/feq/9w@v@SG34qyVX3eGVyTJ9t76zKPm4zsqDx2nouOwFVbF9qyqmQfieOxv4S1jsI8qHjW8kDXxdyzlklyRZRinrK7DrCs8N2oB72T750EsLy698PhMJoQEBCAIVhTWIQX9DOnA1hQcxZwls0c8lWdqJJNBlVMHQ10KLxSeKDxjMbhXA3FnOKpt5VbBeFRtP@JxlWXRccfOPF@38eZssIHxagk9bCCzQI/GdyKhxaI4g6QA/EQgOkwqKy4bMLks28YDvEwF26YGbomCSzA10bK00KIzWRrw8IKS/ZQsbljizUqxkCEh@Ef6Pw "Ruby – Try It Online") Some slight variations: ``` ->l{l.chunk(&:odd?).flat_map{|i,j|i&&j.reverse||j}} ->l{l.chunk(&:odd?).flat_map{|i,j|!i ?j:j.reverse}} ->l{l.chunk(&:even?).flat_map{|i,j|i ?j:j.reverse}} ``` ### Ruby 2.7, 48 bytes ``` ->l{l.chunk{_1%2}.flat_map{_1>0?_2.reverse: _2}} ``` Unsupported by TIO :( [Answer] # Pyth, ~~29~~ 28 bytes ``` JYVQ=+J*%hN2+YN=Y*%N2+NY;+JY ``` [Test suite.](http://pyth.herokuapp.com/?code=JYVQ%3D%2BJ%2a%25hN2%2BYN%3DY%2a%25N2%2BNY%3B%2BJY&test_suite=1&test_suite_input=%5B0%2C1%5D%0A%5B1%2C3%5D%0A%5B1%2C2%2C3%5D%0A%5B1%2C3%2C2%5D%0A%5B10%2C7%2C9%2C6%2C8%2C9%5D%0A%5B23%2C12%2C32%2C23%2C25%2C27%5D%0A%5B123%2C123%2C345%2C0%2C1%2C9%5D&debug=0) Direct translation of [my python answer](https://codegolf.stackexchange.com/a/84353/48934) (when has translating from python to pyth become a good idea?) [Answer] # TSQL 118 bytes ``` DECLARE @ TABLE(i int identity, v int) INSERT @ values(123),(123),(345),(0),(1),(9) SELECT v FROM(SELECT sum((v+1)%2)over(order by i)x,*FROM @)z ORDER BY x,IIF(v%2=1,max(i)over(partition by x),i),i desc ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/507955/reverse-odd-sequences)** [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~15~~ 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437 ``` Çⁿ╜"}☻≥º╚( ``` [Try it online!](https://staxlang.xyz/#c=%C3%87%E2%81%BF%E2%95%9C%22%7D%E2%98%BB%E2%89%A5%C2%BA%E2%95%9A%28&i=%5B0%2C1%5D%0A%5B1%2C3%5D%0A%5B1%2C2%2C3%5D%0A%5B1%2C3%2C2%5D%0A%5B10%2C7%2C9%2C6%2C8%2C9%5D%0A%5B23%2C12%2C32%2C23%2C25%2C27%5D%0A%5B123%2C123%2C345%2C0%2C1%2C9%5D&a=1&m=2) **Tied Jelly!** So sad that packing only saved one byte. Unpacked version with 11 bytes: ``` {|e_^*}/Frm ``` ## Explanation `{|e_^*}` is a block that maps all even numbers `n` to `n+1`, and all odd numbers `n` to `0`. ``` {|e_^*}/Frm { }/ Group array by same value from block |e 1 if the element is even, 0 if odd. _^ Get another copy of the current element and increment by 1 * Multiply them F For each group execute the rest of the program r Reverse the group m Print elements from the group, one element per line. ``` [Answer] ## [Perl 5](https://www.perl.org/) with `-p`, 42 bytes ``` map{$_%2?$\=$_.$\:print$\.$_,$\=""}$_,<>}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saBaJV7VyF4lxlYlXk8lxqqgKDOvRCVGTyVeByimpFQLZNjY1Vb//29oZMwFwsYmplwGXIZcllz/8gtKMvPziv/rFgAA "Perl 5 – Try It Online") [Answer] # [J](http://jsoftware.com/), 27 bytes ``` [:;]<@(|.^:{.);.1~1,2|2-/\] ``` [Try it online!](https://tio.run/##RY6xDsIwDET3fMWJpVRqQ@NQ0qQgISExMbFCGTvwC1T99WAnijrY8rvzWf7GnUY14xJQNegQuFqN2/Nxj68wTufrftGf8NP1qM1qGlqoPbynWEcAMy8bJZXAwCq7ATHmXlyQ@Nyz0MHB44QBXjF4xgzJJl7lMMlAPcipTXFJKYeTbmGPvfzDeZmKKnfNHw "J – Try It Online") A minor improvement over [miles' J answer](https://codegolf.stackexchange.com/a/84357/78410). ### How it works ``` [:;]<@(|.^:{.);.1~1,2|2-/\] NB. Input: an integer vector V 1,2|2-/\] NB. Pairwise difference modulo 2 and prepend 1 NB. giving starting positions for same-parity runs ] ;.1~ NB. Cut V at ones of ^ as the starting point and (|.^:{.) NB. reverse each chunk (head of the chunk) times NB. (effectively, reverse odd chunks only) <@ NB. and enclose it [:; NB. Finally, flatten the result ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 53 bytes ``` a=>a.map((c,k)=>o.splice(n=c&1?+n:k+1,0,c),o=n=[])&&o ``` [Try it online!](https://tio.run/##DcY7DsIwDADQq2SKbNVEzcJPctl6iapDZCJUGuyIIK4feNN7pm9q8t7q56B2z33mnnhK4ZUqgNCOPFlotWySQVl8vA163YdIIwmSsfKyovfWxbRZyaHYA2ZY4kjuRO5C7kju/M@K2H8 "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 54 bytes ``` a=>a.map((c,k)=>o.splice(n=c&1?n:k+1,0,c),o=[],n=0)&&o ``` [Try it online!](https://tio.run/##DcY7DsMgDADQqzAho7oIlv4kp1suEWVALqrSUBuFKtcnfdP7pD013pb6O4u@ch@pJxqS/6YKwLg6GtS3WhbOIMQ2PuWxniIGZIdK04xCwVmrnVWaluyLvmGEKQY0VzR3NBc0t39m5/oB "JavaScript (Node.js) – Try It Online") [Answer] # [R](https://www.r-project.org/), 69 bytes ``` v=scan();ifelse(o<-v%%2,v[rep(2*cumsum(r<-rle(o)$l)-r+1,r)-seq(v)],v) ``` [Try it online!](https://tio.run/##Dck7CoAwDADQPeewkGg7GBEH60nEQaSCUH8p5vq124MnOeuUtvVCGo89xBTw9k6NYauzhAe53r4zfSeKdxLLUhXJSdNaIZfCi0qLVcrcQcvQMRRwDzxA/gE "R – Try It Online") Ungolfed, commented version: ``` o=v%%2 # get the odd numbers in the list r=rle(o)$l # find the run lengths of odd/even numbers # reverse the indices of all the runs: e=cumsum(r) # the indices of the ends of each run ie=rep(e,r) # for each index in v, the index of the end of its run is=rep(e-r+1,r) # for each index in v, the index of the start of its run irev=is+(ie-seq(v)) # reverses all runs # the above 4 steps can be combined as: irev=rep(2*cumsum(r)-r+1,r)-seq(v) # so: use the reversed indices for odd numbers, and leave the even numbers unchanged ifelse(o,v[irev],v) ``` [Answer] # [Clojure](https://clojure.org/), 66 bytes ``` #(mapcat(fn[x](if(some odd? x)(reverse x)x))(partition-by odd? %)) ``` [Try it online!](https://tio.run/##TY9NDoIwEIX3PcVLjMl0YQJFReLCgzQsUNoEoxQLGtyZeFMvggMEcdHk/Xyddk4Xd75701FuLGy3oGtWnbKGbKnblApLtbsauDw/oJXkzcP42rBspaQq803RFK5cHZ8jspSyk4JyV5sbdAstdIAw/bzeez4shQ4RTT4avZqTwQwM1B8FxVmAGAm22CH54QEn8ZgJrZjk6wos1AYqnrC5iIeif2HIIkTrDfhb88g@mMp@eijSFFT5omwuJcjy6rzjFw "Clojure – Try It Online") [Answer] # [Factor](https://factorcode.org) + `grouping.extras`, 62 bytes ``` [ [ odd? ] group-by [ last2 swap [ reverse ] when ] map-flat ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZHBTgIxEIbjdZ_i5wF2A11xQRM9Gi9ejCfCoS6z0Fi2tZ0VCeHuO3jhgu-kT2N3FwgE59CZ-f-vM2n69V3InI3b_F58Pj89PN5fQ3pvco-55BmmzlRWldOEPthJD09vFZU5ebySK0nDOmJeWqdKRm7mVmlyScVKK1aBOkjsiBLrjJVTycqUSS61jqkoKGfcRNEqQogVuuhhjdPo1OrO7yH9x0-PfHFGdFr1aII4I9Ka2RNdZBjiCoNwrg8zuqHLWnUHinArDBZ1IfoQWaA7R2rWqIfFjZEivew3zxw2dN3tnXpDL1pvKy7iwc_tCCOYyeQO4_Yf4pdlULT0LOAX0obG0Ts5T4FYzKgMaS5tXGjJGLdTtkFA0tabTZv_AA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .γÈN>*}í˜ ``` [Try it online](https://tio.run/##yy9OTMpM/f9f79zmwx1@dlq1h9eenvP/f7ShkbEOCBubmOoY6BjpGOpYxgIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/vXObD3f42WnVHl57es5/nf/R0QY6hrE60YY6xmDSCEob6xiBaAMdcx1LHTMdCx1LINfIWMcQqMBIB8gwMtUxMgcpAQsa6xibmOoAjQKqiwUA). **Explanation:** ``` .γ } # Adjacent group the (implicit) input-list by: È # Check if the value is even (1 if even; 0 if odd) N>* # Multiply it by the 1-based index # (adjacent odd values will be grouped together, and every even # value is in its own separated group) í # After the adjacent group-by: reverse each inner list ˜ # Flatten the list of lists # (after which the result is output implicitly) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` λ&›₂¥*;ḊRf ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBUCIsIiIsIs67JuKAuuKCgsKlKjvhuIpSZiIsIiIsIlswLDFdXG5bMSwzXVxuWzEsMiwzXVxuWzEsMywyXVxuWzEwLDcsOSw2LDgsOV1cblsyMywxMiwzMiwyMywyNSwyN11cblsxMjMsMTIzLDM0NSwwLDEsOV0iXQ==) Port of 05AB1E. Another 10-byter that I produced independently: `⁽₂Ḋƛh∷ßṘ;f` ]
[Question] [ It's very simple: Your program or function should generate the following text: ``` Elizabeth obnoxiously quoted (just too rowdy for my peace): "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG," giving me a look. ``` ## Fine print You may write a [program or function](https://codegolf.meta.stackexchange.com/a/2422/17249), which [returns the output as a string or printing it to STDOUT (or closest alternative).](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) You may optionally include a single trailing newline in the output. ## Scoring **The number of bytes in your code** multiplied by **the number of unique bytes in your code** Lowest score wins. For example, a brainfuck or a whitespace answer would have a huge advantage here, as the multiplier would be very low (8 and 3 respectively). However, generally, writing programs in those languages produces much longer code which may negate that advantage. [Standard loopholes which are no longer funny](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) are **banned**. [Answer] # CJam, ~~266~~ ~~281~~ 456 bytes \* ~~14~~ ~~12~~ 7 unique = ~~3724~~ ~~3372~~ 3192 [Try it online.](http://cjam.aditsu.net/#code=14301201124204202034420112034224204431020210101232301021240204310431312122132100240400222324402030223103420431324402222132223233141443401210314023001122320404112224314302132421403301243334313000011124244441400003310332301330220022110121411122100040310110020040121444302100143202204330334033211334242120304123121024200421121232100303121022431044444423243331440434010014400~~10~~100~~1~43c~c~4~~41c~100~~1~43c~c~123~~100~~1~43c~c~44~~14~~43c~c100~~40c~c43c~~) ``` 14301201124204202034420112034224204431020210101232301021240204310431312122132100240400222324402030223103420431324402222132223233141443401210314023001122320404112224314302132421403301243334313000011124244441400003310332301330220022110121411122100040310110020040121444302100143202204330334033211334242120304123121024200421121232100303121022431044444423243331440434010014400~~10~~100~~1~43c~c~4~~41c~100~~1~43c~c~123~~100~~1~43c~c~44~~14~~43c~c100~~40c~c43c~~ ``` ### Explanation The strategy I've used is to treat each character in the string as a base-123 digit and encode that as a decimal number in the program. The program then converts that number back to base 123 and maps each base-123 digit back to a character. Because it's hard to explain why the program is in its current state, I'll explain each version of it. Here's what the end of the program looked like in the first version: ``` ...2068438725 123b:c ``` This implements the strategy in the most straightforward way possible. The number, encoded normally in base 10, is converted back to base 123 and each base-123 digit is mapped back to a character. But this uses 4 unique non-digit characters, and being able to get rid of any one of them would likely be worth the size hit due to having to use less straightforward code. First, I realized that I could get rid of the `b` and the `:` operators by creating them at runtime as their ASCII character values converted back to a character (with the already present `c` operator) and evaluating them with the `~` operator. It turned out to be a little tricky to do this with the `:` operator, since it has to be parsed together with the following `c` operator. I solved this by producing the characters `:` and `c` and then producing and evaluating the character `+`, which concatenates the former two characters into the string `:c` which can then be evaluated properly. Second, I realized that the `~` operator I just introduced had a handy new overloaded variant: when given a number, it produces the bitwise complement. By using this twice in a row after a number, I could introduce a token break in the source with no resultant computational effect, allowing me to replace the spaces used to separate numbers with `~~`. The final result is 15 more bytes of code at the end, but this cost is greatly outweighed by the benefit of eliminating 2 unique characters out of 14. Here's a comparison of the end of the first version with the end of the second version: ``` ...2068438725 123[ b ][ :c ] ...2068438725~~123~~98c~58c99c43c~~ ``` Using any fewer than the 2 operators I was using would be impossible, but I still wanted fewer unique characters. So the next step was to eliminate digits. By changing the number's encoding so that each decimal digit was really a base-5 digit, I could potentially eliminate the digits 6-9. Before eliminating anything from the end of the prgoram, it looked like this: ``` ...4010014400 10b5b123b:c ``` As mentioned before, eliminating the space is easy. But the `b`, `:`, and `c` would not be so easy, as their character codes are `98`, `58`, and `99`, respectively. These all contained digits marked for elimination, so I had to find ways to derive them all. And the only useful numeric operators with character values not containing 5-9 were decrement, increment, multiply, and add. For `98`, I initially used `100~~40c~40c~`, which decrements `100` twice. But then I realized I could make yet another use of the `~` operator, as bitwise complement lets me get negative numbers which, when added, let me emulate subtraction. So I then used `100~~1~43c~`, which adds `100` and `-2` and is 2 bytes smaller. For `58`, I used `44~~14~~43c~`, which adds `44` and `14`. And for `99`, I used `100~~40c~`, which decrements `100`. The final result is pretty big and obfuscated, but the cost of the significantly larger number and processing code were slightly outweighed by the big benefit of eliminating 5 unique characters out of 12. Here's a comparison of the final end of the program before eliminations and after eliminations: ``` ...4010014400 10[ b ][ 5 ][ b ]123[ b ][ :c ] ...4010014400~~10~~100~~1~43c~c~4~~41c~100~~1~43c~c~123~~100~~1~43c~c~44~~14~~43c~c100~~40c~c43c~~ ``` [Answer] # Whitespace, 1157 937 bytes \* 3 unique = 3471 2811 By popular(?) request, I'm posting my whitespace solution. In order to reduce the code needed, I hardcoded the entire string as one binary number (7 bits for each byte). A simple loop extracts the characters and prints them. [Source code on filebin.ca.](http://filebin.ca/1tmc6DSS3EBh) **NOTE:** [The specifications allow for arbitrary large integers](http://compsoc.dur.ac.uk/whitespace/tutorial.php), but the [Haskell interpreter on the official page](http://compsoc.dur.ac.uk/whitespace/download.php) is limited to 20 bits. Use, for example, [this ruby interpreter on github/hostilefork/whitespaces.](https://github.com/hostilefork/whitespacers) The ruby script to create the whitespace program (l=WHITESPACE, t=TAB, u=NEWLINE, everything after // ignored, writes to a file `prog.h`): ``` str = 'Elizabeth obnoxiously quoted (just too rowdy for my peace): "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG," giving me a look.' def b2ws(bin) bin.chars.map{|x|x=='0' ? "l" : "t"}.join end def d2ws(dec,pad=0) b2ws(dec.to_s(2).rjust(pad,'0')) end bin = str.reverse.chars.map do |x| " " + d2ws(x.getbyte(0),7) + " // char <#{x=="\n" ? "LF" : x}>" end data = "lll // pushes string as one large number\n#{bin.join("\n")}\nu" File.open('prog.h','w') do |fout| fout << data << "\n" fout << <<-eos // output string loop ulllu // label 0 // extract, print, and remove the last 7 bits of the data lul // dup llltlllllllu // push 128 tltt // mod tull // print as char llltlllllllu // push 128 tltl // div // break loop if EOS lul // dup utltu // jump to 1 if top of stack is zero ululu // jump to 0 ulltu // label 1 uuu eos end ``` For illustration, the whitespace program in human-readable form. See below for a simple script to convert it to an actual whitespace program. ``` lll // pushes string as one large number ltltttl // char <.> ttltltt // char <k> ttltttt // char <o> ttltttt // char <o> ttlttll // char <l> ltlllll // char < > ttllllt // char <a> ltlllll // char < > ttlltlt // char <e> ttlttlt // char <m> ltlllll // char < > ttllttt // char <g> ttltttl // char <n> ttltllt // char <i> tttlttl // char <v> ttltllt // char <i> ttllttt // char <g> ltlllll // char < > ltllltl // char <"> ltlttll // char <,> tlllttt // char <G> tlltttt // char <O> tllltll // char <D> ltlllll // char < > tlttllt // char <Y> tlttltl // char <Z> tlllllt // char <A> tllttll // char <L> ltlllll // char < > tllltlt // char <E> tlltlll // char <H> tltltll // char <T> ltlllll // char < > tltlltl // char <R> tllltlt // char <E> tltlttl // char <V> tlltttt // char <O> ltlllll // char < > tltlltt // char <S> tltllll // char <P> tllttlt // char <M> tltltlt // char <U> tlltltl // char <J> ltlllll // char < > tlttlll // char <X> tlltttt // char <O> tlllttl // char <F> ltlllll // char < > tlltttl // char <N> tltlttt // char <W> tlltttt // char <O> tltlltl // char <R> tlllltl // char <B> ltlllll // char < > tlltltt // char <K> tlllltt // char <C> tlltllt // char <I> tltltlt // char <U> tltlllt // char <Q> ltlllll // char < > tllltlt // char <E> tlltlll // char <H> tltltll // char <T> ltllltl // char <"> ltlllll // char < > ltttltl // char <:> ltltllt // char <)> ttlltlt // char <e> ttllltt // char <c> ttllllt // char <a> ttlltlt // char <e> tttllll // char <p> ltlllll // char < > ttttllt // char <y> ttlttlt // char <m> ltlllll // char < > tttlltl // char <r> ttltttt // char <o> ttllttl // char <f> ltlllll // char < > ttttllt // char <y> ttlltll // char <d> tttlttt // char <w> ttltttt // char <o> tttlltl // char <r> ltlllll // char < > ttltttt // char <o> ttltttt // char <o> tttltll // char <t> ltlllll // char < > tttltll // char <t> tttlltt // char <s> tttltlt // char <u> ttltltl // char <j> ltltlll // char <(> ltlllll // char < > ttlltll // char <d> ttlltlt // char <e> tttltll // char <t> ttltttt // char <o> tttltlt // char <u> tttlllt // char <q> ltlllll // char < > ttttllt // char <y> ttlttll // char <l> tttlltt // char <s> tttltlt // char <u> ttltttt // char <o> ttltllt // char <i> ttttlll // char <x> ttltttt // char <o> ttltttl // char <n> ttllltl // char <b> ttltttt // char <o> ltlllll // char < > ttltlll // char <h> tttltll // char <t> ttlltlt // char <e> ttllltl // char <b> ttllllt // char <a> ttttltl // char <z> ttltllt // char <i> ttlttll // char <l> tllltlt // char <E> u // output string loop ulllu // label 0 // extract, print, and remove the last 7 bits of the data lul // dup llltlllllllu // push 128 tltt // mod tull // print as char llltlllllllu // push 128 tltl // div // break loop if EOS lul // dup utltu // jump to 1 if top of stack is zero ululu // jump to 0 ulltu // label 1 uuu ``` --- Basically, the string to output is a long integer, and you need to reduce its score. > > Take a number x, and convert it to base b. Its length will be `floor(log_b(x)+1)`, and it will contain `b` different symbols. So the score is `b*floor(log_b(x)+1)`. `x` is a given large number, and if you plot this for b, you'll find the minimum is pretty much at `b=3` (and `b=2` is almost as good). Ie, the length reduces slightly as you use higher bases (log), but size of the charset increases linearly, so it isn't worth it. > > > Thus I looked for a language with only 0/1's, but I didn't find any, and then I remembered there was whitespace and tried it. In whitespace, you can enter binary numbers with 0's and 1's directly. --- # Old code, worse score but more interesting Old code [on filebin](http://filebin.ca/1tigMYBtHOJK). The ruby script I used for creating the program (l=WHITESPACE, t=TAB, u=NEWLINE, everything after `//` ignored, writes to a file `prog.h`): ``` str = 'Elizabeth obnoxiously quoted (just too rowdy for my peace): "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG," giving me a look.' + "\n" def shift(x) (x-97)%128 end EOS = "lttltl" #26 STACK = [] bin = str.reverse.chars.map do |x| byte = shift(x.getbyte(0)) rf = STACK.index(byte) STACK.unshift(byte) y = byte.to_s(2).chars.map{|y|y=='0' ? 'l' : 't'}.join ph = "lll#{y}u" # pushing directly if rf bn = rf.to_s(2).chars.map{|y|y=='0' ? 'l' : 't'}.join cp = "ltll#{bn}u" # copying from stack end if STACK.size>0 && STACK[0]==STACK[1] "lul // dup #{x.inspect}" elsif cp && cp.size < ph.size "#{cp} // copy <#{x.inspect}> (from #{rf})" else "#{ph} // push <#{x.inspect}> (#{shift(x.getbyte(0))})" end end File.open('prog.h','w') do |fout| fout << "ll#{EOS}u // push EOS" << "\n" fout << bin.join("\n") << "\n" fout << <<-eos // output string ullu // label 0 // add 97 (128) before printing lllttlllltu // push 97 tlll // add llltlllllllu // push 128 tltt // mod tull // print top of stack // break loop if EOS lul // dup ll#{EOS}u // push EOS tllt // subtract utltu // jump to 1 if top of stack is zero uluu // jump to 0 ulltu // label 1 uuu eos end ``` For illustration, the whitespace program in human-readable form. See below for a simple script to convert it to an actual whitespace program. ``` lllttltlu // push EOS llltltlltu // push <"\n"> (41) llltllttltu // push <"."> (77) llltltlu // push <"k"> (10) llltttlu // push <"o"> (14) lul // dup "o" llltlttu // push <"l"> (11) lllttttttu // push <" "> (63) llllu // push <"a"> (0) ltlltu // copy <" "> (from 1) llltllu // push <"e"> (4) lllttllu // push <"m"> (12) ltlltlu // copy <" "> (from 2) lllttlu // push <"g"> (6) lllttltu // push <"n"> (13) llltlllu // push <"i"> (8) llltltltu // push <"v"> (21) ltlltu // copy <"i"> (from 1) lllttlu // push <"g"> (6) ltllttlu // copy <" "> (from 6) llltllllltu // push <"\""> (65) llltlltlttu // push <","> (75) lllttllttlu // push <"G"> (102) lllttltttlu // push <"O"> (110) lllttlllttu // push <"D"> (99) ltlltltu // copy <" "> (from 5) lllttttlllu // push <"Y"> (120) lllttttlltu // push <"Z"> (121) lllttlllllu // push <"A"> (96) lllttltlttu // push <"L"> (107) ltlltllu // copy <" "> (from 4) lllttlltllu // push <"E"> (100) lllttlltttu // push <"H"> (103) llltttllttu // push <"T"> (115) ltllttu // copy <" "> (from 3) llltttllltu // push <"R"> (113) ltlltllu // copy <"E"> (from 4) llltttltltu // push <"V"> (117) ltlltttlu // copy <"O"> (from 14) ltlltllu // copy <" "> (from 4) llltttlltlu // push <"S"> (114) lllttlttttu // push <"P"> (111) lllttlttllu // push <"M"> (108) llltttltllu // push <"U"> (116) lllttltlltu // push <"J"> (105) ltlltltu // copy <" "> (from 5) llltttltttu // push <"X"> (119) ltlltlllu // copy <"O"> (from 8) lllttlltltu // push <"F"> (101) ltllttu // copy <" "> (from 3) lllttlttltu // push <"N"> (109) llltttlttlu // push <"W"> (118) ltlltllu // copy <"O"> (from 4) ltlltllltu // copy <"R"> (from 17) lllttlllltu // push <"B"> (97) ltlltltu // copy <" "> (from 5) lllttltltlu // push <"K"> (106) lllttllltlu // push <"C"> (98) lllttltlllu // push <"I"> (104) ltllttttu // copy <"U"> (from 15) llltttllllu // push <"Q"> (112) ltlltltu // copy <" "> (from 5) ltllttlltu // copy <"E"> (from 25) ltllttttlu // copy <"H"> (from 30) ltllttttlu // copy <"T"> (from 30) llltllllltu // push <"\""> (65) ltlltllu // copy <" "> (from 4) llltlttlltu // push <":"> (89) llltlltlllu // push <")"> (72) llltllu // push <"e"> (4) llltlu // push <"c"> (2) llllu // push <"a"> (0) llltllu // push <"e"> (4) lllttttu // push <"p"> (15) ltlltttu // copy <" "> (from 7) lllttlllu // push <"y"> (24) lllttllu // push <"m"> (12) ltlltlu // copy <" "> (from 2) llltllltu // push <"r"> (17) llltttlu // push <"o"> (14) llltltu // push <"f"> (5) ltllttu // copy <" "> (from 3) ltllttlu // copy <"y"> (from 6) lllttu // push <"d"> (3) llltlttlu // push <"w"> (22) llltttlu // push <"o"> (14) ltlltttu // copy <"r"> (from 7) ltlltltu // copy <" "> (from 5) ltlltlu // copy <"o"> (from 2) lul // dup "o" llltllttu // push <"t"> (19) ltllttu // copy <" "> (from 3) ltlltu // copy <"t"> (from 1) llltlltlu // push <"s"> (18) llltltllu // push <"u"> (20) llltlltu // push <"j"> (9) llltllltttu // push <"("> (71) ltlltltu // copy <" "> (from 5) lllttu // push <"d"> (3) llltllu // push <"e"> (4) ltlltttu // copy <"t"> (from 7) llltttlu // push <"o"> (14) ltlltttu // copy <"u"> (from 7) llltllllu // push <"q"> (16) ltllttlu // copy <" "> (from 6) lllttlllu // push <"y"> (24) llltlttu // push <"l"> (11) llltlltlu // push <"s"> (18) ltlltltu // copy <"u"> (from 5) llltttlu // push <"o"> (14) llltlllu // push <"i"> (8) llltltttu // push <"x"> (23) ltlltlu // copy <"o"> (from 2) lllttltu // push <"n"> (13) llltu // push <"b"> (1) ltlltlu // copy <"o"> (from 2) ltlltlttu // copy <" "> (from 11) llltttu // push <"h"> (7) llltllttu // push <"t"> (19) llltllu // push <"e"> (4) llltu // push <"b"> (1) llllu // push <"a"> (0) lllttlltu // push <"z"> (25) llltlllu // push <"i"> (8) llltlttu // push <"l"> (11) lllttlltllu // push <"E"> (100) // output string ullu // label 0 // add 97 (128) before printing lllttlllltu // push 97 tlll // add llltlllllllu // push 128 tltt // mod tull // print top of stack // break loop if EOS lul // dup lllttltlu // push EOS tllt // subtract utltu // jump to 1 if top of stack is zero uluu // jump to 0 ulltu // label 1 uuu ``` This whitespace program itself is rather simple, but there are three golfing optimizations: * use `lul` to clone the stack when there's a duplicate character * use `ltl` to clone the n-th entry of the stack if its shorter than pushing the char directly * shift down all bytes by 97 (mod 128), makes the binary numbers smaller --- A simple ruby script to convert my human readable whitespace code to an actual whitespace program (read a file `prog.h` and writes to a file `prog.ws`): ``` WHITESPACE = "l" NEWLINE = "u" TAB = "t" File.open('prog.ws','w') do |fout| code = "" fin = File.read('prog.h') fin.each_line do |line| line.gsub!(/\/\/.*/,'') line.scan(/#{NEWLINE}|#{WHITESPACE}|#{TAB}/i) do |x| code << case x.downcase when NEWLINE.downcase "\n" when WHITESPACE.downcase " " when TAB.downcase "\t" else "" end end end fout << code end ``` [Answer] # [Insomnia](https://codegolf.stackexchange.com/questions/40073/making-future-posts-runnable-online-with-stack-snippets/41868#41868), 575 bytes \* 4 = 2300 ``` dyedd=dyyyye=d=yd=dddde=ded=deey=eyy=de=edd=eydyee=yeyy=yey==ddyee=eydee=y=eyeedd=dde=yddd=eede=yedde=eeyd==yeyy=yyddy=eyy=dy=dddye=dyey=ede=yddd=dde=de=yyye=yyye=ddyyy=dyy=yeyddy=eyyyde=eed=ddd=yd=edyyd=eeydd=yedd=eye=eee=eeyy=yyyedde=d=eyyyedy=d=yddyye==dyyede=ddd=eydd=yd=ddde==eeeeyy=yeyd=deyy=yyy=ydy=dy=dd=e=ey=dddddy=yeey=ey=eed=ddd=eedy=ddddde=ydeyy=edd=ydy=ddy=yeedd=ydde=dde=edyye=ded=yeed=dddddde=eedy=eyde=ydy=ydydd=eyydd=dd=dddd=ddyye=ydeey=ed=eeeye=y=ydydde=eyyd=eyee=dy=edeyed=dyed==eyyddey=dd=yddd=yddd=de=ddedy=eyydd=eeedy==eyyydeee=d=d=eydd=yey=dyy==yyyedy= ``` Uses 4 characters `dye=`. ### Solution 1b (unpublished): 783 bytes \* 3 = 2349 ``` eeeeyeeyy=eeyy=yeyye=yyyeeyye=eeeye=yeyey=eyeyyy=eyy=eeyeye=yeyeyyy=yyeeye=yeyy=yey==yyeyeyeye=eyyey=y=yyyyyy=y=eyyeyyyyyyye=eeye=yyeeyye=eyeyeyyy==yeyy=yeyyyeyye=yyyeeyy==eeyyeee==eeyye=yyyyeyyeyyye=yyyyyyy=yeye=eyyyyy=eeye=eeyeeeeey=eyeye=eeee=yeyyye=eyyyyye=y=eeeyyy=eyyeyee=yyy=eyye=yeyeeee=yyeyeyyyy=eeyy=yyyyy=eyyyy=yyeeyye=e=eyyyyy=eyey==eyeyy=yyyyyeyeyeye=ye=yyyyyy==eeeeyy=yeye=yeyyey=yyy=eyyyeeeye==yeeyyeyy=e==yeeeyyyeyy=yeey=ey=eee=eyeyy=yyeeee=yeeyyyyy=yee=yeyyy=yeeeeyy=eyeeeeeye=eeeyy=yyeeeeyyye=yey=yyyyeeyye=yyyyyyy=yeee=eeeeyyeye=eyeeye=eeyyeyyy=eeyee=yyyyyeeyy=eee=eeyyeyyyyy=eeey=eyyeeyy=eyyeyyy=eeeeyeee=eeeye=y=yyyeyy=yyeeee=yyeyey=ey=eyyyyyeyyy=yeye==yeeyyyeyy=yeye=yyyyeeyy=eeeyyeeyyy=yeeyeyyy=eeyye=eee=eyyye==eyeyeyyyyy=e=eeyeeye=yeey=eyeyy=eyeye=ey=eyyeye= ``` Only uses 3 characters `ey=`. ### Solution 1: 826 bytes \* 3 = 2478 ``` yoyoy~oyoyo~oyooyy~ooyyoyy~ooyyyyoy~~yoyyo~ooyoooyooo~yoyyo~oyoyoyyy~yyo~oyyoo~~ooooy~oyyyyy~oyoyoo~~oyyyoooyy~~oyoyooyyy~yyooo~yoyo~yoyyyyo~yooyo~y~yyoyyyooyy~oyyooy~ooyoy~oyyooy~ooyyo~yoyyoo~o~ooyo~yooyyoo~yoyoy~ooyyyyooo~oyoyyo~yyoyyyoo~yyo~yyooyyo~yoyyoooy~~yoyyyooyoyy~oyoyyy~yoooyyoy~yooyy~yooyyo~yyooyyoo~oyoyo~oyyy~oyyo~oyyoyo~oyyyoo~oyoyyoo~yooyo~ooooo~~yoyyoyyoyoo~yoyyooo~y~ooooy~yyyoy~ooooyyoyyoy~oyyoo~oyyoyo~yoyyyooy~oyooo~yoyyoyy~yyyyyo~oyooy~oyoyy~yoyyyoy~ooyoy~yoyyoooy~~oyyyo~ooooooy~yooyoyyoyo~yooyyo~oooyyo~yoyooyyo~oyyy~o~yooooy~oyoyyooooy~~yoyyooyyo~oy~yyyoyyyyy~yoyyyoy~yooo~oooy~oooooyyoyyyo~yoyyo~y~oooyyyoyoo~yyooooyoyy~y~oooyyyoy~~yoy~oyyoyoyyy~yoyyyyy~oyooo~yyyyooo~yooyyoy~yooyo~yoyyyo~yyoyyyo~o~ooooooyoy~oyoyyoy~yyoooo~ooooyy~oyoyoy~ooyyo~yyoooyo~yyyyyo~oyyo~yooyyooyyoy~~ooyyyyoyyy~ooyyo~yyooo~ ``` Only uses 3 characters: `yo~`. A program is used to generate this. Currently, all programs only use instructions 0, 1, 2, 6. In other words, they manipulate the bits in a single byte and print out the result. [Answer] # Ruby 144 Bytes \* 39 Unique = 5616 ``` puts"Elizabeth obnoxiously quoted (just too rowdy for my peace): \"#{'the quick brown fox jumps over the lazy dog,'.upcase}\" giving me a look." ``` Sometimes the simplest is the best. [Answer] # Brainfuck, 1264 bytes \* 7 unique = 8848 Yeah, it's a terrible score. ``` ++++[++++>---<]>++.-[--->+<]>.---.-[--->+<]>++.[->+++++<]>-.+.+++.[--->+<]>---.------------.--[--->+<]>--.+++++[->+++<]>.-------------.++++++++++++.+.+++++++++.[->+++<]>+.++++++.++++++.--.-------.-[--->+<]>.-[---->+<]>++.----[->++++<]>+.++++.------.+++++.+++[->+++<]>.-.-[--->+<]>-.++++++++.-----[->+++<]>+.+++++++++++.--.+.[---->+<]>+++.---[->++++<]>.-----..[--->+<]>-----.---[----->++<]>.---.++++++++.[->+++<]>-.+[--->+<]>++.-[---->+<]>++.++[->+++<]>.+++++++++.+++.[-->+++++<]>+++.+[----->+<]>.--[--->+<]>.-[---->+<]>++.[-->+++++++<]>.-----------.----.++.++.--[->+++<]>.-[-->+++<]>--.[-->+<]>+++.++.>-[--->+<]>-.------------.---.-[-->+<]>--.[-->+++++<]>+.++++.------------.------.++++++++.---[->++++<]>.+[->++<]>.>-[--->+<]>---.---.++++++++.---------.++[----->++<]>.+++[->++<]>.+++++++++.+++++++++.[--->++++<]>.+++++[->++<]>.>-[--->+<]>.--------.+++.+++.+[--->+<]>++++.[-->+++++<]>-.+++++++.--[----->+<]>+.+++++++++++++.--[----->++<]>.>-[--->+<]>-.------------.---.-[-->+<]>--.++++++[->++<]>.-----------.-----[-->+++<]>.-.+[--->+<]>++.++[->++<]>.+++++++++++.--------.--[--->++<]>--.----------.--.++[->+++<]>+.++.[->++++++<]>.[------>+<]>.+++++.-------.-[--->+<]>--.+[----->+<]>.--------.--[--->+<]>-.[->+++<]>+.-[->+++<]>.++[--->++<]>.+++..----.[->++++++++++<]>. ``` [Answer] # ><> (Fish) - 578 bytes \* 8 unique = 4624 ``` 14121412412431421124321110441421130402401433401430421141143114240333221142303303210321143224241321121343212340321131301320302344221132340304221130322340321313221100323234202311321143224241341121131213110444324310422421114441421142412420421114400443412442421112412413421113403423411403121100410413412423432421114431403423412401404412402434312421140413410434324324401431443243*3*3+3*1+00p44*4+3*2+01p44*3*4+1+11p44*3*4+1+21p43+3*2*31p43+3*2*41p43*3*41+1p44*3*4+1+42+1p43+3*2*43+1p43+3*2*1+44+1p43+3*2*1+33*1p43*3*3*3+33*1+1p43*3*3*33*2+1p43+3*3*43*1p44*2*1+43*1+1p44*3+3*2+43*2+1p ``` My score isn't as competitive as I was hoping, but I thought this solution was still interesting enough to post. ## Explanation The first section of code is a long string of the digits 0-4 that represent a 3 digit base 5 representation for each character in the string. The remaining code takes advantage of the `p` operator in Fish that allows you to edit the program's source code while the program is running. By using that operator, I was able to generate the Fish code necessary to convert the base 5 characters back to base 10 and output them, and then put that code back into the source code at the beginning of the file before the interpreter reached the end of the line and wrapped around. When the interpreter reaches the end of the line, the code has been modified to look like this: ``` v4121412412431421124321110441421130402401433401430421141143114240333221142303303210321143224241321121343212340321131301320302344221132340304221130322340321313221100323234202311321143224241341121131213110444324310422421114441421142412420421114400443412442421112412413421113403423411403121100410413412423432421114431403423412401404412402434312421140413410434324324401431443243*3*3+3*1+00p44*4+3*2+01p44*3*4+1+11p44*3*4+1+21p43+3*2*31p43+3*2*41p43*3*41+1p44*3*4+1+42+1p43+3*2*43+1p43+3*2*1+44+1p43+3*2*1+33*1p43*3*3*3+33*1+1p43*3*3*33*2+1p43+3*3*43*1p44*2*1+43*1+1p44*3+3*2+43*2+1p >55**$5*++ol?!; ``` When the code wraps around and hits the `v` operator it goes down to the second line, hits the `>` operator and proceeds to loop, each time converting the base 5 encoding back to a base 10 ascii value and then outputting that value. When there are no more values on the stack the `?` operator will skip to the `;` and the program will end. [Answer] # [7](https://esolangs.org/wiki/7), 273 bytes × 7 unique bytes = 1911, noncompeting (language postdates challenge) ``` 501513010250341012432044041204045104011053033043511402401130443235151151105240424404004144031133304214014044433043401032201433022042551243201043511102223044114403120042140450415114434050440500114042432010430032533041340424320250451514210501020420444010403043040402343447403 ``` [Try it online!](https://tio.run/nexus/7#PY8BCsNQDEKvpIlh9z9Z96RsUBoi@uJ/Tj6vrDltLE92lChmKGf@tm61q@zZ0VRiw4qAdHWgZpoUYebiaWZI8AV7CSzaGSRWZubuveqXT5eZ0v1SRi8jB7f3y7h2PKl18k8L8vWK9yfzrrQjCPyw0dulfrVPX6lZoPmgPM8X "7 – TIO Nexus") Unfortunately, this is an old challenge, meaning that I don't get to win with one of my newest languages. However, the language was created with no knowledge of the challenge (I just randomly stumbled across it in "related questions"), but nonetheless pretty much turned out to be a perfect fit. 7 programs on PPCG normally get submitted in packed format, packing eight commands into three bytes (the language has twelve commands, but only eight can appear in a source file, meaning that three bits are enough). However, the language also supports an octal format in which each command is written as an ASCII digit, and that's what I've used here, meaning that only seven distinct bytes are used (the `6` command isn't necessary in a program that just prints a simple string). The program is very simple; it consists of two stack elements, a long string that just gets printed verbatim, a `7` to separate the elements (unfortunately unavoidable), and `403` which is a simple way of printing a constant string in 7 (`40` escapes the second stack element, whilst moving it to the top of the stack, then `3` prints it and discards the old first stack element, i.e. the `403` itself). So how did I get the string as short as 269 bytes? 7 supports multiple I/O formats, and one of its formats is [US-TTY](https://en.wikipedia.org/wiki/Baudot_code#ITA2), a character set (specifically, a variant of Baudot) which was widely used before ASCII was invented. (The `5` at the start of the second stack element, i.e. the start of the program, specifies the string's encoding; the rest is the string content itself.) It's a five-bit character set, and the commands `0` to `5` can safely be stored in strings whilst being unescaped consistently (so that escaping it once will exactly reproduce the original), so the language uses pairs of commands (36 options) to encode characters of US-TTY (32 options, with 4 being used for directives to the 7 interpreter itself). Of course, there are more than 32 unique characters that people might want to output (and more than 32 characters appear in the string), so two of the characters are "shift codes" that switch between four character sets (uppercase letters, lowercase letters, figures, and a user-defined "figures extension" which 7 uses for the remaining ASCII characters that aren't in the other character sets; however, all the characters in the string are "natively" in US-TTY so the details of the extension didn't matter). Here's the program's output, with non-ASCII characters added to show where shifts occur (and a line break added to make reading easier, which isn't in the original string): ``` Ełlizabeth obnoxiously quoted Ø(Łłjust too rowdy for my peaceØ): "ŁTHE QUICK BROWN FOX JUMPS OVER THE LAZY DOGØ," Łłgiving me a lookØ. ``` I count ten shifts added to 124 characters of input, a fairly negligible ratio. As such, the ability to use only just over two bytes of input per input character, times 7 unique bytes, means that the score on this challenge is incredibly good. (I guess a language that was designed specifically for this challenge would use some sort of string compression, rather than a pre-existing character set, but even though Baudot and US-TTY weren't designed for golfing, they're still fairly concise.) [Answer] # Python 2, ~~163~~ ~~147~~ ~~145~~ 143 bytes \* ~~35~~ ~~36~~ 35 unique = ~~5705~~ ~~5292~~ ~~5220~~ 5005 That's probably about as good as I'm going to get it. ### Edits: 1. Removed `.capitalize()` in favor of using `E`. 2. Changed to use `'` instead of backslash escaping quotes. 3. Removed `+` and some spaces to use commas in the `print` statement. ``` print"Elizabeth obnoxiously quoted (just too rowdy for my peace):",'"the quick brown fox jumps over the lazy dog,"'.upper(),"giving me a look." ``` [Answer] # Python 2, ~~14508 11700 11088 10164 9486 9746 7860~~ 145 bytes \* 36 unique = 5220 I saw the title and thought this was an interesting challenge for the rather wordy Python. These are my notes as I tackled this problem. My first try reduced the uniques to 31: ``` print''.join(chr([69,108,105,122,97,98,101,116,104,32,111,98,110,111,120,105,111,117,115,108,121,32,113,117,111,116,101,100,32,40,106,117,115,116,32,116,111,111,32,114,111,119,100,121,32,102,111,114,32,109,121,32,112,101,97,99,101,41,58,32,34,84,72,69,32,81,85,73,67,75,32,66,82,79,87,78,32,70,79,88,32,74,85,77,80,83,32,79,86,69,82,32,84,72,69,32,76,65,90,89,32,68,79,71,44,34,32,103,105,118,105,110,103,32,109,101,32,97,32,108,111,111,107,46][r])for r in range(124)) ``` I thought I could do better. By using `map`, uniques came down to 26: ``` print''.join(map(chr,(69,108,105,122,97,98,101,116,104,32,111,98,110,111,120,105,111,117,115,108,121,32,113,117,111,116,101,100,32,40,106,117,115,116,32,116,111,111,32,114,111,119,100,121,32,102,111,114,32,109,121,32,112,101,97,99,101,41,58,32,34,84,72,69,32,81,85,73,67,75,32,66,82,79,87,78,32,70,79,88,32,74,85,77,80,83,32,79,86,69,82,32,84,72,69,32,76,65,90,89,32,68,79,71,44,34,32,103,105,118,105,110,103,32,109,101,32,97,32,108,111,111,107,46))) ``` At about this time, I noticed in the question text that the score was `uniques * bytes`, not just uniques! That meant my scores for the above were 14508 and 11700. Not very competitive. So I now reduce the bytes by storing the text as a hex string: ``` # 308*36 = 11088 print''.join(chr(int('456c697a6162657468206f626e6f78696f75736c792071756f74656420286a75737420746f6f20726f77647920666f72206d79207065616365293a202254484520515549434b2042524f574e20464f58204a554d5053204f56455220544845204c415a5920444f472c2220676976696e67206d652061206c6f6f6b2e'[i*2:i*2+2],16)) for i in range(124)) ``` Size was reduced but more unique characters. But if I used a packed 2 digit decimal string with a 32 offset: ``` # 308*33 = 10164 print''.join(chr(int('37767390656669847200796678798873798583768900818579846968000874858384008479790082798768890070798200778900806965676909260002524037004953413543003450475546003847560042534548510047543750005240370044335857003647391202007173867378710077690065007679797514'[i*2:i*2+2])+32) for i in range(124)) ``` This has the same number of bytes but saves 3 uniques. I hatch a new plan. If I pack a Python long integer with 7 bit characters, I could extract each one by shifting: ``` # 306*31 = 9486 h=1073974643401006528619595312441225198653732186368270382545648881135648217524502741093886285232362673460172159947573049818819511630304840724474679255867143965214892747087773876949021986013520804726327302180335979259392708372721217579101211940864406962137554744750 w='' while h:w=chr(h&127)+w;h>>=7 print w ``` Well that reduced the score to 9486. An interesting experiment, but nowhere near good enough. Now what if I get rid of the function names and rely on string formatting? ``` # 443 * 22 = 9746 print('%c'*124)%(69,108,105,122,97,98,101,116,104,32,111,98,110,111,120,105,111,117,115,108,121,32,113,117,111,116,101,100,32,40,106,117,115,116,32,116,111,111,32,114,111,119,100,121,32,102,111,114,32,109,121,32,112,101,97,99,101,41,58,32,34,84,72,69,32,81,85,73,67,75,32,66,82,79,87,78,32,70,79,88,32,74,85,77,80,83,32,79,86,69,82,32,84,72,69,32,76,65,90,89,32,68,79,71,44,34,32,103,105,118,105,110,103,32,109,101,32,97,32,108,111,111,107,46) ``` I now have only 22 uniques, but the score does not improve. Ok, What if I took the obvious way and just printed the string: ``` # 131*60 = 7860 print'Elizabeth obnoxiously quoted (just too rowdy for my peace): "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG," giving me a look.' ``` Score of 7860. I should have done this first. But I would not have learned so much. I guess I could reduce uniques by 26 if I dynamically produced the upper case parts, so: ``` # 145*36 = 5220 print'Elizabeth obnoxiously quoted (just too rowdy for my peace): '+'"the quick brown fox jumps over the lazy dog,"'.upper()+' giving me a look.' ``` I think Python will not get much better than 5220. The task of minimising the unique characters in Python sure was instructive though. Update: mbomb007 has a better Python solution scoring 5005. Nice work. [Answer] # [><> (Fish)](http://esolangs.org/wiki/Fish) - 138 Bytes \* 65 Unique = 8970 The simple route, i.e. Hello World: ``` !v'Elizabeth obnoxiously quoted (just too rowdy for my peace): "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG," giving me a look.'r! >l?!;o ``` Well, for my first foray into ><> this was a challenge. I think I see some improvements, but it was fun learning it :) Or to make it overly complicated - 1567 bytes \* 27 Unique = 42309 ``` !\f8+3*:o2*f2*-:o3-:of+2+:ofa+-:o1+:o3+:of+:oc-:o\7+:od-:oc+:o1+:o9+: of-:o6+:o6+:o2-:o7-: od+:o\8-:o4+:o6-:o5+:of -:o1-:o\\6+:ob+ :o2-:o1+:o\:o5-:o:o\3+ :o3-:o8+:of4+-:oab ++:o\f4+-:o9+ :o3+: o\! !5:of+a+:o1-:off+2+o:f-6-oa-:o8-:of3*1-:oa-:o2-:!fo3*7+:o2+:o:d+o:o5!f+:o7-:off+2+o6+:o8-!f:off!f+2+o4-:off+2+ob+!f:o3+::\ff f f f f f f f f \!f- - f f f f f ff 3 f f f f f f f f : + + + + + ++ * + + + + + + + + o 2 2 2 2 2 2a 1 2 2 2 2 2 2 2 2 c + + + + + ++ + + + + + + + + + + o o o o o \oo4-o \ o; o o o o o o o \:off+2+o9-:ob-:o4-:o2+:o2+:of4*%:of2++:o2,3+:o2 +:o3*f-3-:oc-:o3-:o\c+:o4+:oc-:o6-:o8+:o\9-:of 1++:o3-:o8+:o9-:o\8-:o9+: o9+: o\e-:ob+:o8- :o3+:o3+ :o\4-:o7+:o2-f-:od+:o\2+:o c-:o3-:o\7+:ob\ ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 380 bytes \* 11 chars = 4180 score ``` "234413410442342343401431404112421343420421440410421432430413441112423432421431401400112130411432430431112431421421112424421434400441112402421424112414441112422401342344401131213112114314242234112311320243232300112231312304322303112240304323112244320302310313112304321234312112314242234112301230330324112233304241134114112403410433410420403112414401112342112413421421412141"3ô5öçJ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=IjIzNDQxMzQxMDQ0MjM0MjM0MzQwMTQzMTQwNDExMjQyMTM0MzQyMDQyMTQ0MDQxMDQyMTQzMjQzMDQxMzQ0MTExMjQyMzQzMjQyMTQzMTQwMTQwMDExMjEzMDQxMTQzMjQzMDQzMTExMjQzMTQyMTQyMTExMjQyNDQyMTQzNDQwMDQ0MTExMjQwMjQyMTQyNDExMjQxNDQ0MTExMjQyMjQwMTM0MjM0NDQwMTEzMTIxMzExMjExNDMxNDI0MjIzNDExMjMxMTMyMDI0MzIzMjMwMDExMjIzMTMxMjMwNDMyMjMwMzExMjI0MDMwNDMyMzExMjI0NDMyMDMwMjMxMDMxMzExMjMwNDMyMTIzNDMxMjExMjMxNDI0MjIzNDExMjMwMTIzMDMzMDMyNDExMjIzMzMwNDI0MTEzNDExNDExMjQwMzQxMDQzMzQxMDQyMDQwMzExMjQxNDQwMTExMjM0MjExMjQxMzQyMTQyMTQxMjE0MSIzw7Q1w7bDp0o&input=) Pushes base 5 representation of ASCII chars joined together. Splits in pieces of 3, converts back to decimal. Converts ASCII integer back to character. Joins back together. [Answer] ## Perl 6, 139 bytes \* 36 unique = 5004 ``` say 'Elizabeth obnoxiously quoted (just too rowdy for my peace): "'~"the quick brown fox jumps over the lazy dog".uc~'," giving me a look.' ``` [Answer] # Java 8, 141 bytes \* 64 unique characters = 9,024 ``` ()->{return"Elizabeth obnoxiously quoted (just too rowdy for my peace): \"THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG,\" giving me a look.";} ``` 141 bytes, 64 unique characters. Approaches other than the simple "return the string" increase the byte count without saving much on characters used. [Answer] # [Perl 5](https://www.perl.org/), 137 bytes \* 35 unique = 4795 ``` say'Elizabeth obnoxiously quoted (just too rowdy for my peace): "',uc'the quick brown fox jumps over the lazy dog','," giving me a look.' ``` [Try it online!](https://tio.run/##Fco7EoIwFAXQrdyhic4ggwWNvaWLCPCEQMiL@QBh8Uasz7HkdJOzl0k8tTpkS2EEt4Z3xdHrhE/kQD0uU/QBgRmOtz7hzQ5LgiXZ0fWBQpSxE2Gk86tuRnsuc6YdU1ysB6/k8Gctj4SeB1GKssCgVmUGLAQJzTxXIucv26DY@Hx7NVV9r38 "Perl 5 – Try It Online") [Answer] # [Tcl](http://tcl.tk/), 345 bytes, 345 x 13 = 4485 ``` \160\165\164\163 [\163\165\142\163\164 [\162\145\147\163\165\142 \55\141\154\154 \50\\\144\\\144\51 "055451724142456450 5742565770515765635471 616557644544 \5052656364 645757 6257674471 465762 5571 6045414345\51\72 \"241005 2125110313 0222172716 061730 1225152023 17260522 241005 14013231 041707\"\54 475166515647 5545 41 54575753" \\\\1\\1]]\56 ``` [Try it online!](https://tio.run/##7VFLasMwEN33FA/hVaGgkWY0q65yDMuL0pg0YNIQK5Dbp0@JF71AdwWP5PeTZlD7XO73KiWyjKWsjLGvT0bT9q8Plkg7678dqNZ3qWLaizjWSka31QQhmqmJJ2VArahFmGuyYu7RxLxYyaYuKDyWUNX0cZSlLrEBhtwcJVF17VZluiTQzlhkQDSzP5Pq7CrwshgNSZKJxCwZMaXEJlwKYhHPEZIoWoopg0LhbQlbTjRKTlkQVTx6DZWzqZuUwkhRR58JKrBHZ5YDah@Z3zRVK/d1blgxXuaPPda2P56ml04tGNd2OZ4OWOYThnV6OV8bfV3bYVzW70vD25XEeTk2GhDCND2zZBemDu0Lw24LhmHBDcMV7xjn2/kC4lfiKfy/7V@97Q8 "Tcl – Try It Online") --- # [Tcl](http://tcl.tk/), 337 bytes, 337 x 15 = 5055 ``` \160\165\164\163 [\163\165\142\163\164 [\162\145\147\163\165\142 \55\141\154\154 (\\\144\\\144) "055451724142456450 5742565770515765635471 616557644544 (52656364 645757 6257674471 465762 5571 6045414345)\72 \"241005 2125110313 0222172716 061730 1225152023 17260522 241005 14013231 041707\"\54 475166515647 5545 41 54575753" \\\\1\\1]]\56 ``` [Try it online!](https://tio.run/##7VHNasMwDL73KT5CDutgIMmSddqpjxHnMNbQFUJXEhf69p3c9rAH2HEQ2fn@bAnXz/l2K5wpyqI0KmFo64NRef7rnQ2kjfXfDhRrOxc2bYWXUgLrY92iIzM1dtEwq2U1grmKZXMnY/NsOZk6I8eRAVVN4xiTJsTVEXFzZAnNtRk1slkQ5ghR2FmT2rZ4dNPFRUQGYTFmSpxAIhINOGdQZk8ElhBNSBJCyGQieOZYiZMkBik7eelKzKRunHNEsjraPFCG3fuy1KG0YeMbx2L5tk4VK4Zl@thjrfvjadw0asaw1uV4OmCeTujXcXO@1PA1bYdhXr@XirdLEOf5WMOArhvHRzbYOVKH@oV@9wx2/Ywr@gveMUzX84LAr4HH7v9N//pNfwA "Tcl – Try It Online") ## # [Tcl](http://tcl.tk/), 329 bytes, 329 x 16 = 5264 ``` \160\165\164\163 [\163\165\142\163\164 [\162\145\147\163\165\142 \55\141\154\154 (\\d\\d) "055451724142456450 5742565770515765635471 6165576445d (52656364 645757 625767d71 465762 5571 6045414345)\72 \"241005 2125110313 0222172716 061730 1225152023 17260522 241005 14013231 041707\"\54 475166515647 5545 41 54575753" \\\\1\\1]]\56 ``` [Try it online!](https://tio.run/##7VFBagMxDLz3FcOyh6RQkGTJOvWUZ6z3ULohDSxp2HUgv0/lJIc@oMcaybZGM5KN6ud8uxXOFG7hGp4wtP2BqDzvekcj0ob6bwaKtZMLmzbHppQpbIuOzNTYRYOmltUI5iqWzZ2MzbPlZOqMHMUiVLUJG5OGR89QuDmyRMqnoGkosyCoISG1KJzUtsXjFV20ITIIizFT4gQSkWjvnEGZPRFYImlCkhCJTCaCp46VOElikLKTl67EX9SNcw5JVkf7DZRh92dZ6lBicdg4Fsu3dV@xYlj2HxPWOh1P40uDZgxrXY6nA@b9Cf06vpwvNXgtt8Mwr99LxdslgPN8rEFA143jQxvoHKpD/UK/ewq7fsYV/QXvGPbX84KIXyMeu/9Z/tUsfwA "Tcl – Try It Online") --- # [Tcl](http://tcl.tk/), 333 bytes, 333 x 16 = 5328 ``` \160\165\164\163 [\163\165\142\163\164 [\162\145\147\163\165\142 \55\141\154\154 (\\d\\d) "055451724142456450 5742565770515765635471 6165576445d \5052656364 645757 625767d71 465762 5571 6045414345\51\72 \"241005 2125110313 0222172716 061730 1225152023 17260522 241005 14013231 041707\"\54 475166515647 5545 41 54575753" \\\\1\\1]]\56 ``` ## [Try it online!](https://tio.run/##7VHNasMwDL7vKT5CDttgYNmSddqpjxHnMJbQFUJXEhf69t3ntoc9wI4zVmJ9P5KM6@dyvRbJgWEMZSQM7XtHND7OekOZaUP9twLF2l@KmLbAcykT9wu6YKYmHpUytawWYK7RsrkHE/NsOZm6ILMYU1WbWC9YbAy70uPmyJGkTxQqvTmCYpqCGksnzmRSnJN0bBWCIUo0kZAkIcQYOYJLRsjiKUAiSYshJpDIbBbx8IkGSTEJgooHL13hfdRNcqYlq6PdCCqw22CWOhQu4R7HYvm6zRUbhnX@mLDV6XAcnxq0YNjqejjuscxH9Nv4dDpX6hq3w7Bs32vF25nAaTlUCtB143j3El3o2tcv9LuHsesXXNCf8Y5hvpxWMH9lPnb/7/mX7/kD "Tcl – Try It Online") --- # [Tcl](http://tcl.tk/), 148 bytes, 148 x 37 = 5476 ``` puts "Elizabeth obnoxiously quoted (just too rowdy for my peace): \"[string tou "the quick brown fox jumps over the lazy dog"],\" giving me a look." ``` [Try it online!](https://tio.run/##zZBBbsMwDATvecVC8KEt2j6gQI99haKDbbGOEtp0RCq183lXRtA/9LjLWZBL63nb5mIK98Xp3nZkJ0g3yZKkKK@4FjGKeDoXNZgIsvzEFd@SMa6Yqe3p@QNH59VymoaKFDg7UQ2m/oKu4lOlF5zLOCvkRhn7mNv7iiiDC69HhyHd9vBIaMEil3e3KRkUPlMboRbTFA67xfjbxDSh0Ydb4LnqoR7vWSUb3qqlMyerDJwLIRweNRvGgqbgE56WOaPql6qD@5dv@AU "Tcl – Try It Online") ## # [Tcl](http://tcl.tk/), 277 bytes, 277 x 21 = 5817 ``` \160u\164s [subs\164 [\162\145\147sub \55\141\154\154 (\\d\\d) "0554517241b456450 ob56o7051ous5471 61uo6445d(52us64 64oo 62o67d71 46o62 5571 6045414345): 241005 2125110313 0222172716 061730 1225152023 17260522 241005 14013231 041707\" 475166515647 5545 41 54oo53" \\\\1\\1]]\56 ``` [Try it online!](https://tio.run/##7VHBasMwDL3vKx4hh3YwsBRJhsFO/Yw4h3UpXSHUJbahf98pbLvtE2YkIenpyUKqH8vjkchCcyMFY2nHsrkY3XIiUdfoWSTdXEqksil2Kc0ue3RBVZQiCx1FTTQgH9VyDEq5FZVIMGrZRHTeKbfi7U1yhnG2ODsslo2hulUGUSEZRPev8JYhKJhYicJAAwIz@1eRDMEoDgHEDioHHuCABWX@5ZEEGnggBKEYYuogUcnM600itrEhBPVZdOiQ/JHLNCW1RzlV@ELW0/uMUufLdXraUovvqK6X6xnL6Yq@TE@3VrfFOXbAuJS8Vrw0T9yWS/UCdN00fXM9uzjrXD/RH36IXb/gjr7hDePpflvh8bPHU/d/l7/u8gU "Tcl – Try It Online") ## # [Tcl](http://tcl.tk/), 371 bytes, 371 x 16 = 5936 ``` puts "\105\154\151\172\141\142\145t\150 o\142\156o\170\151ous\154\171 \161uot\145\144 \50\152ust too \162o\167\144\171 \146o\162 \155\171 p\145\141\143\145\51\72 \"\124\110\105 \121\125\111\103\113 \102\122\117\127\116 \106\117\130 \112\125\115\120\123 \117\126\105\122 \124\110\105 \114\101\132\131 \104\117\107\54\" \147\151\166\151\156\147 \155\145 \141 \154oo\153\56" ``` [Try it online!](https://tio.run/##7VHLasQwDLzvVwiTU6FgOX6cetrPiHMo3bANmDjEDuzfp6M4l/5ATz0ISaMZPez6lY5j3WshFVm7yM7COHIwkS28Fe8qQE25pc4jCFp4eS9NEpgie95zFTrMUnRCMXupVHOWsoHOByleAiudvEHk3Amtl1oG92eMXQII2M5AxVq2BN@AYcBkeA0m9wA1ljMwxgwDYy@gb0CvkbC5ZDCDXkZkJ923840s82sSI9GY0kPay9LaNokOEZcrOSO0N/O@eecFu66y0sSK0NmMc10fnVdHmSoVGrbp80GlPuZlvAmUaCh1m5cnpWmhroy383MGqd1pSCVvld53AGuaKwik1Dg2LdAE1bN@U3e/hKpL9KJupw8apte6EfI35KP6//W///Uf "Tcl – Try It Online") ## # [Tcl](http://tcl.tk/), 401 bytes, 401 x 16 = 6416 ``` puts "\105\154\151\172\141\142\145\164\150 o\142\156o\170\151o\165\163\154\171 \161\165o\164\145\144 \50\152\165\163\164 \164oo \162o\167\144\171 \146o\162 \155\171 \160\145\141\143\145\51\72 \"\124\110\105 \121\125\111\103\113 \102\122\117\127\116 \106\117\130 \112\125\115\120\123 \117\126\105\122 \124\110\105 \114\101\132\131 \104\117\107\54\" \147\151\166\151\156\147 \155\145 \141 \154oo\153\56" ``` [Try it online!](https://tio.run/##7VLLasQwDLzvV4iQU6Fgya9TvyTOoXTDNmCSJXZg/z4drVNK/6CHHmRJkxlJVlw/8nHc91qoS2x8Yu9gnDhKYgfv1AMPihtaG@IDgmiUiiDod9u0kQkJK7g2laqdo@SVLj/s4JTp1lWdKDkq8SzhtEMQRN5/VzVnMR3LPmNMGsHB7AIhG70DmAKGgMnwBky2AA16C4zRRmAcFAwNsAYJyymDCWqJyp700JYjOs@vTozEoIuF1OqQxjWJiQnr6PQmsW00hOZ9UOy8mNMiToUem8Bpkw/dUaZKhYZter9Sqdd5GS8KZRpK3eblRnlaqC8N3WnIyG/1E0FZt0qvgMo9zxUc6rpxHC/tH/eZHtTv9EbD9LhvhPwF@dj9v4G/9ga@AA "Tcl – Try It Online") --- # [Tcl](http://tcl.tk/), 403 bytes, 403 x 16 = 6448 ``` puts "\105\154\151\172\141\142\145\164\150 o\142\156o\170\151o\165\163\154\171 \161\165o\164\145\144 \50\152\165\163\164 \164oo \162o\167\144\171 \146o\162 \155\171 \160\145\141\143\145\51\72 \42\124\110\105 \121\125\111\103\113 \102\122\117\127\116 \106\117\130 \112\125\115\120\123 \117\126\105\122 \124\110\105 \114\101\132\131 \104\117\107\54\42 \147\151\166\151\156\147 \155\145 \141 \154oo\153\56" ``` [Try it online!](https://tio.run/##7VJBasQwDLzvK0TIqVCwbNk@9SVxDqUbtgGTLLED@/t0tE4p/UEPPciSJjOSrLh@5OO477VQl9j4xF5gnDjaxAIv6oEHxQ2tDfEBQTRKRRD0u2vayISEFVybStUilLzS7Q87iDJlXdVZJUclniVEOwSLyPvvquYspmO5Z4xJIzg6koWSjV4CVAuKBZXhDajsABplwRh9LIyDgqEBziBhe8pgFrWsyp700LZjdaBfnRiJQRcHqdMpjTSJiQn7EBVIbDsNoXkfFDuvJlpFVOmxC5wu@dAdZapUaNim9yuVep2X8aJQpqHUbV5ulKeF@tLQnYaM/FY/EZR1q/QKqNzzXMGhrhvH8dL@cp/pQf1ObzRMj/tGyF@Qj93/K/h7r@AL "Tcl – Try It Online") --- # [Tcl](http://tcl.tk/), 433 bytes, 433 x 15 = 6495 ``` puts "\105\154\151\172\141\142\145\164\150 \157\142\156\157\170\151\157\165\163\154\171 \161\165\157\164\145\144 \50\152\165\163\164 \164\157\157 \162\157\167\144\171 \146\157\162 \155\171 \160\145\141\143\145\51\72 \42\124\110\105 \121\125\111\103\113 \102\122\117\127\116 \106\117\130 \112\125\115\120\123 \117\126\105\122 \124\110\105 \114\101\132\131 \104\117\107\54\42 \147\151\166\151\156\147 \155\145 \141 \154\157\157\153\56" ``` [Try it online!](https://tio.run/##7VJBagMxDLznFWLJqVCwbFk@9SXrPZRmSQNLGtZeyO@TUey09AmFHrSWZmdGsnD9WG63y1YLDZldzBwFwZmTzyw4xU7gargjfFIDo7Y8uSawXI0YmklikJUb@PgpzUmEcjSR/xGoUG@RLKzwXWXtnnbSe6q3QeKzievGNm545BgogWNzeojZ2eVA9aB4UBmnA5UDQGcsBMPZI1gN1AYEuzP7LkN4eHmTPejatuZtoF@dGIVDlwBpsCmdNIlLGesRE0hqq1PtK1TD@tXEXMSU8XsviJCjDrcyVyo0rvP7gUo9nM7TzqCFxlLX0/lIy3ymfWnoRuOC@lg/kZSvtdIroHJZThUcGoZpmnbtDewXutJ@ozca5@tlJdQvqKfh/438tTdyBw "Tcl – Try It Online") ## # [Tcl](http://tcl.tk/), 473 bytes, 473 x 14 = 6622 ``` puts \105\154\151\172\141\142\145\164\150\40\157\142\156\157\170\151\157\165\163\154\171\40\161\165\157\164\145\144\40\50\152\165\163\164\40\164\157\157\40\162\157\167\144\171\40\146\157\162\40\155\171\40\160\145\141\143\145\51\72\40\42\124\110\105\40\121\125\111\103\113\40\102\122\117\127\116\40\106\117\130\40\112\125\115\120\123\40\117\126\105\122\40\124\110\105\40\114\101\132\131\40\104\117\107\54\42\40\147\151\166\151\156\147\40\155\145\40\141\40\154\157\157\153\56 ``` [Try it online!](https://tio.run/##7VJBagMxDLznFWLJqVCwbNk@9SXrPZRmSQMmDWsv5PebsbUh0CeUHoSs8cxIFq5fedtuay2U2PjEXhCcONrEgiwtAw8NN0kMUlTYBz1Ho5J2Do3q1CZypwdWuF@Luom0K9@E9iUKogJRMqKXdtfGrnvayt4d130o/2po9iZtfNfPGC92XpvbwoRNf26jW9As6IxsQGfXYdOYCEYPi@CgcFDI6S7Y7mKEbWYq7qKgG7U64K@ujNKgo4OB07mNqNDEhPWJyiTqckPYlxw69nyyqJuog39tjr1LPmxlrlRoXObPE5V6ulynQ4MyjaUul@uZ8nylY1F0pTGjPtdvHMrPUukdULnlSwWHhmGapkP/K8Mx052OK33QON9vC6F@Qz0N/3/pr/6lBw "Tcl – Try It Online") ## # [Tcl](http://tcl.tk/), 133 bytes, 133 x 60 = 7980 ``` puts "Elizabeth obnoxiously quoted (just too rowdy for my peace): \"THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG,\" giving me a look." ``` [Try it online!](https://tio.run/##zY9JUsMwFET3OUWXyguggANQxYLBzGAIhEnRwomFESj@Rv8LbC5v5MolWL7XveiWpR@GNgpD5d79lgsr76BFQ52jyL7HVySxFTY@IguECIF@qh5vFLDq0dpyaTf3MFcPZznuZudHlzicFk83OCmecTG7vr1H8ZhPMcZXB68vOC5Ot@cKtft2TY2VRQlP9LmrBrYChg62rMBSucZMRuWhWcJY9rZBxmsboX3iOq3VnikIdpLi1jtJHShljJmsf2UeHbKIfWjbtQGJtxIb9T9@/wE "Tcl – Try It Online") ]
[Question] [ A date can be represented by an unsigned integer as such: YYYYMMDD. What you need to do, is write the shortest program or function that figures out the most recent date whose number was divisible by a given number `n` (including today's date) and then returns that date in the format showed above. If there has never been a date (between 00000101 and today inclusive) divisible by the given integer, you should return -1. ## Examples ``` Current Date Input Output 30 July, 2014 4 20140728 30 July, 2014 7 20140729 28 July, 2014 4 20140728 28 July, 2014 7 20140722 28 July, 5 90000 -1 ``` ## Input You can read from STDIN or take a function argument or even expect the input to be stored in a variable. The input will be an unsigned integer. ## Output Write to STDOUT or return (or save in a variable) the integer representing the date in the format YYYYMMDD. ## Restrictions You may use any standard library your language offers. [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply. # Winning conditions This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so smallest program (in bytes) wins. In case of a tie, the answer with the most votes wins. [Answer] ## Mathematica, ~~93~~ 60 bytes ``` For[i=0,(r=DatePlus@i--~FromDigits~100)>0&&!n∣r,];r~Max~-1 ``` Expects the input to be stored in `n`. Note that the vertical line `∣` is the unicode character for "divides", which I've counted as 3 bytes (UTF-8). **Edit:** Found a neat trick to avoid the bloated `DateString` and format specification :). **Edit:** Totally forgot about the `-1` requirement. Fixed now. Here is an explanation ``` For[i=0, i-- ,]; (* i is the number of days AFTER today. Hence, we decrement it. *) For[i=0, DatePlus@i-- ,]; (* If no reference date is provided, DatePlus will add the given number of days to today's date. The result is a list of 3 integers, luckily in order {year,month,day} *) For[i=0, DatePlus@i--~FromDigits~100 ,]; (* Interpret these as the digits of a base 100 number. The beauty is that FromDigits doesn't care about digits greater than the base and just carries them over. *) For[i=0,(r=DatePlus@i--~FromDigits~100) ,]; (* Store the number in r. *) For[i=0,(r=DatePlus@i--~FromDigits~100)>0 ,]; (* Make sure it's positive. *) For[i=0,(r=DatePlus@i--~FromDigits~100)>0&&!n|r,]; (* And keep going while n does not divide r. *) For[i=0,(r=DatePlus@i--~FromDigits~100)>0&&!n|r,];r~Max~-1 (* Clamp result to -1. *) ``` Note that I've used `|` instead of `∣` in the explanation, because the Unicode one messes with monospacing. [Answer] ## Python 2 - 150 ``` import datetime as d,re def f(n): t=d.date.today() while t: c=int(re.sub("-","",str(t))) if c%n<1:return c try:t-=d.timedelta(1) except:return-1 ``` Thanks @chill0r for suggestion to remove days=, and Jason S for tip that the try block can be reduced to one line. [Answer] ## C# 136 With the revised specs, a function that takes an unsigned int and returns an int. ``` int F(uint n){var d=System.DateTime.Now;int i;try{while((i=int.Parse(d.ToString("yyyMMdd")))%n>0)d=d.AddDays(-1);}catch{i=-1;}return i;} ``` --- 152 characters with variable input/output Taking advantage of the loose input/output requirements, input is to be stored in the variable `n` (currently counting all characters except the integer literal), and output is provided with the variable `s`. ``` class P{static void Main(){var n=4;var d=System.DateTime.Now;string s;try{while(int.Parse(s=d.ToString("yyyMMdd"))%n>0)d=d.AddDays(-1);}catch{s="-1";}}} ``` --- 204 characters with STDIN/STDOUT: ``` using System;class P{static void Main(){int n=int.Parse(Console.ReadLine());var d=DateTime.Now;string s;try{while(int.Parse(s=d.ToString("yyyMMdd"))%n>0)d=d.AddDays(-1);}catch{s="-1";}Console.Write(s);}} ``` [Answer] # T-SQL (2012) - 148 Assumes there is a free variable @n with the n value. ``` declare @ date=getdate()while convert(char,@,112)%@n>0 and'00010101'<@ set @=dateadd(d,-1,@)print iif(convert(char,@,112)%@n=0,convert(char,@),'-1') ``` [Answer] # [Golflua](http://mniip.com/misc/conv/golflua/) ~~90~~ 86 ``` n=I.r()d="%Y%m%d"i=O.d(d)+0j=0@i>0?i%n==0w(i)O.q()$j=j+1i=O.d(d,O.t()-j*86400)+0$w(-1) ``` An ungolfed Lua version would be, ``` n = io.read() d = "%Y%m%d" i = os.date(d)+0 -- implicitly casts os.date(d) to int j = 0 while i>0 do if i % n == 0 then print(i) os.exit() end j = j+1 i = os.date(d,os.time()-j*86400)+0 end print(-1) ``` [Answer] # MATLAB: 61 ``` -1,s=str2num(datestr(1:now,'YYYYmmDD')),d=s(~mod(s,n)),d(end) ``` Assumes the divisor is stored in `n`. The result will be stored in a variable called `ans`. --- Commented version: ``` -1 % Store -1 in ans in case we don't find anything s=str2num(datestr(1:now,'YYYYmmDD')) % Make a list of date numbers d=s(~mod(s,n)), % Select only those who are dividable and prepend -1 d(end) % Store last found value in ans, if anything is found ``` Will generate an error if no result is found, but the answer is still available in the variable despite that. --- Error could be avoided at the cost of 2 extra chars: ``` s=str2num(datestr(1:now,'YYYYmmDD')),d=[-1;s(~mod(s,n))],d(end) ``` [Answer] # PHP (92=85+7) Expects input to be stored in `$n`. ``` for($d=date("Ymd");!($d%$n==0&checkdate($d/100%100,$d%100,substr($d,0,4))|$d<0);$d--);echo$d ``` I just remembered why I do not like PHP anymore=) EDIT: Now the -1 of the specifications is implemented too. [Answer] # JavaScript (ES6) 115 Expects number in variable n, result stored in variable r. Each day is checked, starting with current date and decrementing - there must be a better way. Moreover, using standard javascript date functions, all dates are gregorian down to year 1 (with leap years accordingly wrong before gregorian reform). ``` for(z=new Date,t=n+1;t>n&&t%n;) d=z.getDate(), t=z.getFullYear()*1e4+(z.getMonth()+1)*100+d, z.setDate(d-1); r=t>n?t:-1 ``` [Answer] ## C# - 144 (Or 124 in LINQPad) + 1 for each digit in `n` This expects the input to be in the variable `n`. By the end of the execution the desired value will be in the variable `r`. This considers `00010101` as the first date, though, because the date `00000101` does not exist. Suggestions for improvement are always welcome. ``` class P{static void Main(){int n=7,r;var d=System.DateTime.Now;try{for(;(r=int.Parse(d.ToString("yyyMMdd")))%n>0;d=d.AddDays(-1));}catch{r=-1;}}} ``` LINQPad version: ``` int n=7,r;var d=System.DateTime.Now;try{for(;(r=int.Parse(d.ToString("yyyMMdd")))%n>0;d=d.AddDays(-1));}catch{r=-1;}r.Dump(); ``` [Answer] ## Groovy - 301 300 chars Very simple (and slow), with no tricks to hide the fact that it uses Joda Time. Golfed: ``` @Grab(group='joda-time', module='joda-time', version='2.3') import org.joda.time.* import org.joda.time.format.* f={DateTimeFormat.forPattern("yyyyMMdd").print(new LocalDate().minusDays(it)) as int} n=args[0] as int;b=0;x=-1;c=0 while(!b){if(f(c++)%n==0){x=f(--c);b=1};if(f(0)-c<=101){b=1}} println x ``` Example run (on 7/30/2014): ``` $ groovy D.groovy 7 20140729 $ groovy D.groovy 16 20140720 $ groovy D.groovy 90000 -1 ``` Ungolfed: ``` @Grab(group='joda-time', module='joda-time', version='2.3') import org.joda.time.* import org.joda.time.format.* f = { DateTimeFormat.forPattern("yyyyMMdd").print(new LocalDate().minusDays(it)) as int } n = args[0] as int b = 0 x = -1 c = 0 while (!b) { if(f(c++)%n==0) { x=f(--c); b=1} if(f(0)-c<=101){b=1} } println x ``` [Answer] ## R, 146 139 ``` D=function(n){ z=as.double(gsub("-","",y<-Sys.Date())) d=F while(z>100&!d){ y=y-1 z=as.double(gsub("-","",y)) d=!z%%n} ifelse(z>100,z,-1)} ``` Good luck with a date that doesn't work. `microbenchmark` reports it takes about half a second to go back 15 days. As of July 31, 2014, this will take something like 20 million seconds (~23 days) to spit out `-1`, at least according to the back of the envelope. **edit**: some shortcuts in the comments [Answer] ## Matlab 104 ``` function d=f(v);for d=fix(now):-1:1 d=str2num(datestr(d,'YYYYmmDD'));if~mod(d,v)return;end;end;d=-1;end ``` Ungolfed : ``` function d = f(v) for d=fix(now):-1:1 d = str2num(datestr(d,'YYYYmmDD')); if ~mod(d,v) return; end end d = -1; end ``` EDIT: I managed to optimise it a bit, but @DennisJaheruddin has the real solution [here](https://codegolf.stackexchange.com/questions/35393/when-was-the-last-time-the-date-was-divisible-by-n/35425#35454) [Answer] # Python 3 - 151 148 bytes, generators ``` from datetime import* t=date.today() f=lambda n:next((y for y in(int((t-timedelta(o)).strftime("%Y%m%d"))for o in range(t.toordinal()))if y%n<1),-1) ``` Thanks @nyuszika7h for `import*` suggestion [Answer] ## Ruby 103 ``` require'date' f=->{d=Date.today (s=d.strftime('%Y%m%d').to_i return s if s%n<1 d-=1)while d.year>0 -1} ``` ### Input Expects the divisor value to be present in variable `n`. ### Output The return value of the `f` function Online example: <http://ideone.com/LoYxG4> [Answer] ## Java : 373 chars This is a port of the Groovy answer, and uses Joda Time. Golfed: ``` import org.joda.time.*; import org.joda.time.format.*; public class D { static int f(int i){return Integer.parseInt(DateTimeFormat.forPattern("yyyyMMdd").print(new LocalDate().minusDays(i)));} public static void main(String[] args){ int n=Integer.parseInt(args[0]);int b=0,c=0,x=-1; while(b!=1){if(f(c++)%n==0){x=f(--c);b=1;};if(f(0)-c<=101){b=1;}} System.out.println(x);}} ``` Sample runs (with joda-time-2.4.jar on classpath: ``` $ java D 7 20140729 $ java D 4 20140728 $ java D 16 20140720 $ java D 90000 -1 ``` Ungolfed: ``` import org.joda.time.*; import org.joda.time.format.*; public class D { static int f(int i) { return Integer.parseInt(DateTimeFormat.forPattern("yyyyMMdd").print(new LocalDate().minusDays(i))); } public static void main(String[] args) { int n = Integer.parseInt(args[0]); int b = 0,c = 0,x = -1; while(b!=1) { if(f(c++)%n==0) { x=f(--c);b=1; } if(f(0)-c<=101) { b=1; } } System.out.println(x); } } ``` [Answer] # Bash+coreutils (8.21), 67 bytes ``` seq -f-%gday $[9**9]|date -f- +[pq]sp[_1pq]sq%Y%m%ddA1=qd$1%%0=p|dc ``` * `seq` generates integers from 1 to 99, one per line, and formats it as `-<x>day` * pipe this to `date -f` which interprets each line and outputs the date formatted into a `dc` expression such as `[pq] sp [_1pq] sq 20140728 d A1 =q d 7% 0=p` (spaces added for readability) + `[pq]` define a macro to print the top of stack, then quit + `sp` save macro in register p + `[pq]` define a macro to push -1, print the top of stack, then quit + `sq` save macro in register q + `20140728` embedded date integer + `d` duplicate top of stack + `A1` push 101 (00000101) + `=q` pop top 2 stack values: compare date and 101, and call macro `q` if equal + `7` push divider + `%` pop divider and dividee, the divide and push the remainder + `0` push 0 + `=p` pop top 2 stack values: compare remainder and 0, and call macro `p` if equal + `d` duplicate top of stack + macro `p` is called: prints date integer and quits `dc` entirely * `dc` expressions are piped to `dc` for evaluation. Once `dc` prints the right value and quits, the rest of the pipeline is torn down ### Output: ``` $ ./lastdivdate.sh 4 20140728 $ ./lastdivdate.sh 7 20140729 $ ./lastdivdate.sh 123456 17901120 $ ./lastdivdate.sh 77777 19910912 $ ./lastdivdate.sh 7777777 -1 $ ``` --- Since this program generates integers from 1 to 99, it will be valid up to just over 1 million years into the future. I hope this limitation is acceptable ;-) --- Thanks @WumpusQ.Wumbley for shortening the return of -1. [Answer] **PYTHON: 134 bytes** Not going to be able to beat the current leader, and it's not that much better than the best Python answer, but I decided to post my best Python solution. ``` from datetime import* def y(a,n): s=a.strftime("%Y%m%d") if int(s)%n==0:yield s try:x=y(a-timedelta(1),n) except:yield -1 yield x ``` Ungolfed: ``` from datetime import * def y(a, n): s=int(a.strftime("%Y%m%d")) if s%n==0: yield s try: x=y(a-timedelta(1), n) except: yield -1 yield x ``` [Answer] # JavaScript (ES5) - 94 It expects the input in variable `x`, and places the output in `o`. ``` for(i=Date.now();i>-7e13&&(o=(new Date(i)).toISOString().replace(/-|T.*/g,''))%x;i-=864e5)o=-1 ``` [Answer] ## k4 ~~(84)~~ (73) ``` f:{f d@*|&~.q.mod[(f:{$[^x;-1;.($x)@&~"."=$x]})'d:{"d"$x+!1+"i"$y-x}[-730457;.z.D];x]} ``` This is just an initial cut with the first algorithm that came to mind; I'm sure better is possible in both performance and length. This version hardcodes the "today" part (that's the `.z.D`); change it to a date literal (`yyyy.mm.dd`) or an integer in the q date system (days since January 1, 2000) to run the test cases. (q won't parse date literals earlier than the early eighteenth century, so for dates before that, you'll need to work out the value and use the appropriate integer directly. January 1, "A.D. 0", from the spec, turns out to be `-730457`, which is used in the function code. July 28, A.D. 5, from the last test case, turns out to be `-728450`.) The given test cases: ``` {f d@*|&~.q.mod[(f:{$[^x;-1;.($x)@&~"."=$x]})'d:{"d"$x+!1+"i"$y-x}[-730457;2014.07.30];x]}4 20140728 {f d@*|&~.q.mod[(f:{$[^x;-1;.($x)@&~"."=$x]})'d:{"d"$x+!1+"i"$y-x}[-730457;2014.07.30];x]}7 20140729 {f d@*|&~.q.mod[(f:{$[^x;-1;.($x)@&~"."=$x]})'d:{"d"$x+!1+"i"$y-x}[-730457;2014.07.28];x]}4 20140728 {f d@*|&~.q.mod[(f:{$[^x;-1;.($x)@&~"."=$x]})'d:{"d"$x+!1+"i"$y-x}[-730457;2014.07.28];x]}7 20140722 "d"$-728450 0005.07.28 {f d@*|&~.q.mod[(f:{$[^x;-1;.($x)@&~"."=$x]})'d:{"d"$x+!1+"i"$y-x}[-730457;-728450];x]}90000 -1 ``` edit: ``` g:.,/$`\:`$$:;f:{$[Z=r:{(z>x)&.q.mod[g z]y}[Z:-730458;y]{x-1}/x;-1;g"d"$r]} ``` This is a different approach which uses one of the convergence operators to decrement the date until either it finds a divisible one or it crosses the 1/1/0000 boundary. It also does the conversion from date to integer slightly differently. The test cases, this time all at once: ``` g:.,/$`\:`$$:;{$[Z=r:{(z>x)&.q.mod[g z]y}[Z:-730458;y]{x-1}/x;-1;g"d"$r]}'[2014.07.30 2014.07.30 2014.07.28 2014.07.28,"d"$-728450;4 7 4 7 90000] 20140728 20140729 20140728 20140722 -1 ``` [Answer] **VBA 343 bytes (module)** ``` Sub divD(i As Long) a = Now() b = Format(a, "yyyymmdd") Do While b / i <> Int(b / i) a = DateAdd("d", -1, a) b = Format(a, "yyyymmdd") If b = "01000101" Then MsgBox -1 Exit Sub End If Loop MsgBox b End Sub ``` [Answer] ## PowerShell - 76 This depends on the number being stored in the variable `$n`. ``` try{@(0..$n|%{'{0:yyyyMMdd}'-f(date).AddDays(-$_)}|?{!($_%$n)})[0]}catch{-1} ``` ]
[Question] [ Given an input integer `n > 1`, output an ASCII-art octagon with side lengths composed of `n` characters. See examples below: ``` n=2 ## # # # # ## n=3 ### # # # # # # # # # # ### n=4 #### # # # # # # # # # # # # # # # # #### n=5 ##### # # # # # # # # # # # # # # # # # # # # # # ##### and so on. ``` You can print it to STDOUT or return it as a function result. Any amount of extraneous whitespace is acceptable, so long as the characters line up appropriately. ### Rules and I/O * Input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * You can use any printable ASCII character instead of the `#` (except space), but the "background" character must be space (ASCII 32). * 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. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` 7ÝΛ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f/PDcc7P//zcFAA "05AB1E – Try It Online") **Explanation** ``` # implicit input as length # implicit input as string to print 7Ý # range [0...7] as directions Λ # canvas print ``` See [this answer](https://codegolf.stackexchange.com/a/160031/47066) to understand the 05AB1E canvas. [Answer] # JavaScript (ES6), ~~114~~ ~~106~~ ~~105~~ ~~104~~ 103 bytes ``` n=>(g=x=>v=x*2>w?w-x:x,F=x=>~y?`# `[~x?(h=g(x--))*g(y)>0&h+v!=n|n>h+v:(y--,x=w,2)]+F(x):'')(y=w=--n*3) ``` [Try it online!](https://tio.run/##ZcjBCoJAEADQu19RBDmjboRWB2HWmz8RgWK6FrIbGe4shL@@1TG8Pd69nuqxed4eL6HNtfUdeU0SFDHJiThKpS2s4JyT8lezK6rNKqjOMxfQkwIWAjFS4FDut308rUm/tfwiBydEwmSTFC9xCYx5GCI4siSEjjL0jdGjGdrdYBR0kCIG/5Mt5rCY42JOiP4D "JavaScript (Node.js) – Try It Online") ### How? This builds the output character by character. Given the input \$n\$, we compute: $$n'=n-1\\w=3n'$$ For each character at \$(x,y)\$, we compute \$(h,v)\$: $$h=w/2-\left|x-w/2\right|\\v=w/2-\left|y-w/2\right|$$ The cells belonging to the octagon satisfy one of the following conditions: * (\$h=0\$ OR \$v=0\$) AND \$h+v\ge n'\$ (in red below) * \$h+v=n'\$ (in orange below) For example, with \$n=4\$ (and \$n'=3\$): $$\begin{matrix}(0,0)&(1,0)&(2,0)&\color{red}{(3,0)}&\color{red}{(4,0)}&\color{red}{(4,0)}&\color{red}{(3,0)}&(2,0)&(1,0)&(0,0)\\ (0,1)&(1,1)&\color{orange}{(2,1)}&(3,1)&(4,1)&(4,1)&(3,1)&\color{orange}{(2,1)}&(1,1)&(0,1)\\ (0,2)&\color{orange}{(1,2)}&(2,2)&(3,2)&(4,2)&(4,2)&(3,2)&(2,2)&\color{orange}{(1,2)}&(0,2)\\ \color{red}{(0,3)}&(1,3)&(2,3)&(3,3)&(4,3)&(4,3)&(3,3)&(2,3)&(1,3)&\color{red}{(0,3)}\\ \color{red}{(0,4)}&(1,4)&(2,4)&(3,4)&(4,4)&(4,4)&(3,4)&(2,4)&(1,4)&\color{red}{(0,4)}\\ \color{red}{(0,4)}&(1,4)&(2,4)&(3,4)&(4,4)&(4,4)&(3,4)&(2,4)&(1,4)&\color{red}{(0,4)}\\ \color{red}{(0,3)}&(1,3)&(2,3)&(3,3)&(4,3)&(4,3)&(3,3)&(2,3)&(1,3)&\color{red}{(0,3)}\\ (0,2)&\color{orange}{(1,2)}&(2,2)&(3,2)&(4,2)&(4,2)&(3,2)&(2,2)&\color{orange}{(1,2)}&(0,2)\\ (0,1)&(1,1)&\color{orange}{(2,1)}&(3,1)&(4,1)&(4,1)&(3,1)&\color{orange}{(2,1)}&(1,1)&(0,1)\\ (0,0)&(1,0)&(2,0)&\color{red}{(3,0)}&\color{red}{(4,0)}&\color{red}{(4,0)}&\color{red}{(3,0)}&(2,0)&(1,0)&(0,0)\end{matrix} $$ [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 5 bytes ``` GH*N# ``` My first answer with Charcoal! Explanation: ``` GH*N# //Full program GH //Draw a hollow polygon * //with 8 sides N //of side length from input # //using '#' character ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9nuXv96zQer9nnfL//8YA "Charcoal – Try It Online") [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~15~~ ~~14~~ 12 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` /⁸⇵╷+×+:⤢n╬┼ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjBGJXUyMDc4JXUyMUY1JXUyNTc3KyVENyV1RkYwQiV1RkYxQSV1MjkyMiV1RkY0RSV1MjU2QyV1MjUzQw__,i=NQ__,v=8) Explanation: ``` / a diagonal of length n ⁸ the input, ⇵ ceiling divided by 2, (storing the remainder) ╷ minus one #× repeat "#" that many times + append that to the diagonal :⤢n overlap that with its transpose ╬┼ quad-palindromize with the overlap being the remainder stored earlier ``` [Alternative 12-byter](https://dzaima.github.io/Canvas/?u=JXVGRjBGJXUyMDc4JXUyMUY1KyVENyV1RkYxMSV1MjU0QiV1RkYxQSV1MjkyMiV1RkY0RSV1MjU2QyV1MjUzQw__,i=Mw__,v=8). [Answer] # [R](https://www.r-project.org/), ~~122~~ ~~117~~ 115 bytes ``` function(n){n=n-1 m=matrix(0,y<-3*n+1,y) v=t(h<-(w=3*n/2)-abs(row(m)-1-w)) m[h*v&h+v-n|h+v<n]=' ' write(m,1,y,,"")} ``` [Try it online!](https://tio.run/##DcyxDsIgEIDhnadoOti7lotSHeFJjEM1Ehi4JhTBRn12ZPmHb/hjtZ2mal/8SH5lYPywYVIimLCk6N9wkrum88iTkjuKbBI4TVBMo@OMtNw3iGuBgKSoIIpwdWM@uCkTf1s138zQDaJEn54QZLtI2ff4qxZmFBYuWP8 "R – Try It Online") Ports the logic from [Arnauld's answer](https://codegolf.stackexchange.com/a/175424/67312), specifically [this revision](https://codegolf.stackexchange.com/revisions/175424/4) in case there are further improvements. Another 2 bytes saved thanks to Arnauld's suggestion of inverting the logic! [Answer] # [Python 2](https://docs.python.org/2/), 96 bytes ``` a=b=n=input() while a>2-n-n:a-=1;b-=a/~-n+1;s=(-~b*' '+'#').ljust(n);print s+s[-1]*(n-2)+s[::-1] ``` [Try it online!](https://tio.run/##DcexCsMgFAXQvV8hdFAjr0GHDsrrj5QOCoEYwo1UQ@iSX7fZzim/Nm9wvUdODM4oe1P6dsx5nUR8OQLBR2IbEnEcT4KxobKiMw1SSCPvUj/WZa9NQYfyzWiimvom@xkUyOnL3l/r/fkH "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 81 bytes ``` a=d=n=input()-1 while a<=n:print' '*a+'#'+' #'[a==n]*(3*n-a+~a)+'#';d-=1;a-=d/n+1 ``` [Try it online!](https://tio.run/##FclLCoAgEADQfacQWowfJKxW2ZwkWgwYKMQkYUSbrm70ti8/JR7c10oYkDFxvopU1jV3TPsmaEae8pm4gABNBlowIFpYCJFXLQfNlsxL6h8fLDpPFkPHxtU6fg "Python 2 – Try It Online") --- **[Python 2](https://docs.python.org/2/), 75 bytes** ``` a=d=n=input()-1 while a<=n:print' '*a+`' `'[a==n]*(3*n-a+~a)`;d-=1;a-=d/n+1 ``` [Try it online!](https://tio.run/##BcFLCoAgEADQfadw5w8Jq1U2J4nAAQOFmCSMaNPVp/fq2/JJAzNCAoJC9W5KO989uRy7wAVorlehJoU0aKMUUa4IQJtRoyGH9kMdQ3LgAzpIPVnPPP0 "Python 2 – Try It Online") If mixing output characters is OK. [Answer] # Powershell, 91 bytes ``` param($n)($s=' '*--$n+'#'*$n+'#') --$n..0+,0*$n+0..$n|%{' '*$_+"#$(' '*(3*$n-2*$_+2))#"} $s ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~107~~ 97 bytes ``` param($n)($z=$n-1)..1+,0*$n+1..$z|%{" "*$_+"#"+($x=" "*($z-$_))+(" ","#")[!($_-$z)]*($n-2)+"$x#"} ``` [Try it online!](https://tio.run/##FcpBCoMwEEbhq9TxL8w4JjSlW09SJLgQXNhU7KKS6tmncfn43vL@jutnGufZbBnW4cVIwsgdkgvifdD21iBp8B55v/7oQg2iUk3K2Lozy@0QRZRLtUXkWTGiQ5a@YHJ3UcJW02Fmjz8 "PowerShell – Try It Online") If there was a cheap way to reverse the first half, this answer would feel a lot better. It builds the left half, then the core (which is either x `#'s` or spaces), then mirrors the left's logic to make the right. Fun fact, you don't need to copy over trailing white-space. Unrolled and explained: ``` param($n) ($z=$n-1)..1 + ,0*$n + 1..$z |%{ #Range that repeats 0 n times in the middle " "*$_ + "#" +($x=" "*($z-$_)) + #Left side (" ","#")[!($_-$z)]*($n-2) + #Core that swaps when it's the first or last row "$x#"} #Right side which is left but backwards ``` [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") ``` (' '@~5 6∊⍨1⊥⊢∘,)⌺3 3⊢<(⍉⌽⌊⊢)⍣2∘(∘.+⍨∘⍳¯2+3×⊢) ``` This solution was provided by Adám - thanks! [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X0NdQd2hzlTB7FFH16PeFYaPupY@6lr0qGOGjuajnl3GCsZAno3Go97ORz17H/V0AXmaj3oXGwEVaACxnjZQD5B@1Lv50HojbePD00EK/qc9apvwqLfvUd9UT/9HXc2H1hs/apsI5AUHOQPJEA/P4P9pCkZc6roKQKjOlaZgjMQ2AQA "APL (Dyalog Unicode) – Try It Online") ## My (almost) original solution: # [APL (Dyalog Unicode)](https://www.dyalog.com/), 61 [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") ``` (((⊃∘' #'¨1+5∘=+6∘=)⊢)1⊥⊢∘,)⌺3 3⊢<(((⊖⌊⊢)⌽⌊⊢)(∘.+⍨(⍳¯2+3×⊢))) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbBA0NjUddzY86ZqgrKKsfWmGobQpk22qbgUjNR12LNA0fdS0F0kC@juajnl3GCsZAng1Y27RHPV0gJY969kJZGkBletqPeldoPOrdfGi9kbbx4ekgcU1NoG0KRlzqugpAqM6VpmCMxDYBAA "APL (Dyalog Classic) – Try It Online") Thanks to Adám for his help! The idea is to find the "diamond" that lies partly in the square and apply an edge-detect filter to "outline" the octagone. [Answer] # [C (clang)](http://clang.llvm.org/), `-DP=printf(` `-DF=for(i` ~~+ 179 = 199~~ 180 bytes ``` i;*m="%*s%*s\n";g(n){P"%*s",n,H;F;--i;)P H;P"\n");}f(n){g(n);F;--i;)P m,i,(H,3*n-i+~i,H;F-2;i--;)P"#%*s\n",3*n-3,H;F;--i;)P m,n-i,(H,n+i+i-1,H;g(n);} ``` [Try it online!](https://tio.run/##TYzBCoMwEETv/QqJFBLNHqrtacmtSI5@QC8iRBZ0W7Q3sZ/edGMPLSzDsPNmeujHjocYCYvJqWOxyN1Y4aDZrG16KMvWY4MAhKbNPLZKAINbSEjifuFkyWpv64KByhelHlRIABKq/Du9p/X/5GQFTz0uqSQ4SbbPbpH4mU0dsTbrIejKoGi963nXS4LefRi7YYlwbd1jlkrQ4r1TuTJiGhfusybHHw "C (clang) – Try It Online") Ungolfed: ``` f(n){ int i; printf("%*d",n,0); for(i=0;i<n-1;i++){ printf("0"); } printf("\n"); for(i=1;i<n;i++){ printf("%*d%*d\n",n-i,0,n+i+i-1,0); } for(i=0;i<n-2;i++){ printf("0%*d\n",n+n+n-3,0); } for(i=n-1;i>0;i--){ printf("%*d%*d\n",n-i,0,n+i+i-1,0); } printf("%*d",n,0); for(i=0;i<n-1;i++){ printf("0"); } } ``` -19 bytes thanks to @ceilingcat [Answer] # [Python 2](https://docs.python.org/2/), 130 bytes ``` def f(n): a=[' '*~-n+n*'#'] b=[' '*(n-i-2)+'#'+' '*(n+2*i) +'#'for i in range(n-2)] return a+b+['#%*s'%(3*n-3,'#')]*n+b[::-1]+a ``` [Try it online!](https://tio.run/##PY7LCoMwEEX3fsWASB5jFo10E@iXSBaRmnZARol20U1/PU2wdHnPfXC39/Fc2eZ8nyNEyco1EG6jAKE/hpG1aIVvYDqRZEPGKiwQT41Wk4IK4pqAgBhS4MdcklaVYpqPV2IIOOEo2k7vopODZjP0paK8ZpxG58zFY8j/BdsP/bUc2RLxAdRAdZbqREnK/fiSvw "Python 2 – Try It Online") On mobile, so not incredibly golfed. [Answer] ## Batch, 260 bytes ``` @echo off set s= for /l %%i in (1,1,%1)do call set s= %%s%% echo %s% %s: =#% call:c %1,-1,3 for /l %%i in (1,1,%1)do echo #%s:~2%%s%%s:~2%# call:c 3,1,%1 echo %s% %s: =#% exit/b :c for /l %%i in (%*)do call echo %%s:~,%%i%%#%%s:~%%i%%%s%%%s:~%%i%%# ``` Outputs two leading spaces on each line. Explanation: Batch has no string repetition operator, limited string slicing capability and requires separate statements to perform arithmetic. It was therefore golfiest to make up a string of the input length in spaces (Batch can at least translate these to `#`s for the top and bottom lines) and then slice from or to a specific position ranging from 3 to the length to generate the diagonals (this is what the last line of the script achieves). [Answer] # [Ruby](https://www.ruby-lang.org/), 96 bytes ``` ->n{[*(n-=2).step(z=n*3+2,2),*[z]*n,*z.step(n,-2)].map{|x|([?#]*2*('# '[x<=>n]*x)).center(z+2)}} ``` [Try it online!](https://tio.run/##NcuxDoMgEADQXzFx8O4EhmvSqdgPIQza4NYLUUwoyrfToen88rZj@bTVNj3J6QhEW0azpxChWKHbyIpRkSueRFH5iSjN6M17jueVL3DP3hMTDH03uPywk3jKiOYVJIUNyshYawM25o7/FI@0d6vLvrYv "Ruby – Try It Online") Not very golfed yet. Might golf if I find the time. [Answer] # [Red](http://www.red-lang.org), 171 bytes ``` func[n][c:(a: n - 1)* 2 + n b: collect[loop c[keep pad/left copy"^/"c + 1]]s: 1x1 s/1: n foreach i[1x0 1 0x1 -1x1 -1x0 -1 0x-1 1x-1][loop a[b/(s/2)/(s/1): #"#"s: s + i]]b] ``` [Try it online!](https://tio.run/##PYxBCoMwEEX3OcVHN9oicWy7yTG6DSloTKhUkqAW7OntFKmbx2P@8CbXb3fXayO82vw7WB2MtqpoFQIqUHlCgzOC6BRsHEdnFz3GmGD1y7mE1PZydH7hMX2yh8wsf5MxswKthFkSh4SPk2vtE4OmtQah5qmiHTWDDwximL3e6k4Ws2zKH6lUyLM84@bM9cGYzmxpGsICj0b87XLY9bCb2L4 "Red – Try It Online") ## Explanation: ``` Red[] f: func [ n ] [ a: n - 1 ; size - 1 c: a * 2 + n ; total size of widht / height b: collect [ ; create a block loop c [ ; composed of size - 1 rows keep pad/left copy "^/" c + 1 ; of empty lines of size c (and a newline) ] ] s: a * 1x0 + 1 ; starting coordinate foreach i [ 1x0 1 0x1 -1x1 -1x0 -1 0x-1 1x-1 ] [ ; for each offset for the 8 directions loop a [ ; repeat n - 1 times b/(s/2)/(s/1): #"#" ; set the array at current coordinate to "#" s: s + i ; next coordinate ] ] b ; return the block ] ``` [Answer] # **Perl 5, ~~201~~ ~~197~~ ~~188~~ ~~187~~ 186 bytes:** ``` $a=<>;$b=3*$a-4;$c='$"x($e-$_)."#".$"x$f."#\n"';$e=($b-$a)/2+1;$d=$"x$e."#"x$a.$/;$f=$a;print$d,(map{(eval$c,$f+=2)[0]}1..$a-2),("#".$"x$b."#\n")x$a,(map{$f-=2;eval$c}reverse 1..$a-2),$d ``` [Try it online!](https://tio.run/##PY3hCoIwFIVfJdYBt3QzV/5a60UqYuodBCayQoTw2Zci9e8e7vnO11Noyxjh7OlsUNnDDk4eDWqbgI0cJHEXim2ZmiP8fF07lhiQ5agknMh1Whg0dnnTUhzhFHIDb@FMHx7dG03Gn67/cBpcizqDT60Wl/1tKpSadVpk/GeoVoOYV1YIXlptVnIKNFB40ebPoYmx/AI "Perl 5 – Try It Online") Reads the size of the octagon from first line of `STDIN`. [Answer] # **Perl 5, 176 bytes** ``` $f=$a=<>;$b=3*$a-4;$c='$"x($e-$_)."#".$"x$f."#\n"';$e=$a-1;$d=$"x$e."#"x$a.$/;print$d,(map{(eval$c,$f+=2)[0]}1..$a-2),("#".$"x$b."#\n")x$a,(map{$f-=2;eval$c}reverse 1..$a-2),$d ``` Based on Nathan Mills' answer above (which I have insufficient rep to comment on!). `$e` can be simplified to `$a-1` saving 6 bytes; `$f` can be chain assigned; saving two bytes; Not sure where the other two come from! While `$e` can be replaced with `$a-1` in the two places it occurs, the extra brackets needed means this only breaks even. **Ungolfed:** ``` $f = $a = <>; $b = 3 * $a - 4; $c = '$"x($e-$_)."#".$"x$f."#\n"'; $e = $a - 1; $d = $" x $e . "#" x $a . $/; print $d, ( map { ( eval $c, $f += 2 )[0] } 1 .. $a - 2 ), ( "#" . $" x $b . "#\n" ) x $a, ( map { $f -= 2; eval $c } reverse 1 .. $a - 2 ), $d ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~76~~ 73 bytes *-3 bytes thanks to Jo King* ``` {(' 'x$_-1~\*x$_,{S/.\S(.)+/* {' 'x$0}*/}...*)[^$_,$_ xx$_-2,[R,] ^$_;*]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkNdQb1CJV7XsC5GC0jrVAfr68UEa@hpautrKVSDJQ1qtfRr9fT0tDSj44AqVOIVKkA6jHSig3RiFYBC1lqxtf@LEysV0jRU4jX1svIz8zSUYvKUNBXS8osUjPT0TK3/AwA "Perl 6 – Try It Online") Returns a list of lines. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~158~~ ~~153~~ 150 bytes * Saved ~~five~~ eight bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` O,c,t,g;o(n){for(O=2*~-n,t=c=O+n;t--;puts(""))for(g=c;g--;)putchar(33-(!t|t>c-2?g<n-1|g>O:t<n-1|t>O?t+O-g&&t-O-g&&~c+g+t+n+n&&c-g-t+n-3+n:g&&g<c-1));} ``` [Try it online!](https://tio.run/##RY6xEoIwEES/RQom8XIFUGkI9GnyDczNeFp4OHhWIr@OAQur3Xn7iiVkonVNjpw69qMR@76Mk0mhPi4oTgOFBOIV0T9e@jRFYe0mcCDPGdpM6TpMpmnQHHTWjrDuuRWsZu7SWfemXeoVEnJZKu6xEDAoCEhZEjLmig3IOU/cElbW@s96H25i4u9RDLWP7en/YjQRYLO@ "C (gcc) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `RM`, 4 bytes ``` S7ø∧ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJSTSIsIiIsIlM3w7jiiKciLCIiLCI1Il0=) new canvas builtin go brr [Answer] # [Python 3](https://docs.python.org/3/), 224 bytes ``` n=int(input()) z=" "*(n-1)+"#"*n+" "*(n-1) print(z) for i in range(n-2):print(" "*(n-i-2)+"#"+" "*(i*2+n)+"#") print((("#"+" "*(n*3-4)+"#\n")*n)[:-1]) for i in range(n-3,-1,-1):print(" "*(n-i-2)+"#"+" "*(i*2+n)+"#") print(z) ``` [Try it online!](https://tio.run/##lY27DgIhEEV7voJgw4AULCYmm@yXqIWFj2nuEoKF/DyCq1vZmExz59xHfOb7jFArJkbWjPjImkiUSUllNJwnqzbKwK5axNSthcR1TpIlQ6YzbpcGBxoX@DFz@/T4EmYzWLz1t0PrFcIEt@vwCEUGdBidP/2YCFvn2/05VKjW/Qs "Python 3 – Try It Online") [Answer] # Perl 5, ~~170~~ ~~168~~ 166 bytes ``` $a=<>-1;$\="#\n";print$x=$_=$"x$a."#"x$a;if(s/^( *) #*/$1 # $1 /){print}while (s/ #/# /){print}$z=$_;for(1..$a){print$_=$z}while(s/# (\s{$a})/ #$1/){print}print$x ``` This works by the magic of regex. The "if" is only needed to deal with the pathological case of n=2, which otherwise outputs something like: ``` ## ## # # ## ``` probably this can be coded away. I think there may be a lot more to gain by creating a string up to the mid-point then reversing it. Of course we then need to insert/delete an extra space if n is odd (or use thin-space :p). **Ungolfed** ``` $a = <> -1; # Subtracting one is very useful! $\ = "#\n"; # Every line ends with a '#' let perl provide. $x=$_ = " " x $a. "#" x $a; # The horiz line (one short) print; # print it plus the extra # if(s/^( *) #*/$1 # $1 /){print} # create a hole and remove a leading space(if n=2 this fails) while (s/ #/# /){ # make the hole bigger print; # and print (with a trailing #) } $z=$_; # store $_ for later use for (1 .. $a) { # nice that we don't have to do 2..$a but not golf-nice $_ =$z; # restore $_ (we could use $z but since we have print; # to restore somewhere, doing it here saves us bytes) } while (s/# (\s{$a})/ #$1/){ # now move the # to the right and reduce the trailing spaces print; } print $x; # and finish... ``` I think this can probably be golfed a bit more, quite apart from significant changes like pushing onto `$@` and printing that at the end. [Golfed spaces around `..` and moved print before assigns in two cases, saving on semicolons.] [Answer] # J, ~~59~~ ~~45~~ 41 bytes ``` h=.|.,],~,:@{.#~_2+# ' #'{~h@|.@|:@h@=@i. ``` [Try it online!](https://tio.run/##y/r/P8NWr0ZPJ1anTsfKoVpPuS7eSFuZK81WT11BWb26LsOhRs@hxsohw8HWIVPvP1dqcka@QpqCEYxhDGOYwBim/wE "J – Try It Online") Will add explanation tonight. [Answer] # Perl 5, 98 bytes ``` $_=2x$_.1x$_.$/;s/2//;s/.$/ #/,y/1/ /while$a.=$_,$b=$_.$b,s/2[#1]/# /;$_=$a.$_ x("@F"-2).$b;y/2/ / ``` [TIO](https://tio.run/##FYxBCsIwEEX3OUVoZqGQdki0qyHgykuIhAQKFqoNVrC5vONk8/jwH69M72XkZ4VEgkwMMfgd4uAaAGlDj42ytUFb0aHG72NeJkhDgGghh2ZmK@bNuDsajSQVuSHq/dBdrl3vj2JQlZZG5pNSZ6X8by2feX1t3Jf0Bw) ]
[Question] [ My first code golf question post! Hope u like it ;-) The task is simple. Write either an stdin-stdout program or a function. Input is a 2D array which contains only either characters or the integer `0`. You are allowed to replace the integers with the character `'0'` or `null` instead in any language (kudos to @SuperStormer for suggesting the "any" part) if you think it makes the problem easier or allows for decreasing code length. Each element of the array contains `0`, `'>'`, `'<'`, `'^'`, `'v'`, or `'x'`. You play golf in the grid by starting at the indices `(0,0)`, and then moving in the direction indicated by the arrows. There is always an arrow at `(0,0)`. `0` is the no-op. The code stops when you get to `'x'`, the golf hole. Each of the arrows that you encounter represents a stroke in golf. However, obviously not all arrows will be used. Your mission is to find how many strokes you did before you get to the hole. TL;DR: Find the number of arrows in your path from `(0,0)` to `'x'`. Examples: ``` [['>',0,0,'v','<'],[0,'>','x','<',0]] > 0 0 v < 0 > x < 0 ``` gives `3`. ``` [['v',0,'>','v',0,0,0],[0,0,0,'>','v',0,0],['>',0,'^',0,'v',0,0],['>',0,0,0,'x','<','<'],[0,0,0,0,0,0,'^']] v 0 > v 0 0 0 0 0 0 > v 0 0 > 0 ^ 0 v 0 0 > 0 0 0 x < < 0 0 0 0 0 0 ^ ``` gives `8`. You do not need to consider handling cases which do not correspond to the input requirements. Example code: (Python 3.8, 149 bytes, and yeah I'm so noob...) ``` def f(g): x=y=r=0 while 1: if(n:=g[x][y])=='x':return r if n:a,b=(0,1)if n=='>'else(0,-1)if n=='<'else(-1,0)if n=='^'else(1,0);r+=1 x+=a;y+=b ``` Have fun golfing! Additional note: Changing the input values to things like "12345" is allowed if you are able to take advantage of language features by doing so. However you must mark your answer and the input code you used if you choose to do so ;-) Additional additional note: Thanks to Unrelated String for this. "The next stroke taken is always the closest in the direction". [Answer] # JavaScript (ES6), 67 bytes Expects a matrix filled with `0` for no-op and the ASCII codes of the other characters. ``` f=(m,x=y=0)=>(q=m[y][x])-120&&(q?c=q:0)/c+f(m,x+c%3-1,y+=~-c%5%3-1) ``` [Try it online!](https://tio.run/##fY7baoNAEIbvfYq5ibOLqzUNvSkZQ@hjyBZka5KWeJZFb/LqdneTWATpwMAc/vnm/8l01qn2u@7DsvrKp@lErBADjRRzSlhDRTrKdJA83L7Gvs@ag6LmPeYvKjhZYaA2u3ArxoBuodq82YZPfd71QFAAJWBUUZHVrLVN60ptSw2@DzpSl6z9MI@PPeMmPE9VZVdd8@hanZnlsNQDSDFBATG4RI0C9yiFXbiBWeLghlYgPfkPSN9B7kb/Qe3dDJw/LUV3wdMKfuJsZ1UwUx7WFp7X0hCd9@kX "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 62 bytes Using the custom mapping of `<^>vx0` to `[-1,0,1,2,3,4]`. ``` f=(m,x=y=0)=>(q=m[y][x])-3&&(q<3&&(c=q,1))+f(m,x+c%2,y+=~-c%2) ``` [Try it online!](https://tio.run/##fY5NCoMwEIX3niII1QSjpO3WyRV6AIkg/hSL8Z8QN726NVaLC@nihcm8xzfvlahkSPuyHf26yfJ5LgBLqmECRoDjDmQ0iUgL4t8dB3eheVPo6JUQrzBJL73c6OTB218GMo/5MCJAEgFHix/IpMW9@fTrqMxohzFXmtlBWWe5fhRYEeSjhUgsK23qoanyoGqe2LBwZCEUudylLtukFoWuoKthFsbU69IEhCX@gNQG4RuI/XQAstPQFtirxIc6p4Fde7Xw7MRR8bf7/AE "JavaScript (Node.js) – Try It Online") [Answer] # Excel (ms365), ~~119~~, 116 bytes -3 Bytes thanks to @[JosWooley](https://codegolf.stackexchange.com/questions/263013/code-golf-for-golf/263022?noredirect=1#comment576209_263022) [![enter image description here](https://i.stack.imgur.com/3tpGK.png)](https://i.stack.imgur.com/3tpGK.png) [![enter image description here](https://i.stack.imgur.com/PxkDD.png)](https://i.stack.imgur.com/PxkDD.png) Formula in `I1`: ``` =Z(A1,A1,0) ``` --- **Explaination**: `Z()` refers to a custom function: ``` =LAMBDA(i,s,c,LET(y,IF(i=0,s,i),IF(i="x",c,Z(OFFSET(i,SWITCH(y,"^",-1,"v",1,),SWITCH(y,"<",-1,">",1,)),y,c+(i>0))))) ``` This is a recursive `LAMBDA()` with 3 parameters: * The starting cell as 'i'; * The starting direction as 's'; * The starting count as 'c', being zero at the 1st iteration. If the current cell ('i') equals 'x' the recursion stops and the function will output the current value of 'c'. If the current cell <> 'x' this means we need to call `Z()` and use the new cell as 'i' which is acquired via `OFFSET()` using the current direction. The 's' will always be equal to the 'y' parameter found while we need to add one to our counter 'c'. [Answer] # [Python](https://www.python.org), 82 bytes *-12 bytes thanks to Jonathan Allan* ``` f=lambda g,w,a=0,x=0:(n:=g[x])<119and(n>0)+f(g,w,a:=[a,n%3+n//14%3*w+~w][n>0],x+a) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3A3ISc5NSEhXSdcp1Em0NdCpsDaw08qxs06MrYjVtDA0tE_NSNPLsDDS10zTAaqxsoxN18lSNtfP09Q1NVI21yrXrymOjgUpidSq0EzWh5p5KV7BViDYz0lEwACNDQwsdBTMIGyRqaGQA5cdyFRRl5pVogMw31dTkygBpBCuHKYWywYgLzkKT41KAWmZpgrAQVQbqEpjNZiimwZGlCcJFGTrmmlAfLVgAoQE) [Takes input as a flattened list of codepoints, plus the width of a row.](https://codegolf.meta.stackexchange.com/a/17117) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 43 bytes ``` WS⊞υιP⪫υ¶≔⁰θW⌕x <v>^KK«F‹¹ι«≔⊗ιφ≦⊕θ»M✳φ»⎚Iθ ``` [Try it online!](https://tio.run/##LY5Ba8MwDIXP9q8QOcmQQXdeCIyWQcsCgV1HwEuUxsyzU9vJCqO/3bPbCISe3oNP6ifpeit1jL@T0gR4NPMSPoJT5oxCQLv4CZcSlHjhzaKDmlMS8GSVyXbxaQqRolfv1dngroRL2jbUmzIDFleo1rorSmiJvhNSwB9no3WA7@Q9Pmf23WMb5GCXL00DKlHCmGiMNXLesqPpHf2QCTQ8TrEbZ41dCQ/KUR@UNTjmh258r0k6TLK9f7yXPuAlRTGuUK8AwFNnwWvo4DEBrlWV/VQdj0@r/gc "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings of spaces, arrows and an `x`. Explanation: ``` WS⊞υιP⪫υ¶ ``` Copy the input to the canvas without moving the cursor. ``` ≔⁰θ ``` Start with `0` strokes. ``` W⌕x <v>^KK« ``` Repeat until the ball goes in the hole. ``` F‹¹ι« ``` If the current character is an arrow, then... ``` ≔⊗ιφ ``` ... change the current direction, and... ``` ≦⊕θ ``` ... increment the number of strokes. ``` »M✳φ ``` Move the cursor in the current direction. ``` »⎚Iθ ``` Output the final count. [Answer] # [Rust](https://www.rust-lang.org), 189 bytes ``` |a|{let(mut c,mut d)=((0,0),(0,0,0));loop{d=match a[c.0 as usize][c.1 as usize]{60=>(0,-1,d.2+1),62=>(0,1,d.2+1),94=>(-1,0,d.2+1),118=>(1,0,d.2+1),120=>break d.2,_=>d};c=(c.0+d.0,c.1+d.1)}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZBLboMwEIb3nMLNprYyIBulhASZHgRZlctDRQESgb0poRfphkV7jB4kt-kQkjSqxprx_9nzsD-_WtuZ8fRYNKTWZUMZ6R2nyg0ptkVDk8SG0VpFT4q5sQ2J_LamcMPTz1Efe7xFa2tICpPPmKSUA2cweYwsqvb7Q5_JWpv0jegk9TjRHbFd-Z4rVOJP9QGXMea5AjLPXwoGgX8GN71ZocZjfgVChEjugY81Xttc7wgSeJFxNkSppNh2mXkcsCFGwYbh8oiPyHEObdmYqnmgi377PCyAFPhmLI1lAx_mDZqC5BzvICIUHAdD949NhuNAMK1b7myblVL4N85linGc4y8) Hate needing to do explicit type conversions from signed to unsigned. Takes input as ASCII character codes. # [Rust](https://www.rust-lang.org), ~~147~~ 143 bytes ``` |a,b|{let(mut c,mut d)=(0,(0,0));loop{d=match a[c as usize]%9{6=>(-1,d.1+1),8=>(1,d.1+1),4=>(-b,d.1+1),1=>(b,d.1+1),3=>break d.1,_=>d};c+=d.0}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY9LboMwEIb3nGIaqZLdDJGdkBSCTA-CUGUeVlCBRGB3UcIZeoBuWLSHym1qmjRN9f-amW9m5MfHZ2s6PZ4eVAO1LBtCoXecqtCgtqohsfHD1TrBsivfCupGxgfxZbRy_dP7UWJ67O0qqY2GDKeYU0EYWjNKw2q_P_S5qKXOdiDjDGQHZjoouQ_6jYiIyzFf8Dmn6Fu6gjeN0l_ilq6wElHaFvIFLOOziPIhzOYiX7BhuDzrNXScQ1s2umruyKzfPg0zBEVizn1kuFniufjTTcuWDAPPhn-dSXxp4ce3CrwEH-1Pncvt43jO3w) Same as above but takes input as a flattened array and length [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 225 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 28.125 bytes ``` 00"£{?¥ṘÞi:\x≠|¨^÷N":∑¬ß_:&+}!‹ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyI9IiwiIiwiMDBcIsKjez/CpeG5mMOeaTpcXHjiiaB8wqhew7dOXCI64oiRwqzDn186Jit9IeKAuSIsIiIsIltbJz4nLCcwJywnMCcsJ3YnLCc8J10sWycwJywnPicsJ3gnLCc8JywnMCddXSJd) Less of a mess than before. Takes `0`s as `"0"` ## Explained ``` 00"£{?¥ṘÞi:\x≠|¨^÷N":∑¬ß_:&+}_!­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁢⁤​‎‏​⁢⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏‏​⁡⁠⁡‌⁣⁤​‎‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏‏​⁡⁠⁡‌⁤⁡​‎‏​⁢⁠⁡‌⁤⁢​‎‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏‏​⁡⁠⁡‌­ 00"£ # ‎⁡Put the list [0, 0] into the register. The register will act as the current character pointer { | # ‎⁢While: ¥ṘÞi # ‎⁣ Indexing the register ? # ‎⁤ Into the input :\x≠ # ‎⁢⁡ Does not give "x" (leaving an extra copy of the retrieved character) | # ‎⁢⁢Do: ¨^ # ‎⁢⁣ Convert the retrieved character to the offsets that character represents. E.g. > maps to [1, 0] as it indicates incrementing the x coordinate. # ‎⁢⁤Characters not in "^<>v" are mapped to [0,0] ÷N" # ‎⁣⁡ Due to a goofy logic bug, ^ and v have their y-offset inverted, so un-invert it :∑¬ # ‎⁣⁢ Check whether the sum of the offsets is not 0 (i.e. that the character is indeed a direction arrow) ß_ # ‎⁣⁣ If it isn't a direction arrow, ignore the direction of the character. Otherwise, leave the offsets on the stack :&+ # ‎⁣⁤ Add whatever offset is on the top of the stack (either a new arrow or the previous direction) to the register. This leaves a copy on the stack. # ‎⁤⁡This act of leaving the copy on the stack is how the number of arrows is determined. Every time an arrow is encountered, it's direction is pushed permanently to the stack. _! # ‎⁤⁢Remove the last item (which will be "x" due to the nature of the while loop stopping with an extra copy) and then push the length of the stack. 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Racket](https://racket-lang.org/), 233 bytes ``` (display(let P([L(read)][x 0][y 0][X 0][Y 0][H 0][a add1])(match(list-ref(list-ref L y)x)['x H]['>(P L(a x)y 1 0(a H)a)]['<(P L(- x 1)y -1 0(a H)a)]['^(P L x(- y 1)0 -1(a H)a)]['v(P L x(a y)0 1(a H)a)][_(P L(+ x X)(+ y Y)X Y H a)]))) ``` [Try it online!](https://tio.run/##VY1PC4JAEMXvfYoXHZwhhPUunj148KgsGkMaRQZhEruf3mbtj8Rj3zzmx7wd5Xjtp3m3Hd@BusvjPoinoZ9Qki1o7KXjxjqYxvpgVbA6WB5MIF2XNEw3mY5nGi6PKR770y@ggGfHNnLIGxtlVKIggWOPBEZTzqL9UbqAGA6JoviPtYHBKdUjNkpX9vww0W8MVnBY@vbaV7EOj5or1MihkJnnmegJgwzBVbwBLeG7CotMQ6vvbxHkkCJdT95qmV8) Input is a two-dimensional [list](https://docs.racket-lang.org/guide/pairs.html) of [symbols](https://docs.racket-lang.org/guide/symbols.html): ``` ((> > 0 0 0 v) (v < 0 ^ < 0) (0 ^ 0 0 > V) (> 0 v 0 x <) (0 0 > 0 ^ 0)) ``` (That is, you don't need to use double quotes. Racket lists use parentheses `()` instead of brackets `[]` and don't use commas `,`.) Output is displayed on STDOUT. If the ball hits the edges, the program crashes with an `index too large` error. --- ## Changelog 1. Removed `#!racket` (`-9` bytes). Thanks a lot [@SuperStormer](https://codegolf.stackexchange.com/users/70761/superstormer)! --- ## Explanation Our program consists of a recursive function. At the initial run, we receive inputs and configure the initial variables. Note that for the golfed version I added an extra variable `a` that is shorthand for `add1`. It isn't necessary for the explanation. ``` (let program ([lst (read)] [x 0] [y 0] [dx 0] [dy 0] [hits 0]) ...) ``` * `lst` is the [input list](https://docs.racket-lang.org/reference/reader.html#%28part._parse-pair%29). * `x` and `y` are the indices at which the ball is currently at. * `dx` and `dy` are the directions that the ball is traveling to. + Used when a `0` or any unrecognizable symbol is seen. * `hits` are the number of hits/strokes that have occurred. We then use [Racket's `match` statement](https://docs.racket-lang.org/guide/match.html) to determine the action we must do. The first argument of the `match` statement is the symbol we are matching to. To get the current symbol we can think of the two-dimensional list as a table of rows and columns. Each row is selected with the `y` variable and inside of the row are columns which are selected with the `x` variable. ``` (let program ([lst (read)] [x 0] [y 0] [dx 0] [dy 0] [hits 0]) (match (list-ref (list-ref lst y) x) ...)) ``` In the body of the `match` statement, we have our cases. The cases are in the for of `[if-match? do-this]`. If the symbol is an `x`, we return the number of `hits`. If it is an arrow, we rerun the program with modified arguments. If is anything else (`_` in the statement), we rerun the program, but we set `x` and `y` according to `dx` and `dy` respectively. ``` (let program ([lst (read)] [x 0] [y 0] [dx 0] [dy 0] [hits 0]) (match (list-ref (list-ref lst y) x) ['x hits] ['> (program lst (add1 x) y 1 0 (add1 hits))] ['< (program lst (- x 1) y -1 0 (add1 hits))] ['^ (program lst x (- y 1) 0 -1 (add1 hits))] ['v (program lst x (add1 y) 0 1 (add1 hits))] [_ (program lst (+ x dx) (+ y dy) dx dy hits)])) ``` To display the results, we surround the `let` statement with a `display` statement. ``` (display (let program (...) ...)) ``` ## Conclusion This was a fun code golf to solve! I learnt something new in the process (the `match` statement) and got a new view on how to see two-dimensional lists (rows and columns). Hope you all have an amazing week further! [Answer] # [C (clang)](http://clang.llvm.org/), 61 bytes Expects an array containing `0`, `'>'`, `'<'`, `'^'`, `'v'`, or `'x'` ``` d;f(*a,m){d=*a?:d;return'x'-d?!!*a+f(a+d%3+d/14%3*m+~m,m):0;} ``` [Try it online!](https://tio.run/##bVDbasMwDH2OvkLtCMrF3bp1Y1D38iG7gBsnraF2R5qGQcl@PVOc0YbRByOfo6Ojg7JJtldu27ZaFlGihI3Pepmo9VzLMq9OpaNvmuj1aJSotIhUqsNZqh8en8NZYtMfy/r5VDbtnXHZ/qRzXBwrbQ73uxVAfTAaqvxYRcZVyN7YVdsXF8MZgq@S/0U0DvW7GwvkBQJtHEtoALgDVhkXdT5e3c2ptw9cIoOAViRwiv5RTYIWJJj2kFuc21MdhqARuLlO1j3tZfXVpZcGQ/hfMthLn3TZfaN9cfjLMYh367Ebp5QAgb8Y3@FF4BNfoscbga9MdZdpfwE "C (clang) – Try It Online") ## Explanation `a` tracks our current position, `m` is the side length of the array, and `d` is the direction we're going (which changes anytime `a != 0`). In each call to `f()` we update the value of `a` going one step in the direction of `d`. ## Commented ``` d; // int d; f(*a,m){ // function f() takes a pointer to int (a) and an int (m) d=*a?:d; // if *a != 0 then d = *a return // 'x'-d? // if d != 'x': !!*a+ // add one if we're changing direction (*a != 0) f(...) // to the result of calling f() recursively : // else 0;} // we're at the end (return 0) ``` [Answer] # x86 assembly (Linux), 19 bytes This solution is a bit cheeky on the input. It expects a pointer to a M×N 2d array with the following symbols: * `0` -> `0` * `x` -> `-128` * `<` -> `-1` * `>` -> `1` * `^` -> `-M` * `v` -> `M` Which is, of course, the offset in bytes to the next element in the pointed-to direction, allowing us to just add the values. As the dimensions of the golf field is encoded into the field itself, we cannot have fields with rows larger than 127 bytes. If the row length is a limitation, just design the field to use all the columns you'd like. Who wants a square golf course anyway? ``` ; int golf(char *ptr) __attribute__((fastcall)); 00000000 <golf>: 0: 83 c8 ff or $0xffffffff,%eax ; int result = -1 ; do { 00000003 <loop>: 3: 80 39 00 cmpb $0x0,(%ecx) ; if (*ptr) { 6: 74 04 je c <skip> 8: 0f be 11 movsbl (%ecx),%edx ; int step = *ptr; b: 40 inc %eax ; result++; ; } 0000000c <skip>: c: 01 d1 add %edx,%ecx ; ptr += step; e: 83 fa 80 cmp $0xffffff80,%edx ; } while (step != -128) 11: 75 f0 jne 3 <loop> 13: c3 ret ; return result; ``` I can save an additional byte by making the input an array of ints rather than chars, but (to me) that violates the rule that: > > [The input array] contains only either characters or the integer 0. > > > I admit the distinction may be pointless when dealing with assembly. [Try it online!](https://tio.run/##rVRNj5swED3jXzFKsgIqiIBtlSjttreeK@2xTZExDsvWAYRNyqrqX286tvlI1Bx6WFkg/MYz82b8BiolP2biJSwYO5@X8FgWFVVdy3fQVRI3PIeyUlDU4uCxJ9rCm0PJRe5DmlKl2jLrFE9TzztQqRgVwvffk7XivSLrQtSZMJ5Ev3bEqVtYhXEAd5z2RNR1gxg7NhmsogC8O856nzjPHOSPsiHOsT5JDGBx7ZT3xCkrZt31GXSneW4s2s56E07oJMl29HiuOOhcxGm5Iud1ThUlsmOMS4kB1lSysoTFF4qtyL9VC3KgpdAdmG2fEbE2xeLUNGBHls5X96MbQATmcU9u4H5w9xo3e7S5vcG0fY/RshfFIQ4iXO@CMB6RKIgDQxhbE4FJ0XJDTdRVAfeIJFNSwKwnm9VkOM0MTJYh@8Tq@sz@krX73Z2Y37JPMYYqLqu79WC8qcpNoKvamFqjudBohi/7EWrkH1SvsS@X3ZpXuDG9uezWllzL70jLimDbtIj1t@fDL93Fn22puCdVXncqsPKe7taHhwcYrgE@weLRigXvH3ZWDCgP3AWwQbUvb8dKrmIl/xsLNdq1FUT4Db8J0ZSxtqaTTyjnrCeKS5XGCAlOYWI8qR8n0E6csQ9KHq0aGoQ/DgeOixknHL@hYF@D9YlfTRUCsHo7DK7dbcYQZmeGOjPzqXCa@21kmSYT0@Q1mSavypQ4Pf6ZbHDr19TNcMr8M/6wg6CFPIfH@@Qv "Assembly (gcc, x64, Linux) – Try It Online") [Answer] # Java 8, ~~129~~ ~~119~~ ~~118~~ ~~117~~ 116 bytes ``` m->{int c=0,p=0,l=m[0].length,d=0,t=0;for(;t<120;p+=d>99?l:d>93?-l:d/62*2-1)d=(t=m[p/l][p%l])>0?t+0*c--:d;return~c;} ``` -1 byte thanks to *@ceilingcat*. Uses ␀-bytes (`'\0'`) instead of `0` for the no-ops. Input as a character-matrix. [Try it online.](https://tio.run/##fVJNb4MwDL33V1hIk2AtNOukSeOrmnbaYd1hR6BSBllLFwIKhnWq2F/vDKXVLpusxLHzrPfsZMdbbu@yj2MqeV3DM8/VYQKQKxT6nacCVn04JCA10y3XURIlUFgepbsJbTVyzFNYgYLgWNjhYYAGbFbRkkERscSRQm1wO8sogwHz3ktteujfLJhXTYMsvL9fSpfc7dImP79bXC/sGysLTKTyai6TqLqSiRWyJU7ZdWrbbuZpgY1W36nXHb1eRtW8SZIxqmnLPIOCmjFfUedqEyXcOjXSc7dcA4oaH3ktwAUlPuEMOxhhzGLW@rGKWbj3Y2bMwGjp3PZ5MnXyY6wIvib8Jeht7/tn2MnWRjfSA7x@1SgKp2zQqYgTpTKNJ1U16IIxTPUP0FnwBdN3kfeFz5zE7yG49OTIXInatJyCV@MAXBfLR3q9B635l@VgORwuD@q6NIT/2I2XBk8ap8pJzV@81n9l4103fJbu@AM) **Explanation:** ``` m->{ // Method with char-matrix parameter and integer return-type int c=0, // Arrow-counter, starting at 0 p=0, // Position, starting at {0,0} l=m[0].length, // Width of the input-matrix d=0, // Direction, starting initialized at anything // (since the cell at {0,0} is guaranteed to contain an arrow) t=0; // Current character, starting at 0 for(;t<120 // Loop until the current character is 'x': ; // After every iteration: p+= // Update the position by increasing by: d>99? // If the direction is 'v': l // Increase by the matrix-width: {x,y}→{x,y+1} :d>93? // Else-if the direction is '^': -l // Decrease by the matrix-width: {x,y}→{x,y-1} : // Else (the direction is '>' or '<'): d/62*2-1) // If the direction is '>': increase by 1: {x,y}→{x+1,y} // If the direction is '<': decrease by 1: {x,y}→{x-1,y} d=(t=m[p/l][p%l]) // Set `t` to the value of the current position >0? // If `t` is an arrow (or 'x'): t // Update the direction to this `t` +0*c-- // And decrease the arrow-counter by 1 : // Else: d; // Keep the direction the same return~c;} // After the loop, return -c-1 as result, // where the -1 is to subtract 'x', since it isn't an arrow ``` [Answer] # Swift, ~~166~~ ~~157~~ ~~135~~ 129 bytes ``` {var x=0,y=0,u=0,v=0,s=0 while 0<1{let i=$0[y][x] if i>119{return s} if i>0{(u,v)=i>63 ?(0,i>95 ?1:-1):(i-61,0) s+=1} x+=u y+=v}} ``` Inspired by [@mousetail's Rust answer](https://codegolf.stackexchange.com/a/263018/106545). Takes a 2D array of ASCII values. [Try it on SwiftFiddle!](https://swiftfiddle.com/qtf36l6wrffgbd5ffycuvs66oy) Explanation: ``` { (arr: [[Int]]) -> Int in // Create some working variables. var x = 0 var y = 0 var dx = 0 var dy = 0 var strokes = 0 // Swift has no dedicated 'loop' keyword while true { let currentValue = arr[y][x] // Swift uses switch/case rather than match, so these ifs are shorter if currentValue > 119 { // It must be 120, 'x' return strokes } if currentValue > 0 { (dx, dy) = currentValue > 63 ? // It may be 'v' or '^' // 'v' = 118, '^' = 94 (dx: 0, dy: currentValue > 95 ? 1 : -1) : // It may be '<' or '>' (dx: currentValue - 61, dy: 0) strokes += 1 } y += dy x += dx } } ``` It might be possible to further optimize those ifs. Original answer: ``` {a in var c=(0,0),d=(0,0,0) var i:Int{a[c.0][c.1]} while 0<1{if i>119{return d.2} if i>0{if i>63{d.1=0 d.0=i>95 ?1:-1}else{d.0=0 d.1=i-61} d.2+=1} c.0+=d.0 c.1+=d.1}} ``` * -9 by using a constant inside the loop rather than a computed local outside it * -22 by using several variables rather than tuples * -6 by combining the assignments to `u` and `v` into a single statement [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~37~~ 32 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ç[¬нZ<#©Āi¼®U}©À®€Á®Á®€À)X11%è}¾ ``` Uses `0` like in the challenge description. [Try it online](https://tio.run/##yy9OTMpM/f//cHv0oTUX9kbZKB9aeaQh89CeQ@tCaw@tPNxwaN2jpjWHGw@tA2EQs0EzwtBQ9fCK2kP7/v@PjlYqU9Ix0FGyU9KBsIAwVicaTCOLAsVAPKBYHJhEEwWrrgCqtgFjuAlQmTil2FgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU3lot46Sf2kJhGtf@f9we/ShNRf2RtkoH1p5pCHz0J5D60JrD6083HBo3aOmNYcbD60DYRCzQTPC0FD18IraQ/v@6xzaZq93aOv/6OhoJTslHQMgVCpT0lGyUYrViQaygWJKFWC@jkFsrI4CUFkZSBlYogyiwQCs1ABVFCgGMVApTglqKLIoWDXUYJhlCAjUExsbCwA). **Explanation:** Since 05AB1E lacks a multidimensional index builtins, I instead rotate the entire matrix, so the cell at coordinate `{0,0}` will always contain the current value. ``` Ç # Convert all characters in the (implicit) input-matrix to codepoint # integers (0s remain 0s) [ # Start an infinite loop: ¬ # Push the first row (without popping the matrix) н # Pop this list and push its first value Z # Push its maximum digit (without popping the value) < # Decrease it by 1 # # Pop this maxDigit-1, and if it's 1: stop the infinite loop # (which is only the case for 'x'=120) © # Store the current value in variable `®` (without popping the value) Āi } # Pop the value, and if it's NOT 0: ¼ # Increase counter `¾` by 1 (starts initially at 0) ®U # And store `®` in variable `X` © # Store the current matrix in variable `®` now (without popping the matrix) À # Rotate its rows once towards the left ® # Push the matrix `®` again €Á # Rotate the values in each of its rows once towards the right ®Á # Similar, but rotate its rows once towards the right ®€À # Similar, but rotate the values in each of its rows once towards the left ) # Wrap all four rotated matrix into a list X # Push the current direction codepoint-integer `X` 11% # Modulo-11 è # (0-based) modular index it into the list of four matrices }¾ # After the infinite loop: push counter `¾` # (which is output implicitly as result) ``` * `Ç`+`Z<` is `[-1,8,5,7,5,1]` for `[0,"^",">","v","<","x"]` respectively (only `1` is truthy in 05AB1E); * `Ç`+`11%4%` (the `4%` is implicit due to modular indexing) is `[2,3,0,1]` for `["^",">","v","<"]` respectively. [Answer] **Ruby - 165 characters** No deviations from the rules. Uses `0` as the no-op. You can test the code [here](https://tio.run/##ZY5fC4IwFMXf76e41cMeXKCv4bXPETIh/4SatOEylOyz2@ZGCDG2nf3OuYf1Qz4tCglTQEzZi/GQs4Rxp8wS3Bqr3BoOW2Bwtp7/xjozmpl43dsqb2ZMgFg0b3jLRz7Rz4JOSoWlhML8TaWNSFsBeV9d79jcsCAyvWDVjkLw5MXm2d4ZA9MEIzl4jk7HCKpO@1jiYzEzkdBEHfSxRwk6ICeagEZoA5rsa1HDU@P@IgesryUe3vqDupZPvdsvXw). ``` s,i,j,x,y=0,0,0,0,0 loop do c = p[i][j] break if c=='x' if c!=0 if c=='v'||c=='^' y=0 x=c=='v'?1:-1 elsif c=='>'||c=='<' x=0 y=c=='>'?1:-1 end s+=1 end i+=x j+=y end ``` The readable version: ``` par_5 = [ ['v',0,'>','v',0,0,0], [0,0,0,'>','v',0,0], ['>',0,'^',0,'v',0,0], ['>',0,0,0,'x','<','<'], [0,0,0,0,0,0,'^'] ] strokes = 0 i = 0 j = 0 i_inc = 0 j_inc = 0 loop do shot = par_5[i][j] if shot == 'x' break end unless shot == 0 if shot == 'v' || shot == '^' j_inc = 0 i_inc = shot == 'v' ? 1 : -1 elsif shot == '>' || shot == '<' i_inc = 0 j_inc = shot == '>' ? 1 : -1 end strokes += 1 end i += i_inc j += j_inc end puts "You had #{strokes} shots!" ``` **Output:** `You had 8 shots!` [Answer] # [Desmos](https://www.desmos.com/calculator), 118 bytes Expects an array in variable `A` and a number in variable `n` (explained later). **Code in ticker** ``` \left\{0<v<120:k->k+1\right\},f(\left\{v=60:-1,v=62,v=94:-n,v=118:n,v=0:d\right\}) ``` **Everything else** ``` i=1 d=0 k=0 v=A[i] f(x)=d->x,i->i+x ``` [Try it on Desmos!](https://www.desmos.com/calculator/4bisr2gsaa) --- **Input, explained** Desmos neither supports characters nor multidimensional arrays, so input is instead recieved as a 1D array `A` containing the rows of the matrix, along with an integer `n` containing the length of a row. For example, the test case ``` [['>', 0, 0, 'v','<'], [ 0, '>','x','<', 0 ]] ``` Turns into ``` n=5 A=[62,0,0,118,60,0,62,120,60,0] ``` To speed things up you can use [this conversion tool](https://tio.run/##RUzLasMwELzrK4Y9SVCMIZdSooC/Iw8ItkwFykpIIiSEfLurjRPKsLPMg0n3@ht5853yssw5XlDuBf6SYq4odfKsGBa9Ghrvj2qOGcGzg@c1/lFYDft6XXYpnEen6cD0RWS6koKvmkCmNWUrONZSFS1zo2yJIVPA0J1TcjzpHn5uobWgnuBCcYh50qMxKmXPVc/E9sHPAw/2MTzJLMsVPXYQblAv/mi1a3xq968EN2yxfTdXnP4A) to automagically convert the input format for you. After you enter your input into the program (see the "testcases" folder), reset the variables (run the action at the bottom of the page), and then start the ticker to run the program. Once the program finishes, the result should be stored in `k`. **Program code, explained** Program code: ``` i=1 pointer to current position d=0 direction of travel k=0 number of arrows v=A[i] shorthand for current value under the pointer f(x)=d->x,i->i+x change the direction and also increment the pointer in that direction ``` Ticker code (prettified for readability): ``` {0<v<120:k->k+1},f({v=60:-1,v=62,v=94:-n,v=118:n,v=0:d}) {0<v<120:k->k+1}, increment k if this is an arrow f({ }) change the direction to... v=60:-1, ...left if '<' v=62, ...right if '>' v=94:-n, ...up if '^' v=118:n, ...down if `v` v=0:d ...no change if 0 ``` As a result of the fact that `i` points to a 1D array, the row number of `i` can be changed by adding/subtracting `n`, which is why the direction changes to `±n` for `'^'` and `'v'`. [Answer] # [Perl 5](https://www.perl.org/), 104 bytes ``` while(($_=$p[$i][$j])ne"x"){$i+=$b=/v/?1:/\^/?-1:/0/?$b:0;$j+=$d=/>/?1:/</?-1:/0/?$d:0;$t++if$_}print$t ``` ``` @p = ( ['v',0,'>','v',0,0,0], [0,0,0,'>','v',0,0], ['>',0,'^',0,'v',0,0], ['>',0,0,0,'x','<','<'], [0,0,0,0,0,0,'^'] ); #@p=(['>',0,0,'v','<'],[0,'>','x','<',0]); while(($_=$p[$i][$j])ne"x"){ $i+=$b=/v/?1:/\^/?-1:/0/?$b:0; $j+=$d=/>;/?1:/<;/?-1:/0/?$d:0; $t++if$_ } print$t ``` [Try it online!](https://tio.run/##ZY3RCoMwDEWfl68QF2hFR93DXtSq/@GqIHOsIlJEnDD27V2tsgmjpAn35N6oZuguWufK4Q4FxynIRIIwICkJ1sk8ESzAjnuwyotg5NL@/8B6ZuNJbO2jNlgSAV4Mx1xx@jUtSXa92E5uEaEwq/B8yK6hFCuOqkApCmyF1zfu7HovOKD0OdacTSw7R@xasuxkesgyrKMwNrw1/MZZannyw7cVj74v71jBG9Qg@xFH0PoD "Perl 5 – Try It Online") ]
[Question] [ Given a positive integer nesting level `n` and string `s` of printable ascii characters( to `~`, output a program which, when run in the same language, outputs a program which outputs a program . . . which outputs the string `s`. A total of `n` programs should be generated, all of which should be run in the same language as your answer. Note: you may output programs or functions -- anything you are allowed by default as a submission. You may input `s` with escaped characters, how a program or function in your language would usually input a string. --- # Example For example, given `n=1` and `s="recursion"`, a Python 2 program might output: ``` print "recursion" ``` Running this would output: ``` recursion ``` --- Given `n=2` and s="PPCG", a Python 2 program might output: ``` print "print \"PPCG\" " ``` Running this outputs: ``` print "PPCG" ``` Running this outputs: ``` PPCG ``` Related (+title inspiration): [One more LUL and I'm out](https://codegolf.stackexchange.com/questions/107323) Also Related (in sandbox - now deleted, but can still be viewed with enough reputation): [Source Code Recursion](https://codegolf.meta.stackexchange.com/a/10273) # Test Cases Make sure that your code works for the following test cases (one per line): ``` n s 2 PPCG 4 Robert'); DROP TABLE Students;-- 17 Deep 2 Spaces In Here 3 "Don't forget quotes!" 5 'Backt`cks might be a h`tch' 6 5%s 8 [Brackets]<Are>(Great){Usually} 3 !"#$%&'()*+,-./ 0123456789:;<=>?@ABCDEFGHIJKLMN 6 OPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ 7 THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG 3 the quick brown fox jumps over the lazy dog ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` Ṿ¡ ``` [Try it online!](https://tio.run/##y0rNyan8///hzn2HFv7//18pI1PpvzEA "Jelly – Try It Online") ``` Ṿ¡ Main link; left argument (text) is x, right argument (repetitions) is y ¡ Repeat y times: Ṿ Uneval x; produce code that outputs x ``` hehe builtins [Answer] # JavaScript (ES6), ~~47~~ 44 bytes *Saved 3 bytes thanks to @HermanLauenstein* Takes input in currying syntax `(n)(s)`. ``` n=>g=s=>`alert(atob("${btoa(--n?g(s):s)}"))` ``` ### Example ``` f(2)('PPCG') ``` Will output: ``` 'alert(atob("YWxlcnQoYXRvYigiVUZCRFJ3PT0iKSk="))' ``` Which will print: ``` 'alert(atob("UFBDRw=="))' ``` Which will print: ``` 'PPCG' ``` ### Demo A more complex example where `alert()` has been overridden so that intermediate results are printed to the console and automatically executed. ``` let f = n=>g=s=>`alert(atob("${btoa(--n?g(s):s)}"))` alert = s => { console.log(s); try { eval(s); } catch(e) {} } alert(f(5)("'Backt`cks might be a h`tch'")); ``` --- # Alternate version, 40 bytes *Suggested by @Shaggy* This one returns an anonymous function instead of a full program. ``` n=>g=s=>`_=>atob("${btoa(--n?g(s):s)}")` ``` [Answer] ## sh + coreutils, 31 bytes ``` yes exec sed 1d \$0|sed $1q;cat ``` Takes `n` as a command-line parameter and `s` on STDIN. [Answer] # [Python 2](https://docs.python.org/2/), 40 bytes ``` f=lambda r,t:r and"print%r"%f(r-1,t)or t ``` [Try it online!](https://tio.run/##TchBCoAgEEDRfacYBkQFW1S7oLOEYaJgKsNEdHqjVm0@vF9vDiWPrfkl2WNzFsjwTGCzw0oxsyAUXlE/GNaFgNt3lVdvyV5rzPVkpbWBv3SbOolhT6nAVSg5lA8 "Python 2 – Try It Online") -4 bytes thanks to xnor [Answer] # Haskell, 17 bytes As of when I write this, this is the shortest answer for a *non-golfing-specific* language. It is a function which takes `s` and `n` in that order, and returns the result or the source code of an expression which, when evaluated, returns the next source code. ``` (!!).iterate show ``` Argument for why this counts: 1. Solutions are allowed to be functions. 2. Their outputs are allowed to be functions. 3. Those functions have no parameters. 4. In Haskell, since it is lazy and everything-is-curried, the most natural — for practical programming purposes — definition of a 0-parameter function is the same as its result; the closest alternative, a 1-parameter function which ignores the parameter, is silly. If `f` is given `PPCG` and `2` as its parameters, the result is the text `"\"PPCG\""` (first generated function), which when evaluated returns the text `"PPCG"` (second generated funtion), and when that is evaluated it returns `PPCG`. Thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi) for suggesting a shortening. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~24~~ 23 bytes -1 thanks to ngn. This is a full program which prompts for `s` and then for `n` and prints to STDOUT. ``` ''''{⍺,⍨⍺,⍵/⍨1+⍵=⍺}⍣⎕⊢⍞ ``` [Try it online!](https://tio.run/##VVDJUsJAEL3PV7S4RFTcEDcUJYCAgokB3BeGMCZIyODMREXEq5ZVePPqQS/@gBc/Jz@CQS@hL939lq6uh5tWqNrCFjV67vNTnjLSk7xqu92fKbf79d@@Z7xxbtIb1j2g43Y/3dc39@XD7b73XT34q74ZqWoijeaRD9FohTAhBaOQ1BQVinE5l4KCcKrEFjwaCqEFv7rQxDrhkLUhQ7x14FIgSW1JwCVlBhFw7VBB@FAAhf0aScZ6XZT1OodGzTAFVAhgMMtCNyUU8Ssjoxwt@oETmXleIvjZWpyR2HiaESyC7RJ3sGW1OmjZLx4KDI@MjknjwYnJqdD0DMzOzYcXIotLyyur0bX12MZmXE4kU1vpTHZ7J5ffHXxSUfe0QrG0f3B4dHxyenZ@UcYVvUouDbN2VbcaNm1eMy6cm9u71n37ofM4@Gcxk4K9UjaxA7KmHOzClnII26W8WgBlP6VBn87Fj48gqaTRkt8oTOKlVtPrUGH01vaCvIMrp9HkQG8Igz5t4fsWVKmBwr8 "APL (Dyalog Unicode) – Try It Online") (the 17 Deep case is omitted as it exceeds TIO's output limit – works offline) `⍞` prompt for `s` `⊢` yield that (to separate `⎕` and `⍞`) `''''{`…`}⍣⎕` prompt for `n` and apply this lambda with a single quote as left argument that many times. `⍺` stands for the left argument (the quote) and `⍵` is stands for the right argument (the input text):  `⍵=⍺` Boolean where the text is equal to a quote  `1+` add one  `⍵/⍨` replicate each character of the argument the corresponding number of times  `⍺,` prepend a quote  `⍺,⍨` append a quote This works because strings in APL are `'` delimited and single-quotes in strings are doubled, while no other characters need escaping. --- Dyalog APL also ships with a utility (`⎕SE.Dyalog.Utils.repObj`) that generates an APL expression which evaluates to its argument (similar to [Jelly's uneval](https://codegolf.stackexchange.com/a/143923/43319)). The following program is therefore equivalent to the above, but works for *all* arrays: ``` ⎕SE.Dyalog.Utils.repObj⍣⎕⊢⎕ ``` [Try it online!](https://tio.run/##bVE9SwNBEO3vV4zVJYUBTf6AqKCgpEgsLDd3E29ls7vsziYEEaxUhBMbSy0U/GH3R@LsfcAV2eLgZua9N@@NsOow3wpl7nbV68u1cbir3j9n56Ozuji6Ian8yKGdLu6r8pd71dsPf@P0riq/YH45BRe0B6EBV5a24NF7aTR4AxuEQqwRyIA1NihBCJJgKZ0nGGhDoBFzzEFqEKCNWwkFZrlUUmPHM0ygfix6ept6oShtC6xOhfSQGSvRRw4qEBzDTHAZV1g@8vflfT3TrdhSPzyiFguFs5OreZ94P2gjqQChVFMM1irJGoGDksR7tJwxyiTG9fwxOIJjGA8n6QUqZdJWAbPC1BRS20AgfEyGRR1mKNeYJ@Okc16@V@V3ZxnXQoUYZGs2KAKjM6ye/pI0TVsxmAD/tIrN28tGG9lC@8AOth9SOMYcJD1AM5/ELh@Vu1CYTb1gc@ppoOixPitblDlqnuJbUxOBEp7@AQ "APL (Dyalog Unicode) – Try It Online") [Answer] # Firefox JavaScript, ~~41~~ 35 bytes ``` f=(s,n)=>"_=>"+uneval(--n?f(s,n):s) ``` Firefox has a nice `uneval`, which does what it sounds like - unevals a given object, in this case - string. [Answer] # Java 8, ~~95~~ 93 bytes ``` String c(String s,int n){return"v->\""+(n-->1?c(s,n).replaceAll("[\\\\\"]","\\\\$0"):s)+'"';} ``` -2 bytes thanks to *@Lynn*. Escaping special characters is so annoying in Java.. [Try it here](https://tio.run/##LY4xa8MwFIR3/4pXUYhEbJNApxhSsqVDp4yOB1V@BKXKk5GeHUrwb1dl8E3HHcd3dz3pyg9I9/43GadjhG9t6VUARNZsTbpwsHQDI1cTS0sMpF4BeQwkpup4FWIrqaqO@08jY0mqDjg4bfDknBTtdZHoRCkW874T6hDVdiM2zZyaIpOG8cdZswJh8raHRz6xEtsOtFoOAVz@IuOj9iPXQ65YGqnbXVcC4RO@iPGGISf7TinV5MVczCmd0TkPTx9c/5Y@/gE) and [try the resulting method here](https://tio.run/##NU5BDoIwELzzirWncoAPED17kYuJF/FQSzXFsiV0qTGGt9cWYZOZzc4mM9MJLwo7KOzaV5BGOAcnofGbAWgkNT6EVFCnE@BMo8YnSH6xugWfV1Gds0iOBGkJNSDsgy8OLKJZqNlWGnZUxlh429G0u01bwFioktEw3U00Wv18iuljG/5Pvt5A5GuVjyPVl3aicogv4lhKjpMx@dpqDj8). **Explanation:** ``` String c(String s,int n){ // Method with String and int parameters and String return-type return"v->\""+ // Return literal "v->" + a leading double-quote + (n-->1? // If `n` is larger than 1: c(s,n) // Recursive-call, .replaceAll("[\\\\\"]","\\\\$0") // with all double-quotes ('"') and slashes ('\') escaped : // Else: s) // The input String +'"'; // + a trailing double quote } // End of method ``` Additional explanation for the regex replacement: ``` .replaceAll("[\\\\\"]","\\\\$0") .replaceAll(" "," ") // Replace the match of the 1st String, with the 2nd [ ] // One of these inner characters: \\\\ // Escaped slash ('\') \" // Escaped double-quote ('"') // And replace them with: \\\\ // Escaped slash ('\'), $0 // plus found match ``` Why all these slashes? ``` \ → \\ // Escapes a single slash for the regex \\ → \\\\ // Escapes both regex-escaped slashes for the String " → \" // Escapes a double-quote for the String ``` [Answer] # [Underload](https://github.com/catseye/stringie), 11 bytes ``` (a(S)*)~^^S ``` [Try it online!](https://tio.run/##K81LSS3KyU9M@a/hX1pSUFqiqWGlZaWl@V8jUSNYU0uzLi4u@P9/AA "Underload – Try It Online") Input needs to start on the stack, with the number on top in the form of a [church numeral](https://esolangs.org/wiki/Underload#Numbers). I don't know if this is a valid input method, but the specification has no input, and placing input to the top of the stack seems like a stranded method used in such languages. [Answer] # [R](https://www.r-project.org/), 62 bytes ``` f=function(n,s){"if"(n,{formals(f)$n=n-1;formals(f)$s=s;f},s)} ``` [Try it online!](https://tio.run/##K/r/P802rTQvuSQzP08jT6dYs1opM00JyKpOyy/KTcwp1kjTVMmzzdM1tEYSKLYttk6rBaqu/Z@mYayjZKygGKOkrKKqpq6hqaWto6unr2BgaGRsYmpmbmFpZW1ja2fv4Ojk7OLq5u7h6eXt4@unpKkBhlxpGqY6CkrqTonJ2SUJydnFCrmZ6RklCkmpCokKGQklyRnqMKUg@B8A "R – Try It Online") Call it like so: `f(n,s)` followed by `n` copies of `()` A named function; returns an anonymous function. All it does is modify the default values of the `formals` of `f`, allowing the resulting function to be called (and then the result of that called, `n` times). when `n` reaches `0`, it returns `s`. R is actually not too bad at escaping! It uses C-style escaping, so you just have to take the input, replace `"` with `\"` and `\` with `\\`, and then wrap the whole thing in `" "`. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 5 bytes ``` ~{`}* ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v646oVbr/3@lgABndyUFIwA "GolfScript – Try It Online") [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 8 bytes Simple translation of [ngn's answer](https://codegolf.stackexchange.com/a/144094/43319). Takes `n` as argument and `s` as Input. ``` ^|'|$ '& ``` [Try it online!](https://tio.run/##KyxNTCn6/z@uRr1GhUtd7f9/JZf8PPUShbT8ovTUEoXC0vyS1GJFJS5FJWUVVTV1DU0tbR1dPX0FA0MjYxNTM3MLSytrG1s7ewdHJ2cXVzd3D08vbx9fP66SjFSg5szkbIWkovzyPKB5FQpZpbkFxQr5ZalFCiDpnMSqSoWU/PT/xgA "QuadR – Try It Online") PCRE **R**eplace all instances of `^|'|$` Beginning of line OR Quote OR End of line `'&` with a Quote and the entire match The Argument specifies how many times to repeat the transformation. [Answer] # Excel VBA (32-Bit), 67 Bytes *Version Restricted to 32-Bit Excel VBA because `2^i` evaluates without error in 32-Bit VBA, but not in 64-Bit VBA* Anonymous VBE immediate window function that takes inputs `n` and `s` from from ranges `[A1]` and `[B1]` and outputs an anonymous function that when evaluated down to only a terminal (after `n` iterations) outputs only `s` as that terminal ``` For i=0To[A1-1]:q=q+"?"+String(2^i,34):Next:?q[B1]Replace(q,"?","") ``` ### Sample Input / Output ``` [A1:B1]=Array(7, "PPCG") For i=0To[A1-1]:q=q+"?"+String(2^i,34):Next:?q[B1]Replace(q,"?","") ?"?""?""""?""""""""?""""""""""""""""?""""""""""""""""""""""""""""""""?""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""PPCG""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" ?"?""?""""?""""""""?""""""""""""""""?""""""""""""""""""""""""""""""""PPCG""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" ?"?""?""""?""""""""?""""""""""""""""PPCG""""""""""""""""""""""""""""""" ?"?""?""""?""""""""PPCG""""""""""""""" ?"?""?""""PPCG""""""" ?"?""PPCG""" ?"PPCG" PPCG ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes ``` (q ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIocSIsIiIsIjNcbkNHQ0MiXQ==) N times, uneval the string. [Answer] # Pyth, 21 bytes ``` L++NsXbJ,N\\+L\\JNyFz ``` [Try it here.](http://pyth.herokuapp.com/?code=L%2B%2BNsXbJ%2CN%5C%5C%2BL%5C%5CJNyFz&input=2%0APPCG&debug=0) Unfortunately the recursive function (not full program as above) is longer (24 bytes): ``` M?GgtG++NsXHJ,N\\+L\\JNH ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 19 bytes ``` '^|''|$'⎕r'''&'⍣⎕⊢⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ooz3tv3pcjbp6jYr6o76pRerq6mrqj3oXA9mPuhY96p0HUvI/jStRXT1JPRkoy2UEAA "APL (Dyalog Classic) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 34 bytes `%p` is a Ruby-specific printf flag that gets the `inspect` value of its argument, similar to `%r` in Python. `$><<` means print. ``` f=->n,s{"$><<%p"%(n>1?f[n-1,s]:s)} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y5Pp7haScXOxka1QElVI8/O0D4tOk/XUKc41qpYs/Z/QWlJsUJadHpqSbFeSX58po4CiBn735hLySU/T71EIS2/CCiiUFiaX5JarKgEAA "Ruby – Try It Online") ]
[Question] [ A digit word is a word where, after possibly removing some letters, you are left with one of the single digits: ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT or NINE (not ZERO). For example, BOUNCE and ANNOUNCE are digit words, since they contain the digit one. ENCODE is not a digit word, even though it contains an O, N and E, since they are not in order. Write a program/function which takes a single (uppercase or lowercase -- you choose) word as input or a parameter and determines if it is a digit word. Make the code as short as possible. If the word is not a digit word, you should return 'NO', 0 or any 'falsey' value (this may vary based on your language). If the word is a digit word, you should output the digit it contains, as a number. You can assume that no words contain more than one digit, so you won't have anything like ONFIVE. ***Test Cases*** ``` BOUNCE 1 ENCODE NO EIGHT 8 BLACKJACK NO FABULOUS NO EXERCISE NO DRIFTWOOD 2 SERVICEMAN 7 INSIGNIFICANCE 9 THROWDOWN 2 ZERO NO OZNERO 1 ``` *This challenge is taken from (and is a very slight modification of) Question 1 from [BIO 2009](http://www.olympiad.org.uk/papers/2009/bio/bio09-exam.pdf). Most of the test cases are taken from [the mark scheme](http://www.olympiad.org.uk/papers/2009/bio/bio09-marks.pdf).* [Answer] # Javascript (ES6), 101 99 bytes ``` f= s=>-~'ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE'.split` `.findIndex(x=>s.match([...x].join`.*`)) ``` ``` <!-- snippet demo: --> <input list=l oninput=console.log(f(this.value))> <datalist id=l><option value=BOUNCE> <option value=ENCODE> <option value=EIGHT> <option value=BLACKJACK> <option value=FABULOUS> <option value=EXERCISE> <option value=DRIFTWOOD> <option value=SERVICEMAN> <option value=INSIGNIFICANCE> <option value=THROWDOWN> <option value=ZERO> <option value=OZNERO> ``` [Answer] # PHP>=7.0, 87 Bytes ``` <?for(;$i++<9;)levenshtein(IntlChar::charName("$i"),"DIGIT $argn",0,1,1)?:die("$i")?>NO ``` If only insertions of chars from one digit as word to the input is done exit the program with the digit. Or change the order to `levenshtein("DIGIT $argn",IntlChar::charName("$i"),1,1,0)` to count not the deletions of chars [levenshtein](http://php.net/manual/en/function.levenshtein.php) [IntlChar::charName](http://php.net/manual/en/intlchar.charname.php) # PHP>=7.0, 112 Bytes ``` for(;$i<9;)$r+=++$i*preg_match("#".chunk_split(substr(IntlChar::charName("$i"),6),1,".*")."#",$argn);echo$r?:NO; ``` [IntlChar::charName](http://php.net/manual/en/intlchar.charname.php) # PHP, 128 Bytes ``` foreach([ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE]as$v)$r+=++$k*preg_match("#".chunk_split($v,1,".*")."#",$argn);echo$r?:NO; ``` [Try it online!](https://tio.run/nexus/php#Hc3NCoJAFEDhfY8xzcKfi9A2C1fXnM0dcNSCCBnEnLB0GM3XN2l94DunxBq749p1w5lRKUghKRavz9G1ujHeXRJCcZVQZDkipLLMIRUVghI3UFghAYpLVgAJwoee@OJzF57DkPeBdW1Xf/S8MWzPosZ8h76e7Ps1e3yBA7AoYH60Jfj//bhtzMhdciQZr@sP "PHP – TIO Nexus") 143 Bytes for more then 1 digit ``` foreach([ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE]as$v)$r.=++$k*preg_match("#".chunk_split($v,1,".*")."#",$argn);echo+$r?strtr($r,[""]):NO; ``` [Try it online!](https://tio.run/nexus/php#Hc69CoMwFEDhvY@RZvDnInStFadrzZKAiVoQkSBWi62GaH19K50PfJxbbAZzotr2U0QUT/KScVFI5JKE@3O2nW4HpxIcQZUCVJohQiLyDBJWIEj2AIkFckB2TxVwxrHWC91caoPI9@noGdv1zUevB0POJGiH7zQ2i3m/VoducAESeMQNjgT/CTfs2mH2qY2X1a7WoRYqQmr3ykW47z8 "PHP – TIO Nexus") [Answer] # Mathematica, 83 bytes (WindowsANSI encoding) ``` ±w_:=Rest@Position[Subsets@w~Cases~#&/@Characters@*IntegerName~Array~9,Except@{},1] ``` Defines a unary function `±` that takes a list of lowercase characters as input and returns either a digit, in a form like `{{7}}`, or else an empty list `{}`. I don't feel like I did a ton of golfy things here, except that `Characters@*IntegerName~Array~9` generates the number-name matches to look for without hard-coding them. Example usage: ``` ±{"i", "n", "s", "i", "g", "n", "i", "f", "i", "c", "a", "n", "c", "e"} ``` yields `{{9}}`. [Answer] # Python 3, 150 bytes ``` from itertools import*;lambda x:([i for i in range(10)if(*' OTTFFSSENNWHOIIEIIEORUVXVGN ERE EHE E NT '[i::9],)in[*combinations(x+' ',5)]]+[0])[0] ``` `combinations` returns all the combinations of things in order. It would be simpler to have a set number for the second parameter of `combinations`, so spaces are added onto the end of the original string that is a parameter of my lambda. That's a simple description of how my entry works. Ask if you would like any more clarification. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~31~~ 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 bytes now that lowercase input is acceptable ``` “¡¦ẇṆb~ṇjṚØ%ĖġṘḥḞṾṇJḌ»Ḳe€ŒPT ``` A full program that expects lowercase input and prints the result, using `0` for the falsey case. As a monadic link taking a list of characters it actually returns a list of integers which contains a single `0` in the falsey case, a single integer between `1` and `9` inclusive in the expected use cases and multiple such entries in cases where more than one number exists in the word. **[Try it online!](https://tio.run/nexus/jelly#AVIArf//4oCcwqHCpuG6h@G5hmJ@4bmHauG5msOYJcSWxKHhuZjhuKXhuJ7hub7huYdK4biMwrvhuLLFknVl4oKsxZJQVP///0lOU0lHTklGSUNBTkNF)** ### How? ``` “¡¦ẇṆb~ṇjṚØ%ĖġṘḥḞṾṇJḌ»Ḳe€ŒPT - Main link: list of characters, s “¡¦ẇṆb~ṇjṚØ%ĖġṘḥḞṾṇJḌ» - dictionary lookup of "one two three four five six seven eight nine" Ḳ - split on spaces ŒP - partitions of s e€ - exists in? for €ach T - truthy indexes ``` [Answer] # Ruby + [to\_words](https://github.com/taimur-akhtar/to_words): ~~49~~ 48+12 = ~~61~~ 60 bytes Uses the flags `-rto_words -n`. Takes lowercase words. Returns `nil` if no "digit" found. -1 byte now that lowercase input is allowed, allowing for the removal of the `i` flag on the regex. ``` p (1..9).find{|i|$_=~/#{i.to_words.chars*".*"}/} ``` For a more pure Ruby answer without external gems, 91+1 = 92 bytes: ``` p (1..9).find{|i|$_=~/#{%w"0 ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE"[i].chars*".*"}/} ``` [Answer] # [Python](https://docs.python.org/), 148 bytes ``` from itertools import* lambda s:[tuple(w)in combinations(s,len(w))for w in("x ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE "+s).split()].index(1)%10 ``` An unnamed function taking an uppercase only word and returning the integer (`1` to `9`), or `0` for `NO`. **[Try it online!](https://tio.run/nexus/python3#JY/BasMwDIbP61OIwKi9ZWW9FjZIE6X11tkQJ2nptkO7JmBI7BB7tG/f2d1B6PslIf1qX76u3aE/ng5gF5/ud@gacqZKw4/pj0ofnDLaEht3jfZ12poRzqA0iS4gOEK5FVCuC0TIRVVAzmoEyXYgsUYOyFbrEjjzg9GjpTM7dMoR@j1T@tRcyJzez58n7Wh6UK4ZnTGdBdUPZnQP13DJNdb5Y0Cipah4ilEcIU9FdoOw2@flJknf33x4zpNltRGVDO0dFimTYTIrWO59isyzxKJmKX4k3AvGJVtxlrM0@V/uPxHbTGxDc4@F8EnseQC6mNwNo9KOBE8xTJ9epzG0N0Xp9Q8 "Python 3 – TIO Nexus")** ### How? For an input string `s` the function traverses through a list of the strings: `"x"`, `"ONE"`, `"TWO"`, `"THREE"`, `"FOUR"`, `"FIVE"`, `"SIX"`, `"SEVEN"`, `"EIGHT"` , `"NINE"`, and `s` itself looking for any matches.\* The comparison used is whether this string, `w`, is one that may be formed from a combination of letters in order from the input. The function `combinations` gets these for us (and only the ones of the required length using `len(w)`), but they are in the form of tuples, so the strings are cast to tuples for the comparison. Of the eleven results the one for `"x"` will always be `False`, while the one for `s` itself will always be `True`. The `"x"` is there to ensure the index of a match with `ONE` through `NINE` are the values required (since Python lists are 0-indexed), the `s` is there to ensure the call to `index(1)` (synonymous with `index(True)`) wont fail when no digit word was found, whereupon the resulting `10` is converted to a `0` with a modulo of ten using `%10`. \* If `s` contains spaces for some reason, the list of `w`s will be longer, but the process will still work since the digit word matches will work the same way, and if none match the first space-split substring from `s` will match, once again giving `10` and returning `0`. If multiple digit words exist the function will return the minimal one. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 26 bytes The falsy value here is **0**. ``` æ‘€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š‘#å1k> ``` Explanation: ``` æ # Compute the powerset of the input ‘€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š‘ # Push "ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE" # # Break on spaces å # Check each for membership 1k # Get the index of 1 in the array (-1 if not found) > # Increment by one ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/nexus/05ab1e#AUAAv///w6bigJjigqzCteKAmuKAouKAnsOt4oCgw6zLhsOIxZLFocOvwr/FuMKvwqXFoOKAmCPDpTFrPv//Qk9VTkNF "05AB1E – TIO Nexus") or [Verify all test cases!](https://tio.run/nexus/05ab1e#FYyxCsIwFEX39xVFVx0cXIU2TTVa8yBtrYh/4C4IDsFBnF0UB6mCToo6CG6FPjr5F/mRGodzz3K4y/mioqvRe7O6FW@jD0afjT7S3eiMbt81bcpteaJHkZef4lFcysy2dbq0Zp1q0WrTk3aWV41yx3GaHTuU1xrTysNEMg5cMvStRLcXgxe6bNC3QOB6SYhJBHzMFRMRB1@JIE4RfYi4GgnGh64EISPRlSIQzP2fxT2FqY@phAlXCDiRVj8 "05AB1E – TIO Nexus") [Answer] # [Japt](https://github.com/ETHproductions/japt), 52 bytes ``` 1+`e two È(e fŒr five £x  v eight ͍`¸a@v fX¬q".* ``` [Try it online!](https://tio.run/nexus/japt#AUsAtP//MStgwo1lIHR3byDDiChlIGbCjHIgZml2ZSDCo3ggwqB2woEgZWlnaHQgw43DgsKNYMK4YUB2IGZYwqxxIi4q//8iRkxPVFVTUiI "Japt – TIO Nexus") [Answer] # [Retina](https://github.com/m-ender/retina), ~~160~~ ~~126~~ 120 bytes ``` O.*N.*E 1 T.*W.*O 2 T.*H.*R.*E.*E 3 F.*O.*U.*R 4 F.*I.*V.*E 5 S.*I.*X 6 S.*E.*V.*E.*N 7 E.*I.*G.*H.*T 8 N.*I.*N.*E 9 \D ``` [Try it online!](https://tio.run/nexus/retina#JY1LDsIwDET3cw8klEUk/rBME7c1H1tKUooQC@5/iZKEhTUzb6Txaj18F7VGrCFskK2ZrVFsqxutiQXXZoe@YGumgrCvga151uaA1MILx@roj8sgTqDWDG0p4wxpub264BOwLJ1O4gkkXkMRHsaM7u787VoOveumu04J9KLoORFC5D7PqgGJ4pM9PZyAJfEg3LN3dSyPUeegs@BNUaFvqeJ@ "Retina – TIO Nexus") Returns an empty string if the input does not contain a digit. -6 bytes thanks to [@CalculatorFeline](https://codegolf.stackexchange.com/users/51443/calculatorfeline). [Answer] ## Haskell, ~~113~~ 111 bytes ``` import Data.List last.((`elemIndices`([]:words"ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE"))=<<).subsequences ``` [Try it online!](https://tio.run/##FY3RCoIwFEDf@4rLnhTCDwh9qLzmwDbQZUFIrpw0csvcos@3ejvn5Zy7dA81DPOszficPKTSy6jQzi/6ZJDOR0HQqkEZajt9U64Nzs3q85w6RzhDEEcOIi8RIeOHEjJaI1T0BBXWyADpLhfAKEMShkkch5F7X516vZX9pWYjtYUEjBz3FwjGSVsf9SGcyYYf2BbJEkiFZU23uF@zv@VcYPGHtKTZb81T0sxf "Haskell – Try It Online") Returns `0` if no digit is found. Find all subsequences of the input word in the list of digits. Prepend an empty string `[]` at index 0 which is part of every subsequence. `elemIndices` returns a list of indices and `=<<` flattens them into a single list. Pick the last index. [Answer] ## JavaScript (ES6), 121 bytes ``` f= s=>[...s].map(c=>a=a.map(s=>s.slice(s[0]==c)),a=`ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE`.split` `)&&1+a.indexOf(``) ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o>0 ``` Returns the lowest detected digit or `0` if no digit was detected (+6 if `NO` is required). [Answer] # [Bash](https://www.gnu.org/software/bash/), 163 bytes ``` a=NO;case $1 in *O*N*E*)a=1;;*T*W*O*)a=2;;*T*H*R*E*E*)a=3;;*F*O*U*R*)a=4;;*F*I*V*E*)a=5;;*S*I*X*)a=6;;*S*E*V*E*N*)a=7;;*E*I*G*H*T*)a=8;;*N*I*N*E*)a=9;;esac;echo $a ``` [Try it online!](https://tio.run/nexus/bash#LY27DsIwEAR/xUUargtvdEoRRU645iKR8GhPliVooMj/y6wN5cxIu8kaHTnYEl1Vu9fb0UhKnlbW1Mw00x0CsC5wpgtaqRuIHu0KBdwWFLr96g44AR8Z9gV8aZrFAcKjDhicszhCKMT/@cQcFwscw/PjKkspiU4yqPTStdr5Lw "Bash – TIO Nexus") ``` a=NO; case $1 in *O*N*E*)a=1;; *T*W*O*)a=2;; *T*H*R*E*E*)a=3;; *F*O*U*R*)a=4;; *F*I*V*E*)a=5;; *S*I*X*)a=6;; *S*E*V*E*N*)a=7;; *E*I*G*H*T*)a=8;; *N*I*N*E*)a=9;; esac; echo $a ``` Don't know RETINA but seems a straight port of that answer. [Answer] # [Java (JDK)](http://jdk.java.net/), 150 bytes ``` s->{for(var i=0;i<9;)if(s.matches("."+"ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE".split(" ")[i++].replaceAll(".","*$0.")+"*"))return i;return"NO";} ``` [Try it online!](https://tio.run/##VVFdT6wwEH3nV0yaa0JdbHy9FzVh2aK9V9sE9sNofKgI2pUFQssmxuxvXwussrfJZObMnE7mzKzlVp6tX973alNXjYG1xaQ1qiB5W6ZGVSWJDoHvOHX7XKgU0kJqDXdSlfDpOACHtDbSWLet1AtsbNFNTKPK18cnkM2rxpYL9n23uxiqHojndZaaK8jhEhxnr8@uPvOqcbeyAXV57quL3z5WuavJRpr0LdMuImiCBKcwXwmY38SUQiQWMURsSSFh95DQJeVA2fXNHDjjFBFdF8q4CBB@VJPJE2myupBpFhRF181Dp7/OCcITdIowbjLTNiUofwgQF8jf7f1@@B9FJtNG24EHTQBoKhY8pMj7xpSHYnaMu2lGOL0Nwn9/rY2pKJgubsUiOfpzT@OQJUddZjGLrGoxG1MJjZcspHcBH3OMJ@yas4iFwX9D2WWJ1UysjqgPNBYjEg@8wz3c@U7v7THgcMpeNvwZ1OMf8cmHNtmGVK0htaWZ3EUn@qTsrUReT/cgJ7Kuiw@3QxgP@9w5ne32Xw "Java (JDK) – Try It Online") ## Saves * 167 -> 153: various optimization thanks to @KevinCruijssen [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 57 bytes ``` ∧"ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE"ṇi₁Ph⊆?∧Pt ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HHciV/P1eukHB/rhCPIFdXLjf/0CAuN88wV65gzwiuYNcwVz8uV093jxAuP08/V6WHO9szHzU1BmQ86mqzB@oOKPn/XynYNSjM09nV19FP6b8fAA "Brachylog – Try It Online") ### Explanation I think this could be shorter if `i` were reversible, but it doesn't appear to be. ``` ∧"..."ṇi₁Ph⊆?∧Pt ∧ Break unification with input "..." String containing words ONE through NINE, newline-separated ṇ Split on newlines i₁ [item, index] pair for some item in that list (1-based index) P Call that pair P h Its first element (the word) ⊆ is a non-contiguous substring of ? the input ∧ And Pt P's last element (the index) is the output ``` [Answer] # [Python](https://www.python.org), ~~125~~ 123 bytes ``` f=lambda b,x=9,i=0:x and f(b,x-1)+x*all(i:=b.find(c,i)+1for c in"NINE EIGHT SEVEN SIX FIVE FOUR THREE TWO ONE".split()[-x]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NVHBboJAEL3PV2w4QbuaYg9VEg4Ig25rdxMQMVoPqCHdhC7EYkLbT-nFS_tP_Y1-QRe0h0le3ryZeTPz-V291c-lOp2-jnXeG_585G6RvWz3GdnSxh1R6d44DcnUnuSmZnq2dd1cZUVhSsfd9nOp9uaOSuvazssD2RGpDM44EmST6ZzEuEBOYrYkIVsgCUUSkfk0QiTzVBDB0ei_VoWsTWvdazbWxcJv4xqGAWORcB_BBkDuiwCBCw3bvjAEGM88_-FeR0eH3jiZiSQ-a5YY-Sw-FwQRC_UwEcAAIMZowXx89DjcATAeswlnIfO9dtAIQHsTaSBS3opXGImuhVjxFtpdHtOW0_4uzo0nZVggVeU2a9txbjdQHmuNBx2G9iqSlvou5F1WptZRnbec6iBVbUqam9Ki5WXz_yf8AQ) -2 bytes from @xnor, also fixing a misalignment with the spec [Answer] # [Factor](https://factorcode.org/) + `math.combinatorics math.text.english`, 53 bytes ``` [ all-subsets 9 [1,b] [ number>text ] map disjoint? ] ``` [Try it online!](https://tio.run/##LU8xTsRADOzzCj8AIlECEpSIhgZdFaXY3TiJj8RObC85DvH2sBEU1tgzo5GnD8lF99P769vLA8zBxzrJHIlDoSnZH6WBB/zfHS9eIw8T2QjrBoZrRk5FNnSri6rBYFF0/1qU2OGxqtbtG6LkYoPila4ADaNDnEL6OJeBPsQ8STbAC2oiQ@iUet9EuhKsn5RwDgzERgNTTykcYT6qbJ1sDFdUAbnyAT/V3kCYplvL8XgK7qG5u4ktNMB5jqhPRwloS6EFOrKzlDefod2Pu95/AQ "Factor – Try It Online") Returns `f` for 'is a digit word' and `t` for 'is *not* a digit word.' * `all-subsets` Get all the subsets of the input. * `9 [1,b] [ number>text ] map` A shorter way to write `{ "one" "two" "three" "four" "five" "six" "seven" "eight" "nine" }`. * `disjoint?` Do the sets not overlap? (This is 2 bytes shorter than saying `intersects?`.) [Answer] # PHP, ~~134 132~~ 128 bytes ``` <?=preg_match(strtr(chunk_split("#(ONE0TWO0THREE0FOUR0FIVE0SIX0SEVEN0EIGHT0NINE",1,".*"),[")|("]).")#",$argn,$m)?count($m)-1:NO; ``` run as pipe with `-nF` or [try it online](http://sandbox.onlinephpfunctions.com/code/04295a445b3a7764dcf1d95d9193dc0e412d11e9). Creates a regex with the words in parentheses; i.e. each word `N` is in the `N`th sub-expression. If a word is found, the matched string will be in `$m[0]` and in the the `N`th element, with the elements between them empty and no empty string behind; i.e. `$m` has `N+1` elements. [Answer] ## Javascript, 121 bytes ``` (s,a=0)=>'ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE'.split``.map((p,i)=>RegExp(p.split``.join`.*`).exec(s)?a=i+1:0)&&a ``` or 116 ``` (s,a=0)=>' ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE'.split` `.map((p,i)=>a|=~s.search(p.split``.join`.*`)&&i)&&a ``` But just recycling material at this point. [Answer] # Pyth, ~~-44-~~ 41 bytes ``` +1xm}dyQc."EX%~)Û#lº,îQÓCe¯4Aô4"\P1 ``` Takes a quoted string, outputs 0 for NO. [Try it!](https://pyth.herokuapp.com/?code=%2B1xm%7DdyQc.%22EX%25%7E%29%C3%9B%23l%C2%BA%2C%C3%AEQ%C2%9C%C3%93Ce%C2%AF%C2%84%164A%C2%94%0E%C3%B4%C2%974%22%5CP%210&input=%22TOWOU%22&test_suite=1&test_suite_input=%22BOUNCE%22%0A%22ENCODE%22%0A%22EIGHT%22%0A%22BLACKJACK%22%0A%22FABULOUS%22%0A%22EXERCISE%22%0A%22DRIFTWOOD%22%0A%22SERVICEMAN%22%0A%22INSIGNIFICANCE%22%0A%22THROWDOWN%22%0A%22ZERO%22%0A%22OZNERO%22&debug=0) ### explanation ``` +1xm}dyQc."EX%~)Û#lº,îQÓCe¯4Aô4"\P1 ."EX%~)Û#lº,îQÓCe¯4Aô4" # Compressed string: "ONEPTWOPTHREEPFOURPFIVEPSIXPSEVENPEIGHTPNINE" (P is close to the other letters, makes the compression better) c \P # split on P: ['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE'] m # map over this list (variable: d) }dyQ # is d a (ordered) subset of the input (Q)? (= element of the powerset) x 1 # get the index of the first true +1 # add one, because the list was indexed at 0 and conveniently -1 (not found) becomes 0 ``` [Answer] # Java, 254 bytes ``` int g(String a,String b){int i=0,p=0;for(char c:a.toCharArray()){p=i;i=b.indexOf(c);if(i<=p)return 0;}return 1;} String f(String a){String[]T={"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"};for(String t:T)if(g(t,a)>0)return t;return"NO";} ``` [**Try Online**](http://ideone.com/wgzkc2) ``` boolean g(String a,String b) { int i = 0, p = 0; for(char c:a.toCharArray()) { p = i; i = b.indexOf(c); if(i <= p) return false; } return true; } String f(String a) { String[]T={"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"}; for(String t:T)if(g(t,a))return t; return"NO"; } ``` [Answer] # C, 198 bytes [**Try Online**](http://ideone.com/gt7A3M) ``` char*T[]={"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"}; g(char*a,char*b){while(*a&*b)a+=(*b++==*a);return!*a;} i;char*f(char*b){for(i=0;i<9;i++)if(g(T[i],b))return T[i];return"NO";} ``` [Answer] # Python 2, 155 bytes ``` import re;lambda k:next((i for i,j in enumerate([re.search('.*'.join(list(s)),k)for s in'ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE'.split()])if j),-1)+1 ``` An anonymous function searching for regex group. Not the best solution here in Python but an alternative way. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~9~~ 8 bytes ``` 9'∆ċ?ṗṠc ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiOSfiiIbEiz/huZfhuaBjIiwiIiwic2VydmljZW1hblxub3puZXJvXG50aHJvd2Rvd25cbmluc2lnbmlmaWNhbmNlXG5mYWJ1bG91c1xuYmxhY2tqYWNrXG5kcmlmdHdvb2Rcbnplcm9cbmJvdW5jZVxuZW5jb2RlXG5laWdodCJd) -1 thanks to EmanresuA 9 bytes but faster: ``` 9'∆ċ:?Þ∩= ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiOSfiiIbEizo/w57iiKk9IiwiIiwic2VydmljZW1hblxub3puZXJvXG50aHJvd2Rvd25cbmluc2lnbmlmaWNhbmNlXG5mYWJ1bG91c1xuYmxhY2tqYWNrXG5kcmlmdHdvb2Rcbnplcm9cbmJvdW5jZVxuZW5jb2RlXG5laWdodCJd) The joys of having number to word built-ins! ## Explained ``` 9'∆ċ:?Þ∩= 9' # From the range [1, 9], keep only items n where: ∆ċ # n as a word ?Þ∩ # under multiset intersection with the input : = # is the same. ``` ]
[Question] [ A sculptor is tasked to creating icicle sculptures for the new museum in Greenland. He has been given specifications by his boss, which consists of two numbers: [s, m] or size and melt. Size *must* be an odd number. He was given some photos of real icicles: ``` vvvvv [5, 0] vvv v vvvvvvv [7, 0] vvvvv vvv v vvvvvvv [7, 2] vvvvv vvvvvvv [7, 3] vvv [3, 1] ``` He needs a program to help draw. Any language allowed. The program needs to take in S and M, any method of input acceptable. You must then print out an ascii art representation of it. S is how many `v`s are on the first layer. M is how many layers are cut out from the bottom. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so as usual this competition is **byte based**. White space does count for byte counting. Least bytes wins. *Edit:* You will never get a set of numbers that draws nothing, for example [5, 3]. Checking code is *not* required however. [Answer] # [V](http://github.com/DJMcMayhem/V), 15 bytes ``` Àévò^lYp2x>òÀñd ``` [Try it online!](http://v.tryitonline.net/#code=w4DDqXbDsl5sWXAyeD7DssOAw7Fk&input=&args=Nw+Mg) Fairly straightforward. ``` À " Arg1 times: év " Insert a 'v' ò ò " Recursively: ^l " Break if there is only one character on this line Y " Yank this line p " Paste it below us 2x " Delete two characters > " Indent this line À " Arg2 times: ñd " Delete a line ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 12 bytes Code: ``` ÅÉ'v×R²F¨}.c ``` Explanation: ``` ÅÉ # List of uneven numbers: [1, 3, 5, ..., input] 'v× # String multiply by 'v', giving ['v', 'vvv', 'vvvvv', ...] R # Reverse the array ²F } # Second input times, do... ¨ # Remove the first element of the array .c # Centralize the array ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w4XDiSd2w5dSwrJGwqh9LmM&input=Nwoy) [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 11 bytes ``` ;-Ý·¹+'v×.c ;- Compute x = Input[1]-Input[0]/2 (e.g. 7,2 -> -1.5) Ý Push [0, ..., x] (e.g. 7,2 -> [0, -1]) · Multiply each value by 2 (e.g. 7,2 -> [0, -2]) ¹+ Add Input[0] to each value (e.g. 7,2 -> [7, 5]) 'v× String multiply by 'v' .c Center all strings and implicitly display them ``` [Try it online!](http://05ab1e.tryitonline.net/#code=Oy3DncK3wrkrJ3bDly5j&input=Nwoy) [Answer] # [MATL](http://github.com/lmendo/MATL), 22 bytes ``` 'v'itQ2/i-wX"R2&PRZ{Zv ``` [Try it online!](http://matl.tryitonline.net/#code=J3YnaXRRMi9pLXdYIlIyJlBSWntadg&input=Nwoy) ### Explanation ``` 'v' % Push character 'v' it % Input first number. Duplicate Q2/ % Add 1 and divide by 2 i- % Input second number. Subtract w % Swap X" % Char matrix of 'v' repeated those many times along each dim R % Upper triangular part 2&P % Flip horizontally R % Upper triangular part Z{ % Split char matrix along first dimension into a cell array of strings Zv % Remove trailing spaces from each string. Implicitly display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Rm-2”vẋµLḶ⁶ẋżðḣL_¥Y ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=Um0tMuKAnXbhuovCtUzhuLbigbbhuovFvMOw4bijTF_CpVk&input=&args=Nw+MA)** ### How? ``` Rm-2”vẋµLḶ⁶ẋżðḣL_¥Y - Main link: s, m µ - monadic chain separation R - range(s) [1,2,3,...s] m-2 - mod -2 [s,s-2,s-4,...,1] ”v - 'v' ẋ - repeat ['v'*s,...,'vvv','v'] (call this y) ð - dyadic chain separation L - length, effectively (s+1)/2 Ḷ - lowered range [0,1,2,...length-1] ⁶ - ' ' ẋ - repeat ['', ' ', ... ' '*(length-1)] ż - zip with y ¥ - last two links as a dyad L - length _ - subtract m ḣ - head Y - join with line feeds - implicit print ``` [Answer] ## Batch, 142 bytes ``` @set/ah=%1-%2-%2 @set s=v @for /l %%i in (3,2,%1)do @call set s=%%s%%vv @for /l %%i in (1,2,%h%)do @call echo %%s%%&call set s= %%s:~0,-2%% ``` [Answer] # Ruby, ~~46~~ 44 bytes ``` ->s,m{0.upto(s/2-m){|i|puts' '*i+?v*s;s-=2}} ``` 2 bytes saved thanks to G B [Answer] # Python, ~~76~~ 73 bytes ``` def f(s,m):print"\n".join([' '*(s/2-i/2)+'V'*i for i in range(s,m*2,-2)]) ``` **Edit:** Saved 3 bytes thanks to @TuukkaX and @Challenger5 (Thanks!) [Answer] ## JavaScript (ES6), 57 bytes ``` f=(s,m,p=``)=>s<m+m?``:p+`v`.repeat(s)+` `+f(s-2,m,p+` `) ``` Outputs a trailing newline. If a leading newline is acceptable, then for 54 bytes: ``` f=(s,m,p=` `)=>s<m+m?``:p+`v`.repeat(s)+f(s-2,m,p+` `) ``` [Answer] ## Python 2, 63 bytes ``` lambda s,m:'\n'.join((s-x)/2*' '+x*'v'for x in range(s,m*2,-2)) ``` [Answer] # [Turtlèd](https://github.com/Destructible-Watermelon/Turtl-d), 53 bytes ``` @v?,:l[v,l][ [ l]rr[ d,ur]ld' l]?<:d[ [ u]d[ ' d]luu] ``` ### [Try it online!](http://turtled.tryitonline.net/#code=QHY_LDpsW3YsbF1bIFsgbF1yclsgZCx1cl1sZCcgbF0_PDpkWyBbIHVdZFsgJyBkXWx1dV0&input=Nwox) ## Explanation: ``` @v, set char var to v, write it to cell ?:l take positive int input, move that many character right, move 1 left [v,l] move left back to the v, writing v on all the cells it goes on [ ] until the current cell is a space [ l] move left until finding a space rr move two right [ ] until cell is a space d,ur move down, write v, move up and right ld' l move left, down, write space [end of big loop] [that part made the "icicle", the next melts some] ?<: Take integer input again, rotate counterclockwise, move that number right (now up the icicle) d move down [ ] until cell is space [ u]d up until space is found, down 1 [ ' d] until space is found, write space to cell and move down luu move left, up, up [end loop] ``` [Answer] ## Java, ~~138~~ 137 bytes ``` void m(int l,int r){int f=l;do{String v="";for(int i=0;i++<l;v+="v");if(l/2<r)break;System.out.printf("%"+f--+"s%n",v);l-=2;}while(l>0);} ``` Ungolfed: ``` void m(int l, int r) { int f = l; do { String v = ""; for (int i = 0; i++ < l; v += "v"); if (l / 2 < r) break; System.out.printf("%" + f-- + "s%n", v); l -= 2; } while (l > 0); } ``` Update: One byte and loop body gone thanks to @ClaytonRamsey. [Answer] # C, 83 bytes ``` i,j;f(s,m){for(i=-1;i++<s/2-m;)for(j=-1;++j<=s;)putchar(j<s?j>=i&&s-j>i?86:32:10);} ``` Ungolfed and usage: ``` i,j; f(s,m){ for(i=-1;i++<s/2-m;) for(j=-1;++j<=s;) putchar(j<s ? j>=i&&s-j>i ? 86 : 32 : 10); } main() { f(5,0); f(7,0); f(7,2); f(7,3); f(3,1); } ``` [Answer] # Pyth, 21 bytes ``` j<E.e+*kd*hyb\v_Uh/Q2 ``` A program that takes input of `S` followed by `M`, newline-separated, and prints the result. [Test suite](https://pyth.herokuapp.com/?code=j%3CE.e%2B%2akd%2ahyb%5Cv_Uh%2FQ2&test_suite=1&test_suite_input=5%0A0%0A7%0A0%0A7%0A2%0A7%0A3%0A3%0A1&debug=0&input_size=2) **How it works** ``` j<E.e+*kd*hyb\v_Uh/Q2 Program. Inputs: Q, E /Q2 Yield Q // 2 h + 1 U Yield [0, 1, 2, ..., Q //2 +1] _ Reverse .e Map over with elements as b and zero-indexed indices as k: yb 2 * b h + 1 * \v "v" characters + prepended with k k * d spaces <E All but the last E elements j Join on newlines Implicitly print ``` ]
[Question] [ This is the cops' thread. For the robbers' thread, click [here](https://codegolf.stackexchange.com/questions/99472/quine-anagrams-robbers-thread). ### Cops' Task * First, write a quine in a language of your choosing. * Next, scramble the quine. Make sure to do this well as the robbers will be trying to unscramble it and find the original source code! Note that the scrambled code does not need to work. * Post an answer on this thread. Include the language, the byte count, and the scrambled code. Your program may not print to STDERR. Here is an example of a cop submission: > > # Python, 29 bytes > > > > ``` > nt _%=_r;_riinp;pr_='t _%%%_' > > ``` > > ### Robbers' Task For the robbers' thread, click [here](https://codegolf.stackexchange.com/questions/99472/quine-anagrams-robbers-thread). ### Safe Submissions If your submission has not yet been cracked after a week of posting, you may add the solution and specify that it is safe. If you do not, your submission may still be cracked. ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the user with the safe submission with the fewest bytes will be the winner of this section. ### Leaderboard Here is a stack snippet to generate a learderboard for this challenge. For it to display properly, please format your submission like this: ``` # Language Name, N bytes ... other stuff ... ``` If your submission gets cracked, please format like this: ``` # Language Name, N bytes, [Cracked!](link) ... other stuff ... ``` If your submission is safe, format like this: ``` # Language Name, N bytes, Safe! ... other stuff ... ``` ``` <script>site = 'meta.codegolf'; postID = 5686; isAnswer = false; QUESTION_ID = 99469;</script><script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>jQuery(function(){var u='https://api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)</code></pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script> ``` [Answer] # C#, 288 bytes ``` Stag is a great shoW. "="=""="="Agent"plastic"Was"tryin"to"Release"an"Astroid"."$Money$"st@le"tigers"and"Agent"plastic"got"mad"."$Money$"sic","man","t0tally"rad"."Sistrs"Rms"titAnic";"Civic"Ace"in"{sC@m}{hic}{vicis}..{cats}sAc}((@))((@)){{{>>{{{{{{}}}}}}}}}\\\\\\\;;;(@)((@)()),,;; ``` My strategy is for all the short ones to get cracked and nobody bothers with this considering how long it is... Also I suppose I should note that this is a full program, not just a function. [Answer] # JavaScript, 1574 bytes, Safe! I spent way too much time on this. Behold the obfuscation. ``` (notice that an unmatch parenthesis remains throughout the entire text. dear "sir", | i cannot express my loathing to you and your things. they truly are a loathsome sight. (regar'less of their quality, they function as the most appalling devices...)[1] | these avocads of thine possession are most unpleasent. (ce n'est pas faux.) Queer; Careful; An' in total repulsing. in this form, those are not seulement cringe... So; CAB's is quite Cruel. (Cruel indeed...) | intention is not great (heh, intention, ;}) run, no, run, since {tu est le ;AqC;}; {{{{============================================}}}} [1]: see? am i not insane? You may dictate the opposite, so i dictate thus. 9 + 4 is 13. Y is this. Y + 4 is 9 + 9 minus one. N is this. f(x) is {x + x}, so f(N) is N plus N is N + N is 3. :^) i'm cruel; not so cruel.) rrrrrrrrrr 0nnnccnnggrrrrttssBBC {({[}(<[<))(((((){{})}[}][[]{}(]))))|} f f r 0nnnccnngrrrrrttesBBA ())(((()))))()))()()()((((()))}{{})((} f f r 0nnnccnngrrrrrttesBBY ]]}(([][]{{{}}})()({}(){}{()}{}()[])][ f f r 4nnnccnngrrrrrttesBSY ))({})(}{)({{{{(()))())))))))()))()()( f f r 4nnnccnngrrrrrtpesqSY )()()((((((((((Z))))))))()(()((()((((( f f r 5nnnccnngrrrrrtlefoSY (((;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;''' f f r 3nnncccngrrrrxtleifSY ''''''''''''''''''',,,,,,,,[[[[[[]]]]] f f r 3nnncccngrrrrxtleifZQ [ ] ] + + + + + + + + + + + + + + + ++ f f r 9nnncccggrrrrxtleifZQ + + + + too not fun...fffffffffffffuuu f f r 5nnncccggrrrrxtlli0ZQ uuuuuuuuuuuu.. | | | |99S ) f f r 0nnncccggrrrrxxll01QQ ``` ## Here's the original source! > > > ``` > function Y(x){return x.charCodeAt()}; > function Q(x){return String.fromCharCode(x)}; > N=Array.prototype; > function B(f,g,h){return function(){ > return f(g.apply(h||this,arguments)); > }}; > function S(f,h){return function(){ > return f.apply(h||this,N.reverse.call(arguments))}} > function id(x){return x}; > function format(){ > args = N.slice.call(arguments); > str = args.shift(); res = []+[]; > for(i = 0; i < str.length; i++){ > c = function(){return str[i]}; > if(B(Y,c) == 95){ > res += args.shift(); > } else if(S(B)(c,Y)() == 94){ > res += q = B(id,Q)(34); > res += args.shift(); > res += q; > } else if(Y(c()) == 39){ > i++; > res += c() == ([][0]+[])[1] ? Q(10) : []+[]; > } else res += c(); > } > return res; > } > console.log(format(Z="function Y(x){return x.charCodeAt()};'nfunction Q(x){return String.fromCharCode(x)};'nN=Array.prototype;'nfunction B(f,g,h){return function(){'n return f(g.apply(h||this,arguments));'n}};'nfunction S(f,h){return function(){'n return f.apply(h||this,N.reverse.call(arguments))}}'nfunction id(x){return x};'nfunction format(){'n args = N.slice.call(arguments);'n str = args.shift(); res = []+[];'n for(i = 0; i < str.length; i++){'n c = function(){return str[i]};'n if(B(Y,c) == 95){'n res += args.shift();'n } else if(S(B)(c,Y)() == 94){'n res += q = B(id,Q)(34);'n res += args.shift();'n res += q;'n } else if(Y(c()) == 39){'n i++;'n res += c() == ([][0]+[])[1] ? Q(10) : []+[];'n } else res += c();'n }'n return res;'n}'nconsole.log(format(Z=^,Z))",Z)) > ``` > > > > [Answer] # [MATL](https://github.com/lmendo/MATL), 20 bytes. [Cracked](https://codegolf.stackexchange.com/a/99679/36398) ``` It'D-whoLl&w#ck'f0Gz ``` Don't attempt to crack this. It'd wholly wack fogs. [Answer] # [Underload](http://esolangs.org/wiki/Underload), 20 bytes, [Cracked!](https://codegolf.stackexchange.com/a/99644/8478) ``` ~*)(a):*(*a:S(*S*~S) ``` I scrambled this via randomizing the order of the characters, because what could be more scrambled than random? A correctly written Underload interpreter crashes when seeing a newline at the top level of the program. As usual in golfing competitions, there's no newline at the end of the program; I'm just placing this reminder here because it's very easy to add one by mistake when copying the program to an interpreter. [Answer] ## [Retina](https://github.com/m-ender/retina/), 20 bytes, [Cracked](https://codegolf.stackexchange.com/a/100059/8478) ``` S`(\?)\1* S`(\?)\1* ``` The program (and output) contains exactly two linefeeds. [You can try Retina online here.](http://retina.tryitonline.net/) A small hint: > > In the process of designing this cop, I found a new shortest Retina quine, which I'll post to our quine challenge once this answer is either cracked or safe. > > > [Answer] ## CJam, 39 bytes, Safe ``` !""$)+023345679:AEORYZZ\_```bbceeffimmz ``` Solution: > > `")A!0z`eZOmRZ$Yei`E"_`\32fm95b67b43f+:c` > > > > Uses some base encoding for obfuscation. However, since the characters are all in ASCII I would have thought someone might be able to figure out `32fm95b??b??f+:c` which would be enough to brute force the rest. > > > [Answer] # Pyth, 38 bytes, Safe Not quite golfed, but works. ``` ````::""@@@@++++22ggKKKKKKKKNNNNZZZZ ``` Unsorted version: ``` K"K++@KZ:`K@`NZNgK2"++@KZ:`K@`NZNgK2 ``` [Answer] # Vim, 22 bytes, [Cracked!](https://codegolf.stackexchange.com/questions/99472/quine-anagrams-robbers-thread/99493#99493) ``` pit^[^[p00tqqqq^V"ltxltx" ``` The `^[` are the literal escape key, and `^V` is `Ctrl-V`, and are therefore counted as one byte, and are kept together in the scrambled code. [Answer] # Python 2, 54 bytes, [Cracked!](https://codegolf.stackexchange.com/a/99557/34543) ``` =l`;lrt,]l n`p,i=,' 1,1'lnt[ll[;,0 ]['r[`][`0'ipll] ] ``` [Answer] # JavaScript, 147 bytes, [Cracked](https://codegolf.stackexchange.com/a/99593/42545) by ETHProductions I'll be very impressed if someone manages to crack this... ``` """"''''((((()))))+++++++++.//99;;;;;;=========>>[[[[[]]]]]``````````````cccdddddddeeeeeeeeeeeffiiiiiiinnnnnnnoooooooorrrrrrrrsttttuuwwwwwwx{{}} ``` ### Intended solution: ``` e=o=>{n=o;``[r=`constructor`][r](`return e=>{`+o+`}`)````};d=e+"";e`for(i in window)if(/ert/.exec(i))w=window[i];w('e='+d+';d=e+"";e'+d[9]+n+d[9])` ``` [Answer] # Haskell, 86 bytes, [cracked by nimi](https://codegolf.stackexchange.com/a/99683/56433) ``` putStr$"Study:ric====>>>>yummy:candy:circus:party:in:syrirrr!!!!!!$[;['=['[$]']='];]$" ``` This a valid Haskell expression which prints: ``` Study:ric====>>>>yummy:candy:circus:party:in:syrirrr!!!!!!$[;['=['[$]']='];]$ ``` So if Ric studies, he can go to the yummy candy circus party! That is, if he figures out where *Syrirrr* is. [Answer] # [V](http://github.com/DJMcMayhem/V), 20 bytes -- Safe! ``` "$033lpqxx|áäéééñññ ``` Note the trailing newline. I wasn't really sure how to scramble them, so I just sorted the characters by ASCII value. Unlike most V answers, this one contains *zero* unprintable characters. Here is a hexdump: ``` 0000000: 2224 3033 336c 7071 7878 7ce1 e4e9 e9e9 "$033lpqxx|..... 0000010: f1f1 f10a .... ``` # Unscrambled code: ``` éññ3äl0éé$áx3|"qpñx ``` [Try it online!](http://v.tryitonline.net/#code=w6nDscOxM8OkbDDDqcOpJMOheDN8InFww7F4Cg&input=) Side not about this link. In previous versions of V, a newline was always automatically printed, which is why this version has the trailing newline. The interpreter at the time I wrote this was a valid quine, although now you can just remove the newline to make it valid. Explanation: ``` éñ " Insert a 'ñ' character ñ ñ " Put all of the following into register 'q' and run it when it's done recording 3äl " Make 3 copies of the character under the cursor 0 " Move to the first column éé " Insert an 'é' character $ " Move to the last column áx " Append an 'x' 3| " Move to the third column "qp " Paste register 'q' (all of the commands we just ran) x " Delete a character ``` [Answer] # Haskell, 99 bytes, Safe ``` "super.quine?"=>#$$$%%%%%&&(())))**++++,,,,/;<<==>>STaabbdeffggghhhjlmmnoppqqrrsssttttuuuvvwwwwxxxx ``` Another Haskell quine, this time with a nice odd 99 bytes. > > > ``` > g%w=(g< $ >w)++w++pure(g.last$w);main=putStr$pred%"h&x>)h=%?x*,,x,,qvsf)h/mbtu%x*qvuTus%qsfe&#" > ``` > > [Try it on Ideone.](http://ideone.com/GDgXTq) The spaces in "g< $ >w" must be removed, I put them there because otherwise the <,$, and > vanish (most likely being interpreted as html tag). > The gibberish string is a string of the program with each char mapped to it's successor, including a final `"` (which is possible to include into the string without escaping because it's mapped to `#`). The helper function `%` takes the string and maps each char to it's predecessor using `pred` (yielding `code"`), then appends the original string (yielding `code"gibberish_code`) and the last char of the decoded string (yielding `code"gibberish_code"`). To convert a char `c` to a string it would normally suffice to put it into a list `[c]` as strings in Haskell are simply char lists, however the successor of `[` is `\`, which would need escaping in the successor-encoded string, so instead `pure` is used which lifts arbitrary types into a Monad (which Monad to use is inferred from the context). > > > [Answer] # PHP, 110 bytes, [Cracked](https://codegolf.stackexchange.com/questions/99472/quine-anagrams-robbers-thread/99887#99887) ``` php$=))$)<9 php .(().)'heroes ? $0(9carrot3?$;<.()trash3,.((3=)catarrh$$9 (,'9cry(3); ;;tryccchhhrrrrxxxxxx ``` [Answer] # Javascript ES6, 49 bytes (cracked) ``` {{$((((((('`fuck rent =+> turn off fin`')))))))}} ``` Is it bad if I focused more on forming coherent words in the scrambled solution? In any case, this is my first Cops and Robbers challenge. **Update**: see comments for cracked code. [Answer] # FurryScript, 199 bytes, Safe! ``` UT TTEDU DT T U T D ES DGT GEL L GL -<<<<<<+++++++[[[[#BESTQUINEEVER!#BESTQUINEEVER!#BESTQUINEEVER!#BESTQUINEEVER!#BESTQUINEEVER!#]]]]+++++++>>>>>>- X XG WPW SS X PW S US WWTLWP XS PE ``` Should be fairly easy to crack. # Unscrambled Code ``` BESTQUINE[ DUP LT +SW +GT +< BESTQUINE#> ] EVER![ DUP EX+ SW EX- LT +SW +GT +< EVER!#> ] <BESTQUINE[ DUP LT +SW +GT +< BESTQUINE#> ]> BESTQUINE# <EVER![ DUP EX+ SW EX- LT +SW +GT +< EVER!#> ]> EVER!# ``` Just the regular quine, but with two subroutines and some more code to swap the strings. [Answer] # Vim, 17 bytes ``` <CR>""&(())::::\npps ``` The `<CR>` is Enter (`^M` or `^J`) in the input and an **added** newline in the output. It is **not** the implicit end of file newline (see `:help 'eol'`). The 17 bytes are what is added to an empty buffer. (Newlines in a text editor are weird; let me know if this isn't clear.) [Answer] # [><>](//esolangs.org/wiki/Fish), 36 bytes, [Cracked!](/a/99659/41024) ``` !!!'''***+...00002333:::;???dddforrr ``` [Answer] # Befunge-93, 15 bytes, [Cracked!](/a/99673/8478) ``` :::@#%+-_,<910g ``` [Try it online!](http://befunge.tryitonline.net/) [Answer] # Python 2, 105 bytes, [Cracked!](/a/99750/41024) ``` ######%%%%''(((((((())))))))****--0011::::;;==@@@@@@@@@@[[[[]]]]aaaaaaggggggiiiiiiiinnpprrrrrrrrrtt~~ ``` The other one was cracked, so this one is more difficult. > > > ``` > print'To find the solution, get to work!' > ``` > > > > [Answer] ## Ruby, 53 bytes - [Cracked](https://codegolf.stackexchange.com/questions/99472/quine-anagrams-robbers-thread/100096#100096) ``` **TEN sTupID,sTupID NET,"TIN"<22"DEN"<<It<DEtINDE\n\n ``` The `\n` are literal newlines. [Answer] ## [QB64](http://qb64.net), 89 bytes ``` (_+cad:effecs:fact), =+cred:scarf:attaccd?, =+eff4c3d:cars:craccd?, (_+csc:f4c3d:fact), " ``` Some salient points: * The code will not work in QBasic: it uses QB64-specific features * Syntax expansion is off * No dollar signs and only one quotation mark * "Poetry" would be a stretch, but it does rhyme [Answer] # Befunge-93, 24 bytes I'm afraid this is a bit late, but I wanted to attempt one without the `g` command. ``` <<_:@00278899p,**++###>! ``` [Try it online!](http://befunge.tryitonline.net/) [Answer] # [OIL](https://github.com/L3viathan/OIL), 77 bytes, Safe ``` 0 0 1 1 1 1 1 1 1 1 1 2 2 4 4 4 6 8 10 11 11 11 12 17 18 18 18 18 22 26 26 32 ``` Good luck with that. Solution, "commented" (remove comments before running or it won't work): ``` 0 # nop twice 0 1 # copy element from cell 1 to 1 (so do nothing again) 1 1 4 # print what's in cell 1 (a zero) 1 11 # print a newline 4 # and the same thing again; printing zero and a newline 1 11 1 # copy what's in cell 2 (a 1) into cell 2 2 2 1 # copy what's in cell 12 (two lines before; a 2) into cell 18 12 18 10 # check if the value in the cell of the following line (starting with 2; we'll jump back here) 18 # (this is cell 18) 1 # is equal-ish to the one in cell 1 (a zero) 32 # if yes, jump somewhere 22 # otherwise jump one cell ahead 1 # copy what's currently in cell 18 (first a 2) into cell 26 18 26 4 # print cell 26 26 8 # increment cell 18 18 11 # print a newline 6 # and jump back to cell 17 17 ``` So to summarize, it works by first printing two zeros, and then comparing every line starting with the third one with zero, and if it isn't zero, printing it, else exiting (since OIL reads zero from any empty/non-existent cell). Any variable lines contain the value they have when they are printed (since I'm lazy, I obtained this by first making a near-quine where those cells have some arbitrary non-zero value, and using the result, which is a quine). [Answer] # [Jelly](//github.com/DennisMitchell/jelly), 3 bytes, [Cracked!](/a/99651/41024) ``` Ṙ”Ṙ ``` [Try it online!](//jelly.tryitonline.net#code=4bmY4oCd4bmY) Here is the solution: > > What, you want the solution? Find it! > > > ]
[Question] [ Given a list \$X\$ of 2 or more integers, output whether, for all \$n\$ such that \$0 \leq n < length(X)-2\$, there exists a pair of equal integers in \$X\$ separated by exactly \$n\$ elements. In other words: output whether, for all overlapping slices/windows of the input, there exists at least one slice/window of each length wherein the head of the slice/window equals the tail. For example: `[1, 1, 3, 2, 3, 1, 2, 1]` will return truthy, because ``` [1, x, x, x, x, x, x, 1] These 1s are separated by 6 elements, the most possible in an 8 element list, [x, 1, x, x, x, x, x, 1] These 1s are separated by 5 elements, [1, x, x, x, x, 1, x, x] These 1s are separated by 4 elements, [x, 1, x, x, x, 1, x, x] These 1s are separated by 3 elements, [x, x, x, 2, x, x, 2, x] These 2s are separated by 2 elements, [x, x, 3, x, 3, 1, x, 1] These 3s are separated by 1 element (as are the 1s, but either pair is sufficient), [1, 1, x, x, x, x, x, x] And these 1s are separated by 0 elements, the least possible. ``` But `[1, 1, 2, 2, 1, 1]` will return falsy, as there is no pair of equal elements separated by exactly one element. That is, there is no length 3 slice/window with a head equal to it's tail. See all length 3 slices/windows below: ``` [1, 1, 2] [1, 2, 2] [2, 2, 1] [2, 1, 1] ``` Standard I/O applies, input does not have to allow negatives, or input can be a string of characters, etc. Anything reasonable as long as you're not cheating :) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! ## Examples Truthy ``` [1, 1] [1, 1, 1] [3, 3, 7, 3] [2, 2, 1, 2, 2] [2, 1, 2, 2, 2] [1, 3, 1, 3, 1, 1] [1, 1, 3, 2, 3, 1, 2, 1] [1, 1, 1, 1, 1, 1, 2, 1] ``` Falsy ``` [1, 2] [1, 2, 1] [1, 2, 3, 4] [3, 1, 3, 1, 3] [3, 1, 1, 3, 1] [1, 3, 1, 1, 3, 1] [1, 1, 2, 2, 2, 2, 1, 1] [1, 1, 1, 1, 1, 1, 1, 2] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ ~~8~~ 6 bytes Uses inverted boolean output. ``` IÐƤÄPẸ ``` [Try it online!](https://tio.run/##y0rNyan8/9/z8IRjSw63BDzcteP/4fZHTWuA6P//6GiuaEMdBcNYHQgNZRrrKACROZAE8Yx0FIzAciAGVADKgwoYgtXDSSTjjMGKjGEakC1CQlCZWB2Ic2BmImmAGGICdRzCPoQAVAzFOahiCDfDPITDOWAncMXGAgA "Jelly – Try It Online") ``` ÐƤ # Map over each suffix: I # Increments (differences between adjacent elements) Ä # For each list, get cumulative sums PẸ # Is there a zero in each column? ``` This is basically: *Is there a zero on each diagonal of the subtraction table?*. The naive implementation would be: ``` _þ`ŒDP€Ẹ ``` [Try it online!](https://tio.run/##y0rNyan8/z/@8L6Eo5NcAh41rXm4a8f/w@1ABhD9/x8dzRVtqKNgGKsDoaFMYx0FIDIHkiCekY6CEVgOxIAKQHlQAUOwejiJZJwxWJExTAOyRUgIKhOrA3EOzEwkDRBDTKCOQ9iHEICKoTgHVQzhZpiHcDgH7ASu2FgA "Jelly – Try It Online") [Answer] # JavaScript (ES6), 39 bytes Returns a Boolean value. ``` a=>a.every((_,d)=>a.some(v=>a[d++]==v)) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RL7UstahSQyNeJ0UTxC3Oz03VKAOyolO0tWNtbcs0Nf8n5@cV5@ek6uXkp2uoR4cUlZZkVMaqa3Ihi6dpRBvqKBjGamIVxi5jrKMAROZAEoukkY6CEVgniIFdHiqJXd4QbDicxO0yY7ARxjDj8HgBCcEUoqhUj8mLdkvMKcYRODhcidtOiLNMsIccwn845aFK8AUOXiWI8IXFBXGBA/XrfwA "JavaScript (Node.js) – Try It Online") Or **38 bytes** with an inverted output, assuming the input list does not contain any 0: ``` a=>a.some((_,d)=>a.every(v=>a[d++]^v)) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5Rrzg/N1VDI14nRRPESy1LLarUKAMyo1O0tWPjyjQ1/yfn5xXn56Tq5eSna6hHhxSVlmRUxqprciGLp2lEG@ooGMZqYhXGLmOsowBE5kASi6SRjoIRWCeIgV0eKold3hBsOJzE7TJjsBHGMOPweAEJwRSiqFSPyYt2S8wpxhE4OFyJ206Is0ywhxzCfzjloUrwBQ5eJYjwhcUFcYED9et/AA "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // given an array a[] of N entries a.every((_, d) => // for each distance d = 0 to N - 1: a.some(v => // is there some value v at position i (implied) ... a[d++] == v // ... such that a[i + d] is equal to v? // (we increment d instead of storing i explicitly) ) // end of some() ) // end of every() ``` [Answer] # [Rust](https://www.rust-lang.org), 63 bytes ``` |k:&[u8]|(0..k.len()).all(|z|(z..k.len()).any(|q|k[q-z]==k[q])) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jVNBboMwEDz0xiuWHCpbclCTVGqUCOXWTyArQqmREA5JbFO1CbykFw7tC_qa9jW1DRSKAurKspfdYVgvs2_vIpOq_IxS2IdxijBcHM4UROB_ZCqaLr82ebK6DbIlzdGd5yUeZxqFvZBzlJ9zdO7G0leUn_IkOE3P1Pf1STGuaL5vHtegzXGigwDEXo5sp9jTVjCZcUXgWT8eBIY4hcCB2pASGbM5tw0as5EZgRkl1-MDqQUBvR70fi07JzC37xpnAFBnBwAzy_-7j5S3sCSLhnDsIp3VQ1Lc-igKuRxt1lDFI5-vSrwfaGV722FAjRlt1jim7Xjze_7ZrN6VKbYu1QJvQkaKjLO9UV0lwE7SmJmESqHgQ4QM1gvlVvJ4x7Tg13_ARxGniqcumlxWmwIuxYRYdlJT9OChlEwoFzX8PvSGooMvrFfo6SmqcSrL6vwB) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~12~~ 11 bytes ``` żƛ?l'ṪǏ⁼;;A ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLFvMabP2wn4bmqx4/igbw7O0EiLCIiLCJbMSwgMywgMSwgMSwgMywgMV0iXQ==) *-1 thanks to EmanresuA but also -10 rep thanks to EmanresuA so now I have to edit the post so the upvote can be returned* ## Explained ``` żƛ?l'ṪǏ⁼;;A żƛ # For every number n in the range [0, len(input)] ?l # Overlapping windows of length n of the input 'ṪǏ⁼; # Get all sublists where the list is the same after appending the head of the list to the list with the tail chopped off. That is, `a[:-1] + [a[0]] == a` ; # End map A # Are all the items truthy? ``` [Answer] # [J](http://jsoftware.com/), 18 16 bytes ``` [:*/[:+.//.@|.e. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o6209KOttPX09fUcavRS9f5rcnGlJmfkKxgq2CqkAUlDNC6qgDEQmisYIwsZAaEhiEQVBAuhChoCNUMwhiXGQLXGYD2Y9kMhSAoiZwCVM0LjwvQiBIwVTJCFYNYbowuChVE14xCGegvsQQwpJMf@BwA "J – Try It Online") *-2 thanks to ovs!* Explanation slightly out of date (can't update right now), but idea is same. Consider `3 3 7 3`: * `-/~` Differences table: ``` 0 0 _4 0 0 0 _4 0 4 4 0 4 0 0 _4 0 ``` * `|.` Reversed: ``` 0 0 _4 0 4 4 0 4 0 0 _4 0 0 0 _4 0 ``` * `0&e./.` Is there a zero in each diagonal going this way `/`: ``` 1 1 1 1 1 1 1 ``` * `[:*/` Are they all 1: ``` 1 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~9~~ 8 bytes Saved one byte thanks to [@Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) ``` &=T&XdaA ``` [Try it online!](https://tio.run/##y00syfn/X802RC0iJdHx//9oQx0FIDLWUTACk4ZghmEsAA "MATL – Try It Online") **Explanation:** ``` &= # input == input' T # get all diagonals from... &Xd # spdiags (i.e. rotate matrix 45 degrees) a # `any` applied to columns A # all ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` fqG&=&f-m ``` Outputs a truthy or falsy value, which is [allowed by default](https://codegolf.meta.stackexchange.com/a/19205/36398). Specifically, outputs * a non-empty array containing only ones, which [is truthy](https://codegolf.stackexchange.com/a/95057/36398), or * an array containing at least a zero, which [is falsy](https://codegolf.stackexchange.com/a/95057/36398). [Try it online!](https://tio.run/##y00syfn/P63QXc1WLU039///aEMdBSAy1lEwApOGYIZhLAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8D@t0F3NVi1NN/e/vXpJUWlJRqV6rXpaYk5xpXosl0tURcj/aEMdBcNYLjAFYRnrKACROZAEcox0FIzAMiAGhA/lQPiGYMVwEmGSMViJMUw5khVICCEBNQtJAKzZBOIehC1wPlQI2QkoQghXwnyA3QlguwE), including truthiness/falsihood test. ### How it works ``` % Implicit input f % Find: gives indices of non-zeros. Since the input contains non-zero % integers, this gives [1 2 ... n] where n is the input length q % Subtract 1, element-wise. Gives [0 1 ... n-1] G % Push input again &= % Matrix of pairwise equality comparisons &f % Two-output find: gives row and column indices of nonzero (i.e. true) entries - % Subtract, element-wise m % Ismember. This gives an array containing only true (or 1) if 0, 1,... n-1 % are all contained in the above result (note that 0 will always be contained) % Implicit display ``` [Answer] # [Husk](https://github.com/barbuz/Husk/wiki/Commands), ~~10~~ 8 [bytes](https://github.com/barbuz/Husk/wiki/Codepage) ``` Πm▲∂↔´Ṫ= ``` Port of [*@ovs*' second Jelly answer](https://codegolf.stackexchange.com/a/249389/52210): > > Is there a zero on each diagonal of the subtraction table? > > > -2 bytes thanks to *@Steffan*, by using this instead: > > Is there a 1 on each diagonal of the equality table? > > > Outputs `1`/`0` for truthy/falsey respectively. [Try it online.](https://tio.run/##yygtzv7//9yC3EfTNj3qaHrUNuXQloc7V9n@//8/2lDHUMdYxwiIDYGkYSwA) **Explanation:** ``` ´ # Use the given input-argument twice, Ṫ # to apply double-vectorized, creating a table = # checking for each pair if they're equal ↔ # Reverse each inner row ∂ # Now pop and take all anti-diagonals of this matrix # (`∂↔` basically takes all diagonals of the matrix†) m # Map over each diagonal-list: ▲ # Maximum: check if any value in the diagonal-list is truthy Π # Product: check if all are truthy for each diagonal # (after which the result is output implicitly) ``` † Although Husk has an anti-diagonals builtin `∂`, it lacks a diagonals builtin. The reason for this is probably because the anti-diagonals can be computed on an infinite matrix, whereas this isn't the case for the diagonals, as [assumed by *@MartinEnder* here](https://codegolf.stackexchange.com/questions/153978/generalized-matrix-trace/153982#comment375944_153982). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ ~~9~~ 6 bytes ``` .s€αPO ``` [Try it online](https://tio.run/##yy9OTMpM/f9fr/hR05pzGwP8//@PNtZRMNRRgJKxAA "05AB1E – Try It Online") or [verify all testcases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKS/X@94kdNa85tDPD/r8MFkuEqz8jMSVUoSk1MUcjM40rJ51JQ0M8vKNGHGACl0My0UVABq81L/R9tqKNgGMsFpiAsYx0FIDIHkkCOkY6CEVgGxIDwoRwI3xCsGE4iTDIGKzGGKUeyAgkhJKBmIQmANZtA3IOwBc6HCiE7AUUI4UqYD7A7AWI3AA). Returns zero if there are pairs at every distance, otherwise returns a non-zero number. If this output format isn't allowed, it's +1 bytes for adding `_` in the end (and then it returns 1 if there are pairs at every distance and 0 otherwise). Alternatively, if you are willing to stretch the output format more you can remove the `O` in the end, and then it returns a list containing only zeros iff there are pairs at every distance ``` .s All suffixes € Map each suffix to: α The absolute difference of each value in the suffix from the matching value in the input P Product of each list - it's zero iff there's at least one pair of equal elements with distance X O Sum - since all values are positive, this is zero iff all values in the map are zero ``` [Answer] # [Knight](https://github.com/knight-lang/knight-lang), 91 bytes ``` ;=l~1;W E++'=x'=l+1l'P'1;=aT;=wF;W<=w+1w l;=bF;=s~1;W<=s+1s-l w=b|b?E+'x'sE+'x'+s w=a&a bOa ``` Enter each number in the input list on their own line, with a trailing newline. [Try It Online!](https://tio.run/##lVhrc9s2Fv3uXwFzU4sQaVpKO92JaNiTeO2dTBs5G7v17EpKBIKQxIYiFT4spxL717MX4AvUy@kHayTg4L5w7gP@gz7SmEXeIjkNQpd/Yz6NY/RL4E1nyXUUhRHiTwkP3BjJX6ssB7ynUcyb@8qZEvUhDRJv/jzuLok4na9YGMRJlLIkjHSKV8nMi604TCPGCc1gx1s8zLyExwvKuF7sz2nCZvrZR30wHA0HwxjWs97IWP9j8HEYjNr6MFi/wLh9hrMF559hN@JJGgVIET7ojNbrIPX9LBfmmIx08MrnCaLEsfgTZ7oCx3YhQhwhhNBL8aWnQojy3YpTB2zXKaixfB5Mkxk26YCNcJaE4LgXTHdalWUyHOj@v@@v78hgZOeh@p36KV/FCU08hhbiFnQHrxxrKzz2BKL4SCPwoWPTcymm0G9Tw8j9Y0SuD@jIKmXZ3kRnuLCHZYqvWZQGMuxRuEQBX@aMyFzupNMd63u8k0KsehNw/XTu8GgPrtwE3Jsw9DkN9gCr3axg1a8QjIj6FfHy0G2QLE4XQropRX1yaUKBa7mjipIdzhS/63O7PCl@N0FbbpQLKox/8YV5BYIiD6ymAePhJPdacePkRDEe@Jh/K6MghFchKEKyxZ@S63U23d@M8OD16f9G7TOzW1GenpyICxYyde1eE9pw5qbzReXMuHTmhczPDI8zP5nVrhzXtp6c0Ma1TVUcUnHHTWCWk3mRxjNdrGI7T5Xr/u9vP9z2313378kqKxLmrcuDZIMDz7k/oKd/fhqJz87pq08Qgs0ASKFgbHaITZ4AAZua8ZFHvYkHuDxEOU4ECsz1poGQo3gyqDGjipq5wXtQIoMfQ89FnWNxP6Xldp2gal3Wx78Fn4NwGSCvsgy1Gqa1xs2YSxdwGV8lut9Lr6FrbIcUAlqkC8WbpCo2ak5R11W4Up6vOWNQpXTgDGrwQfhpEz5P/YPwdhPueo@ql/WWuInGJZSi3tFkZgFvAqZIPQO/912SdkWDIEwQqII7Qc5X9CePQg1MDd2/qbtW@AN9Vh@IT/1Q0bcIl4f11eLX62Odnnfwdznfbn@H9/xpEQaCpDTh0iCUhFAbAz4Fvj1yBMbxCIz091SSc/Xe9tabiwaqQfya9n1oiId5r1Tvivj9oqTinPNCSKOElBVEtNuNHNAEWMfaoc4g5RXOPxNKFs7BTC6PWFoVjL95Sg2OWCujA83x2eAICjmEKj1Ha40wzHHx8G7UvsTD7pn5UtJKRAOY5ahEAg1iWMmHGGrlw50Aay3Rlth63dJa4guuXaqHVlH0wKq5FwCTXPQlDYFQPGBhKpa520MvVjQb72rp0v5mHpndDl6vOxs1qxgQDtUs4cS4ABQKt0uPANW6rIgvOIXeo1agZxhfjVoHGV@h1EuFxaK7winq3n0NWI9mJOJfUi/iujaJNWyuxIgstxxli8083/20iELGY4G6@a1/df/2tn9X9@YbqAGHWrPCkvyCYTKvxAwcpdPJm1ZmVVvh1WVPZp2xtvBZzhgu5mkxH4sfLszH7jkrZ2O3nI0nRFpklaYIZceTPXR650HvDqaIRtN0LgaOFyvX6GYIlKCJ8BI6qiMaqc3zwE5wptyxCITOTMfkGyMFLLGNsUKIIzT/HtA5J07@HVTHhG3PrvKAbllWhaoqS17FNaE98cJA14xKahUeB5UjpzxKDaKZSDMcK5dRdXFD26pNt84fnCWWF0v@mjAuZZNCFYr41IsTLl3EKwhtV/Sq8oG08ZbQtT6YhOYpDHkOJOoTZYn/FUEvQGxGI/gFM4sfBlOoSXZNEDoijqIRAlN1LvVqiySDF6juKHmA1dpTj1H5e8PeSQOtH6JHIRkKZeq7wlapwj2GWqlklQg4NqsQaO81U8fkoniSaZrpkDfpZMIji/p@yHQYwN1QBInqHWBEByZyEyjvwJMSO2D4Z5sZ4OoSMo7rXejCcke@5CyRWw8eJL42DDSMGWFW7HvwQuyY6LSe7MtKw3CmWvYht6zRuid@CL7@9PLVT69@/ufLVz@35WpEAzeci7Cp5681k5ILETLaCG0Nab1uCUiV6Hl4C6sctbuBAZelmbkkaxKF8ytgwFXowqBZvJ1wrzRXvU6LFbjXiZjZVCPfSCOpunSVLxWPS/mpbo/ldtWHms7tcVT7jzxUFESLP3mbVVzBHlcK5Fur@QBqIH@tkMJj1ZAymVT0vwS3LqrxrRHs0rI4ccM0sZYRNG4QmOc5NmkjZrdNQbXWQpo2HMrnYfnvD6Da5R4FBaJjlukPWNzbCR6LLnk0xmY1Pak2GUBWUU7qixMtt/CyEYbTLaR4IexCtreQokPvQp5tIeW7YAfyh22Z4W47P24h5fy9A3leISvSlEfEbFAdUc9c7D8z3Xfmcv8ZUfx3njmpzui0zPDGf2wui2O9Rg6unz1Ge852btrKsXzX3BUwosAaVUY8btdrUKk89JspTa3ipe6QSr/TEP5QCV@JPmo30tfGG4m3k8xvcxHQ/skF3Rkstu37v5VDMmi13abTeK6ZohEoP8taVqWjELJea1ozaneFAleqKA89o8ol7rbmClxmvRjwL6kB82VdERxsMKM2yXBFV65bx18ttfY1H/GAg@iMv9nE/6trP6Brw2iRpxbxja7fet/q2oTe22R5Yz@ck6XRXSLfJs6NTWKBPiex0Y1PfbQkztq5vDZaT61YfhoxrNETipxb@m0Mz1hP9Dz7W/eoe/Tj0Uv468Jn9@j/) Also made a [test suite](https://tio.run/##lVh7V9s4Fv978imE2yEWNiaBnpktxnBaFnY5QwNb0uHsJmkjy0riqWOnfhA6ifvVu1fyS84D2pNDsKXffeq@lL/IA4lo6M7ifT9w2HfqkShCf/jueBJfhGEQIvYYM9@JkHhbpBngloQRq@9LNAXqfeLH7vR53F0cMjJd0MCP4jChcRCqBC/iiRsZUZCElFkkhR13dj9xYxbNCGVqvj8lMZ2oBx/VXn/Q7/UjWE@PB9ryRe9j3x/sqX1/@RLjvQOczhj7DLshi5PQRxLzXmuwXPqJ56UZM1unVgsvPBYjYtkGe2RUleDYzFlwEsuyyBl/OJYhlvRsRIkNuqsExBge88fxBOukRwc4jQMw3PXHG7VKU@EO1P3v7cWd1RuYmav@JF7CFlFMYpeiGT8F1cYL21hzjzkCLz6QEGxomeREsMnlm0TTMvuoJdZ7ZGAUvEx3pFKc60NTydY0THzh9jCYI5/Ns4hIHWYn4w3rW6wTTIxqE3CdZGqzcAuu2ATc2yDwGPG3AMvdNI@qa3BGSLwy8DLXrQRZlMw4d12w@uSQmECsZYZKQjYYk79XdJssyd/roDUzigUZxr54XL0cQZALWhOfsmCUWS2ZsbsrKQ/xmD0VXuDMSxfkLlmLnyLWq2zqXg5w783@/wZ7B3q7DHmyu8sPmPNUla7CpeHUSaaz0phhYcxLkZ8pHqZePKlM2al03d0ltWMbyzgk43bqwDQL5lkSTVS@is0sVS46f169v@m8u@h0rUWaJ8yVw/x4JQaeM79H9v/@NODfrf3Xn8AFqw4QTEHZ9KlocjkIoqnuH0HqjlzAZS7KcNxRoK479jkfyZJehRmUoZkpvAXFM/ghcB3U2uHnU2huVgkq12V1@MH/7AdzH7mlZqhZU605rPtcmIAL/0re/dHw6jvaukvBoXm6ELwaVPlGFVPEcaRYKeirmNGIVDpwCjX4Sfh@HT5NvCfhe3W44z7IVlZb/CRqh1CwekfiiQFx41OJ6wHYve2QlHPi@0GMQBScCbK/or9ZGCigauD8pOxK4K/kWXnAPvECSd4smD8tr2K/XO6o5KSFf8j4vb0fsJ49zgKfBymJmVAIxQHURp@NId4eGALlWAhKelsqyYl8blvrzWkNVQv8Kuw70BCfjnupepeB38lLKs5injOplZCigvB2u5IDCgerWHmqMwh@ufHPuJIGU1CTCRJDKZ3xk1Syc/ha4R1ojs86h4eQbRGp5yjNAYY5LurfDfbOcL99oB@KsOLegMiy5UACCXxYyYYYYmTDHQcrTd6W6HLZVJr8AVcmVUMrL3qg1dT1IZIc9CUJIKCYT4OELzPnGL1ckHS4qaUL/et5pLdbeLlsrdSsfEB4qmZxI4Y5IBe4Xno4qJJlhGzGCPQeuQI9E/HlqPVkxJco@VBhMe@uQEWcu68@PSapFbIviRsyVRlFCtYXfEQWW7a0RSeu53yahQFlEUddfuicd69uOndVb76EGvBUa5aiJDtgmMxLNj1b6nTipKVZ1ZTi6uxYZJ22NPBBFjGMz9N8PuYvDszHzgktZmOnmI1HltDIKFThwnZGW8LpnQu92x8jEo6TKR84Xi4crZ0iEIJG3EroqDZvpCbLHDvCqXTG3BEq1W2drYwUsERXxgrOziLZs0@mzLKzZxAdWXR9dhUEqmEYJaqsLFkVV7j02A18VdFKrqV7bFSMnIKUaJaiI0WzjYxH2cU1Za023dh/MRobbiTiV4dxKR3lolDIxm4UM2EiXoBr27xXFReklbuEqnRAJTRNYMizIVEfCY29rwh6AaITEsIbzCxe4I@hJplVgJCBZUsSwTFl55KPNk8yuIGqtpQHWK491RiV3TfMjWGgdAL0wDlDoUw8h@sqRDg7UCulrOIOx3rpAuVW0VVsneZXMkXRbettMhqx0CCeF1AVBnAn4E4iagsiogUTuQ4hb8OVEtug@GeTamDqHDKOqW3owmJH3OQMnlv3LiS@0vcVjKlFjchz4YbY0tF@NdkXlYbiVNbsfaZZrXWPvABsfXX4@tXr334/fP3bnlgNie8EU@42mf5C0Yl1yl1Gaq6tIM03TQ4pEz1zb66VLXc3UOCsUDPjZIzCYHoOEXAeODBo5ncnfFyoKx@nQXPcm5jPbLKSb4WSRF46z5byy6X4lreHYrvsQ3Xjthiq/EcQ5QXRYI/uahWXsDulAHHXql@AasjrEsktlhUpkklG/5PH1mk5vtWcXWgWxU6QxMY8hMYNDLM8xzqp@eymzqiSmnNT@n1xPSx@/oBQO9siIEe09CL9AYuPN4KHvEs2hlgvpydZJw2ClZeT6uB4y82trLlhfw3JbwibkHtrSN6hNyEP1pDiXrAB@es6z2Cznh/XkGL@3oA8KZFl0BQkfDYoSWSa0@004200Z9tpePHfSLNb0qikyPDaLzZnOdlxLQeXz5KRY3s9N02JLNvVNznMkmC1KsMvt8sliJQu@vWUJkZ@U7etUr5dY35fMl/wPmrW0tfEK4m3MZivMhbQ/q1TstFZdN32f0lEwmmV3rpdu67pvBFIr0UtK9ORM1kuFaXutbtcgCNEFETPiHIsZ11yCS6yng/4Z0SD@bKqCDbWqFappDm8K1et41tTrn31SzzgwDvD76Y1Qm@vb87/QOjFLOFXGLg/u764OJazwajxi2l539rmPbrQtKb12LQ8re01b5tt0yJd05pfmvcn1lxrz5FnWvalaUUcfWJFWjva99Dcspf22YXWfGxG4luLYI3sEmTfkEYDGKDb9zfvbrvoRUw@MwQlDSndMIknXxXQBgYsrhToB1ikWshF6jcEZbBh3v/76voCneSLGmojF2P0D/TiOghmiI8hyXiCGKETFAt@KGYwJlESscYv52@ur9EIvaAwRwgZlcX8F/mNRFuUvSRexFaVNW8@dG8/dFGzCc6F84x5LHuuz1bN@AkrRkLQT1qxSvR9aEB88XHE/J65udGGj/iCf0fw@R3@GofwaYvv8uGQo47yv5zkCFaPxH7JI/uIhcw14q3CcIJXjZLRUSPnd5Rt114KwYeykpWI/wM) cuz I'm bored lol (Basically equivalent Python code: [Try It Online!](https://tio.run/##dVDLasMwELzrKxZfIhGnoLjQYqqrv8A31we7kYlAKMZykEPpt7trya9AC2I1sztoZtU@@uvNJO9tN44X2UBDB5YSAhoEaGmQIamQ5N1dEnCIskpbiV13VVoCdalwR87gA3RKAOpVAWARnziCWWpTYWfpyU1ir67h1sFQ2FIIrEdX4mByrKAyF6jRqe2U6WnFxlxEUVTwGHhJ/BVQEgOeN6xIzjGc/WQCgc8kcO7Fa91eSrwkWeQ7i93xAwxBSCEH@UWbQ0O/1Q87sAa3UKAM5C@21aqn0aeJWElCePzGbAk/p9g8gu1r2GTLt/K5tQ//1Nr2W3b/O7z3nsL/mz17yj7@Ag)) [Answer] # [R](https://www.r-project.org), 56 bytes ``` \(x,n=seq(x),`?`=Map)any(\(i)all(\(j)x[j]-x[i+j]?n)?n-1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3LWI0KnTybItTCzUqNHUS7BNsfRMLNBPzKjViNDI1E3NygHSWZkV0VqxuRXSmdlasfZ6mfZ6uoSZE_y1G1zSNZA1DHQVDTU0uGBPBM9ZRACJzIAkVMNJRMAKrADEQYlABhJghWCOcRDXdGKzUGKYNzWokhCqJZDaaBNgwE4SbEbajiEGF0Z2IIYzwDcy3uJ0IcRckNBcsgNAA) Outputs `FALSE` for truthy and `NA` for falsey. [Answer] # [Python](https://www.python.org) NumPy, 51 bytes ``` lambda a:all(map((a==[*zip(a)]).trace,a.argsort())) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVDNTsMwDBaXHfoUPjqoVHRFAk3qW3DbdjAsgUj5k5chlVfZZRIa7wRPQ0natUhIluPP_mx_zvEzdPHVu9OHajfnQ1Q3D1-NIfu0I6AVGYOWAiK17fr6XQcksRVVZHqWJVXEL3vPEYUQQ-ujYm_BHWzoQNvQF4GYqSuUZzCgHfggHd6KiiXtjHZyj2JVgG4TDeUbGTRCFBBYu4gK9Tj79H21WNcl1NsiPTlqSujtvvc9WJawTJXfIOMBZFwn8sVPk5pEaUb6bMXMpsIwa5ZIzXdZz7TlgofUXMKf1KRyvOB_CXl3_o8f) Takes a numpy array. ### How? Mostly straightforward.`zip` and `argsort` are used to avoid the direct `numpy` import. `zip` does roughly the same as transpose. The comparison with `a` creates a boolean table of pairwise incidence. The diagonals of this table are the distance groups. Taking the trace at different offsets returns a positive (hence truthy) value if there is a pair at that distance. `argsort` seems to be the cheapest way to create the offsets 0,...,n-1 not necessarily in order but we don't care. [Answer] # Clojure, ~~137~~ 136 bytes ``` (defn h[c](loop[n(count c)](if(not(contains?(set(map #(=(first %)(last %))(partition n 1 c)))true))false(if(> n 2)(recur(dec n))true)))) ``` Ungolfed: ``` (defn head-eq-tail [col] (loop [n (count col)] (if (not (contains? (set (map #(= (first %) (last %)) (partition n 1 col))) true)) false (if (> n 2) (recur (dec n)) true)))) ``` [Answer] # Desmos, 43 bytes ``` f(x)=∑_{y=1}^{x.length}abs(x[y...]-x).min ``` Uses `0` for truthy, and any other positive integer for falsey. [Try it on Desmos!](https://www.desmos.com/calculator/khmwikhogw) [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 15 bytes ``` 0∊1⊥⍳∘≢↓⍤¯1∘.=⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbBINHHV2Gj7qWPurd/KhjxqPORY/aJj/qXXJovSGQq2f7qHfF/5LU4hKgyupHfVOB1KPerepW6hppQFqzlgsipl5SVFqSUanOBVJ6aIWChqGCoSaYBNPGCsYK5grGQJaRghFQDEiC2WAWmG0IVAHBMH3GQBljsAq4SVAIEoHZm5aYU4xiLcQwmCaQESZgB0AtgLLBPLi1CB7UQWBHolsLMvs/AA "APL (Dyalog Classic) – Try It Online") Returns `0` if there are such pairs, and `1` otherwise. [Answer] # [C (clang)](http://clang.llvm.org/), 78 bytes ``` h;r;d;i;f(*t,n){for(r=1,d=n;--d;r&=h)for(h=i=0;i+d<n;)h|=t[i]==t[i+++d];*t=r;} ``` [Try it online!](https://tio.run/##fZXbjtowEIbv9yksJKqcUDM5AfW6vaj6FIBWkDhL1MWgJFJpt7x6qRPbiTO7LTJxMt/v8cxPEvJF/rIXz/f7kda0oBUtHa8NhPtanmunZhAUTNDFoqD1B3Z0u@CRVSyklV88Cuoef7N2U@1Yd/R9v9hRr2U1vd0r0ZLTvhKOS14fiPx0gZY37RNsdoSRVwgI3OgYjsYwIrEicUDkWMqjDRMFo4BE/cruxObpwDVEPBu2jXtJ/Hb/pV1Z3KeITbqJcDVpwRpYuB6Ek1ogHONoBYCN5PbJhEaDRWMjE0FsC7RmIkiQD@9pUru/yBrYMcj@5YRq2dwQXi9vlFitDPTdoOdYz4meUz1nel7qeaXndWCsNCcmI5iUYHKCSQomK2RjbSoiVG1N9YufS0eJ3I/60tPXAbF5hHiEeIx4jHiCeIJ4iniKeIZ4hvgS8SXiK8RXiK8RXyMOITYoxIo3FmIPAZsI2EXANgL2EbCRgJ0EbCVgLwGbKQPWLcKvF563vPjP3S5H@O7QafKzaFqSH/e1J488/85rlW22vX6Lttf1V/lNZwGxr@OZXi3fx8TpKqlEwa9yWUj16aPpw9Q4NjJEKPH9Xu32ydR7enw0ZTr1ePaaHbUxEZrKJwTjsShdkCxG9Hu5g6b7XGopKp3ZvJkXssHqS9flp9lGTt1/ijvd8LAR1h4nfsovP52DlMp3oScscdlFBVrdyFK8wzTGZWz4BXETprgdWXwm84LMm62QhTXB8Cs1jHFT5O3hdv@Tly/75@a@@PEX "C (clang) – Try It Online") Inputs a pointer to an array of integers and its length (because poiters in C carry no length info). Returns, through the input pointer, \$1\$ if the array has pairs at every distance or \$0\$ otherwise. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` ⊙θ⬤θ∨‹μκ⁻λ§θ⁻μκ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMxr1KjUEfBMScHRPkXafikFhdr5OooZGvqKPhm5pUWa@QApUs881JSK0BKIGJgBRBg/f9/dLShjgIQGesoGIFJQzDDMDb2v25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Outputs an inverted Charcoal boolean, i.e. `-` if there is a distance with no pair, nothing if there is a pair at every distance. Explanation: ``` θ Input array ⊙ Any distance satisfies θ Input array ⬤ Every element satisfies μ Current index ‹ Is less than κ Current distance ∨ Logical Or λ Current value ⁻ Does not equal θ Input array § Indexed by μ Current index ⁻ Subtract κ Current distance Implicitly print ``` [Answer] # [Desmos](https://desmos.com/calculator), 63 bytes ``` k=l.length f(l)=0^{∏_{n=2}^k∑_{i=n}^k0^{(l[i-n+1]-l[i])^2}} ``` Returns `0` if truthy, `1` if falsey. [Try It On Desmos!](https://www.desmos.com/calculator/yjyiznpgr3) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/h2uvimo1yo) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` āsŒʒ¬Qθ}€gêQ ``` I have the feeling this can be shorter. EDIT: And it defintely can: see [*@CommandMaster*'s 05AB1E answer, halve the size of mine](https://codegolf.stackexchange.com/a/249436/52210). I do like how this challenge can be done with a lot of different approaches, though. [Try it online](https://tio.run/##yy9OTMpM/f//SGPx0UmnJh1aE3huR@2jpjXph1cF/v8fbaijAETGOgpGYNIQzDCMBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/I43FRyedmnRoTeC5HbWPmtakH14V@F/nf3S0oY5hrA6IBNPGOsY65jrGQJaRjhFQDEiC2WAWmG0IVAHBMH3GQBljsAq4SVAIE4Hog/OAqk3AdkHNgrLBPLgNCB7UbrB70G0AmR0LAA). **Explanation:** ``` ā # Push a list in the range [1, (implicit) input-length] s # Swap so the input-list is at the top Œ # Pop and get all its sublists ʒ # Filter this list of sublists by: ¬Qθ # Check if the first and last items are the same: ¬ # Get the first item (without popping the list) Q # Check for each item if it's equal to this first item θ # Then pop and push the last check }€ # After the filter: map over each remaining sublist: g # Pop and push the length ê # Sorted-uniquify this list of lengths Q # Check if it's equal to the [1,length] list we created initially # (after which the result is output implicitly) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~13~~ 12 bytes ``` *FsMqVRQ>LQU ``` [Try it online!](https://tio.run/##K6gsyfj/X8ut2LcwLCjQzicw9P//aGMdYx1DHeNYAA "Pyth – Try It Online") -- [Truthy test suite](https://tio.run/##K6gsyfiv/F/Lrdi3MCwo0M4nMDRQwdb1//9oQx0Fw1guMAVhGesoAJE5kARyjHQUjMAyIAaED@VA@IZgxXASYZIxWIkxTDmSFUgILAEA) -- [Falsy test suite](https://tio.run/##K6gsyfiv/F/Lrdi3MCwo0M4nMDRQwdb1//9oQx0Fo1guMKWjYAhnGesomAA5QMoQzAGRcD5UCKIYixDECDgyRJZAQ0axAA) Outputs zero for false, non-zero for true. Pretty much a port of Command Master's [05AB1E answer](https://codegolf.stackexchange.com/a/249436/65425) but double the length :/ Pyth has a prefix function (`._`) but no suffix function, so building the suffixes costs a few extra bytes with `>LQU`. [Answer] # [R](https://www.r-project.org), 90 bytes ``` \(x,l=length,n=l(x),m=1:n)l(table(abs(outer(m,m,Vectorize(\(a,b)(x[a]==x[b])*(a-b))))))==n ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVE7jsIwEBUtp7C2GqOhCAGxWmmuscUChY0cQJoElDhS2KvQhIJDsafZxHZIUmCN5vPm92zf7nn9N1nZvLTHqyDBp8LCHiIUkURvgxujaGTd6DZaoFi4XOsEIEQBiFz9Sw_Gxa4o7hqGiwbiMnKaKC7GxLrpg1Y_bhlo9pt7IGAjYmOsZ99d7Q0xR6EhRo_SJvPP588WKmRikx3sETNiqCSmFH1lksEqzQaULuBcWpNDiil-m70956dfA1tQqCVUG7UjqjZ6J2eg5lq6Q5SFDR-sLhe-gv8lFImcBsS9Tgv4yrr29h8) Just checking that all distances are represented in the matrix of distances (where elements are zeroed for non-matches). [Answer] # [Julia](https://julialang.org) ## 52 bytes ``` !X=0:length(X)-1⊆[I[1]-I[2] for I=findall(X.==X')] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBLUbtkqLSkoxK22iuaEMdBcNYHQgNZRrrKACROZAE8Yx0FIzAciAGVADKgwoYgtXDSSTjjMGKjGEakC1CQlCZWK60xJximKNgJiNpgxhlAnUiwlaEAFQMxVGoYgiXw7yFw1FQJ8RyLS0tSdO1uGmiGGFrYJWTmpdekqERoalr-KirLdoz2jBW1zPaKFYhLb9IwdM2LTMvJTEnRyNCz9Y2Ql0zFqrXAyQbYQsJdC4FBYfE4uLUohIFoJEgwVSu1LwULi6IInAYoKkBiYEVQcxbsABCAwA) ## 45 bytes - thanks to @MarcMush ``` !X=keys(X)⊆findall(X.==X').|>x->x[1]-x[2]+1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBLUbtkqLSkoxK22iuaEMdBcNYHQgNZRrrKACROZAE8Yx0FIzAciAGVADKgwoYgtXDSSTjjMGKjGEakC1CQlCZWK60xJximKNgJiNpgxhlAnUiwlaEAFQMxVGoYgiXw7yFw1FQJ8RyLS0tSdO1uKmrGGGbnVpZrBGh-airLS0zLyUxJ0cjQs_WNkJdU6_GrkLXriLaMFa3ItooVtsQqikwLb9IIcIWEtpcCkBQUJSZV5KTpxFha6cYocmVmpfCBRPS5OKCKAcHAw7VEIMXLIDQAA) [Answer] # x86 32-bit machine code, 18 bytes ``` 57 89 D7 49 AF 60 89 D6 F2 A7 61 E1 F7 0F 94 C0 5F C3 ``` [Try it online!](https://tio.run/##fVPRbpswFH3GX3HLlMluaZRAt1Vh2Uuf97KnSWkUucYES2AQNhsp4tfHLk7IUCdVsizuOeeeeyRfRFXdH4UYBm4KoPDDpyTdeFVjMpCJIl5R/ho/Arxa4iVSgBQtqTeeEdwkxCn5RWYmWS0rLUEUlVOUFQrysqxeoSaekfYVeO7w84haWsJ8YDGRrZW1Bv/Jh8OBW1url8bKw4HSlBsreJ4zBiLjNaRUaQs6AFFqY2Esbjk6kA9Ki7xJJHw1NlHlMvtGiLHcKgHG1o2wYOVoZSR0ziJ2zXz3uI97MnFmt4ctdKQLA@jWAaz7PiBddCmm@gFrxPB8wdtBnxDCntCpxo85eoEm9PPZLnJENPN9vM6JnDyaWt/S83OlL5HDeeRwHnk9mT5cw80zRG/QC/F/5DnxL1M4O@v3I08p@5iMb1BwpSkjHfHSsgZ6flne2BI@Wthc380w4nlVjR0p9RfqWfsBroNd4jLYJWe4BFf2WX/nIlPjLpaJ3PgjN05q8XFXAZywTEroJjksVuFPdDttKW20UUctE7dutyxlu/bubs/iHn5nKpdAT3CDJu1TNB8IdKHg5YRRmcvVjiTud4NbvYpJPwx/RJrzoxnuiyjEC/@6LbbK/C8 "C++ (gcc) – Try It Online") Following the `fastcall` calling convention, this takes the length of an array of 32-bit integers in ECX and its address in EDX, and returns 0 or 1 in AL. In assembly: ``` f: push edi # Save EDI onto the stack. mov edi, edx # Set EDI to the array address. dec ecx # Subtract 1 from the length in ECX. r: scasd # Advance EDI, also performing an unnecessary comparison. pusha # Push all the registers onto the stack. mov esi, edx # Set ESI to the array address. # The distance between EDI and ESI increases each iteration. repne cmpsd # Compare values at addresses EDI and ESI and advance both, # repeating ECX times but stopping if they are equal. popa # Restore all registers' values from the stack. loopz r # Subtract 1 from ECX, and jump back if it's nonzero # and the result of the last comparison is equal. setz al # Set AL based on whether the result of the last comparison is equal. pop edi # Restore the value of EDI from the stack. ret # Return. ``` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 41 bytes ``` a->sum(i=1,#a,prod(j=i,#a,a[j]-a[j-i+1])) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVBLCsIwEMWbDLpJMFmkFeymvUgJMiCVFD-htgvP4qYg4pn0NCbp1KYLYZh58-b3kvvLYmN2B9s_KsifXVvJ7M1RFtfuxEyuxAqFbS57VufGYyxrLZ2TZq0058PAZ5GhtccbQ5AF2MacWweXPllCxZBzAWWpBCjtgI8EUwHOts77LBGQhJoHRFBGhAr9Px-tS0NTOg7EhyKLKuO-mAoLNiRsujURxM2kzLlJ7_iYP1KCBE0f2PdD_AI) Returns `0` for truthy, other integers for falsy. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` v=ṘÞḋṠA ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwidj3huZjDnuG4i+G5oEEiLCIiLCJbMSwgMV1cblsxLCAxLCAxXVxuWzMsIDMsIDcsIDNdXG5bMiwgMiwgMSwgMiwgMl1cblsyLCAxLCAyLCAyLCAyXVxuWzEsIDMsIDEsIDMsIDEsIDFdXG5bMSwgMSwgMywgMiwgMywgMSwgMiwgMV1cblsxLCAxLCAxLCAxLCAxLCAxLCAyLCAxXVxuWzEsIDJdXG5bMSwgMiwgMV1cblsxLCAyLCAzLCA0XVxuWzMsIDEsIDMsIDEsIDNdXG5bMywgMSwgMSwgMywgMV1cblsxLCAzLCAxLCAxLCAzLCAxXVxuWzEsIDEsIDIsIDIsIDIsIDIsIDEsIDFdXG5bMSwgMSwgMSwgMSwgMSwgMSwgMSwgMl0iXQ==) Lyxal never posted my golf, so here goes [Answer] # [Scala](https://www.scala-lang.org/), 94 bytes Golfed version. [Try it online!](https://tio.run/##hVJba4MwFH7vrzhIHxJQwXYw6FAYexiDPQy6PYkPpzbadN6WpIUh@e1OU227aRmc3L7vy7kkR8aYYVNu9ixW8IaCP1fv5boDoZ4BbFkCOfKCoEjlCh6FwO9wrQQv0oiu4KPgCnyjBDhiBopJ9YSSyRZ95VIRw8Bp79ngUfsvMgKXNrR2386/8YUNC6PvNiOqx0eUZ7yd58kElubicnAyneSVTWrGcadlJtDdqORLnlNUz94o7RZ7eZPh6f4tzRRiJHRmlvOPukkpGMY7qM8Y@EHvrWo7QmUFkda8Hlg3/zx1CrFCy4beIotqcAKY1wkZlFRbp5h61o2m67qE4GrNvsKXQkXUr48oYOOjm7EiVbsH4oEqYUPdHKua@wHhV@e9HyDZOx51uoVT7Vai3B5ipV15yHWjmx8) ``` def f(a:Seq[Int])={var b=a.length;(1 to b).map{i=>(i to b).map{j=>a(j-1)-a(j-i)}.product}.sum} ``` Ungolfed version. [Try it online!](https://tio.run/##hVLLasMwELz7KxaTgwSOwHGhEEig9FAKPRTSnkwOW8d25PqFpBSK8be7svxqaoeCLC0zo91ZeWWAKTZN8ZGEgYJXFPypfCsOLQqVBXAKI8iQ5wRFLLfwIAR@@wcleB4f6Rbec65gZ5QAX5iCCqV6RBlKjb5wqYhhoItdB1zq/EVmoOeAXvd6v8Y3DmyMvg1mVI/PKNdkG/dFA5656A1Jlk3@Wouaed1lmSl0N2t58rlE9eyN1m6x05sMT/dva6YRI6GWOcY/yqJChBicoRox2O37bKWeCJXmRNqramBZ9tlNCrF924F@HW1aw3oPqyoig5LWdlezttqvn7uI4NbY9J9z1U6bPsZhIy6oApClYR6rM2UZltoYnxwRviRIJgEAkgTW@kn01oWc9lzNSlGcLoHqXDF5yYyz2mqaHw) ``` object PariGpToScala { def main(args: Array[String]): Unit = { val testCases = List( List(1, 1), List(1, 1, 1), List(3, 3, 7, 3), List(2, 2, 1, 2, 2), List(2, 1, 2, 2, 2), List(1, 3, 1, 3, 1, 1), List(1, 1, 3, 2, 3, 1, 2, 1), List(1, 1, 1, 1, 1, 1, 2, 1), List(1, 2), List(1, 2, 1), List(1, 2, 3, 4), List(3, 1, 3, 1, 3), List(3, 1, 1, 3, 1), List(1, 3, 1, 1, 3, 1), List(1, 1, 2, 2, 2, 2, 1, 1), List(1, 1, 1, 1, 1, 1, 1, 2) ) testCases.foreach { testCase => println(s"${testCase.mkString("[", ", ", "]")} -> ${f(testCase)}") } } def f(a: List[Int]): Int = { (1 to a.length).map { i => (i to a.length).map { j => a(j - 1) - a(j - i) }.product }.sum } } ``` ]
[Question] [ **The input:** As an example, take a list containing a number of bits (in this case, 32): ``` 11000010000100111011000011001011 ``` We can calculate a simple [checksum](https://en.wikipedia.org/wiki/Checksum) of this data by dividing it into evenly sized blocks, and taking the XOR of each of them. For example, with eight bit blocks: ``` 11000010 00010011 10110000 11001011 10101010 ``` We then append this to the end, making it 40 bits: ``` 1100001000010011101100001100101110101010 ``` This will be the form your input is given in. To validate a checksum in this form, you just take the XOR of each block, including the checksum. If it's valid, it will result in a string of zeroes. **The challenge:** I've got a bunch of data with checksums. The problem is, I don't remember what the block size was! Your task is to write a program or function which takes input of any length, and returns all of the block sizes where the checksum is valid. Blocks with sizes that do not fit evenly into the input should be ignored (so `7` would not be allowed in the output given `00000000`). In the example above, the valid block sizes would be `[1, 2, 4, 8]`, and the invalid ones would be `[5, 10, 20]`. Note that block sizes of one are possible (valid if the XOR of every bit in the string results in 0). A block the size of the entire string is not valid (so `8` would not be allowed in the output given `00000000`), and blocks with sizes less than two do not need to be handled. You can produce output and take input in any reasonable manner, such as lists of bits, strings of `0`s and `1`s, integers representing the binary values, etc. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes per language wins! **Test cases:** ``` 1100100001000000 -> [1, 2, 4] 010010100100 -> [1, 2, 3] 0000000000 -> [1, 2, 5] 101101000 -> [1, 3] 10010110 -> [1, 2] 10000000 -> [] 0101010 -> [] 11 -> [1] 1 -> (does not need to be handled) -> (does not need to be handled) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 8 bytes Input is a list of bits. ``` gѨʒιOÈP ``` [Try it online!](https://tio.run/##yy9OTMpM/f8//fDEQytOTTq30/9wR8D//9EGOoY6BjoQEsEyiAUA "05AB1E – Try It Online") **Commented**: ``` gÑ # push the divisors of the length of the input ¨ # remove the last one (the length itself) ʒ # filter this list on: ι # push [a[0::b], a[1::b], ..., a[(b - 1)::b]] where a is the input b the divisor # this groups the digits from each group at the same index together O # sum each list ÈP # are all sums even? ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~33~~ ~~31~~ ~~28~~ ~~30~~ 33 bytes ``` {((|/2!+/#[;x]0N,)')_&~(!#x)!'#x} ``` [Try it online!](https://ngn.bitbucket.io/k#eJyNjk1qwzAQhfdzimc5VBJ2aslONhHkCLlAMKXFClkUe1EtDGlz9ugnGMfe9I0YZuZjRu9yuAnxW9VZUeVnM7bqVEouP97uIstHmfF8/CMid3jnfCOY1kr590xKMcNUHKV5aCf5xs8jSrWKbSpn2yHCUDNTMp8Yk1QIZy7cSaKKln8C2yNw1iXqEruW5gYQNeON55OAFd+3NJnEkjcBJtdYwTrCl7tPGC2FwApojYXSOU+WIBLRDfYH/eDQW9vBDfiyuH723bftJK1W/rHzABIUYO8=) Takes input as a list of `0`s and `1`s. * `&~(!#x)!'#x` divisors of the length of the input * `((...)')_...` drop records from the right side (divisors) if the left side (run on each divisor) is truthy * `#[;x]0N,` split the input into equal pieces, each of length corresponding to the current divisor * `|/2!+/` are there an odd number of 1's in any "column" of the split-out input? [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 29 bytes ``` D,g,@@,T2€BbB^ L,bLd1_Rþ%A$þg ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ13HwUEnxOhR0xqnJKc4Lh@dJJ8Uw/igw/tUHVUO70v/r5KTmJuUkqhgaBdtqGCoYACF6CxDBYgsqhpDuAqEPBzHcvlzIZlugKIabjKGKgyIpsKQgKwhUOQ/AA "Add++ – Try It Online") I'm surprised Add++ was this short. Takes input as a list of bits ## How it works ``` D, ; Define a helper function g, ; called g @@, ; that takes 2 arguments e.g. [8 [1 1 0 0 0 0 1 0 0 0 0 1 0 0 1 1 1 0 1 1 0 0 0 0 1 1 0 0 1 0 1 1 1 0 1 0 1 0 1 0]] T ; Split into chunks; [[1 1 0 0 0 0 1 0] [0 0 0 1 0 0 1 1] [1 0 1 1 0 0 0 0] [1 1 0 0 1 0 1 1] [1 0 1 0 1 0 1 0]] 2€Bb ; Convert from binary; [67 200 13 211 85] B^ ; Reduce by XOR; 0 L, ; Define an unnamed lambda ; Example argument: [1 1 0 0 0 0 1 0 0 0 0 1 0 0 1 1 1 0 1 1 0 0 0 0 1 1 0 0 1 0 1 1 1 0 1 0 1 0 1 0] bL ; Length; 40 d ; Duplicate; [40 40] 1_ ; Decrement; [40 39] R ; Range; [40 [1 2 3 ... 37 38 39]] þ% ; Filter false Mod; [1 2 4 5 8 10 20] A$ ; Push the argument below; [[1 1 0 ... 0 1 0] [1 2 4 5 8 10 20]] þg ; Filter false on g; [1 2 4 8] ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes ``` ⟨{ġ\+ᵐ~×₂ᵐl}ᶠxl⟩ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSu9qhtw6Ompoe7Omsfbp3w/9H8FdVHFsZoA9l1h6eDJLZOyKl9uG1BRc6j@Sv/Y8rpqeXYgeT/R0cb6BjqGOhASATLIFYn2kAHEwKFIQoRyg2gYjAjDJFE4BBsnCHCGrAKw9hYAA "Brachylog – Try It Online") ``` ⟨{ġ\+ᵐ~×₂ᵐl}ᶠxl⟩ ⟨ x ⟩ remove l the input's length from { }ᶠ all results of: ġ split the input into equal sized groups \ transpose +ᵐ the sum of each column is ~×₂ᵐ the result of a multiplication of some number by 2 l get the length of the block ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` fö¬ΣFz≠C¹hḊL ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8X/a4W2H1pxb7Fb1qHOB86GdGQ93dPn8//8/OtpAx1DHQAdCIlgGsTrRBjoYECgKUYdQDRODmWCIJIKsD2EDTIUhhISrQmcZwu1BlkG1C8lMsLmxAA "Husk – Try It Online") ``` f # filter truthy elements x of ḊL # the divisors of the length of the input h # except the last one (the length itself) # using this function: ö # apply 4 operations: ¬ # NOT Σ # the sum of F # folding each pair of elements by z # zipping each pair together by ≠ # xor (not equal) C¹ # to the input split into blocks of size x ``` [Answer] # [Ruby 2.7](https://www.ruby-lang.org/) `-nl`, ~~85~~ 75 bytes *Saved a whooping 10 bytes, thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)!* ``` p (1...~/$/).select{|i|~/$/%i+eval($_.scan(/.{#{i}}/).map{|i|i.to_i 2}*?^)<1} ``` [Try it online!](https://tio.run/##RYvRCgIhEEXf/YqFNnCLxpmeg/6kxZZ9EEwlLQjXPj1Ti5p7GeYe7lxv50fOruMEAE/RiwH8rOcpxEUtNa/Vdr5LzfsR/CQNFxBXUaVUihfpaktBsKPq9mlzPA0HSjkTIRZ/FyLDBj6U4W9YYQ3XC1tghP@fKkbE6GVdUNb4vDP6DQ "Ruby – Try It Online") TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, i.e., `_1`, which saves 2 bytes. [Answer] ## [SageMath](https://www.sagemath.org/), ~~99~~ 104 bytes ``` f=lambda s:[d for d in divisors(len(s))[:-1]if 0^eval("^".join(["0b"+s[x:x+d]for x in(0,d..len(s)-1)]))] ``` The two instances of the `^` operator here are actually different operators! Sage [preprocesses the source code](https://doc.sagemath.org/html/en/reference/repl/sage/repl/preparse.html) to treat `^` as exponentiation, but `eval` is just ordinary Python eval, which treats `^` as bitwise xor. The expression `0^X` is used as a shorter way to express `X==0`. It works because 0⁰=1, whereas 0ⁿ=0 for non-zero n. (This trick was used by Julia Robinson in her work on Hilbert’s Tenth Problem, and is employed in the famous paper [*Diophantine representation of the set of prime numbers*](https://www.jstor.org/stable/2318339).) This function takes its input as a string of zeroes and ones, and returns a list of numbers. --- **Edit**: Thanks to ovs for pointing out that I had overlooked the part of the problem statement that says blocks the size of the whole string are not allowed. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` LÆḌs@^/ẸɗÐḟ ``` [Try it online!](https://tio.run/##y0rNyan8/9/ncNvDHT3FDnH6D3ftODn98ISHO@b/D3vUtOZwu@bRSQ93zvj/X8nQ0AAIYIQhkAsVAfEgfDBU0lFQMoCIgVWC@XAA4oF1ghCEA9YNlUAoQjLN0FAJAA "Jelly – Try It Online") Input as a list of bits, the Footer does this for you ## How it works ``` LÆḌs@^/ẸɗÐḟ - Main link. Takes a list of bits, B, on the left L - Length of B ÆḌ - Proper divisors ɗÐḟ - Filter proper divisors k, keeping those which return False: s@ - Split B into pieces of length k ^/ - Reduce columnwise by XOR Ẹ - Are any true? ``` Monads you could use instead of `Ẹ`: * `S`: Sum of columns * `T`: Indexes of non-zero elements * `Ḅ`: Convert from binary * `Ḍ`: Convert from decimal * `Ṭ`: Generate an array which would yield the original argument under `T` * `Ṁ`: Maximum * `§`: Sum of rows [Answer] # [Perl 5](https://www.perl.org/) `-lF`, 68 bytes ``` map{@a=$i=0;//;map$a[$i++%$']+=$_,@F;@F%$_+(grep$_%2,@a)||say}1..$#F ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saDaIdFWJdPWwFpf3xrIVUmMVsnU1lZVUY/VtlWJ13Fws3ZwU1WJ19ZIL0otUIlXNdJxSNSsqSlOrKw11NNTUXb7/9/Q0AAIYIQhkAsVAfEgfDD8l19QkpmfV/xf19dUD8j/r5vjBgA "Perl 5 – Try It Online") [Answer] # [Python 3.8](https://docs.python.org/3.8/), 110 bytes ``` lambda n:(l:=len(n))and[b for b in range(1,l)if not(eval('^'.join('0o'+n[a:a+b]for a in range(0,l,b)))or l%b)] ``` [Try it online!](https://tio.run/##TU/RToQwEHy/r9gXs91cNe1xRkOCP8JhUqB4aC0EqlEJ345t4U63m3Zmmul2@m937mzy2A9Lk50Wo97LWoFNmUkzoy2zRMrWeQlNN0AJrYVB2RfNJDfUNmA7x/SnMgyf8e61ay1D0eHe5ipV@7IIJvVnEtzwkoi8am5KKhanRzdCBgylFML3tgmBHEWUVj3Qa3ni9Xi1YhHpCv@5wwqiRE47/dXryuk6TMslhwOHY8E3lFzR/Yougj/WloV/ozrr6k0P8cOnj8PDsUIOEckEaRfSOq5D3p@2ZzEch8tgSnfgK8RtmKNI@qG1jjU4uRlun2AaZ5i2IfmYZbqYkZZf "Python 3.8 (pre-release) – Try It Online") Inputs a string of \$1\$s and \$0\$s and returns a list of all possible block sizes where the checksum is valid. [Answer] # [Python 3](https://docs.python.org/3/), ~~94~~ 86 bytes Input is a list of bits. ``` lambda s:[d for d in range(1,len(s))if~-any(len(s)%d+sum(s[x::d])%2for x in range(d))] ``` [Try it online!](https://tio.run/##RY3BCsIwDIbvPkUuYwlOafVW2JPMHSrdtNDVslbYLr56bTtxSQj5v5@fuDU8X/Yax/YWjZzuSoIXnYLxNYMCbWGW9jEgb8xg0RPp8XOSdsVNVuro3xP6bhFC9VRdcmzZY4qoj5mFwYeMa84ZS/NbjAErYKPA/gWJFZwvVgRwtmdyA@f12TujA5I4ABhowWgfcJIOtQ1NeUuULDcnjSMaovgF "Python 3 – Try It Online") **Commented**: ``` lambda s:[ ] # lambda function with a list of digits s as input and a list of integers as output d for d in range(1,len(s)) # take the block size d in 1,2,...len(s)-1 if ~-any( for x in range(d)) # if for no index in 0,1,...,d-1 len(s)%d # the block size does not divide the input size +sum(s[x::d])%2 # or there is an odd number of 1's at this index ``` --- # [Python 3.8](https://docs.python.org/3.8/), 86 bytes Same length as a recursive function ``` f=lambda s,d=1,x=0:s[d:]and[x][d-x:]+f(s,d+(w:=len(s)%d+sum(s[x::d])%2+x//d>0),~-w*~x) ``` [Try it online!](https://tio.run/##RY3BCsIwDIbvPkUuY4mbmupFCvVFxg6TbjjourJWVi@@@qxTNAk/@b@fEPcIt9Gezm5alk6ZZrjqBnyplSijYukrLevG6irWld5FWRcdprTAWSrTWvSU6cLfB/RVlFLXlB2LeDjoC1P53M3bZ6SlGycIrQ/QW8iFYE7zFWbgFXwo8K8gsRW/N14NCP7fvBuEyPfemT4gyQ2AAQWm9wGHxmFvQ7m@JUqRm5LHDg3R8gI "Python 3.8 (pre-release) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 62 bytes ``` sTr/@Mod[i=0;1+##&@@s~Partition~UpTo@i++&/@s,2]~Cases~{1..} ``` [Try it online!](https://tio.run/##TYxBCoMwEEX3HiMBN1pNui2WAemyYKldiYtgU8xCI0kKBTGH6A16wh4h1VRKZ4bPvP@Z6ZhpeceMaJi7ZU6/n69SpXCU10pkZEcjjEMAbQumjDBC9vYylBJEFIUp6Hhb25xpru1Ik2Ryp7vgpiqU6E2FN/sblPLwGBTXer6EvGWKNYYrDbgO7blhvR0DRCkh86xCCIoDRLz3DTz/aqE58eEKxPO6/79Y2tsUBVPtPg "Wolfram Language (Mathematica) – Try It Online") Input a list of bits. Xor gives the same result as the sum of its arguments mod 2, but `Xor` is not `Listable`, while `Plus` and `Mod` are. Mathematica's `Listable` functions only reduce when all arguments are lists of the same length or scalars. Thus if the block size does not evenly divide the total length, so `Plus` remains unevaluated. The resulting expresion `Plus[...]` cannot be matched by `{1..}`. ``` Mod[i=0;1+##&@@s~Partition~UpTo@i++&/@s,2] (* calculate bitwise complements of possible checksums of the input *) % ~Cases~{1..} (* find those which only contain 1s *) Tr/@ % (* get the length of each. *) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` IΦLθ∧ι¬∨﹪Lθι⌈﹪↨ΣE⪪θι⍘λ⊕Lθ⊕Lθ² ``` [Try it online!](https://tio.run/##dY3NCsIwEIRfJcctRIhePakgCLYKeYIlCW0gP226Fd8@Jv6gF4edgeVbdtSASUV0OV@TDQQHnAmO1pFJcDahpwGmhrNd0GA56yLBJUEb9eLiL7fFLd6tX/yH7nE2IOuOI8jRWYLpdViJpFLXg@PsFFQy3gQy@vux6i/ibNO8tc1ZrEWZZ4i8urkH "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Charcoal has no bitwise Or operator nor an easy way to reduce it over an array so I emulate it by performing a sum using a large base and then separately reducing each digit modulo 2. ``` θ Input string L Length Φ Filter over implicit range ι Current value (i.e. is non-zero) ∧ Logical And ¬ Logical Not Lθ Length of input string ﹪ Modulo (i.e. does not divide by) ι Current value ∨ Logical Or θ Input string ⪪ ι Split into substrings of current length E Map over substrings λ Current substring ⍘ Convert string from base ⊕Lθ Incremented input length Σ Take the sum ↨ Convert to array using base ⊕Lθ Incremented input length ﹪ ² Vectorised modulo by 2 ⌈ Take the maximum i.e. are any odd? I Cast to string Implicitly print ``` [Answer] # Scala, ~~95~~ 93 bytes ``` b=>1.to(b.size/2)filter{s=>b.grouped(s).reduce((_,_).zipped.map(_^_)).toSet==Set(b.size%s*2)} ``` [Try it online!](https://scastie.scala-lang.org/NkFGxpSqSq6zSwD8vPqwEw) Accepts input as a list of ints. `b` is the input block. `1.to(b.size/2)` is a range of all possible block sizes, and `filter{s=>...}` is used to keep only those that divide `b` evenly and that result in a string of zeroes. `b.grouped(s)` splits `b` into chunks of size `s`, then `reduce` is used to xor all the chunks together. The function to reduce with is `(_,_).zipped.map(_^_)` (the underscores are placeholders for actual parameters). `(_,_).zipped` zips the two lists together, and `map(_^_)` applies xor to each pair in both lists. Finally, `toSet` is invoked on the result of xor-ing the chunks together, so now it's either a `Set(0)` if it had only zeroes, or `Set(1)` or `Set(0,1)` if it had ones. We can check both that this result is `Set(0)` and that `s` divides `b` evenly by comparing that set with `== Set(b.size % s * 2)`. `b.size % s * 2` will be 0 if `s` divides `b` evenly, but if not, it will be 2 or some higher number, not `1`. The result from earlier can only contain a `0` or `1`, so it will only match if `b.size % s` is `0` and the result from earlier is a `Set` with just a `0`, checking both conditions at once. [Answer] # [Pip `-n`](https://github.com/dloscutoff/pip), 31 bytes ``` {!#y%a&!$BX(FB_My<>a)}FI1,--#Ya ``` [Try it online!](https://tio.run/##K8gs@P@/WlG5UjVRTVHFKULDzSnet9LGLlGz1s3TUEdXVzky8f///waGBkAEJgz@6@YBAA "Pip – Try It Online") Input as a string of 0s and 1s. ## Explanation ``` {!#y%a&!$BX(FB_My<>a)}FI1,--#Ya a → input 1,--#Ya range 1..length(a)-1 Ya store input in y { }FI filter each i by the following: #y%a length(a) mod i ! logical not (is divisor) & and y<>a input split into chunks of length i FB_M mapped from binary to decimal $BX( ) folded by bitwise xor ! logical not (checksum validity) is true? join with newlines(-n flag) ``` [Answer] # JavaScript (ES10), 94 bytes Expects a string. ``` s=>(g=k=>s[++k]?[(h=i=>(t=s.substr(i,k))?t[k-1]?'0b'+t^h(i+k):~0:0)(0)?[]:k,g(k)].flat():[])`` ``` [Try it online!](https://tio.run/##dc/JDoIwEAbgu0/RcHEmLE5dLiSFB2lqxIXFEjG2evTVEVERFWeaHpqv/7T75JKYzak4Wv9QbXd1KmojIsiEFpGRrqtVLCEXRXNmhQnMeW3sCQpPI8ZWap@reEzrsWuXORSuxvBKISEQxlKF2stAowrSMrGAoVS4WtWb6mCqcheUVQYpOJwTNeu5ETmIbDJhknts6rG5Gn15av3jksOa@vCzX99Vq7/84sc32W38i/f8bABT61@2Hz6E@@/o8NAX7925v5Dzt/kYr@ob "JavaScript (Node.js) – Try It Online") ### Commented ``` s => ( // s = input string g = k => // g is a recursive function taking a block size k s[++k] ? // increment k; if s[k] is defined: [ // begin an array: ( h = i => // h is a recursive function taking a counter i (t = s.substr(i, k)) // t is the next substring of maximum size k ? // if it's non-empty: t[k - 1] ? // if the size of t is k: '0b' + t // convert it from binary to decimal ^ // and XOR it with h(i + k) // the result of a recursive call to h : // else: ~0 // stop and invalidate the final result // (the length of s is not a multiple of k) : // else: 0 // stop )(0) // initial call to h with i = 0 ? // if the result is not 0: [] // append an empty array (removed by flat()) : // else: k, // append k g(k) // append the result of a recursive call to g ].flat() // end of array; flatten it : // else: [] // stop )`` // initial call to g with k zero'ish ``` [Answer] # [R](https://www.r-project.org/), 93 bytes ``` function(x,l=sum(x|1))which(!sapply(seq(l=l-1),function(n)l%%n|any(rowSums(matrix(x,n))%%2))) ``` [Try it online!](https://tio.run/##jZDtCoIwFIb/exWLEM6BBU4L@uNVdAFiZjiamzlNDe/dDPOrIGVsHNh59j47afPwBb94Z6GCm6f5M9Ruc81lkHEloaTC1XkMZc0Qi4gHEWy0nySiAh3eQbhix5AO7RKFacralxWkqjjlsYbYz1Jetg9JRNO0EbHJQp25AViUUYt251hZaPwIwZtAsiWM2MQxBv5nLbGHnu0yx@QF0plyvTFbzJtTqyylkqExG9Bnr4Var79Wk77B6Ltiw2ymN/O/T9RWTILsydFoXg "R – Try It Online") For each `n` up to the length of the input minus 1, rearranges the input bits into a matrix with `n` rows: the checksum is valid if the sum of every row is an even number. [Answer] # [Julia](http://julialang.org/), 71 bytes ``` a->filter(i->L%i<1&&!any(xor(a[j:i:L]...) for j=1:i),1:(L=length(a))-1) ``` expects an `Array{Bool}` [Try it online!](https://tio.run/##bZDPToQwEIfvfYqx0d02AdK6eiHCwZsJb4AcyG6rQ5qygZrgc5h48ul8EaRlXdhk@@/yffObZpoPg7UcRp2NdZxrNE51DOO8uMMnudnc1PaTDW3H6rJJMS2qJEk46LaDJpMp8kimrMiMsm/undWcx5KPTvWuhwxKQqUUYjqnRwgKkOUApYzgPoKHilARjFmbqF8rY@eN8zrxC@NxMqb6ELEIZ2MXsAjGQpeAGV@mz/jFunL@n98ruKZSrsEquiIVIcTPiWHUcEALYSyEeEfjNB7NntvWJGzfGqP2jiGHJIat2HIeJNTBy6Ah/9nHDq0zltHfny@gEaDvpnH2lenVNfN7ZUZAXx1Tw3FqqA5w23B6KrYH4u/4Bw "Julia 1.0 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 109 bytes ``` f s=[x|x<-[1..l s-1],rem(l s)x==0,not.or.foldr1(zipWith(/=))$x#map(=='1')s] l=length _#[]=[] n#x=x:n#drop n x ``` [Try it online!](https://tio.run/##XY7BasQgFEX3@YpHMjAKjtVOuynzvqMLkRJI0kiNkehChv57atI0dKIics99B/s6fLXWznMHAVX6TreLkpxbCBep2dQOJD9pQhTMjZGPE@9G20yS3I1/N7EnT0jpKVVD7QniWZ5p0IVF27rP2BcfldKodOGqhOnNVc00enCQ5qE2DhD8ZFwEDpsMSHZQHlxDwTgPJ8haIF1udCGuWbHkCIqUUgqRz3YJUTIlGTwzeNG0gHUxUoq19VvdG9eHxr52/vqf5@lVsOHrIxMr3iYP6E96@M@yD6mUi2FP9PwD "Haskell – Try It Online") If taking the input as a list of booleans counts as a reasonable manner it would go down to 99 (not sure if it does, though): # [Haskell](https://www.haskell.org/), 99 bytes ``` f s=[x|x<-[1..l s-1],rem(l s)x==0,not.or.foldr1(zipWith(/=))$x#s] l=length _#[]=[] n#x=x:n#drop n x ``` [Try it online!](https://tio.run/##XY7BasQgEIbveYohWVgF12q3vZSd5@hBpASSNFJjJHqQpe@emjQN3Ywiw3zf/NjX4au1dp47CKjSd7pdlOTcQrhIzaZ2ILmlCVEwN0Y@TrwbbTNJcjf@3cSePCGlp1QFXVi0rfuMffFRKY1KF65KmN5c1UyjBwdpHmrjAMFPxkXgsEUAIYiUB9dQMM7DCYbaA@mykZvMzvJMeRfiiotFQVCklFKIfLdHiJIpyeCZwYumBazFSClW61fdjeuDsdfOX//zvL0GbPj6yMSKt80D@gs9/Gc5h6mUS8I@0fMP "Haskell – Try It Online") ]
[Question] [ A *digit addition generator* of an integer `n` is any integer `x` that satisfy the equation `x + s(x) = n`, with `s(x)` being the sum of the digits of `x`. (We will work under base 10 for convenience.) For example, a digit addition generator for `29` would be `19`, because `19 + (1 + 9) = 29`. Some numbers have more than one generator. An example might be `216`, which has generators of `198` and `207`. Your objective is to generate the sequence `a_n` where `a_i` is the **lowest** digit addition generator of every non-negative integer `i`, and *anything other than a non-negative integer* if there is none for `i`. The non-negative terms in your result should match the sequence [A096234](https://oeis.org/A096234). You may find [this paper](https://arxiv.org/pdf/2112.14365.pdf) related to the challenge. Fewest bytes win; standard rules apply. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `gM`, 28 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 3.5 bytes ``` '∑+?= ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJnPU0iLCIiLCIn4oiRKz89IiwiIiwiMCJd) Outputs an empty list for no result. I think (spoiler I did) I ninja'd someone in the process of writing this lol. ## Explained ``` '∑+?= ' # filter the range [0, n] by: ∑+ # sum of digits + x ?= # equals input? # g flag prints minimum. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ý.ΔDªOQ ``` Outputs `-1` if there is no result. [Try it online](https://tio.run/##yy9OTMpM/f//8Fy9c1NcDq3yD/z/38gSAA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf8Pz9U7N8Xl0Cr/Q@sC/9fq/I82stQxMjTTMdAxBCEgNjLWsbQwN9Mx1AHKgMQsdAwtLWIB). **Explanation:** ``` Ý # Push a list in the range [0, (implicit) input-integer] .Δ # Find the first value of this list that's truthy for, or -1 if none are: D # Duplicate the current value ª # Convert the first value to a list of digits, # and append the duplicated number to this list O # Sum the list together Q # Check whether it's equal to the (implicit) input-integer # (after which the result is output implicitly) ``` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 44 bytes ``` f(n,i)=if(i>n,x,i+sumdigits(i)-n,f(n,i+1),i) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN3XSNPJ0MjVtM9M0Mu3ydCp0MrWLS3NTMtMzS4o1MjV18yAKtA01gaqgelTT8os08hRsFQx0FAwNgERBUWZeCVBESUHXDkgAdWhqQhXDLAIA) Returns `x` when there is no solution. [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs `-1` for no result. ``` ôÈ+ìxÃbU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9Mgr7HjDYlU&input=Mjk) (Eventually) outputs `undefined` for no result. ``` @¶X+ìx}a ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QLZYK%2bx4fWE&input=Mjk) ``` ôÈ+ìxÃbU :Implicit input of integer U ô :Range [0,U] È :Pass each through the following function + : Add ì : Convert to digit array x : Reduce by addition à :End function bU :First 0-based index of U ``` ``` @¶X+ìx}a :Implicit input of integer U @ :Function taking an integer X as argument ¶ : Test U for equality with X+ : Add to X ì : Convert X to digit array x : Reduce by addition } :End function a :Get the first integer >=0 that returns true ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 21 bytes Anoymous tacit prefix function. Requires 0-indexing (`⎕IO←0`). ``` ⍸⊢<\⍤=0,⍨⍳+1⊥¨⍎¨∘⍕¨∘⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/x/17njUtcgm5lHvElsDnUe9Kx71btY2fNS19BCQ1QckOmY86p0KpTf/TwNqAoo/6mp@1LvmUe@WQ@uNH7VNBBoXHOQMJEM8PIP/azzqXaWTdmiFJlCDoYERAA "APL (Dyalog Extended) – Try It Online") `⍸` where do we find that `⊢` the argument `<\` is the first (lit. cum. right-ass. less red.) `⍤` that:  `=` equals `0,⍨` zero appended to `⍳` the range `+` plus `1⊥` the sum (lit. base-1 eval.) `¨` of each of `⍎` the evaluation `¨` of each `⍤` of:  `⍕` the stringification  `¨` of each  `⍤` of:   `⍳` the range [Answer] # [C (clang)](http://clang.llvm.org/), 58 bytes *loops forever if there's no solution* ``` d,s;f(*i,n){for(*i=s=0;n-s;)for(s=d=++*i;d;d/=10)s+=d%10;} ``` [Try it online!](https://tio.run/##JY7BTsMwEETP8VesilLZjQMOB0S1OF/CJfLGraV0g@K0HKr8OmYLt5nZN6MNbZgGPpVCNmPUh2TZ3OO8iPLZO@Q2o3n47Mk3zSEhIb34zpnceKo7h1t5ShymK43wkVdK8/O5Vyrxqi5DYn2bExl1V5UkwBaWcUWlqu9zmkbQOQwc9a6mnYU9G@jBGRC4inovpAU2KO5rkfYfB20PNX2y8P9jj/smgyKvC4NDtZXX7u0nxGk45dLKSz68H38B "C (clang) – Try It Online") # [C (clang)](http://clang.llvm.org/), 70 bytes For comparison, this returns negative values when there's no solution. ``` g,o,l;f(*i,n){for(*i=g=-n;g++;*i=n+l?*i:-g)for(l=o=g;o;o/=10)l+=o%10;} ``` [Try it online!](https://tio.run/##LY7BTgMxDETPm6@wihYlTQK7IKGCm/IjXFZJk0YKTrXdcqn21wmuxMljz/hpvPVlotRaMtUUjHKbDalbrDMrl5wlTFoja9Llc5s/bFJ3s7jqElasz24cVNGu9uOAa3vI5Ms1HGF/WUKuT6eDEJkW8T1lkj81ByVuouMLkIH5uKAQHfNAEjgYEAj28MpTa1LAyS7KR44ZIIW8nWd@jXLTB7AH6MMXbcw/6e6vTGN5nYlZYm0v49uvj2VKl2a5j/O79z8 "C (clang) – Try It Online") [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~71~~ \$\cdots\$ ~~66~~ 64 bytes ``` [](int&n){for(int m=n,d=n=0,t;m-d;)for(d=t=++n;t;t/=10)d+=t%10;} ``` [Try it online!](https://tio.run/##VdHRbpswFAbg@zyFxbQJCmhgm3StcW6mPUWSC2RMhtqYCMwULcqrj/02oKZIcHx8vmNhW10u6UmpqRptRxo57Y9ha@w3E92arndDcpYmqaWRWWLFOa1F5Aq1tDKOjbDCfpd5FtWxtF/zTNwnsfnSGvU@1pqUbTfYXlfn3cPcH61s1@82fumqNWF02xA8g61fX@diidqO6OsFma6JJLcsIWmekHwOdA5sDnwOBcpgWwRkzwhgPxDAXhAWlsNRuByQuhySQuagFDSHpYulsAyWwjKXwzJYCstgKSxbLIPlsAyWuxyWwzJYDstg@WI5bAHLYQuXwxawHLaA5bDFui3YLWwBu3U57JbehT8z1ZnBEvW76p/w1epN9/ujO6/gcP1FD9eXn3iLICGPOQuWbtwj8Tfcmlpf0ZaJZVjOtzG0f3W4XkMkSBz7ckTmG3OPa7do9QXxaVpjem3e@/rxATQkBJDYY@S2YVsz6o9yE9ro82oDVrMfU/7/VDdaUpbrT5ckIOkOH4yGOfXj9WS0lMPRzx9MMC9139ynf6p5r07DlKZYVJ7MGMe0@g8 "C++ (gcc) – Try It Online") *Saved 6 bytes thanks to [c--](https://codegolf.stackexchange.com/users/112488/c)!!!* [Answer] # JavaScript, 49 bytes Loops forever, in theory, if there's no result but, in practice, throws a recursion error. ``` n=>(g=x=>n-eval([x,...x+``].join`+`)?g(++x):x)`0` ``` [Try it online!](https://tio.run/##BcFBCoAgEADA7@xiSnSqQHtIBCuRooSJieypr9tMtM2@Zwm5yjZ3p3vSBrxmbZK8mr1h50EpxYLoUPEJiQTh5kF@jCsjjdRzCamCg2lB7D8) [Answer] # [Raku](https://raku.org/), 34 bytes ``` {first 0..$^n: {$_+.comb.sum==$n}} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Oi2zqLhEwUBPTyUuz0qhWiVeWy85PzdJr7g019ZWJa@29n9xYqWCBlCBkYGmnZ2eWtp/AA "Perl 6 – Try It Online") Returns the `first` element of the range `0` through the input number `$^n`/`$n` such that the element `$_` plus the sum of its digits `.comb.sum` is equal to the input number. If there is no such number, `Nil` is returned. [Answer] # [R](https://www.r-project.org), ~~45~~ 46 bytes *Edit: +1 byte to correctly handle input of zero, but then -1 byte thanks pajonk for removal of useless accidental space* ``` \(n){while(n-F-sum(F%/%10^(0:F)%%10))F=F+1;+F} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHSnJTEdNulpSVpuhY39WI08jSryzMyc1I18nTddItLczXcVPVVDQ3iNAys3DRVgSxNTTdbN21Da223Wqguc5ARGkaWmlwQhqEZlGUApY01FZQV8vIVivNzSksy8_MUUisyi0uKIdoXLIDQAA) Tests increasing integers until it finds a solution, so loops forever if no solution exists. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 8 bytes ``` x|msajdT ``` [Try it online!](https://tio.run/##K6gsyfj/v6ImtzgxKyXk/38jQzMA "Pyth – Try It Online") Returns `-1` for no result. ### Explanation ``` x|msajdTdQQQ # implicitly add dQQQ # implicitly assign Q = eval(input()) m Q # map lambda d over range(Q): jdT # list the digits of d a d # append d to this list s # sum the list | Q # short circuiting or, does nothing unless the input is 0, then [] -> 0 x Q # find the first index of Q in the mapped list (or xors with 0 for 0), returns -1 if not found ``` [Answer] # [Arturo](https://arturo-lang.io), ~~40~~  35 bytes ``` $->x[0while[x<>+∑digits<=<=]->1+] ``` [Try it!](http://arturo-lang.io/playground?zkCRSL) Causes an infinite loop when there is no result. ``` $->x[ ; a function taking an integer x 0 ; push 0 to stack while[x<> ; while x doesn't equal... <=<= ; duplicate top of stack twice +∑digits ; digit sum then add ] ; end while condition ->1+ ; increment top of stack (while body) ] ; end function ``` [Answer] # [Elixir](https://elixir-lang.org/), 74 72 bytes ``` import Enum c=& &1-?0 r=&find(1..&1,fn x->&1==x+sum map'#{x}',c end)||-1 ``` [Try it online!](https://tio.run/##ZctBC4IwGIDhu7/iY8HcaA4/QcFgderQqZ8QphMGbslUGGS/fdUt6fw@rx5MMD5GY8eHn@HsFpu0igLF7JQnXtHeuI6hlBRF7yBkR4pKhf20WLDNmO6e4ZWKFrTr@LpmGC9Xadw06nZmn/49y1yA5wKG5q6HA5Dm5ghPfpyXrKg3oKj/BVZbghXh8Q0 "Elixir – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~89~~ ~~53~~ ~~49~~ 44 bytes ``` #&@@Pick[r=Range@#,r+Tr/@IntegerDigits@r,#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1nNwSEgMzk7usg2KDEvPdVBWadIO6RI38EzryQ1PbXIJTM9s6TYoUhHOVbtv39aWrRbaV5ySWZ@npVVcU5@SV4sV0BRZl5JdJqCvoMCxARjA4PY/wA "Wolfram Language (Mathematica) – Try It Online") Thanks to @ovs and @att! [Answer] # [Julia](https://julialang.org), ~~42~~ 37 bytes ``` ~n=argmax(x->x+sum(digits(x))==n,0:n) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FjdV6_JsE4vScxMrNCp07Sq0i0tzNVIy0zNLijUqNDVtbfN0DKzyNKGKg5UVXCsScwtyUq24HIoz8ssV6owMzbi4lBVCUotLirkcEouLU4tKFOoMFBRsbRUMEAJGliABQ0uEiLEBSMTIBGI0zD0A) -5 bytes thanks to MarcMush: use `argmax` instead of `findfirst` [Answer] # Java, 85 bytes ``` n->{for(int i=-1;i++<n;)if((i+"").chars().map(d->d-48).sum()+i==n)return i;return-1;} ``` Outputs `-1` if there is no result. [Try it online.](https://tio.run/##PZAxb4MwEIX3/IoTky2MVWiVQihZOjdLxjSDa0zrFA5km1RVxG@nNkkq@U728@l9T3cSZ5Gc6u9ZtsJaeBMaLysAjU6ZRkgFu/BcBJAkdKSlV6aVb9YJpyXsAKGaMdlemt4sM7pK0lLH8QuWVDeE6DiKKJdfwlhCeScGUifbOnnKKbdjR2isqwqpUW40CLq8XrzFNJeBM4wfrefccOde19D5oGTvjMbPw1HQa8g73inrXoVVG1Q/IfnheMkKlqVr9sDScHxlj6zIn9csZf4naDlLi3yiixHA/tc61fF@dHzwENciubvG0ebdRTFy@S/R206m@Q8) **Explanation:** ``` n->{ // Method with integer as both parameter and return-type for(int i=-1;i++<n;) // Loop `i` in the range (-1,n]: if((i+"") // Convert `i` to a String .chars() // Then to an IntStream of codepoints .map(d->d-48) // Then to an IntStream of digits .sum() // And sum those digits together +i // Add integer `i` ==n) // And if it's equal to input `n`: return i; // Return `i` as result return-1;} // If no result is found, return `-1` instead ``` Using a recursive function which throws a `StackOverflowError` when there is no result is also **85 bytes**: ``` n->f(n,0)int f(int n,int i){return(i+"").chars().map(d->d-48).sum()+i==n?i:f(n,i+1);} ``` [Try it online.](https://tio.run/##jZHPb8IgFMfv/hUvPUFKG@uMqza6w7Kj7uBlifPAKJ1oCw1QjWn6r6@Duh@HXUbgAe/B@3x5HOmZRsf81LOSGgNrKmQ7AhDScl1QxmHjt4MDGPJW4sx5upEzG5Cw7GW0KpAkY5z5cHE7RLwVuNXcNloiEQYBjtmBaoNwXNEa5dEqj6Ypjk1TIRyK5VI@iIVPJMIEZ12feULdvJWCgbHUuumsRA6Vk4i2Vgv5vttTfJNXKD1wLTf2kRq@kPziNe/27WROJsmMjEniuxuTOzJP72ckIS7ifSlJ5mmHh0QAVl/bryXA9mosr2LV2Lh2RFtK9I0Ig8WrDUIP8lVzz5Ix@4nioUq@dYxadnCKKTs9n11VS3V50lpp4Br/n/T3fvCLGD6k6z9UbYWSpo9ejJmuPwE) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes ``` NθI⌊Φ⊕θ⁼θ⁺ιΣι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMM3My8ztzRXwy0zpwQo65mXXJSam5pXkpoCVKmj4FpYmphTrFGooxCQU1qskamjEAxUnKkJAdb//xsZmv3XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Takes `i` as an input and outputs `None` if no generator exists. Explanation: Brute force approach. ``` Nθ First input as an integer θ First input ⊕ Incremented Φ Filter on implicit range ι Current value ⁺ Plus ι Current value Σ Digit sum ⁼ Equals θ First input ⌊ Take the minimum I Cast to string Implicitly print ``` 23 bytes for a less inefficient version: ``` NθI⌊Φ…·⁻θ×⁹Lθθ⁼θ⁺ιΣ⌈⟦⁰ι ``` [Try it online!](https://tio.run/##LYzLCsIwFET3fkWWNxDBumiQLkWhYKWoO3FxLaG9kETzKv59jMWBWZ2ZM0zohxfqnFv7TvGczFN5cLxZ9Z5shD2GCB1ZMsnAkXQstLWDToFmdUE7qh9NAZxgNzIqwE6wk7JjnIqFc8Fc6cEl1MumL08gwa5F1@Fn0d43gtGD/9PkXNVSym1V5/Wsvw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Starts checking for generators starting from `i` minus `9` times the number of digits of `i`. 28 bytes for a more efficient version: ``` NθI⌊ΦELθ⁻⁻θ﹪×⁵θ⁹×⁹ι⁼θ⁺ιΣ⌈⟦⁰ι ``` [Try it online!](https://tio.run/##LY3NasMwEITvfQofZXBgV1r9kWNooVCXQHsrPaiJSQSyHdtSyNurcpI9DMzOfMzh7ObD6ELO78Mlxc/U/3Uzm@rty372Q2Q7t0TW@sH3qWdvPsSStu7CPrrhFM@l2FQlTQt76FTseExhZN@@7xYmm2qt2LrI42ObyterfZ2SC3diHwrpm@qrTLTudp/6gdL7rZ@3zdmgkchJcUmouSCSIKTkGoG4skIDCa0ASmSUEVoaIrCkLFhQWiOalbIoyApURnLkqPLmGv4B "Charcoal – Try It Online") Link is to verbose version of code. Explanation: As above, but only checks for generators which when doubled are equivalent to `i` modulo `9` (because `i` equals the generator plus its digit sum but both the generator and the digit sum are equivalent modulo `9`) although it actually computes the maximum possible generator by subtracting `5i` reduced modulo `9` from `i`. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 73 72 bytes ``` n=>{for(int i=-1;i++<n;)if((i+"").Sum(d=>d-'0')+i==n)return i;return-1;} ``` [Try it online!](https://tio.run/##XVA9a8MwEJ2tX3FkiYQ/iFNobRx7CbRLC4UMHUoHVZbTA1tqJTmlGP929xIylA56evfupHd3yqfKOr2MHs0RDj8@6KFif6PsEc3XP2lv@16rgNb47EEb7VBVjH2O7z0qUL30Hp6dPTo5sIlFV90HGeg6WWzhSaLhgkWUje5Ho3ZoQgIEDXRQL6Zups46TgJgneYVxvHOVAI7zjFerUR2GAfe1k2brjdrEWNdG@F0GJ0BrK6Ens1LRQb0k5bqA/hJOkByAaO/z2avb9O2TGCb3yawSSC/nDNsbxIoizuScyJUcckUBGUxU9tRtKfRba@zF4dB04Y07zgKQXYzm5df "C# (.NET Core) – Try It Online") This is a C# port of this [answer](https://codegolf.stackexchange.com/questions/261861/lowest-digit-addition-generator/261871#261871). All the kudos goes to Kevin Cruijssen. I really like that .NET's `sum` is taking a lambda to avoid the common map followed by sum! [Answer] # [Python 3](https://docs.python.org/3/), 63 bytes ``` g=lambda n:min(x for x in range(n)if x+sum(map(int,str(x)))==n) ``` [Try it online!](https://tio.run/##DcgxDoAgDAXQq3Rso5NOmnCYGhWbyIcAJnh69I0vvfWKmHv37taw7UpYg4EbnTFTIwNlhT8YYie1oTyBgyY21LHUzE1EnIP0lP9iz9Mi0j8 "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 56 bytes ``` f=lambda n,o=0:(o+sum(map(int,str(o)))==n)*o or f(n,o+1) ``` [Try it online!](https://tio.run/##PcpBCoAgEAXQfadwOT9dZEFQ4GGMkIJ0RG3R6adWLR@8/LSD0yQS3OXjtnuVDLthJdb1jhR9pjM1U1shBuBcQs@Kiwr0RW0huXyBAo12BrpfCyAv "Python 3 – Try It Online") [Answer] # [Fig](https://github.com/Seggan/Fig), \$11\log\_{256}(96)\approx\$ 9.054 bytes ``` [KFax'=#x+S ``` [Try it online!](https://fig.fly.dev/#WyJbS0ZheCc9I3grUyIsIjIxNiJd) ``` [ # The first item from a # the range from 1 to x # the input, F ' # filtered by: S # the digit sum of n + # plus n = # is equal to #x # the program's input, K # sorted (smallest to largest). ``` [Answer] # Swift, ~~84~~ 80 bytes ``` {n in(0...n).map{($0,"\($0)".reduce($0){$0+$1.hexDigitValue!})}.first{$1==n}!.0} ``` Takes an `Int` in and returns an `Int`. [Try it online!](https://tio.run/##FcaxCsIwEIDhV7mWDDnUIxUXhTi5@AJOLkUTPWiPkl5RCHn2WJf/@@cPRz3UISjEE9irKMLuDKvgaxZgsY6IBGnsp2yN27b3tdhSCs/lEf6fjduYjt7he@EX660fltAULBQ5zZpN572UhlypU2JRG@3@iFh/) Ungolfed: ``` { (n: Int) -> Int in (0...n) // a sequence of all integers from 0 to n, inclusive // the parens are needed to avoid parsing as 0...(n.map) .map { i in // transform each one ( // return a tuple of: i, // 0. the integer itself "\(i)".reduce(i) { $0 + $1.hexDigitValue! } // 1. the digit sum plus the number // technically, wholeNumberValue would be more correct than hexDigitValue ) } .first { $1 == n }! // find the first one where the sum is the input .0 // and return the number that gave that sum } ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=sum -pa`, 29 bytes ``` $_=0;$_++while"@F"-sum$_,/./g ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tbAWiVeW7s8IzMnVcnBTUm3uDRXJV5HX08//f9/I8t/@QUlmfl5xf91fX0yi0usrEJLMnNsgWqAAqZ6BoYG/3ULEgE "Perl 5 – Try It Online") [Answer] # [Desmos](https://desmos.com/calculator), 66 bytes ``` I=[0...n] f(n)=I[[i+∑_{k=0}^imod(floor(i/10^k),10)fori=I]=n].min ``` Returns `undefined` if no solution exists. [Try It On Desmos!](https://www.desmos.com/calculator/9esxyqdldh) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/qz6ogtumcb) [Answer] # [Ruby](https://www.ruby-lang.org/), 46 bytes ``` 1.step{|c|p (1..c).find{|x|x+x.digits.sum==c}} ``` [Try it online!](https://tio.run/##KypNqvz/31CvuCS1oLomuaZAQcNQTy9ZUy8tMy@luqaipkK7Qi8lMz2zpFivuDTX1ja5tvb/fwA "Ruby – Try It Online") [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `M`, 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` æDS+= ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faGm0kq9S7IKlpSVpuhbLDi9zCda2XVKclFwMFVqwyMgSwgIA) #### Explanation ``` æDS+= # Implicit input æ # Filter [1..input] by: D # Duplicate S # Sum digits + # Add = # Equals input? # Take the minimum # Implicit output ``` [Answer] # Haskell, 52 bytes ``` a n=find((==n).ap(+)(sum.map digitToInt.show))[1..n] ``` [Try it online!](https://tio.run/##VY1BSwQxDIXv@RU5eGgRizugMgvjZb0I7klv4iHa7k7YNh3aLOKvHzvDXjYQeO8j72WkegoxzjOnKRfFXRYtObp9FvJwgS@k5HYjlSvwxlWvwJ7@vgNAIhYc0GfANjEolkD@VbTBReF2i@9aWI5494yNr3csGgr9KN7gWSJLqOgw0YSmjvm36UPJaf2A981R20utbXINABDKcGDxxgyDWEeTubWmnpNbijwfWT9yS7il0trPjXPyNc9dD93mEbqnB@j6/h8) [Answer] # [Scala](http://www.scala-lang.org/), 71 bytes [Try it online!](https://tio.run/##TY5BS8NAEIXv/RVD6WEX06WJoElwC6IePIgH8aQiY7oJI8mm7I6ClPz2OE2tujCP5c2bbyZW2OLYv727iuEOycNuBvI@sYWqvPVs1yJgR2/XagXcg9emJr9RJAYZ7h84kG9Mh1v1ajBeU0OsTfzoTkhbK@nG8X24aaNTy1SPQt@4GjpZpTA0sYTLEPDr6YB50SU8epKF/@5gF/kKo4viTmGVFQlk6VkCqwTSqfaSnSZQ5Odip/KRxNTJRYpcT7S6D6COOLhY/qH1zz6ArdzBrVdxvjh2y2de7KrfQT3MD7hhtq9h/AY) ``` n=>(0 to n).find(i=>(i.toString.map(_.asDigit).sum+i)==n).getOrElse(-1) ``` ]
[Question] [ In most programming languages, arithmetic is written with *infix notation* -- i.e. the operator is put in between the operands -- e.g. `1+2`. In contrast, with **Polish notation** (a.k.a *prefix notation*), the operator comes *before* the operands -- e.g. `+1 2`. As long as the number of operands for each operator is fixed, this means that parentheses are never necessary, unlike with infix notation. ## The Challenge Given a string consisting of nonnegative integers (digits 0 through 9), spaces, `+`, `-`, `*`, and `/` representing a single expression in Polish notation, add parentheses around each sub-expression, maintaining the whitespace. The parentheses should start right before the operator and end right after the last operands. You can assume each function has arity 2 (i.e. it takes in exactly 2 operands). You can also assume there will be no extra preceding zeros (e.g. `000` or `09`). ## Test Cases | Input | Output | | --- | --- | | `+1 2` | `(+1 2)` | | `++ 1 2 3` | `(+(+ 1 2) 3)` | | `+1 +2 3` | `(+1 (+2 3))` | | `* *1 2 /3 0` | `(* (*1 2) (/3 0))` | | `//30 300/18 205` | `(/(/30 300)(/18 205))` | | `/ -20/ 30 30 999` | `(/ (-20(/ 30 30)) 999)` | | `/////1 2 3 4 5 6` | `(/(/(/(/(/1 2) 3) 4) 5) 6)` | | `/1/2/3/4/5/6/7/8 9` | `(/1(/2(/3(/4(/5(/6(/7(/8 9))))))))` | Standard loopholes are forbidden. As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest program wins. [Answer] # Regex (Perl / PCRE / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), ~~48~~ ~~47~~ ~~45~~ ~~44~~ 43 bytes ``` s~([*-/]( *(\d++|\((?1)\))){2})(?!\))~($1)~ ``` [Try it online!](https://tio.run/##HYzbCoJQEEXfz1fsROJciDkXrcQuH5LRQwkKVmJBoOWvn47uh5m9FsO0ZdekPu73Ov9UdVPy3UEM1@p5b3OD2fjXyE9yRWcOyYubUt@C86MRhRBisD/Bj4tQRx4bMfo87pfLtqsf76h4RIH2JsfM8eXnlYFlSiEsOIaQYKY5oYScPDlogBE5Dac1mS2sThlhZTVhlkCWZeEiZP6EBCnWjAxZcpRQSmva0BbZHw "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##nVNhb5swEP3Or7giVNsJxJC0XVNCo0ptpUzbPqyrNinJEAGTsBJANlmjpslfz85E09Rp3YcigY/z@b13z/YsUov96PYuACmiBByZACEgBwMSvukhxmBYLSqwJARQSTEPpajyKBaU8E5rGIaLKK/DuFxWWS7khE6YP/nMFbGR1oYUk@Fc6IKiFkWtaBjejj7chCGzwWO@kaVALTl2p0cBUYRBvZDlIxTiEW7WsajqrCwo@ZgplRVzMJVJcI2VoBRc5E19aNYnl2RH4Pn5oG8Z1fEC1Y1dp3/lTKaRs7Uoa7U7g8vh9ykntpWwfxOZo@JnlGcJJCLPllktpKnpdOdiXeVlIpDLRmp2II7LVVGjfHYUnLyC@FWWKLxYLWdCQpn@QVYNtDp00sVOrPQQ93SsKbHNzqFNPSaYnWM2jXIlfCMtcXuxTVXLUFV5hjJSBpECK2abxpQYjo8Bp6tSUXOeLdX66vr@2/uVaWNJEAQN0CuG3xdSxOW8yJ5EAmkeofWkY8Udov0/eB4HAZkTZs2DWq6EDwLRtO4OCo/9rZEVWahETc0qlqIzi@KHWuInbNo3bTAdz9RYL8qQdSUVSvh/2Y/DlKstRCOo9RS4vpUHKZ40Re@@XI8@MZ9tUCi18jF6kIsCI@Z40yAwJ4XJsFitZjiDadu1Ha9pC4GYiBelLkG7nwLPNwA0g49wVhW8OP@WxKOg8M1tcDxbO9@AHGEww915QIhc72Plb0HDgmnlpr/968pQ5u/Vjo5bDp9SaNFJ0m4/TygdemzCGNt0t4wOjzDcUctju/3brrHRCHAK1LCRFxeOtzUvYzzQHbzbvliLGPhKST7LCq5v@@@pfduDrtFuAw7QQzMAMKO/@rcFLZ3nPXABDM57LvRcl3vn0HVPDQ5O1@XQJAH6/T5W4NMgwQmcwpnBPd7lPX7CT/kZf8fPof8L "Bash – Try It Online") - PCRE1 [Try it online!](https://tio.run/##fVNhb5swEP3Or7giq9gJxJC0XSPqRpPaSZ22fdhWbVLIEAFDWAkgm6xV2@SvZ2fyYeq0Dsn4OJ/fvfds2lW7v5i1qxaIAgGtkkWsZFslqaQOHw1mcbxKqi5Om3VbVlJFNGJh9JlrxwUHR47JuJCmoO5k3Wkax@9uPlzHMXMhYKFV5kCJmvuLI@Foh0G3Us091PIerh9S2XZlU1PnY6l1WRdga9vBPSRDKrgpWITQ788unZ0Dz88HfuukS1fIbu5707detEi8LaFsMBxdXM5@LLjjkoz9u5F9U/9KqjKDTFbluuyksk07o1w@tFWTSezlYmt2aJw2m7pD@uxInLyC@E01SLzerJdSQZP/QdY9tD4oGaMSkh/iiYlNS5Q5Osg0c4bZArN5UmkZWnmjZIIydadi3VYl0sgZJBpIyp56U1I4PgZcbhtN7aJc64e3V7ff329sF0uEED3QK4bf1kqmTVGXjzKDvErQemdE0pFj/D94ngrhFA4jhejURoYgEc3wHiHxNNxaZV3GWnbUblMlR8skvesUvuJevu2C7QW2wXpRhl03SiOF/5f9PCz5xkI0gpJH4YekEjneNE2/fL26@cRC9oREKanm6EEla4yYFyyEsKPaZlisN0tcwbTru17Qy0IgJtNVY0rQ7kcRhBaA6RAiHGnFi/tPFF4FjaNywQtc43wPcoTBEk/nDiEqc45tuAUDCzap7HD71y9DWbjXOzofeHxBYUCjbDh8jiidBSxijD2Nt4zOjjDcURKw3X4/DGBsDYeAE0yQHwBmzNt8DmBg8nwCPoDF@cSHie/z4BzG/qnFwRv7HPokwHQ6xQp8eiQ4gVM4s3jAx3zCT/gpP@Nv@DlMfwM "PHP – Try It Online") - PCRE2 [Try it online!](https://tio.run/##bVJdb9owFH3Pr7iNJsWGFOcDKIR5VbehCYkWqe22h8CkdHGoNcdBdthKv/46uwmrqknNQ2If3XvuOfdks6tvKx3vZbmpTA12Z30j1uJuAoYb13X39pmknWO2ItAhy7zbfVwSchrSJaX0IXqi5PQIj89kGdLnPdanYXIcrhxZgEmD1RH3rJeAyaQVcLXTdXY3NaYyxDuX1kq9Bte6HnVybtJDV2VyklOQGqyoe1stK03wREym14L0R/5gRKn/ioxP/DAa/AcNB/44RuShU2YbgoS@@47QTrf3/sPpD5c@0TcFzfTvTMkccqFkKWthUJYBDqZnN0rWKKqRp4Qmhh7x/psc302FlvS2vBEGquKVyyJZobK15cEEflZbXfPQKSoDRePUpPEqcQDpC869NS7sUBI4IJQVCbSt8MjhwZNe0ubTm325WFxOP51dTX3wyhf0/Ov8ejafXTSgfQE/L67P5nNE7l6Qb9PLj4ur6VNarByLu49Wbd6YwQTucW4jTbUh7GzP1rnUB32NfUUh0zmoFHNGuUuNehVXadAGD39upRIQYj2UzfraeXZ7g3vzwfqg/IM7/@CKTnAQhxJ/FuzAEWXa0AYJ3BiR/Wqn3iewMVLXhDqoLpz8uwmdc0X33RAip9sF/ECMHACINO/m2oFOg7MYAgCHsTiAOAhYOIIoGDgMjqOAQQsCjMdjrMCnZYI@DGDosJBFLGZ9NmBDdsJGMP4L "Python 3 – Try It Online") - Python `import regex` This is a single regex substitution to be repeatedly applied until it has nothing to match (or until there is no change, where necessary or convenient). In the following explanation, `␣` represents a space: ``` s~ # Begin substitution - match the following: ( # Define subroutine (?1); $1 = the following (the entire match): [*-/] # Character class of the four arithmetic operators. This also # includes "," and ".", but those are guaranteed not to be in the # input. ( ␣* # Any number of spaces, minimum zero. ( # Define subroutine (?2) as an argument to an operator: \d++ # Any number of digit characters, minimum one; force all of # them to be consumed (prevent backtracking). | # or... \( # An opening parenthesis (?1) # Recursively call (?1) \) # A closing parenthesis ) ){2} # Do the above twice (for two arguments). ) (?!\)) # Assert there is no closing parenthesis following this, as that # would indicate that this expression has already been parenthesized. ~ # Replace with the following: ($1) # Preserve $1 (the entire match), and surround it with parentheses. ~ # Flags: # No global flag. For better efficiency, adding the "g" flag # would allow the substitution loop to end sooner, but it's # not needed. ``` Saved 1 byte by using `{2}` instead of a subroutine call for the second argument (shamelessly stolen from [Neil's regex](https://codegolf.stackexchange.com/a/250879/17216)). ## Bonus: Convert Polish notation to infix notation, ~~58~~ 52 bytes ``` s~([*-/]) *(\d++|\((?2)(?1)(?2)\)) *((?2))~($2$1$3)~ ``` [Try it online!](https://tio.run/##fVNhb5swEP3Or7giq9gJxJC0XSPqRpPaSZ22fdhWbVLIEAFDWAkgm6xV2@SvZ2fyYeq0Dsn4OJ/fe/ds2lW7v5i1qxaIAgGtkkWsZFslqaQOHw1mcbxKqi5Om3VbVlJFNGJh9JlrxwUHR47JuJCmoO5k3Wkax@9uPlzHMXMhYKFV5kCJmvuLI@Foh0G3Us091PIerh9S2XZlU1PnY6l1WRdga9vBPSRDKbgpWITQ788unZ0Dz88HfeukS1eobu5707detEi8LaFsMBxdXM5@LLjjkoz9m8i@qX8lVZlBJqtyXXZS2YbOdC4f2qrJJHK5SM0OxGmzqTuUz47EySuI31SDwuvNeikVNPkfZN1D60MnY@yE5Id4YmJDiW2ODm2aOcNsgdk8qbQMrbxRMsE2dadi3VYlysgZJBpIyp56U1I4PgZcbhtN7aJc64e3V7ff329sF0uEED3QK4bf1kqmTVGXjzKDvErQemdE0pFj/D94ngrhFA4jhejURoYgEc3oHqHwNNxaZV3GWnbUblMlR8skvesUvuK@fdsF2wtsg/WiDFk3SqOE/5f9PCz5xkI0gpJH4YekEjneNE2/fL26@cRC9oRCKanm6EEla4yYFyyEsKPaZlisN0tcwbTru17Qt4VATKarxpSg3Y8iCC0AwxAiHGnFi/tPFF4FjaNywQtc43wPcoTBEk/nDiEqc45tuAUDCzap7HD71y9DWbjXOzofeHzBYECjbDh8jiidjRmdBczMETMLJmI7SsYkIBO22@@HAYyt4RBwggkKBcCMeZvPAQxMnk/AB7A4n/gw8X0enMPYP7U4eGOfQ58EmE6nWIFPjwQncApnFg/4mE/4CT/lZ/wNP4fpbw "PHP – Try It Online") - PCRE2 ``` s~ # Begin substitution - match the following: ([*-/]) # Define subroutine (?1): Character class of the four arithmetic # operators. This also includes "," and ".", but those are guaranteed # not to be in the input. ␣* # Any number of spaces, minimum zero. ( # Define subroutine (?2) as an argument to an operator: \d++ # Any number of digit characters, minimum one; force all of # them to be consumed (prevent backtracking). | # or... \( # An opening parenthesis (?2) # An argument (?1) # An operator (?2) # An argument \) # A closing parenthesis ) ␣* # Any number of spaces, minimum zero. ( # $3 = the following: (?2) # second argument ) # No need for "(?!\))", because parenthesized expressions won't be in # ARGUMENT ARGUMENT OPERATOR format. ~ # Replace with the following: ($2$1$3) # ( argument1 operator argument2 ) ~ # No flags ``` See also [Convert from postfix notation to infix notation](https://codegolf.stackexchange.com/questions/5847/convert-from-postfix-notation-to-infix-notation/250890#250890), which adds parsing of operator precedence. # Regex (Perl / Boost), ~~47~~ 46 bytes ``` s~([*-/] *(\d++|\((?1)\)) *(?2))(?!\))~\($1\)~ ``` [Try it online!](https://tio.run/##HYzbCsIwEETf8xWjFEkayubSqiVqP8SID1powUtRQajaX49p52GHc1imqx@XIiT9Vrl3015qvtmJz6m5XzunMZnwHPg@zeiAlPuzlF/PeaWFFyKKygjBq1mEwfNEezEEl/SLRfdob6@5v80jbbXDxMnxF6SGYVIiFixDTDTjHTFFOnqyUAAjsgpWKdJrGFUwQmYUYZJAWZbxI2ZaQo4CS0aaDFnKqaAlrWiN8g8 "Perl 5 – Try It Online") - Perl **[Try it online!](https://tio.run/##fVRtj9o4EP6eXzHQqthJaAIsW0jIrlTpPpxU9UPbk@5UelFIHIganCg23TfYn146dgIbuHIRSvDMPI8fz4wnLsv@Mo73rzIe55uEwWxRFEI6FVuy@7ersrwx4lVUQVh@/QYBfOq@v7v7vhht/nl4@PvL6vpuRfbimXw1@843MMk8saztnJDbAZ1TiobbIaXktoOL5zl5PZjT5z09Z@jaYJZBWPrGi4gMNVQsWt8YGZdQVvgOWVUVFYkLLiRoTeaaCREtGX0SMvG8GANgNoPGqv5qO@NJ7kPF5KbiMPB3oCjFA5fRfcNJnxpve6PuZx0CetWl/q5ORMLybB24PmCecqSqIr5kRLu4rT9R/VkcWTdIOgkl4f2Iwiw4rhe4PtCaacaTUJPXZKag8GQAPmlRAfF9YVkHi3qyFEhHBTWbfPzrwwf/6GW5YDrEFEHQm897CK0RlnWG2f0epKUcI0VNvTN2uiDrKOPkoEYjLKvsBD3R2247pE6RMtEXgpN8@xqk42budnvIojbYVxN7PKFn1u1oaE/f2YPhGD3YG/EKK/SaUNN6O7u5/bdr13qP@51U8k/@I8qzpK5dJpkqJ6C8@lBNurG7WzUoG40dcfEIJlYEc@v22jTpKY040KSXadITGtUco2EooUAmfRc9T19Gz@NFuC6ScO1DtJEFiFYE9sg6kmGaVUKGBc8fYHvmivLcb7UTbov1mvOeD6lqLHGXyXiFhUwPZY0j7IZe1vMApWwDOBOTKb9fN84Cr@p3v4USl1BKv7iEuv8/1P0l1LpGvQng@VK6foNaIkqcoP6TQr@NSlgabXLpwcmo6f6hqujBocHSPFpCV3mwES7Nn1qFHmNtwRhBShsKbAkNwybP@BInTLmRrcqp6/eo5o8OWjKZZ5yRWlXG7Tqe@uej4pEC2lWPElV13OQxGLzMi2bGtFHqaQspNvKsI8OKlXkUM6L3tPEANgj84RFOWNT@Gh006tqJPQYpD25QHE5bz5sTJbFiwbS2clJHNMl1fWO3twYwNCwL8AMj7UWLequlCaayOyNwAQzHGbkwcl1nMIGhOzYc6A9dB7QRYDqdYgQ@mgmuYAzXhjNwhs7IuXLGzrXzzpnA9Gesqi72/VznJtSp@QU "C++ (gcc) – Try It Online") - Boost** Boost needs parentheses escaped in its replacement argument, because its conditional-replacement syntax uses parentheses. This isn't compatible with PCRE or Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/), as they will interpret it as a literal `\(` and `\)`. This exposes a bug in Boost's subroutine call processing. If `{2}` is used to match two arguments, instead of `(?2)` to match the second argument, it makes an incorrect full match. Example: `+(+ 1 2) 3` If the regex `([*-/]( *(\d++|\((?1)\))){2})(?!\))` is used, it matches `+(+ 1 2)` instead of the entire expression, so the closing parenthesis is added in the wrong place. But if the regex `([*-/]( *(\d++|\(([*-/]( *\d++){2})\))){2})(?!\))` (with `(?1)` replaced with itself to one level of depth) is used instead, it correctly matches the full string. The bug is still present in the latest version of Boost. I have [reported it](https://github.com/boostorg/regex/issues/178). # Regex (PCRE / Ruby), ~~47~~ ~~46~~ 44 bytes ``` s~([*-/]( *(\d++|\(\g<1>\))){2})(?!\))~(\1)~ ``` [Try it online!](https://tio.run/##nVNhb5swEP3Or7ggVNsJxJC0XVNCo0ptpUzbPqyrNqnJEAFDWAkgm6xR2/SvZ2eiaeq07kORApfz@b13z75FpJa76dV1AFJECTgyAUJAjsckfNNDjPGkXtZgSQigliILpaiLKBaU8H53EobLqGjCuFrVeSHkjM6YP/vMFbGR1oYUk2EmdEHZiLJRNAyvph8uw5DZ4DHfyFOglrx1552AKMKgWcrqHkpxD5ebWNRNXpWUfMyVyssMTGUS3GMlKAU3eXMf2v3JGXkm8PS017eKmniJ6m5dZ3TuzOaRs7Uo6/b647PJ9zkntpWwfxOZ0/JnVOQJJKLIV3kjpKnpdOdiUxdVIpDLRmq2J46rddmgfNYJDl9B/CorFF6uVwshoUr/IKsWWu07GWAnVrqPhzrWlNhmf9@m/iaYzTCbRoUSvpFWeLzYpmpkqOoiRxkpg0iBFbPH1pQYDg4Al@tKUTPLV2pzfnHz7f3atLEkCIIW6BXDb0op4ior8weRQFpEaD3pW3GfaP/3nsdBQDLCrCxo5Fr4IBBN6@6j8NjfGnmZh0o01KxjKfqLKL5rJL7Ctn3TBtPxTI31ogxZ11KhhP@X/dgvudpCNIJaD4HrW0WQ4k1T9PrLxfQT89kjCqVWcYseFKLEiDnePAjMWWkyLFbrBa5g2nZtx2vbQiAm4mWlS9Duh8DzDQDN4COcVQcv7r8l8Soo/BU2OJ6tnW9BOhgs8HTuEKLQ51j7W9CwYFqF6W//GhnK/J16prddh88pdOks6fWecI6ysXc2Y4w9DraMTjoYPtOZx553b5tjo1XglCjiUZ6eOt7WPIvxRvdxuH2xETHwtZJ8kZdcj/vvpV3Pg4HR6wF@YIhuAGBGv/XfLnR1ng/BBTA4H7owdF3uncDAPTI4OAOXQ5sEGI1GWIFPiwSHcATHBvf4gA/5IT/ix/wdP4HRLw "Bash – Try It Online") - PCRE1 [Try it online!](https://tio.run/##fVNhb5swEP3Or7giq9gJxJC0XSNKo0ntpE7bPmyrNilkiIAhrA4gm6xV2@SvZ2fyYeq0DsnmOJ/fe/ds2lW7v5i1qxaIgghaJcpEiVammaAOHw1mSbJKZZdkzbqtpFAxjVkYf@baccHBUWAyKYUpqDtRd5omybubD9dJwlwIWGhVBVCi5v7iKHK0w6BbqeYeanEP1w@ZaLuqqanzsdK6qkuwte3gHpKjFNwULELo9@eXzs6B5@eDvnXaZStUN/e96VsvXqTellA2GI4uLmc/FtxxSc7@TWTf1L9SWeWQC1mtq04o29CZzsVDK5tcIJeL1OxAnDWbukP57Cg6eQXxm2pQeL1ZL4WCpviDrHtofehkjJ2Q4hBPTGwosc3RoU3zzjFbYrZIpRahVTRKpNim7lSiW1mhjIJBqoFk7Kk3JYPjY8DlttHULqu1fnh7dfv9/cZ2sSSKoh7oFcNvayWypqyrR5FDIVO03hmRbOQY/w@eZ1HklA4jZdSpjQhBIJrRPULhWbi1qrpKtOio3WZKjJZpdtcpnJK@fdsF2wtsg/WiDFk3SqOE/5f9PCz5xkI0gpLHyA@JjAq8aZp@@Xp184mF7AmFUiLn6IEUNUbMCxZRZMe1zbBYb5a4gmnXd72gbwuBmMhWjSlBux@jILQADEOIcKSNXtx/ovAqaBzSBS9wjfM9yBEGSzydO4SQ5hzbcAsGFmwi7XD71y9DWbjXOzofeHxBYUDjfDh8xv@ovAguY8bY03jL6OwIwx2NA7bb74cBjK3hEPAFExQIgBkzm88BDEyeT8AHsDif@DDxfR6cw9g/tTh4Y59DnwSYTqdYgU@PBCdwCmcWD/iYT/gJP@Vn/A0/h@lv "PHP – Try It Online") - PCRE2 **[Try it online!](https://tio.run/##bZJtb5swFIW/8ytOsklACBhI2zVtSRWtaIrUdlPaaZOARTQYgkRIZifrS17@enZJ0myqygdsX5/7@Ppci/nD80bAw1X3vmsJHieGCvUceQoR2FHNUyWtRJxLjrvnchY/@UJMRBPqTS5lXmaoyzopeJkoCWFE4ETb7KSjrlUsl0i8NQtss901wyg2Vx81vWFYF53LXxF7H9wr/8RFniDhRT7OZ1zs8VWVwpLTIp9pib4r0Sp4mc1GqHk4ep/2Q0yoyHI@fuACk/QfVe6xKWHtc2SSRrMjm9OFtOT8oaZNmyJwI31F3KAVWTwejgbDUSywwHK4xDCms4YK8DjiJci0wzQncoqlhz7P@NP07Kz35fZr3//cvfMPmqe3Gv/nvX975V8dFOO3ipvv1/e9696tD3yAjMccscQ3LgpVgrqEtIgzaH1qKAX473lONvJyVl36VTVWkUvExWP8LDEp9cNhmfq/A01BHmRvTCCvVkofr/VYJX/cdruZVnVuMxc24fKCEyqQTfTpJUjKfPHI391G4WV8JulYat5LrYpP5zO5hVc6Z7dTBKYTeV49LOvnlFIEtmWZbrTrFzAVOV0rDYp9ZDAg5waDjVxrQcNkkYaGFiaGsQy1MLtwOqGu6wt3pWuXNZqutdDR15uN4cBVDAM0oEVUgCLVv1o20KjirAUbUBhr2WjZNnNO4drHCoPp2gzbINBut0lB35aEIxzjRGEOc1mLHbFjdsI@sVO0/wI "Ruby – Try It Online") - Ruby** Ported to Ruby's subroutine syntax. ## \$\large\textit{Functions}\$ # [Ruby](https://www.ruby-lang.org/), ~~75~~ ~~74~~ ~~69~~ ~~67~~ 66 bytes *-5 bytes thanks to Steffan* *-1 byte thanks to Dingus* ``` ->s{0while s[/([*-\/]( *(\d++|\(\g<1>\))){2})(?!\))/]&&="(#$1)";s} ``` [Try it online!](https://tio.run/##JYzRjoIwFETf@YqR3ZhCU29bRCXduh9C@7IRXJKGGNGYxfXb2cLOw70zJ5O53r9@ptZO4jg85eO7Cw2GmlidC0eeIWfuxPmvY@78oY4uy7KnfmXscxUt@fXapuztXWWpGV7TaKXB/0Sw5@Y2GHQtxlXEl3tMTX8yo1ULDbVQ3trU9akJNtRysxHaLxVcrl1/Q1sHbxDBxBV0wjniQ5EgKpL5zjFHPnMqIIGEqJAopCR1gJZlQhBaEhYIVFUVG1HLErYosUtIkaaCtlTSjvZ0QPUH "Ruby – Try It Online") # [Python](https://docs.python.org/) (with [`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), ~~107~~ ~~106~~ 105 bytes ``` import regex f=lambda s,p=0:s==p and s or f(regex.sub('([*-/]( *(\d++|\((?1)\))){2})(?!\))',r'(\1)',s),s) ``` [Try it online!](https://tio.run/##NY1NboMwEIX3PsXrChtCxoaQBiIrB4EsiIAWyTEIU6lJ27NTg9rRaH4@vXkzPub3wabL0t/HYZoxtW/tJ@u0qe@3pobbjVoWTusRtW3gMEzo@Cbau48bD3gZxnTlCHnVRNF3xflFiUoI8ZX8CH558WOwmwJeKd@d8Pn/yT3cGU8tWec9DXq7kr2bm94WDH0H01puxPbXlLG6ah1UNihgtCll4cGmehYYp97OXDDvps5/W2sb3flzsUQKCYsi@IaUwYcna13XEOHKKYUEGFEqkUpJ6oREZowQJ5KwQSDPc6/wsTnhgAxHRooSSulAGR3plU7IfwE "Python 3 – Try It Online") # [Python 3.8+](https://docs.python.org/3.8/) (with [`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), ~~101~~ ~~100~~ 99 bytes ``` lambda s:[s:=regex.sub('([*-/]( *(\d++|\((?1)\))){2})(?!\))',r'(\1)',s)for i in s][-1] import regex ``` Can't [Try it online!](https://tio.run/##LYzBboMwEETv/orpCRtK1oYkBSIrHwI5JAJSJMdBmEpN2n47tVHmsLszmn3jY/6827wYp6XXzWLOt0t7hqtqV@mpu3bfG/d14RGv45ROHDFv2iT5bTg/KtEIIX6yP8GPb/6M3qeIN8pvJ/r7hAGDhTvVqTqx4TbepxkrcHkZ93AHPLVkoWzW8sNt3NwOtmIYepjOciNwti1MoGgdNTaqYLSpZRWwofWsME6DnblgnqYOL9fZVvf@XSyJQsaSBH4hZ/DySZjBxohDTjkkwIhyiVxKUgUyuWOENJOENQTKsvQNr5WELXbYM1KUUU5b2tGePqhA@Q8 "Python 3.8 (pre-release) – Try It Online") - Confirmed to work on my machine, but `regex` is not installed on TIO or ATO. Just like in [Remove redundant parentheses](https://codegolf.stackexchange.com/questions/250596/remove-redundant-parentheses/250617#250617), it's guaranteed that a fewer number of substitution iterations will be needed than the number of characters in the input, so this "do this for each character of `s`" trick works. The maximum number of substitutions approaches \$1/2\$ of the number of characters in the input string: $$\lim\_{n\to\infty}{n\over {2n+2}}= {1\over 2}$$ # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 100 bytes ``` [char[]]($p="$args")|%{$p=$p-replace'[*-/](?> *(\d+|\(((\()|[^)]|(?<-3>.))+\))){2}(?!\))','($&)'};$p ``` [Try it online!](https://tio.run/##RYzRboJAFETf@Yop2cpdKL0LqJVY9UOAJsQuhYQAQRoTgW@niy@dh7l3TibTtXfd30pd14soTuOSXMu8T7KMRHeyRd7/3Gw5vY4mic7vdVfnV@0krs8ZXc5wKf32ppSIUpJT8iWziS6ffnR@l9JLpZRjONPlxXzOm0NiI535KLrF2OOkjkXb6/xakqhRNRBV0/0OcqwKEg853vtq0H7Z3obZlIMj/gH8pm30va4aDVvQRhQQtbTnxQsQWp4HcxBZMDJk9TW6cFfOERRgMUcKkVIcHBCqncXwQ8V4QiCOY9Mwei5hix32FgcccsRb3vGeP/iA@A8 "PowerShell – Try It Online") Uses [Neil's regex](https://codegolf.stackexchange.com/a/250879/17216) with an additional -8 byte golf. Applies the substitution the same number of times as the length of the input in characters. # [PHP](https://php.net/), 104 bytes ``` function($s){while($p!=$s=preg_replace('~([*-/]( *(\d++|\((?1)\))){2})(?!\))~','($1)',$p=$s));return$s;} ``` [Try it online!](https://tio.run/##HY5Pb4JAEMXvfIqRbMIOf7K7oFakhEtN04s2tDcxxNpFSAhuFkwPtn51uzCHnZ3fvLx5qlaP50zVCkiVPqprdxqaS0dJj7efumklJWqWkj5VWp5LLVV7PEnq3OneDdiBgkuLb8/7LSjNBBaIeAv/kGYz8707vkOJQMcnyjggJloOV92RPvl7JNVFU9KkPCFtWp3l0NOPz5e3LSZ4g6aipN33g26lSdJiIA5pahedjUbcX7/MxmCf@4HAZFI3KE/1ZZQkYFxFAuMMU@j22A@l1NocxFn6nm9ey@2u3OT5Ls/szcjXYK/JeBNNMk9AaHkemAaRBaYMGd9xdMEdOYuAA1iMRRwizplYQcgXFoMg5AwmCBDHsVGYmpxgDgtYWkywkEVszhZsyZ7YCuJ/ "PHP – Try It Online") Thanks to Steffan for pointing out a 1 byte golf that has the added bonus of making this anonymous rather than recursive. Knocking off an additional 2 bytes from that has the further bonus of removing the "Undefined variable" warnings from this non-recursive function. ## \$\large\textit{Full programs}\$ # [MATL](https://github.com/lmendo/MATL), ~~54~~ 48 bytes *-6 bytes thanks to Luis Mendo* ``` t"'([*-/]( *(\d++|\((?1)\))){2})(?!\))' '($1)'YX ``` [Try it online!](https://tio.run/##JYy7DsIwDEV3vuKCkOwkqpxHW5qpC5/AAKKVQGKErRvw7cEpd7DOPbb8ui/PcivLjvhqG5kZlqeHc5@JeQxmMsa849fwuFUkEO@Docu5zMdTIRcQaUPOQQFJERq1df6Fha07SfCAdpHkkbyXMCD6rho00QtWDeSc1yvN@hMtOvRVBYmSpJVOejnIgEw/ "MATL – Try It Online") This too applies the substitution the same number of times as the length of the input in characters. # [Perl](https://www.perl.org/) `-p`, ~~51~~ ~~50~~ 49 bytes ``` 1while s;([*-/]( *(\d++|\((?1)\))){2})(?!\));($1) ``` [Try it online!](https://tio.run/##HYzNDoIwEITvfYox8dDSkOkPRRoOPIh4k0QSIkRMPKivbi18h92ZL5tdhscUUrKv2zgNWFt5LkpeJArZX7X@9FJ2VvVKqbf7Ktkdcmzl0aqUtIUTWiMveIFMNtvcaoFi8/QwgCC9gTeGtoEzQRClM8QugRhjvsjsn1AhoBa0dPSsGFjzxAbxNy/Pcb6vqVz@ "Perl 5 – Try It Online") # [PHP](https://php.net/) `-F`, 98 bytes ``` <?for($s=$argn;$p!=$s=preg_replace('~([*-/]( *(\d++|\((?1)\))){2})(?!\))~','($1)',$p=$s););echo$s; ``` [Try it online!](https://tio.run/##VZBPT@MwEMXP5FM8ogjbDdbkD2WpnJAbUk972CNFlUlMU6mKLSfSSqXw1btOFw68w4zn59Ebj1/12J@90R2k78AYfFWx7ZfYuWrerOfJWCfa7waVuOs6FM6b3dYbd9Ct4eyTPy8kvXAs@KZL09OG8yYXGyHEe/EheHMdjp/slvEkF@w2ccFBKKFM29tkVOfvYdEMIAfEVfPePCY@Zh8zijdDrBge0drOKPBWTwrzhQhsrTCaCdLC7Z150/uDAlk3kesdve6HOUO2IDO1kB3G3vppa50ZtpPe1b8HyKeLMSqsccLffn8wWD/9qfH1KdAKnY2uniGPSI54OZ3m4epY5@pn4wHVTfn/aZc1Eh1HnR0MyuB9TnMUUZoiJJQRggKZ41wusJg5lciAiKjMUGYZ5Q8osmVEkEVGuEBgtVqFjqCLE@6wxH1EORVU0h0t6Z5@0QNW/wA "Bash – Try It Online") [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 102 bytes ``` f(s++t)|all(<'!')t=g s++t g(' ':s)=' ':g s g s|all(>'/')s=s g(c:s++t)|elem c"+-*/"='(':c:g s++g t++")" ``` [Try it online!](https://tio.run/##NczBToQwEAbgO0/x05i0pZIpsKwLEe4ejAePxhhCWNwIK6HdGBPfHduuNmk7@eaf6S/r@p0u3Udvtu0ojFJW/nTTJO55zKVtRniKRsHBayMb/zmL3A2xlhOXpnEg@vo6PUzDjJ6pNCHWcMHrvg5bRlilmGSbHYxFXePZrqfziLTFwxOEjIIbNFgu1vUgzPvnF4xE2/4T82nmQSxu2OImjnF0mSiau9PZzc7d8viGsOqFqQw5uwVTCq5C4Wu449y/f5Ig8V0qoAEPRIVGoTVlB@S6DIQ014TgQFVV15w7YTF2KLEPllFOBe2opD3d0QEVe91@AQ "Curry (PAKCS) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~93~~ ~~92~~ ~~90~~ ~~89~~ ~~86~~ ~~85~~ 84 bytes ``` t"t'(?<!\()[*-/]'1&XXX<t?:&)w0XH&)40hwb'\d+|[\(-/ ]'XX"@gt1)t47>Ew41>-H+XH2=?41XH]&h ``` [Try it online!](https://tio.run/##FcJBCoQgFADQq1gLv06I2giDQ2WbwCN8SBcTQS1mdh/czN2NHu/3oW@t1BKIMDRJyPWhdAbLEXGg8OayGIxcOnOWDdLe/dcklGYZENv5ICvJvaalODup2GHsx@AsxszPWkEz1RvNnubOvPdwAQ) Or [verify all test cases](https://tio.run/##JYmxCsIwFEV3v@LZIWkaQl6aiFZq66CQD3B40AZUBDvoFujiv8dU73A599z3Lb7SNcUi8rJv12MphkrpwA0jojb2eyZmJM@Ew2m@8/EhP8NYKg2BExXHZzQium13np3plJfk60PvDPnAphRCoNMlcWmg5isuJWQAmxFysl36Lyqolk9bQIC8tbYIFlGbHdS4WQyoGjX8NEDTNPwL). The code uses a non-recursive approach, based on the facts that * each operator must have a `(` immediately before, and * the corresponding `)` must be placed immediately after the first number for which the count of numbers minus operators to the right of the `(` equals `2`. The procedure is as follows: Repeat these steps as many times as the input length (it would suffice to repeat as many times as the number of operators in the input string): 1. Find the first operator (`+-/*`) that is not predeced by `(`, if any. 2. Insert `(` right before that. 3. Take the substring after that position until the end and split it into groups, where each group is either a number (one or more digits), an operator, an opening or closing parenthesis, or whitespace (one or more spaces). 4. Start a counter at `0`. For each group from the previous step, increment the counter if the group is a number, and decrement it if the group is an operator. 5. When the counter reaches `2`, insert `)` right after that group. [Answer] # Rust Nightly, ~~332~~ ~~319~~ ~~307~~ 292 bytes Can probably be golfed a lot more. ``` |b:&[char]|b.iter().chain([&' ']).scan((vec![9],1),|(a,q),&b|Some(if '0'>b{let mut o=if*q<1{*q=1;let mut u=format!("");while{let z=a.last_mut()?;*z-=1;*z<1}{a.pop();u.push(')')};u.push(b);u}else{b.into()};if b!=' '{o.insert(o.len()-1,'(');a.push(2)}o}else{*q=0;b.into()})).collect::<String>() ``` [Playground Link](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=0dbe926fc22712cbb2512dd45e26d65c) [Answer] # [Prolog (SWI)](http://www.swi-prolog.org/), ~~292~~ ~~274~~ ~~125~~ ~~91~~ 129 bytes * -18 bytes thanks to Steffan * -999999 bytes thanks to Seffan * -19 bytes thanks to JoKing * -15 bytes by myself :). I realized I didn't really need to return the value "Z" since it's only possible value could be a space. * +28 bytes to fix spacing bug :( Just like my other answer inputs require a trailing space. I'm very new to prolog so this is probably nowhere near optimal. ``` N+Z:-N=32,$N,\X,X+Z;N/Z. $N:-put(N). \N:-get0(N). 32/32. X/Z:-X<48,$40,$X,\D,D+W,W+Z,$41;X^Z. X^Z:-X>48,$X,\W,W^Z;X=Z. :- \X,X+_. ``` [TIO](https://tio.run/##HY2xDsIwDET3fEWGDKA4SZt0QAll6uy1VhSVCVWVkFpBEZ8fTJeTfffs217rc53N@7vUijpHg33woBAKAemc0GUrFEazffYTnq0oPM@PvTmW4F3wVpDjQ7p2F1BdA4qgDDDoEUad2WkTTfyEhaHbH2KAwykn6jmIRh5ld1urdK13XgYpfw) [Answer] # [Pip](https://github.com/dloscutoff/pip), 50 bytes ``` W#aI@aQsOPOaEIaLT0OxPBt&'(.POaEL{Oa~XIa:$'WDQxO')} ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJXI2FJQGFRc09QT2FFSWFMVDBPeFBCdCYnKC5QT2FFTHtPYX5YSWE6JCdXRFF4TycpfSIsIlwiXCIiLCIiLCJcIiArLyAtMjAvIDMwIDMwICA5OTkyIDBcIiJd) (Note: the footer is because DSO doesn't flush the output buffer until a newline is output.) ### Explanation Loop through the input string. * If the first character is a space, pop and output it. * If the first character is an operator: + Output an open paren. + Pop and output the operator. + Push 1 (representing a close-paren) and 0 (representing the space between an operator's first and second operands) to a stack. * Else (this is a number): + Output the first run of digits in the string. + Remove the first run of digits from the string. + Pop the stack; while the result is 1, output a close-paren and repeat. ### Ungolfed ``` $expr: a $stack: "" W # $expr { I @ $expr Q " " { O PO $expr } EI $expr LT "0" { O '( O PO $expr $stack PB 1 $stack PB 0 } EL { O $expr ~ `^\d+` $expr : $' W DQ $stack { O ') } } } ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 129 bytes ``` f=->(s){def k a;i,j=a.shift;j=~/\d/?(i+j): i+"("+j+k(a)+k(a)+")"end;h,t=s.scan(/(.*[^ ])( *)$/)[0];k(h.scan(/( *)([0-9]+|.)/))+t} ``` [Try it online!](https://tio.run/##XYzdasJAEEbvfYqPxYuZrNlZEwpNQ@qDpBFWY8iPiDTxQqq@erq2CMa5@C7OOcz3aXMexyoLP6nnn3JXoYNLm0WbOdPXTTWkbXaTr1JW1OiWP9BoRUq3uiPH/6NY7Q5lWi@GrDf91h1IyAT5GgUTAp4L57ZIO6of0kPKbZgU@mJYmPVwHY@ozNbt9/73EpHi2RPQ8AjxBMKfL@/7qgIE915iWGBiRGKL2FpZviOyb1OHMLKCvwBIkkTx@As "Ruby – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), 47 bytes ``` O({a:POysNa?a.VfaLT0?pJa.(fMJt)a}Y(aw,+XD,XX))y ``` This is a different enough approach that I thought it warranted its own answer. [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJPKHthOlBPeXNOYT9hLlZmYUxUMD9wSmEuKGZNSnQpYX1ZKGF3LCtYRCxYWCkpeSIsIiIsIiIsIlwiICsvIC0yMC8gMzAgMzAgIDk5OSAwICBcIiJd) ### Explanation First, we tokenize the input: ``` (aw,+XD,XX) a Command-line argument ( ) Find all matches of this regex: w Run of whitespace , or +XD Run of digits , or XX Any single character ``` Now we're going to run a recursive descent parser on this list of tokens, popping each token as it's parsed. Unfortunately, functions in Pip are call-by-value rather than call-by-reference, so we store the list in the global variable `y` and modify that at each step. This also means our function doesn't actually take any arguments. Calling a function with no arguments can be a bit tricky in Pip, so sometimes we'll call it with a dummy argument that gets ignored. ``` {a:POysNa?a.VfaLT0?pJa.(fMJt)a} { } Recursive function, parses y and returns a parenthesized string POy Pop the first token from y a: Store it in the local variable a sNa? If it contains a space (whitespace token): a. Concatenate it to Vf a recursive call to the current function aLT0? Else, if it is lexicographially earlier than "0" (operator): a.( ) Concatenate it to f the current function MJ called on each character in t "10" (i.e., called twice) and the results joined into a single string pJ Join the string "()" on the above result a Else (number token), just return the token ``` This function parses exactly one expression. In particular, if the input had trailing spaces, the final whitespace token is not parsed and remains in `y`. Therefore, the overall program is: ``` O({...}Y(...))y (...) Tokenize the input Y Yank the list of tokens into y ( ) Call, with that argument {...} the parser function O Output the resulting parenthesized expression without a newline y Autoprint the remainder of y, if any, with a trailing newline ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~67~~ ~~66~~ 58 bytes ``` +`[*-/](?> *\d+| *\(((\()|[^)]|(?<-2>.))+\)){2}(?!\)) ($&) ``` [Try it online!](https://tio.run/##HYu9CgIxEIT7PMUIIrsJcfcSBANyeZDLiYIWNhZiZ3z2c88p5ueDed3fj@d1WcJl8lFmqiN8u4VuTkSNuE9nnjvVU0zjnjk05k/6Ut1YcbTdsX0HJBcCLJAdTEZWX6eHX7lkKOBEsiKrynBE0oMTxKSCPwRKKT8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Much like @Deadcode's answer, the expression tries to find unparenthesised expressions to parenthesise. Explanation: ``` +` ``` Repeat until no more substitutions can be made. ``` [*-/] ``` Match an operator. Edit: Saved 1 byte thanks to @Deadcode. ``` (?> *\d+ ``` Atomically match an integer parameter, ... ``` | *\(((\()|[^)]|(?<-2>.))+\)) ``` ... or a balanced parenthesised parameter, ... (Edit: Saved a further 8 bytes thanks to @Deadcode) ``` {2} ``` ... twice. ``` (?!\)) ``` Ensure that the operator wasn't previously parenthesised. (This test shamelessly stolen from @Deadcode to save 1 byte.) ``` ($&) ``` Parenthesise the operator and its parameters. Alternative approach, ~~60~~ 58 bytes: ``` (?<=(()\d+|[^*-/]|(\2|())(?<-2>.))*)\d+ $&$#4$*) [*-/] ($& ``` [Try it online!](https://tio.run/##HYq9CgIxEIT7fYoB47GbEDeXKBjwp/Qh7hQPtLCxEMu8e0ycYob5Zj7P7@u91DVf7pXPhyOzzA9Xppv1ei08x8IibfDxtBGxfSQzmNXWWKGpn4jNUKsbEck5tEAiNDXSvVcL27kmBIBUU0AKQcc9YtiRwseg@EMg5/wD "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` (?<=(()\d+|[^*-/]|(\2|())(?<-2>.))*)\d+ $&$#4$*) ``` Consider the minimum number of integers that would complete the prefix expression at any given point; this value increases at an operator and (obviously) decreases at an integer. Working back from a given integer, up to the point that the value decreases below the current value, count the number of times it is equal. This is the number of parentheses that should be appended. ``` [*-/] ($& ``` Prefix a `(` to each operator. [Answer] # [Python](https://www.python.org), 186 bytes ``` lambda s,a=[]:(t:=s.rstrip(),[a:=c<'!'and a[:-1]+[c+a[-1]]or a+[c.isdigit()and c or"("+c+a.pop()+a.pop()+")"]for c in re.findall("\d+|.",t)[::-1]],a)[2][-1]+' '*(len(s)-len(t)) import re ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PU9LboNADF2HU7hssBl-AVVKULlFd4TFAKEdicBomC4q9SbdRKraI3TRm-Q29SS0s7Cfn5-fPe9f-tU-z9P5Y6gOny92iHeXn1Ge2l7CEsmqbkq0ZbUkZrFGaaSolmXVPQR3gZx6kHUZbxtRd0LWDJrZgOQqUUuvnpRFcqIOZuOjL1iU6Jk9_rNPfjPwTAdqAnNMBjX1chzRP_TiLfEjS3XpFjSRpDpv3AoRQBDieJxwodglS-Spk56NZYf1B4_OVDnTWbMko9IDGbWVup6bLHrk2_yD9ckDbdRkcUBJVdVG5qgNw1t25Apbopv3-fIttpBv0EXyhADOUHCNV0hQsCk_7rvoeg7grUZH8MUhhG4uLSAD2GAIGF6H0TFEAF6aFhkUWZZud5Bn9xtMcWUIV459UojzLIVrA2C_37MOkDlcSefF9N_5vw) Handling trailing whitespace added a lot of bytes, even though leading whitespace didn't. If we didn't have to handle trailing whitespace: # [Python](https://www.python.org), 149 bytes ``` lambda s,a=[]:[a:=c<'!'and a[:-1]+[c+a[-1]]or a+[c.isdigit()and c or"("+c+a.pop()+a.pop()+")"]for c in re.findall("\d+|.",s)[::-1]][-1][-1] import re ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PU5BboNADDyHV7h7ia0lQIIqJaj8ojfCYYHQrkRgtdBDpT6jPfUSqWr_lN_UJrQr2R6Px975_HGv0_PQX77a_Pj9MrWb_fWjM-eqMTCGJi_KrDBZXj-s79amb8AU2WZb6qLWpmBQDh4Md5EdG_tkJyQR1TB4hUqzKHKDQ_qvilTZ8k4Ntgd_ilrbN6brUB0b_RapcKQikw9KOS4R2LMb_MTaxdyjrFtZH9ypx4SyAExY5XY2Fo2uYxfqOCkKwHnbT9iioTyvQn9ynuGtCrnAiuh2-3J911vYrVAyBVoDV0i5xxkSpHyUH88ly0wA3noUgiiI4zSBNEni7R52yf0KY1wYwoUTFWx2SQzzAOBwOLAOkDlcSKKZ_jP3Cw) If there was no whitespace or multi-digit numbers: ## [Python](https://www.python.org), 90 bytes ``` lambda s,a=[]:[a:=a+[c.isdigit()and c or"("+c+a.pop()+a.pop()+")"]for c in s[::-1]][-1][0] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3o3ISc5NSEhWKdRJto2OtohOtbBO1o5P1MotTMtMzSzQ0E_NSFJIV8ouUNJS0k7UT9QryCzQ04bSSplJsWn4RUEVmnkJxtJWVrmFsbDSQiDaIhdiwuaAoM69EI01DSV_XSN_Y2FJJUxMis2ABhAYA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes ``` ⊞υω⭆θ⎇№+-*/ι∧⊞O⊞Oυ⁺⊟υ)ω⁺(ι⎇›№⭆χλι№⭆χλ§θ⊕κ⁺ι⊟υι ``` [Try it online!](https://tio.run/##dY7LDoIwEEX3fEXT1YyWgLoirowLw8JIoj/QQCNELDi0Pr6@FsQQF04mmczrnpuXkvJG1s5ltivBCvbAdZBRpQ0cjS/nvWzhJthJkZb0gm1j/YrPw1nEBatQsI0uoH8@tIqkaei38YpZbTvImhasv@bIEXvKOOcwyOBE2JGSRtFImkwsYsFq/DD/7TYm1YV69oZTnZO6Km1UARdE/AIrXwcvg5SPtXMRC5dxxFZxnyxJksCF9/oN "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υω ``` Start with `0` on top of the stack. ``` ⭆θ ``` Loop through the input characters. ``` ⎇№+-*/ι ``` If this is an operator, then... ``` ∧⊞O⊞Oυ⁺⊟υ)ω ``` ... increment the top of the stack, push `0` to the top of the stack, and... ``` ⁺(ι ``` ... output the operator prefixed with a `(`. ``` ⎇›№⭆χλι№⭆χλ§θ⊕κ ``` Otherwise, if this is a digit but the next isn't, then... ``` ⁺ι⊟υ ``` ... output the digit followed by a number of `)`s given by the top of the stack. ``` ι ``` Otherwise, just output the character. [Answer] # [nearley](https://nearley.js.org), 78 bytes ``` m->_ p _{%a=>a.flat(1/0)%} p->[\d]:+|[-+/*] _ p _ p{%a=>['(',a,')']%} _->" ":* ``` Post-processing functions for production rules, denoted by `{%...%}`, are evaluated in JavaScript. Each function is called with an array of post-processed results for each terminal or non-terminal from which the rule is produced. This [EBNF grammar](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form) is defined by three non-terminal production rules `m`, `p`, and `_`. * `_` is zero or more spaces * `p` is one or more digits OR one of `-`, `+`, `/`, `*` followed by `_`, `p`, `_`, then `p`. * `m` is `_`, `p`, then `_`. The post-processing function of `p` wraps the result in parentheses when it is produced by `[-+/*] _ p _ p`, and the post-processing function of `m` flattens the nested array of characters produced from parsing the complete input. You can test it in the [Nearley Parser Playground](https://omrelli.ug/nearley-playground/), but you'll need to add the the code above and the test cases yourself since there's no permalink feature. Alternatively, if you're comfortable with the Developer Tools in your browser, you can evaluate the following snippet on the console while loaded on that page to save yourself from having to insert the test cases manually. ``` localStorage.playgroundState=String.raw`{"active":0,"compiled_grammar":"module.exports={ParserRules:[{name:'m',symbols:['_','p','_'],postprocess:a=>a.flat(1/0)},{name:'p$ebnf$1',symbols:[/[\\d]/]},{name:'p$ebnf$1',symbols:[/[\\d]/,'p$ebnf$1'],postprocess:a=>[a[0],...a[1]]},{name:'p',symbols:['p$ebnf$1']},{name:'p',symbols:[/[-+/*]/,'_','p','_','p'],postprocess:a=>['(',a,')']},{name:'_$ebnf$1',symbols:[]},{name:'_$ebnf$1',symbols:[{literal:' '},'_$ebnf$1'],postprocess:a=>[a[0],...a[1]]},{name:'_',symbols:['_$ebnf$1']}],ParserStart:'m'}","tabs":[{"name":"Add parentheses to Polish notation","editor_value":"m->_ p _{%a=>a.flat(1/0)%}\np->[\\d]:+|[-+/*] _ p _ p{%a=>['(',a,')']%}\n_->\" \":*","errors":[],"tests":["+1 2","++ 1 2 3"," +1 +2 3","* *1 2 /3 0 ","//30 300/18 205","/ -20/ 30 30 999","/////1 2 3 4 5 6","/1/2/3/4/5/6/7/8 9"]}]}`;location.reload() ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), ~~178~~ ~~177~~ 175 bytes *-3 bytes thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)* ``` S/L:-atom_codes(S,L). [C|T]*P*R:-C=32,T*Q*R,P=[C|Q];C>47,[C|T]+P+R;T*E*Q,Q*F*R,append([[40,C],E,F,[41]],P). [N|T]+[N|P]+R:-N>47,T+P+R. X+_+X. S^T:-S/L,L*P*R,append(P,R,M),T/M. ``` [Try it online!](https://tio.run/##Nc7BCoJAEAbgu08xdNLd2TXNChS7SJ0sVt2DIKtISgiVUkGX3t12g@Ywh@Gfb2Z6jNfxwp7vYZ4LNw1Z@xpvzXns@qddYOpwq0o@UhFB8pAl8cpHSTKSo4j1PFNRsgu2@ItQQfNIkj3JMCMHHWmnqb93dlUFS0wU7vGAVeAphcKoJ7Oiu1BUyyfDSENwq6QNLblV1DJk@iVMzfG/JjDHo4PSPfI5ZAsAVxe4nueB78MKAljDBmBRlwjvx/Dq7dLh8xc "Prolog (SWI) – Try It Online") ### Explanation The other Prolog answer cleverly reads characters from stdin one at a time. I wanted to try a more "traditional" solution, a predicate which takes a string and generates another string. ``` S/L:-atom_codes(S,L). ``` Define the `/` operator as a shortcut for converting an atom or string to a list of codepoints and vice versa. ``` [C|T]*P*R:- ``` The `*` operator is the main workhorse here. It takes a list of codepoints (the first of which is `C` and the remainder of which are `T`) and parses one Polish-notation expression from the beginning of it, returning the correctly parenthesized parsed expression in `P` and the rest of the list of codepoints in `R`. It has three branches: ``` C=32,T*Q*R,P=[C|Q] ``` If `C` is a space, parse everything after the space and prepend a space to the result. ``` C>47,[C|T]+P+R ``` If `C` is a digit, parse a run of digits using the `+` operator (defined below). ``` T*E*Q,Q*F*R,append([[40,C],E,F,[41]],P). ``` Otherwise, `C` is an operator. Parse a subexpression `E`, then parse another subexpression `F`. Finally, concatenate an open paren, the operator `C`, both subexpressions, and a close paren together to form the result `P`. To parse a run of digits: ``` [N|T]+[N|P]+R:-N>47,T+P+R. ``` If the list of codepoints starts with a digit `N`, parse a run of digits from the portion following `N`, and prepend `N` to the result. ``` X+_+X. ``` Otherwise, the remainder is the same as the input. The result is a "don't care" (`_`), which apparently works because (based on its use in the calling predicate) it has to be a list, and the empty list is the first possibility Prolog tries. The `^` operator is the main predicate: ``` S^T:-S/L,L*P*R,append(P,R,M),T/M. ``` It takes a string `S`, converts it to a list of codepoints `L`, parses `L` into a parenthesized expression `P` and remainder `R`, concatenates `P` and `R` into `M` (so as to keep any trailing spaces), and converts `M` back into the string result `T`. --- If I can take and return lists of codepoints instead of strings, this solution is **145 bytes**: ``` [C|T]*P*R:-C=32,T*Q*R,P=[C|Q];C>47,[C|T]+P+R;T*E*Q,Q*F*R,append([[40,C],E,F,[41]],P). [N|T]+[N|P]+R:-N>47,T+P+R. X+_+X. X^Y:-X*P*R,append(P,R,Y). ``` [Answer] # Python3, 226 bytes ``` lambda s:f(s)[0] import re f=lambda s:((' '*O[0].count(' '))+'('+O[0].lstrip()+(J:=f(s[len(O[0]):]))[0]+(T:=f(J[1]))[0]+')',T[1])if(O:=re.findall('^(?:\s+)*[\*\-\+/]',s))else((O:=re.findall('^(?:\s+)*\d+',s))[0],s[len(O[0]):]) ``` [Try it online!](https://tio.run/##dY5Ba4QwFITv/op3y0vibqJSWAXpbQ972cvejAVblQayGhL3sL/eJlJaLDSHwMw3zBv7XD7nqThZt55rtZru/t534KsRPW1km@i7nd0CbkjG@gciEiDsGvjxY35MS5SUcoKEb6bxi9MWKcdLVYemxgwTRkKrlsZajrcILk32rQkl6S0qPeK1qt1wHPXUd8YgecPXSnlOWaOYOiguWpJ6SgfjB/w3q3q@pUJ3uj@/WqfD4nPYmkEeZie/BodgQbEzIbyQjP9fxIDFvChAAuyIEIWEQkqRnSCXL3sGh1wK2AIAZVkGun4B) [Answer] # [C (GCC)](https://gcc.gnu.org), 174 bytes ``` #define p putchar( f(char *x){int s[100]={0},*S=s,b,c;for(;*x;){if(b=*x==32)p*x++);for(c=0;isdigit(*x);b=c=1)p*x++);for(*S+=c;*S==2;)p')'),*S=0,*--S+=1;b||++S+p'(')+p*x++);}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TZLBboMwDIa1IzyF1R2wExABNKlVlqfosUJTS0uXw1pUqITU8iS79NLr3md7mjkZVOMQ7P-zfyyHz3v1tq-q2-1-7upk_v31vN3V9rCDBppzV72vTxjW6N4gerrYQwftKlOqNBc1xGJp2ngTV7o-nlCLXnNFjRsjemOKnBrRS0keVkZp227t3nbIRnpjKpP9LxBLaSrNhibX1EQUkXNXsUgSJpneXK9SLmUTYURy7BuGv6l_ntYfa3tAuoSBH9UeV6WfEgywFsxkBvksdhG6kDj2sgTOoJgQ-pygmAqAH25w56PMZfgnolNpKhYgnFtagBoNBaDwhuhEIgAPHEvTQkGhVJrNIVcvY0OKo0w4god7CkmuUvAYYLFYTC2ADHAk7hvMaBYGg-Y-Xi2guzXLFwD2Ncv5lCZ3qwpq5EXZkvTjrjNFmgGnrWcyK50whOOmp__kFw) Note: as it is, it works up to `100` nested brackets. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~32~~ 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÎĆü2vyÇн₆%Ígi'(?>0}y¬?dRJi')×? ``` Input as a list of characters. [Try it online](https://tio.run/##yy9OTMpM/f//cN@RtsN7jMoqD7df2PuoqU31cG96prqGvZ1BbeWhNfYpQV6Z6pqHp9v//x@tpK@ko6QAxLpAbATEBkAMEzOG8tHZIGwJx7EA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVnlopb2SwqO2SQpK9pXBof8NIo60Hd5jVFZ5uP3C3kdNbaqHe9Mz1TXs7QxqKw@tsU8J8spU1zw83f5/be2hbfb/tQ0VjLi0tRWAlIIxlwIQAEVAJIirpaAFEtc3VjDg0tc3NlAwNjDQN7RQMDIw5dJX0DUy0FcACyooWFpaAlUAAdgcBRMFUwUzLn1DfSN9Y30TfVN9M31zfQsFSwA). Port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/250895/52210), so make sure to upvote him as well! **Explanation:** ``` Î # Push 0 and the input character-list Ć # Enclose it; append its own head ü2 # Pop and push its overlapping pairs v # Loop over each pair of characters `y`: y # Push the current pair `y` Ç # Convert both to its codepoint integer н # Pop and leave just the first integer ₆% # Modulo-36 Í # +2 g # Then pop and push the length i # If this is 1 (which means it's an operator character): '(? '# Print "(" > # Increase the current value by 1 0 # Push a new 0 } # Close the if-statement y # Push pair `y` again ¬ # Push its first character (without popping the pair) ? # Pop and output this first character d # Check for both characters whether they're digits R # Reverse the pair J # Join them together to a string i # If this is "01": ')× '# Pop the top value, and push a string with that many ")" ? # Pop and print it ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~136~~ ~~132~~ 125 bytes ``` #define p putchar( x;*s;r(n){for(;*s&&n<2;x||p*s<40?n--,*s++:p'(')+!!r(!p*s++))))for(x=!++n;*s>47;)x=p*s++);}f(*a){s=a;r(0);} ``` [Try it online!](https://tio.run/##dVDvboIwEP8sT3GwTK8goYDLppXtBfYGygeC4EhYJYAJifLqY9eimCzZfWj7@3dtL3XTMpHHYXg6ZHkhM6igOrfpV1Kj0Qm7ETVKdslPNRKYz@U2EN31WtnNdsU/pOsu7cZxNtUCF8wxzRrNShGMSmW6yHQcScn31atgXTSKos/RTtiliRJqzwkP30khkV2MWSFbKE67eOdzHkMERM0@LceHwFrqI6ozIzAKDhCEcBJREwzCyQJUlFHrw6ggjiwqmk12G2zV0QuB35vagLZuioplDEArWvS8kEPIuee/QcBf7hEPbzzDm/K4wQM34B5oHWC9Xk8hQFLwJql7SGSWMesFJWmegHo8ERdQbP2AVicKaGrwp6qafDlaz2Wzl1lXZWmbHTagYZ0157IF2NAn1KSLeNyABhczQS/JUdNMwL@N93IvLWXujX74SfMyOTbDLw "C (clang) – Try It Online") ]
[Question] [ Inspired by [Create a binary wall](https://codegolf.stackexchange.com/questions/135323/create-a-binary-wall) Given a list of positive integers, we can write them out all above each other like so, for `[2, 6, 9, 4]` as an example: ``` 0010 0110 1001 0100 ``` We can imagine this as a wall: ``` ..#. .##. #..# .#.. ``` However, this is a very weak wall, and it has collapsed! Each `1` (`#`) falls down until it hits the "ground" or another `1` (`#`). The `0`s (`.`s) are present in spots left by moved `1`s. This becomes the following: ``` .... .... .##. #### ``` Which translates back to: ``` 0000 0000 0110 1111 ``` Which, as a list of numbers, is `[0, 0, 6, 15]`. # Another test case ``` [10, 17, 19, 23] ``` This becomes: ``` 01010 10001 10011 10111 ``` which becomes: ``` 00000 10011 10011 11111 ``` translating back to: ``` [0, 19, 19, 31] ``` # Challenge Given a list of positive integers, apply this transformation to the list. Input/Output as lists of positive integers in any reasonable format. Standard loopholes apply. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! [Answer] # [MATL](https://esolangs.org/wiki/MATL), 4 bytes ``` BSXB ``` Try it at [MATL Online](https://matl.io/?code=BSXB&inputs=%5B2%2C+6%2C+9%2C+4%5D&version=20.2.2) **Explanation** ``` % Implicitly grab input as an array % STACK: [10, 17, 19, 23] B % Convert each element to binary where each decimal number results in a row % STACK: [0 1 0 1 0; % 1 0 0 0 1; % 1 0 0 1 1; % 1 0 1 1 1] S % Sort each column, placing all of the 1's at the bottom of each column % STACK: [0 0 0 0 0; % 1 0 0 1 1; % 1 0 0 1 1; % 1 1 1 1 1] XB % Convert each row from its binary representation to its decimal number % STACK: [0, 19, 19, 31] % Implicitly display the result ``` [Answer] # [Python](https://docs.python.org/), 68 bytes ``` f=lambda a:a and[x|y&a[0]for x,y in zip([0]+f(a[1:]),f(a[1:])+[-1])] ``` [Try it online!](https://tio.run/##NcgxCoAwDEDRq2SSFiu0OoiCJwkZIlIsaC3iYMW7xy4ODz4/5Ws9Yifip433eWHgsYgL3m@uGC3544TbZAgRnpBUObVXjG4kbf6osXGkSdIZ4qW8QmcNuL4YDLQdaS3yAQ "Python 3 – Try It Online") [Answer] ## JavaScript (ES6), 50 bytes ``` f=a=>a.map(_=>a.map((e,i)=>a[a[i]|=a[--i],i]&=e))&&a ``` Explanation: Suppose two rows of the wall were like this: ``` 0011 0101 ``` The result needs to be this: ``` 0001 0111 ``` In other words, the first row becomes the AND of the two rows and the second row becomes the OR of the two rows. This just needs to be repeated enough times for all the bits to fall to the bottom. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` BUz0Ṣ€ZUḄ ``` [Try it online!](https://tio.run/##y0rNyan8/98ptMrg4c5Fj5rWRIU@3NHy////aEMDHQVDcyC21FEwMo4FAA "Jelly – Try It Online") [Answer] # [Python 3.5](https://docs.python.org/3/), 60 bytes ``` def f(a,*t): if t:b,*r=f(*t);t=f(a|b,*r);a&=b return(a,*t) ``` [Try it online!](https://tio.run/##JczBCoMwEATQc/MVcyqJ7KFqaTHil4iHSF0akChheyj473FLD8PAg5n9K@8ttaW8FgbbQJU4bxAZ4meq8sBWpRftcPzA9eE6zAZ5kU9O/0HhLWNFTBgbwoPQEe4TYaxvhPqpUWjayZvLnmMSq6erc@UE "Python 3 – Try It Online") Takes input like `f(2, 6, 9, 4)`. Assumes input is non-empty. Uses a lot of [tuple unpacking](https://www.python.org/dev/peps/pep-0448/). [Answer] # [Japt](https://github.com/ETHproductions/japt), 16 bytes ``` m¤z3 ®¬n qÃz mn2 ``` [Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=baR6MyCurG4gccN6IG1uMg==&inputs=WzIsIDYsIDksIDRd,WzEwLCAxNywgMTksIDIzXQ==&flags=LVE=) using the `-Q` flag to format the array result. ## Explanation ``` m¤z3 ®¬n qÃz mn2 Implicit: U = input array. [10, 17, 19, 23] m¤z3 Map U to binary strings and rotate the array left 90° 1010 0111 10001 -> 1011 10011 0001 10111 1000 111 ®¬n qà Sort each binary string, putting 0s and spaces at the start 0111 0111 0001 0001 111 z mn2 Rotate right 90° and convert each back to a number 0000 0 10011 -> 19 10011 19 11111 31 Implicit output of resulting array ``` [Answer] # Mathematica, 64 bytes ``` #~FromDigits~2&/@(Sort/@(PadLeft[#~IntegerDigits~2&/@#]))& ```  is [`\[Transpose]`](https://reference.wolfram.com/language/ref/character/Transpose.html) This converts the input (a list of numbers) to a list of lists of digits, pads it to be a square matrix, transposes it, sorts the rows so the 1's "fall" to the bottom, transposes back, then converts back into numbers. [Answer] # Octave, ~~29~~ 25 bytes *4 bytes saved thanks to @Stewie* ``` @(x)bi2de(sort(de2bi(x))) ``` [Answer] # [J](http://jsoftware.com/), 13 bytes ``` /:~"1&.|:&.#: ``` [Try it online!](https://tio.run/##y/r/P03B1kpB36pOyVBNr8ZKTU/ZiosrNTkjX0HDOk1TzU7BSMFMwVLBRMFawdBAwdBcwdBSwcj4/38A "J – Try It Online") ## Explanation ``` /:~"1&.|:&.#: Input: array M #: Convert each in M to binary with left-padding |:& Transpose /:~"1& Sort each row &.|: Inverse of transpose (which is just transpose) &.#: Inverse of converting to binary ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` bí0ζR€{øC ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/6fBag3Pbgh41rak@vMP5//9oIx0FMx0FSx0Fk1gA "05AB1E – Try It Online") Kinda different algorithm from Magic's. [Answer] # Dyalog APL, ~~24~~ ~~21~~ 19 bytes ``` 2⊥↑{⍵[⍋⍵]}¨↓2⊥⍣¯1⊢⎕ ``` [Try it online!](http://tryapl.org/?a=%7B2%u22A5%u2191%7B%u2375%5B%u234B%u2375%5D%7D%A8%u21932%u22A5%u2363%AF1%u22A2%u2375%7D10%2017%2019%2023&run) (modified so TryAPL accepts it as valid) ### How? * `⎕` evaluated input (arrays are space separated) * `2⊥⍣¯1⊢` converts each each of the arguments to binary (transposed of what is in the question) * `↓` turns a 2D array into a vector of vectors * `{⍵[⍋⍵]}¨` sorts each of the elements of the vector * `↑` turns the vector of vectors into a 2D array again * `2⊥` convert from binary (since it sort of transposes it, we arrive at the correct result) [Answer] # Dyalog APL (23 characters) ``` {2⊥¨↓⍉↑{⍵[⍋⍵]}¨↓2⊥⍣¯1⊢⍵} ``` 1. Convert the input arguments into a binary matrix 2. Split the matrix into columns 3. Sort the columns into ascending order 4. Convert the sorted rows back into decimal ## Example ``` {2⊥¨↓⍉↑{⍵[⍋⍵]}¨↓2⊥⍣¯1⊢⍵}10 17 19 23 0 19 19 31 ``` Thanks to Zacharý for correcting me on this one. [Answer] # JavaScript, ~~127~~ 125 bytes ``` a=>a[m='map'](_=>b[m]((n,i)=>n&&(b[i]--,d|=1<<i),d=0)&&d,b=[...Array(32)][m]((_,c)=>a[m](e=>d+=!!(2**c&e),d=0)&&d)).reverse() ``` [Try it online](https://tio.run/##TY7hSsMwFEZfJQNJ7503Ye2GMrYb8DliWNMmk441GakMRH32OiaIP78D5/Cd/NVPfRku7yrlEOcjz56NtyNXo79UDg5sOjs6gEQDsklSQmcHpxSFL673@wEp8AqlDNSx1Vq/lOI/YN2gu2sH6vEedBDZhEdeLKBZLnsZ/0REXeI1likCzrs@pymfoz7nN7C2oSfa0saRrVdUP1O9pWbtnL6dAy/YiNY@fHp9ykNqSbTfTiiljLjBI3j8x9vfAdVrqhB38w8) *-2 bytes thanks to [Cows quack](https://codegolf.stackexchange.com/users/41805/cows-quack)* [Answer] ## Python 2, 142 bytes ... and still golfing... hopefully –– Any help appreciated! ``` def c(l):b=[bin(n)[2:]for n in l];print[int(n,2)for n in map(''.join,zip(*map(sorted,zip(*['0'*(len(max(b,key=len))-len(x))+x for x in b]))))] ``` A big chunk of this is for padding the numbers with zeroes. More readable: ``` def collapse(nums): bins = [bin(n)[2:] for n in nums] bins = [('0'*(len(max(bins, key = len)) - len(x))) + x for x in bins] print [int(n, 2) for n in map(''.join, zip(*map(sorted, zip(*bins))))] ``` This creates an array of the binary string representations, pads it, rotates it 90º clockwise, sorts each row, rotates it back 90º, and then creates integers out of each row. [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` m¤ù yñ mÍ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=baT5IHnxIG3N&input=WzEwLCAxNywgMTksIDIzXQ) ``` m¤ù yñ mÍ :Implicit input of array m :Map ¤ : To binary strings ù :Left pad each with spaces to the length of the longest y :Transpose ñ :Sort each and transpose back m :Map Í : To decimal ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` mḋTmOT0mo↔ḋ ``` [Try it online!](https://tio.run/##yygtzv7/P/fhju6QXP8Qg9z8R21TgJz///9HG@mY6VjqmMQCAA "Husk – Try It Online") ]
[Question] [ Help! My **[Completely Automated Lights From Darks Separator V3001.01](http://i.ebayimg.com/00/s/NTEyWDUxMg==/z/E1MAAOSwr81UPxrD/$_1.JPG)** broke! :( # Guidelines --- ## Task Write a program that will take an input of an array (or a list in some languages) of any amount of strings that are either the letter L or the letter D (representing lights or darks) and output an array that contains two arrays, one with all the L's, and one with all the D's. --- ## Rules * It's code golf so the shortest answer in bytes wins * Input will only ever contain capitals * There must be the same number of L's in the output as there is in the input, same goes for the D's * The input may only have one element (or maybe even *zero* elements) * If one or both of the output arrays contain no elements, output an empty list (in some languages this may mean you need to output a string) * Always have the first array be the array of L's --- ## Example output: `["L","D","L","D","D"] -> [["L","L"],["D","D","D"]]` `["L","L","L"] -> [["L","L","L"],[]]` `["D","D"] -> [[],["D","D"]]` `[] -> [[],[]]` [Answer] # [Python 3](https://docs.python.org/3/), 37 bytes ``` lambda a:[[c]*a.count(c)for c in"LD"] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHRKjo6OVYrUS85vzSvRCNZMy2/SCFZITNPycdFKfZ/QVEmUDRNI1rJR0lHyQWIYTRQVlOTC1UeglHFsagFcv4DAA "Python 3 – Try It Online") [Answer] # APL, 8 bytes ``` 'DL'~⍨¨⊂ ``` Explanation: * `⊂`: enclosed input * `~⍨¨`: without each * `'DL'`: 'D' and 'L' Examples: ``` ('DL'~⍨¨⊂) 'LDLDD' ┌──┬───┐ │LL│DDD│ └──┴───┘ ('DL'~⍨¨⊂) 'LLL' ┌───┬┐ │LLL││ └───┴┘ ('DL'~⍨¨⊂) 'DD' ┌┬──┐ ││DD│ └┴──┘ ('DL'~⍨¨⊂) '' ┌┬┐ │││ └┴┘ ``` [Answer] # [Haskell](https://www.haskell.org/), 28 bytes ``` f l=[filter(==[c])l|c<-"LD"] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hxzY6LTOnJLVIw9Y2OjlWM6cm2UZXycdFKfZ/iW10tJKPko6SCxDDaKCEDkQUgkE8uHhsLFduYmaegq1CbmKBr4JGQWlJcEmRT55ecUZ@uaaCCkhYIU2h5D8A "Haskell – Try It Online") If the input can be a list of characters, the `[]` around `c` can be removed. [Answer] # PHP, 46 bytes Assumed given list is: `$arr = ['L','L','D','D','L','D','D','D','D','L'];` `foreach($arr as $b){$a[$b][]=$b;};print_r($a);` [Answer] # Mathematica, 27 bytes ``` Rest/@Gather[{L,D}~Join~#]& ``` Pure function taking a list of `L`s and `D`s (symbols, not characters/strings) as input and returning a list of two lists. For example, ``` Rest/@Gather[{L,D}~Join~#]& @ {D, L, L, D, L} ``` returns `{{L, L, L}, {D, D}}`. [Try it online!](https://tio.run/##y00sychMLv6fZvs/KLW4RN/BHSiQWhRd7aPjUlvnlZ@ZV6ccq/Y/oCgzryQ6zaHaRUfBB4xAjNrY/wA) `Gather` by itself is close to what we want, but fails to meet the spec in two ways: it doesn't produce empty lists if the input is missing `L`s or `D`s, and it doesn't always sort `L`s to the left. Replacing the input `#` with `{L,D}~Join~#` solves both problems at once: it means there will be at least one `L` and at least one `D`, and the `L`s will be returned first since an `L` was encountered first. `Rest/@` then removes the initial `L` and `D`. (I tried a solution using `Count`, but due to currying issues, it didn't seem to be shorter: `±q_:=#~Table~Count[q,#]&/@{L,D}` is 31 bytes.) [Answer] ## Haskell, 32 bytes ``` import Data.List partition(>"K") ``` Just a boring library function. [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrzbYgsagksyQzP0/DTslbSfN/bmJmnoKtQko@l4JCQVFmXomCikKaQrSSj5KOkgsQw2gXpVgsKiA4VgFNCqoBTTj2PwA "Haskell – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 26 bytes ``` ->x{x.partition{|e|e==?L}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf166iukKvILGoJLMkMz@vuia1JtXW1t6ntvZ/QWlJsUJadLSSj5KOkgsQw2gXpdhYBVtbBaiUj1KsTjRUAiLJhaIVqgZVC1QbUC1CMarZCEORFSHJAoX/AwA "Ruby – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~13~~ ~~12~~ 10 bytes ``` 2Æf¥"LD"gX ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=MsZmpSJMRCJnWA==&input=WyJMIiwiRCIsIkwiLCJEIiwiRCJdCi1R) (`-Q` flag for visualisation purposes only) --- ## Explanation Implicit input of array `U`. ``` 2Æ ``` Generate the array `[0,1]` and pass each element through a function, with `X` being the current element. ``` f¥ ``` Filter `U` by checking for equality... ``` "LD"gX ``` ...with the character in string `LD` at index `X`. [Answer] # PHP7, ~~52~~ 45 bytes *-7 bytes thanks to @Jörg Hülsermann* ``` foreach($argv as$a)$$a[]=$a;print_r([$L,$D]); ``` Use with CLI as `php -r a.php L L L D D L D` The script goes through the provided arguments and appends them to an array based on its value. [Answer] # Common Lisp, ~~66~~ 65 bytes ``` (defun f(x)`(,(remove"D"x :test'equal),(remove"L"x :test'equal))) ``` [Try it online!](https://tio.run/##S87JLC74/18jJTWtNE8hTaNCM0FDR6MoNTe/LFXJRalCwaoktbhEPbWwNDFHEy7hgyahqflfo6AoM69EQSNNQV0DqFEBjH2QaAgGKQUA) If, instead of strings, we use symbols, then it is much shorter: # Common Lisp, ~~42~~ ~~41~~ 40 bytes ``` (defun f(x)(mapcar'remove'(D L)`(,x,x))) ``` [Try it online!](https://tio.run/##DclLCsAgDAXAq2SXF/AYLj2EYhWEasV@yO1TmeXks93TDEep76AKFfQ0c1q8Sr@@wvAUJMKpUxExzNXGQ6jECOS3sH/HDw) ``` (f '(D D L L D L D)) ; => ((L L L) (D D D D)) ``` [Answer] # [Racket](https://racket-lang.org), 48 bytes ``` (compose list((curry partition)(λ(x)(eq? x'L)))) ``` Just apply this anonymous function to, e.g., `'(L D L D D L)` [Answer] ## Mathematica, ~~22~~ 18 bytes *4 bytes saved by the genius of CalculatorFeline!* ``` Cases@@@{#|L,#|D}& ``` [Try it online](https://tio.run/##y00sychMLv6fZvvfObE4tdjBwaFaucZHR7nGpVbtf0BRZl6JQ5pDtYuOi44PBNf@BwA "Mathics – Try It Online"), or at the [Wolfram sandbox](https://sandbox.open.wolframcloud.com/)! Input is a list of the symbols `L` and `D` — not strings, just the letters on their own, like in [Greg Martin's answer](https://codegolf.stackexchange.com/a/131835/66104). The syntax `#|L` is shorthand for `Alternatives[#,L]`, but the `@@@` syntax replaces the head `Alternatives` with `Cases`, so this code is equivalent to `{Cases[#,L],Cases[#,D]}&`. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 42, 37 bytes ``` l('L'). w(L,D,W):-partition(l,W,L,D). ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P0cjQtNKN8JW3Uddj6tcw0fHRSccKFCQWFSSWZKZn6eRoxOuAxTV1Pv/v1zDUcdJJxqoVAeMXeB0rKYeAA "Prolog (SWI) – Try It Online") Given that `W` is a list of washing, `w/3` will unify `L` and `D` into lists of Lights and Darks respectively, by partitioning the washing against a predicate which succeeds if an item is a Light. [Edit: golfed -5 thanks to [Fatalize](https://codegolf.stackexchange.com/users/41723/fatalize)] [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~10~~ 9 bytes ``` mc@dQ1"LD ``` [Test suite](http://pyth.herokuapp.com/?code=mc%40dQ1%22LD&test_suite=1&test_suite_input=%5B%22L%22%2C%22D%22%2C%22L%22%2C%22D%22%2C%22D%22%5D%0A%5B%22L%22%2C%22L%22%2C%22L%22%5D%0A%5B%22D%22%2C%22D%22%5D%0A%5B%5D&debug=0). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` 'Lù'DÃ) ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f3edw86Gd6i6HmzX//49W8lHSgeJYAA "05AB1E – Try It Online") [Answer] # Javascript (ES6), 37 bytes This is based on a (now deleted) Javascript (ES6) answer. ``` a=>[(b=c=>a.filter(d=>c==d))`L`,b`D`] ``` **Ungolfed version:** ``` function(array) { function filter(character){ return array.filter(function(d) { return character == d; }); } return [filter("L"), filter("D")]; } ``` **Example code snippet:** ``` f= a=>[(b=c=>a.filter(d=>c==d))`L`,b`D`] console.log(f(["L", "D", "L", "D", "D"])) ``` [Answer] # C#, 61 bytes ``` using System.Linq;a=>new[]{a.Where(c=>c<69),a.Where(c=>c>68)} ``` Full/Formatted Version: ``` using System; using System.Linq; class P { static void Main() { Func<char[], System.Collections.Generic.IEnumerable<char>[]> f = a => new[] { a.Where(c => c < 69), a.Where(c => c > 68) }; Console.WriteLine(string.Join(", ", f(new[]{ 'L', 'D', 'L', 'D', 'D' }).SelectMany(a => a.Select(c => c)))); Console.ReadLine(); } } ``` [Answer] # [F#](http://fsharp.org/), 37 bytes ``` let f s=List.partition(fun a->a="L")s ``` [Try it online!](https://tio.run/##SyvWzc3Py///Pye1RCFNodjWJ7O4RK8gsagksyQzP08jrTRPIVHXLtFWyUdJs/h/QVFmXklanoKSqqOSgkaaQjRQ2FrJBYhhtItSrCYXdmUQjFUat85Yzf8A "F# (Mono) – Try It Online") Takes input as a list of strings, and returns two lists, the first with elements where `fun a -> a="L"` is true and the other with elements that result in false. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ẎfЀ⁾LDW€€ ``` [Try it online!](https://tio.run/##y0rNyan8///hrr60wxMeNa151LjPxyUcxGha8/9w@9FJD3fO@P8/Wt1HXUdB3QVEIFgu6rEA "Jelly – Try It Online") In Jelly a string is a list of 1-char Python strings, e.g. `['a', 'b', 'c']`. That's why you get output such as `[[['L'], ['L']], [['D'], ['D'], ['D']]]`, since 1-char Jelly strings behave the same. Doesn't work as a full program, hence the `ÇŒṘ` at the bottom. [Answer] # [Perse](https://github.com/faso/Perse), 21 bytes ``` part(i,fn(x){x=="L"}) ``` I may or may not have implemented the list partition function specifically for this challenge. Takes the input as an array of strings. [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` Mof-"DL ``` [Try it online!](https://tio.run/##yygtzv6fq1EcrPOoqfG/b36arpKLz////6OjlXyUdJRcgBhGuyjF6kBEIRjEg4vHxgIA "Husk – Try It Online") ### Explanation ``` Mof-"DL M "DL For each character in ['D','L']: of- keep only those strings that are not empty if that character is removed ``` [Answer] # Java 8, ~~110~~ 106 bytes ``` a->{String[]r={"",""};for(char c:a)r[c/69]+=c;return new char[][]{r[1].toCharArray(),r[0].toCharArray()};} ``` -4 bytes thanks to *@Nevay*. **Explanation:** [Try it here.](https://tio.run/##rZBNT8MwDIbv/RVWL01FF@CCBFEnIXaEXcYt6iGkGUtpk8pNh6Yqv71k7cYkrkNKLH/otR@7EnuxsK0yVfk16qa16KAKOdo7XdNnRHHoWCRr0XXwJrQZIgBtnMKtkArWxxBA7gTyghcgyeyCSFmo@PDD65xwWsIaDOQwisVy2DjU5pMXmA9xnMWxZ1uLkxbkk0iRy9uHx@ImlwyV69GAUd@/Uwbk9wV19iXEEyBJM@R3f1Ke@ZHN89v@ow7zTxh7q0towirkTBFo5z02h86phtre0TaUXG3IfAFaKtW@21lADJXkAjQkr0kGyepoLt4q8Wk6HeG6tidzdbN/gjrrfeTHHw) ``` a->{ // Method with char-array parameter and 2D char-array return-type String[]r={"",""}; // Two Strings in an array for(char c:a) // Loop over the characters of the input r[c/69]+=c; // Append either of the two String with the character // c/69 will result in 0 for 'D' and 1 for 'L' // End of loop (implicit / single-line body) return new char[][]{ // Return a 2D character-array r[1].toCharArray(), // With the String for L's converted to a char-array r[0].toCharArray()}; // and String D's converted to a char-array } // End of method ``` [Answer] # Octave, 21 bytes ``` @(A){A(a=A>72),A(~a)} ``` Input is an array of characters, output is a cell array. Recycled from my answer [here](https://codegolf.stackexchange.com/questions/70779/consolidate-an-array/70827#70827). Sample execution on [ideone](https://ideone.com/akbaAJ). [Answer] # [R](https://www.r-project.org/), 35 bytes ``` x=scan(,'');list(x[i<-x>'D'],x[!i]) ``` [Try it online!](https://tio.run/##K/r/v8K2ODkxT0NHXV3TOiezuESjIjrTRrfCTt1FPVanIloxM1bzv4@Cj4ILEILJ/wA "R – Try It Online") Reads from stdin. [Answer] # Julia, 26 bytes ``` g(s)=s[s.=="L"],s[s.=="D"] ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 20 bytes ``` ->l{[l-[?D],l-[?L]]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOjpHN9reJVYHRPnExtb@L1BIi45W8lHSUXIBYhjtohQby4WQgmC4EKoKIP0fAA "Ruby – Try It Online") [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 8 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` `LDdẊcx× ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSU2MExEZCVFMSVCQSU4QWN4JUMzJTk3JmZvb3Rlcj1kJmlucHV0PSU1QiUyMkwlMjIlMkMlMjJEJTIyJTJDJTIyTCUyMiUyQyUyMkQlMjIlMkMlMjJEJTIyJTVEJTIwLSUzRSUyMCU1QiU1QiUyMkwlMjIlMkMlMjJMJTIyJTVEJTJDJTVCJTIyRCUyMiUyQyUyMkQlMjIlMkMlMjJEJTIyJTVEJTVEJTBBJTVCJTIyTCUyMiUyQyUyMkwlMjIlMkMlMjJMJTIyJTVEJTIwLSUzRSUyMCU1QiU1QiUyMkwlMjIlMkMlMjJMJTIyJTJDJTIyTCUyMiU1RCUyQyU1QiU1RCU1RCUwQSU1QiUyMkQlMjIlMkMlMjJEJTIyJTVEJTIwLSUzRSUyMCU1QiU1QiU1RCUyQyU1QiUyMkQlMjIlMkMlMjJEJTIyJTVEJTVEJTBBJTVCJTVEJTIwLSUzRSUyMCU1QiU1QiU1RCUyQyU1QiU1RCU1RCZmbGFncz1D) #### Explanation ``` `LDdẊcx× # Implicit input -> ["L","D","L","D","D"] `LD # Push the string "LD" -> ["L","D","L","D","D"] "LD" d # Split it into characters -> ["L","D","L","D","D"] ["L","D"] Ẋ # Store it in x without popping -> ["L","D","L","D","D"] ["L","D"] c # Count occurrences in the input -> [2,3] x× # Multiply by x elementwise -> [["L","L"],["D","D","D"]] # Implicit output ``` [Answer] # [Haskell](https://www.haskell.org/) (Lambdabot), 41 bytes ``` reverse.map tail.group.sort.("LD"++).join ``` [Try it online!](https://tio.run/##VY29DoIwGEX3PsWXskCAvgEDAcNSDIsTEtPEotXSNm11MT57rT8MDic3uecm98zclUsZHmUCtN52u7rbQDMMkJRPJBajrYdGK2@1JL1W7LiWLfOMUOE8mqt9sPzOreNkYQY8E5KcrL4Z4uKSpJi2OM8zctFCBc@dd1AhgBFGTHGB28iaLZ6iKX7my9r8@XdMCC1MKKgg3vYHSI0VypM5g89JeAE "Haskell – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 27 bytes ``` ($args-eq'L'),($args-eq'D') ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0MlsSi9WDe1UN1HXVMHwXNR1/z//7@Pgo@CCwgDAA "PowerShell – Try It Online") --- Edit: previously `$args.where({$_-eq'L'},'sp')` for 28 bytes. Could be `$args.where({+"0x$_"},'sp')` for 27 if not for the rule that L's must come first. [Answer] # [CJam](https://sourceforge.net/p/cjam), 14 bytes ``` "LD"qf{1$e=*}` ``` Input is a list of characters (string), output is a list of lists of characters (list of strings). [Try it online!](https://tio.run/##S85KzP3/X8nHRakwrdpQJdVWqzbh/38fIHABAiDp4wIA "CJam – Try It Online") Explanation: ``` "LD" e# Push the string "LD" | "LD" q e# Push the input | "LD" "LDLLDLDDL" f{ e# Foreach char in "LD", push input and: | ['L "LDLLDLDDL" 1$ e# Copy from 1 back | ['L "LDLLDLDDL" 'L e= e# Count occurences | ['L 5 * e# Repeat character | ["LLLLL" } e# End | ["LLLLL" "DDDD"] ` e# Stringify: | "[\"LLLLL\" \"DDDD\"]" e# Implicit output: ["LLLLL" "DDDD"] ``` ]
[Question] [ Given a string, reverse it interleavingly. Here's how to do it for `abcdefghi` and `abcdefghij`, 0-indexed: 1. Separate the chars at even indices from the chars at odd indices: ``` a c e g i b d f h a c e g i b d f h j ``` 2. Reverse the chars at odd indices: ``` a c e g i h f d b a c e g i j h f d b ``` 3. Interleave into one string again: ``` ahcfedgbi ajchefgdib ``` # Rules * You must support both even-length and odd-length strings. * 0-index-wise, you must reverse the chars at odd indices, not even. * 1-index-wise, of course, you must reverse the chars at even indices, not odd. * Input will consist of printable ASCII (code points 32-126), no newlines. * You can take input either as a string or as a list of chars (NOT 1-char strings). E.g. `String`/`char[]` or `char*` are allowed, but `String[]`/`char[][]` or `char**` aren't. # Test cases ``` Input Output ``` ``` Hello, World! HdlroW ,olle! Hello World! H!llooW rlde ABCDEFGHIJKLMNOPQRSTUVWXYZ AZCXEVGTIRKPMNOLQJSHUFWDYB !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ }"{$y&w(u*s,q.o0m2k4i6g8e:c<a>_@]B[DYFWHUJSLQNOPMRKTIVGXEZC\A^?`=b;d9f7h5j3l1n/p-r+t)v'x%z#|!~ P P AB AB xyz xyz ``` For the empty string, return the empty string itself. [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` t2L)P5M( ``` [Try it online!](https://tio.run/nexus/matl#@19i5KMZYOqr8f@/emJSckpqWnpGpjoA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S/hfYuSjGWDqq/HfJeS/ukdqTk6@jkJ4flFOiqI6F4SP4Do6Obu4url7eHp5@/j6@QcEBgWHhIaFR0RGASUVFJWUVVTV1NU1NLW0dXT19A0MjYxNTM3MLSytrG1s7ewdcGuPjomNi09ITEpOSU1Lz8jMys7JzcsvKCwqLiktK6@orKquqa0DWhEAdgOQAAqpAwA). ### Explanation ``` t % Implicit input. Duplicate % STACK: 'abcdefghi', 'abcdefghi' 2L % Push [2, 2, 1j]. This represents 2:2:end when used as an index % STACK: 'abcdefghi', 'abcdefghi', [2, 2, 1j] ) % Get entries at those indices % STACK: 'abcdefghi', 'bdfh' P % Flip % STACK: 'abcdefghi', 'hfdb' 5M % Push [2, 2, 1j] again % STACK: 'abcdefghi', 'hfdb', [2, 2, 1j] ( % Write entries at those indices. Implicit display % STACK: 'ahcfedgbi' ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` s2ZU2¦Z ``` This is a full program. [Try it online!](https://tio.run/nexus/jelly#@19sFBVqdGhZ1P@Hu7ccbn/UtCby///EpOSU1LT0jEwuOCuLyyM1JydfRyE8vygnRRHCg3EcnZxdXN3cPTy9vH18/fwDAoOCQ0LDwiMio7i4ArgcA7gqKqsA "Jelly – TIO Nexus") ### How it works ``` s2ZU2¦Z Main link. Argument: s (string) s2 Split s into pairs. Z Zip/tranpose, grouping characters by the parity of their indices. ¦ Sparse application: U Upend; reverse both strings in the pair. 2 Replace the second string with the reversed string. Z Zip/transpose, interleaving the two strings. ``` [Answer] # [Alice](https://github.com/m-ender/alice), 10 bytes ``` /ZY \IOR@/ ``` [Try it online!](https://tio.run/nexus/alice#@68fFckV4@kf5KD//79Hak5Ovo5CeH5RTooiAA "Alice – TIO Nexus") Half of the bytes of this program are spent on correctly formatting the source, the actual commands are just `IYRZO`, because Alice has just the right builtins for this task. ### Explanation As I said, the mirrors (`/\`), the newline and `@` are there just to make the ip move in the right direction and terminate the program at the end. The actual code, linearised, is the following: ``` IYRZO I Input a line Y Unzip it into its even positions and its odd ones R Reverse the odd positions Z Zip it back again O Output ``` Quite straightforward, I'd say. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~108~~ ~~96~~ ~~94~~ 93 bytes *Saved 1 byte by using [@Neil's neat trick](https://codegolf.stackexchange.com/a/123083/41805) of using `s[s.length+~i|1]`* ``` String f(char[]s){int a=s.length,b=0;String c="";for(;b<a;b++)c+=s[b%2<1?b:a+~b|1];return c;} ``` [Try it online!](https://tio.run/##dZFZV4JQFIWf8VdcKQsCSW0WycwGmwcrK6S6l0FRvNDloiniXydMXT71dvY6w/72Oh3Yh1nXM3HH6Ma6A30fVMIU41NIbT2uU2LjFrA4vQ2Jqvl8aGMKoOJLjolbtC0iJSfPh3SFZWXLJZyMSlBGgsDrguKrKFMo5cuoCIUJGuc1mZg0IBjochQzXoAcWwczM9B3bQP0oI252UVVG/EJCjO9OfeARWwOwKIdshDphmm12jYrLutOImqm47giaLjEMdILvZSV4@rJ6dl57eLy6vrm9u7@4bH@9PzSeH17T5og3WRXVjNr6xy/IYhZaTOXL2xt7@zu7R8U5ZJyWD76f11tNrWPz68lS9fpYdf7Jj4N@oOf4SgcR5PEY8r7xzwDn@OzEZ/kZepDn5o9yQ2o5CVJqYM5i4MSdavJFyqEwCHH87ycYqJUFP8C "Java (OpenJDK 8) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~52~~ 50 bytes -2 bytes (and a bug fix) thanks to pxeger ``` s=bytearray(input()) s[1::2]=s[1::2][::-1] print s ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9g2qbIkNbGoKLFSIzOvoLREQ1OTqzja0MrKKNYWSkdbWekaxnIVFGXmlSgU//@v7pGak5OvoxCeX5SToqgOAA) or [Try all test cases](https://tio.run/##dY9ZV4MwEIXf@RWpVQNKVXCP4r7Uva5VgWoooaTGgCFYcPvrmFM9xydfZua7c@65M2kp44TbVR33uzGJeiENQBWSCEQ6NpAGMicoJcFC4FIJil0LIdt3fruLUMPyNSCIzAUHWTWIKSPAUs7CoTzNpa5MqaBcgsKEHodmpBfGcKpgkzCWmKCdCBbWoPbDf7i5tb2zu7ffPDg8Oj45PWudX1xeXd@0b@/u1RLURuqjY@Me1I2JSbMxNT1j2bNz8wuLS8toZdVZW9/43@56fufhEQdd9Wgvpv0n9syT9EVkMn8dFOXb@8fnl4poDW9QRUnwGw) [Answer] # Octave, 32 bytes ``` @(a,b=a(x)=a(flip(x=2:2:end)))a; ``` [Try it online!](https://tio.run/nexus/octave#@@@gkaiTZJuoUaEJJNJyMgs0KmyNrIysUvNSNDU1E63/J@YVa6h7pObk5CuE5xflpCiqa/4HAA "Octave – TIO Nexus") [Answer] ## JavaScript (ES6), 48 bytes ``` f= s=>s.replace(/./g,(c,i)=>i%2?s[s.length+~i|1]:c) ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Ḋm2U m2żÇ ``` [Try it online!](https://tio.run/nexus/jelly#@/9wR1euUShXrtHRPYfb////n5iUnJKalp6RmQUA "Jelly – TIO Nexus") ``` Ḋm2U Helper Link -> Dequeue (return last len-1 elements), take every second element, reverse m2żÇ Main Link -> Take every second element, then interleave with the result of the helper link ``` *-1 byte thanks to Dennis* [Answer] # [Retina](https://github.com/m-ender/retina), ~~17~~ 13 bytes ``` O^$`(?<=\G.). ``` [Try it online!](https://tio.run/nexus/retina#U9VwT/jvH6eSoGFvYxvjrqep9/9/YlJySmpaekYmF5yVxeXo5Ozi6ubu4enl7ePr5x8QGBQcEhoWHhEZxaWgqKSsoqqmrqGppa2jq6dvYGhkbGJqZm5haWVtY2tn74Bbb3RMbFx8AsKa7JzcvPyCwqLiktKy8orKquqa2jqQK4AmAgA "Retina – TIO Nexus") Fixed an error thanks to Neil. Saved 4 bytes thanks to Kobi. Selects each letter preceded by an odd number of characters and reverses them. Does this by using `\G` which matches the end of the last match. [Answer] # PHP>=7.1, 58 Bytes ``` for(;$i<$l=strlen($a=$argn);$i++)echo$a[$i&1?-$i-$l%2:$i]; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/079962836fdfa0b85b9c82a8e096e8c4fafc41b3) [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 13 bytes 12 bytes of code, +1 for the `-P` flag. *Saved 1 byte thanks to @Shaggy* ``` ¬ë íU¬Åë w)c ``` ## Explanation: ``` ¬ë íU¬Åë w)c ¬ Split the input into an array of chars ë Get every other char, starting at index 0 í Pair with: U¬ Input, split into a char array Å .slice(1) ë Get every other char w Reverse c Flatten -P Join into a string ``` [Try it online!](https://tio.run/##y0osKPn//9Caw6sVDq8NBdKtQFa5ZvL//0oeqTk5@ToK4flFOSmKSgq6AQA) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 9 bytes Requires `⎕IO←0` (default on many systems) for proper definition of odd and even. ``` ⌽@{2|⍳≢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OA5KOevQ7VRjWPejc/6lz0qHdr7f//aQrqiUnJKalp6RmZ6lzIvCx1AA "APL (Dyalog Unicode) – Try It Online") `⌽` reverse `@` at the elements filtered by the mask result from applying the `{` anonyomous function  `2|` the mod-2 of  `⍳` the indices of  `≢` the tally (length) of  `⍵` the argument `}` on the argument [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes `ι` and `.ι` have been added since this challenge was posted, both of them save bytes here. ``` Sι`R.ιJ ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/@NzOhCC9czu9/v/3SM3JyddRCM8vyklRBAA "05AB1E – Try It Online") If we were allowed to take a list of string of length 1, [`ι`R.ι`](https://tio.run/##yy9OTMpM/f//3M6EIL1zO///j1byUNJRUEoFETlwIh9E6IAIBRARDhcrgitJARGKSrEA) would work for 5 bytes. ``` S # split the string into a list of characters ι # uninterleave: push [even indices, odd indices] ` # push both values seperately to the stack R # reverse the odd indices .ι # interleave the two lists J # join into a string ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), `s`, 3 bytes ``` yṘY ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=y%E1%B9%98Y&inputs=Hello%20World!&header=&footer=) Turns out by making my answer valid I saved a byte. Oh the irony ## Explained ``` yṘY y # un-interleave Ṙ # reverse Y # re-interleave ``` [Answer] # [Röda](https://github.com/fergusq/roda), 34 bytes ``` f a{a/=""a[::2]<>reverse(a[1::2])} ``` [Try it online!](https://tio.run/##K8pPSfz/P00hsTpR31ZJKTHaysoo1sauKLUstag4VSMx2hAkoFn7PzcxM6@aK9E2WikxKTklNS09I1NJB8HOAnI8UnNy8nUUwvOLclIUYXwE19HJ2cXVzd3D08vbx9fPPyAwKDgkNCw8IjIKKKmgGKOkrKKqpq6hqaWto6unb2BoZGxiamZuYWllbWNrZ@@AW3t0TExsXHwCwi3ZObl5@QWFRcUlpWXlFZVV1TW1dUA7QO4FuxnicKjzlWK5qtMUSqyjE7gSYmvT8osUShQy8xQSuWr/AwA "Röda – Try It Online") ### Explanation ``` a/="" Convert the argument a into an array of length-1 strings <> Interleave a[::2] Every even element of a with reverse(a[1::2]) Every odd element of a reversed ``` --- Here is an alternative solution at the same bytecount ### ~~36~~ 34 bytes ``` {[_/""]|_[::2]<>reverse(_1[1::2])} ``` This is an anonymous function that takes input as a string from the input stream. [Answer] # [Python 2](https://docs.python.org/2/), 67 bytes ``` lambda s,j=''.join:j(map(j,zip(s[::2]+' ',s[1::2][::-1]+' ')))[:-1] ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQrJNlq66ul5WfmWeVpZGbWKCRpVOVWaBRHG1lZRSrra6grlMcbQhiAwV0DcEimpqa0SD2/4KizLwShTQN9cSk5JTUtPSMzCx1TS5MUaDgfwA "Python 2 – TIO Nexus") [Answer] # [OCaml](http://www.ocaml.org/), 70 bytes ``` let f s=String.(mapi(fun i c->s.[(length s land-2-i-i)*(i mod 2)+i])s) ``` [Try it online!](https://tio.run/##XYy7DoJAFERr@YoL1a4CBa3BRCtKEgsKY7HsAy65sIbFRP15xDUWUk1mzslYKXqaZ9ITGHD5eRpxaFLWixsycx8AQSYHl14Y6aGZWnBAYlBJlmCCfMsQeqsg4zu8csf9DeOQBxvhnB6XYiASrTRaNTVGkC@tlkqbpsWI7/@1H@i@XifbpSqs12KhiWwMlR1Jhd4tFI22gtgS6XCtl14p1/Px5PclVuDxfHnySR7Mbw "OCaml – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 63 bytes ``` (_:r)!(a:s)=a:s!r _!_=[] f s=([' '|even$length s]++reverse s)!s ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/XyPeqkhTUSPRqljTFkgoFnHFK8bbRsdypSkU22pEqyuo16SWpeap5KTmpZdkKBTHamsXAQWKilMVijUVi//nJmbmKdgqpORzKQBBQWlJcEmRT56CikKaglJiUnJKalp6RqYSPsksbLIeQMfl6yiE5xflpCjiVIBH3tHJ2cXVzd3D08vbx9fPPyAwKDgkNCw8IjIKm2oFxRglZRVVNXUNTS1tHV09fQNDI2MTUzNzC0sraxtbO3sH3OZFx8TExsUnIPyTnZObl19QWFRcUlpWXlFZVV1TW4fN0gDs7sYmCjRF6T8A "Haskell – Try It Online") Usage: `f "some string"`. For odd strings like `abcdefghi`, the function `f` passes the string and its reversal to the function `!`, which alternates taking chars from both strings. For even strings this does not work, and we need to append a dummy character first to get the offset right. [Answer] # C, 69 bytes ``` c,l;f(char*s){l=strlen(s);for(c=0;c<l;++c)putchar(s[c&1?l-l%2-c:c]);} ``` Pretty simple. Walks the string, printing either the current character or the opposite one. ### Ungolfed and explained: ``` f(char *str) { int len = strlen(str); // Get the total length for(int c = 0; c<len; ++c) // Loop over the string putchar(s[ // Print the char that is, c & 1 // if c is odd, ? l - l % 2 - c // c chars from the end (adjusting odd lengths), : c // and at index c otherwise ]); } ``` [Answer] ## Mathematica, 82 bytes ``` ""<>(f=Flatten)[{#&@@#,Reverse@Last@#}&@f[Characters@#~Partition~UpTo@2,{2}],{2}]& ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes ``` DgÉi¶«}2ô.BøRćR‚˜øJ¶K ``` [Try it online!](https://tio.run/##ATMAzP8wNWFiMWX//0Rnw4lpwrbCq30yw7QuQsO4UsSHUuKAmsucw7hKwrZL//9hYmNkZWZnaGk "05AB1E – Try It Online") I'm guessing the reason this wasn't done in 05AB1E yet is because it's gross... Yet another time the `zip` function's auto-drop-last-element hurts instead of helps. *P.S. If you have improvement suggestions on my answer, post your own; it's likely enough of an improvement to warrant you getting the points. I am pretty ashamed of this answer.* [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 18 bytes **Solution:** ``` {x[w:&2!!#x]:x@|w} ``` [Try it online!](https://tio.run/##y9bNz/7/v7oiutxKzUhRUbki1qrCoaa8VskjNScnX0chPL8oJ0VR6f9/AA "K (oK) – Try It Online") **Examples:** ``` > {x[w:&2!!#x]:x@|w}"Hello, World!" "HdlroW ,olle!" > {x[w:&2!!#x]:x@|w}"Hello World!" "H!llooW rlde" ``` **Explanation:** Interpretted mostly right-to-left, find the odd-indices characters, reverse them and put them back into the string ``` {x[w:&2!!#x]:x@|w} / solution { } / lambda function with implicit parameter x #x / count x, #"Hello, World!" -> 13 ! / til, !13 -> 0 1 2 3 4 5 6 7 8 9 10 11 12 2! / 2 modulo, 2!0 1 2 3 4 5 6 7 8 9 10 11 12 -> 0 1 0 1 0 1 0 1 0 1 0 1 0 & / where true, @0 1 0 1 0 1 0 1 0 1 0 1 0 -> 1 3 5 7 9 11 w: / store in variable w |w / reverse w, |1 3 5 7 9 11 -> 11 9 7 5 3 1 x@ / index into x at these indices x[ ]: / assign right to x at these indices ``` [Answer] # J, 26 bytes ``` [:,@,./(0 1$~#)]`(|.@])/.] ``` ### ungolfed ``` [: ,@,./ (0 1 $~ #) ]`(|.@])/. ] ``` ### explanation * `(0 1$~#)]`(|.@])/.]` Use Key `/.` to split the input into the even/odd groups: `(0 1$~#)` creates the group definition, by repeating 0 and 1 cyclically to the length of the input. We use the gerundial form of Key for its main verb `]`(|.@])`, which applies the identity to the first group and reverses the second group: `(|.@])`. * Now that we have the two groups, the odd one reversed, we just zip them together and flatten: `,@,./` [Try it online!](https://tio.run/##PYpJC4JAGEDv/oqvBVQYRrsKgvuejfsSQpBKxMCAXqu/boLg4V3ee@9lnEFVQIaV5a4gDWFJkOFy/p3E7iF8sNaJEu4WkTti4EdV4QHBV4Fx5rjh@WIwAu8NlDIEFZtof@AhNjB4PZ1YBYhROhz2kWyR7EI3TMt2XM8Pwuga30iSZnlRVnXTbqfemrVdurmfhmTtURJkXuFUVmMsfw "J – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~8~~ 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ó oÔrí ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8yBv1HLt&input=ImFiY2RlZmdoaSI) ``` ó oÔrí :Implicit input of string ó :Uninterleave o :Modify last element Ô : Reverse r :Reduce by í : Interleaving ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 3 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` ^rI ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSU1RXJJJmZvb3Rlcj0maW5wdXQ9SGVsbG8lMkMlMjBXb3JsZCEtJTNFSGRscm9XJTIwJTJDb2xsZSElMEFIZWxsbyUyMFdvcmxkIS0lM0VIIWxsb29XJTIwcmxkZSUwQUFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaLSUzRUFaQ1hFVkdUSVJLUE1OT0xRSlNIVUZXRFlCJTBBJTIwISUyMiUyMyUyNCUyNSUyNicoKSolMkIlMkMtLiUyRjAxMjM0NTY3ODklM0ElM0IlM0MlM0QlM0UlM0YlNDBBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWiU1QiU1QyU1RCU1RV8lNjBhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5eiU3QiU3QyU3RH4tJTNFJTIyJTIwJTdEJTVDJTIyJTdCJTI0eSUyNncodSpzJTJDcS5vMG0yazRpNmc4ZSUzQWMlM0NhJTNFXyU0MCU1REIlNUJEWUZXSFVKU0xRTk9QTVJLVElWR1hFWkMlNUNBJTVFJTNGJTYwJTNEYiUzQmQ5ZjdoNWozbDFuJTJGcC1yJTJCdCl2J3glMjV6JTIzJTdDIX4lMjIlMEFQLSUzRVAlMEFBQi0lM0VBQiUwQXh5ei0lM0V4eXomZmxhZ3M9Qw==) #### Explanation ``` # Implicit input ^ # Uninterleave into two parts and push them separately to the stack # "Hello, World!" -> "Hlo ol!", "el,Wrd" # "ABCDEF" -> "ACE", "BDF" # "P" -> "P", "" r # Reverse the top of stack (second part from before) # "Hello, World!" -> "Hlo ol!", "drW,le" # "ABCDEF" -> "ACE", "FDB" # "P" -> "P", "" I # Interleave the two strings together # "Hello, World!" -> "HdlroW ,olle!" # "ABCDEF" -> "AFCDBE" # "P" -> "P" # Implicit output ``` [Answer] # Python 3, ~~93~~ 87 bytes ``` lambda s:"".join("".join(t)for t in zip(s[::2],reversed(s[1::2])))+("",s[-1])[len(s)%2] ``` [Answer] # [Perl 6](https://perl6.org), ~~63 58~~ 55 bytes ``` {[~] .comb[{flat roundrobin (0,2...^*>=$_),[R,] 1,3...^*>=$_}]} ``` [Test it](https://tio.run/nexus/perl6#dY9nVyoxEIa/51cERdyFsDTFsoL07r30XtwSYDFs1i0IIvx1buB48ZMnk3My75N5Z8axMFxFBUUEyw30KFTFMHbYDvYjKCh0KQ@2UyLZ0KSOrppU1nTIBVFYEISxNx5zT3g0qKMRDKHIWdqNdgdmlbCxZcMYJJqOLY4XZiY2uMCwEeAFk9rU5MK8CBzWvMn@icAgkg59pyIRTKn5Xe@PQ26o6YZjoyFeG1ixscrDLYBQs@BxWO4EeQT/UwRPCtgdJFlR8XQ214A0V6ZYnckaAGdxAaSFMmdPVZMBKGBCKIIdahLVBQoqMWkHIkoIdn3DM3OxhEGWYACSqXQmm8sXiqVy5eXP32qt3mi22p1urw@S/XQ32843i/VylaFKrdQotHKdTC8FAHRdXLqvPNcc7/UhvxAIhsKRm9vo3f3Do/gUiz8nfvcdDEfjyevPGm9kqVPj3bRsZ/Wx3nxuv3Z7AHcXW/fG88E5Xgu9CzS4DL/daNHZPX5UnqT4JDFKDTK9XKfQKjUqNeb/Ui83i@18N9tPD5Pj59eYLKoP07v57SJCQnrA8Js@m19dr68@L79cewCq7LDljwFY0@P9Bw "Perl 6 – TIO Nexus") ``` {[~] flat roundrobin .comb[{0,2...*},{$_-1-$_%2,*-2...*}]} ``` [Test it](https://tio.run/nexus/perl6#dY/ZVuJAEIbv@ykaBUwgCYuKSwTZdx32HTFLB4JNOmZBMMKrMw3jOFdzuvqcrv/r@qvKtRFcJwRFBKstDCpERTB58Mb7KdSw5ECLuIZqEVk3oKCQlTz2olxcEITQjvP8Mz7G@2eBOBfi/2jT3YG6pB1kOzAJsW4gm2GFuYVMJjJpR1jBIg6xmDgrApf27dB/IjCxZMDwqUgEGrG@6/kUZCa6YboON0EbEykOUlnoAQh1Gx7nZE6Q5eBfysGTAnYHSVZUpM0XOpAWiobUuawD8CMugbRUFvSp6jIAZYQx4WCfWFj1gbKKLdKHHMEY@b7hD/PRhEKaIAAy2Vy@UCyVK9Va/en5V6PZane6vf5gOAKZUW5Q6JU6lVatQVG9WW2Xu8V@fpgFAPrOzv2B4AXDhsIcL0Sisfjl1XXi5vbuXnxIph7T//cdT6Yvs9d/a7zhlUHMd8t23PXHZvvpfe32AO7OPP82@MG4IZt7F0h0FX@70hPzW3SvPEipWXqaHeeHxX65W23Xm9T/qVXrVHqlQWGUm2ReHl@TsqjeaTeL6@UljhkRk7fCDru@2AQ@z798ewAa9NDljwFo0@P9DQ "Perl 6 – TIO Nexus") ``` {[~] flat roundrobin .comb[{0,2...*},{[R,] 1,3...^$_}]} ``` [Test it](https://tio.run/nexus/perl6#dY/XduIwEIbv9RQiIcQGYVpCigOh9@zSe4mLDCbGclwIxDGvzgpONnu1ZzTn6J9P84/GsTDcJjmJB5s9DEhExjB1dCeHGVQ0wYYmcXTZJKKqQ04iG3HiRlGc47igh9xJG81gDCWonPsX3sw7UouMjS0bpqCm6thiWG5pYoOJTDsRljOJTUwmzvLAoUO79B0PDE3QYejcxAOFmN/94TRkpqpuODaa4p2BJRvLLHQBhKoFT59kzpBF8C9F8FwB3lEQJRkry5UKhJWkYHkpqgD8FNdAWEsrepVVEYAK1jSC4ICYmuwDFVkzyQAiomnY9w1/mI8KCqnAAGRz@UKxVK5Ua/XGy6/fzVa70@31B8PRGGTH@WGxX@5W2/UmRY1WrVPplQaFUQ4A6Lu49F8Frhk2GEJhLhKNxRM3t8m7@4dH/imVfs7833cync0Xr//WeNM2OjHeTct2th@7/af75R0A9C5c/z7wwThBC71zJLqJv92oyeU9fpSehPQiM8tNCqPSoNKrdRot6v/Srner/fKwOM5Ps/Pn15TIyw/K3ep2ndBiesQImyGb3V7vrj4vv3wHAJo06PKnA@jQU/4B "Perl 6 – TIO Nexus") ``` { # bare block lambda with implicit parameter 「$_」 [~] # reduce using string concatenation operator flat # make the following a flat list roundrobin # grab one from each of the following 2 lists, # repeat until both are empty .comb\ # split the input into graphemes (implicit method call) [ # index into that sequence { 0, 2 ... * }, # code block producing every non-negative even number { # code block producing reversed odd numbers # (「$_」 here contains the number of available elements) [R,] # reduce with reversed comma operator # (shorter than 「reverse」) 1, 3 ...^ $_ # odd numbers stopping before it gets # to the number of input elements } ] } ``` I had to use [`roundrobin`](https://docs.perl6.org/routine/roundrobin) rather than [`zip`](https://docs.perl6.org/routine/zip), because [`zip`](https://docs.perl6.org/routine/zip) stops as soon as one of the input lists is exhausted. [Answer] # Mathematica, 62 bytes takes as input a string ``` (s=Characters@#;Row@Riffle[s[[;; ;;2]],Reverse@s[[2;; ;;2]]])& ``` [Try it online!](https://tio.run/nexus/mathics#S7P9r1Fs65yRWJSYXJJaVOygbB2UX@4QlJmWlpMaXRwdbW2tYG1tFBurE5RaBpRPdQCKGcEEYzXV/gcUZeaVKDikKTgoeaTm5OTrKITnF@WkKCr9BwA "Mathics – TIO Nexus") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 24 bytes *Bytes golfed thanks to @Adám* ``` A⊣A[i]←⌽A[i←2×⍳⌊2÷⍨⍴A←⎕] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPd6b/jo67FjtGZsY/aJjzq2QtkARlGh6c/6t38qKfL6PD2R70rHvVucQRJ902NBen578Sl7pGak5OvoxCeX5SToqjOBROBCQAA "APL (Dyalog Unicode) – Try It Online") [Answer] # GNU APL 1.2, 24 bytes ``` R[X]←⌽R[X←2×⍳⌊.5×⍴R←⍞]◊R ``` APL works from right to left. `⍴R←⍞` assigns user input to `R` and then evaluates its length. Halve this by multiplying by `.5` and apply `⌊` floor function. `⍳` returns all numbers from 1 to the argument. APL operates on arrays, so `2×` the array we just got from `⍳` doubles each element, giving us just the even indices (1-indexed, so relies on `⎕IO` being 1). When accessing multiple indices of a vector, APL gives the elements at those indices in a vector. `R[X←2×⍳⌊.5×⍴R←⍞]` gives just the even-indexed elements. `⌽` reverses the elements. Then, assign the reversed values back to the even indices (assigning these indices to `X` saves 6 bytes). `◊` is the statement separator. After the reversing is done, evaluate `R` to print the result. ]
[Question] [ This problem is "inspired" from a question that was originally asked on [Quora](https://www.quora.com/unanswered/How-should-one-find-the-maximum-deviation-from-a-given-number-of-consecutive-integers) (not for code golfing). I just want to make it a challenge for you guys (and my first problem submission here). Given an array of integer elements `v` and an integer `d` (we assume that d is lower or equal to the array's length), consider all the sequences of `d` consecutive elements in the array. For each sequence, compute the difference between the maximum and minimum value of the elements in that sequence and name it the deviation. Your task is to write a program or function that computes the maximum value among all deviations of all the sequences considered above, and return or output that value. Worked-through Example: ``` v: (6,9,4,7,4,1) d: 3 The sequences of length 3 are: 6,9,4 with deviation 5 9,4,7 with deviation 5 4,7,4 with deviation 3 7,4,1 with deviation 6 Thus the maximal deviation is 6, so the output is 6. ``` This is code golf, so the shortest answer in bytes wins. [Answer] # Dyalog APL, 7 bytes ``` ⌈/⌈/-⌊/ ``` Test it on [TryAPL](http://tryapl.org/?a=f%u2190%u2308/%u2308/-%u230A/%20%u22C4%203%20f%206%209%204%207%204%201&run). ### How it works ``` ⌈/⌈/-⌊/ Dyadic chain. Left argument: d. Right argument: v ⌊/ Reduce v by d-wise minimum, yielding the minima of all slices of length d. ⌈/ Reduce v by d-wise maximum, yielding the maxima of all slices of length d. - Subtract, yielding the ranges of all slices of length d. ⌈/ Take the maximum. ``` [Answer] ## JavaScript (ES6), 73 bytes ``` with(Math)(v,d)=>max(...v.map((a,i)=>max(...a=v.slice(i,i+d))-min(...a))) ``` [Answer] # Python, 60 bytes Saving 5 bytes thanks to Neil ``` f=lambda v,d:v and max(max(v[:d])-min(v[:d]),f(v[1:],d))or 0 ``` My first recursive lambda! Usage: ``` print f([6,9,4,7,4,1], 3) ``` [Answer] # Perl, 48 bytes Includes +5 for `-0pi` Give the width after the `-i` option, give the elements as separate lines on STDIN: ``` perl -0pi3 -e '/(^.*\n){1,$^I}(?{\$F[abs$1-$&]})\A/m;$_=$#F' 6 9 4 7 4 1 ^D ``` Just the code: ``` /(^.*\n){1,$^I}(?{\$F[abs$1-$&]})\A/m;$_=$#F ``` (use a literal `\n` for the claimed score) [Answer] # R, ~~63~~ ~~62~~ 56 bytes Billywob has already provided a great [R answer using only the base functions](https://codegolf.stackexchange.com/a/96926/59052). However, I wanted to see if an alternative approach was possible, perhaps using some of R's extensive packages. There's a nice function `rollapply` in the `zoo` package designed to apply a function to a rolling window of an array, so that fits our purposes well. We use `rollapply` to find the `max` of each window, and we use it again to find the `min` of each window. Then we take the difference between the maxes and mins, which gives us the deviation for each window, and then return the `max` of those. ``` function(v,d)max((r=zoo::rollapply)(v,d,max)-r(v,d,min)) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~13~~ 7 bytes ``` ▲m§-▼▲X ``` [Try it online!](https://tio.run/##yygtzv7//9G0TbmHlus@mrYHyIr4//@/8f9oMx1LHRMdcyA2jAUA "Husk – Try It Online") -6 bytes from Jo King. ## Explanation ``` ▲m§-▼▲X Slices of length n m map to §- difference between ▼▲ min and max ▲ take the maximum of that ``` [Answer] # R, 80 77 bytes bytes Edit: Saved 3 bytes thanks to @rturnbull ``` function(s,d)max(sapply(d:sum(1|s)-d+1,function(i)diff(range(s[i:(i+d-1)])))) ``` [Answer] # Mathematica, ~~41~~ 37 bytes ``` Max[MovingMap[MinMax,#,#2-1].{-1,1}]& ``` [Answer] ## PowerShell v2+, 68 bytes ``` param($v,$d)($v|%{($x=$v[$i..($i+++$d-1)]|sort)[-1]-$x[0]}|sort)[-1] ``` Iterative solution. Loops through `$v`, but really we're just using that as a counter rather than actually going through the values. Each iteration, we're slicing `$v` by `$i..($i+++$d-1)`, where `$i` defaults to `0`. We `|sort` those elements, and store the result into `$x`. Then we take the biggest `[-1]` and subtract the smallest `[0]`. We then `|sort` those results and take the biggest `[-1]` of that. That number is left on the pipeline and output is implicit. ### Examples ``` PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(6,9,4,7,4,1) 3 6 PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(1,2,3,4,5,6) 3 2 PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(7,2,3,4,5,6) 3 5 ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~12~~ 10 bytes Uses [CP-1252](http://www.cp1252.com) encoding. ``` Œù€{øÀ`-ÄZ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=xZLDueKCrHvDuMOAYC3DhFo&input=WzYsOSw0LDcsNCwxXQoz) **Explanation** ``` Œ # sublists of v ù # of length d €{ # sort each ø # zip À # rotate left (last 2 lists will be largest and smallest) ` # flatten (lists with smallest and largest item will be on top) - # subtract largest from smallest Ä # take absolute value (as we will have negatives after the previous step) Z # take the largest ``` [Answer] # Ruby, 45 bytes ``` ->a,d{a.each_cons(d).map{|b|b.max-b.min}.max} ``` I feel like this could be a lot better. [Answer] # Scala, 48 bytes ``` (_:Seq[Int])sliding(_:Int)map(s=>s.max-s.min)max ``` Ungolfed: ``` (a:Seq[Int],d:Int)=>a.sliding(d).map(s=>s.max-s.min).max ``` Explanation: ``` (_:Seq[Int]) //define a function with a seq of ints as an argument sliding(_:Int) //get the sequences with the length of an int argument map(s=> //map each sequence s.max-s.min //to its deviation )max //and take the maximum value ``` [Answer] # Java 8, 140 128 Shaved a bunch off, in part thanks to VTCAKAVSMoACE. ``` int l(int[]a,int d){int x=0,i=0,f,j,k;for(;i<=a.length-d;i++)for(j=i;j<i+d;j++)for(k=i;k<i+d;)x=(f=a[j]-a[k++])>x?f:x;return x;} ``` Ungolfed ``` int l(int[]a,int d){ int x=0,i=0,f,j,k; for(;i<=a.length-d;i++) for(j=i;j<i+d;j++) for(k=i;k<i+d;) x=(f=a[j]-a[k++])>x?f:x; return x; } ``` [Answer] # [Factor](https://factorcode.org/) + `math.statistics`, 32 bytes ``` [ clump [ range ] map supremum ] ``` [Try it online!](https://tio.run/##DcwxCgIxEAXQfk/xT7AgiqIeQGxsxGrZIgxjDCbZ7MykEPHsMcVr39ORLdIe9@vtcsKbJXNEETb7FAnZ4GWpJWSP5Ow1qjkLaoEUymvlTKw4D8MXexyxw6Hb4Idtm0CxpoIJ4rJnzD0o0NrvVBPmRi5GjO0P "Factor – Try It Online") * `clump` Get the windows of [first input] of length [second input] * `[ range ] map` Map each window to its 'deviation' (which Factor calls `range`) * `supremum` Maximum element [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 70 bytes ``` (0..(-$d+$v.count)|%{$s=$v[$_..($_+$d-1)]|sort;$s[-1]-$s[0]}|sort)[-1] ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvUqZgq@CgYaZjqWOiYw7EhppcKilAMeP/GgZ6ehq6KinaKmV6yfmleSWaNarVKsW2KmXRKvFAKZV4bZUUXUPN2Jri/KISa5XiaF3DWF0gZRBbCxbSBAn8//8fAA "PowerShell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ŒIùεW-}à ``` Inputs in the order \$v,d\$. [Try it online.](https://tio.run/##yy9OTMpM/f//6CTPwzvPbQ3XrT284P//aDMdSx0THXMgNozlMgYA) **Explanation:** ``` Œ # Get all sublists of the first (implicit) input-list `v` Iù # Only keep those with a length equal to the second input-integer `d` ε # Map over each d-sized sublist: W # Push the minimum of the current sublist (without popping the list) - # Subtract this minimum from each value in the list }à # After the map: pop and push the flattened maximum # (which is output implicitly as result) ``` The map `εW-}` could alternatively be `D€ß-` for a vectorized subtraction. [Answer] # MATLAB with Statistics and Image Processing Toolboxes, 33 bytes ``` @(v,d)max(range(im2col(v,[1 d]))) ``` This defines an anonymous function. Example use: ``` >> f = @(v,d)max(range(im2col(v,[1 d]))); >> f([6,9,4,7,4,1], 3) ans = 6 ``` You can also [try it on Octave at Ideone](http://ideone.com/Dfi7Ch) (but Octave, unlike Matlab, requires explicitly loading the image package). ### Explanation ``` im2col(v,[1 d])) % Takes overlapping blocks of size d from v, and arranges them as % columns of a matrix range(...) % Maximum minus minimum of each column. Gives a row vector max(...) % Maximum of the above row vector ``` [Answer] # Java 7,159 bytes Java = expensive(i know it can be golfed much more) ``` int c(int[]a,int d){int[]b=new int[d];int i,j,s=0;for(i=-1;i<a.length-d;){for(j=++i;j<i+d;)b[i+d-1-j]=a[j++];Arrays.sort(b);s=(j=b[d-1]-b[0])>s?j:s;}return s;} ``` # Ungolfed ``` static int c ( int []a , int d){ int []b = new int[ d ]; int i , j , s = 0 ; for ( i = -1 ; i < a.length - d ;) { for ( j = ++i ; j < i + d ;) b[ i + d - 1 - j ] = a[ j++ ] ; Arrays.sort( b ) ; s = ( j = b[ d - 1 ] - b[ 0 ] ) > s ? j : s ; } return s ; } ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 10 bytes ``` YCS5LY)dX> ``` [Try it online!](http://matl.tryitonline.net/#code=WUNTNUxZKWRYPg&input=WzYsOSw0LDcsNCwxXQoz) ### Explanation Consider inputs [6,9,4,7,4,1], 3 as an example. ``` % Implicitly take the two inputs: v, d % STACK: [6,9,4,7,4,1], 3 YC % Matrix of overlapping d-blocks of v % STACK: [6 9 4 7 9 4 7 4 4 7 4 1] S % Sort each column % STACK: [4 4 4 1 6 7 4 4 9 9 7 7] 5LY) % Keep first and last rows % STACK: [4 4 4 1 9 9 7 7] d % Differences along each column % STACK: [5 5 3 6] X> % Maximum % STACK: 6 % Implicitly display ``` [Answer] # PHP, ~~89~~ 87 bytes ``` for($i=1;$r=array_slice($argv,++$i,$argv[1]);$d=max($r)-min($r))$o=$d>$o?$d:$o;echo+$o; ``` Not particularly clever or pretty but it works. Use like: ``` php -r "for($i=1;$r=array_slice($argv,++$i,$argv[1]);$d=max($r)-min($r))$o=$d>$o?$d:$o;echo+$o;" 3 6 9 4 7 1 ``` for `v`=`6,9,4,7,4,1`, `d`=`3` Edit: 2 bytes saved thanks to Jörg Hülsermann [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ṡµṂ€ạṀ€Ṁ ``` [Try it online!](https://tio.run/nexus/jelly#@/9w58JDWx/ubHrUtObhroUPdzaAGDsb/v//b6ZjqWOiYw7Ehv@NAQ "Jelly – TIO Nexus") Uses the same algorithm as Dyalog APL, but I figured this myself before looking at it. Explanation: ``` ṡµṂ€ạṀ€Ṁ ḷ“Main link. Arguments: v d.” ṡ ḷ“Overlapping sublists of x of length y.” µ ḷ“Start a new monadic chain.” Ṃ€ạṀ€ ḷ“Find the deviation of each of the elements of x.” Ṁ ḷ“Take the maximum of x.” ``` Note: `x`, `y` are left, right arguments respectively. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` s₎ᶠ⟨⌉-⌋⟩ᵐ⌉ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/hRU9/DbQsezV/xqKdT91FP96P5Kx9unQDk/P8fHW2mY6ljomMOxIaxOsax/6MA "Brachylog – Try It Online") [Answer] # [Arturo](https://arturo-lang.io), 59 bytes ``` $[a,n][max map 0..-size a n'x[z:a\[x..x+n-1](max z)-min z]] ``` [Try it](http://arturo-lang.io/playground?VCYkUQ) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ãV mÍ®Ì-ZÎÃÍ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=41Ygbc2uzC1azsPN&input=WzYsOSw0LDcsNCwxXSAz) ``` ãV # subsequences of length V mÍ # sort each, ascending ®Ì-ZÎà # map each to last - first Í # sort, ascending # -h flag prints the last element ``` [Answer] # [Desmos](https://www.desmos.com), ~~62~~ 58 bytes ``` r=v[i-d+1...i] f(v,d)=[r.max-r.minfori=[d...v.length]].max ``` [Try it on Desmos!](https://www.desmos.com/calculator/bnvread4ok) -4 bytes thanks to [Aiden Chow](https://codegolf.stackexchange.com/users/96039/aiden-chow) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 12 bytes ``` ÞS'L⁰=;ƛG$g- ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJHIiwiIiwiw55TJ0zigbA9O8abRyRnLSIsIiIsIjYsOSw0LDcsNCwxXG4zIl0=) #### Explanation ``` ÞS'L⁰=;ƛG$g- # Implicit input ÞS # All sublists of the first input ' ; # Filtered by the following: L # The length of the sublist ⁰= # Equals the second input ƛ # Map over the filtered list: G # Push the maximum of the sublist $g # Swap and push the minimum - # Subtract to find the deviation # G flag gets the maximum of this list # Implicit output ``` [Answer] # [Uiua](https://uiua.org), 10 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` /↥-⊃/↧/↥⍉◫ ``` [Try it!](https://uiua.org/pad?src=0_3_1__ZiDihpAgL-KGpS3iioMv4oanL-KGpeKNieKXqwoKZiAzIFs2IDkgNCA3IDQgMV0K) ``` /↥-⊃/↧/↥⍉◫ ◫ # windows ⍉ # transpose ⊃/↧/↥ # maxes and mins of each column - # subtract /↥ # maximum ``` [Answer] # [CJam](http://sourceforge.net/projects/cjam/), 17 bytes ``` q~ew{$)\(\;-}%:e> ``` (Also `q~ew:$z)\(\;.-:e>`) [Try it online!](http://cjam.tryitonline.net/#code=cX5ld3skKVwoXDstfSU6ZT4&input=WzYgOSA0IDcgNCAxXQoz) ### Explanation ``` q~ e# Read the two inputs. Evaluate ew e# Overlapping blocks { }% e# For each block $ e# Sort ) e# Get last element (that is, maximum) \( e# Swap, get first element (minimum) \; e# Swap, delete rest of the block - e# Subtract (maximum minus minimum) :e> e# Maximum of array ``` [Answer] ## Haskell, 56 bytes ``` _#[]=0 d#l|m<-take d l=max(maximum m-minimum m)$d#tail l ``` Usage example: `3 # [6,9,4,7,4,1]` -> `6`. Considering ranges less than `d` doesn't change the overall maximum, so we can run `take d` down to the very end of the list (i.e. also include the ranges with the last `d-1`, `d-2`, ... `0` elements). The recursion stops with the empty list where we set the deviation to `0`. [Answer] # [Actually](http://github.com/Mego/Seriously), 13 bytes ``` ╗╜@V`;m@M-`MM ``` [Try it online!](http://actually.tryitonline.net/#code=4pWX4pWcQFZgO21ATS1gTU0&input=WzYsOSw0LDcsNCwxXQoz) -6 bytes from the observation in nimi's [Haskell answer](https://codegolf.stackexchange.com/a/97003/45941), that slices shorter than `d` don't affect the maximum deviation. Explanation: ``` ╗╜@V`;m@M-`MM ╗ store d in register 0 ╜@ push d, swap so v is on top V push all slices of v whose length is in [1, d] `;m@M-`M map (for each slice): ;m@M- get minimum and maximum, subtract min from max M get maximum of list of deviations ``` ]
[Question] [ If you place a knight on any square of a chessboard, what is the smallest amount of steps to reach every position? **Rules** * It is an 8 by 8 board. * The knight starts at an arbitrary position, taken as input. * The knight moves 2 squares in one direction and 1 square in the other, for example, a knight on the square marked N can move to any of the squares marked X: ``` . X . X . X . . . X . . N . . X . . . X . X . X . ``` **Example** With input `1, 0`, we start by putting a 0 in that position: ``` . 0 ``` We then put a 1 in the positions that are a knight's move away from that 0, i.e. they are 2 squares away in one direction and 1 square away in the other. We don't fill in the 0: ``` . 0 . . . . . 1 1 . 1 . ``` Then, we fill in all the empty cells that are exactly two knight's moves away with 2s: ``` . 0 . 2 . 2 2 . 2 1 2 . 1 2 1 . . 2 2 . 2 . 2 . . 2 . 2 . . ``` Then, the 3s: ``` 3 0 3 2 3 2 3 . 2 3 2 1 2 3 . 3 1 2 1 . 3 2 3 . 2 3 2 3 2 3 . 3 3 2 3 2 3 . 3 . . 3 . 3 . 3 . . 3 . 3 . 3 . . . ``` And we continue until we've filled the entire 8x8 board: ``` 3 0 3 2 3 2 3 4 2 3 2 1 2 3 4 3 1 2 1 4 3 2 3 4 2 3 2 3 2 3 4 3 3 2 3 2 3 4 3 4 4 3 4 3 4 3 4 5 3 4 3 4 3 4 5 4 4 5 4 5 4 5 4 5 ``` **Challenge** The pattern printed for a knight, as short as possible, in any reasonable format. [Answer] # [Knight](https://github.com/knight-lang/knight-lang), ~~272~~ ~~264~~ ~~193~~ ~~190~~ 188 bytes ``` ;=nF;=xP;=yP;=sS*'9'64+*8y xT0;W>9=n+1n;=r~1W>8=r+1r;=c~1W>8=c+1c;=a~3W>4=a+1a;=b~3W>4=b+1b&?5+*a a*b b&&&&>8=x+a r<~1x&>8=y+b c<~1y>E Gs+x*8yT=qGs+r*8cT=sSs+x*8yT+1q;=i~8W>64=i+8iO Gs i 8 ``` Input is 0-based horizontal and vertical coordinates, each on separate lines. A fitting language for this challenge... or maybe not... [Try it Online!](https://tio.run/##lVhrU9tIFv2eX9FoM1htCWFn2CxYtKmEJVOpnZhsYIbatZ3QarVtTWTJ6AFmbPHXmdt6tvwiQxWUpD59X33uo/mD3tOQBc4sOvB8mz8zl4Yh@o/njCfRRRD4AeLziHt2iNK3RZIBPtMg5PV1aU@B@hJ7kTN9GXcVBZxOF8z3wiiIWeQHKsWLaOKERujHAeOEJrDizG4mTsTDGWVczdenNGIT9fCr2h8MB/1BCN@TzlBb/qP/deANm@rAW77GuHmIkxnn32E14FEceEgS3m8Nl0svdt0kE2bpjLTwwuURosQy@JwzVYJjMxchthBC6Jl46MgQIj0bYWyB7SoFNYbLvXE0wTrtsyFOIh8cd7zxRquSJA0Huv7f54sr0h@aWah@p27MF2FEI4ehmTgF1cILy1gLjzmCKN7TAHxomfQ0FZPrN6mmZf4xkn7v06FRyDKdkcpwbg9LJF@TIPbSsAf@A/L4Q8aIxOZWPN7wfYt3qRCjWgRcL55aPNiCKxYB9973XU69LcByNclZ9SsEI6BuSbwsdCskC@OZkK6nor7ZNKLAtcxRSckGZ/L3at8mT/L3OmjNjeKDDON3rjAvR1DkgNXUY9wfZV5LbuzvS8YDH7OnIgpCeBmCPCRr/Cm4XmXT9Ych7r87@P@weai3S8rT/X1xwEKmqlwrQhtO7Hg6K525LZx5neZngm8TN5pUruxVtu7v09qxjWUcknF7dWCSkXkWhxNVfMVmlioXvd8/frnsfbroXZNFkifMR5t70QoHXnK/Tw/@/DYUf1sHJ98gBKsBSIWCsckuNjkCBGyqxyfd6owcwGUhynAiUGCuM/aEHMmTfoUZltTMDN6CEhl87zs2au2J8yksN6sEleuyevub993zHzzklJahRs20xm095qkLuIivFN0fpdfA1tZDCgHN04XiVVLlCxWnqG1LXCn2V5zRqFQ6cAI1eCf8oA6fxu5OeLMOt5172ctqSZxE7RAKUZ9oNDGANx6TpB6C39sOSTmnnudHCFTBmSDrEf3JA18BU337b@quFP5EX9QH4mPXl/TN/Ifd@irxy@WeSk9b@IecbzZ/wHs@n/meICmNeGoQinyojR4fA9/uOQLjeABGulsqyal8blvrTbeGqhG/on0PGuJu3kvVuyR@Ly@pOOO8EFIrIUUFEe12JQcUAVaxsqszpPJy518IJfOnYCZPtxhKGYy/uUsOjvhWRAea44vBERSyCJV6jtIYYpjjwsHVsHmGB@1D/U1KKxENYJYlEwk0iGElG2KokQ13Aqw0RFtiy2VDaYgHXLlUDa2i6IFVU8cDJtnoLvaBUNxjfiw@c7uDXi9ocruppaf21/NIb7fwctlaqVn5gLCrZgknbnNArnC99AhQpcsI@IxT6D1yBXqB8eWotZPxJUo@VPiYd1fYRe2rR491aEICfhc7AVeVUahgfSFG5HTJkpbYxHHtb7PAZzwUqA@/9c6vP172rqre/AFqwK7WLLEkO2CYzEsxfUvqdOlJS7OqKfHqrJNmnbY08GHGGC7maTEfixcb5mP7lBWzsV3MxiOSWmQUpghle6MtdPrkQO/2xogG43gqBo7XC1trJwiUoJHwEjqqJRqpybPAjnAinbEIhMp0S@crIwV8YitjhRBHaPbs0SknVvYMqkPC1mfXdINqGEaJKitLVsUVoT1yfE9VtFJqGR4LFSNnupVqRNGRollGJqPs4pqyVpsurT84iwwnTPmrw7iUjHJVKOBjJ4x46iJeQGjbolcVF6SVu4Sq9MAkNI1hyLMgUeeURe4jgl6A2IQG8AYzi@t7Y6hJZkUQOiSWpBECU3Yu@WjzJIMbqGpJeYDl2lONUdl9w9xIA6Xno3shGQpl7NrC1lSFvQe1UsoqEXCslyFQPiu6ikk3v5Ipim6R9/FoxAODuq7PVBjAbV8EiaotYEQLJnIdKG/BlRJbYPh3k2ng6gNkHFfb0IXTlfQmZ4jcunEg8ZWBp2DMCDNC14EbYktHB9VkX1QahhPZsi@ZZbXWPXJ98PXozcnRydt/vTl520y/BtSz/akIm7z/QtEp6YqQ0VpoK0jjXUNAykTPwptbZcndDQw4K8zMJBmjwJ@eAwPOfRsGzfzuhDuFufJxGizHvYvEzCYb@T41ksqfzrNP@eUy/Ssv36bLZR@qO7fFUeW/6aa8IBp87qxWcQm7VypI71r1C1AN@WuJFB7LhhTJJKP/LbjVLce3WrALy8LI9uPIeAigcYPALM@xTmsxu6wLqrTm0pTBIL0e5mQDpp1tkV@wESC4sxFzK3rjq1uslzOTbIkGFBVFpDou0Whz32rOH6whxb1gE7K5hhR9eRPycA2Z3gY2IH9al@lvtvPrGjKdujcgT0tkSZVii5gIyi3ynu72PeNte8627xElf@Oe/XKPSou8rv2f5izf1qll3vLFbbRjrWekKW3LVvVNASMSrFZbxJV2uQSV0vW@nsjUyO/nFin1WzXhN6XwheieZi1pTbySbhvJ/DETAU2fdOnGYLF133@RNqVBq@zWrdolTRflX3otKhgt/ksphCyXilKP2lWuwE5VFJteUGUTe11zCS5avRjrz6gGU2VhAnQ4rDGtMkmzRS@uGsZTQ6549as74CA6RRWBieW@/wY64fPzc/tV69WzSbwPJpl/Nskj/IZXzcZJ4@2R1jx@RPPrlnnTPSGe1vZMEjy1b7rHJNDagUlY9sK0NjMJffr5pntEqNamJrGyF0trW/tn/9SaFNGmhax9@IENc42i4PSpPRcvj5qFGLw8di/QL6E2B53X5A6eguYxuwZb8m9a@84kztPxTfftEXG0Y@cS4MhBx38B) Here's the Knight code translated to Python: [Try It Online!](https://tio.run/##bZFRb8IgFIXf@RUnfYKCiZ2b6Yzsj5hmoRUdicEKNLO/voNaU9PsgQS@A/eec2n78HO1m7J1w3DUJ/iu9sGELmjqBZRALdCwHYHVv98eEllGcLo6GBgLp@xZ04u21LN0CeYUBXsNsxhLKF6P4lSDS/iDqSLQl3RfSrVQg6MNI3A6dM4@OCH32NzYQI1tu0AZI/0SJHsv/rPPDDm27wJl3vO7QCGwZiSZt7O/bbKWmJtZOdpNsFnCkaqZrt7E5iGMSv2vksai8jiGvIaU@JgoUiTF3XRKeWreTKf4ZFXs7/sSyh7Ttp@2KbI/jJEq9kVvO/kkDXcVe7YEFuPwr3O48YIRsvjHMWHrnuXMLi5eVmwYCrL@Aw) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~34~~ ~~32~~ ~~31~~ 29 bytes ``` 8t&Oli(9:"tt3Zv&+3=Z+g<@Q*+]q ``` Input is a cell array with the vertical and horizontal coordinates, starting at top left, 1-based. [Try it online!](https://tio.run/##y00syfn/36JEzT8nU8PSSqmkxDiqTE3b2DZKO93GIVBLO7bw//9qQx3DWgA "MATL – Try It Online") ### How it works ``` 8t&O % Push 8×8 array of zeros li( % Write 1 at the position taken as input 9:" % For each k in [1, 2, ..., 9] t % Duplicate. This is the current pattern, to be extended. A 0 in an % entry means position not yet reached. A non-zero value indicates % the required number of moves plus 1 t % Duplicate again 3Zv % Symmetric range: [1 2 3 2 1] &+ % 5x5 matrix of pair-wise additions 3= % True for entries that equal 3. This gives a 5×5 matrix containing % the 8 possible moves for a knight Z+ % 2-dimensional convolution of the two above matrices, maintaining % the size of the former (8×8) in the output g % Convert the result to logical: non-zeros become 1 < % Less than (element-wise)? This indicates *new* available positions @Q* % Multiply element-wise by k+1 + % Add, element-wise. This updates the pattern with the new values ] % End q % Subtract 1 element-wise. Implicit display ``` [Answer] # [gbz80](https://rgbds.gbdev.io/docs/v0.5.2/gbz80.7/) [machine code](https://www.pastraiser.com/cpu/gameboy/gameboy_opcodes.html) on [Better Game Boy](https://bgb.bircd.org/), 128 127 124 123 118 117 bytes ``` 11 03 04 21 80 FF 06 08 0E 08 7C 22 0D 20 FC 3E 0D 22 3E 0A 22 05 20 F0 70 26 2F CD 7A 01 52 18 08 64 64 01 00 80 FF 00 00 76 24 3E 37 BC 28 43 3E 07 BA 38 3E BB 38 3B 3E 80 2E 0A 83 2D 20 FC 82 4F F2 BC 38 2D 7C E2 D5 14 1C 1C CD 7A 01 14 1D CD 7A 01 1D 1D CD 7A 01 15 1D CD 7A 01 15 15 CD 7A 01 15 1C CD 7A 01 1C 1C CD 7A 01 14 1C CD 7A 01 D1 25 C9 ``` Eight more bytes can be saved from severe compromises to printed data, read the [assembly source](https://github.com/SNBeast/Knight_Board_GB_ASM_Golf_Thing/blob/main/source.asm#L9) to learn more. As a detail of the Game Boy platform, it must be placed at 0x150, and be jumped to from the entrypoint at 0x100. I opted to not count that because of it being standard GB dev practice (the entrypoint gives you only four bytes to work with). I know that this answer sucks in terms of length (all those calls!), but I was overcome by the urge to do it for a problem after [seeing someone else do x86 real-mode machine code elsewhere](https://codegolf.stackexchange.com/a/185978/114388), and for this problem to get it to 0x80 bytes. I have no idea why I did this, I'm an ASM noob, but here we are. BGB is specified because of the desire to print the answer. BGB has a debug print function that is only usable by its debugger (and that of no$gmb and a few others). The initial position is encoded in the second and third byte and zero-indexed: second is y, third is x. As for checking my answer, I suppose the only way is to have you download my ROM, or for you to assemble my assembly using [rgbds](https://rgbds.gbdev.io/). I have put both on [GitHub](https://github.com/SNBeast/Knight_Board_GB_ASM_Golf_Thing). My assembly is incredibly undercommented. Edit 1: Shortened corrective increments and decrements into a push and pop, saving one byte. Edit 2: Moving various things around allowed saving 3 bytes, as well as much better pruning. Edit 3: Remove decrement that was never necessary, saving 1 byte. That's embarrassing. Edit 4: Removing a useless load and moving things around in the init loop to allow use of postincrement indexing saved 5 bytes, and the ability to remove 9 8 bytes with severe compromises was identified. Edit 5: thejonymyster reminded me that I may assume valid input, moving one byte from compromises to saved. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 55 bytes ``` GraphDistance[8~KnightTourGraph~8,#+8#2+1]~Partition~8& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@9@9KLEgwyWzuCQxLzk12qLOOy8zPaMkJL@0CCxTZ6GjrG2hbKRtGFsXkFhUklmSmZ9XZ6H2P6AoM68kOi3aQEfBIDb2PwA "Wolfram Language (Mathematica) – Try It Online") Using the built-in `KnightTourGraph` function. --- If the strict output format is required: # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 69 bytes -6 bytes and fixed a bug thanks to [@att](https://codegolf.stackexchange.com/users/81203/att) and [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan) ``` StringRiffle[GraphDistance[8~KnightTourGraph~8,#+8#2+1]~Partition~8]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@z@4pCgzLz0oMy0tJzXavSixIMMls7gkMS85NdqizjsvMz2jJCS/tAgsU2eho6xtoWykbRhbF5BYVJJZkpmfV2cRq/Y/AGhISXRatIGOgkFs7H8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/) with [numpy](https://numpy.org/), ~~138~~ ~~136~~ 133 bytes ``` lambda*a:(S:=sum(D:=-abs(mgrid[:8,:8].T-a).T,0))-(amin([*D//2,S//3,2//S],0)+S&-2)+equal(*D)*(S&-~amin(S)//6==-4)*2 from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY49DoIwGIZ3T8Ek31dbq5UY0qQbN6ibOJQoSmJL5WdwcfMULiRG7-RtBHF6kvcv7-Ptr82pdN0zV-mrbXIWf-5nY7O9IUaClqpuLSRSMZPVYI9Vsd_KmMp4N98wg_MNXSAyMLZwsCUJ54JqzldUcK53vTfTUyZwdri05gwkQQK9cPvFNXK-VopFSMQkr0obuNb6a1BYX1YN-Z9hvipcAzks-jU6YDlAjIhohLQ-eBWmLnUhjqWuG_kF) Example, with arguments 1,2 (a=`[1,2]`): ``` mgrid[:8,:8] [[[0 0 0 0 0 0 0 0] [[0 1 2 3 4 5 6 7] [1 1 1 1 1 1 1 1] [0 1 2 3 4 5 6 7] [2 2 2 2 2 2 2 2] [0 1 2 3 4 5 6 7] [3 3 3 3 3 3 3 3] [0 1 2 3 4 5 6 7] [4 4 4 4 4 4 4 4] [0 1 2 3 4 5 6 7] [5 5 5 5 5 5 5 5] [0 1 2 3 4 5 6 7] [6 6 6 6 6 6 6 6] [0 1 2 3 4 5 6 7] [7 7 7 7 7 7 7 7]] [0 1 2 3 4 5 6 7]]] ``` This produces two matrices that hold the co-ordinates. ``` D:=-abs(mgrid[:8,:8].T-a).T [[[-1 -1 -1 -1 -1 -1 -1 -1] [[-2 -1 0 -1 -2 -3 -4 -5] [ 0 0 0 0 0 0 0 0] [-2 -1 0 -1 -2 -3 -4 -5] [-1 -1 -1 -1 -1 -1 -1 -1] [-2 -1 0 -1 -2 -3 -4 -5] [-2 -2 -2 -2 -2 -2 -2 -2] [-2 -1 0 -1 -2 -3 -4 -5] [-3 -3 -3 -3 -3 -3 -3 -3] [-2 -1 0 -1 -2 -3 -4 -5] [-4 -4 -4 -4 -4 -4 -4 -4] [-2 -1 0 -1 -2 -3 -4 -5] [-5 -5 -5 -5 -5 -5 -5 -5] [-2 -1 0 -1 -2 -3 -4 -5] [-6 -6 -6 -6 -6 -6 -6 -6]] [-2 -1 0 -1 -2 -3 -4 -5]]] ``` Transpose, subtract `a`, and transpose again: this subtracts the arguments from the two matrices, respectively. Also take the absolute value and negate. This produces the negative vertical and horizontal distances from the given square. ``` S:=sum(D,0) [[ -3 -2 -1 -2 -3 -4 -5 -6] [ -2 -1 0 -1 -2 -3 -4 -5] [ -3 -2 -1 -2 -3 -4 -5 -6] [ -4 -3 -2 -3 -4 -5 -6 -7] [ -5 -4 -3 -4 -5 -6 -7 -8] [ -6 -5 -4 -5 -6 -7 -8 -9] [ -7 -6 -5 -6 -7 -8 -9 -10] [ -8 -7 -6 -7 -8 -9 -10 -11]] ``` Add the two matrices for the negative taxicab distance from the given square. The reason for the negation is that we really want rounding-up division, but only have easy access to rounding-down division with `//`. \$\lfloor\frac{-n}{d}\rfloor = -\lceil\frac{n}{d}\rceil\$ ``` O:=amin([*D//2,S//3,2//S],0) [[-1 -1 -2 -1 -1 -2 -2 -3] [-1 -2 0 -2 -1 -2 -2 -3] [-1 -1 -2 -1 -1 -2 -2 -3] [-2 -1 -1 -1 -2 -2 -2 -3] [-2 -2 -2 -2 -2 -2 -3 -3] [-2 -2 -2 -2 -2 -3 -3 -3] [-3 -3 -3 -3 -3 -3 -3 -4] [-3 -3 -3 -3 -3 -3 -4 -4]] ``` The `*D//2,S//3` part produces concentric octagons corresponding to the furthest points the knight can reach in a number of moves. `2//S` is 0 with a RuntimeWarning for S=0, −2 for S=1, −1 for S≥2; it makes a difference only in the case S=1, changing the values of the squares adjacent to the given square from −1 to −2. ``` S-(O+S&-2) [[1 2 3 2 1 2 3 4] [2 3 0 3 2 3 2 3] [1 2 3 2 1 2 3 4] [2 1 2 1 2 3 2 3] [3 2 3 2 3 2 3 4] [2 3 2 3 2 3 4 3] [3 4 3 4 3 4 3 4] [4 3 4 3 4 3 4 5]] ``` A correction for parity: the number of moves should have the same parity as the the taxicab distance `S`. Add `S`, round down to the nearest multiple of 2 (by zeroing the low bit), and subtract `S`; also negate and simplify. Finally, some more adjustments: `+equal(*D)*(S&-~amin(S)//6==-4)*2` * The squares two steps away along a diagonal should have value 4 instead of 2. * If the given square is a corner square, the diagonally adjacent square should also have value 4 instead of 2. * `equal(*D)` checks for squares sharing a diagonal with the given square. * `amin(S)`, the negated highest taxicab distance, is −14 if the given square is a corner square, and otherwise ranges from −8 (for a centre square) to −13. * `-~amin(S)` is one higher: −13 for corner squares, −7 to −12 otherwise. * Floor-dividing by 6 produces −3 for corner squares and −2 otherwise. * On the diagonals, S is even. ANDing with −2 = ...11102 leaves it unchanged, whereas ANDing with −3 = ...11012 zeroes the twos bit, mapping both −2 and −4 to −4. The result: ``` [[1 2 3 2 1 2 3 4] [2 3 0 3 2 3 2 3] [1 2 3 2 1 2 3 4] [4 1 2 1 4 3 2 3] [3 2 3 2 3 2 3 4] [2 3 2 3 2 3 4 3] [3 4 3 4 3 4 3 4] [4 3 4 3 4 3 4 5]] ``` [Answer] # [Python](https://www.python.org) Numpy, 126 bytes ``` lambda*z:H[z] from numpy import* x=mat(tri(8)).I x-=x*x x+=x.T H=8-inner(*([kron(x,x)-eye(64)<0,1]**c_[:8]).T).A H.shape=4*[8] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=Lc4xCsIwGEDhPadwa_6YhCpFgpjBre7d2iJVUyyaNMQUUgcv4lIQvZO3kVKnb3rwnh_b-3Nrhlcti3fnaya-j2ulD6eK3Ndpfi9R7Vo9M522_azRtnWeoCB15bF3DRYAfIcCk4EEFOYy8AylUrDGGOUwwfnFtQYHGoCpXuFVApuYLkpCjvt8LUrgGfAtSvntXFklE5KL8n_BrGuMxzWOaQx0ZDGynEhoAvSmrIwKU5gIpmgYJn8) ## How The entire solution is precomputed, the function itself does no more than a simple lookup. The finalised lookup table is 8x8x8x8, but while building it is reduced to 64x64. We start by setting up the single step matrix and then take powers to cover sequences of moves. #### 1 1D considerations The 1D case is easy but useful to build on. We can go 1 or 2 units up or down. If we represent that in a 2D source-target matrix *x* this means that the two diagonals just above the main diagonal must be set and the two below. #### 2 Go 2D The two dimensions must be combined in an AND like way because the restriction 1 or 2 up or down holds along both axes. The Kronecker product does that, but there is the additional constraint that if it is 1 or 2 along one axis it must be the other along the other axis. This can be enforced by giving the 1. and 2. off diagonals different signs. After Kroneckering the valid bits will all be negative. #### 3. Construct 1D There are many ways to construct *x*. The shortest I found was: Get the upper or lower triangle. Take the inverse. This is almost what we want only shifted one unit to the centre. This can be fixed by taking the difference with the square. Finally, we must add (or OR) the transpose. #### 4. Putting the bits together After taking the Kronecker product we need to add the identity matrix so taking nth power gives the indicator of what's reachable in up to n steps. Conveniently, as the matrix at this point is boolean valued multiple paths to the same target are only counted as one. To get the right distance indices we must count in how many powers a target does not occur. Therefore, the type of the matrices must be changed to int *after* taking powers but *before* adding them together. We do this by taking the inner product with a vector of ones which forces coercion to int and then sums. ### Previous [Python](https://www.python.org) Numpy, 131 bytes ``` lambda y,x:65-((D:=Z==y*8+x)+sum(D:=D|M@D for _ in Z)).reshape(8,8) import numpy Z=numpy.c_[:64];X=Z//8+Z%8*1j M=abs((X-X.T)**2)==5 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=Lc7LCoJAGIbhvVcxm2h-HQ-FxWD80MJtuxYyGaKlZOQ4eICEdl1GGyHqnrqbMFs98MIH3-OtuuZUyv6ZYfhqm8zkn_slLpJjTDp29ZYLk1LfQ4HY6dy4glG3xRD822btk6ysSERySQSAVaX1KVYp5YyDlheqrBoi20J1msCf1iHaeUt3vwpQ2DY3xITrs7O2wTipKQ3MwNqCrs8BcfG_Yqoqlw3NqMMcYAOzgfmIy1xgdapwGspQTmEc9f3oFw) Conceptually straight-forward approach. Form the full 64-by-64 indicator matrix of knight's moves (by checking for Euclidean distance \$=\sqrt 5\$). Repeatedly multiply by it the indicator vector of the starting position. [Answer] # [Python](https://www.python.org) (*without* numpy), ~~142~~ 135 bytes ``` lambda x,y,k=[9]*64,r=range(64):[k:=[(x*8+y!=i)*k[i]and-~min(k[j]for j in r if(i%8-j%8)**2^(i//8-j//8)**2==5)for i in r]for _ in r][-1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY5BCoMwFAX3nuJvhCSNKMVKKuQkIS2Cpv0GowQLuukReoFu3NQ79TZV224eDG8W85y7sb-2bppet95E4v0oKwOGDHzkVqqjZlnKvfSFu1QkSynNA7BqYGI3apkEYFoPZ0AHPl90q1AXrozuDTpiVa3Xu95uQEMwFFEdCsrY_kQwjhdaZkUpD3R1cXN1AJ1H1xNLv1WzIQlPfvBP_QA) Takes in x and y coordinate as separate inputs, outputs a flattened square list. The code for finding if two positions are a knight's move from each other is taken from [Arnauld's answer to "Where can the knight be in N moves?"](https://codegolf.stackexchange.com/a/145676/113573). --- -7 bytes from @CursorCoercer by moving the code onto a single line & into a lambda [Answer] # JavaScript (ES7), ~~129 123~~ 122 bytes *Saved 1 byte thanks to a suggestion from [@Coder](https://codegolf.stackexchange.com/users/114260/coder) on [my answer](https://codegolf.stackexchange.com/a/145676/58563) to a previous challenge* ``` f=(x,y,n=0,m=[...s=1/0+''].map(_=>[...s]))=>m.map((r,Y)=>r.map((V,X)=>V<=n|((x-X)*(y-Y))**2^4||f(X,Y,n+1,m)),m[y][x]=n)&&m ``` [Try it online!](https://tio.run/##JcjRCoIwFADQX@lJ79Xr0uix62fIRFaIaRhuE41wsH9fYo/nvNtvu3bLOH8yY599CAPDRo4M56S5EUKsXJzzNI6V0O0MDy6PVIhc6qNgoXrH8kdFckd1Y@MBtkxiAi6rEZPkcr96P4CkmkxakEYk3TjVbIoNRpEOnTWrnXox2RcMUNApRww/ "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: x, y, // the current position (x, y) n = 0, // a move counter n m = [... // the output matrix m[], initialized to an array s = 1 / 0 + '' // of 8 arrays made of the string "Infinity" ].map(_ => [...s]) // i.e. ["I", "n", "f", "i", "n", "i", "t", "y"] ) => // m.map((r, Y) => // for each row r[] at position Y in m[]: r.map((V, X) => // for each entry at position X in m[]: V <= n | // do nothing if V is less than or equal to n ( // or if the squared product of (x - X) * // x - X and (y - Y) // y - Y ) ** 2 ^ 4 || // is not equal to 4 f( // otherwise, do a recursive call: X, Y, // pass the new position (X, Y) n + 1, // increment the move counter m // pass m[] unchanged ) // end of recursive call ), // end of inner map() m[y][x] = n // set the current square to n ) && m // end of outer map(); return m[] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~24 23~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` W8p¤ạṢ€ċؽʋƇ$ƬŒṬĖP€o/’ ``` A monadic Link that accepts a pair of integers and yields a list of lists of integers. **[Try it online!](https://tio.run/##ATsAxP9qZWxsef//VzhwwqThuqHhuaLigqzEi8OYwr3Ki8aHJMasxZLhuazEllDigqxvL@KAmf/Dh0f//zEsMQ "Jelly – Try It Online")** (The footer pretty prints the grid) ### How? Repeatedly finds coordinates reachable from the current list of coordinates starting with just the given coordinate. Then creates grids from each of these lists with their grid number at the identified coordinates and reduces these with logical OR to keep the first non-zero value at each coordinate. This has the initial position as \$1\$ rather than \$0\$, so all numbers are then reduced by one. ``` W8p¤ạṢ€ċؽʋƇ$ƬŒṬĖP€o/’ - Link: integers [x, y] W - wrap -> [[x, y]] Ƭ - collect up while distinct applying: $ - last two links as a monad: ¤ - nilad followed by link(s) as a nilad: 8 - eight p - ([1..8]) Cartesian power ([1..8]) -> all coordinates Ƈ - keep those for which: ʋ - last four links as a dyad: ạ - absolute difference (vectorises) Ṣ€ - sort each ؽ - [1,2] ċ - count occurrences ŒṬ - convert to grids of zeros with ones at the coordinates Ė - enumerate -> [[1, 1st grid], [2, 2nd grid], ...] P€ - product of each -> grids with 1s replaced by grid number / - reduce by: o - logical OR (vectorises) ’ - decrement ``` --- Alternative 22, same method just identifying the existence of `[1,2]` and `[2,1]` by filtering for those which, when sorted, are invariant under the operation of getting the range of their length (`[1,2]`): ``` W8p¤ạṢJƑ$Ƈ¥Ƈ$ƬŒṬĖP€o/’ ``` [Answer] # [C (clang)](http://clang.llvm.org/), 153 bytes 12 bytes thanks to ceilingcat! ``` e;r(*b,x,y,l,i){for(;i--&&x>0&y>0&x<9&y<9&l<9;b[e=x+y*8]>l?b[e]=l:0)e="XVTPJFDB"[i]-65,r(b,x+e%5-2,y+e/5-2,l+1,8);}f(*b,x,y){r(memset(b,1,324),x,y,0,8);} ``` [Try it online!](https://tio.run/##VY5Ba4QwFITv@ytCYCUxkeq2W9zGbKGUHnraQykF8aA2LkJ0S7SQIP712qe1hT7yGCZ8mUkZlDpvz9OkhCF@wS13XPOaDtXFEFEHgefZY@g5WJscPAerk4MoUiUtc36cHfU9mEzqu5Aqid9eX07PT48POK2z4HbPDYFMprb7YMcdU1ezahbxmIqxWgvpYEijmk71AEf8endDl3@ECzU1ed0SioYNgqnbHhVpHGVisRW8QBEcuvqLQWRmHJIoEiCJRDEoY78J/zD7g9kVszP2R83zYQCrCN6@I8yh2SIGoT6Ks7VxgT77jmC83oybcfoqK52fu@kb "C (clang) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~59~~ 58 bytes ``` ⊞υ⟦⁰NN⟧Fυ«≔⊟ιη≔⊟ιθJηθIΣιF⁸F⁸«Jλκ¿›⁼⁵⁺X⁻λη²X⁻κθ²℅KK⊞υ⟦⊕Σικλ ``` [Try it online!](https://tio.run/##XZDBagMhEIbPu08xxxEsJIFCoadQSkkhqdDeQg92Y7qyrrtRpz2UPLsZQ7aEHBydz9@Zf2xaHZpBu5wVxRZJwnYmYeVHShvqv0xAcZN@isd6PwRAEvBXV8sY7bdHNYxoWdry7S07FPZK/fgxYHtJVbA@4ZOOCd@pZ5ko9Fz3QcC0c/3poZPQFUll94AvwejEZp4PpF3EewnKUeSGvwzX1vPZFS8SFryucVf6Fyw4voWd9dqhMqZDJgL@P2Hlm2B645PZTQbZgARXxq@O9THnOczy3Y87AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υ⟦⁰NN⟧ ``` Start a breadth-first search by placing a `0` at the input coordinates. ``` Fυ« ``` Loop over the squares as they are discovered. ``` ≔⊟ιη≔⊟ιθJηθIΣι ``` Set this square to the current number of steps. ``` F⁸F⁸«Jλκ ``` Loop over the whole board. ``` ¿›⁼⁵⁺X⁻λη²X⁻κθ²℅KK ``` If this is an empty square that is a Euclidean distance of √5 from the current square, then... ``` ⊞υ⟦⊕Σικλ ``` ... save this square as being one more step away. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 121 bytes ``` .+ *#8*$(8*_ ¶ ^(#)*((?<-1>.)*)_ $2$#1 s)+`(?<=(\d)(....|.{11}|.{13})?.{7})_|_(?=.{7}(....|.{11}|.{13})?(\d)) $.(_$1*_$4* ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0@bS0vZQktFw0IrXuHQNq44DWVNLQ0NextdQzs9TS3NeC4VIxVlQ65iTe0EoKitRkyKpoYeENToVRsa1oJI41pNe71q81rN@Jp4DXtbEBOLCpBGTS4VPY14FUOteBUTrf//DQwB "Retina – Try It Online") Takes input as a pair of 0-indexed digits. Explanation: ``` s)` ``` Run the whole script in single-line mode where `.` also matches newlines. ``` .+ *#8*$(8*_ ¶ ``` Treat the input as base 10 and insert that many `#`s followed by an empty chessboard of 8 rows of 8 `_`s terminated by spaces and newlines to bring each row up to 10 characters. ``` ^(#)*((?<-1>.)*)_ $2$#1 ``` Replace the `n`th character of the chessboard with a `0`, removing `n`. (`$#1` is just a weird way of saying `0`; I can't use `0` literally because it will tokenise with the previous `2`.) ``` +` ``` Repeat until no more changes can be made. ``` (?<=(\d)(....|.{11}|.{13})?.{7})_|_(?=.{7}(....|.{11}|.{13})?(\d)) ``` Search for all empty squares that are a knight's move away from a square that already contains a digit (which will always be the largest digit so far). ``` $.(_$1*_$4* ``` Replace them with the next digit. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~48~~ 46 bytes ``` 8 8#{x&1+&/'x@&'4=*/4#i-\:'i:!8 8}/9*~(!64)=8/ ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs7JQsFCurlAz1FbTV69wUFM3sdXSN1HO1I2xUs+0UgTK1upbatVpKJqZaNpa6HNxpSkYKBgCAGgsDDo=) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~191~~ ~~179~~ 176 bytes *-15 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* ``` f(a,x,y)int*a;{a[x=x*8+y]=!memset(a,1,256);r(a,x);}r(a,x,b,y)int*a;{for(b=0;++b<9;x/8==y>>3&a[x]+1<a[y-=8*~(~b&1)*~-(b&2)]&x>>6==y>>6&&r(a,y,a[y]=a[x]+1))y=x-~(b&1)*~-(b/2&2);} ``` [Try it online!](https://tio.run/##VZDLaoQwFIbX41NYoSHRyKhtxRLji9gsEjuWCFqxs0gY9NXtORZm6Crk@28kXfrVdfveU80d98xO11iLm26ddHGVeCWfxsv4c7mCnvPirWRiQSsT63Fy8wj13ws1MhNJYup34c6VlL5pXgiUqSSvdetTWcUb3QzJWbyl1JCCKeKapjycJSHY6Tk4lfxLMealSzd6j5wLCIl1n@mxym7BCXfhElrYtnUF@xbxnQ/Ah4MPBz/NC@CeRs@fYcRD3Vp46aCYAG0NHvLHFCED9J@sQTBqO1Esw37dlq8KjPiHGc8wM1ONxv0X "C (gcc) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 155 bytes ``` sub{$_=$"x64;($x,$y,$i,@_)=@_,"$x$y"=~/^[0-7]{2}$/&&s/(?<=^.{@{[$x+$y*8]}}) /0+$i/e&&push@_,map{/./;$x+$&-3,$y+$'-3,$i+1}21,41,12,52,25,45,14,54while@_;$_} ``` [Try it online!](https://tio.run/##LY5Ra8IwEMff9ymChKhNNKamrhKv9mXb4wYT@uC0tEVnQEttJ0sp7VfvIu7guPsd///dFYfy7PWXGuEj9NUtbXAMeGAWUo2wYbhmWLMwHkMYswE2uB5Ax/fb2eR517gt5oRUfLRewX7ahM0WG4prx9@17RjxGcWaHwgpbtXJui9J0fApV3cNmcztaoqH96qpaF3BpGDCZZ7LXI9JjwnJPPl70udDGCsct716Kkqd/yCCjyPBZmMEHar4tPFbjslXzr/LvleQvyowHwpqm9WnM1wOF5I6fo3MZqaiYAk5FbmCshNR4ENJRakge0BGRaYg6eZRICGhIlGQPiClIiVrjzoJSpwUpcSGNRiaoHLVCXOHmqYos1AHL@itosbe3MDVdqXjZxv7y/@MiqsC3flRsJCgqa/frRxp5P8B "Perl 5 – Try It Online") Somewhat ungolfed: ``` $f= sub { $_ = $"x64; #init board string to 64 spaces ($x, $y, $i, @_) = @_ #move x, y and i from head of @_ param array , "$x$y"=~/^[0-7]{2}$/ #if x,y within board && #and s/(?<=^.{@{[$x+$y*8]}}) /0+$i/e #space found+replaced by i+1 in current x,y && #and push @_, #push possible jump to cells to todo-queue map {/./; $x+$&-3, $y+$'-3, $i+1 } 21, 41, 12, 52, 25, 45, 14, 54 #knight pos cells digits x-3,y-3 while @_; #...all that while there's more to do $_ #return filled up 64 char board string } ;print &$f( 1 , 0 ) =~ s/.{8}/$&\n/gr,"\n"; ``` Output: ``` 30323234 23212343 12143234 23232343 32323434 43434345 34343454 45454545 ``` ]
[Question] [ Given an input `n`, your program or function must output the smallest positive integer `k` such that `n` rounded to the nearest multiple of `k` is greater than `n`. ### Example. Given an input `20`, the output value should be `3`: * The nearest multiple of `1` is `20`, which is **not** greater than `20`. * The nearest multiple of `2` is `20`, which is **not** greater than `20`. * The nearest multiple of `3` is `21`, which **is** greater than `20`, so it is output. ### Test Cases ``` #Input #Output 2 3 4 5 6 4 8 3 10 4 12 7 14 3 16 6 18 4 20 3 22 4 24 5 26 3 28 5 30 4 32 3 34 4 36 8 38 3 40 6 42 4 44 3 46 4 48 5 50 3 52 6 54 4 56 3 58 4 60 7 62 3 64 5 66 4 68 3 70 4 72 11 74 3 76 6 78 4 80 3 82 4 84 5 86 3 88 5 90 4 92 3 94 4 96 7 98 3 1000 6 ``` The output given any odd input should be 2. ### Rules * `n` is a positive integer less than `2^32` * rounding is performed such that if two multiples of `k` are equally distant from `n`, the greater one is chosen (["round halves up"](https://en.wikipedia.org/wiki/Rounding#Round_half_up)). In this way, every odd `n` yields an output of `2`. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code **in each language** wins. [Answer] # [Python 3](https://docs.python.org/3/), 48 38 bytes **Edit:** -10 bytes by using recursion ``` l=lambda x,y=2:y*(x%y>=y/2)or l(x,y+1) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P8c2JzE3KSVRoUKn0tbIqlJLo0K10s62Ut9IM79IIUcDKKxtqPk/DcjJVMjMUyhKzEtP1TDUMTQwMNS04uIsKMrMK9HI1AEqzdTU/A8A) [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes ``` @<rX}a ``` [Try it online!](https://tio.run/##y0osKPn/38GmKKI28f9/QwMA) ## Explanation: ``` @ <r X}a XYZ{U<UrX}a X // X = 0; Increments when the condition in between {...} fails { }a // Return the first integer X where: U // The input <U // is less than the input rX // rounded to the nearest multiple of X ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 13 bytes ``` tQ:yy/Yo*<fX< ``` [Try it online!](https://tio.run/##y00syfn/vyTQqrJSPzJfyyYtwub/f0MDAwMA) Or [verify all inputs from `1` to `1000`](https://tio.run/##y00syflvaGBgYKXk8L8k0KqyUj8yX8smLcLm/38A). ### Explanation Consider input `6`. ``` t % Implicit input. Duplicate % STACK: 6, 6 Q: % Add 1, range % STACK: 6, [1 2 3 4 5 6 7] yy % Duplicate top two elements % STACK: 6, [1 2 3 4 5 6 7], 6, [1 2 3 4 5 6 7] / % Divide, element-wise % STACK: 6, [1 2 3 4 5 6 7], [6 3 2 1.5 1.2 1 0.8571] Yo % Round to closest integer. Halves are rounded up % STACK: 6, [1 2 3 4 5 6 7], [6 3 2 2 1 1 1] * % Multiply, element-wise % STACK: 6, [6 6 6 8 5 6 7] < % Less than, element-wise % STACK: [0 0 0 1 0 0 1] f % Find: indices of nonzeros (1-based) % STACK: [4 7] X< % Minimum of vector. Implicit display % STACK: 4 ``` [Answer] # [Python 2](https://docs.python.org/2/), 35 bytes ``` f=lambda n,i=1:n%i*2/i or-~f(n,i+1) ``` [Try it online!](https://tio.run/##DcgxDoAgDADAWV/RxQQUI2Uk4TEYRZtoIYTFxa9Xb7zytDOzE0nhive6RWBDAT0PNLqFINf5Teq/CbWkXIGAGGrkY1do0Frt@65U4gZkICnS8gE "Python 2 – Try It Online") [Answer] # JavaScript (ES6), ~~28~~ 25 bytes ``` n=>g=x=>n%x>=x/2?x:g(-~x) ``` * 3 bytes saved thanks to Arnauld. --- ## Test it ``` o.innerText=(f= n=>g=x=>n%x>=x/2?x:g(-~x) )(i.value=64)();oninput=_=>o.innerText=f(+i.value)() ``` ``` <input id=i type=number><pre id=o> ``` Or test all numbers from 1-1000 (Give it a minute to run): ``` f=n=>g=x=>n%x>=x/2?x:g(-~x);[2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,7,2,3,2,5,2,4,2,3,2,4,2,11,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,11,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,7,2,3,2,5,2,4,2,3,2,4,2,13,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,9,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,7,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,10,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,11,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,8,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,9,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,7,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,8,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,10,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,7,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,8,2,3,2,5,2,4,2,3,2,4,2,9,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,10,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,7,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,8,2,3,2,5,2,4,2,3,2,4,2,13,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,13,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,7,2,3,2,5,2,4,2,3,2,4,2,11,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,6,2,4,2,3,2,4,2,9,2,3,2,5,2,4,2,3,2,4,2,7,2,3,2,6,2,4,2,3,2,4,2,5,2,3,2,5,2,4,2,3,2,4,2,8,2,3,2,6].forEach((x,y)=>o.innerText+=`\n-----------------------------\n${(++y+"").padStart(7)} |${(y=f(y)()+"").padStart(8)} | ${x==y}`) ``` ``` <pre id=o> Input | Output | Pass</pre> ``` [Answer] # [Proton](https://github.com/alexander-liao/proton), 33 bytes ``` n=>[x for x:2..n+2if n%x>=x/2][0] ``` [Try it online!](https://tio.run/##FcmxCoAgEADQ3a@4JVASU0dBfyQcGjJuOUUchOjbr3rra72OSlwiU0z7hFI7zOCNodVjAVpminPzebeZ/0MI0A@6Tum0s07BLeDTOtKQqKFIVEo8/AI "Proton – Try It Online") [Answer] # [Pyth](https://pyth.readthedocs.io), ~~12~~ 11 bytes ``` hfgy%QTTm+2 ``` **[Try it here.](https://pyth.herokuapp.com/?code=hfgy%25QTTm%2B2&input=20&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6&debug=0)** [Answer] # [Proton](https://github.com/alexander-liao/proton), 33 bytes ``` x=>[y for y:2..x+2if x%y>=y/2][0] ``` [Try it online!](https://tio.run/##KyjKL8nP@59j@7/C1i66UiEtv0ih0spIT69C2ygzTaFCtdLOtlLfKDbaIPY/SC5TwUqhKDEvPVXDUMfQwFBToZpLAQgKijLzSjSKS4o0MjX1crJKi0s0TDR1FHKAXE2u2v8A "Proton – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÷R%1<.¬;1TṂ ``` A monadic link taking and returning positive integers. **[Try it online!](https://tio.run/##y0rNyan8///w9iBVQxu9Q2usDUMe7mz6//@/CQA "Jelly – Try It Online")** or see a [test suite](https://tio.run/##AUMAvP9qZWxsef//w7dSJTE8LsKsOzFU4bmC/8W8w4figqwKNTBS4bikO8i3w4csQCIxMDFSbTLCpMOHwqRq4oKs4oCdfEf/ "Jelly – Try It Online"). ### How? ``` ÷R%1<.¬;1TṂ - Link: number, n e.g. 10 R - range(n) [ 1,2,3 ,4 ,5,6 ,7 ,8 ,9 ,10] ÷ - n divided by [10,5,3.33..,2.5,2,1.66..,1.42..,1.25,1.11..,1 ] %1 - modulo by 1 [ 0,0,0.33..,0.5,0,0.66..,0.42..,0.25,0.11..,0 ] <. - less than 0.5? [ 1,1,1 ,0 ,1,0 ,1 ,1 ,1 ,1 ] ¬ - not [ 0,0,0 ,1 ,0,1 ,0 ,0 ,0 ,0 ] ;1 - concatenate a 1 [ 0,0,0 ,1 ,0,1 ,0 ,0 ,0 ,0 , 1] T - truthy indices [ 4 ,6 ,11] Ṃ - minimum 4 ``` Note: The concatenation of `1` is just to handle the cases where `n` is one of `1` ,`2`, or `4` when the result needs to be `n+1` (`‘R÷@%1<.¬TṂ` would also work). [Answer] # [Haskell](https://www.haskell.org/), ~~33~~ 32 bytes ``` f n=[i|i<-[1..],2*mod n i>=i]!!0 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY6sybTRjfaUE8vVsdIKzc/RSFPIdPONjNWUdHgf25iZp6CrUJuYoGvgkZMnq5dQVFmXomKRp6OAlCvpqZCtJGOiZ6euUHsfwA "Haskell – Try It Online") *Saved one byte thanks to w0lf* [Answer] # Dyalog APL, ~~23~~ 22 bytes ``` {⊃x/⍨⍵<x×⌊.5+⍵÷x←⍳1+⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR13NFfqPelc86t1qU3F4@qOeLj1TbSDn8PYKoPSj3s2GIF4tULXCIaCizcYGAA) [Answer] # Pyth, 5 bytes ``` fgy%Q ``` [Test suite](https://pyth.herokuapp.com/?code=fgy%25Q&input=20&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A8%0A10%0A12&debug=0) No rounding builtins, just checking for the first positive integer T, where double the input mod T is greater than or equal to T. Explanation: ``` fgy%Q fgy%QTT Implicit variable introduction. f Find the first positive integer T such that the following is truthy: %QT Input % T y Doubled g T Is greater than or equal to T ``` [Answer] # x86 Machine Code, 17 bytes This code implements a basic, iterative solution in the form of a reusable function: ``` 31 F6 xor esi, esi 46 inc esi ; set ESI (our temp register) to 1 Loop: 89 C8 mov eax, ecx ; copy 'n' to EAX for division 46 inc esi ; eagerly increment temp 99 cdq ; extend EAX into EDX:EAX F7 F6 div esi ; divide EDX:EAX by ESI 01 D2 add edx, edx ; multiply remainder by 2 39 F2 cmp edx, esi ; compare remainder*2 to temp 7C F4 jb Loop ; keep looping if remainder*2 < temp 96 xchg eax, esi ; put result into EAX (1 byte shorter than MOV) C3 ret ``` The function follows the [fastcall calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_fastcall), so that the single parameter (`n`) is passed in the `ECX` register. The return value (`k`) is, per usual, returned in the `EAX` register. [Try it online!](https://tio.run/##nY9NbsIwEIXX8SlGqSrZFKqQIH4aYJMWiVUP0FSRsZ1gKTgodlCkiqs3nZCy6q4L672x3/ibEZNCiK4TlbEOxJHX0C7nSSXVxydswE/baJq2u3nazvAsV2mbLAe/Qr9bDG8BZl5DzPZ3qIsEdYYZfEsiPybWcacFNMbqwigJWcadq/WhcSrLKM25dYKXJWNAR8jftYbRe5jhHL8zxd2DNqJspIK1dVJXz8ct0cbBiWtDe8PrQoyHPUYjLC6MfBHv3DhL/beLMrA3ffHis5h4eVXDrUsjIoxR1huYBgG6p03IiIet3rnGRE79R5m6yTZ1qMYfgx7DMCjVrP/rSu6Y1LxLeecAtceqKSXgdnBQELK/5OmNDNE/uR7xauWa2kAQk2v3LfKSF7abnKLwBw "C (gcc) – Try It Online") [Answer] # Java 8, 42 bytes Lambda from `Integer` to `Integer`. ``` n->{for(int f=1;;)if(n%++f*2>=f)return f;} ``` [Try It Online](https://tio.run/##TU9Na8MwDD0nv0IUAvGSmq29zU2Ogx12KuwydvASOyhz7ODIgVLy2zN3zWAg0BPS@1AvZ7l3o7J9@72O4ctgA42R0wRvEi1c02T0OEtSMJGkuOwjgQdCw3WwDaGz/GUDp1dLqlO@hA3U4F2w7bs0QUG12n191c7naAl09SQEQ53brCj0w6GuNPOKgregxbImIo3O9zib8eywhSGGys/k0XYfnyB9N7FbxiTKwq8uQgUHEdsJjo@3XsT5fpOcLxOpgbtAPD5lyfxJ8UgfJOW7rIVnyNpdCVj@y87lOJpLjowxEYWWNNay/gA) ## Acknowledgments * -1 byte thanks to *Kevin Cruijssen* [Answer] # [Perl 5](https://www.perl.org/), 24 + 1 (-p) = 25 bytes ``` 1while$_%++$k<$k/2;$_=$k ``` [Try it online!](https://tio.run/##K0gtyjH9/9@wPCMzJ1UlXlVbWyXbRiVb38haJd5WJfv/fzNTY2MzC/N/@QUlmfl5xf91CwA "Perl 5 – Try It Online") Tries each integer `$k` starting at 1 until it finds a remainder that is at least half of `$k`. [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 45 bytes ``` : f 1 begin 1+ 2dup mod over 1+ 2/ >= until ; ``` [Try it online!](https://tio.run/##XcuxCoMwGEXhvU9xcBXTROhiqS8iWWqMDai/BPX1U83odOHjXC9x@1WjvyalBo/hO4xhwZTUbl@ZxSHHEDM8aT/syxYm3sloTU3nxNIFywsVUQVULUUWj6KPV1NOIqt9nA996zKdYfoD "Forth (gforth) – Try It Online") ### Code Explanation ``` : f \ start a new word definition 1 \ start a counter at 1 begin \ start an indefinite loop 1+ \ add 1 to counter 2dup mod \ duplicate input value and counter, get remainder of input/counter over 1+ 2/ \ get counter/2 (add 1 to force rounding up) >= \ check if remainder is greater than counter/2 until \ end loop if true, otherwise go back to beginning ; \ end word definition ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` ∞.ΔIs/Dò‹ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8vXNTPIv1XQ5vetSw8/9/EwA "05AB1E – Try It Online") ## Explanation ``` ∞.ΔIs/Dò‹ Full code ∞.Δ Returns the first number for which the following code returns true -> stack is [n] Is Push the input and swap the stack -> stack is [input, n] / Divide both of them -> stack is [input/n] Dò Duplicate and round the second -> stack is [input/n, rounded(input/n)] ‹ Check if input/n got larger by rounding -> stack is [bool] -> if bool is true, abort and return the current number ``` [Answer] # [Rockstar](https://github.com/RockstarLang/rockstar), 681 bytes ``` Thought takes Patience and Control While Patience is as high as Control Let Patience be without Control Give back Patience Rock takes Art Love is neverending Sex is bottomless Put Thought taking Art & Love into your head If your head is Sex Give back Art Else Limits are inspiration Put Art with Limits without your head into the rubbish Give back the rubbish Listen to Chance Questions are unstoppable Until Questions is Chance Build Questions up Put Thought taking Chance, Questions into your mind Answers are independence (but) Put Questions over Answers into the world Put Rock taking the world into the world If your mind is as big as the world Say Questions Break it down ``` You can [try rockstar online](https://codewithrockstar.com/online), but you'll need to copy and paste the code across. It will prompt you for an input number. I didn't go for lowest byte count , because Rockstar is obviously not made for golfing, so instead I tried to go for Rock 'n' Roll lyrics. ## Explanation: This is based on the same solution as others (python, java): ``` Iterate up from 2: if n % iterator >= ceil(n/2) return iterator ``` First I need to define modulus and ceiling functions though, which for poetry's sake are called Thought and Rock. The below is a less poetic version with different variable names, and explanations where the syntax is unclear. Parentheses denote comments. ``` Modulus takes Number and Divisor While Number is as high as Divisor Put Number minus Divisor into Number (blank line ending While block) Give back Number (return Number) (blank line ending function declaration) Ceil takes Decimal Put Modulus taking Decimal, 1 into Remainder If Remainder is 0 Give back Decimal (return Decimal) Else Put Decimal with 1 minus Remainder into Result Give back Result (return Result) (blank line ending if block) (blank line ending function declaration) Listen to Input (Read from STDIN to Input) Index is 1 Until Index is Input Build Index up (Increment by 1) Put Modulus taking Input, Index into LHS Put Index over 2 into RHS Put Ceil taking RHS into RHS If LHS is as big as RHS Say Index Break it down (Break from loop) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` ɓ÷Ḟ,¥Ċ$×ạÐṂ⁸Ṁ>⁸µ1# ``` [Try it online!](https://tio.run/##ATAAz/9qZWxsef//yZPDt@G4nizCpcSKJMOX4bqhw5DhuYLigbjhuYA@4oG4wrUxI////zE "Jelly – Try It Online") Full program. [Answer] # [Swift 3](https://www.swift.org), 51 bytes ``` {n in(2..<n+2).filter{Float(n%$0)>=Float($0)/2}[0]} ``` For some *extremely* bizarre reasons, `[0]` doesn't work online. Here is the online compiler-compatible version (that uses `.first!` instead): ``` {n in(2..<n+2).filter{Float(n%$0)>=Float($0)/2}.first!} ``` **[Test Suite (online-compatible).](http://swift.sandbox.bluemix.net/#/repl/5994a31a83068d0a59311b80)** [Answer] # [C# (Mono)](http://www.mono-project.com/), 39 bytes ``` n=>{int i=1;for(;n%++i*2<i;);return i;} ``` [Try it online!](https://tio.run/##HYw/C8IwEMX3@xS3CIlV0Tpe00VwUhAcnEtM5aC9QJIKUvrZY3R5P94fno3b0YvPU2R54f0TkxsJwA5djHiDGWLqElt8e37itWNRuoTnSWzDkjZYpMUeTRbTzsUgmwP1PiiSVVXxum6YNAWXpiDItORyXmpU/y0arKmgweP@x6p4DScv0Q9u9wic3IXFqV6x1gQLLPkL "C# (Mono) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ç&╬▼⌐╔ñ ``` [Run and debug it](https://staxlang.xyz/#p=8726ce1fa9c9a4&i=2%0A4%0A6%0A8%0A10%0A12%0A14%0A16%0A18%0A20%0A22%0A24%0A26%0A28%0A30%0A32%0A34%0A36%0A38%0A40%0A42%0A44%0A46%0A48%0A50%0A52%0A54%0A56%0A58%0A60%0A62%0A64%0A66%0A68%0A70%0A72%0A74%0A76%0A78%0A80%0A82%0A84%0A86%0A88%0A90%0A92%0A94%0A96%0A98%0A1000&a=1&m=2) ]
[Question] [ Your challenge is to minify [Brainfuck](http://esolangs.org/wiki/Brainfuck) code, according to these rules: * Remove anything that is not one of `+-><[].,`. * For any group of consecutive `+` or `-` characters, if the amount of `+`s and `-`s is the same, remove them. * Do the same as above, but with `>` and `<`. * Remove sequences of the `+-><` characters if they do nothing. For example, you should remove `+>-<->+<`. (This may be the trickiest and hardest one to implement.) Make sure you don't get any false positives, like `+>-<+>-<`, which should not be removed. --- Test cases: Input ``` ++++++[->++++++<]>. prints a $ [-]< resets tape >,[>,]<[.<] reverses NUL terminated input string ++-->><< does nothing ``` Output ``` ++++++[->++++++<]>.[-],[>,]<[.<] ``` Input ``` Should disappear: ++>>+<+++<->-->-<<->-< Should disappear: +++>-<--->+< Should stay: +++>-<+>---< ``` Output ``` +++>-<+>---< ``` --- You may accept input and output however you would like - stdin/stdout, a function, etc., but input may not be hardcoded. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in character count will win. [Answer] ## Brainfuck, 579 bytes ``` ,[<<+>>>>+<<[[<+>>+<-]++++++[>-------<-]>-[-[-[-[--------------[--[<+++++[>----- -<-]>+[--[<<[-]>>-]]<]>[>>-<<<<<[-]<[<]<<<[<]>>>>>>>>[<]<-[+>]+[->+]>>>>+>[<-]<[ >+<-<]>]<]>[<<<[-]-[<]>>>>>>>>>>>[<]<<<<<<[<]<-[+>]+[-<+]<<<+<[>-<<<]>[-<+<]]]<] >[+>[-<]<[<<]<[-]>>]]<]+>[-[<-]<[>+>+<<-<]<[-]>+>]<<[>-]>[,>]<]<+<[>]>[>>>[<<<<[ -<]<<<]>>>+>>>>[<<<<->>>>[>>>[-<]>>>>]]]>[<<<[<+[-->>]]>[-[.[-]]]>[<]>[<<++++++[ >+++++++<-]>+>>[<<.>>-]<<++>-[<.>-]+++[<+++++>-]+<<<<<<+>[<<[>->>>>>.[[-]<<<<]<< <+>>>]>[->->>>>[-]]]<[->+[>>>>>]>>[<]<<<<<<<<[[-]<]>[++.[-]>>>>>>>]<]]>>]<[>>>>> >>]+[-<<<<<[-]<<],] ``` With formatting and some comments: ``` , [ <<+>> >>+<< [ [<+> >+<-] ++++++[>-------<-] >- [ not plus - [ not comma - [ not minus - [ not period -------------- [ not less than -- [ not greater than <+++++[>------<-]>+ [ not open bracket -- [ not close bracket <<[-]>>- ] ] < ] > [ greater than >>-<< <<<[-]<[<]<<<[<] >>>>>>>>[<] <-[+>] +[->+] >>>>+>[<-] <[>+<-<] > ] < ] > [ less than <<<[-]-[<] >>>> >>>>>>>[<] <<<<<<[<] <-[+>] +[-<+] <<<+<[>-<<<] >[-<+<] ] ] < ] > [ minus +>[-<] <[<<] <[-]>> ] ] < ] +> [ plus -[<-] <[>+>+<<-<] <[-]>+> ] << [ comma or period or bracket >- ] >[,>] < ] comma or period or bracket or eof <+< [ start and end same cell > ] > [ >>> [ <<<<[-<]<<< ] >>>+>>>> [ start right of end <<<<->>>> [>>>[-<]>>>>] ] ] > [ <<< [ <+[-->>] ] >[-[.[-]]] >[<] > [ <<++++++[>+++++++<-]>+>> [<<.>>-] <<++>-[<.>-] +++[<+++++>-] +<<<<< <+> [ << [ go left >->>>>>. [[-]<<<<] <<<+>>> ] > [ toggle left right ->->>>>[-] ] ] < [ toggle right left ->+[>>>>>]>>[<] <<<<<<<< [ [-]< ] > [ go right ++.[-] >>>>>>> ] < ] ] >> ] <[>>>>>>>] +[-<<<<<[-]<<] , ] ``` This uses the same approach as Keith Randall's solution, minifying all contiguous sequences of `+-<>` optimally by simulation. For example, `+++>-<+>---<` becomes `++++>----<` and `>+<+<<+>+<->>>>` becomes `+<+>>+>`. [Try it online.](http://brainfuck.tryitonline.net/#code=LFs8PCs-Pj4-Kzw8W1s8Kz4-KzwtXSsrKysrK1s-LS0tLS0tLTwtXT4tWy1bLVstWy0tLS0tLS0tLS0tLS0tWy0tWzwrKysrK1s-LS0tLS0tPC1dPitbLS1bPDxbLV0-Pi1dXTxdPls-Pi08PDw8PFstXTxbPF08PDxbPF0-Pj4-Pj4-Pls8XTwtWys-XStbLT4rXT4-Pj4rPls8LV08Wz4rPC08XT5dPF0-Wzw8PFstXS1bPF0-Pj4-Pj4-Pj4-Pls8XTw8PDw8PFs8XTwtWys-XStbLTwrXTw8PCs8Wz4tPDw8XT5bLTwrPF1dXTxdPlsrPlstPF08Wzw8XTxbLV0-Pl1dPF0rPlstWzwtXTxbPis-Kzw8LTxdPFstXT4rPl08PFs-LV0-Wyw-XTxdPCs8Wz5dPls-Pj5bPDw8PFstPF08PDxdPj4-Kz4-Pj5bPDw8PC0-Pj4-Wz4-PlstPF0-Pj4-XV1dPls8PDxbPCtbLS0-Pl1dPlstWy5bLV1dXT5bPF0-Wzw8KysrKysrWz4rKysrKysrPC1dPis-Pls8PC4-Pi1dPDwrKz4tWzwuPi1dKysrWzwrKysrKz4tXSs8PDw8PDwrPls8PFs-LT4-Pj4-LltbLV08PDw8XTw8PCs-Pj5dPlstPi0-Pj4-Wy1dXV08Wy0-K1s-Pj4-Pl0-Pls8XTw8PDw8PDw8W1stXTxdPlsrKy5bLV0-Pj4-Pj4-XTxdXT4-XTxbPj4-Pj4-Pl0rWy08PDw8PFstXTw8XSxd&input=KysrKysrWy0-KysrKysrPF0-LiAgIHByaW50cyBhICQKWy1dPCAgICAgICAgICAgICAgICAgIHJlc2V0cyB0YXBlCj4sWz4sXTxbLjxdICAgICAgICAgICByZXZlcnNlcyBOVUwgdGVybWluYXRlZCBpbnB1dCBzdHJpbmcKKystLT4-PDwgICAgICAgICAgICAgIGRvZXMgbm90aGluZw) (If a simulated cell's absolute value gets close to 256, there will be overflow issues.) The overall structure is ``` while not EOF: while not EOF and next char not in ",.[]": process char print minified sequence (followed by the char in ",.[]" if applicable) ``` The tape is divided into 7-cell nodes; at the beginning of the inner loop, the memory layout is `0 s 0 c 0 a b` where `s` is a boolean flag for start cell, `c` is the current character, `a` is the negative part of the simulated cell value (plus one), and `b` is the positive part of the simulated cell value. When the minified sequence is being printed, the memory layout is `d n e 0 0 a b` where `d` is a boolean flag for direction, `a` and `b` are as before (but become one/zero when printed), and `n` and `e` are only nonzero for the end node; `n` is related to how many times the node has been seen, and `e` is the value of the char that halted the inner loop (plus one). Originally I considered keeping track of more information per node: leftmost and rightmost node as boolean flags, and node's position in relation to the start and end nodes. But we can avoid that by looking at neighboring cells when needed, and by doing left and right scans in order to find the start node. When printing the minified sequence and deciding how to move the simulated pointer, we can take a general approach: start by moving away from the end node (in an arbitrary direction if start and end nodes are the same), turn around at leftmost and rightmost nodes, and stop based on the number of times the end node has been seen: 3 times if the start and end nodes are the same, otherwise 2. [Answer] ## REBEL - 104 ``` _/^_$/$</([^][<>.,+-]|\+-|-\+|<>|><)//((?<X>(<|>))+[+-]+(?!\2)(?<-X><|>)+(?(X)(?!)))([+-]+)/$3$1/.+/$>$& ``` ## Usage: Input: Reads one line from stdin. Output: Prints one line to stdout. ## Anomalies\*: * Entering `_` causes another line to be read and used, rather than outputting nothing. * The second test outputs `++++>----<` instead of `+++>-<+>---<`. But that's OK, right? ;) * `>-<+` etc. are replaced with `+>-<` etc. ## Spoiler: > > Implementing anomaly #3 makes things quite trivial. > > > **\* It's not a bug, it's a feature!** [Answer] ## Python, 404 chars This code does a perfect optimization of all subsequences of `+-<>`. A bit more than you asked for, but there you go. ``` M=lambda n:'+'*n+'-'*-n def S(b): s=p=0;t=[0];G,L='><' for c in b: if'+'==c:t[p]+=1 if'-'==c:t[p]-=1 if G==c:p+=1;t+=[0] if L==c:s+=1;t=[0]+t if p<s:k=len(t)-1;t,p,s,G,L=t[::-1],k-p,k-s,L,G r=[i for i,n in enumerate(t)if n]+[s,p];a,b=min(r),max(r);return(s-a)*L+''.join(M(n)+G for n in t[a:b])+M(t[b])+(b-p)*L s=b='' for c in raw_input(): if c in'[].,':s+=S(b)+c;b='' else:b+=c print s+S(b) ``` It works by simulating the `+-<>` operations on the tape `t`. `s` is the starting position on the tape and `p` is the current position. After simulation, it figures out the extent `[a,b]` that needs to be operated on and does all the +/- in one optimal pass. [Answer] ## CoffeeScript - 403 *397* ``` i=prompt().replace /[^\]\[,.+-><]/g,'' x=(c)-> t={};p=n=0 for d in c t[p]?=0;switch d when'+'then n=1;t[p]++;when'-'then n=1;t[p]--;when'<'then p--;when'>'then p++ (n=0if v!=0)for k,v of t;n s=e=0;((e++;(i=(i.substr 0,s)+i.substr e;e=s=0)if x (i.substr s,e-s).split "")while(i[e]||0)!in['[',']',0];e=++s)while s<=i.length r=/(\+-|-\+|<>|><|^[<>]$)/g i=i.replace r,'' while r.test i alert i ``` [Demo](https://bit.ly/1jZTUMz) (please forgive the use of bit.ly here, the whole URL would break the markdown) Uncompressed version (w/ debug code): ``` console.clear() input = """Should disappear: ++>>+<+++<->-->-<<->-< Should disappear: +++>-<--->+< Should stay: +++>-<+>---<""" input = input.replace /[^\]\[,.+-><]/g, '' console.log input execute = (code) -> stack = {} item = 0 console.log code nop = false for char in code switch char when '+' then nop = true; stack[item]?=0;stack[item]++ when '-' then nop = true; stack[item]?=0;stack[item]-- when '<' then item-- when '>' then item++ console.debug stack (nop = false if v != 0) for k,v of stack nop start = 0 end = 0 while start <= input.length while input.charAt(end) not in [ '[', ']', '' ] end++ if execute (input.substring start, end).split("") input = (input.substring 0, start) + input.substring end end = start = 0 console.log input end = ++start input = input.replace /(\+-|-\+|<>|><|^(<|>)$)/g, '' while /(\+-|-\+|<>|><)/.test input console.log 'Result: ' + input ``` ]
[Question] [ Inspired by [this question](https://codegolf.stackexchange.com/questions/66202/product-over-a-range) by [@CᴏɴᴏʀO'Bʀɪᴇɴ](https://codegolf.stackexchange.com/users/31957/c%E1%B4%8F%C9%B4%E1%B4%8F%CA%80-ob%CA%80%C9%AA%E1%B4%87%C9%B4). Taken from the question: > > Your task is simple: given two integers a and b, output ∏[a,b]; that > is, the product of the range between a and b. You may take a and b in > any reasonable format, whether that be arguments to a function, a list > input, STDIN, et cetera. You may output in any reasonable format, such > as a return value (for functions) or STDOUT. a will always be less > than b. > > > Note that the end may be exclusive or inclusive of b. I'm not picky. > ^\_^ > > > The difference for this challenge is we are going to be picky about the range type. Input is a string of the form `[a,b]`, `(a,b]`, `[a,b)`, or `(a,b)` where a `[]` is an inclusive boundary and `()` is an exclusive boundary. Given the explicit boundaries, provide the product of the range. Also the input range will always include at least 1 number, meaning ranges like `(3,4)` are invalid and need not be tested. ## Test cases ``` [a,b) => result [2,5) => 24 [5,10) => 15120 [-4,3) => 0 [0,3) => 0 [-4,0) => 24 [a,b] => result [2,5] => 120 [5,10] => 151200 [-4,3] => 0 [0,3] => 0 [-4,-1] => 24 (a,b] => result (2,5] => 60 (5,10] => 30240 (-4,3] => 0 (0,3] => 6 (-4,-1] => -6 (a,b) => result (2,5) => 12 (5,10) => 3024 (-4,3) => 0 (0,3) => 2 (-4,0) => -6 ``` --- This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. --- ## Leaderboard The Stack Snippet at the bottom of this post generates the catalog 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 ``` ``` var QUESTION_ID=66285,OVERRIDE_USER=44713;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] # LabVIEW, 38 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490) "slightly" modified, now sets the ranges by scanning for () and [] and adding the index to the numbers. [![first](https://i.stack.imgur.com/L0Bmo.gif)](https://i.stack.imgur.com/L0Bmo.gif) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~24~~, 18 bytes ``` ₌≬k+iE₍ht‛(]f=+÷rΠ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuaAiLCIiLCLigoziiaxrK2lF4oKNaHTigJsoXWY9K8O3cs6gIiwiIiwiKDIsIDVdIl0=) I'm actually really proud of this answer, because it uses the new modifier parsing of 2.6. With syntax highlighting: [![syntax highlighted version](https://i.stack.imgur.com/PPx1y.png)](https://i.stack.imgur.com/PPx1y.png) ## Explained ``` ₌≬k+iE₍ht‛(]f=+÷rΠ ₌ # Apply the following to the same stack: ≬ # The next 3 elements as a single lambda, taking argument n: k+iE # eval(n[1:-1]) - the two numbers separated by a comma ₌ # and ₍ht # [n[0], n[-1]] - the range brackets ‛(]f= # Does the first bracket equal "(" and does the last bracket equal "]" - this determines how much to offset the range; because the two numbers in the original input will be passed to Vyxal's range function which acts like python's range() function + # add those offsets: an exclusive range start means the first number needs to be incremented because range() includes the first argument. an inclusive range start means the last number needs to be incremented because range() stops before the last argument. ÷r # push the range between the two numbers + their offsets Π # and take the product ``` [Answer] ## Minecraft 15w35a+, program size 638 total (see below) Same as my answer [here](https://codegolf.stackexchange.com/a/66329/36670), but modified. Since Minecraft has no string input, I took the liberty of keeping scoreboard input. If that is a problem, consider this answer non-competitive. [![enter image description here](https://i.stack.imgur.com/172CS.png)](https://i.stack.imgur.com/172CS.png) This calculates `PI a,b` with inclusive / exclusive specified by the two levers. [![enter image description here](https://i.stack.imgur.com/XzAy3.png)](https://i.stack.imgur.com/XzAy3.png)Input is given by using these two commands: `/scoreboard players set A A {num}` and `/scoreboard players set B A {num}`. Remember to use `/scoreboard objectives add A dummy` before input. Scored using: `{program size} + ( 2 * {input command} ) + {scoreboard command} = 538 + ( 2 * 33 ) + 34 = 638`. This code corresponds to the following psuedocode: ``` R = 1 T = A loop: R *= A A += 1 if A == B: if A.exclusive: R /= T if B.exclusive: R /= B print R end program ``` Download the world [here](http://www.mediafire.com/download/3698b1mumrtmtzj/PPCG__Product_Inclusive_Exclusive.zip). [Answer] ## Python 2, 72 bytes ``` lambda s:reduce(int.__mul__,range(*eval(s[1:-1]+'+'+`']'in s`))[s<'[':]) ``` To extract the numbers we evaluate `s[1:-1]`, the input string with ends removed, which gives a tuple. The idea is to get the `range` of this tuple and take the product. ``` lambda s:reduce(int.__mul__,range(*eval(s[1:-1])) ``` The fudging happens to adjust the endpoints. The upper endpoint is easy, just cut off the first element if the input starts with `(`, done as `[s<'[':]`. The other endpoint is trickier. Python doesn't have a clean way to conditionally remove the last element of a list because `l[:0]` removes the whole thing. So, we do something weird. We modify the tuple string before it is evaluated to tack on the string `"+True"` or `"+False"` depending on whether s ends in `]` or `)`. The result is that something like `3,7` becomes either `3,7+False` which is `3,7`, or `3,7+True` which is `3,8`. Alternate, prettier 72: ``` lambda s:eval("reduce(int.__mul__,range((s<'[')+%s+(']'in s)))"%s[1:-1]) ``` [Answer] # Pyth, 20 bytes ``` *FPW}\)ztW}\(z}FvtPz ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=%2AFPW%7D%5C%29ztW%7D%5C%28z%7DFvtPz&test_suite_input=%282%2C8%5D%0A%5B2%2C8%29%0A%5B2%2C8%5D%0A%282%2C8%29&test_suite=0&input=%282%2C8%5D) or [Test Suite](http://pyth.herokuapp.com/?code=%2AFPW%7D%5C%29ztW%7D%5C%28z%7DFvtPz&test_suite_input=%282%2C8%5D%0A%5B2%2C8%29%0A%5B2%2C8%5D%0A%282%2C8%29&test_suite=1&input=%282%2C8%5D) ### Explanation: ``` *FPW}\)ztW}\(z}FvtPz implicit: z = input string tPz remove the first and last character of z v evaluate, returns a tuple of numbers }F inclusive range tW remove the first number, if }\(z "(" in z PW remove the last number, if }\)z ")" in z *F compute the product of the remaining numbers ``` [Answer] # Ruby, ~~79~~ 77 bytes ``` ->s{a,b=s.scan /\-?\d+/;(a.to_i+(s[?[]?0:1)..b.to_i-(s[?]]?0:1)).reduce 1,:*} ``` **~~79 bytes~~** ``` ->s{a,b=s.scan(/\-?\d+/).map &:to_i;((s[?[]?a:a+1)..(s[?]]?b:b-1)).reduce 1,:*} ``` **Ungolfed:** ``` -> s { a,b=s.scan /\-?\d+/ # Extracts integers from the input string, s ( a.to_i+(s[?[]?0:1).. # Increase start of the range by 1 if s contains `(` b.to_i-(s[?]]?0:1) # Decrease end of the range by 1 if s contains `)` ).reduce 1,:* } ``` **Usage:** ``` ->s{a,b=s.scan /\-?\d+/;(a.to_i+(s[?[]?0:1)..b.to_i-(s[?]]?0:1)).reduce 1,:*}["(2,5]"] => 60 ``` [Answer] ## Seriously, 31 bytes ``` ,#d@p@',@s`εj≈`Mi(@)']=+)'(=+xπ ``` Takes input as a string (wrapped in double quotes) [Try it online](http://seriouslylang.herokuapp.com/link/code=2c2364407040272c407360ee6af7604d69284029275d3d2b2927283d2b78e3&input=) (input must be manually entered) Explanation: ``` ,#d@p@ get input, take first and last character off and push them individually ',@s`εj≈`Mi split on commas, map: join on empty, cast to int; explode list (@)']=+)'(=+ increment start and end if braces are ( and ] respectively (since range does [a,b)) xπ make range, push product ``` [Answer] # JavaScript (ES6), 68 bytes ``` s=>(f=_=>a>b||a++*f())([a,b,c]=s.match(/-?\d+|]/g),a-=-(s<'['),b-=!c) ``` [Answer] # [Julia 0.4](http://julialang.org/), 75 bytes ``` s->prod((x=map(parse,split(s[2:end-1],",")))[1]+(s[1]<41):x[2]-(s[end]<42)) ``` [Try it online!](https://tio.run/##Xc4xDsIwDIXhnVMgT7ZwhlhlqWjFPawMkdqKokKjGkRvHzJCxvfpH979vcwxT10216dtHRD37hETprjZyJaW@YWm0o7PwfnAwEBE6sOpqA@XxlO7qwRXZkkKCFG@2m39HCcEFT4T0OEPwi9gXWBdqBOWShouZ4DyFw "Julia 0.4 – Try It Online") This is an anonymous function that accepts a string and returns an integer. To call it, give it a name, e.g. `f=s->...`. Ungolfed: ``` function f(s::AbstractString) # Extract the numbers in the input x = map(parse, split(s[2:end-1], ",")) # Construct a range, incrementing or decrementing the endpoints # based on the ASCII value of the surrounding bracket r = x[1]+(s[1] == 40):x[2]-(s[end] == 41) # Return the product over the range return prod(r) end ``` [Answer] # Python 3, 104 ``` y,r=input().split(',') t=int(y[1:])+(y[0]<')') for x in range(t+1,int(r[:-1])+(r[-1]>'[')):t*=x print(t) ``` Takes input from stdin. [Answer] # MATLAB, ~~86~~ 70 bytes ``` s=sscanf(input(''),'%c%d,%d%c');a=s<42;disp(prod(a(1)+s(2):s(3)-a(4))) ``` This also works with **Octave**. You can try [online here](http://octave-online.net/?s=QHPazBNGkfyhbhbdFrYAnJeGZmDvKMKYapOgHyikJRbmUTQP). I have added the code as a script to that workspace, so you can just enter `productRange` at the prompt, then enter your input, e.g. `'(2,5]'`. --- So the code first scans the input to extract the brackets and the numbers together: ``` s=sscanf(input(''),'%c%d,%d%c'); ``` This returns an array which is made of `[bracket, number, number, bracket]`. The array is compared with `42`, actually any number between 42 and 90 inclusive will do. This determines which sort of bracket it was, giving a 1 if it is an exclusive bracket, and a 0 if an inclusive bracket. ``` a=s<42; ``` Finally, we display the product of the required range: ``` disp(prod(a(1)+s(2):s(3)-a(4))) ``` The product is of numbers staring with the first number `s(2)` plus the first bracket type `a(1)` (which is a 1 if an exclusive bracket), ranging up to and including the second number `s(3)` minus the second bracket type `a(4)`. This gives the correct inclusive/exclusive range. [Answer] # PowerShell, ~~146~~ 104 Bytes ``` param($i)$a,$b=$i.trim("[]()")-split',';($a,(1+$a))[$i[0]-eq'(']..($b,(+$b-1))[$i[-1]-eq')']-join'*'|iex ``` Golfed off 42 bytes by changing how the numbers are extracted from the input. Woo! ``` param($i) # Takes input string as $i $a,$b=$i.trim("[]()")-split',' # Trims the []() off $i, splits on comma, # stores the left in $a and the right in $b ($a,(1+$a))[$i[0]-eq'(']..($b,(+$b-1))[$i[-1]-eq')']-join'*'|iex # Index into a dynamic array of either $a or $a+1 depending upon if the first # character of our input string is a ( or not # .. ranges that together with # The same thing applied to $b, depending if the last character is ) or not # Then that's joined with asterisks before # Being executed (i.e., eval'd) ``` [Answer] # [Perl 6](http://perl6.org), 60 bytes ``` {s/\((\-?\d+)/[$0^/;s/(\-?\d+)\)/^$0]/;s/\,/../;[*] EVAL $_} ``` There is a bit of mis-match because the way you would write the `(2,5]` example in Perl 6 would be `2^..5` (`[2^..5]` also works). So I have to swap `(2` with `[2^`, and `,` with `..`, then I have to `EVAL` it into a Range. --- usage: ``` # give it a name my &code = {...} # the `$ =` is so that it gets a scalar instead of a constant say code $ = '(2,5)'; # 12 say code $ = '[2,5)'; # 24 say code $ = '(2,5]'; # 60 say code $ = '[2,5]'; # 120 say code $ = '(-4,0)' # -6 say code $ = '[-4,0)' # 24 say code $ = '(-4,0]' # 0 say code $ = '[-4,0]' # 0 say code $ = '(-4,-1)' # 6 say code $ = '[-4,-1)' # -24 say code $ = '(-4,-1]' # -6 say code $ = '[-4,-1]' # 24 # this is perfectly cromulent, # as it returns the identity of `*` say code $ = '(3,4)'; # 1 ``` [Answer] ## Mathematica, 128 bytes ``` 1##&@@Range[(t=ToExpression)[""<>Rest@#]+Boole[#[[1]]=="("],t[""<>Most@#2]-Boole[Last@#2==")"]]&@@Characters/@#~StringSplit~","& ``` This is too long... Currently thinking about a `StringReplace` + `RegularExpression` solution. [Answer] # JavaScript (ES6), 90 bytes ``` s=>eval(`for(n=s.match(/-*\\d+/g),i=n[0],c=s[0]<"["||i;++i<+n[1]+(s.slice(-1)>")");)c*=i`) ``` ## Explanation ``` s=> eval(` // use eval to allow for loop without return or {} for( n=s.match(/-*\\d+/g), // n = array of input numbers [ a, b ] i=n[0], // i = current number to multiply the result by c=s[0]<"["||i; // c = result, initialise to a if inclusive else 1 ++i<+n[1] // iterate from a to b +(s.slice(-1)>")"); // if the end is inclusive, increment 1 more time ) c*=i // multiply result `) // implicit: return c ``` ## Test ``` var solution = s=>eval(`for(n=s.match(/-*\\d+/g),i=n[0],c=s[0]<"["||i;++i<+n[1]+(s.slice(-1)>")");)c*=i`) ``` ``` <input type="text" id="input" value="(5,10]" /> <button onclick="result.textContent=solution(input.value)">Go</button> <pre id="result"></pre> ``` [Answer] # TI-Basic, 69 bytes ``` Input Str1 expr("{"+sub(Str1,2,length(Str1)-2 prod(randIntNoRep(min(Ans)+(sub(Str1,1,1)="("),max(Ans)-(sub(Str1,length(Str1),1)=") ``` Output is stored in `Ans` and displayed. Replace `randIntNoRep(` with `seq(I,I,` (+3 bytes) if the calculator does not support it. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 57 bytes ``` 1##&@@ToExpression["Range"<>(#/."("->"[1+"/.")"->"-1]")]& ``` [Try it online!](https://tio.run/##TY9Ba4MwFMfv@RQSR4ks2RKrXpwibD3sNtbdQg5BbBtYjWgGhdLP7mKitbf/e3m/33s5S3NqztKoWo6HYmRhuKmqH727dH0zDEq3HH7L9tjAtxKFry8QQVJCzp6hzdGUCRMwEptR6aAI9qZX7XF3Mb2sDX/a173qzGfb/Rn/giGwTJ5jGBRl4KIAH5qDq8L6VvyqtsnBl500XJHyUL2f5GRq@qFSlkEQa2zXCoCv0yxW@iZGHuM0mnxxAniKGXUFS1lMAScJ3rraZrpG26Z3xvLCIRMwCcRdMBvEahCrwX59VqBFkVGA7oYtjRNbPwjQIshcexaQzAn82bEXRIvA89HK@7Nd20@R7B8 "Wolfram Language (Mathematica) – Try It Online") Input a list of characters. Fairly straightforward. Mathematica uses `[` `]` to introduce arguments, and `Range` is inclusive on both ends. --- ### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 69 bytes ``` 1##&@@ToExpression["Range"<>#~StringReplace~{"("->"[1+",")"->"-1]"}]& ``` [Try it online!](https://tio.run/##TY9Pb4MgGIfvfAqDS6MZJGjVi9N4WA@7Le1uhAMxtCVpxViWNDH2qzsE/@z2e19@zwPcub6KO9ey5uO5GCPf31XVjzo82048HlI1FB55cxHwo/RfJ93J5nIU7Y3X4tXDAOIS0ugdIhhOEUcMDmw3SuUVnisfnrrjtaZvp7qTrf5q2l/tThAEhslzBL2i9Gxk4FNR0EukhuImG5GDb9PUVOLyXElTDCBS010MoH4qIKkGNtIYpeEkiRNAUxQRO0RpFBNAcYL2djaZbNGsycoYnllkAiYBWwWzgW0GthnMf2dFsCgyAoLVsCdxYuZ/gmARZHY9C3BmBe7ZsROEi8Dx4ca7Z9u1a@HsDw "Wolfram Language (Mathematica) – Try It Online") Input a string. [Answer] # Japt, ~~43~~ 41 bytes ``` [VW]=Uf"\\d+";ÂV+Â('A>Ug¹oÂW+Â('A<UtJ¹r*1 ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=W1ZXXT1VZiJcXGQrIjvCVivCKCdBPlVnuW/CVyvCKCdBPFV0SrlyKjE=&input=Ils1LDEwKSI=) [Answer] # CJam, 34 bytes ``` r)\(@+"[()]"2/\.#\',/:i.+~1$-,f+:* ``` [Try it online](http://cjam.aditsu.net/#code=r)%5C(%40%2B%22%5B()%5D%222%2F%5C.%23%5C'%2C%2F%3Ai.%2B~1%24-%2Cf%2B%3A*&input=(5%2C10%5D) Explanation: ``` r Read input. ) Split off last character. \ Swap rest of input to top. ( Split off first character. @ Rotate last character to top. + Concatenate first and last character, which are the two braces. "[()]" Push string with all possible braces. 2/ Split it into start and end braces. \ Swap braces from input to top. .# Apply find operator to vector elements, getting the position of each brace from input in corresponding list of possible braces. The lists of braces are ordered so that the position of each can be used as an offset for the start/end value of the interval. \ Swap remaining input, which is a string with two numbers separated by a comma, to top. ',/ Split it at comma. :i Convert the two values from string to integer. .+ Element-wise addition to add the offsets based on the brace types. ~ Unwrap the final start/end values for the interval. 1$ Copy start value to top. - Subtract it from end value. , Build 0-based list of values with correct length. f+ Add the start value to all values. :* Reduce with multiplication. ``` [Answer] # R, ~~102~~ 104 bytes ``` f=function(s){x=scan(t=gsub('\\(|\\[|,|\\)|\\]',' ',s))+c(grepl('^\\(',s),-(grepl('\\)$',s)));prod(x[1]:x[2])} ``` Ungolfed ``` f=function(s){ # remove delimiting punctuation from input string, parse and return an atomic vector x=scan(t=gsub('\\(|\\[|,|\\)|\\]',' ',s)) + # add /subtract from the range dependent on the `[)` pre/suf-fixes c(grepl('^\\(',s),-(grepl('\\)$',s))) # get the product of the appropriate range of numbers prod(x[1]:x[2]) } ``` edit to allow negative numbers [at the expense of 2 more characters [Answer] # JavaScript (ES6), 79 As an anonymous method ``` r=>eval("[a,b,e]=r.match(/-?\\d+|.$/g);c=a-=-(r<'@');for(b-=e<'@';a++<b;)c*=a") ``` Test snippet ``` F=r=>eval("[a,b,e]=r.match(/-?\\d+|.$/g);c=a-=-(r<'@');for(b-=e<'@';a++<b;)c*=a") // TEST console.log=x=>O.innerHTML+=x+'\n' ;[ ['[2,5)',24],['[5,10)',15120],['[-4,3)',0],['[0,3)',0],['[-4,0)',24], ['[2,5]',120],['[5,10]',151200],['[-4,3]',0],['[0,3]',0],['[-4,-1]',24], ['(2,5]',60],['(5,10]',30240],['(-4,3]',0],['(0,3]',6],['(-4,-1]',-6], ['(2,5)',12],['(5,10)',3024],['(-4,3)',0],['(0,3)',2],['(-4,0)',-6] ].forEach(t=>{ r=F(t[0]),k=t[1],console.log(t[0]+' -> '+r+' (check '+k+ (k==r?' ok)':' fail)')) }) ``` ``` <pre id=O></pre> ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 25 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Ugly as hell! ``` ůJ q, rȰ+Uø'()õY-Uø')Ã× ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xa9KIHEsIHLIsCtV%2bCcoKfVZLVX4JynD1w&input=WwoiWzIsNSkiCiJbNSwxMCkiCiJbLTQsMykiCiJbMCwzKSIKIlstNCwwKSIKCiJbMiw1XSIKIls1LDEwXSIKIlstNCwzXSIKIlswLDNdIgoiWy00LC0xXSIKCiIoMiw1XSIKIig1LDEwXSIKIigtNCwzXSIKIigwLDNdIgoiKC00LC0xXSIKCiIoMiw1KSIKIig1LDEwKSIKIigtNCwzKSIKIigwLDMpIgoiKC00LDApIgpdLW1S) (includes all test cases) [Answer] # [Haskell](https://www.haskell.org/), 94 bytes ``` f=(\(h:a,_:b)->product[a!h..init b!last b]).span(','/=);c!')'=c!' '-1;c!'('=c!' '+1;c!_=read c ``` [Try it online!](https://tio.run/##LcfRCoMgFIDhVznCQGXmCHbVOHuRFnEyQ5lZqGOP7wp28/98jvLbhlDrguIlXEdq7CbZPPe0zR9TemJOax99gYkFyscGqfNOUXDFbygfhnHJ8Sjwpj0l/rqeGjFZmsHUlXwEBB@LTWQKXCC77Qsaltq36j78AA "Haskell – Try It Online") [Answer] # [Julia 0.4](http://julialang.org/), 64 bytes ``` s->prod((x=parse(s[2:end-1]).args)[]+(s[1]<41):x[2]-(s[end]<42)) ``` [Try it online!](https://tio.run/##yyrNyUz8n2b7v1jXrqAoP0VDo8K2ILGoOFWjONrIKjUvRdcwVlMvsSi9WDM6VhsoaBhrY2KoaVURbRSrC@QCVQAFjDQ1/zsUZ@SXK6RpKEUb6ZhqKmlyoQjEIgtooKvQQFcRrWukY4QmYqIDdAumENCg/wA "Julia 0.4 – Try It Online") Based on [Alex A's answer](https://codegolf.stackexchange.com/a/66312/98541) # [Julia 1.0](http://julialang.org/), 69 bytes ``` s->prod((:)(Meta.parse(s[2:end-1]).args+[s[1]<'*',-(s[end]<'*')]...)) ``` [Try it online!](https://tio.run/##yyrNyUw0rPifZvu/WNeuoCg/RUPDSlPDN7UkUa8gsag4VaM42sgqNS9F1zBWUy@xKL1YO7o42jDWRl1LXUcXKAmUAnM0Y/X09DQ1/zsUZ@SXK6RpKEUb6ZhqKmlyoQjEIgtooKvQQFcRrWukY4QmYqIDdAqmENCg/wA "Julia 1.0 – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), 20 bytes ``` $*VaR^"(][)"['U"+1"] ``` [Replit!](https://replit.com/@dloscutoff/pip) Or, verify all test cases with this 22-byte version in Pip Classic: [Try it online!](https://tio.run/##Tc49DgIhEAXgfk9BiAW4kDAs0Gm8gI2FDZk1VsbEYrOWxrMjy6/dvMm8L7M8l/AJu/31fpkpQ8@ppzBSOgLF8CVncmK3@c3j8AheC8vJ4Ui0GbwVoFIAC1oNXhoxpRxn1ce4Vq0T@5gqW2EDsAFFwC5gFyRgIVglnBpYEyalTcx/AKuAS@sCSJeA/LbOAK9A7vPez2@ndb6SLsj19QM "Pip – Try It Online") ### Explanation Conveniently, `,` is Pip's range operator; it is inclusive on the lower end and exclusive on the upper end. So if we turn the brackets into appropriate tweaks to the numbers, we can use eval to generate the range. ``` $*VaR^"(][)"['U"+1"] aR In the input, replace each string in "(][)" This string ^ Split into a list of characters with the corresponding string in [ ] this list: 'U ( becomes U (increment the following number) "+1" ] becomes +1 (add 1 to the preceding number) [ and ) don't have a corresponding replacement, so they are simply deleted (leaving the numbers unchanged) V Evaluate the result as a Pip expression $* Fold on multiplication ``` ]
[Question] [ Inspired by [Find the largest fragile prime](https://codegolf.stackexchange.com/questions/41648/find-the-largest-fragile-prime). By removing at least 1 digit from a positive integer, we can get a different non-negative integer. Note that this is different to the `Remove` function in the linked question. We say a prime number is delicate if all integers generated this way are not prime. For example, \$60649\$ generates the following integers: ``` 0, 4, 6, 9, 49, 60, 64, 66, 69, 604, 606, 609, 649, 664, 669, 6049, 6064, 6069, 6649 ``` None of these integers are prime, therefore \$60649\$ is a delicate prime. Note that any leading zeros are removed, and that the requirement is "not prime", so \$0\$ and \$1\$ both qualify, meaning that, for example, \$11\$ is a delicate prime. Similar to the standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rule, you are to do one of the following tasks: * Given a positive integer \$n\$, output two distinct, consistent\* values depending on whether \$n\$ is a delicate prime or not * Given a positive integer \$n\$, output the \$n\$th delicate prime * Given a positive integer \$n\$, output the first \$n\$ delicate primes * Output infinitely the list of delicate primes \*: You may choose to output two sets of values instead, where the values in the set correspond to your language’s definition of truthy and falsey. For example, a Python answer may output an empty list for falsey/truthy and a non-empty list otherwise. You may choose which of the tasks you wish to do. You can input and output in any [standard way](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), and, as this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins For reference, the first 20 delicate primes are: ``` 2, 3, 5, 7, 11, 19, 41, 61, 89, 409, 449, 499, 881, 991, 6469, 6949, 9001, 9049, 9649, 9949 ``` A couple more to look out for: ``` 821 - False (Removing the 8 and the 1 gives 2 which is prime) ``` --- I'll offer a +100 bounty for an answer which implements one of the standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") I/Os rather than the [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") method, that either: * is shorter than a naive [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") implementation (please include such a version as proof if one hasn't already been posted) * or that doesn't rely on checking whether values are delicate primes or not when generating values (e.g. may use the fact that only specific digits can occur, or something else that isn't simply slapping a "loop over numbers, finding delicate primes") This is kinda subjective as to what counts as "checking for delicate primes", so I'll use my best judgement when it comes to awarding the bounty. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ### Code Uses the **05AB1E**-encoding. Checks whether the given number is a *delicate prime* or not. ``` æpJΘ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8LICr3Mz/v83MzGzBAA "05AB1E – Try It Online") or [Check for all numbers between 1 and 9949](https://tio.run/##yy9OTMpM/f@oYx6nklt@kUJiTo5CZl5JanpqUTGQoRBtqKNgpKOgp6ejAFQTqxTDpXBqkgKnkndqaoFCSUaqQl5pbhJIbXlGalEqWCQtPycnvzwzL10hs1ihpKg01UpBKeb/4WUFXudm/K/l4jIyOLSYU8m1oqQoMbkEoiOzqLhEwcgAZhhQuZmJmSUA). ## Explanation ``` æ # Get the powerset of the number. p # Check for each element whether it is a prime. J # Join these numbers into one big number. Θ # Check whether this joined number is equal to 1. ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~16~~ 14 bytes ``` </1⍭⍎⍕(⊢,,¨)\⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfmf9qhtQvV/G33DR71rH/X2PeqdqvGoa5GOzqEVmjGPerf@r/2fpqBuZmBmYqnO9ah3R9qhFQpANWBys6GBAQA "APL (Dyalog Extended) – Try It Online") -2 bytes (`∊⍎¨¨ → ⍎⍕`) thanks to @ngn. Full program that takes a single number from stdin and prints 1 (true) or 0 (false). The trick here is how it generates all non-empty subsequences: * `(⊢,,¨)/ str` gives all subsequences of `str` which include the last character. ``` (⊢,,¨)/ '1234' → '1' (⊢,,¨) '2' (⊢,,¨) '3' (⊢,,¨) '4' → '1' (⊢,,¨) '2' (⊢,,¨) '4' '34' → '1' (⊢,,¨) '4' '34' '24' '234' → '4' '34' '24' '234' '14' '134' '124' '1234' ``` * `(⊢,,¨)\ str` applies `(⊢,,¨)/` to each prefix of `str`, giving all non-empty subsequences as a list of lists of strings. ``` (⊢,,¨)\ '1234' → '1' ('2' '12') ('3' '23' '13' '123') ('4' '34' '24' '234' '14' '134' '124' '1234') ``` Explanation of whole code: ``` </1⍭⍎⍕(⊢,,¨)\⍞ ⍞ ⍝ Take n from stdin as a string ( )\ ⍝ For each prefix, reduce from right by ,¨ ⍝ prepend the previous char to each string ⊢, ⍝ and append to the previous list of strings ⍎⍕ ⍝ Convert nested strings to a single string, ⍝ and then eval it to get a simple integer vector 1⍭ ⍝ Test each number for primality </ ⍝ Test if the only truth is the last one ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 7 6 bytes ``` ṗ⊇ᵘṗˢȮ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pvaAAEj@Yvq37UtuFRU5Na7elF5f8f7pz@qKv94dYZQMbpRSfW/f8PAA "Brachylog – Try It Online") ``` ṗ⊇ᵘṗˢȮ the implicit input ṗ is a prime ⊇ᵘ and from every unique subset ṗˢ select the primes Ȯ and this should be a list with one element (the prime input itself) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` DŒPḌẒḄ’ ``` A monadic Link accepting a positive integer which returns zero (falsey) if it's a delicate prime, or a non-zero integer (truthy) if not. **[Try it online!](https://tio.run/##AR8A4P9qZWxsef//RMWSUOG4jOG6kuG4hOKAmf///zYwNjQ5 "Jelly – Try It Online")** Or see the [first twenty](https://tio.run/##ASEA3v9qZWxsef//RMWSUOG4jOG6kuG4hOKAmf/Dh8KsJDIwI/8 "Jelly – Try It Online"). ### How? ``` DŒPḌẒḄ’ - Link: n e.g. 824 409 D - decimal digits [8,2,4] [4,0,9] ŒP - power-set [[],[8]...,[8,2,4]] [[],[4],...,[4,0,9]] Ḍ - undecimal [0,8,2,4,82,84,24,824] [0,4,0,9,40,49,9,409] Ẓ - is prime? [0,0,1,0,0,0,0,0] [0,0,0,0,0,0,0,1] Ḅ - from binary 32 1 ’ - decrement 31 0 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ¥à f_°j ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=peAgZl%2bwag&input=IjYwNjQ5Ig) or [test `[0,1000)`](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWY&header=cw&code=peAgZl%2bwag&input=MTAwMA) ``` ¥à f_°j :Implicit input of integer string ¥ :Is equal to à :Combinations f :Filter _ :By passing each through a function ° :Postfix increment, to cast to an integer j :Is prime? ``` [Answer] # [J](http://jsoftware.com/), 25 23 bytes *-2 thanks to Jonah!* Returns a list containing either 1 being truthy or 0 otherwise. ``` 1</@p:(#~2#:@i.@^#)&.": ``` [Try it online!](https://tio.run/##HYrBCgIxDETvfsXQgruFbk3XWtugUBA8efIDvIiL60Xvgr9e0w3My2Qmr6pcN@HI6GBBYNHgcLpeztUfNuXDvf6Nmsvsyk2btVNczepxf77RS/N1ZVJkMDt4kjEYGKPF1mJnsbfwXpQtguwoSs1TQ2jIgpQkz7k9hCh3zK3KRC2mxceFktc/ "J – Try It Online") ### How it works ``` 1</@p:(#~2#:@i.@^#)&.": &.": convert the number to a string ( 2 ^#) 2 ^ length #:@i.@ enumerated and to base 2 #~ select from the string based on the bit mask &.": convert from strings to numbers 1 p: primes -> 1, non-primes -> 0 so in the delicate prime case, we have (2^L) - 1 zeros and one 1 for the input itself </@ reduce from left to right with less-than (so last position is 1, everything else 0) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~14~~ 8 bytes ``` qjfP_sTy ``` [Try it online!](https://tio.run/##K6gsyfj/vzArLSC@OKTy/38lc3Olf/kFJZn5ecX/dVMA "Pyth – Try It Online") ## Explanation ``` qjfP_sTy f # filter y # all subsets of input P_sT # with a primality test j # join result of filter on newlines q # check if it equals input ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 53 bytes ``` ^ ; +%`;(.) $1;$'¶$`; .+ $* %A`^.?$|^(..+)\1+$ ^1+¶+$ ``` [Try it online!](https://tio.run/##DcO7DYAgEADQ/uY4InjJRRQ/hMJYuYQhWFjYWBhL53IAFsN7ybuP57z2ovSaSoQApFLQbABtwCp/mAIwAdaglhR5xjdqZjKbJYRoKX@EpbjGg7OylZ10speDHOUkvf8B "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ^ ; +%`;(.) $1;$'¶$`; ``` Generate all subsequences of the input. ``` .+ $* ``` Convert then to unary. ``` %A`^.?$|^(..+)\1+$ ``` Delete the ones that aren't prime, but don't delete the newlines. (A multiline replace also works, but is harder to format an explanation for.) ``` ^1+¶+$ ``` Check that the original input was prime but none of the proper subsequences were. [Answer] # [Scala](http://www.scala-lang.org/), ~~173~~ 170 bytes ``` n=>(s"$n".indices.toSet.subsets.filter{x=>1<x.size&x.size<s"$n".size}.map(_.toSeq.sorted.map(""+n).mkString.toInt).toSet+n).filter{x=>x>1&2.to(x/2).forall(x%_>0)}==Set(n) ``` [Try it online!](https://tio.run/##hVA9T8MwEN37K04WVLaIjBPSNKmaSDAgMTCVEalyWxcZXCfELoqo@tvDOQUqJoZ7d37vPu3W0si@Xr2qtYdHqS2oziu7cXDbNHAYjT6kge0MHqyHsoK7ujZKWih7W1bUkQtLuLYbvVaO@3qhPHf7lVPe8a02XrWHrqzieced/lTjk5ufqkJ45DvZ0OVQ@c5d3Xq1GShCrizju7eFb7V9QR3Hs9OAIJx7d1U8TlCg3XWCfN1KY2h3uawEO5YlplPLeoAG23hjKXlq92pG2AiAJBHcRDCJYBpBHKMVEaToM7Q8xCJAGqBAyHPkiyIkpBm@syJIhRCBFkOcDYg8XtcY7SmJgLDhIPytnx221H4fxMIeZzoT2OAPR57tvTTuZ2MBMaSQCEgnEAsB@TT7nfTfoGP/BQ "Scala – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~163~~ 154 bytes ``` function(x,n=nchar(x),s=sum)(a=apply(!expand.grid(rep(list(0:1),n)),1,function(v)(y=s((x%/%10^(n:1-1)%%10)[v]*10^(s(v):1-1)))&s(!y%%1:y)==2))[1]&!s(a[-1]) ``` [Try it online!](https://tio.run/##ZY/RboMwDEXf@xVBFZU9pVvcdZWKlC9BrIogjEg0jWLawtczYNoextuVfc@RHUfHl8q2rjSdvYTorlaP9d2Xnbt56KXXvmxMhB4la75fEYw2IbQDJLYPxlevX9FVEG2A1nEHKiOUHlGS/LM8EAbNAH36lpL6BJ/RnjCdMuaP4mUe8VRapog7hmSYltmAWh8Qcyp2CYPJ91Tg@lo4qdPxjGIrliAcCyN@K2KpbNYQHd6PHzO0hBnyt24NPhtXNsA/D1NGSim5kuHsqV3kTtT2@U/Bm/Eb "R – Try It Online") Checks for primes among the numbers formed by removing all combinations of digits from x. The first combination is removal of *no* digits: this must be TRUE, and all other prime tests must be FALSE. Commented: ``` is_delicate_prime= function(x, # x = number to test n=nchar(x), # n = number of digits of x s=sum) # s = alias to sum() function (a= # a = matrix of all prime-tests: apply( # apply the function v to each of... !expand.grid(rep(list(0:1),n)), # all combinations of n of TRUE/FALSE... 1, # row-by-row... function(v) # defining the output of v as: (y=s((x%/%10^(n:1-1)%%10) # the digits of x... [v] # (considering only the elements chosen by v)... *10^(s(v):1-1))) # multiplied by 10^((v-1)..0)... &s(!y%%1:y)==2)) # tested for primality AND non-zero [1] # Finally, output TRUE if a[1] is TRUE... &!s(a[-1]) # and the sum of all other elements of a are FALSE ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 54 bytes ``` Select[FromDigits/@Subsets@@RealDigits@#,PrimeQ]=={#}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pzg1JzW5JNqtKD/XJTM9s6RY3yG4NKk4taTYwSEoNTEHIuigrBNQlJmbGhhra1utXKv2H8jLK4lW1rVLc1COVatzLCpKrKwzMuCCiEMNDUrMS091MDQAAp202Nj/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # JavaScript (ES6), ~~98~~ 95 bytes Expects `n` as a string. Returns a Boolean value. ``` n=>[...n].reduce((a,x)=>[...a,...a.map(y=>(g=k=>y%--k?g(k):(p+=q=y>1&k<2,y))(y+=x))],[p=0])|q/p ``` [Try it online!](https://tio.run/##JchBDoIwEEDRq8xGmElLLS6VwYMQFg0UomBbQA1NvDti3Pz8vLt5m6WZb@GZOd/arePNcVkppVytZtu@Goto5Ep/NPIX9TABI5fY88BlPGTZcO1xoDMGwRPHMk@G4iQjEUbBK1Etq8C6ps90DFvnZ3TAkF/AQQG51no/IQi63QWkKUGSQOPd4kerRt@jo@0L "JavaScript (Node.js) – Try It Online") ### How? We compute the powerset of the digits of `n` in such a way that the order is preserved and `n` itself is computed last. The result is true if the only prime among the resulting integers is the last one. [Answer] # [Python 2](https://docs.python.org/2/), ~~139~~ \$\cdots\$ ~~145~~ 142 bytes Added 36 bytes to fix a bug kindly pointed out by [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger). Saved 5 bytes thanks to [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger)!!! ``` lambda n,R=range:all((g<2or any(g%i<1for i in R(2,g)))-(`g`==n)for g in{int(''.join(n[j]for j in R(len(n))if i>>j&1))for i in R(1,2**len(n))}) ``` [Try it online!](https://tio.run/##rZBNb8IwDIbv/ApftsQoTG0ohSLCceeJa4dEoB9L1aVVmgua9ts7p@UwaddFsmM/rxM76e/@o7NyrNT72OrPa6HBipNy2tblXrct5/VBdg60vfP6yRziihIDxsKJS1Ej4opf6otSFoNSk/JlrOeMvTSdsdzmzTkIzXykLQkhmgrM8dg8x4i/7ouFXC4fFd84OsXZqzYtA8He9DAwXBQ9KMilgLWAjYCtgDgmywQktKdkuxBHwSXBZeR2O@JZFgqSlPI0C1IWRQFHU5xOnvh5EebxYR7@p812biWJStrXxNbbuXVCLKF48z9j4H4BtAZ6bcUH77hHnMitc668eeJ8GrLoEZSCYRJ7Rz8PXgCD1RGYgEGAyx9HzuMP "Python 2 – Try It Online") Inputs an integer as a string and returns `True` if it's a delicate prime or `False` otherwise. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~146~~ 144 bytes *-2 bytes by removing redundant parentheses* I was also working on a very similar answer just before [Noodle9](https://codegolf.stackexchange.com/users/9481/noodle9) posted theirs, and I combined ideas from that to get this ([upvote it!](https://codegolf.stackexchange.com/a/211382)). That one is now quite different because they initially had a broken one, so I thought I'd post mine. ``` lambda s,R=range:(l:=len(s))*all((g!=int(s))^(g>1)&all(g%k for k in R(2,g))for g in{int(''.join(s[j]for j in R(l)if i>>j&1))for i in R(1,2**l)}) ``` [Try it online!](https://tio.run/##jVHBboMwDL33K7zDmrjKJhJogErhI3ptO4muhUEzQIEdJsS3MweOuzSSnednx35Jut/hq23CpHNzYc6zzb@vtxx6cTQub8r7gduDsfeG94i73FrOyxdTNYOPP3iZSdx6tnx9QNE6eEDVwJErUSL6uKR49OWMvddtRW1O9cUn6rXQYlVAlWX1Vq4HqpWXQu12FiecneHs/KPi6JOBWJAMGW5uHRg4KQGhgL2AWICUZKmAiHZNlngceBd5l5JLEuLT1BdEmmKd@lQaBJ4OFqwXT/xl4@UMXg4PqLOAf8PidaCitKKMIhwSH1JJGK9CIuIjwvtnREmt9TPS8LABWj29QMH7wfEBcWE655@6YOMwwVsGYz/B6E58ucStQzAGrm1r6e8uE8P5Dw "Python 3.8 (pre-release) – Try It Online") Explanation: ``` lambda s,R=range:(l:=len(s))*all((g!=int(s))^(g>1)&all(g%k for k in R(2,g))for g in{int(''.join(s[j]for j in R(l)if i>>j&1))for i in R(1,2**l)}) lambda s : function ,R=range alias `range` built-in to `R` { s[j]for j in R(l)if i>>j&1 for i in R(1,2**l)} compute the power-set (excluding the empty set) int(''.join( )) convert each list of digits to an integer all( for g in ) check the integers for primality all(g%k for k in R(2,g)) check for factors in the number (g>1)& makes sure 0 and 1 aren't treated as prime (g!=int(s))^ ensure the number itself is prime (l:=len(s))* store the length in `l` ``` [Answer] # [SageMath](https://doc.sagemath.org/), 139 bytes ``` def f(n):s=str(n);l=len(s);return p(n)*all(~-p(g)for g in{int(''.join(s[j]for j in R(l)if i>>j&1))for i in R(1,2**l-1)}) R=range;p=is_prime ``` [Try it online!](https://sagecell.sagemath.org/?z=eJytkU1uwyAQhfc-xawKRKTyX-yQiBwi29SqIhtHWC5GQFaWe_YOpLtuizTD43ugGWBQI4zUsJOXPjgU51nOylDPzk6FpzNgEe7u80y_95Y-2Lg4eIA2qzaBEvI-LRp336YuGhMacKUz0yPoy2V6K1g6oF-84OVuN-8LtrHsKt3dPNTZSu0_rdNfKsucpOTjWbZ1T4AnVVSEZYMFCbeSQ8XhwKHlUBQYgkONc4NxjDqPqY5JYDoekQsRN9QNrhsRLZHnEedJNykj77LYZIhN0j9l2lepEmmJc4Wsal-la2Q16sP_tMFOGeDweFuzhBQjDSzBfnFO9QEtmvocLAMpwScTnw8_YyRr2GB_gdVvsLrb75FuI-wHUpV4AQ==&lang=sage&interacts=eJyLjgUAARUAuQ==) Port of my Python answer. [Answer] # [Python 3](https://docs.python.org/3/), 181 bytes **Using [itertools](https://docs.python.org/3/library/itertools.html) and a golfed recipe for `powerset`.** ``` lambda s,R=range:all(p(int(''.join(t)),R)for t in sum(([*combinations(s,k)]for k in R(1,len(s))),[]))>p(int(s),R) from itertools import* p=lambda n,R:any(n%i<1for i in R(2,n))or 2>n ``` [Try it online!](https://tio.run/##fVFfT8IwEH/fp7gXQwuN2RCQLc6PwMNekZiiLVa269JWE2P87PO6gQSMXnK3@//7Xdd@hBeLN50uH7paNttnCV5UpZO4U4Wsa9Yyg4GNRtev1iALnIuKa@sggEHwbw1j6/GTbbYGZTAWPfNizzexYx87KpaJWiHznCbXG87vh4U@7kna8oCJoiokfjC8MndZHDbD8FQg5xRO7zHRzjZggnLB2tqDaVrrwrhbQQl5Pk@TZ1WbJxmUp8R6KuBGwFzArYAsI80FzOi7IF1GP41mFk1OZrmkfJ7HhtmC4kUeS3maxnTa@4veUn6TRIIYCfbPRBeueJEAiZa1V4@t9SaYdyUOMaqdjDHxSkXaNxo9LPjhPMwfSzaAZj44RtefKlFa1/8O@Et6RDgiFjASgDz51XHiNCkh6@uK0mcs/mcwAB1P/Rvo2DEAHYZXb81WObAalHPW@QI@v4CRaoRJ9HXLR9f0zI0M7HzP5Jz/5RuLC1jOu28) Expects input as a string. The function `p` returns `True` if its input is not prime, and `False` if it is prime; the main function returns `(forall t, p(t)) > p(s)` where `t` takes all the "subvalues" of `s`. The only way for booleans to satisfy this inequality is `True > False`, which means all `t` are nonprimes and `s` is not nonprime. *Disclaimer: There were already two python answers when I posted this one.* ]
[Question] [ In honor of [Star Wars day](http://en.wikipedia.org/wiki/May_the_fourth), write a program to display the following text, scrolling like the [Star Wars opening crawl](http://en.wikipedia.org/wiki/Star_Wars_opening_crawl): ``` It is a period of civil war. Rebel spaceships, striking from a hidden base, have won their first victory against the evil Galactic Empire. During the battle, Rebel spies managed to steal secret plans to the Empire's ultimate weapon, the Death Star, an armored space station with enough power to destroy an entire planet. Pursued by the Empire's sinister agents, Princess Leia races home aboard her starship, custodian of the stolen plans that can save her people and restore freedom to the galaxy... ``` You may output an animated GIF or have your program display it. The output must show the following: * The text must start from the bottom of the image/display * It must scroll upwards until it reaches the top. It must take at least `30` seconds for a piece of text to reach the top. The animation must continue until all the text reaches the top. * In this distance, the text must get smaller until it is less than `1/3` the size (length and font) * The text must be slanted to follow this angle. * The text must be left and right justified. The text given is already justified for monospaced fonts, however, you may remove the extra spaces (not newlines) and justify it yourself. * The text must be yellow * The background must be black [This video](http://youtu.be/UKRIUiyF0N4?t=16s) shows the opening crawl. Good luck, and *May the fourth be with you*! [Answer] # HTML/CSS, 1047 I could golf this a lot more by deleting the `-webkit` prefixes etc., but this will do for the time being: ``` <html><head><style>body{font-family:sans-serif;background:#000;margin:0 auto;height:400px;width:800px;text-align:justify;position:relative;perspective: 150px;-webkit-perspective:150px;}div{font-size:63px;line-height:63px;color:#ee6; position:absolute;-webkit-transform:rotateX(70deg);transform:rotateX(70deg);}p{ position:relative;-webkit-animation:s 90s linear forwards;animation:s 90s linear forwards;}@-webkit-keyframes s{from{top:800px;}to{top:-2000px;}}@keyframes s{from{top:800px;}to{top:-2000px;}}</style><body><div><p>It is a period of civil war. Rebel spaceships, striking from a hidden base, have won their first victory against the evil Galactic Empire.</p><p>During the battle, Rebel spies managed to steal secret plans to the Empire's ultimate weapon, the DEATH STAR, an armored space station with enough power to destroy an entire planet.</p><p>Pursued by the Empire's sinister agents, Princess Leia races home aboard her starship, custodian of the stolen plans that can save her people and restore freedom to the galaxy...</p></div> ``` [**Live demo**](http://ruletheweb.co.uk/may-4th.html) [Answer] # HTML+CSS+SVG 1614 1625 I wanted to be visually correct, too. SVG used for masking and animation. HTML+CSS used for transforms. I didn't check if the text gets to exactly 1/3 size. Recommended viewing in Chrome due to `-webkit-` prefix. Requires CSS 3D transforms to work; you may need to open `chrome://flags` and pick 'Override software rendering list'. Included in bytecount are newlines and blanks. Update 1: Adding support for Firefox and other browsers that don't need prefixes. Added 11 bytes even after further cleanup. Cleanup was possible because browsers luckily interpret SVG using HTML-crunching parsers as opposed to XML-compilant parsers. [Live](//ivan.vucica.net/codegolf/may4th.html) ``` <div id=a> <div id=b> <svg width=760 height=1000> <g mask=url(#m)> <g transform=translate(0,0)> <animateTransform attributeName=transform type=translate dur=50 fill=freeze from=0,700 to=0,-450 /> <foreignObject width=760 height=800> <div style=width:740; > <p>It is a period of civil war. Rebel spaceships, striking from a hidden base, have won their first victory against the evil Galactic Empire.</p> <p>During the battle, Rebel spies managed to steal secret plans to the Empire's ultimate weapon, the DEATH STAR, an armored space station with enough power to destroy an entire planet.</p> </div> <p>Pursued by the Empire's sinister agents, Princess Leia races home aboard her starship, custodian of the stolen plans that can save her people and restore freedom to the galaxy...</p> </foreignObject> </g> </g> <defs> <linearGradient id=g x1=0 y1=0% x2=0 y2=100%> <stop offset=0% /> <stop offset=25% /> <stop offset=35% stop-color=#fff /> <stop offset=100% stop-color=#fff /> </linearGradient> <mask id=m> <rect width=100% height=100% fill=url(#g) /> </mask> </defs> </svg> </div> </div> <style> body { margin: 0; width: 100%; height: 100%; perspective: 700px; -webkit-perspective: 700px; background: url(http://vucica.net/s.php); } #a { position: absolute; width: 100%; height: 700px; bottom: 0; transform-style: preserve-3d; } #b { margin: auto auto auto auto; width: 760px; height: 100%; font-family: Courier; font-weight: bold; text-align: justify; font-size: 24pt; color: yellow; overflow: hidden; transform: rotateX(45deg); -webkit-transform: rotateX(45deg); } svg { position: absolute; width: 760px; height: 100%; } ``` [Answer] # HTML, 762 ``` <div><pre>It is a period of civil war. Rebel spaceships, striking from a hidden base, have won their first victory against the evil Galactic Empire. During the battle, Rebel spies managed to steal secret plans to the Empire's ultimate weapon, the Death Star, an armored space station with enough power to destroy an entire planet. Pursued by the Empire's sinister agents, Princess Leia races home aboard her starship, custodian of the stolen plans that can save her people and restore freedom to the galaxy...</pre></div><style>pre{transform:perspective(300px)rotateX(25deg);position:absolute;left:99px;color:yellow;animation:a 30s linear}@keyframes a{100%{font-size:0px}}body{background:black}</style> ``` Kind of choppy (read: **extremely** choppy :P). [Here's a JSFiddle](http://jsfiddle.net/Q4n4y/1/) (with `-webkit-` vendor prefixes added so it works in Chrome). [Answer] ## PerlMagick, 661 program + 547 text file = 1208 Too late for the anniversary, but OP said 'animated GIF', so... TL;DR: [a link to animated GIF (5 Mb, 480\*240, 1360 frames)](https://drive.google.com/file/d/0Bxkg1eqq0xXxdDNVdWhsVkpLckE) (there's a false start each time I try this link now - it's not in the file, maybe try to download it first. And some slight flickering... maybe I'll explain it later, - not a piece of cake, the whole IM and GIF idea ;) ). With newlines and indentation for readability: ``` use Image::Magick; $i=Image::Magick->new( depth=>8, page=>'480x440+20+0', background=>'#000', fill=>'#ff0', font=>'UbuntuMono-R.ttf', pointsize=>22 ); $i->Read('text:-'); $j=$i->Clone; $i->Extent(y=>-440); for(1..680){ ($i->[2*$_]=$j->Clone)->Extent(y=>$_-440); ($i->[2*$_-1]=$i->[2*$_]->Clone) ->Composite(image=>$i->[2*$_-2],compose=>'Blend',blend=>50) } $i->Distort(method=>'Perspective','virtual-pixel'=>'Background', points=>[0,0,180,180,480,0,300,180,0,420,0,420,480,420,480,420]); $i->Extent(geometry=>'480x240+0+200'); $g=Image::Magick->new(size=>'480x150'); $g->Read('gradient:#000-#fff'); $i->Composite(image=>$g,compose=>'Multiply'); $i->Set(delay=>10,loop=>0); $i->Animate() ``` It reads text from STDIN, but geometry is hard-coded, so probably any other text would not be a good idea. It could be shorter, but I added fading to the text as it gets to the top, and, moving up by single pixel resulted in a choppy animation, so I did some interpolation. It eats 2.2 Gb of RAM and takes 2-3 minutes on a 8 y.o. desktop (and probably won't work for Windows folks), so here's how to get a GIF: replace (or add to) the last line (creates 200+ Mb file): ``` $i->Write('out.miff') ``` And then run ``` convert -size 8x1 gradient:black-yellow palette8.png convert +dither out.miff -remap palette8.png out+.gif convert +dither out+.gif -layers optimize out++.gif ``` Trade-offs between quality (palette size etc.) and final GIF size are obvious. Calling `$i->Remap` from PerlMagick directly doesn't work, there's probably a bug, it takes hours long as it (I think) tries `+remap` first. Actually, reasonable (only slightly bigger) GIF size can be achieved without global palette but using `$i->Quantize` which reduces each frame local palette to required size. Oh, and without any palette optimizations i.e. saving GIF from above script 'as is' produces about 9 Mb GIF file. ]
[Question] [ ## Background [**Elias omega coding**](https://en.wikipedia.org/wiki/Elias_omega_coding) is a universal code which can encode positive integers of any size into a stream of bits. Given a positive integer \$N\$, the encoding algorithm is as follows: 1. Start with a single zero in the output. 2. If \$N=1\$, stop. 3. Prepend the binary digits of \$N\$ to the current output. 4. Let \$N\$ be the number of digits just prepended, minus one. Go back to step 2. In Python-like pseudocode: ``` n = input() s = "0" while n > 1: # bin(n) is assumed to give a plain string of bits, without "0b" prefix s = bin(n) + s n = len(bin(n)) - 1 output(s) ``` ## Illustration The number 1 gets encoded into a single `0`. The number 21 gets encoded into `10100101010`, or `10 100 10101 0` in chunks, where each chunk is added to the output stream in the following order: first "0" by default, then the binary of 21, then 4 (the bit length of 21 minus 1), then 2, then stop. ## Task Given a positive integer \$N\$, output its Elias omega code. You can take the input number \$N\$ in any convenient format, including its representation in binary. The output must be a valid representation of a flat stream of bits, which includes: * a plain string or array of zeros and ones, or * a single integer whose binary representation corresponds to the stream of bits. Outputting the bits in reverse or outputting a nested structure of bits (e.g. `["10", "100", "10101", "0"]` for 21) is not allowed. Shortest code in bytes wins. ## Test cases ``` N => Omega(N) 1 0 2 100 3 110 4 101000 5 101010 6 101100 7 101110 8 1110000 12 1111000 16 10100100000 21 10100101010 100 1011011001000 345 1110001010110010 1000 11100111111010000 6789 11110011010100001010 10000 111101100111000100000 1000000 1010010011111101000010010000000 ``` This is OEIS [A281193](http://oeis.org/A281193). [Answer] # [Dodos](https://github.com/DennisMitchell/dodos), ~~96~~ ~~91~~ 90 bytes ``` > > E + > E E - + L B > B B B + L H + H L > > - H H - - + > - dip + dot > dab ``` [Try it online!](https://tio.run/##JYsxDoAgFENneoruhEEPwEBCwsAlNH9hwkTv/y06vbR9tWnzdg@ZmRUhMkOoTIzsLNBQIJQvt2U0dNVrSVDR5Kb/Kdi4EIX5QIodp7vv2ws "Dodos – Try It Online") I've re-discovered this crazy and wonderful language today, so I've wasted two hours building this :D ### Explanation Dodos programs are composed by a series of function definitions, each non-indented symbol here is a function name and the indented lines following the symbol are the definition (the first 2 lines are the definition of the main function). Each function takes a list of number as input and produces new list by concatenating in a list the outputs of the definitions of each line. Each line can be interpreted as function composition, where `F G H` means `F(G(H(input)))`. Recursion is where the crazy part really start: if while computing a function `F(x)` we try computing `F(y)` for any `y≤x`, then Dodos surrenders and returns the input unchanged. This prevents infinite recursion from happening, and it is the only form of conditional branching in the language. It can take a while to enter the right mindset to write anything in Dodos ^^" So, starting from the bottom let's see what these functions are doing: `dab`, `dot`, and `dip` are the only three builtin commands in Dodos, here redefined as `>`, `+`, and `-` to save bytes in the rest of the program. `dab` returns the input list without the first element; `dot` sums all elements of the input list (and returns 0 if the list is empty); `dip` subtracts 1 from each element of the list **and then takes the absolute value of each element**: negative numbers don't exist in Dodos! Any time we try to subtract 1 from 0 we obtain 1 as a result. I had originally written much more about the rest, but this post is long enough as it is, so I will only provide descriptions of the input/output of each function. Trying to understand how each function works can be a good exercise, but if you want more information leave me a comment and we can discuss more in chat :) `H` - Input: a number `n`. Output: `n%2` followed by (0 repeated `n//2` times) `L` - Input: a list of 0s and 1s `l`. Output: `[tail(l),tail(l) with each bit flipped]` (hint: `+ L` will compute the length of `l` - 1) `B` - Input: a number `n`. Output: the binary representation of `n`, with a leading `0` `E` - Input: a number `n`. Output: the Elias omega coding of `n`, with an extra leading `01` and missing the trailing `0`. `main` - Input: a number `n`. Output: the Elias omega coding of `n`. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~16 13~~ 11 bytes ``` ṁḋ↔Θ↑←¡ȯ←Lḋ ``` [Try it online!](https://tio.run/##yygtzv7//@HOxoc7uh@1TTk341HbxEdtEw4tPLEeSPkARf///29kCAA "Husk – Try It Online") Outputs a flat boolean array. -2 using the idea from Jonathan Allan's answer. ## Explanation ``` ṁḋ↔Θ↑←¡ȯ←Lḋ ¡ȯ create an infinite list using: Lḋ length of binary digits ← decremented ↑ take the longest prefix with: ← elements that aren't falsy when decremented(1) Θ prepend 0 to that ↔ reverse ṁḋ convert each to binary and flatten ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly) Is there a trick to make for shorter code? ``` BL’ƊƬṣ1UBF ``` A monadic Link accepting a positive integer which yields a list of ones and zeros. **[Try it online!](https://tio.run/##y0rNyan8/9/J51HDzGNdx9Y83LnYMNTJ7f///2bmFpYA "Jelly – Try It Online")** ### How? ``` BL’ƊƬṣ1UBF - Link: n e.g. n=12 Ƭ - collect up starting with n until no change: Ɗ - last three links as a monad: (3) (1) (0) B - to binary [1,1,0,0] [1,1] [1] [0] L - length 4 2 1 1 ’ - decrement 3 1 0 0 <- 0=0: stop } -> [12,3,1,0] ṣ1 - split at ones [[12,3],[0]] U - upend [[3,12],[0]] B - to binary [[[1,1],[1,1,0,0]],[0]] F - flatten [1,1,1,1,0,0,0] ``` [Answer] # JavaScript (ES6), 50 bytes ### With `.toString(2)` ``` f=(n,s=0,b=n.toString(2))=>n-1?f(b.length-1,b+s):s ``` [Try it online!](https://tio.run/##dZBdDoIwEITfPQWPbeRnFxHQBD2EJwAExJDWUOL1EQsxdIt97Hydzswzf@eq7NvX4Al5r8axzphwVQZukQl/kLehb0XDQs6zi/DwWrPC7yrRDA8P3WKv@FmNpRRKdpXfyYbVDB19OHeCwIGdKYZrEYHKB0NGKkfm6@k9JY6UsDxiQtghEkpYHqkZ85uDIhiayEZWjGkbbWRNhja20Wu6J71wcaQbR0caXhtq2jYFk0V9YKtynKQnUhnnqMsXG@Zg8MsH8GeJ@RLMwdaBfhMCjB8 "JavaScript (Node.js) – Try It Online") ### Without `.toString(2)` ``` f=(n,i,q=n*2>>i)=>n>!!i?q?f(n,-~i)+q%2:f(i-2,1):'' ``` [Try it online!](https://tio.run/##dZDNDoIwEITvPgUeDFRBdit/koDPYtSaGlJEjEdfHbEQQ7fYY@frdGZux9exPT3k/Rmo@nzpOlF4ypd@U6g1L0vJilKVy6U8NAfRC8Fbsk2z4rnwZMB9ZLnrdqdatXV12Vb11RMeOvow5oShAwtT5FMRgco7Q0YqR@br/j0lYkpYHgkh7BApJSyPzIz5zUER5CYykxUT2kYbWZOhjc306u9JLxwd6cZRTMNrQ03bpmCyqA/MVU7SbE8q4xB1/GLGHAx@/AD@LDFcgjnYNNBvQoDuAw "JavaScript (Node.js) – Try It Online") [Answer] # [J](http://jsoftware.com/), 29 28 bytes ``` 1;@}.1#:&.>@|.&|.<:@#@#:^:a: ``` [Try it online!](https://tio.run/##pdNNCsIwEAXgvacYLBgFG2Zq1Rp/CAiuXHkAQcQgbryAnj1Go9a2SalNS2lWXx8zrxfd5UzBUgCDISAI88Qc1rvtRtNc3jlFosdX8sZ7N74QMpKR2IuD0IPO6Xi@ggJK7Ikx@@4PcQAQCwi6jPs5WpZMMAxzFSRlk8LNUTWnzdpaVpC6TQoxxy6TwnJO3GZQzml1R595tlQVZC6TwkxKPHvP0/5pG3NSY7ZqgOk8efZOpbyNXZMT0bejPGmuN5DNf5SO3Sb93PhPF1450bN3Ksy0mL1GNp2fZjOnWcyLzbtgc6K/S74JVPv2/c7bfKr6AQ "J – Try It Online") This approach, which I prefer to the strightforward recursion, is thanks to [Jonathan Allen's nice idea](https://codegolf.stackexchange.com/a/219114/15469). -1 thanks to Bubbler * `<:@#@#:^:a:` Iteratively convert to binary `#:`, get size `#`, and decrement `<:`, keeping track of results `a:`. * `1...&|.` Reverse both arguments `&|.` (1 on the left, and the output of the previous step on the right). A golfy way to include the constant 1 (which is unaffected by reversal, and which we'll use in the next step) while reversing step 1's output. * `|.` Rotate by 1. So now we have the output of step 1 reversed and rotated left by 1. Importantly, the `0` is now in the correct place all the way on the right, though we still have a stray `1` at the beginning... * `#:&.>@` Convert to binary `#:` under open `&.>`. A golfy way to convert every element to binary and box it. * `1;@}.` Kill the first element `1...}.` (the stray `1`) and raze `;` (unbox so we have a single list of numbers) ## [J](http://jsoftware.com/), 29 bytes (recursive approach) ``` 0&g=.((,~g<:@#@])#:)`[@.(1=]) ``` [Try it online!](https://tio.run/##pdPBCoJAEAbge08xJLQKusxYqS0JQtCpU9cIgmiNLr1Br25bm5m5G@Yq4p4@f2Z@L9WYMwm5AAYhIAj1RBxW2826wkmZc98Pb@VSFF6xDzwRHHYF9ynfB1UwOh3PV5BAsT4xpt8IEAlwuhRaH7VJSnV0JcTfJrmb025OnXWwLGFmNsnFnJtMcsuZmE2nnGl3R/U8B6oSMpNJbibFlr03af@0lZn8MAc1QHWeLHunr7y9XZUT0bajJmmj95DVfzSbm036uPGfLjxzomXv1JppO/sPWXU@zRZGs50X@3dB50R7l2wT6Pbt/Z2X@VCrOw "J – Try It Online") -3 thanks to Bubbler's realization we could 1-line it Straightforward implementation of the recursion formula. [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 70 bytes ``` D,f,@,BBBFJ D,g,@,bL1_ +? n:x y:'0' Wn,`s,$f>x,`x,$g>s,`y,s+,`n,x-1 Oy ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ03HQcfJycnNi8tFJx3ITvIxjOfStufKs6rgqrRSN1DnCs/TSSjWUUmzq9BJqNBRSbcr1kmo1CnW1knI06nQNeTyr/z//78FAA "Add++ – Try It Online") Add++ isn't too golfy. `f` is a function that converts its input to a binary string. `g` gets a string and returns it's length minus one. We then set **x** and **n** equal to the input, and **y** equal to the string `'0'`. Now, we enter a while loop, looping while **n** is non-zero. The loop has the following steps: * Set **s** equal to `f(**x**)` * Set **x** equal to `g(**s**)` * Prepend **s** to **y** * Set **n** equal to **x - 1** Finally, output **y** [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), `d`, ~~15~~ ~~13~~ ~~11~~ ~~10~~ 9 bytes ``` ≬bL‹↔1€Rb ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=d&code=%E2%89%ACbL%E2%80%B9%E2%86%941%E2%82%ACRb&inputs=12&header=&footer=) ## Explained (old) ``` ≬bL‹↔1€Rb ≬bL‹ # lambda: len(bin(argument)) - 1 ↔ # generate_until_no_change(^, input) 1€ # ^.split(1) R # map(reverse, ^) b # bin(^) # `d` flag: deep_sum(^) ``` [Answer] # [Perl 5](https://www.perl.org/) `-n`, 58 bytes ``` while($_>1){unshift@a,$_=sprintf"%b",$_;$_=y///c-1}say@a,0 ``` [Try it online!](https://tio.run/##K0gtyjH9/788IzMnVUMl3s5Qs7o0rzgjM63EIVFHJd62uKAoM68kTUk1SQnItQaKVOrr6yfrGtYWJ1YClRj8/29k@C@/oCQzP6/4v66vqZ6BocF/3TwA "Perl 5 – Try It Online") [Answer] # [Rust](https://www.rust-lang.org/), ~~129~~ 87 bytes ``` |mut n|{let mut s=0.to_string();while n>1{let b=format!("{:b}",n);n=b.len()-1;s=b+&s}s} ``` [Try it online!](https://tio.run/##jZFBj4IwEIXv@ytGDqbNuqbjIuqS@lcMJHUlgZqlNR6Q345QKsXLtpxK8r33Zt7UN6W7s4QqKySh0EApNAjg3aO6aZCPZvgfnoqztb6elK4L@Utoer8UpQB5REPk/Hytq0wvSNT85G20kjSVPF@Xonf9wlTx/HOpWtV26QdkSolan8TfgjhVrwFBkNIVRCyi/2MbgyHzgt8jiF4wto69p5fdTqzfN3mxAcPuJtbvu7eLDfN6Ydy86JD1MHFdGHv/OXCuCKmlB10xaIO8x4y3s61NkFEGhDEnRPOxoOKS3f4wqw7H5Wx4SCxzapvNQksdKfZ2i/ns03VGq7Z7Ag "Rust – Try It Online") My first Rust answer! ~~(and first time appeasing the Rust compiler gods)~~ A straight translation of the algorithm in the main post. Ungolfed: ``` fn e(mut n: usize) -> String { let mut s = "".to_string(); while n > 1 { let mut b = format!("{:b}", n); n = b.len() - 1; b.push_str(&s); s = b; } s+"0" } ``` * -42 bytes from @Bubbler through a closure and miscellaneous golfs [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~25~~ ~~20~~ 18 bytes -2 bytes thanks to coltim ``` 1_,/|0,2\'(#1_2\)\ ``` [Try it online!](https://tio.run/##JcbLCYAwEEXRVh64SAIRZyZfrSWQXVwIqcDeR9TNPfda5zlVx8Hdbzd5acYu3KW5psNYhiAgIiGjoIIFnCEMJkKI6ZWQS92/o79EDvoA "K (ngn/k) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 39 bytes ``` f=->n,s=?0{n>1?f[/.$/=~x="%b"%n,x+s]:s} ``` [Try it online!](https://tio.run/##VU/LDoIwELz7FRuj4WCFLvJQk8KHNMSogXiqhmKCQfx1hLIF7WlmZ3Z2Wj4vr64rxDZRTIuUNyrBtJCeu/LEpxbL9WW5Vqze6Oyo206CRAY8YwsA6TNATnjXYyQcDPNeIRqO1KqRodNiPFKr7oecYZc4@mYwp2FE6cZkm@A0nA/1lE4h2alqENojxm7EaYWThubxnypRvD/YMjgeooh5mZOBEvh/zRHz@QO/R6Yv9e5F5ubn6w0aeCsG@Rsez0pDCQIKqTI2IAG5W91PmoHjQNt9AQ "Ruby – Try It Online") Recursive function that takes \$N\$ as an integer. A regex match returns the index of the last bit in the binary representation of \$N\$, which is equivalent to one less than the bit length of \$N\$. [Answer] # [Zsh](https://www.zsh.org/), 50 bytes ``` <<<${${1#?}:+`$0 ${$(([#2]$#1-1))#??} ''`}$1${2-0} ``` [Try it online!](https://tio.run/##qyrO@J@moanx38bGRqVapdpQ2b7WSjtBxUAByNPQiFY2ilVRNtQ11NRUtrevVVBXT6hVMVSpNtI1qP2vycWVpmAIwgYgAsICMw3AbKgwVBzEgZsJ4gMBxNT/AA "Zsh – Try It Online") Neat recursive solution ``` <<<${${1#?}:+`$0 ${$(([#2]$#1-1))#??} ''`}$1${2-0} $1 # N ${2-0} # $2, unless it is unset; then substitute "0" ${${1#?}:+ } # If after removing ?any digit from $1 there is something left, then substitute `$0 ` # Backtick subshell, $0 is the current program ${$(([#2]$#1-1))#??} # Take the #length of $1, subtract one, substitute as 2#binary, remove the "2#" '' # Add empty second argument to cause ${2-0} to substitute nothing on recursion <<< # Print to stdout ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~57~~ 56 bytes Saved a byte thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! ``` f=lambda n:n>1and f(len(f'{n:b}')-1)[:-1]+f'{n:b}0'or'0' ``` [Try it online!](https://tio.run/##bVHBboMwDL3zFRaXEC1IMdDSRaU/0vVAIaioXUCQSdsqvp2FEFg7zRc/vzw/R3b7pS@Nisexym75@7nMQQl1wFyVUAU3qYKK3JU4D4SGSI8ixNOLYzhpOsLJqGWve8ggQAYRg5hBwmDDYMsgZbBjgIZFU0VGgJwbSbKxyMBtunudMXeJc@rJz1YWWpaTq899Br55sgldNUkXtHK4cosOraWDjz18nvVQPvmgU/yaWIFlVw5t8D8jcLZyLSvvGvg/k5@M1q8ZCfWKiyyuspv2QN4@ojQpCAOLMCbUq5oONJNQK/iu28BegsGyPSo8MDHdpgo0tUXb1UpPN9Vinw4QHuDei32MA9zdrKPMsv5k7j3@AA "Python 3 – Try It Online") Inputs an integer and returns a string. [Answer] # Scala, 74 bytes ``` x=>{var n->r=x->"0";while(n>1){val b=n.toBinaryString;r=b+r;n=b.size-1};r} ``` [Try it online!](https://scastie.scala-lang.org/x6baD4erTouPj04TjyqdsQ) So this is a bit embarrassing: the imperative version is 13 bytes shorter. # Scala, 87 bytes ``` Seq.unfold(_){n=>val b=n.toBinaryString;Option.when(n>1)(b,b.size-1)}./:("0")(_.++:(_)) ``` [Try it online!](https://scastie.scala-lang.org/uB4DEWGBQdG4wKQJuWtj7w) [Answer] # [Japt](https://github.com/ETHproductions/japt), 19 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` @=¤T=U+T U=ÊÉ}f Tj0 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QD2kVD1VK1QgVT3KyX1mClRqMA&input=Njc4OQ) ``` @ ... }f - return first falsey value returned by @ =¤ - convert input(U) to binary T=U+T - append to variable T(initially 0) U=ÊÉ - returns lenght -1 and assigns to U Tj0 - discards first bit of T and implicitly print ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~87~~ 86 bytes ``` l,a;g(n,b)char*b;{l=1;for(*b=48;n>1;n=a)for(a=0;bcopy(b,b+1,++l),*b=48+n%2,n/=2;)a++;} ``` [Try it online!](https://tio.run/##VVFRjoIwEP3vKSYmJq2MsUVENl08gnsA1w9AYEmwGNBNdg1nZ9uCwPaj7cx7M@9Nm6yTMlJ515UYyZwqjFnyFdWrWD7LUMisqukqDr1AqoOQKoyYyUQhl3FS3X5ojLEj0HFKhpbmqKWLahO6kkWOI9vuuyoucE@bO4VC3UEBexIwChA/siytTyA4hzOE8AQOrSSQU83CAQamM7dal2Z0sbzA@gDL5lMtENSLohktIbb549qcbCuBLm7Rwx36uMcAhYvCR1egFsOttzMnR38fvNkb73fOtT65RoUCamzqUaG3XeimHKQ@36EpftMqo0aMbYZAc5iGHacARmCY19rRJWczRNsdwazwAB/XNI/okREBw@LEfV21EbIdA8GJNyHGJNnNY437s9gU7@exxoOpmR2SCHdK2I7Cnyv0L0Fc8T9ptcxXTVpiYBP9oHMJS7aYKeATIuzqFYh5/JkN0UsM5baQj@hQzEd3w3dNluetxyE4/wM "C (clang) – Try It Online") * saved 1 thanks to @ceilingcat suggestion of using Linux bcopy instead of memcpy. * function tacking a number `n` and a buffer `b`. # Explanation * `l` length of result, used to shift the buffer. * `a` length of current `n`. * second for loop shifts the buffer by one and push next bit at the beginning. * first loop resets `n` to length `a` which is already minus 1. * initially we set `l` to 1 and the first bit to '0' [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 bytes ``` É?T=¢+T,ߢÊÉ:T É? // If input U - 1, aka if U > 1, = // then assign ¢ // U to a binary string +T // plus builtin variable T (initially zero), T // to the builtin variable T. , // Following that, ß // recursively run the application again with a new input of Ê // the length of ¢ // the current input to binary string É // minus one. : // If the initial check was falsy instead, T // we're finished, return the result which is stored in T. ``` [Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=yT9UPaIrVCzfosrJOlQ=&input=Njc4OQ==) [Answer] # [Factor](https://factorcode.org/) + `math.extras`, 73 bytes ``` [ { f } swap [ [ make-bits append ] keep log2 ] until-zero reverse rest ] ``` [Try it online!](https://tio.run/##LU07DoJAFOw9xVwAAviNFpbGxsZYEYoVH0qAZX378Ec4O65gJplPMpnJVCo196fj/rBboyDWVKJSchvIP@diR0cvYWVh6d6QTsnCMIm8DedasJm0CBFhihnmWGCJFaIQYRCg62O0yNDBPpVB7FCpgrxhWRlD@oLEHZNBWV8j5xsteel9iGswPYgtObWCpK/@AyECbF3zl0f2kZakuP8C "Factor – Try It Online") Takes an integer and returns an array of `f`s and `t`s to represent 0 and 1 bits respectively (which is the default bit array representation). `until-zero` is two bytes shorter than `dup 0 > loop`. Also, `make-bits` gives the binary representation in LSB-first order (so `4 make-bits` is `{ f f t }`), so a `reverse` is needed at the end. ``` [ ! A quotation, input: n { f } swap ! Put the initial s="0" under n [ ... ] until-zero ! Repeat until n becomes zero... [ make-bits append ] keep ! Append bits of n to s, and keep n at the top log2 ! Next term (floor of log 2 = bit length - 1) reverse rest ! Reverse s and remove the part representing 1 ] ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ┴P&:ë▄▒ë╙G²╟ì ``` [Run and debug it](https://staxlang.xyz/#p=c150263a89dcb189d347fdc78d&i=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A21&m=2) A generator with a filter. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 54 bytes ``` Rest[#<>0//.a_/;a>1:>Floor@Log2@a<>a~IntegerDigits~2]& ``` [Try it online!](https://tio.run/##LYvLCsIwFET39zcKXV1tEvtSa8hCBMGFj6UUuZS0BmwLbVyJ/fUY1NWcGc60ZO@6JWsqcvXGnfVor0EhWRTN6RatSfKV3D36flCHvhGKCknTvrO60cPWNMaOkyhDd3oabdVxMJ1/z2StgjKcLhV10ws4gkBYIMQICUKKkCHkCNyv3DfhBc6YV@LkSx7TLF/@mP2DMXi7Dw "Wolfram Language (Mathematica) – Try It Online") Returns a `StringJoin` of digits. [Answer] # C (MinGW), 79 bytes Uses `itoa()` which is woefully lacking from the standard, but present on Windows systems. The TIO link therefore contains a shoddy version of that function that only supports base 2. ``` d;f(n){int s[9]={0};d++;n>1&&f(strlen(s)-1,itoa(n,s,2));printf(--d?s:"%s0",s);} ``` [Try it online!](https://tio.run/##XVPtjpswEPwNT7GHlBwOcLHpXe5SmvYRqv5Oo4rjI7WaGISd6tIoz56uDQQDihQ8O7M7u3izaJ9lt@USfpx49gdSkUPOG3UGrqrUJ1BWDeTFsRJSNanilUgPUJ@aupKFfHJR910czpBXhYT3VBYQu9nvtIGFkXOhQITQIjIEfW7SnH8Q9@I6BlbFsd6u17ukOy8UbEDiSXM5/uNbCf6DIK7jGDIPgh1yHumjiWqDPkeAJiDwB8sNxFOyR5m3FTAHthtEbSXgUZSAFixUECDU6lqecUPNa1OoUyO0testT0pfkIu2KLfr3eZCr0keBIn4yubz0sdRHQrhSxKx0MxBhDKMCUnqBiWlH0X5N/nZm0nqhZIk19vfiuewv49LD7sbWvFRm1l1Sm8WMZp7IQiCprSJZIiBP5Pkp8CoVqFP19UZjykXvkmCvk6Zwgal@qXOdeE6CJpBC0zjTOoidHUdQ87wy8qtHqQWXBh0T@hR7xpqKB4gRnvwkwWyHny2mcjt8ZcxfuevRviQ/HWM3/lvdlGdvw@w2A5Yldlq7MiI7o2xadDyhueRN9ap@/6fX8ZWjNhwhgTUZjDzUNv26vVtPbLNWgtdOisRtVhdMjrppj1Qu1W75L15LcDPby2Y3sZ2yTh8Acn/FVXpD5eDwLIHp7eMoCQI9ILtLQFu2BPe9THQ3dvbfw "C (gcc) – Try It Online") [Answer] # Java 8, 77 bytes ``` n->{String r="0",b;for(;n>1;r=b+r,n=b.length()-1)b=n.toString(n,2);return r;} ``` [Try it online.](https://tio.run/##PVA9b4MwEN3zK05MWBzIJglJY5GlU4dm6RhlMMShpOSIjElVIX47NYF2ue97791d1UOF1/PXkFeqaeBdldQtAEqy2lxUruEwpgAf1pRUQO6/uU6hDRCTrtEvnGmssmUOByBIBwr33TxsUo97mMlLbXxJeyFNmgUGKc2iSlNhP30WCpalFNl6WvEJYyaNtq0hMLIf5Ih/b7PK4c80j7o8w83p9Ked4wkUm0SORE45WN3YV9Vo2AHp7/GY46kTGOMSV7jGBDe4RRGjSDAWKDjH5Wo9eo7JZvvyjPhkOe/ZE9u94Kex@hbVrY3ujthW5P8RBd4OvICi/L/C5vf0wy8) **Explanation:** ``` n->{ // Method with Integer parameter and String return-type String r="0", // Result-String, starting at "0" b; // Temp-String, uninitialized for(;n>1 // Loop as long as `n` is larger than 1: ; // After every iteration; r=b+r, // Prepend `b` to the result-String n=b.length()-1) // Set `n` to the length of `b` minus 1 b=n.toString(n,2); // Set `b` to `n` converted to a binary-String return r;} // After the loop, return the result-String `r` ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 50 bytes ``` ^. $.%'*_¶$& +`(_+)\1 ${1}0 /^../}`0?_ 1 ^.|¶ $ 0 ``` [Try it online!](https://tio.run/##XYorEsIwFAD9niOF0Myk76VfFJJLME0QCAyig4NeqwfoxcJAHWZ3xU635/1x1VzY5B0lLtnoDhfFvHQW5BRR7Dnl0WN8sS/jupjd/1aN3ldz2u7Rv9cFDJKzEqhpaOnoGdCAdgRFRaib9muh64fjr2SjyAc "Retina – Try It Online") Takes input in binary, but link includes test suite with decimal to binary conversion for convenience. Explanation: ``` /^../}` ``` While the input is greater than 1, ... ``` ^. $.%'*_¶$& ``` ... prepend a decremented unary copy of the length... ``` +`(_+)\1 ${1}0 0?_ 1 ``` ... and convert from unary to binary. ``` ^.|¶ $ 0 ``` Remove the last result, join the remaining results together and append a trailing `0`. [Answer] # [R](https://www.r-project.org/), ~~70~~ ~~64~~ 61 bytes ``` function(N){while(N>1)F=c(N%/%2^((N=log2(N)%/%1):0)%%2,F);+F} ``` [Try it online!](https://tio.run/##bZDdCsIwDIXvfYqBFFoUTOr@VOblLvsIyhhzDuYG/uCF@OxzbkOa1Ny1X3JyTq5dUVfZ7dheijJLutOjye9V20ijXs9zVRfS7FGlSS6NWAl9kNIkdVvqnvdvVFtQQuhlqnaL9G1LSfTGUt7cg5lNtEUQKFvbDCnzyVw/SXHAMJsOKeaLI4bZdEx8fXdTjppwxxyGzPsgwe6CTo@Tov@lKXDSolf0A@Z2kBpauRyQRhwK3IBhFG9oQBztTeKOLNjNkzT8zT1@AbmN7eN3LYDuAw "R – Try It Online") To my disappointment, a no-frills iterative implementation of the pseudocode comes-out significantly shorter than my initial [recursive approach](https://tio.run/##bZDbCsIwDIbvfYqBDFqomNQdVNwr7BHUsRODacHDlfjsc3ZDmtTeFPIlf/4/t6Huu@J@Mpe6LbKhyZrntXx05ipyZbLXW5675izyg1alMAqkakR1WPWm1SKX4TrEsZ6Pvz6Kag8yDLUyUkpXVWAwPRksA1i4RDsEgbKNy5CyiMyNkxTHDLPphGK@OGWYTW@Jr@9uylET7pnDhHm3Euwu6PV4KcYqTYGzFr1iFDO3Vsq2cjkgjWgf@AGTdLujAXGyN4t7suA2z9LwN/dUAnIb18fvWgDDBw)... [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 77 bytes ``` param($n)while($n-1){$s=($l=[Convert]::ToString($n,2))+$s;$n=$l.Length-1}$s+0 ``` [Try it online!](https://tio.run/##PYxBC4IwGIbv/oohX7EPU5xHYyF07RDVLUKEpg7WlG3lwfzta3TwPb08z8s7DpMwthdKeWj57MfGNC8KGqdeKhFKynAGyykofj8O@iOMe5Tlbbg6I3UXBrsCMQG7B81BZSehO9enbAGb5H6JQOrx7SzhBBrT2e9mrijUuIoASAwBZeslZufmeZFd7yjLEUl6IEC30JKqxpgskffMs8Kz/J8f "PowerShell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Î[b©#®ì®g< ``` [Try it online](https://tio.run/##yy9OTMpM/f//cF900qGVyofWHV5zaF26zf//RoYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/X@DyuikQyuVD607vObQunSb/7U6/6MNdYx0jHVMdEx1zHTMdSx0DI10DM10jAx1DA0MdIxNTEG0gY6ZuYUlmGUAIQ0MYgE). **Explanation:** ``` Î # Push 0 and the input-integer [ # Start an infinite loop: b # Convert the current integer to a binary string © # Store this binary string in variable `®` (without popping) # If this binary string is equal to 1: # # Stop the infinite loop # (after which the string at the top is output implicitly as result) ®ì # Prepend binary string `®` in front of the current result-string ®g< # Push the length of `®` minus 1 for the next iteration ``` [Answer] # [Perl 5](https://www.perl.org/) (`-l060p`), 51 bytes ``` $\=($,=sprintf"%b",$_).$\,$_=-1+length$,while$_>1}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lxlZDRce2uKAoM68kTUk1SUlHJV5TTyUGSNnqGmrnpOall2So6JRnZOakqsTbGdZW//9vZPgvv6AkMz@v@L9ujoGZQQEA "Perl 5 – Try It Online") [Answer] # [Red](http://www.red-lang.org), ~~119~~ 115 bytes ``` func[n][o: copy"0"until[t: copy[]until[insert t n % 2 n: to 1 n / 2 1 > n]n:(length? t)- 1 insert o t n < 1]next o] ``` [Try it online!](https://tio.run/##TZDLCsIwEEX3@YpBEHQhJrUvg@g/uA1ZlDaxhTIpMQX9@hha0ZnVuQeGy4w3XbybTmlmZbQztgq1chJaN703fDNjGEYV1qz0Ggd8Gh8gAMIWMkDJggOR0jElAVdAjXI3GnyE/gZhf0jyu@OWrQsIjeaVoo7WedO0fbKKQRoByyycET4RzgkXhEvCFeGasMgIl6RLEM/5vzcvqOe/rqo@U88pc860gskPGEBNTZeuq8Cmv@j4AQ "Red – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` ←0W⊖θ«←⮌θ≔⍘⊖Lθ²θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMPKJzWtREdByUBJ05qrPCMzJ1VBwyU1uSg1NzWvJDVFo1BTU6GaixNFcVBqWWpRcSpIzpqL07G4ODM9T8MpsTg1uASoLB1Fv09qXnpJBkipjoIREBcCtdT@/28IBAaGBkBgaAChDQz@65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input in binary. Explanation: ``` ←0 ``` Output the trailing `0`. ``` W⊖θ« ``` Repeat until `N=1`. ``` ←⮌θ ``` Prepend `N` to the output. ``` ≔⍘⊖Lθ²θ ``` Replace `N` with its binary decremented length. 20 bytes for decimal input: ``` Nθ←0W⊖θ«←⮌⍘θ²≔⊖L⍘θ²θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDyic1rURHQclACShUnpGZk6qg4ZKaXJSam5pXkpoCVKmpUM3FiaI4KLUstag4VcMpsTg1uAQok65RqKNgpKkJNILTsbg4Mz0PxQyf1Lz0kgwsynUUQA6p/f/f0AAM/uuW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `N`. ``` ←0 ``` Output the trailing `0`. ``` W⊖θ« ``` Repeat until `N=1`. ``` ←⮌⍘θ² ``` Prepend `N`'s binary representation to the output. ``` ≔⊖L⍘θ²θ ``` Replace `N` with its decremented binary length. ]
[Question] [ In the US, clothing size sometimes has rough designations like M, L, XXL, etc. The US designation of the "men's jacket" category depends on the height of the person. So, in this challenge, you should implement this conversion, which is defined by the following table, taken from [this site](https://www.blitzresults.com/en/mens-clothing-sizes/): ``` US size Body height (cm) XXXS 160 - 164 XXS 162 - 166 XS 166 - 170 S 168 - 173 M 171 - 176 L 174 - 182 XL 180 - 186 XXL 184 - 189 3XL 187 - 193 4XL 191 - 194 5XL 193 - 198 6XL 197 - 200 ``` \* I chose the "men's jacket" category from there because it has the most variability ### Input Body height, in cm. As a number or a string. ### Output Size designation - as a return value or printed. ### Additional rules * For some sizes, designation is uncertain (e.g. 174, 175 and 176 correspond to both M and L) - your converter should return one of these, deterministically or not * If it's easier, output fully spelled versions like XXXXL instead of 4XL; however, 2XL and 2XS are invalid (apparently they are used in real life, but I decided to forbid them because I thought they weren't) * Assume the input is valid, i.e. a whole number between 160 and 200 [Answer] # [Python 2](https://docs.python.org/2/), ~~58~~ ~~55~~ ~~52~~ ~~49~~ ~~47~~ 45 bytes -13 bytes with great contributions from [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) (thanks!!!), [xnor](https://codegolf.stackexchange.com/users/20260/xnor) and [xash](https://codegolf.stackexchange.com/users/95594/xash). Switched from Python 3 to Python 2 for an extra 2 bytes. Tried to profit from the overlapping regions. You don't even need a size M, because the sizes of S and L don't have a gap between them. Luckily, the number of X's for S and L can be expressed as a linear integer expression. ``` lambda h:max(173-h>>2,h/3-60)*'X'+'SL'[h>173] ``` [Try it online!](https://tio.run/##bdDNbsIwDADgO09hTkm2wJoU9QctvABsHNih0sahE@1SiRbUdNIY4tk7J6WskxapUvTZsV0fT40@VLLN1Vu7T8v3XQp6XqZfVIT@RC8WkusHfxJ47I4k5J5sVuRVLzC2bU3xnRl1HgEeKgKPi2DG5kCSJNkQ3rNEDjoeaMBF6DkdYIToW/y1UKC550@EA/Q64yKSVlcDjXCCqGv1h21y3E1gveeQi9i/zru6NYyxYdz/xtB99Kj3YSDk0vNuARe5jEb5oQYNRQV1Wn1kbj3g8tyzIoe0OlHcpNICrzvQj0pLd8upZkoZsBWoFhy0ZByMreU2Pi2arDSUba@17Kkz87lvQAFZL4nTbG@y/@LP6xdYL8fjcZd2rIuqAZLT84Vh@HyZ40em2LtMG6q5m4Zf37P2Bw "Python 2 – Try It Online") Just for fun (and for educational purposes) the original 58 bytes submission: ``` lambda h:(-h+173)//4*'X'+'S'if h<174else(h-180)//3*'X'+'L' ``` [Answer] # JavaScript (ES8), 50 bytes This version is derived from [the method used in Python by agtoever](https://codegolf.stackexchange.com/a/214807/58563). ``` n=>'SL'[q=n/87>>1].padStart(q?n/3-59:177-n>>2,'X') ``` [Try it online!](https://tio.run/##VdFLj4IwEADgO79iQoy08cXDpaCCJ0/rxgQuREIi8bHZjSmKZi@E385OafHRQ9P2S2em09/8L7/ty5/LfcSLw7E5BQ0PQiNeG@k14BOPhaGVjS/5Ib7n5Z1cl3zijD78mcXYiIehPTQSgzbxFgKoNAA9SZJYBxwzSMFyzSFOU8iG0iQps4W5nSlS5qIxU1lHyjxhjrKvN2OWsC7m@t2maJ7d5Vu/5vNEnd6jlg6ltff8hymUxtB852kSW/NFLf70xVqU5gjzXk2gNIxpm/h2rZ5r2qkoCcfmYivnwGERCMPVYEDbhu8LfivOx/G5@Ca7XsVr6FWkPN7wyolwSsXXrfiBMFoD6VXxNkXMoN/HYGEAap@a6mjxPLIyWIK@@RRl6aso2kR6TXd0rtXNPw "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 61 bytes ``` n=>'6543X LMS X3'[i=59-n/3.4|0].trim()+(i<6?'XL':i>8?'XS':'') ``` [Try it online!](https://tio.run/##RdDBjoIwEAbgO08xIca2UVm0iICgJ0@LMZELkZBoVDZs3GLA7IXl2dmpFrmQ8k37Tzvfp99TdS7z@2Miisu1zYJWBCtizy0eQ7iNIOYkyYO5OxEf3LD@zNR4lPkPZSOa@/aaxCHx8pWDi4h4hLA2OkAAtQag8zjSwYMEprY5xo8F6Vh63PtMut05snIbfWEql6zckc6Vb9@@mErvcsLeLXRn1uWHXb4j7@O8@8rCy5/7XeW89wW62/W13u7Kvm73rnnvXLqj3O4dc2YmvktrlpqWFSUVOCwczxIE@IGs4Wo0Ys8BngtRFbercSu@6HFQiwYGNS2vFR7JqGDMuJ8uG3GhFmuADurokGAxheEQw1YBqP/EVOT3NE1hDfruU15L3@z3u73esCNbak37Dw "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 82 bytes ``` lambda x:"3XXSMLXX3456XXS LXXXXXSS LLLLL"[~-x/3-53-x/177-x/189+(x==195)::12] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCSsk4IiLY1yciwtjE1AzIVFBQAHKAIBjEBHJAQCm6TrdC31jX1BhIGZqbg0gLS22NCltbQ0tTTSsrQ6PY/2n5RQqZCpl5CkWJeempGoZmBjoKRgaGmlZcnAVFmXklCpk6CmkamZr/AQ "Python 2 – Try It Online") -2 bytes thanks to ovs [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 36 bytes ``` {"XSL"(&0|(-4!x)|-3!-7-x),1+0>x}173- ``` [Try it online!](https://ngn.codeberg.page/k/#eJytT01rg0AQve+vGCUkijF1o3HV0NJT6cGevAhNYYXoZiHRoEbM13/vxBgKuYSWwr43wzLvzZssOKpxFKra0DpppqO0+sm0FZOZrT6mhvXSnimzTUJEcBrwKI7jCyH4Bw95GOOzETOE+6rRmW8s2MJzPZ9SXx8RklXykFYBR2HEO0Q86rQxvg5X6vlW4pCIR1LVjkOVq07Hs45dZLKR+Xsqxap+K8oIPQLqWkDdKcJFeEAZRThAPfz3LpUB9fHPtxGMbJL23sC5ihkKGA4x7D009C7V74U443swtSzSZMH1cMXQ7tPM79110ohA/GKclFZgaNlIzuXlNENxqE4Gn8On47F93p8Ow/Y82Y+bDPgAu1FpEVCzAJL1Gopdvd3VFSRlCk2ylkvo9kJWlLDqtlR4qDWZ4BVqL6thnSZVDUWe9nqQ6JCDzH8sOod6lcK2LBq5TJe9nfqFaTExxcTiUWJxS0xxtfhbYvEfiSn5BpLj8Sg=) Adapted by @ngn from [@agtoever's python golf](https://codegolf.stackexchange.com/a/214807/98547). # [K (ngn/k)](https://codeberg.org/ngn/k), 51 bytes ``` |$`SXXX`SXX`SX`M`L`LX`LX3`LX5`LX6@(159+\7\8689119)' ``` [Try it online!](https://ngn.codeberg.page/k/#eJytT01rg0AQve+vGCUkijF1o3HV0NJT6cGevAhNYYXoZiHRoEbM13/vxBgKuYSWwr43wzLvzZssOKpxFKra0DpppqO0+sm0FZOZrT6mhvXSnimzTUJEcBrwKI7jCyH4Bw95GOOzETOE+6rRmW8s2MJzPZ9SXx8RklXykFYBR2HEO0Q86rQxvg5X6vlW4pCIR1LVjkOVq07Hs45dZLKR+Xsqxap+K8oIPQLqWkDdKcJFeEAZRThAPfz3LpUB9fHPtxGMbJL23sC5ihkKGA4x7D009C7V74U443swtSzSZMH1cMXQ7tPM79110ohA/GKclFZgaNlIzuXlNENxqE4Gn8On47F93p8Ow/Y82Y+bDPgAu1FpEVCzAJL1Gopdvd3VFSRlCk2ylkvo9kJWlLDqtlR4qDWZ4BVqL6thnSZVDUWe9nqQ6JCDzH8sOod6lcK2LBq5TJe9nfqFaTExxcTiUWJxS0xxtfhbYvEfiSn5BpLj8Sg=) `bin`s the input, using a reduced subset of the available sizes to reduce the byte count. * `(...)'` run a binary lookup of the (implicitly provided) height against the list of heights; this returns the index of the first value equal to or larger than the input * `(159+\7\8689119)` a compressed version of `160 163 166 171 177 183 187 193 198` * ``SXXX`SXX`SX`M`L`LX`LX3`LX5`LX6@` index into the list of sizes * `|$` convert to string and reverse the characters The sizes with heights unique to them are: * `XXXS` => `160 161` * `XXS` => `165` * `XS` => `167` * `L` => `177 178 179` * `XL` => `183` * `3XL` => `190` * `5XL` => `195 196` * `6XL` => `199 200` The only heights not covered by these sizes are `171 172 173`, which can be covered by either `S` or `M`. `M` is preferable, as it minimizes the differences between successive items of the list of heights. The other cutoffs between sizes were similarly chosen. [Answer] # [J](http://jsoftware.com/), 49 bytes `M` is not needed, and the Xs are written out. ``` (+/\157,6 7#4 3)&(('X'#~0>._1+5|@-I.),'LS'{~5>I.) ``` [Try it online!](https://tio.run/##PY9dS8MwFIbv8yteNjCJ7bKk62dmiyAIQtVhbwLdWEQcKmPezKuV/fV6uk0hz/l4z3tC8tWPFN@gtOAIoWGJicLdS33fi2C6NEkWpsjGMWbySgju@PioK7U2QdLdTh6UDHnd8MMxqajuJWO70jrnGn@i8Y1/9LV3dE6cwyX@JVezfWnXEdolTKqJmIiI9Ew2aDnlGWGIQSNPTp6cZjn1@dAXRAZTkK8gXxFfatotMkRas9fttrQ7hAo3I4M9Y@9vH98Qzz97/@QX2i@MX0QyFJv5ao7WdkocFDoL2pMYHyEqHOy/IFp7PUWEyk7p6Z0KJV2qV3KksRq@Enyq2LD@Fw "J – Try It Online") Prints the table with all possible outputs. First column is the `f(n)`, followed by `n`, followed by the possible sizes for `n`. * `157,6 7#4 3`: `157 4 4 4 4 4 4 3 3 3 3 3 3 3` * `(+/\…)&f` `157 161 165 169 173 177 181 184 187 190 193 196 199 202` are the intervals `…,x_0], (x_0, x_1], (x_1, x_2], …`. * `'LS'{~5>I.` get the interval index of `n` – if it is less than 5, then S, otherwise L. * `('X'#~0>._1+5|@-I.),` interval index, subtracted by 5 (…, XS is -1, S is 0, L is 1, XL is 2, …), absolute value, take `max(n-1, n)` to lower the L side by one. Take this amount of X's and prepend it to the S/L. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~37~~ 36 bytes Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for -1 byte! Looking at some answers in practical languages, this seems way too long. ``` ‘—ŽS‘.sR…MLX`6׫ηí)˜IŽ6lbS3+.¥Ƶz+›Oè ``` [Try it online!](https://tio.run/##AUUAuv9vc2FiaWX//@KAmOKAlMW9U@KAmC5zUuKApk1MWGA2w5fCq863w60py5xJxb02bGJTMysuwqXGtXor4oC6T8Oo//8xNzU "05AB1E – Try It Online") or [See all outputs](https://tio.run/##AVUAqv9vc2FiaWX/NDFMIDE1OSt2eT8iIC0@ICI//@KAmOKAlMW9U@KAmC5zUuKApk1MWGA2w5fCq863w60py5x5xb02bGJTMysuwqXGtXor4oC6T8Oo/yz/) This uses the following lookup table: ``` XXXS 160 - 162 XXS 163 - 166 XS 167 - 170 S 171 - 173 M 174 - 176 L 177 - 179 XL 180 - 183 XXL 184 - 186 3XL 187 - 190 4XL 191 - 193 5XL 194 - 196 6XL 197 - 200 ``` `"SXXX"ηíR…MLX`6׫ηí)˜` generates all possible outputs, `IŽ6lbS3+.¥Ƶz+›Oè` selects the correct one. ``` ‘—ŽS‘ # dictionary string "XXXS" .s # take the suffixes ["S", "SX", "SXX", "SXXX"] R # reverse the list ["XXXS", "XXS", "XS", "S"] …MLX # push string literal "MLX" ` # push each character to the stack 6× # repeat "X" 6 times "XXXXXX" « # concat with "L" "LXXXXXX" η # take prefixes ["L", "LX", ..., "LXXXXXX"] í # reverse each ["L", "XL", ..., "XXXXXXL"] ) # put the entire stack into a list ˜ # and flatten the list I # push the input Ž6l # compressed integer 1577 b # convert to binary "11000101001" S # split into digits [1,1,0,0,0,1,0,1,0,0,1] 3+ # add 3 to each digit [4,4,3,3,3,4,3,4,3,3,4] .¥ # un-delta, cumulative sum with 0 prepended Ƶz # compressed integer 162 + # add to each element # [162,166,170,173,176,179,183,186,190,193,196,200] › # is each item larger than the input O # sum the results è # index into the list of possible outputs ``` --- A port of [agtoevers's Python answer](https://codegolf.stackexchange.com/a/214807/64121) comes in at ~~28~~ 25 bytes in the legacy edition: ``` Ƶи‹i'SƵвI-4ë'LIƵΔ-3}÷'X×ì ``` [See all outputs!](https://tio.run/##MzBNTDJM/W9i6KNgaGqpXVZpr6Sga6egZF/5/9jWCzseNezMVA8GsjZV6pocXq3uU3ls67kpusa1h7erRxyefnjNf53/AA "05AB1E (legacy) – Try It Online") Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for -3 bytes! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~42~~ 26 bytes ``` ≔⁻N¹⁷³θ×X÷±θ⁴×X⊖⊖÷θ³§LS›⁰θ ``` [Try it online!](https://tio.run/##bY47C8IwFIV3f0XodAMRWiqIOBUKEtAi6OBak0sNNFfzaPHfxzjZweVwhu881KP36tmPKTUhmIHgZGgKIOk1xW6yd/TABau2dVbH96uzNxThaiwGKG6FYJJia2ajEToc@ojgMrnh/B/bovJokSJqWPpfhxOs5nyRbqIkjW8ojpdccPCYJzyU3zMZSqnalWk9jx8 "Charcoal – Try It Online") Link is to verbose version of code. Port of @Port of @agtoever's answer, so outputs using `XXXL` etc.. Explanation: ``` ≔⁻N¹⁷³θ ``` Subtract 173 from the input. ``` ×X÷±θ⁴ ``` If it's negative then print a number of `X`s equal to a quarter of the negated value. ``` ×X⊖⊖÷θ³ ``` If it's positive then print a number of `X`s two less than a third of the value. ``` §LS›⁰θ ``` Output `S` for negative and `L` for positive. The resulting lookup table: ``` XXXS 160 - 161 XXS 162 - 165 XS 166 - 179 S 170 - 173 L 174 - 182 XL 183 - 185 XXL 186 - 188 XXXL 189 - 191 XXXXL 192 - 194 XXXXXL 195 - 197 XXXXXXL 198 - 200 ``` Previous 42-byte answer using `3XL` style output: ``` §⪪”{➙✳FI2κ?↓gVK¤↘⸿⊙⁻QR”¶Σ÷N⁺¹⁶²E⁸Σ…426676ι ``` [Try it online!](https://tio.run/##LYzBCoMwEER/RXJaIYVq27TSU7EXwRYhlxy8WA0YiDGkibRfn67YYecxsMP0Y@f6udMxNk4ZDzdfmUF@gFutPBAhBG/NBjRejQl9WHFawURNaEJaQ1Ka8DBBZfxdLWqQmGzwzzC9pAN8Njq8IWM5TR6dhcvWLr@9luU4WyDHnLEzwzGV/nWNMSv2cbfoHw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Implements the following lookup table: ``` XXXS 160 - 161 XXS 162 - 165 XS 166 - 167 S 168 - 173 L 174 - 179 XL 180 - 186 3XL 187 - 192 5XL 193 - 196 6XL 197 - 200 ``` `XXXS` is used for sizes of up to 161, and subsequent sizes depends on how many digits from the substring `426676` can added while the keeping the total less than the input, with `0` digits giving `XXS` and `7` digits (by repeating the initial `4`) giving `6XL`. (It's not possible to repeat additional digits as the 6th digit must be at least 6 but neither of the first two digits can be that high.) [Answer] # [Python 3](https://docs.python.org/3/ "Python 3"), ~~278~~ ~~277~~ ~~260~~ 217 bytes -1 byte thanks to @HyperNeutrino -17 bytes thanks to @SunnyMoon another -43 bytes thanks to @HyperNeutrino ``` lambda x:[c for a,b,c in[[160,165,"3XS"],[162,167,"XXS"],[166,171,"XS"],[168,174,"S"],[174,183,"L"],[180,187,"XL"],[184,190,"XXL"],[187,194,"3XL"],[191,195,"4XL"],[193,199,"5XL"],[197,201,"6XL"]]if x in range(a,b)][0] ``` [Try it online!](https://tio.run/##Nc@9DoIwFAXgWZ@i6QTJHVr@2pL4Bm4uJNgBULSJAiEM@PR4ys/Wr03PPXf4Te@@i5f2cl8@1bd@VGzOy4a1/cgqqqlhritLmQmSWUo8Lm7cEhzBinhxOCOpJLxTgwnxTThJHRO/rtKI0v7rTjwa4ZN2KzjxkzYbCWNycjiGDfH0sKJIYHLmbV3LZjRmY9W9ngEWCG0p7OK3cf5@b56iHmooZCm9lpPa0Jbt@2hkCpufT8PouiloAxeGyx8 "Python 3 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 39 bytes ``` $_=$_<174?X x(57-$_/3).S:X x($_/3-60).L ``` [Try it online!](https://tio.run/##Fcq9DoJAFEThnqewoJAC3OVn516j8QXsbOyoLEyIELTw6V0PxUlmkm95rNOQczmey/EU1V/uu@9@UF2Oh65qbsftbrtOoWquOccUipgitdRRTwMlEhl5EYUTTjjhhBNOOOGEE85whjOc4QxnOMMZznCGc5zjHOc4xznOcY5znHvRhvCbl89zfr1zvUx/ "Perl 5 – Try It Online") With all tests: [Try it online!](https://tio.run/##bdJdb4IwFAbge37FyVInJMioIh8y3C53oVfugsQYsmlRtvERionG4F9npzjUBbgq7dPznqbNWP4zruIjCb2K7z9PJPCyNHNJ8Ewt48WHgzy2BiR4GinaYiJ@xXhg6oo2KytX2nMG74wXk8k8zZkrxUfosUPmQrbnu9cTwfGJkGCpr8pSBTGiKwjTXAL85PgjW2LgtO/7/qK/UsUkNXVNo6ahqC3TEDRDYcy2uRI0JhpLb5kbQWMLM2qZ@Z2xqDDtrNm9MdDYw3Y/N0RtcS67o@cbonZdx@kwV0RtC40z6jINoo7o2TE6zR/CEsLY3eaCqINZQ11XXAnvDPBySZRkINd3JOZP9V4xv00L8OCRhLIguKFZwBeAC19plEAfsEhfheZdICzLm@RFjpJneZQUITy8sWi7Ky6J6xi8KfQGDgfcydYF20ygxx/UOlitUy6F0m@57uV8/h@j1vWxr1LapAkLCny0UbJ1q18 "Perl 5 – Try It Online") Recognising that size M is not needed and that the number of X'es can be calculated from a difference divided by 3. Uses unquoted barewords for S, L and X. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~26~~ ~~25~~ 25 bytes *Edit: fixed bug, same bytes* ``` §:oR'X?_-3<0o?'S'L<1-57/3 ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8VHDMkMzAwUjA4P/h5Zb5QepR9jH6xrbGOTbqwer@9gY6pqa6xv//w8A "Husk – Try It Online") ``` §:oR'X?_-3<0o?'S'L<1-57/3 -57/3 # x = (height/3)-57 §: # now join 2 strings: o?'S'L<1 # string 1: 'S' if x<1, 'L' otherwise ȯR'X # string 2: repeat 'X' ?_-3<0 # if x is positive: x-3 times # if x is negative: -x times ``` [Answer] # [Groovy](http://groovy-lang.org/), ~~74 71 70~~ 64 bytes ``` f={('XXXSXXSXSSMLXLXXL3XL4XL5XL6XL'=~/\d?X*./)[it/3.4-47as int]} ``` [Try it online!](https://tio.run/##VdJBb4IwFAfwO5/i3aSLVhSGuEyXbJcd6ollaeI8NO6p3RAMrS7OsK/uWlAEwsX8eP/3@uo6z7LD8XxeTU5uh3Me2zeOZ4wzzpnPWcDZPWchZ53JX//j84nf0T6ZS933adALRkKBTPWiOMvtLss1fImDoHstE6p0jmJLX7IkwaXOcuU4M7GDg0j2qGACcwcuT9m38wDuIPQoHYQB6TYt7kBpQ2thywxVFhobeU2zVFlkzW/a7GqjgbVWJqstMBYNW/3YpV9k54zas1gsrawbN82vbWRs3JoluNrYzjJunf2@Nt9a1LSwNpM59DziLJxqwzI9YK7w/broauMUU50fY9QuuVyNS@o0ukqEtrUnQOhNAWlZVH9It6WZa@8a@8bjAgoobuXL6pLd22XTdZ7tdzJdPx/dE0g990xJF04p/sBbjmiaPU5dUtxOdH0aGaarjagCBmVAQ3V2@SGz1Axnk5lMv/HzVaiNOajNh4IQ4jitlVAUy40p2KBcb8yBlPw1e@pNy0mEUmj@xiu3UmK2WX3gFOd/ "Groovy – Try It Online") 1. `('XXXSXXSXSSMLXLXXL3XL4XL5XL6XL'=~/\d?X*./)` finds all matches of the regex against the string, i.e. `[XXXS, XXS, XS, S, M, L, XL, XXL, 3XL, 4XL, 5XL, 6XL]`. 2. `it/3.4-47as int` converts the height to a valid index within the list of matches. 3. `(string=~pattern)[index]` retrieves the match at the given index [Answer] # [Python 3](https://docs.python.org/3/), 85 bytes ``` lambda s:[b for*b,a in b"3XSB XXSD XSH SK LT XLX 3XL_ 5XLd 6XLf".split()if s-99<a][0] ``` [Try it online!](https://tio.run/##FctBC4IwFADgv/Lw9BYmmiQonaJD0G7r8EAktrbVwKa4HfTXr/ru37zF9@TrZKcFVnAeFulfBqumzA9lxbp5cT7imqstmoCYRvlRWkLoegW/s1O5/C@V1STOQCQuQOIK4gb8DsQJauIPOBLX0BC3WRHm0UVkzkLYt@1JDn05JIYrY4U2z0kbZCx9AQ "Python 3 – Try It Online") Outputs as a list of ASCII code-points. [Answer] # [Julia](http://julialang.org/), 65 bytes ``` x->split("XXXS XXS XS M L XL XXL 3XL 5XL 6XL")[x.<162:4.3:204][1] ``` [Try it online!](https://tio.run/##RdDNaoQwEADge55iyMmAXYxxYwy720uP7mkvAfFQ1hVSxC7qFh@k9NSn64vYSdIqOBI/Mz/M26Ozr3xeWjjCMj@dxntnp4gaYy7g4wJnKMHggyEw9hjSlJRV8@7AZaqzndBpktUVr5cGy7zY6xQRAF@EwvEEXCaayywOiBYwRZQBnQWUmueJR28BFaLweF4x54ghvdww01yloWb5X1Nhd/XXyKtHd7PwKDbMNS9Co2zFAhsVYfj9hgJReZQb5rgIHJ4R8nEbbBvZGEaGK7Fge2iqsSakfR/Cp1sK3iZu9Ptg@6nrozULX4zBM9Cf70@goN3hC2iMqdjI/yW3viHLLw "Julia 1.0 – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 57 bytes ``` .+ $*1-174$* (1+)-\1 - -(1111)*1+ $#1$*XS 111 X X?X?1*- L ``` [Try it online!](https://tio.run/##K0otycxL/M9lZGCgosXlq6iWoFdtaGagA@TXcvkncKlq@CYY/tfT5lLRMtQ1NDcBKtIw1NbUjTHk0uXS1TAEAk0tQ6C0sqGKVkQwF5DPFcEVYR9hb6ily@Xz/z8A "Retina 0.8.2 – Try It Online") Link includes test suite. Port of @agtoever's answer, so outputs using `XXXL` etc.. Explanation: ``` .+ $*1-174$* (1+)-\1 - ``` Convert to unary and subtract 174. ``` -(1111)*1+ $#1$*XS ``` If the result is negative, then negate, subtract 1, and divide by 4, which gives the size in `X*S`. ``` 111 X X?X?1*- L ``` Otherwise, divide by 3 and subtract up to 2, which gives the size in `X*L`. The resulting lookup table: ``` XXXS 160 - 161 XXS 162 - 165 XS 166 - 179 S 170 - 173 L 174 - 182 XL 183 - 185 XXL 186 - 188 XXXL 189 - 191 XXXXL 192 - 194 XXXXXL 195 - 197 XXXXXXL 198 - 200 ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 128 bytes ``` L=kfd90HK H=uBgI0LP s=$[$1-150] c=L ((s<24))&&c=S for ((;;i++)) { (($[64#${L:i:1}]<s&&s<$[64#${H:i:1}]))&&echo $c&&exit c=X$c } ``` [Try it online!](https://tio.run/##S0oszvj/38c2Oy3F0sDDm8vDttQp3dPAJ4Cr2FYlWsVQ19DUIJYr2daHS0Oj2MbIRFNTTS3ZNpgrLb9IQUPD2jpTW1tTU6EaKKsSbWairFLtY5VpZVgba1OsplZsAxXzgIiB9KYmZ@QrqCQDGRWZJUBzI1SSuWq5/v//b2hhDgA "Bash – Try It Online") Ungolfed version below for review: ``` # Size cm range -150 >Low <High # of X #XXXS 160-163 10-13 9 3 #XXS 164-165 14-15 13 16 2 #XS 166-170 16-20 15 1 #S 171-173 21-23 20 0 #M #L 174-179 24-29 30 0 #XL 180-186 30-36 37 1 #XXL #3XL 187-193 37-43 44 3 #4XL #5XL 194-196 44-46 43 47 5 #6XL 197-200 47-50 46 51 6 #L=20 15 13 9 0 43 46 #H=30 37 16 44 0 47 51 L=kfd90HK H=uBgI0LP # print the high and low threshold arrays to verify base64 numbers for ((k=0;k<7;k++)) { l=$[64#${L:k:1}] h=$[64#${H:k:1}] echo $k: low:$l high:$h } echo # Test set: check algorithm on all values [160-200] for ((j=160;j<=200;j++)) { s=$[j-150] c=L;((s<24))&&c=S for ((i=0;i<8;i++)) { l=$[64#${L:i:1}] h=$[64#${H:i:1}] ((l<s&&s<h))&&echo $j:$c&&break c=X$c } } ``` [Try it online!](https://tio.run/##VZJBb6MwEIXP9q8YCYSIKiQbjB0I9LCnrJaVVsoekKocCHECgYQVJq26VX57dpx2U/U09vvs5zcjbyrTXK8OrNq/GqA@wlid9poEPGbksRheSLZs9w1xYNhBSZ2yLFeESxZwGRHCsUYkISSyxAKBIEaANSbIuCQhMotkwBVDJIOQEW4PUQd1xVFHr5AHYUQQEUadn9QpEKGLQvdQBKF9hFlUIpjju3NplSCyRVmvsiyoE92wCngSWT0QWISw@YTFscUJ2ibS6oGQBE8IRWLqyBtTmA4zCBXgABDHnEiKafKQAY@BR5AAAxGBkNRZ5hGDSAGXIISVFcScFnm32yZs@YMu8/O3/XdW/EIH@DO2pwmmRkODE4XqtIV@eEFh1KYZ@i1U41i9GpgGeNZju3uFTWW0FHA6Hzd6NHQ3jOD7Xc4WXaYW3cPDbAZvFKDP3ScpHPetSLuUX9YoNf@l5V3SdTOA26X20dTtbyFStyH0Qi2yCX9rM4HRUwp1o@sOqn4/jO3UHGE44aaH56o/awNP9gPgmNYfkQ45CotDhjPCcs9lMMTBfqQ1xV2dFwvfN1koZjPPq/MVau/XW@yozeaL9n7zS0/tRwNfuvoUfb/PjOeZrLG@710eUrf2vM2oq@52ps5Lt8bVBZu9Xv8B "Bash – Try It Online") ]
[Question] [ The difference list of a list of integers is the list differences of consecutive members. For example the difference list of ``` 1, 3, 2 ,4 ``` is ``` 2, -1, 2 ``` Your task is to take as input a difference list and output what the difference list would look like if the original list were sorted. For example the difference list ``` 2, 1, -2, -1 ``` Might represent a list ``` 2 4 5 3 2 ``` Which when sorted is ``` 2 2 3 4 5 ``` Which has a difference list of ``` 0 1 1 1 ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with less bytes being better. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` .¥{¥ ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f79DS6kNL//@PNtJRMNRR0AVSuoaxAA "05AB1E – Try It Online") ### Explanation ``` .¥{¥ .¥ # Undelta the input list { # Sort it ¥ # And get the deltas ``` [Answer] # [Python 3](https://docs.python.org/3/) with [Numpy](http://www.numpy.org/), ~~56~~ ~~54~~ 53 bytes *2 bytes off thanks to [@Artyer](https://codegolf.stackexchange.com/users/48878/artyer) (Numpy's `sort` instead of standard `sorted`). 1 byte off thanks to [@notjagan](https://codegolf.stackexchange.com/users/63641/notjagan) (moving `0` into `cumsum`)* ``` lambda x:diff(sort(cumsum([0]+x))) from numpy import* ``` The code defines an anonymous function that inputs a list or a Numpy array and outputs a Numpy array. [Try it online!](https://tio.run/##Dco7DoAgDADQ3VN0bFUS0c3Ek6iDnzSSWCAIiZ4emd7y/BcvZ4fM05LvTfZzg3c8DTM@LkQ8kjxJcO7W5iWiioMTsEn8B0Z8GXX2wdiIjHPfgm5BFZReifIP "Python 3 – Try It Online") [Answer] # Mathematica, 40 bytes ``` Differences@Sort@Accumulate@Join[{1},#]& ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` 0;+\ṢI ``` [Try it online!](https://tio.run/##y0rNyan8/9/AWjvm4c5Fnv8Ptx@d9HDnjP//o410FAx1FHSBlK5hLAA "Jelly – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` Ẋ-O∫ ``` [Try it online!](https://tio.run/##yygtzv7//@GuLl3/Rx2r////H22kY6ija6SjaxgLAA "Husk – Try It Online") ### Explaination ``` -- implicit input, e.g [2,1,-2,-1] ∫ -- cumulative sum [0,2,3,1,0] O -- sort [0,0,1,2,3] Ẋ -- apply function to all adjacent pairs in the list [(0,0),(0,1),(1,2),(2,3)] - -- subtract [0,1,1,1] ``` [Answer] # [Pyth](https://pyth.readthedocs.io), 9 bytes *-1 byte thanks to @EriktheOutgolfer*. ``` .+S+0sM._ ``` **[Test Suite.](http://pyth.herokuapp.com/?code=.%2BS%2B0sM._&input=%5B2%2C+1%2C+-2%2C+-1%5D&test_suite=1&test_suite_input=%5B2%2C+-1%2C+2%5D%0A%5B2%2C+1%2C+-2%2C+-1%5D&debug=0)** # [Pyth](https://pyth.readthedocs.io), 10 bytes ``` .+S.u+YNQ0 ``` [Try it online!](http://pyth.herokuapp.com/?code=.%2BS.u%2BYNQ0&input=%5B2%2C+1%2C+-2%2C+-1%5D&debug=0) or [Try more test cases](http://pyth.herokuapp.com/?code=.%2BS.u%2BYNQ0&input=%5B2%2C+1%2C+-2%2C+-1%5D&test_suite=1&test_suite_input=%5B2%2C+-1%2C+2%5D%0A%5B2%2C+1%2C+-2%2C+-1%5D&debug=0). [Answer] ## JavaScript (ES6), ~~57~~ 56 bytes *Saved 1 byte thanks to [@ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions)* ``` a=>a.map(n=>t-=n,p=t=0).sort((a,b)=>b-a).map(n=>p-(p=n)) ``` ### Demo ``` let f = a=>a.map(n=>t-=n,p=t=0).sort((a,b)=>b-a).map(n=>p-(p=n)) console.log(JSON.stringify(f([2, 1, -2, -1]))) ``` [Answer] # Java 8, 123 bytes The standard solution: cumulative sum input, sort, then diff. No substantial implementation tricks either. ``` l->{int s=l.length,d[]=new int[s+1],i=0;while(i<s)d[i+1]=d[i]+l[i++];for(java.util.Arrays.sort(d);i-->0;)l[i]=d[i+1]-d[i];} ``` Cast to `Consumer<int[]>`. Output is mutated input. [Try It Online](https://tio.run/##ZVC7bsMwDJztr@BoI5aQdFUcoOjcKehkaFBtOWUqS4YkJwgCf7tL5bGkEwneHXnHozop5kZtj93vgsPofIQjzfgU0fB379UliPwf0E@2jegs/3A2TIP2Is/H6dtgC61RIcCnQgvXPBs9nlTUEKKKBD7pW7SxkTvosO/3tFp3Xzb1UC@G7a6EQqgNN9oe4k/VNbK2@gxJFFYbWWG9FucfNLrAbSi7BmlYU5ErQ/1Kit754jUGD3So6EqBjO3WoiTqTURalrRiXjJBju8xHoZPDjsYKEyxjx7toZGg/CGUKVt2C0GuoIanPQnXtwo2FTAqbDPTwuw1JFdtq8dYoC0TvL@EqAfupsjpWzYaWzwMR3c/mpiJOufz8gc) ## Ungolfed lambda ``` l -> { int s = l.length, d[] = new int[s + 1], i = 0 ; while (i < s) d[i + 1] = d[i] + l[i++]; for (java.util.Arrays.sort(d); i-- > 0; ) l[i] = d[i + 1] - d[i]; } ``` ## Acknowledgments * -3 bytes thanks to *Olivier Grégoire*, master of unholy autoincrementation * -1 byte thanks to *Nevay* [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes ``` a₀ᶠ+ᵐ,0o{s₂↔-}ᶠ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P/FRU8PDbQu0H26doGOQX138qKnpUdsU3Vqg2P//0UY6hjrxRjrxhrH/owA "Brachylog – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~31~~ 32 bytes *-4 bytes thanks to @user2390246 for* `diffinv` *+5 bytes from Jarko for `cat`* ``` cat(diff(sort(diffinv(scan())))) ``` Reads from stdin, writes to stdout. `diffinv` is an inverse of `diff` for a given starting value (0 by default). Since it's `diff`ed again, it doesn't matter what that value is. As pointed out by Jarko Dubbeldam, I needed to properly output the result, at the cost of five bytes. Alas. [Try it online!](https://tio.run/##K/r/PzmxRCMlMy1Nozi/CMLKzCvTKE5OzNPQBIH/RgqGCrpGCrqG/wE "R – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 83 bytes ``` l,r=input(),[1] for i in l:r+=[r[-1]+i] r.sort() print[b-a for a,b in zip(r,r[1:])] ``` [Try it online!](https://tio.run/##FcsxCoAwDEbhvafIqJgKdRQ8SciggxiQtvzWQS9f6/SW7@WnHClOtZ6MxWK@S9ezBHV7AhlZpHPGsAjEBx1MHcYroSGXYbHI5lf66crbj1/LHRgSZu21VpmYApNvafsH "Python 2 – Try It Online") *Horrible* solution. [Answer] # [Perl 6](https://perl6.org), 46 bytes ``` {[\+](0,|@_).sort.rotor(2=>-1).flat.map(*R-*)} ``` [Try it](https://tio.run/##K0gtyjH7n1upoJacn5KqYPu/OjpGO1bDQKfGIV5Trzi/qESvKL8kv0jDyNZO11BTLy0nsUQvN7FAQytIV0uz9n9xYqUCWKeRjoKhjoIukNI1/A8A "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit signature :(*@_) [\+]( # triangle reduce using &infix:«+» 0, # start with 0 |@_ # Slip in the arguments from the outer block ) # (0, 2, 3, 1, 0) .sort # sort the results (0,0,1,2,3) .rotor(2=>-1) # group in twos ((0,0),(0,1),(1,2),(2,3)) .flat # flatten (0,0,0,1,1,2,2,3) .map(*R-*) # grab 2 values at a time, and subtract first from second # (0, 1, 1, 1) } ``` [Answer] # [Haskell](https://www.haskell.org/), 74 bytes ``` import Data.List g=sort.scanl(+)0 h l|k<-g l=map(\(x,y)->x-y)$zip(tail$k)k ``` [Try it online!](https://tio.run/##DcixDsIgEADQWb7iBgaI0Fhn6eToH1iHi5py4aCkMLTGf6edXvI8lvBlbo1inpcKd6zYPahUMblyRFfemFid9UV44H@42QnYRcxqVKvZtB1Wu2n5o6wqEsugQ4tICRx8ZnHKC6UKEvzzaqA3YA9s/2o7 "Haskell – Try It Online") Straightforward. [Answer] # TI-Basic (TI-84 Plus CE), 23 [bytes](http://tibasicdev.wikidot.com/one-byte-tokens) ``` Prompt X augment({0},cumSum(LX→X SortA(LX ΔList(LX ``` Prompts for user input. The list must be input with a leading `{`, with numbers separated by `,`, and with an optional trailing `}`. TI-Basic is a [tokenized language](http://tibasicdev.wikidot.com/one-byte-tokens); `ΔList(` and `cumSum(` are two-byte tokens, all other tokens used are one byte each. Example run (with `NAME` as the program name and `{4,-2,7,-4,0}` as the input): ``` prgmNAME X=?{4,-2,7,-4,0} {2 2 1 0 4} ``` Explanation: ``` Prompt X # 3 bytes, get list input, store in LX augment({0},cumSum(LX→X # 12 bytes, # store the list ({0} prepended to the cumulative sum of LX) to LX SortA(LX # 4 bytes, sort LX ascending ΔList(LX # 4 bytes, implicitly print the difference list of LX ``` [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 136 bytes As unnamed generic lambda, assuming input to be like `std::list` and returning via reference parameter. ``` [](auto&L){auto r=L.begin(),l=L.insert(r,0);while(r!=L.end())*r+++=*l++;for(L.sort(),l=r=--L.end();--l!=L.begin();*r---=*l);L.erase(l);} ``` [Try it online!](https://tio.run/##VY5BbsMgEEX3nGLiShUYiJoujfEJuEHbhYtxikQgAqxGsnx2F9KqVTczX2/@nxl9vfKz1vuD9dotk@ltSDma8TKgX@RsygNC45IDzHJ/ecNVPiqy3lGU6vhuztZjwlzR1icTM47siYjPD@sMjoeCjZ8wIW2klMrWUSrmELE6plC8NRgl5z8uwbk7/G0VbeSclxARxRDHZHCR2y4Qsj7DZaymFUHKU9fVZ/uCB1AgYX1mcGLAS@OnTSCYsSK1ldv352@dIt9BHZYMfQ@3WhoGjUD/B82rL2xD@xc "C++ (gcc) – Try It Online") Ungolfed: ``` [](auto&L){ auto r=L.begin(), l=L.insert(r,0); //adds a zero right in front while(r!=L.end()) *r++ += *l++; //sum left to right for( L.sort(), //sorting invalidates the iterators l=r=--L.end(); //so, reinit --l!=L.begin(); //decrement l beforehand *r-- -= *l //diff right to left ); L.erase(l); //l==L.begin(), so this removes the temporary 0 } ``` [Answer] # Pyth, 8 bytes ``` .+S+M.uP ``` [Demonstration](https://pyth.herokuapp.com/?code=.%2BS%2BM.uP&input=%5B2%2C+1%2C+-2%2C+-1%5D&debug=0) ``` .+S+M.uP .+S+M.uPNQ Implicit variables .u Q Apply the following function to the input repeatedly until it stops changing, then output the list of values, including the starting value. PN Remove the last element. No-op if the list is empty. +M Sum each list. This gives the cumulative sums in reverse order, including a 0 at the end for the empty list. S Sort .+ Deltas ``` [Answer] # TI-Basic, 20 bytes ``` cumSum(augment({0},Ans->L1 SortA(L1 ΔList(L1 ``` [Answer] # [Perl 5](https://www.perl.org/), 87 + 1 (-a) = 88 bytes ``` $a[0]=1;push@a,$a[-1]+$_ for@F;@a=sort{$a<=>$b}@a;print$a[0]-$_,$"while($_=shift@a)&&@a ``` [Try it online!](https://tio.run/##HctBCsIwEEDRqwQZimIiidBVGpmVO08gJYzQkkBpQhJxIV7dsbj6vMXPU1l6ZqC7Hp2x@VkDktyozHgEL@ZU8GqRXE2lvYEGd4HHB8nmEtf23xR4CbtXiMu0B@9qiHNDOnQdEvNZCiOF2qLMN@UW01pZ3fqTNpoV/QA "Perl 5 – Try It Online") [Answer] # VB.NET (.NET 4.5), 109 bytes ``` Sub A(n) Dim c=n.count-1 For i=1To c n(i)+=n(i-1) Next n.Sort() For i=c To 1 Step-1 n(i)-=n(i-1) Next End Sub ``` A function that expects a list as input and modifies it directly. The original parameter can then be used for output 1. Recreates an original list by adding forwards through the list (assumes an implicit 0 as the first element) 2. Sorts the original list 3. Gets the differences by going backwards (so I don't need to keep track of a different list) (the implicit first element of 0 means the first difference is the same as the smallest element) [Try it online!](https://tio.run/##nVJNj5tADD3Dr7A4NKAWJHrPIeqXKjW9ZP/AMHiJ1cGOZsym2z@fekiqTXta9YJsP/Oe/TxPlBYX2sEl8i2jtrOwXGg@SdQEh@ekOHcfJAT0SsKp@4KMkXy5l3EJCPv@clgG2NUMLsE3SlrLI3xlxQlj05QfaQbK0K0EG8gKMAom3igEVHiWBYgDMcKIPriI8CgRgsgJnlwkNwRMK5N/FVNSx0pOERyPlpMlgX6hhaBHhORmhCxX@i13XhbWtje6nVfzYkWAElSr4ktHVX62qWjbw4PYJP/K0w@EYVElnqDqq1W7epAKVCY02VhyTc3brX3bvim/408tuTuYz3VzY/aZuYeD4mkd6H8E2r8EPlmP3edS5CPtHXHt4pSyi0mjEdV2oqIYbdGwXomu3v6p5RLj2cDrXW9wU1rDBvzR8YSrpbzMA8YEAwY520D3GPFpUfshQLcbx/p98xL3d3F7D@QFLNvVAXI1Pwd0/pintCMGKxXeXqME7M6RFGsD3kD1Dqrcznn14rb76sH1tV5@Aw) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~15~~ 14 bytes -1 byte thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn). ``` (¯2-/⍋⊃¨⊂)0,+\ ``` `+\` cumulative sum `0,` prepend a zero `(`…`)` apply the following tacit function on that:  `⊂` enclose (so we can pick multiple items)  `⍋⊃¨` let each of the indices that would sort the argument pick from that  `¯2-/` reversed pairwise difference [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wSNQ@uNdPUf9XY/6mo@tOJRV5OmgY52DFBOwUjBUAEoCcSGAA "APL (Dyalog Unicode) – Try It Online") --- Original solution found by the Code Golf Hackathon participants at [the Dyalog '17 User Meeting](https://www.dyalog.com/user-meetings/dyalog17/workshops.htm#TP03): ``` ¯2-/l[⍋l←+\0,⎕] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@h9Ua6@jnRj3q7cx61TdCOMdB51Dc1FiT3XwEM0riMFAwVgMqA2BAA "APL (Dyalog Unicode) – Try It Online") `⎕` prompt for input `0,` prepend a zero `+\` cumulative sum `l←` store as `l` `⍋` find the indices that will sort `l` `l[`…`]` use that to index into `l` `¯2-/` reversed pairwise difference [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` 0hYsSd ``` [Try it online!](https://tio.run/##y00syfn/3yAjsjg45f//aCMFQwVdIwVdw1gA "MATL – Try It Online") ``` 0 # push 0 h # horizontal concatenate with implicit input Ys # cumulative sum S # sort d # diff (implicit output) ``` [Answer] # J, 10 bytes ``` /:~&.(+/\) ``` # explanation "sort under scan sum": In J, the Under conjunction `&.` applies the transformation to its right to the input, then applies the verb to its left (in this case sort `/:~`) and then does the reverse transformation. That is, J understands how to invert a scan sum, which is exactly what's needed here: the successive differences are the input that, when scan-summed, will produce that scan-sum. [Try it online!](https://tio.run/##y/r/P81WT0Hfqk5NT0NbP0aTKzU5I18hTcFIwVAh3kgh3vD/fwA "J – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` ÞRs¯0p ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwiw55Sc8KvMHAiLCIiLCJbMiwxLC0yLC0xXSJd) [Answer] # [Gaia](https://github.com/splcurran/Gaia), 7 bytes ``` 1¤++⊣ȯọ ``` [Try it online!](https://tio.run/##S0/MTPz/3/DQEm3tR12LT6x/uLv3f@qjton/o40UDBV0jRR0DWMB "Gaia – Try It Online") ### Explanation ``` 1¤+ Prepend 1 +⊣ Cumulative sums ȯ Sort ọ Deltas ``` [Answer] # [k](https://en.wikipedia.org/wiki/K_(programming_language)), 16 bytes ``` 1_-':{x@<x}@+\0, ``` [Try it online!](https://tio.run/##y9bNz/7/P83KMF5X3aq6wsGmotZBO8ZA53@ag56VgVXCfyMFQwVdIwVdQwA "K (oK) – Try It Online") ``` 0, /prepend a 0 +\ /cumulative sum {x@<x}@ /sort 1_-': /differences list ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), 10 bytes ``` iT å+ n än ``` [Test it](http://ethproductions.github.io/japt/?v=1.4.5&code=aVQg5SsgbiDkbg==&input=Wy0yLCAxMDAsIC0yLCAtMV0=) [Answer] # [Röda](https://github.com/fergusq/roda), 42 bytes ``` {i=0{[0];[i]if i+=_}|sort|slide 2|[_2-_1]} ``` [Try it online!](https://tio.run/##DcuxDsIgFEbhWZ7iHzq0EZLCqOFJkNw2AslN1CZUJ@DZkeV808lH2HsRl4SbxaMXtmtxq7879pzAV0utnkf@1vPFIcJUR0aR9q03Id47fzBmZyS0hBoo7VGR5mU0x/B7xnmbSGKibRGt/wE "Röda – Try It Online") This is similar to the [Perl 6 answer](https://codegolf.stackexchange.com/a/138590/66323). `.sort` is `|sort`, `.rotor(2=>-1).flat` is `|slide 2` and `.map(*R-*)` is `|[_2-_1]`. Explanation: ``` { i=0 /* initialize variable i */ /* the following block recreates the original list from differences: */ { [0]; /* push 0 to the stream */ [i]if i+=_ /* add every number in the stream to i and push i back */ }| sort| /* sort the numbers */ slide 2| /* for values i1, i2, i3, ... in the stream push pairs i1, i2, i2, i3, ... */ [_2-_1] /* calculate difference of numbers in each pair in the stream */ } ``` The statement `[i]if i+=_` is equivalent to ``` for sfv do if i += sfv do push(i) done done ``` The `+=` operator does not push values to the stream, so it is truthy. I could also have used some kind of block (eg. `{|j|i+=j;[i]}_`) to tie the addition and pushing statements together, but `if` is shorter. [Answer] ## Julia 0.6.0 (34 bytes) Pretty much a copy of what has been done in R and Python 3 `x->diff(sort(cumsum(vcat([0],x))))` [Answer] # [Factor](https://factorcode.org/), 45 bytes ``` [ 0 prefix cum-sum natural-sort differences ] ``` [Try it online!](https://tio.run/##Jc1BCsIwEEbhfU/xXyDFdqkHEDduxJV0McSJBpO0zkxAEc8eKe4f3wvkbZZ2Ph2O@y2Un5WLZ8WDpXBCJrv3amRRLXqFzmKx3LAIm70XicWw67oPRgxwI9yAb9cu2KxFiC/4mp3WjEJWhZJbAVxjCCz/0dQ8pYS@/QA "Factor – Try It Online") Add a 0 to the start of the input, cumulative sum, sort, differences. ]
[Question] [ ## Presented in honor of [APL as an interactive tool turning 50 this year](http://www.dyalog.com/50-years-of-apl.htm) ### [Background](http://www.jsoftware.com/papers/APLQA.htm) > > [Ken [Iverson]](https://en.wikipedia.org/wiki/Kenneth_E._Iverson) presented his paper *[Formalism in Programming Languages](http://www.jsoftware.com/papers/FPL.htm)* in August 1963 at a Working Conference on Mechanical Language Structures, Princeton, N.J. The list of conferees is full of famous and soon-to-be famous names, and a few future Turing Award winners (Backus, Curry, Dijkstra, Floyd, Iverson, Newell, Perlis, Wilkes). The paper also records the discussion that occurred after the presentation, ending with an exchange between Ken and [[Edsger] Dijkstra](https://en.wikipedia.org/wiki/Edsger_W._Dijkstra), in which Ken’s reply to Dijkstra’s question was a one-liner. > > > ### [Challenge](http://keiapl.org/anec/#Dijkstra) > > How would you represent a more complex operation, for example, the sum of all elements of a matrix ***M*** which are equal to the sum of the corresponding row and column indices? > > > Write a snippet or expression (no need for a full program or function) to calculate the sum of each element in a given integer matrix which is equal to the sum of its indices. Or, as FryAmTheEggman puts it: given a matrix ***M*** with elements ***a***ij return the sum of each ***a***ij where ***a***ij = i + j. You may assume the matrix already being in a variable or memory location, or you may take it as an argument or input. You may use either 0 or 1 based indices. ### Test cases ```   ``` `0` for empty matrix ``` 2 ``` `0` for 0 based indices or `2` for 1-based ``` 1 5 2 9 4 2 5 9 6 ``` `2` for 0 based or `10` for 1 based ``` 0 3 0 4 0 4 1 4 4 3 1 2 -2 4 -2 -1 ``` `11` ``` 3 -1 3 3 3 -1 3 1 ``` `6` for 0 based or `3` for 1 based ### Anecdote Iverson's answer was ++/(***M*** = ***⍳***¹ ⨢ ***⍳***¹)//***M***, which is neither valid in the *Iverson Notation* as defined in *A Programming Language*, nor in what eventually became APL. In Iverson notation, it would have been +/(***M*** = ***⍳***¹(*μ*(***M***)) ⨢ ***⍳***¹(*ν*(***M***)))/***M***. In the very first versions of APL it was `+/(,M=(⍳1↑⍴M)∘.+⍳1↓⍴M)/,M`. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~15~~ ~~14~~ 10 bytes ``` 3#fbb+y=*s ``` The input has rows separated by `;`. For example: `[1 5 2; 9 4 2; 5 9 6]`. 1-based indexing is used. [Try it online!](http://matl.tryitonline.net/#code=MyNmYmIreT0qcw&input=WzMgLTEgMyAzOyAzIC0xIDMgMV0K) Or [verify all test cases](http://matl.tryitonline.net/#code=YAozI2ZiYit5PSpzCkRU&input=W10KWzJdClsxIDUgMjsgOSA0IDI7IDUgOSA2XQpbMCAzIDAgNDsgMCA0IDEgNDsgNCAzIDEgMjsgLTIgNCAtMiAtMV0KWzMgLTEgMyAzOyAzIC0xIDMgMV0). ### Explanation I'll use the example with input `[3 -1 3 3; 3 -1 3 1]` in the explanation. ``` 3#f % Three-output find: for all nonzero values of implicit input matrix, pushes % three column vectors with row indices, column indices, and values % Stack contains: [1;2;1;2;1;2;1;2], [1;1;2;2;3;3;4;4], [3;3;-1;-1;3;3;3;1] bb % Bubble up twice: move vectors of row and column indices to top % Stack contains: [3;3;-1;-1;3;3;3;1], [1;2;1;2;1;2;1;2], [1;1;2;2;3;3;4;4] + % Element-wise sum of top two arrays % Stack contains: [3;3;-1;-1;3;3;3;1], [2;3;3;4;4;5;5;6] y % Duplicate the vector of nonzero values onto the top of the stack % Stack contains: [3;3;-1;-1;3;3;3;1], [2;3;3;4;4;5;5;6], [3;3;-1;-1;3;3;3;1] = % Element-wise equality test of top two arrays % Stack contains: [3;3;-1;-1;3;3;3;1], [0;1;0;0;0;0;0;0] * % Element-wise multiply of top two arrays % Stack contains: [0;3;0;0;0;0;0;0] s % Sum of array % Stack contains: 3 ``` [Answer] # APL, ~~13~~ 12 bytes **1 byte thanks to @jimmy23013.** 1-indexed. The array is stored in the variable `m`. ``` ~~+/,m×m=+/¨⍳⍴m~~ +/∊m∩¨+/¨⍳⍴m ``` [Try it online!](http://tryapl.org/?a=+/%u220Am%u2229%A8+/%A8%u2373%u2374m%20%u2190%202%204%20%u2374%203%20%AF1%203%203%203%20%AF1%203%201&run) Based on [the answer in J](https://codegolf.stackexchange.com/a/85793/48934), which is a language based on APL. In TryAPL, to key in: `+/m`em`c`1+/`1`i`rm` With the array: `+/m`em`c`1+/`1`i`rm `[ 2 4 `r 3 `21 3 3 3 `21 3 1` ### Explanation ``` +/∊m∩¨+/¨⍳⍴m m temp ← variable ⍴ temp ← shape of temp ⍳ temp ← a 2D array where each element is the corresponding index. for the example, this gives: ┌───┬───┬───┬───┐ │1 1│1 2│1 3│1 4│ ├───┼───┼───┼───┤ │2 1│2 2│2 3│2 4│ └───┴───┴───┴───┘ +/¨ each element in temp ← its sum m∩¨ temp ← intersect each element in temp with the variable +/ temp ← sum of temp ``` [Answer] ## JavaScript, ~~49~~ 46 bytes ``` a.map((b,i)=>b.map((c,j)=>r+=c==i+j&&c),r=0)|r ``` Edit: Saved 3 bytes thanks to @MartinEnder pointing out that snippets are allowed. [Answer] ## [Retina](https://github.com/m-ender/retina), 46 bytes Byte count assumes ISO 8859-1 encoding. ``` \d+ $* M!`(?<=(\S* |.*¶)*)(?<-1>1)+\b(?(1)1) 1 ``` Input uses space and linefeed separators to represent the matrix. Indices are 0-based. [Try it online!](http://retina.tryitonline.net/#code=XGQrCiQqCk0hYCg_PD0oXFMqIHwuKsK2KSopKD88LTE-MSkrXGIoPygxKTEpCjE&input=MCAzIDAgNAowIDQgMSA0CjQgMyAxIDIKLTIgNCAtMiAtMQ) ### Explanation Not quite the kind of challenge Retina was made for, but it's doing surprisingly well... :) **Stage 1: Substitution** ``` \d+ $* ``` This simply expands all the integers in the string as unary numbers using `1` as the unary digit. Negative numbers like `-3` will simply become things like `-111`. **Stage 2: Match** ``` M!`(?<=(\S* |.*¶)*)(?<-1>1)+\b(?(1)1) ``` Due to the `!` option, this prints all the matches of the given regex. Said regex uses [balancing groups](https://stackoverflow.com/a/17004406/1633117) to check whether the current number is the same as the sum of its indices. To do that, we first determine the sum of indices with the lookbehind `(?<=(\S* |.*¶)*)`. This adds one capture for each number in front of the current one on the same line (via `\S*` ) as well as one capture for each line in front of the current one (via `.*¶`) to group `1`. Hence, we get the zero-based sum of indices as a result. Then we try to match the entire next number while removing captures from this stack with `(?<-1>1)+\b`. And then we make the match fail if any captures are left on group `1` with `(?(1)1)` to ensure equality. Note that negative numbers are never matched, because the lookbehind cannot get past the `-` in front of list of `1`s and the `(?<-1>1)+` can't match it either. This gives us a list of all the unary numbers which equal the sum of their indices. **Stage 3: Match** ``` 1 ``` We end with another match stage, but without the `!` option, this just counts the number of matches, which both sums all the unary numbers from the previous result and also converts that sum back to decimal. [Answer] # J, 15 bytes ``` +/,M*M=+/&i./$M ``` Uses zero-based indexing and assumes the matrix is already stored in variable *M*. ## Explanation ``` +/,M*M=+/&i./$M $a Get the shape of M / Insert between the shape &i. Create a range from 0 to each end exclusive +/ Forms a table which is the sum of each row and column index M= 1 if the element is equal to its index sum else 0 M* Multiply by their values , Flatten +/ Reduce using addition to get the sum ``` [Answer] # Jelly, ~~15~~ ~~14~~ 10 bytes **4 bytes thanks to Adnan.** 1-indexed. ``` ~~L€R€+"LR$=³×³FS~~ ~~L€R€+"LR$=׳FS~~ J€+"J=×⁸FS ``` [Try it online!](http://jelly.tryitonline.net/#code=SuKCrCsiSj3Dl8KzRlM&input=&args=W1szLC0xLDMsM10sWzMsLTEsMywxXV0) [Verify all testcases at once.](http://jelly.tryitonline.net/#code=SuKCrCsiSj3Dl-KBuEZTCsOH4oKs&input=&args=W10sW1syXV0sW1sxLDUsMl0sWzksNCwyXSxbNSw5LDZdXSxbWzAsMywwLDRdLFswLDQsMSw0XSxbNCwzLDEsMl0sWy0yLDQsLTIsLTFdXSxbWzMsLTEsMywzXSxbMywtMSwzLDFdXQ) (Slightly modified.) [Answer] # R, 24 bytes ``` sum(M[M==row(M)+col(M)]) ``` 1-based. Test cases: ``` > M<-matrix(nrow=0,ncol=0) > M <0 x 0 matrix> > sum(M[M==row(M)+col(M)]) [1] 0 > M<-matrix(2,nrow=1,ncol=1) > M [,1] [1,] 2 > sum(M[M==row(M)+col(M)]) [1] 2 > M<-matrix(c(1,9,5,5,4,9,2,2,6),nrow=3) > M [,1] [,2] [,3] [1,] 1 5 2 [2,] 9 4 2 [3,] 5 9 6 > sum(M[M==row(M)+col(M)]) [1] 10 > M<-matrix(c(0,0,4,-2,3,4,3,4,0,1,1,-2,4,4,2,-1),nrow=4) > M [,1] [,2] [,3] [,4] [1,] 0 3 0 4 [2,] 0 4 1 4 [3,] 4 3 1 2 [4,] -2 4 -2 -1 > sum(M[M==row(M)+col(M)]) [1] 11 > M<-matrix(c(3,3,-1,-1,3,3,3,1),nrow=2) > M [,1] [,2] [,3] [,4] [1,] 3 -1 3 3 [2,] 3 -1 3 1 > sum(M[M==row(M)+col(M)]) [1] 3 ``` [Answer] ## CJam, ~~23~~ ~~21~~ 20 bytes *Thanks to Peter Taylor for saving 3 bytes.* ``` ee{~_@f-_,,.=.*~}%1b ``` Expects the matrix to be on the stack and leaves the sum instead. Indices are zero-based in either case. [Test it here.](http://cjam.aditsu.net/#code=%5B%5B%200%203%20%200%20%204%5D%0A%20%5B%200%204%20%201%20%204%5D%0A%20%5B%204%203%20%201%20%202%5D%0A%20%5B-2%204%20-2%20-1%5D%5D%0A%0Aee%7B~_%40f-_%2C%2C.%3D.*~%7D%251b) [Answer] # Python 2 - ~~60~~ 57 bytes It's a code snippet, so it would be a few more bytes if I actually returned the value, I guess. `e=enumerate;sum(i*(x+y==i)for x,r in e(a)for y,i in e(r))` Thanks for the help Leaky Num :-) Quick explanation. `a` is an array holding numbers. Simply iterate through indexes and sum up all values where the value equals the sum of the index. [Answer] # k4, 24 bytes Assumes the matrix is stored in `m`. ``` +//7h$m*m=(!#m)+/:\:!#*m ``` This is one of those puzzles where the simplifications involved in designing k from APL (and J) really hurt—k’s `!` is the equivalent of APL’s `⍳` but only works on vectors, so I have to assemble the matrix of indices myself; inner product is one character in APL but five in k; and I lose three characters to handling the empty matrix properly because k doesn’t have strongly-typed matrices. [Answer] # Pyth, 14 bytes 0-indexed. ``` ss.e.e*ZqZ+kYb ``` [Test suite.](http://pyth.herokuapp.com/?code=ss.e.e%2aZqZ%2BkYb&test_suite=1&test_suite_input=%5B%5D%0A%5B%5B2%5D%5D%0A%5B%5B1%2C5%2C2%5D%2C%5B9%2C4%2C2%5D%2C%5B5%2C9%2C6%5D%5D%0A%5B%5B0%2C3%2C0%2C4%5D%2C%5B0%2C4%2C1%2C4%5D%2C%5B4%2C3%2C1%2C2%5D%2C%5B-2%2C4%2C-2%2C-1%5D%5D%0A%5B%5B3%2C-1%2C3%2C3%5D%2C%5B3%2C-1%2C3%2C1%5D%5D&debug=0) [Answer] ## PowerShell v2+, 43 bytes ``` %{$j=0;$_|%{$o+=$_*($_-eq$i+$j++)};$i++};$o ``` As a snippet. Usage is to explicitly pipe the matrix to this (see examples below). Assumes that `$i`, and `$o` are either null or zero at the start (I've explicitly set them as such in the examples below), and utilizes 0-index. Does a foreach loop on each row of the matrix. We set `$j` to `0`, and then go through each element of the row in another loop `$_|%{...}`. Each inner loop, we increment `$o` by the current element multiplied by a Boolean `($_-eq$i+$j++)`, meaning if that Boolean is `$TRUE`, it'll be `1`, otherwise `0`. Then we exit the inner loop, increment `$i`, and start the next row. Finally, we leave `$o` on the pipeline at the end. ### Examples ``` PS C:\Tools\Scripts\golfing> $o=0;$i=0;$j=0;@(@(3,-1,3,3),@(3,-1,3,1))|%{$j=0;$_|%{$o+=$_*($_-eq$i+$j++)};$i++};$o 6 PS C:\Tools\Scripts\golfing> $o=0;$i=0;$j=0;@(@(0,3,0,4),@(0,4,1,4),@(4,3,1,2),@(-2,4,-2,-1))|%{$j=0;$_|%{$o+=$_*($_-eq$i+$j++)};$i++};$o 11 ``` [Answer] # Ruby, 63 bytes With z as a two-dimensional array of numbers: ``` s=0;z.each_index{|i|z[i].each_index{|j|s+=i+j if z[i][j]==i+j}} ``` Not terribly exciting at all. If z is a flattened array with x and y having the sizes of the arrays, such as: ``` x=z.size y=z[0].size z=z.flatten ``` Then we have this monstrousity - perhaps more ruby-ish with it's fancy products and zips, but actually larger: ``` (1..x).to_a.product((1..y).to_a).zip(z).inject(0){|s,n|s+(n[0][0]+n[0][1]==n[1]+2?n[1]:0)} ``` [Answer] ## Actually, 21 bytes ``` ñ`i╗ñ"i╜+@;(=*"£Mi`MΣ ``` [Try it online!](http://actually.tryitonline.net/#code=w7FgaeKVl8OxImnilZwrQDsoPSoiwqNNaWBNzqM&input=W1swLDMsMCw0XSxbMCw0LDEsNF0sWzQsMywxLDJdLFstMiw0LC0yLC0xXV0) Thanks to Leaky Nun for making me stop being lazy and finally write this. This uses 0-indexed matrices, and takes input as a nested list. Explanation: ``` ñ`i╗ñ"i╜+@;(=*"£Mi`MΣ ñ enumerate input `i╗ñ"i╜+@;(=*"£Mi`M for each (i, row) pair: i╗ flatten, store i in register 0 ñ enumerate the row "i╜+@;(=*"£M for each (j, val) pair: i╜+ flatten, add i to j @;( make an extra copy of val, bring i+j back to top = compare equality of i+j and val * multiply (0 if not equal, val if they are) i flatten the resulting list Σ sum the values ``` [Answer] # Matlab/Octave, 48 bytes 1-indexed. Will not handle the first test case because `[1:0]` has size 1x0 for some reason ``` sum(sum(M.*(M-[1:size(M,1)]'-[1:size(M,2)]==0))) ``` Tested in Octave 3. Full program: ``` M = [2] sum(sum(M.*(M-[1:size(M,1)]'-[1:size(M,2)]==0))) M = [1 5 2; 9 4 2; 5 9 6] sum(sum(M.*(M-[1:size(M,1)]'-[1:size(M,2)]==0))) M = [ 0 3 0 4; 0 4 1 4; 4 3 1 2;-2 4 -2 -1] sum(sum(M.*(M-[1:size(M,1)]'-[1:size(M,2)]==0))) M = [ 3 -1 3 3; 3 -1 3 1] sum(sum(M.*(M-[1:size(M,1)]'-[1:size(M,2)]==0))) ``` [Answer] # Lua, 70 bytes 1-indexed. ``` s=0 for i=1,#a do for j=1,#a[i]do s=i+j==a[i][j]and s+i+j or s end end ``` Bonus: it works for ragged arrays! Input stored in `a`, output stored in `s`. # Full program: ``` function Dijkstras_Challenge(a) s=0 for i=1,#a do for j=1,#a[i]do s=i+j==a[i][j]and s+i+j or s end end print(s) end Dijkstras_Challenge({}) Dijkstras_Challenge({{2}}) Dijkstras_Challenge({{1,5,2},{9,4,2},{5,9,6}}) Dijkstras_Challenge({{0,3,0,4},{0,4,1,4},{4,3,1,2},{-2,4,-2,-1}}) Dijkstras_Challenge({{3,-1,3,3},{3,-1,3,1}}) ``` [Answer] # PHP, 59 bytes ``` foreach($a as$y=>$r)foreach($r as$x=>$v)$s+=($v==$x+$y)*$v; ``` expects array $a defined; must be empty or 2-dimensional, 0-indexed. calculates sum to $s (previously 0 or undefined - 0 equals NULL) Happy Birthday APL! **functions and test suite** ``` function f0($a) { foreach($a as$y=>$r)foreach($r as$x=>$v)$s+=($v==$x+$y)*$v;return $s|0; } function f1($a) { foreach($a as$y=>$r)foreach($r as$x=>$v)$s+=($v==$x+$y+2)*$v;return $s|0;} $samples = [ [], 0, 0, [[2]], 0, 2, [[1,5,2],[9,4,2],[5,9,6]], 2, 10, [[0,3,0,4],[0,4,1,4],[4,3,1,2],[-2,4,-2,-1]],11,11, [[3,-1,3,3],[3,-1,3,1]],6,3 ]; function test($x,$e,$y){static $h='<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';echo"$h<tr><td>",out($x),'</td><td>',out($y),'</td><td>',out($e),'</td><td>',cmp($e,$y)?'N':'Y',"</td></tr>";$h='';} while($samples) { $a=array_shift($samples); test($a,'B0:'.array_shift($samples),'B0:'.f0($a)); test($a,'B1:'.array_shift($samples),'B1:'.f1($a)); } ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes ``` {iiʰI-ʰ=∧Ihh}ᶠ+ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wvzoz89QGT91TG2wfdSz3zMiofbhtgfb//9EK0bE60dFGsSDSUMdUxwjIsNQxAdOmOpY6ZmAZAx1jHQMdEyATSOoYglkmQDFDsLp4I6AgkIg3BCs2BjKAcsZANpQJFFeIBQA "Brachylog – Try It Online") ``` + The output is the sum of { }ᶠ all possible results of i taking a row from the input with its index, i taking an element with its index ʰ from that row, I Ihh and outputting the element =∧ so long as the index of the row is equal to -ʰ the value of the element minus its index within the row. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes ``` ArrayRules/*Cases[p_~_~v_/;Tr@p==v:>v]/*Tr ``` [Try it online!](https://tio.run/##LYvLCoMwEEX3@YqC0IVMiPFRsEWx9AdKcScioUQq1CJJKpSgv54Oms3cM/fMjMK85CjM8BSuL9xVKfF7fN9Ss/AmtNTN1K3dOnfsUqtqKor5XM4tC2vl7mr4mCagZV8F7ZFVltgFiLXxsgWHDGKkg80h9ZRBDqddR5BABOlWYwL3nGLP/TmNUeCgfP9JkFAnm/QLKrK4Pw "Wolfram Language (Mathematica) – Try It Online") 1-indexed. ``` ArrayRules (*Convert into a list of (position->value) Rules*) /*Cases[p_~_~v_/;Tr@p==v (*select those where sum(position)==value*) :>v]/*Tr (*and find the sum of those values*) ``` ]
[Question] [ On that challenge you have to solve that challenge. # Contest is over! Check the end of the question **Specs:** 1. Write the smallest code (Any language\*). 2. The score of an answer is the sum of: * Code length **without whitespace**. * Number of answers using that same language squared. * Length of the name of the biggest language on the contest minus the length of your language. * Downvotes minus Upvotes (a.k.a. minus Total of Votes) 3. Write the position of the users and the score. 4. Each user can write only one answer. 5. The lowest score wins. --- **Testing:** So, at the end of the contest, a possible input could be (STDIN): The columns are: Username, Language, Code length(w/o whitespace) and TotalVotes ``` UserA Python 100 1 UserB Perl 30 2 UserC Java 500 3 UserD Brainfuck 499 4 UserE Perl 29 5 ``` If your user name has spaces like "My User Name" it'll become "MyUserName" so the input will always have **exactly 4 columns**. The output will be (STDOUT): ``` 1 UserE 33 2 UserB 37 3 UserA 103 4 UserD 496 5 UserC 503 ``` Explanation: ``` User P N^2 L V A 100 1 3 -1 B 30 4 5 -2 C 500 1 5 -3 D 499 1 0 -4 E 29 4 5 -5 ``` Brainfuck is the largest name with 9 chars (`9 - 9 = 0`). Perl and Java have 4 chars (`9 - 4 = 5`). Python has 6 chars (`9 - 6 = 3`). Perl has 2 entries so each get 4 extra points. --- **About languages:** The name of the language must contain only English letters (i.e. [A-Za-z]) and those which don't fit that must be "translated" to something else. By the end of the contest, every language must have it's representation (You may propose better representations) Examples: ``` Python3 -> Python Ruby1.9 -> Ruby Shell Script -> Shell C++ -> Cpp C# -> CSharp ><> -> Fish ``` --- # Deadline: August 20, 2011 00:00 UTC > > At the end of the contest, the winner must use his/her program to find the winner. It's allowed to non winners to use their programs to find the winner and tell him/her to use his/her program to find the winner. :) > > > The winner (see above) gets the answer accepted! \*The [Whitespace language](http://en.wikipedia.org/wiki/Whitespace_%28programming_language%29) has the unfair advantage of being able to introduce unlimited complexity without a penalty on the character count. Answers written in Whitespace may be on the contest but can't win. If you can make the logic of your program in *whitespaces*, you also can't win. That's a subjective topic, but if your program can increase considerably in size without being penalized, it falls in that condition. --- # Final Input Alphabetical order of names (as of Aug 20th 2011 UTC 00:00) ``` boothby Sage 41 9 Harpyon Python 203 4 JBernardo Python 184 7 JoeyAdams PostgreSQL 225 6 jpjacobs AWK 269 4 Lowjacker Ruby 146 2 PeterTaylor Golfscript 82 4 rmackenzie CommonLisp 542 2 shesek Javascript 243 3 userunknown Scala 252 1 ``` As both mine and boothby's answers are not allowed to win, the winner should proclaim himself the winner by editing this question and posting the final output below. # Final Output ``` 1 boothby 39 2 PeterTaylor 79 3 Lowjacker 151 4 JBernardo 185 5 Harpyon 207 6 JoeyAdams 220 7 shesek 241 8 userunknown 257 9 jpjacobs 273 10 rmackenzie 541 ``` [Answer] **Sage: 48 42 41 non-whitespace (60246 bytes total)** Just to be a prick: ``` s = ' ' for c in '<lots of whitespace>'.split(s): s+=chr(len(c)) exec s ``` Note that the first line should be equivalent to `s='\t'`, but the SE code block translates the tab to 4 spaces. The whitespace unpacks to: ``` exec preparse(""" import sys instances = {} maxlen = 0 inputs = [line.split() for line in sys.stdin.readlines()] for i in [0..len(inputs)-1]: user, language, length, votes = inputs[i] if language in instances: instances[language]+=1 else: instances[language]=1 if len(language) > maxlen: maxlen = len(language) scoresheet = [] for i in [0..len(inputs)-1]: user, language, length, votes = inputs[i] length = int(length) votes = int(votes) score = length + (maxlen - len(language)) + instances[language]*instances[language] - votes scoresheet.append((score,user)) scoresheet.sort(reverse=False) for user, score in scoresheet: print user, score""") ``` Note that my use of `[0..len(inputs)-1]` ensures that this isn't a Python script, since Sage is a superpython\*. Unfortunately, exec falls back on Python... so I've gotta preparse it. edit 1: splitting on tabs, not newlines -- what was I thinking? edit 2: made the code easier on the eyes, and recycled the splitting tab by pushing another 'newline' to the whitespace \*ok, not quite: we break xor [Answer] ## Golfscript, 83 chars (82 not counting whitespace) ``` n/{},{' ':s/}%.{1=}%\{~~\~\-\.`{=}+4$\,,.*\,-+2${,}%$)\;+[\]}%$\;.,,]zip{~)s@~s@n}% ``` Explanation: ``` # Split the string containing all the input on newlines n/ # Remove empty lines {}, # Split each line on spaces (storing the space character in variable s) {' ':s/}% # We now have an array of arrays of words. Duplicate it, filter the copy to contain # only the second word of each array, and reorder with the array of second words first .{1=}%\ # Map each line { # Unpack the array ["user" "lang" "length" "votes"] and evaluate the integers ~~\~\ # Subtract votes from length and bring "lang" to the top -\ # Create a function to match the string "lang" .`{=}+ # Stack is currently [array of langs] "user" (length-votes) "lang" {"lang"=} # Duplicate the array of langs and apply the match function as a filter 4$\, # Get the length of the array of matches and square it ,.* # Stack is [array of langs] "user" (length-votes) "lang" (num with lang)^2 # Bring the "lang" to the top, get its length, subtract and add \,-+ # Stack is [array of langs] "user" (score-length of longest lang) # Get an array of length of language names and sort it 2${,}%$ # Drop it apart from the largest value, and add that to the score )\;+ # Package the "user" score from the top of the stack as [score "user"] [\] }% # Sort. Since each element is a [score "user"] value, this will sort by score. $ # Discard the [array of langs]. \; # Stack is an array of [score "user"] arrays. Get its length and create an array of the # same length which counts from 0. .,, # Group and zip, so we go from [[score0 "user0"] ... [scoren "usern"]] [0 ... n] to # [[[score0 "user0"] 0] ... [[scoren "usern"] n]] ]zip # Map each [[scorei "useri"] i] { # Expand, increment i (so we count from 1 rather than 0), add a space ~)s # Bring the [scorei "useri"] to the top, unpack, add a space @~s # Bring the scorei to the top, add a newline @n }% # We now have an array [[1 " " "userA" " " scoreA "\n"] ... [n " " "userZ" " " scoreZ "\n"] # so Golfscript's standard output formatting does the rest ``` [Answer] ## Python, 184 That's why I love spaces. ``` import sys x = sys.stdin.read( ).split() z = x [ 1 : : 4 ] for i , ( j , k ) in enumerate ( sorted ( zip ( [ int(i) - int(j) + z.count(k) ** 2 + max(map(len, z)) - len(k) for i, j, k in zip ( x[2 : : 4], x[3 : : 4], z ) ], x[ : : 4] ) ), 1 ): print i, k, j ``` It's much more readable! [Answer] ## PostgreSQL - 225 non-space characters **242 → 225:** Replaced subqueries with [windowing clauses](http://www.postgresql.org/docs/current/static/tutorial-window.html). ``` \set QUIET 1 \t \a \f ' ' CREATE TEMPORARY TABLE t (u TEXT, l TEXT, c INT, v INT); \copy t FROM PSTDIN WITH DELIMITER ' '; SELECT row_number() OVER (ORDER BY score), * FROM (SELECT u, c + count(*) OVER (PARTITION BY l)^2 + max(length(l)) OVER () - length(l) - v AS score FROM t) AS q ``` *tested on 9.2devel* ### Usage and output: ``` $ psql -f meta.sql < meta.in 1 UserE 33 2 UserB 37 3 UserA 103 4 UserD 496 5 UserC 503 ``` [Answer] ## Python 2 - 210 203 non-space characters ``` import sys e=enumerate n=len l=[x.split()for x in sys.stdin.readlines()] for i,(x,y)in e(sorted((int(x[2])-int(x[3])+n(list(y for y in l if y[1]==x[1]))**2+max(n(x[1])for x in l)-n(x[1]),i)for i, x in e(l))):print i+1,l[y][0],x ``` ### Usage and output: ``` $ cat meta.txt | python meta.py 1 UserE 33 2 UserB 37 3 UserA 103 4 UserD 496 5 UserC 503 ``` [Answer] ## AWK, 277 269 non-space characters Used `in` to cut 8 chars. Spaced version and commented version: ``` { # read in user strings u[NR]=$0 # count number of times language has been used l[$2]+=1 } END{ # get maximum language length M=0 X=NR for (g in l){ f=length(g) if(f>M) M=f } # get score for user i for(i in u){ split(u[i],c) s[i]=c[3]+l[c[2]]^2+M-length(c[2])-c[4] } # sort scores and users for(i=2;i<=X;++i){ for(j=i;s[j-1]>s[j];--j){ t=s[j] x=u[j] s[j]=s[j-1] u[j]=u[j-1] s[j-1]=t u[j-1]=x } } # output for(i=1;i<=X;++i){ split(u[i],c) print i,c[1],s[i] } } ``` usage: ``` awk -f meta.awk data.txt ``` [Answer] # Common Lisp - 546 **(when golfed boy consolidating parenthesis, not counting spaces)** ``` ;;;; This is an answer to Code-Golf question ;;;; 3203/meta-golf-challenge ;;;; By using Common Lisp I plan to have the longest ;;;; Language-name while I cannot hope to have the ;;;; lowest character count due to Lisp's ;;;; linguistic tradition I can avoid the 16 or 25-pt ;;;; penalty atached to being the 4th or 5th PY ;;;; based answer. (defun f (i) (loop for e in y do (if (eq i (nth 0 e)) (return (nth 1 e)) ) ) ) (setf x (loop for l = (read-line () () () ()) while l collect (loop for i = 0 then (1+ j) as j = (position #\Space l :start i) collect (subseq l i j) while j) ) ) (setf y (loop for a in x collect (list (+ (read-from-string (nth 2 a)) (expt (reduce #'+ (loop for b in x collect (if (string= (nth 1 a) (nth 1 b)) 1 0) ) ) 2 ) (+ 5 (- (reduce #'min (loop for b in x collect (length (nth 1 b)))) (length (nth 1 a)))) (* -1 (read-from-string (nth 3 a))) ) (car a) ) ) ) (setf g (sort (loop for c in y collect (nth 0 c)) #'<) ) (loop for i = 0 then (1+ i) while (< i (length g)) do (setf a (nth i g)) (format t "~A ~A ~A~%" (1+ i) (f a) a) ) ``` Heavily golfed, my common lisp solution was and is the longest on the board. So I decided to cheat a bit by writing a significantly shorter bootloader and claiming that as my submission. ~~(I consider @Boothby's submission to be a precedent in favor of this behavior)~~ Major thanks to **Peter Taylor** for his help squeezing every last char out of this bootstrapper. # BASH - 35 ``` wget -q goo.gl/R4R54 cat -|clisp l.lsp ``` **Usage**: cat ./test0 | bash ./btstrp.sh **Joey Adams** pointed out that this is not a fair solution because I can "arbitrarily increase the complexity of your solution without a corresponding increase in code size", a point not clearly expressed in the spec. [Answer] ## Ruby, 146 characters + 4 spaces ``` b=$<.map &:split puts b.map{|u,l,c,v|[b.map{|_,n|n.size}.max-l.size+b.count{|_,n|n==l}**2+eval(c+?-+v),u]}.sort.map.with_index{|(s,u),i|[i+1,u,s]*' '} ``` [Answer] # JavaScript, 243 chars ``` for(g=0,H="length",i=J.split("\n"),p=[],l={};i[H]&&p.push(a=i.pop().split(" "));) X=a[1],X[H]>g&&(g=X[H]),l[X]=l[X]+1||1 for(i=-1;m=p[++i];)p[i]=[m[0],+m[2]+Math.pow(l[m[1]],2)+(g-m[1][H])-m[3]] p.sort(function(a,b){return a[1]<b[1]?-1:1}).join("\n") ``` Longer than most of the other solutions... but the best I could come up with in JavaScript. ## Usage Input should be in a J variable. For example, open a console and write: ``` J="UserA Python 100 1\nUserB Perl 30 2\nUserC Java 500 3\nUserD Brainfuck 499 4\nUserE Perl 29 5"; for(g=0,H="length",i=J.split("\n"),p=[],l={};i[H]&&p.push(a=i.pop().split(" "));) X=a[1],X[H]>g&&(g=X[H]),l[X]=l[X]+1||1 for(i=-1;m=p[++i];)p[i]=[m[0],+m[2]+Math.pow(l[m[1]],2)+(g-m[1][H])-m[3]] p.sort(function(a,b){return a[1]<b[1]?-1:1}).join("\n") ``` # CoffeScript, 177 chars About the same logic, in CoffeScript: ``` g=0;H="length";l={};([A,+C+Math.pow(l[B],2)+(g-B[H])-D] for [A,B,C,D] in for a in J.split "\n" then [_,X]=a=a.split " ";X[H]>g&&g=X[H];l[X]=l[X]+1||1;a).sort((a,b)->`a[1]<b[1]?-1:1`).join "\n" ``` [Answer] # Scala 269 266 252 without blanks and newlines. ``` val b = io.Source.stdin.getLines.toList.map (_.split (" ")) b.map (a => { val l = b.filter (_(1) .equals ( a(1))).size a(0) -> (a (2).toInt + l * l + (b.map (x => x(1).length).max - a(1).length) - a(3).toInt) }).sortBy (_._2).zipWithIndex .map (m => m._2 + " " + m._1._1 + " "+ m._1._2).mkString ("\n") ``` Invocation: ``` cat user.lst | scala -i metagolf.scala ``` ### updates: * simplified (l => l.foo) -> (\_.foo) * invocation * Gareths hint of stdin my solution: ``` * 0 boothby 39 1 PeterTaylor 79 2 Lowjacker 151 * 3 JBernardo 185 4 Harpyon 207 5 JoeyAdams 220 6 shesek 241 7 userunknown 257 8 jpjacobs 273 9 rmackenzie 541 ``` \*) out of contest ]
[Question] [ # Task Given a positive integer `n`, draw the corresponding rocket. # Examples From `n = 1` to `4` the rockets are below. For your program's output, the trailing newline after a rocket is optional. ``` | / \ *---* | o | | o | *---* /_\ | / \ / \ *-----* | o o | | o o | | o o | | o o | *-----* /___\ | / \ / \ / \ *-------* | o o o | | o o o | | o o o | | o o o | | o o o | | o o o | *-------* /_____\ | / \ / \ / \ / \ *---------* | o o o o | | o o o o | | o o o o | | o o o o | | o o o o | | o o o o | | o o o o | | o o o o | *---------* /_______\ ``` You can check [this reference implementation](https://tio.run/##bZDNCsIwEITveYohXtq0Rat4EXyTglQb7YJsQloPgu9es63/eAlhd@bb2fXXvnW8GobGHtH5@mC7lnzC6UYhYAutFRRm6MlLIYsVaJNwVqbIoG9a3oq1ElFr60bh6AIIxAg1n2zCORY5ilKIbwKJbz66hbeMyILSB7WqvrB711wVOusljxlbxeh5pjAv@TQgShXOxFYMU0Q4bXj83H7EojOR9eGVoT44fzl35Pi19xR3N40u/kQNtr@EuPcgJ@D3Ccp8Ldv7QNwnn0dOhzs) (ungolfed). --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing! [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~131~~ 117 bytes ``` param($n)' '*$n+" |" $n..1|%{" "*$_+"/$(' '*++$i)\";$x="*-$('-'*++$i)*"} $x ,("| $('o '*$n)|")*$i $x " /$('_'*--$i)\" ``` [Try it online!](https://tio.run/##LcxBCoMwEEbhfU4x/IwkmRil3ZbepCAuhAoaxS4qND371Ei334O3Lu9hez2HaVJd@62fHSdvyQqnAMownJrmkqsPCMJdQMuu5BB49A/ceL9D4mHxb4Kv4d3UDpkOXs6Vz/DCYwmgcuisxHgeVPX6Aw "PowerShell – Try It Online") Line breaks added for clarity, but they could just as easily be `;` (it's the same byte count either way). We're basically brute-force building the rocket one line at a time. We start by taking input `$n`, then construct a string of `$n` spaces and the nose antenna. We then loop from `$n` down to `1`, using a triangular number trick with `$i` to get the appropriate number of middle spaces for the nose cone. Including the construction of the joiner into the loop allows us to re-use `++$i` to both create the joiner and increment for our triangular number, saved into `$x` for later use. We then use array-multiplication with the comma operator to construct the body of the rocket, then `$x` onto the pipeline again for the bottom. Finally we output the engine part with the appropriate `_` in between. All of those strings are left on the pipeline, and default implicit output gives us newlines for free. *-14 bytes thanks to VisualMelon.* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes ``` NθP×θ_←↗¹Pθ←²↑*↑⊗θ↘*UO⊕θ⊗θo ↑P⊕θ↑↗θ|‖B ``` [Try it online!](https://tio.run/##XY89D4IwEIZ3fwXpVAwO6gabYSHxK0RmA3hAk9JCvWJM/O8V0Ah1vLvneXNvXqUqlyk3JhKNxqOuM1C0dYPFQXNkjWIC6YXVcKet55ArcYeT7ID6eyiwH84j4idNzMoKPWdtu@2EDILnbOZOH7kk9iKUOuNw68VpH8qH@MZ/@FPGpShpJHIFNQgc@bnbg9Ihv1@Txv7KFm3sv9DUgLyGxBgKDjnuNCKogj@pGxizNauOvwE "Charcoal – Try It Online") Link is to verbose version of code. Works by drawing the left half of the rocket and reflecting it. Explanation: ``` Nθ ``` Input the size of the rocket. ``` P×θ_ ``` Print the `_`s at the base of the rocket. ``` ←↗¹ ``` Move left and print the `/` at the left of the base. ``` Pθ←² ``` Print the `-`s on the second layer. ``` ↑*↑⊗θ↘* ``` Print the left side of the rocket, and leave the cursor inside the body. ``` UO⊕θ⊗θo ↑ ``` Fill the rocket with `o`s and move the cursor up. ``` P⊕θ↑ ``` Print the top row of `-`s and move the cursor up. ``` ↗θ|‖B ``` Print the nose cone and reflect to complete the rocket. Alternate solution, also 38 bytes: ``` Nθ×θ_↖¹P←θ²↑*F⊗θ←⪫|¶… o⊕θP←⁺²θ↖*↖θ|‖B← ``` [Try it online!](https://tio.run/##bY5BC4IwGIbv/Yqx0xZ2yG55yy5GhUTdgtD1icLcdG6B4H9fk0FKdfyej@d9X1ZmismMW5uIxuizqXNQpKXRIlWV0ORa1dCRNkD4gemHbm/NEQodoLVDJ8N11Xju6aSHc8WFLLEDhVSI7KXJOTxdFUXpXD7IShA83AUOUNwzDnEpG4KRdHcimIIahPYi/duectORcFzxu9cP@ILTXDyM7wsUHJjeGa1BFbz3wTSydmNXL/4G "Charcoal – Try It Online") Link is to verbose version of code. Works by drawing the right half of the rocket and reflecting it. Explanation: ``` Nθ ``` Input the size of the rocket. ``` ×θ_↖¹ ``` Print the base of the rocket. ``` P←θ²↑* ``` Print the second layer. ``` F⊗θ←⪫|¶… o ``` Print the body of the rocket. ``` ⊕θP←⁺²θ↖* ``` Print the top of the rocket. ``` ↖θ|‖B← ``` Print the nose cone and reflect to complete the rocket. [Answer] # T-SQL, 265 bytes ``` DECLARE @n INT=0,@o varchar(max)=''z:SELECT @o+=space(@-@n)+'/'+replicate(' ',@n*2)+' \ ',@n+=1IF @n<@ GOTO z PRINT space(@)+' | '+@o+stuff(replicate('*'+replicate('-',@*2+1)+'* ',2),5+2*@,0,replicate('|'+replicate(' o',@)+' | ',2*@))+' /'+replicate('_',@*2-1)+'\' ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/edit/1199167)** [Answer] # [Python 2](https://docs.python.org/2/), ~~165~~ 154 bytes ``` i=input() m=["*-"+"--"*i+"*"] print"\n".join([" "*i+" |"]+[" "*(i-x)+"/ "+" "*x+"\\"for x in range(i)]+m+["|"+" o"*i+" |"]*2*i+m+[" /"+"_"*(i*2-1)+"\\"]) ``` [Try it online!](https://tio.run/##PYw5CsMwEEV7n2L4laRBMXFqn8QWIUWWCXhkhAMK@O6K5CLdX9/63V5Rh1JkFF0/m7HdMk5wHgzv4YThELo1iW6YFad3FDUT6KhoR@DDGPHZMnqqP6o@M@YZj5gokyilmz7vRmzgpe73Nop/ghuqajn1tbg2mBv82R6IYEu5/AA "Python 2 – Try It Online") *-11 with thanks to @wilkben for some great hints* Nothing very exciting here. Just builds each line in a list and then prints with `'\n'.join()`. [Answer] # IBM/Lotus Notes Formula Language, ~~262~~ ~~246~~ 236 bytes ``` L:=@NewLine;M:="*"+@Repeat("-";i*2+1)+"*"+L;N:=@Repeat(" ";i+1)+"|"+L; @For(x:=0;x<i;x:=x+1;@Set("N";N+@Repeat(" ";i-x)+"/"+@Repeat(" ";x*2+1)+"\\"+L)); @Set("N";N+M+@Repeat("|"+@Repeat(" o";i)+" |"+L;2*i)+M+" /"+@Repeat("_";i*2-1)+"\\"); ``` Basically a port of my Python 2 answer. Newlines in the code added for readability. They are not required by the interpreter. The formula takes it's input from `i` which is a numeric field on the same form. There is no online interpreter for Notes formula so here is a screen shot of the output from 1 to 4: [![enter image description here](https://i.stack.imgur.com/SDSPg.png)](https://i.stack.imgur.com/SDSPg.png) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~52~~ ~~50~~ ~~47~~ ~~45~~ 43 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '|'/ILúí`©„ oI>∍'|ìI·иI>'-×'*ì.ø`®ð'_:».º.c ``` -2 bytes thanks to *@Grimmy*. [Try it online](https://tio.run/##AUcAuP9vc2FiaWX//yd8Jy9JTMO6w61gwqnigJ4gb0k@4oiNJ3zDrEnCt9C4ST4nLcOXJyrDrC7DuGDCrsOwJ186wrsuwrouY///NA) or [verify some more test cases](https://tio.run/##AUwAs/9vc2FiaWX/NUX/J3wnL05Mw7rDrWDCqeKAniBvTj7iiI0nfMOsTsK30LhOPictw5cnKsOsLsO4YMKuw7AnXzrCuy7Cui5j/yzCtj//). **Explanation:** ``` '| '# Push a "|" IL # Push a list in the range [1,input] '/ ú '# Push a "/" with that many leading spaces í # And reverse each string so the spaces become trailing ` # And push all strings in this list to the stack © # Store the last one in variable `®` (without popping) „ o # Push string "o " I> # Push the input+1 ∍ # Extend the string to that size '|ì '# And prepend a "|" I· # Push the input doubled и # And repeat the string that many times as list I> # Push the input+1 again '-× '# And create a string with that many "-" '*ì '# And prepend a "*" .ø # Then surround the earlier created list with this string ` # And push all separated to the stack ® # Push the string from variable `®` again ð'_: '# And replace all its spaces with "_" » # Now join every string on the stack by newlines .º # Mirror it intersected horizontally .c # And centralize each line (which adds leading spaces where necessary) # (after which the result is output implicitly) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 130 bytes ``` ->n{["%#{n+2}s"%?|,*(1..n).map{|x|"%#{n-x+2}s%#{x*2}s"%[?/,?\\]},k="*-"+"--"*n+?*,[[?|,*[?o]*n,?|]*" "]*n*2,k," /#{?_*n+=n-1}\\"]} ``` [Try it online!](https://tio.run/##VYxBDoIwEEX3nKIZQqLTKQTUJc5B2sbogg2xEpEE0/bsFYgbdu/lv/z39Pimrk3q6ryGIvdONnGEggPhoS5Ldyyf98GHOWyjmtd5oRm3THNFbIyN1LeACiQoBegkI2m9fmh@WXTEwSIIWBAb6glElXu@LWHrVB2NARvTMH1G0enaZitlf232etrrea8Xm34 "Ruby – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 248 bytes ``` i;f(n){char d[i=2*n+4],o[i];d[i]=o[--i]=!memset(d,45,i);o[--i]=*o='|';*d=d[i]=42;for(i=1+n;i;)printf(--i-n?"%*s/%2$*s\\\n":"%*s|\n",i,"",~i-2*~n-i);for(puts(d);i<=4*n;)i++<=2*n?o[i]="o "[i&1]:puts(o);printf("%s\n /%.*s\\",d,--n,memset(o,95,n+=n));} ``` This is surprisingly hard to get right, especially with off-by-one errors. I still might be overflowing the stack... I fixed the bug I mentioned with `n=23` and onwards; turns out that `i` was being decremented in the wrong place, so `o` was being overwritten and one byte of it was left uninitialized. Luckily, fixing this didn't cost me anything. I've added a testcase for `n=50` and a fun one for `n=0`. *-11 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!* [Try it online!](https://tio.run/##bY7NboMwEITveQrXKo1t7CZQODQbKw8CHCIc2j2wjoD2kp9XpwZxqtjL7n4azUxtvup6HBEaQfJWf5875gq0qaI4q7QvsILwV9YXxoT10l7a/jIIp7Nco4QFK2@39y0oZ2dxlkLjO4E2iQkQ5LVDGhoRpIZOPFL9LkpfVV@WJfHD9N/DoVFzrp9oUvUkE7wni@vP0AsnAY82UwQS4/g4lTtNzSz3jBf4llSHWeclLEk86ktiu@h9CuHaaWNIL9W9/sw1xZakhMcY5Kw9I4lfj05ubhsWphF7CWz25KGZhIUmqzRdpR@rNFul@f@4x/gH "C (gcc) – Try It Online") Also, here's your rocket at `n=0`: ``` | *-* *-* /| |\ ``` Looks more like space junk to me... Ungolfed and an explanation (plus this weird corner case): ``` int i; void f(int n) { char d[i=2*n+4], // holds the *---* line; 2*n+1 dashes plus an extra 3 for the asterisks and the null byte o[i]; // holds the | o | line; 2*n+1 for the 'o ' and extra 3 for pipes and null byte d[i]=o[--i]=!memset(d,45,i); // null-terminate d and o; set d to dashes starting at d + 1 and ending at d+i-2 o[--i]=*o='|'; // set the first and last bytes of o to the pipe *d=d[i]=42; // set the first and last bytes of d to asterisks for(i=1+n;i;) // print top of rocket printf(--i-n?"%*s/%2$*s\\\n":"%*s|\n",i,"",~i-2*~n-i); // on first iteration, print the tip and the correct number of spaces; the * before s pads the empty string with a variable number of spaces // after that, print the cone; use 2$*s to use the second argument to save a byte // if anyone can figure out how to remove the need for newlines, that would be appreciated // print the dashed line for(puts(d);i<=4*n;) // generate and print the tube i++<=2*n? // first half of loop o[i]="o "[i&1] // generate ' o ' :puts(o); // print the line // n+=n here doubles n for the correct number of underscores printf("%s\n /%.*s\\",d,--n,memset(o,95,n+=n)); // print the last dashed line and then generate the underscores and print in one go // it's shorter doing a sized print than null-terminating o } ``` And for the explanation of the corner case: the leading and terminating `|` are set as well as one character (the ) but never printed because there is only one iteration (as `0 <= 0` and `0 <= 2 * 0`). Because `n` is `0`, `d` is not set by `memset`, and is printed as `| |`. The rest should be pretty self-explanatory; the middle is not printed because the loop terminates before it can begin and neither is the cone for pretty much the same reason. There's only one `-` in `*-*` because `n` is `0` (in `2n+1`). [Answer] # Batch, ~~700~~ ~~614~~ ~~573~~ ~~538~~ ~~498~~ 452 bytes Notes: * **Must be started from `cmd.exe`'s command line using:** `Echo(rockets n|cmd /V:On`, where `n` is an integer. * Program builds the Nth rocket on a line by line basis, incrementing the values used to repeat characters using the N value * If the file is run without a parameter, it will output rocket n 1 by default. * lines `1` and `7` have trailing spaces **filename**: `rockets.bat` ``` @ECHO OFF&Set $=Set !$!}=ECHO(&!$!F=For /L %%A in (1,1,&!$!D=)Do &!$!P=^|&!$!/A _=]=W=1,H=O=2,L=3 %F:1,1=2,1%,%1%D%!$!/A W+=1,O+=1,H+=2,_+=2,L+=2 !$!.=!P!&!$![=!W!&%F%!O!%D%!$!.= !.! %}%!.!&%F%!W!%D%(!$!.=/ %F:A=B%![!%D%!$!.= !.! %F:A=C%!]!%D%!$!.=!.! !$!.=!.!\&%}%!.!&!$!/A [-=1,]+=2) !$!*=*&%F%!L!%D%!$!*=!*!- !$!*=!*!*&%}%!*!&!$!.=!P! %F%!W!%D%!$!.=!.!o !$!.=!.!!P!&%F%!H!%D%%}%!.! %}%!*!&!$!.= /&%F%!_!%D%!$!.=!.!_ !$!.=!.!\&%}%!.! ``` [The ungolfed version [1131 bytes]](https://pastebin.com/bp6EBEuy) [Answer] # [Wren](https://github.com/munificent/wren), 156 bytes I am very surprised that Arnauld is so easy to outgolf ... ``` Fn.new{|n|" "*(n+1)+"| "+(n..1).map{|i|" "*i+"/%(" "*(1+2*(n-i)))\\ "}.join()+"*%("-"*(1+2*n))* "+"| %("o "*n)| "*2*n+"*%("-"*(1+2*n))* /%("_"*(2*n-1))\\"} ``` [Try it online!](https://tio.run/##bY5BCsIwEEX3PUUYEDIJHYm4desF3BaklCyi7VRiMUjTs8dpdely/n//MSl6Lq82qjh2dz@pkypnJvZpzpxBgdFsHVrIFVjNRA5paB9zDlsZLOx3esOcPQhbB0RsmgoWuo2BtSyNAPUPYEQjIshKwlFmjCI2Uvzh1Kq@SiJ37VYtLOXyfk5@oBTD5PX3Z@ravtdHxPIB "Wren – Try It Online") [Answer] # JavaScript (ES6), ~~158~~ 156 bytes This implements the straightforward *repeat everything* approach. ``` n=>` `[N=n*2,R='repeat'](n+1)+`| ${(g=k=>k?` `[R](k)+`/${' '[R](N-k---k)}\\ `+g(k):s=`*${'-'[R](N+1)}* `)(n)+`|${' o'[R](n)} | `[R](N)+s} /${'_'[R](N-1)}\\` ``` [Try it online!](https://tio.run/##ZYyxDoIwFEX3fkUHE/qo1YBOJsU/YGAVYgkWoiUtAeICfHtt0cUwvnPuO6/yXQ5V/@xGps1D2ppbzROBxS3lOoz3GQ962clyDAqiaQRUzGg3kYYrnqir32UFUQ4fd1OAA3@lTDHGFCx5jgRtnL0MXITOs693mSVEAoj2Of9nVqFhwTNaiynQYcG@ef81I98TtjJ6MK08tKYhNYkA0D@JN@S0IWcA@wE "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), ~~164~~ 162 bytes This one builds the rocket recursively. ``` f=(n,x=y=0,w=2*++n)=>y<w+n?`/\\ |*-o `[(x>w?x=~!++y:(y?y-n&&~y+3*n?y>n?x&1?2:x%w?6:3:x+y-n&&x-y-n&&2:x%w?5:4:x-n?2:3)||x>n)&7]+f(n,x+1,w):` /${'_'.repeat(w-3)}\\` ``` [Try it online!](https://tio.run/##Zc3disIwEAXge5/CBa2ZTqO28QeCaR5ku9iirewiE1ExE6y@enXdq8WrA985cH6qS3XaHL8PZ0luW3ddYwQlbIKZJt5kMSKBycPKI9lyUhT9NpauV34Kzr1lc/9ADFoEGyRF0T2gismGnCxHqc00D71daKUZXz3LV/z5XM80S3quFLQt5wTR8gub33dMEw@67E8G19F6ND7Wh7o6Cy8V3Iqi7DaOTm5fj/duJxqRAvT@S/Ym6k1mAN0D "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = size of the rocket x = y = 0, // (x, y) = current coordinates w = 2 * ++n // w = width of the rocket - 1; increment n ) => // y < w + n ? // if this is not the last row: `/\\ |*-o\n`[ // pick the next character from this string ( x > w ? // if this is the end of the row: x = ~!++y // increment y and set x to -1 : // else: ( y ? // if this is not the first row: y - n && // if this is neither the top ~y + 3 * n ? // nor the bottom of the tank: y > n ? // if this is not the fairing: x & 1 ? // if x is odd: 2 // append a space : // else: x % w ? 6 // append either a 'o' : 3 // or a '|' on the borders : // else (fairing): x + y - n && // append a '/' if we're located on x - y - n && 2 // a border, or a space otherwise : // else (top or bottom of the tank): x % w ? 5 // append either a '-' : 4 // or a '*' on the borders : // else (first row): x - n ? 2 // append either a space : 3 // or a '|' in the middle ) // || x > n // turn '/' into '\' if we're in the right side ) & 7 // turn -1 into 7, false into 0, true into 1 ] + f(n, x + 1, w) // end of character lookup; recursive call with x+1 : // else: ` /${'_'.repeat(w - 3)}\\` // append the nozzle and stop the recursion ``` [Answer] # [Python 2](https://docs.python.org/2/), 126 bytes ``` p=n=input() s="_ |"+" \/"*n+"--**"+" o||"*2*n+"--**__\/" while s:p+=s>"^";print' '*p+s[3]+s[:2]*(n-p)+s[:4:2];s=s[4:];p-=p>0 ``` [Try it online!](https://tio.run/##NYlBCsMgEEX3OYXMJokiLSYrZXKR1LoqRChm6BhKQejRrVl08/jvP/rkbU@mVsKEMdGRh7FjhG8QBRQIcbuATAq0lvL0vRSQ5v@E0HL33uLzIdiSQl7gDo5eMeVe9JIUr5NvsMbLIWkazz03c4y8ztY70kjLtdbpBw "Python 2 – Try It Online") Includes some trailing whitespace, which I hope is allowed. One of them is the first character of `s`, a `DEL` character. The main idea is to store the design of each line of the rocket in a big template string `s`. It's a bit easier to see in this slightly less golfed version, where the template for each line is given in a list: **134 bytes** ``` n=input() p=n+2 w="*--*" for a,b,c,d in["| "]+["/ \\"]*n+[w]+["| o|"]*2*n+[w,"/__\\"]:p-=p>0;p+=c=="_";print' '*p+a+(b+c)*(n-p)+b+d ``` [Try it online!](https://tio.run/##HclNCoMwEEDhfU4xzEaTSbCku8r0IiriD6VuJoMoUvDuae3ye08/2ztJzFl4Ed230hploWgORheCQ/NKKwx@9JOfYZEGTwDAjhqsANoWOyfUHJdPSOeP8R88Vn1/7YcG1uetVuKJGXusdV1kK6BwSgOVI03WlRLU0khzzvcv "Python 2 – Try It Online") Each line of the rocket is drawn from a template like this with four characters `a,b,c,d` specified for each line: ``` abcbcbcbcbd ``` It's an `a` followed by alternating `b`'s and `c`'s followed by a `d`. The number of leading spaces, which also governs the number of repetitions of `bc`, is given by `p`, and is updated with each new line. I'm aware that Python 3's f-strings and walrus operator could probably shorten many things, but I like Python 2 for golfing ASCII art because it means finding hacks to do things like that instead. [Answer] # [Perl 5](https://www.perl.org/), 150 +1 (-p) = 151 bytes ``` $x=($n=$_)*2;map{$r.=$"x($n-$_).'/'.$"x(2*$_+1).'\ '}0..$n-1;$s='*'.'-'x$x."-* ";$l='|'.' o'x$n." | ";$_=$"x$n.$"."| $r$s".$l x$x."$s /".'_'x--$x.'\ ' ``` Run with `-p`, provide input to stdin. Started with basically the reference implementation, and just golfed it down, though there might be better ways. I could save a byte by leaving off the final newline, but I like it better with it in. [Try it online!](https://tio.run/##Hc3BCsIwDMbx@56ihA@ilWZu4Gn0TYTiwYNQu7J6KDhf3Zp6/P9Cknzf4qU1VH9A8ghHOy/PW35jEw@qik5ReGTpOVuE06R9HfhzFtHxtKB4tizsuKIKOTvQguh5VzOrYhIye8fQb2qChPYBGwoJovmvoZiRhANX57T7h9bm75pfjzWV5vIP "Perl 5 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~292~~ ~~289~~ 257 bytes Thanks to @mypronounismonicareinstate **-32B** ``` n=>{dynamic r="",t="*",i=n,j;for(;i-->0;)r+=" ";r+=" |\n";for(;++i<n;){for(j=0;j<n+i+2;++j)r+=n-i-j==0?"/":" ";r+=@"\ ";}for(;i-->0;)t+="--";t+="-*\n";r+=t;for(;++i<n*2;){r+="|";for(j=0;j++<n;)r+=" o";r+=" |\n";};r+=t+" /";for(;i-->1;)r+="_";return r+"\\";} ``` [Try it online!](https://tio.run/##TZAxa8MwEIXn@leImyyfRZxAl57ldOrUvYuhFNcOJ@gFZGUISX67K8mFetEh3XvvO90wm2Hm5e0iQ8sSajUHz3Lq1GQXsd3t@ypfPzwobwHqYKGCmq3UjqazL4mN6RrSHi0ooFzuvcDaRORWSN/SxdmGXCvIeIjvLjnEsHHWNkfYwcuf/RX6AuixzQ4x1BigXKsUHnVhQ6gOkZHQ95WbUYgJnQc6bwd7ZDeC2sH/D/ar8jMKx3DxojxC30fxQkUUqTIuRrHdk@L2OR6Iunj68BzGd5axnErWmpZf "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 95 bytes v1.0.2, my goal is to get this sub-60, which I think is actually doable. ``` :i)" ":s*"|"n i,{:j i\-s*"/ "2s*j*"l"n}%"*-""--"i*"*"n+++:q{"| ""o "i*"|"n}2i**q" /""__"i*);"l" ``` This program uses miniscule L instead of backslash since I spent like four hours today trying to find a way for GS to print ONE backslash and couldn't get it to work. It's ridiculous. Temporary patchfix, looks acceptable in TIO. WANNA SEE A GROSS PROGRAM? Okay, so this is obviously a disaster, so we're going to need to go through it *very* carefully to see why it works. Let's break this into chunks. ``` :i)" ":s*"|"n #Top Needle i,{:j i\-s*"/ "2s*j*"l"n}% #Roof "*-""--"i*"*"n+++:q #First star-dash line {"| ""o "i*"|"n}2i** #Cabin q #Second star-dash line " /""__"i*);"l" #Rocket cone ``` So, that's mildly more digestible for my format. Work is slow today, so enjoy this overly arduous explanation. Before we start this, I'm clarifying one thing. Input is from the header, slotted right into the stack, and our output is let on the stack, printed out when the program finishes. ``` :i)" ":s*"|"n #Print the top needle :i #Set our input to i; we'll call it INDEX. ) #Increment the INDEX on the stack by 1 (not the variable) " ":s #Put a space on the stack, and make s remember it. We'll call it SPACE. * #Multiply this space by INPUT+1 "|" #Needle! n #Newline ``` So, our stack now looks something like `" ""|""/n"`, which is concatenated all together on output. Every future chunk ends with n characters, and we never back up further in the stack, so we never touch this again. ``` i,{:j i\-s*"/ "2s*j*"l"n}% #Print the roof i, #Make an array of size INDEX, from 0 to i-1 { }% #Block notation. On every element in this array, perform this {:j }% #Remember our index as J { i\- }% #Subtract J from INDEX { s* }% #Make that many spaces { "/ " }% #Make a slash then a space { 2s*j* }% #Make 2*j spaces { "l" }% #lmao backslash no work { n}% #Add a newline ``` Which is for what we're looking, for every line. Done INDEX times, we have our roof!. Next! ``` "*-""--"i*"*"n+++:q #Print the star-line. "*-" #First two characters. "--" #Next two. i* #We want a number of those double-dashes equal to INDEX. "*" #Last asterisk n #Newline +++ #Concatenate that all together. We haven't done this before, but... :q #We're remembering this entire line in Q, which saves us a TON ``` Next we have the o-cabin. Surprisingly the easiest part of the program. ``` {"| ""o "i*"|"n}2i** #Build the cabin 2i* #Double INDEX { } * #Perform the block 2*INDEX times {"| " } * #First two characters { "o " } * #You know the drill. Combination of the two prev tactics. { i* } * #Make that many windows this row { "|" } * #East wall { n} * #Newline, as always. ``` Now comes the trickiest part of the entire program ``` q #Print the second star line q #Print Q, as established above ``` And the bottom of the rocket. ``` " /""__"i*);"l" #Bottom of the rocket " /" #So, how's your day been? Mine's been pretty slow. "__" #Slow enough that I had time to write this whole post. i* #Boss isn't even watching. Maybe I'll do another later. ); #Remove the last _, since we've one too many. "l" #lmao backslashes ``` And that's everything! Why don't you check my work by [trying it out online](https://tio.run/##FcsxCoQwEEDRqwwfLJwYhJTZqwgWgsuIxHVjp549xvI/@N9tnfP0t99RQonWIsSsXCSx7oyL2OBr90LIuigr6W5QD95jipKcc3E/uQQ2ea3OdzDVHelhHKu1n3qW8gA "GolfScript – Try It Online")? 78 is the max size you can get before it starts to linebreak on TIO on my monitor, try to find yours! [Answer] # Clojure (307 bytes) Great challenge, because it let me crank up Def Leppard's "Rocket" and Elton John's "Rocket Man" while coding. Always a plus! :-) Golfed: ``` (defn r[n s](apply str(repeat n s)))(defn b[n](r n \ ))(defn p[s](println s))(defn k[n](let[t(str \*(r(inc (* n 2))\-)\*)](p(str(b(inc n))\|))(doseq[l(range 0 n)](p(str(b(- n l))\/(b(inc(* 2 l)))\\)))(p t)(doseq[l(range 1 (inc(* n 2)))](p(str "| "(r n "o ")\|)))(p t)(p(str " /"(r(inc(* 2(dec n)))\_)\\)))) ``` [Try it online!](https://tio.run/##XY/BCsIwEETvfsWS025BtNW/SYq0NYoa0pjGg@C/182mRfCykNl5M5vBjfdXtPOMZ3vxELWHqcUuBPeGKUWMNtguAatEVDy99i1GlgysUtAMhXjzyYmzqI9sdDbphBwFpsKINz8AVgw3RGZLpiIG8xp72XmWPzlgnOxTO4ydv1rYs/7zbRl37NsVhuOa/CZj8o0B0j9ew@KT2jUJ1AeUfESNoKR2oZc17FS5ODfwl@Q6MqdSRJsNPqCmPBuZB5lHmucv "Clojure – Try It Online") Ungolfed: ``` (defn repeat-str [n s] (apply str (repeat n s))) (defn blanks [n] (repeat-str n \ )) (defn rocket [n] (let [ top-bottom (str \* (repeat-str (inc (* n 2)) \-) \*) ] (println (str (blanks (inc n)) \|)) (doseq [ l (range 0 n) ] (println (str (blanks (- n l)) \/ (blanks (inc (* 2 l))) \\))) (println top-bottom) (doseq [ l (range 1 (inc (* n 2))) ] (println (str "| " (repeat-str n "o ") "|"))) (println top-bottom) (println (str " /" (repeat-str (inc (* 2 (dec n))) \_) \\)))) ``` [GUITAR..! DRUMS..!](https://www.youtube.com/watch?v=bpcc43NV394) [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 65 bytes ``` ›ð*\|+,(⁰nε\/꘍nd›\\꘍+,)×⁰d›-×+:,⁰d(\|‛ o⁰*ð\|+++,),‛ /\_⁰d‹*\\++, ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%80%BA%C3%B0*%5C%7C%2B%2C%28%E2%81%B0n%CE%B5%5C%2F%EA%98%8Dnd%E2%80%BA%5C%5C%EA%98%8D%2B%2C%29%C3%97%E2%81%B0d%E2%80%BA-%C3%97%2B%3A%2C%E2%81%B0d%28%5C%7C%E2%80%9B%20o%E2%81%B0*%C3%B0%5C%7C%2B%2B%2B%2C%29%2C%E2%80%9B%20%2F%5C_%E2%81%B0d%E2%80%B9*%5C%5C%2B%2B%2C&inputs=4&header=&footer=) Slowly constructs the string bit by bit. ]
[Question] [ * Alice (A) and Bob (B) decided to have a battle. * Each combatant has 10 health. * They take turns to roll a 6 sided die for damage. * That damage is removed from their opponent's health. * In the end either Alice or Bob, will vanquish their foe. --- Show me how the battle went. Outputting these codes for the actions which have taken place. Attack ``` B a A ^ Combatant ^ Action (attack) ^ Target ``` Roll ``` B r 4 ^ Combatant ^ Action (roll) ^ Value ``` Health change ``` A h 6 ^ Combatant ^ Attribute (health) ^ Value ``` Win ``` A w ^ Combatant ^ Action (win) ``` --- Example output: ``` A a B A r 4 B h 6 B a A B r 6 A h 4 A a B A r 6 B h 0 A w ``` --- Here are the rules: * Write in any language. * A single roll of the die should have an equal chance of resulting in any one of the numbers 1, 2, 3, 4, 5, or 6. * Alice always starts (Bob is chivalrous, in an old-fashioned way). * Output an action for each turn. * You must report the attack, roll, damage and win actions. * Combatants are upper case, actions are lower case. * It must not consistently produce the same result. * There must be at least one whitespace character between an output combatant, action and value. * The win action takes place when the opponent has zero or less health. * All parts of an action must be on the same line. * There should be one action per line. * Fewest bytes wins. Have at it! [Answer] # [Python 3](https://docs.python.org/3/), 131 bytes ``` x,y="AB" from random import* X=Y=10 p=print while X>0:p(x,"a",y);d=randint(1,6);p(x,"r",d);Y-=d;p(y,"h",Y);x,y,X,Y=y,x,Y,X p(y,"w") ``` [Try it online!](https://tio.run/##Hc1BCsMgFATQvacIfxXLFBIKXVR@oD2FLgO2KDRGRIie3tqshuExTKzZ7eHWWkFler5IfNK@DWkNtoff4p7yRWg2PE8ickw@ZHE4/30PepkecSyglVClsvwfdR5n3KU6JRGsVObKtvcKcgQjVb@ChuGKAgMtTjpItvYD "Python 3 – Try It Online") -8 bytes thanks to officialaimm -2 bytes thanks to ChooJeremy [Answer] # [Python 3](https://docs.python.org/3/), 127 bytes *This is an improvement on [@HyperNeutrino answer](https://codegolf.stackexchange.com/a/159903/20064) that wouldn't fit in a comment. See the explanation below.* ``` x,y="AB" s=id(0) X=Y=10 p=print while X>0:p(x,"a",y);s=s**7%~-2**67;d=s%6+1;p(x,"r",d);Y-=d;p(y,"h",Y);x,y,X,Y=y,x,Y,X p(y,"w") ``` [Try it online!](https://tio.run/##HY1BCsIwFAX3OYV8KDTxFVKFFgxf0FMkSyFCClJDU2iy8eqxdDnMwMSyhu98rTWjMD2eJBJPvtVSWHbcaxE5LtO8ii1Mn/fJ3vUtthn0IhRpEielxubXXZQaRuM5NcO5N0exELw0rmO/cwEFgpNm38DCcUGGgxWH2kjW@gc "Python 3 – Try It Online") --- ## An epic quest for a shorter python dice roll **TL;DR: It's possible to shave 4 bytes off the standard python dice roll by using RSA encryption.** I wanted to see if the standard python dice roll (**32 bytes**) could be shortened a bit: ``` from random import*;randint(1,6) ``` In particular, `id(x)` is quite convenient to bring some non-deterministic value into the program. My idea then was to somehow hash this value to create some actual randomness. I tried a few approaches, and one of them paid off: [RSA encryption](https://en.wikipedia.org/wiki/RSA_(cryptosystem)#Encryption). RSA encryption, due to its simplicity, only requires a few bytes: `m**e%n`. The next random value can then be created by encrypting the previous one. Assuming the `(e,n)` key is available, the dice roll can be written with **22 bytes**: ``` s=id(0);s=s**e%n;s%6+1 ``` That means we have about 10 bytes to define a valid RSA key. Here I got lucky. During my experiments, I started to use the [Mersenne prime](https://en.wikipedia.org/wiki/Mersenne_prime) **M67** only to realize later on that [Mersenne made a mistake](https://en.wikipedia.org/wiki/Mersenne_prime#History) including **M67** in his list. It turns out to be the product of `p=193707721` and `q=761838257287`. I had found my modulus: ``` n=~-2**67 ``` Now, the exponent and the [Charmichael totient](https://en.wikipedia.org/wiki/Carmichael_function) `lcm(p-1,q-1)` need to be coprime. Luckily again, the first prime number that do not divide the totient of n is only one digit long: 7. The dice roll can then be written using **28 bytes** (4 bytes less than the standard approach): ``` s=id(0);s=s**7%~-2**67;s%6+1 ``` One good thing with **M67** is that the random value generated has 66 bits, which is more than the usual 64 bits RNG. Also, the use of RSA makes it possible to go back in time by decrypting the current value multiple times. Here are the encrypting and decrypting keys: ``` Encryption: (7, 147573952589676412927) Decryption: (42163986236469842263, 147573952589676412927) ``` I'm definitely not an expert in statistics or cryptography, so I can't really tell whether or not this RNG checks the criteria for "good randomness". I did write [a small benchmark](https://gist.github.com/vxgmichel/2f7cb31f32c5d92810d44ccca36c99b7) that compares the standard deviation of the occurrences of the 1 to 6 dice rolls using different RNGs. It seems like the proposed solution works just like other ones. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~146~~ 141 bytes ``` f(A,B,r,t,a,b){for(A=B=10;r=1+clock()%6,A*B>0;t=!t)printf("%c a %c\n%c r %u\n%c h %i\n",a=65+t,b=66-t,a,r,b,t?A-=r:(B-=r));printf("%c w",a);} ``` [Try it online!](https://tio.run/##TYyxDsIgFAB3vwKbkPDsI2kHGSRo4CdculASaiNSgxiHpr8uVieXyy13jg/OleKZRoMJM1rsYfZTYloZ1TYyqbZ2YXJXBlSg3pljI7PaZrinMWbPKuqIJdR1cZVE6PMnF0LHLlZoldjXGXslBP@@E/aYT5qrdGBmJYD8@7zWAORSbnaMDOaNZyA3S3k7H@zwKPxsQ/gA "C (gcc) – Try It Online") De-golf: ``` f(A,B,r,t,a,b){ for(A=B=10; //Initialize HP r=1+clock()%6, // Get the number of processor cycles the program has consumed. This is relatively random, so I call it good enough. A*B>0;t=!t) // Flip t for change of turns printf("%c a %c\n%c r %u\n%c h %i\n", // Print the turn a=65+t,b=65+!t,a,r,b, // 65 is ASCII for 'A', 66 for 'B' t?A-=r:(B-=r)); // Deduct the damage. printf("%c w",a); // Print the winner } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 49 bytes ``` "BaABr0Aha"S3ô»D„AB‡[6LΩ©Tǝ¤H®-©16ǝ=®0‹#s]н…ÿ w? ``` [Try it online!](https://tio.run/##AVAAr/8wNWFiMWX//yJCYUFCcjBBaGEiUzPDtMK7ROKAnkFCw4LigKFbNkzOqcKpVMedwqRIwq4twqkxNsedPcKuMOKAuSNzXdC94oCmw78gdz///w "05AB1E – Try It Online") **Explanation** ``` "BaABr0Aha" # push the initial state of B S # split to list of characters 3ô # divide into 3 parts » # join each part on space and all on nl D„AB‡ # make a copy with A and B inverted [ # start a loop 6LΩ© # pick a random number in [1 ... 6] Tǝ # insert at position 10 of the string ¤H # get the last char of the string and # convert from hex ®-© # subtract the random number 16ǝ= # insert at position 16 and print ®0‹# # if the hp is less than 0, break s # swap the other string to the stack top ] # end loop н…ÿ w? # print the winner ``` [Answer] # [Perl 5](https://www.perl.org/), ~~93~~ ~~88~~ 87 bytes ``` $A=$B=10;$_=B;${$_^=v3}-=$%=1+rand 6,say"$_ a $' $_ r $% $' h $$_"until//>$$_;say"$_ w" ``` [Try it online!](https://tio.run/##K0gtyjH9/1/F0VbFydbQwFol3tbJWqVaJT7Otsy4VtdWRdXWULsoMS9FwUynOLFSSSVeIVFBRZ0LSBcpqKhyqagrZCioqMQrleaVZObo69sB2dZQheVK////yy8oyczPK/6v62uqZ2igZwAA "Perl 5 – Try It Online") [Answer] # JavaScript (ES6), 122 bytes ``` f=(h=[10,10,p=0])=>`${x='AB'[p]} a ${y='BA'[p]} ${x} r ${d=Math.random()*6+1|0} ${y} h ${H=h[p^=1]-=d} ${H<1?x+' w':f(h)}` ``` [Try it online!](https://tio.run/##HcmxDoIwFIXh3afoQNJWhNDFwXg1MLH4BARDQynVIG2AKAT77LWYnOX835O/@VgPDzNFvRaNcxKIgoIlBz8DSUnhUgXrDDjNcGFKizgK1gVwlv7vzptFg28CbnxS8cB7oV@E7o8h@yabLxYp7zmowtyBlRGILedndp1DjD74JImitnK17kfdNXGnWyIJpe4H "JavaScript (Node.js) – Try It Online") [Answer] # [Java (JDK 10)](http://jdk.java.net/), 180 bytes ``` v->{var r="";int p=0,H[]={10,10},h=0;for(;H[0]*H[1]>0;)r+=r.format("%3$c a %4$c%n%3$c r %d%n%4$c h %d%n",h+=Math.random()*6-h+1,H[p]-=h,p+65,(p^=1)+65);return r+(char)(66-p)+" w";} ``` [Try it online!](https://tio.run/##LY8xb4MwEIX3/IoTCpIdjAVqy@I6Y5UlU6QuiEouhNjUGMsYqijit1OXdrrv3r270@vELNKu@VprLcYRzkIZeOwA7PSpVQ2jFz6UeVAN9GGGLt4pcysrEO424s0K0IUjdPJK03YytVeDoW//8PoeVsnf1hFavs7p8TELB45HEVPGg@UZOZUVf@QZybOFSJ6xdnCIncqsOpzKvDpmDLuEOxrkXngUxU/7GgTEz/s6NlvjIG4CBgHkhhGRCT8LL6kTphl6hA9FKpM8vLJVyiWxSfFCkP3gOQ6Embv6yRlwCaqlcBgVRWpxEsF3xJaVbTEv99FfezpMntqQx2uDWiqs1XdkJq0x/rUtu2X9AQ "Java (JDK 10) – Try It Online") ## Credits * -8 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~122 120 96 92~~ 91 bytes ``` f=->x=?A,y=?B,m=10,n=m{p [x,?a,y],[x,?r,r=1+rand(6)],[y,?h,t=n-r] t<1?p([x,?w]):f[y,x,t,m]} ``` Saved 1 byte thanks to [Asone Tuhid](https://codegolf.stackexchange.com/users/77598/asone-tuhid). [Try it online!](https://tio.run/##KypNqvz/P81W167C1t5Rp9LW3kkn19bQQCfPNre6QCG6Qsc@UacyVgfEKNIpsjXULkrMS9Ew0wQKVerYZ@iU2ObpFsVyldgY2hdogFSVx2papQHlKnRKdHJja/@nRcf@BwA "Ruby – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 142 bytes ``` #define R(c,t)r=rand()%6+1,c&&printf(#c" a "#t"\n"#c" r %d\n"#t" h %d\n",r,t-=t<r?t:r),t||puts(#c" w") f(A,B,r){for(A=B=10;A*B;R(B,A))R(A,B);} ``` [Try it online!](https://tio.run/##RY7BasMwEETP8VcsMgnaVgLn0kMVE@xP8KWXUnBlKxW1ZbNe00OSX68apYVehplZlnlWn6yNMe9650MPjbSKkUpqQydx@/S4V3a3m8kHdjK3AloQOYvXIFIg2HbJsoCPX6tIsS75QEd@JlR8ucwrL/fPL4GZk5WqFeHZTSSrsi73hakeatPIWlWITTqjucbbHIytDxLhnG2WOw37sZcFwhvYYbKfEtFkGyeT/vElrP@Sel4pQGGya/y2bmhPS9QvYdJ@nAdvPUftbul99QP78AM "C (gcc) – Try It Online") [Answer] # Java 8, ~~230~~ ~~229~~ 228 bytes ``` v->{for(int h=104,a=h,x=0,y=1,A=10,B=A,r=0,t=0,T;a<119;System.out.printf("%c %3$c %c%n",x+65,y=(a<98?t=r+=Math.random()*6-r+1:a>h?(T=x<1?A-=t:(B-=t))<0?0:T:A*B<1?-16:(x^1)+17)+48,a=a<98?114:a>h?h:A*B<1?119:97))x^=a>h|A*B<1?1:0;} ``` -2 bytes thanks to *@ceilingcat*. Note: there is already [a much shorter Java answer, so make sure to upvote his](https://codegolf.stackexchange.com/a/159906/52210)! I use a completely different approach however, so figured it was worth posting as well. **Explanation:** [Try it online.](https://tio.run/##LVDfb4IwEH7fX9GYmbRSCM2cPwqV4Lu@SPayzKQrMHBYTKkE4/zb2akkd9f0u/su930H2Uq3PmX6kP72qpJNgzay1NcXhEptM5NLlaHt/YtQW5cpUvjj/rQkAOwGCdFYaUuFtkgjgfrWXV3z2mDgo0Iwf0qlKGgnfHoRjMaA0LWIqQHAQiaBDBlbBrtLY7OjV5@tdzLAzfForND47RWKGusR7ZzZO6zAMlwuIiuMIzbSFp6ROq2PmExmrnEYl6siwonoQhbFrrAcr6ESEvqRzxMeT9bQcNmM427PiMPmxJku4MDHUsamD34xzMFZfDknpNsLgP8GkPvBrQ@eyk/n7wqUDwY8DDqCfXhnQcLP55ckT@u0p7A@V9Xg2q3/Bw) ``` v->{ // Method with empty unused parameter and no return-type for(int h=104, // Temp integer with unicode for 'h' to save bytes a=h, // Second part (Action) x=0, // First part y=1, // Third part A=10, // Score player A, starting at 10 B=A, // Score player B, starting at 10 r=0, // Random dice-roll t=0, // Previous dice-roll T; // Temp integer a<119 // Loop until there is a winner: ; // After every iteration: System.out.printf(// Print: "%c %3$c %c,%n", // The three parts with spaces, and a new-line // First part: x+65, // Add 65 to `x` to convert 0/1 to 65/66 // (unicode values of A/B) (y= // Third part (after set-up): (a<98? // If the previous action was 'a' t=r+=Math.random()*6-r+1 // Roll the dice, and save it in `t` :a>h? // Else-if the previous action was 'r': (T=x<1? // If the first part changed to player A: A-=t // Subtract the previous dice-roll from A : // Else: (B-=t)) // Subtract the previous dice-roll from B <0? // If this score is below 0: 0 // Use 0 : // Else: T // Use this score : // Else (the previous action was 'h'): A*B<1? // Is there a winner: -16 // Change the third part to a space : // Else: (x^1)+17) // Change the third part to the other player +48, // Add 48 to convert it to unicode a= // Second part: a<98? // If the previous action was 'a': 114 // Change it to 'r' :a>h? // Else-if the previous action was 'r': h // Change it to 'h' : // Else (the previous action was 'h'): A*B<1? // If either score is 0: 119 // Use 'w' : // Else: 97)) // Use 'a' x^= // First part set-up: a>h // If the previous action is 'r', |A*B<1? // or there is a winner: 1 // Change A→B or B→A : // Else: 0;} // A/B remains unchanged ``` [Answer] ## Batch, 174 bytes ``` @set/aA=B=10 @set c=A @set d=B :g @set/ar=%random%%%6+1,h=%d%-=r @echo %c% a %d% @echo %c% r %r% @echo %d% h %h% @if %h% gtr 0 set c=%d%&set d=%c%&goto g @echo %c% w ``` Explanation: `%` variable references are substituted at parse time. This has two useful benefits: * `%d%-=r` subtracts `r` from the variable named by `d` (i.e. indirect reference) * `set c=%d%&set d=%c%` is simply a straight swap. [Answer] # PHP 7.1: 159 bytes ``` <?php $A=$B=10;$t='AB';while($A>0&&$B>0){$a=$t[0];$b=$t[1];$d=rand(1,6);$$b-=$d;echo"$a a $b\n$a r $d\n$b h {$$b}\n";$t=strrev($t);}echo($A>0?'A':'B')." w\n"; ``` [Run it in the browser here!](http://sandbox.onlinephpfunctions.com/code/79a833581d55a878c3e79a8da8cfb5a8a5cc1303) # PHP 5.6: 156 bytes ``` <?php $A=$B=10;$t='AB';while($A>0&&$B>0){list($a,$b)=$t;$d=rand(1,6);$$b-=$d;echo"$a a $b\n$a r $d\n$b h {$$b}\n";$t=strrev($t);}echo($A>0?'A':'B')." w\n"; ``` [Run it in the browser here!](http://sandbox.onlinephpfunctions.com/code/ad3752f87c8167f19b29920b4309d5728f413706) Here's what the PHP 5.6 solution looks like with formatting and comments: ``` <?php // Initialize both HP counters $A = $B = 10; // Set the turn order as a string (which 5.6 allows to be unpacked into a list) $t = 'AB'; // Run this loop as long as both players have HP while ($A > 0 && $B > 0) { // Unpack the turn string into $a and $b variables; on the first run, $a = 'A' // and $b = 'B'. This is no longer possible in PHP 7.0, so the PHP 7.0 // solution needed to use an array instead. list($a, $b) = $t; // Set damage to a random number between 1 and 6 $d = rand(1, 6); // Subtract the damage from the referenced value $b. On the first turn, this // is 'B', so this ends up subtracting $d from $B. Next turn, $b will be 'A', // so it'll subtract $d from $A $$b -= $d; // Echo the string (interpolated values) echo "$a a $b\n$a r $d\n$b h {$$b}\n"; // Reverse the turn order string ('AB' becomes 'BA', which will affect the // call to list in the first line of the while-loop) $t = strrev($t); } // Someone's run out of HP; figure out whom by figuring out who still has HP echo ($A > 0 ? 'A' : 'B') . " w\n"; ``` [Answer] # F#, 238 235 bytes I thought I was doing well, but you've all far outclassed me! ``` let p=printfn let mutable A=10 let mutable B=A let x h a d= p"%s a %s"a d let i=(new System.Random()).Next(1,7) let j=h-i p"%s r %i"a i p"%s h %i"d j if j<=0 then p"%s w"a j while A*B>0 do B<-x B"A""B" if B>0 then A<-x A"B""A" ``` [Try it online!](https://tio.run/##VY9RS8MwFIXf@ysOkbFVXNs9CbIMWtAnEXG@iQ/Zmi4pbRLSzG2/vt6sKviW833nXm6aYbm3Xo55jmcpvEFPCWJnjwFPNxABKgT3kOfNoIR3mfWHhLpbKRGUxJw678dgvRbdHM7bVu4DGuunPUp2LkuSj/WjCf7yarUJm8@kkwG90AbCH77AMSISx50n35jkGvtjELtOouSr4j@peDmBMxQEap4Ajs0Ges8GRoBy1JovjDxhexmC7LM3YWrbL9I0e5HnsFjd3ac/vZarpf7d4THTtOMvq5hrtJR1g3bNi/hvM8kTE8TJnZSOp95WmwK1JVatl2dUrGSsYtNoVNfJMqqSONkRxfgN) Thanks to Rogem for the brilliant advice to use A\*B>0 instead of A>0&&B>0 (takes off 3 bytes). Thank you also to officialaimm, whose hint about predefining printf in the Python answer helped me shave a few bytes off too. [Answer] # [Haskell](https://www.haskell.org/), 204 bytes My attempt with Haskell, I wasn't able to get it more competitive unfortunately ``` import System.Random main=getStdGen>>= \g->putStr$q(randomRs(1,6)g)10(10::Int)"A ""B " (!)=(++) l="\n" q(x:z)a b p o=p!"a "!o!l!p!"r "!show x!l!o!"h "!show n!l!if n<1then p!"w"else q z n a o p where n=b-x ``` [Try it online!](https://tio.run/##NYw9y8IwFEb3/oqbi0OCH9jFoZiCLuKqq0vEa1NMb9ok0uqfr@GFdzvn4fBYE1/k3Dy3Xe9DgusnJuo2F8MP3xWdaVk3lK7pcSKuaw23Zl337zyExSDDX3WJslztVKPKrSy3VXXmpPAAiEfAQgql5XKpCqfxxlgMcqq@ysAdevC6F2gAhRdOZAwZo/UjTNm9QPvvnL19Au/LZIkhpyOSiwQDfIHBgM9vo6VAwPq@nub5Bw "Haskell – Try It Online") Explanations: ``` import System.Random --import random module main= --main function, program entry point getStdGen -- get the global random number generator >>= \g-> --using the random generator g putStr $ q --print the result of function q, passing in .. (randomRs (1,6) g) --an infinite list of random numbers, 1 to 6 generated by g 10 (10::Int) --the starting health of both players, --type annotation sadly seems to be required "A " "B " --The names of the players, --with an extra space for formatting (!)=(++) --define the operator ! for list (String) concatenation, -- we do this a lot so we save a bit by having a one byte operator l="\n" -- define l as the newline character q --define function q (x:z) --our list of random numbers, split into the next number (x) and the rest (z) a -- the health of the active player b -- the health of the player getting attacked p -- the name of the active player o -- the name of the player getting attacked = p!"a "!o!l --create the attack action string with a newline !p!"r "!show x!l -- append the roll action !o!"h "!show n!l -- append the health remaining ! -- append the result of the following if if n<1 -- if the player being attacked has been defeated then p!"w" -- append the win string for the active player else q z n a o p --otherwise append the result of calling q again with --rest of the random numbers, and the active players swapped where n=b-x -- define the attacked player's new health n -- their current health b - the random roll x ``` [Answer] # [Julia 0.6](http://julialang.org/), 175 bytes ``` p=println() f(l="AB",h=[10,10],a=1)=(while min(h...)>0;d=3-a;p(l[a]," a ",l[d]);r=rand(1:6);h[d]-=r;p(l[a]," r ",r);p(l[d]," h ",max(h[d],0));a=d;end;p(l[findmax(h)[2]]," w")) ``` [Try it online!](https://tio.run/##RcpBCsIwEIXhvacoWc1AWhKFLgwj6DVCFgPTkkgMJSj19rHtxuX/3vf85MRjawstNZV3LoCnGTKp@0PpSN4abU3QTBYJ1pjy1L1SgTgMA96ME7r07BbInoNWHXdKZy8BXaXKRcBeR3RxW3qqf1Y3VvFo2Ttu/eIv7FAbRMckbipyiDkVOU7057DrVSG29gM "Julia 0.6 – Try It Online") Long, ungolfed version: ``` function status(player, health) println("$player h $(max(0,health))") end function roll(player) x = rand(1:6) println("$player r $x") x end function play() players = ["A","B"] healths = [10, 10] attacker = 1 while min(healths...) > 0 println("$(players[attacker]) a $(players[3-attacker])") healths[3-attacker]-=roll(players[attacker]) status(players[3-attacker], healths[3-attacker]) attacker = 3 - attacker end winner = findmax(healths)[2] println("$(players[winner]) w") end ``` [Answer] ## VBA, ~~222~~ ~~185~~ 179 Bytes This recursive solution involves 3 subs 1. g is the *game start* that kicks off the first turn 2. t is called for each *turn*. It uses recursion. 3. ~~p is shorter than Debug.Print when used more than 3 times (only 4 in this solution)~~ *Edit:* Now that I learned that `Debug.?` is an acceptable alternative to `Debug.Print`, `Debug.?x` is shorter than calling a Sub to print. ``` Sub g() t "A",10,"B",10 End Sub Sub t(i,j,x,h) d=Int(Rnd()*6)+1 Debug.?i &" a "&x Debug.?i &" r "&d h=h-d If h<1Then Debug.?i &" w" Else Debug.?x &" h "&h t x,h,i,j End If End Sub ``` This was a fun challenge. If you know of an online interpreter like TIO for VB6/VBScript/VBA please leave a comment. Then I can post a link to a working solution. If you want to test this code and have Microsoft Excel, Word, Access, or Outlook installed (Windows only), press Alt+F11 to open the VBA IDE. Insert a new code module (Alt+I,M) and clear out Option Explicit. Then paste in the code and press F5 to run it. The results should appear in the Immediate Window (press Ctrl+G if you don't see it). *Edit 1:* Removed whitespace that the VBA editor will automatically add back in. Reduced by 37 bytes *Edit 2:* Removed Sub p()\* to save 6 bytes after learning `Debug.?` is an acceptable alternative to `Debug.Print`. Calling a [Sub](https://codegolf.stackexchange.com/a/166127/69061) to handle `Debug.?` only saves bytes after more than six calls. ]
[Question] [ A positive integer **x** is a square triangle number iff there are two different positive integers, **y** and **z**, which are smaller than **x** such that all of the sums **x + y** **x + z** **y + z** are perfect squares. For example 30 is a square triangle number because **30 + 6 = 62** **30 + 19 = 72** **6 + 19 = 52** --- Your task is to write some code that takes a positive integer as input and determines whether or not it is a square triangle number. You should output one of two distinct values, one if the input is a square triangle number and the other otherwise. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better. ## Testcases Here are all of the square triangle numbers under 1000 ``` 30,44,47,48,60,66,69,70,78,86,90,92,94,95,96,98,108,113,116,118,120,122,124,125,126,132,138,142,147,150,152,154,156,157,158,159,160,165,170,176,180,182,185,186,188,190,192,194,195,196,197,198,200,207,212,214,216,218,221,222,224,227,230,232,234,236,237,238,239,240,246,248,253,258,260,264,266,267,268,270,273,274,275,276,278,280,281,282,283,284,285,286,290,296,298,302,303,306,308,310,312,314,317,318,320,322,323,324,326,328,329,330,331,332,333,334,335,336,338,340,344,347,350,351,352,356,357,360,362,364,368,370,371,372,374,376,377,378,380,382,384,385,386,387,388,389,390,392,394,396,402,405,408,410,413,414,415,418,420,422,423,424,426,429,430,432,434,435,436,438,440,442,443,444,445,446,447,448,449,452,456,458,462,464,466,467,468,470,472,476,477,479,480,482,484,485,488,490,491,492,494,496,497,498,500,501,502,503,504,505,506,507,508,509,510,512,515,516,518,522,523,524,527,528,530,533,536,538,540,542,543,546,548,549,550,551,552,554,557,558,560,562,563,564,566,568,569,570,571,572,573,574,575,576,578,579,582,585,588,590,592,593,594,598,600,602,603,604,605,606,608,610,612,613,614,615,616,618,620,621,623,624,626,627,628,630,632,633,634,636,638,639,640,641,642,643,644,645,646,650,652,656,657,658,659,660,662,666,667,668,670,672,674,677,678,680,682,683,686,687,689,690,692,694,695,696,698,700,701,702,704,706,707,708,709,710,711,712,713,714,715,716,717,718,719,720,722,723,726,728,730,734,737,739,740,742,744,745,746,750,752,755,756,758,760,762,764,765,767,768,770,772,773,774,776,778,779,780,782,783,784,785,786,788,789,790,791,792,793,794,795,796,797,798,800,802,803,804,805,810,812,814,816,817,818,819,820,822,825,826,827,828,829,830,832,833,834,836,837,838,840,842,846,847,848,849,850,851,852,854,855,856,858,860,861,862,863,864,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880,882,884,888,890,891,893,896,897,898,902,903,904,905,908,912,913,914,915,916,918,920,923,924,926,927,928,929,931,932,933,935,936,938,940,941,942,944,946,947,948,950,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,970,972,974,976,978,980,981,984,986,987,988,992,993,995,996,998 ``` [OEIS A242445](http://oeis.org/A242445) [Answer] # [Haskell](https://www.haskell.org/), 62 bytes ``` f x|l<-(^2)<$>[1..x]=or[b>x|c<-l,b<-l,a<-l,a-x+b-x==c,c<b,b<a] ``` [Try it online!](https://tio.run/##HY3LCoMwEEV/ZRAXkUykUSktJH5Bu@rSWkikxdL4QC2dhf@eGjeHwz2L25r583TO@xfQ6pRgjyxRcVnJNKVaD1NlS1obJRzaALNDELeCtG6wUXYLpvadefcaOjNegd0JRAnjd7kt06WHGOZ2@AEB5xCFEgXbN7a9JglU8og55gcsCpQZnk@1/wM "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` R²_fṖŒcS€Æ²Ẹ ``` [Try it online!](https://tio.run/##AS0A0v9qZWxsef//UsKyX2bhuZbFkmNT4oKsw4bCsuG6uP8xMDAww4fDkGZq4oCdLP8 "Jelly – Try It Online") ### How it works ``` R²_fṖŒcS€Æ²Ẹ Main link. Argument: x R Range; yield [1, 2, ..., x]. ² Square; yield [1², 2², ..., x²]. _ Subtract; yield [1²-x, 2²-x, ..., x²-x]. Ṗ Pop; yield [1, 2, ..., x-1]. f Filter; keep those values of n²-x that lie between 1 and x-1. This list contains all integers n such that n+x is a perfect square. We'll try to find suitable values for y and z from this list. Œc Yield all 2-combinations [y, z] of these integers. S€ Take the sum of each pair. Ʋ Test each resulting integer for squareness. Ẹ Any; check is the resulting array contains a 1. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~93~~ ~~87~~ 86 bytes -1 byte thanks to Dennis ``` lambda n:{0}in[{m**.5%1for m in[x+y,n+x,n+y]}for x in range(1,n)for y in range(1+x,n)] ``` [Try it online!](https://tio.run/##TcoxCoQwEEDR3lNMIxiVJQo2AU@iFll2owNmlGCRIDn7mHQWv3n8M1zbQT2bceZd2@9PA6lbRqTptnX9GcrOHA4sJPBNaKnxqbDErD4pOE3rv@paEpnCi/IqFs6ML5ZSqALQgKlQqNMhXYDMDw "Python 2 – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 19 bytes ``` ~hṪ>₁ℕ₁ᵐ≜¬{⊇Ċ+¬~^₂} ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy7j4c5Vdo@aGh@1TAWSD7dOeNQ559Ca6kdd7Ue6tA@tqYt71NRU@/@/oaHZfwA "Brachylog – Try It Online") Also 19 bytes: `~hṪ>₁ℕ₁ᵐ≜{⊇Ċ+}ᶠ~^₂ᵐ` ### Explanation ``` ~hṪ Ṫ = [Input, A, B] Ṫ>₁ Ṫ is strictly decreasing (i.e. Input > A > B) Ṫ ℕ₁ᵐ All members of Ṫ are in [1, +∞) Ṫ ≜ Assign values to A and B that fit those constraints Ṫ ¬{ } It is impossible for Ṫ… ⊇Ċ …that one of its 2-elements subset… Ċ+ …does not sum… ¬~^₂ …to a square ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 150 bytes ``` param($x)filter f($a,$b){($c=[math]::Sqrt($a+$b))-eq[math]::Floor($c)}1..($i=$x-1)|%{$y=$_;1..$i|%{$o+=+($y-ne$_)*(f $x $y)*(f $x $_)*(f $y $_)}};!!$o ``` [Try it online!](https://tio.run/##PcrRCoIwAIXhV5lwgi2bJN0pu@0FuoyQFRMH0@ka5DCffU2o7v7zcUb7Uu7ZKWNiHKWTPcXMWm28cqSlkAfc2ULxENde@u5WVZfJ@eR5csbV9OOzsdalH1vLoqDQAjMv2Xu3IAg0dULobdlc5BSBDwoN29OWYCYI//pa2Gpd6yyDjTGejh8 "PowerShell – Try It Online") or [Verify some test cases](https://tio.run/##PczRCoIwFAbge59iyQm21kRvlXXZC3QZIUsmCurmMnLYnn3NKO/@8/H/R6uXNI9Gdp2vn0M1tWpANQZxhDtZMFT82oupueX5ZTRTcBqcMDn@@dwpZUKPuGjb68VrYUSPYSageBplSYKh5TCzjLz3C1gOZREQ2vVSlFMMlg0SSnLANYIZgd3Sz@yanCt2O1DerS@zNA3zGErETihGFGH97fgP "PowerShell – Try It Online") Takes input `$x`. Establishes a `filter` (here equivalent to a function) on two inputs `$a,$b`, which returns a Boolean true iff the `[math]::sqrt` of `$a+$b` is `-eq`ual to the `Floor` of that square root (i.e., it's an integer square root). The rest of it is the meat of the program. We double-for loop up from `1` to `$x-1`. Each iteration, we check whether `$y` is `-n`ot`e`qual to `$_` (i.e., $z), and whether the function is true for all combinations of `$x`, `$y` and `$_`. If it is, `$o` is incremented by one (which makes it non-zero). Finally, at the end, we double-Boolean-negate `$o`, which turns `0` into `False` and non-zero into `True`. That's left on the pipeline and output is implicit. [Answer] # [Haskell](https://www.haskell.org/), ~~75~~ 69 bytes ``` f x=or[all(`elem`map(^2)[1..x])[x+y,x+z,y+z]|y<-[1..x-1],z<-[1..y-1]] ``` [Try it online!](https://tio.run/##JYrBCoMwEER/ZY8JWcVUWyjol4QUc4hUutmK7SEJ/nsM7WGYx5t5us/LE5WyQJzeu3FEYvbkwxzcJh4XaXTbRitNVAmjyphUtkcam59vtMX851TZluBWnrZ95a8RjAuwPLjufYcwDAi32rqm1wjXe/2f "Haskell – Try It Online") Could probably be improved if someone knows a shorter way to test if a number is square. I'm pretty sure using `sqrt` ends up being longer because `floor` turns the result into an integral type so you need to put `fromIntegral` in somewhere before you can compare to the original. EDIT: Thanks @Wheat Wizard for taking off 6 bytes! [Answer] ## JavaScript (ES7), ~~75~~ 71 bytes ``` f= n=>(g=i=>i?--j?[n+i,i+j,j+n].some(e=>e**.5%1)?g(i):1:g(j=i-1):0)(j=n-1) ``` ``` <input type=number min=1 oninput=o.textContent=f(+this.value)><pre id=o> ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes ``` Lns-IL¨Ãæ2ù€OŲO0› ``` [Try it online!](https://tio.run/##ASgA1/8wNWFiMWX//0xucy1JTMKow4PDpjLDueKCrE/DhcKyTzDigLr//zE4 "05AB1E – Try It Online") Thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) for ~~-3~~ -1 byte ~~and a fix~~! [Answer] # [R](https://www.r-project.org/), 79 bytes ``` function(x){s=(1:x)^2 S=outer(y<-(z=s-x)[z>0&z<x],y,"+") diag(S)=0 any(S%in%s)} ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NCs7rYVsPQqkIzzogr2Da/tCS1SKPSRlejyrZYt0IzusrOQK3KpiJWp1JHSVtJkyslMzFdI1jT1oArMa9SI1g1M0@1WLP2f3FiQUFOJdAcExOdNM3/AA "R – Try It Online") computes all the values of `y,z` with `y<-(z=s-x)[z>0&z<x]`, then computes all their sums with `outer(y,y,"+")`. This yields a square matrix where off-diagonal entries are potentially squares, as `y==z` only if they are on the diagonal. Hence, `diag(S)=0` sets the diagonals to zero, which are not perfect squares, and we test to see if `any` element of `S` is `%in%s`. [Answer] # [SWI-Prolog](http://www.swi-prolog.org/), 88 bytes ``` s(A,B,C):-between(A,B,C),C<B,between(1,B,X),B+C=:=X*X. g(X):-s(1,X,Y),s(Y,X,Z),s(Y,Z,Y). ``` [Try it online!](https://tio.run/##ZY@xCoMwEIZ3n@K6JfUU7Sg6VAdd7OSQWjq0ECRQtJiADn13ezE6lIYM9/0/95G8x@E1dIGe1LJodsYcC54ET2kmKfuNsUhz3KOYIsEx94ssycRRhF7HBK1oagReOWp2paF1Q0tJuBipDbvdEQRdHnqOq09DUYVQP2YOSeABnQpSy7hCxyqOcHBQgtJU@xA7XiUNQukEm5WCWvW/Tgo26@66yNlYnW3@hLbcnd6mWDt6fYRwiiLuFqZRGcnsh5Yv) ``` s(A, B, C) :- between(A, B, C), % Find an integer C between A and B (inclusive), C < B, % which is less than B. between(1, B, X), % Find an integer X between 1 and B (inclusive), B+C =:= X*X. % of which (B+C) is the square. g(X) :- s(1, X, Y), % Find Y: 1 <= Y < X, and X+Y is a perfect square s(Y, X, Z), % Find Z: Y <= Z < X, and X+Z is a perfect square s(Y, Z, Y). % Make sure that Z > Y and Y+Z is a perfect square ``` `g(X)` is the rule that takes an integer as parameter and outputs whether it is a square triangle number (true/false). [Answer] # JavaScript (ES7), 72 bytes Returns `0` or `1`. ``` x=>(g=y=>z?y>z?![x+y,x+z,y+z].some(n=>n**.5%1)|g(y-1):g(x-1,z--):0)(z=x) ``` ### Demo ``` let f= x=>(g=y=>z?y>z?![x+y,x+z,y+z].some(n=>n**.5%1)|g(y-1):g(x-1,z--):0)(z=x) for(n = 1; n < 150; n++) { f(n) && console.log(n) } ``` [Answer] # C, 113 bytes ``` p(n){return(int)sqrt(n)==sqrt(n);}f(x,y,z,r){for(r=y=0;++y<x;)for(z=y;++z<x;p(x+y)&p(x+z)&p(z+y)&&++r);return!r;} ``` Returns `0` if the number is square triangle, `1` otherwise. [Try it online!](https://tio.run/##LU5BCoMwEDw3r4hCJUsixHPMT3oR2xRBU7taMBG/3nTTdi6zM7vsTF/f@z6lWXjY8ba@0IvBr7A8cSXL2v9gDic2FVRUCLt7oEAbrDZShnYzkI1oA8lIchabDFBlipliVpWUCOaXUKA5EqXwqRu8ALYzTqAnPGdzbxvDfdtorQ2X0sN3nTE4LgpHdYCdsp6R7p0oz9eLLxWnmuxI796N3X1J9Th9AA) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 49 bytes ``` {∨/{0=+/(⍺=⍵),1|.5*⍨(⍺+⍵)(⍺+k)(⍵+k)}/¨,⍳2⍴1-⍨k←⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqRx0r9KsNbLX1NR717rJ91LtVU8ewRs9U61HvCpCINkgEzMgGUVuBVK3@oRU6j3o3Gz3q3WKoC1SXDTQHKFX7/79G2qEVQBlDAwNNfQgNAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` ṖŒc;€ŒcS€Æ²ẠƊ€Ẹ ``` [Try it online!](https://tio.run/##y0rNyan8///hzmlHJyVbP2paA6SCgdThtkObHu5acKwLyH64a8f///8NzQA "Jelly – Try It Online") ### How? ``` ṖŒc;€ŒcS€Æ²ẠƊ€Ẹ || Full program. || Ṗ || Popped range. Yields [1, N) ∩ ℤ. Œc || Pairs (two-element combinations). ;€ || Append N to each. Ɗ€ || For each of the lists, check whether: Ạ || ... All ... S€ || ... The sums of each of their... Œc || ... Disjoint Pairs Ʋ || ... Are perfect squares. Ẹ || Test whether there is any value that satisfies the above. ``` [Answer] # [Clean](https://clean.cs.ru.nl), ~~95~~ ~~88~~ 86 bytes ``` import StdEnv @x#l=[1..x-1] =or[all(\n=or[i^2==n\\i<-l])[x+y,y+z,z+x]\\y<-l,z<-l|y<>z] ``` [Try it online!](https://tio.run/##FYyxCsMgFAD3fIXQpcUYYudYMqRDoVtGtSCJKcLTlMQWlX57bbIcxw03gFYu23l8g0ZWGZeNfc2LR70fr@5TtOEAjNOqCoTKgs0LVwBH4XYzjzNjTgjTEJAnHnAsI05lwkEKEbdYpg3f2FySzL1X25WhyYDXC2rRPqV1LfNvmEA910xu99xFp6wZ1j8 "Clean – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 73 bytes ``` ->n{(1...n).any?{|b|(1...b).any?{|c|[n+b,b+c,n+c].all?{|r|r**0.5%1==0}}}} ``` [Try it online!](https://tio.run/##NYu7CoAwDAB/xUVQq6EKjtUPEQdTdCpBqoKl8dvjA7ztDs4fGGQxUnUUsxoAKIeJQh8Z@XP83fJACktUtiRlR5ice6pnXxQa2rQ2Rl8Psibv12idwza72e6RT16Gc7xEbg "Ruby – Try It Online") [Answer] # [Julia 0.6](http://julialang.org/), 61 bytes Start reading from the function `all`. The first argument is an anonymous function checking that the square root of a number is an integer, this is applied to each value in the second argument. The single argument to `any` is a `Generator` with two for loops, which for each iteration contains the output of the `all` function. Thanks to Mr Xcoder for -2 bytes. ``` x->any(all(x->√x%1==0,[x+y,x+z,y+z])for y=1:x-1for z=1:y-1) ``` [Try it online!](https://tio.run/##yyrNyUw0@59mm5Sanpn3v0LXLjGvUiMxJ0cDyHzUMatC1dDW1kAnukK7UqdCu0qnUrsqVjMtv0ih0tbQqkLXEMSsAjIrdQ01/6fmpXA5FGfklyukaRgbaCLYhppcBUWZeSU5eRppmXkpGml6GkZWhgYGmpraQG0A "Julia 0.6 – Try It Online") [Answer] # [Pyt](https://github.com/mudkip201/pyt), 63 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage) ``` 0←Đ⁻Đ`⁻Đ3ȘĐ3Ș+√ĐƖ=4ȘĐ3ȘĐ3Ș+√ĐƖ=4ȘĐ3ȘĐ3Ș+√ĐƖ=4Ș6Ș**4Ș↔+↔łŕ⁻Đłŕŕŕ ``` Tests all possible combinations of y,z such that 1≤z<y<x Returns 1 if x is a square triangle number, 0 otherwise [Try it online!](https://tio.run/##K6gs@f/f4FHbhCMTHjXuPjIhAUwan5gBJrQfdcw6MuHYNFsTqACRomYnZmhpAelHbVO0gfho09GpYHNBDBD8/9/EBAA) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~20~~ ~~19~~ 18 bytes ``` q:2XN!tG+wsvX^1\aA ``` [Try it online!](https://tio.run/##y00syfn/v9DKKMJPscRdu7y4LCLOMCbR8f9/YwMA "MATL – Try It Online") Returns 1 for falsey, 0 for truthy. Testcases up to 500: [Try it online!](https://tio.run/##y00syflvamBgpeQQ4fG/0Moowk@xxEO7vLgsIs4wJtHxf529g8t/AA "MATL – Try It Online") (using `H` instead of `G`). Runtime is quadratic in the input size, so enumerating the testcases from `1` to `n` runs in `O(n^3)`, which is why enumerating all testcases up to 1000 times out on TIO. * -1 byte and a conjecture less thanks to @LuisMendo * -1 byte by a more clever check of integer-ness. Removing `q` generates a sequence with the desired sequence as a subset, but without the constraint that `y` and `z` be strictly smaller than `x`. An example is `x=18`, `y=7`, `z=18`. ``` q: % Push 1...n-1 2XN % Generate all permuations of choosing 2 numbers from the above. ! % Transpose to take advantage of column-wise operators later on. G+ % Add n to these combinations, to have all combos of x+y and x+z t ws % Duplicate the combinations, swap to the top of the stack and sum to get y+z. v % Concatenate vertically. The array now contains columns of [x+y;x+z;y+z]. X^ % Element-wise square root of each element 1\ % Get remainder after division by 1. a % Check if any have remainders, columnwise. If so, it is not a square triangle. A % Check whether all combinations are not square triangle. ``` ]
[Question] [ The RGB color value `#00FF00` is a rather important one: it is used to make movies, TV shows, weather announcements, and more. It is the famous "TV green" or "green screen" color. ## The Challenge Your task is to write a program that takes two input images, both in PNG format (or in your image library's image object type) and of the same dimensions. One image can be any old image. The other one is the image that will have a background of the color `#00FF00`. The output image will consist of the second image overlaid over the first, with no `#00FF00` color present (except in the first image). Input and output may be done with files, a GUI, etc. You are allowed to take an array of RGB values as input, as seen [here](https://codegolf.stackexchange.com/a/132724/64706). You may assume that an image has only pixels of full opacity. ## Basically... Make a program that takes every `#00FF00` pixel in one image and replace it with the corresponding pixel in the background image. ## Test Cases Generously provided by @dzaima: Background: [![my profile image](https://i.stack.imgur.com/qaraP.png)](https://i.stack.imgur.com/qaraP.png) Foreground: [![dennis](https://i.stack.imgur.com/Bc0s5.png)](https://i.stack.imgur.com/Bc0s5.png) Output: [![output](https://i.stack.imgur.com/svMKa.png)](https://i.stack.imgur.com/svMKa.png) --- Of course, standard loopholes are *strictly forbidden*. This includes using an online resource to do it for you. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code win and the best programmer prosper... [Answer] # x86-64 (and x86-32) machine code, ~~13~~ ~~15~~ 13 bytes changelog: 1. Bugfix: the first version was only checking G=0xff, not requiring R and B to be 0. I changed to modifying the background in place so I could use `lodsd` on the foreground to have fg pixels in `eax` for the short-form `cmp eax, imm32` encoding (5 bytes), instead of `cmp dh,0xff` (3 bytes). 2. Save 2 bytes: noticed that modifying the bg in place allowed using a memory operand for `cmov`, saving a 2-byte `mov` load (and saving a register, in case that matters). --- This is a function following the x86-64 System V calling convention, callable directly from C or C++ (on x86-64 non-Windows systems) with this signature: ``` void chromakey_blend_RGB32(uint32_t *background /*rdi*/, const uint32_t *foreground /*rsi*/, int dummy, size_t pixel_count /*rcx*/); ``` **The image format is RGB0 32bpp, with the green component at the 2nd lowest memory address within each pixel.** The ~~foreground~~ background image is modified in-place. `pixel_count` is rows\*columns. It doesn't care about rows/columns; it just chromekey blends however many dwords of memory you specify. RGBA (with A required to be 0xFF) would require using a different constant, but no change in function size. Foreground DWORDs are compared for exact equality against an arbitrary 32-bit constant stored in 4 bytes, so any pixel-order or chroma-key colour can be easily supported. The same machine code also works in 32-bit mode. To assemble as 32-bit, change `rdi` to `edi` in the source. All other registers that become 64-bit are implicit (lodsd/stosd, and loop), and the other explicit regs stay 32-bit. But note that you'll need a wrapper to call from 32-bit C, because none of the standard x86-32 calling conventions use the same regs as x86-64 SysV. NASM listing (machine-code + source), commented for asm beginners with descriptions of what the more complex instructions do. (Duplicating the instruction reference manual is bad style in normal usage.) ``` 1 ;; inputs: 2 ;; Background image pointed to by RDI, RGB0 format (32bpp) 3 ;; Foreground image pointed to by RSI, RGBA or RGBx (32bpp) 4 machine ;; Pixel count in RCX 5 code global chromakey_blend_RGB32 6 bytes chromakey_blend_RGB32: 7 address .loop: ;do { 8 00000000 AD lodsd ; eax=[rsi], esi+=4. load fg++ 9 00000001 3D00FF0000 cmp eax, 0x0000ff00 ; check for chromakey 10 00000006 0F4407 cmove eax, [rdi] ; eax = (fg==key) ? bg : fg 11 00000009 AB stosd ; [rdi]=eax, edi+=4. store into bg++ 12 0000000A E2F4 loop .loop ;} while(--rcx) 13 14 0000000C C3 ret ## next byte starts at 0x0D, function length is 0xD = 13 bytes ``` To get the original NASM source out of this listing, strip the leading 26 characters of each line with `<chromakey.lst cut -b 26- > chromakey.asm`. I generated this with `nasm -felf64 chromakey-blend.asm -l /dev/stdout | cut -b -28,$((28+12))-` NASM listings leave more blank columns than I want between the machine-code and source. To build an object file you can link with C or C++, use `nasm -felf64 chromakey.asm`. (Or `yasm -felf64 chromakey.asm`). To strip the addresses and line numbers as well, `cut -b16-30,41-` works well. **untested**, but I'm pretty confident that the basic idea of load / load / cmov / store is sound, because it's so simple. I could save 3 bytes if I could require the caller to pass the chroma-key constant (0x00ff00) as an extra arg, instead of hard-coding the constant into the function. I don't think the usual rules allow writing a more generic function that has the caller set up constants for it. But if it did, the 3rd arg (currently `dummy`) is passed in `edx` in the x86-64 SysV ABI. Just change `cmp eax, 0x0000ff00` (5B) to `cmp eax, edx` (2B). --- With SSE4 or AVX, you might do this faster (but larger code size) with `pcmpeqd` and `blendvps` to do a 32-bit element size variable-blend controlled by the compare mask. (With `pand`, you could ignore the high byte). For packed RGB24, you might use `pcmpeqb` and then 2x `pshufb`+`pand` to get TRUE in bytes where all 3 components of that pixel match, then `pblendvb`. (I know this is code-golf, but I did consider trying MMX before going with scalar integer.) [Answer] # Mathematica ~~57~~ 35 bytes update: by default, a green background is removed using `RemoveBackground`. The first submission included the unnecessary second parameter, `{"Background",Green}". --- ``` #~ImageCompose~RemoveBackground@#2& ``` Removes the background of image 2 and composes the result with image 1. --- **Example** [![i1](https://i.stack.imgur.com/XFtX8.png)](https://i.stack.imgur.com/XFtX8.png) The following, in prefix rather than infix form, shows more clearly how the code works. [![i2](https://i.stack.imgur.com/jHzme.png)](https://i.stack.imgur.com/jHzme.png) [Answer] # [Python 3](https://docs.python.org/3/) + [numpy](http://www.numpy.org/), 59 bytes ``` lambda f,b:copyto(f,b,'no',f==[0,255,0]) from numpy import* ``` [Try it online!](https://tio.run/##bVAxDoMwEJvLK24DqhtCAgUq8ZI0A7QKrdSQKKIDr6d3iIFKnWzHTmwlLPPTT2odu9v67t3w6MHicL37sMw@I4rp5FO0XacFyqpCYfLERu9g@riwwMsFH@fzaqGDPsZ@ybTWhUSQFYIyCLokIhXCpWYl2KETYQwmJ33QZLYIfFWV/5KFYgehFb8uiaYmVSA0rTE0bzhuoSA5kmOM@yhGhHJ/milCta0lpK1MGRHqPcOUGthgpB1bMyEViK13pP@CIU9CfE1zZvP1Cw "Python 3 – Try It Online") Input is given in the format of a `numpy` array, with integer triplets representing pixels (where `#00FF00` in hex color code is equivalent to `[0, 255, 0]`). The input array is modified in place, which is allowed [per meta](https://codegolf.meta.stackexchange.com/a/4942). ## Example Images ### Input (from the question) Background: [![ckjbgames' profile picture](https://i.stack.imgur.com/hI4PZ.png)](https://i.stack.imgur.com/hI4PZ.png) Foreground: [![Dennis' profile picture](https://i.stack.imgur.com/PW11T.png)](https://i.stack.imgur.com/PW11T.png) Foreground image after running the function: [![Merged image with #00FF00 replaced with background pixels](https://i.stack.imgur.com/2ohU0.png)](https://i.stack.imgur.com/2ohU0.png) ## Reference Implementation (uses `opencv` to read image files) ``` g = lambda f,b:copyto(f,b,'no',f==[0,255,0]) from numpy import* import cv2 f = cv2.imread("fg.png") b = cv2.imread("bg.png") g(f, b) cv2.imshow("Output", f) cv2.imwrite("out.png", f) ``` Displays the image to the screen and writes it to an output file. [Answer] # Processing, ~~116~~ 99 bytes ``` PImage f(PImage b,PImage f){int i=0;for(int c:f.pixels){if(c!=#00FF00)b.pixels[i]=c;i++;}return b;} ``` Unfortunately, processing doesn't support java 8 stuff, like lambdas. Example implementation: (saves image as `out.png` and also draws it on screen) ``` PImage bg; void settings() { bg = loadImage("bg.png"); size(bg.width,bg.height); } void setup() { image(f(bg, loadImage("fg.png")), 0, 0); save("out.png"); } PImage f(PImage b,PImage f){int i=0;for(int c:f.pixels){if(c!=#00FF00)b.pixels[i]=c;i++;}return b;} ``` [Answer] ## Bash + ImageMagick, 45 bytes ``` convert $1 $2 -transparent lime -composite x: ``` Takes two images as arguments and displays the output on the screen. Change `x:` to `$3` to write to a third file argument instead. The method is simple: read the "background" image; read the "foreground" imagek; reinterpret the color "lime" (#00ff00) as transparency in the second image; then composite the second image onto the first and output. ## ImageMagick: 28 bytes? I could have submitted this as [an ImageMagick answer](https://codegolf.meta.stackexchange.com/questions/8828/is-imagemagick-a-programming-language) but it's not clear how to deal with the arguments. If you want to posit that ImageMagick is a stack-based language (which is kinda sorta not really true but almost... it's weird) then `-transparent lime -composite` is a function that expects two images on the stack and leaves one merged image on the stack... maybe that's good enough to count? [Answer] # [MATL](https://github.com/lmendo/MATL), ~~40~~ ~~37~~ 31 bytes ``` ,jYio255/]tFTF1&!-&3a*5M~b*+3YG ``` Example run with the offline interpreter. The images are input by their URL's (local filenames could also be provided). [![enter image description here](https://i.stack.imgur.com/2s24A.gif)](https://i.stack.imgur.com/2s24A.gif) ### Explanation ``` , % Do this twice j % Input string with URL or filename Yi % Read image as an M×N×3 uint8 array o % Convert to double 255/ % Divide by 255 ] % End t % Duplicate the second image FTF % Push 1×3 vector [0 1 0] 1&! % Permute dimensions to give a 1×1×3 vector - % Subtract from the second image (M×N×3 array), with broadcast &3a % "Any" along 3rd dim. This gives a M×N mask that contains % 0 for pure green and 1 for other colours * % Mulltiply. This sets green pixels to zero 5M % Push mask M×N again ~ % Negate b % Bubble up the first image * % Multiply. This sets non-green pixels to zero + % Add the two images 3YG % Show image in a window ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 27 bytes ``` M?q(Z255Z)GHG.wmgVhded,V'E' ``` It takes quoted input. The input are the two paths of the image files. Output a file `o.png` Unfortunately that cannot be tested on the online interpreter for safety reason (`'` is disabled on it). You will need to get [Pyth](https://github.com/isaacg1/pyth) on your computer to test it. **Explanation** ``` M?q(Z255Z)GHG # Define a function g which takes two tuples G and H and returns G if G != (0, 255, 0), H otherwise V'E' # Read the images. They are returned as lists of lists of colour tuples , # Zip both images m hded # For each couple of lists in the zipped list... gV # Zip the lists using the function g .w # Write the resulting image to o.png ``` [Answer] # Matlab 2016b and Octave, ~~62~~ 59 bytes Input: A = MxNx3 unit8 foreground matrix, B = MxNx3 unit8 background matrix. ``` k=sum(A(:,:,2)-A(:,:,[1 3]),3)==510.*ones(1,1,3);A(k)=B(k); ``` Output: A = MxNx3 unit8 matrix Sample use: ``` A = imread('foreground.png'); B = imread('backgroundimg.png'); k=sum(A(:,:,2)-A(:,:,[1 3]),3)==510.*ones(1,1,3);A(k)=B(k); imshow(A) ``` [Answer] # C++, 339 bytes This uses CImg, and it can take files in other formats, too. The result is displayed in a window. ``` #include<CImg.h> using namespace cimg_library; int main(int g,char** v){CImg<unsigned char> f(v[1]),b(v[2]);for(int c=0;c<f.width();c++){for(int r=0;r<f.height();r++){if((f(c,r)==0)&&(f(c,r,0,1)==255)&&(f(c,r,0,2)==0)){f(c,r)=b(c,r);f(c,r,0,1)=b(c,r,0,1);f(c,r,0,2) = b(c,r,0,2);}}}CImgDisplay dis(f);while(!dis.is_closed()){dis.wait();}} ``` Compile with `g++ chromakey.cpp -g -L/usr/lib/i386-linux-gnu -lX11 -o chromakey -pthread`. [Answer] # R, 135 bytes ``` function(x,y,r=png::readPNG){a=r(x);m=apply(a,1:2,function(x)all(x==0:1));for(i in 1:4)a[,,i][m]=r(y)[,,i][m];png::writePNG(a,"a.png")} ``` Anonymous function, takes 2 png file paths as arguments and output a png picture called `a.png`. Slightly ungolfed, with explanations: ``` function(x,y){ library(png) # readPNG output a 3D array corresponding to RGBA values on a [0,1] scale: a = readPNG(x) # Logical mask, telling which pixel is equal to c(0, 1, 0, 1), # i.e. #00FF00 with an alpha of 1: m = apply(a, 1:2, function(x) all(x==0:1)) # For each RGB layer, replace that part with the equivalent part of 2nd png: for(i in 1:4) a[,,i][m] = readPNG(y)[,,i][m] writePNG(a,"a.png") } ``` [Answer] # SmileBASIC, 90 bytes whats the key ``` DEF C I,J DIM T[LEN(I)]ARYOP.,T,I,16711936ARYOP 2,T,T,T ARYOP 6,T,T,0,1ARYOP 5,I,I,J,T END ``` `I` is the foreground and output, `J` is the background. Both are integer arrays of pixels, in 32 bit ARGB format. ## Ungolfed ``` DEF C IMAGE,BACKGROUND 'function DIM TEMP[LEN(IMAGE)] 'create array "temp" ARYOP #AOPADD,TEMP,IMAGE,-RGB(0,255,0) 'temp = image - RGB(0,255,0) ARYOP #AOPCLP,TEMP,TEMP,-1,1 'temp = clamp(temp, -1, 1) ARYOP #AOPMUL,TEMP,TEMP,TEMP 'temp = temp * temp ARYOP #AOPLIP,IMAGE,IMAGE,BACKGROUND,TEMP 'image = linear_interpolate(image, background, temp) END ``` ## Explanation: ARYOP is a function that applies a simple operation to every element in an array. It is called like `ARYOP mode, output_array, input_array_1, input_array_2, ...` First, to determine which pixels in the image are green, `-16711936` (the RGBA representation of the green color) is subtracted from each pixel in the foreground image. This gives an array where `0` represents green pixels, and any other number represents non-green pixels. To convert all nonzero values to `1`, they are squared (to remove negative numbers), then clamped to between `0` and `1`. This results in an array with only `0`s and `1`s. `0`s represent green pixels in the foreground image, and should be replaced with pixels from the background. `1`s represent non-green pixels, and those will need to be replaced with pixels from the foreground. This can easily be done using linear interpolation. [Answer] # PHP, 187 bytes ``` for($y=imagesy($a=($p=imagecreatefrompng)($argv[1]))-1,$b=$p($argv[2]);$x<imagesx($a)?:$y--+$x=0;$x++)($t=imagecolorat)($b,$x,$y)-65280?:imagesetpixel($b,$x,$y,$t($a,$x,$y));imagepng($b); ``` assumes 24bit PNG files; takes file names from command lines arguments, writes to stdout. Run with `-r`. **breakdown** ``` for($y=imagesy( # 2. set $y to image height-1 $a=($p=imagecreatefrompng)($argv[1]) # 1. import first image to $a )-1, $b=$p($argv[2]); # 3. import second image to $b $x<imagesx($a)?: # Loop 1: $x from 0 to width-1 $y--+$x=0; # Loop 2: $y from height-1 to 0 $x++) ($t=imagecolorat)($b,$x,$y)-65280?: # if color in $b is #00ff00 imagesetpixel($b,$x,$y,$t($a,$x,$y)); # then copy pixel from $a to $b imagepng($b); # 5. output ``` [Answer] # JavaScript (ES6), 290 bytes ``` a=>b=>(c=document.createElement`canvas`,w=c.width=a.width,h=c.height=a.height,x=c.getContext`2d`,x.drawImage(a,0,0),d=x.getImageData(0,0,w,h),o=d.data,o.map((_,i)=>i%4?0:o[i+3]=o[i++]|o[i++]<255|o[i]?255:0),x.drawImage(b,0,0),createImageBitmap(d).then(m=>x.drawImage(m,0,0)||c.toDataURL())) ``` Takes input as two `Image` objects (in currying syntax), which can be created with an HTML `<image>` element. Returns a Promise that resolves to the Base64 data URL of the resulting image, which can be applied to the `src` of an `<image>`. The idea here was to set the alpha value for each `#00FF00` pixel to `0` and then paint the foreground, with its background keyed out, on top of the background. ## Test Snippet Including the foreground and background by their data URLs was too large to post here, so it was moved to CodePen: [Try it online!](https://codepen.io/justinm53/pen/rwEaQw) [Answer] # [OSL](https://github.com/imageworks/OpenShadingLanguage), 83 bytes ``` shader a(color a=0,color b=0,output color c=0){if(a==color(0,1,0)){c=b;}else{c=a;}} ``` Takes two inputs. The first is the foreground, and the second, the background. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~248~~ 245 bytes *-3 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* ``` #define F(N)for(i=0;i<N;++i) #define V x,y,z,w *S="P%d %d %d %d ";V;v[6];main(i,f)int**f;{F(2)fscanf(f[i]=fopen(f[i+1],"r"),S,&x,&y,&z,&w);for(printf(S,V);~*v;x=0){F(3)x||putchar(i[!(*v|v[1]-255|v[2])*3+v]);F(3)v[i+3]=getc(*f),v[i]=getc(f[1]);}} ``` [Try it online!](https://tio.run/##PY5Bb4JAEIXv/gqKkewsY6IQe5nu1aNpQsKF7IGsjN1DV0Lpior967g0aZM5vJeZ974x65Mx07Q8NmxdE@3FAfjcCas2ZN8OlKYWFn/LMhrwije8LGSh4vfVMfqfmEry1aumz9o6YZHBul5KpvteZMBfpnYsuLJa8blt3CzTrca4iwELTAZMrpjcMLkAzfi2C3EWBZZAP9LToDYQmnIYxrH97s1HHV6sXoT0o6@2ep3tdkFkGmSeeg00n/qAyLU6Nb0RkgH9TP91HCJAj8c0PQE "C (gcc) – Try It Online") ]
[Question] [ Given a number **n**, generate the first **n** columns of this pattern: ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ################################ ... ``` The height of the column at (1-indexed) **n** is the number of trailing `0` bits in **n**'s binary representation, plus one. As a result, the bottom layer has every column filled in, the second layer every second column, the third layer every fourth column, etc. ## Rules * You may input and output through any standard method. * You may assume the input is an integer between 1 and 999, inclusive. * The output may contain any amount of whitespace, as long as the pattern is intact. * The pattern must be 1-indexed, and in the same format as shown here. * You may use any single non-whitespace character in place of `#`, but you may not change the space character. ## Test cases ``` 1 # 2 # ## 3 # ### 4 # # # #### 5 # # # ##### 7 # # # # ####### 32 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ################################ ``` A few larger test cases can be found [here](https://gist.github.com/ETHproductions/96417705cfb7c3b851d2fb3ff2829092). ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **the shortest code in bytes in each language wins.** [Answer] # [Python 2](https://docs.python.org/2/), 54 bytes ``` i=n=input() while i:i-=1;print((' '*~-2**i+'#')*n)[:n] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9M2zzYzr6C0REOTqzwjMydVIdMqU9fW0LqgKDOvRENDXUFdq07XSEsrU1tdWV1TK08z2iov9v9/QwMA "Python 2 – Try It Online") Prints with lots of leading whitespace. Each row `i` counting down from `n` repeats a pattern of `2**i-1` spaces followed by a `#`. This pattern is repeated up to the width of the ruler, which is the input `n`. This is done by multiplying the pattern string by `n` and taking the first `n` characters with `[:n]`. The pattern can be made by string formatting for an equal length alternative. ``` i=n=input() while i:i-=1;print('%%%ds'%2**i%'#'*n)[:n] ``` A cute slicing method is longer. ``` n=input();s=~-2**n*' '+'#' exec"s=s[1::2]*2;print s[:n];"*n ``` [Answer] # [Python 3](https://docs.python.org/3/), 74 bytes ``` n=int(input()) a=1 while a<n:a*=2 while a:print(("%%%dd"%a%4*n)[:n]);a//=2 ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P882M69EIzOvoLREQ1OTK9HWkKs8IzMnVSHRJs8qUcvWCMa1KigCqdRQUlVVTUlRUk1UNdHK04y2yovVtE7U17c1@v/f2AgA "Python 3 – Try It Online") [Answer] # [V](https://github.com/DJMcMayhem/V), ~~17~~, 16 bytes ``` é#Àñä}Är {ñÎÀlD ``` [Try it online!](https://tio.run/##K/v///BK5cMNhzceXiJWe7ilSKEayOw73JDj8v//f3MA "V – Try It Online") Hexdump: ``` 00000000: e923 c0f1 e416 7dc4 7220 7bf1 cec0 6c44 .#....}.r {...lD ``` *Thanks to @KritixiLithos for saving one byte!* This algorithm is *horribly* inefficient, but it should work in theory for any size input. It works by generating the first *n* iterations of the following pattern: ``` # # ## # # # #### # # # # # # # ######## # # # # # # # # # # # # # # # ################ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ################################ ``` And then chopping off all but the first *n* columns. As such, this will produce a ton of leading whitespace, but the OP said: > > The output may contain any amount of whitespace, as long as the pattern is intact > > > Explanation: ``` é# " Insert an '#' Àñ ñ " 'N' times: ä<C-v>} " Duplicate every line blockwise (duplicating horizontally instead of vertically) Ä " Duplicate the top line. This conveniently puts us on the first non-whitespace character (that is, '#') r " Replace this character with a space { " Move to the beginning of the buffer Î " On every line: Àl " Move 'N' characters to the right ('l' for right, makes sense, right?) D " And delete everything after the cursor ``` [Answer] # JavaScript (ES6), ~~61~~ 58 bytes ``` f=(n,c=n,s='')=>c?f(n,c>>1,s+s+' ')+` `+(s+1).repeat(c):'' ``` *Saved 1 byte thanks to @ETHProductions, then 2 more bytes when I saw that any character could be used.* A recursive solution. **Test cases:** ``` f=(n,c=n,s='')=>c?f(n,c>>1,s+s+' ')+` `+(s+1).repeat(c):'' console.log(f(32)); console.log(f(1)); console.log(f(5)); console.log(f(7)); ``` **Animation:** ``` f=(n,c=n,s='')=>c?f(n,c>>1,s+s+' ')+` `+(s+1).repeat(c):'' for(let i = 1 ; i < 64 ; i++) { setTimeout(_=>document.querySelector('pre').textContent=f(i), i*40); } ``` ``` <pre> ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 21 bytes ``` '# '[1+⊖0⍪∨⍀⊖2⊥⍣¯1⍳⎕] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO9qDQntei/urKCerSh9qOuaQaPelc96ljxqLcByDF61LX0Ue/iQ@sNH/VuftQ3NRak4z9YC5exEQA "APL (Dyalog Unicode) – Try It Online") `'# '[`…`] index the string with  `⎕` get input  `⍳` that many **i**ntegers  `2⊥⍣¯1` convert to binary, using as many digits as needed (one number in each *column*)  `⊖` flip upside down  `∨⍀` vertical cumulative OR reduction  `0⍪` concatenate zeros on top  `⊖` flip upside down (i.e. back up again)  `1+` add one (for 1-based indexing) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 bytes ``` Rọ2‘4ẋz⁶ṚY ``` [Try it online!](https://tio.run/##ASAA3/9qZWxsef//UuG7jTLigJg04bqLeuKBtuG5mln///8zMg "Jelly – Try It Online") 1 byte saved after the OP added a relaxation that the character doesn't have to be `#`. [Answer] # Octave, 45 bytes ``` @(n)[[sort(cummin(de2bi(g=0:n)'));g|1]+32 ''] ``` Try it on [Octave Online!](http://octave-online.net/#cmd=(%40(n)%5B%5Bsort(cummin(de2bi(g%3D0%3An)%27))%3Bg%7C1%5D%2B32%20%27%27%5D)(20)) Instead of `'#'` prints `'!'`. [Answer] # [PHP](https://php.net/), 139 bytes ``` for($f=array_fill(0,$l=1+log($a=$argn,2)," ");$n++<$a;)for($h=1+strspn(strrev(decbin($n)),$i=0);$i<$h;)$f[$l-++$i][$n]=3;echo join(" ",$f); ``` [Try it online!](https://tio.run/##HctBCsMgFEXReVcR5A38aCFNhka6kBCKTWO0iIopha7eSkZ3cm52uU737HJ3gSl71OOgqk2Fw2pTivk9rA@B9xJB30RIO4fRp5QDSdYxUohCTDCKzs01dnzKkSNvKduXv7b16SNHJJLwum@Hn@AUwc4IVyHglxlx0aPaVpe6d2qaXZiEJVXrHw "PHP – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 20 17 bytes *Saved 3 bytes thanks to @Shaggy and @ETHproductions* ``` õ_¤q1 o Ä ço÷z w ``` [Try it online!](https://tio.run/##y0osKPn///DW@ENLCg0V8hUOtygcXp5/uPnQ9iqF8v//jY0A "Japt – Try It Online") ## Explanation: Input: 5 ``` õ_¤q1 o Ä ço÷z w õ à // Create a range [1...Input] [1,2,3,4,5] _ // Map; At each item: ¤ // Convert to binary ["1","10","11","100","101"] q1 // Split on "1" [["",""],["","0"],["","",""],["","00"],["","0",""]] o // Get the last item ["","0","","00",""] Ä // Add 1 [["1","01","1","001","1"]] ço // Fill with "o" ["o","oo","o","ooo","o"] · // Join with new-lines ["o\noo\no\nooo\no"] z // Rotate 90 degrees ["ooooo\n o o \n o "] w // Reverse [" o \n o o \nooooo"] ``` [Answer] # C, ~~84~~ 74 bytes ``` f(i,l,m){putchar(32+3*!(i&m));i<l?f(i+1,l,m):m?putchar(10),f(1,l,m>>1):1;} ``` ### Ungolfed: ``` void f(int counter, int length, int mask) { putchar((counter&mask) ? ' ' : '#'); if(counter<length) { f(counter+1, length, mask); } else if(mask) { putchar('\n'); f(1, length, mask>>1); } } ``` ### Test with: ``` int main() { f(1, 32, 1023); putchar('\n'); f(1, 1, 1023); putchar('\n'); f(1, 999, 1023); putchar('\n'); } ``` ### Explanation Once again, recursion takes less characters in C than iteration, so the two loops are expressed as the two recursional invocations. Also, C is a great language for playing tricks with boolean expressions, allowing the decision of whether to put a blank or a `#` to be expressed by the expression `32+3*!(i&m)`. A space has the ASCII value of 32, the `#` is ASCII 35, so we get a blank if any of the bits in the mask is set in `i`. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 15 Bytes ``` j_.tm*Nhx_.Bd1S ``` [Try it!](https://pyth.herokuapp.com/?code=j_.tm%2aNhx_.Bd1S&input=70&debug=0) ### explanation ``` j_.tm*Nhx_.Bd1S m SQ # map over the numbers from 0 to the implicit input (lambda variable: d) .Bd # Convert d to a binary string: (12 -> 1100) _ # reverse: (1100 -> 0011) x 1 # get the location of the first 1 ( 2 ) *Nh # make one more than that " quotation marks (""") _.t # transpose the list of quotation mark strings and reverse it j # join on newline ``` [Answer] # [Python 2](https://docs.python.org/2/), 47 bytes ``` f=lambda n:n and' '.join(f(n/2))+'\n'+n*'#'or'' ``` [Try it online!](https://tio.run/##DcvRCkAwFAbgVznl4hgnMqSUJ8HFpGXi31puPP347r/wPoeHTslOl7m33RBGkMHOxNXpHXKbo9ZKlbyASxScsY/MyfpIIAeaG9HSSie9DNLqdaQQHR6C/FOlDw "Python 2 – Try It Online") [Answer] # JavaScript (ES8), 71 bytes The [padStart()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart) function was introduced in ECMAScript 2017! ``` N=>eval(`for(s='',n=1;n<=N;n*=2)s='\\n'+'#'.padStart(n).repeat(N/n)+s`) ``` ``` f= N=>eval(`for(s='',n=1;n<=N;n*=2)s='\\n'+'#'.padStart(n).repeat(N/n)+s`) console.log(f(+prompt())) ``` --- # JavaScript (ES6), 77 bytes ``` N=>eval(`for(s='',n=1;n<=N;n*=2)s='\\n'+(' '.repeat(n-1)+'#').repeat(N/n)+s`) ``` ``` f= N=>eval(`for(s='',n=1;n<=N;n*=2)s='\\n'+(' '.repeat(n-1)+'#').repeat(N/n)+s`) console.log(f(+prompt())) ``` [Answer] # Mathematica, 69 bytes ``` Rotate[Grid["#"~Table~#&/@(IntegerExponent[2*#,2]&/@Range[#])],Pi/2]& ``` [Answer] ## ([WESRRMICGSE](https://codegolf.stackexchange.com/a/102566/60951)): 237 bytes ``` IF(ROW()<=FLOOR(LOG(COUNTA(R1C:R[-1]C,R[1]C:R[1024]C)+1,2),1)+2,LEFT(REPT(REPT(" ",FLOOR(POWER(2,LOG(COUNTA(R1C:R[-1]C,R[1]C:R[1024]C)+1,2)-ROW()+2),1)-1) &"#",COUNTA(R1C:R[-1]C,R[1]C:R[1024]C)+1),COUNTA(R1C:R[-1]C,R[1]C:R[1024]C)+1),"") ``` Alright. 'splaining time. First off, replace every `COUNTA(R1C:R[-1]C,R[1]C:R[1024]C)+1` with simply `[i]`, for input. the token counts the number of cells, not including itself, that contain a formula, and then adds one, to include itself. Since WESRRMICGSE drags a formula according to the input you give it, this token always results in the input. we have: ``` IF(ROW()<=FLOOR(LOG([i],2),1)+3,LEFT(REPT(REPT(" ",FLOOR(POWER(2,LOG([i],2)-ROW()+2),1)-1) &"#",[i]),[i]),"") ``` This is much more readable. You're going to see the `FLOOR(LOG([i],2),1)` token a lot, which simply means take the nearest power of 2 which is less than the input (`[i]`) number. eg: `4->4, 5->4, 6->4, 7->4, 8->8 ...etc`. I'll replace that with `GS[[i]]` ``` IF(ROW()<=GS[[i]]+3,LEFT(REPT(REPT(" ",,FLOOR(POWER(2,LOG([i],2)-ROW()+2),1),1)-1) &"#",[i]),[i]),"") ``` better. breaking down the if clause, we're testing if the row is less than or equal to `GS[[i]]+3`, because all rulers' height is equal to the GS[[i]]+1, this selects the rows which are equal to the height of the ruler. `+1` for 1-indexing rows, and `+1` again for WESRRMICGSE offset. The `FALSE` result yields an empty cell (""), and a true result yields `LEFT(REPT(REPT(" ",,FLOOR(POWER(2,LOG([i],2)-ROW()+2),1),1)-1) &"#",[i]),[i])` currently still editing, stay tuned [Answer] # [Haskell](https://www.haskell.org/), ~~64~~ 62 bytes ``` l m=([2..2^m]>>" ")++'#':l m f n=unlines$take n.l<$>[n,n-1..0] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P0ch11Yj2khPzyguN9bOTklBSVNbW11Z3QoowZWmkGdbmpeTmZdarFKSmJ2qkKeXY6NiF52nk6drqKdnEPs/NzEzT8FWoaC0JLikSEFFIU3B2Og/AA "Haskell – Try It Online") Example usage: `f 10`. [Answer] # k, 33 bytes ``` `0:|" #"{(1+!x){~y!x}/:(x>)(2*)\1} ``` This only seems to work in [AW's interpreter](https://kparc.com). [![Example of it working in AW's interpreter.](https://i.stack.imgur.com/ZKnb9.png)](https://i.stack.imgur.com/ZKnb9.png) [The oK version](http://johnearnest.github.io/ok/?run=%600%3A%7C%22%20%23%22%7B%281%2B%21x%29%7B~y%21x%7D%2F%3A%7Bx%3Ey%7D%5Bx%5D%282%2a%29%5C1%7D32%3B) (which you can try online) seems to have a bug, requiring a slight change to make it work: ``` `0:|" #"{(1+!x){~y!x}/:{x>y}[x](2*)\1} ``` [Answer] ## C#, 174 bytes This method has two parameters, an input for the ruler length, and an output which is the ruler as string. Golfed: ``` void R(int n,out string s){var l=new int[++n];int i,x=n,y=0;for(s="";x-->1;)for(i=0;0==(l[x]=(x>>i++&1)*i);y=y<i?i:y);for(y++;y-->0;s+='\n')for(x=0;++x<n;s+=y<l[x]?'#':' ');} ``` Indented: ``` void R(int n,out string s){ // Return the result in an out parameter. var l=new int[++n]; // Use a 1-based array. int i,x=n,y=0; // for(s="";x-->1;) // For each number x on the ruler for(i=0;0==(l[x]=(x>>i++&1)*i);y=y<i?i:y) // ... find lowest set bit of x, counting the maximum value. ; // for(y++;y-->0;s+='\n') // Count down each line. for(x=0;++x<n;s+=y<l[x]?'#':' ') // Output # for numbers that are tall enough. ; // } ``` ### [Try it online!](https://dotnetfiddle.net/inhmxA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~27~~ 23 bytes ``` ↶F…·¹N«Jι⁰#W¬﹪鲫A÷ι²ι# ``` [Try it online!](https://tio.run/##Vcy9DoIwFAXgGZ6iweU2gURxdDJhwSghxheopcBNSkv652B49irq4nhyznf4yAzXTMbYYtDuLHoH9JD22hCoFZfeYhBXpgYBu5zUavau8dNdGKCUkmeanPw03zRgTrZvl7QGlYNsk63hMaIUBBrt4KI7Lz@z8geTo7U4KKgwYCe@TU5wdf8vS7rEuC9jEWJh5Qs "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 4 bytes by switching to `JumpTo`. [Answer] # J, 38 bytes ``` 3 :'|.|:''#''#~,.(1+|.i.1:)@#:"0>:i.y' ``` Not great. Lmk if the byte count is off -- I'm on my phone. [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` ↔T' ↑moR'#→İr ``` [Try it online!](https://tio.run/##yygtzv7//1HblBB1hUdtE3Pzg9SVH7VNOrKh6P///8ZGAA "Husk – Try It Online") I saw a ruler sequence builtin(`İr`), so I just went ahead and found a challenge I could cheat on. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 91 bytes ``` n->{int i=10,j;String s="";for(;i-->0;s+="\n")for(j=0;j++<n;)s+=j>>i<<i<j?' ':35;return s;} ``` [Try it online!](https://tio.run/##hY6xboNAEERr/BUrGoMwJxzHiuQD0kVKkcplkuKMAe0ZL@husWRZfDu5CPdX7Wjm7Wi0uqm0H2rS58s8jKcOK6g6ZS18KaTHKnh6lhW7c@vxDFeXREc2SO33LyjT2tiBgXZVYmTsRDNSxdiT@HiK/JO4bmuzgeWthAYKmCktH0gMWGyzjZZLBrYIQ9n0JpKYpmUmbVKEPxTG/5YuMqmTJCcZO1uXJeY55vp9DevDbi9NzaMhsHKag0C6Tce75foq@pHF4Mq5o6gRahi6e7SNYw/x4iV2XuLVS@y9xJt/xzJ1Wk3zHw "Java (OpenJDK 8) – Try It Online") Ungolfed: ``` n->{ int i=10,j; // Since we are allowed extra whitespace, set columns always to 10 String s = ""; for(;i-->0;s+="\n") // Every iteration add a newline, i=9..0 for(j=0;j++<n;) // j=1..n+1 s+= j>>i<<i<j // if j has less than i trailing 0s in binary form ?' ' // add a space else :35 // # (java handles ternary return types weirdly) } ``` [Answer] ## CJam, 34 bytes ``` ri{2bW%0+0#)}%_'#f*\:e>f{Se]}zW%N* ``` Meh. [Answer] # [C (gcc)](https://gcc.gnu.org/), 70 bytes ``` f(x,l,n){for(l=512;l/=2;)for(n=0;n++<=x;)putchar(n^x+1?n%l?32:35:10);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9No0InRydPszotv0gjx9bU0Mg6R9/WyFoTxM@zNbDO09a2sa2w1iwoLUnOSASKxVVoG9rnqebYGxtZGZtaGRpoWtf@z03MzNPQrOZSAII0DUMDoCCYDdRVrKGkBOWlaRgbAZm1/wE "C (gcc) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 60 + 1 (-n) = 61 bytes ``` $n=0|1+(log)/log 2;say(($"x(2**$n-1),X)x($_/2**$n))while$n-- ``` [Try it online!](https://tio.run/##K0gtyjH9/18lz9agxlBbIyc/XVMfSCgYWRcnVmpoqChVaBhpaank6Rpq6kRoVmioxOuD@Zqa5RmZOalACd3//83M/@UXlGTm5xX/1/U11TMwNPivmwcA "Perl 5 – Try It Online") [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) ``` õ_&n)¤çTÃz3 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=9V8mbimk51TDejM&input=MzI) ``` õ_&n)¤çTÃz3 :Implicit input of integer U õ :Range [1,U] _ :Map each Z &n : Bitwise AND with -Z ) : Group that operation ¤ : Result to binary string ç : Fill with T : 0 à :End map z3 :Rotate 90° clockwise 3 times :Implicit output joined with newlines ``` ]
[Question] [ **Input:** A list/array of integers for which each item is in the range of `2-36`. **Output:** The sum of the integers (as base 10), where each next integer is in the base of the previous value (starting with a regular base 10). **Example:** Let's say we have an input like this: `[4, 12, 34, 20, 14, 6, 25, 13, 33]` Then we have a sum like this: ``` 4 (4 in base-10) + 6 (12 in base-4 ) + 40 (34 in base-12) + 68 (20 in base-34) + 24 (14 in base-20) + 6 (6 in base-14) + 17 (25 in base-6 ) + 28 (13 in base-26) + 42 (33 in base-13) = 235 ``` ***Mathematical base explained:*** I considered assuming everyone knows how base works, but I'll give a brief example of how it works anyway, just in case. Let's take the `34 in base-12` for example, how did we get `40`? ``` 1-34 in regular base-10: 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 So, from 1 to 34 is 34 steps in base-10 1-34 in base-12: 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 2A, 2B, 30, 31, 32, 33, 34 So, from 1 to 34 is 40 steps in base-12 ``` [Here is perhaps a useful calculator.](http://planetcalc.com/2095/) **Challenge rules:** * Array size will be in reasonable range (like `1-100` / see test cases). * The test cases will never contain integers of which the current value is invalid for it's previous base (i.e. You will never have something like `19 in base-6` or `6 in base-6`, because base-6 only contains the digits `0-5`). * You can take the input any way you'd like. Can be as an int-array, as a comma/space-separated string, etc. Your call. (You are also allowed to take the int-array reversed, which could be useful for stack-based programming languages.) **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-golfing languages. Try to come up with as short an answer as possible 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:** ``` [4, 12, 34, 20, 14, 6, 25, 13, 33] -> 235 4+ 6+ 40+ 68+ 24+ 6+ 17+ 28+ 42 [5, 14, 2, 11, 30, 18] -> 90 5+ 9+ 2+ 3+ 33+ 38 [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 12, 2, 11, 3, 10, 2, 10] -> 98 12+ 13+ 11+ 9+ 8+ 7+ 6+ 5+ 4+ 3+ 5+ 2+ 3+ 3+ 3+ 2+ 2 [36, 36] -> 150 36+ 114 ``` [Answer] # Python 3, 40 bytes ``` lambda a:sum(map(int,map(str,a),[10]+a)) ``` Tests are at **[ideone](http://ideone.com/7ZUpcU)** `map(str, a)` creates a generator, `G`, that calls `str` on each value in `a`, converting to strings `map(int, G, [10]+a)` creates a generator that calls `int(g, v)` for pairs across `G` and `[10]+a` `int(g, v)` converts the string `g` from the integer base `v` (if `v` is in `[2,36]` and `g` is valid) `sum` does what it says on the tin [Answer] # Python 2, 48 bytes ``` lambda a:sum(int(`x`,y)for x,y in zip(a,[10]+a)) ``` Tests are at **[ideone](http://ideone.com/ePipjY)** `zip(a,[10]+a)` traverses pairs of the values in `a`, and the previous value or `10` for the first the `backticks` in the `int` call convert `x` to a string, `s` `int(s, y)` converts the string `s` from the integer base `y` (if `y` is in `[2,36]` and `s` is valid) `sum` does what it says on the tin [Answer] # Perl, ~~35~~ ~~34~~ 33 bytes Includes +2 for `-ap` Run with the list of numbers on STDIN: ``` basemix.pl <<< "4 12 34 20 14 6 25 13 33";echo ``` `basemix.pl`: ``` #!/usr/bin/perl -ap $\+=$&+"$`$& 10"*/.$/*$`for@F}{ ``` I've been waiting for ages for a chance to use this abuse... ## Explanation The input numbers can have at most 2 digits. A number `xy` in base `b` is simply `b*x+y`. I'm going to use the regex `/.$/` so the first digit ends up in `$`` and the last digit in `$&`, so the contribution to the sum is `$&+$b*$``. I abuse the fact that `for` does not properly localize the regex variables (like for example `map` and `while` do) so the results of a match in the previous loop is still available in the current loop. So if I'm careful about the order in which I do the operations the base is available as `"$`$&"`, except for the very first loop where I need the base to be 10. So I use `"$`$& 10"` instead The way the first `$&` works is an abuse too since it is actually changed by the `/.$/` while it is already on the stack waiting to be added. The final abuse is the `}{` at the end which changes the loop implied by `-p` from ``` LINE: while (defined($_ = <ARGV>)) { ...code.. } continue { die "-p destination: $!\n" unless print $_; } ``` to ``` LINE: while (defined($_ = <ARGV>)) { ...code.. } { } continue { die "-p destination: $!\n" unless print $_; } ``` Which means `$_` will be undefined in the print, but it still adds `$\` in which I accumulated the sum. It is also a standard golf trick to get post-loop processing [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~7~~ ~~6~~ 5 bytes Uses the [05AB1E](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md) encoding. Saved 1 byte using the new built-in `š` as suggested by *Kevin Cruijssen* ``` TšüöO ``` **Explanation** Input list is taken reversed, as allowed by challenge specification. ``` Tš # prepend a 10 to the list üö # reduce by conversion to base-10 O # sum ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/5OjCw3sOb/P//z/a0EBHwUhHAUQZAylDCM8IzDPRUTDVUTDTUTDXUbDQUbCEKAOpMTSKBQA) [Modified testsuite](https://tio.run/##yy9OTMpM/V9TVql8eP3/kEOrDu85vM3/v85/Y2MFQ2MFI1MFMwVDEwUjAwVjEwVDIwUTLkMLBWMDBUNDBSOQhCmXoQGIBZSHihkBWUBxoD5zBQsFS5AUUMLQiMvYTMHYDAA) [Answer] # PHP, ~~53~~ 51 bytes ``` for(;$x=$argv[++$i];$b=$x)$s+=intval($x,$b);echo$s; ``` Iterates over the input, converting each input to string variant. Then takes the integer value using the previous number as base. For the first number, the base will not be set, PHP will then start off with 10 (inferred from the number format). Run like this (`-d` added for aesthetics only): ``` php -d error_reporting=30709 -r 'for(;$x=$argv[++$i];$b=$x)$s+=intval($x,$b);echo$s;' -- 12 11 10 9 8 7 6 5 4 3 12 2 11 3 10 2 10;echo ``` ## Tweaks * Actually, no need to convert to string, as CLI arguments are already string. Saved 2 bytes. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 7 bytes ``` ṙ1DḅṖḌS ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmZMUThuIXhuZbhuIxT&input=&args=WzQsIDEyLCAzNCwgMjAsIDE0LCA2LCAyNSwgMTMsIDMzXQ) [Answer] # Java, 86 bytes ``` s->{int[]b={10};return s.reduce(0,(r,n)->{r+=n.valueOf(""+n,b[0]);b[0]=n;return r;});} ``` ## Testing and ungolfed ``` import java.util.function.ToIntFunction; import java.util.stream.Stream; public class Main { public static void main(String[] args) { ToIntFunction<Stream<Integer>> f = s -> { int[] b = {10}; // Base, initialized with 10 return s.reduce(0, (r, n) -> { // Typical use of reduction, sum starts with 0. r += n.valueOf("" + n, b[0]); // Add the value in the previous base. b[0] = n; // Assign the new base; return r; }); }; System.out.println(f.applyAsInt(Stream.of(new Integer[]{4, 12, 34, 20, 14, 6, 25, 13, 33}))); } } ``` [Answer] ## JavaScript ES6, ~~45~~ ~~42~~ 41 Bytes ``` const g = a=>a.map(v=>s+=parseInt(v,p,p=v),s=p=0)|s ; console.log(g.toString().length); // 42 console.log(g([4, 12, 34, 20, 14, 6, 25, 13, 33])); // 235 console.log(g([5, 14, 2, 11, 30, 18] )); // 90 console.log(g([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 12, 2, 11, 3, 10, 2, 10] )); // 98 ``` Conventiently `parseInt(x,0) === parseInt(x,10)`. **edit**: Saved 1 byte thanks to @ETHproductions [Answer] # Pure bash, 38 ``` b=10 for i;{((t+=$b#$i,b=i));} echo $t ``` The input list is given at the command-line. `for i;` automatically iterates over the input parameters (equivalent to `for i in $@;`). [Ideone.](https://ideone.com/l6myr3) [Answer] # Java 7, ~~109~~ ~~89~~ 86 bytes ``` int c(int[]a){for(Byte i=1;i<a.length;a[0]+=i.valueOf(a[i]+"",a[++i-2]));return a[0];} ``` Golfed 20 bytes thanks to *@cliffroot* (of which 12 because of a stupid mistake I made myself). **Ungolfed & test code:** [Try it here.](https://ideone.com/gPDKU2) ``` class M{ static int c(int[] a){ for(Byte i = 1; i < a.length; a[0] += i.valueOf(a[i]+"", a[++i-2])); return a[0]; } public static void main(String[] a){ System.out.println(c(new int[]{ 4, 12, 34, 20, 14, 6, 25, 13, 33 })); System.out.println(c(new int[]{ 5, 14, 2, 11, 30, 18 })); System.out.println(c(new int[]{ 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 12, 2, 11, 3, 10, 2, 10 })); System.out.println(c(new int[]{ 36, 36 })); } } ``` **Output:** ``` 235 90 98 150 ``` [Answer] ## Actually, 12 bytes ``` ;p(dX(♂$♀¿Σ+ ``` [Try it online!](http://actually.tryitonline.net/#code=O3AoZFgo4pmCJOKZgMK_zqMr&input=WzQsIDEyLCAzNCwgMjAsIDE0LCA2LCAyNSwgMTMsIDMzXQ) Explanation: ``` ;p(dX(♂$♀¿Σ+ ; dupe input p pop first element from list (dX pop and discard last element from other copy (♂$ stringify all elements in first copy ♀¿ for each pair of elements in the two lists, interpret the first element as a base-(second element) integer Σ sum + add first element of original list ``` [Answer] ## [CJam](http://sourceforge.net/projects/cjam/), 15 bytes ``` l~{A\:A10bb}%:+ ``` [Try it online!](http://cjam.tryitonline.net/#code=bH57QVw6QTEwYmJ9JTor&input=WzQgMTIgMzQgMjAgMTQgNiAyNSAxMyAzM10) ### Explanation ``` l~ e# Read and evaluate input. { e# Map this block over the input... A e# Push A. Initially this is 10, afterwards it will be the value of the e# last iteration. \:A e# Swap with current value and store that in A for the next iteration. 10b e# Convert to base 10 to get its decimal digits. b e# Interpret those in the base of the previous A. }% :+ e# Sum all of those values. ``` [Answer] # Haskell, ~~65~~ 59 bytes ``` b%x|x<1=x|y<-div x 10=b*b%y+x-10*y sum.((10:)>>=zipWith(%)) ``` Test it on [Ideone](http://ideone.com/dWMAuf). [Answer] # Matlab, 68 bytes Not a very creative solution, but here it is: ``` function[s]=r(x);j=10;s=0;for(i=x)s=s+base2dec(num2str(i),j);j=i;end ``` Tests: ``` >> r([4,12,34,20,14,6,25,13,33]) ans = 235 >> r([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 12, 2, 11, 3, 10, 2, 10]) ans = 98 >> r([5, 14, 2, 11, 30, 18]) ans = 90 >> r([36,36]) ans = 150 ``` [Answer] # JavaScript (ES6), ~~54~~ ~~48~~ 40 bytes I used a recursive approach. ``` f=([b,...a],c)=>b?parseInt(b,c)+f(a,b):0 ``` Saved 6 bytes, thanks to Lmis! Saved 8 more bytes, thanks to Neil! [Answer] # [Perl 6](https://perl6.org), ~~52~~ 50 bytes ``` {sum (10,|@_).rotor(2=>-1).map:{+":{.[0]}<{.[1]}>"}} {sum (10,|@_).rotor(2=>-1).map:{":{.[0]}<$_[1]>"}} ``` ## Explanation: ``` # bare block lambda with implicit parameter 「@_」 { sum ( 10, |@_ ) # the input with a preceding 10 .rotor( 2 => -1 ) # grab 2 values, back up one, repeat .map: { # create a string of the form ":10<4>" ":{ .[0] # first element from $_ }<{ .[1] # second element from $_ }>" } } ``` [Answer] # Python 2, 52 bytes ``` f=lambda x:x[1:]and int(`x.pop()`,x[-1])+f(x)or x[0] ``` Test it on [Ideone](http://ideone.com/CBEcYy). [Answer] ## Julia, 63 Bytes ``` f(l)=sum([parse(Int,string(l[i]),l[i-1])for i=2:length(l)])+l[] ``` Parses each number (except the first) taking the previous element as base and sums. Adds the first element at the end [Answer] ## Ruby, 52 bytes ``` ->a{eval a.zip([10]+a).map{|e|'"%s".to_i(%s)'%e}*?+} ``` ### ungolfed ``` ->a{ eval( a.zip([10]+a).map { |e| '"%s".to_i(%s)' % e }.join("+") ) } ``` ### usage ``` f=->a{eval a.zip([10]+a).map{|e|'"%s".to_i(%s)'%e}*?+} p f[[4, 12, 34, 20, 14, 6, 25, 13, 33]] # => 235 ``` [Answer] # Scala, 67 bytes ``` def f(a:Int*)=a zip(10+:a)map{t=>Integer.parseInt(""+t._1,t._2)}sum ``` Explanation: ``` def f(a: Int*) = //declare a method f with varargs of type Int as parameter a zip (10 +: a) //zip a with 10 prepended to a, resulting in... //...Array((4,10), (12,4), (34,12), (20,34), (14,20), (6,14), (25,6), (13,25), (33,13)) map { t => //map each tuple t to... Integer.parseInt( //...an integer by parsing... ""+t._1, t._2 //...a string of the first item in base-second-item. ) } sum //and sum ``` [Answer] # Mathematica, 59 bytes I wish Mathematica's function names were shorter. But otherwise I'm happy. ``` Tr[FromDigits@@@Transpose@{IntegerDigits/@{##,0},{10,##}}]& ``` For example, ``` Tr[FromDigits@@@Transpose@{IntegerDigits/@{##,0},{10,##}}]&[4,12,34,20,14,6,25,13,33] ``` yields `235`. `{##,0}` is a list of the input arguments with 0 appended (representing the numerals); `{10,##}` is a list of the input arguments with 10 prepended (representing the bases). That pair of lists is `Transpose`d to associate each with numeral with its base, and `FromDigits` (yay!) converts each numeral-base pair to a base-10 integer, the results of which are summed by `Tr`. [Answer] ## Common Lisp, 83 ``` (lambda(s)(loop for b ="10"then x for x in s sum(#1=parse-integer x :radix(#1#b)))) ``` ### Details ``` (defun base-mix (list) (loop for base = "10" then string for string in list sum (parse-integer string :radix (parse-integer base)))) ``` The `loop` construct accepts *"v then w"* iteration constructs, where *v* is an expression to be evaluated the first time the iteration variable is computed, and *w* is the expression to be evaluated for the successive iterations. Declarations are evaluated one after the other, so `base` is first "10", then the previous element `string`of the list `list` being iterated. The `sum` keyword computes a sum: the integer read from `string` with base *b*, where *b* is the integer parsed from the `base` string, in base 10. `#1=` and `#1#` are notations to define and use *reader variables*: the first affects an s-expression to a variable, the other one replaces the reference by the same object. This saves some characters for long names. ### Example ``` (base-mix '("4" "12" "34" "20" "14" "6" "25" "13" "33")) => 235 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 7 bytes ``` äÏsnX}A ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg=&code=5M9zblh9QQ==&input=WzQsMTIsMzQsMjAsMTQsNiwyNSwxMywzM10=) ``` äÏsnX}A :Implicit input of array ä :Take each consecutive pair of elements Ï :Pass them through the following function as X & Y s : Convert Y to a base-10 string nX : Convert to an integer from base-X } :End function A :Before doing any of that, though, prepend 10 to the array :Implicit output of the sum of the resulting array ``` ]
[Question] [ **Recursively prime-encoded integers** Consider \$11681169775023850 = 2 \times 5 \times 5 \times 42239 \times 5530987843\$. This isn't a nice prime factorisation, as \$42239\$ and \$5530987843\$ make it difficult to store this factorisation in a small manner. Being primes, we can't then factorise them, but we can factorise \$p - 1\$, which is guaranteed to not be prime (ignoring \$p = 3\$). by doing this we get: * \$42239 \to 42238 = 2 \times 7 \times 7 \times 431\$ * \$5530987843 \to 5530987842 = 2 \times 3 \times 17 \times 54225371\$ This helps, but \$431\$ and \$54225371\$ are still pesky, so we run the same procedure (prime factorising their decrement). Just to be safe, we'll also do it with \$17\$ so that we can only have single digit primes (\$2,3,5,7\$) in the final result. This eventually results in: ``` [2, 5, 5, [2, 7, 7, [2, 5, [2, 3, 7]]], [2, 3, [2, 2, 2, 2], [2, 5, [2, 2, 2, 5], [2, 2, 2, 2, 2, [2, 2, [2, 2, 2, 3, [2, 3, 7]]]]]]] ``` representing \$11681169775023850\$. [This](https://tio.run/##y0rNyan8///opIc7ZzxqWpP1qGGOgq6dwqOGuQ93tjzcOfvhzlVcOofb0g63P2qYeXi@it2hhUBllv///zc0NLMAYktzc1MDI2MLUwMA) is a program that shows the steps of decomposition of the input, and [this](https://tio.run/##y0rNyan8//9wW5rCo4aZh@erKBzaqWBnqWL/qGkN1@H2o5Me7pzx//9/Q0MzCyC2NDc3NTAytjA1AAA) is a program which decomposes a given integer. The representations for the integers from 2 to 25 are: ``` 2 [2] 3 [3] 4 [2, 2] 5 [5] 6 [2, 3] 7 [7] 8 [2, 2, 2] 9 [3, 3] 10 [2, 5] 11 [[2, 5]] 12 [2, 2, 3] 13 [[2, 2, 3]] 14 [2, 7] 15 [3, 5] 16 [2, 2, 2, 2] 17 [[2, 2, 2, 2]] 18 [2, 3, 3] 19 [[2, 3, 3]] 20 [2, 2, 5] 21 [3, 7] 22 [2, [2, 5]] 23 [[2, [2, 5]]] 24 [2, 2, 2, 3] 25 [5, 5] ``` For example, for `[2, [2, 5]]`, we first multiply the inner list and increment to get `[2, 11]`. From here, we just multiply, resulting in the final output of `22` --- You are to take the representation of a recursively prime-encoded integer and output the original integer. The input will be a jagged list, where each element is either a single digit prime (\$2,3,5,7\$) or a list where the same rule applies. The input will never contain empty lists, and will never be empty. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins ## Test cases ``` [2, 2, 2, 5] -> 40 [[2, 2, 3]] -> 13 [[2, 3, 5]] -> 31 [3] -> 3 [2, 3, 3, 5] -> 90 [2, [2, [2, 5]]] -> 46 [[2, 5]] -> 11 [[2, 2, 7, [2, 2, 2, 2, 3, 7]]] -> 9437 [2, 2, 2, 2, 2, 3, 5] -> 480 [2, 2, 2, 7, [2, 2, 2, 2]] -> 952 [2, [2, 2, 3, 7, [2, 3, 3]]] -> 3194 [2, 3, 3, [2, 2, 2, 2, 2, 2, 7]] -> 8082 [5, [2, 2, 7], [2, [2, [2, 5]]]] -> 6815 [5, [2, [2, 2, [2, 2, 2, 5], [2, [2, 5, 5, 5]]]]] -> 824935 [3, 3, [2, 2, 3, 3], [2, 7, [2, [2, 2, 2, 5]]]] -> 387279 [7, [2, 2, 5, 5], [2, 3, 5, [2, 3, 7]]] -> 912737 [[2, [2, [2, 5, [2, 2, 3]], [2, 2, 2, 2, 3, 3, 7]]]] -> 528719 [2, 2, 2, 2, 7, [2, 5], [2, 2, [2, 2, 2, 2, 2, 2, 3]]] -> 952336 [2, 3, 3, [2, 3, 5], [2, 5, 5, [2, 2, 7]]] -> 809658 [[2, 2, 2, 3, [2, 2, [2, 3, 7]]], [2, 2, 2, 2, 2, 2, 3, [2, 2, 3], [2, 2, 7, [2, 3, 3, 7]], [2, 5, [2, 2, 2, [2, 5]], [2, [2, 2, [2, 2, 3]]]]]] -> 3511306351619449 [5, 7, 7, [2, 3, [2, 5], [2, [2, 2, 2, 5]]], [2, 2, 2, 7, [2, [2, [2, 2, 2, [2, 5]]]], [2, 2, 2, 2, 2, 3, 3, [2, 5, [2, 3, [2, 2, 2, 2]]]]]] -> 8013135306533035 [2, 3, 3, [2, 2, 2, 3, 3], [2, 3, [2, [2, 5]]], [2, 3, [2, 2, 3, [2, 2, 2, 2, 2, 3], [2, [2, 5, 7, 7]], [2, 2, [2, 5], [2, 2, [2, 2, 3]]]]]] -> 2925382459116618 ``` [Answer] # [Python 2](https://docs.python.org/2/), 42 bytes *Thanks to @tsh for suggesting a 2-byte improvement* ``` f=lambda x=1,*a:x<2or-(x*-1or~f(*x))*f(*a) ``` [Try it online!](https://tio.run/##dVPLboMwELzzFb4VoqRivRjbUemPIFRRNVEi5YFS0qSX/npqbOMHpZIjYntndnd23H33u/OJPh7b6tAe3z9acq9guWjX9xd6vqzS@2IF58vPNl3cs2yhPm32uO32hw2BdUL2p25Jzte@IxU5tl26@WoPS3Jpb2/q5tqn2fNnd9j36RNZvZKnLEtId9mfeqJ4VEBGqkqjHzVdErNYM4QWeVLbM2z0CaA5wSFEnyAkNZp/ib3BES9zfTT@FMLQlobEMgC4LNwEuqWYuAXJAnkSXdIgUyHy4DKmsXhGXTGW2WxQN2d7kUXQxDQb1dUMgSIXio25EN74LsdOdWApgLlAGxyqHEDMakakoIVEhY1K0bWaHY84w5woOOUyqb0KzKdCvasn2gLlg7pRCz5p0/wdi0VrOKOCg4yHw0chZtr2PI2bDWI5UR49moXljEWLXJZMOOvQUKegv/nEQXOe2PtBQ6c6@NnOjRMbNzpkAJiX6lMqQxVSG4CHCerJ8P0Ewz2PTRWVMNeY145Fmdw7cN7KAQGZqpEh5oPLZjwfeA1jZ0/JZ54Kxs7mgaD0P2cEClJJGaoXwCRAWYL4BQ "Python 2 – Try It Online") `-(x*-1or~f(*x))` computes for a given element, its decoded value. If `x` is an integer, the `or` will short circuit, resulting in `x` as the value. If it is a list, `x*-1` will return an empty list, and the result becomes a recursive call on `x`: `-~f(*x)`. This result is then multiplied by the rest of the elements through recursion: `f(*a)`. Finally, the default `x=1` argument assists in the terminating condition of `x<2`. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 13 bytes ``` ¯1+(≡+×/)⍥1⍣≡ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//9B6Q22NR50LtQ9P19d81LvU8FHvYiD3f9qjtgmPevsedTUfWm/8qG3io76pwUHOQDLEwzP4v4mBgq1CmgKQ6xXs76egHm2kowBBprHqXMZoksZAMRMzTB0wbBobC1RhZmFoiqbGFCIPROaxCOUwLUA9libG5mh6YBrgWiHIGGQGSIupkYW5oSUWTXCj4TqNY2MxTYEaFKsOAA "APL (Dyalog Extended) – Try It Online") Takes a nested APL array (which can be obtained from JSON-converting the test cases) and returns the original number. ### How it works This uses the Depth operator `f⍥n`, which hasn't made into mainstream yet. A depth-1 value in a mixed array can be a vector or a scalar (if one of its siblings is nested). `≡+×/` is an expression that keeps scalar intact (product is itself and its depth `≡` is 0), and evaluates product + 1 for vectors. Now, we can simply repeat this at depth 1 until the entire value becomes a single number, and subtract 1 at the end (to negate the +1 applied at the very last layer). [Answer] # [yuno](https://github.com/hyper-neutrino/yuno), 5 bytes ``` ᴘ’)υ‘ ``` [Try it online!](https://yuno.hyper-neutrino.xyz/#WyIiLCLhtJjigJkpz4XigJgiLCIiLCIiLCIiLFsiWzIsIDMsIDMsIFsyLCAyLCAyLCAzLCAzXSwgWzIsIDMsIFsyLCBbMiwgNV1dXSwgWzIsIDMsIFsyLCAyLCAzLCBbMiwgMiwgMiwgMiwgMiwgM10sIFsyLCBbMiwgNSwgNywgN11dLCBbMiwgMiwgWzIsIDVdLCBbMiwgMiwgWzIsIDIsIDNdXV1dXV0iXV0= "yuno online interpreter") ``` (ᴘ’)υ‘ Main Link ( )υ Deep Recurse; on each sub-list and recursively, call ᴘ - Product ’ - Increment ‘ Decrement ``` I've had the idea for `υ` from ever since I first started drafting yuno, but this adverb was implemented after this challenge. **Old version** # [yuno](https://github.com/hyper-neutrino/yuno), 7 bytes ``` ɫ’)ᴅ?Ͼᴘ ``` [Try it online!](https://yuno.hyper-neutrino.xyz/#WyIiLCLJq+KAmSnhtIU/z77htJgiLCIiLCIiLCIiLFsiWzIsIDMsIDMsIFsyLCAyLCAyLCAzLCAzXSwgWzIsIDMsIFsyLCBbMiwgNV1dXSwgWzIsIDMsIFsyLCAyLCAzLCBbMiwgMiwgMiwgMiwgMiwgM10sIFsyLCBbMiwgNSwgNywgN11dLCBbMiwgMiwgWzIsIDVdLCBbMiwgMiwgWzIsIDIsIDNdXV1dXV0iXV0= "yuno online interpreter") Expect this to get shorter later once I implement more adverbs. For now, this is the same approach as my Jelly solution. ``` (ɫ’)ᴅ?Ͼᴘ Main Link Ͼ For each item ? - If ᴅ - It has depth (it is a list and not just a single number) (ɫ’) - Monadic function: ɫ - Call this link as a monad ’ - And increment ᴘ Take the product ``` [Answer] # JavaScript (ES6), 35 bytes ``` f=a=>a.map(n=>p*=+n||f(n)+1,p=1)&&p ``` [Try it online!](https://tio.run/##dVRNj5swEL3zKzjt2t0EYQ/Gtlbm1ksP7aFHirQoTVqqLKAERSt1@9tTMMYflEpG4PG8@XjzzK/6Vl8Pl6Yf9m33/Xi/n1Stijp5rXvUqqL/oJ7a9/cTavET2fWK4IeH/j6ol6iku3herIr3RZylUWlsUGkLgdkCk4u2AIlKmL8icwILXqbatDwjYg6bz0FMBEJsFj472jVG4gYkM@BRcEi9TJlIvcMwjMEzaosxkecN6OZMLzLzmlhno7qayVGkYozGrAuvXJdLp9oxF4RZR@Pss@xB5lUtSEEzCSM2KEXXOu94ENPPCYJTLqPSscBcKtC7csUtoXxiN2jBJa2qf8di0BrOqOBEhsPhCxEbbbs4lZ0NQL5iHhya@eUsRYtU5kxY6VCfJ6@/7cRecy6w04OGrnlws90aJ1R2dMAIgTQfX/koqExqAXA/Qbkavpugv@ehqIISthpz3LEgk70HVlspAQJsrJEBpJPKNjTvaQ1CZa@Db1wVCJXNPULp/5ThMUglZTDeACYJyXMiopdkuDSvCCfX/twM6PFb@4j1/@wtVkX8tpj3hTHfJvOnr18@J319uR7RDWP8HA3Jqbt8rA8/ESqbXdxVeHL7HcXxoWuv3fmYnLsf6IQarFS3m94j6A9@vv8F "JavaScript (Node.js) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~22~~ 17 bytes ``` 1+1##&@@#&//@#-1& ``` [Try it online!](https://tio.run/##dVNNi9swEL3rVwSn5FKHtTSWJRESXOgeeivd3oQOJnhbQTYOWRcWQn57Kku2PlwXHKKPeW9m3jy9Nf3v9q3p9bF5vO4f@DNerzd1vd48PdXrLd48vnYS3XTe3fcnfW53SO9/ds8fl2v7/q67c/3SX/X514/2cmqOrbxlMtsesluWZ2pY3LO7qvUOdSmo26HvBtbL11rv912utwezUii/DTlyx/n80V@bYy8/vRyv@tJ/O1/@9O4mz5Ah/3I65dlqe1i5tbqrhyT5yn1UDTdlgeR4BsqeYHAnMITYE8BIgluh8QYmvCjs0fQzCEdbOZKRAWOfhblA/xkmNoJECQwllyTKVPIiukxpRjwlvpiR2W3ANjf2IsqoiXk2YqsZAnnBDRv1IUyFLqdObWDFMfWBY3CscgRxn5qQnJQCDDYpxdbqdizhjHMCZ4QJJIMKNKQCu5MzbTFhg7pJCyGpUv@OZURbOCWcYZEOh01CLLQdeJSfDUA1Ux4CmsblTEXzQlSUe@uQWKeov@XEUXOBOPjBQuc6hNkujROUHx1QjKGozF9lDFUKawAWJ5Cz4YcJxnuWmiopYamxoB1NMvl34L1VYMBATY0UoBhctuD5yGuQOntOvvBUIHU2iwQl/3NGpCARhIJ5AVRgXFWY/wU "Wolfram Language (Mathematica) – Try It Online") ``` 1+1##&@@#&//@# expressions become the product of their arguments plus 1 -1& subtract 1 (outermost list doesn't increment) ``` [Answer] # [Perl 5](https://www.perl.org/) (`-p`), 30 bytes ``` y/,]/*)/;s/\[/(1+/g;$_=-1+eval ``` replacing `[` , `,`, `]` with `(1+`, `*`, `)` resp., and evaluating. [Try it online!](https://tio.run/##dVPLTsMwELznK3rIodCm9nrjF1HhC/iCYFUcCkKqaEUREj9PcGzHjxAkV43tndnd2fHl@HHiw5WsmvvVend7Q0hXH/c1dMM32RpiD7oreerJGjbktasP@wY2x6/n0zB@28h9fXg4370MPduu/OJm5Gpp1YczNO4E0J/gGOJOEKoe/VcVbnDCa@qOpp9FeFrhSQIDQMwifWBclkkGkG5RVsUlyzK1imaXJU3AcxaLCcx@g6650Itusybm2ZirZgxUVFk2HkOkSV1OnbpAoYDHwBCcq5xB/DITUrFWo8UWpbha/U4WnHlOVJJJXfVJBZ5Sodv1M22ByVHdooWU1Ji/YwloB@dMSdDlcOQkxELbicfE2SCKmfKY0DwvZypaUS24itZhuU5Zf8uJs@YScfKDg851SLNdGieaODrkAEiF/RPWUK12BpB5gn42/DTBfC9LUxUlLDWWtONFpvgOorcoICC3NXJEOrpswfOZ17B09px84alg6WyZCcr@c0amINOMo30BXAMIAernfPl8O79fh@aR7ygMzenyCw "Perl 5 – Try It Online") # [Perl 5](https://www.perl.org/), 42 bytes ``` sub f{my$r=1;map$r*=@$_?1+f(@$_):$_,@_;$r} ``` with a recursive function [Try it online!](https://tio.run/##dVPbbsIwDH3vV/ShD8Bg1HHTJKAC/1FVFZNAQoKByjZpQvz6ujRJc@k6Kb3EsY/t45PboTnTtr1/vsXHx@U7aQpYX/a3pJkVu6TewstxIr/TVVLPd/U6aZ5tUhfS9jh87c8JPKdFkZDtdXWMT8fl5HU2XWy697ItyTzWi1bxYhNnaVQaG1bKAqgt2LkoC0JUov6LzAn28SJVpv6RERo21yAGAcBmYdrRLonETJDIkEXBIfEyZTz1DkMYE0@JLcYg6w2q5kwvIvOaGGYjqprOkadcolHrwirXZd@pcsw5UOtonH2WvRC9qj6Sk0ygjA1KUbXqHQsw/ZzIGWEiKh0L1KVCtSsH3AJhHbtBCy5pVf0di4lW4ZRwBiIcDuuJGGnb4VR2Noj5gHl00dQvpy@apyKn3EqH@Dx5/Y0n9ppzwE4PKnTIg5vt2DixsqNDCoBpLj@5FFQmlACYn6AcDN9N0N@zUFRBCWONOe5okMneA6utFBCQyhopYtqpbETzntYwVPYQfOSqYKhs5hFK/lOGxyARhKK8AVQA5Dnwn@vt43R9v7eL8@0X "Perl 5 – Try It Online") [Answer] # [J](http://jsoftware.com/), 46 45 bytes ``` [:(*>:)/[:;L:1^:_[:*/L:0;~&1^:((1=#)*1<L.)L:2 ``` [Try it online!](https://tio.run/##XYzBTsMwEETv@YoRSDSOihsnBVTH4QASJ6sHrhGgpjiNIThV7Eqc@PXgxCAhDrvSvpm3b@MZXTQoORZYIgX3c0lx/ygfxorHyS0nq4oXkrNn/lLxZCV5Wnxd@CuOWXlOEiYkJZJnI4nqkqKAwPaOolXdUQ1o@gEfu3dtDjDKOvWKuv/0u9PW2ch55J0nb8VlQ2axU42bStj3xu20sdDmeHJLDPrQ/ksmH4Oyp85Fkdq3PXIWoBDIkOMq0E36Q2foMQJfXweeoZ5HZL9Gzjbrv9nk3YSGfzB@Aw "J – Try It Online") I thought this was going to be like 10 chars... [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ß‘µ¹ŒḊ?€P ``` [Try it online!](https://tio.run/##y0rNyan8///w/EcNMw5tPbTz6KSHO7rsHzWtCfj//3@0kY6CMRiBWBAE4sdCBKDiIGwaG4sqaISmDSoUi6RFR8EciGD64AahcMF6wAAA "Jelly – Try It Online") ``` ß‘µPŒḊ?€P Main Link € For each element: ? - If ŒḊ - It has depth (isn't a number) ß‘µ - Call this link on the sub-list, take the product, and increment it P - Otherwise, take the product (or first element, or sum, w/e) P Take the product ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` â╥¡░Ω↕¬∟oqFµ+ ``` [Run and debug it](https://staxlang.xyz/#p=83d2adb0ea12aa1c6f7146e62b&i=%5B2,+2,+2,+5%5D+%0A%5B%5B2,+2,+3%5D%5D+%0A%5B%5B2,+3,+5%5D%5D+%0A%5B3%5D+%0A%5B2,+3,+3,+5%5D+%0A%5B2,+%5B2,+%5B2,+5%5D%5D%5D+%0A%5B%5B2,+5%5D%5D+%0A%5B%5B2,+2,+7,+%5B2,+2,+2,+2,+3,+7%5D%5D%5D+%0A%5B2,+2,+2,+2,+2,+3,+5%5D+%0A%5B2,+2,+2,+7,+%5B2,+2,+2,+2%5D%5D+%0A%5B2,+%5B2,+2,+3,+7,+%5B2,+3,+3%5D%5D%5D+%0A%5B2,+3,+3,+%5B2,+2,+2,+2,+2,+2,+7%5D%5D+%0A%5B5,+%5B2,+2,+7%5D,+%5B2,+%5B2,+%5B2,+5%5D%5D%5D%5D+%0A%5B5,+%5B2,+%5B2,+2,+%5B2,+2,+2,+5%5D,+%5B2,+%5B2,+5,+5,+5%5D%5D%5D%5D%5D+%0A%5B3,+3,+%5B2,+2,+3,+3%5D,+%5B2,+7,+%5B2,+%5B2,+2,+2,+5%5D%5D%5D%5D+%0A%5B7,+%5B2,+2,+5,+5%5D,+%5B2,+3,+5,+%5B2,+3,+7%5D%5D%5D+%0A%5B%5B2,+%5B2,+%5B2,+5,+%5B2,+2,+3%5D%5D,+%5B2,+2,+2,+2,+3,+3,+7%5D%5D%5D%5D+%0A%5B2,+2,+2,+2,+7,+%5B2,+5%5D,+%5B2,+2,+%5B2,+2,+2,+2,+2,+2,+3%5D%5D%5D+%0A%5B2,+3,+3,+%5B2,+3,+5%5D,+%5B2,+5,+5,+%5B2,+2,+7%5D%5D%5D+%0A%5B%5B2,+2,+2,+3,+%5B2,+2,+%5B2,+3,+7%5D%5D%5D,+%5B2,+2,+2,+2,+2,+2,+3,+%5B2,+2,+3%5D,+%5B2,+2,+7,+%5B2,+3,+3,+7%5D%5D,+%5B2,+5,+%5B2,+2,+2,+%5B2,+5%5D%5D,+%5B2,+%5B2,+2,+%5B2,+2,+3%5D%5D%5D%5D%5D%5D+%0A%5B5,+7,+7,+%5B2,+3,+%5B2,+5%5D,+%5B2,+%5B2,+2,+2,+5%5D%5D%5D,+%5B2,+2,+2,+7,+%5B2,+%5B2,+%5B2,+2,+2,+%5B2,+5%5D%5D%5D%5D,+%5B2,+2,+2,+2,+2,+3,+3,+%5B2,+5,+%5B2,+3,+%5B2,+2,+2,+2%5D%5D%5D%5D%5D%5D+%0A%5B2,+3,+3,+%5B2,+2,+2,+3,+3%5D,+%5B2,+3,+%5B2,+%5B2,+5%5D%5D%5D,+%5B2,+3,+%5B2,+2,+3,+%5B2,+2,+2,+2,+2,+3%5D,+%5B2,+%5B2,+5,+7,+7%5D%5D,+%5B2,+2,+%5B2,+5%5D,+%5B2,+2,+%5B2,+2,+3%5D%5D%5D%5D%5D%5D+%0A&m=2) recursion's a bit clunky here, but thankfully it works. [Answer] # [Ruby](https://www.ruby-lang.org/), 41 bytes ``` f=->n{n.map{|x|x*0==0?x:f[x]+1}.reduce:*} ``` [Try it online!](https://tio.run/##dVPLasMwELz7Kwy9pW3Qaq1XwO2HGB36SG4NIRBwSfLtrqy3FBVkjJbdmd3Z0fny@bssh/H17Xg9bn8@TtfbfJs3ZBzJ@7w7TLN@hvv2vP@@fO13m/ty6g/TRF96d5jW/VM/kM6GfRy1jQKmKNrUNYrgouhuXcDDkGSiisRw@NZqS8UTqEcEKNiFK4jHoApfrAYUXTlAzPGTSFIllHAeh9GiQc/iLugEcLOqoRqwZqauO5MsifSoLKYJnRSIKqzJXAIrkn1BvpmszB0dqiUdFPr6oi3bu7uJAjfnRimoUK46qcMSJdrbVGkPVAT1i5ESudaPqwsIKwSjUoB6XKAI4jRkSFg67g6RN7aCCYHlbYUBJFGcycJqNNcum7fdQDZoAk@esaW1JmnvrTWjjitFBoCEmx83phtUNIfISabKGGmz@V2UpivaaA2XNGQFU3ozUUJAQGb6ZIgkOLDxNjIfYun@mqDxpLB0vsiEpf85JVOSKsrQvBCmADgH2S1/ "Ruby – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 34 bytes ``` ~(`, $* ^. .+¶$$.( \[ $$.(_ ] $*) ``` [Try it online!](https://tio.run/##dVIxDsIwDNzzig5FKlBVolaUJ/CIYCgDAwsDYuZZPICPhTRxYyekUqrWjX13Pvt5e90f14PbdMfJvbupb1S7U@dBDfvvp22HTp2smt8Xhf5m65wd@yYejcpSBEjfMP/23@CfGEJM9MHy@ATK1sgQJl6m4@tMSJQ/R4lXq0OmIowYQNAoRZW4Y@BTVqcrg6x50c0JlCTtEKnxYKzICIOSGJkMiRm4Jc2wECIrncnEMQHiv5VUU9hplsYq7XD1v2/ANVpSs6xELHBJQ51EyGc4nl0oLTvludRGAohpYEaC2WJY7L2MTT78jK7WBLujM6a0mLi2f2IjIN@2EqiytpBvnRFGjWvTJWd@ "Retina – Try It Online") Link includes test cases. Explanation: ``` , $* ``` Change all separators into multiplication operators. ``` ^. .+¶$$.( ``` Change the opening `[` into code to replace the input with the product of the values. ``` \[ $$.(_ ``` Change the remaining `[`s into code to increment the product of the values. ``` ] $*) ``` Change the `]`s into code to terminate the product expressions. ``` ~(` ``` Evaluate the resulting program on the original input. For example, the input `[2, 2, 2, 7, [2, 2, 2, 2]]` is transformed into the following Retina program: ``` .+ $.(2*2*2*7*$.(_2*2*2*2*)) ``` The `2*2*2*2*` evaluates to `________________`, so the `$.(_)` results in `17`, and the outer multiplication then produces the final result of 952. [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ËɪßD)ÄÃ× ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=y8mq30QpxMPX&input=WzIsIDMsIDMsIFsyLCAyLCAyLCAzLCAzXSwgWzIsIDMsIFsyLCBbMiwgNV1dXSwgWzIsIDMsIFsyLCAyLCAzLCBbMiwgMiwgMiwgMiwgMiwgM10sIFsyLCBbMiwgNSwgNywgN11dLCBbMiwgMiwgWzIsIDVdLCBbMiwgMiwgWzIsIDIsIDNdXV1dXV0) or [test 2-25](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=y8mq30QpxMPX&input=WwpbMl0KWzNdClsyLCAyXQpbNV0KWzIsIDNdCls3XQpbMiwgMiwgMl0KWzMsIDNdClsyLCA1XQpbWzIsIDVdXQpbMiwgMiwgM10KW1syLCAyLCAzXV0KWzIsIDddClszLCA1XQpbMiwgMiwgMiwgMl0KW1syLCAyLCAyLCAyXV0KWzIsIDMsIDNdCltbMiwgMywgM11dClsyLCAyLCA1XQpbMywgN10KWzIsIFsyLCA1XV0KW1syLCBbMiwgNV1dXQpbMiwgMiwgMiwgM10KWzUsIDVdCl0tbVI) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=y8mq30QpxMPX&input=WwpbMiwgMiwgMiwgNV0KW1syLCAyLCAzXV0KW1syLCAzLCA1XV0KWzNdClsyLCAzLCAzLCA1XQpbMiwgWzIsIFsyLCA1XV1dCltbMiwgNV1dCltbMiwgMiwgNywgWzIsIDIsIDIsIDIsIDMsIDddXV0KWzIsIDIsIDIsIDIsIDIsIDMsIDVdClsyLCAyLCAyLCA3LCBbMiwgMiwgMiwgMl1dClsyLCBbMiwgMiwgMywgNywgWzIsIDMsIDNdXV0KWzIsIDMsIDMsIFsyLCAyLCAyLCAyLCAyLCAyLCA3XV0KWzUsIFsyLCAyLCA3XSwgWzIsIFsyLCBbMiwgNV1dXV0KWzUsIFsyLCBbMiwgMiwgWzIsIDIsIDIsIDVdLCBbMiwgWzIsIDUsIDUsIDVdXV1dXQpbMywgMywgWzIsIDIsIDMsIDNdLCBbMiwgNywgWzIsIFsyLCAyLCAyLCA1XV1dXQpbNywgWzIsIDIsIDUsIDVdLCBbMiwgMywgNSwgWzIsIDMsIDddXV0KW1syLCBbMiwgWzIsIDUsIFsyLCAyLCAzXV0sIFsyLCAyLCAyLCAyLCAzLCAzLCA3XV1dXQpbMiwgMiwgMiwgMiwgNywgWzIsIDVdLCBbMiwgMiwgWzIsIDIsIDIsIDIsIDIsIDIsIDNdXV0KWzIsIDMsIDMsIFsyLCAzLCA1XSwgWzIsIDUsIDUsIFsyLCAyLCA3XV1dCltbMiwgMiwgMiwgMywgWzIsIDIsIFsyLCAzLCA3XV1dLCBbMiwgMiwgMiwgMiwgMiwgMiwgMywgWzIsIDIsIDNdLCBbMiwgMiwgNywgWzIsIDMsIDMsIDddXSwgWzIsIDUsIFsyLCAyLCAyLCBbMiwgNV1dLCBbMiwgWzIsIDIsIFsyLCAyLCAzXV1dXV1dCls1LCA3LCA3LCBbMiwgMywgWzIsIDVdLCBbMiwgWzIsIDIsIDIsIDVdXV0sIFsyLCAyLCAyLCA3LCBbMiwgWzIsIFsyLCAyLCAyLCBbMiwgNV1dXV0sIFsyLCAyLCAyLCAyLCAyLCAzLCAzLCBbMiwgNSwgWzIsIDMsIFsyLCAyLCAyLCAyXV1dXV1dClsyLCAzLCAzLCBbMiwgMiwgMiwgMywgM10sIFsyLCAzLCBbMiwgWzIsIDVdXV0sIFsyLCAzLCBbMiwgMiwgMywgWzIsIDIsIDIsIDIsIDIsIDNdLCBbMiwgWzIsIDUsIDcsIDddXSwgWzIsIDIsIFsyLCA1XSwgWzIsIDIsIFsyLCAyLCAzXV1dXV1dCl0tbVI) Takes advantage of the fact that the sub-arrays are never singletons. ``` ËɪßD)ÄÃ× :Implicit input of array Ë :Map each D É : Subtract 1 (resulting in NaN if it's an array) ª : Logical OR with ßD : A recursive call with argument D ) : Group that together Ä : Add 1 to the result à :End map × :Reduce by multiplication ``` [Answer] # [R](https://www.r-project.org/), ~~65~~ 57 bytes ``` r=function(l,z=0)`if`(is.list(l),prod(sapply(l,r,1))+z,l) ``` [Try it online!](https://tio.run/##jVTLasMwELz7Kwy9WNQtktZ6HdJvSUkbCJgk2M6h@fnU9UuvlRoQmCij2dmd3e0e3ffhcu6H7nYYdo9ud7ydD8Ppcq7a@r6jZH867qtT/96e@qFqSX3tLl9V/3m9tj8joqsZIa/3uiUuTTWBeV3ORxBSvpRvH2VDiwjlQIGsQAZpIEyECxBYDITtzwLTBCvFDDIURYXfv5BrFjItzipjLJurstTbGWUpG8Y0oIp0UbcntrqaZvBxQBtJ8GwNFmn2AmavNg9Mk6k0JpvPmc7vNdVIfOG9VCS2xLNm4ZKaiSyXwxk2KcI8H@IE0LwxgISIcp1qZG8UKiFQD1pxZWJy3zvhi4Xpxvnl9hDjCuuiZCn9FAjBu3QNskQRXCtm8r2qXL8yNtgwxO1PAPlEi4FPLsKEnMpoaqTQ2RHloaVBjdPSgyr6GvwxmqhSBvhN/l8TA3EbFQRjQOX4keN8NgadChXqwTyK@zW8U@nhjLJI1c13UqCq7OJyjWTAQIypCgCKjWZiEwUDCvhiSelILDbAt4gKbObPTIPvJzdcwLh9hGFMSqaL4vEL "R – Try It Online") Recursively adds 1 to the product of all list elements. This would end-up one-too-many, so we skip adding 1 for the outermost loop. [Answer] # MMIX, 56 bytes (14 instrs) ``` typedef union _rpe { struct { uint64_t flag : 1; // must be 1 uint64_t val : 63; }; union _rpe *list; } rpe; uint64_t __mmixware rpd(rpe encoded); ``` Lists terminate on a `union _rpe` that isn't a list (`flag` is on) whose `val` is 0. (MMIX pointers must be positive for user programs, or a trap occurs.) ``` 00000000: 48000003 ec008000 f8010000 fe010004 H¡¡¤ġ¡⁰¡ẏ¢¡¡“¢¡¥ 00000010: e3020001 8f040000 e7000008 f303fff9 ẉ£¡¢Ɓ¥¡¡ḃ¡¡®ṙ¤”ż 00000020: 42030003 1a020203 f1fffffb f6040001 B¤¡¤ȷ££¤ȯ””»ẇ¥¡¢ 00000030: 23000201 f8010000 #¡£¢ẏ¢¡¡ ``` ``` rpd BNN $0,0F // if(encoded.flag) ANDNH $0,#8000 POP 1,0 // return encoded.val; 0H GET $1,rJ SET $2,1 // uint64_t i = 1; 0H LDOU $4,$0 // loop: rpe n = *encoded.list; INCL $0,8 // encoded++; PUSHJ $3,rpd // uint64_t j = rpd(n); BZ $3,0F // if(!j) goto end; MULU $2,$2,$3 // i *= j; JMP 0B // goto loop; 0H PUT rJ,$1 ADDU $0,$2,1 POP 1,0 // return i + 1; ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` FS≡ι[⊞υ¹]¿⊖Lυ⊞υ×⊕⊟υ⊟υIυ¿Σι⊞υ×⊟υΣι ``` [Try it online!](https://tio.run/##XU49C8IwEN39FYdTAnHQIoIddREcCnULHUK82kD6QZPoIP72GJtqi@GGvHfv42QletkK7X3Z9kBOTedsbnvV3AilYB7KygqIovBcSGEQlny5h8yZijgGa5qObBFYVQI5ouyxxsbilZyxudmgoyHo67ioGk1omVRZ230kDMYPTQF1iMzCDZYchLEfNl1csRRO21iTuzrc9B8bExiM22B6ec853zCIkzAYAY9oVxTFj5vPpEwmwe7ni9YIt/OAgfhuZl1DUHx@dddv "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FS≡ι ``` Loop over and switch on the input characters. ``` [⊞υ¹ ``` For `[` push a `1` to the predefined empty list. ``` ]¿⊖Lυ ``` For `]` if the list has more than one element, then... ``` ⊞υ×⊕⊟υ⊟υ ``` ... increment the top element and multiply the second element by it, otherwise... ``` Iυ ``` ... print the result. ``` ¿Σι⊞υ×⊟υΣι ``` Otherwise for digits multiply the top element by the value of the digits. [Answer] # [Gaia](https://github.com/splcurran/Gaia), ~~14~~ 12 bytes Defines a function which takes a nested list and returns an integer. ``` ⟨::C⟨←)⟩¿⟩¦Π ``` [Try it online!](https://tio.run/##bVI7jgIxDL1KWgqaWFEkChqOEbmgWCE6uAEVNfSs2Aqxp1hpD8AhcpEhjj9JAGUmk9jPz/bzbNbb9TTl632xWJU9H0@zfP39/6Pt9viZvsi1y4eLmy9dPnzv8vG8r84pJe9oBXR8BOQTFFM5QXnpAhXh5SkuRgXUuOiEidCx@vXuLXoEojLWEMkjkZSxI/BE6VJgW3wpRT3V2TXEAFrIKGOlRHSKFmZMUl8QhlI6f6L2rLRNrtYmwzpT5BqH0gQ8dqoSBWdNmrZey06fxDUviFmlZM2sVJVrVAoQVcGokamTT5UZxtdcbQJ9OWBpoZs2vs9W5wDDj9U6GmjbRKO25t/klX7wCQ "Gaia – Try It Online") ``` ⟨ ⟩¦ # map over each element in the input :: # two copies of the TOS C # compare for two ints (0), count occurences for two lists (1) ⟨ ⟩¿ # if the TOS is truthy: ←) # recursively call the function and add 1 Π # after the map: take the product ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 37 bytes ``` f(a)=vecprod([if(#b',f(b)+1,b)|b<-a]) ``` [Try it online!](https://tio.run/##dVTbaoQwEP0V2T40Un1oBslL2x8J8xDbWoTSBlkKhf13NzExM4kRouxkzpwzN9eaZe6/7LpOwrSvf5/vdvn9EHqexMP42E1ibJ@eu7G9jS@9wXY11n7/C9P0b41d5p@r@3nxxqXx8W3XaC27JpwByQTcDfAOb4B/hQuIYEmPw@wRAzIiFdzpuFAVoPxWZpy1SGR6kYbSSYQht5Jabprufkg@VUmfISKq6M2ODQdjSKa5ZRMslVExDSpsIGLYLJ11KEuQJA7dgxRUetReXaUkCq@0j01j4OIss6TNmE@nmyGBAIoLK8SyWBpPbTCASHNTnE0XM6MJVFYsB/F1OJYAWYZQ7CiebiJbDDh8NbJYoYNuvn2KtUqeTTj2xv0H3AE "Pari/GP – Try It Online") ]
[Question] [ [Inspiration.](https://chat.stackexchange.com/transcript/message/42442315#42442315) Given (by any means): * A two-argument (or single argument consisting of a two-element list) [black box function](https://codegolf.meta.stackexchange.com/a/13706/24877), `f: ℤ+ × ℤ+ → ℤ+` (input and output are 1, 2, 3,…) * A strictly positive integer matrix with at least two rows and two columns return the matrix's *function trace*. What is a *function trace*? A normal matrix trace is the sum of the major diagonal (top-left to bottom-right) of a matrix: `[[1,2,3],[4,5,6],[7,8,9]]` → `[1,5,9]` → `1+5+9` → `15` But instead of summing, we want to apply `f` along the diagonal: `[[1,2,3],[4,5,6],[7,8,9]]` → `[1,5,9]` → `f(f(1,5),9)` or `f(1,f(5,9))` Please state whether you use left-to-right or right-to-left. The given matrix and all intermediate values will be strictly positive integers within your language's integer domain. The matrix may be non-square. ### Examples `f(x,y) = xy`, `[[1,2,3],[4,5,6],[7,8,9]]` → `1×5×9` → `45` `f(x,y) = xy`, `[[1,2,3],[4,5,6],[7,8,9]]` → `159` → `1` `f(x,y) = x-y`, `[[4,5,6],[1,2,3]]` → `4-2` → `2` `f(x,y) = (x+y)⁄2`, `[[2,3,4],[5,6,7],[8,9,10]]` → `5` or `7` `f(x,y) = x+2y`, `[[1,2,3],[4,5,6],[7,8,9]]` → `47` or `29` `f(x,y) = max(x,y)`, `[[1,2,3],[4,5,6],[7,8,9]]` → `max(1,5,9)` → `9` `f(x,y) = 2x`, `[[1,2,3],[4,5,6],[7,8,9]]` → `2` or `4` `f(x,y) = lcm(x,y)`, `[[2,2,2],[2,2,3],[2,3,3],[4,4,4]]` → `lcm(2,2,3)` → `6` [Reference implementation.](https://tio.run/##nZJBa9swFMfv@hTvlq1RYFbtZqnPG3SM7tDSS/BBOLYrcORiu1tD2WWDNg11KYOS0y677AOUMug130RfJHuS7MQb6SU2QQ@////3/lLEz9LeaMLTLFku1fT6M0/PI3V1H0s4znkYwZiXubjw8@xL4YdZWvgjwZOPkUzKU1/IUeELP43i8kCXujjhqVmP0CYTPxfJqW2aSndNUbeji7OcgIbjTHXzy06D5lHVTyh5mk4I6NlWo2bf/5WtVBCLvCgJrCOiw8BvZ9pvlGMhxfh8TECn18Tqca3vOTUPmyKMCkJg/32Wg4D9A2kcxIxstox@AWL9DfeHn2y8oZp9a3TBWmJ3bgY/1JbWPgrTFfGEWMfq/NDQwLpOq/f/xJUhaInaMxtXPUD/AzXbqmgsactkUoWZDHkZSfxZV3NNVHWnAbDh0b5I61amTSGRYVh4zu/kCI@a4CVcLjuXqnpezFX19LVTX0R19/Dh6NMhdIZDhzK6G9ChSz26h2ufvqWDIOiYmerqBziLubeYD0ztesTQdraGeRbkWE7vBU7jt7yW3@0xszL0v0JAFwGvF3/YJghaqYsQRNE@rhiFOm/aNA/wOvZtlC7b/ojcvgaxgSWp2@m2IE0wOZ63sjMdw61TTH@/kIIhhqGd1Th9ThaLbxu39xc "APL (Dyalog Unicode) – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~40~~ 30 bytes ``` function(m,F)Reduce(F,diag(m)) ``` [Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP08jV8dNMyg1pTQ5VcNNJyUzMV0jV1Pzf5pGbmJJUWaFhpGVoYGOMRAmVRbll9uGaOrAdVboVGpqVGhXauobaXLBNSRrmFiZ6RhaGWvq5IF0GCF0JugmaP4HAA "R – Try It Online") [Verify the test cases.](https://tio.run/##jY9BC4JAFITv/grxtE@flLsStOQp8FSX6BzoqiG0K2xKu79@06DQi8Qwp/mY90a7xj/EvmsGJfq2U0RiDpe6GkRNcqza4k4kgGuILHrdGpLwPbJRpdXdK7sCBmEA3kp8m8eCpHyHCWeAagLoDIznIOXJdln0e9CgBWIiCxu6dnjBm4iGdo2Whfm7jIZmMYniV@xjhumkcaLoHtmsRQ2yrPWT89PxDJ57Aw "R – Try It Online") Traverses down the diagonal, so left-to-right in this case. For arithmetic operators, you can use `"+"` or backticks around the operators (`+,*,-,%/%,^,%%`) Pretty straightforward: `Reduce` is R's equivalent to a `fold`, and ~~the diagonal of a matrix is those elements `a_ij` where `i==j`, i.e., where the `row` and `col`umn indices are the same.~~ `diag` has the appropriate behavior for non-square matrices. [Answer] # [Haskell](https://www.haskell.org/), 39 bytes Thanks @Laikoni for helping me fix the previously invalid solution! ``` f!m=foldl1 f[h|h:_<-zipWith drop[0..]m] ``` Associates to the left, [try it online!](https://tio.run/##Rc69TsMwFAXgPU9xanWwiVPRQvmpki6sMDEwuBZ16phYJHaUOCAh3j04DO10rr57dXRrNXxWTTNNZtEWxje6WcOI@rfevefZj@3ebKihe9@J69VKtnJqlXUooH0CWNeNAXmGvlIa@XKPjyo8eRcqF4a4b1X3AnqgxnHDsj3i9Wvonx2WMA5pCrIDmXOo/TeoWfwXMgYzulOw3g1Jch5RxEYBSpTWhIOmDCxKnMgwlrNkF2nHZpari2j7FeWgUCJ@QhVSlAzHyEds5iM5CbHmG34jubjlW34X854/8Ecp/wA "Haskell – Try It Online") (replace `foldl1` by `foldr1` for right-associative) [Answer] # [Mathematica](https://www.wolfram.com/mathematica/), 16 bytes *-1 byte thanks to Martin Ender.* ``` #~Tr~Fold[g]@*0& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X7kupKjOLT8nJTo91kHLQO1/uoKtgrKCloKykYIaF1dAUWZeSXSagoNCdbWhjoKRjoJxrY5CtYmOgqmOghmIaa6jYKGjYFlbG/sfAA "Wolfram Language (Mathematica) – Try It Online") ## Alternate solution, 17 bytes ``` Fold[g]@*Diagonal ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y0/JyU6PdZByyUzMT0/LzHnf7qCrYKygpaCspGCGhdXQFFmXkl0WnR1taGOgpGOgnGtjkK1iY6CqY6CGYhprqNgoaNgWVsbG/sfAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~61~~ ~~57~~ 53 bytes ``` function m=g(f,m)for i=diag(m)'(2:end)m=f(m(1),i);end ``` [Try it online!](https://tio.run/##jZDRTsMgFIav16c4N4uwnalgu9otTXwCr7xbZkI6mCSDxrXT7gV8AG/2QHsTX6RCqxPvGkIOBL6Pn1MWtXiTbasOtqh1acHkW6LQUFXuQecbLbbE0CvCF9JuqMkVMYRR1HTp9q2bMIbHsoa9fD3ovdyAVlC/SLj43kUFRWlroa0/tSAsXBtQeiejaPwkq7oQlawWUaTyB9LgkUIzOeJo5GPAasWQ4916uYoxwbmrKd5jtl7TMXx9fAI7n5LzKevWcRI6ngc4oJcAS3oDCwWzQPAL9qILGM94V3nAkWZ6pDccf1EHYOxQJ8DUVfcystvuAx2bgGt0Gj485cP@30dIPc@zQGBE0y1woMLfZ@4oo902VPFJMzgJ90HiAN4V5n8O7gTcgfxH5FvTC93466rnuit9nnnUfgM "Octave – Try It Online") Defines a function `g` which takes a function handle `f` and matrix `m`. On the first iteration, `m(1)` returns the top-left matrix element; after that, it just returns `m`. [Answer] # [Clean](https://clean.cs.ru.nl), 56 bytes ``` t[[h:_]]f=h t[[h]:_]f=h t[[h:_]:r]f=f h(t[t\\[_:t]<-r]f) ``` [Try it online!](https://tio.run/##NYw7D4IwFIV3fkXHVi@JxTeRTQcTN8ZSTcNDmtBC4Gr0z1uvg8PJ@b4znLKrjQ@urx5dzZyxPqBSbXrTusna6Mea5M@E6UjWsJajwqJQtxT1IaZNBOuGfkSWY3XyzyhHQ5LR58A4MqUkJLDUoFawhg31Fnawp5YLkBJkorVgis8F8Jgyo1wFOOvBmZcOn7LpzH0K8fkSjm9vnC2nLw "Clean – Try It Online") Folds from right-to-left. `[t\\[_:t]<-r]` is the same as `map tl r`, but does not need `import StdEnv`. [Answer] # [Haskell](https://www.haskell.org/), ~~47~~ ~~45~~ 42 bytes ``` f%((h:t):r)|[]<-t*>r=h|x<-tail<$>r=f h$f%x ``` [Try it online!](https://tio.run/##FcpNDsIgEEDhvaeYhU1mdGqk/jfFG3gCggkLCcTSNMiiC@6OdPHybZ4zv@9nHEuxDaLrE/WRcpJS6ZzjinR5Gdpk/Dhsn1FacGibhUoACUoJ7vikWZ35wtfqje/8qIojC8Gi03pj1xH3xLirtbU3cfATB7PoTTB@qkMw8wtwjn5KcABsAhHY8gc "Haskell – Try It Online") Defines a function `(%)` which takes a function and a matrix as a list of lists as input. The function is folds from right-to-left: ``` f % [[1,2,3], -> f 1 ( f % [[5,6], -> f 1 ( f 5 ( f % [[9]] ) ) -> f 1 ( f 5 ( f 9 ) ) ) [4,5,6], [8,9]] ) [7,8,9]] f % ((h:t):r) -- (h:t) is the first row and r the remaining rows | [] <- t *> r = h -- a shorter way of checking wether t==[] or r==[] | x<-tail<$>r = f h $ f%x -- apply f to h and the result of recursively calling (%) on -- the remaining matrix with the first column removed ``` *Edit: -2 bytes thanks to [BMO](https://codegolf.stackexchange.com/users/48198/bmo) and -3 bytes thanks to [Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb)!* [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 bytes ([Adám's SBCS](https://github.com/abrudz/SBCS)) ``` ⎕/1 1⍉⎕ ``` [Try it online!](https://tio.run/##hZAxTsMwFIb3nOLfSElLlaYgMSIqJCQGBi7gOqa15NghdhDcoFSEDZhY6EB3kDhAb@KLlNdElaCiMDw9y@/7//fbLFed9JYpM1ouffWCY5MKcKZ3HIYCuWJcpBiLQiAtBZyBE3ysJWcKhbCukNxJo@1eo17VSakU8sKMCpYhtOUwk9YS025smIXUThSMhNe0ymQZ06ltBbX@4bEbI/bVHZ2CteOpzkuHGGHGaOFNgyZIfPXhq/fDDa6HcFA/CEfnZ7gsdZ2wDSEdBYBjXDqYAoPOetYYRkHdLuhV9AFWWIRSgzSwLBOkSElN6Vc3VyVRtWsCJTWxgvEx@fzI/y3i4nn7bHdj5KdPvfX0IOj8KoyjWtpbfPpqHm339tNZ5Kevq/oDup/85zDbAPo1EO4jbhOVtLp96vM@3VH0wE/evgA "APL (Dyalog Unicode) – Try It Online") -3 thanks to a suggestion to convert this to a full program by [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m). Right-to-left. [Answer] # [Haskell](https://www.haskell.org/), 44 bytes ``` f#m=foldl1 f$zipWith(!!)m[0..length(m!!0)-1] ``` [Try it online!](https://tio.run/##Fcq9DoMgGIXh3as4RAdpvho@@z94HR0Ig0mlEoGa1i69eQrb8@acefwsk/cp2ToM9uUfnmGbn1vvbptbIWTQquv8FJ85gxBK7tmk8PUY0O5kVYXRxez17eKGBmWpoTUTesLBEPSRcCKcCy@EK@FWyIrA@cW9MekP "Haskell – Try It Online") [Answer] # [Standard ML (MLton)](http://www.mlton.org/), 59 bytes ``` fun t[h::_]f=h|t([h]::_)f=h|t((h::_)::r)f=f(h,t(map tl r)f) ``` [Try it online!](https://tio.run/##LY07D8IwDIR3foXVKQEXkfKOVHZmxhCqLqWVmodagzrw34sjGKzTdz6fR9fnrqfg57l5eSDTal3Zpmw/JExrGeQPRFpIrQfmRrRIwtURqAc25Pyue3A1Dd0EJRijsMCtRbPDPR5Yj3jCM6vaoFKoCmsX6aLicGoRceg8QQDReBjLy/jI7j6TbFw9rSncuNg/Gen/RIIJcYUh5jxLTCnX@Z/Wk52/ "Standard ML (MLton) – Try It Online") Folds from right-to-left. ### Ungolfed: ``` fun trace [h::_] f = h | trace ([h]::_) f = h | trace ((h::_)::r) f = f (h, trace (map tl r) f) ``` [Try it online!](https://tio.run/##bY1PC8IwDMXvforgqdVMrP8dzLtnj7VKEesGazu2Kjv43We66c1AeCS/95LGloktg3ddZ54OQq1vd5B5ml4V9GUgg3wE8P4yJnNFlP9lLAZ5mta8ZwZYjj9mdQWhhIh499IlWB3qoiWblAIXuFQoV7jGDekWd7gnFXMUAsVCqVFMXMkcz7CqLlwAD8w4aLJDcxmf3ZjT4ujCLPgTHXYPGofXwyMO0ldT9FVCPcHotIUbVLeq@wA "Standard ML (MLton) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes Thanks @Zgarb for fixing my submission! ``` Ḟ₁§z!Tŀ ``` Associates to the left, [Try it online!](https://tio.run/##yygtzv7//@GOeY@aGg8tr1IMOdrwP0H3///oaEMdIx3jWJ1oEx1THTMgba5joWMZGwsA "Husk – Try It Online") (for a right-associative version simply replace `Ḟ` by `F`) ### Explanation Unfortunately there's no easy way to get the diagonal of a matrix, so most the bytes are for that: ``` Ḟ₁§z!Tŀ -- function ₁ is the function and matrix A implicit, example: § -- fork A T -- | transpose A: [[1,4,7],[2,5,8],[3,6,9]] ŀ -- | enumerate A: [1,2,3] z! -- and zipWith index: [1,5,9] Ḟ₁ -- right fold function ``` [Answer] # [Python 2](https://docs.python.org/2/), 61 bytes ``` lambda f,m:reduce(f,[l[i]for i,l in enumerate(m)if len(l)>i]) ``` [Try it online!](https://tio.run/##bcxNDsIgGIThvadgCWZMav1vohdBFmg/KgnQhtCknB5tbFy5mN3zzpDTqw916a734rR/tJoZ@CZSOz6JG0gnrTJ9ZBaO2cAojJ6iTsS9sIY5CtyJm1WiDNGGxDq@vEzIzbTJkHKPA44KcosaO6XE6p9cz/Ir8CtOOOMyl1WFZZ@@vAE "Python 2 – Try It Online") This works left-to-right. [Answer] ## JavaScript (ES6), ~~58~~ 56 bytes ``` g=(f,a,r=a[i=0][0],e=a[++i]&&a[i][i])=>e?g(f,a,f(r,e)):r ``` Folds left-to-right. Edit: Saved 2 bytes by using the fact that the array is strictly positive. Alternate solution, also 56 bytes: ``` (f,a,g=r=>(e=a[++i]&&a[i][i])?g(f(r,e)):r)=>g(a[i=0][0]) ``` [Answer] # JavaScript, 46 bytes ``` f=>a=>a.reduce((p,l,i)=>l[i]?f(p[0]|p,l[i]):p) ``` Thanks to @Shaggy, use bitwise or save one byte. That's magic. ``` g = f=>a=>a.reduce((p,l,i)=>l[i]?f(p[0]|p,l[i]):p) c=()=>o.value=g(eval(`(x,y)=>${f.value}`))(m.value.split(/\n/g).map(x=>x.trim().split(/\s+/).filter(v=>v.length).map(v=>+v)).filter(x=>x.length)) ``` ``` <p>a = <textarea id=m>1 2 3 4 5 6 7 8 9</textarea></p> <p>f = (x, y) => <input id=f type=text value="x + y" /></p> <p><button onclick=c()>Calc</button></p> <p>Result = <output id=o></output></p> ``` [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/attache), 14 bytes ``` Fold#/Diagonal ``` [Try it online!](https://tio.run/##pZDNCsIwEITvfYqAnnREG/8PSkURBAVPXkLU2KZaKC2UKIL47HVrLUjBS51AdmHzzWZXGaPci04X2g8iLeo@0mUcerX2IlDnOFJhKq2iZlwwYTFSfmc6NsG@JYQNjq6E6KGPAcUhRhhL@SYkyvj@P7xVxgsst/mBzW46UWft7FBg9Bg9wgjGkCL1hN35yXvZguLrKdSo8OuNuuOPoR@8cXiiMr6eb0rdOeGcMP6xyZaR29EpbCxKrG0SRIZNpsx3nJWXJcZNXw "Attache – Try It Online") Set to `f` and call as `f[function, array]`. ## Explanation This is a fork of two functions: `Fold` and `/Diagonal`. This, for arguments `f` and `a`, is equivalent to: ``` Fold[f, (/Diagonal)[f, a]] ``` `/`, when applied monadically to a function, returns a function that is applied to its last argument. So, this is equivalent to: ``` Fold[f, Diagonal[a]] ``` This folds the function `f` over the main diagonal of `a`. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 77 bytes ``` func z(F,M,r){for(e=1;e<M[1]&&e<M[2];)r=@F(r==""?M[1,1]:r,M[++e,e]) return r} ``` [Try it online!](https://tio.run/##bZNdb5swFIbv/Ss8qlVQHDXYXNWxWlVap12w60kVq1BKNlI@IgcKLMpvz3xscFLoDee1n@P3HMucpH07bZpyjXd5s3c70nsHhLFM60aWuPN7dEQaF1n5CV9YXmdFOuc3lu@qNpUz/tvyfVO80Cl3VQPeLR1zOtrPO6TnGkXSzfiqv@/vOttlW/2aptAbi/@sXy1t/2Z56vZfxFIvMa5Fz7XoRYe/4mHRiRrE8aIkH@3ydWHtso26jVBmY9qSX97zdizt6etgbB7ln/tEIiK9w6aSbioCnq6i5yC@voZIY@5J8fDkSiEc514BEsR3kkTPvp@SNPbQYC@Pp8dv33/8PKAoUKeF@tJYMHwFXljgsimwrNo9wWA6bKyrvCnKPYLK3PezldCHuQcbW7FUe9uVseKeChnZxsL335OcI/VRCQhFFMpRriIU1F6Z0Lt@wHG2WEztqLGjM7sA7BjYMa7ihd1y6I590h0zduyDHYpC8Am5itoH1sQ0CopaxUABphZTiylgpjGzmAFmRlkckrFcCHhQDBRCO5mVNXb0/AhHvbiRjnqMwOMj1uNjsJYTrKfTYC0B0zOG4areU/lCTY4eNshh5xw1Sb2hasym9kk3mCfdBNGBwGSNaGTq/zdQCWAhsCM6/Qc "AWK – Try It Online") I was curious if `AWK` could do functional programming at all. I think this counts. The "Matrix" is defined as a standard associative array, with extra fields `M[1]=#rows` and `M[2]=#columns`. The function name is passed in as a string which is evaluated via the `@F(...)` syntax. Evaluation is performed left to right. The `r` parameter is a placeholder to prevent overwriting an existing `r` variable and to avoid the need to reinitialize for each call. Typically extra space is added to designate such placeholders in `AWK`, but this is code golf, so every byte counts. :) The TIO link implements all the test cases. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 10 bytes Folds from right-to-left Saved 5 bytes using a new built-in as suggested by *Kevin Cruijssen* ``` Å\`[.g#I.V ``` **Explanation** Works the same as the old version, except that `Å\` is a new built-in for pushing the main diagonal. [Try it online!](https://tio.run/##yy9OTMpM/f//cGtMQrReurKnXtj//9HRhjpGOsaxOtEmOqY6ZkDaXMdCxzI2luvQdm0A "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##yy9OTMpM/W/hFvr/cGtMQrReunKEXtj/Wp3/WlzR0YY6RjrGsTrRJjqmOmZA2lzHQscyNpYrF4@cLlAOJgZRE8ulbQ0UBDJ1TICCQCkdcyANVK5jaACUPbRdG495jxpmVZ/bgUdBzKHt@LXrHdoPth4IgRJGUIUg50A0AGFsLAA) **Old Version** ``` ¬g£vyNè}[.g#I.V ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0Jr0Q4vLKv0Or6iN1ktX9tQL@/8/OtpQx0jHOFYn2kTHVMcMSJvrWOhYxsZyHdquDQA "05AB1E – Try It Online") or as a [Test suite](https://tio.run/##MzBNTDJM/V9jdHhLWWVC6P9Da9IPLS6r9Du8ojZaL105Qi/sf63O/@hoQx0jHeNYnWgTHVMdMyBtrmOhYxkby6XFhVsuFygHE4OoieXSBYoBWTomQDGgjI45kAaq1jE0AEpqW@Mx7dB2bTyyjxpmVZ/bgUdBzKHtYKuBEChqBFUFcgpENRBCjNE7tB8A) **Explanation** ``` ¬ # get the head of the input (first row) g # get its length (number of columns) £ # take that many rows from input v # for each row_index, row (N,y) do: y # push the row Nè # get the nth element of the row } # end loop [.g# # loop until one value remain on the stack I.V # run the input function ``` [Answer] # Java 8, ~~88~~ ~~81~~ ~~70~~ 69 bytes ``` m->{try{for(int i=1;;m[0][0]=f(m[0][0],m[i][i++]));}finally{return;}} ``` Puts the result in the very first cell of the matrix instead of returning an integer (to save a byte). [Try it online.](https://tio.run/##7ZXfT4MwEMff91f0xQRchw5/i1MTn40P843w0HVFO6GQUiYN6d8@W8qmRqYvM8HEQArcHdf7fnIcC7REoywnbDF/WeEEFQW4R5TVAwDQrBAcYQEKgQTFwHofSSGMFwDKBIgds1bQrNK1dgA4ESVnoBrKoLGoZm2WvJwlOtdCb@uVgiZeXDIsaMa8u4wVZUr4lc4VRmF0DTCYrNLRdS24rOOMN1vRyTgI0vAw0uckdto7mIY0CulwGLluoGLKUJLI2pYRKLUyO5tSTCGDTRGtrmVG5yDVop2p4JQ9hRFyNwpNJfqal@IeaW8FJoCR17VnLXhjqsfQh0cKfrEfwxN42mE/g@fwwvJRFpbxGcjOBuftw5JwTuekfd4O/h39fot@DV952EMYk1w4H9S4NmgqC0FSLyuFl2sCImEfgyziNrTl8td4GK@rK3728uzVqaB0@4FnGwaLbfdtMepJW2h18LhDt6YBzzrsuing@PAX@kLPKPfA//9WPo1t/396fCLSDI4UVT0aHD0h4@9XfRko@ujQ7W/hZAZQNz997J5TgtOO5rGvGt8PP3NHHjzheZOhM4VxfptCXo1vqksTJmG19ztNrAZq9QY) Both folds `[[1,2,3],[4,5,6],[7,8,9]]` to `f(f(1,5),9)`. -7 bytes indirectly thanks to *@KamilDrakari* by using a similar trick as he did in [his C# answer](https://codegolf.stackexchange.com/a/154011/52210): instead of having a maximum boundary for the loop based on the rows/columns, simply try-catch the `ArrayIndexOutOfBoundsException`. -11 bytes replacing `catch(Exception e)` with `finally`. **Explanation:** ``` m->{ // Method with integer-matrix parameter and no return-type try{for(int i=1; // Start the index at 1 (0-based indexing) ;) // Loop indefinitely: m[0][0]= // Replace the value in the first cell with: f(m[0][0], // Call f with the current value of the first cell m[i][i++]));} // and the next diagonal cell as arguments finally{ // If an ArrayIndexOutOfBoundsException occurred we're done, return;}} // in which case we'll terminate the method ``` **Black box input format:** Assumes a named function `int f(int x,int y)` is present, which is allowed [according to this meta answer](https://codegolf.meta.stackexchange.com/a/13707/52210). I have an abstract class `Test` containing the default function `f(x,y)`, as well as the lambda above: ``` abstract class Test{ int f(int x,int y){ return x+y; } public java.util.function.Consumer<int[][]> c = m->{try{for(int i=1;;m[0][0]=f(m[0][0],m[i][i++]));}finally{return;}} ; } ``` For the test cases, I overwrite this function `f`. For example, the first test case is called like this: ``` int[][] inputMatrix = new int[][]{ new int[]{1,2,3}, new int[]{4,5,6}, new int[]{7,8,9} }; new Test(){ @Override int f(int x,int y){ return x*y; } }.c.accept(inputMatrix); System.out.println(inputMatrix[0][0]); ``` [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 86 bytes ``` T I =1 T =M<1,1> I I =I + 1 T =EVAL(F '(T,M<I,I>)') :S(I)F(RETURN) DEFINE('T(M,F)') ``` [Try it online!](https://tio.run/##PZDPC4MgFIDP@ld468m8lO1XVFCkIKw2TAe77jzWYf8/7Zlzh4Tv8wPf6/NensurXEkFA18dMazJKXGsGetc5C01wRi2Y9Gqe3cBzTJwYqyNMC3POKlmMFyDVc7bidOBDEqbSUHmYBQai/VvZj9CJ3p0lHTWsgaP7gGZFPKntme3ISIUCEUCiSAjFFtWJgjZPkHIDhHklh0ThOyUIGRnSq7e3Tzu5gC1CCOGnUBNA6cIBD@cE39BjzYtibfrFw "SNOBOL4 (CSNOBOL4) – Try It Online") Defines a function `T` (for `TRACE`) that takes an `ARRAY` and a string `F` that's the name of a function. Folds left-to-right. Using indirect reference (`$`) doesn't work with functions. So using `EVAL` and passing a string to the name seems to be the only way to get a black-box function in SNOBOL. Also, it's quite painful to define arrays; however, because invalid array references cause `FAILURE`, this works for non-square arrays -- if `I` is out-of-bounds in either dimension, the `F(RETURN)` forces the function to return. ### Edit: Possibly, based on [this meta post](https://codegolf.meta.stackexchange.com/a/13707/67312), I may assume that the black-box function `F` is defined under the name `F`, which would drop this to 75 bytes (remove use of `EVAL` and `,F` in the function definition). However, I prefer this version since it's closer to passing a reference to a function. [Answer] # C, 76 bytes ``` i,t;f(g,A,n,m)int*A,(*g)();{for(t=*A,i=m+1;--n*--m;t=g(t,*A))A+=i;return t;} ``` Left-to-right. [Try it online!](https://tio.run/##jZLNbqMwEMfveYpRo1Y2jNViPluLVhyaF9jeunuo0oAs1W6VUgmU5tWbDrAJpOyiYAbw378ZD@NZimK53M2fV7m2K1gwzUHbEvL5XDP6wGbG1WzBPL5gkswnC8hCsogsJkv4TmOpclZghhYNJycnQ@YUnHG1yV/XrExJ0KlxPSWEdYQwqkwLVqKTcZ65qVbrVfmxtlCq7SGdh/tfD0wjWATD4W1NYXN2dv78254h5OyiyRIha58tQ5nOmvTNk7aMzzYzoKsRMu/xD6Sw8VCijwGGGGGMCV5vVc/IExi/Y7rVlhyuBt3qD3/0roZQeMI20QlMfAKT7BPaD7@1hqdBZIu2dfYQfLp5r8iRQlN5rAQjJhwp0UiJR0qCELTKtjvB3GvaD6q2AaHen@XfJqmcWh1I@U@ymdiuEtR/wGxaKaiFUN2mzWXBSaFSw8C2D@tPJiAGCQRTJKvcmsMlyJ4PJyODC3L4e9EkfVvDHfncwMAjnvKQTtWTyX9LZ6htjoIfCqnAnFfw@UmvWoHrGn5UQUPRd1/L/OWpeN@JF/MN) [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 79 bytes ``` (load library (d D(q((M)(i(h M)(c(h(h M))(D(map t(t M))))( (q((F M)(foldl F(D M ``` The last line is an unnamed lambda function that takes a function and matrix and returns the matrix trace. The trace is left-associative (i.e. `f(f(1,5),9)`). [Try it online!](https://tio.run/##jY/LTsMwEEX3/Yq7Y6IuoKFQ2EfddZcfcBOHWPIjTRzqfH06zgMQEqirmfE5uuPxyg5adc04knaihFbnVrTDhkpkdCE6JaSoBpeC6qlJKCMjGnjyceI5ynmUj9GrnC41jpThNFLhjJHWI5OVshIyCNNoiaq3hVfOdvC18BCttA8eyvIo1y8kMVZ8foAuIAoYEtAjaIupTePmaIRtOvxUJs7dgtPwG4YJbSiH6XU60x1SPDPf4wWvXA94w/sckaNx1zusrj8vYSue9QV/HcJv2DNlBweuHIHd06p9X/PvMiPCPT9fj/9TGm8 "tinylisp – Try It Online") ### Ungolfed We define a helper function to compute the diagonal; then `generalized-trace` is merely a small wrapper around the library function `foldl`. ``` (load library) (def diagonal (lambda (matrix) (if (head matrix) (cons (head (head matrix)) (diagonal (map tail (tail matrix)))) nil))) (def generalized-trace (lambda (func matrix) (foldl func (diagonal matrix)))) ``` When computing the diagonal recursively, we check whether `(head matrix)` is truthy. If the matrix is out of rows, it will be the empty list (nil), and `head` of nil is nil--falsey. Or, if the matrix is out of columns, its first row (head) will be the empty list (nil)--falsey. Otherwise, there will be a nonempty first row, which is truthy. So, if the first row doesn't exist or is empty, we return nil. Otherwise, if there is a nonempty first row, we take `(head (head matrix))`--the first element of the first row--and `cons` (prepend) it to the result of the recursive call. The argument to the recursive call is `(map tail (tail matrix))`--that is, take all rows but the first, and take all but the first element of each row. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 42 bytes ``` f->a->fold(f,[a[i,i]|i<-[1..min(#a,#a~)]]) ``` [Try it online!](https://tio.run/##jZDRCsIwDEV/pbiX1qXq6nRKdT9SKhRlo7DNIj60IP76TCci@rIRCEnuySXEmZvltetrciR9xUvDy@raXGgFyigLVj/sgatssWhtRxMDiXkyrVlvnGsC9YSXxN1sd8dyFpsZqalXmWaYhWYMiFLUQ2BR9POAfQYC1jKHDWxlATvYa43TL3SaAvEIveUB/ZWpTwNbChyhBLlEDAqJLpCt/oxSMeWo1vihHifF3I9Dzbn92AkkhRQDH4@NWxg6PvkF "Pari/GP – Try It Online") [Answer] # [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~72~~ ~~69~~ 60 bytes ``` m=>{try{for(int i=1;;m[0][0]=f(m[0][0],m[i][i++]));}catch{}} ``` [Try it online!](https://tio.run/##vVNdT4MwFH0ev6KPMOo@cDpNB4kx8cklJj74QHiotWxNRllot0FIf/u8wFiGOn2aFFruxzkXbu5h6ooptt8oIRfotVCaJ8SSNOFqTRlH6zVblBZbUaWQzsCTlZbSVAuGnjaSzYTU@PAEKCZt7IFpkcoqGkZhFDRQ5KN94gelzooyTjMbokj4Y0KScBTB7cf24Q0noYhC4bqR4xDDqGbL0pg9sdab9xXQH6psU/GB5lRI2ymtLc1QQnUmGFdQSfJdGJUW@nI17mYfYw9fG9wYE3yDb1tjiu/wvTH4kvAOouH6AwEpeNIiAIynrQHl8Hh04Q/@f/hw2P19WC3GO2WrGnNCDcuYDpkhVsc@ji5qtyCMUAxeGJ1O5vcJsnNcOH6Q9wt8LlZNtjOnejl4SXe172xqfvULTe4WztA7j3Vtr/8Td116TvOzSK@f/9TtFUsQSz84WvKMf2tg76hZkNeIwDFDUzhcF9TX68XgrTsI0iVg15K3W0WC06m8j6lU6YoP3jKh@bOQnYxG/FWeseq1/wQ "C# (Visual C# Compiler) – Try It Online") `try/catch` allows the diagonal to be correctly reached by simply going along it and terminating when out of bounds. 3 bytes saved because, as pointed out by Kevin Cruijssen, [black-box functions can be assumed to exist under a specific name](https://codegolf.meta.stackexchange.com/a/13707/71434). 9 bytes saved by returning via [modifying an argument](https://codegolf.meta.stackexchange.com/a/4942/71434). Thus, the function is called by storing the desired function under the name `f`, calling `trace(matrix)`, and the result is stored in `matrix[0][0]`. Alternatively, if you really like verbosity, # [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~97 + 13 = 110~~ ~~78~~ 69 bytes ``` (int[][]m)=>{try{for(int i=1;;m[0][0]=f(m[0][0],m[i][i++]));}catch{}} ``` [Try it online!](https://tio.run/##vVPfb4IwEH6Wv6KPIPUXc3NL1WRZsqeZLNnDHggPXS3aRIqhVSGkf7s7QIxM3Z4cBy339b47uNzHVIcptt8oIRfoI1OaR8SSNOJqTRlH6zVb5BZbUaWQTgBJcktpqgVDrxvJxkJqfHimKCT12TPTIpbFqR/4wbSiogna2wcocibTXCdZHsZJgSExGRAS@f0A7kloH95w5IvAF64bOA4xjGq2zI3ZE2u9@VpBnUO5bSzmaEaFtJ3c2tIERVQngnEFJSXf@UFuoR9XBVfrAHv4zuDKGeJ7/FA7I/yIn4zBt6Q3GFWuPxgQgoc1A8h4VDtQDg/6N/7g/6f3es3fB6s53mm2ojEnqcGMaSQzxGr4xxlG9TL1AxQCCqPTiDyfIDvFGUxx2s7wtbNisp0Z1cvue7wrsauhaeeXNKmbOT3vOte1vfal3GXpGU2vMr12eqnbKxYhFs85WvKEnzWwddQsyKtPYBujEWyuC@prtUJAyw6CdAn4pfbtWpEAOgX6EksVr3j3MxGavwnZiKjEX8QZq7T9Nw "C# (Visual C# Compiler) – Try It Online") 32 bytes saved by using a predefined function, because not taking the function as a parameter allowed removing the `System` import and the long `Func` generic type. [Answer] # JavaScript, ~~61~~ ~~57~~ ~~56~~ ~~52~~ ~~50~~ ~~44~~ 42 bytes Reduces left to right. Assumes the function is assigned to variable `f`, as per [this meta post](https://codegolf.meta.stackexchange.com/a/13707/58974) brought to my attention by Mr. Xcoder & totallyhuman. Can't say as I agree with it as it directly contradicts our existing consensus that we may not assume input is assigned to a pre-defined variable, but I'll take the few bytes saving for now. ``` a=>a.map((y,z)=>x=(n=y[z])?z?f(x,n):n:x)|x ``` --- ## Test Cases ``` g= a=>a.map((y,z)=>x=(n=y[z])?z?f(x,n):n:x)|x o.innerHTML=[[`f(x,y) = xy`,[[1,2,3],[4,5,6],[7,8,9]],(x,y)=>x*y,45],[`f(x,y) = x<sup>y</sup>`,[[1,2,3],[4,5,6],[7,8,9]],(x,y)=>x**y,1],[`f(x,y) = x-y`,[[4,5,6],[1,2,3]],(x,y)=>x-y,2],[`f(x,y) = <sup>(x+y)</sup>⁄<sub>2</sub>`,[[2,3,4],[5,6,7],[8,9,10]],(x,y)=>(x+y)/2,7],[`f(x,y) = x+2y`,[[1,2,3],[4,5,6],[7,8,9]],(x,y)=>x+2*y,29],[`f(x,y) = max(x,y)`,[[1,2,3],[4,5,6],[7,8,9]],(x,y)=>Math.max(x,y),9],[`f(x,y) = 2x`,[[1,2,3],[4,5,6],[7,8,9]],(x,y)=>2*x,4],[`f(x,y) = lcm(x,y)`,[[2,2,2],[2,2,3],[2,3,3],[4,4,4]],(x,y)=>-~[...Array(x*y).keys()].find(z=>!(++z%x|z%y)),6]].map(([a,b,c,d],e)=>`Test #${++e}: ${a}\nMatrix: ${JSON.stringify(b)}\nFunction: ${f=c}\nResult: ${g(b)}\nExpected: ${d}`).join`\n\n` ``` ``` <pre id=o></pre> ``` [Answer] # APL NARS, 20 bytes, 10 chars ``` {⍺⍺/1 1⍉⍵} ``` test: ``` f←{⍺⍺/1 1⍉⍵} ⎕←q←3 3⍴⍳10 1 2 3 4 5 6 7 8 9 ×f q 45 *f q 1 {⍺+2×⍵}f q 47 ⌈f q 9 {2×⍺+0×⍵}f q 2 -f ⊃(4 5 6)(1 2 3) 2 {(⍺+⍵)÷2}f ⊃(2 3 4)(5 6 7)(8 9 10) 5 ∧f ⊃(2 2 2)(2 2 3)(2 3 3)(4 4 4) 6 ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~55~~ 53 bytes ``` ->f,m,n=m[i=0][0]{(k=m[i+=1]&.[]i)?(n=f[n,k];redo):n} ``` [Try it online!](https://tio.run/##ndFRT8IwEAfwdz9FUxKzstvc6sZEM/wg5z2gAiG4YSYkbZZ99nl1gJD0Ae0lvfTll/9dm/2r7VdlH82WUEFdVrguE8KE2mDjHmGZ0m2MtFbPQV0usYYNPTWL9616rLv@c7/7EnLUrlBEMwO2NWPbgRgOYgoa7gkwgxwm3At4gCmRoE6K45EvuyDLlbzxWL/Y9VbqpaLzWEdiIC@Jc0r7qMCEVt3pHw6RAciYYhAK7pwJ0uTSdFQuto0ovNFCfRrzDxsrHKinPhH5oriaG1avF72UHpt/fKd22TLvsPHHWyXsaXlc7OiD65Y5@FwH13kTJftv "Ruby – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes Left-to-right. ``` ŒDḢç/ ``` [Try it online!](https://tio.run/##y0rNyan8f3hZzv@jk1we7lh0eLn@////o6ONdIAwVgdMG4NpYzBtogOEsbEA "Jelly – Try It Online") **Disclaimer:** I do not know if this an acceptable input method for black-box functions. This assumes that the function is implemented in the link above, and is thus "named" (that is, it's callable with) `ç`, but otherwise I have no way to assign it to `ç`. If anyone has more experience with Jelly + black box functions, I would appreciate thoughts. After spending some time in chat, we [figured](https://chat.stackexchange.com/transcript/message/42464622#42464622) that using `ç` might indeed be valid. [Answer] ## Clojure, 30 bytes ``` #(reduce %2(map nth %(range))) ``` Reduces "from the left". [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` F₁►L∂↔ ``` [Try it online!](https://tio.run/##yygtzv7/3@1RU@Ojabt8HnU0PWqb8l/fSPv//@hoIx1jHZNYnWhTHTMdcyBtoWOpY2gQGwsA "Husk – Try It Online") takes function in the footer. Folds from the left. ]
[Question] [ Consider a **permutation** of the integers `1`, ..., `n`, such as this one for `n = 6`: ``` [5,2,4,3,6,1] ``` If you view the permutation as a mapping from `[1,2,3,4,5,6]` to `[5,2,4,3,6,1]`, the permutation can be decomponsed into disjoint **cycles**. A cycle is a subset of elements that map to each other. For example, `1` gets mapped to `5`, which gets mapped to `6`, which gets mapped back to `1`. So one cycle is `[1,5,6]`. The other cycles are `[2]` and `[3,4]`. Thus the **number of cycles** for this permutation is `3`. In general, the cycles of a permutation are unique (up to order), and the number of cycles for a permutation of size `n` varies from `1` to `n`. # The challenge Given a non-empty permutation, output its number of cycles. Input is an array formed by the `n` integers `1`, `2`, ..., `n`, where `n > 0`. Each integer occurs exactly once. The order in which they appear defines the permutation, as in the example above. Instead of an array you can use a list, a string with a separator between the numbers, a separate input for each number, or anything that's reasonable. For a permutation of size `n`, instead of the 1-based set of integers `1`, ..., `n` you can consistently use the 0-based set `0`, ..., `n-1`. If so, please indicate it in your answer. The code should work for `n` up to `20` in a reasonable time, say less than one minute. Code golf. All builtins allowed. # Test cases This assumes 1-based, array input. ``` [1] -> 1 [3,2,1] -> 2 [2,3,4,5,1] -> 1 [5,2,4,3,6,1] -> 3 [8,6,4,5,2,1,7,3] -> 2 [4,5,11,12,7,1,3,9,10,6,8,2] -> 1 [4,2,5,11,12,7,1,3,9,10,6,8] -> 5 [5,8,6,18,16,9,14,10,11,12,4,20,15,19,2,17,1,13,7,3] -> 3 [14,5,17,15,10,18,1,3,4,13,11,16,2,12,9,7,20,6,19,8] -> 7 ``` # Related This [related challenge](https://codegolf.stackexchange.com/q/1668/36398) asks for the actual cycles of the permutation, not the number of them. Requiring only the number of cycles can lead to shorter algorithms that sidestep generating the actual cycles. [Answer] # J, 4 bytes ``` #@C. ``` This assumes that the permutation is 0-based. It uses the builtin `C.` which given a list representing a direct permutation outputs a list of cycles. Then `#` composed `@` on that returns the number of cycles in that list. [Try it here.](http://tryj.tk) [Answer] # JavaScript, ~~99~~ 98 bytes This solution assumes the array and its values are zero-indexed (e.g. `[2, 1, 0]`). ``` f=a=>{h={},i=c=0;while(i<a.length){s=i;while(!h[i]){h[i]=1;i=a[i]}c++;i=s;while(h[++i]);}return c} ``` **Explanation** ``` // assumes the array is valid and zero-indexed var findCycles = (array) => { var hash = {}; // remembers visited nodes var index = 0; // current node var count = 0; // number of cycles var start; // starting node of cycle // loop until all nodes visited while(index < array.length) { start = index; // cache starting node // loop until found previously visited node while(!hash[index]) { hash[index] = 1; // mark node as visited index = array[index]; // get next node } count++; // increment number of cycles index = start + 1; // assume next node is right after // loop until found unvisited node while(hash[index]) { index++; // get next node } } return count; // return number of cycles }; ``` [Answer] # Mathematica, 45 bytes ``` Length@ConnectedComponents@Thread[Sort@#->#]& ``` It generates a graph and counts its connected components. [Answer] # Mathematica, ~~37~~ ~~28~~ 27 bytes ``` #~PermutationCycles~Length& ``` Thanks @alephalpha for saving 9 bytes, and @miles for 1 more byte. [Answer] ## Python, 64 bytes ``` l=input() for _ in l:l=[min(x,l[x])for x in l] print len(set(l)) ``` This golfed code happens to be idiomatic and readable. Uses 0-indexing. Each value looks at what it points to and what the pointed value points to, and points to the smaller of the two. After enough repetitions, each element points to the smallest element of its cycle. The number of distinct elements pointed to is then the number of cycles. It suffices to do `n` iterations. Alternatively, we could iterate until the list no longer changes. This strategy gave me a recursive function of the same length, 64 bytes: ``` f=lambda l,p=0:len(set(l*(l==p)))or f([min(x,l[x])for x in l],l) ``` Reducing was 65 bytes ``` lambda l:len(set(reduce(lambda l,_:[min(x,l[x])for x in l],l,l))) ``` The `set(_)` conversions can be shortened to `{*_}` in Python 3.5, saving 2 bytes. [Answer] # Python, 77 69 67 bytes ``` f=lambda p,i=1:i and0 **p[i-1]+f(p[:i-1]+[0]+p[i:],p[i-1]or max(p)) ``` [Answer] # Jelly, ~~12~~ ~~10~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ị³$ÐĿ«/QL ``` Saved 1 byte thanks to @[Dennis](https://codegolf.stackexchange.com/users/12012/dennis). This uses 1-based permutations. It works by applying the permutation repeatedly until it reaches a previous permutation while also keeping its previous values. By keeping track of the changes, it will create the orbit for every value along the columns of that table. Then, by finding either the minimum or maximum of each column, a label for that cycle can be created. Then deduplicate that list of labels and get the length of it which will be the number of disjoint cycles. [Try it here.](http://jelly.tryitonline.net/#code=4buLwrMkw5DEv8KrL1FM&input=&args=WzUsMiw0LDMsNiwxXQ) ## Explanation ``` ị³$ÐĿ«/QL Input: permutation p $ Chain (ị³) as a monad ³ The input p ị For each value x, get the value at index x in p ÐĿ Invoke it on p initially, and repeat it on its next value until it returns to a previous value and keep track of the results This will create a table where each column is the orbit of each value «/ Get the minimum value along each column of that table Q Deduplicate L Get the length and return ``` [Answer] ## Haskell, 111 bytes ``` l!i|l!!i<0=l|1<2=(take i l++[-1]++drop(i+1)l)!(l!!i) f(x:y)|x>=0=0|1<2=1+f y c l|l==[-1|x<-l]=0|1<2=1+c(l!f l) ``` Uses 0-based indexing [Answer] # Pyth, 9 bytes ``` l{mS.u@QN ``` Uses 0-based indexes. [Try it online](https://pyth.herokuapp.com/?code=l%7BmS.u%40QN&test_suite=1&test_suite_input=%5B0%5D%0A%5B2%2C+1%2C+0%5D%0A%5B1%2C+2%2C+3%2C+4%2C+0%5D%0A%5B4%2C+1%2C+3%2C+2%2C+5%2C+0%5D%0A%5B7%2C+5%2C+3%2C+4%2C+1%2C+0%2C+6%2C+2%5D%0A%5B3%2C+4%2C+10%2C+11%2C+6%2C+0%2C+2%2C+8%2C+9%2C+5%2C+7%2C+1%5D%0A%5B3%2C+1%2C+4%2C+10%2C+11%2C+6%2C+0%2C+2%2C+8%2C+9%2C+5%2C+7%5D%0A%5B4%2C+7%2C+5%2C+17%2C+15%2C+8%2C+13%2C+9%2C+10%2C+11%2C+3%2C+19%2C+14%2C+18%2C+1%2C+16%2C+0%2C+12%2C+6%2C+2%5D%0A%5B13%2C+4%2C+16%2C+14%2C+9%2C+17%2C+0%2C+2%2C+3%2C+12%2C+10%2C+15%2C+1%2C+11%2C+8%2C+6%2C+19%2C+5%2C+18%2C+7%5D). ### How it works ``` m map for d in input: .u cumulative fixed-point: starting at N=d, repeatedly replace N with @QN input[N] until a duplicate is found, and return all intermediate results S sort { deduplicate l length ``` [Answer] ## JavaScript (ES6), 49 bytes ``` a=>a.reduce(g=(c,e,i)=>e<i?g(c,a[e],i):c+=e==i,0) ``` Uses zero-based indexing. Explanation: `reduce` is used to invoke the inner function `g` on each element of the array. `c` is the count of cycles, `e` is the array element, `i` is the array index. If the element is less than the index, then it's a potential cycle - the element is used to index into the array to find the next element in the cycle recursively. If we started out or end up with the original index then this is a new cycle and we increment the cycle count. If at any point we find a value larger than the index then we'll count that cycle later. [Answer] # C, 90 bytes Call `f()` with a mutable `int` array, 1 based indexing. The second parameter is the size of the array. The function returns the number of cycles. ``` i,j,c;f(a,n)int*a;{for(c=i=0;i<n;++i)for(j=0,c+=!!a[i];a[i];a[i]=0,i=j-1)j=a[i];return c;} ``` [Try it on ideone](http://ideone.com/WkVZ6m). The algorithm: ``` For each index If index is non-zero Increment counter Traverse the cycle, replacing each index in it with 0. ``` [Answer] ## [GAP](http://gap-system.org), 30 bytes Straightforward, the second argument to `Cycles` gives the set on which the permutation should act: ``` l->Size(Cycles(PermList(l),l)) ``` ]
[Question] [ ## Challenge: Given a list of multi-line strings, overlap them (in the top-left) and output the result. **Example:** Input: `["aaaa\naaaa\naaaa\naaaa","bb\nbb\nbb","c"]` Output: ``` cbaa bbaa bbaa aaaa ``` ## Challenge rules: * Input-format is flexible. You are allowed to get the input as a 2D list of lines (i.e. `[["aaaa","aaaa","aaaa","aaaa"],["bb","bb","bb"],["c"]]`) or 3D list of characters (i.e. `[[["a","a","a","a"],["a","a","a","a"],["a","a","a","a"],["a","a","a","a"]],[["b","b"],["b","b"],["b","b"]],[["c"]]]`). You are allowed to take all the inputs one by one through STDIN. Etc. * Output format is strict. You can choose to print or return the multi-line string. (If your language doesn't have any strings, outputting as a 2D list of characters is allowed as alternative. But only if your language doesn't have strings at all.) * The order of the input-list is of course important (but you are allowed to take the input in reverse if you choose to). * Inputs will only contain printable ASCII in the unicode range \$[33,126]\$ (`!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~`). * Inputs will only be rectangles (so no weird shapes). The output aren't necessary rectangles, though. * Trailing spaces and a single trailing newline is allowed. Leading spaces and/or newlines not. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases: Input: `["aaaa\naaaa\naaaa\naaaa","bb\nbb\nbb","c"]` Output: ``` cbaa bbaa bbaa aaaa ``` Input: `["12345\n54321","00\n00\n00\n00","001\n011\n012"]` Output: ``` 00145 01121 012 00 ``` Input: `["sm\noo\nmr\nee\nt!\nh_\ni_\nn_\ng_","!@#$%^\n&*()_+\nqwerty\nuiopas","this\nis_a\ntest"]` Output: ``` this%^ is_a_+ testty uiopas t! h_ i_ n_ g_ ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 24 bytes *Saved 2 bytes thanks to @Grimy* Assumes that the returned string is printed on a terminal that supports [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code). Contains the unprintable character `ESC`, which is escaped (no pun intended) as `\x1B` below. ``` a=>`\x1B[2J\x1B[H`+a.join`\x1B[H` ``` This doesn't work on TIO, but you can [Try it online!](https://tio.run/##FYzLDoIwEEU/hBX1kSLKwj3GpfEXGG0bLFACM9ipGr@@1sVJ7uLcM5q34da7JRyQHjZ2dTT1SWfN8Zo1F12aaiSH@r9jS8g02WqiXnayETwDEgHOHtBawJADDgrQJTDRK7EX@Xm13twBtztZqBLw@bE@fAFfjhbDSQiD4/RhZVLBchC3oog/ "JavaScript (Node.js) – Try It Online") to see the raw output instead. ### How? The [CSI sequences](https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences) used are: * ED (Erase in Display): `ESC``[``2``J` where \$2\$ means *"clear entire screen"* * CUP (Cursor Position): `ESC``[``H` which means *"moves the cursor to row \$n\$, column \$m\$"* where both \$n\$ and \$m\$ are omitted and implicitly set to \$1\$ (top-left corner of the screen). ### Example output [![output](https://i.stack.imgur.com/l9kya.png)](https://i.stack.imgur.com/l9kya.png) [Answer] # [R](https://www.r-project.org/), ~~120~~, ~~111~~ ~~110~~ 107 bytes ``` function(x,`!`=ncol,M=array('',Reduce(pmax,Map(dim,x)))){for(m in x)M[1:!t(m),1:!m]=m write(t(M),1,!M,,'')} ``` [Try it online!](https://tio.run/##lVLBbtswDL3rK2hnm6VVG@q0vRQzsFsv82XXKEsVRW4EWJQnKavbIt@e0t7WYcMuFUCKEh4fHyXG0wL2th9shO6AJruAYAL@sDE7vIO8dwm6EL3OcA2Gl/Xy4vJK4dXlxbIuZXl@rvCPzRc1RfXslqVgC8gBNPQuZQgdEE904xSZvY7aZBsTu2l@l@aP4okBfGkmPBcUOvj0AWoKSATX4BBSjmnoXeaPslJYiTmDclYrt15P6F34aHTf87h1uJMvcC0rAs/YmdTB2Ux8nAqyI2Njc8OpQ01L4b@eWttuFf40OpiSuLrm9KJ8lLfFbYMm9LJtdIz6gVeV/Gp3B2P54PUoWz3wnfNyFLSepn781M8o2lV9XWTuhaTdrxvP7qPLlmfe0pUsWjlJP546/kqBghmd@fxK7FfyK//vfxTJKwxBoY8KrVWYC4X7jUJHhmR3G@IpPi/evP2m8N17LjZnCr/f00Q9KDy4MOhEgGmyKCdtSH@2Kf9d6/QM "R – Try It Online") A function accepting a list of matrix of characters (3D input is accepted). (as you can notice from the byte count, this is not very easy to do in R...) * -9 bytes thanks to @Giuseppe * -4 bytes thanks to @RobinRyder [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` a/Y ``` [Try it online!](https://tio.run/##y0rNyan8/z9RP/L/4fZHTWuyHjXM4eL6/z@aSwEIoqOVEoFASQcbFasTrZSUBOTBCJBAslJsrA5Mr6GRsYkpUM7UxNjIECxtYADkohAQUUMQxxBCGiEbUZwLFMvPBxK5RUAiNRVIlCgCiYx4IJEJIvJARHo82CRFB2UV1TggX01LQzNeG8goLE8tKqkEMkoz8wsSi8GqSjIyi0G6i@NBnilJLS4BWskVCwA "Jelly – Try It Online") Hadn't used Jelly in a while but I thought the challenge in the comments was beatable. Very directly uses logical and (`a`) to perform the stacking operation between each element of the input (`/`). `Y` is used to print in the required format. [Answer] # [Python 2](https://docs.python.org/2/), 88 bytes ``` n,f=None,filter for l in map(n,*input()):print''.join(f(n,x)[-1]for x in map(n,*f(n,l))) ``` [Try it online!](https://tio.run/##bY1NbsMgEIX3nILQH4xLq2Anm0qReoJeANHKcXFNZAPBRHVO7zJYlVqpLD5m3rw346@xd7ZaWvehD4SQxfLu8Oqs5p0Zog6ocwEP2Fg8Nr6wvDTWX2LB2LMPxkZKn07O2KJLo5nJR6HAP//yw2RgjC3Zj9IJhPSsWwwXy3qRkoiq3u0JJ/tdXQmiuCTbbWr/YFUFNGJlRZRCKd2kl4R/Psgcj6n7AQjtGqPTSDmmzgHHANQaGDfAHgNNps38xFRxLOnm5eb27g2U@7Jg7w9Qnb90iFeoLsb5ZlqdsTdT3jLhJm/WU6RKfQM "Python 2 – Try It Online") --- ### Explanation (with example): Takes a 2D list as input. ``` Input: [["12345","54321"],["00","00","00","00"],["001","011","012"]] ``` First the input list is zipped, to get the rows of each input rectangle (`map(None,l)` is the same a zip longest): ``` map(n,*input()) gives: ('12345', '00', '001') ('54321', '00', '011') (None, '00', '012') (None, '00', None) ``` Each of these rows are then filtered to removed `None`s, and zipped again: ``` map(None,*filter(None,l)) filter(None,l) for each l gives: ('12345', '00', '001') ('54321', '00', '011') ('00', '012') ('00',) map*... gives: [('1', '0', '0'), ('2', '0', '0'), ('3', None, '1'), ('4', None, None), ('5', None, None)] [('5', '0', '0'), ('4', '0', '1'), ('3', None, '1'), ('2', None, None), ('1', None, None)] [('0', '0'), ('0', '1'), (None, '2')] ['0', '0'] ``` Which is a list of characters for each position of the desired result. These lists are filtered again, and the last one is taken: ``` filter(None,x) gives: [('1', '0', '0'), ('2', '0', '0'), ('3', '1'), ('4',), ('5',)] [('5', '0', '0'), ('4', '0', '1'), ('3', '1'), ('2',), ('1',)] [('0', '0'), ('0', '1'), ('2',)] ['0', '0'] and with [-1]: ['0', '0', '1', '4', '5'] ['0', '1', '1', '2', '1'] ['0', '1', '2'] ['0', '0'] ``` Lastly the resulting lists are joined and printed: ``` print''.join(..) 00145 01121 012 00 ``` [Answer] # R, ~~107~~ 97 bytes ``` function(x)for(i in 1:max(lengths(x))){for(m in x)if(i<=length(m))cat(m[i],'\r',sep='');cat(' ')} ``` Doesn't appear to work on TIO, which might be related to the use of the `\r` carriage return character. It does work on my local installation of R. Takes input as a list containing a vector of rows: ``` x <- list(c("aaaa","aaaa","aaaa","aaaa"),c("bb","bb","bb"),c("c")) ``` Loops over the rows of each rectangle, printing a carriage return after each, restarting the line. If we stretch the rules a little, we can do away with checking the length of the input and just loop infinitely, printing a huge amount of newlines: # R, 85 bytes ``` function(x)for(i in 1:8e8){for(m in x)if(i<=length(m))cat(m[i],'\r',sep='');cat(' ')} ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 22 [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 list of 2D character arrays as argument. Prints. ``` (⊃{⍺@(⍳⍴⍺)⊢⍵}/)⌽,∘⊂1⌷↑ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT//vmfeobcKjvqluviGHVjzqmAFkegX7@6nHxOSpA9lBQEaR@n@NR13N1Y96dzloPOrd/Kh3C5Cp@ahr0aPerbX6mo969uqAdHY1GT7q2f6obeL/NJCZvX1A/Z7@QJ2H1hsDRYG84CBnIBni4Rn8P03BM089WikRCGLy0EklHaWkpJg8CAZykpVi1bl0dXW5oLoMjYxNTGPyTE2MjQyB0gYGMXkIDBYwBLIMwYQRmt7i3Ji8/PyYvNyimLzU1Ji8EsWYvIz4mLxMIM4D4vR4oAGKDsoqqnExeWpaGprx2jF5heWpRSWVMXmlmfkFicVABSUZmcVAPcXxQBeXpBaXAC0BAA "APL (Dyalog Unicode) – Try It Online") This works by creating a canvas, then appending that to the list of blocks, and reducing (folding) with a function that places blocks in the corner. `↑` mix the 2D block to create an orthogonal 3D block, padding them with spaces as needed `1⌷` take the first layer `⊂` enclose that  `∘` then `⌽,` prepend the reversed list of blocks `(`…`)` apply the following tacit function:  `{`…`}/` reduce using the following anonymous lambda:   `⊢⍵` with the right argument as canvas…   `⍺@(`…`)` amend with the elements of the left argument, placed **at** the following indices:    `⍴⍺` the shape of the left argument    `⍳` the **ɩ**ndices of an array of that shape  `⊃` disclose (because the reduction enclosed to reduce rank) [Answer] ## Haskell, 66 bytes ``` unlines.foldl((const?)?)[] (g?(a:b))(c:d)=g a c:(g?b)d;(_?a)b=a++b ``` Input is taken as a list of list of strings in reverse order, e.g. for the first test case: `[["c"],["bb","bb","bb"],["aaaa","aaaa","aaaa","aaaa"]]`. [Try it online!](https://tio.run/##XY7bTsMwDIbv9xRZOSihY1q77aaoKg8AV1zWJUrT9CBStzQpiJenWJ0EEpY@y/7tX3ar3JuxdqlTWGa0HRq3rwdbWc71gM5nIhN5seFNxlVSCsF1Uom0YYrphMRSVA9cZkqUqQrDculVhyxlvRqfJePj7F/89IRsz2qCVLZeoHoyH2ZyRrB8wxjLA0UB@D8Hu6AsAS9Qo4Nid9mP4uPpDHg@HeOIBocD4B@rEFEVrSn@dbkecBgA@wnQGEC/BWwlYEcg0Uiybh@vrm9eAW/vuJAh4PunmfwX4NwNo3K04NvOkcdJ@tIb54OiWL51bVXjlns9jj8 "Haskell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes Port of [TFeld's python solution](https://codegolf.stackexchange.com/a/186373/47066) 2 bytes saved thanks to *Grimy* ``` ζεðKζðδK€θJ, ``` [Try it online!](https://tio.run/##TY9LDoIwEIavgvURH3AH13KEBk1NGiERKhZjcOl5XLBQ4p59D@FFan9GSTdfvsnMtP8oLfaZtNa05tU1sWm7xjzjz/1h3pvQWs450ywMWM6SMOBMwRV5Dj@TS7gkr@Aj8hS@I888Lzw//BwFd4uuWgNjYAJMgS1Nz@BLYA4saNlhRf0SfqU4fT6HPlFN/Qs8ozMcToAA9D9BP50OY9pLr4ffhHerHFqVeyOxUVSo6Chu9Rc "05AB1E – Try It Online") **Explanation** ``` ζ # transpose input with space as filler ε # apply to each ðK # remove spaces ζ # transpose with space as filler ðδK # deep remove spaces €θ # get the tail of each J # join each , # print ``` **Alternative 14 byte version** ``` õζεÅ»DŠg.$J}θ, ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8NZz285tPdx6aLfL0QXpeipeted26Pz/Hx2tVJyrpKOUnw8kcouARGoqkChRBBIZCkAiE0TkgYh0BaVYHYVoJUUHZRXVOKCAmpaGZrw2kFFYnlpUUglklGbmFyQWQ5SVZGQWg/QXKySCDEwtLlGKjf2vq5uXr5uTWFUJAA "05AB1E – Try It Online") **Explanation** ``` õζ # zip with empty string as filler ε # apply to each Å» } # cumulative reduce by D # duplicate second input Š # move down twice on stack g.$ # remove len(other_copy) elements from the other input J # join with other copy θ, # print the last element ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 5 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` H11╋╋ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjI4JXVGRjExJXVGRjExJXUyNTRCJXUyNTRC,i=JTVCJTIyJTIxJTIxJTIxJTVDJTVDJTIyJTJDJTIyYWFhLyU1Q25hYWFhJTVDbmFhYWElNUNuYWFhYSUyMiUyQyUyMmJiJTVDbmJiJTVDbmJiJTIyJTJDJTIyYyUyMiU1RA__,v=8) If overlapping `/`+`\` → `X`, `-` + `|` → `+`, etc. would be fine, [2 bytes](https://dzaima.github.io/Canvas/?u=JXVGRjI4JXVGRjRF,i=JTVCJTIyJTIxJTIxJTIxJTVDJTVDJTIyJTJDJTIyYWFhLyU1Q25hYWFhJTVDbmFhYWElNUNuYWFhYSUyMiUyQyUyMmJiJTVDbmJiJTVDbmJiJTIyJTJDJTIyYyUyMiU1RA__,v=8) would work. [Answer] # [Python 2](https://docs.python.org/2/), 77 bytes ``` for t in map(None,*input()): r='' for s in t: if s:r=s+r[len(s):] print r ``` [Try it online!](https://tio.run/##bYxNbsMgEIXX5RQT@oOdsAhOskGKlBP0AohWTkRqpBgoECU5vctgdVGps/hm3tObFx558K6bboO9GBDS3M2JUjqdfYQM1sHYh@bdO8OX1oVrbtpWEoh7xghgJmEmS/Jkz5Bk3KdVVBfjmtRKTSBE6zLEqW6CvUpR0W22O8rpbrvpBNVc0fW6yD@YXYFCzOyo1qR892WK8c/Cn@OxqF@gcZrfWBoZB@Y9coxIY5B5gRwAaStd5RcwzUGxxeH55fUDnbdl036u8Pq@mZgfeF2tD32ak3mwqbYk6GuzSZlp/QM "Python 2 – Try It Online") [Answer] # [PowerShell 6](https://github.com/TryItOnline/TioSetup/wiki/Powershell), console only, 20 bytes based on Arnauld's [answer](https://codegolf.stackexchange.com/a/186374/80745). This work with console only and doesn't work on TIO. ``` cls $args-join"`e[H" ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkqZgq1D9PzmnmEslsSi9WDcrPzNPKSE12kPpfy0XlxpQXikRCBLy0EklBaWkpIQ8CAZykpX@AwA "PowerShell – Try It Online") --- # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 103 bytes ``` $args|%{$l=$_-split' ';$r=&{$r+($l|%{''})|%{($x=$l[$j++])+($_-replace"^.{0,$("$x"|% Le*)}")}|?{$_}}} $r ``` [Try it online!](https://tio.run/##hVJtbqMwEP3PKRxnCFBIFWjyaxVtDrA3WDU2od6ElTNQ7GgTEc6eDtAPqKruSGPzZt48D/aUxT9VmYPS@gZ/2JrVN0irvbm6Neg1iLkpdW49x/sB1XpWQxX6oCnpeU1Amw/nNejf8DcMHwNKiXmlSp1mim/v60UEPoczv7rsl7oLGh401581iKZpHKhujeNsfIeRRf3W2sbnKZnEzyuP@G4nsXcCGQ@i9yov26WpN8C7/@BW0etg4HzRQpw8LFcSV8uHJKazFguJH94FYvqKuyUZNUKZ5Wp4ErGSeBxIRnDxTR/mKLEoJB4riUpJtBOJByExJ0fyvaBmJpspuFuJszs/EKHEZ3pQe5F4yosyNUSwh9xQjRF0lVYZO2q4TbrbYUctUYTDSFtkL8NIrz3iTIboIEaKI4QjtBdv/x@wK3NZ3SHQOSoTgTqXKrPqiQYTRJ@plDlpS4EZzeum47EpozFNrc1x35H4K4vP1TN/F@FdbvqmMGUnzIrjUaFl7S2wVovZgj3lrdqF9TzjNM7tBQ "PowerShell – Try It Online") Unrolled: ``` $args|%{ $l=$_-split"`n" $r=&{ # run this scriptblock in a new scope $r+($l|%{''})|%{ $x=$l[$j++] # a new line or $null $w="$x"|% Length $y=$_-replace"^.{0,$w}" # remove first chars from the current line $x+$y # output the new line plus tail of the overlapped line }|?{$_} # filter out not empty lines only } # close the scope and remove all variables created in the scope } $r ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 68 + 23 = 91 bytes ``` n=>{C.Clear();n.ForEach(k=>{C.SetCursorPosition(0,0);C.Write(k);});} ``` 23 bytes is for the import, `using C=System.Console;` Does not work in TIO, since it isn't a console. [Try it online!](https://tio.run/##XU5Na8MwDD0nv8Lk5EBnencTGKYbOwwKPezQ9uB4ambqyCA5GyPkt2deu@0wIQn00PtwfOciwTKyx16YZv/JCQZlInIMoEsXLLPYUezJDmIqOdnknfh5u3fJR9z8kUKAK8LqERDIO/W0xXEAsl2ADSfKJm17bhZs2skoE8CSrDWqh0hb697k5YrvIZmRONIusv/Wk@vVutZGvZBPIC@1nnMv@jfNe/Sv4tl6lDeLw0lY6rnOeYviLBE@DqepsrmO@H9Xq6rrjnibfLgqa5fFXM7LFw "C# (.NET Core) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 67 bytes Input is a list of lines. Builds a list of lines and does overwriting as it goes through the inputs, then joins them with a newline (represented by the variable `$/`) at the end to match the strict output. ``` ->i,*r{i.map{|e|j=-1;e.map{|l|r[j+=1]||='';r[j][0,l.size]=l}};r*$/} ``` [Try it online!](https://tio.run/##RYzRCoMgAEXf/YqQoNXKqdVTcz@SPjRmYFiI1cOWfrtrGyO45@FeONeu92foGQ/FTeWZ3RQaO7M56QZWkEb@mna2Hc6MCOdYkjR7ES3ONZrVSwqmvW9sFl98UJNZl4hF8RVZ2T3QbLRaTpBPfILp/1geM0w92I056tuvKgKhZVWDuiopAQDjIzsEYPKBvgE "Ruby – Try It Online") [Answer] # C (GCC, MinGW) 138 bytes Assumes that CR puts the cursor at the start of the current line. ``` d,i,l;f(S,n,p,t)char**S,*p,*t;{for(d=i=0;i<n;d+=l)p=strchr(t=S[i],10),printf("\n%.*s\r"+!!i,l=p?p-t:strlen(t),t),S[i++]+=l+!!p;d&&f(S,n);} ``` Tested with: ``` int main() { char *test1[] = {"aaaa\naaaa\naaaa\naaaa","bb\nbb\nbb","c"}; char *test2[] = {"12345\n54321","00\n00\n00\n00","001\n011\n012"}; char *test3[] = {"sm\noo\nmr\nee\nt!\nh_\ni_\nn_\ng_","!@#$%^\n&*()_+\nqwerty\nuiopas","this\nis_a\ntest"}; f(test1, 3); f(test2, 3); f(test3, 3); } ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~71~~ 67 bytes ``` function y=f(x) for k=1:size(x) y(1:(t=size(x{k})),1:t(2))=x{k};end ``` Function that takes a vertical cell array of char matrices, and returns a char matrix. [Try it online!](https://tio.run/##y08uSSxL/f8/rTQvuSQzP0@h0jZNo0KTKy2/SCHb1tCqOLMqFcSv1DC00iixhXCrs2s1NXUMrUo0jDQ1bUFc69S8lP9AzJWSWVygkaZRHa2eCATq1ihUrLVCtHpSEpALJMCcZPVYoFH/AQ) Or [verify all test cases](https://tio.run/##fZBLbsIwEIb3nMKoD9ttF9iBTSJLvQeiVghOsRAxxANtijh7Os5QVdlgyZ/nn6c8oYLy7Pq@PjUV@NCwztTiW07q0LKdUXn0Py7pTqhcgCF52V2lfFM5CC2lSbJwzabHOwEXwSpm2GXJSzy8GD2rgi35eo0SMYiKr64FlWkqUzqbLzBjMc@0oqTZDPUIN7dKShH1f6eMOsU9BkJA7FuEcwiYIrYW4ROahE9L/abvD49PH@h4fhHSvqJx/HItdGicfDiUkdJg62Oqjzb9Kw0cJm98PIha0AZwP2xwcMb/zFtM34llo1j/Cw). [Answer] # [Javascript (browser)](https://developer.mozilla.org/en-US/), ~~216~~ ~~208~~ 204 bytes My attempt at this. I'm not happy about the size, and there must certainly be more for improvement, but I'm not that experienced at golfing. ``` var n='\n',x=s=>s.split``.reverse().join``,i,j,f=a=>a.map(s=>s.split(n).map(y=>x(y))).reduce((a,b)=>{for(i=0;i<b.length;i++){j=a[i];if(!j)j=b[i];a[i]=b[i].padStart(j.length,j)}return a}).map(s=>x(s)).join(n) ``` Anyways, what it does is first split all the strings, then reverse all the strings, then whilst looping in a reduce operation [padStart](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart) all the strings together. Then reverse all the strings again and then join them back with newlines. Special thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for reminding me that the last part in a for loop happens at the end and a total byte savings of 8 bytes. ``` var n='\n',x=s=>s.split``.reverse().join``,i,j,f=a=>a.map(s=>s.split(n).map(y=>x(y))).reduce((a,b)=>{for(i=0;i<b.length;a[i]=b[i++].padStart(j.length,j))if(!(j=a[i]))j=b[i];return a}).map(s=>x(s)).join(n) console.log(f(["aaaa\naaaa\naaaa\naaaa","bb\nbb\nbb","c"])); console.log(f(["12345\n54321","00\n00\n00\n00","001\n011\n012"])); console.log(f(["sm\noo\nmr\nee\nt!\nh_\ni_\nn_\ng_","!@#$%^\n&*()_+\nqwerty\nuiopas","this\nis_a\ntest"])); ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~51~~ 47 bytes ``` f(char**s){for(;*s;printf("\e[s%s\e[u",*s++));} ``` [Try it online!](https://tio.run/##bU/RCsIwDHzfV4SJ0HZT8bnij6gPtctmcWtHU6cy/Pba@iAIJiHkyOXI6VWndVwYq/tbg7Cj0Bi3vuxhI2BAj/0TggOPg5sQ7spbYzsCsSkmZ5pMUj25/5TYMn1RXgjic@s8k4Lk6I0NLSuPeKAlpX4ra0FVxbl8xbSCQRnL8qB8p2vIAiDSPB1OHOYCoGUZVVsuE/jK2f9Zcvkxoq5IQKPSCOkTsPgI6dYNY8hWXjGqFMVvi@dz8amo3w "C (gcc) – Try It Online") -4 bytes thanks to ceilingcat. Uses the CSI sequences for save/restore cursor position. Just iterates over the passed string array (in the same format as `argv`) and prints `<save position>string<restore position>` for each. This does leave the cursor at the top left, so when running at the terminal it is important to leave enough newlines afterwards so that the prompt doesn't clobber the input. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 7 bytes Takes input as an array of multi-line strings, outputs a single multi-line string. ``` ú y_¸¬Ì ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=%2biB5X7iszA&input=WyJzbQpvbwptcgplZQp0IQpoXwppXwpuXwpnXyIsIiFAIyQlXgomKigpXysKcXdlcnR5CnVpb3BhcyIsInRoaXMKaXNfYQp0ZXN0Il0) ``` ú y_¸¬Ì :Implicit input of array ú :Right pad each line of each element with spaces to the length of the longest y :Transpose _ :Map ¸ : Split on spaces ¬ : Join Ì : Last character :Implicitly join and output ``` [Answer] # T-SQL query, ~~297~~ 295 bytes Using ¶ as separator and a table variable as input. ``` DECLARE @ table(a varchar(max),k int identity(1,1)) INSERT @ values('aaaa¶aaaa¶aaaa¶aaaa'),('bb¶bv¶bb'),('c'); WITH c as(SELECT k,row_number()over(partition by k order by k)s,value v FROM @ CROSS APPLY string_split(a,'¶')s),m(i,l,e)as(SELECT*FROM c WHERE k=1UNION ALL SELECT k,s,STUFF(e,1,len(v),v)FROM m JOIN c ON-~i=k and s=l)SELECT top 1with ties e FROM m ORDER BY rank()over(partition by l order by-i) ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1061453/overlapping-string-blocks)** [Answer] # Javascript (browser), ~~129~~ 124 bytes My first attempt at code golfing. I read the links given in the rules (loopholes, standard rules...), so I hope I did anything wrong! --- I kept the inputs as they are in the first post (flat array form). ``` _=o=>{o=o.map(i=>i.split`\n`),r=o.shift();for(a of o)for(l in a)b=a[l],r[l]=r[l]?b+r[l].slice(b.length):b;return r.join`\n`} ``` Thanks to **[Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)** for saving 5 bytes. --- [Answer] # [Pyth](https://github.com/isaacg1/pyth), 18 bytes ``` L.tb0VyQsme #dy #N ``` [Try it online!](http://pythtemp.herokuapp.com/?code=L.tb0VyQsme+%23dy+%23N&test_suite=1&test_suite_input=%5B%5B%2212345%22%2C%2254321%22%5D%2C%5B%2200%22%2C%2200%22%2C%2200%22%2C%2200%22%5D%2C%5B%22001%22%2C%22011%22%2C%22012%22%5D%5D%0A%5B%5B%22aaaa%22%2C%22aaaa%22%2C%22aaaa%22%2C%22aaaa%22%5D%2C%5B%22bb%22%2C%22bb%22%2C%22bb%22%5D%2C%5B%22c%22%5D%5D%0A%5B%5B%27sm%27%2C+%27oo%27%2C+%27mr%27%2C+%27ee%27%2C+%27t%21%27%2C+%27h_%27%2C+%27i_%27%2C+%27n_%27%2C+%27g_%27%5D%2C+%5B%27%21%40%23%24%25%5E%27%2C+%27%26%2a%28%29_%2B%27%2C+%27qwerty%27%2C+%27uiopas%27%5D%2C+%5B%27this%27%2C+%27is+a%27%2C+%27test%27%5D%5D&debug=0) (note: the code itself evaluates only one block, the interpreter's test suite mode runs the program once for each line of input) Based on [TFeld's Python 2 solution](https://codegolf.stackexchange.com/a/186373/71803). Explanation: ``` L.tb0 # define a lambda function called y which does a transpose, padding with integer 0's VyQ # loop over transposed first input line (Q = eval(input()) ) (loop index = N) s # concatenate array of strings (implicitly printed) m # map over y #N # transpose of non-falsy values of N e # for each item: last element of array #d # relevant space at the start! filter with identity function, removes falsy values ``` for an explanation of why the algorithm itself works, see TFeld's answer. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal/wiki/Tutorial), 4 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page) ``` FθPι ``` [Try it online (verbose)](https://tio.run/##DYw7DsIwEAV7TpGYj2w@J6BJhWjo6LLBsiILr@SsE3sD4vRmi2me5s0YXB6Ti7XeUtaL2TTNY42Mc0ZijeZaa9@rMgGlBDRlIO@BuAUKFggFEt5WnVXbbXf7F9DhqI09AS1fn/kHtGKaXRGBAxb5FOuk4AvL9Ly3ahjq5RP/) or [try it online (pure)](https://tio.run/##S85ILErOT8z5///9nmXndrzfs@Hczv//o6OVinNj8vLzY/Jyi2LyUlNj8koUY/Iy4mPyMoE4D4jT45V0lBQdlFVU42Ly1LQ0NOO1Y/IKy1OLSipj8koz8wsSi4EKSjIyi4F6iuMTgSakFpcAhUI8FJViYwE). **Explanation:** Loop over the input-list of multi-line strings: ``` For(q) Fθ ``` And print the multi-line string without moving the cursor: ``` Multiprint(i); Pι ``` ]
[Question] [ Let's get back to basics! * Your code, a complete program or function, must convert the official Unicode name of a printable Basic Latin character into the corresponding character. For example, for the input `LOW LINE` your code must output `_`. * You only need to take a single character name as input. * You cannot use any preexisting function or library, built-in or otherwise, which offers any logic relating specifically to Unicode character names (e.g. Python's `unicodedata`, Java's `Character.getName`, and so on.) * For input other than one of these names, any behavior is acceptable. This is code golf: shortest code in bytes wins. To avoid any ambiguity, this is the full set of official character names we'll be using (borrowed from [this question](https://codegolf.stackexchange.com/questions/57143/print-the-character-names)): ``` SPACE ! EXCLAMATION MARK " QUOTATION MARK # NUMBER SIGN $ DOLLAR SIGN % PERCENT SIGN & AMPERSAND ' APOSTROPHE ( LEFT PARENTHESIS ) RIGHT PARENTHESIS * ASTERISK + PLUS SIGN , COMMA - HYPHEN-MINUS . FULL STOP / SOLIDUS 0 DIGIT ZERO 1 DIGIT ONE 2 DIGIT TWO 3 DIGIT THREE 4 DIGIT FOUR 5 DIGIT FIVE 6 DIGIT SIX 7 DIGIT SEVEN 8 DIGIT EIGHT 9 DIGIT NINE : COLON ; SEMICOLON < LESS-THAN SIGN = EQUALS SIGN > GREATER-THAN SIGN ? QUESTION MARK @ COMMERCIAL AT A LATIN CAPITAL LETTER A B LATIN CAPITAL LETTER B C LATIN CAPITAL LETTER C D LATIN CAPITAL LETTER D E LATIN CAPITAL LETTER E F LATIN CAPITAL LETTER F G LATIN CAPITAL LETTER G H LATIN CAPITAL LETTER H I LATIN CAPITAL LETTER I J LATIN CAPITAL LETTER J K LATIN CAPITAL LETTER K L LATIN CAPITAL LETTER L M LATIN CAPITAL LETTER M N LATIN CAPITAL LETTER N O LATIN CAPITAL LETTER O P LATIN CAPITAL LETTER P Q LATIN CAPITAL LETTER Q R LATIN CAPITAL LETTER R S LATIN CAPITAL LETTER S T LATIN CAPITAL LETTER T U LATIN CAPITAL LETTER U V LATIN CAPITAL LETTER V W LATIN CAPITAL LETTER W X LATIN CAPITAL LETTER X Y LATIN CAPITAL LETTER Y Z LATIN CAPITAL LETTER Z [ LEFT SQUARE BRACKET \ REVERSE SOLIDUS ] RIGHT SQUARE BRACKET ^ CIRCUMFLEX ACCENT _ LOW LINE ` GRAVE ACCENT a LATIN SMALL LETTER A b LATIN SMALL LETTER B c LATIN SMALL LETTER C d LATIN SMALL LETTER D e LATIN SMALL LETTER E f LATIN SMALL LETTER F g LATIN SMALL LETTER G h LATIN SMALL LETTER H i LATIN SMALL LETTER I j LATIN SMALL LETTER J k LATIN SMALL LETTER K l LATIN SMALL LETTER L m LATIN SMALL LETTER M n LATIN SMALL LETTER N o LATIN SMALL LETTER O p LATIN SMALL LETTER P q LATIN SMALL LETTER Q r LATIN SMALL LETTER R s LATIN SMALL LETTER S t LATIN SMALL LETTER T u LATIN SMALL LETTER U v LATIN SMALL LETTER V w LATIN SMALL LETTER W x LATIN SMALL LETTER X y LATIN SMALL LETTER Y z LATIN SMALL LETTER Z { LEFT CURLY BRACKET | VERTICAL LINE } RIGHT CURLY BRACKET ~ TILDE ``` [Answer] # IA-32 machine code, ~~161~~ ~~160~~ 122 bytes Hexdump of the code: ``` 33 c0 6b c0 59 0f b6 11 03 c2 b2 71 f6 f2 c1 e8 08 41 80 79 01 00 75 ea e8 39 00 00 00 08 2c 5e 4a bd a3 cd c5 90 09 46 04 06 14 40 3e 3d 5b 23 60 5e 3f 2d 31 32 29 25 2e 3c 7e 36 39 34 33 30 21 2f 26 7d 7c 2c 3b 7b 2a 37 5d 22 35 20 3a 28 5c 27 2b 38 5f 24 5a 3c 34 74 17 3c 1a 74 16 33 c9 86 c4 0f a3 0a 14 00 41 fe cc 75 f6 8a 44 02 0e c3 8a 01 c3 8a 01 04 20 c3 ``` This code uses some hashing. By some brute-force search, I found that the following hash function can be applied to the bytes of the input string: ``` int x = 0; while (s[1]) { x = (x * 89 + *s) % 113; ++s; } ``` It multiplies `x` by 89, adds the next byte (ASCII-code), and takes a remainder modulo 113. It does this on all bytes of the input string except the last one, so e.g. `LATIN CAPITAL LETTER A` and `LATIN CAPITAL LETTER X` give the same hash code. This hash function has no collisions, and the output is in the range 0...113 (actually, by luck, the range is even narrower: 3...108). The hash values of all relevant strings don't fill that space completely, so I decided to use this to compress the hash table. I added a "skip" table (112 bits), which contains 0 if the corresponding place in the hash table is empty, and 1 otherwise. This table converts a hash value into a "compressed" index, which can be used to address a dense LUT. The strings `LATIN CAPITAL LETTER` and `LATIN SMALL LETTER` give hash codes 52 and 26; they are handled separately. Here is a C code for that: ``` char find(const char* s) { int hash = 0; while (s[1]) { hash = (hash * 89 + *s) % 113; ++s; } if (hash == 52) return *s; if (hash == 26) return *s + 32; int result_idx = 0; int bit = 0; uint32_t skip[] = {0x4a5e2c08, 0xc5cda3bd, 0x04460990, 0x1406}; do { if (skip[bit / 32] & (1 << bit % 32)) ++result_idx; ++bit; } while (--hash); return "@>=[#`^?-12)%.<~69430!/&}|,;{*7]\"5 :(\\'+8_$"[result_idx]; } ``` The corresponding assembly language code (MS Visual Studio inline-assembly syntax): ``` _declspec(naked) char _fastcall find(char* s) { _asm { xor eax, eax; mycalc: imul eax, eax, 89; movzx edx, [ecx]; add eax, edx; mov dl, 113; div dl; shr eax, 8; inc ecx; cmp byte ptr [ecx + 1], 0; jne mycalc; call mycont; // skip table _asm _emit 0x08 _asm _emit 0x2c _asm _emit 0x5e _asm _emit 0x4a; _asm _emit 0xbd _asm _emit 0xa3 _asm _emit 0xcd _asm _emit 0xc5; _asm _emit 0x90 _asm _emit 0x09 _asm _emit 0x46 _asm _emit 0x04; _asm _emit 0x06 _asm _emit 0x14; // char table _asm _emit '@' _asm _emit '>' _asm _emit '=' _asm _emit '['; _asm _emit '#' _asm _emit '`' _asm _emit '^' _asm _emit '?'; _asm _emit '-' _asm _emit '1' _asm _emit '2' _asm _emit ')'; _asm _emit '%' _asm _emit '.' _asm _emit '<' _asm _emit '~'; _asm _emit '6' _asm _emit '9' _asm _emit '4' _asm _emit '3'; _asm _emit '0' _asm _emit '!' _asm _emit '/' _asm _emit '&'; _asm _emit '}' _asm _emit '|' _asm _emit ',' _asm _emit ';'; _asm _emit '{' _asm _emit '*' _asm _emit '7' _asm _emit ']'; _asm _emit '"' _asm _emit '5' _asm _emit ' ' _asm _emit ':'; _asm _emit '(' _asm _emit '\\' _asm _emit '\'' _asm _emit '+'; _asm _emit '8' _asm _emit '_' _asm _emit '$'; mycont: pop edx; cmp al, 52; je capital_letter; cmp al, 26; je small_letter; xor ecx, ecx; xchg al, ah; decode_hash_table: bt [edx], ecx; adc al, 0; inc ecx; dec ah; jnz decode_hash_table; mov al, [edx + eax + 14]; ret; capital_letter: mov al, [ecx]; ret; small_letter: mov al, [ecx]; add al, 32; ret; } } ``` Some noteworthy implementation details: * It uses a `CALL` instruction to get a pointer to the code, where the hard-coded table resides. In 64-bit mode, it could use the register `rip` instead. * It uses the [`BT`](https://en.wikipedia.org/wiki/Bit_Test) instruction to access the skip table * It manages to do the work using only 3 registers `eax`, `ecx`, `edx`, which can be clobbered - so there is no need to save and restore registers * When decoding the hash table, it uses `al` and `ah` carefully, so that at the right place `ah` is decreased to 0, and the whole `eax` register can be used as a LUT index [Answer] # JavaScript ES6, 228 ~~236 247 257 267 274 287~~ Note: 7 chars saved thx @ev3commander Note 2: **better than JAPT** after 7 major edits, ``` n=>n<'L'?"XC!DO$MP&OS'SK*N--FU.ZE0TW2HR3OU4FI5IX6EI8NI9EM;LS=R->IA@MF^AV`MM,NE1EN7LO:".replace(/(..)./g,(c,s)=>~n.search(s)?n=c[2]:0)&&n:'~ / ; |?"\\ ) }]_+ #% < ( {['[(n<'Q')*13+n.length-(n>'T')-4]||n[21]||n[19].toLowerCase() ``` Run the snippet to test ``` F=n=> n<'L'?"XC!DO$MP&OS'SK*N--FU.ZE0TW2HR3OU4FI5IX6EI8NI9EM;LS=R->IA@MF^AV`MM,NE1EN7LO:" .replace(/(..)./g,(c,s)=>~n.search(s)?n=c[2]:0)&&n: '~ / ; |?"\\ ) }]_+ #% < ( {['[(n<'Q')*13+n.length-(n>'T')-4] ||n[21]||n[19].toLowerCase() //TEST console.log=x=>O.innerHTML+=x+'\n' ;[ ['&','AMPERSAND'], ['\'','APOSTROPHE'], ['*','ASTERISK'], ['^','CIRCUMFLEX ACCENT'], [':','COLON'], [',','COMMA'], ['@','COMMERCIAL AT'], ['8','DIGIT EIGHT'], ['5','DIGIT FIVE'], ['4','DIGIT FOUR'], ['9','DIGIT NINE'], ['1','DIGIT ONE'], ['7','DIGIT SEVEN'], ['6','DIGIT SIX'], ['3','DIGIT THREE'], ['2','DIGIT TWO'], ['0','DIGIT ZERO'], ['$','DOLLAR SIGN'], ['=','EQUALS SIGN'], ['!','EXCLAMATION MARK'], ['.','FULL STOP'], ['`','GRAVE ACCENT'], ['>','GREATER-THAN SIGN'], ['-','HYPHEN-MINUS'], ['A','LATIN CAPITAL LETTER A'], ['B','LATIN CAPITAL LETTER B'], ['C','LATIN CAPITAL LETTER C'], ['D','LATIN CAPITAL LETTER D'], ['E','LATIN CAPITAL LETTER E'], ['F','LATIN CAPITAL LETTER F'], ['G','LATIN CAPITAL LETTER G'], ['H','LATIN CAPITAL LETTER H'], ['I','LATIN CAPITAL LETTER I'], ['J','LATIN CAPITAL LETTER J'], ['K','LATIN CAPITAL LETTER K'], ['L','LATIN CAPITAL LETTER L'], ['M','LATIN CAPITAL LETTER M'], ['N','LATIN CAPITAL LETTER N'], ['O','LATIN CAPITAL LETTER O'], ['P','LATIN CAPITAL LETTER P'], ['Q','LATIN CAPITAL LETTER Q'], ['R','LATIN CAPITAL LETTER R'], ['S','LATIN CAPITAL LETTER S'], ['T','LATIN CAPITAL LETTER T'], ['U','LATIN CAPITAL LETTER U'], ['V','LATIN CAPITAL LETTER V'], ['W','LATIN CAPITAL LETTER W'], ['X','LATIN CAPITAL LETTER X'], ['Y','LATIN CAPITAL LETTER Y'], ['Z','LATIN CAPITAL LETTER Z'], ['a','LATIN SMALL LETTER A'], ['b','LATIN SMALL LETTER B'], ['c','LATIN SMALL LETTER C'], ['d','LATIN SMALL LETTER D'], ['e','LATIN SMALL LETTER E'], ['f','LATIN SMALL LETTER F'], ['g','LATIN SMALL LETTER G'], ['h','LATIN SMALL LETTER H'], ['i','LATIN SMALL LETTER I'], ['j','LATIN SMALL LETTER J'], ['k','LATIN SMALL LETTER K'], ['l','LATIN SMALL LETTER L'], ['m','LATIN SMALL LETTER M'], ['n','LATIN SMALL LETTER N'], ['o','LATIN SMALL LETTER O'], ['p','LATIN SMALL LETTER P'], ['q','LATIN SMALL LETTER Q'], ['r','LATIN SMALL LETTER R'], ['s','LATIN SMALL LETTER S'], ['t','LATIN SMALL LETTER T'], ['u','LATIN SMALL LETTER U'], ['v','LATIN SMALL LETTER V'], ['w','LATIN SMALL LETTER W'], ['x','LATIN SMALL LETTER X'], ['y','LATIN SMALL LETTER Y'], ['z','LATIN SMALL LETTER Z'], ['{','LEFT CURLY BRACKET'], ['(','LEFT PARENTHESIS'], ['[','LEFT SQUARE BRACKET'], ['<','LESS-THAN SIGN'], ['_','LOW LINE'], ['#','NUMBER SIGN'], ['%','PERCENT SIGN'], ['+','PLUS SIGN'], ['?','QUESTION MARK'], ['"','QUOTATION MARK'], ['\\','REVERSE SOLIDUS'], ['}','RIGHT CURLY BRACKET'], [')','RIGHT PARENTHESIS'], [']','RIGHT SQUARE BRACKET'], [';','SEMICOLON'], ['/','SOLIDUS'], [' ','SPACE'], ['~','TILDE'], ['|','VERTICAL LINE'], ].forEach(t=>{ var r=F(t[1]),ok=r==t[0] //if (!ok) // uncomment to see just errors console.log(r+' ('+t[0]+') '+t[1]+(ok?' OK':' ERROR')) }) console.log('DONE') ``` ``` <pre id=O></pre> ``` [Answer] # [Japt](https://github.com/ETHproductions/Japt), 230 bytes ``` V=U¯2;Ug21 ªU<'R©Ug19 v ªV¥"DI"©`ze¿twâ¿¿¿¿e¿i`u bUs6,8)/2ªUf"GN" ©"<>+=$#%"g`¤grp¤qºnupe`u bV /2 ªUf"T " ©"[]\{}()"g"QSUCAP"bUg6) ªUf" M" ©"!\"?"g"COE"bUg2) ªV¥"CO"©",:@"g"ANE"bUg4) ª" &'*-./\\;~^`_|"g`spaµp¿豢¿Èögrlove`u bV /2 ``` Each `¿` represents an unprintable Unicode char. [Try it online!](http://ethproductions.github.io/japt?v=master&code=Vj1VrzI7VWcyMSCqVTwnUqlVZzE5IHYgqlalIkRJIqlgemWNdHfiBwOHoGWIaWB1IGJVczYsOCkvMqpVZiJHTiIgqSI8Pis9JCMlImdgpGdycKRxum51cGVgdSBiViAvMiCqVWYiVCAiIKkiW11ce30oKSJnIlFTVUNBUCJiVWc2KSCqVWYiIE0iIKkiIVwiPyJnIkNPRSJiVWcyKSCqVqUiQ08iqSIsOkAiZyJBTkUiYlVnNCkgqiIgJicqLS4vXFw7fl5gX3wiZ2BzcGG1cMKX6LGiDMj2Z3Jsb3ZlYHUgYlYgLzI=&input=IlJJR0hUIENVUkxZIEJSQUNLRVQi) Ungolfed: ``` V=Us0,2;Ug21 ||U<'R&&Ug19 v ||V=="DI"&&"zeontwthfofisiseeini"u bUs6,8)/2||Uf"GN" &&"<>+=$#%"g"legrpleqdonupe"u bV /2 ||Uf"T " &&"[]\{}()"g"QSUCAP"bUg6) ||Uf" M" &&"!\"?"g"COE"bUg2) ||V=="CO"&&",:@"g"ANE"bUg4) ||" &'*-./\\;~^`_|"g"spamapashyfusoreseticigrlove"u bV /2 ``` This was really fun. I've split up the character names into several large chunks: ### 0. Take first two letters `V=Us0,2;` sets variable `V` to the first two letters of `U`, the input string. This will come in handy later. ### 1. Capital letters This is the easiest: the capital letters are the only ones that have a character at position 21, which all happen to be the correct letter and case. Thus, `Ug21` is sufficient. ### 2. Lowercase letters Another fairly easy one; the only other name that has a character at position 19 is `RIGHT SQUARE BRACKET`, so we check if the name is comes before `R` with `U<'R`, then if it is (`&&`), we take the 19th char with `Ug19` and cast it to lowercase with `v`. ### 3. Digits These names all start with `DI` (and fortunately, none of the others), so if `V=="DI"`, we can turn it into a digit. The first letters of some of the digits' names are the same, but the first two letters are sufficient. Combining these into one string, we get `ZEONTWTHFOFISISEEINI`. Now we can just take the index `b` of the first two chars in the digit's name with `Us6,8)`and divide by two. ### 4. `SIGN` There are seven names that contain `SIGN`: ``` < LESS-THAN SIGN > GREATER-THAN SIGN + PLUS SIGN = EQUALS SIGN $ DOLLAR SIGN # NUMBER SIGN % PERCENT SIGN ``` First we check that it the name contains the word `SIGN`. It turns out `GN` is sufficient; `Uf"GN"` returns all instances of `GN` in the name, which is `null` if it contains 0 instances, and thus gets skipped. Now, using the same technique as with the digits, we combine the first two letters into a string `LEGRPLEQDONUPE`, then take the index and divide by two. This results an a number from `0-6`, which we can use to take the corresponding character from the string `<>+=$#%`. ### 5. `MARK` There are three characters that contain `MARK`: ``` ! EXCLAMATION MARK " QUOTATION MARK ? QUESTION MARK ``` Here we use the same technique as with `SIGN`. `M` is enough to differentiate these three from the others. To translate to a symbol, this time checking one letter is enough: the character at position 2 is different for all three characters. This means we don't have to divide by two when choosing the correct character. ### 6. `LEFT/RIGHT` This group contains the brackets and parentheses, `[]{}()`. It would be really complicated to capture both `LEFT` and `RIGHT`, but fortunately, they all contain the string `T`. We check this with the same technique as we did with `SIGN`. To translate to a symbol, as with `MARK`, checking one letter is enough; the character at position 6 is unique for all six. ### 7. `CO` The rest of the chars are pretty unique, but not unique enough. Three of them start with `CO`: `COMMA`, `COLON`, and `COMMERCIAL AT`. We use exactly the same technique as we did with the brackets, choosing the proper symbol based on the character at position 4 (`A`, `N`, or `E`). ### 8. Everything else By now, the first two characters are different for every name. We combine them all into one big string `SPAMAPASHYFUSORESETICIGRLOVE` and map each pair to its corresponding char in `&'*-./\;~^`_|`. ### 9. Final steps Each of the parts returns an empty string or `null` if it's not the correct one, so we can link them all from left to right with `||`. The `||` operator returns the left argument if it's truthy, and the right argument otherwise. Japt also has implicit output, so whatever the result, it is automatically sent to the output box. Questions, comments, and suggestions welcome! [Answer] # Python 2, 237 bytes Get the hash of the string and modulo divide it by 535. Subsequently convert it to a unicode character with that number. The position of the unicode character in a precompiled list of unicode characters is subsequently converted to the ascii character. ``` print chr(u"""ǶŀȎdȊÏöǖIhȏƜǓDZǠƣƚdžƩC+ĶÅĠěóƋŎªƱijůŰűŪūŬŭŶŷŸŹŲųŴŵžſƀƁźŻżŽƆƇƈŖÐŗǀǼǿǾǹǸǻǺȅȄȇȆȁȀȃȂǭǬǯǮǩǨǫǪǵǴǷNȌ~B""".index(unichr(hash(raw_input())%535))+32) ``` [Answer] # Javascript, ~~501~~ ~~499~~ ~~469~~ ~~465~~ ~~451~~ 430 bytes ``` a=prompt();c="5SACEgEARKeQARKbNIGNbDIGNcPIGN9AANDaAPHEgLSIShRSIS8AISK9PIGN5CMMAcHNUS9FTOP7SDUSaDERO9DONE9DTWObDREEaDOURaDIVE9DSIXbDVENbDGHTaDINE5CLON9SLONeLIGNbEIGNhGIGNdQARKdC ATjLKETfRDUSkRKEThCENT8LINEcGENTiLKETdVINEjRKET5TLDE".match(/.{5}/g).indexOf(a.length.toString(36)+a[0]+a.slice(-3));if(c>=33)c+=26;if(c>=65)c+=26;alert(a.length==20&&a[0]=="L"?a.slice(-1).toLowerCase():a.length>21?a.slice(-1):String.fromCharCode(32+c)) ``` # Explanation: That long string is a compressed list. `a.length.toString(36)+a[0]+a.slice(-3)` determines how, if at all, the string will be represented in the list. Also, special logic for letters. (with strings, `a[0]` is a builtin shorthand for `a.charAt(0)`, by the way) [Answer] ## PowerShell, ~~603~~ ~~547~~ 464 bytes ``` $a=-split$args $b=switch -W($a[0]){ "LEFT"{switch -w($a[1]){"C*"{"{"}"P*"{"("}"S*"{"["}}} "RI*"{switch -w($a[1]){"C*"{"}"}"P*"{")"}"S*"{"]"}}} "LA*"{("$($a[3])".ToLower(),$a[3])[$a[1]-like"C*"]} "DI*"{@{ONE=1;TWO=2;THREE=3;FOUR=4;FIVE=5;SIX=6;SEVEN=7;EIGHT=8;NINE=9;ZERO="0"}[$a[1]]} "COMME*"{"@"} "APO*"{"'"} } $c='COM,LES<GRA`GRE>QUE?QUO"COL:REV\LOW_EXC!EQU=DOL$AMP&AST*PER%PLU+SEM;SOL/SPA CIR^HYP-FUL.NUM#TIL~VER|' ($b,$c[$c.IndexOf($a[0][0..2]-join'')+3])[!$b] ``` (`LineFeed` counts the same one byte as `;`, so I'll leave the breaks in for readability) Edit 1 - Took many elements out of the switch statement and instead populated a hashtable for lookups. Edit 2 - Oh yeah ... indexing into a string, that's the way to go ... Essentially takes the input, splits it on spaces, and does a wildcard `switch` on the first word to filter out the goofy ones. Sets the result of that to `$b`. If `$b` doesn't exist, the string `$c` gets evaluated on the first three letters of the first word and outputs the character immediately following, otherwise we output `$b`. Some tricks include the `LATIN CAPITAL LETTER R` which indexes into an array based on whether the second word is `CAPITAL`, and outputs the corresponding uppercase/lowercase letter. The other "trick" is for the `DIGIT`s, by indexing into a hashtable. Note that it's not shorter to do the same index-into-a-string trick here (it's actually longer by one byte). [Answer] ## Javascript, ~~416~~ ~~411~~ 389 bytes ``` l=(E)=>{return E=E.replace(/LA.*N|BR.*T|SIGN|MARK| |TION/g,"").replace(/(.).*(.{3})/,"$1$2"),E.match("CER")?E[3]:E.match("SER")?E[3].toLowerCase():(a="SACE EAMA!QOTA\"NBER#DLAR$PENT%AAND&APHE'AISK*PLUS+CMMA,HNUS-FTOP.SDUS/CLON:SLON;LHAN<EALS=GHAN>QUES?CLAT@RDUS\\CENT^LINE_GENT`VINE|LSIS(RSIS)LARE[RARE]LRLY{RRLY}TLDE~DERO0DONE1DTWO2DREE3DOUR4DIVE5DSIX6DVEN7DGHT8DINE9",a[a.indexOf(E)+4])} ``` This is a more readable format(explanation coming later): ``` function l(k){ k=k.replace(/LA.*N|BR.*T|SIGN|MARK| |TION/g,'').replace(/(.).*(.{3})/,'$1$2') if(k.match('CER')) return k[3]; if(k.match('SER')) return k[3].toLowerCase(); a="SACE EAMA!QOTA\"NBER#DLAR$PENT%AAND&APHE'AISK*PLUS+CMMA,HNUS-FTOP.SDUS/CLON:SLON;LHAN<EALS=GHAN>QUES?CLAT@RDUS\\CENT^LINE_GENT`VINE|LSIS(RSIS)LARE[RARE]LRLY{RRLY}TLDE~DERO0DONE1DTWO2DREE3DOUR4DIVE5DSIX6DVEN7DGHT8DINE9" return a[a.indexOf(k)+4]; } ``` Minus 5 bytes from combining key and value strings. **Explanation:** The regular expressions on the first line reduce the inputs into unique 4 character keys. Note that uniqueness is only guaranteed for the specific set of names specified in the challenge, and duplicates would be very common for normal English! Even for this challenge, I had to remove common words like bracket and sign to get a unique set. To return the character, I check to see if it's a latin character by check for the strings "SER" and "cer", and return the last character of the input, in lowercase for ser. For everything else, I refer to a string that contains all of the 4 character keys, followed by the correct character. I then use indexof and ~~substring~~ character indices to pull and return the character. **Edit:** Used more wildcards to reduce regex size, replaced substr with character indices and shaved off antoher twenty chars. Rule sticklers will note that this final update is posted after the challenge has ended, however I don't think it changed my ranking. This is just practice for a novice. [Answer] # Python 3, 148 bytes ``` lambda s:chr(83-b'gfhtg\32}urgx_}3qeo|e~cwu~S~q~I,vqG\34jc}d*9~~_L|p~~~~~JJy'[sum(b' !" *1! "2;D$# ! # !!( '[ord(c)%25]-32for c in s[:-1])]+ord(s[-1])) ``` For your viewing convenience, I’ve replaced two non-printable bytes with the octal escape codes `\32` and `\34`; undo this to get the 148 byte function. I computed parts of this hash function with [GPerf](https://www.gnu.org/software/gperf/). [Answer] # [Perl 6](http://perl6.org), ~~348~~ 242 bytes ``` { /NI/??9!!chr 32+ '0A40W00SV0M20LR0O20IJ0LH0WH0YS0H20ID0A50P10IH0F70K10HF0I30LL0JX0JF0HX0LU0LE0JF0AJ0IX0RK0M40XF0QR0PD15Z16016116216316416516616716816916A16B16C16D16E16F16G16H16I16J16K16L16M16N16O1140V313F0XS0FU0N712A12B12C12D12E12F12G12H12I12J12K12L12M12N12O12P12Q12R12S12T12U12V12W12X12Y12Z0ZA0PU11L0AA' .comb(3).map({:36($_)}).first(:k,[+] .ords) } # 348 ``` ``` {chr 32+"\x95ǐǠŬšƉĘŗȌȴĎĽ\x96ŖŁöģěĈśŊčĂĹŔĸ¤ĦƱŮȃƿƍʶʷʸʹʺʻʼʽʾʿˀˁ˂˃˄˅ˆˇˈˉˊʠʡʢʣʤɝǚʅǥâĿʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛɱɲɳɴɵțųɃ\x9b".ords.first: :k,[+] .ords.map(*%43)} ``` ``` { chr 32+ "\x95ǐǠŬšƉĘŗȌȴĎĽ\x96ŖŁöģěĈśŊčĂĹŔĸ¤ĦƱŮȃƿƍʶʷʸʹʺʻʼʽʾʿˀˁ˂˃˄˅ˆˇˈˉˊʠʡʢʣʤɝǚʅǥâĿʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛɱɲɳɴɵțųɃ\x9b" .ords.first: :k,[+] .ords.map(*%43) } ``` usage: ``` my &code = {...} # testing my $test = [~] (' '..'~')».uniname».&code; my $comparison = [~] ' '..'~'; say $test eq $comparison; # True say code 'HYPHEN-MINUS'; # - ``` ]
[Question] [ ## Similar figures Two rectangles are *similar* if the ratios of their sides are the same. Consider these two rectangles; a rectangle 5 lines tall and 11 chars wide: ``` =========== =========== =========== =========== =========== ``` and a rectangle 10 lines tall and 22 chars wide: ``` ====================== ====================== ====================== ====================== ====================== ====================== ====================== ====================== ====================== ====================== ``` These shapes are similar because the ratios of their sides are the same. To put it formally (with \$h\$ being the shortest side and \$w\$ being the longest side): $$ \frac{h\_1}{w\_1} = \frac{h\_2}{w\_2} $$ You can also do: $$ \frac{h\_1}{h\_2} = \frac{w\_1}{w\_2} $$ ## The challenge Write a program or function that takes a "main" rectangle and some "other" rectangles and prints which of "others" are similar to "main". ## The input A shape and a list of shapes. Each shape consists of 2 non-zero positive integers, which denote the width and height of the rectangle. For instance, this: ``` (4,2), (3,9) ``` denotes two rectangles, a 4x2 and a 3x9. The exact format of the input may be however you desire. ## The output The indices of the "other" shapes that are similar to "main". You may choose whether the indices are 0- or 1-based, as well as the exact format and order of the output. ## Sample program In Python: ``` main = eval(raw_input()) # The main rectangle. rects = eval(raw_input()) # The list of rectangles. similar = set() for i, rect in enumerate(rects): if max(main)*min(rect) == min(main)*max(rect): # Cross-multiply # They are similar. similar.add(i) print similar ``` ## Sample input and output Input: ``` (1, 2) [(1, 2), (2, 4)] ``` Output: ``` set([0, 1]) ``` Input: ``` (1, 2) [(1, 9), (2, 5), (16, 8)] ``` Output: ``` set([2]) ``` ## Winning This is code-golf, so the shortest submission wins. ## Notes * This should go without saying, but **standard loopholes are banned**. * **No builtins for locating similar figures may be used.** (I don't even know if that exists, but I would't be surprised!) [Answer] ## Python, 61 bytes ``` lambda a,b,l:[i for i,(x,y)in enumerate(l)if x/y in[a/b,b/a]] ``` Yes, I'm using spending 9 chars to write `enumerate`. Takes input like `1, 2, [(1, 9), (3,6), (2, 5), (16, 8)]`. For Python 2, input values need to be written as floats. One char longer (62) in Python 3: ``` def f(a,b,l,i=0): for x,y in l:b/a!=x/y!=a/b or print(i);i+=1 ``` [Answer] # CJam, ~~22~~ ~~20~~ 19 bytes ``` {:$::/_0=f=ee::*0-} ``` The above is an anonymous function that pops a single array of floating point pairs (first pair is needle) from the stack and pushes the array of 1-based indexes in return. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%7B%3A%24%3A%3A%2F_0%3Df%3Dee%3A%3A*0-%7D~p&input=%5B%5B1.0%202.0%5D%20%5B1.0%209.0%5D%20%5B2.0%205.0%5D%20%5B16.0%208.0%5D%5D). ### How it works ``` :$ e# Sort each pair. ::/ e# [a b] -> a/b _0= e# Push a copy of the array and extract the first float (needle). f= e# Check which floats are equal to the needle. ee e# Enumerate the resulting Booleans. ::* e# Multiply each Boolean by its index. e# This yields 0 for the needle (index 0) and for non-matching e# haystack pairs (Boolean 0). 0- e# Remove all zeroes from the array. ``` [Answer] # [Haskell](https://www.haskell.org/), 48 bytes ``` (a!b)l=[i|(i,(x,y))<-zip[0..]l,x/y+y/x==a/b+b/a] ``` [Try it online!](https://tio.run/##FcVBCsIwEAXQq/yCixk6NqZiqWBOErJIQHAwlqJdJOLdI32b94if5z3n1ih2ibPz@iMVKlKZb8evrv40DCFLMbWvpjgXTeqTiaG9oi5wWN@6bDiAOobFCE9WcGUBnWXaGwWXfTsJZg7tDw "Haskell – Try It Online") Call this like `(!) 1 2 [(1, 9), (3,6), (2, 5), (16, 8)]`. A near-port of my [Python answer](https://codegolf.stackexchange.com/a/56040/20260). The expression `zip[0..]l` enumerates the list with its indices. The expression `x/y+y/x==a/b+b/a` checks that the ratio `x/y` is either `a/b` or `b/a`, since the function `f(z) = z + 1/z` has `f(z) = f(1/z)` and no other collisions. [Answer] ## [Snowman 1.0.2](https://github.com/KeyboardFire/snowman-lang/releases/tag/v1.0.2-beta), 61 chars ``` }vgvgaC"[0-9]+"sM:10sB;aM2aG:AsO:nD;aF;aM0AAgaA*|:#eQ;AsItSsP ``` Pure gibberish (unless you happen to know Snowman), a.k.a. [exactly in line with the language's design goal](https://github.com/KeyboardFire/snowman-lang/blob/57913d7894b744914d8ec660dcb70adfc5d3035b/doc/snowman.md) of being as confusing as possible. Input format is same as in the post, output format is also the same minus `set(` and `)`. Ungolfed (or unminified, really): ``` }vgvgaC // read two lines of input, concatenate "[0-9]+"sM // use a regex to grab all numbers :10sB;aM // essentially map(parseInt) 2aG // take groups of 2 (i.e. all the ordered pairs) // now map over each ordered pair... : AsO // sort :nD;aF // fold with division - with 2 array elements, this is just a[0]/a[1] ;aM // we now have an array of short side to long side ratios // take out the first one 0AAgaA // active vars beg, b=array[0], g=the rest *| // store first ordered pair in permavar, bring the rest to top // select indices where... : # // retrieve first ordered pair eQ // equal? ;AsI tSsP // to-string and output ``` I'm pretty proud of some of the tricks I used in this one: * I used the same input format as in the post. But instead of trying to parse it somehow, which would get really messy, I just concatenated the two lines and then used a regex to extract all the numbers into one big array (with which I then did `2aG`, i.e. get every group of 2). * `:nD;aF` is pretty fancy. It simply takes an array of two elements and divides the first one by the second one. Which seems pretty simple, but doing it the intuitive way (`a[0]/a[1]`) would be far, far longer in Snowman: `0aa`NiN`aA|,nD` (and that's assuming we don't have to worry about messing with other existing variables). Instead, I used the "fold" method with a predicate of "divide," which, for an array of two elements, achieves the same thing. * `0AAgaA` looks innocuous enough, but what it actually does is store a `0` to the variables, then takes all variables with an index greater than that (so, all variables except for the first one). But the trick is, instead of `AaG` (which would get rid of the original array and the `0`), I used `AAg`, which keeps both. Now I use `aA`, at-index, using the *very same `0`* to get the first element of the array—furthermore, this is in consume-mode (`aA` instead of `aa`), so it gets rid of the `0` and original array too, which are now garbage for us. Alas, `0AAgaA*|` does essentially the same thing that GolfScript does in one character: `(`. However, I still think it's pretty nice, by Snowman standards. :) [Answer] # Pyth, 15 bytes ``` fqcFS@QTcFSvzUQ ``` [Answer] # Mathematica, 41 bytes ``` Position[a=Sort@#;Sort@#/a&/@#2,{x_,x_}]& ``` Usage: ``` Position[a = Sort@#; Sort@#/a & /@ #2, {x_, x_}] &[{1, 2}, {{1, 2}, {2, 5}, {16, 8}}] (* {{1}, {3}} *) ``` [Answer] # Pyth - 14 bytes Filters by comparing quotients, then maps `indexOf`. ``` xLQfqcFSTcFvzQ ``` [Test Suite](http://pyth.herokuapp.com/?code=xLQfqcFSTcFvzQ&input=%281%2C+2%29%0A%5B%281%2C+2%29%2C+%282%2C+4%29%5D&test_suite=1&test_suite_input=%281%2C+2%29%0A%5B%281%2C+2%29%2C+%282%2C+4%29%5D%0A%281%2C+2%29%0A%5B%281%2C+9%29%2C+%282%2C+5%29%2C+%2816%2C+8%29%5D&debug=0&input_size=2). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~16~~ 13 [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") ``` (=.×∘⌽∨=.×)⍤1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X8NW7/D0Rx0zHvXsfdSxAsTRfNS7xPB/2qO2CY96@x71TfX0f9TVfGi98aO2iUBecJAzkAzx8Az@b6hgpJCmYKpg9Kh3C4htpGCiYKhgCaRNFQzNFCwA "APL (Dyalog Unicode) – Try It Online") -3 thanks to @ngn! Explanation: ``` (=.×∘⌽∨=.×)⍤1 ( ∨ ) ⍝ "OR" together... =. =. ⍝ ...fold by equality of: ×∘⌽ ⍝ - the arguments multiplied by itself reversed x ⍝ - the argument multiplied by itself ⍤1 ⍝ Applied at rank 1 (traverses) ``` Output format is a binary vector like `1 1 0 0 1` of which "other" rectangle is a look-a-like. # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 11 [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") ``` =/-×⍥(⌈/)¨⌽ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/31Zf9/D0R71LNR71dOhrHlrxqGfv/7RHbRMe9fY96pvq6f@oq/nQeuNHbROBvOAgZyAZ4uEZ/D9NQcNQwUhTQcNUwehR7xYgGwhNFAwVLIG0qYKhmYKFJgA "APL (Dyalog Extended) – Try It Online") Explanation: ``` =/-×⍥(⌈/)¨⌽ ⍝ takes only a right argument: ⍵, shape: (main (other...)) ⌽ ⍝ two transformations: - ⍝ - left (L) vectorized negation: -⍵ ⌽ ⍝ - right (R): reverse. (main other) => (other main) (⌈/)¨ ⍝ transformation: calculate the max (since L is negated, it calculates the min) ⍝ (/ reduces over ⌈ max) ⍝ this vectorizes, so the "main" side (with only one rect) will get repeated once for each "other" rect on both sides ×⍥ ⍝ over multiplication: apply the transformation to both sides. F(L)×F(R) =/ ⍝ reduce the 2-element matrix (the "main" that's now the side of the "other") to check which are equal ``` Output format is the same as the main Dyalog answer. Thanks to Adám for the help golfing + Extended. [Answer] # Julia, 62 bytes ``` f(m,o)=find([(t=sort(m).*sort(i,rev=true);t[1]==t[2])for i=o]) ``` The `find` function locates true elements in a boolean vector. `.*` performs elementwise multiplication of vectors. Ungolfed: ``` function f(m::Array, o::Array) find([(t = sort(m) .* sort(i, rev=true); t[1] == t[2]) for i in o]) end ``` Usage: ``` f([1,2], {[1,9], [2,5], [16,8]}) ``` [Answer] # K5, 19 bytes I think this will do the trick: ``` &(*t)=1_t:{%/x@>x}' ``` Takes a list of pairs where the first is the "main". Computes the ratio by dividing the sorted dimensions of each pair. Returns a list of the 0-indexed positions of the matching pairs. (arguably the input format I chose makes this -1 indexed- if this is considered invalid tack on a `1+` to the beginning and add two characters to the size of my program.) Usage example: ``` &(*t)=1_t:{%/x@>x}'(1 2;1 2;2 4;2 5;16 8) 0 1 3 ``` This runs in [oK](http://johnearnest.github.io/ok/index.html)- note that I implicitly depend on division always producing floating point results. It would work in Kona if you added a decimal point to all the numbers in the input and added a space after the `_`. [Answer] # Octave / Matlab, 44 bytes Using an anonymous function: ``` @(x,y)find((max(x))*min(y')==min(x)*max(y')) ``` The result is in 1-based indexing. To use it, define the function ``` >> @(x,y)find((max(x))*min(y')==min(x)*max(y')); ``` and call it with the following format ``` >> ans([1 2], [1 9; 2 5; 16 8]) ans = 3 ``` You can [try it online](http://ideone.com/cURDeg). --- If the result can be in **logical indexing** (`0` indicates not similar, `1` indicates similar): **38 bytes**: ``` @(x,y)(max(x))*min(y')==min(x)*max(y') ``` Same example as above: ``` >> @(x,y)(max(x))*min(y')==min(x)*max(y') ans = @(x,y)(max(x))*min(y')==min(x)*max(y') >> ans([1 2], [1 9; 2 5; 16 8]) ans = 0 0 1 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes ``` z{iXhpᵐ/ᵛ∧Xt}ᵘ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv6o6MyKjAMjSf7h19qOO5RElQOEZ//9HA4GhjlFsrA6E1ok20jGJBXORxC3B4qZA0tBMxwIoHQsA "Brachylog – Try It Online") Takes input as a list *containing a list containing* the main rectangle and the list of other rectangles (so test case 1 is `[[[1,2]],[[1,2],[2,4]]]`), and outputs a list of 0-based indices through the output variable. ``` z Zip the elements of the input, pairing every "other" rectangle with the main rectangle. { }ᵘ Find (and output) every unique possible output from the following: iX X is an element of the zip paired with its index in the zip. h That element ᵐ with both of its elements p permuted ᵛ produces the same output for both elements / when the first element of each is divided by the second. ∧Xt Output the index. ``` If that sort of odd and specific input formatting is cheating, it's a bit longer... # [Brachylog](https://github.com/JCumin/Brachylog), 18 bytes ``` {hpX&tiYh;X/ᵛ∧Yt}ᶠ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wvzqjIEKtJDMywzpC/@HW2Y86lkeW1D7ctuD//@joaEMdo1gdGGWkYxIbi@ACKUuwqCmQNDTTsQBKxgIA "Brachylog – Try It Online") Takes input as a list containing the main rectangle and the list of other rectangles (so test case 1 is the more obvious `[[1,2],[[1,2],[2,4]]]`), and outputs a list of 0-based indices through the output variable. ``` { }ᵘ Find (and output) every possible output from the following: p A permutation of h the first element of the input X is X, & and i a pair [element, index] from t the last element of the input Y is Y, h the first element of which ᵛ produces the same output from / division ; as X X. ∧Yt Output the index. ``` To determine if two width-height pairs represent similar rectangles, it just takes the four bytes `pᵐ/ᵛ` (which outputs the shared ratio or its reciprocal). All the rest is handling the multiple rectangles to compare, and the output being indices. [Answer] # [dzaima/APL](https://github.com/dzaima/APL), 7 bytes ``` =/⍤÷⍥>¨ ``` [Try it online!](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsZ/W/1HvUsOb3/Uu9Tu0Ir/mv81HnU1GSoYaSqkKWiAaQ0jBRNNENsSzDYFsc0ULDT/5ReUZObnFf/XLQYA "APL (dzaima/APL) – Try It Online") [8 bytes](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsb/R707bPUf9S45vP1R71K7Qyv@a/7XeNTVZKhgpKmQpqABpjWMFEw0QWxLMNsUxDZTsND8l19QkpmfV/xftxgA) outputting a list of indices instead of a boolean vector ``` ¨ for each (pairing the left input with each of the right) ⍥> do the below over sorting the arguments =/ equals reduce ⍤ after ÷ vectorized division of the two ``` [Answer] # Haskell, 75 bytes ``` import Data.List a(x,y)=max x y/min x y s r=elemIndices(True).map((==a r).a) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 57 bytes ``` $args|%{$x,$y=$_|sort ($i++)[$r-$y/$x] if(!$r){$r=$y/$x}} ``` [Try it online!](https://tio.run/##jYxhS8MwEIa/51ec2U0SlqId61ChkP8hMuJ6nYGydUnEjra/va6Zrvsk3pe7e3iftz58kfMfVFUDlnk7oHE7381bbBSectx0/uACE2gXC/mKLsHTAzZvzJbiDp1s0eWR9P3QMzYDuy/sljwYR5Am78ZTwbRgcB4ltEjVUq2kgnhNW4uItcjU8@VLpbxKY3CcSVqqbIyla/V0k/tn@QgnaXVTnv0hPUZLQgdzaKON1NS0DVQoQAM54OaCHfnPKpzBPZagDczA15UJwe53McBR8J8QT@jIrz1cvvzanPVs@AY "PowerShell – Try It Online") Indices are 1-based. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~58~~ 56 bytes -2 bytes thanks to mazzy x2 ``` param($x,$y,$b)$b|%{($i++)[$x/$y-($z=$_|sort)[0]/$z[1]]} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/b8gsSgxV0OlQkelUkclSVMlqUa1WkMlU1tbM1qlQl@lUldDpcpWJb6mOL@oRDPaIFZfpSraMDa29n8tF5eaSpqCoYKRgoaGoY6Rpo6GkY4JkDTVsQSSIBFNLiUlJEVGOqYgCTMdC3QZgtpNsSsyAKn6DwA "PowerShell – Try It Online") This slightly abuses the `input may be however you desire` clause by having the first shape's components come separately to save 3 bytes. # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~61~~ 59 bytes ``` param($a,$b)$b|%{($i++)[$a[0]/$a[1]-($x=$_|sort)[0]/$x[1]]} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/b8gsSgxV0MlUUclSVMlqUa1WkMlU1tbM1olMdogVh9IGsbqaqhU2KrE1xTnF5VogkUrgKKxtf9rubjUVNIUNAx1jDQVNMCUjoaRjgmQNNWxBJJmOsaamlxKSijKjHRMgVKGZjoWmHKYRoBEiFX2HwA "PowerShell – Try It Online") Uses conditional indexing to swap between the current zero-based index and null based on whether or not the ratios line up. Luckily in this case, `$i` increments regardless of it being printed or not. [Answer] # Javascript (ES6), 75 ``` (a,b)=>b.filter(e=>e.l*a.h==a.l*e.h||e.l*a.l==a.h*e.h).map(e=>b.indexOf(e)) ``` Alternative, also 75 ``` (a,b)=>b.map((e,i)=>e.l*a.h==a.l*e.h||e.l*a.l==a.h*e.h?i:-1).filter(e=>e+1) ``` Input is taken as a JSON object, and an array of JSON objects ``` { l: length of rectangle, h: height of rectangle } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ʒ‚ε{ü/}Ë}J¹Jsk ``` [Try it online](https://tio.run/##yy9OTMpM/f//1KRHDbPOba0@vEe/9nB3rdehnV7F2f//R0cb6hjF6kQb6ZjExnKBOQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmWCvpJCYl6KgZA9kPGqbBGRUJoS6hP0/NSniUcOsc1urD@/Rrz3cXesV6VWc/V/nfzQQGOoYxepEG@mYxMbqKIB5QFoBLGEJljAFkoZmOhYI@VgA). **Explanation:** ``` ʒ # Filter the (implicit) input-list by: ‚ # Pair the current width/height with the (implicit) input width/height ε # Map both width/height pairs to: { # Sort from lowest to highest ü/ # Pair-wise divide them from each other }Ë # After the map: check if both values in the mapped list are equals }J # After the filter: join all remaining pairs together to a string ¹J # Also join all pairs of the first input together to a string s # Swap to get the filtered result again k # And get it's indices in the complete input-list # (which is output implicitly) ``` The `J`oins are there because 05AB1E can't determine the indices on multidimensional lists a.f.a.i.k. --- If outputting the width/height pairs that are truthy, or outputting a list of truthy/falsey values based on the input-list, it could be **8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** instead: ``` ʒ‚ε{ü/}Ë ``` [Try it online](https://tio.run/##yy9OTMpM/f//1KRHDbPOba0@vEe/9nD3///R0YY6lrE60UY6pkDS0EzHIjaWCyhmFAsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmWCvpJCYl6KgZA9kPGqbBGRUJoS6hP0/NSniUcOsc1urD@/Rrz3c/b9W5380EBjqGMXqRBvpmMTG6iiAeUBaASxhCZYwBZKGZjoWCPlYAA). ``` ε‚ε{ü/}Ë ``` [Try it online](https://tio.run/##yy9OTMpM/f//3NZHDbPOba0@vEe/9nD3///R0YY6lrE60UY6pkDS0EzHIjaWCyhmFAsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmWCvpJCYl6KgZA9kPGqbBGRUJoS6hP0/tzXiUcOsc1urD@/Rrz3c/b9W5380EBjqGMXqRBvpmMTG6iiAeUBaASxhCZYwBZKGZjoWCPlYAA). [Answer] # [Uiua](https://www.uiua.org/), 10 bytes ``` ⊚↥∩/=⊃×÷⊙⍉ ``` [Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4oqa4oi6KOKGpeKIqS894oqDJ8OX4oeMw5cpCmYg4oaQIOKKmuKIuigvPcOX4oa74omF4oip4o2PLCwpCmYg4oaQIOKKmuKGpeKIqS894oqDJ8OX4oeMw5fiipnijYkKZiDihpAg4oqa4oi6KOKGpeKIqS894oqDw5fDtykKZiDihpAg4oqa4oal4oipLz3iioPDl8O34oqZ4o2JCmYgMV8yIFsxXzIgMl80IDNfNSAxNl84XQpmIDNfNSBbMV8yIDE1XzkgM181IDE2Xzhd) -2 if I can take the second input transposed. ``` ⊚↥∩/=⊃×÷⊙⍉ input: a shape S, a list of shapes M (2d matrix with two columns) ⊙⍉ transpose the 2nd input ⊃×÷ fork(mul, div): take S and M and give S*M and S/M the operations are done between each item of S and each row of M ∩/= both(reduce by equal): for each of the two matrices, compare the two rows elementwise and give 1 when equal for similar shapes, * gives 1 if in reverse order, / otherwise ↥ boolean OR of the two vectors ⊚ vector of indices of ones ``` ]
[Question] [ Your input is an array of numbers: a [permutation](https://en.wikipedia.org/wiki/Permutation) of \$\{1, 2 \dots n\}\$ for some integer \$n \geq 2\$. How many times must you repeat this list before you can "pick out" the numbers \$[1, 2 \dots n]\$ in order? That is: find the lowest \$t \geq 1\$ so that \$[1, 2 \dots n]\$ is a [subsequence](https://en.wikipedia.org/wiki/Subsequence) of \$\text{repeat}(\text{input}, t)\$. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): write the shortest program or function that accepts a list of numbers and produces \$t\$. ## Example For `[6,1,2,3,5,4]`, the answer is `3`: ``` 6,1,2,3,5,4 6,1,2,3,5,4 6,1,2,3,5,4 ^ ^ ^ ^ ^ ^ ``` ## Test cases ``` [2,1] -> 2 [3,2,1] -> 3 [1,2,3,4] -> 1 [4,1,5,2,3] -> 2 [6,1,2,3,5,4] -> 3 [3,1,2,5,4,7,6] -> 4 [7,1,8,3,5,6,4,2] -> 4 [8,4,3,1,9,6,7,5,2] -> 5 [8,2,10,1,3,4,6,7,5,9] -> 5 [8,6,1,11,10,2,7,9,5,4,3] -> 7 [10,5,1,6,11,9,2,3,4,12,8,7] -> 5 [2,3,8,7,6,9,4,5,11,1,12,13,10] -> 6 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Ụ>ƝS‘ ``` [Try it online!](https://tio.run/##LY47DsJADEQv5CLe/za0HIAySkmDcgE6RENPlYaOkgsg6FC4R3IRM/YirWTPG2tmD/txPIosr/vme9utp0nm9@eynh/zdXlOmHhbkd4RD9R7apMxPQVsgZiiKuyJGo/meFPYKVOCztDF3ATmQAqmXlWQrCnG0NABIv6Pq2ENZ1bPgVYL1lKACCupWdu3iB2aMkyVRfthBb1jTUEDarvhBw "Jelly – Try It Online") ``` Ụ -- Grade up. Indices that would sort the input >Ɲ -- For each pair of adjacent values, is the left larger than the right? S -- Sum the boolean results ‘ -- Increment by 1 ``` [Answer] # [Python 3](https://docs.python.org/3/), 36 bytes ``` f=lambda x,*p:p==()or(x-1in p)+f(*p) ``` [Try it online!](https://tio.run/##RY5LbsMwDET3OgV3kVKmMCV/A7gXEbpw0QQR4NhCqrTp6V1SjtHlzDwOJ/6myzy5ZTn343D9@Bzggft4jH2vzXzTjwOFCaJ5Oet9NMvPJYwnoKOCMEWE@Z4i9HAdoj59DyOKe0/avH7FMSS9g8Mb7IxREG9hSpo7GDDrnVm8RXoXxCrvcBNOeWLhsMySlC@RsBJrg2tcierJOLkXiw1ssM5mqXzDZpu5mgO72S0L4Tu2G2nOQSUBjyg44efPrPvP5CuRAJajLj9bJzU8uWBNwkhvno9k@XuzFYjXyjrOS4FJ@vghTykyVP8B "Python 3 – Try It Online") The number of repeats needed is equal to the number of pairs `x` and `x+1` such that the `x+1` appears before `x` in the permutation, plus one. [Answer] # [Julia 1.0](http://julialang.org/), 30 bytes ``` a->sum(diff(sortperm(a)).<0)+1 ``` [Try it online!](https://tio.run/##ZZBBDoIwEEX3nILEDY2jYVpoaaLGexgWJErESDAg0dvXmYJCcPv@m@mf3vp7VeDbleHeFZtD19fRuSrLqGva5@PS1lEhxHYXizW6Y3dtXmEZnSRgLsJVKIMfUvCFaoJIUEHiMU44AYSUo@USDcNEOs6o@X6OKAAD2ofJFBoKMz@nSZDLOCPI85Ziwy97IZ0LVD4mg8qOjv13uB0ii5IU68sMJ5jZyTFxZJff8@cDSmpnFgv5FxVzci1Jqd/NLlLXOBes68B9AA "Julia 1.0 – Try It Online") -2 bytes thanks to @dingledooper. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` ⇧¯0<∑› ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLih6fCrzA84oiR4oC6IiwiIiwiWzgsNiwxLDExLDEwLDIsNyw5LDUsNCwzXSJd) Port of ovs's jelly answer. ``` ⇧ # Grade up ¯0< # Cumulative differences less than 0 ∑› # Sum + 1 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~33~~ ~~31~~ 30 bytes -1 thanks to [alephalpha](https://codegolf.stackexchange.com/questions/242303/how-many-laps-around-the-permutation/242316?noredirect=1#comment545953_242316) ``` Count[#-##2&@@@#~Subsets~2,1]& ``` [Try it online!](https://tio.run/##LY7BCoMwEETv/kbA0xZM1GgOLYH@QIvH4sGKUg9aqPEk@ut2NvE282bY2bFxn25s3NA2R3897t9lci9xEULF1lqxV8t77ty8K5J1fDyXoXP28Rt86dZbUcd71TbTvkYrKhtFa0qnkBApZSwzkpSzZaMpJHnIUm9hqCDNoAAofa4BFaMSgnsGqOBLAWIoAcXIyU3gvCAlhwrY@ON@GiRHpjk14T2SCmsFp@xL/gJZxkXJdzCC6WSLtuMP "Wolfram Language (Mathematica) – Try It Online") Input `[list]`. Doesn't work for \$n=1\$, but we're guaranteed \$n\ge 2\$. --- ### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~37~~ 36 bytes ``` Tr@Boole[Set@a;Set[a,#,a]!=#-1&/@#]& ``` [Try it online!](https://tio.run/##LY5BCoMwEEX33qIEXI3URI1KsUhPULA7cRFEqVAVxJ3o1dM/xk2Y/16YP6NZv91o1qE1ti/sZylf8/zr6qpbS/PAWxsSZJpbIQLp30vR@Pa9DNNai@DZczyq1kzH5m2K5E7eFtE1SAwRxTzGJCnhyEGTM4lz0RkRKCXNIAXITq8BFaMMA//LgVLe5CCKQlCUXDx3nBukZKmA83P5WQ2SwGm2uTuPpEJbypZzxlfAxfxR8h6UoDrcvd3@AQ "Wolfram Language (Mathematica) – Try It Online") The number of repeats is also equal to the number of prefixes `...,x` that don't contain `x-1`. ``` Set@a; clear prefix &/@# for each: #-1 predecessor Set[a,#,a]!= not in prefix Tr@Boole[ ] count ``` [Answer] # [R](https://www.r-project.org/), 34 bytes ``` function(l)sum(diff(order(l))<0)+1 ``` [Try it online!](https://tio.run/##JchBCoAgEEDRfadoOUMGjVoL8TbagFAKluefDFef96vw7FfhlsObSoYLn3ZDTMxQajxrH@g3XEgYtCOcGMwIOfsngFWkdqWVweGju6s/iygf "R – Try It Online") Port of e.g., [Sundar R's answer](https://codegolf.stackexchange.com/a/242308/67312). # [R](https://www.r-project.org/), ~~77~~ ~~69~~ 67 bytes ``` function(l){while(all(combn(rep(l,T),max(l),is.unsorted)))T=T+1 +T} ``` [Try it online!](https://tio.run/##JclBCsIwFIThfU/h8g19Cmmji1JvkQvUmGDgNZG0RUE8e4x09fPN5OIP47H4Ldo1pEiCz@sRxNEkQjbNt0jZPUnYgOfpXX8Oy2mLS8qruwMwV9OqpjXf4qkbFBpP/R416H8saVZ85o577L5UV9VNA@UH "R – Try It Online") Brute force: `combn(rep(input,t),max(input))` generates all `length(input)` subsequences of \$\text {repeat}(\text {input},t)\$, and check for one that is sorted. -2 bytes thanks to pajonk. [Answer] # [Haskell](https://www.haskell.org/), ~~39~~ 34 bytes *Thanks [@Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string) for -3 bytes* *Thanks [@Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler) for another -2 bytes* ``` f[]=1 f(h:t)=sum[1|elem(h-1)t]+f t ``` [Try it online!](https://tio.run/##VZBBDoMgEEX3nsJFF5pOEwdEpIknMSxMKtFUbVPprnenAzYpLOe9D/NhGvb7uCzOmV53mJliutqy299rj59xGddiumBp9dnk1q3DvHW3R5Y/X/NmT6ZngPo/cUhnpJlDHZEaEISnEWvgyIkkyQMlBhKaiEvibUg35FhkWpr9KUVG@i2Jo2YVSarz0yrRvgSizzCyKiyOS5IQFGl8SB3PAmTUROr4N7gnlFKkRbjQp5BqVdp9AQ "Haskell – Try It Online") Port of [@dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)'s [Python](https://codegolf.stackexchange.com/a/242320/96039) answer Answered as part of the current Haskell LYAL event. Tell me if there are any golfs, this is my first time coding in Haskell. [Answer] # [Factor](https://factorcode.org/), 42 bytes ``` [ arg-sort differences [ 0 < ] count 1 + ] ``` Port of @SundarR's [Julia answer](https://codegolf.stackexchange.com/a/242308/97916). ## Explanation Arg-sort the input (i.e. get the indices that sort the input), get their first-order differences, count how many elements are negative, and add one. ``` ! { 6 1 2 3 5 4 } arg-sort ! { 1 2 3 5 4 0 } differences ! { 1 1 2 -1 -4 } [ 0 < ] count ! 2 1 ! 2 1 + ! 3 ``` [Try it online!](https://tio.run/##VZFNT4QwFEX3/Irr2gyZ8o0at8aNG@NqMosGHyMRC7adxNH42/G9gg5uSDnnvo9Cqxs/2Onp8f7h7goHMmR1331q3w3G4ZWsoR5v2r@ER@w8G@e7xmG05P1ptJ3xcPR@JNOQO59i@vBWO1xH0RcSKHzjAptbJPyarkHKQDFIkf0ixShjmAe8KiyWZH7OpqGfYIElRxaRsShZVCFfsEzWqmIgdTWrMkxaZB4kL7hlK0vNvv7vZROlJJSwrsPwv1VLudKWmZKczJivpxKuLNeNhFdh65p9HlpKTKXSYAkW0bSDtoeNG6zHc9e2ZOevvcMWN9ijGY78FxQusZ@42uhx7E@IHZqetJ1@AA "Factor – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~11~~ ~~8~~ 7 bytes ``` &Sd0<sQ ``` [Try it online!](https://tio.run/##y00syfn/Xy04xcCmOPD//2hDAx1THUMdMx1DQx1LHSMdYx0THUMjHQsd81gA "MATL – Try It Online") Straight port of my Julia answer (using the second output of `sort` in place of `sortperm` - thanks to @Giuseppe for that idea, saving me 3 bytes). Another -1 byte thanks to @LuisMendo (so rusty with MATL I forgot `&` even existed!) [Answer] # [Octave](https://www.gnu.org/software/octave/), 24 bytes ``` @(a)nnz(tril(a==a'+1))+1 ``` [Try it online!](https://tio.run/##PY7LCoNADEX3/YruOoNBzKjzWAj9j@JiKBUKxUIRF/356Y3R7pJzQu5935e8Psp0Huq6LleT7Tx/zfJ5vkwehnyp2NqKy2Rujni0Jwwt/UfG2FKnS0dMvQBdPantD99uACsF8ooCUNxuPLBTGDHKbQIM8vHAiG3AEbibdBjJYhbtINIWstcA62G9@KR1iR1Sg3ohURrBdnLK8gtRqNCMtvwA "Octave – Try It Online") Port of [@dingledooper's Python 3 answer](https://codegolf.stackexchange.com/a/242320). [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), ~~49~~38 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {0=⌈/⍵:1⋄~1∊⍺:1+⍵∇⍵⋄(⍵-1)∇⍨¯1+⍺↓⍨⍺⍳1}⍨ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31dNf4VHbBAUDAA&c=qzawfdTTof@od6uV4aPuljrDRx1dj3p3WRlqA4UedbSDyO4WDSCla6gJ5q84tB4kuetR22QgB8To3WxYC2QCAA&f=VU@7DcJADO0zhUsiuYjvf/sQPlKkFBcYAYkCiQUo6JiDUTIJz3c0kXWy/T72eRnLUmi9PWlnSHraWWpZkC05VI6EvHaoAzXcg@mW6uVqtixs2LPjyAHCiD6xBRKAGSAJWVUZSARutgMS7DKAt9A1Ra6uAExEOQM01x126wXnoQqqy5DpCDHYHzFB26S/AuVUJzoQy/CZoe/KPLX79az/0QiPiHihCtb7@/D9tJXr40XlNF@mPR3P15HkBw&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) A dfn submission which uses recursion (yuck) to keep track of things. Instead of looking for increasing numbers, we decrement the sequence and always look for a `1`: this means that, as we recurse, we don't need to keep track of the number we are searching for. `⍺` contains the tail of the sequence where we can still look for 1s, and `⍵` contains a copy of the original sequence, but decremented by the amount of times we already found the next digit. Then, we just look for the next number in the sequence tail. * If it's there, chop the sequence tail and call the function recursively, after decrementing the original sequence again and the new tail. * If it's not there, use `⍵` to reset the sequence tail, and add a `1` to the recursive result because we needed one extra repetition. Recursion stops when the decremented copy of the original sequence has 0 as its largest element. --- @Razetime also shared a “boring Jelly port” in the comments for 8 bytes: ``` 1+1⊥2>/⍋ ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~9~~ 8 bytes ``` {⊇Ċ-1}ᶜ< ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/pRV/uRLl3D2ofb5tj8/x9toWOmY6hjCEQGOkY65jqWOqY6JjrGsf8jAA) ### Explanation Saved 1 byte by porting everybody else's approach. ``` {⊇Ċ-1}ᶜ< { }ᶜ Count how many ways there are to satisfy this predicate: ⊇ A subsequence of the input Ċ Of length 2 - Has a difference (first element minus second element) 1 Equal to 1 (first element is 1 + second element) < The output is the next integer larger than that result ``` --- Old solution that implements the spec directly: ``` ;.j₎⊇~o?∧ ; Pair the input with . Some as-yet unknown value which will be the output j₎ Repeat the former a number of times equal to the latter (trying 0 first, then 1, then 2, etc., until the rest of the predicate succeeds) ⊇ Some subsequence of the result ~o Is a sorted version of ? The input ∧ Output whatever we calculated earlier as . ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/31ov61FT36Ou9rp8@0cdy///jzbTMdQx0jHWMdUxif0fAQA "Brachylog – Try It Online") [Answer] ## Python3, 109 bytes: ``` from itertools import* f=lambda x,c=1:c if any(sorted(x)==[*i]for i in combinations(x*c,len(x)))else f(x,c+1) ``` [Try it online!](https://tio.run/##RZFRboMwEES/61Os8hNI3SgGAiQSPUIvQKPKEKNaMjbCVpWcnu46of3cmeedkXe6h29n83qal2WY3Qg6qDk4ZzzocXJz2LGhMXLsrhJuvG/EuQc9gLT3xKOrrsktbZp2py@Dm0GDttC7sdNWBu2sT267nhtlkUpTZbyCIcE1ryJdfLPZbFibcXGBt3fIWJvzdchZK3DIeRFHwdqCC34kaYVL/iCOTyan9yShwCteRrFgbYViHbkSjWyVaxyIP6Fc0eZoHMnAEgd0MPzpnf49ShWCgAytUwx7VKqw8gFnQQztjfW5yDC9WheQVlM79AuCBe3DQKxyiFDJ6FceXw/SB/b3rYM2eJrkw1nFwe/9ZHRItp92m6Zn9iI5dNDAKKcEX@0NnVGaL/UjDQe90pSAPOLe45nxGBKv1y2/) Brute force solution, extremely slow. ## Python3, 115 bytes: ``` v=lambda o,n:not o or(o[0]in n and v(o[1:],n[n.index(o[0])+1:])) f=lambda x,c=1:c if v(sorted(x),x*c)else f(x,c+1) ``` [Try it online!](https://tio.run/##RZHBboMwEETP9VescgluthEGEhIkesyxP0BR5QSjWiI2wihKvz7ddYp63Jm3Myt7/Jm/vcsP4/R43OpBX8@dBo@ucn4GD35KfJO21oED7Tq40aiqFl3jttZ15h5tuSFNShD9knDHS62qC9ieVoKfZtMld4n314s0QzDQJ0RslHyEerVaiSZD1cLbO2SiyXEZctEoGnIs4qhEU6DCHUsLvMcnsftjct5niQQscR/FQjQliYfI7cnIFvlAA/NHkktOjsaODToiJYfK/7zjv8etSjGQkXWMZc@TSjo5pVkxw7nxfFQZtZdLAGsHvo78gmHFeVRIp6QR2gt@FXsd6eVAh1n0fgIL9A29HWYzJR/eGYSwDeNg52T96dZSVuJFI5yhhqseE9rakmcmPXyZmx4Q7EJzA/GEh2CoIDlVdZ9oKev6jNBQyIlyWjFO1hE@mzAHGBnu1vLxCw) Much faster version. [Answer] # JavaScript (ES6), 45 bytes ``` f=(a,k=0)=>a.some(n=>!a[k+=k+1==n])||1+f(a,k) ``` [Try it online!](https://tio.run/##fZDNDoIwEITvPoXeaFiRLT@FQ30R46FBNApSI8aT7467WDUR8Nr5ZjqzJ3M3bXE9Xm7Lxu7Krttrz0ClQ6HXJmjtufQavV6YTeXryketm614PNDfMyW6wjatrcugtgeP3jYScCvEfLWay9mvFsFXjQYqkhpB7HQc6DEgJMxM5qfwykg@KdFIB2aIAAWpo@IBpYjK@qSUSDnJZaRyYk6c4naOTEZI2h4SShMdnP@BeQoiOySxeV/4PVwNTxcSgGziKv0ZASUtUJNfMJTxDcgQsxv5R@pIc0LnSrsn "JavaScript (Node.js) – Try It Online") [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 8 bytes ``` 1+/<':<: ``` [Try it online!](https://ngn.codeberg.page/k#eJxFjs1ugzAQhO9+Ch8qtVVNYG2DAUd9ERQpKCU/SgIpEDVR1T57Z01Qb7vfzO7MtqS3ePlcLkshxvL7qbr/9uVWSnnz6+7oX9bb+nDyN3/3/evqR4yVluT1CoORPBoeCaOR1hMvVpJMGUy2TE5qCt1MdwywSiczbxk5oDx4MmA9wRwjewtAxx99OmHEJuAIfCjFrHAWEcsaQhFCjHehYoKN2MEfQ11JGqluOmaScyOolq3EvxCFConPVkLEYj+Ol6GM40330ey603YxjPXm2Nw2+7rdNYtNd44/r80wHrp2iLXVJjHxvvuKznV7j071ZYjqvru2H9G4b6JL05+vY81mUWlFKxm9Sy0qo+bFiIqwGGXDSqKyilTKaDZnanKkD4/he0YAyqksQCsqB5gHXwZBzzjHwv4C2PHnIKQsoEQCBeEPrfjXOJWIDRpSEcKmSg6VE+zEHv4b6ivSSHfzA2Y5t4Nu2Uz8D4GokgRT9gcxk5WY) Essentially a port of @ovs' [Jelly answer](https://codegolf.stackexchange.com/a/242305/98547). * `<:` [grade-up](https://github.com/JohnEarnest/ok/blob/gh-pages/docs/Manual.md#asc) the input (generates a permutation vector which would sort argument into ascending order) * `<':` check if each value is less than its predecessor * `1+/` take the sum, seeded with 1 [Answer] # [Desmos](https://desmos.com/calculator), 55 bytes ``` l=sort([1...L.length],L) f(L)=\total(\{l[2...]<l,0\})+1 ``` [Try It On Desmos!](https://www.desmos.com/calculator/xxtr47njj1) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/vwhjb4g0sa) \$f(L)\$ takes in a list \$L\$ and returns the lowest value of \$t\$ as specified in the challenge. The code basically just does the "grade up" trick that many of the other answers were doing. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes ``` IΣEθ›κ⌕θ⊕ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUCjUEfBvSg1sSS1SCNbR8EtMy8FJOSZl1yUmpuaV5KaopGpCQHW//9HRxvpGOtY6JjrmOlY6pjomOoYGuoAoZGOobGOoUFs7H/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Based on @dingledooper's observation that the number of repeats is `1` plus the number of times `x+1` appears before `x`, although because `Find` returns `-1` when the value is not found, the formula believes `n+1` appears before `n`, thus automatically adding the extra `1` to the result. ``` θ Input array E Map over values κ Current index › Is greater than ⌕ Index of ι Current value ⊕ Incremented θ In input array Σ Take the sum I Cast to string Implicitly print ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` >kā<‹O ``` The same approach as [*@dingledooper*'s uses in his Python answer](https://codegolf.stackexchange.com/a/242320/52210). [Try it online](https://tio.run/##yy9OTMpM/f/fLvtIo82jhp3@//9Hm@kY6hjpGOuY6pjEAgA) or [verify all test cases](https://tio.run/##LY47DgIxDESvstraxTr/SIht6DlAlAIkCkRBgYS0HTQcgNvQc5K9SBg7VPa8sWZ8vR2O51O7L/M4rK/3MM7Lrm0v3@dmfXz2jVophrhSsdQnY1py2BwxeVHYA3Xu1bGqsFOkAB2hk7oBzIAkTLnKIFFSlKFhAkT8H2fFEs4sngHNGiylAB5WEDP3t4gNmiJMkUn6YTm5Y0lBA2qnWn8). **Explanation:** ``` > # Increase each value in the (implicit) input-list by 1 k # Get the index of these values in the (implicit) input-list # (or -1 for the max+1 that isn't found) ā # Push a list in the range [1,length] (without popping the list) < # Decrease each by 1 to make the range [0,length) ‹ # Do a smaller than check for the values of the two lists O # Sum the amount of truthy values # (which is output implicitly as result) ``` [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 15 \log\_{256}(96) \approx \$ 12.35 bytes ``` e1+z0AhEDLRz.<S ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhbrUw21qwwcM1xdfIKq9GyCIaJQyQVro810DHWMdIx1THVMYiGCAA) Port of Kevin Cruijssen's 05AB1E answer. #### Explanation ``` e1+z0AhEDLRz.<S # Implicit input e E # For each number in the input: 1+ # Increment it Ah # And get the index z0 # in the input (-1 if not found) DLR # Duplicate and push [0..length] z.< # Do a less than check S # Sum the truthy values # Implicit output ``` [Answer] # [Uiua](https://uiua.org), 10 bytes [SBCS](https://www.uiua.org/pad?src=0_7_1__IyBTaW5nbGUtYnl0ZSBjaGFyYWN0ZXIgZW5jb2RpbmcgZm9yIFVpdWEgMC44LjAKIyBXcml0dGVuIGhhc3RpbHkgYnkgVG9ieSBCdXNpY2stV2FybmVyLCBAVGJ3IG9uIFN0YWNrIEV4Y2hhbmdlCiMgMjcgRGVjZW1iZXIgMjAyMwojIEFQTCdzICLijbUiIGlzIHVzZWQgYXMgYSBwbGFjZWhvbGRlci4KCkNPTlRST0wg4oaQICJcMOKNteKNteKNteKNteKNteKNteKNteKNteKNtVxu4o214o21XHLijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbUiClBSSU5UQUJMRSDihpAgIiAhXCIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0-P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX7ijbUiClVJVUEg4oaQICLiiJjCrMKxwq_ijLXiiJril4vijIrijIjigYXiiaDiiaTiiaXDl8O34pe_4oG_4oKZ4oan4oal4oig4oSC4qe74paz4oeh4oqi4oeM4pmtwqTii6_ijYnijY_ijZbiipriipviip3ilqHii5XiiY3iip_iioLiio_iiqHihq_imIfihpnihpjihrvil6vilr3ijJXiiIriipfiiKfiiLXiiaHiip7iiqDijaXiipXiipziipDii4XiipniiKnCsOKMheKNnOKKg-KqvuKKk-KLlOKNouKsmuKNo-KNpOKGrOKGq-Kags63z4DPhOKInuK4ruKGkOKVreKUgOKVt-KVr-KfpuKfp-KMnOKMn-KVk-KVn-KVnCIKQVNDSUkg4oaQIOKKgiBDT05UUk9MIFBSSU5UQUJMRQpTQkNTIOKGkCDiioIgQVNDSUkgVUlVQQoKRW5jb2RlIOKGkCDiipc6U0JDUwpEZWNvZGUg4oaQIOKKjzpTQkNTCgpQYXRoVUEg4oaQICJ0ZXN0MS51YSIKUGF0aFNCQ1Mg4oaQICJ0ZXN0Mi5zYmNzIgoKRW5jb2RlVUEg4oaQICZmd2EgUGF0aFNCQ1MgRW5jb2RlICZmcmFzCkRlY29kZVNCQ1Mg4oaQICZmd2EgUGF0aFVBIERlY29kZSAmZnJhYgoKIyBFeGFtcGxlczoKIwojIFdyaXRlIHRvIC51YSBmaWxlOgojICAgICAmZndhIFBhdGhVQSAi4oqP4o2PLuKKneKWveKJoOKHoeKnuyziipdAQi4iCiMgRW5jb2RlIHRvIGEgLnNiY3MgZmlsZToKIyAgICAgRW5jb2RlVUEgUGF0aFVBCiMgRGVjb2RlIGEgLnNiY3MgZmlsZToKIyAgICAgRGVjb2RlU0JDUyBQYXRoU0JDUwo=) ``` +1/+/<⍉◫2⍏ ``` [Try it!](https://uiua.org/pad?src=0_7_1__ZiDihpAgKzEvKy884o2J4perMuKNjwoKZiBbMiAxXQpmIFszIDIgMV0KZiBbMSAyIDMgNF0KZiBbNCAxIDUgMiAzXQpmIFs2IDEgMiAzIDUgNF0KZiBbMyAxIDIgNSA0IDcgNl0K) [Answer] # [Scala 3](https://www.scala-lang.org/), 70 bytes Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=hZJNToNAFMcTlz3FS1czkVIGKNBGmujCpAtXxrhommZsS8XQgcBUraYn8AhuutGNJ6qncZgH6gIrC5iQ3__jPXh9L2Y84c7HuN0R6QPPRXuyP05v7hYzCRc8FvDcagHc8wSiAZDTPOeb8UjISThUdwrh21pGnWB_PjWf4uw6lrcjMV88mkWay7MNmZpTRs0Vz8qTTc0iieexWBJ1nKVrIUkWDjPC6ElGLEqPGbp9Hr0AzBcRrFQBwvNlMQBMvpS5kk_oAK5ELCFU7UBdmXorE0EiLEhsAxilFLpdsBsBx4BfjNPIMM0o0q0w1oi5yseAHsIHQz1Nomfvx7Y53anhkjTAN8CreLeR9zUf1OaeVtkHJYFmMKivJT4OUql6f6nK1Vla5miLb2X_PyWugDE0sLWuX89Yb89v_hyW5hiaYGW7bsBsPbt_MB_pAJep9S5aMmxVjlVuw6pcPOWybW3xn9zt8PkF) ``` _.zipWithIndex.sortBy(_._1).map(_._2).sliding(2).count(p=>p(1)<p(0))+1 ``` Ungolfed version. ``` def f(a: Array[Int]): Int = { val sortedIndices = a.zipWithIndex.sortBy(_._1).map(_._2) sortedIndices.sliding(2).count(pair => pair(1) < pair(0)) + 1 } ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 28 bytes ``` \d+ $* \b1(1*)\b(?=.*\b\1\b) ``` [Try it online!](https://tio.run/##LY47DgIxDER7nwOkbLDQOv8UiJJLpIAIChoKtPcP4yyN5XnjzOT72t6fxzia232054kOlloXI3Zp3VwvZ9t6k9aXMRwLedYpmJ4DBRaOulPinUVQP3dsnDlRhirTSSCOCqZeVOisr0GQuQIh8g8roEaKqOPA6gz0BBlhJLXq/g0Wh4ZMKop2wgh6JZqAbNStPw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Uses @dingledooper's observation again. ``` \d+ $* ``` Convert to unary. ``` \b1(1*)\b(?=.*\b\1\b) ``` Count the matches of `1+$.1` that are followed by `$.1`. When this is positive, the word boundary anchors simply ensure that `$.1` is exactly matched, but conveniently when `$.1` is `0` we get an extra "false" match which automatically increments the final result for us. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~70~~ 57 bytes ``` i;t;f(a,n)int*a;{for(i=t=n;t;)a[i%n]+t+~n?i++:t--;a=i/n;} ``` [Try it online!](https://tio.run/##XZRtj5swDMff36eIKlWCEnSEZ46xezHtU7TVhCi9RXdLTwVp1Sr20dc5cWhjEMXEv78dx0npwreuu91kPdZHr@XKl2rctPX1eDp7shkbBcBvt3Kt9sEY/FWvMghexjCs20Y@q3q6gZ79aqXyfHZ9YnBpx9gPo9juWcOuMRdTfXfG6Ew4dSfoFuBOeOqAFEHKBc80dFCGKOcYlZG4fJ5HQ0C84LmDC8QF4NLE5iCJHUGJghLcOkcFgkJX4EiqWQJLiUADhVtV5ahENMt0oUJobQyqylTlrkfYhoEgA2muxRU2hIsY6ixccTx3N9EE1BXIMjOBVguoOppqsiE/FMYM8k9/Onomjf9sRxsccubQmNKY0oTShNKU0pTSjNKM0pzSnNKC0oLSktKS0orSilIRLdoRLfiyXYt@iUXDYPzYgo3ZgwG3wFCO/wg0CZoUTYYmR1OgKdFU3B4sa20eETvb3V8@@27sD/MhYZAedPiSmjszd2GeuQ3tTmoYWfezPW/g2Xfv/RkzrHaX7/HuUn2DX7bizB0nKxsNnwzm6dmlOvQXCItq@/pl7tJc16NPd0/NgsCofZMMvyWP3kE67J/R7GsXM2UpnPAlfhRlC4JilJnLv2v09XkG0dFbrYf1ARYoX/UqX1ZbMONW7n064QDJYM/hc0n9PfjvvV@WMk@xZ@FXtj6w9bBTkH7g9173TTPMU01P0@1fd/xo34Zb@Ps/ "C (gcc) – Try It Online") *Saved a whopping 13 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!!* Inputs a pointer to an array of numbers that are a permutation of \$\{1, 2 \dots n\}\$ and \$n\$ (because pointers in C carry no length info). Returns how many times this array must be repeated before you can *pick out* the numbers \$\{1, 2 \dots n\}\$ in order. [Answer] # [PHP](https://php.net), ~~81~~ ~~74~~ 67 bytes ``` array_reduce($a,function($c,$x){return[$x,$c[1]+($x<$c[0])];})[1]+1 ``` Implementation of algorithm from ovs' answer: count all pairs where right < left, then add 1. Since array\_reduce takes only one "carry" param, but we want each iteration to know both the running total and the previous value, we make 'carry' be an array with both elements in, which is a few bytes shorter than making a global, but makes a warning the first time we access the (uninitialized) array. Reduced from first submission by moving all calculation into the return. Reduced further since it apparently doesn't need to be a program, just a code snippet that takes an array and outputs a value, so all the boilerplate can go away into a header/footer. [Try it online!](https://tio.run/##NZDNqoMwFIT3PkUWWSg9C@O/2EsfREIJaYrdqKQVvJQ@u50TbTaZ882QOWQe5u18mYc5ksZ78/8Uf6KPRJ@R0oQ7p59SUDkVQRekqOQ5TBXtXnm4eZgxUU1VIDVIExIVaBZYA8XJFqzm1w6KvhQYVYfRHgbXKMVuBt6Ggn0BoBJmxXa7r0kqQ2MdbAYN7wKz4KTil9CD@hQJ3UX3yTtjBxH/fsE8hTSJeEfODpPYAr16d1usQ4buy2hfj2mMpSW5Jm/vXosfe7mStL3Sp1iuZ6hUJ7r7JEzU1n02nC8) [Answer] # [Perl 5](https://www.perl.org/), 58 bytes ``` sub{$_="@_;"x@_;my$i;1while++$i&&s/.*?\b$i\b//;1+@_-y/;//} ``` [Try it online!](https://tio.run/##bZDNbsIwEITvPMUqcgkU0@D8B8sl90rl0hugSLQOtQokCqCCEM8e1g6VgujFseeb3Z1NKat1UJNc1LvD8kwyYaUZt454bE5Ecfb7rdZyMCCq2905L8@T@ZKo@dJxOBuk2fDkcMe51LyTF1WvMwOAmUvZAsQruPhY0Ebz6J/qtVSGqkd9o7OW7lNGA80e@oS0qQluVd7dDM2Q0IiGhvotGiGNTWWIDveBx6jqDgnySE83juDOgTuM0IKRb6bkH5OOyJh2uuhJTKBmkai9@ggB02Y90vwGylxMGD201DDWO6HR11VMT8AsGHdk3GHjxhP6Z/PZnHpEUSL7IiUZv0lkJbok76VE9RuprNR2n1tPw3AHII@l/NzLrzEQiWxV7PG2wpvalge8Y9l8a1GkQqA@Abv4sWEM9vv0A6ZvNu9c6is "Perl 5 – Try It Online") ]
[Question] [ **Input** Integers a1, a2, a3, b1, b2, b3 each in the range 1 to 20. **Output** ``` True if a1^(a2^a3) > b1^(b2^b3) and False otherwise. ``` ^ is exponentiation in this question. **Rules** This is code-golf. Your code must terminate correctly within 10 seconds for any valid input on a standard desktop PC. You can output anything Truthy for True and anything Falsey for False. You can assume any input order you like as long as its specified in the answer and always the same. For this question your code should always be correct. That is it should not fail because of floating point inaccuracies. Due to the limited range of the input this should not be too hard to achieve. **Test cases** ``` 3^(4^5) > 5^(4^3) 1^(2^3) < 3^(2^1) 3^(6^5) < 5^(20^3) 20^(20^20) > 20^(20^19) 20^(20^20) == 20^(20^20) 2^2^20 > 2^20^2 2^3^12 == 8^3^11 1^20^20 == 1^1^1 1^1^1 == 1^20^20 ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~31~~ 29 bytes *-2 bytes thanks to Grimy* ``` *.log10* * ***>*.log10* * *** ``` [Try it online!](https://tio.run/##VYvRCsIwDEXf@xV5EGkr2KZ1Q53bl0hBcB2Dzsn2NNRvrwkIMgLJuZeTZzulMg8LbGOd9T6NHVoNNFo365grEccJZOof7azgJQCGc2eu952piOfbAhHeGyM@2Qd5CIWCBgomrwQG6ejCpQbPiErQLVmiiixnWaPN5Cz//gKeVj3p/yRcoLEsB24o@4COpSMTfgE "Perl 6 – Try It Online") Believe it or not, this is *not* an esolang, even if it is composed of mostly asterisks. This uses [Arnauld's formula](https://codegolf.stackexchange.com/a/184737/76162), with log10 instead of ln. [Answer] # [R](https://www.r-project.org/), 39 bytes ``` function(x,y,z)rank(log2(x)*(y^z))[1]<2 ``` [Try it online!](https://tio.run/##dY7LTsMwEEX3@YqRurHRVOrYBYHUVGIBK1Y8VggkJ3Ueakgq44q0iG8PtqFpG6jHsq25Z66v6UZQ6GqlDWTrOrVlU4NtIFVVBbbQ@@ZHaQtQJl@/6dq@Q1kHWbcrnVq9gMYstIkyiPsJpgiVQCUxIUwEJpJ/5iz17YQ4uofrifCQXuRfUQ5x14@3uMEtN6pesqrJBWv5Gdu8bjl/ppeZ6DImcYrnrqYoOfyuEcxhPJ7D7fXdw02UMUKB0pVAOmBmgXm8f/KIxItgIyZ7nwHipMNNV/zvTwNGTAITH9m4GF4KB/8/sI9LAi/9RT1zZEO7GL5OIT@1CzJEum8 "R – Try It Online") Returns FALSE when `a > b` and TRUE if `b < a` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ ~~9~~ ~~11~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .²Šm*`› ``` Port of [*@Arnauld*'s JavaScript](https://codegolf.stackexchange.com/a/184737/52210) and [*@digEmAll*'s R](https://codegolf.stackexchange.com/a/184738/52210) approaches (I saw them post around the same time) -2 bytes thanks to *@Emigna* +2 bytes as bug-fix after *@Arnauld*'s and *@digEmAll*'s answers contained an error -4 bytes now that a different input order is allowed after *@LuisMendo*'s comments Input as `[a1,b1]`, `[a3,b3]`, `[a2,b2]` as three separated inputs. [Try it online](https://tio.run/##yy9OTMpM/f9f79CmowtytRIeNez6/z/aSMcolivayABC6RgZxAIA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/hphSdaKiTZBhrq2Tv6RJqr6SjEJ1orJNkDBEIgwgY6SQZQQTsIyOUFB61TVJQsv@vd2jT0QW5WgmPGnb91/kfbaxjGssVbapjDCRNdEyApCGYbaxjCCSNdIzAbIQaMx0jA5CEAZw2tMTPx0@DLQDxIByImAXIGUY6hoZgy41jAQ). **Explanation:** ``` .² # Take the logarithm with base 2 of the implicit [a1,b1]-input Š # Triple-swap a,b,c to c,a,b with the implicit inputs # The stack order is now: [log2(a1),log2(b1)], [a2,b2], [a3,b3] m # Take the power, resulting in [a2**a3,b2**b3] * # Multiply it with the log2-list, resulting in [log2(a1)*a2**a3,log2(b1)*b2**b3] ` # Push both values separated to the stack › # And check if log2(a1)*a2**a3 is larger than log2(b1)*b2**b3 # (after which the result is output implicitly) ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 56 bytes ``` (a,b,c,d,e,f)->a>Math.pow(d,Math.pow(e,f)/Math.pow(b,c)) ``` [Try it online!](https://tio.run/##hVJdaoNAEH7vKQZBcGFjoyalSWj60OdAIY@Swqprahp/0E1CCR6g9@jJehE77rq2sYXALvPtzDfzjePs2JGNdtFbE@5ZVcGKJRmcbwCKMjkywSHJBC9jFnJ4zk94nvK0YCWXHIAgz/ecZRAqr4VsYLRNgkCZUJlIGa5MTBaYXrcyh2CfhFAJJtAc8ySCFFuw1qJMsq2/AVZuK9KpXXYQpgU8QGMxGtCQRpTTmIyWbLli4tUu8pMV0R62sdv@hXxCmoWsie34G9QRvBIV1lNKAGfwKEwoTOVB4EFN@5hDwaUtw5PA@R1D153Oc8eDxNYxvM7sGsMdXzCkpvR3ZhDFDhw09x0aNq5l1RlE@/NXdyZLOuqrJ8Oo9tGep6O1mnScl5actpz1XE2c9AMfrBL@CvzBtl6sluyPN1Rm@Y4GrgaeBhMNphuy6Eqv3yvBUzs/CBvXOhOxZZjRi4XXjAiYFfy8zMzo8v8X0909grE0YA7G18encb2HWq573XwD "Java (JDK) – Try It Online") ## Credits * [@Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%c3%98rjan-johansen) for finding a bug in my solution. * Saved 10 bytes by reusing [@tsh's advantageous operands agencing](https://codegolf.stackexchange.com/a/184819/16236). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes ``` #2^#3Log@#>#5^#6Log@#4& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X9koTtnYJz/dQdlO2TRO2QzMNFH7H1CUmVei4JAebaxjomMKhCY6xrFccFFDHSMdYyA00jFEEjXWMQOrNTJAUQzkIiNDS9xyRgax//8DAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~11~~ 9 bytes ``` >&(^.@^/) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/7dQ04vQc4vQ1/2typSZn5CsYKtgqGCuYKJgqpAGxiYIxRNgAKGyoYASUSgNiIwVDhLCxghlUtZEBTDnIFCAPjCqAchC2oWUFQhumNJCNpBsEIZJguYr/AA "J – Try It Online") Arguments given as lists. * `>` is the left one bigger? * `&(...)` but first, transform each argument thusly: * `^.@^/` reduce it from the right to the left with exponention. But because ordinary exponentiation will limit error even for extended numbers, we take the logs of both sides [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 44 bytes ``` import StdEnv $a b c d e f=b^c/e^f>ln d/ln a ``` [Try it online!](https://tio.run/##bY1BS8NAEIXPza94hx4UJrRJtCi0nvQgeLLHNIXJ7mwb2GxKsyr@eddNCLYHYXi8@fbNW2WFXWg7/WEFLTcuNO2pO3tsvX5xn8mcUUNBQ2A29V4tZG@erINeROGw9RyzG5RzXAWx26FkQk1QBE0QgqmwTuMPJ9wM4rt3YXsLL71X3EtfJV9HOcsFDK3JbFaiINwR7seJpqhoxBkhp@GxGE024bitpnS@/EtHez3Z4784X04l@VA5nE96wQVlUR9Gk1VV@FHG8qEP6etbeP523DYqLjakxnDv05b98Rc "Clean – Try It Online") Uses an adaptation of Arnauld's formula. [Answer] # [Python 3](https://docs.python.org/3/), 68 bytes ``` lambda a,b,c,d,e,f:log(a,2)*(b**c)>log(d,2)*(e**f) from math import* ``` [Try it online!](https://tio.run/##dY3NCsMgEITveQqPKnOImpa20D5JL@ZHE4hRxEuf3hqhkBzKLrvMN8Nu@KTZbypb8iTvvGrXj5po9BgwYoJ5rN5SDck47Tkf2GvXY9UT54Y1JnpHnE4zWVzwMfEc4rIlaqlCh0upDoqx5kcFJFQpCXGgCteale0pXOSxxf2/J9ujV87vrI4TVxASt32V9/kL "Python 3 – Try It Online") Port of @Arnualds answer, but with the base for log changed. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 11 bytes ``` 2(?9•??e*)> ``` I'm beginning to understand Vyxal. [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=2%28%3F9%E2%80%A2%3F%3Fe*%29%3E&inputs=3%0A2%0A1%0A1%0A2%0A3&header=&footer=) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes Uses the method from [Arnauld's JS answer](https://codegolf.stackexchange.com/a/184737/47066) ``` 2F.²IIm*ˆ}¯`› ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fyE3v0CZPz1yt0221h9YnPGrYBRTjAkIDKAEA "05AB1E – Try It Online") [Answer] ## Excel, 28 bytes ``` =B1^C1*LOG(A1)>E1^F1*LOG(D1) ``` Excel implementation of the same formula already used. [Answer] # JavaScript, 51 bytes ``` f=(a,b,c,h,i,j)=>(l=Math.log)(a)*b**c-l(h)*i**j>1e-8 ``` ~~Surprisingly, the test cases doesn't show any floating-point error. I don't know if it ever does at this size.~~ This just compares the logarithm of the numbers. Equality tolerance is equal to `1e-8`. [Answer] # bc -l, 47 bytes ``` l(read())*read()^read()>l(read())*read()^read() ``` with the input read from `STDIN`, one integer per line. `bc` is pretty fast; it handles a=b=c=d=e=f=1,000,000 in a little over a second on my laptop. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 86 bytes Thanks to @ØrjanJohansen for pointing out a flaw in this and @Ourous for giving a fix. ``` #import<cmath> int a(int i[]){return pow(i[1],i[2])/pow(i[4],i[5])>log(i[3])/log(*i);} ``` [Try it online!](https://tio.run/##hVPNboMwDD7DU3jdBVaqkv5pA1Zphx32DCgHlEKXigKCoE6rePV1doC1VKsKcuIv9ue/KKIoJlshTqdHuS/yUgViH6nPtSkzBZFFqwy5fSxjVZcZFPnBkiHjjgxn3J62cEFwye11mm8RztFA2pO0/QbDZiKtNzEEMq9UGUf7tamD7yOZWTYcTUMnyYpahRxe4Th3Fs4S/4Uzb/wLaxXycKU9AEwAMAx0BVigLDshfd44JpoYqjOCnZDOWhPB1QVr5jo9i9RrYS@3bTO3s3UZ9Fm/n02UkaHyjDsBxhrT6JvLa9V2R60hgxHN/VvYldYSk7yE9naQ5fq4BVDJ7zhPrHZY9nQAQ5fbPozHUk/cqNTG8wRmhiCA0Qe5eFgajDD0OfbO6ycvecsbEnea7bSsZhD23odE7Rxnm5Ti6pPR@1cRCxVvPBgR7icj@U3Gm1B1lFLtmhFZFwVfMqhCmWBb8PB6d1AwAfZfv4NodIOm0b0L1zeb049I0mhbnSaHXw "C++ (gcc) – Try It Online") Takes input as a 6-integer array. Returns 1 if \$a^{b^c} > d^{e^f}\$, 0 otherwise. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` l⁵×*/}>/ ``` [Try it online!](https://tio.run/##y0rNyan8/z/nUePWw9O19Gvt9P@HWx9aqv@oYa6GtUq4yqOmNUBkdGiZNVBEEy5gfGhZ1LGuLBCnYY6ClpYCUDbrUeM@HYVjXTogIV07kJDO4eX6XIfbgcoi//@P5oqONtZRMI3VUYiONtFRMAExTHUUjGNjY3WAcoYgJkjOSEfBCMQAKjaEysH1mQHlDNA0GhnABJGYIJahJSEVQBZUBdROMAMhDZWFuRbkDrAyIyTbdRQsYHLGUGcb4ZIzBIoYgjzFFQsA "Jelly – Try It Online") Based on [Arnauld’s JS answer](https://codegolf.stackexchange.com/a/184737/42248). Expects as input `[a1, b1]` as left argument and `[[a2, b2], [a3, b3]]` as right argument. Now changed to use log to the base 10 which as far as correctly handles all the possible inputs in the range specified. Thanks to Ørjan Johansen for finding the original problem! [Answer] # TI-BASIC, ~~27~~ 31 bytes ``` ln(Ans(1))Ans(2)^Ans(3)>Ans(5)^Ans(6)(ln(Ans(4 ``` Input is a list of length \$6\$ in `Ans`. Outputs true if the first big number is greater than the second big number. Outputs false otherwise. **Examples:** ``` {3,4,5,5,4,3 {3 4 5 5 4 3} prgmCDGF16 1 {20,20,20,20,20,19 ;these two lines go off-screen {20 20 20 20 20 19} prgmCDGF16 1 {3,6,5,5,20,3 {3 6 5 5 20 3} prgmCDGF16 0 ``` **Explanation:** ``` ln(Ans(1))Ans(2)^Ans(3)>Ans(5)^Ans(6)(ln(Ans(4 ;full program ;elements of input denoted as: ; {#1 #2 #3 #4 #5 #6} ln(Ans(1))Ans(2)^Ans(3) ;calculate ln(#1)*(#2^#3) Ans(5)^Ans(6)(ln(Ans(4 ;calculate (#5^#6)*ln(#4) > ;is the first result greater than the ; second result? ; leave answer in "Ans" ;implicit print of "Ans" ``` --- **Note:** TI-BASIC is a tokenized language. Character count does ***not*** equal byte count. [Answer] # APL(NARS), chars 36, bytes 72 ``` {>/{(a b c)←⍵⋄a=1:¯1⋄(⍟⍟a)+c×⍟b}¨⍺⍵} ``` Here below the function z in (a b c )z(x y t) would return 1 if a^(b^c)>x^(y^t) else would return 0; test ``` z←{>/{(a b c)←⍵⋄a=1:¯1⋄(⍟⍟a)+c×⍟b}¨⍺⍵} 3 4 5 z 5 4 3 1 1 2 3 z 3 2 1 0 3 6 5 z 5 20 3 0 20 20 20 z 20 20 19 1 20 20 20 z 20 20 20 0 2 2 20 z 2 20 2 1 2 3 12 z 8 3 11 0 1 20 20 z 1 1 1 0 1 1 1 z 1 20 20 0 1 4 5 z 2 1 1 0 ``` {(a b c)←⍵⋄a=1:¯1⋄(⍟⍟a)+c×⍟b} is the function p(a,b,c)=log(log(a))+c\*log(b)=log(log(a^b^c)) and if aa=a^(b^c) with a,b,c >0 and a>1 bb=x^(y^t) with x,y,t >0 and x>1 than ``` aa>bb <=> log(log(a^b^c))>log(log(x^y^t)) <=> p(a,b,c)>p(x,y,t) ``` There is a problem with the function p: When a is 1, log log 1 not exist so I choose to represent that with the number -1; when a=2 so log log a is a negative number but > -1 . PS. Seen the function in its bigger set in which is defined ``` p(a,b,c)=log(log(a))+c*log(b) ``` appear range for a,b,c in 1..20 is too few... If one see when it overflow with log base 10, the range for a,b,c could be 1..10000000 or bigger for a 64 bit float type. ]
[Question] [ ## Introduction: Inspired by these two SO questions (no doubt from the same class): [print the elements in the subarray of maximum sum without adjacent elements java](https://stackoverflow.com/q/55691215/1682559) and [Maximum sum of non adjacent elements of an array, to be printed](https://stackoverflow.com/q/55688939/1682559). ## Challenge: Given a list of integers, output a subsequence consisting of non-adjacent elements that have the highest sum. Here some examples: * `[1,2,3,-1,-3,2,5]` would result in `[1,3,5]` (with a sum of `9`) at the 0-based indices `[0,2,6]`. * `[4,5,4,3]` would result in either `[4,4]` (with a sum of `8`) at the 0-based indices `[0,2]` or `[5,3]` (also with a sum of `8`) at the 0-based indices `[1,3]`. * `[5,5,10,100,10,5]` would result in `[5,100,5]` (with a sum of `110`) at either the 0-based indices `[0,3,5]` or `[1,3,5]`. What's most important about these examples above, the indices containing the elements are at least 2 apart from each other. If we look at the example `[5,5,10,100,10,5]` more in depth: we have the following potential subsequence containing non-adjacent items; with their indices below it; with their sums below that: ``` [[5],[10],[100],[10],[5],[5],[100,5],[10,5],[10,10],[5,5],[5,10],[5,100],[5,5],[5,10],[5,100],[5,10],[5,100,5],[5,100,5],[5,10,5],[5,10,10]] // non-adjacent subsequences [[5],[ 4],[ 3],[ 2],[1],[0],[ 3,5],[ 2,5],[ 2, 4],[1,5],[1, 4],[1, 3],[0,5],[0, 4],[0, 3],[0, 2],[1, 3,5],[0, 3,5],[0, 2,5],[0, 2, 4]] // at these 0-based indices [ 5, 10, 100, 10, 5, 5, 105, 15, 20, 10, 15, 105, 10, 15, 105, 15, 110, 110, 20, 25] // with these sums ^ ^ // and these two maximums ``` Since the maximum sums are `110`, we output `[5,100,5]` as result. ## Challenge rules: * You are allowed to output key-value pairs of the index + value. So instead of `[5,100,5]` you can output `[[0,5],[3,100],[5,5]]` or `[[1,5],[3,100],[5,5]]` as result (or `[[1,5],[4,100],[6,5]]`/`[[2,5],[4,100],[6,5]]` when 1-based indexing is used instead of 0-based). + If you use key-value pairs, they can also be in reverse or random order, since it's clear which values are meant due to the paired index. + Outputting just the indices without values isn't allowed. It should either output the values, or the values/indices as key-value pairs (or two separated lists for 'keys' and 'values' of the same size if key-value pairs are not possible in your language of choice). * You are allowed to output all possible subsequences with the maximum sum instead of just one. * As you can see from the examples, the input-list can contain negative and duplicated values as well. You can assume the input-integers are within the range \$[-999,999]\$. * The output-list cannot be empty and must always contain at least one element (if a list would only contain negative values, a list containing the single lowest negative value would then be output as result - see last two test cases). * If there is one possible output but for multiple different indices, it's allowed to output both of them even though they might look duplicates. (i.e. the example above, may output `[[5,100,5],[5,100,5]]` for both possible index-combinations). ## Test cases: ``` Input: Possible outputs: At 0-based indices: With sum: [1,2,3,-1,-3,2,5] [1,3,5] [0,2,6] 9 [4,5,4,3] [4,4]/[5,3] [0,2]/[1,3] 8 [5,5,10,100,10,5] [5,100,5] [0,3,5]/[1,3,5] 110 [10] [10] [0] 10 [1,1,1] [1,1] [0,2] 2 [-3,7,4,-2,4] [7,4] [1,4] 11 [1,7,4,-2] [7] [1] 7 [1,2,-3,-4,5,6,-7] [2,6] [1,5] 8 [800,-31,0,0,421,726] [800,726]/[800,0,726] [0,5]/[0,3,5]/[0,2,5] 1526 [-1,7,8,-5,40,40] [8,40] [2,4]/[2,5] 48 [-5,-18,-3,-1,-10] [-1] [3] -1 [0,-3,-41,0,-99,-2,0] [0]/[0,0]/[0,0,0] [0]/[3]/[6]/[0,3]/ [0,6],[3,6]/[0,3,6] 0 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` ►Σ†!¹mü≈tṖŀ ``` [Try it online!](https://tio.run/##yygtzv7//9G0XecWP2pYoHhoZ@7hPY86O0oe7px2tOH////RFgYGOrrGhjoGQGhiZKhjbmQWCwA "Husk – Try It Online") ## Explanation ``` ►Σ†!¹mü≈tṖŀ Implicit input, say L=[4,5,3,4]. ŀ Indices: [1,2,3,4] Ṗ Powerset: [[],[1],[2],[1,2],..,[1,2,3,4]] t Tail (remove the empty list): [[1],[2],[1,2],..,[1,2,3,4]] m For each, ü de-duplicate by ≈ differing by at most 1. For example, [1,2,4] becomes [1,4]. † Deep map !¹ indexing into L: [[4],[5],[4],..,[5,4],[4,3]] ► Maximum by Σ sum: [5,4] ``` [Answer] # [Haskell](https://www.haskell.org/), 60 bytes ``` snd.([]%) r%(h:t)=max(r%t)$(r++[h])%drop 1t r%_=(sum r<$r,r) ``` [Try it online!](https://tio.run/##LY5tboMwDIb/c4r8KFKi2lUSoKXTOMJOQKMqakupBiwKTNrplzoEOZFffz12b@fvxzCErrmEebofeGtykfmc9x@LaEb7x32@iB33@33bG5Hf/Y9jaqGOa8Pn35H5z50HL8JoXxNr2Gjd15Vx51/Twg6sE6zNWKtAQwGoAAtSlQHKlVBBCcWqK9JK0ot/qyuZHJCtimZPNIEayq2Swi3QEY6RegQ8rcmaeFgokGSlpn59TKQ4WgPSAVRIeyhAVa8MOnNbLhMzEvB8jqulMVn4v3WDfc4Bb869AQ "Haskell – Try It Online") The helper function `%` recursively branches on choosing whether the include the first element and drop the second, or to skip the first element. It takes the maximum of all outcomes, which are tuples whose first element is the sum, and whose second element is the corresponding list which is extracted for the output. To handle the rule that the empty list is disallowed even if it would have the smallest trick, we do a cute trick of writing `sum r<$r` rather than `sum r`.This makes a list whose elements all are `sum r` and whose length is that of `r`. That way, when we choose the maximum, we prioritize any list over an empty `r`, but otherwise comparisons depend on the first element which is `sum r` . [Answer] # [R](https://www.r-project.org/), ~~136~~ 125 bytes ``` function(l,G=unlist(Map(combn,list(y<-seq(a=l)),y,c(function(x)'if'(all(diff(x)>1),l[x],-Inf)),F),F))G[which.max(Map(sum,G))] ``` [Try it online!](https://tio.run/##PU7BboMwDL3vK3arIz1PBMJGpXbHoR32BVUPLFvUSCFdS9Ho1zOHAbIt@fk9P/s6uscdj66P9ubPkQLqfR@D72700fyQPbefERO877j7vlCzD0rhDkvrzqA23m2oCYG@vHOCX7VCOAxH8Ht0In9LqerD78nb01PbDJN517eolTqOjixp5CjAGlxIVyr1kKYGJQyKGZWCdCaZatXobGkgMffi8iKbnMOs7P9ghpWYcKGRSZhcyPx5WU3KCiyXhVrMBbKu0nfpx/VmNk1M8uHtNt0TZvwD "R – Try It Online") *-6 bytes thanks to [digEmAll](https://codegolf.stackexchange.com/users/41725/digemall)*, who incidentally also [outgolfed me](https://codegolf.stackexchange.com/a/183541/67312). Returns the shortest subsequence as a `list`, breaking ties on lexicographically first by indices. Brute-force generates all index subsequences, then `Filter`s for those that are non-adjacent, i.e., where `all(diff(x)>1)`. Then subsets `[` into `l` using these indices, selecting `[[` the first one where the sum is the max (`which.max`). ~~I'm pretty sure this is the first R answer I've ever written that uses `Filter`!~~ sad, `Filter` is ungolfy, no wonder I've never used it... [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes Saved 1 byte thanks to *Kevin Cruijssen* ``` ā<æʒĆ¥≠W}èΣO}θ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//SKPN4WWnJh1pO7T0UeeC8NrDK84t9q89t@P//2gLAwMdXWNDHQMgNDEy1DE3MosFAA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##JU67CsJAEOz9ll24vUdyAUuxtRKLkELBwsrCOoWNYJsvEETxE6xNKot8hD9yzl7Ye8zN7szc8bTdHfZJ7HKxTsN53j@/3XD5PH7X26btX@N91Y7vRKkWsuSIhdgBhWZWewrkyQEFIDFYunNPjB6Ewg1FiUm25DM7PTK0asfqVBCXoCI82AkZlLeYtYU6qCgSIxC0egOyxKzGl3KcmbxUy1Wlcab5Aw) **Explanation** ``` ā< # push [0 ... len(input)-1] æ # compute powerset ʒ } # filter, keep lists where: ≠W # no element is 1 in the ¥ # deltas Ć # of the list with the head appended è # index into the input with each ΣO} # sort by sum θ # take the last element ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (v2), 14 bytes ``` {~ba~c∋₁ᵐ}ᶠ+ᵒt ``` [Try it online!](https://tio.run/##ATUAyv9icmFjaHlsb2cy//97fmJhfmPiiIvigoHhtZB94bagK@G1knT//1sxLDIsXzEsXzMsNV3/Wg "Brachylog – Try It Online") Function submission; input from the left, output from the right, as usual. Very slow; a five-element list is probably the maximum for testing on TIO. ``` {~ba~c∋₁ᵐ}ᶠ+ᵒt ~b Prepend an arbitrary element to the input a Take a prefix or suffix of the resulting list ~c Ordered partition into contiguous sublists ∋₁ Take the second element ᵐ of each sublist { }ᶠ Find all possible ways to do this +ᵒ Sort by sum t Take the greatest ``` The results we get from prefixes aren't incorrect, but also aren't interesting; all possible results are generated via taking a suffix (which is possibly the list itself, but cannot be empty), but "suffix" is more verbose in Brachylog than "prefix or suffix", so I went with the version that's terser (and less efficient but still correct). The basic idea is that for each element we want in the output list, the partition into contiguous sublists needs to place that element and the element before into the same sublist (because the element is the *second* element of the sublist), so two consecutive elements can't appear in the result. On the other hand, it's fairly clear that any list without two consecutive elements can appear in the result. So once we have all possible candidate lists, we can just take the sums of all of them and see which one is largest. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ŒPm€2SÞṪ ``` [Try it online!](https://tio.run/##y0rNyan8///opIDcR01rjIIPz3u4c9X///@jDXWMdIx1dA11dI2BLNNYAA "Jelly – Try It Online") This is a function submission (it's almost usable as a full program, which is what the TIO link does, but the output format is a little weird; when used as a function, though, it just outputs the list of elements from the subsequence). ## Explanation I found a much terser algorithm (loosely inspired by my previous Brachylog answer), saving 6 bytes over the Jelly and Brachylog answers and 3 bytes over the current leading answer. ``` ŒPm€2SÞṪ ŒP On the set of all subsequences of {the input}, m 2 remove every second element of € each subsequence, ÞṪ then {return} the resulting subsequence with the maximal S sum ``` The basic idea is that we don't look for the subsequence we want directly; rather, we find a subsequence with an additional element inserted in between each of the elements we want. This is always possible if the elements of the subsequence we want are not adjacent in the original list (because there'll always be at least one in between to insert), and never possible if the elements of the subsequence we want are adjacent in the original list. So all we have to do is look at all the subsequences of the input, then take alternating elements from them, to get a list of all the non-adjacent-item subsequences of the input. This algorithm will return many of the non-adjacent-item subsequences more than once, but that doesn't matter, because we're just looking for a maximal element, and repeating elements of the set we're taking a maximum of has no influence on the maximum. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 14 bytes ``` JŒPḊf’$ÐḟịµSÞṪ ``` [Try it online!](https://tio.run/##JY6/CsIwEMb3PkWHjneQpH9dfAAnwUlKRx2kL@BWXAq6SCcF/@ziKrS4Gfog6YvEu4RLwi9f7r4vu01d761djN3S9Mft1FwjfTb903xPv89KP8zwsmNnhgtMzS3EeTg1d9Ctk6JAt9Phvba2DEoJCmJACRgTpRUEZQIpJBAzpoRS0OLtX6VwJ1Ax0FhO3agg8bq/eVbsiuyXAeasFeSEsQRBlSjqVplz4bkCkIJJdwnEKAtnQJ/zqcL78TjOZhwqqqD6Aw "Jelly – Try It Online") Thanks to @EriktheOutgolfer for saving 2 bytes! [Answer] # JavaScript (ES6), ~~138 132 130 129~~ 126 bytes Outputs key-value pairs. ``` a=>a.reduce((a,x,i)=>[...a,...a.map(y=>[[x,i],...y])],[[]]).map(m=a=>a.some(s=p=([v,i])=>p-(s=~~s+v,p=i)<2)|s<m||(r=a,m=s))&&r ``` [Try it online!](https://tio.run/##bVHRjoIwEHy/r/DJtLktlAKKifVHSB8a5S5eRAi9M2di/HVuCppTaktLuzO7O7v9sifrtt2@/RbHZlf1H7q3emOjrtr9bCvGLP3SnutNGUWRJb9FtW3ZGZYSiPGms@GGytIYPmC1HiK4pq6Y061m5QlExGgF7terez9Rq/d8rfjFrevLhXXaUq0d5/N512@bo2sOVXRoPtkHKxNSlJJISKQ45WaGwfksjmeAUhjeJg4Z5ZRROhDv4@aQUWbiMgc4dcrhlEh8fj1nyQdrmCeRTyke8wAK2IRpXrMBTOkodokqhILiCR32F9FHtgmjL1@QlW@m8I1akFiaf7KiRUAvUL1IE5KYmUImtTA3uof8NR5O4zmoxGsrSOBR4C8fO1v4e8DP8djFIBBvPjb5xhdhn@RYiVcnVivfL3kXJyELosYd//4P "JavaScript (Node.js) – Try It Online") ### Step 1 We first compute the powerset of the input with \$[value, index]\$ pairs. ``` a.reduce((a, x, i) => // for each value x at position i: [ // update a[] to a new array consisting of: ...a, // all previous entries ...a.map(y => // for each value y in a[]: [[x, i], ...y] // append [x, i], followed by all original entries ) // end of map() ], // end of new array [[]] // start with a = [[]] ) // end of reduce() ``` ### Step 2 We then look for the maximum sum \$m\$ among these sets, discarding sets with at least two adjacent elements. The best set is stored in \$r\$. ``` .map(m = // initialize m to a non-numeric value a => // for each entry a[] in the powerset: a.some(s = p = // initialize s and p to non numeric values ([v, i]) => // for each value v and each index i in a[]: p - ( // compute p - i s = ~~s + v, // add v to s p = i // update p to i ) < 2 // if p - i is less than 2, yield true ) | // end of some() s < m || // unless some() was truthy or s is less than m, (r = a, m = s) // save a[] in r[] and update m to s ) && r // end of map(); return r[] ``` [Answer] ## Haskell, ~~81~~ 80 bytes ``` snd.maximum.map((,)=<<sum).tail.f f(a:b:c)=f(b:c)++map(a:)(f c) f a=[]:map(:[])a ``` [Try it online!](https://tio.run/##LU5RbsMgDP3PKfgE1Y6AJG2KyhF2giyaWDa6aCFCSyvt9GMmRAb5@T372V9u@/5clhTta9rWjzq43zk8A@XIOQh7u23PIOqHm5faV547824mYT3P6XTKbc4I7tkkKs@cHUaTOTOMwqXg5pVZRsTLG@PxZ14frGZRsKFigwINDaACbAh1IxDXQgctNDvuCCtJL/9DV7IkoNgRzV5oAjW0h1LKo9DZHLPrGfCykz35YaNAUrSa@vW5OOXRHpAOIKHsoQJVv3vQmcdyWTyzA16vebUcxyr9TX5x9y3hFOM/ "Haskell – Try It Online") `f` builds all valid subsequences by either skipping the next element (`f(b:c)`) or using it and skipping the next (`map(a:)(f c)`) and recursively work on the rest. For the result, build all subsequences (`f`), drop the empty subsequence (which occurs first in the list: `tail`), make pairs `(<sum>,<subsequence>)` (`map((,)=<<sum)`), find the maximum (pairs are compared in lexicographical order) -> `maximum`) and drop the sum (`snd`). Edit: -1 byte thanks to @Lynn. [Answer] # [J](http://jsoftware.com/), 47 bytes ``` >@{:@(<@#~/:+/@#~)1(-#~0=1 1+/@E."1-)[:i.&.#.=~ ``` [Try it online!](https://tio.run/##RVDLTsMwELz7K0a1RBNBXK9jN6lFUASCE@LAtVJ9qKgoFz4AkV8P65eIFXl2xrsz9te6UdsLJo8t7qDh@e8Unt5fX9aH@cfPzf0sl52/3fHWUtPJRU8E4vpZbahrj/6qbpRU07K2Qrw9KnycP7/RHL3086@ar8qcZAtCDydE0hJG53FhaLgIhNAzcll3TCXVMrToK0ta1z6XysTwVvoYTXGmrjZUTXhlbuB5iWO/iIOBrUrqrWz@smSw/0/LjSHm2iMMWR45xGDKkViEnvgVNayhKJRTsLpYR5MRwUXGlrBMRn8mA43JhN@k3iTfS2fvODscDjGkFusf "J – Try It Online") *-7 bytes thanks to FrownyFrog* # original # [J](http://jsoftware.com/), 54 bytes ``` [:(>@{:@/:+/&>)]<@#~"1[:(#~0=1 1+/@E."1])[:#:@}[[email protected]](/cdn-cgi/l/email-protection)^# ``` [Try it online!](https://tio.run/##VVBBTsMwELznFaNEoo1KHa9jN6lFKgsEJ8SBa1V8QFTAhQcg@vWwa8dCZBV5d2bHM8nnXKvVGZPHCtfQ8PxuFe6eHx/mo18fwrcPnd90V4f2dBOaS02MNhc9EWjThXtV06k9@saHHxU@lHlp5raqnm4V3l7fv7D@R7Ug9HBVlbjUY@tx5tbwEAmx585l3nIl1vKaRZ9RB9K66FwaE8LHouNukjt1saFiwpWxoVzNftJHA1uYpC1ofjJlsPtLy8IouXaIQ6ZHDqExmGVJxtgTBLSGhFj2YPViLjYjohPELnEZlAQMRhqTDf@V8i06VRLrHEEM4n4vWXU1/wI "J – Try It Online") [Answer] # T-SQL, ~~122~~ ~~119~~ 118 bytes Input is a table variable. This query picks all elements from the table variable, combining these with all non-adjacent elements with higher position values and show the text generated for the highest sum of these values. ``` WITH C(y,j,v)as(SELECT*,x*1FROM @ UNION ALL SELECT y+','+x,i,v+x FROM @ JOIN C ON~-i>j)SELECT TOP 1y FROM C ORDER BY-v ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1032334/maximum-summed-powersets-with-non-adjacent-items)** ungolfed [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 144 bytes ``` If[Max[a=#]>(d=Max[m=Tr/@(g=a[[#]]&/@Select[Subsets[Range[x=Length@#],{2,x}]&@#,FreeQ[Differences@#,1]&]&@a)]),{Max@a},g[[#]]&@@@Position[m,d]]& ``` [Try it online!](https://tio.run/##XZBRa4MwEMff/RQFQVq4UBO1tQ8ZeRiDwQbd2reQh8xGK0wLmoEgfnZ3mS8zXAKX313@908abe@m0bYu9Fzy@bWU73qQmofqaXvjLm/4tduLbcW1lKFS0V5czLcprLz8fPXG9vJTt5WRA38zbWXvIlQwMhgmFYkQXjpjPuRzXZamM21hemRURVjTO7WDEQcIPUG1SAshzo@@tvWjlQ3ckMznrm7tRmxKOVJgkAChQBLMskkF/4opZJBCsoYZQhrjctu/QWPvDBhrhIOOqEoYpH7vwn3KnDfivByAHNfVHF2QhEKMkTJUYAdvmlPNgeBDsMNzh5TQ/E8eP8D3Hi9znTg5nZxh1xAE8/wL "Wolfram Language (Mathematica) – Try It Online") [Answer] # Pyth, 19 bytes ``` esDm@LQdtf!q#1.+TyU ``` Try it online [here](https://pyth.herokuapp.com/?code=esDm%40LQdtf%21q%231.%2BTyU&input=%5B800%2C-31%2C0%2C0%2C421%2C726%5D&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=esDm%40LQdtf%21q%231.%2BTyU&test_suite=1&test_suite_input=%5B1%2C2%2C3%2C-1%2C-3%2C2%2C5%5D%0A%5B4%2C5%2C4%2C3%5D%0A%5B5%2C5%2C10%2C100%2C10%2C5%5D%0A%5B10%5D%0A%5B1%2C1%2C1%5D%0A%5B-3%2C7%2C4%2C-2%2C4%5D%0A%5B1%2C7%2C4%2C-2%5D%0A%5B1%2C2%2C-3%2C-4%2C5%2C6%2C-7%5D%0A%5B800%2C-31%2C0%2C0%2C421%2C726%5D%0A%5B-1%2C7%2C8%2C-5%2C40%2C40%5D%0A%5B-5%2C-18%2C-3%2C-1%2C-10%5D%0A%5B0%2C-3%2C-41%2C0%2C-99%2C-2%2C0%5D&debug=0). ``` esDm@LQdtf!q#1.+TyUQ Implicit: Q=eval(input()) Trailing Q inferred UQ Generate range [0-len(Q)) y Take the powerset of the above f Filter keep elements of the above, as T, using: .+T Take differences of consecutive elements of T q#1 Keep those differences equal to 1 ! Logical NOT - empty lists evaluate to true, populated ones to false Result of the filter is those sets without consecutive numbers t Drop the first element (empty set) m Map the remaining sets, as d, using: L d For each element of d... @ Q ... get the element in Q with that index sD Order the sets by their sum e Take the last element, implicit print ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), 24 bytes ``` e:w;ċz⟨ọ1>¦ẏ⟩⁇‼⁇E‡ev2%Σ⌠ ``` [Try it online!](https://tio.run/##S0/MTPz/P9Wq3PpId9Wj@Sse7u41tDu07OGu/kfzVz5qbH/UsAdIuj5qWJhaZqR6bvGjngX//0cbKhgpGCvoGiroGgNZprEA "Gaia – Try It Online") Ugh, `E‡` does some weird stuff...according to the documentation, it *should* do something like "given length `i` set of lists `X` and length `j` set of indices `Y`, return `X[i][Y[j]]`", but instead returns `[X[i][Y[j]] X[i][Y[-j]]` where negative indexing represents the complement, so we have to do `ev2%` to extract only the ones we want. ``` e | eval as a list l : | dup w | wrap as a list ; | push l again ċ | push [1..len(l)] z | push all subsets of [1..len(l)] -- index powerset. ⟨ ⟩⁇ | filter this for: ọ | deltas 1>¦ | are greater than 1 ẏ | all (all deltas greater than 1) ‼⁇ | filter for non-empty lists E‡ | table extract elements. Given l and index set i, this pushes | [l[i] l[setdiff(1..l,i)]] for some reason ev2% | get the l[i] only by unlisting, reversing, and taking every other element Σ⌠ | Get the one with the maximum sum ``` [Answer] # [R](https://www.r-project.org/), ~~108~~ 107 bytes ``` function(v,M=-Inf){for(j in J<-seq(a=v))for(i in combn(J,j,,F))if(all(diff(i)>1)&sum(v[i])>sum(M))M=v[i] M} ``` [Try it online!](https://tio.run/##lZLfa8IwEMff/SsCwkjgwpL@0AqrDwMHyrrJqk@SB@cWiGhlOn0Z@9u7u1Y7Z@3DkrYkl376/d5dt7mNc7vPFp9uk/EDJLEcZlZ82c2WL5nL2OhO7t4/@Dw@CEFBR8HFZv2a8REsAR6EcJbPVyv@5qzlTvS1uNnt1/wwc0b0aZUIkcS0bSXfeZsNn8bTCbs@xs9pOrx/HLCXQTp9nKSttvzXaFm@4Bo88EFqkD6uQiHKb7cZm2k8CE1NtsACCCEA//T6aRAWQGBuZyH4po6FiGmFF91/1cIiWtMrTapLoV@TylyrzTE3nHWyzE2bJgwr0cXkpAfBOUwYxk2zWkldCBbYVY@sagAqSqpoB2T3iBPmQadRLcJiSV@Dwhl4qO11iCSMjnCLTaBVua5yI5cRSOwecuq8ARHuTVNJQvxFosIn/ilVOwiTurkBqsyMXMpejyqqTiYV2kNz5RMq4fwH "R – Try It Online") -1 thanks to @Giuseppe [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~70~~ 63 bytes ``` MaximalBy[Select[q=Rest@Subsets@#,!FreeQ[q,#~Riffle~_]&],Tr,1]& ``` [Try it online!](https://tio.run/##JU/LasMwELz7L0oghzJLJdlOnIPB5NBboU16M6YoQaYGOxBbhRbj/Lq7K7GSGO3OQxqs/3aD9d3Vrm25vtnfbrD98a8@u95dfX0vT27y1fnnMjk/VRs8vY7OfdR3bB6nrm179/hqtg0@R@hmu3omT@WczBoGKUiDUkb5gmTOkCNDKjBnqBUv2XGqVTjBJYBle2aTQRb78RaxEVcSvx1oL72CnSjVUFyZYbbZBRfRFSAO5n5IYEy6CAb8uJiqop/I6XCQULUkS/I@djdfPbcvVfjW@g8 "Wolfram Language (Mathematica) – Try It Online") High-level search ``` Select[q=Rest@Subsets@#, ] (*choose nonempty subsets of the input such that*) !FreeQ[q, ]& (*there exists a subset of the input which matches*) #~Riffle~_ (*this list, with an item inserted between adjacent elements*) MaximalBy[ ,Tr,1]& (*and return one with the greatest total*) ``` `,1` is required so as not to inadvertently return invalid sets (otherwise, for example, an input of `{1,1,1}` would result in an output of `{{1,1},{1,1},{1,1}}`) [Answer] # [Haskell](https://www.haskell.org/), ~~300~~ 168 bytes ``` import Data.List h[]=1>2 h(x:y)=fst$foldl(\a c->((fst a)&&(c-snd a>1),c))(1<2,x)y z=snd.last.sortOn fst.map((,)=<<sum.snd).filter(h.fst).map unzip.subsequences.zip[0..] ``` [Try it online!](https://tio.run/##FYzBboMwEETvfMUeomhXMitMq6aqMKceK/UDKAeXGGHVOJQ1UsLPU1dze/NmJis/LoTj8PNyWxO822T5w0sqpq43uq2LCe9vDzKjpNN4C9eAXxaGskXMBCydzziUEq9gW01qIELd1OpOj2I3GXOwkljy9WeEvODZLoiKTNPINnM2iEcfkltx4tzTvwBb3P3Csn2L@91cHJxwBl3F3B@z9REMLKuPCU6wQ/daVap80qrKea61utQv/fEH "Haskell – Try It Online") -132 bytes thanks to all the feedback from [@nimi](https://codegolf.stackexchange.com/users/34531/nimi) :) --- [Original](https://tio.run/##TY/BboMwEETv/oo9WJGtmgholVZR4VBVPfUPCFI2xIATYyh2JMPPU5NIVbWX1cybHW2L9iq1XhbVDf3o4BMdbr@VdeS/8HUzlVO9IXVRZkVJavDZrAbwRbzdamka14IvSfNwG@b3E89YhwPU1oEX62bNGTzfNzCRNnBJnpL2AQaG1r0@a3ZAqKKcsTWFfLNhVbTGME@4qDhnyXsqPJ/IJfTXSjs5sgNDceJR3sKJe3INRij7U9n9bsKeOIq7xAOkAxTOUo2h2IYnPyZW9d2Aozz25hjKAzQDZppe6YU21N5OVv7cpKmkpTXg0qEykMEwKuOAwgzFWxyL6DkRcZiXNBGv6a5cfgE "Haskell – Try It Online") ### Ungolfed (original) ``` import Data.List import Data.Function f :: [Int] -> [(Int, Int)] -- attach indices for later use f [] = [] f xs = zip xs [0..length xs] g :: [[(Int, Int)]] -> [([Int], [Int])] -- rearrange into list of tuples g [] = [] g (x:xs) = (map fst x, map snd x) : g xs h :: [Int] -> Bool -- predicate that checks if the indices are at least 2 apart from each other h [] = False h (x:xs) = fst $ foldl (\acc curr -> ((fst acc) && (curr - snd acc > 1), curr)) (True, x) xs j :: [([Int], [Int])] -> [([Int], [Int])] -- remove sets that don't satisfy the condition j xs = filter (\(elements, indices) -> h indices) xs k :: [([Int], [Int])] -> [(Int, ([Int], [Int]))] -- calculate some of elements k xs = map (\(elements, indices) -> (foldl1 (+) elements, (elements, indices))) xs l :: [(Int, ([Int], [Int]))] -> ([Int], [Int]) -- grab max l xs = snd $ last $ sortBy (compare `on` fst) xs z -- put things together ``` ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes ``` ≔⟦υ⟧ηFθ«≔υζ≔Eη⁺κ⟦ι⟧υ≔⁺ζηη»≔Φ⁺υηιη≔EηΣιζI§η⌕ζ⌈ζ ``` [Try it online!](https://tio.run/##VY1NC4JAEEDP@Sv2uAvjwaSTpwiEDoLQcdnDopZDutZ@hBj99s1Ng5rTDO/xpmqlrgbZeb83Bi@KcieAtCyLzoMm9M7IM9qsyAGZZvA9C3mjLZCyc4ZegXAUjAFxP8YHTSG3JF/RCnLsbKMX7haOq/MfP7meYsiGx6VGZelBGkv39qjqZgxKjqoOTwo5Yj/rEwuTec95AltIIU4gTudtJ4SPH90b "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⟦υ⟧η ``` The variable `u` is predefined with an empty list. This is put in a list which is assigned to `h`. These variables act as accumulators. `u` contains the sublists that include the latest element of the input `q` while `h` contains the sublists that do not (and therefore are suitable for appending the next element of the input). ``` Fθ« ``` Loop over the elements of the input. ``` ≔υζ ``` Save the list of sublists that contain the previous element. ``` ≔Eη⁺κ⟦ι⟧υ ``` Take all of the sublists that do not contain the previous element, append the current element, and save the result as the list of sublists that contain the current element. (I don't use `Push` here as I need to clone the list.) ``` ≔⁺ζηη» ``` Concatenate both previous sublists into the new list of sublists that do not contain the current element. ``` ≔Φ⁺υηιη ``` Concatenate the sublists one last time and remove the original empty list (which Charcoal can't sum anyway). ``` ≔EηΣιζ ``` Compute the sums of all of the sublists. ``` I§η⌕ζ⌈ζ ``` Find an index of the greatest sum and output the corresponding sublist. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 22 bytes ``` Êo à k_mÄ øZÃm!gU fÊñx ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVFo&code=ym8g4CBrX23EIPhaw20hZ1UKZsrxeA&input=Wy01LC0yLC0xLC02LC05XQ) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 21 bytes Ever have one of those challenges where you completely forget how to golf?! ``` ð¤à fÊk_än ø1îmgUÃñx ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=8KTgIGbKa1/kbiD4McOubWdVw/F4&input=Wy01LC0xOCwtMywtMSwtMTBdCi1R) ``` ð¤à fÊk_än ø1îmgUÃñx :Implicit input of array U ð :Indices of elements that return true when ¤ : Converted to a base-2 string (to account for 0s) à :Combinations f :Filter by Ê : Length (to remove the empty combination) k_ :Remove elements that return true än : Deltas ø1 : Contains 1 à :End remove ® :Map m : Map gU : Index into U à :End map ñ :Sort by x : Sum :Implicit output of last element ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~63~~ ~~70~~ 65 bytes ``` f=lambda a:a and max([a[:1],a[:1]+f(a[2:]),f(a[1:])],key=sum)or a ``` [Try it online!](https://tio.run/##XVBda8MwDHxef4UeEyaD7TgfDfSXGD94dGFlS1raDtZfn@rkZQ8DW5zOp5Osy@P@cV78uk6Hrzy/HTPlUe5ypDn/VDHH0SXW@DpVOfox1QzgBCT@fH8cbt9zfb5SXidEphudFopVdNxzSEx9zYSMPFPDZASZRrNWXvf6GiRhktgINSjVKuUsri0Aeuds8bNI7OaNI4TXHPa92hnpErRqE278v8FQYsoUnaD@b4wBzU0jKqsneJj4Dqat70q/4juIEL@ACtOF4gDOuOG3B36vsxtXp3H3crmeljvWJksVuSyzAgJcnw "Python 2 – Try It Online") 5 bytes thx to [ArBo](https://codegolf.stackexchange.com/users/82577/arbo) ]
[Question] [ Given two positive integers `a` and `b`, output the frequency distribution of rolling a `b`-sided die `a` times and summing the results. A frequency distribution lists the frequency of each possible sum if each possible sequence of dice rolls occurs once. Thus, the frequencies are integers whose sum equals `b**a`. ## Rules * The frequencies must be listed in increasing order of the sum to which the frequency corresponds. * Labeling the frequencies with the corresponding sums is allowed, but not required (since the sums can be inferred from the required order). * You do not have to handle inputs where the output exceeds the representable range of integers for your language. * Leading or trailing zeroes are not permitted. Only positive frequencies should appear in the output. ## Test Cases Format: `a b: output` ``` 1 6: [1, 1, 1, 1, 1, 1] 2 6: [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1] 3 6: [1, 3, 6, 10, 15, 21, 25, 27, 27, 25, 21, 15, 10, 6, 3, 1] 5 2: [1, 5, 10, 10, 5, 1] 6 4: [1, 6, 21, 56, 120, 216, 336, 456, 546, 580, 546, 456, 336, 216, 120, 56, 21, 6, 1] 10 10: [1, 10, 55, 220, 715, 2002, 5005, 11440, 24310, 48620, 92368, 167860, 293380, 495220, 810040, 1287484, 1992925, 3010150, 4443725, 6420700, 9091270, 12628000, 17223250, 23084500, 30427375, 39466306, 50402935, 63412580, 78629320, 96130540, 115921972, 137924380, 161963065, 187761310, 214938745, 243015388, 271421810, 299515480, 326602870, 351966340, 374894389, 394713550, 410820025, 422709100, 430000450, 432457640, 430000450, 422709100, 410820025, 394713550, 374894389, 351966340, 326602870, 299515480, 271421810, 243015388, 214938745, 187761310, 161963065, 137924380, 115921972, 96130540, 78629320, 63412580, 50402935, 39466306, 30427375, 23084500, 17223250, 12628000, 9091270, 6420700, 4443725, 3010150, 1992925, 1287484, 810040, 495220, 293380, 167860, 92368, 48620, 24310, 11440, 5005, 2002, 715, 220, 55, 10, 1] 5 50: [1, 5, 15, 35, 70, 126, 210, 330, 495, 715, 1001, 1365, 1820, 2380, 3060, 3876, 4845, 5985, 7315, 8855, 10626, 12650, 14950, 17550, 20475, 23751, 27405, 31465, 35960, 40920, 46376, 52360, 58905, 66045, 73815, 82251, 91390, 101270, 111930, 123410, 135751, 148995, 163185, 178365, 194580, 211876, 230300, 249900, 270725, 292825, 316246, 341030, 367215, 394835, 423920, 454496, 486585, 520205, 555370, 592090, 630371, 670215, 711620, 754580, 799085, 845121, 892670, 941710, 992215, 1044155, 1097496, 1152200, 1208225, 1265525, 1324050, 1383746, 1444555, 1506415, 1569260, 1633020, 1697621, 1762985, 1829030, 1895670, 1962815, 2030371, 2098240, 2166320, 2234505, 2302685, 2370746, 2438570, 2506035, 2573015, 2639380, 2704996, 2769725, 2833425, 2895950, 2957150, 3016881, 3075005, 3131390, 3185910, 3238445, 3288881, 3337110, 3383030, 3426545, 3467565, 3506006, 3541790, 3574845, 3605105, 3632510, 3657006, 3678545, 3697085, 3712590, 3725030, 3734381, 3740625, 3743750, 3743750, 3740625, 3734381, 3725030, 3712590, 3697085, 3678545, 3657006, 3632510, 3605105, 3574845, 3541790, 3506006, 3467565, 3426545, 3383030, 3337110, 3288881, 3238445, 3185910, 3131390, 3075005, 3016881, 2957150, 2895950, 2833425, 2769725, 2704996, 2639380, 2573015, 2506035, 2438570, 2370746, 2302685, 2234505, 2166320, 2098240, 2030371, 1962815, 1895670, 1829030, 1762985, 1697621, 1633020, 1569260, 1506415, 1444555, 1383746, 1324050, 1265525, 1208225, 1152200, 1097496, 1044155, 992215, 941710, 892670, 845121, 799085, 754580, 711620, 670215, 630371, 592090, 555370, 520205, 486585, 454496, 423920, 394835, 367215, 341030, 316246, 292825, 270725, 249900, 230300, 211876, 194580, 178365, 163185, 148995, 135751, 123410, 111930, 101270, 91390, 82251, 73815, 66045, 58905, 52360, 46376, 40920, 35960, 31465, 27405, 23751, 20475, 17550, 14950, 12650, 10626, 8855, 7315, 5985, 4845, 3876, 3060, 2380, 1820, 1365, 1001, 715, 495, 330, 210, 126, 70, 35, 15, 5, 1] ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 38 bytes ``` @(a,b)round(ifft(fft((a:a*b<a+b)).^a)) ``` [Try it online!](https://tio.run/##JcgxCoAwDEDR3ZMkGkpbbQdR8CRCqgZcLIh6/Ujp8Hnw8/bwd6jMxhhdgCnhnd9rh1PkgRLwyG2auEuIZmVEFXAUsRHwlb4SyBciDQVnydm6g0X9AQ "Octave – Try It Online") ### Explanation Adding independent random variables corresponds to convolving their probability mass functions (PMF), or multiplying their characteristic functions (CF). Thus the CF of the sum of `a` independent, identically distributed variables is given by that of a single variable raised to the power of `a`. The CF is essentially the Fourier transform of the PMF, and can thus be computed via a FFT. The PMF of a single `b`-sided die is uniform on `1`, `2`, ..., `b`. However, two modifications are required: * `1` is used instead of the actual probability values (`1/b`). This way the result will be de-normalized and will contain integers as required. * Padding with zeros is needed so that the FFT output has the appropriate size (`a*b-a+1`) and the implicit periodic behaviour assumed by the FFT doesn't affect the results. Once the characteristic function of the sum has been obtained, an inverse FFT is used to compute the final result, and rounding is applied to correct for floating-point inaccuracies. ### Example Consider inputs `a=2`, `b=6`. The code `a:a*b<a+b` builds a vector with `b=6` ones, zero-padded to size `a*b-a+1`: ``` [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0] ``` Then `fft(...)` gives ``` [36, -11.8-3.48i, 0.228+0.147i, -0.949-1.09i, 0.147+0.321i, -0.083-0.577i, -0.083+0.577i, 0.147-0.321i, -0.949+1.09i, 0.228-0.147i, -11.8+3.48i] ``` One can almost recognize the [sinc function](https://en.wikipedia.org/wiki/Sinc_function) here (Fourier transform of a rectangular pulse). `(...).^a` raises each entry to `a` and then `ifft(...)` takes the inverse FFT, which gives ``` [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1] ``` Although the results in this case are exactly integers, in general there may be relative errors of the order of `1e-16`, which is why `round(...)` is needed. [Answer] # Mathematica, 29 bytes ``` Tally[Tr/@Range@#2~Tuples~#]& ``` Just generates all possible dice rolls, takes their totals, then counts. Each frequency comes labeled with its value. # Mathematica, 38 bytes ``` CoefficientList[((x^#2-1)/(x-1))^#,x]& ``` Expands `(1+x+x^2+...+x^(a-1))^b` and takes the coefficients of `x`. Since `1+x+x^2+...+x^(a-1)` is the generating function for a single die roll and products correspond to convolutions - adding values of dice - the result gives the frequency distribution. [Answer] # [Haskell](https://www.haskell.org/), ~~90~~ ~~79~~ ~~77~~ 75 bytes Thanks to Lynn for the [Cartesian product trick](https://codegolf.stackexchange.com/a/52945/24877). -11 bytes thanks to many Haskell tricks from Funky Computer Man, -2 bytes from naming, -2 bytes thanks to Laikoni. Golfing suggestions are welcome! [Try it online!](https://tio.run/##Fcq7CsMwDEDRPV@hgGZDCXSqt4zJ1DF0UCDIpn5hyTR/7ybTgct1JN8jhN59LLkqzKRkFi86MJx2exhzfgYadxupQDgSq0OuuRWUa8e7Sou3KzDuL2SgHsknsFCavrUuCRDE5d/FND77Hw "Haskell – Try It Online") ``` import Data.List g x=[1..x] a!b=map length$group$sort$map sum$mapM g$b<$g a ``` **Ungolfed** ``` import Data.List rangeX x = [1..x] -- sums of all the rolls of b a-sided dice diceRolls a b = [sum y | y <- mapM rangeX $ fmap (const b) [1..a]] -- our dice distribution distrib a b = [length x | x <- group(sort(diceRolls a b))] ``` [Answer] # Pyth - 10 bytes Just takes all possible dice combinations by taking the cartesian product of `[1, b]`, `a` times, summing, and getting the length of each sum group. ``` lM.gksM^SE ``` [Test Suite](http://pyth.herokuapp.com/?code=lM.gksM%5ESE&test_suite=1&test_suite_input=1%0A6%0A2%0A6%0A3%0A6%0A5%0A2%0A6%0A4&debug=0&input_size=2). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` LIãO{γ€g ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fx/PwYv/qc5sfNa1J///fjMsYAA "05AB1E – Try It Online") ## How? ``` LIãO{γ€g - Full program. L - Range [1 ... input #1] I - Input #2. ã - Cartesian Power. O - Map with sum. { - Sort. γ - Group consecutive equal elements. €g - Get the length of each ``` [Answer] # [R](https://www.r-project.org/), 58 bytes ``` function(a,b)table(rowSums(expand.grid(rep(list(1:b),a)))) ``` [Try it online!](https://tio.run/##JcVBCoAgEADAe6/ouAtbkJWH6Be9QFNDMBUz6vdWNJdJxdRzU8zp12yDB0ESs5BOQwrXcu4H6DsKr9otWQVJR3D2yNBNEkngqxjoiGNlgP31fyOxL04Dlgc "R – Try It Online") [Answer] # [R](https://www.r-project.org/), 52 bytes ``` function(a,b)Re(fft(fft(a:(a*b)<a+b)^a,T)/(a*b-a+1)) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNRJ0kzKFUjLa0EjBOtNBK1kjRtErWTNOMSdUI09UF83URtQ03N/2kapjqmBpr/AQ "R – Try It Online") A port of [@Luis Mendo's Octave solution](https://codegolf.stackexchange.com/a/144197/67312), `fft(z, inverse=T)` unfortunately returns the unnormalized inverse FFT, so we have to divide by the length, and it returns a `complex` vector, so we take only the real part. [Answer] ## SageMath, 40 bytes ``` lambda a,b:reduce(convolution,[[1]*b]*a) ``` [Try it online](http://sagecell.sagemath.org/?z=eJxLs81JzE1KSVRI1EmyKkpNKU1O1UjOzyvLzyktyczP04mONozVSorVStTk5eLlStMw1jHTBADfEBA1&lang=sage) `convolution` computes the discrete convolution of two lists. `reduce` does what it says on the tin. `[1]*b` is a list of `b` `1`s, the frequency distribution of `1db`. `[[1]*b]*a` makes a nested list of `a` copies of `b` `1`s. --- # [Python 2](https://docs.python.org/2/) + [NumPy](https://numpy.org), 56 bytes ``` lambda a,b:reduce(numpy.convolve,[[1]*b]*a) import numpy ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFRJ8mqKDWlNDlVI680t6BSLzk/ryw/pyxVJzraMFYrKVYrUZMrM7cgv6hEAazgf0FRZl6JQpqGsY6Z5n8A "Python 2 – Try It Online") I've included this solution with the above one, since they're essentially equivalent. Note that this function returns a NumPy array and not a Python list, so the output looks a bit different if you `print` it. `numpy.ones((a,b))` is the "correct" way to make an array for use with NumPy, and thus it could be used in place of `[[1]*b]*a`, but it's unfortunately longer. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṗS€ĠẈ ``` **[Try it online!](https://tio.run/##ARkA5v9qZWxsef//4bmXU@KCrMSg4bqI////Nv8z "Jelly – Try It Online")** Note that this takes the arguments in reverse order. ## How? ``` ṗS€ĠL€ - Full program (dyadic) | Example: 6, 2 ṗ - Cartesian Power (with implicit range) | [[1, 1], [1, 2], ... , [6, 6]] S€ - Sum each | [2, 3, 4, ... , 12] Ġ - Group indices by values | [[1], [2, 7], [3, 8, 13], ... , [36]] L€ - Length of each group | [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1] ``` --- Alternative solutions: ``` ṗZSĠL€ ṗZSµLƙ ṗS€µLƙ ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~102~~ 91 bytes ``` lambda b,a:map(map(sum,product(*[range(a)]*b)).count,range(b*~-a+1)) from itertools import* ``` [Try it online!](https://tio.run/##Jci9DsIgFEDhnae4IyCatP4MTfokyABtURLgkls6uPjqqHU433DKqz4x982P9xZtcrMFp@yQbOG/1i2pQjhvU@VSk82PhVthpBPiNOGWq/o/J99He@iEYJ4wQagLVcS4QkgFqcoWYQStO3UzSve7592r6r/e1MUYxjwSBAgZ4sCgUMgVPJdBtA8 "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 61 bytes ``` g x=[1..x] a#b=[sum[1|m<-mapM g$b<$g a,sum m==n]|n<-[a..a*b]] ``` [Try it online!](https://tio.run/##VYzRisMgFETf8xUDzdNiQjRqlxI/Yb9AfDCwpKU1hG0LhXa/Peu9sQ8LzlVn5txjvJ6/L5d1nfBwXrbtI1RxNzp/vScvX2loUly@MNXjUE@IIttIzs3hNQ@Nj20bP8YQ1hRPMxyWn9N8Qw2709WzqSTsAV4K/DuhUm9fCfQCWsAIWJ6aHcW1/l3rOZVdVq4oAuneFxWPMupYBjJvoDa@BCTDiYXeEruhhtarjj5E93lo8oym8dmVF3ucco8JU1ZYXtz8rn8 "Haskell – Try It Online") Use as `a#b`. Partly based on [Sherlock9's Haskell answer](https://codegolf.stackexchange.com/a/144152/56433). [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` :Z^!Xs8#u ``` Same approach as [Maltysen's Pyth answer](https://codegolf.stackexchange.com/a/144147/36398). Inputs are in reverse order. [Try it online!](https://tio.run/##y00syfn/3yoqTjGi2EK59P9/Ey4zAA "MATL – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 26 bytes ``` a->b->Vec((1/(1-x)%x^b)^a) ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9R1y5J1y4sNVlDw1Bfw1C3QlO1Ii5JMy5R839BUWZeiUaahqGmhpmmJheMa4TKNUblmmoCFSC4ZpoaJkhcQwNNEEZRbgrk/wcA "Pari/GP – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 53 bytes ``` $g=join',',1..<>;map$r[eval]++,glob"+{$g}"x<>;say"@r" ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3TYrPzNPXUddx1BPz8bOOjexQKUoOrUsMSdWW1snPSc/SUm7WiW9VqkCKFmcWKnkUKT0/78Zl9G//IKSzPy84v@6vqZ6BoYGAA "Perl 5 – Try It Online") Input format: ``` b a ``` [Answer] ## JavaScript (ES6), 94 bytes ``` f=(n,m,a=[1],b=[])=>n?[...Array(m)].map((_,i)=>a.map((e,j)=>b[j+=i]=(b[j]|0)+e))&&f(n-1,m,b):a ``` ``` <div oninput=o.textContent=f(+n.value,+m.value).join`\n`><input id=n type=number min=0 value=0><input id=m type=number min=1 value=1><pre id=o>1 ``` Limited by 32-bit integer overflow, but floats could be used instead at a cost of 1 byte. [Answer] # [J](http://jsoftware.com/), ~~25 24 21~~ 20 bytes ``` 3 :'#/.~,+//y$i.{:y' ``` [Try it online!](https://tio.run/##y/r/P8VWT8FYwUpdWV@vTkdbX79SJVOv2qpS/X9qcka@Q4qDkp61XryRQnFJSmaeuvp/QwUzLiMgNgZiUwUjLjMFEy4A) Initially I incremented the [0..n-1] list to get [1..n] but apparently it’s not necessary. [Answer] # Javascript (ES6), 89 bytes ``` b=>g=a=>a?(l=[..."0".repeat(b-1),...g(a-1)]).map((_,i)=>eval(l.slice(i,i+b).join`+`)):[1] ``` Takes input in currying syntax in reverse order `f(b)(a)` ``` f=b=>g=a=>a>0?(l=[..."0".repeat(b-1),...g(a-1)]).map((_,i)=>eval(l.slice(i,i+b).join`+`)):[1] r=_=>{o.innerText=f(+inb.value)(+ina.value)} ``` ``` <input id=ina type=number min=0 onchange="r()" value=0> <input id=inb type=number min=1 onchange="r()" value=1> <pre id=o></pre> ``` [Answer] # [Actually](https://github.com/Mego/Seriously), ~~13~~ 12 bytes -1 byte thanks to Mr. Xcoder. [Try it online!](https://tio.run/##ASoA1f9hY3R1YWxsef//UuKImeKZgs6jO@KVl@KVlOKMoOKVnGPijKFN//8zCjY "Actually – Try It Online") ``` R∙♂Σ;╗╔⌠╜c⌡M ``` **Ungolfed** ``` Implicit input: b, a R∙ ath Cartesian power of [1..b] ♂Σ Get all the sums of the rolls, call them dice_rolls ;╗ Duplicate dice_rolls and save to register 0 ╔ Push uniquify(dice_rolls) ⌠ ⌡M Map over uniquify(dice_rolls), call the variable i ╜ Push dice_rolls from register 0 c dice_rolls.count(i) Implict return ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 191 bytes Outputs frequencies as a vertical column. ``` func p(z){for(m in z)S[z[m]]++ for(i=$1;i<=$1*$2;i++)print S[i]}func t(a,b,z,s){if(a){if(R++)for(n in z)for(i=0;i++<b;)s[n,i]=z[n]+i else for(i=0;i++<b;)s[i]=i t(--a,b,s)}else p(z)}{t($1,$2)} ``` [Try it online!](https://tio.run/##ZY6xDoMgFEV3v4KBgVcwqTbpov5EHQkDNpq8tKIRmiYYvp0Kjl3ucN85N09/XzFOH/MkK/OwT8vGZoKGeOill7NSnBepxI5WDbZHXmjdIOewbmgc6SWqkH3HtBiEFxZ2nJjO@Ti4ZJtz8hy6Jr0dGrDSCFSdl0ZxLMa3HckfcdyxcKws07iFkKn0atgdo5WgNYQYb@T@Aw "AWK – Try It Online") Adding 6 more bytes allows for multiple sets of inputs. ``` func p(z,S){for(m in z)S[z[m]]++ for(i=$1;i<=$1*$2;i++)print S[i]}func t(a,b,z,s){if(a){if(R++)for(n in z)for(i=0;i++<b;)s[n,i]=z[n]+i else for(i=0;i++<b;)s[i]=i t(--a,b,s)}else p(z)}{R=0;t($1,$2)} ``` [Try it online!](https://tio.run/##ZY6xDoMgFEV3voKBgVcwqbbpov6EjoRBG01e2lIjNE0wfDsFHbvc4b5zT97wfcQ4f8ydLtzLHrb5vfIXRUM99Mqrl9ZCkFxiy8oam5QnVtUoBCwrGkd7hTrsBscHOUovLWw482HPLnF5bQ7lITrneTPWYJWRqFuvjBZIpqed6B@R7kgcL4ostxB2Kj0LYesS5zgrJasgxHihN1LR6w8 "AWK – Try It Online") [Answer] ## Clojure, 86 bytes ``` #(sort-by key(frequencies(reduce(fn[r i](for[y(range %2)x r](+ x y 1)))[0](range %)))) ``` An example: ``` (def f #(...)) (f 5 4) ([5 1] [6 5] [7 15] [8 35] [9 65] [10 101] [11 135] [12 155] [13 155] [14 135] [15 101] [16 65] [17 35] [18 15] [19 5] [20 1]) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 142 bytes ``` i,j,k;int*f(a,b){int*r=malloc(sizeof(int)*(1+a*~-b));r[0]=1;for(i=1;i<=a;i++)for(j=i*~-b;j>=0;j--)for(k=1;k<b&k<=j;k++)r[j]+=r[j-k];return r;} ``` [Try it online!](https://tio.run/##TVDbcoMgFHxOvoKx0wYUW0mTviD5EccHNJqARjuAL83YX7cHTdLMcDkse9hly/hUltOL6sp2OFYote6o@vfzYVJU04arzoU1lrQgV18acZFt25fYqp@qrzFgJMQskuFvXBDCTZbkgvG6N1jBrlIhuYoi4gEtlGdxfRAJ13E8gw2wmrR4a1KheQNMk@k8ErDGTc5N5QbTIcPHCZTQRarOSyJpTuS6XvnSVdaV0lY2Y7scCXRl9ItuYX7C3M/VjrLEjz3dJyNfr2Z30KrAh0pvP3m8Qz6e/gbmxdZLzVpS/KupnN/Q4hmN2B0Pkans0DrwtATo8e/BlWdp8CbbLGcDzBoHr8eALnQIcL65m9QQkE59wriIGeEaMvJ@Hq30qVcvveOiZHGQBx4Y1@P0Bw "C (gcc) – Try It Online") [Answer] # [Julia](http://julialang.org/), 43 bytes ``` f(n,d)=reduce(conv,repmat([ones(Int,d)],n)) ``` [Try it online!](https://tio.run/##JclBCoMwEEDRvacYxMUMDCHamp3d9wziIpgELHYiaez100pWD/5/nftmTSkBhR1Nybtz9bhG@XLyx9tmnKP4Dz4l///CQlRCTGBhE5ixZ0MMOFRulZGHC8P3i15zr2seNS0NwJE2ybtg21mYHtBhQKuUImqp8eLKDw "Julia 0.6 – Try It Online") ]
[Question] [ ## Input None ## Output 52 cards. No duplicates. Cards are represented as their unicode characters, e.g. 🂹. The [Unicode codepoints](http://unicode.org/charts/PDF/U1F0A0.pdf) follow the following format: * The first three digits are `1F0`. * The next digit is `A`, `B`, `C`, or `D` for spades, hearts, diamonds, and clubs respectively. * The next digit is `1` through `C` and `E` for the various numbers/face cards. `1` is ace, `2`-`A` are the number cards, and `B`, `D`, and `E` are the jack, queen, and king respectively. (`C` is the knight, which isn't in most decks.) **Example output:** 🂶🃁🃛🃎🂧🂵🃗🂦🂽🂹🂣🃊🃚🂲🂡🂥🂷🃄🃃🃞🂺🂭🃑🃙🂪🃖🂳🃘🃒🂻🃆🂮🃍🂱🂴🃋🂸🃈🃅🃂🂨🃓🃉🂾🃇🂩🂢🂫🃔🃕🂤🃝 ## Rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer wins. * [Forbidden loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Your deck must be actually randomized. If run 20 times, 20 random (and most likely unique) outputs must be generated. ## Note If you only see boxes, install [the DejaVu fonts](https://dejavu-fonts.github.io/). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~25 23~~ 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 62R%⁴g180<11T+“¢¬⁷’ẊỌ ``` A niladic link returning a list of characters, or a full program that prints the shuffled deck. **[Try it online!](https://tio.run/##ATUAyv9qZWxsef//NjJSJeKBtGcxODA8MTFUK@KAnMKiwqzigbfigJnhuorhu4z///Vuby1jYWNoZQ)** ### How? ``` 62R%⁴g180<11T+“¢¬⁷’ẊỌ - Main link: no arguments 62 - literal 62 R - range(62) -> [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] ⁴ - literal 16 % - modulo -> [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14] 180 - literal 180 g - G.C.D. -> [1,2,3,4,5,6,1,4,9,10, 1,12, 1, 2,15,180, 1, 2, 3, 4, 5, 6, 1, 4, 9,10, 1,12, 1, 2,15,180, 1, 2, 3, 4, 5, 6, 1, 4, 9,10, 1,12, 1, 2,15,180, 1, 2, 3, 4, 5, 6, 1, 4, 9,10, 1,12, 1, 2] 11 - literal 11 < - less than?-> [1,1,1,1,1,1,1,1,1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1] T - truthy -> [1,2,3,4,5,6,7,8,9,10,11, 13,14, 17,18,19,20,21,22,23,24,25,26,27, 29,30, 33,34,35,36,37,38,39,40,41,42,43, 45,46, 49,50,51,52,53,54,55,56,57,58,59, 61,62] “¢¬⁷’ - base 250 number 127136 + - addition (vectorises) -> card character ordinals Ẋ - shuffle the list Ọ - convert to characters - full program has an implicit print ``` [Answer] # JavaScript (ES6), ~~107~~ ~~106~~ 108 bytes ``` a=[] for(S of'ABCD')for(N of'123456789ABDE')a.splice(Math.random()*-~a.length,0,eval(`'\\u\{1F0${S+N}}'`)) a ``` ``` a=[] for(S of'ABCD')for(N of'123456789ABDE')a.splice(Math.random()*-~a.length,0,eval(`'\\u\{1F0${S+N}}'`)) a o.innerHTML = a.join`` ``` ``` <div id=o style="font-size:80px"></div> ``` -1 byte thanks to [@nderscore](https://codegolf.stackexchange.com/questions/124565/print-a-shuffled-deck-of-cards/124606#comment306395_124606) --- # JavaScript (ES6), ~~120~~ ~~119~~ 121 bytes Previous version. ``` a=[],[...'ABCD'].map(S=>[...'123456789ABCE'].map(N=>a.splice(Math.random()*-~a.length|0,0,eval("'\\u\{1F0"+S+N+"}'")))),a ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~106~~ 94 bytes -5 bytes thanks to musicman523 (1. use `sample(...,52)` as an inline equivalent to `shuffle` [thanks to totallyhuman]; 2. use `~v&2` instead of `v%4<2`; plus a further 1 byte as a consequence as a space may be removed) ``` from random import* print(*sample([chr(v+127137)for v in range(63)if~v&2or~v%16>4],52),sep='') ``` **[Try it online!](https://tio.run/##FcsxDsIgFADQ3VOw2EKtA2DbSS9iHAiCkAj/55eQdOmtnVGnNz3cSoCsW/MEiZHJzx8xIVAZDkgxFz6sJuHb8bsNxOtJqkXqRXggVlnM//NyfNYi@r12CmivRznfLo9xUmJcHV77XrT2yXC2xgb3BQ)** [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~22~~ 21 bytes Saved 1 byte thanks to *carusocomputing*. ``` …1F0A4£14L13KhJâ«Hç.r ``` [Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//@KApjFGMEE0wqMxNEwxM0toSsOiwqtIw6cucv//9W5vLWNhY2hl "05AB1E – Try It Online") **Explanation** ``` …1F0 # push the string "1F0" A4£ # push the string "abcd" 14L # push range [1 ... 14] 13K # remove 13 h # convert to hexadecimal J # join to string "123456789ABCE" â # cartesian product « # prepend the string to each char in the list H # convert to decimal ç # get the chars with those code points .r # randomize ``` [Answer] # Bash + coreutils, 56 bytes ``` printf %b\\n \\U1F0{A..D}{{1..9},A,B,D,E}|shuf|tr -d \\n ``` We use `printf` to write each card on its own line, shuffle the lines, then concatenate all the lines by removing the newline characters. Note that although the coreutils `printf` command requires exactly 8 hexadecimal digits after `\U`, the Bash built-in `printf` lets us omit leading zeros. [Answer] # [Python 3](https://docs.python.org/3/), 112 bytes ``` from random import* *a,=map(chr,range(127136,127200)) del a[::16],a[::-15],a[11::14] shuffle(a) print(*a,sep='') ``` [Try it online!](https://tio.run/##FczBCoMwEATQe77Cm4mk4GprQfBLioelJo1gkmVND/36dD29YQaGfiXkNNbqOceGMW3CHilz6VSHdolI@h3YyvRxGoYnjJMVhr43Rm3uaPA1zzCt9vIGjysASHVf1Rm@3h9Oo1HEeypaHk9HS9uaWv8 "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 107 bytes Saved 6 bytes thanks to @totallyhuman and 3 thanks to @CCB60! ``` from random import* print(*sample([chr(int('1F0'+a+b,16))for a in'ABCD'for b in'123456789ABDE'],52),sep='') ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehKDEvBUhl5hbkF5VocRUUZeaVaGgVJ@YW5KRqRCdnFGmABNQN3QzUtRO1k3QMzTQ10/KLFBIVMvPUHZ2cXdRBvCQQz9DI2MTUzNzC0tHJxVU9VsfUSFOnOLXAVl1d8///r3n5usmJyRmpAAA) [Answer] # [PHP](https://php.net/)>=7, 102 bytes ``` for(;$i++<64;)in_array(($c=127136+$i)%16,[0,12,15])?:$q[]=IntlChar::chr($c);shuffle($q);echo join($q); ``` No Online Interpreter available for the [IntlChar::chr](http://php.net/manual/en/intlchar.chr.php) method # [PHP](https://php.net/), 112 bytes ``` for(;$n++<4;shuffle($r))for($i=0;$i++<14;)$i==12?:$r[]=pack("c*",240,159,131-($n>2),$n*16+112+$i);echo join($r); ``` [Try it online!](https://tio.run/##FYyxCsIwFAB3v0LkDUmTQl@sgqa1g3Rw0cVNpJSQmqgkIerqXzvHdrw7uGBCqppgwkzH6GMXdfDxbd2NfNvueDof9i2VafCRSHCMVaV8mc8wPDWBSOnkwdaFBDs2LCUdqUbRbCFernXo1YMsVLbgoiw4rjYcl5gTcDtBObgM1wxRMLBUamX8/O6tm74ypZ/zueqV0X8 "PHP – Try It Online") # [PHP](https://php.net/), 116 bytes ``` for(;$c=ab89[$n++];shuffle($r))for($i=0;$i++<14;)$i==12?:$r[]=hex2bin(f09f8.(2+($n>2)).$c.dechex($i));echo join($r); ``` [Try it online!](https://tio.run/##FYyxDsIgFEV3v8LhDbwQm5Y4tFLsYDq46OJmmqZFEIwBgpo4@dfOiNu9OefeYEJqu2DCQsXo4xhV8PFp3ZV8@vFwPO13PfKkfSQcpJjmujmDo3TgD/PS@q4IRMQ/BitKDpbStlpzzE1UrNtAPA/CqDebrSO6bHRdEEYJuC1DLEAWFyUzzmtEnqNf3nw28ylP6ev8Sk6Z/wA "PHP – Try It Online") # PHP, 121 Bytes ``` for(;$c=ABCD[$n++];shuffle($r))for($i=0;$i++<14;)$i==12?:$r[]=json_decode('"\ud83c\udc'.$c.dechex($i).'"');echo join($r); ``` [Try it online!](https://tio.run/##FYxbC8IgGIb/SowPVCRp1UXMyejwL9aI8ICOUHEM@uNd27ebF573lH2u/ZBRXSpUglbX2/0xQuR8kotfnftYCoWxLYagDhIC5317lgxJtcehgzJOal5SfBmrk7GUNM/VXE4aVRMBWqDv7RfnTJCGMImYdnMKcXuWtf5i2us3dv4 "PHP – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~40~~ 38 bytes ### [Jonathan Allan's method](https://codegolf.stackexchange.com/a/124569/43319) ``` ⎕UCS((11>180∨16|⍳62)/127136+⍳62)[?⍨52] ``` `(`…`)` on the following array  `⍳62` the first 62 integers  `127136+` add 127136 to that  `(`…`)/` filter that with the Boolean   `⍳62` first 62 integers   `16|` modulus 16   `180∨` GCD of 180 and that   `11>` whether 11 is greater than those `[`…`]` select the following elements  `?⍨52` shuffle the first 52 integers (pick 52 random integers out of a bag of the first 52 integers) `⎕UCS` convert to corresponding symbols in the **U**nicode **C**haracter **S**et --- ### Version 16.0 (currently in beta) solution (33 characters) ``` ⎕UCS(127136+⍸11>180∨16|⍳62)[?⍨52] ``` `(`…`)` on the following array  `⍳62` first 62 integers  `16|` modulus 16  `180∨` GCD of 180 and that  `11>` whether 11 is greater than those  `⍸` indices where True  `127136+` add 127136 to that `[`…`]` select the following elements  `?⍨52` shuffle the first 52 integers (pick 52 random integers out of a bag of the first 52 integers) `⎕UCS` convert to corresponding symbols in the **U**nicode **C**haracter **S**et --- [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes ``` A¹²⁷¹³⁶χA⪫E…χ⁺⁶⁴χ℅ιωσWσ«A‽σχA⪫⪪σχωσ¿﹪﹪﹪℅χ¹⁶¦¹⁵¦¹³χ ``` [Try it online!](https://tio.run/##XY3BDoIwDIbP4yl27BI4IIoHT8abCZHoEywDoUnZyAZyMD773CKJxkP/pn/b71e9tMpI8v7oHHYa8s0@L8qUK3FIVutsUEMlR7hK3bWgUl7T7KDcxiuR8lNgSDW1FjCOSygXvpceqeXgBH8mbEUFQmOG4H0C2G/CbSScwMXNF8LwzqEyzUzmr11sg1oSxOu8jLKLUgiRMFZb1BPEiJf3Pnv4zNEb "Charcoal – Try It Online") Link is to verbose version of code. Creates the string of all the 64 characters in the block but filters invalid cards out as they are randomly selected. (Speaking of which, random selection without replacement from a string is only 11 bytes, compared to 17 for an array.) Edit: Subtraction from an array and other Charcoal improvements have cut down the size to 41 bytes: [Try it online!](https://tio.run/##XYy9DsIgFIVneIo73pvQoVbr4GScGxt9AqTVkiBYaHUwPjtC1MXlnOQ7P2qQXjlpYtyGoC8WG3nDeilglwKppt5ja@aA5WJdVrUATUQCRtrwx6BNDzgSPDn7jg/Sdu6amIAhVX74OJ@mfIZj5p8502fAxnWzcX@295220mBulnWWVZaKiDPWem0nzOevGGNxj0Uwbw "Charcoal – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 23 bytes ``` kA4Ẏk^ḢṪ\DoẊ`1F0`vpHCÞ℅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrQTThuo5rXuG4ouG5qlxcRG/huopgMUYwYHZwSEPDnuKEhSIsIiIsIiJd) Port of 05AB1E. ## How? ``` kA4Ẏk^ḢṪ\DoẊ`1F0`vpHCÞ℅ kA4Ẏ # Get the first 4 letters of the uppercase alphabet k^ # Push string "0123456789ABCDEF" ḢṪ # Remove head and tail: "123456789ABCDE" \Do # Remove the D: "123456789ABCE" Ẋ # Cartesian product of strings: ["A1", "A2", "A3", "A4", ..., "DC", "DE"] `1F0` # Push string "1FO" vp # Prepend to each: ["1FOA1", "1FOA2", ..., "1FODE"] H # Convert each from hexadecimal: [127137, 127137, ..., 127198] C # Convert each to their unicode representation: ["🂡", "🂢", ... "🃞"] Þ℅ # Randomly shuffle ``` Port of Jelly is same byte count: # [Vyxal](https://github.com/Vyxal/Vyxal), 23 bytes ``` 62ɾ16%180ġ11<T»ƛǔḭ»+CÞ℅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI2Msm+MTYlMTgwxKExMTxUwrvGm8eU4bitwrsrQ8Oe4oSFIiwiIiwiIl0=) ## How? ``` 62ɾ16%180ġ11<T»ƛǔḭ»+CÞ℅ 62ɾ # Push range [1, 2, ..., 62] 16% # Modulo each by 16 180ġ # GCD each with 180: [1, 2, 3, 4, 5, 6, 1, 4, 9, 10, ..., 12, 1, 2] 11<T # Indices where item is less than 11: [0, 1, 2, 3, ... 13, 16, 17, ..., 26, ...] »ƛǔḭ» # Push compressed integer 127137 + # Add to each (vectorizes) C # Convert each to their unicode representation Þ℅ # Randomly shuffle ``` For both solutions, add `s` flag if it needs to be a string instead of a list. [Answer] # [Alice](https://github.com/m-ender/alice), 34 bytes ``` '?rwd.n$@U,!6?44*%a7+-F$K?'🂡+OK ``` [Try it online!](https://tio.run/##S8zJTE79/1/dvqg8RS9PxSFUR9HM3sRESzXRXFvXTcXbXv3D/KaF2v7e//9/zcvXTU5MzkgFAA "Alice – Try It Online") ### Explanation ``` '?r push numbers 0-63 onto stack w store return address (start main loop) d get stack depth .n$@ if zero, terminate U random number in [0, depth) , move corresponding stack element to top ! store on tape ? copy back from tape 44*% mod 16 a7+- subtract 17 6 F does the result divide 6? $K if so, return to start of main loop ? copy card number from tape again '🂡+ add 0x1F0A1 O output K return to start of main loop ``` [Answer] ## [><>](https://esolangs.org/wiki/Fish), ~~49~~ ~~50~~ 49 bytes ``` "🂡"v =?v>:1+}:88+%:c-:3-**?!~{l4d* {>x o^>l?!; ``` [Try it online!](https://tio.run/##S8sszvj/X@nD/KaFSmVctvZldlaG2rVWFhbaqlbJulbGulpa9op11TkmKVpc1XYVXPlxdjn2itb//3/Ny9dNTkzOSAUA "><> – Try It Online") *(+1 byte to make the randomness better)* I'm interpreting "random" to mean "every possible outcome has a non-zero probability". This isn't a uniform distribution. There are two stages to this code. First, the fish puts all the cards on the stack, using the first two lines. Starting with the ace of spades, the fish duplicates and increments it, then checks if the previous card's hex code ends in 0, C or F by multiplying together *x* (*x*-12) (*x*-15), where *x* is the charcode mod 16, and checking if that's zero. If it is, it deletes the offending card from the stack. It repeats until the stack has 52 cards, then swims into stage 2: ``` v {>x o^>l?!; ``` This bit of code shuffles and prints the stack. The `x` sets the fish's direction randomly: * If the fish swims up, it hits the `v` and goes back to the `x` without doing anything. The left direction is similar. * If the fish swims right, it wraps and hits the `{`, rotating the entire stack to the left, then returns to the `x`. * If the fish swims down, it prints the card at the front of the stack then returns to the `x`. It's clear that every possible order of the cards can be produced: at any point in stage 2, every card that hasn't been printed yet can be printed next if the fish swims rightwards enough times. This shuffling technique usually doesn't move cards very far apart if they were already near each other, but then again, [neither does shuffling by hand](https://www.math.upenn.edu/~pemantle/papers/overhand2.pdf). [Answer] # R, 61 bytes ``` cat(intToUtf8(sample(c(127137:127198)[-c(12,28,44,47,60)]))) ``` Randomly sample the vector of integer representations of the cards unicode values (which can be obtained from `utf8ToInt()` fucntion) and remove the unwanted knight/joker cards. [Answer] ## C# (146 141 bytes) ``` using System.Linq;()=>Enumerable.Range(0,52).OrderBy(i=>System.Guid.NewGuid()).Aggregate("",(s,i)=>s+"\uD83C"+(char)(56481+i+i/13*3+i%13/12)) ``` [Online demo](http://ideone.com/BgEiYG) This uses extremely bad style in shuffling with `Guid.NewGuid()`, but it's code-golf. It then builds the surrogate pairs manually. [Answer] # Perl 5, 75 bytes ``` @c=map{7946+$_%4+$_/64}4..51,56..59;print chr(16*splice@c,@c*rand,1)while@c ``` Note that this uses the code points for queens as given in the question (i.e. last digit `C`). For the actual code points (last digit `D`), replace `51,56` with `47,52`. [Answer] # Java 8, 216 bytes ``` import java.util.*;()->{List<Long>l=new ArrayList();for(long i=52;i-->0;l.add(i));Collections.shuffle(l);for(Long x:l)System.out.print((char)(x.parseLong("1F0"+(char)(65+x/12)+((x%=4)>9?(char)(x>2?69:65+x):x),16)));} ``` **Explanation:** [Try it here.](https://tio.run/##PVDLbsIwELznK1ZIlezSmIcKEqQJqir1RFEljlUPi@MQU2NHtkODEJ/dc3AK7WWlndnZ3ZkdHjA2ldC7/KuV@8pYD7uAsdpLxe4TGAzgHQNoCvClgM3Ri5ibWvso4gqdgzeU@hQBSO2FLZALWHUtwMHIHDihSejOUSjOo5ccVqAhhZbQODstpfNPS6O3mUq1@IZna/HYgUFWGEtUoECmk3Ei4zgbJophnhNJafJilBLcS6Mdc2VdFEoQdRV1@6CZK7o@Oi/2zNSeVTb8Rwgv0VLSsAqtE90c6Y1eh73@jZhO@s1gNKZ9Qpq79JFms8WfJBsvprN5N0DnDX0YTWl44twmnbGq3qhg7Obv1/c@pELWPlzdfnwC0mskmv3ncW5/tIk58lJcAA) NOTE: Untested because even though I've installed the linked font, I still see boxes. Probably have to restart my PC or something.. ``` import java.util.*; // Required import for List, ArrayList and Collections ()->{ // Method without parameter nor return-type List<Long>l=new ArrayList(); // List for(long i=52;i-->0;l.add(i)); // Fill the list with 1 through 52 Collections.shuffle(l); // Randomly shuffle the list for(Long x:l) // Loop over the shuffled list System.out.print( // Print the following character: (char)(x.parseLong( // Convert the following String to a character: "1F0"+ // The literal String "1F0" + (char)(65+x/12)+ // either A, B, C or D by using x/12, adding 65, // and casting it to a char + ((x%=4)>9? // If the current item mod-4 is 10 or higher: (char)(x>2?69:65+x) // Convert it to A, B, C or E : // Else (1 through 9): x) // Simply add this digit ,16)) ); } // End of method ``` [Answer] # Dyalog APL, 35 bytes ``` ⎕ucs(∊127150+(16×⍳4)-⊂2~⍨⍳14)[?⍨52] ``` based on [Adám's answer](https://codegolf.stackexchange.com/questions/124565/print-a-shuffled-deck-of-cards#answer-125024) uses `⎕io←0` [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~51~~ ~~41~~ ~~39~~ 22 bytes With some inspiration from [Jonathan's Jelly solution](https://codegolf.stackexchange.com/a/124569/58974). ``` #?ö¬k@B§XuG y#´Ãmd## ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=Iz/2rGtAQqdYdUcgeSO0w21kI38jiA==&input=LVM=) (or [view output with increased `font-size`](https://ethproductions.github.io/japt/?v=1.4.5&code=Iz/2rGtAQqdYdUcgeSO0w21kI38jiA==&input=LVM=)) --- ## Explanation ``` #? :63 ö¬ :Random permutation of range [0,63) k :Remove elements that return true @ :When passed through this function B : 11 § : Less than or equal to X : Current element u : Modulo G : 16 y : GCD #´ : 180 à :End function m :Map ## : Add 127136 d : Get character at that codepoint ``` ]
[Question] [ **Updates: Time limit removed. You must be able to describe output - see new rule.** A [pangram](http://en.wikipedia.org/wiki/Pangram) is a sentence that uses every letter in the alphabet at least once, such as: > > *[The quick brown fox jumps over the lazy dog.](http://en.wikipedia.org/wiki/The_quick_brown_fox_jumps_over_the_lazy_dog)* > > > A *perfect* pangram uses every letter exactly once. Consider writing a program that is a perfect pangram, using the 95 [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters (hex codes 20 to 7E) as the alphabet: ``` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` Such a program must contain exactly 95 characters, with each printable ASCII character occurring exactly once, but in any order. (Thus there are 95! = 1.03×10148 possibilities.) Your task is to write this program such that the number of printable ASCII characters printed to stdout is as high as possible (i.e. prolific). Your score is the number of printable ASCII characters your program outputs **(the *total* amount, not the *distinct* amount: `AABC` scores 4 whereas `ABC` scores 3)**. The highest score wins. # Details * The output may contain any characters (including duplicates) but only instances of the 95 printable ASCII characters count towards your score. + You can use [this JSFiddle](http://jsfiddle.net/CalvinsHobbies/6x5c1b0c/#base) to count the number of printable ASCII characters in any string. * If your language does not have stdout use the most appropriate alternative. * Your program... + must have finite runtime **(the time limit has been removed)** + must have finite output + may contain comments + must compile and run without (uncaught) errors + must not prompt for or require input + must be time invariant and deterministic + must not use external libraries + must not require a network connection + must not make use of external files - (you may use the program file itself as long as changing the file name does not alter the program's behavior) * If this task is impossible is some language that's just too bad. * You must give your exact output **or precisely describe it if it is too large to fit in a post**. You do not actually have to run your program. As long as it *would* run in a finite amount of time on a computer with an unbounded amount of memory it is valid. # Example This simplistic Python 2 program is a possible solution: ``` print 9876543210#!"$%&'()*+,-./:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghjklmoqsuvwxyz{|}~ ``` It outputs `9876543210` which contains 10 printable ASCII characters, thus scoring 10. [Answer] # Perl, 70\*18446744073709551615\*10^987654320 ``` say q{!"#%&'+,-./:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\]^_`bcdfghijklmnoprtuvwz|}x(1e987654320*~$[) ``` Output: ``` !"#%&'+,-./:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\]^_`bcdfghijklmnoprtuvwz| ``` repeated **18446744073709551615\*10^987654320** times. `$[` is by default `0`, so `~$[` is equivalent to `18446744073709551615`. As a side note, I ran out of memory trying to create the number `10^987654320`. --- ## Old Answer (7703703696): ``` say qw(!"#$%&'*+,-./:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`bcdefghijklmnoprtuvz{|}~10)x98765432 ``` Output is: ``` !"#$%&'*+,-./:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`bcdefghijklmnoprtuvz{|}~10 ``` repeated 98765432 times. Note: Run all samples with `perl -Mbignum -E` [Answer] # GolfScript, over 2↑↑↑(9871↑↑2) chars ``` 2 9871.?,{;0$[45)63]n+*~}/ #!"%&'(-:<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ\^_`abcdefghijklmopqrstuvwxyz| ``` Prints an integer. Take advantage of unlimited [CPU register size](https://codegolf.stackexchange.com/users/26997/calvins-hobbies) (which determines the maximum string length in Ruby), memory and run time. The linefeed is solely for readability. ### The code ``` 2 # Push 2. 9871.? # Push b := 9871↑↑2 = 9871↑9871 = 9871**9871. ,{ # For each i from 0 to b - 1: ;0$ # Discard i and duplicate the integer on the stack. [45)63]n+* # Replicate ".?\n" that many times. ~ # Evaluate. }/ # ``` ### The score Define **b = 9871↑↑2** (see [Knuth's up-arrow notation](http://en.wikipedia.org/wiki/Knuth's_up-arrow_notation)). * **.?** executes **f : x ↦ x↑x**. * The inner block executes **g : x ↦ fx(x)**. Since **f(x) = x↑x = x↑↑2**, **f2(x) = (x↑x)↑(x↑x) > x↑x↑x = x↑↑3**, **f3(x) = ((x↑x)↑(x↑x))↑((x↑x)↑(x↑x)) > (x↑x↑x)↑(x↑x↑x) > x↑x↑x↑x = x↑↑4** and so forth, we have **g(x) > x↑↑(x+1) > x↑↑x**. * The outer block executes **h : x ↦ gb(x)**. Since **g(x) = x↑↑x = x↑↑↑2**, **g2(x) = (x↑↑x)↑↑(x↑↑x) > x↑↑x↑↑x = x↑↑↑3**, **g3(x) = ((x↑↑x)↑↑(x↑↑x))↑↑((x↑↑x)↑↑(x↑↑x)) > (x↑↑x↑↑x)↑(x↑↑x↑↑x) > x↑↑x↑↑x↑↑x = x↑↑↑4** and so forth, we have **h(x) > x↑↑↑(b+1)**. * We start with the integer **2** on the stack, so the code calculates **h(2) > 2↑↑↑(b+1).** * The score is the number of decimal digits of **h(2)**, which is **log(h(2)) + 1 > log(2↑↑↑(b+1)) > 2↑↑↑b**. Thus, the score is larger than **2↑↑↑(9871↑↑2)**. **2↑↑↑n** grows at a ridiculous pace as **n** gets larger. **2↑↑↑4 := 2↑↑2↑↑2↑↑2 = 2↑↑2↑↑4 = 2↑↑65536**, which is a right-associative power tower of **65536** copies of **2**:                                                                 [![2↑↑↑4](https://i.stack.imgur.com/AQQdt.png)](http://en.wikipedia.org/wiki/Knuth's_up-arrow_notation#Computing_2.E2.86.91mn "Knuth's up-arrow notation # Computing 2↑ᵐn")                                                                  Similarly, **2↑↑↑5 := 2↑↑(2↑↑↑4)**, which is a power tower of **2↑↑↑4** copies of **2**. Now, the score isn't **2↑↑↑4** or **2↑↑↑5**, it's larger than **2↑↑↑b**, where **b > 2 × 1039 428**. That's a big number... [Answer] # Bash+coreutils, 151,888,888,888,888,905 (1.5\*10^17) ``` seq 9E15;#\!%*+,-./2346780:=@ABCDFGHIJKLMNOPQRSTUVWXYZ]^_abcdfghijklmnoprtuvwxyz~"'$&()?<>`{}|[ ``` Outputs integers 1 to 9x1015, one per line. Takes a long time. Why `9E15`? It turns out that GNU `seq` appears to use 64-bit floats (double) internally. The largest whole number we can represent with this type, before increment by one stops working due to lack of precision, is 253 or 9007199254740992. The closest we can get to this with exponential notation is 9E15 or 9000000000000000. To calculate the score, I am using adding up all the numbers with a given number of digits and adding 9E15, because there is a newline between each number: ``` 8000000000000001*16 + 900000000000000*15 + 90000000000000*14 + 9000000000000*13 + 900000000000*12 + 90000000000*11 + 9000000000*10 + 900000000*9 + 90000000*8 + 9000000*7 + 900000*6 + 90000*5 + 9000*4 + 900*3 + 90*2 + 9 + 9000000000000000 ``` I could pipe this output through `od` for an extra order of magnitude or so, but that makes the score calculation much harder. --- Pre-rule change answer: # Bash+coreutils, 18,926,221,380 ``` seq 1592346780;#\!%*+,-./:=@ABCDEFGHIJKLMNOPQRSTUVWXYZ]^_abcdfghijklmnoprtuvwxyz~"'$&()?<>`{}|[ ``` Outputs 1 to 1592346780. On my mid 2012 macbook (which is not that far off the linked benchmark), this takes about 9m45s. I couldn't resist optimizing it a bit more, even though its probably meaningless. ### Output: ``` $ time ./pangram.sh | wc 1592346780 1592346780 18926221380 real 9m46.564s user 11m7.419s sys 0m10.974s $ ``` [Answer] ## GolfScript, ≈ 3\*10^(2\*10^7) i.e. ≈ 3x1020000000 ``` 87 9654321?,`0${;.p}/#!"%&'()*+-9:<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_abcdefghijklmnoqrstuvwxyz|~ ``` **How it works** ``` 87 9654321? "Pushes 87^9654321 to stack"; , "Pushes an array [0, 1, 2 ... (87^9654321) - 1] to stack"; ` "Creates a string representation of the array like "[0 1 2...]"; 0$ "Copies the string"; {;.p}/ "Print the string wrapped in quotes X times"; #... "This is all comment"; ``` Here `X` is the character count (length) of the string representation of the array `[0, 1, 2..,(87^9654321) - 1]` which will be like `[0 1 2 3 4 ... (87^9654321) - 1]` ~~I am trying to calculate `X` here so as to find my score. `(87^9654321) - 1` is roughly `10^(10^7.272415829713899)` with `18724742` decimal digits.~~ `X` is roughly `3*10^(2*10^7)` so `X*X` is also same only. Note that these values are on a very lower side as due to computation limitations of [(even) wolframa](http://www.wolframalpha.com/input/?i=sum%20%28floor%28log10%28x%29%29%20%2B%201%29%20for%20x%20%3D%201%20to%20%2887%5E9654321%20-%201%29), I was not able to compute `sum (floor(log10(x)) + 1) for x = 1 to (87^9654321 - 1)` which is the true value of `X` [Answer] # MATLAB, 95 Code ``` char(37-5:126)% !"#$&'*+,./0489;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`bdefgijklmnopqstuvwxyz{|}~ ``` Output ``` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` Output contains all specified ASCII characters, each exactly once, and in order. [Answer] # Ruby, 89 ``` p %q{!"#$&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnorstuvwxyz|~} ``` Output: ``` "!\"\#$&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnorstuvwxyz|~" ``` Contains all ASCII characters except, `p`, , `%`, `q`, `{`, and `}`. [Answer] # GolfScript, 93 ``` { !#$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz|~} ``` Output: ``` { !#$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz|~} } ``` Contains all ASCII characters except `"` and `'`. [Answer] # Golfscript - 27\*265439870 This my first Golfscript submission! :) ``` 12,`{.+}6543 9870?*#!"$%&'()-/:;<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_abcdefghijklmnopqrstuvwxyz|~ ``` Explanation: ``` 12, - Creates an array of ascending numbers from 0 to 11 ` - Converts the array to a string {.+} - Duplicates the string on the stack and concatenates the two 6543 9870? - Calculates 6543^9870 and pushes it to the stack * - Repeat the block 6543^9870 times #... - The rest is a comment ``` The output is a load of lists of numbers. Consider the following code: ``` 12,`{.+}1* ``` With `12,` it produces the following array: ``` [0 1 2 3 4 5 6 7 8 9 10 11] ``` The backtick turns that into a string, passing it to the block `{.+}`. This duplicates the string and then concatenates the two, producing: ``` [0 1 2 3 4 5 6 7 8 9 10 11][0 1 2 3 4 5 6 7 8 9 10 11] ``` The `1*` tells the interpreter to execute the previous block one time (21 = 2). So, based upon that: ``` 12,`{.+}n* ``` Outputs the output of `12,`` 2n times. ]
[Question] [ Good Afternoon, Your goal is to, in the least amount of source code bytes, recreate any of Piet Mondrian's 'Composition' paintings (for instance, [Composition #10](https://i.stack.imgur.com/MnYZx.jpg)). The recreation can either use the actual colors, or replace it with the appropriate colours from the [Windows Default 16 Color Palette.](http://en.wikipedia.org/wiki/File:Windows_16colors_palette.png) Your recreation can be outputted in PNG, BMP or NetPBM, either to a file or to STDOUT, or directly to the screen. Your recreation must be a resolution of 512x512 or higher. Your recreation must not access the internet. If your program requires data files, then their size will be added to the size of your source. Your score will be the size of your source file in bytes. Please state with your entry which painting you're recreating, and provide a link to the original and a picture of your recreation. Good Luck. [Answer] # Tikz, 175 bytes ## [Composition III in Black and White](https://commons.wikimedia.org/wiki/File:Piet_mondrian,_composizione_in_bianco_e_nero_III,_1930.jpg), 175 bytes ``` \documentclass[tikz]{standalone}\begin{document}\tikz{\def\b{;\draw[line width=}\def\a{)--(}\clip(1,1\a1,5\a5,5\a5,1)\b2mm](0,4\a6,4\a6,3\a4,3)\b1mm](4,0\a4,5);}\end{document} ``` [Verify it in the Blogosphere](https://www.sharelatex.com/project/589a2bb0641ba85023013f00) This is perhaps one of Mondrian's most minimalistic works and I am surprised no one has found it yet. It is not however particularly interesting so I have included several other paintings in my answer. ### Explanation There is a bit of a wrapper that is associated with every tikz answer. The wrapper is: ``` \documentclass[tikz]{standalone}\begin{document}\tikz{ }\end{document} ``` Once you get past the wrapper there are a few `\def` statements that save bytes but unfortunately obfuscate the code: ``` \def\b{;\draw[line width=}\def\a{)--(} ``` If we make all the proper substitutions our code comes out looking like: ``` \clip(1,1)--(1,5)--(5,5)--(5,1); \draw[line width=2mm](0,4)--(6,4)--(6,3)--(4,3); \draw[line width=1mm](4,0)--(4,5); ``` The first bit is a `\clip` and is very important, but we will skip over it for the time being. Now we draw the first line on the blank canvas, This line is rather thick so we use `[line width=2mm]` to set the thickness to `2mm`: ``` \draw[line width=2mm](0,4)--(6,4)--(6,3)--(4,3); ``` This connects a couple of nodes and produces this shape: ![](https://i.stack.imgur.com/wPt4C.png) Next we `\draw` a second stroke, however this stroke is thinner so we have to set the line thickness to `1mm`: ``` \draw[line width=1mm](4,0)--(4,5); ``` Now our painting looks like: ![](https://i.stack.imgur.com/5vsmV.png) This is close to the original but not quite, so here is where the `\clip` comes into play. We use the `\clip` to remove all the extra lines from our canvas and set the canvas to the correct size. With the canvas resized we get the image: [![Composition III in Black and White](https://i.stack.imgur.com/hlslr.png)](https://i.stack.imgur.com/hlslr.png) --- ## [Composition With Yellow Patch](http://www.piet-mondrian.org/images/paintings/composition-with-yellow-patch-1930.jpg), 214 bytes ``` \documentclass[tikz]{standalone}\begin{document}\tikz[line width=2mm]{\clip(1,1)rectangle(7,7);\draw(0,8)rectangle(4,3.5)rectangle(6.5,1.2)rectangle(4,0);\draw[fill=yellow](6.5,3.5)rectangle(8,2.5);}\end{document} ``` [Evaluate it in CyberSpace](https://www.sharelatex.com/project/589e9f480fc1f31f144f72ad) *Explanation to come* --- ## [Composition II in Blue and Yellow](http://www.piet-mondrian.org/images/paintings/composition-iii-with-blue-yellow-and-white-1936.jpg), 225 bytes ``` \documentclass[tikz]{standalone}\begin{document}\tikz[line width=2mm]{\clip(1,1)rectangle(7,10);\draw(8,9)rectangle(3,6)rectangle(0,0);\draw[fill=yellow](0,0)rectangle(3,2);\draw[fill=blue](0,11)rectangle(3,9);}\end{document} ``` [Assess it over the Webbernetz!](https://www.sharelatex.com/project/589e8f6b0fc1f31f144f716d) *Explanation to come* --- ## [Composition B (No. 2) in Red](http://www.tate.org.uk/art/images/work/T/T07/T07560_10.jpg), 232 bytes ``` \documentclass[tikz]{standalone}\begin{document}\tikz[line width=2mm]{\clip(1,1)rectangle(10,13);\draw[line width=1mm](1.2,5)--(1.2,9);\draw[fill=red](0,14)rectangle(5,9);\draw(0,9)rectangle(11,5)(7,0)rectangle(5,14);}\end{document} ``` [Attempt it within the Internet!](https://www.sharelatex.com/project/589a227d641ba85023013d00) ### Explanation First here is the code with line breaks inserted to make it more readable: ``` \documentclass[tikz]{standalone} \begin{document} \tikz[line width=2mm]{ \clip(1,1)rectangle(10,13); \draw[line width=1mm](1.2,5)--(1.2,9); \draw[fill=red](0,14)rectangle(5,9); \draw(0,9)rectangle(11,5)(7,0)rectangle(5,14); } \end{document} ``` The first command of interest is ``` \draw[fill=red](0,14)rectangle(5,9); ``` This draws a red rectangle with a black outline. For the upper left hand corner of the painting. ![](https://i.stack.imgur.com/1Bhwg.png) We then draw two more rectangles with white interiors and black outlines to create the grid pattern on the painting ``` \draw(0,9)rectangle(11,5)(7,0)rectangle(5,14); ``` ![](https://i.stack.imgur.com/i9xvL.png) We then draw in a thin line ``` \draw[line width=1mm](1.2,5)--(1.2,9); ``` ![](https://i.stack.imgur.com/GsFkx.png) And crop the image to the proper size ``` \clip(1,1)rectangle(10,13); ``` ![](https://i.stack.imgur.com/ur7Ri.png) --- ## [Composition II in Red, Blue and Yellow](https://upload.wikimedia.org/wikipedia/commons/a/a4/Piet_Mondriaan%2C_1930_-_Mondrian_Composition_II_in_Red%2C_Blue%2C_and_Yellow.jpg), 251 bytes ``` \documentclass[tikz]{standalone}\begin{document}\tikz[line width=1mm]{\clip(1,1)rectangle(9,9);\draw[fill=yellow](8.5,6)--(0,6)--(8.5,6)--(8.5,2)rectangle(10,0);\draw[fill=red](3,3)rectangle(10,10);\draw[fill=blue](0,0)rectangle(3,3);}\end{document} ``` [Test it upon the World Wide Web!](https://www.sharelatex.com/project/589a2640641ba85023013e57) ### Explanation First I will insert some line breaks to make my code readable ``` \documentclass[tikz]{standalone} \begin{document} \tikz[line width=1mm]{ \clip(1,1)rectangle(9,9); \draw[fill=yellow](8.5,6)--(0,6)--(8.5,6)--(8.5,2)rectangle(10,0); \draw[fill=red](3,3)rectangle(10,10); \draw[fill=blue](0,0)rectangle(3,3); } \end{document} ``` The first line of importance is: ``` \draw[fill=yellow](8.5,6)--(0,6)--(8.5,6)--(8.5,2)rectangle(10,0); ``` This draws the following shape: ![](https://i.stack.imgur.com/FO4KB.png) This strange shape is the yellow rectangle in the lower right corner and the two lines that are no the edge of a colored rectangle. Next we insert the red square and cover up the extra lines made by the last shape: ``` \draw[fill=red](3,3)rectangle(10,10); ``` This comes out looking like: ![](https://i.stack.imgur.com/zhHTL.png) Now we insert our blue square: ``` \draw[fill=blue](0,0)rectangle(3,3); ``` ![](https://i.stack.imgur.com/m5AiH.png) Now all that is left is to crop out all the unnecessary parts of the image using a `\clip` ``` \clip(1,1)rectangle(10,10); ``` [![Composition II in Red, Blue and Yellow](https://i.stack.imgur.com/uQPme.png)](https://i.stack.imgur.com/uQPme.png) --- ## [Composition II](http://www.piet-mondrian.org/images/paintings/composition-2-1922.jpg), 308 bytes ``` \documentclass[tikz]{standalone}\begin{document}\tikz[line width=2mm]{\clip(1,1)rectangle(12.6,13);\draw(0,0)rectangle(10,4)rectangle(2,12)--(0,12);\draw[fill=red](10,1.6)rectangle(14,0);\draw[fill=yellow](6,12)rectangle(10,14);\draw[fill=blue](0,4)rectangle(2,8);\fill(10,10)rectangle(14,14);}\end{document} ``` [Check it out on the *Information-Super-Highway*](https://www.sharelatex.com/project/589ea5900fc1f31f144f7331) *Explanation to come* [Answer] # Mathematica ~~202~~ 287 bytes. **Just For Fun! 330 bytes: Mondrian with "Boogie Woogie" in Its Title** ``` Column[{"Boogie Woogie", Grid[{{"",i["",b->Red],\[SpanFromLeft]},{"",\[SpanFromAbove],\[SpanFromBoth]},{i["",b->Blue],"",""},{\[SpanFromAbove],\[SpanFromAbove],i["",b -> Yellow]}},Dividers->{{2->t@5,3->t@6},{2->t@9,3->t@7,4->t@6}},ItemSize->{{1->3,2->9,3->1},{1->6,2->6,3->2,4->2}}]},Alignment->Center] ``` [![enter image description here](https://i.stack.imgur.com/8IfIB.png)](https://i.stack.imgur.com/8IfIB.png) --- **Actual Submission [287 bytes]** `\[SpanFromLeft]` and similar expressions take up roughly 85 bytes. In mathematica each such expression has its dedicated one character symbol. ``` t=Thickness;b=Background;i=Item; Grid[{{"",i["",b->Red], \[SpanFromLeft]},{"",\[SpanFromAbove],\[SpanFromBoth]},{i["",b->Blue],"",""},{\[SpanFromAbove],\[SpanFromAbove],i[ "",b->Yellow]}}, Dividers->{{2->t@5, 3->t@6},{2->t@9,3->t@7,4->t@6}},ItemSize->{{1->3, 2->9, 3->1}, {1->6, 2->6, 3->2, 4->2}}] ``` ![side by side](https://i.stack.imgur.com/D3lJS.png) Output on left; photo of Piet Mondrian, Red Blue Yellow Composition on right. [Answer] ### Ruby, 112 (111) characters [Piet Mondrian - composition in B (No.II) with Red](http://www.tate.org.uk/art/artworks/mondrian-composition-b-noii-with-red-t07560) ``` b="0 "*9 w="2 "*9 puts"P3 609 771 2",["1 0 0 "*267,w*8+b*2+w*79,w*89].map{|x|(x+b*3+w*42+b*3+w*66)*249}*(b*2436) ``` my production on the left, the upscaled reference on the right. ![enter image description here](https://i.stack.imgur.com/1aCr5.png) The colors can be tweaked slightly - up to a precision of 1/9 - without loss of score by tweaking the max-value in PPM. I've chosen the "suitable Win16 color" approach. 8/9 white is probably closer to the canvas original color, but 9/9 is closer to the author's intention. ~~One character can be saved if we replace `"1 0 0 "` with `(w+b+b)` (#F00 red). I believe that counts as "close enough"~~ file ouptut version (not golfed) ``` File.open "tmp.ppm", ?w do |f| b="0 " w="2 " s=b*27+w*378+b*27+w*594 f.puts"P3 609 771 2",["1 0 0 "*267,w*72+b*18+w*711,w*801].map{|x|(x+s)*249}*(b*21924) end ``` [Answer] # SmileBASIC, ~~2774~~ 1892 bytes ### [Broadway Boogie Woogie](https://upload.wikimedia.org/wikipedia/commons/3/30/Piet_Mondrian%2C_1942_-_Broadway_Boogie_Woogie.jpg) ``` GCLS-920851D$="w$BȜąr:BȂąr7?Ƣǘy1SƑǘb<?ŵǘw-/ƶvyFMƮeb<<ŶIr:,ėǭy:Sėǘw-LŒƄw7;ėƎrkLćƄrBMĜey26ğ¸bKBē²y,Bć²w<Dđïw+DüïyDÒïw--çvyU8Òpw.1±syBM¨eb;<Iy28¥żrJNůbwN{ůr?@Ǣb3>Sǭw.Fb¤w24D­rMF5¤w,7Nnr[75ny1X=e FOR I=1TO 36G A(),A(),A(),A(),A()NEXT D$=" w*+r6,r1+b<*w1+b/+b++r(+w*+w,Br )b+*b()w0,w=+b,,r5+b1+r ,w24-Ȃ w w#.r-#-Ǥ w*+r4,b3+r6*w2+b,-r-,b++r*+b**r(*b(*r*+b<-w@+b -w ,r4+b1+b%-w,5-ǔ w +r)+w?#-ƹǘ w +r%-b,#-ƭ +w *r +w/,b2,r1-b;-w7+b*.w5+r1+r +-ƒ> w +r'-b*#-ž *r+)w +r?+b:+b1-b2+w:+w*+w3-b4-r4-b6,w2+r--w3+b1+r )w52-ş w*+r )w ,b>+r7+b :w -b,+r:+w*+w7,r 6w ,r7-r0.w/+bM+b1+b ,w24-ľ *w +r)+r *w5+r9,b7.w++w ,r.+w*+w6*b Dw *r06w -r5+b *w8+w +r1+b ,w *r(7-ü w*+w )b +w*+r*+bD-rC/r7+b*+r5+bD-r,.b/.w.+b *w8+r +w1+b'+r,4-Ò w*+b )w+*r+*w +b )w<0wX-w +r*+b /wd-w/.b/*w+-r 7w)+bC+r,3-p *w+)w +b*+w*+b )w@2wU*w+*w++wx-wQ-w.,bT+b,.-* +w +r++r5,w6+w %|üŭ w3+r1*w(+r0+r7*b (w )r3*w+*w,+r-*w +b5+r )w6+w.,r1+w *b*-w +b *w(,r()w ,r+*r :| ȋ+w7*b 1w4)w +r %|şǷ+r,*w)+w.*w*)w ?r -w+'|pǷ)w,)w +b*#| Ƿ+r/+b()w ?r -w+*w),r(*w *b +w *r +| Ǣ w+(w +b1*w(+r0+b7)b *w *r2)w +b *w,+r7+b5+r )w6+b/+b )w1,r7+b.*b9*w +b*8| Ǎ w3+w )b0*w +r4)w +r/+w**w**b +w6+w )r1*b3+w /|üň+b-*w1+w%*r(-w +r *w.+w')r (w5*| ň w3+w )r0*w +b )r5*b/+w3+w *r +w *r,+w9+r3+w-*b (w +r,+b2,w /r3+b0)r *b+-w+*r :| ij w3+b )w)*r 'w +b (w+)w *r1+b0*w.+r6+b )w0)w,)w +b4+w +b0)w'*r1*b))w+*b.*b1(w+*r ;| 3w +b )w*)b 'w +b.)r 'w )b0+r <b,+b6+b.,b=+r 3w ,b +w *b 6w *r);b)+b7+b 1w=9| Z w3+r (w.-w +b1+w +r0+r )w +r (w,+r6+b *w),r8+b?+bJ*w:)w+)w.*r1)w+*r 7| >+r )w6+r2*b1+r6*b1*w +b*(| , FOR Q=1TO 27S=A()T=A()R=A()L=A()FOR I=1TO L R A(),89R A(),A()NEXT NEXT DEF A()RETURN-32+ASC(POP(D$))END DEF R L,C IF L THEN IF R-13THEN G C,L,11,T,S:T=T+L ELSE G C,11,L,T,S:S=S+L END DEF G C,H,W,Y,X GFILL X,Y,X+W-1,Y+H-1,-1716698*(C>88)-2302505*(C==87)-6080725*(C==82)-14597488*(C<67)END ``` [![screenshot](https://i.stack.imgur.com/BigQ2.png)](https://i.stack.imgur.com/BigQ2.png) Each of the "lines" in the image is stored in this format: ``` x,y,direction,numberOfSegments, yellowLength,nextColor,colorLength, yellowLength,nextColor,colorLength,... ``` All the numbers are stored as `CHR$(number+32)`, colors are stored as one character; `w`,`y`,`r`, or `b`, and direction is stored as `|` or `-` The extra rectangles are just stored as: ``` x,y,width,height,color, x,y,width,height,color,... ``` In the same way. [Answer] # SVG - 455 ~~480~~ - [Mondrian Composition II in Red, Blue, and Yellow](https://i.stack.imgur.com/n2D19.jpg) If you can embed Javascript into SVG and make it dynamic, its a programming language. Ergo, this is a program. Turns out if an `x` or `y` coord is missing in SVG it defaults to 0. Also `red` is shorter than `#f00`! ``` <?xml version="1.0" encoding="utf-8"?><svg xmlns="http://www.w3.org/2000/svg"><rect x="145" fill="red" width="455" height="440"/><rect y="432" fill="#00F" width="150" height="168"/><rect x="550" y="517" fill="#FF0" width="50" height="83"/><rect x="140" width="16" height="600"/><rect y="430" width="600" height="16"/><rect y="180" width="140" height="25"/><rect x="550" y="430" width="15" height="170"/><rect x="550" y="515" width="50" height="16"/></svg> ``` Pretty Printed: ``` <?xml version="1.0" encoding="utf-8"?> <svg xmlns="http://www.w3.org/2000/svg"> <rect x="145" fill="red" width="455" height="440"/> <rect y="432" fill="#00F" width="150" height="168"/> <rect x="550" y="517" fill="#FF0" width="50" height="83"/> <rect x="140" width="16" height="600"/> <rect y="430" width="600" height="16"/> <rect y="180" width="140" height="25"/> <rect x="550" y="430" width="15" height="170"/> <rect x="550" y="515" width="50" height="16"/> </svg> ``` [Answer] # SmileBASIC, 67 bytes ``` GCLS-1GFILL 353,0,367,#R,0GFILL.,121,#R,156,0GFILL 367,266,#R,293,0 ``` I picked an easy one: [Composition III in Black and White](https://commons.wikimedia.org/wiki/File:Piet_mondrian,_composizione_in_bianco_e_nero_III,_1930.jpg) Luckily SB's graphics page is exactly 512x512 pixels, but it won't all fit on the 400x240 screen so I can't get a screenshot easily. Explained: ``` GCLS -1 'fill screen with &HFFFFFFFF (white) GFILL 353,0,367,511,0 'draw vertical line in &H00000000 (black) GFILL 0,121,#R,156,0 'draw horizontal line GFILL 367,266,#R,293,0 'draw small horizontal line ``` [Answer] # Processing, ~~15,447~~ ~~15,441~~ 15,439 bytes ``` String i="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5OjcBCgoKDQwNGg8PGjclHyU3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3N//AABEIAJcAlwMBEQACEQEDEQH/xAAbAAACAgMBAAAAAAAAAAAAAAAEBQMGAAECB//EAEgQAAEDAwIEAwUFAwgHCQAAAAECAwQABRESIQYTMUEiUWEUMoGRoRVCcZLRI2KxBxYkU3KywfAzNDVDUlSCRHOTlKLS4eLx/8QAGgEAAgMBAQAAAAAAAAAAAAAAAwQBAgUABv/EADcRAAIBAwMDAgQDBwQDAQAAAAECAwAEERIhMQUTQSJRFDJhcSORoUJSgcHR4fAVJFOxBjPxQ//aAAwDAQACEQMRAD8AvV0lXkXe2JYtKXGSo813ONG49ayViluFM8o0snA/e/j4oxbQdC8Hk1zYLQ7aJ91kxkuPrnO63EOkANELWrCcY7qPyFB+Jv13EPP1/vTEsiSKFJxipp8y4QI9wmQ4jb0ltBWW1nCRjfzHrQOmvJ8c2oY/e+lUlUFAF3NC8O8ZJuxiR3RHTcHwdTKEOYyATsTt0HnWobiT4kogynvUtaOia22qVq3/AGfxFcr8ouFbrR5qVYKG0gIyQBv9wUtPNeJKdEeR75/vVhIJIVjJ3FR/z9tR6Smen9Q7+lD+Nvf+MfnRT05806hXVVyipl2xCJDCiQF4Kdxt0ODTtxNcKqmBdXvSZh0Nok2qbn3L/km/zD/3Ul8V1I//AI/qP612iL96s59x/wCSb/MP1rviepf8P6j+tToi/erpDtxJCVRGgn8f/tR7ae9aQCWLA+4/rVWVMbGkVvs3sN7ulxZ5rj8sKC0LUnQkZz4cDPzJqwNy0kisgA3wfejSTholX2prA9rZi4ZYSpJUSNXX+IoNqtzb2noTLe239aE5V5NzUvOuP/JI/wA/GhfF9S/4f1H9anRF71tL08k6oiE7f570zaz3jvpljwPuP61V1jA2NbW/PCvDDQoef+TVrie8STEUeR96hVQjc1BOkXP7OlFqAlTwYWW0HopWDge954q1qZ7hWjuF0g7c1DBV+U1TrupU3hWGOLnFWQe0LIU0eqsLAT977uT8KvDbSJIYIslAMg+SaLFP2/X5NO5Eu8ov9paZtochKb/ayMHKcBWPvd9u3eqQQGdu9N6WXYD3FDd8HSvB5oXh9qMzfb85CmrlyHHiZEdZyI55izgY9SR8KtA8jyOHXamLkkxJkU9us6PGutsjOvBDkheG0HPi3H61FzFcNNG0edI59qVVlC4PNR8PXGNOuV2ZYe5i472lwFJ8J1LGPmDQrCOZZpTITgnb9aPPGUVD70DNmM3h+72y2rK5kZCkvIwUgZBAGehot/Yy+iSMYyd/qKpbyor5aqtw3wreIV7iyHW2kIa1ZUl4E7oUO1AntpniITk1qzX0LRlfen6rtHek3+0hxZmRbe8XkqBwPCnv32UKixsLuBe5OdiPes0PGzgL70ksvC1uncOsT3S/zVsqUdK/CCM428thTaRAqCTWhNezJPoHAq0/ybb8KRyf61z+8aNB8tJX/wD7yatFGpKsrt66sG3SurtqrUK7xbhebxbWXHA/HbWHPAQB22NJpb3iSFpcaDxRNUYxgUZwpbzbLMmMqS/JIcUrmPr1KOcd6Jbdwp6+atPIHfUKcUxQayurqzFdXVFJz7M8B15av4UC5LLCxXkA1ZPmAqt377KVYo3281GeYMg6UysY16VeffGr61nWt9NHarIoLMTTHY7kmkUe5cICpsVaLjDDaUDIEhOO+3Wnnt7h5lkGw9qAHRVKnmhbA3Zvte6vWpbK5Dq9UlTT+vJK1Hfc43KqiGQvI6kYwaNN3DGurjxRVzRDXdra66I6nELyhSsEp3HQ9e1LXM7idO23p844qiR5UkipLTGjxJdwcQhltT7upRRgFR1KO/nuT86m1UxSSGRwQeKmRy4Ue1ArMZC725ELIlKZXlTWnWTvjONzQraaYTya2Onxn+VWAXK1TeEbheE8RQjcn5qYuVcwyNSW/cOM5264607GWLjfatK7jgER0YzVoZlxrnf73BaiuI1RXEGaEJ0OAhA8Ku/X/wBNQlu4laRpAVPC53FZIkC4GN6RO8D29kAu3daU9tegfxqY4VfZWzj2rQbqbg6ioq6cMQGLRaUQm5IcSlSlBSiATk57UWJowNINIXEpmbXimvMQP94j8wqxljBwWFC0ms5rf9Yj81d3o/3hXYPtWc1vstBPlqqVkVuCK7cVWbXb4MXiK8zGpaS7ISoOJLicJ3z06j41mJcSvLJG+w8GmpH1RKKdWl1swtSXmlp1HxJWCKZs4nhh0u2T70GTd9hRfNb/AKxH5hTPfi96Hg+1a5qD/vEfmqRIhOAR+ddpNdcxv+sR+apZ1Ub1wBIoW6aXrXNbS+GtUdaeYFgaMg71RpFCltjjxUhTVYRY4cnheDCnPqntsyVuB1bhyT4h1Sd8BRFJyPJPCpjAj34xtR4XMLkA5yKSt8AynR+zudvV54ycem1elXqsagKece9Z7W7HerDwlZoNmXKDK2jKLaESVpeJClJJycE+HcnasE9xZXkkOzE4/OnXlLxqntW7pw9EevNpeW+8lbKyUAacHJHXI9KyZLX4dlhXJD8n2pmO5IjYYrU+da7Yvlz5D6NRUEctGrOnrnA/CutOiwXhdYnJ08/5/CgSXLRgavNA8JQrPKvt1mW+VMcce0qcS6lISBk4wNOfrWtNZXBRIpgAifKfJ+9BSZdym5NWW8WGPdrc9BfeebbcwSpspyMEHuD5eVHKZGKtFKYmDqOKgstrYtwRbWXXlojN6QtenUdwd8ADv5VnW8cS3L6Sc0WeZ3Gogb0NxBwXA4gjtsyZcxpLaiQWijJyMd0mnen24sHLxnJNAkbuDBpszaWWdkvOkAAb6f0paDp6RSGQHc5/WrtKWGMVpVpbUc85wfAUq/RY2YnUd6ss5AxWvsdrO7zh+Aqv+hxfvGrfEn2rtq1toVkOubjG4FN2fTUtX1Kc0N5S4qtQeFord7vUr2qRqmIWFghICQT22/jQHu2v5Ph2GBGciiKvZIlG5NMuGuHo1us4iMSnnWw4pWtWnO+PIYp4Kk8RAOxqJZmeTWRSLi26vWK6NxGGm3UKYS6VOg5BKlDsf3aHa/8AjMMyklzQJb2QHAFJf54y0+IQ4xI36q/Wm4//ABW3Rw+s7UI37kYr0SPBTLjMSFrUlS20qIAGBkZ7/jSl/YLcPueKYjlKiorjZWnbVPjl9xKXoy2yoIGUgpIyPnQ7W2XpytKpzjfepZzIQtKrZBgcP8NQo0m4pbYQ84EOSFIb1KJUrHlnr8qrPjqsKyMdO+dqvErRuQgyaE4Yt9mtToh2+/R5q5LusaXG9WcYwAk79KJ8KhlSTV8tHnkkkXLJiibHwnHhXm9y2Zy3FT3itbZbSA2eYtWAe/vHrRb8J1BBHqxp9qTjzFvjmmd3tbMziCzTXeZzIqlFvSfDud81E95JDKkIUENXLGGBf2pDxTw/cbtJaVAaQvlKd16l6cZIx/A0boiGymmeXHqxx9M/1od0DIFC+P7VPwFZp1pnT/bW0J1NpA0rz0JzTdz1G3uToj5XnNUihaPc1dcelAyvvRMHmq/brQzG4uuVyS48XJKNKkKPhHudBj90fOlIr5pJ2g0jA8jk/eiGIBNeasFO0OsqK6tV1dW6murAO1TXGqlZ7RcY3EF9lPyUcmUhfJSlxRKN+uCMD4UoIgCxxzTss8bRoqjimnCMGXb7MI8+cqa+HFEvKTgkHGB1NdapojAK4oNxIryalGKo/wDKeXDxJHQ0kqUqGgBKRkk619KaHUHtdl+9Gt+nRXMZeQkYqpPsTGmlOPxn20DqpbSkj5kVUddkOwIo46PanZSfzr3S1/7Mh/8AcI/uipzqOazGUKSoqO9IkLs09MJYRJVGcDSj0SvScHoe/pQrgqIWL8YNXhx3Fz7155xmmczwTZU3R0OyRPc5i07g+F3HQDtjtScRja2Xtjate0ZfiXK+38xSLgrJ4vtAwrZ9Rxp/cXV4sluKYvGHYYbV6VYoF0i3i8vT7iiTGkOlUVoIxyU61nB232KR8Kd7dqm8C6WPJzya85l/Jru82luZxFZpy3nUriKVpQkjSvJHXvWdd3HauY1AyG/Sm4n0wuuPajLTtJnZGMObfmV+lKdILGeYsf8AN6pOBoXFJV2Zi3XeZOaedW5LWStKiMIwT0xVOtAqiMOSaOkxddGnii1pbS3qScq270lcQQLDrV8tVVLFsEbVzw9Z2418l3QPOFUlrSpokFKd09Pl9a1elCTtgtiouJAyCMDirNWxSdZXV1arq6t1NdWdqkGuquWq7Q5l9u8GO4syI6Vc1JQQBvjYnY/CsqOwu4pJJW+VuNxRTIpUKOacWoKTEwvrqNG6fHLFBpm+bJqJSpO1effygviLxpb5KkrUhiO2tQSNz417VN3bSzoVQE5GK0rGSMQMjMBv5pdxBxMxc7S9EZjSEKWUnUojsc1kWnRbqGYORn86PCY431dxfzr1K1/7MiHzYR/dFeiGwrEfBYkVzepbUCzT5j4UpqPHW6sJ6kJSScVxiEw7Z4O351XVp3qqz+MoMLhK33hLUjkSZK2kJSElQI5mc74+4aG1jKgEVuQNPOasJATqberY8Xfb2U9W8DOT6mhP8T3lxjTjerArikfDV6j3K+X2Iw04FwnihwqxhR5i07flNL2Nq0M8rncMf50a5j0xIfcVFcOKIrF5tsVcR1bkg+EpWAE79TS63sM4M7R7rxREtn0t6qF4Z4qYnXC7NNxXUlhxIJWoYOVODt/ZqhH+mDvn1d3cAeMf/aCMTekbYoa43V+zXF2ZdnHJsCa5pixmsIMfzye/X6VpXHw9zAjMhq1tDIzMA2KsaVwioJ9mVk7f6SvPRNZvIEEfP1q5EuDg0rt/ETKOKrlam4jgEVB8ZWCFe4dvzfStWa1HS1NyDqVv2fagB+96OCKsLlzQloO8snPYEUzNfdqAS42O9QseW00ia43Yc4hXZhAeC0Z/a8xJSfDn8aO82mwF5jkceaHj8Tt1JF4xYk3uRa0wXQtgKJc1pIOMfrScnUhHCJStO/BELqBpou8IwTyFdCfeFKL1tWYLo3NBNucb0s4f4vbvUVx9EF1jQ5y9K1gk7A56etaPUb34GQKV1ZGdqHFH3ePFKbVfoQvd8LNrDbyEOKcdTpBcwfMDPzrPE8ynUzEh+B7Zpua2VIw2aacKcSIuVnEgxHmyXFDSpQJ2xRZpz0p/h3Bc85+9LKO9+INqqfEkkcQ8XiI02qPob5JcWNQJTqVnb8cVqQdc+Gte4YyfpVpemal16960rhF3G85v8SydvrQR/wCXrt+CR/H+1Lf6Y379Wfhbi5u4xzHEJxBioSkkuBWrttt6Utd9TEWG0Z1U+9j2wPVmj71xAiLZ50gxlrDUdaygODJwCcdKUTqfxhFvoK6ts+2ds0Iw6BqqtSuM2m+FbfO+z14deWkN84ZTgr9PT6108Da/g9ROjfV70a3i7vrzirDe7yi3xJF5LK3EQ0jLKVbr8WNj0+99KZsc386yatONsH6UvJiMEVzark2YrdyDAQLg0h/SSAUahqwT3PioM0h6XO7Mdeon+G9WUGZQOMVYuWklJ0J26ZSNq2hGo2ApYkgc0utKQJU7KUgBeOnqqsTpmXmmD744/WmZtgMUHaLHHg3q6zUvOuLmHKm140o6+7t61vSyBoguNhSijDVuKhvmx1A5VzE5+deSgjtlEZVvVmn2Lbg8UwYWVXWQkpGkDYnqelbUV2Zbp4CNlpdo9K6h5o/Gew0+WK0CoIxjahZxWgjckJH4gVwH7NdQN3CRFBAG6hvjr1rH63gWuQPIpiAktvSfGFjfqR0ry0X/ALAB9KbPBqzhIG2E4PbFe/CBlGRWb71XbIi8DiO5qnyWHIRz7O0hI1I37+EdvU0OO8t5pDFGuGXmpKOq5J2qx4SNkj4DtRsZwTVc1zjfVp+ldoFSDkc1gGDnp+IqNC5yBXHFaCUjokeuBU6Qd8V25riWnMR4ADJbIFLXUOuBlQb4NWRsMCTUMBA9ibCkjIKsgj1qlhGyQKr8ipkPrOKjkBv7TYODr07bbfe60OQ2y3iA/P49vNSNWgmo7egiVN1DCSvY4/eV0+lBsYHE8pkGxJ/7qXYFQBQLNkuieIEXBV6cVEDPLMMhWCr/AIs5/wAKctoZYk0u2qrtLGYyqrS7h2y3SPcru49eHHm3XQW0EK/ZjW4cdfJQHwpGSRb5jHajtlfmI/a9v+j+dVAKDLb0VZLbcWrxc1yLq48y5s22rV+z3PTejWc5kd7djuo5o07J21wKaN2pxtSVB5PhII8J7UnB0d45RJq4NDa4yuMUqiWecjim5TTeFKZeT4I/i/Ze56+n1rUuRHOO3CQrjnHJ+9BTK7txUd4h3Ju8xHk391lhtKSuPkgOYUc9+42+FZrTXFl6GBcnyM04jwshBUZpoxJVOc5TUgIVjVlK87fCrC5uL38JVaPG+aBpRBnOaEdtM+Nd3LjIubkiGpGhMMpOEqwPF19PKiyq0EH4n4n0ogmjddIXH1qdRylSUx9JIwCPu7UpHPEHA+G/SqMpx81ZY7LdIENTEy9uTHCskOKSQQMDb3j5fWtS+t5biQPC+gYGwoUbKgORmpGUrVIeQhehxoZU4Pv1lI2tyijDJyfLUY7AE+a6U1LuUF4x5y4y1JUhChvpOOtMQGa9xcKxVfaq5WI4Zc0PbY86K01bZNydlSEZ1SVZyrv0z5etTPcvJMbQEg+9XYKfxQNvaq5d+OVwJ8mB7M4pUZ0tl3n41474xRbgyGMRqxBHmm4LAOokJ5pWxxFceIeIbVGiTJMFCnClwJdKgse9uNuwI+NEsGeNGjkOotwT4qLrp/bQyA7Cr5d7bLXbJaGrmtpamVhKxnKDjr1pJra4t17zSkhd8fSlklj1AFahsNums2lhDtzcfWCvLisgq8R9askVxd4mSQge1dNIgcgLWpthnyb/AA7k1dnGmGGwhyOEqws+LfOr94du1PT2YlGQcNjY1WO4VIypXk0Lw5bprF0vKpF0ckocdGhtecNeNw4G/qB8KH0+5MrNC2+nbP22q9yVKrgYq0g71pUliq5wtMuEm7XtufBMZll4COvf9qNbgz8gPnWZZwxRyyFDknmnLlVCJiqpxFxs9DvMyFaCWpDDxS+pxCFJUO2B2qwsZbaVrgsMPRbREuSUYcUsPH/EI/7Uz/5dNEM780//AKfBXoHBk5y5QI8ySrVKfYKnVAYCjqxsO2wFLWr27XT4B1+TWXdxNG2kcUp4xt7Vy4mYZdWtOIOvKAM55hHf8a07nqMnT7TuouSTjekFhWWTSTioOGLWzbOLYyGlrUFxHFHmAZ6gdhUWXU5Oo2rtIuCCK54FhkwrVepagGgSQBqHWrM4Uc0QZPFBhace+PnVO9Gdsj864A00ongVFVS2xrui/XlcmahcVbaxGbHVs52J8P8AiayIJbfvygLuOaemKmFAvNG8Fx7jFsSWrvLTLlB1WXUgDI2wOgp20ltZY9dsulPb60o4cNhjvRmGzdyNR1+X/TQAlv8AGB8/iVbU3bx4qlWRqE/xbxT7c3HWlMlOjnBJ3yrOM/CmYwDI2aeuC4t49J8UVNagtcWcN+xNxkZec18kJBPh2zipOzriqIzmCTV9Kt19ElVmnpglv2ox1hkue7rwcZ9M1aftdpjN8uN/t5pFScjHNVm1PXJuEw3cXkpkgq5gZWQj3jjHwxXkJ50WYrbMQninkXI9Y3qvcBXKXKhylvT3nvGnxKeKu3mTTnUppVK6SeKcuIkUgBatXCDd4TLuq7vyDGWtBicr3inU5ur1wUfWt21t4EhR4wcsATn3xvWM5YsQeKcM3FLi0p5axk96WtOpi4lCBCKs8WlcmkVh4oZmXO7x24DzZiu6FrJGF+NwZH5frRL2SLpoVwNRfnH09/zqIwZQRxj3qvXpxPFdzl2+M37IuC6VqccTq5gO22PnSc/ct0F2TqD+PI807Z3CxsRigP5jyc59vY/8FVKnqi86DitD41farHwZeGrfIXw+uM6qRb2ClcgYCHDqB27/AHvpWk8kVpbreBcs3gc1kzO1xM2Km4stD95kszo8oRwlnlFBByfET1H40/8A6lFDa65I9QO+NqTa3ZpMA+KRcOuOWbjNEaSVyTylIDic43Tq79OlVk6tA1rrjhK/bFMJ0+QDuM4q0cVcTtW63tuKhPu6nMYRgkYBNY0tyOpRmJVK/embe19edQruV/RbYq4EFxLbPP5SR4lAAK0j1oa9EkVg+vjfiqiQu3bou08TtXKAiWmFIYC1KHLcxqGDinrjqi27adBOPaqPalTjIrorUgvvpO8lKkp29wnuaTjUW8hn5EnjyM+9cTqAQ+KhsK5Vnt4iXKQZ8gLKi+2jSCD0GPSjtew2P4KISOdq5wJ21rt96XDiZr+eCoQhv6gD4yRj3M0t3MTfH42/d80c25FuCTVKctyuIeMrvFQ41HIedc1vJJHvAY+tbpty8YnBA1b0SLqCxqIypOKnetiuCbjbLo641O/pBAZipwo+E+dWgtdTatXAqlz1ASRlQh3r0K83wR7VNe9jdWW2lnSk7qx2G1Y03UPiQYDGRnbPj2oEdvllOaGsV5bl2mPIMBxBc1ZSoAkYUR5UJbpLUdntFiPI4P2q00J1Eaqg/nIzG4ii2ZqyuJElIWZCEAIT7+x2/c+orctNF3bmZlxg8HmlZCyvjNc2DiESrleGPYnWRHeCQpZ2X43Bkben1FZPdaykZjlwxOw8U1JbjQpz4qyomxiQkPJ1HptT8d/aSNoRwTSvbkwc0pst5tr1wuLbcttS23MLSAcp8Sx5ehrPtmW3nke4OAeM/wAaYmifQpArLZeLc7d57LcppbjWykjOU71eEGGZp5to2+U+KE3qACcjmnHtcYJ1FxOnz3rRNxbCPu5GKHh+KTwrtbXOIJjCJSC62klaQN0+71rIilRLt5pD6DwfFNPC6xAgbmnPtTBQXA4NGepBxWuLu3aHug+ildDA4xvQU+/2i3JQ5NnMspWcJKwfEcVe2mhucrCc49qhwU+apZV4t0VhT8mU2hpOMqIJG+36UFL+1d9CuM0RYZTgKKyPd7fKjpfYkJW0sEpUAdx3/wAaluoWqPoL71DQOp+XFRW/iK0XJCzCnIdS2QFaQrYkfhRrqaK1K/EYUncfaqKrOPTvSy2S7gb3cfbYbbMIhYjPA5Lu+34bVldqKEtNnOvYe2/tTjhO2uk5I5ptb3m4sctvrCF6icEdq6zmjs4hFdHDf5igyKXbKcUmRKug4wU4WWxZsHD56+5+Ofe26UTFur/GlvT+n5Uc6exoz6vald0gcIO30szFKE2a6VpRzHPEVHqMbU6hhmhadD6BzVFvLiLCDFdsQeFLDd4Ln7RiStf7HK3FAnp+HeutpIJkaSE5VefpXT3U7DQ/mrTc7tBj26W88/oabaKlq0k6QBuaX+Ls7z/bo27bfXegBGT1EcVFZrzb5VsYfjSFOMr1aFaTvhRB7VxmtbD/AG8jbrU6Xk9QHNdHiS1ouke1mSRMkDU23yz4hueuMfdNMQXUMy5jO1cbeTBcigZXEFrsr6zcJKke0qVy/ATnSd+g294UvaCASyFGzvv96J2ppAMCjz9jtvoSt2Mh1WNILoCj+AzV4bOzX8WNRt5oLSvwfNVdybw7YZ0pwspfXLcXrEZwKKSlRJ1DO26z9ata9KN47mUhlHA9qJPdvGihqJ4Scs1zu1xehQFNOKQFuKcPvZVt0JosvTJk2uCGT9ke1LpMpGU5q2CFH08vlDT6k1xtYhH2tPpq/cPJ2NK4tmgtXqXITFbS66kgrGcn3evypCOxJmaOQfh+BR3uXKAZpp7JHKNHKTp8qfFrD2jDj0+1L6mzmhJ1gtNwQ2idBZfSg5SFgnHY0S3gS2z2RjNc7F9zUz9qgPslmRFacaVjKCnbzoK2NujawuKus0g4asYtUCMyGWIrSGk7JSE9vKpazt2YMV3qGlduTXEKyWuAFJhwGGQs5UG0Y1du3pRJ7eO4x3RnHFUUsvy0qh2mW3cLi49dFPx1oX7OwUf6uc7Y88UPtx4yRkL4o7yqyBQuD71LwpbpEezpbu0o3CSHFZfdThRHYVTTDfZkeLFDy0ewanPsrBTjlIx5Yopt4+32yu1V1tzQz1ktbslEt6BHXIa/0bhRlSfwNXWKNIzEo9J5FQSScmtSLPbJDjbr8BhxbJy0pSMlJ9PpUQwxwqUjGAf1rixODWXCDCVb5KXorTjZQQpKk5ChjcGl5IobZDMF+Xf8quGLnSaqrnEtpsqzbkWkhLIGOVpCfENXT403ZWSdShFyVGW96FJKYW0UZY5ttv09mazbktOtL5KVrCdY8JOx/wCo0tcqllcraqnzDP0/zajRyPJEd6ZogW65PvpmQWHuQrCOY2FYyTnGf7I+VCtJYpZJFRMEHf8AOrMXUAhqHl8IWubc41xd5/tEcJCNLmE+EkjbHmTTFvbJDbvAnDZoTMzMGqkTLdbLnc5bXDzZRIjPuCYXioBSisgY6/eSvy7VMPUrbpgxJnfb8qYu4biaNdR2o/8Ak+kot96useRnmNtpQoI33CjReodctzCj770COwljGpuKvwuccoKvHgelJx9QikhMy50jmpMTKdNIbdxPb3uJbjCRz+cyklYUnYbo6b+opMF7f/fOco/FE+caByKfNXFlaCoBeB6U5b38VwhdPFUeJ0ODUa7zGQhSiHcJSVHCfKlV63bM4QA1Jt2AyaX2LjK1Xxhx6D7RobUEnmN6dyM+dPdQu4+nsEl5PtVI0LnArdq4xtt1dkNxUyAWCAvWkAZJI8/Q0C56nDAoZvNMNZSLjNcQOM7XNucqAymRzopPM1NgDZQGxz5mmbm5S2t0ncelqWVO45Uciop16jWRxMmYHNE53kM8sZwpW4z6Vm2lu6O9wD83FNKndGlfG5p9BC0skOEFQUelaNqsyx/jH1Uq2nORROaZqtYTXV1arq6gb6FKsk9KJSIiiwvElZwlrb3j6DrVHQSKVPBq8bBWDHxXmiuHZ8lRfVdYs8q2MlJ2XjbtnpjHXtVI+v2vTB8MyHI9q6e3NxIZE2BqwcKJYsREabKjmU49zG2kuAKWnTjYHBPQ/KgXN/b3o+OWM+gY/wA/OujjaL8PPNMuEVuO3O+KVeY09tTyVNx2dJVFBW54V479Bv3SavbW6ovdVca9/vneiTujgKo3G1bu3G1rs8iFHlNyeZLXpRo0Y6gb5UP+IV1jdLeRySIMBaFIO2QPetcLzrbcbveG4iQXWHf2wLOnfWsde+4NIWEEndd5NwdxTlyjoi1FabvbHeIbtEREWl6OcLcLKdKvF2PU/Gulh+AkM1yQUY4AG+P6UISGb8MeKf8AtkQAjlnfybqR1a0VPlOn7VUQuTmktmudom8WXKHGbSZjKCpwlkDbKO/fqKrZxtJOZOYzuo/tRZYikYbzVk5Tf9Wkee1a6xqowopM5J3NZyGTtym/yio7MY4UVOo1pqJGZBDUdlAJzhLYH8Ks6K5ywzULleKxMWO3nQw0nPXSgDNQyI3IFTqPvWkxmErKkMNJWrqoIGTUlQQAeBUVVLZfIU683mJ7I6TAQ4slxKdJ0nHh3/SkU6ZJE8khcENwM8UdZQ5CimvBl2ZvVjTNjpcShTqk4cIJyMeVWsImihw5yd6tcx9uQrTunqWrK6urK6uoO8x2pdomxpCNbLzC0LQCRqSQQRtvQLmWSGFpI+QM1ZFDMAa8hutwk2K4vWy2SPZojGChnCVFJUkKVuoE7knqaxIkF6vemGWPmt62giEY2p7wK21fZqLjdP6TLiyOWw5nTy08vOAE4H3ldfOr5Mbi0G0b8j3/AMxSl7EinIFW3hmzw7Zcbw7DjKaVJcSpwlSlazrcPc7bqV086b6fdyzO8Tn0psPsNh+lITKFUMBzT4JTgZQnbpkdK01AUenbNBOTzS61IZRMncuM00rWNSkNhJX4ldTjf/5rOs7szyyxlcaaNIpVBk0kDNxavM9cuWHYqlHktaMcvfzxvtWL1i67x7WMYP8AKnI9GgYG9HayWeXgY86WPVHa1+GwMcZqnaXXqzj6UXZwPaCooSCUHxhIBO47/CtvpElx21V1wmNqBPg8Gm3XoK2dsUvWh61ORU132z2rqitEHyNdUVrB8jXDmp4qvWm5xJd5ukaM/reZC9aNJGjxY7isO1ilinllYbeKclQiJSaa2tS3IuVDfUdh8Kb6bcNPBrbnNAlXS+1F4Pka0cihDeswfI12a6tV1dQHEEZUyw3GKl1TKno62w4nqjIxkfOhTTCGMyEZA8e/0qyqScCkdg4WS1aWEvyRIcyrU66zlSvEcZJJOw2rHe2PUf8AcRtoB/ZHA/hTKyvCO3ninDFmSwyttp1KNR1ZQ1p3+BpqLp2mBoy+SfPkVRpmZgTSrhKzqtdzvby5q3/aHQoJUMcvxuHbc+Y+VV6bOpZ4sYxtn3xtmi3b60XAxQ914hgWVDHtciaoPq0pKGwcHA6+L1pPps6MjjUT9T4/WrfDO+4ArfDvD8iPOuMs3qS+iWQtDawcNAqWrA8R7Kx8KeliS6hQQnQRyRy33pYZjY6xmhbFCYe4qu7Dd7dkSGweZFKVYZ8Y6ZOKNedK71siEYI/a8mqxz6WJ5+lNTww+b23cBdngwgEGJp8CvCRvv5nPTtQbbpkUSAMM/wpn4rKFQtLLXEaPG12bZvchbwQSqHpUEMj9n03x3Hzpq7iE8K28Z0afIoCxvH+Kw2NWkW9xKgfa3Djzz+tIw9NkjlDmUke1S0qkY01ioDij/rbifw//avcdPeaTUshX6VCShRuKWjhuQL6m5i8y+WGtBi5OjOMZ6/4UyLZvg/h9XqznV5qmr16sUMeEJPsc6P/ADhn5lPBxLmTqZ3zpT4ulWjgKTpIWyF8e9FnnEi4C4qdvhZ5MqA8q+TSIrQbU3k6XjjGpW/WhvZtIJAHI1H8qmOfRHoK5+tLbZwomJeLrKRdnVKkoc1J0Y0ZVnY53610xjniSJGwU5I8496qkjodR3HtUsHhJauHl29u+zQVOavaQSFjcHHWos4YxcC4jbIH7PiiXU/cOCuKMkcKuP2Vq2/bU1Cm9P8ASUnxqwe+/epNoxuTcazv48CqQTiLxnFcXDhFyZAhxBe57Ps2MutnxOYTjxb1e1tzbSPJq1agdj4z7VSWTunIGKcot5Soq9pcyfjQbaxMMhfWW+lc0m3FB3izKk2uYymW8guNKSFJ6jPcUqelvGTIrlj7H/qix3AUj00LaOHy1Zm4rk+QpWHBrV7w1E+vrUx9PZ3WZiVOc48bVM04ZjtW7DwomzwlRhc5cnU5r1vYJGwGPw2+tO9RtBeyiQtpwMYFAik7YxzQlk4aTFuN1e9rkq57urCyMDxrO35vpWcLGWf8OQaQOCPNNy3QKjanijapGgOpiulO4CkA4+daENxaOdEZGfpSpEiDeg7Rd7W5cLg2xOYUppelaEq9zxKGD8sUtEkFlI7yOAG/l/8AaJJHIVHpxWrdcbSbzNQxNjqkAHmISQFDcdfnRkQQMbp5PQ3GTt/ChMSw0gbimC73am5iYa7hGTJUNSWtfiI3OQPgaYF1AU7gYFR5qxglxqC7UuiT7KriKWWJcQzQg81KQNYHh6n5Utojhb4xnwjcZ4rtbOO0BxTlM2KpQSh9B27Zo8d7bStpRwTVCjLyKwToxXoDySry3/SrLdQtIUDZb2qNBxk8UKu/2lFwTAVOaEpSdaWSDqKd9+noasZ4xC02fSDjPjNRpOdPmhXeL+HWn3WXLswHG1FK04VlJHntRC6hVfw24+1ESGST5RnFdw+KbFNkCPGubLrpBVpSFZwOvagyXMUK63bFWa1lUZKmldvn3L7Su5lwEsxdC/Y3QvPPOdtsnHyrNSG2hdpmfAk/nR5gvbXRuRXdm4gbt1iS/wATNi1PqdI5KsuYHbdIPUA07BHb2ZNtG+fNACSznKrTSTxJZ4smPGfmpQ/I2aTy1nUcgdh6jrR4riOZGkU5C8/ShMjKcHzWn+JLOxNahOzQmS8Mtt8pZyPxAx2NVju4niMyn0ipKMDijBcIqklYdykdfCr9KpHfQvGZQ2w5rijA4NCXe8QI1rlPuyQltDRUo6FHA+ApV76G5UxQN624+5q4jKHLDahrbxBbDZUTfa8xwlay5yl9ATk4057VMN0tuBbzt6xUmMyHKDY0RA4itVwjpkRJKnGlKKQrkrTuDg9QKNL1G3hbSzb1xt5FOCKXWXiK3y510bZlFxTDoSscpY0kqWMbjf3TSMN21u7Szt6WPp+1GltnCjApw1FhDSQ0gE7Z3rQgtbeJtUa4pZpHOAaVWi12tq43FbUZtK3HMrIB8R1KP+P1rLtUF3PKkw1BTt9OaYlmfQN6YM2SzsTHZbMJpuQ8P2jqc5UPXetmWCGSIRyDKjgUqHYHOaxyx2lcxE1cJoyUDCXd8pGCNvmfnQxaWwj7YX0nxV/iJAMA0BDtFrb4hmyURGw6tJC175V7vXf0FZsbGW7ezk3jUbDwP4cVdhpUP5pymHEQcpZRq6d60orKCJtaJvQi7MME1sRoqXCsMpCvMZzVltoBIX071GskYzQy7PaDNTOVAYMtKdKX9PiA8vw3PzonaQxGLHpO+PH5VGTnPmqbxxwkuVPju2GDHbK0LVJIUEFayQQT59DVJEJVVXgcVoWNxHEG1cnFD8G8K3G339qRcmGfZw2tKsOBW5G21DFsH2kAIo13do8eF5q5MBlT8tBAKG0q0pI2Tv2rFtz3J5kbcLx9Pt7UmdgpFah2+23S3j7QhsSwHDs+2F7/AB/GnukgSQ9x92zjPnH3qJHaN/ScUW9abS68y89boa3Wf9EtyOlSm/7JxtWmkSIhRRgHn60tqJOSaxy22lyQ3Jct0JchsYQ6qMkrR+BxkdTXLFGsZjVQFPIxsf4VJYk5JqblxACkMsgHqOWMH6VVIIUUqqgA/QVOpvehbpHtq7c+h2JHcQUEKQpoEKHkRil5o4bVDPHGARvwBxV1LOdJNRW+BavstpkQISWCkp5Ps40YJORjGKtCI7lRcSINR88muLPHsp4ohiJaojaWmIUNlodENxwkD4AUV7aCQ5ZAT9hUd2Q8sfzpVaY1tYlXBaIkZHMcBJSyAVeJfXA36n51kWMayyyLKMgE4B3xv49qPNI2kb1//9k=";PImage x=loadImage(i);void draw(){image(x);} ``` Brute force, and I haven't managed to find a way to remove the draw function. It errors in the main processing engine, I think because it's too big of a b64. You can test it [here](http://jsfiddle.net/73TmL/26/). JS fiddles does crop it though, to 100\*100px. My base64 works, but the online environment doesn't. :( [Answer] # Love2D, 4956 + 395 + 1 = 5351 bytes ``` f=io.open("d","rb")s=f:read("*a"):gsub("(.)(.)",function(a,b)return a:rep(b:byte())end)o=love.image.newImageData(512,512)c={{244,243,248},{173,24,0},{250,209,5},{30,64,164}}o:mapPixel(function(x,y)i=math.floor((x+math.floor(y/4)*512)/4)O=3-i%4 n=s:sub(math.floor(i/4)+1,math.floor(i/4)+1)if n and#n>0 then b=math.floor(n:byte()/(4^O))%4 else b=0 end return unpack(c[b+1])end)o:encode("png","o") ``` The Data file is stored [HERE](https://www.dropbox.com/s/j9p9129sh2l5kdo/d?dl=0) **Output:** [![Output](https://i.stack.imgur.com/oTkOr.png)](https://i.stack.imgur.com/oTkOr.png) **Original:** [![Original](https://i.stack.imgur.com/BXHNP.jpg)](https://i.stack.imgur.com/BXHNP.jpg) ## Explanation ``` f = io.open("d","rb") -- Open the image in raw format. s = f:read("*a"):gsub("(.)(.)",function(a,b)return a:rep(b:byte())end) -- And read it's contents. o=love.image.newImageData(512,512) -- Make the output image c = {{244,243,248},{173,24,0},{250,209,5},{30,64,164}} -- Build the Pallet o:mapPixel(function(x,y) -- Fill the image, based on a function i = (x+y*512) -- The position this pixel exists on the string, 0 indexed. O = 3-i%4 -- The offset. The byte stores 4 pixels, so this is the id among a group of 4. n = s:sub(math.floor(i/4)+1,math.floor(i/4)+1) -- And this gets the byte itself. if n and #n > 0 then -- Sometimes this is null and I don't like it. b = math.floor(n:byte()/(4^O))%4 -- /4^offset % 4 gives us the value of the index on the pallet. else b = 0 -- Fallback plan. end return unpack(c[b+1]) -- Set the pixel to the colour required. end) o:encode("png","o") -- Store it in Appdata as "o", which is a png file. ``` ## The Encoder. This is just the script I used to encode the image. Gif worked out more compressed, but I wasn't challenged to display a gif. ``` img = love.image.newImageData("mondrian.jpg") -- white 0 -- blue 3 -- yellow 2 -- red 1 cols = {{244,243,248},{173,24,0},{250,209,5},{30,64,164}} local s = "" for y = 0, 511 do for x = 0, 511 do local r,g,b = img:getPixel(x,y) local n = 0 local D = math.huge for k,v in pairs(cols) do local d = (v[1]-r)^2 + (v[2]-g)^2 + (v[3]-b)^2 if d < D then n = k-1 D = d end end s = s .. n end end -- Convert base 4 to base 256 -- How many digits do we need- Every 4 digits encd = "" for str in s:gmatch"...." do local n = str:sub(1,1) * 4^3 + str:sub(2,2) * 4^2 + str:sub(3,3) * 4^1 + str:sub(4,4) * 4^0 encd = encd .. string.char(n) end f = io.open("stored.dat","wb") smlr = "" lst = "" c = 0 for s in encd:gmatch"." do if s == lst then c = c + 1 while c > 255 do smlr = smlr .. lst .. string.char(255) c = c - 255 end else if c > 0 then smlr = smlr .. lst .. string.char(c) end lst = s c = 1 end end f:write(smlr) ``` Mostly competing for the bounty. There are likely better ways to do this, but I thought it would be interesting to try to use a simple pallet and run length decoding. EDIT: Input image was simplified, slightly less accurate, but a magnitude less bytes. ]
[Question] [ Your job is to write a program that takes a number N as input and outputs all 2-by-N mazes that are solvable. Output format can be in the form of any two distinct values representing wall and empty - I use `x` and `.` here but you can use anything. You can have a matrix, array, string, ascii art, whatever is convenient, and it can be horizontal, as shown in my examples, or vertical. A maze is solvable if it has a path of empty cells (represented here as `.`) from the left end to the right end. For example, ``` xxxx..... .....x..x ``` is solvable, because you can trace a path (marked with O): ``` xxxxOOOOO OOOOOx..x ``` But this is not. ``` xxx.x.. ..xxx.. ``` You cannot pass through diagonal gaps, so this is also not: ``` xxx... ...xxx ``` # Testcases ``` 1: . . . x x . 2: .. .. .. .x .x .. .. x. .. xx x. .. xx .. ``` [Answer] # Excel, ~~163~~ 143 bytes ``` =LET(a,BASE(SEQUENCE(3^A1)-1,3,A1),b,FILTER(a,ISERROR(FIND(12,a))*ISERROR(FIND(21,a))),SUBSTITUTE(b,2,0)&" "&SUBSTITUTE(SUBSTITUTE(b,1,0),2,1)) ``` Use `1` for walls and `0` for empty cells. ## Original ``` =LET(a,BASE(SEQUENCE(3^A1)-1,3,A1),b,FILTER(a,ISERROR(FIND(12,a))*ISERROR(FIND(21,a))),SUBSTITUTE(SUBSTITUTE(b,1,"X"),2,0)&" "&SUBSTITUTE(SUBSTITUTE(b,2,"X"),1,0)) ``` Uses `0` for empty cells and `X` for walls. [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnBsMSryudqTL8Nd4?e=Mw1dW8) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~192~~ ~~190~~ 188 bytes * Saved two bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) using `++u<=`\$\iff\$`u++<` and `puts("")`'s return value of `1` (i.e. the number of printed bytes). * Saved two bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat); transforming `(a=L>>_+o&1)|(b=L>>o++&1)||(l=v=0),l|=a,v|=b;` into `v=(a=L>>_+o&1)|(b=L>>o++&1)?l|=a,v|b:(l=0);` which when naming the major equivalent segment `@` becomes `@||(l=v=0),l|=a,v|=b;` and `v=@?l|=a,v|b:(l=0);`. ``` s,o,l,v,a,b,L;e(_){for(L=0;L++<1<<2*_;s||puts("")){for(l=v=o=s=0;o<_;s|=l&v)v=(a=L>>_+o&1)|(b=L>>o++&1)?l|=a,v|b:(l=0);for(l=0;l/2<!s;l+=puts(""))for(o=0;o<_;)putchar(46+(L>>l*_+o++)%2);}} ``` [Try it online!](https://tio.run/##jY/BUsIwEIbvPkXsDEzSBFJiRWwbvHlw@gjOMGkIpWNIsAlVx/LsNQgjV4@7/37f7spJLeVAY/BijfBbYcBzq@SWAJaw2SRJJ3cJiOlNGLg2MiBVoxtTS@EB3Hq/dxml0q5VbfVm6ryQb@pTBlmtptLu6MGp1tF79pik9Ioi4ESn1sB/WFB9eeUui/4hfKeMpQ/zRSAGRyzRpCOCVKTMFVyh741tYcmTvMS4mBUFi1e56/v9wTsYReica95xy12YssUp5nrcoY5DwcvlcoXteIZ6WJ0Ki3EonnTPBen6KgtogvKzI8k1ZcWtyzXmf/5TZC9iFLrh8BamcwyDTMfBjTEaMZQfj8NONAaa34sANIHB2BSL8IVBaN82xm9gZAAHo3X2aiJiAjT8AA "C (gcc) – Try It Online") --- Uses `.` as a path character and `/` as a wall character. Requires `n < 16` assuming an `int` is 32 bits wide and can thus hold `2*n +1` bits. Due to this problem's combinatorial nature, this restriction should be of little hindrance. Else one may need to consider 128 bit systems. If one was to allow barely printable characters like tab (ASCII `9`) and newline (ASCII `10 = 9+1`), one could save a byte by substituting `s!46+!9+!`. Even more extremely, outputting literal zeroes and ones, `s!46+!!` would save three bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes Returns a list of mazes where each maze is a list of `2×1` slices. `0`'s are walls. ``` T2ãIãʒ∊ü&PĀ ``` [Try it online!](https://tio.run/##AS0A0v9vc2FiaWX//1Qyw6NJw6PKkuKIisO8JlDEgP99dnnigqxTw7hKwrssIiIs/zI "05AB1E – Try It Online") Footer prints mazes horizontally. Same idea as my APL answer, for each `2×2` submaze check if it is solvable (contains `11` in the top or bottom row). **Commented:** ``` T # push integer / string 10 2ã # all pairs of 1/0 Iã # all n-tuples of pairs of 1/0 # each n-tuple represents a 2×n maze ʒ # filter the mazes on: ∊ # extend the maze by mirroring (for n=1) ü& # bitwise and of adjacent maze slices PĀ # is the product not equal to 0? ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), ~~109~~ 84 bytes ``` \0⅛\1⅛\2⅛?(¾3n›e(¼_)ƛ0+⅛_nt0=[n›⅛n2+⅛|nt1=[n›⅛|n2+⅛]])ƛ\0`00 `øṙ\1`01 `øṙ\2`10 `øṙ;⁋ ``` My first Vyxal answer, which is probably why it's so bad. -25 bytes thanks to lyxal. [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%5C0%E2%85%9B%5C1%E2%85%9B%5C2%E2%85%9B%3F%28%C2%BE3n%E2%80%BAe%28%C2%BC_%29%C6%9B0%2B%E2%85%9B_nt0%3D%5Bn%E2%80%BA%E2%85%9Bn2%2B%E2%85%9B%7Cnt1%3D%5Bn%E2%80%BA%E2%85%9B%7Cn2%2B%E2%85%9B%5D%5D%29%C6%9B%5C0%6000%0A%60%C3%B8%E1%B9%99%5C1%6001%0A%60%C3%B8%E1%B9%99%5C2%6010%0A%60%C3%B8%E1%B9%99%3B%E2%81%8B&inputs=3&header=&footer=) [Answer] # [Python 3](https://docs.python.org/3/), ~~91~~ 83 bytes Returns a list of lists of strings with characters `.` and `x`. ``` f=lambda n,*d:[[]][n:]or[w+[x]for x in{'.x','x.'}^{*d,'..'}for w in f(n-1,x[::-1])] ``` [Try it online!](https://tio.run/##PcpBCoMwEIXhvaeY3Zg0BsRdIFfwAmkKKTFUqKNEwbTSs6eGQneP/3vLa3vM1OUc9NNNd@@ABPfKGGsNKTtHs19MsmGOkGCkA2VCgUni53ZwL1Ceq@B@IoSamlYko1TTWmZzDxq6qvDk3sPv0TNVASxxpK3mJQtYh0XjlZD9geUv "Python 3 – Try It Online") The output is vertical. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 78 bytes ``` f=n=>n?f(n-1).flatMap(a=>(g=eval(a+=` `))%22?[a+22,a+g]:[a+12,a+21,a+22]):[''] ``` [Try it online!](https://tio.run/##FcxBCoMwEEDRfe9RnCFVyHSnTDxBTyBBB5uElphIFa@f6ubzVv8rh2zz77PudcpvV4rnxCb1HlKtsfFR9pesIGwgsDskgiiebhPinagfRBE9RAXbntQXSV8hi@1QVbZ0Hp7YLOdiZDPntOXompgDjIhd@QM "JavaScript (Node.js) – Try It Online") 2 as path, 1 as wall # [JavaScript (Node.js)](https://nodejs.org), 88 bytes ``` f=n=>n?f(n-1).flatMap(a=>(g=a.slice(0,2),g%11?[11,g]:['01',10,11]).map(_=>_+` `+a)):[''] ``` [Try it online!](https://tio.run/##PctBCsMgEADAe/9RdIkRt701aF7QFwQxi1VJMRqa0O/bnHoe5k1f2v1n2Y6@1FdoLeqiTRkjLz2CjJmOJ22ctOFJk9zz4gNX4gYiXRHHCVEk@5iYQiZQCUQLcj2D08Z182XuCOBkZtsQ@f1vvpa95iBzTdwBDO0H "JavaScript (Node.js) – Try It Online") 1 as path, 0 as wall [Answer] # [Haskell](https://www.haskell.org/), 66 bytes ``` (d%) r%0=[[]] r%n=[h:t|h<-max[d,"x.",".x"][r,d],t<-h%(n-1)] d=".." ``` [Try it online!](https://tio.run/##Fco9DsIgGADQvaf4QmwC4Sc2bqZ4Ap0cHCgDKVYaaSUUE2o8u6jbG54zy/3qfRlkV7CtSRXrrVRK6x9mqdw@vV3LJ5OVZSgLxJDISKvIrGap5a7GM2@IrqxEQqAymXGWkwknCM90TvE4wwaGh7exAfwaw2VMDnCXYeWHTCkCQJSuhPwX7MqnH7y5LYX3IXwB "Haskell – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes ``` NθEΦEX³θE◧⍘ι³θΣλ⬤ι⁻³∧μ⁺λ§ι⊖μE²⭆ι§.x⁼⊕λν ``` [Try it online!](https://tio.run/##RY3BDoIwEETvfkXDqU2qBzlywqgJiRgSvqBC1SbbBUqr/H3dyoE9zUzm7XRv5bpBQYwVjsHfg31oxydR7Bpn0PNajfxqwFOYZDN8SeWSTUKyf6D6m356flKzbj0hL24ky8XaaIPlIEiUACmvDYY54SX23ErWAFkg6yvs9ZIqZ905bTV6TQ2x3jp1pH//hWTMBmWHJZPsMgUFM69ww4FAXD8UMeZx/4Ef "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Represents mazes internally as a list of digits, `0` = no walls, `1` = upper wall, `2` = lower wall. (`3` would be an impossible maze, of course.) ``` Nθ Input `N` as a number. EX³θ Map over potential mazes E◧⍘ι³θΣλ Split into lists of walls Φ Filter over mazes where ⬤ι All columns satisfy ⁻³∧μ⁺λ§ι⊖μ Consecutive sums do not total 3 E Map over filtered mazes E² Map over each row ⭆ι Map over the maze and join §.x⁼⊕λν Select wall or space Implicitly print ``` [Answer] # [J](http://jsoftware.com/), 43 bytes ``` [:(#~(0=&#.*&(2#.\0,]))/"2)-]\"#.2#:@i.@^+: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o600lOs0DGzVlPW01DSMlPViDHRiNTX1lYw0dWNjlJT1jJStHDL1HOK0rf5rcqUmZ@QrpCkYQhjqurq66jAx4/8A "J – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 4ṗ’Ḋ&ƝP$Ƈd2 ``` A monadic Link accepting a positive integer that yields a list of lists of pairs where `0` represents a wall and `1` represents space. **[Try it online!](https://tio.run/##ASUA2v9qZWxsef//NOG5l@KAmeG4iibGnVAkxodkMv/Dh8WS4bmY//8y "Jelly – Try It Online")** ### How? ``` 4ṗ’Ḋ&ƝP$Ƈd2 - Link: integer, n 4 - four ṗ - ([1,2,3,4]) Cartesian power (n) -> all n-tuples made from alphabet [1,2,3,4] ’ - decrement -> all n-tuples made from alphabet [0,1,2,3] (first is all zeros) Ḋ - dequeue (remove the first, to make the rest work when n=1) Ƈ - filter keep those for which this is truthy (non zero): $ - last two links as a monad - f(potential): Ɲ - for neighbours: & - bitwise AND P - product d2 - div-mod two (vectorises) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~47~~ ~~40~~ 43 [bytes](https://github.com/abrudz/SBCS) Assumes `⎕IO←0`, `0`'s are walls. -7 bytes inspired by [this answer](https://codegolf.stackexchange.com/a/165670/64121). -4 bytes thanks to [Razetime](https://codegolf.stackexchange.com/users/80214/razetime)! (Commute `⍴` to save on parenthesis, replicate first `⌿` instead of replicate along the first axis `/[0]`) ``` {(⌊/⌈/[1]2⌊/x,⌽x)⌿x←(2*2×⍵)2⍵⍴↑⍳2⍴⍨2×⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6s1HvV06T/q6dCPNow1ArErdB717K3QfNSzvwKoQsNIy@jw9Ee9WzWNgMSj3i2P2iY@6t1sBGL1roBI1f5PA6p81Nv3qKv5Ue8aoNSh9cYgdX1Tg4OcgWSIh2fw/zQFIwA "APL (Dyalog Unicode) – Try It Online") `⌊/⌈/[1]2⌊/x,⌽x` is checking if a maze is solvable, everything else is just generating and filtering all mazes. [Answer] # [Haskell](https://www.haskell.org/), 80 bytes ``` f n=[m|m<-mapM(["..","x.",".x"]<$f)[1..n],all(<"xx").z(z max)m$tail m] z=zipWith ``` [Try it online!](https://tio.run/##NY2xCsIwFEX3fMUjdEigDYhr2i/QycGhFHnQ1gbznqFGCMF/j63gcofD5ZwFX4/J@1Jm4LanD9mGMJxVL42RtUz7mCQHW826PxjDQ43eKytTktpklYEwaaoiOg80iNxmF64uLoXQcTs@BbBt1gnHEwsIq@No/MT3uFRbUcAeuynVdeEdL3E9sdy0Pwh/ovdnOX4B "Haskell – Try It Online") Takes `n` as input, returns the list of all the \$2\times n\$ solvable mazes; each maze is represented as a list of list of characters, where `.` is an empty cell and `x` is a wall. # [Haskell](https://www.haskell.org/), 81 bytes ``` f 1=pure<$>g e f n=[x:h:t|h:t<-f$n-1,x<-g h] g".."=[e,"x.",".x"] g s=[e,s] e=".." ``` [Try it online!](https://tio.run/##Nc2xCoMwFAXQPV/xeDgomIB0k8QvsFNHkRIwJlJ9DTFChv57qoUOdzn3wnV6f5l1zXmGRvkjGFl0FgybgdSQWtfGzxnJ54J4UyfJLbiRWRQC1WBqTAJrFAlPg/2SfWRGXXXe9EJqejMgyYPRU08MfFgoitWQja44Pxhs2t@fZdl1/oiPGHpCrMQP4S/Vtcy3Lw "Haskell – Try It Online") Recursive version. [Answer] # [JavaScript (V8)](https://v8.dev/), 101 bytes Prints all solutions, with `0` = empty and `1` = wall. ``` n=>{for(i=q=1<<n;i--;)for(j=q;j--;)i&(j|j*2|j/2)||print((g=n=>n--?[i>>n&1]+[j>>n&1]+` `+g(n):'')(n))} ``` [Try it online!](https://tio.run/##LYtBCoNADEX3PYgmlVC0m9Ix04NIQSmMJItUR3HT6dmnCl399x58HbZheUWZVtpuOXA29p/wjiA8c9225oTI4VGUZ6eHSAGa9NwkvTSY0hTFVoCR96sRPTrx3or6WXX6h/7UVyMY3ssS98FvDnDF/AM "JavaScript (V8) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 75 bytes A port of my Python answer. ``` (!"") 0!_=[[]] n!d=[x:w|x<-"..":[w|w<-[".x","x."],w/=d],w<-(n-1)!reverse x] ``` [Try it online!](https://tio.run/##DcQ9DsIgGADQvacoXxwgKfgzNnADnRyRNKQFbaSEQCsMPbvoG95Lp7dxrlrxqBgBkOaEBiGlUo1Hk5Clz3vhFBiDXuY9cyqBFeigMFBdPorpP6fY0zNB0XxMTKYtqi569mLR4TbgsK33NV4927ybvUnkYNtL/Y7W6WeqdAzhBw "Haskell – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip) `-P`, 39 bytes ``` Y3**a[01t00]@^_MtNI_.RV_FI@>(_TB3)My+,y ``` Outputs each maze as a list of 2x1 slices, where `0` is a space and `1` is a wall. [Try it online!](https://tio.run/##K8gs@P8/0lhLKzHawLDEwCDWIS7et8TPM14vKCzezdPBTiM@xMlY07dSW6fy////ugH/jQE "Pip – Try It Online") Here's a version with nicer output: [Try it online!](https://tio.run/##K8gs@P8/0lhLKzEy2sCwxMAg1iEu3rfEzzNeLygs3s3TwU4jPsTJWNO3Ulun8r9bbqVCNZdCgEJULpCs4Kr9/183578xAA "Pip – Try It Online") ### Explanation Observing that a slice with both walls (`11`) is no good, we try all combinations of slices `00`, `01`, and `10`, with the further rule that `01` and `10` cannot be adjacent. I tried using Cartesian product at first, but found that abusing base conversion was shorter. ``` Y3**a[01t00]@^_MtNI_.RV_FI@>(_TB3)My+,y a is command-line arg; t is 10 (implicit) Y3**a Yank 3 to the power of a into y variable y+,y Range from y to 2*y M For each number in that range: _TB3 Convert to base 3 @>( ) Remove the leading 1 We now have a list of all strings of 0,1,2 whose length equals the input number 0 represents a slice with a wall in the lower half, 1 with a wall in the upper half, and 2 a slice with no walls. FI Filter that list on this function: t 10 NI is not a substring of _.RV_ the string concatenated to its reverse M For each string in the remaining list: ^_ Split it into digits [01t00]@ and use each digit to index into the list [01;10;00] ``` [Answer] # [Zsh](https://www.zsh.org/) `-F`, 57 bytes ``` eval for\ {1..$1}\ (01 10 00) 'grep -Ev "1 1|10 01"<<<$@' ``` [Try it online!](https://tio.run/##qyrO@F@cWqKg66Zg/D@1LDFHIS2/KEah2lBPT8WwNkZBw8BQwdBAwcBAU0E9vSi1QEHXtUxBCShWAxI1VLKxsVFxUP//HwA "Zsh – Try It Online") Outputs as a space-separated list of pairs of characters, with `1` representing walls and `0` representing gaps. * `for\ {1..$1}\ (01 10 00)`: construct the string `for 1 (01 10 00) for 2 (01 10 00) for 3 (01 10 00) ... for n (01 10 00)` * `eval`uate that string, which is n nested for-loops using the loop variables `1` to `n`, creating all the combinations of `01 10 00` (so all possible mazes) * `<<<$@` - print all the variables numbered `1` to `n` separated by spaces * `grep -Ev "1 1|10 01"` - filter out combinations which match either `1 1` or `10 01` (i.e., diagonal walls) ]
[Question] [ A string is dot-heavy when its morse representation contains more dots than dashes. For example, the letter E is a single dot, which means it is Dot-heavy. # Input * The input string will only contain characters in the range of `[a-z]` or `[A-Z]`. You can decide if they should *all* be upper case, or all lower case. `AAA` is fine, `aaa` is fine, `aAa` is not. * The input string will always be at least 1 character in length. * You may assume that input strings will never have an equal amount of dots and dashes. # Output You should return [Truthy](https://codegolf.meta.stackexchange.com/a/2194/41257) for inputs that contain more dot characters. You should return Falsy for inputs that contain more dash characters. Edit: I will allow a positive value for dot and a negative value for dash as well. # Test cases ``` | input | morse representation | result | |------------------------------------------------| | S | ... | Truthy | | k | -.- | Falsy | | HELLO | .... . .-.. .-.. --- | Truthy | | code | -.-. --- -.. . | Falsy | ``` # Reference ![International Morse Code](https://i.stack.imgur.com/35Dsn.png) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes wins. [Answer] # x86-16 machine code, 42 bytes ``` 00000000: fc32 e4bb 1c01 ac24 1fd0 e8d7 7206 51b1 .2.....$....r.Q. 00000010: 04d2 e859 240f 2c03 02e0 e2ea c353 4452 ...Y$.,......SDR 00000020: 7412 5130 3146 2452 3100 t.Q01F$R1. ``` **Listing:** ``` FC CLD ; LODS string functions forward 32 E4 XOR AH, AH ; running sum = 0 BB 0119 MOV BX, OFFSET TBL-1 ; offset data by -1 byte for one-based index LETTER_LOOP: AC LODSB ; load next char from DS:SI into AL, advance SI 24 1F AND AL, 1FH ; convert ASCII letter to one-based index D0 E8 SHR AL, 1 ; divide index by 2, CF=1 if odd index D7 XLAT ; look up letter in table 72 06 JC ODD ; odd index use low nibble; even use high 51 PUSH CX ; save loop counter B1 04 MOV CL, 4 ; set up right shift for 4 bits D2 E8 SHR AL, CL ; bit shift right 59 POP CX ; restore loop counter ODD: 24 0F AND AL, 0FH ; isolate low nibble 2C 03 SUB AL, 3 ; dash/dot difference remove +3 positive bias 02 E0 ADD AH, AL ; add difference to sum, set result flags E2 EA LOOP LETTER_LOOP ; loop until end of input C3 RET ; return to caller TBL: DB 53H, 44H, 52H, 74H, 12H, 51H DB 30H, 31H, 46H, 24H, 52H, 31H, 30H ``` **Explanation** Input: string at `DS:SI` (upper or lower case OK). Output: Truthy if `SF == OF` (use `JG` or `JL` to test). The letter difference table values are stored as binary nibbles, so only takes 13 bytes in total. One byte can be saved by converting the input ASCII into a one-based index (`'a' = 1`, etc), however that would offset the table lookup index by one byte, not one nibble. Fortunately for us, the opcode of the previous `RET` instruction is `C3`, so that `3` is used for the `'a' = 1` nibble index. **Example Output:** [![enter image description here](https://i.stack.imgur.com/sehx1.png)](https://i.stack.imgur.com/sehx1.png) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~24~~ 15 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") -9 thanks to Ven Anonymous tacit prefix function taking uppercase as argument. ``` >/'.-'⍧∊∘⌂morse ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/305fXU9X/VHv8kcdXY86ZjzqacrNLypO/Z/2qG3Co96@R31TPf0fdTUfWm/8qG0ikBcc5AwkQzw8g/@nqQerc6Wpe4MID1cfH38Qw9nfxVUdAA "APL (Dyalog Extended) – Try It Online") `⌂morse` convert to list of Morse strings `∘` then `∊` **ϵ**nlist (flatten) `'.-'⍧` count the number of dots and dashes in that `>/` more dots than dashes? (lit. greater-than reduction) [Answer] # [Java (JDK)](http://jdk.java.net/), ~~131~~ ~~124~~ ~~110~~ ~~84~~ 64 bytes Interestingly, "dot" is dash-heavy and "dash" is dot-heavy. Takes input in all caps as an `IntStream` (scroll down for a version with an actual `String` for an extra 8 bytes). I've had quite a lot of help golfing this one: Thanks to [Expired Data](https://codegolf.stackexchange.com/users/85908/expired-data) for golfing 20 bytes, to [Neil](https://codegolf.stackexchange.com/users/17602/neil) for golfing 26 bytes, to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%C3%A9goire) for golfing 18 bytes and to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for golfing 2 bytes. Contains 26 unprintable characters inside the double quotes. ``` c->c.map(a->"".charAt(a-65)-4).sum()>0 ``` [Try it online!](https://tio.run/##jY5BS8QwFISxTav0V4SeEqHBg3opFhY8uAfxUG/i4W0a19QmKcnrwrL0t9fgYsGbp/cGZr6ZHg5Q9d3Xos3oPNI@ajGhHkRAr8CI67oYp92gJZUDhECfQVt6KrRF5T9AKrq1YVQSnT/tnBsUWNo5xCPbWmx/EFTyev6FBASM5@B0R01EsejRdv/2TsHvA4/klUf1@j3QRVaNFAZGBlVTkpxkWZ5e5UmaJ@SCJNllGjVJSCnkJ/gNRtv9Ha9uuQiTYby5WeqiPQZURrgJxRhLcbBsrRDn0eXjy@sZERjn/J@ZTfv0JzQX8/IN "Java (JDK) – Try It Online") Ungolfed: ``` c -> // lambda taking input as an IntStream in upper case and returning a boolean c.map(a -> "" // map each character's ASCII value to its net dot impact (unprintable characters here) .charAt(a - 65) // translate the ASCII code into a zero-based index into the above string (65 is 'A') - 4) // unprintables are > 0, this restores the proper values .sum() > 0 // add up all the values, positive sum indicates a dot-heavy input string ``` # [Java (JDK)](http://jdk.java.net/), ~~131~~ ~~124~~ ~~110~~ ~~84~~ 72 bytes For purists; takes input as a `String`. Thanks to [Expired Data](https://codegolf.stackexchange.com/users/85908/expired-data) for golfing 20 bytes, to [Neil](https://codegolf.stackexchange.com/users/17602/neil) for golfing 26 bytes and to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%C3%A9goire) for golfing 10 bytes. ``` s->s.chars().map(a->"".charAt(a-65)-4).sum()>0 ``` [Try it online.](https://tio.run/##jY4xa8MwEIWpLbvFv@LwJA0WHZouoYZAh3YoHdytdLjISqrUlox0DoTg3@6KNHju9O7g43vvgEesDu3PPIzbzihQHYYAb2gsnAtjSfsdKg2vNgxakfPnrXOdRgutIzrxhryxe1BiPRVXQyCkGEdnWuij58p8fgH6fRBRu8jALNcTzKGqg1Tf6AMXsseBY1WXLGdZlqd3eZLmCbthSXabxp8lrLywG4rY40pUD0KGseeivp/XRXMKpHvpRpJDLKfO8qVK/i0vn98/SiH@yW6alws8FdP8Cw) Ungolfed: ``` s -> // lambda taking input as a String in upper case and returning a boolean s.chars() // convert to a stream of characters .map(a -> "" // map each character's ASCII value to its net dot impact (unprintable characters here) .charAt(a - 65) // translate the ASCII code into a zero-based index into the above string (65 is 'A') - 4) // unprintables are > 0, this restores the proper values .sum() > 0 // add up all the values, positive sum indicates a dot-heavy input string ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Oị“ÆġwıMƥ)ɠịṙ{’D¤Æm>4 ``` **[Try it online!](https://tio.run/##ATQAy/9qZWxsef//T@G7i@KAnMOGxKF3xLFNxqUpyaDhu4vhuZl74oCZRMKkw4ZtPjT///9DT0RF "Jelly – Try It Online")** ### How? ``` Oị“ÆġwıMƥ)ɠịṙ{’D¤Æm>4 - Link: list of characters ([A-Z]), S ¤ - nilad followed by link(s) as a nilad: “ÆġwıMƥ)ɠịṙ{’ - base 250 integer = 14257356342446455638623624 D - to decimal digits - -- that is the number of dots less the number of dashes plus 4 - ... for each of OPQRSTUVWXYZABCDEFGHIJKLMN O - ordinals of S e.g. "ATHROUGHZ" -> [65,84,72,82,79,85,71,72,90] ị - index into (1-indexed & modular, so O gets the 79%26 = 1st item - or A gets the 65%26 = 13th item Æm - arithmetic mean >4 - greater than 4? ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~22~~ 21 bytes Saved a byte thanks to *Kevin Cruijssen* ``` SA•U(Õþć6Δ »›I•‡3-O.± ``` [Try it online!](https://tio.run/##yy9OTMpM/W/i9j/Y8VHDolCNw1MP7zvSbnZuCteh3Y8adnkCBR81LDTW9dc7tPG/zv9irmyujNScnHyu5PyUVAA "05AB1E – Try It Online") **Explanation** ``` •U(Õþć6Δ »›I• ``` is **35344527512513031462452313** compressed to base 255. ``` S # split input into list of chars ‡ # transliterate A # the lowercase alphabet •...• # with the digits from the compressed string 3- # subtract 3 from each O # then sum the result .± # and take the sign ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 47 bytes ``` n=>n.Sum(i=>("[E[LduRgmQSMK"[i%13]>>i%2*3)%8-3) ``` Uses [Level River St's](https://codegolf.stackexchange.com/a/181425/84206) 'magic string'. Be sure to upvote their solution as well! It's not everyday C# beats Ruby, Python, Javascript, C, Retina, and Perl! [Try it online!](https://tio.run/##LcZBS8MwFADge35FeFBIpC2bvci2xlNFsSKuEw/VQ0jS9aF7KUk6kLHfXi9@p8/EwkRcHmYyu5gC0jFHSmqoF6oVld18ElgrAX3Tt3beH09v3csz9Jitqy@lMLu9qWR2V1Ry2bLBB6fNKM46cM2R@BOVe6ftwTdkhSy76QeTgE8CKdlHwORaJCfgsrpyjPyyvkKu80Ho8uDfp8kFIeVudQ9Wx7EYnT7/wgasT/@X26Vj3@yxadtXZrx1fw "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes ``` 9“¡ȷṡẓh)ėḂYF@’ḃ_4ị@OS0< ``` [Try it online!](https://tio.run/##ATcAyP9qZWxsef//OeKAnMKhyLfhuaHhupNoKcSX4biCWUZA4oCZ4biDXzThu4tAT1MwPP///0hFTExP "Jelly – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~84~~ ~~82~~ ~~81~~ ~~79~~ 75 bytes Assumes all caps. ``` r;f(char*s){for(r=0;*s;r+="+-+,,-*/--*-)+(+),.*,-*+)+"[*s++%65]-43);s=r>0;} ``` [Try it online!](https://tio.run/##PczPC4IwHAXwc/srxkDY9t1K6MehYRApCAke6lYdZDLz0IxNuoh/u2lgt8/jPZ6WldbD4JSh@lk47llnGkddFCrulYOIgAQhJF9JySUDCkws@ZiBAblxDxDstg@5WTPlI3cIVT98mrrEFdWN9S2eTvH4ijq0eLvatoaSoMR7HPi7JQIb6pnAninUIzTW@FXUlv7mFSUXMhYTzjPSJMvyOZzyOJkdHy/p3/l1Yj98AQ "C (gcc) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~73~~ ~~70~~ 69 bytes ``` lambda s:sum(int(`0x21427b563e90d7783540f`[ord(c)%25])-3for c in s)>0 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYqrg0VyMzr0QjwaDCyNDEyDzJ1Mw41dIgxdzcwtjUxCAtITq/KEUjWVPVyDRWU9c4Lb9IIVkhM0@hWNPO4H9BEVCrQpqGerC6Jhec443M8XD18fFHFnD2d3FV1/wPAA "Python 2 – Try It Online") Uppercase only -3 bytes, thanks to Erik the Outgolfer --- Both upper- and lowercase version: # [Python 2](https://docs.python.org/2/), ~~73~~ 71 bytes ``` lambda s:sum(int(oct(0x1d7255e954b0ccca54cb)[ord(c)%32])-3for c in s)>0 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYqrg0VyMzr0QjP7lEw6DCMMXcyNQ01dLUJMkgOTk50dQkOUkzOr8oRSNZU9XYKFZT1zgtv0ghWSEzT6FY087gf0ERULNCmoZ6sLomF5yTjczxcPXx8UcWSM5PSVXX/A8A "Python 2 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~69 68~~ 65 bytes *-3 bytes thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* Expects the input string in uppercase. Returns \$0\$ or \$1\$. ``` s=>!Buffer(s).map(n=>s='30314624523133534452741251'[n%26]-4-~s)<s ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1k7RqTQtLbVIo1hTLzexQCPP1q7YVt3YwNjQxMzIxNTI2NDY2NTYBMgyNzE0MjVUj85TNTKL1TXRrSvWtCn@n5yfV5yfk6qXk5@ukaahHqyuqakAAvr6CoZcaJLeSJIG6JIerj4@/iAF2HQ6@7u4gjVj0@niGOwBk8TQ6eIfArEVpPM/AA "JavaScript (Node.js) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 20 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ÉBÜ◙ƒ╣<Hf6─òɼsäS╗◄↔ ``` [Run and debug it](https://staxlang.xyz/#p=90429a0a9fb93c486636c49590ac738453bb111d&i=S%0AK%0AHELLO%0ACODE&a=1&m=2) Unpacked, ungolfed, and commented, it looks like this. ``` "45D.J57KBJa`"I" string literal with code points [52 53 68 46 74 53 55 75 66 74 97 34 73] $ flatten to string "52536846745355756674973473" ; push input @ get string characters at indices (using input codepoints as indices; lookups wrap around) :V arithmetic mean 53> is greater than 53 ``` [Run this one](https://staxlang.xyz/#c=%2245D.J57KBJa%60%22I%22%09string+literal+with+code+points+[52+53+68+46+74+53+55+75+66+74+97+34+73]%0A%24+++++++++++++++%09flatten+to+string+%2252536846745355756674973473%22%0A%3B+++++++++++++++%09push+input%0A%40+++++++++++++++%09get+string+characters+at+indices+%0A++++++++++++++++%09%28using+input+codepoints+as+indices%3B+lookups+wrap+around%29%0A%3AV++++++++++++++%09arithmetic+mean%0A53%3E+++++++++++++%09is+greater+than+53&i=S%0AK%0AHELLO%0ACODE&m=2) [Answer] # [Ruby](https://www.ruby-lang.org/), 64 bytes ``` ->s{n=0;s.bytes{|i|n+=("[E[LduRgmQSMK"[i%13].ord>>i%2*3)%8-3};n} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664Os/WwLpYL6myJLW4uiazJk/bVkMp2jXaJ6U0KD03MNjXWyk6U9XQOFYvvyjFzi5T1UjLWFPVQte41jqv9r9qeXWwgreCh6uPj7@Cs7@La61ebmJBdU1WTYFCdJZOWnRWbGwtl4a9o56efZQmFrn/AA "Ruby – Try It Online") Uses a 13-byte magic string, 2 numbers `0..7` encoded in each byte. Subtract 3 for a range `-3..4`. The ASCII code for `A` (and also `N`) taken modulo 13 is by coincidence, zero. [Answer] # GNU sed, 113 bytes Accepts lower-case inputs, one per line. Output is 1 for dot-heavy or 0 for dash-heavy. Since the question didn't specify the output for exactly balanced lines, I produce an empty line in that case. ``` s/[acnpxz]//g y/bdfgjklqruvwy/ieitmtimeeitm/ :e s/h/ii/ s/s/ie/ s/i/ee/ s/o/mt/ s/m/tt/ s/et\|te// te /e/c1 /t/c0 ``` 1. First, remove the letters which are themselves balanced. 2. Replace unbalanced letters with their equivalents (e.g. Q is `--·-`, so its net contribution is `--`, i.e. M). 3. Expand these equivalents into the corresponding count of E or T. 4. Remove paired E and T 5. If we have an E remaining, we're dot-heavy; if we have a T remaining, we're dash-heavy; otherwise (nothing remaining) evenly balanced. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 51 bytes ``` T`L`35344527412513031462452313 . $*<>>> +`<>|>< ^< ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyTBJ8HY1NjExNTI3MTQyNTQ2MDY0MTMCMg3NjTm0uNS0bKxs7Pj0k6wsauxs@HiirP5/z@Yy5vLw9XHx5/L2d/FFQA "Retina 0.8.2 – Try It Online") Link includes test cases. Only accepts upper case (+6 bytes for mixed case). Shamelessly stealing @Arnauld's string but I was going to use the same algorithm anyway. Explanation: ``` T`L`35344527412513031462452313 . ``` Change each letter into the difference in numbers of dots and dashes, plus three, so `O=0` and `H=7`. ``` $*<>>> ``` Represent the difference as that number of `<`s and three `>`s. (Sadly I can't use dots because they're special in regex.) ``` +`<>|>< ``` Remove matched pairs of `<`s and `>`s. ``` ^< ``` Check whether there are still any dots left. [Answer] # [Bash](https://www.gnu.org/software/bash/)+coreutils,  64 60 bytes ``` tr a-z 35344526512513031462452313|sed s/./\&z-+/g|dc -eIK?^p ``` [Try it online!](https://tio.run/##S0oszvj/v6RIIVG3SsHY1NjExNTIzNTQyNTQ2MDY0MTMCMg3NjSuKU5NUSjW19OPUavS1dZPr0lJVtBN9fS2jyv4/z8jNScnHwA "Bash – Try It Online") Takes a string in lowercase, outputs zero for falsy, nonzero for truthy # Explanation Uses tr and sed to create a dc program that looks like (for the example input 'hello'): ``` IK6z-+4z-+5z-+5z-+0z-+^p IK Push 10, then 0 to the stack 6z-+ Push 6 (three more than the dots minus dashes in 'h'), subtract 3, and accumulate ... Do the same for all other letters, so the stack now has the total dots minus dashes ^ Raise 10 to this power - precision is zero so this turns negative/positive to falsy/truthy p Print result ``` [Answer] # [R](https://www.r-project.org/), 74 70 bytes ``` f=utf8ToInt;sum(f("42433250265364746315325464")[f(scan(,''))-96]-52)<0 ``` input should be lower case, returns TRUE or FALSE [Try it online](https://tio.run/##K/qfZptWmpdckpmfp1GhWV2cnJhnowsX0dPT06yuqAUqKi1JswjJ98wrsS4uzdVI01AyMTIxNjYyNTAyMzU2MzE3MTM2NAXyTcxMlDSj0zRABmnoqKtraupamsXqmhpp2hj8r@UCaixW0gRR2RAqIzUnJ19J8z8A) [Answer] # TI-BASIC (TI-84), 111 bytes ``` :Ans→Str1:"ABCDEFGHIJKLMNOPQRSTUVWXYZ→Str2:"35344527512513031462452312→Str3:0<sum(seq(expr(sub(Str3,inString(Str2,sub(Str1,X,1)),1)),X,1,length(Str1))-3 ``` I used the same string for determining dot-heaviness as some of the other answers. Program returns truthy (`1`) if the input string is dot-heavy, falsy (`0`) if not. Input string must be in all-caps. Input is stored in `Ans`. Output is stored in `Ans` and is automatically printed out when the program completes. **Ungolfed:** ``` :Ans→Str1 :"ABCDEFGHIJKLMNOPQRSTUVWXYZ→Str2 :"35344527512513031462452312→Str3 :0<sum(seq(expr(sub(Str3,inString(Str2,sub(Str1,X,1)),1)),X,1,length(Str1))-3 ``` **Example:** ``` "HELLO HELLO prgmCDGF3 1 "CODE CODE prgmCDGF3 0 ``` **Explanation:** (TI-BASIC doesn't have comments, assume that `;` indicates a commment) ``` :Ans→Str1 ;store the input into Str1 :"ABCDEFGHIJKLMNOPQRSTUVWXYZ→Str2 ;store the uppercase alphabet into Str2 :"35344527512513031462452312→Str3 ;store dot-dash+3 for each letter into Str3 :0<sum(seq(expr(sub(Str3,inString(Str2,sub(Str1,X,1)),1)),X,1,length(Str1))-3 ;full logic sum( ;sum the elements of seq( ) ;the list evaluated by sub( ) ;the substring of Str3, ;Str3 inString( ), ;at the index of sub( ) ;the substring of Str1, ;Str1 X, ;starting at X 1 ;of length 1 Str2, ;in Str2 1 ;of length 1 expr( ), ;converted to an integer X, ;using X as the increment variable 1, ;starting at 1 length(Str1) ;ending at the length of Str1 -3 ;then subtract 3 from all elements in the list 0< ;then check if the sum is greater than 0 ;implicitly output the result ``` --- **Note:** The byte count of a program is evaluated using the value in **[MEM]**>**[2]**>**[7]** (124 bytes) then subtracting the length of the program's name, `CDGF3`, (5 bytes) and an extra 8 bytes used for storing the program: 124 - 5 - 8 = 111 bytes [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 21 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` Ạ»œfḅ“ƈ©OMṾȤØ»ṆdN3-Sʂ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWN9Uf7lpwaPfRyWkPd7Q-aphzrOPQSn_fhzv3nVhyeMah3Q93tqX4GesGn2paUpyUXAzVtGBpRmpOTj6EAwA) Port of Emigna's 05AB1E answer. #### Explanation ``` Ạ»œfḅ“ƈ©OMṾȤØ»ṆdN3-Sʂ # Implicit input Ạ # Push the lowercase alphabet »œfḅ“ƈ©OMṾȤØ» # Push compressed integer 35344527512513031462452313 Ṇ # Transliterate the input string (^^ --> ^) dN # Convert to a list of digits 3- # Subtract 3 from each S # Sum the list ʂ # Sign of the sum # Implicit output ``` [Answer] # [Morsecco](https://codegolf.meta.stackexchange.com/a/26119/72726) 175 bytes morsecco has a small advantage here: it knows morse code by nature. Do `. - .-.` to `R`ead the stdin (special address `-`), `-.- .-` to `K`onvert from `·T`ext, `-.- --` to `K`onvert to `M`orse and you already have the morse transcript. But then the work begins! ``` . - .-. -.- .- -.- -- . . - . -- - -.-. - - - . . -... -.. --.. --. - .- . . - . -.-. . - .. .- - . -- --.. --. . - .- - .. .- - . - - .-.. --.. --. - .- --. - .- -.-. - --- ``` One funny golfing trick in the third line (handling of space or dash): `C`oncatening a dot in front of the character turns the space into a null `.` , but the dash into a minus 1 (`.-`), so this value can simply be added to the total count. The `Output is simply the first character of the count, which happens to be a dot for negative numbers and a dash for positive numbers, so the output is the character with less occurrences. [Answer] # [Perl 5](https://www.perl.org/) `-pF`, 53 bytes ``` $p+=y/a-z/35344526512513031462452313/r-3for@F;$_=$p>0 ``` [Try it online!](https://tio.run/##DcexCoAgEADQn3EL0/M8lzCa3PqGCCoIIg9zqY/v6m2P13KQiOIm3mbWj0FC78kFAkeAFsEH9x8BTdG45TKkTk1RcW9FllzfzHXP5yV6pNaCFc3pAw "Perl 5 – Try It Online") [Answer] # [Factor](https://factorcode.org/), 66 bytes ``` : f ( s -- ? ) >morse [ [ 45 = ] count ] [ [ 46 = ] count ] bi < ; ``` [Try it online!](https://tio.run/##VYw9D4IwGIR3fsWFSQec1KH4MRiDJARJiJNhqPUlEoTi2zLw6ysRFnPDXZ7cXSmV1exueZxGApJZDgaGPj21igxq4pbeaKR9odFsCB2TtUPHVWsRenEqkGWnyAmUWMAgCHDEEoepfB@13mCPAkr346KY0PYPPSrsEDo/98eTlefXs1/OSXKds9JP@kX3BQ "Factor – Try It Online") [Answer] # C++ (compiled with Visual Studio 2017) 171bytes ``` int f(string i){const char*c="1322131421130102123023121211210120032121323101112232";int j=0,h[2]={0};while(j<sizeof(i)/28)*h+=c[i[j]-97],h[1]+=c[i[j++]-71];return*h>h[1];} ``` if we take the main program that exists for test purposes into account as well its more. this is the ungolfed "tidy" variant ``` #include "stdafx.h" int main() { const int dotCount[] = {1,3,2,2,1,3,1,4,2,1,1,3,0,1,0,2,1,2,3,0,2,3,1,2,1,2}; const int dashCount[] = {1,1,2,1,0,1,2,0,0,3,2,1,2,1,3,2,3,1,0,1,1,1,2,2,3,2}; std::cout << "Enter String:\n"; std::string input; std::cin >> input; int inputsHeavyness[2] = { 0 }; for(int i = 0;i < sizeof(input)/sizeof(std::string);i++) { inputsHeavyness[0] += dotCount[input[i] - 'a']; inputsHeavyness[1] += dashCount[input[i] - 'a']; } if (inputsHeavyness[0] > inputsHeavyness[1]) { std::cout << "Dot Heavy\n"; } else { std::cout << "Dash Heavy or Neutral\n"; } return 0; } ``` assumes all lowercase [Answer] **c (118 characters)** returns a positive value for over-dot-ness and negative value for over-dash-ness ``` int n(char* c){int v=25124858,d=3541434,i=0,o=0;for(;c[i]!=0;i++)o=(1&(v>(c[i]-65)))>0?(1&(d>>(c[i]-65)))>0?o+1:o-1:o;return o;} ``` un-golfed ``` int n(char* c) { // Bitwise alpha map: // more dots = 1 // more dashes or equal = 0 int d=3541434; // validation bit map. // dot/dash heavy = 1 // even = 0 int v=25124858; int i=0,o=0; for(;c[i]!=0;i++) // iterate through all values { // There is no way to make this pretty // I did my best. // If the little endian validation bit corresponding // to the capitol letter ascii value - 65 = 0, // the output does not increment or decrement. // If the value is one it increases or decreases based // on the value of the d bitmap. o=(1& ( v > (c[I] - 65))) > 0 ? (1 & (d >> (c[I] - 65))) > 0 ? o + 1 : o - 1 : o; } return o; } ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 22 bytes ``` {▄="Yⁿ∩┐↑rⁿ¼~<↔"$▒3-§+ ``` [Try it online!](https://tio.run/##y00syUjPz0n7/7/60bQWW6XIR437H3WsfDRlwqO2iUVAzqE9dTaP2qYoqTyaNslY99By7f//1YvVudSzgTgjNScnH0gn56ekqv8HAA "MathGolf – Try It Online") Uses the same method as many other answers, where `ⁿ∩┐↑rⁿ¼~<↔"` represents the magic number `35344527512513031462452313`. [Answer] # Python 2, ~~90~~ 86 bytes ``` import morse s=''.join(morse.string_to_morse(input())) print s.count('.')>s.count('-') ``` worked on my local with the [morse](https://pypi.org/project/morse/) library. -4 bytes. Thanks for the tip @JoKing! Also, it's 1 byte more if it's in Python 3. # Python 3, 87 bytes ``` import morse s=''.join(morse.string_to_morse(input())) print(s.count('.')>s.count('-')) ``` Though the question assumes the number of '.'s and '-'s will not be equal; in case they are equal, this code will return True. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 19 bytes ``` n»¨g±„ẇ⟇PNĖṡø»Ŀ3-∑± ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJuwrvCqGfCseKAnuG6h+Kfh1BOxJbhuaHDuMK7xL8zLeKIkcKxIiwiIiwiayJd) Saying the same joke but ~~louder~~ shorter is fun :p Ports 05AB1E ## Explained ``` n»¨g±„ẇ⟇PNĖṡø»Ŀ3-∑± n # Lowercase alphabet »¨g±„ẇ⟇PNĖṡø» # 35344527512513031462452313 Ŀ # transliterate 3- # - 3 ∑± # sign of sum ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 16.5 bytes (33 nibbles) ``` +.$-=$`D8 3 2954b0ccca54cb75c957 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWNxW09VR0bVUSXCwUjBWMLE1NkgySk5MTTU2Sk8xNky1NzSHqoMrXRivFKGWk5uTkxygpxUIFAQ) Approach based on [Emigna's O5AB1E answer](https://codegolf.stackexchange.com/a/181340/95126). Input is lowercase. Outputs the dot-dash sum: positive values are truthy in Nibbles, negative values (as well as zero) are falsy. To directly compare to the [Vyxal](https://codegolf.stackexchange.com/a/261553/95126), [Thunno](https://codegolf.stackexchange.com/a/261545/95126), [O5AB1E](https://codegolf.stackexchange.com/a/181340/95126) etc. answers, add 2 nibbles (+1 byte; prefix ``$`) to output the sign of the sum, although this isn't necessary here due to Nibbles' truthy/falsy convention. ``` `D 2954b0ccca54cb75c957 # interpret hex 2954b0ccca54cb75c957 8 # in base 8 # (digits: 51251303146245231335344527) .$ # now map over the input =$ # getting the digit at the modular index # of each input codepoint - 3 # subtract 3 from each + # and sum the result ``` [Answer] # C++, 76 bytes This assumes the input is in ASCII (or any encoding that's compatible for letters, e.g. UTF-8 or ISO-8859.1). Input may be in either case. ``` [](auto s,int&i){i=0;for(int c:s)i+="DDFDEEECHFBCFBDADBEGCEFCDBD"[c&31]-68;} ``` It's a function that accepts a string and and integer reference. The integer gets assigned a positive number (truthy) for dot-heavy input or a negative number (falsey) for dot-light input. Balanced input returns zero. The magic string encodes the weight of each of `A`..`Z`, offset by `D` (i.e. D represents a Morse-balanced letter). That's the `68` we subtract from each value. I did attempt encoding two Morse symbols per char in the magic string, but the cost of unpacking was too great. ### Test program: ``` auto f = [](auto s,int&i){i=0;for(int c:s)i+="DDFDEEECHFBCFBDADBEGCEFCDBD"[c&31]-68;}; #include <iostream> #include <string> int main(int argc, char **argv) { int i; while (*++argv) { std::string s{*argv}; f(s, i); std::cout << s << ": " << i << '\n'; } } ``` ### Output: ``` ./181318 S k HELLO code S: 3 k: -1 HELLO: 6 code: -1 ``` [Answer] # GNU [sed](https://www.gnu.org/software/sed/) `-E`, 112 bytes An approach could not differ more from the existing `sed` solution, but beating it by only one byte! This one builds a map from +4 dots to +3 dashes then two `s` commands taking turns in moving one of their side down until one of them has no moves left: ``` s/^/H S IFLV EDRU :_GKWT_JQYM_O!/ :1 s/((\S)\S* (.).*)\2/\1\3/ T- s/((.)_[^_]*([^_]).*!.*)\3/\1\2/ t1 c. q :- c- ``` [Try it online!](https://tio.run/##Hcq9DsIgFEDh/T4F3YAEbmg3Vov1N41SNUZahmqMS6uhvr4oLmc5X7hdxX14xxiwwwWxZDnfHIkp9weifbU@NX61O299nSFoBQEpdZY5ywmVTHLmcnTKFQiN@E/J/KXzLaepP5AlUySTI0wKegkv0AJ6EeOsLs1nfE6PcQhRmC8 "sed – Try It Online") [Answer] # [Scala 3](https://www.scala-lang.org/), 91 bytes A port of [@Level River St's Ruby answer](https://codegolf.stackexchange.com/a/181425/110802) in Scala. --- Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=lVDLSsNAFN33Ky5DS2bUBDWb0jIDVQNKU4oNbgxdjGkSE9JJmJlWSsiXuOlGN4L_079x0lRw64X74hzOPdz3TxXxgrtfIbJF-calQMvDonzJ40jDjGcC6h7AKk5gbRbMZapGMJGS78JAy0ykSzKCJ5FpoIZpqFteQDIC3KGUPQhNDPax0Yk9PISKsnrLJQh6OVZOGuubnY6Vk5Qy5tFrnVEmzinGKPRCf7VZpOvHYDZFDq-qYoezwZVLHF0aTcbMdn3mEjIY2i5pxqI5nfgGE36mNEYBugA0bcu95_vzdrid33mI_N6DGnKgrAfHqIxjXQisUD8Hm0G_TnBOGkSOeNM7NmxNLNAlWM_Wf2SM6-4jf_TaPLne77v-Aw) ``` s=>{var n=0;s.getBytes.foreach{i=>n+=(("[E[LduRgmQSMK".apply(i%13).toInt>>(i%2*3))%8-3)};n} ``` Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=lVHBTsJAEI1XvuJlg-muWqJyISQ0QSXRUEKUeLHhsJa2bANb011UQvgSL1z04h_xNW7bVeDoYXfm5b15uzPz8aVCPuPN74C4MnvjuSTjzedCx25re7TNntMo1BhwIbGqAZMoxtwAyvNEtdHNc74MRjoXMhmzNh6l0OiUSuCVzxAbRI2wkjB0PEsWdA5p6HOLVSOJ9NVSR6oRZ3nEwylWEKbC8pWhkJPo3VQJHOOieUCpqYi1pS5xgkM2nJr3OiBBL_Ani4dkfj8a9Akt_difUuLUfJgW4obO7qSG51XGzLi24KL5K17bKGsVKoMvlKZkRM5A-sV12_P9YZFcD296hO11lu46ezGz0TNJFamncD3UVzFN2ZqwfWfqdB3oDM6T8x8b04Wd_c6vOOtqxXbTGxt_AA) ``` object Main { def main(args: Array[String]): Unit = { val f = (s: String) => { var n = 0 s.getBytes.foreach { i => val index = i % 13 val shift = i % 2 * 3 val char = "[E[LduRgmQSMK"(index) n += ((char.toInt >> shift) % 8 - 3) } n } List("S", "K", "HELLO", "CODE").foreach { j => println(s"$j -> ${f(j)}") } ('A' to 'Z').foreach { j => println(s"$j -> ${f(j.toString)}") } } } ``` ]
[Question] [ **Let's count...** Count up to 2 and back to 1 Count up to 4 and back to 1 Count up to 6 and back to 1 ... ok you got it... put all these together and you'll get the following sequence ``` {1,2,1,2,3,4,3,2,1,2,3,4,5,6,5,4,3,2,1,2,3,4,5,6,7,8,7,6,5,4,3,2,1,2,3...} ``` **Challenge** Given an integer `n>0`for 1-indexed (or `n>=0` for 0-indexed), output the nth term of this sequence **Test cases** ``` Input->Output 1->1 68->6 668->20 6667->63 10000->84 ``` **Rules** your program must be able to compute solutions up to n=10000 in under a minute This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] # JavaScript (ES7), ~~59 ... 44~~ 43 bytes *Saved 1 byte thanks to Titus* Expected input: 1-indexed. ``` n=>(n-=(r=(~-n/2)**.5|0)*r*2)<++r*2?n:r*4-n ``` Initially inspired by a formula for [A004738](http://oeis.org/A004738), which is a similar sequence. But I ended up rewriting it entirely. ### Test cases ``` let f= n=>(n-=(r=(~-n/2)**.5|0)*r*2)<++r*2?n:r*4-n console.log(f(1)) // -> 1 console.log(f(68)) // -> 6 console.log(f(668)) // -> 20 console.log(f(6667)) // -> 63 console.log(f(10000)) // -> 84 ``` ### How? The sequence can be arranged as a triangle, with the left part in ascending order and the right part in descending order. Below are the first 4 rows, containing the first 32 terms: ``` 1 | 2 1 2 3 | 4 3 2 1 2 3 4 5 | 6 5 4 3 2 1 2 3 4 5 6 7 | 8 7 6 5 4 3 2 ``` Now, let's introduce some variables: ``` row | range | ascending part | descending part r | x to y | 1, 2, ..., i | 4(r+1)-(i+1), 4(r+1)-(i+2), ... ------+---------+-----------------------------+----------------------------------------- 0 | 1 - 2 | 1 | 4-2 1 | 3 - 8 | 1 2 3 | 8-4 8-5 8-6 2 | 9 - 18 | 1 2 3 4 5 | 12-6 12-7 12-8 12-9 12-10 3 | 19 - 32 | 1 2 3 4 5 6 7 | 16-8 16-9 16-10 16-11 16-12 16-13 16-14 ``` We start with 2 elements at the top and add 4 elements on each new row. Therefore, the number of elements on the 0-indexed row ***r*** can be expressed as: ``` a(r) = 4r + 2 ``` The 1-indexed starting position ***x*** of the row ***r*** is given by the sum of all preceding terms in this arithmetic series plus one, which leads to: ``` x(r) = r * (2 + a(r - 1)) / 2 + 1 = r * (2 + 4(r - 1) + 2) / 2 + 1 = 2r² + 1 ``` Reciprocally, given a 1-indexed position ***n*** in the sequence, the corresponding row can be found with: ``` r(n) = floor(sqrt((n - 1) / 2)) ``` or as JS code: ``` r = (~-n / 2) ** 0.5 | 0 ``` Once we know ***r(n)***, we subtract the starting position ***x(r)*** minus one from ***n***: ``` n -= r * r * 2 ``` We compare ***n*** with ***a(r) / 2 + 1 = 2r + 2*** to figure out whether we are in the ascending part or in the descending part: ``` n < ++r * 2 ? ``` If this expression is true, we return ***n***. Otherwise, we return ***4(r + 1) - n***. But since ***r*** was already incremented in the last statement, this is simplified as: ``` n : r * 4 - n ``` [Answer] # [Haskell](https://www.haskell.org/), 37 bytes ``` (!!)$do k<-[1,3..];[1..k]++[k+1,k..2] ``` [Try it online!](https://tio.run/##BcFBCoAgEADAr6zgodAWrWP1ksWDUJKsmlT/32au@PJZikjaB6VGfdzA20TeLohhJY/IwRhi4y0jzkFqzA126E9uH2iosUMCcojeuSA/ "Haskell – Try It Online") Zero-indexed. Generates the list and indexes into it. Thanks to Ørjan Johansen for saving 2 bytes! --- # [Haskell](https://www.haskell.org/), 38 bytes ``` (!!)[min(k-r)r|k<-[0,4..],r<-[1..k-2]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P81WQ1FRMzo3M08jW7dIs6gm20Y32kDHRE8vVqcIyDTU08vWNYqN/Z@bmJmnYKtQUJSZV6KgopCbWKCQphBtoKdnaGAQ@x8A "Haskell – Try It Online") Zero-indexed. Generates the list and indexes into it. --- # [Haskell](https://www.haskell.org/), 39 bytes ``` n%k|n<k=1+min(k-n)n|j<-k+4=(n-k)%j (%2) ``` [Try it online!](https://tio.run/##BcGxCoAgEADQva@4IUERRaNRvyQaHJL09JBq9N@v9@704tUaMwmcFDB63QtJNKRo1mBQ71GSQSXqkqMUm@KeCkGE8RT6YIWeBmQ4nLXeuZN/ "Haskell – Try It Online") Zero-indexed. A recursive method. [Answer] # [Python](https://docs.python.org/2/), 46 bytes ``` f=lambda n,k=2:-~min(n,k-n)*(n<k)or f(n-k,k+4) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIU8n29bISrcuNzNPA8jWzdPU0sizydbML1JI08jTzdbJ1jbR/M@VBuTnKWTmKUQbGgBBrIK2QlFiXnqqBpCraVVQlJlXAjRKQSmmREkHpFHzPwA "Python 2 – Try It Online") Zero indexed. [Answer] ## [Husk](https://github.com/barbuz/Husk), 8 bytes ``` !…ṁoe1DN ``` 1-indexed. [Try it online!](https://tio.run/##yygtzv7/X/FRw7KHOxvzUw1d/P7//29oAAQA "Husk – Try It Online") ## Explanation ``` !…ṁoe1DN Implicit input (an integer). N Positive integers: [1,2,3,4,... ṁo Map and concatenate D double: [2,4,6,8,... e1 then pair with 1: [1,2,1,4,1,6,1,8,... … Fill gaps with ranges: [1,2,1,2,3,4,3,2,1,2,3,4,5,6,... ! Index with input. ``` [Answer] # [Perl 6](https://perl6.org), 29 bytes ``` {({|(1...$+=2...2)}...*)[$_]} ``` [Try it online](https://tio.run/##ZZFhT8IwEIa/91e8RLSrloVtMEiWyWd/gyKpW5HFseJaMAT57bNdgIk2uV7z3HvX63Uj6zJutlpiF/tZQtZ73GUql0ibg3f49gLf9/sPaWhdyI52v2fP/cX82GixB10WtTaIxqAcbdZrNE5IG6In/6RRGJiVhBZrCaHbc7YSZSmrdzk7p3o2lUF@7uAFPOTOIj6y1p3HPLb2n0341NqfGMPM1t5LTdHrgVaKdo0RvX1DXuhNaYGH/gIMBwK4uL9cG4/eTnIMEFDGQZGmj5curdZyRo6EnAsEcCvBDYILi6dnFneshY6Fw18wnpyEEXHTf9FG1GZgCjusFJX6SrqLhnY56XTUKmWVX@mu5u6GrtSHa/yiG6Ar7h6mZaaqXGOpavsrwqAU9jtVJWnzAw "Perl 6 – Try It Online") 0-based ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 ( # generate an outer sequence { # bare block lambda |( # flatten into outer sequence # generate an inner sequence 1 # start at 1 ... # go (upward) towards: $ # an anonymous state variable (new one for each outer sequence) += 2 # increment by 2 ... # go (downward) towards: 2 # stop at 2 (1 will come from the next inner sequence) ) } ... # keep generating the outer sequence until: * # never stop )[ $_ ] # index into outer sequence } ``` The inner sequence `1...$+=2...2` produces ``` (1, 2).Seq (1, 2, 3, 4, 3, 2).Seq (1, 2, 3, 4, 5, 6, 5, 4, 3, 2).Seq (1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2).Seq (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2).Seq ... ``` To get it to be 1-based, add `0,` before the second `{`, or add `-1` after `$_` [Answer] # R, 64 bytes ``` function(n)unlist(sapply(seq(2,n,2),function(x)c(2:x-1,x:2)))[n] ``` Function that takes an argument `n`. It creates a vector `2:n` with increments of 2. For each of these, the vector `1:(x-1)` and `x:2` is created. This in total will be longer than `n`. We `unlist` it, to get a vector and take the `n`-th entry. [Answer] # [Python 2](https://docs.python.org/2/), 56 bytes ``` def f(x):n=int((x/2)**.5);print 2*n-abs(2*n*n+2*n+1-x)+2 ``` [Try it online!](https://tio.run/##JYw7DoAgEAV7TrGx2gU/SGKj8SY2GkWlWA1S4OmRxOZNMsm8@w3HxSaldbNgMVLP48kBMTaGpKw7Gm6fBRjJ1bw8mClZ5VVtFUmZZC8PDk4GP/O@Yas19QL@yJVQTKEoRb52lD4 "Python 2 – Try It Online") This is 0-indexed. *-1 byte thanks to @JustinMariner* **How this Works** We note that the 1-indexed `n`-th group (`1, 2, ... 2n ..., 2, 1`) occurs from elements numbered 0-indexed `2(n-1)^2` to `2n^2`. To find the element at index `x`, we can find the group number `n` that `x` is in. From that, we calculate the distance from the center of the group that `x` is. (This distance is `abs(2*n**2+2*n+2-x)`). However, since the elements *decrease* further away from the center of a group, we subtract the distance from the maximum value of the group. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ### Code: ``` ÅÈ€1Ÿ¦¹è ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//cOvhjkdNawyP7ji07NDOwyv@/7cEgv@6JQA "05AB1E – Try It Online") ### Explanation: ``` ÅÈ # Get all even numbers until input (0, 2, ..., input) €1 # Insert 1 after each element Ÿ # Inclusive range (e.g. [1, 4, 1] -> [1, 2, 3, 4, 3, 2, 1]) ¦ # Remove the first element ¹è # Retrieve the element at the input index ``` [Answer] # JavaScript, 39 bytes ``` f=(n,t=2)=>n>t?f(n-t,t+4):n>t/2?t-n+2:n ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~, 9 bytes ``` ḤŒḄṖµ€Fị@ ``` [Try it online!](https://tio.run/##ASEA3v9qZWxsef//4bikxZLhuIThuZbCteKCrEbhu4tA////Njg "Jelly – Try It Online") Also 1 indexed, and finishes pretty fast. One byte saved thanks to @ErikTheOutgolfer! Explanation: Hypothetically, let's say the input (`a`) is 3. ``` µ€ # (Implicit) On each number in range(a): # Ḥ # Double # [2, 4, 6] # ŒḄ # Convert to a range, and Bounce # [[1, 2, 1], [1, 2, 3, 4, 3, 2, 1], [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]] # Ṗ # Pop # [[1, 2], [1, 2, 3, 4, 3, 2], [1, 2, 3, 4, 5, 6, 5, 4, 3, 2]] # F # Flatten # [1, 2, 1, 2, 3, 4, 3, 2, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2] # ị@ # Grab the item[a] # 1 # ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 15 bytes ``` li:"@EZv4L)]vG) ``` 1-based. [**Try it online!**](https://tio.run/##y00syfn/PyfTSsnBNarMxEcztsxd8/9/MzMLAA "MATL – Try It Online") This times out for the largest test cases in TIO, but finishes in time on my desktop computer (compiler running on MATLAB R2017a). To display elapsed time, add `Z`` at the end of the code. ``` >> matl 'li:"@EZv4L)]vG)Z`' > 10000 84 15.8235379852476 ``` ### Explanation The code generates many more terms than necessary. Specifically, it computes `n` "pieces" of the sequence, where each piece is a count up and back to 1. ``` l % Push 1 i % Push input, n : % Range [1 2 ...n] " % For each k in that range @E % Push 2*k Zv % Symmetric range: [1 2 ... 2*k-1 2*k 2*k-1 ... 2 1] 4L) % Remove last entry: [1 2 ... 2*k-1 2*k 2*k-1 ... 2] ] % End v % Concatenate all stack contents into a column vector G) % Get n-th entry. Implicitly display ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~12~~ 10 bytes ``` !ṁ§¤+hḣṫİ0 ``` [Try it online!](https://tio.run/##yygtzv7/X/HhzsZDyw8t0c54uGPxw52rj2ww@P//v6EBEAAA "Husk – Try It Online") 1-indexed, works quite fast ### Explanation ``` !ṁ§¤+hḣṫİ0 ṁ İ0 Map the following function over the even numbers and concatenate the results together § ḣṫ Get the ranges 1-n and n-1, then... ¤+h remove the last element from both of them and concatenate them together ! Return the element of the resulting list at the given index ``` [Answer] # Mathematica, 90 bytes ``` Flatten[{1}~Join~Table[Join[Rest[p=Range@i],Reverse@Most@p],{i,2,Round[2Sqrt@#],2}]][[#]]& ``` [Try it online!](https://tio.run/##FcaxCsIwEADQXxEKTjfY7IWbHARBottxQ9SrHtSkTU6X0v561De9V7Cn3krtu7ofgplEmttlPSSN6yVcB6F/yUsxGjsf4kNQGbx8JBfBYyqGI8Os4MCnd7yTO0/ZsGFwCzNRw7ytp6zRNthTu/vhWr8 "Mathics – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), 62 bytes ``` .+ $* ^((^.|\2..)*)\1. 6$*1$2$2;1 (?=.+;(.+))\1(.+).*;\2.* $.2 ``` [Try it online!](https://tio.run/##HYoxCoAwEAT7e8cJlwssXoooBLH0EyFoYWFjIZb@PUYXhilmr/0@zq12sqwVnlipiBQ8OQBOXTZQZDUOHJKRzBN8EnjXyidoak8lRqjVKI4Uf@JA1re9 "Retina – Try It Online") Link includes test cases. Input is 1-indexed. The first stage is just decimal to unary conversion. The second stage finds the highest square number `s` strictly less than half of `n`; `$1` is `s²`, while `$2` is `2s-1`. It calculates two values, first the number of numbers in the current up/down run, which is `4(s+1) = 4s+4 = 2$2+6`, and secondly the position within that run, which is `n-2s² = n-(2$1+1)+1 = n-$&+1`, which just requires a `1` to make up for the `1` used to enforce the strict inequality. The final stage then counts from that position to both the start and end of the run and takes the lower result and converts it to decimal. [Answer] # Mathematica, 67 bytes ``` (t=z=1;While[(x=3-4t+2t^2)<#,t++;z=x];If[#-z>2t-2,4t-5+z-#,#-z+1])& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvtfo8S2ytbQOjwjMyc1WqPC1ljXpETbqCTOSNNGWadEW9u6yrYi1tozLVpZt8rOqETXSMekRNdUu0pXWQcoom0Yq6n2P6AoM69EwSEt2tAACGL//wcA "Mathics – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 43 + 1 (-p) = 44 bytes ``` $_=($n=2*int sqrt$_/2)+2-abs$n/2*$n+$n+1-$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lZDJc/WSCszr0ShuLCoRCVe30hT20g3MalYJU/fSEslTxuIDHVV4v//twSCf/kFJZn5ecX/dX1N9QwMDf7rFgAA "Perl 5 – Try It Online") I was working on a formula to calculate the n-th element directly. Then I saw that @fireflame241 had done that work, and I golfed it into Perl. ~~# [Perl 5](https://www.perl.org/), 50 + 1 (-n) = 51 bytes~~ ``` push@r,1..++$",reverse 2..++$"while@r<$_;say$r[$_] ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gtDjDoUjHUE9PW1tFSacotSy1qDhVwQjCL8/IzEl1KLJRibcuTqxUKYpWiY/9/98SCP7lF5Rk5ucV/9f1NdUzMDT4r5sHAA "Perl 5 – Try It Online") Results are 0 indexed. [Answer] # [Haskell](https://www.haskell.org/), ~~115~~ 81 bytes ``` y%x=snd(span(<x)$scanl(+)y[y+1,y+3..])!!0 g 1=1 g x|1%x>2%x=1+g(x-1)|1>0=g(x-1)-1 ``` [Try it online!](https://tio.run/##JcuxCsMgFEDRvV@RQAI@bMSXrjVTx/xByPBoi5WqleigkH83gS6Xs9wPxe/b2mpc@G2peVAiMZuYaumziv7FYiDP7hm6@CRvGYeyFI7Xwm9CrNC28qIbVHg279jnaTw/5JrlAWHHSao/B6yOjFdhMz51jgLTsKAQo1zrAQ "Haskell – Try It Online") There is some magic going on here. Could probably be shorter if I used a normal approach though. ## Explanation First we define `%`. `%` is a function that takes two variables `x`, and `y`. It constructs a list `scanl(+)y[y+1,y+3..]` and finds the first element of that list greater than `x`. `scanl(+)` just performs iterative sums, to get the triangular numbers we would do `scanl(+)0[1..]`, to get the square numbers we would do `scanl(+)0[1,3..]`. The two lists in particular we will be constructing are `scanl(+)2[3,5..]` and `scanl(+)1[2,4..]` these are the inflection points of the pattern. Now we define the main function `g` which takes an `x`. If `x` is one we return `1` because that's the first value. Otherwise we check the next two inflection points, if the down inflection is larger `1%x>2x` we return the successor of `g$x-1` otherwise we return the predecessor of `g$x-1`. ## Ok but why does that work? First of all "Whats with the way we find vertices?". Its important to note the distance between consecutive vertices of the same type. You will notice that the differences are growing by 2 each time. This makes sense because the triangles bases become wider by 2 each time. We can make a list constant difference using a list literal like so `[2,4..]` and we use `scanl(+)` to to turn these lists into our vertex lists, based on the location of the first vertex and the first difference. So now that we have a way of finding upward and downward vertices we can use that information to get the values. We say that the first value is `1` otherwise we have to take either the successor or the predecessor. If the next vertex is a upward one we want to take the predecessor, otherwise we take the successor. # [Haskell](https://www.haskell.org/), ~~56~~ ~~51~~ 46 bytes Here's my better solution with less math and fewer bytes. ``` d x|e<-[1..x-1]=e++map(x+1-)e (([1..]>>=d)!!0) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P0WhoibVRjfaUE@vQtcw1jZVWzs3sUCjQttQVzOVK90WJBFrZ2eb8j83MTPPtqAoM69EBaQiXVFRM9pAT8/QIPY/AA "Haskell – Try It Online") [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 14 bytes ``` SF}SDtO_+)sQt@ ``` [Try it here!](http://pyke.catbus.co.uk/?code=SF%7DSDtO_%2B%29sQt%40&input=10) ``` S - range(1, input) F}SDtO_+) - for i in ^: } - ^ * 2 S - range(1, ^) + - ^ + v tO_ - ^[1:-1:-1] s - sum(^) Qt@ - ^[input-1] ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 120 bytes Explanation: pretty simple, the first nested loop climbs up to our max, the second climbs back down to 2. The repeat for each multiple of 2. ``` x=>{var a=0;for(int i=2,j=0;j<x;i+=2){for(var b=1;b<=i&j<x;b++,j++){a=b;}for(var c=i-1;c>1&j<x;c--,j++){a=c;}}return a;} ``` [Try it online!](https://tio.run/##hc49a8MwEAbguf4VIpRiY6tEGZyALC2BTu3UoUPpIKtyOJNKQZJDitBvd2W33kpycHAfz/BKh6Wxahwc6AN6/XZefdFMHoVz6BQy54UHiZ4GLRvQvkrNOzZeGA9nYZFga9oZm6czArap@rT3zYVCyTZFmD6TahmhbcPgYXq1ZVn1ZVkEwVoaFyIZYEIlJ7ORGC9G0hit8oPVSNA40iXR2cAnehGgc@dtiv7@gYQ9uCJkd3ujnTmqxzcLXj2DVvn9iiDMUehyUsRVQf839Q7zROrdNbOgG6re/rF6e8WRdaoZztOvjFkcfwA "C# (.NET Core) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~78~~ 75 bytes *Saved 1 byte thanks to Step Hen* *Saved 1 byte thanks to Mr. Xcoder* ``` ->n{a=0;b=2;c=1;n.times{if a==b then c=0;b+=2;end;c=1if a<2;a+=c<1?-1:1};a} ``` [Try it online!](https://tio.run/##XY5BDoMgFET3nuLv0FiJuCzSHsV8KU1tAE3BRYOcnWLThelu8uZlMq91fKek0YCA5mIDipaPouNSMG6pn4xyYboDCjGCfygLchfqbCh726297DuOtZA9uzbszCLHmLxyfphXv6w@L5NAiiPpeygZpaxtK@rnAanBBQJsSiujrN8gH6IStS5/5Ks5iPQ5T7YkJyDV/yCJpMjRwYGnDw "Ruby – Try It Online") Hopefully I can get some tips for pulling the bytecount down more. I tried to take a simple approach. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 53 bytes ``` n->{int i=2;for(;n>i;i+=4)n-=i;return n>i/2?i-n+2:n;} ``` [Try it online!](https://tio.run/##jVFtS8MwEP7c/Ip8TFkbWZ0vLHYyREFwfpmKICKxTbvM9lLSdDrGfntNuzqHUxBy5O655567S@Z8wX1VCJjHb7XMC6UNnluMVkZmdKw1X5YM7SWSCiIjFdCrzvmFUxoteE6vwUxbjyFUVK@ZjHCU8bLEEy4BrZDTgaXhxl4LJWOc2xSxVRLSp2fMdVq6yLFUxx4JxmIRDjGId7yJVn0v8Bo79AbWvv0j79jaPnbinVrb5tbMCk@XpRE5VZWhhe1sMiCb/alRm1nIdheqOaTiIlOliEnfwxHNBKRm5tKcF6TZbDhMJMS3ZnYndO5aiVaLuK77z17Rn8wd4WYikQpNJ@PHl4fxzf1lW7VGzs93taV4t7CJ4aN71q9fPOvkPNw5I5zgsAZ/tGr4MgxYojRhMJJM9sKBC34omRam0oAteBCcSx96wRDYum6m71IJ5UWRLYlt2E63RvUn "Java (OpenJDK 8) – Try It Online") *-2 bytes thanks to Nevay.* 1-indexed. **TL;DR** We split the sequence into convenient chunks, find the chunk `n` is in, then find the `nth` position in the chunk. Here, we can split the sequence like `[[1,2],[1,2,3,4,3,2],[1,2,3,4,5,6,5,4,3,2],...]`, which gives us chunk sizes of `4i-2`. Starting with `i=2`, we subtract `i` from `n`, essentially moving upwards a chunk at a time. Once we satisfy `n<=i`, we know `n` is now the position of the correct value in the current chunk. We then get the value by comparing `n` to `i`, the size of the chunk. The midpoint of each chunk is equal to `i/2+1`; if `n` is less than this, we simply return `n`. If `n` is greater, we return `i-n+2`. # Example ``` n = 16, i = 2 Is n > i? Yes, n = n - 2 = 14, i = i + 4 = 6 Is n > i? Yes, n = n - 6 = 8, i = i + 4 = 10 Is n > i? No, stop looping. 10 / 2 + 1 = 6 Is n > 6? Yes, return i - n + 2 = 8 - 6 + 2 = 4 ``` [Answer] # [Python 2](https://docs.python.org/2/), 5! bytes (120 bytes :P) ``` r=range a=[] for i in r(2,998,2): for j in r(1,i+1): a.append(j) for j in r(i-1,1,-1): a.append(j) print a[input()-1] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8i2KDEvPZUr0TY6listv0ghUyEzT6FIw0jH0tJCx0jTSoGLEyScBRE21MnUNgQKJuolFhSk5qVoZGmiyGfqGuoY6uiiKykoyswrUUiMzswrKC3R0NQ1jP3/HwA "Python 2 – Try It Online") Straightforward, makes the list and then takes input'th element [Answer] # [Python 3](https://docs.python.org/3/), 184 156 bytes ``` l,n,r=list,next,range h=lambda x:l(r(1,x))+l(r(x-2,1,-1)) def g(): x=3 while True:yield from h(x);x+=2 def f(i): x=g() for _ in r(i-1):n(x) return n(x) ``` [Try it online!](https://tio.run/##JY7dCsIwDIWv16fInQ1GWRVUJvUpvJfJOlfoOokVK2PPPlsXyB985yTPb@gGv59nR55YO/sK5E0MxLV/GNFpV/f3poZYOclSUURc5yludqRooxBFY1p4SKxEEfVeFJ/OOgNXfpvqa41roOWhh05GPMe13v3xVtqFTzpRtAPDDawHljY5Vj6xomAT3uwhL3MmgnmFDKUn4HBKuZTDkUCVKSg7Ptn6IFdjOYG@wKim1TZp@zrILKd0OHdEnH8 "Python 3 – Try It Online") golfed with Python generator for "lazy" evaluation [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 47 bytes ``` g=q{p=p+1~p=:|_Xg\g=g+q~g=1or g>=r|r=r+1┘q=q*-1 ``` ## Explanation ``` g=q var g is the current value of the sequence; set to 1 at the start { DO infinitely p=p+1 raise the step counter (var p) ~p=:|_Xg IF p equals the input term a (read from cmd line) THEN QUIT, printing g \ ELSE g=g+q raise (or decrement) g by q (q is 1 at the start of QBIC) ~g=1 IF g is at the lower bound of a subsequence or g>=r OR g is at the upper bound (r start as 2 in QBIC) |r=r+1 THEN increment r (this happens once on lower bound, and once on upper, total of 2 raise per subsequence) ┘q=q*-1 and switch q from 1 to -1 ``` [Answer] # [Röda](https://github.com/fergusq/roda), 54 bytes ``` f n{seq 1,n|{|i|seq 1,2*i;seq 2*i-1,2}_|head n+2|tail} ``` [Try it online!](https://tio.run/##JYjBCsIwGIPP3VPk4KHTCXaHKYhPIrIV2rIftJ1dPci6Z6@/LJDkS2IwuhQHv8z2DdX4vGTKG7d7uv6J@8hr7fNotYE/tDlpeq7lpcljqYQLEQTmu2rQXdhbdOcG6sR6wIRKiOkzj3LYEW4Yat4pfuEk1ciYIvkke35N8LZayw8 "Röda – Try It Online") Call with: `try f(n)` This function returns quickly the answer, but *after* that does some unnecessary calculations and eventually runs out of memory. As the function does return the actual answer shortly after it is called (clearly under a minute), I think this answer is valid. (In Röda functions can return values before they exit due to parallelism.) [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform),99 95 86 bytes ``` n=>{int i=1,t=2,d=0;for(;n>1;){i+=1-2*d;if(i==t){d++;t+=2;}if(i==1)d--;n--;}return i;} ``` [Try it online!](https://tio.run/##fcoxSwQxEAXg2vyKlIm7K5ctzoMx2xxYaWVhIRZLklsGzgmXzAoS8tvXiK3nwIPH@8blwcUUtjUjLfLlK3P4AOHOc87yUkTmmdHJz4hePs9IKnNqj2/vck5L1kU8ruQekLhvmRa7kZ1KqxKt6dmOvbc7OMWkgCYDumBnzTDeesCTQmtZF991wJ0dof5ORvthAGqpKfCaSCLUDYS4OUbK8RzuXhNyeEIKalFGa/hb9ofr9K/t76@i2bX70Srq9g0 "C# (.NET Core) – Try It Online") Lambda function that takes and returns an integer. Single loop that handles counting up and down. [Answer] # PHP, 65+1 bytes ``` for($x=$d=$z=1;--$argn;)$d=($x+=$d)>1?$x>$z?-1:$d:!!$z+=2;echo$x; ``` Run as pipe with `-R` or [try it online](http://sandbox.onlinephpfunctions.com/code/778690bea522f241f2e93c5c31c4c758c55d48e3) (or uncomment one of the other versions). A port of [tsh´s recursive JavaScript](https://codegolf.stackexchange.com/a/140160/55735) takes 66 bytes: ``` function f($n,$t=2){return$t<2*$n?$t<$n?f($n-$t,$t+4):$t-$n+2:$n;} ``` A port of [Arnauld´s solution](https://codegolf.stackexchange.com/a/140133/55735) takes 62+1: ``` $n=$argn;echo($n-=($r=(~-$n/2)**.5|0)*$r*2)<++$r*2?$n:$r*4-$n; ``` A golfed port of [Xanderhall´s Java](https://codegolf.stackexchange.com/a/140193/55735) has the shortest code so far (55+1 bytes): ``` for($n=$argn;$n+2>$i+=4;)$n-=$i-2;echo$n*2>$i?$i-$n:$n; ``` [Answer] # [Pyth](https://pyth.readthedocs.io), ~~19~~ 18 bytes ``` -yhKs@/Q2 2a*yKhKt ``` **[Try it here!](https://pyth.herokuapp.com/?code=-yhKs%40%2FQ2+2a%2ayKhKt&test_suite=1&test_suite_input=0%0A67%0A667%0A6666%0A9999&debug=0)** ]
[Question] [ # The Art of Word Shaping Given a binary matrix and a string of letters, replace all 1's in the matrix, moving from top to bottom and from left to right within each row, with the letters of the string. Once the letters have been formed into the shape of the matrix, print the matrix, replacing 0's with spaces. It's probably easier to just give an example or two. --- Case: *Base case...* **Input One:** ``` [0,0,1,0,0] [0,1,0,1,0] [1,0,0,0,1] [0,1,0,1,0] [0,0,1,0,0] "PPCGPPCG" ``` **Output One:** ``` P P C G P P C G ``` --- Case: *If the input string is longer than the number of ones...* **Input Two:** ``` [1,0,0] [0,1,0] [1,0,1] lambda ``` **Output Two:** ``` l a m b ``` --- Case: *If the input string is shorter than the number of ones...* **Input Three:** ``` [1,1,1] [1,0,1] [1,1,1] PPCG ``` **Output Three:** ``` PPC G P PCG ``` --- # Available Assumptions * You may assume the input string is never empty. * You may assume the matrix will never be empty. * You may not assume that the binary matrix will never be all zeros. # Rules * If the string is shorter than the number of ones, repeat the string; all ones must be replaced. * If the string is longer than the number of ones, only use what is needed. * You may use True/False in place of integers/bits for the input. * Trailing spaces ARE REQUIRED, all zeros must be **replaced** with spaces. * A single trailing newline is acceptable. * This is code-golf, lowest byte count wins. [Answer] # Vim, ~~44~~ 42 bytes ``` qqy$P0xjf1"_xP{@qq@q:s/0/ /g^M:s/,/^V^M/g^M{D ``` Saved 2 bytes thanks to [@DjMcMoylex](https://codegolf.stackexchange.com/users/31716/drmcmoylex)! Here, the `^M` is a literal newline, and the `^V` is `CTRL-V` Takes the input in this format: ``` PPCG 00100,01010,10001,01010,00100 ``` **Disclaimer:** If the string is longer than ~40 chars long, your computer might run out of ram. Explanation: ``` qq @qq@q # Start recording a recursive macro. y$P0x # Duplicate the string and cut out the first character jf1"_xP{ # Find the first 1, and replace it with the cut character from the string. # Now we have replaced all the 1's with their respective character, but we still have the array in the original format, and we have the string massivly duplicated at the first line, so we need to clean it up: :s/0/ /g^M # Replace all 0's with a space :s/,/^V^M/g^M # Replace all ,'s with a newline. The ^V acts like a backslash, it escapes the newline so that the command isn't run too soon {D # Delete the first line ``` Here's a gif of me "running" the "program": [![Me typing the keys](https://i.stack.imgur.com/8qBz7.gif)](https://i.stack.imgur.com/8qBz7.gif) [Answer] ## [Retina](http://github.com/mbuettner/retina), ~~41~~ 33 bytes ``` 0 +1`(.)(.*)(\D+)1 $2$1$3$1 A1` ``` [Try it online!](http://retina.tryitonline.net/#code=MAogCisxYCguKSguKikoXEQrKTEKJDIkMSQzJDEKQTFg&input=UFBDRwowMDEwMAowMTAxMAoxMDAwMQowMTAxMAowMDEwMA) The input string is given on the first row of the input, followed by the matrix. Since Retina has no concept of lists (or really anything except strings), there are no separators in the binary matrix except for linefeeds to separate rows. ### Explanation ``` 0 ``` Turns zeros into spaces. ``` +1`(.)(.*)(\D+)1 $2$1$3$1 ``` Repeatedly replace the first `1` with the first character of the input string while also rotating that character to the end of the input string. This takes care cases where there are more `1`s than characters in the input string. ``` A1` ``` Discard the first line, i.e. the input string. [Answer] # JavaScript ES6, ~~67~~ ~~53~~ ~~50~~ 49 bytes Saved 3 bytes thanks to @ETHproductions Saved 1 more thanks to @Neil ``` (a,b,i)=>a.replace(/./g,c=>+c?b[++i]||b[i=0]:' ') ``` ``` f= (a,b,i)=>a.replace(/./g,c=>+c?b[++i]||b[i=0]:' ') G=_=>h.innerHTML = f(`00100 01010 10001 01010 00100`,z.value) h.innerHTML = G() ``` ``` <input id=z oninput="G()" value="PPCG"></input> <pre id=h> ``` Old code before I knew that string matrices are a valid input format: ``` (a,b)=>a.map(c=>c.map(d=>d?b[i++%b.length]:' ').join``,i=0).join` ` ``` ``` f= (a,b)=>a.map(c=>c.map(d=>d?b[i++%b.length]:' ').join``,i=0).join` ` G=_=>h.innerHTML = f([[0,0,1,0,0],[0,1,0,1,0],[1,0,0,0,1],[0,1,0,1,0],[0,0,1,0,0]],z.value) h.innerHTML = G() ``` ``` <input id=z oninput="G()" value="PPCG"></input> <pre id=h> ``` [Answer] ## Perl, 40 bytes 36 bytes of code + `-i -p` flags. ``` @F=$^I=~/./g;s/1/$F[$i++%@F]/g;y;0; ``` (note the final space and the lack of final newline). To run it, write the input string after `-i` flag, and supply the matrix in the input : ``` perl -iPPCGPPCG -pe '@F=$^I=~/./g;s/1/$F[$i++%@F]/g;y;0; ' <<< "00100 01010 10001 01010 00100" ``` If your Perl is a bit old, you might need to add a final semicolon (after the space). [Answer] # Python 2, ~~114~~ 71 bytes Turns out I was re-inventing the wheel, a simple double replace on a multiline string works quite well. The string has the additional benefit of being able to count zeros directly rather than having to do the really ugly `s*len(L)*len(L[0])` for a nested list ``` lambda S,s:S.replace("0"," ").replace("1","{}").format(*s*S.count('0')) ``` Old solution: ``` lambda s,L:"\n".join(["".join(map(lambda n:chr(n+32),l)).replace("!","{}")for l in L]).format(*s*len(L)*len(L[0])) ``` First we convert everything + 32 with `chr` (all zeros become spaces), then we replace all of the `!` with `{}` to allow using the `format` function. ~~If `NULL` can be counted as a space~~ If I decide to cheat and use `NULL` instead of space, I can skip the addition of 32 to save 12 bytes. (`print` displays `'\x00'` as a space) ``` lambda s,L:"\n".join(["".join(map(chr,l)).replace('\x01','{}')for l in L]).format(*s*len(L)*len(L[0])) ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 11 bytes ``` yz:)1Gg!(c! ``` Inputs are a numeric matrix (with `;` as row separator) and a string. [**Try it online!**](http://matl.tryitonline.net/#code=eXo6KTFHZyEoYyE&input=WzAsMCwxLDAsMDsgMCwxLDAsMSwwOyAxLDAsMCwwLDE7IDAsMSwwLDEsMDsgMCwwLDEsMCwwXQonUFBDR1BQQ0cn) Or verify test cases: [**1**](http://matl.tryitonline.net/#code=eXo6KTFHZyEoYyE&input=WzAsMCwxLDAsMDsgMCwxLDAsMSwwOyAxLDAsMCwwLDE7IDAsMSwwLDEsMDsgMCwwLDEsMCwwXQonUFBDR1BQQ0cn), [**2**](http://matl.tryitonline.net/#code=eXo6KTFHZyEoYyE&input=WzEsMCwwOyAwLDEsMDsgMSwwLDFdCidsYW1iZGEnCgo), [**3**](http://matl.tryitonline.net/#code=eXo6KTFHZyEoYyE&input=WzEsMSwxOyAxLDAsMTsgMSwxLDFdCidQUENHJwoK). ``` y % Take the two inputs implicitly. Duplicate the first % STACK: [1,0,0; 0,1,0; 1,0,1], 'lambda', [1,0,0; 0,1,0; 1,0,1] z % Number of nonzeros % STACK: [1,0,0; 0,1,0; 1,0,1], 'lambda', 4 : % Range % STACK: [1,0,0; 0,1,0; 1,0,1], 'lambda', [1 2 3 4] ) % Reference indexing (select values) % STACK: [1,0,0; 0,1,0; 1,0,1], 'lamb' 1Gg % Push first input as a logical matrix; will be used as index % STACK: [1,0,0; 0,1,0; 1,0,1], 'lamb', [1,0,0; 0,1,0; 1,0,1] ! % Transpose. This is necessary because MATL uses column-major order % (down, then accross) ( % Assignment indexing (fill with values). Since the original matrix % is numeric, the new values are introduced as their ASCII codes % STACK: [108, 0, 109; 0, 97, 0; 1, 0, 98] c % Convert to char % STACK: ['l m'; ' a '; ' b'] ! % Transpose back. Implicitly display % STACK: ['l '; ' a '; 'm b'] ``` [Answer] # APL, 18 bytes ``` {(⍴⍺)⍴X\⍵⍴⍨+/X←,⍺} ``` This is a function that takes a boolean matrix as its left argument and a string as its right argument. ``` (↑(1 0 0)(0 1 0)(1 0 1)) {(⍴⍺)⍴X\⍵⍴⍨+/X←,⍺}'lambda' l a m b ``` Explanation: APL has a built-in that does something like this, `\` (expand). However, it only works on vectors, and it requires each character to be actually used. * `X←,⍺`: flatten the matrix and store the result in X. * `⍵⍴⍨+/X`: reshape the character vector so that it has the required amount of elements (this also takes care of lengthening the string by repeating characters if necessary). * `X\`: take one of the characters for each `1` and a space for each `0` in `X`. * `(⍴⍺)⍴`: reshape the result so that it has the shape of the original matrix. [Answer] # PHP, ~~110~~ ~~91~~ ~~97~~ ~~88~~ ~~82~~ ~~81~~ ~~80~~ 75 bytes saved 6 bytes thanks to @user59178 ``` while(""<$c=$argv[1][$i++])echo$c<1?$c?:" ":($s=$argv[2])[$k++%strlen($s)]; ``` Run with `-r`. Expects matrix as multiline string in first argument, string in second argument. [Answer] ## PowerShell v2+, 70 bytes ``` param($a,$b)$b|%{-join($_|%{if($_){$a[$n++];$n%=$a.length}else{' '}})} ``` Takes input word as `$a` and the matrix as an array-of-arrays as `$b` (see examples below). Loops through `$b`, then loops through the elements of each row `$_|%{...}`. Inner loop is an `if`/`else` condition, where we either output `$a[$n++]` and take mod-equal to the length of the string, or output a space `' '`. Those are `-join`ed together back into a string. Each of the strings is left on the pipeline, and implicit output with newlines between happens via `Write-Output` at program completion. ``` PS C:\Tools\Scripts\golfing> .\the-art-of-word-shaping.ps1 'PPCGPPCG' @(@(0,0,1,0,0),@(0,1,0,1,0),@(1,0,0,0,1),@(0,1,0,1,0),@(0,0,1,0,0)) P P C G P P C G PS C:\Tools\Scripts\golfing> .\the-art-of-word-shaping.ps1 'lambda' @(@(1,0,0),@(0,1,0),@(1,0,1)) l a m b PS C:\Tools\Scripts\golfing> .\the-art-of-word-shaping.ps1 'PPCG' @(@(1,1,1),@(1,0,1),@(1,1,1)) PPC G P PCG ``` [Answer] ## Python 3, 104 (or 83) Bytes ``` import itertools as i def f(s,L):s=i.cycle(s);return'\n'.join(' '.join(next(s)*e for e in l)for l in L) ``` There is shorter option (83 Bytes), but it will fail if string is more than 999 times shorter than needed: ``` def f(s,L):s=list(s)*999;return'\n'.join(' '.join(s.pop(0)*e for e in l)for l in L) ``` [Answer] # Groovy, 63 ``` {a,b->i=0;a.replaceAll("1",{b[i++%b.size()]}).replace("0"," ")} ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~10~~ 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) +1 byte to work around a weird bug with Japt's `-m`ap flag that I've never come across before. ``` ®®?VgT°:SÃq ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=rq4/VmdUsDpTw3E&input=WwpbMCwwLDEsMCwwXQpbMCwxLDAsMSwwXQpbMSwwLDAsMCwxXQpbMCwxLDAsMSwwXQpbMCwwLDEsMCwwXQpdCiJQUENHIg) ``` ®®?VgT°:SÃq :Implicit input of 2D boolean array U & string V ® :Map ® : Map ? : If truthy (i.e., 1) Vg : Get the character in V at index T° : T (initially 0) postfix incremented : : Else S : Space à : End map q : Join :Implicit output joined with newlines ``` [Answer] # Pyth, 12 bytes ``` jms?R@z~hZ\ ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=jms%3FR%40z~hZ%5C%20&input=%5B%5B0%2C0%2C1%2C0%2C0%5D%2C%20%5B0%2C1%2C0%2C1%2C0%5D%2C%20%5B1%2C0%2C0%2C0%2C1%5D%2C%20%5B0%2C1%2C0%2C1%2C0%5D%2C%20%5B0%2C0%2C1%2C0%2C0%5D%5D%0APPCGPPCG&debug=0) ### Explanation: ``` jms?R@z~hZ\ dQ implicit d and Q at the end I use the variable Z, which is initialized with 0 by default m Q map each line d of the Q (input matrix) to: ?R d map each number d of the line either to @z~hZ input[Z++] (increase Z, but lookup in input string with old value) \ or space s join chars to a string j print each string on a separate line ``` [Answer] ## ES6, 78 bytes ``` (a,b,x=0)=>(b.map(r=>r.map(i=>i?a[x++%a.length]:' ')+'\n')+'').replace(/,/g,'') ``` I tried [Answer] # Common Lisp, 152 bytes ``` (defun m(g w)(let((a 0))(loop for r in g do(loop for e in r do(format t"~[ ~;~c~]"e(char w a))(if(= e 1)(setf a(mod(1+ a)(length w)))))(format t"~%")))) ``` Usage: ``` * (m (list (list 1 0 1) (list 0 1 0) (list 1 0 1)) "ppcg") p p c g p ``` This function loops through each element of each row of the grid. The `format` control string either prints a space if the element is a 0 or consumes the character argument if the element is 1. A newline gets printed after every row of the grid. If the string is too short, it repeats from the beginning; if it's too long, only the appropriate part gets outputted. [Answer] ## [Pip](http://github.com/dloscutoff/pip), 18 bytes 17 bytes of code, +1 for `-l` flag. ``` Yb{a?y@++vs}MMa^s ``` Takes the array as the first command-line argument like this: `100 010 101` (needs to be quoted in shells) and the string as the second command-line argument. [Try it online!](http://pip.tryitonline.net/#code=WWJ7YT95QCsrdnN9TU1hXnM&input=&args=LWw+MDAxMDAgMDEwMTAgMTAwMDEgMDEwMTAgMDAxMDA+SmFiYmVyd29ja3k) ### Explanation ``` a and b are cmdline args, s is space, v is -1 Yb Yank b into global variable y a^s Split a on space into list of rows { }MM Map this function to the items of the items of a (i.e. each character): a Function argument ? Ternary operator (truthy if 1, falsey if 0) ++v If truthy, increment v... y@ ... and use it to index into y (cyclically) I.e.: each time we hit a 1, replace it with the next character of y s If falsey, space The result is a list of lists of characters; -l concats sublists and newline-separates the main list ``` [Answer] # Java, 237 233 Bytes *Edit: saved 4 Bytes thanks to Mukul Kumar* Golfed: ``` String T(int[][]m,String b){int l=m.length,a=0;String o="";for(int i=0;i<l;i++){for(int j=0;j<l;j++){if(m[i][j]==1&&a<b.length()){o+=Character.toString(b.toCharArray()[a]);a++;if(a== b.length()-1)a=0;}else o+=" ";}o+="\n";}return o;} ``` Ungolfed: ``` public String T(int[][] m, String b) { int l = m.length,a=0; String o = ""; for(int i = 0; i < l; i++) { for(int j = 0; j < l; j++) { if(m[i][j] == 1 && a < b.length()) { o += Character.toString(b.toCharArray()[a]); a++; if(a == b.length() - 1) a = 0; } else o += " "; } o += "\n"; } return o; } ``` Testing: ``` int[][] matrix = new int[][] {{ 0, 0, 1, 0, 0 }, { 0, 1, 0, 1, 0 }, { 1, 0, 0, 0, 1 },{ 0, 1, 0, 1, 0 }, { 0, 0, 1, 0, 0 },}; TheArtOfWordShaping taows = new TheArtOfWordShaping(); System.out.println(taows.T(matrix, "PPCGPPCG")); matrix = new int[][] {{1,0,0}, {0,1,0}, {1,0, 1}}; taows = new TheArtOfWordShaping(); System.out.println(taows.T(matrix, "lamda")); matrix = new int[][] {{1,1,1},{1,0,1},{1,1, 1}}; taows = new TheArtOfWordShaping(); System.out.println(taows.T(matrix, "PPCG")); P P C G P P C P l a m d PPC P P CPP ``` [Answer] ## Pyke, 12 bytes ``` .FdRIKQoQl%@ ``` [Try it here!](http://pyke.catbus.co.uk/?code=.FdRIKQoQl%25%40&input=PPCG%0A%5B%5B1%2C1%2C1%5D%2C%5B1%2C0%2C1%5D%2C%5B1%2C1%2C1%5D%5D) Outputs a matrix of characters Or 9 bytes, noncompetitive. ``` .FdRIKQo@ ``` [Try it here!](http://pyke.catbus.co.uk/?code=.FdRIKQo%40&input=PPCG%0A%5B%5B1%2C1%2C1%5D%2C%5B1%2C0%2C1%5D%2C%5B1%2C1%2C1%5D%5D) * Add wrapping on indexables where the index asked for is bigger than the length of the indexable. ​ .F - deep\_for(input) I - if ^: Qo@ - Q[o++] dR - else " " Even more noncompetitive, 8 bytes ``` .FIQo@(P ``` [Try it here!](http://pyke.catbus.co.uk/?code=.FIQo%40%28P&input=PPCG%0A%5B%5B1%2C1%2C1%5D%2C%5B1%2C0%2C1%5D%2C%5B1%2C1%2C1%5D%5D) * `print_grid` now aligns empty strings properly * `deep_for` now does type-guessing on falsies of a different type to the truthies ​ ``` .F ( - deep_for(input) I - if ^: Qo@ - input[o++] P - pretty_print(^) ``` [Answer] # Java,122 bytes ``` String g(int[][]a,char[]b){String r="";int e=0;for(int[]c:a){for(int d:c){r+=d==0?' ':b[e++%b.length];}r+='\n';}return r;} ``` [Answer] # [J](http://jsoftware.com/), 18 bytes ``` ({' '&,)~$$,*+/\@, ``` [Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NarVFdTVdDTrVFR0tLT1Yxx0/mtylaQWl9jqKaQmZ@Q7pCko6SkZWOvFG3FxqQcEOLuDsLoCSAnIKAMuAwNDAyBpCIRcQJaBIZQNEdf8DwA "J – Try It Online") * `,*+/\@,` Flatten the matrix, then multiply the flatten by the scan sum of the flatten. * `({' '&,)~` Prepend a space to the replacement chars, and the index into that using the result of the previous step. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` SƶDêþIÞ𚇠``` Inputs in the order \$matrix, string\$, where the \$matrix\$ is a multi-line string. Outputs the result as a list of characters. [Try it online](https://tio.run/##yy9OTMpM/f8/@Ng2l8OrDu/zPDzv8IajCx81LPz/X0lJydDQkMvQAIgNDYE8roAAZ3cA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgpFOZ8KhhmdLh/Uo6OlxKjsklpYk5CvmlJUBpiGzo/@Bj21wOrzq8L@LwvMMbji581LDwv61SQFFqSUmlbkFRZl5JagpUh5KOl86hbfb/o6OVDAwMDQxi8oCkIZACsg0M4TywnJKOUkCAszsIK8XqKEQrwdSDVBsCZXMSc5NSEqFyhoZgYSBhaAjVqRQbCwA). **Explanation:** ``` S # Split the first (implicit) multi-line string to a list of characters ƶ # Multiply each by its 1-based index (the 0s and "\n" remain unchanged, only # the 1s are changed to their 1-based index) D # Duplicate this list ê # Remove all 0s except for a leading one, by using a sorted-uniquify þ # Remove the newline, by only keeping numbers I # Push the second input-string Þ # Cycle its characters indefintely ðš # Prepend a leading space " " ‡ # Transliterate the 0s and 1-based indices with these characters # (after which the resulting list of characters is output implicitly) ``` With an actual matrix as I/O, it would have been 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) instead by adding a trailing `¹gä`: [try it online](https://tio.run/##yy9OTMpM/f8/@Ng2l8OrDu/zPDzv8IajCx81LDy0M/3wkv//o6MNdYAwVgdIG0BpED@WKyDA2R0A) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@Z8KhhmdLh/Ur2SgqJeSlAER0uJcfkktLEHIX80hKgMqAqncqE0EMr/wcf2@ZyeNXhfRGH5x3ecHTho4aFh9alH17y31YpoCi1pKRSt6AoM68kNQWqUUnH69BunUPb7P9HA4GBjoGOIRAbxOpEQ1iGYDZYDMRDE0eoj9VRCghwdgdhpVgdBaBZKOZAzTAEqctJzE1KSYSrMgSbagg1HcKHmqYUGwsA) (note that the `S` also implicitly flattens, although an actual flatten `˜` could be used here as well). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 10 bytes ``` $¨Svv¨i?ðṠ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwiJMKoU3Z2wqhpP8Ow4bmgIiwiIiwiW1sxLCAwLCAwXSwgWzAsIDEsIDBdLCBbMSwgMCwgMV1dXG5cImxhbWJkYVwiIl0=) First time I've used `¨S` in an answer I think. Takes matrix then string ## Explained ``` $¨Svv¨i?ðṠ $ # Push matrix then string to the stack ¨S # and set the input source to the characters of the string. This quite literally overrides argv. vv # to each item in the matrix: ¨i # if the item is 1: ? # take input (which will be next character of string) ð # else: space Ṡ # sums of items # j flag joins on newlines ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` ‛ %İṠ⁋$% ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigJsgJcSw4bmg4oGLJCUiLCIiLCJbWzAsIDAsIDEsIDAsIDBdLCBbMCwgMSwgMCwgMSwgMF0sIFsxLCAwLCAwLCAwLCAxXSwgWzAsIDEsIDAsIDEsIDBdLCBbMCwgMCwgMSwgMCwgMF1dXG5bXCJQXCIsXCJQXCIsXCJDXCIsXCJHXCJdIl0=) ``` İ # Index into... ‛ % # " %" Ṡ⁋ # Join each into a string, join by newlines $% # Replace %s with corresponding elements of the input ``` [Answer] # Mathematica, 76 bytes ``` ""<>(s=#2;f:=(s=RotateLeft[s];Last[s]);Map[If[#1,f," "]&,#,{2}]~Riffle~"\n")& ``` Unnamed function of two arguments, the first of which (`#`) is an array of `True`s and `False`s, and the second of which (`s`) is a list of characters. The helper function ``` f:=(s=RotateLeft[s];Last[s]) ``` is defined, which puts the moves the first character of `s` to the end and then returns that just-moved character. Calling `f` several times will cyclically return the characters of `s` in order. The core function is ``` Map[If[#1,f," "]&,#,{2}] ``` which calls `f` on every `True` value in the input array and returns a space on every false input. (The `{2}` tells `Map` to work on elements of the array's component lists, rather than those lists themselves.) Those 60 bytes return an array of characters-of-`s` and spaces. The wrapper ``` ""<>(...~Riffle~"\n")& ``` puts newlines between each of that array's lists and then concatenates everything. [Answer] # C++, 61 bytes ``` for(auto&i:m){for(int&j:i)cout<<(j?s[k++%l]:' ');cout<<'\n';} ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 52 bytes ``` ->a,s{i=-1 a.gsub(/(0)|1/){$1?" ":s[(i+=1)%s.size]}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3TXTtEnWKqzNtdQ25EvXSi0uTNPQ1DDRrDPU1q1UM7ZUUlKyKozUytW0NNVWL9Yozq1Jja2uheiMKSkuKFdyilQwMDA0MuICEoQEXkGVgCGWDxZV0FJQCApzdQVgplosLpAlCgrQaGhoCtQCxoSFMoVIsxPwFCyA0AA) ]
[Question] [ Create a program, that outputs a hello world string ("Hello world", "Hello, World" etc.), and source code. Output is written to stdout or equivalent. Hello world string is embedded in the source code. For example, the output for might be ``` (some source code here)hello world(some source code here) ``` **When the output is compiled or interpreted again, it should create a similar output, but the hello world string must have a different punctuation or capitalization.** For example, the previous example could create the following output ``` (some source code here)hello, wORld(some source code here) ``` Each "(some source code here)" in these examples can change after each execution, or it can be the same. **Your output must contain a valid hello world string exactly once.** It may contain any amount of invalid hello world strings. Source code may contain any amount of comments, and the hello world string may be embedded in comments. The first program can have either zero or one valid hello world strings, but no more. Following punctuation is valid: ``` hello, world hello world helloworld ``` Any capitalization is acceptable. For example, these are valid hello world strings: ``` Hello, world hellO WORld HELLoworlD ``` These strings are not valid: ``` Hello world Hello(newline)world Hello,world Hello, Steve ``` Your program fails as soon as one of the following conditions are met: * It outputs a hello world string that has been output during some earlier execution, * output is no longer valid source code in the same language, or * output does not contain exactly one valid hello world string. **Your program is not valid for this contest unless at least two first executions are successful.** This means that the third output is allowed to be invalid. Output of your program may not be random. First execution should always create the same second output, second execution should always create the same third output, etc. Score is calculated as amount of bytes in the source code of the initial program. Lowest score wins. Following bonuses do apply (up to -60%): * -5% \* (N - 2), where N is the index of the execution after which your program produces invalid output. This bonus caps at -50%. If your program succeeds 12 times or more, you get the max bonus. * -10%, if your outputs (including first source code) include all three valid punctuation alternatives. Your submission should include the first source code, and it should also contain the outputs of the successful executions. If your program succeeds more than 12 times, add output for 12 executions. ## Example Next line is the first source code. When we execute it, it is the first execution. ``` hello world(some source code here) ``` Next line is the output from the first source code code. It is the first output. ``` hello, world(some source code here) ``` Next line is the output from the second execution. It is the second output. ``` helloworld(some source code here) ``` When we executed the first output, this program became eligible for the -10% bonus. That means we have two outputs, and one original code, which all have different punctuation. Moreover, because the second output was valid, this program is eligible for this contest. Next line is the output from the third execution. It is the third output. ``` Helloworld(some source code here) ``` Next line is the output from the fourth execution. It is the fourth output. ``` hellworld(some source code here) ``` This output was invalid. Index of the last valid execution was 4. This program is eligible for -5% \* (4 - 2) bonus and -10% bonus from the punctuation. This makes total of -20%. The length of the first source code ("hello world(some source code here)") was 34 bytes, so the final score is 27.2. [Answer] # Mathematica, ~~214~~ 194 - 50% = 97 bytes ``` (a = "helloworld"; b = Apply[StringJoin, Tuples[Thread[Characters[{ToLowerCase[a], ToUpperCase[a]}]]], {1}]; StringReplacePart[ToString[#0, InputForm], b[[FirstPosition[b, a] + 1]], {7, 16}]) & ``` I decided to optimize for string count here. This runs for 1024 programs without stopping, going through every combination of uppercase and lowercase letters. The execution can be seen [here](http://pastebin.com/Y0NZJA2q). [Answer] # Pyth, 17 bytes A different Pyth solution: ``` "r\"helloworld\"1 ``` Output: ``` r"helloworld"1 ``` Second output: ``` HELLOWORLD ``` [Answer] # Vitsy, 33 - 33\*.05\*(11-2) = 18.15 Bytes Heh! Beat that! You probably will. :c ## First output: ``` '0DV\{25^-V\}}1+{rd3*Z;helloworld ' Start capturing as a string 0DV Push 0 to the stack and set it as the final variable. \ Repeat the next item this many times. (1, 2, 3... on outputs.) { Rotate the stack leftwards. 25^ Push 32 to the stack. - Subtract the top item by it - this will make lowercase uppercase. V\ Do the next item final variable times. } Rotate the stack rightwards. } And again... 1+ Add one. This makes the 0 in this code a 1, then 2... r Reverse the stack. d3* Get the character ' Z Output all items in the stack. ; End execution. helloworld String to manipulate. ``` ## Second output: ``` '1DV\{25^-V\}}1+{rd3*Z;helloworlD ``` ## Third output: ``` '2DV\{25^-V\}}1+{rd3*Z;helloworLD ``` ## Fourth output: ``` '3DV\{25^-V\}}1+{rd3*Z;hellowoRLD ``` ## Fifth output: ``` '4DV\{25^-V\}}1+{rd3*Z;hellowORLD ``` ## Sixth output: ``` '5DV\{25^-V\}}1+{rd3*Z;helloWORLD ``` ## Seventh output: ``` '6DV\{25^-V\}}1+{rd3*Z;hellOWORLD ``` ## Eighth output: ``` '7DV\{25^-V\}}1+{rd3*Z;helLOWORLD ``` ## Ninth output: ``` '8DV\{25^-V\}}1+{rd3*Z;heLLOWORLD ``` ## Tenth output: ``` '9DV\{25^-V\}}1+{rd3*Z;hELLOWORLD ``` ## Eleventh output: ``` ':DV\{25^-V\}}1+{rd3*Z;HELLOWORLD ``` This is the last output, as it will cause an error. [Answer] ## CJam, N = ~~3~~ 4, 28 bytes - 10 % - 10 % = 22.4 ``` {`_E=-"_~Hello!, World"2<}_~ ``` this starts the following chain: ``` {`_E=-"_~Hello, World"2<}_~ {`_E=-"_~Hello World"2<}_~ {`_E=-"_~HelloWorld"2<}_~ {`_E=-"_~Helloorld"2<}_~ ``` where the last one no longer contains a valid "Hello, World". [Test it here.](http://cjam.aditsu.net/#code=%7B%60_E%3D-%22_~Hello!%2C%20World%222%3C%7D_~) ### Explanation ``` {` e# Quine framework. Leaves a string representation of the block on the stack. _E= e# Make a copy and get the 14th element, which is the character of the first 'o'. - e# Remove that character from the string. "_~Hello!, World" e# Push this string, so the "Hello, World!" is part of the code. 2< e# Truncate to just "_~" to get the output right. }_~ ``` Note that the initial program does not contain a valid "Hello, World", but that allows us to go one iteration further. [Answer] # CJam ~~69~~ 60 - 50% = 30 I'm still beginner, Please tell me how to golf in CJam. ``` {`_40>\40<_38>~)`2Te[\25<"helloworld"00YbATe[.{{el}{eu}?}`+]W%"_~"}_~ ``` It's tedious to print each iteration, as it will valid for 99 iterations. It works by enumerate the capitalization of hello word. The tedium is to splitting strings into parts as both "hello world" and the counter have to be updated. Explanation ``` {`_40>\40<_38>~)`2Te[\25<"helloworld"00YbATe[.{{el}{eu}?}`+]W%"_~"}_~ {` e# standard quine framework. Thanks for Dennis. _40> e# get the Yb11.. \40< e# get those that not included in top _38>~)`2Te[ e# get the accumulator and increment it \25< e# get those before "hello world" "helloworld" e# the Hello World 00 e# accumulator YbATe[ e# convert to binary and align right. .{{el}{eu}?} e# Uppercase if the corresponding bit is 0 ` e# add quote +]W% e# reorder stack "_~"}_~ ``` NOTE: I don't read the Mathematica answer, sorry, I think it was original With reordering, and different capitalization, I lose 9 bytes. ``` {`_6<\"helloworld"01YbW%.{{eu}{el}?}`\I>_2<~)`2Te[\2>"_~"}_~ {` "_~"}_~ e# Standard quine framework _6<\ e# Get "{~_6<\" "helloworld" e# The helloworld 01 e# The accumulator Yb e# Convert to base 2 W% e# Reverse the binary .{{eu}{el}?} e# Convert to uppercase while the corresponding bit is 1. ` e# Add quote _2< e# Get accumulator ~)`2Te[ e# Increment the accumulator \2> e# get the rest ``` ## CJam 73 - 60% = 29.2 This time also enumerate the punctuation. ``` {`:Z6<"HELLOWORLD"0:AYbW%.{{eu}{el}?}`", ":B-_6<BA3%>@6>A)ZW%52<W%"_~"}_~ {`:Z "_~"}_~ e# Standard Quine Framework 6< e# take the first 6 character "HELLOWORLD" e# Hello, world 0:A e# Accumulator YbW%.{{eu}{el}?}` e# See above ", ":B e# Punctuation - e# Delete punctuation _6< e# "hello BA3%> e# punctuation @6> e# world" A) e# incremented accumulator ZW%52<W% e# Remaining part ``` [Answer] # GolfScript, 35 bytes − 50% = 17.5 ``` 0"HelloWorld"{@@{^.32&\}%`@".~"}.~ ``` I decided to go for overkill on the number of executions before a repeat. This program, with its output fed back into the GolfScript interpreter, will produce **890** distinct Hello World strings before the first repeat. As a brief sample, here are the first 15 iterations: ``` 0"HelloWorld"{@@{^.32&\}%`@".~"}.~ 0"HeLlOWoRlD"{@@{^.32&\}%`@".~"}.~ 0"HelLOWorLD"{@@{^.32&\}%`@".~"}.~ 0"HeLLOWoRLD"{@@{^.32&\}%`@".~"}.~ 0"HellowORLD"{@@{^.32&\}%`@".~"}.~ 32"HeLlOworld"{@@{^.32&\}%`@".~"}.~ 0"hELloWoRlD"{@@{^.32&\}%`@".~"}.~ 32"helLowORld"{@@{^.32&\}%`@".~"}.~ 0"HeLLoWORlD"{@@{^.32&\}%`@".~"}.~ 32"HellOWORld"{@@{^.32&\}%`@".~"}.~ 0"hElLOWORlD"{@@{^.32&\}%`@".~"}.~ 32"heLLOWORld"{@@{^.32&\}%`@".~"}.~ 32"HelloworLd"{@@{^.32&\}%`@".~"}.~ 32"hElLoWoRLd"{@@{^.32&\}%`@".~"}.~ 0"HEllOWorlD"{@@{^.32&\}%`@".~"}.~ ``` The way it works is by iterating through the string, flipping the capitalization of each letter (by XORing its ASCII code with 32) if the previous letter (after possibly having its case flipped) is lowercase. The first letter will have its case flipped if the number at the beginning program is 32 rather than 0 — and the number output for the next iteration will be 32 whenever the last letter of the string is lowercase, thus causing any changes at the end of the string to propagate back to the beginning on the next iteration. (This particular feedback process was obtained in a totally *ad hoc* manner. I originally wanted to just run a simple binary counter using uppercase and lowercase as the bits, but that took too many bytes to implement, so I started tweaking it to find something shorter that would still yield a fairly high cycle length. Since the theoretical maximum, using case-flipping only, is 210 = 1024, getting an 890-iteration cycle is pretty nice.) Alas, the bonus for additional iterations is capped at −50%; without the cap, this program would have a whopping −4440% bonus. ;-) [Answer] # Pyth, 18 bytes ``` "-\"hello world\"d ``` Which returns: ``` -"hello world"d ``` Which in turn prints: ``` helloworld ``` I had a solution that did all three spellings, but it's longer even with the bonus. [Answer] # Ruby, 81 - 50% = 40.5 Original code: ``` _='_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)';puts _%[_,'HELLOWORL'+?D] ``` Successive outputs: ``` _="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"HELLOWORLD"]).sub(/[[:upper:]]/,&:swapcase) _="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"hELLOWORLD"]).sub(/[[:upper:]]/,&:swapcase) _="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"heLLOWORLD"]).sub(/[[:upper:]]/,&:swapcase) _="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"helLOWORLD"]).sub(/[[:upper:]]/,&:swapcase) _="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"hellOWORLD"]).sub(/[[:upper:]]/,&:swapcase) _="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"helloWORLD"]).sub(/[[:upper:]]/,&:swapcase) _="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"hellowORLD"]).sub(/[[:upper:]]/,&:swapcase) _="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"hellowoRLD"]).sub(/[[:upper:]]/,&:swapcase) _="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"helloworLD"]).sub(/[[:upper:]]/,&:swapcase) _="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"helloworlD"]).sub(/[[:upper:]]/,&:swapcase) _="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"helloworld"]).sub(/[[:upper:]]/,&:swapcase) ``` I think this counts as the full 50%? Might be off by one. Also, there's probably a better-scoring non-bonus solution in Ruby. The original code doesn't contain "helloworld", but it builds a quine that replaces the first capital letter in its source code with the lowercase version. So each successive run of the quine outputs one fewer capitalized letter. The trick here is to use a format string to interpolate both the string itself, for quining, and the Hello World string, so that it only appears once. [Answer] # [Simplex](http://conorobrien-foxx.github.io/Simplex/), 21 bytes. This is what Simplex was *born* for. I can definitely go farther with this. (I keep on hitting Ctrl+Enter, sorry! I blame it on the tablet keyboard) ## Attempt 3, v.0.8+, 31 -5% = 29.45 bytes (UTF-8 methinks) That emote in the middle expresses myself. Sort of. Why did I do this, again? .\_. ``` "\"f[helloworld]-:D-``\"§R'Hg"g " " ~~ write that string \"f[helloworld]-:D-``\"§R'Hg ~~ escaped quotes g ~~ output that string ``` 2nd Output: ``` "f[helloworld]-:D-``"§R'Hg " " ~~ write that string f[helloworld]-:D-`` ~~ string to be written §R ~~ go to second cell 'H ~~ set it to H charcode g ~~ output that string ``` 3rd output: ``` f[Helloworld]-:D-`` f ~~ turns off safety mode (heck yeah error suppression!) [ ]- ~~ write inside to outer program H ~~ sort strip e ~~ write e = 2.718281828459045... to the strip ll ~~ writes 1 twice to the cell o ~~ outputs 1 wo ~~ apply o backwards through the strip (outputs 1) r ~~ error! tries to access register for modification. nope! l ~~ write 1 to to the current cell d ~~ reverse the strip (NOP) : ~~ removes last char of outer program D ~~ double the current byte (2) - ~~ writes previous char to outer program `` ~~ suppress outer program evaluation and instead output it ``` Final output: ``` HelloworlD ``` ## Attempt 2, v.0.8+, 21 bytes (UTF-8, I think) ``` "\"helloworld\"§'Hg"g " " ~~ write that string \"helloworld\"§'Hg ~~ escaped quotes g ~~ output that string ``` Output: ``` "helloworld"§'Hg " " ~~ write that string helloworld ~~ string to be written § ~~ go to first cell 'H ~~ set it to H charcode g ~~ output that string ``` Final output: ``` helloworld ``` ## Attempt 1, v.0.7+ ~~28~~ 26 bytes I'm not sure if this qualifies for the first bonus… ``` "BhelloworldB"t[s32S;]'gs; " " ~~ write that string BhelloworldB ~~ the string t[ ] ~~ apply the inner from left to right s ~~ output as character 32S ~~ subtract 32 ("capitalize") ; ~~ add the current byte's char to the outer program 'g;s ~~ add g to the outer program ``` First output: ``` "HELLOWORLD"g ``` The outer program is evaluated at the end of execution (it does it for y; this is what the outer program looks like: ``` "HELLOWORLD"g " " ~~ write that string g ~~ output that string as string characters ``` Final output: ``` HELLOWORLD ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), score 8 ``` `kh#`kH+ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60kh%23%60kH%2B&inputs=&header=&footer=) Outputs: ``` kh#Hello, World! ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=kh%23Hello%2C%20World!&inputs=&header=&footer=) Outputs: ``` Hello World ``` ## Explained ``` `kh#` ``` Push the string `"kh#"` onto the stack (which, when literally executed, is the constant `"Hello World"` and a comment) ``` kH+ ``` Push the string `"Hello, World!"` onto the stack and concatenate the two strings together. Implicitly print the string. [Answer] # PHP, 297 - 40% = 178.2 bytes Not really competitive but it was fun to write ``` <?ob_start(function($s){$s=substr(str_replace(0,0+(int)true,$s),!i,ord(I)+ord(I));$h=hello.world;$h[0]=$h[0]^' ';return "<"."?".$s."?".">".$s.$h;});?>ob_start(function($s){$s=substr(str_replace(0,0+(int)true,$s),!i,ord(I)+ord(I));$h=hello.world;$h[0]=$h[0]^' ';return "<"."?".$s."?".">".$s.$h;}); ``` It's a variation of this quine: ``` <? ob_start(function($b){ return "<"."?\n$b?".">\n$b"; });?> ob_start(function($b){ return "<"."?\n$b?".">\n$b"; }); ``` but it also adds "helloworld" to the output and replaces `0` with `0+1` (in the next iteration `1` with `1+1` and so on). Using `substr` any existing "helloworld" output gets removed before the new "helloworld" gets added. To get different output, one letter of "helloworld" gets capitalized (determined by the incrementing number). This is the relevant code: ``` $h=hello.world;$h[0]=$h[0]^' ' ``` A challenge was to not use any numbers except here and for the number replacement ``` str_replace(0,0+(int)true,$s) ``` There you already see that `+1` is realized as `+(int)true`. For the substring arguments I needed `0, 146`: ``` !i, ord(I)+ord(I) ``` The non-empty string "i" gets coerced to `true` and negated. `false` is a valid integer argument and is treated like `0`. `ord(I)` is the ASCII value of "I": 73 ### Output (1st iteration): ``` <?ob_start(function($s){$s=substr(str_replace(1,1+(int)true,$s),!i,ord(I)+ord(I));$h=hello.world;$h[1]=$h[1]^' ';return "<"."?".$s."?".">".$s.$h;});?>ob_start(function($s){$s=substr(str_replace(1,1+(int)true,$s),!i,ord(I)+ord(I));$h=hello.world;$h[1]=$h[1]^' ';return "<"."?".$s."?".">".$s.$h;});Helloworld ``` ### Output (2nd iteration): ``` <?ob_start(function($s){$s=substr(str_replace(2,2+(int)true,$s),!i,ord(I)+ord(I));$h=hello.world;$h[2]=$h[2]^' ';return "<"."?".$s."?".">".$s.$h;});?>ob_start(function($s){$s=substr(str_replace(2,2+(int)true,$s),!i,ord(I)+ord(I));$h=hello.world;$h[2]=$h[2]^' ';return "<"."?".$s."?".">".$s.$h;});hElloworld ``` ### Output (10th iteration): This is the last valid output but not a valid program anymore ``` <?ob_start(function($s){$s=substr(str_replace(10,10+(int)true,$s),!i,ord(I)+ord(I));$h=hello.world;$h[10]=$h[10]^' ';return "<"."?".$s."?".">".$s.$h?>ob_start(function($s){$s=substr(str_replace(10,10+(int)true,$s),!i,ord(I)+ord(I));$h=hello.world;$h[10]=$h[10]^' ';return "<"."?".$s."?".">".$s.$hhelloworlD ``` > > Scroll far to the right to find the "Hello world" strings! > > > [Answer] # Pip, 48 - 50% = 24 ``` V Y"`V Y`.RPyRh:ST`helloworld`UCh@<0.h@>0R0o+0" ``` which evolves as follows: ``` V Y"`V Y`.RPyRh:ST`helloworld`UCh@<1.h@>1R1o+1" V Y"`V Y`.RPyRh:ST`Helloworld`UCh@<2.h@>2R2o+2" V Y"`V Y`.RPyRh:ST`HElloworld`UCh@<3.h@>3R3o+3" V Y"`V Y`.RPyRh:ST`HELloworld`UCh@<4.h@>4R4o+4" V Y"`V Y`.RPyRh:ST`HELLoworld`UCh@<5.h@>5R5o+5" V Y"`V Y`.RPyRh:ST`HELLOworld`UCh@<6.h@>6R6o+6" V Y"`V Y`.RPyRh:ST`HELLOWorld`UCh@<7.h@>7R7o+7" V Y"`V Y`.RPyRh:ST`HELLOWOrld`UCh@<8.h@>8R8o+8" V Y"`V Y`.RPyRh:ST`HELLOWORld`UCh@<9.h@>9R9o+9" V Y"`V Y`.RPyRh:ST`HELLOWORLd`UCh@<10.h@>10R10o+10" V Y"`V Y`.RPyRh:ST`HELLOWORLD`UCh@<11.h@>11R11o+11" V Y"`V Y`.RPyRh:ST`HELLOWORLD`UCh@<12.h@>12R12o+12" ``` with the last output being invalid because the `HELLOWORLD` hasn't changed. (Correct me if I haven't done the bonus right.) Thanks to this question, I just discovered a new quine technique! The base quine is `V Y"`V Y`.RPy"`: ``` Y" " Yank that string into the variable y V Evaluate it as a Pip expression: RPy y wrapped in double quotes (repr) `V Y`. Prepend that regex pattern When this is evaluated, it returns a pattern object, which is auto-printed--conveniently, without the `` delimiters ``` Our extra code modifies the string in `y`, before repr-ing it, as follows: * Replace the current helloworld with one in which the leftmost `0` characters are uppercased; * Replace all occurrences of `0` with `o+0` (where `o` is a builtin variable that equals 1). The next time around the number in the code is `1` instead of `0`, and so forth. [Answer] # Javascript, 52 bytes ``` function(){return '("hello world").replace(" ","")'} ``` ## Test `=>` `<='("hello world").replace(" ","")'` `=> eval('("hello world").replace(" ","")')` `<= 'helloworld'` [Answer] # BBC BASIC, 56 bytes I had a crack at this before I realized how late to the game I am. For what it's worth, here's my version and my first attempt at StackExchange code golf. Here, *V.* echoes out the characters given by the ASCII codes in the following comma separated list and *P.* is shorthand for print. I make use of the backspace character to overwrite the existing 'helloworld' string. **Input code:** ``` V.80,46,34:P."helloworld";:V.8,68,34,59:P.":V.8,8,76,68" ``` **First Output:** ``` P."helloworlD";:V.8,8,76,68 ``` **Second Output:** ``` helloworLD ``` It can be tested online at <https://bbc.godbolt.org/> [Answer] ## ///, 23 bytes ``` /,//\/ \/\/hello, world ``` [Try it online!](https://tio.run/##K85JLM5ILf7/X19HXz9GXyEGSGSk5uTk6yiU5xflpPz/DwA "/// – Try It Online") First output: ``` / //hello world ``` Second output: ``` helloworld ``` [Answer] # [Keg](https://github.com/JonoCode9374/Keg), ~~32~~ ~~28~~ ~~23~~ ~~22~~ 21 bytes ``` CKQNVNKKDG`(⑨,)`‘H%c¡ ``` [Try it online!](https://tio.run/##y05N///f2TvQL8zP29vFPUHj0cQVOpoJjxpmeKgmH1r4/z8A "Keg – Try It Online") This prints: ``` CKQNVNKKDG(⑨,)HelloWorld ``` Which prints: ``` HELLOWORLD ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), score ~~15~~ 9 *-9 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs).* ``` ’"Ÿ™ ‚ï"á ``` [Try it online!](https://tio.run/##ARwA4/9vc2FiaWX//@KAmSLFuOKEoiDigJrDryLDof// "05AB1E – Try It Online") Output: ``` "hello world"á ``` Second output: ``` helloworld ``` --- ``` ’... # trimmed program ’... # push "\"hello world\"á" # implicit output "..."á # trimmed program á # push only letters in... "..." # literal # implicit output ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 20.5 bytes ``` `⌐÷:aBk⁋+›bḢ¨£ßN∑kTtp+q‛:Ė+,helloworld`:Ė ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiYOKMkMO3OmFCa+KBiyvigLpi4biiwqjCo8OfTuKIkWtUdHArceKAmzrElissaGVsbG93b3JsZGA6xJYiLCIiLCIiXQ==) This outputs all 1024 different capitalisations of `helloworld`. ``` ` q‛:Ė+ `:Ė # Quine structure , # Eventually print the result helloworld # Ignored ⌐÷ # Push the bits before and after the comma :a # Check capitalisation Bk⁋+›bḢ # Binary increment ¨£ßN∑ # Capitalise kTtp # Prepend a comma + # Append to the rest of the code ``` ]
[Question] [ Your task, if you choose to accept it, is to write a program/function that accepts an integer \$N\$ as input. The program/function should output/return a list of the first \$N\$ prime numbers. But here's the catch: you are not allowed to use *prime characters* in your code. A prime character is a character whose Unicode code point is a prime number. In the printable ASCII range, these are: ``` %)+/5;=CGIOSYaegkmq ``` But the rule also applies to non-ASCII characters if your code uses those. * A valid input is an integer \$N\$ where \$0 < N \le T\$, where you can choose \$T\$, but it has to be greater than or equal to \$10000\$. \$T\$ does not have to be finite. * For invalid inputs (non-integers, integers out of range), throw an exception or output/return nothing/null. * An integer with leading/trailing whitespace as input is considered invalid. * An integer with a `+` as sign character as input is considered invalid. * An integer with leading zeros as input is considered valid. * If your language allows you to pass an already-parsed integer as input, the above parsing rules (except the range one) don't apply, because the int is already parsed. * The input is always base-10. * Use of built-in prime generators and primality testers (this includes prime factorization functions) is not allowed. * The source restriction is imposed on Unicode characters, but the byte counting for the score can be in another encoding if you wish. * The output can contain a single trailing newline, but this is not required. * If you output/return the prime number list as a string, then every prime number must be delimited by one or multiple non-digit char(s). You can choose which delimiter you use. * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, the shortest code in bytes wins. ## Stack Snippet to verify your code You can use the below Stack Snippet to verify that your code does not contain prime chars: ``` var primes=[],max=10000;for(var i=2;i<=max;i++){primes.push(i);}for(var N=2;N<Math.sqrt(max);N++){if(primes.indexOf(N)===-1){continue;}primes=primes.filter(function (x){return x===N||x%N!==0;});}function setText(elem,text){var z=('innerText' in elem)? 'innerText' : 'textContent';elem[z]=text;}function verify(inputCode,resultSpan){var invalidChars=[];var success=true;for(var i=0;i<inputCode.length;i++){var cc = inputCode.charCodeAt(i);if (cc>max){setText(resultSpan,"Uh oh! The char code was bigger than the max. prime number calculated by the snippet.");success = false;break;}if (primes.indexOf(cc)!==-1){invalidChars.push(inputCode[i]);}}if (invalidChars.length===0&&success){setText(resultSpan, "Valid code!");}else if(success) { var uniqueInvalidChars = invalidChars.filter(function (x, i, self){return self.indexOf(x)===i;});setText(resultSpan, "Invalid code! Invalid chars: " + uniqueInvalidChars.join("")); }}document.getElementById("verifyBtn").onclick=function(e){e=e||window.event;e.preventDefault();var code=document.getElementById("codeTxt").value;verify(code,document.getElementById("result"));}; ``` ``` Enter your code snippet here:<br /><textarea id="codeTxt" rows="5" cols="70"></textarea><br /><button id="verifyBtn">Verify</button><br /><span id="result"></span> ``` [Answer] # Python 3.7+, 183 bytes ``` for E,E.__clªss_ᵍᵉtitᵉᵐ__ in[__builtins__.__loªdᵉr__,ᵉxᵉc],:E[f'd{101:c}f F(n\x29:\n p,f\x3d1,1\n whil{101:c} n>0:p,f\x3d-~p,f*p*p\73n-\x3df{37:c}p>0!\x3dprint(p\x29'] ``` [Try it online!](https://tio.run/##LYxBCoMwEEWvkq5qJZakWUizcKeXMDJQJRiQGDSlFmn3XRR6DvdewJt4kjSCi5k////HmKetW82ck22HUpyeAcpmmfoe1vm7zh@rrN/r/ANASucAt7tqrNI9gEebdpkq33cA2MvgpywwT3N5rEZKKC9fEmWBFsPlyoVGBksxsIpi6s2jVs0OIZ0QvpfR2x@hCY2ImY62RI4s9pBJyGGzplPaBmb7eSxcFlBycn8 "Python 3 – Try It Online") Assumes an infinite upper bound, takes integer input via function argument, and prints the primes on separate lines. Without substitutions for characters (except `\n`): ``` for E,E.__class_getitem__ in[__builtins__.__loader__,exec],:E[f'def F(n):\n p,f=1,1\n while n>0:p,f=-~p,f*p*p;n-=f%p>0!=print(p)'] ``` The string in the above code: ``` def F(n): p,f=1,1 while n>0:p,f=-~p,f*p*p;n-=f%p>0!=print(p) ``` Python 3.7 [added](https://peps.python.org/pep-0560/) the `__class_getitem__` magic method: if `A` is a class, then `A[x]` calls `A.__class_getitem__(x)`. Assigning `exec` to this attribute of a class allows us to call it without `)`. Unfortunately, we cannot create our own class without either using the `class` keyword (`a`) or calling the `type` function (`)`), so we must use a built-in class. The only one that allows the assignment to be made without error is `__builtins__.__loader__`. Python [normalizes](https://docs.python.org/3/reference/lexical_analysis.html#identifiers) all identifiers to NFKC, and this allows us to spell `__class_getitem__`, `__loader__`, and `exec` without using any of the letters `aegm`. The exact substitutions are U+00AA for `a`, U+1D49 for `e`, U+1D4D for `g`, and U+1D50 for `m`. We use a `for` loop to make assignments without using `=`, and these let us call `exec` via `E[f'...']` in the body. Inside the string passed to `exec`, we use octal (`\73` instead of `;`), hex (`\x3d` instead of `=`), and decimal (`{37:c}` instead of `%`) escapes for banned characters. The code simply tests the primality of each positive integer using [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem). A function was used instead of a lambda as the recursion limit causes the latter to stop working well below 10000. [Answer] # CJam, ~~19~~ ~~18~~ ~~30~~ ~~34~~ ~~33~~ ~~19~~ ~~17~~ ~~21~~ 20 bytes [Try it online.](http://cjam.aditsu.net/#code=5%7B_3%5C%23%2C2%3E__ff*%3A~-%3CN*%7D~) ``` {_3\#,2>__ff*:~-<N*} ``` This is probably one of the most horribly inefficient algorithms I've ever implemented. But I did it for the size! My answer consists of a code block, which acts like an anonymous function in CJam. Run it with an integer immediately preceding it on the stack, and the resulting list is dumped onto the stack. I treat the upper bound on the input as infinite so I don't have to check that bound. My algorithm starts by raising 3 to the `input`th power, which is guaranteed to give a number larger than the `input`-th prime if the input is valid. Then a list of the integers from 2 to this number minus one is generated, which is a large enough swath to contain all the prime numbers we want. To get rid of the composite numbers... *sigh*... we create a list of every pairwise product, which should generate all composite numbers from 4 to some stupidly large value, large enough for our purposes. Then it's just a matter of removing every element from the original list that is in this composite list, trimming it down to the first `input` elements, and joining the elements with the newline character. The algorithm *should* work for any input. However, whether or not the interpreter/computer has enough memory or time is a whole other question, because the time and space requirements are exponential with respect to the input. So if the input is larger than about 5 for the online interpreter or about 8 for the offline one, then the answer to that question is probably no. [Answer] # Java. 474 bytes ``` i\u006dport j\u0061v\u0061.util.*\u003bvoid b(int b\u0029{Lon\u0067 c\u003d2L,d,f[]\u003d{}\u003bfor(f\u003dArr\u0061ys.copy\u004ff(f,b\u0029,Arr\u0061ys.fill(f,0L\u0029\u003bb-->0\u003b\u0029for(d\u003d0L\u003bf[b]<1\u003bf[b]\u003dd<1?c:f[b],d\u003d0L,c\u002b\u002b\u0029for(lon\u0067 h:f\u0029d\u003dh>0&&c\u002fh*h\u003d\u003dc?1:d\u003bj\u0061v\u0061x.x\u006dl.bind.JAXB.un\u006d\u0061rsh\u0061l(""\u002bArr\u0061ys.\u0061sList(f\u0029,Lon\u0067.cl\u0061ss\u0029\u003b} ``` Takes input via function argument, outputs via thrown exception. Indented: ``` i\u006dport j\u0061v\u0061.util.*\u003b void b(int b\u0029{ Lon\u0067 c\u003d2L,d,f[]\u003d{}\u003b for(f\u003dArr\u0061ys.copy\u004ff(f,b\u0029,Arr\u0061ys.fill(f,0L\u0029\u003bb-->0\u003b\u0029 for(d\u003d0L\u003bf[b]<1\u003bf[b]\u003dd<1?c:f[b],d\u003d0L,c\u002b\u002b\u0029 for(lon\u0067 h:f\u0029 d\u003dh>0&&c\u002fh*h\u003d\u003dc?1:d\u003b j\u0061v\u0061x.x\u006dl.bind.JAXB.un\u006d\u0061rsh\u0061l(""\u002bArr\u0061ys.\u0061sList(f\u0029,Lon\u0067.cl\u0061ss\u0029\u003b } ``` Escaped characters removed: ``` import java.util.*; void b(int b){ Long c=2L,d,f[]={}; for(f=Arrays.copyOf(f,b),Arrays.fill(f,0L);b-->0;) for(d=0L;f[b]<1;f[b]=d<1?c:0,d=0L,c++) for(long h:f) d=h>0&&c/h*h==c?1:d; javax.xml.bind.JAXB.unmarshal(""+Arrays.asList(f),Long.class); } ``` Explanation: ``` Long c,d,f[]={}; //Initialize variables. for(f=java.util.Arrays.copyOf(f,b),Arrays.fill(f,0L);b-->0;) f=java.util.Arrays.copyOf(f,b),Arrays.fill(f,0L) //Initialize f to an array of 0's. b-->0 //Iterate over the first b primes. for(d=0L;f[b]<1;f[b]=d<1?c:0,d=0L,c++) d=0L d=0L //Initialize d to 0. f[b]<1 c++ //Increment c while the b'th prime is 0. f[b]=d<1?c:0 //If d = 0, the b'th prime = c, else continue. for(long h:f) //Iterate over all found primes. d=h>0&&c/h*h==c?1:d; h>0 //Ignore non-found primes. c/h*h==c //Equivalent to c%h==0 ?1:d //If h is prime and c is divisible by h, d = 1. Otherwise d stays unchanged. javax.xml.bind.JAXB.unmarshal(""+Arrays.asList(f),Long.class) //Print solution to stderr javax.xml.bind.JAXB.unmarshal( ,Long.class) //Prints what's contained to stderr. Arrays.asList(f) //Convert f to list. ""+ //Convert to string. ``` My original solution used a `return` statement. After asking [this question](https://stackoverflow.com/q/28635275/4230423) on StackOverflow, [regettman](https://stackoverflow.com/users/1707091/rgettman) was kind enough to provide a way to output/return without using prime letters. As usual, suggestions are welcome :) [Answer] # Ruby, 74 ``` ->n,*o{o<<[2..n*n][0].find{|x|!o.find{|y|1.>x.^y.*x.div y}}until o[n-1] o} ``` Explanation: `*o` initializes an empty output array. until it has `n` items, we find the smallest number >=2 that doesn't divide any item currently in `o`, then add it to `o`. To test for division, yikes. All the good operators are disallowed, and I can't even use `divmod`. Best I could see was to use `x.div y`, which takes x divided by y and rounds down, then multiply that by y again. If it equals x, there was no rounding, so y divides x. `1.>x.^` is an equality test, checking whether the result of xor is 0. The `.` before every operator is because you can't mix `.`-free operator calls and parenthesis-free method calls. Edit: The range-checking specifications were added after I posted this, I think. To comply requires 79 characters: ``` ->n,*o{o<<[*2..-~n*n].find{|x|!o.find{|y|1.>x.^y.*x.div y}}until o[n-1]||n<1 o} ``` [Answer] # CJam, ~~38~~ ~~37~~ 30 bytes ``` {_~2#,2>\{(\{1$37c~},\p}*'<(~} ``` [Try it here](http://cjam.aditsu.net/#code=10%0A%7B_~2%23%2C2%3E%5C%7B(%5C%7B1%2437c~%7D%2C%5Cp%7D*'%3C(~%7D%0A~) I think this should comply with all the rules and works for any non-negative *N* (i.e. *T* is infinite). It's horribly inefficient though, so don't try it for large numbers. This is a block - the closest thing to an (unnamed) function - which expects an integer on the stack, prints all the prime numbers and leaves the stack without its input. For all invalid inputs it will either throw an error or print nothing. Most of the code is input validation, followed by the sieve of Eratosthenes. I only needed to work around the input restriction in 3 places: * `)` is increment in CJam. I needed that once, but could replace it with `~` (bitwise complement) because I was squaring the numbers afterwards anyway. * `%` is modulo. I'm using `37c~` instead, which first creates the character `%` and then eval's that. This makes the code a lot slower. * `;` pops and discards an element from the stack. I need to do this at the end. Instead I'm using `'<(~` which pushes the character `<`, decrements it and eval's that. [Answer] # Bash + coreutils, 227 bytes ``` printf -vb br`dc<<<Di14B8209P` printf -vc -- $[$1-0] [ "${1#$c}" -o $c -lt 1 ]||{ for i in {2..104729} { for f in `jot $[i-1] $[i-1] 1` { [ 0 -lt `dc<<<"$i $f~p"` ]||$b } [ $f -lt 2 ]&&printf $i\ &&: $[c--] [ $c -lt 1 ]&&$b } } ``` This was quite tricky. Some things I ran into: * Most loops (`while` and `until`) are unusable because they most close with `done` which is a shell keyword and cannot be the result of a variable expansion (unless `eval` is used, but that is out too). The only usable loop is `for`/`in` which allows `{`/`}` instead of `do`/`done`. `for (( ; ; ))` is also not usable. * `=` is out, so we need another way to assign variables. `printf -v` is good for this. * We know that p(10000) is 104729 so for the outer loop for potential primes we can simply loop from 2 to 104729 and break once we have enough primes * `jot` generates the list of potential factors in the inner loop. If a potential factor divides a potential prime, then it is not prime and we break out early * Fortunately `break` is a shell builtin and not a keyword, so may be generated as a result of an expansion. `dc` converts a base 13 number to the bytestream `eak`. * To check if a potential factor divides a potential prime, we cannot use the usual `/` or `%` shell arithmetic operators. So this is outsourced to `dc`s `~` operator, which pushes quotient and remainder to the stack. * `-lt` - less-than - is the only usable shell comparison operator. * `echo` is no use for output. `printf` works though as long as we avoid `%` Getting the input validation right is a bit of a pain. This returns nothing in the case of invalid input. ### Output: ``` $ ./primenoprime.sh 10 2 3 5 7 11 13 17 19 23 29 $ ``` [Answer] # [Rust](https://www.rust-lang.org/), 2720 1695 bytes ``` |n|for i in 0..n{if i<3&&i>1||i&1>0&&0<[0x2196820D864A4c32816D129A64B4cB6Eu128,0x4A2882D129861144A48961204A0434c9|1<<28,0x148A48844224064B0834992132424030|1<<80,0x64048928124108A00B40B4086c304204|1<<0|1<<84|1<<120,0xc02104c94112422180124496804c3098,0x220824B0826896810804490000982D32|1<<104,0x69009244304340069004264940A28948|1<<36,0x86122D22400c06012410DA408088210,0x14916022c044A0020110D301821B0484,0x4cA2100800422094092094D204A6400c|1<<84,0x34c108144309A24A48B081041018200|1<<28|1<<64,0x241140A2180032402084490880422402|1<<8|1<<20|1<<68,0x29260008360044120A41A00101840128|1<<72,0xc20c26484822006D10100480c0618283|1<<100,0x10c02402190024884420482024894810|1<<44|1<<7*8|1<<104,0x60901300264B0400802832cA01140868,0x430800112186430c32100100D0248082|1<<16,0x24880906002D20430092900c10480424,0x4000814196800880430082090932c040|1<<60,0x926094022080c3292048489608481048|1<<4*13,0xA04204901904004A0104422812000|1<<7*8,0x800084424002982c02c801348348924|1<<96,0x1864328244908A0004D0048442043698|1<<28|1<<112,0x861104309204A44028024001020A0090,0x4424990912486084c90804422c004208|1<<36,0x4040208804321A011000211403002400|1<<88,0xA2020c90116802186030014084c30906,0x8801904800841028224148929860004,0x120100100c061061020004A442681210,0x140128040A0c94186412422194032010|1<<7*8,0x4882402D20410490014000D040A40A29,0x822902002484490424080130100020c1|1<<76,0xA0cA0006112100104816814802486100|1<<20,0x2414480906810c044200B09104000240|1<<120,0x84420004802c10c860A00A011242092|1<<16|1<<112,0x12824414814804820022130406980032,0x2c00D86424812004D028804340101824,0x180110c04120cA41020000A241081209,0x48044320240A08320941220A41804A4,0x820104128864008A6086400c001800|1<<96][i>>8]&1<<{[i&{1<<8}-1][0]>>1}{print!{"{} ",i}}} ``` [Try it online!](https://tio.run/##TVTbahtBDH33V2zzYJKQBkkjJprWNaxxv8L4ISwxLLRuyQVCbX@7e442xQ1mY89qRuemeX57eT3v9t3Px3F/fXOY/Xh67XZfdvvrt5fxz9NN9607H/fH3a/nbuzGfSf39/vDuOvGRZnPx6Uej@NclzKfy2Ij76athsk6qvc@FAuta7XWV1/5sKrf39TiTt69twjjm6iqjtpoVU28Fy8@tKMuFlmoHngX7mYuOESieGumxRwLRVgYgsLqgjPQz1wlepGV8xN1KOI4mIVTdX5FL8IQU0E7V2wz0xD8dzDAYpFGAGYSxr5WATFwtqBC8NdAoFgeJk4EWG3YXkhBhD/dqjcXkG0erCwVhaBstiYhGaRKIl73wCrQRCVZN61iNqAXqJgoKoooXq9Ak9186FGLPWhigiaNzzUlrDx4oopCyAnQSlytNyoNMkCsPE5kUprPympgUQKGFAKN0TpIN0LSgaSb1ZY7a0rUrEKPKHi6Q9neFajZwMEuyx@MmE0GKBIegCwIBmpAhyoAS5RJyxQAa2ynENEm/1Fo/A4lNXt7GvlwG/9ZIE20YAuT4lQHp9rQC0lFgoUMoAa/FREtgogqocqaZ8PlPKymEiDd4I8YVS00F2ggplOM9ICs1Rl5SYlQBJBNWqF1k0JJBwLBImaJHRvJMPEQl1YkA7/VgtI@0woajQTgPt5DeuRaJrNAmBlia@cMCGYI3WxAeItjPDAFqUwji2RpYWkiTBFfU/LUs9QWF/shCRVE0pgU5siBOGgDMMBUCJAzg6YNFBHbIIGh5UgwrIR@iTkGkvGhLKa0AN2NRtAgn8jEx4ghGKCs0JG@sIKG5RBKjkykIJQZwQUf5JREcX2QU0osk5EMEz/Uixwwt/pvqphGoOqFIw9lpqmHM4W7L@rCeqaPvivNIBpGBFs5HC1BN7Ywz/mgEdRfkiRCkmdljGSg7JWJIz4YDkBOXXEPfMyfTJPnnokLpp8OyQoyMwbU63JrpXs5OIY0DpAAHSgw2MC5KcEXSzXtR0t25RAhh0CK67TlkLM3vOOVDUzMGTJi6ZvnEGfWeTcmLiUjn/SFFrxtsdRSNaAuHFKgwdwh8rjoeBsEnSByyozFCN5R0SM/eVlBmJikaHW7GZfL2M7x47AZ5wem5PRZtxvZLpd6Ovx@Hvevnw5Xh9Ps6m48nU7nr7PdNXWXm9np/Bc "Rust – Try It Online") [Lookup table generator](https://play.rust-lang.org/?version=stable&mode=release&edition=2021&gist=d00e709d3560207c376d52d5bce8648f) Yikes, I'm fairly confident rust doesn't even count as primitive recursive with the restrictions, because mutability and function calls are disallowed, meaning there is no way to maintain state across loop iterations. Works up to 10111. My strategy was to form a lookup table by packing the primality of every odd number into array of 128 bit integers, and then just using a good old fashioned mask and shift to recover the value. The `5`s in the hexadecimal representation are dealt with by removing the 1 bit and orring it in at runtime. To deal with operator precedence issues, I abused the fact that blocks are also expressions, so I can use curly braces instead of parentheses. [Answer] # Haskell, 90 bytes ``` \n->[fst c|c<-zip[p|p<-[2..],not$or[b>p-1&&b-1<p|b<-[u*v|u<-[2..p-1],v<-[2..p-1]]]][1..n]] ``` This is an anonymous function which takes an integer `n` as input. How it works: `[p|p<-[2..],not$or[b>p-1&&b-1<p|b<-[u*v|u<-[2..p-1],v<-[2..p-1]]]]` (first example of prime number one-liners at the [Haskell wiki](https://wiki.haskell.org/Prime_numbers_miscellaneous#One-liners) but with the `elem` function replaced) creates an infinite list of primes. `zip` it with the numbers from `1`to `n` to make a list of `(prime, seq. number)` pairs. Remove seq. number, again. Result is a list of primes of length `n`. [Answer] # Rust, 64897 bytes ``` |n|println!{"{:?}",&[2,3,6-1,7,11,13,17,19,23,29,31,37,41,43,47,60-7,0x3b,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,0x97,0x9d,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,0xfb,0x101 ...} ``` (code snipped due to character limit, [full solution here](https://gist.github.com/vintermann/863374c3114b4e421336a2b4ae06e9ec)) The following rust features become unavailable due to the prime restriction: * function calls, as they require ')' * regular bindings, since they require let (e) * macro definitions, they require macro-rules! (a,e,m) * match statements, they require match (a,m) and => (=) * mutability, since it's always introduced with the mut keyword (m). * return (e), break (a,e), continue (e) * else (e) What you can technically use: * if. But without else, they're useless in expression contexts, so only good for side effects. * macros. Standard macros like print! are usually followed by (), but it's actually legal to use {} or [] instead. Without this, the task would be impossible. * closures, in the most narrow sense. You can't call them (requires ()) or bind them(requires let), but you can define a single non-recursive one. Without this, the task would obviously become impossible. * structs. * for loops. These are promising, since they actually allow variable binding, and they take an iterator, which can still be defined with the range syntax. The iterator can even be an expression. * Builtin operators, except +, % and /. The short-circuiting logical operators seem promising. I simply couldn't make anything Turing-complete with these tools. I'm sorry. All that was left was to include the full first 10000 primes, cleaned of 5's. At least you can slice it and have a valid solution, in the most narrow sense possible. I very much would like experts on Turing tarpit diving (or on Rust!) to tell me if I could have done anything better! [Answer] ## GNU APL, ~~75 68 67 65 59 56~~ 55 characters `⎕IO` must be `1`. ``` ∇z←p n z←2,j←3 j←j--2 →2×⍳∨⌿1>z|j z←z,j →2×⍳n>⍴z z←n↑z∇ ``` I came back on this months later realizing that I had an extra space! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` 2ḍƇ`L<3Ʋ# ``` [Try it online!](https://tio.run/##y0rNyan8/9/o4Y7eY@0JPjbGxzYp////3xwA "Jelly – Try It Online") The character codes are `[50, 7693, 391, 96, 76, 60, 51, 434, 35]` ## How it works ``` 2ḍƇ`L<3Ʋ# - Main link. Takes N on the left Ʋ - Define a monad f(k): Ƈ - Filter the range [1, 2, ..., k] on the following: ḍ ` - Divides k cleanly? L - Length <3 - Less than 3? 2 # - Count up k = 2, 3, 4, ... until n integers return true. Return those integers ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 131 bytes ``` [].fill.constructor`M${`for(N\x3D1\x3bM\x3bn-N||--M-print(n\x29\x29for(n\x3Di\x3DN-\x3D-1\x3bi-->2\x3b\x29n\x2fi-~~[n\x2fi]||n--`}` ``` [Try it online!](https://tio.run/##VY5RT8IwFIXf/R2atczbAgLRLONFg@Fh44EnMxY2m5ZUa4vdXJY4@etzF554uF9Ocr6T3I@yKSvh9bGG5rFXMQmCkOzjJR/1Wc6UNoYJZ6va/4ja@SK5/S2U8yTdtQ8vkwHvCcJC2nUACRy9tjWxu3b6hIeqRVUjUkDCeaYBllMMqKGvNJxO2SXlXWcBir@iH/ExpawyWkiyuIcZjW7wHWckM@5AeHZHQz6P4ufX9Wb7VsrD59d3zplspSCKDvYqlk1phnw9XIVBgC2ZjGnU/wM "JavaScript (V8) – Try It Online") [Answer] # [Pyth](http://pyth.herokuapp.com) - 12 bytes Uses pyth's prime factorization function to see if # is prime. Uses `!tPT` trick suggested to me at my answer for primes under million problem. ``` <f!tPTr2^T6Q ``` Since the filter only works for primes under n and not first n, I just looked up the inverse of pi(x) for 10,000 and got 104,000 so I use primes under 10⁶ and get first n. This doesn't actually run, so you should test by replacing `^T6` with `^T3` and restrict n to under 1000. Input from stdin and output to stdout. ``` < Q Slice first n f r2^T6 filter on range 2->10⁶ ! Logical not (gives true if tail is empty) t Tail (all but first, so gives empty if prime fact is len 1) PT Prime factorization of filter var (len 1 if num is prime) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞¦ʒDÑPQ}sôн ``` Input as integers. [Try it online](https://tio.run/##AR4A4f9vc2FiaWX//@KInsKmypJEw5FQUX1zw7TQvf//MTA) or [verify it's valid, and some test cases](https://tio.run/##yy9OTMpM/a/0/1HHvEPLTk1yOTwxILC2@PCWC3v/Kx3a5q0UUJSfXpSYa6WgZG/LpeScn5KqW5CfmVdSrKCRmFepUFCUmZtabK8Jkj@0MvjoviNtxdku9koKj9omAYUKEMzDC3S4lIJSi0tzgHrT8osUog11DA1igRp1Qlz9DA/vgqv0O7ROL0znPwA). Or 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) if we include string inputs, and comply to the other rules: * Non-integer strings; leading whitespaces; or leading `+` are invalid * Leading `0` are valid ``` ∞ʒDÑPQ}s0ì>ôн¦ ``` [Try it online](https://tio.run/##ASIA3f9vc2FiaWX//@KInsqSRMORUFF9czDDrD7DtNC9wqb//ys3) or [verify it's valid, and some test cases](https://tio.run/##yy9OTMpM/a/0/1HHvFOTXA5PDAisLTY4vMbu8JYLew8t@690aJu3UkBRfnpRYq6VgpK9LZeSc35Kqm5BfmZeSbGCRmJepUJBUWZuarG9Jkj@0Mrgo/uOtBVnu9grKTxqmwQUKkAwDy/Q4VIKSi0uzQHqTcsvUog21DE0iAVq1Alx9TM8vAuu0u/QOr0wnVoupeCC1OTMxByF5MTi1GKQQqWknEQlJQVzJSVtIDYAYqCAOUhQs6zyUcMypcP7lZBNqjw8AWzWfwA). **Explanation:** ``` ∞ # Push an infinite positive list: [1,2,3,...] ¦ # Remove the leading 1: [2,3,4,...] ʒ # Filter it by: D # Duplicate the current integer Ñ # Pop and push a list of its divisors P # Take the product of this list of divisors Q # Check if it's still the same as the duplicated integer # (only if the divisors are {1,value}, the value will be a prime) }s # After the filter: swap so the (implicit) input-integer is a the top ô # Split the infinite list into parts of that size н # Pop and leave just the first part ``` *For the program with additional string input validation:* * The `0ì` will prepend a leading `"0"` to the input (to fix the test cases with leading `+`, which would otherwise be interpret as integers); * The `>` will then increase the string-integer by 1 (implicitly converting it to an integer if it's valid first), because we haven't removed the leading `1` with `¦` yet; * The `¦` will then: + Remove the leading `1` from the list for valid inputs; + Or remove the `1` from itself, leaving an empty string for invalid inputs. Because the `s0ì>ô` will have been no-ops, after which `н` will leave not the first part, but the first integer in the list, which is the `1`. *Minor notes:* 1. Uses [05AB1E encoding](https://github.com/Adriandmen/05AB1E/wiki/Codepage), with [the following codepoint-integers](https://tio.run/##yy9OTMpM/f//6L4jbXpHGv//BwA). 2. `ôн` could have been `£`, but unfortunately `£` with code-point 163 is a prime. 3. Even if prime-builtins were allowed, `Å` in the builtin `Åp` with code-point 197 is a prime as well. Although `<ÝØ` would in that case be a short 'valid' alternative: [Try it online](https://tio.run/##yy9OTMpM/f/f5vDcwzP@/zcHAA) or [verify it's 'valid', and some test cases](https://tio.run/##yy9OTMpM/a/03@bw3MMz/isd2uatFFCUn16UmGuloGRvy6XknJ@SqluQn5lXUqygkZhXqVBQlJmbWmyvCZI/tDL46L4jbcXZLvZKCo/aJgGFChDMwwt0uJSCUotLc4B60/KLFKINdQwNYoEadUJc/QwP74Kr9Du0Ti9M5z8A). `<Ý` pushes a list in the range `[0,input)`, whereas `Ø` converts each value in this list to their 0-based value'th prime. ]
[Question] [ Given an input integer `n >= 10`, output the average of all deduplicated rotations of the integer. For example, for input `123`, the rotations are `123` (no rotation), `231` (one rotation) and `312` (two rotations). The average of those is `(123 + 231 + 312) / 3` or `222`. As another example, take `4928`. The rotations are `4928`, `9284`, `2849`, and `8492`. Taking the average of those four numbers equals `6388.25`. For another example, for input `445445`, the deduplicated rotations are `445445`, `454454`, and `544544`, so the output is `481481`. For input `777`, there is only one deduplicated rotation, so the output is `777`. ## Rules * If applicable, you can assume that the input/output will fit in your language's native Integer type. * The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * [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. [Answer] # [Python 3](https://docs.python.org/3/), ~~38~~ 36 bytes ``` lambda*n:10**len(n)//9*sum(n)/len(n) ``` Takes the digits as separate arguments. *Thanks to @Rod for suggesting Python 3, saving 2 bytes.* [Try it online!](https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRK8/K0EBLKyc1TyNPU1/fUqu4NBfEggj8T8svUshTyMxTMDQy1lEwsTSyAJImpkCko2Bubm7FxVlQlJlXopGmXp1nZVaroGunUJ2moZWbWKABFNZRKC4pAhqjqWllUauu@R8A "Python 3 – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 9 bytes ``` 10⊥≢⍴+/÷≢ ``` A monadic function taking a vector of digits as an argument. [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRDg0ddSx91LnrUu0Vb//B2IOv//3SgeHWaAkSqd/Gh9YaPuoAKttYqPOqdq@Ccn1eWWlRSrFCSr5CokJNZXKKQn6aQkpmeCRRLyywC8tPyixRSE4tTQRKlxalc6QqGRsZA0sTSyAJEmZgCEZBhbm4OAA "APL (Dyalog) – Try It Online") I take the average of the digits `+/÷≢`, then repeat it by the length of the input `≢⍴`, and finally convert from base 10. Conceptially, I am taking the sum of the rotations (without carrying): ``` 4 2 9 8 2 9 8 4 9 8 4 2 +8 4 2 9 ----------- 23 23 23 23 ``` This is just `4+2+9+8` repeated 4 times. Then converting from base `10` (which does the carrying for me) and dividing by the length. Although I divide by the length earlier on because it is equivilent and saves bytes. [Answer] # Java 10, ~~163~~ ~~137~~ ~~76~~ ~~72~~ 71 bytes ``` n->(Math.pow(10,n.size())-1)/9*n.stream().mapToInt(i->i).sum()/n.size() ``` -36 bytes thanks to *@Nevay*. -61 bytes thanks to *@OlivierGrégoire* by creating a port of [*@Dennis*' Python 3 answer](https://codegolf.stackexchange.com/a/162438/52210). -1 bytes by taking the input as a List of digits instead of String. **Explanation:** [Try it online.](https://tio.run/##tY9NT8MwDIbv@xU@JijNKAzBVKjEEYntMm6Ig2mzLaVNqsTdNFB/ezH7uCCOIx@W7Lx@8rrCDSZV@TEUNcYIM7TuawRgHZmwxMLA/CcFKH33XhsoRMUNuiNb68cQcPdsI90/sXplQg5OZqzu@fKJhGQLmIODBxhckosZ0lq3fivSS@V0tJ9GSJmkcjy94JSCwUZI3WD74hkpbJJbqWPHxfFJPmQHeMt2GH78Y@NtCQ17FwsK1q1e31AefC92kUyjfUe65ReqnXC6EM5s4Y9Jfk8XNcZ9PVVX6lryys5Jnagpc@/@gTtRN2ofz86@VbxP1H7UD98) ``` n-> // Method with String parameter and double return-type (Math.pow(10,n.size())-1)/9 // Repunits the same length as the input-size *n.stream().mapToInt(i->i).sum() // multiplied by the sum of digits /n.size() // divided by the input-size ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` d´MKA ``` [Try it online!](https://tio.run/##yygtzv6fm/@oqTHlf8qhLb7ejv///482NDLWMbE0stAxNTEBIh1zc/NYAA "Husk – Try It Online") ### Explanation ``` d´MKA A Take the average of the digits ´MK Replace each element of the original list with the average d Join the list to get a number ``` --- # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` A§modṙŀ ``` [Try it online!](https://tio.run/##yygtzv6fm/@oqTHlv@Oh5bn5KQ93zjza8P///2hDI2MdE0sjCx1TExMg0jE3N48FAA "Husk – Try It Online") ### Explanation ``` A§modṙŀ ŀ Take the range [1..length(input)] §m ṙ Rotate the input by each element of the range od Convert each list of digits to a number A Take the average of the list ``` [Answer] # [R](https://www.r-project.org/), ~~84~~ ~~73~~ 64 bytes ``` function(D,K=sum(D|1))mean(array(D,K+1:0)[1:K,1:K]%*%10^(K:1-1)) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NFx9u2uDRXw6XGUFMzNzUxTyOxqCixEiSubWhloBltaOWtA8SxqlqqhgZxGt5WhrpAlf/TNJI1zHWAUFOTC8Q20bHUMdKxAMoAAA "R – Try It Online") Input as list of digits. Thanks to MickyT for shaving off 11 bytes! 8 bytes shaved by Dennis' proof that deduplication is unnecessary. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes ``` Ṗ⌊ṁ ``` *-2 bytes thanks to @lyxal* [Try it online!](https://vyxal.pythonanywhere.com/#WyLhuaAiLCIiLCLhuZbijIrhuYEiLCIiLCIxMjMiXQ==) Explanation ``` Ṗ # Permutations ⌊ # Convert each to an integer ṁ # Mean ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` vÀD}\OIg/ ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/7HCDS22Mv2e6/v//JiamQAQA "05AB1E – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ñJä⌠╤► ``` [Run and debug it](https://staxlang.xyz/#p=a44a84f4d110&i=%22123%22%0A%224928%22%0A%22445445%22%0A%22777%22&a=1&m=2) This program takes a quote-delimited string as input, and expresses the average as a reduced fraction. e.g. `777/1` It's not necessary to de-duplicate the rotations. It never changes the result. Unpacked, ungolfed, and commented, it looks like this. ``` :) get all character rotations {em convert strings back to integers :V mean - integer inputs means result will be rational ``` [Run this one](https://staxlang.xyz/#c=%3A%29%09get+all+character+rotations%0A%7Bem%09convert+strings+back+to+integers%0A%3AV%09mean+-+integer+inputs+means+result+will+be+rational&i=%22123%22%0A%224928%22%0A%22445445%22%0A%22777%22&a=1&m=2) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 bytes ``` ṙJḌÆm ``` [Try it online!](https://tio.run/##y0rNyan8///hzpleD3f0HG7L/X90j8vhdpVHTWvc//83NDLWUTCxNLIAkiamQKSjYG5uDgA "Jelly – Try It Online") ### How it works ``` ṙJḌÆm Main link. Argument: A (digit array) J Yield the indices of A, i.e., [1, ..., len(A)]. ṙ Rotate A 1, ..., and len(A) units to the left, yielding a 2D array. Ḍ Convert each rotation from decimal to integer. Æm Take the arithmetic mean. ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 15 bytes ``` {.sum/$_*1 x$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoFZk@79ar7g0V18lXstQoUIlvva/NVdxIkhGQ8nQyFhJLzk/N0nPJ7O4RPM/AA "Perl 6 – Try It Online") The average is the digit average applied to each decimal position, so digit average times 111.... `1 x $_` produces a string of 1s which get coerced to strings by the multiply. Takes a list of digits as input. A sequence would require a .cache before the sum, and a number or string input would need a .comb. [Answer] # [Perl 5](https://www.perl.org/) `-lpF`, ~~24~~ 22 bytes ``` #!/usr/bin/perl -lpF $_=1x@F/s/./+$&/g*eval ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tawwsFNv1hfT19bRU0/XSu1LDHn/39DI2MuE0sjCy4TE1Mg4jI3N@f6l19QkpmfV/xfN6fA7b@ur6meoYGeAQA "Perl 5 – Try It Online") Doing it as a list of digits is only 1 byte shorter and feels like cheating: ``` #!/usr/bin/perl -p $;+=$_}{$_=1x$./$.*$ ``` [Try it online!](https://tio.run/##K0gtyjH9/1/FWttWJb62WiXe1rBCRU9fRU9L5f9/Ey4TLlMuMPkvv6AkMz@v@L9uwX9dX1M9QwM9AwA "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 60 bytes ``` ->n{a=b=c=0.0;a,b,c,n=a+n%10,b*10+1,c+1,n/10while n>0;a*b/c} ``` [Try it online!](https://tio.run/##DcpBCsIwEEDRq2Tjph3bmRpJRaYXCVlkgkVBhyKIkbZnj4H/dv/9kV@ZuRwnXSMLJ8YOrxEEEijHVg@EIA1hS5Aq7Qm/98fzZnSqXyN92oun4QT2Moxg7bkGzrnQveKybnlbjM9gZp9D2Msf "Ruby – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 22 bytes ``` FromDigits[0#+Mean@#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfrSg/1yUzPbOkONpAWds3NTHPQTlW7X9AUWZeSbSyjoKSgq6dgpKOQlq0cmysgpqCvoNCdbWhjpGOca2OQrWJjiWQaQFhmuiY6oBJENdcBwhra/8DAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 33 bytes ``` ->n{10**(k=n.size)/9*n.sum*1.0/k} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6v2tBAS0sj2zZPrzizKlVT31ILyCrN1TLUM9DPrv1foJAWHW2oY6RjHBvLBeaY6FgCuRYIromOqQ6YhAmZ6wBhbOx/AA "Ruby – Try It Online") A port of [Dennis's Python 3 answer](https://codegolf.stackexchange.com/a/162438/77598) ### Here's my lame attempt (74 bytes) ``` ->s{a=(1..s.size).map{|i|s.chars.rotate(i).join.to_i}|[];a.sum*1.0/a.size} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664OtFWw1BPr1ivOLMqVVMvN7GguiazplgvOSOxqFivKL8ksSRVI1NTLys/M0@vJD8@s7YmOtY6Ua@4NFfLUM9APxGssfZ/gUJatJKhkbFSLBeYaWJpZAFnm5gCEYxnbm6uFPsfAA) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 43 bytes ``` x=>eval(x.join`+`)*'1'.repeat(n=x.length)/n ``` [Try it online!](https://tio.run/##BcFRCoAgDADQ46hFi6KPQuwiESi1SpEtSsLb23vBfe7dHn@nhnjHcpiSzYyfi3IBgLxCYE@2tqoSnYAHb3RJkskQkc50qZaK3phejgiRT3lIMUz9KJTS5Qc "JavaScript (Node.js) – Try It Online") > > Can we take input as a list of digits? – Dennis♦ 7 mins ago > > > @Dennis Sure, that's fine. Go save some bytes. :p – AdmBorkBork 3 mins ago > > > [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 bytes Takes input as an array of single digit strings. ``` xpUÊ)÷UÊ ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=eHBVyin3Vco=&input=WyI0IiwiNCIsIjUiLCI0IiwiNCIsIjUiXQ==) --- ## Explanation ``` :Implicit input of array U pUÊ :Repeat each string length of U times x ) :Reduce by addition ÷UÊ :Divide by the length of U ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~21~~ 14 bytes[SBCS](http://github.com/abrudz/sbcs) ``` +/≢÷⍨⍳∘≢(⍎⌽)¨⊂ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRt/Uediw5vf9S74lHv5kcdM4A8jUe9fY969moeWvGoqwmo6tAKdUMjY3UFdRNLIwsQZWIKRECGubm5OgA "APL (Dyalog Unicode) – Try It Online") Tacit prefix function. Takes input as a string. Thanks to Adám for [an enlightening 7 byte save](https://chat.stackexchange.com/transcript/message/44041397#44041397). ### How? ``` +/≢÷⍨⍳∘≢(⍎⌽)¨⊂ ⍝ Main fn, example argument '123' ⊂ ⍝ Enclose the argument (turns it into a scalar) ¨ ⍝ Use each of the left arguments to ( ⌽) ⍝ Rotate, then ⍎ ⍝ Convert strings into numbers ⍳∘≢ ⍝ Tally (≢) the argument, then index (⍳) from 1. ⍝ Returns 1 2 3 for a 3 digit argument, and rotates the argument 1, 2, then 3 times. ⍨ ⍝ Use the result as left argument for ÷ ⍝ Divide ≢ ⍝ By the number of rotations +/ ⍝ And sum the results ``` [Answer] # Python 2, ~~83~~ 77 bytes ``` def f(a):b={int(`a`[i:]+`a`[:i])for i in range(len(`a`))};print sum(b)/len(b) ``` EDIT: -6 bytes thanks to @ovs [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes ``` I∕×ΣθI⭆θ1Lθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwyWzLDMlVSMkMze1WCO4NFejUFNHASwTXAJUle6bWKBRqKOgZKikqQmU8UnNSy/JACrS1LT@/9/E0sjiv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ θ θ Input as a string Σ Sum of digits ⭆ 1 Replace each character with the literal `1` I Cast to integer × Multiply L Length ∕ Divide I Cast to string Implicitly print ``` [Answer] # [J](http://jsoftware.com/), 10 bytes ``` 10#.#$+/%# ``` This is a port of H.PWiz's great APL solution to J. Takes a list of digits as an argument. ## Explanation: `+/%#` the average of the digits (divide `%` the sum of the digits `+/` by their number `#`) `#$`creates a list of copies of the average according to the number of digits `10#.` convert form base 10 [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DQ2U9ZRVtPVVlf9rcilwpSZn5CukKZgAoSmEhAkZKhgpGCPkLYFcCxjXHAT/AwA "J – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 34 bytes Takes input as a list of digits. ``` n->fromdigits([vecsum(n)|x<-n])/#n ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1y6tKD83JTM9s6RYI7osNbm4NFcjT7OmwkY3L1ZTXznvf2JBQU6lRp6Crp1CQVFmXgmQqQTiKCmkARVq6ihERxvqGOkYxwJZJjqWQKYFhGmiY6oDJkFccx0gjI3V/A8A "Pari/GP – Try It Online") [Answer] ## C++, ~~218~~ 208 bytes -10 bytes thanks to Zacharý ``` #include<set> #include<cmath> float a(int m){std::set<int>a;int n=m,t,c=0;for(;n>0;n/=10)++c;for(;n<c;++n){a.insert(m);t=m%10;m=m/10+std::pow(10.f,c-1)*t;}int s=0;for(int v:a){s+=v;}return float(s)/a.size();} ``` And, to test : ``` int main() { printf("%f\n%f\n%f\n%f\n",a(123),a(4928),a(445445),a(777)); } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` œÅA ``` Port of [*@tybocopperkettle*'s Vyxal answer](https://codegolf.stackexchange.com/a/252104/52210), so make sure to upvote him/her as well! [Try it online](https://tio.run/##yy9OTMpM/f//6OTDrY7//xsaGQMA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/o5MPtzr@1/kfbWhkrGNiaWShY2JiCkQ65ubmsQA). **Explanation:** ``` œ # Get all permutations of the (implicit) input # e.g. 123 → ["123","132","213","231","312","321"] ÅA # Take the average of this list # → 222.0 # (which is output implicitly as result) ``` [Answer] # [Thunno](https://github.com/Thunno/Thunno) `E`, \$ 9 \log\_{256}(96) \approx \$ 7.41 bytes ``` DLzP.ZDAA ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSq1LsgqWlJWm6FitdfKoC9KJcHB0hfKjwgiUmlkYWEDYA) Port of Vyxal. #### Explanation ``` DLzP.ZDAA # Implicit input. The E flag keeps it as a string. DL # Duplicate and get the length of the input string. zP # Permutations of the input with the same length. .ZD # Converted to integers from lists of characters. AA # Get the average of this list of integers. # Implicit output. ``` [Answer] # TI-Basic, 10 bytes ``` mean(Ans)int(1/9₁₀^(dim(Ans ``` Takes input in `Ans` as a list. Port of [Dennis's Python 3 answer](https://codegolf.stackexchange.com/a/162438/52210). [Answer] # Pyth, 12 bytes ``` csms.<zdlzlz ``` Probably improvable. ``` c lz Divide by the length of the input: s Reduce by + m lz Map over d = [0 ... the length of the input]: s.<zd Shift the input d characters to the left and cast to int ``` [Try it here!](http://pyth.herokuapp.com/?code=csms.%3Czdlzlz&input=123&test_suite=1&test_suite_input=123%0A4928%0A445445%0A777&debug=0) [Answer] # J, 23 Bytes ``` (+/%#)".~.(|."0 1~i.@#) ``` Takes input as a string ### Explanation ``` (|."0 1~i.@#) | All rotations ~. | Deduplicate ". | Convert each to int (+/%#) | Average ``` [Answer] # Matlab, 65 bytes ``` c=num2str(n);l=nnz(c);mean(str2num(c(mod((1:l)+(0:l-1)'-1,l)+1))) ``` Gonna work on this, pretty sure it can be done better. [Answer] ## Clojure, 139 bytes ``` #(let[n(count %)G(set(apply map list(for[i(range n)](take n(drop i(cycle %))))))](/(apply +(for[g G](read-string(apply str g))))(count G))) ``` Quite sub-optimal language features for converting sequences of characters to integers. [Answer] # dc, 37 bytes This is a full program, reading input and printing the output: ``` ?1sd[O~rzsadO<x+ldO*1+sd]dsxxOkld*la/p ``` It works by separating the number into its digits, and multiplying the mean of the digits by the appropriate length repdigit (which is built up in `d` as we go). ``` ? # read input 1sd # initialize d=1 [ ]dsxx # define and execute recursive macro x: O~r # remainder and quotient of /10 zsa # a = number of digits dO<x # recurse if needed +ldO*1+sd # increment repdigit d Ok # after executing x, set precision ld*la/ # multiply by repdigit; divide by a p # print the result ``` ]
[Question] [ In [The Settlers of Catan](https://en.wikipedia.org/wiki/Catan) board game, there are five resource types: Brick, Log, Ore, Wheat, and Sheep. Building a settlement costs a Brick, a Log, a Wheat, and a Sheep. However, you can also trade in four identical resources to get a resource of a different type. For instance, if you had four ores in your hand, you could trade all of them in and get one sheep. Your job is to determine whether or not I can build a settlement, given my hand. ## Your Task Input will be a sequence of the letters `B`, `L`, `O`, `W`, and `S`, taken in any reasonable format. These letters correspond to the five resource types given above. You should output whether or not I have the resources necessary to build a settlement, taking into account the possibility of trading four of a kind. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. ## Notes * You do not have to output what trades I need to perform or how many settlements I could build. A simple "yes" or "no" will do. * You may *not* assume that the input is in any specific order. In particular, you may not assume that resources of the same type are grouped together, so `OBLSO` is a valid input. * This is [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'"), so you may use any value you want to mean "yes" and "no", as long as the two chosen values are distinct and consistent. * The only rules we're concerned with here are the ones listed above. More complicated Settlers of Catan rules like trading with other players or at harbours are not relevant here. * The input characters (`B`, `L`, `O`, `W`, `S`) can be substituted with other values if it is easier for your particular language of choice, so long as there are five distinct inputs. If you use other input values, please specify them in your answer. ## Examples ``` BLWS -> Yes OOOOWLB -> Yes (trade four O for a S) OOW -> No BBBO -> No (empty input) -> No BBBBLW -> No BBBBBLW -> Yes (trade four B for a S) OOOOOOOOOOOOOOOO -> Yes (sixteen O; trade for B, L, W, S) BLBLBLBLBL -> Yes (trade L for W and B for S) BLSWBLSWBLSW -> Yes (extra, unused resources are ignored) ``` [Answer] # [Python 2](https://docs.python.org/2/), 54 bytes ``` lambda s:sum((s+"BLSW"*3).count(n)/4for n in"BLSWO")>3 ``` [Try it online!](https://tio.run/##XU/LCsIwELz3K5ZAMdH6wOpFqIccPAV6UMhBRaq2WKipZNODX1/TSG1wQkJ2hp3deb3No1bLtkhObZU9r/cMcIPNk1KcEC72koxjNrvVjTJUsfmqqDUoKJXTUsK2cWtyNJdbhjlCAkdqFbkn0UE3OYsoSS2k4D0BHSNJtMsq/Ja/v@20EPKPcIzv5mNQuOiPN6pbsr8@zXnqr@CmCCGldJbwVc5B0KX9xYtA59hUxqYfSNwEYPHSpTIwCpcLhHC61u4ZQQjUay@GgvVmrP0A "Python 2 – Try It Online") For each of our resources, we count the number of *“freedoms”* given by having *n* of that resource. A freedom represents an *opportunity* to fill one of the brick-log-wheat-sheep slots we need to fill in order to settle, accounting for the fact that we can convert our resources. For all of BLSW, having *one* of the resource gives us one such freedom, and every additional excess of 4 gives us another. The freedom-counting rule is like this: ``` * Having 1 brick/log/wheat/sheep gives 1 freedom. * Having 5 bricks/logs/wheat/sheep gives 2 freedoms. * Having 9 bricks/logs/wheat/sheep gives 3 freedoms. * … ``` So *n* bricks/logs/wheat/sheep give ⌊(n+3)/4⌋ freedoms. For ores, only the excess foursomes count. The freedom-counting rule is like this: ``` * Having 4 ores gives 1 freedom. * Having 8 ores gives 2 freedoms. * Having 12 ores gives 3 freedoms. * … ``` So *n* ores give ⌊n/4⌋ freedoms. **Theorem:** we can settle if and only if we have ≥ 4 such “freedoms”. So we count our freedoms and check if there are ≥ 4 of them. To handle counting ores as ⌊n/4⌋ but other resources ⌊(n+3)/4⌋, we artificially inflate the counts for the other resources by 3 and then count ⌊n/4⌋ for all of them. We do this by mapping `(s+"BLSW"*3).count` instead of `s.count`. **Proof**: * Suppose we can settle. Then for each of [B, L, S, W], we either (a) used 1 of that resource that we already had, or (b) sacrificed 4 of some other resource (including ores) to create it. In either case, we count at least 1 freedom by the above rules. So we have ≥ 4 freedoms. * Suppose we have 4 freedoms, k of which are due to “excesses” (every freedom from ores is an excess, and every freedom from other resources *past* the first one also is) and 4−k of which are witness of owning at least one brick/log/wheat/sheep (the one that gave the “first freedom”). Then we fill 4−k slots with the brick/log/wheat/sheep that gave us our first freedom, and fill the remaining k slots by converting our excesses. All 4 slots are filled and we can settle. We can obviously still do this if we have *more* than 4 freedoms. This proof sucks, but I’m sleepy. I’m sure there’s a better explanation. [Answer] # [Python 2](https://docs.python.org/2/), ~~52~~ 51 bytes -1 byte thanks to [Luke](https://codegolf.stackexchange.com/users/63774/luke) (replace `>=0` with `<0`, inverting the `False`/`True` results) ``` lambda h:sum(~-(h+"O").count(c)/4for c in"BOWLS")<0 ``` An unnamed function taking a string of the characters **B**, **O**, **W**, **L**, and **S** (as in the OP) and returning `False` if you can settle or `True` if not. **[Try it online!](https://tio.run/##XU65DsIwDJ3hKywvTUQLCDFVwJA5UoYOWVhCSpVKNKl6DF349ZD0WLBlvcOW/NppMM5efHV/@o9qXqUCk/djQ74ZMQcUSI/ajXYgmp6uletAQ22RCckLpLezj5ZRtgwuEGRcFpgCilCSs4XKCIwxEXHl4XBjKxV/Na/51osq5DZI8/2u7Wo7zN9TSLJHkkJFoqIQA6F1CCEdTu8evf8B "Python 2 – Try It Online")** (coerces the output to the `yes/no` of the OP). ### How? This is a port of my Jelly answer. We need to make up for any missing **B**, **W**, **L**, or **S** from the remainder after using one of each of them. As such we can add an extra **O** to our hand, then reduce all the counts by one, then integer divide all counts by four and then sum - if the result is zero or more we can settle (either because there were no missing required resources or because we can trade to acquire the missing one(s)). ``` lambda h:sum(~-(h+"O").count(c)/4for c in"BOWLS")<0 lambda h: - a function that takes h (a string) for c in"BOWLS" - for each letter, c, in "BOWLS": h+"O" - append "O" to h ( ).count(c) - count c instances - - negate ~ - bitwise not (this is -x-1) /4 - integer divide by 4 - (NB: -1 and 0 are not affected) sum( ) - sum the five values <0 - less than zero? (inverted result) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ;5ċЀ5’:4S>- ``` A monadic link accepting a list of numbers representing the resources you own and returning `1` if you can settle down or `0` if not. The resources are `1, 2, 3, 4, 5` where `5` represents **Ore**. **[Try it online!](https://tio.run/##y0rNyan8/9/a9Ej34QmPmtaYPmqYaWUSbKf7////aEMdBSMdBexkLAA "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##y0rNyan8/9/a9Ej34QmPmtaYPmqYaWUSbKf7P9MByH3UMMfJJzzY/1HD3MPtD3d3A/mVqcVAMi8fKMT1cPeWo3sOtwMVqmRBVCvo2ikAZSL//wfp4/IHgnAfJyAdzuXk5OTPBSKBMmAKRPujAS4nHxgEMoPDYRgA "Jelly – Try It Online") (using the OP IO). ### How? The idea is to first count the resources by type, then reduce all counts of **B**, **L**, **W**, and **S** by one - if we counted none for any of these four then they will now have entries of **-1** - we need to acquire them from our remaining resources (This is actually achieved by adding an extra **O** (`5`) and reducing *all five* counts by **1**). Next we integer-divide all these values by four to see how many units we may trade for with each of our remaining counts by resource type while not affecting the **-1** and **0** counts (note that **-1** integer-divided by four is **-1**, not **0**). Lastly we add up the values and check if the result is greater than or equal to zero (here greater than **-1** can be used since we always have integers). ``` ;5ċЀ5’:4S>- - Link: list of numbers (BLWSO:12345) e.g. [3,2,2,2,2,2,5,5,5,5] (WLLLLLOOOO) ;5 - concatenate a five [3,2,2,2,2,2,5,5,5,5,5] 5 - literal 5 Ѐ - map across implicit range(5) = [1,2,3,4,5]: ċ - count [ 0, 5, 1, 0, 5] ’ - decrement (vectorises) [-1, 4, 0,-1, 4] :4 - integer divide by four [-1, 1, 0,-1, 1] S - sum 0 - - literal -1 -1 > - greater than? 1 ``` [Answer] # [Pyth](https://pyth.readthedocs.io), 14 bytes ``` gsm/t/+Q4d4U5Z ``` **[Try it here!](https://pyth.herokuapp.com/?code=gsm%2Ft%2F%2BQ4d4U5Z&input=%5B0%2C+1%2C+3%2C+2%5D&test_suite_input=%5B0%2C+1%2C+3%2C+2%5D%0A%0A%5B4%2C+4%2C+4%2C+4%2C+3%2C+1%2C+0%5D%0A%0A%5B4%2C+4%2C+3%5D%0A%0A%5B%5D%0A%0A%5B0%2C+0%2C+0%2C+0%2C+1%2C+3%5D%0A%0A%5B0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+3%5D%0A%0A%5B4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%5D%0A%0A%5B0%2C+1%2C+0%2C+1%2C+0%2C+1%2C+0%2C+1%2C+0%2C+1%5D%0A%0A%5B0%2C+1%2C+2%2C+3%2C+0%2C+1%2C+2%2C+3%2C+0%2C+1%2C+2%2C+3%5D%0A&debug=0&input_size=2) or [Verify all the test cases.](https://pyth.herokuapp.com/?code=%3C3s%2FR4%2FL%2BQ%2a3U4U5&test_suite=1&test_suite_input=%5B0%2C+1%2C+3%2C+2%5D%0A%0A%5B4%2C+4%2C+4%2C+4%2C+3%2C+1%2C+0%5D%0A%0A%5B4%2C+4%2C+3%5D%0A%0A%5B%5D%0A%0A%5B0%2C+0%2C+0%2C+0%2C+1%2C+3%5D%0A%0A%5B0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+3%5D%0A%0A%5B4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%5D%0A%0A%5B0%2C+1%2C+0%2C+1%2C+0%2C+1%2C+0%2C+1%2C+0%2C+1%5D%0A%0A%5B0%2C+1%2C+2%2C+3%2C+0%2C+1%2C+2%2C+3%2C+0%2C+1%2C+2%2C+3%5D%0A&debug=0&input_size=2)** # [Pyth](https://pyth.readthedocs.io), ~~31 27 17~~ 16 bytes ``` <3s/R4/L+Q*3U4U5 ``` **[Verify the test cases.](https://pyth.herokuapp.com/?code=%3C3s%2FR4%2FL%2BQ%2a3U4U5&test_suite=1&test_suite_input=%5B0%2C+1%2C+3%2C+2%5D%0A%0A%5B4%2C+4%2C+4%2C+4%2C+3%2C+1%2C+0%5D%0A%0A%5B4%2C+4%2C+3%5D%0A%0A%5B%5D%0A%0A%5B0%2C+0%2C+0%2C+0%2C+1%2C+3%5D%0A%0A%5B0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+3%5D%0A%0A%5B4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%5D%0A%0A%5B0%2C+1%2C+0%2C+1%2C+0%2C+1%2C+0%2C+1%2C+0%2C+1%5D%0A%0A%5B0%2C+1%2C+2%2C+3%2C+0%2C+1%2C+2%2C+3%2C+0%2C+1%2C+2%2C+3%5D%0A&debug=0&input_size=2)** # How do these work? ### Explanation #1 ``` gsm/t/+Q4d4U5Z - Full program. m U5 - Map over the range [0, 5) with a variable d. +Q4 - The input, with a 4 appended (this corresponds to O) / d - Count the occurrences of the current value in ^. t - Decrement. / 4 - Integer division by 4. s - Sum g Z - Is non-negative (is the sum ≥ 0)? - Output implicitly. ``` ### Explanation #2 ``` <3s/R4/L+Q*3U4U5 - Full program. *3U4 - The range [0, 4) repeated 3 times. +Q - The input with ^ appended. /L U5 - Count the occurrences of each element in [0, 5) in ^. /R4 - Integer division of each by 4. s - Sum. <3 - Is higher than 3? - Output implicitly. ``` --- These are the codes used by my program: ``` B -> 0 L -> 1 S -> 2 W -> 3 O -> 4 ``` [Answer] # Java 8, 101 bytes Lambda from `int[]` to `boolean`. Assign to `Function<int[], Boolean>`. ``` a->{int h,f[]=new int[5],i=0;for(int x:a)f[x]++;for(h=f[4]/4;i<4;)h+=--f[i]>>-1|f[i++]/4;return~h<0;} ``` [Try It Online](https://tio.run/##hVKxboMwEJ3JV9wIwlCS0CUEhlbq1ikjYnCJCU4dg8CkiVKq7O1X9keobUjaRJUinazze3fnu@db4y12ipLw9fK1K5sXRlNIGa5reMaUw2FklBXdYkGgFlhIMqMcM1jLNLcRlLlZw1NBC@4@Dc6cchEnCB6KghHMI0gxXxAhGIGww050kDzkKIuTkJM3UNH3CaKhF2RFZSpyN8NWFu8S29ZQHmaxn9z5AZ37gZXboeNkMU2iaDp@l45tK64ioqn4R/59/Po@fs69oO2MYCS770camt8WdAkbOZi5EBXlqzgBXK1qS81p6L4lkuKa1BDCqTuFKd44eAjGCCYIpi3SgI/gbBNNehfMZLjJxN78AbjGh8r/wJfM3wdv22@58anQ9XkRMtVT3PZ1UqvkNeQHgalVAvwohYNZr18vqbHY14Js3KIRrtwjLhg3z@vg4rJke1OnWVagSo6ktd0P) ## Input and output Input is an array of integers from 0 to 4, inclusive. 4 represents Ore, and the other mappings are immaterial. My test cases are direct translations of those in the question, with 0 as Brick, 1 as Log, 2 as Wheat, and 3 as Sheep. Output is whether a settlement can be built. ## Ungolfed ``` a -> { int h, f[] = new int[5], i = 0 ; for (int x : a) f[x]++; for (h = f[4] / 4; i < 4; ) h += --f[i] >> 31 | f[i++] / 4; return ~h < 0; } ``` ## Explanation `h` is the number of resource quadruples available to trade. We iterate over each resource type (except Ore), incrementing `h` for each quadruple of extra resources we have, and decrementing where no resources are present. Then our result is whether `h` is nonnegative. The line ``` h += --f[i] >> 31 | f[i++] / 4; ``` adjusts `h` appropriately regardless of whether there are no resources (shortage) or there is at least one resource (surplus). `f[i]` is decremented to account for the required resource in the surplus case, producing -1 in the shortage case. The signed right shift reduces the expression to 0 (surplus case) or -1 (shortage case), so that a bitwise OR with the number `f[i++] / 4` of surplus quadruples (in the surplus case) has no effect in the shortage case but results in the number itself in the surplus case. ## Acknowledgments * -9 bytes thanks to Nevay, master of bits [Answer] # [Retina](https://github.com/m-ender/retina), 34 bytes ``` ^ BBBLLLWWWSSS O`. ((.)\2{3}.*){4} ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP47LycnJx8cnPDw8ODiYyz9Bj0tDQ08zxqjauFZPS7PapPb/fyefcKAMEIT7OAHpcJAWfy4QCZQBUyDaHw1wOfnAIJAZHA7DAA "Retina – Try It Online") Explanation: Building a settlement requires 4 resources which are either your first B, L, W, or S, or any other 4 resources of the same type. This is equivalent to adding three of each of those four types of resources, and then counting to see whether you have four sets of four. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes ``` œ-4R¤©Ġs€4ẎL€>3+®e€$S>3 ``` [Try it online!](https://tio.run/##y0rNyan8///oZF2ToENLDq08sqD4UdMak4e7@nyAtJ2x9qF1qUCGSrCd8f///6MNdRSMdBRMdBSMdRSws2MB "Jelly – Try It Online") Refer to the following table for the values: ``` B: 1 L: 2 O: 5 W: 3 S: 4 ``` [Answer] # [Retina](https://github.com/m-ender/retina), 43 bytes ``` O`. O{4} a }`([^a])\1{4} $1a O D`[^a] .{4} ``` [Try it online!](https://tio.run/##K0otycxL/P/fP0GPy7/apJYrkas2QSM6LjFWM8YQxFcxTOTy5@JySQCJcekBhf7/dwIBn3AA "Retina – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 79 78 bytes **Edit:** -1 byte thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) ``` lambda x:3<sum((a>0)+~-a*(a>1)//4for a in map(x.count,"BLSW"))+x.count("O")//4 ``` [Try it online!](https://tio.run/##XY87C8IwFIVn@ytCpsRGq9SpWIcOTgWHChlUJNYUC33RJFAX/3pM7RNPCNx8OfdyT/WWr7JwdeJfdcbyx5OBxnP3QuUIscMG258VW5pqix1nl5Q1YCAtQM4q1KzjUhWSwCCMKMTY7gGCJ9iateRC3mMmuAA@uCDjoxEk51pxTIzJiIbBAEBLKCRHlonuOdam0yikf@BH5tPmmn6CcDhzFtHh9vRmWW26cWdSc6Ey2YadcnjWoqpTEzFBIzS7dlasvw) [Answer] # [MATL](https://github.com/lmendo/MATL), 19 bytes ``` Oh!5:=s4&\w4:)ghs3> ``` Input is a numeric row vector where the letters are represented as numbers as follows: ``` B: 1 L: 2 W: 3 S: 4 O: 5 ``` Output is `1` for truthy, `0` for falsy. Try it online!: [verify all test cases](https://tio.run/##y00syfmf8N8/Q9HUyrbYRC2m3MRKMz2j2Njuv0vI/2hDBSMFYwWTWK5oUwUINAaKGEL5xkDaUAEETYEsOAesCYkH48OMwAHBOowU0DBU1ARoMRodCwA). ### How it works 1. Count ocurrences of each resource. 2. Div-mod them by 4. 3. Count how many of the remainders for the first four resources (letters `BLWS`) are nonzero. This gives a number *c*. 4. Sum the quotients. This gives a number *s*. 5. Output whether *c*+*s* ≥ 4. ### Commented code ``` Oh % Append 0 to implicit input. This is just in case inpout is empty ! % Convert into column vector 5: % Push row vector [1 2 3 4 5] = % Compare for equality, element-wise with broadcast s % Sum of each column. Gives number of times that each entry of % [1 2 3 4 5] appears in the input 4&\ % Mod-div 4, element-wise. Pushes vector of remainders and then vector % of quotients of division by 4 w % Swap. Brings remainders to top 4:) % Get the first four entries g % Convert to logical. This transforms non-zero values into 1 h % Concatenate with vector of quotients s % Sum 3> % Does the result exceed 3? Implicitly display ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 61 bytes ``` 510ap\~1(n; 1+$ap> i:0(?v8%:ag 0:ga:v?=5:+1<$-}$,4-%4:-}-${:) ``` [Try it online!](https://tio.run/##S8sszvj/39TQILEgps5QI8@ay1BbJbHATiHTykDDvsxC1SoxncvAKj3Rqsze1tRK29BGRbdWRcdEV9XESrdWV6XaSvP/f0MjGAQA "><> – Try It Online") Uses the following resource mapping: ``` O -> 0 B -> 1 L -> 2 W -> 3 S -> 4 ``` It doesn't really matter what mapping is used, as long as they're in the range `0-4`, and `0` is used for O. Makes use of the fact that looking for the combination `BLWS` is the same as looking for the combination `OBLWS` while already having an `O` in hand. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes 0 -> Ore 1 -> Brick 2 -> Log 3 -> Wheat 4 -> Sheep Returns 0 when false, and 1 otherwise. ``` {γvyDĀi¼¨}g4÷}¾)O3› ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/@tzmskqXIw2Zh/YcWlGbbnJ4e@2hfZr@xo8adv3/b2gEgwA "05AB1E – Try It Online") **Explanation:** ``` {γvyDĀi¼¨}g4÷}¾)O3› Implicit input, e.g. 0030201 { Sort -> 0000123 γ Split into chunks of consecutive elements: [0000, 1, 2, 3] vy For each chunk... DĀ ...is different than 0? i¼¨} ...if true: increment the counter by 1, and remove 1 element from the chunk g4÷ ...divide the number of elements by 4 } End For ¾ Push the counter ) Wrap the entire stack in a list O Sum of that list 3> True if > 3 Implicit output ``` # Non-competive solution: 17 bytes There was a bug in 05AB1E when I first submitted that solution, where some operators badly handled empty inputs. This resulted in this solution answering `1` on an empty input. This has now been fixed, so this solution works just fine. The difference here is that we add an ore prior to removing one of each resource, indiscriminately, counting the number of resources removed that way. We then decrement the counter by 1 to get the correct number of B, L, W and S. ``` 0«{γε¨g4÷¼}O¾<+3› ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f4NDq6nObz209tCLd5PD2Q3tq/Q/ts9E2ftSw6/9/QyMYBAA "05AB1E – Try It Online") [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 116 bytes ``` s=>Array.from("BLOWS").reduce((m,c)=>Math.floor(((s+"BLSW".repeat(3)).match(new RegExp(c,'g'))||"").length/4)+m,0)>3 ``` [Try it online!](https://tio.run/##XZBRa4MwEMef56cIUmhCnevo3orChL45hPUhDyJrSE/tFo0k6bZi@9ldtHOVXQjc/e7uf7m8s0@muTo05l43hz2oStYfcOryoNNB@KwUO/m5khV2ozihW5f4CvZHDhhXHidB@MJM6edCSoUx1gtbtaWurWmAGbwixK@Y4SWu4Qu9QrH5bjD35sWckPPZtWIC6sKUD09kUXlLEq46AQYZ0OaNMw0aBShNraYd7Bl1hMxL3cQajaMRoJ5Q18uZ0Nfwz7ed1mL6Dwxkqja1WyaKxzMZ1a833imOomT6hGFKHFNKB0l0zWSOc1vNz6XaMPs1PQrC1rnjstZSgC9kgXeztufpMrugWZvj34D00eA/ZpcdWTsXsu5@AA "JavaScript (SpiderMonkey) – Try It Online") Super Clunky bad answer. I'm sure it could be cleaned up more. Method inspired by Lynn's answer in this thread. [Answer] # [Kotlin](https://kotlinlang.org), ~~131~~ 129 bytes ## Submission ``` fun r(i:String):Any=i.split("").groupingBy{it}.eachCount().map{when(it.key){ ""->0 "O"->it.value/4 else->(it.value+3)/4}}.sum()>3 ``` ## Test ``` fun r(i:String):Any=i.split("").groupingBy{it}.eachCount().map{when(it.key){ ""->0 "O"->it.value/4 else->(it.value+3)/4}}.sum()>3 data class TestData(val input:String, val output:Boolean) { fun run() { val out = r(input) if (out != output) { throw AssertionError("Failed test: ${this} -> $out") } } } fun main(args: Array<String>) { listOf( TestData("BLWS", true), TestData("OOOOWLB", true), TestData("OOW", false), TestData("BBBO", false), TestData("", false), TestData("BBBBLW", false), TestData("BBBBBLW", true), TestData("OOOOOOOOOOOOOOOO", true), TestData("BLBLBLBLBL", true), TestData("BLSWBLSWBLSW", true) ).forEach(TestData::run) println("Test passed") } ``` **Cannot work on TryItOnline, but works on** [try.kotlinlang.org](https://try.kotlinlang.org) ]
[Question] [ # Objective Write a program or function that checks if a variable name is valid and output 1 or `True` if it is valid, 0.5 if it is valid but starts with an underscore (\_), and 0 or `False` if it is not valid. # Rules * A variable name in most languages is valid if it begins with an underscore or letter (a-z, A-Z, \_) and the rest of the characters are either underscores, letters, or numbers. (a-z, A-Z, 0-9, \_) * Output 1 or `True` if the variable name is valid and 0 or `False` if not valid. * However, it is not good practice to start a variable with an underscore, so return 0.5 if it starts with an underscore and the name is valid. # Test Cases ## Input `abcdefghijklmnop` ## Output `1` ## Input `_test_` ## Output `0.5` (starts with an underscore) ## Input `123abc` ## Output `0` (starts with a number) ## Input `A_b1C_23` ## Output `1` ## Input `_!` ## Output `0` (not 0.5 because it's not valid) ## Input `magical pony1` ## Output `0` (no spaces) [Standard loopholes](http://meta.codegolf.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 shortest code wins. **Bonus:** -10% if your program/function outputs `0` for an empty string(`""`). [Answer] ## JavaScript (ES6), 37 - 10% = 33.3 bytes Saved 4 bytes thanks to @edc65 Saved 5.6 bytes thanks to @Mateon ``` s=>!/^\d|\W|^$/.test(s)/-~(s[0]=='_') ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~25~~ ~~24~~ ~~20~~ 19 bytes Code: ``` ¬D'_Qsa·+¹žj-""Q*2/ ``` Explanation: ``` ¬ # Push input and also push the first character. D # Duplicate the first character. '_Q # Check if it is equal to an underscore character. sa # Swap and check the duplicate if it's an alphabetic character. · # Double the value. + # Add both values up ¹ # Take the first input. žj- # žj is short for [a-zA-Z0-9_]. This will be substracted from the initial string. ""Q # Check if the string is empty. * # Multiply this with the first value. 2/ # Halve it, resulting into 0.0, 0.5, or 1.0. ``` In short, the formula for the string `s` in pseudocode is: ``` ((s[0] == '_' + s.isalpha() × 2) × (s.remove([a-zA-Z0-9_]) == "")) / 2 ``` [Try it online!](http://05ab1e.tryitonline.net/#code=wqxEJ19Rc2HCtyvCucW-ai0iIlEqMi8&input=bWFnaWNhbCBwb255MQ) Uses **CP-1252** encoding. [Answer] ## PHP (50 - 10% = 45) Thanks to Schism for the -2 :) ``` preg_match('/^[a-z_]\w*$/i',$s)?$s[0]=='_'?.5:1:0; ``` Not to compete with the golflang answers, but I thought I'd try it anyways. ``` preg_match('/^[a-z_]\w*$/i', $s) # Matches every a-zA-Z0-9_ string that doesnt start with a number ? $s[0] == '_' # Then, if it starts with an _ ? .5 # give 0.5 points : 1 # If it doesn't, give 1 : 0; # If it didn't match the regex, give 0 ``` Something to note is that in PHP, without the `/u` modifier, `\w` only selects ASCII letters. In some other languages/Regex flavours, this pattern won't work. **Edit**: I see a lot of people using \w and \d in their answers, when they use a language that includes non-ASCII letters and digits too. That is NOT the puzzle. They are wrong. (Can't downvote/comment yet, sorry to need to tell it this way.) [Answer] # Retina, ~~30 - 10% = 27~~ ~~28 - 10% = 25.2~~ 29 - 10% = 26.1 bytes Both versions qualify for bonus, as they handle empty input correctly (outputs `0`) I had to fix a bug caused by one of .NET regex features, which considers some (read as many) Unicode characters as "word" characters. Fortunately, this cost me only a single byte in both versions. It only came down to adding a modifier to make the regex matching behavior compliant to ECMAScript standards. More about that [here](https://msdn.microsoft.com/en-us/library/20bw873z%28v=vs.110%29.aspx#Anchor_5). ### New ~~28~~ 29-byte version, made by @MartinBüttner. Thanks! ``` ^_ $_¶_ Mme`^(?!\d)\w+$ 2 0.5 ``` ### Explanation First, we check if the input starts with an underscore. If it does, the input is duplicated, with a newline in between. For example: `_test_` -> `_test_\n_test_`, where `\n` is the newline. Then we try to match anything, that doesn't start with a number, but is followed by any number of "word" characters (`a-z`, `A-Z`, digits, and underscore) *on each line*. Note that if input started with an underscore and was replaced to two lines, this will match both lines. Then we check if we had 2 matches, and replace them with `0.5`. Empty or invalid line will always yield 0 matches, and valid variable names always yield 1 match. --- ### My own ~~30~~ 31-byte version ``` Ae`^\d|\W ^_.* 0.5 ^\D.* 1 ^$ 0 ``` ### Explanation First of all, we check if input starts with a digit or contains a non-word character (anything other than `a-z`, `A-Z`, digits and underscore). If it does, it's discarded, because it's invalid. Then we check if it starts with an underscore. If it does, it's replaced with `0.5`. Then we check if it starts with a non-digit character (at this point the first character is either `0`, `a-z`, or `A-Z`. Only `a-z` and `A-Z` are non-digits, obviously). If it does, it's replaced with a `1`. Then we check for empty string and replace it with `0`. [Try it online!](http://retina.tryitonline.net/#code=Xl8KJF_Ctl8KTW1lYF4oPyFcZClcdyskCjIKMC41&input=X3Rlc3Rf) [Try it online! Old version](http://retina.tryitonline.net/#code=QWVgXlxkfFxXCl5fLioKMC41Cl5cRC4qCjEKXiQKMA&input=X3Rlc3Rf) [Answer] # Python 3, 36 bytes ``` lambda s:s.isidentifier()/-~(s[:1]=='_') ``` The code is **40 bytes** long and qualifies for the **-10% bonus**. Note that this will only work correctly for code pages that don't have non-ASCII letters/digits. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 27 bytes ``` 1)95=2/8M3Y2m+G7M95h4Y2hmA* ``` This works in [current version(15.0.0)](https://github.com/lmendo/MATL/releases/tag/15.0.0) of the language. Input is a string with single quotes. [**Try it online!**](http://matl.tryitonline.net/#code=MSk5NT0yLzhNM1kybStHN005NWg0WTJobUEq&input=J190ZXN0Xyc) ### Explanation ``` 1) % take input implicitly. Get its first element 95= % true if it equals 95 (underscore) 2/ % divide by 2: gives 0.5 if underscore, 0 if not 8M % push first element of input again 3Y2 % predefined literal: string with all letters m % true if it's a letter + % add. Gives 1 if letter, 0.5 if underscore G % push input again 7M % push string with all letters again 95h % concatenate underscore 4Y2h % predefined literal: string with all digits. Concatenate mA % true if all input chars belong to that concatenated string * % multiply. Display implicitly ``` [Answer] ## [Pyke](https://github.com/muddyfish/PYKE), 21 bytes ### (noncompeting, added string subtraction, various string constants) ``` Qh~u{Q~J\_+-|!Qh\_qh/ ``` Explanation: ``` Qh~u{ - Check first char isn't a digit Q~J\_+- - Is the input alphanumeric + "_" |! - Combine Qh\_q - Is the first char an "_" h/ - Combine ``` [Answer] ## Pyth, 27 bytes ``` c!|-rz0++G\_JjkUT}hzJhqhz\_ ``` [Test Suite](http://pyth.herokuapp.com/?code=c!|-rz0%2B%2BG%5C_JjkUT%7DhzJhqhz%5C_&input=abcdefghijklmnop%0A123abc%0A_test_&test_suite=1&test_suite_input=abcdefghijklmnop%0AABcdefghijklmnop%0A123abc%0A_test_&debug=0) [Answer] # [Gogh](https://github.com/zachgates7/Gogh), 29 bytes ``` ÷"[^\W\d]\w*"g¦"_.*"g+÷2=0.5¿ ``` Run using: ``` $ ./gogh no '÷"[^\W\d]\w*"g¦"_.*"g+÷2=0.5¿' "_test" ``` --- ### Explanation ``` “ Implicit input ” ÷ “ Duplicate the TOS ” "[^\W\d]\w*"g “ Fully match the STOS against the TOS (regex) ” ¦ “ Swap the STOS and TOS ” "_.*"g “ Fully match the STOS against the TOS (regex) ” + “ Add the TOS to the STOS ” ÷ “ Duplicate the TOS ” 2= “ Determine if the TOS is equal to 2 ” 0.5¿ “ Leave the correct output on the stack ” “ Implicit output ” ``` [Answer] # Perl, 21 bytes ``` $_=!/\W|^\d//2**/^_/ ``` The score includes **+1 byte** for the `-p` switch. Try it on [Ideone](http://ideone.com/7JreBb). [Answer] # Pyth, 19 bytes ``` c!:z"\W|^\d"0h!xz\_ ``` Try it with the [Pyth Compiler](http://pyth.herokuapp.com/?code=c%21%3Az%22%5CW%7C%5E%5Cd%220h%21xz%5C_&input=abcdefghijklmnop%0A123abc%0A_test_&test_suite=1&test_suite_input=abcdefghijklmnop%0A_test_%0A123abc%0AA_b1C_23%0A_%21%0Amagical+pony1&debug=0). Note that this will only work correctly for code pages that don't have non-ASCII letters/digits. ### How it works ``` c!:z"\W|^\d"0h!xz\_ (implicit) Save the input in z. :z 0 Test if z matches the following regex: "\W|^\d" A non-word character or a digit at the beginning. This returns True iff z is an invalid name. ! Apply logical NOT to yield True iff z is a valid name. xz\_ Find the first index of the underscore in z. This yields 0 iff z begins with an underscore. h! Apply logical NOT and increment. This yields 2 if z begins with an underscore, 1 otherwise. c Divide the two results. ``` [Answer] # [Factor](http://factorcode.org/), 84 \* 0.9 = 76.5 ``` USE: regexp [ R/ [_a-zA-Z]\w*/ R/ _.*/ [ matches? 1 0 ? ] bi-curry@ bi 0 = 1 2 ? / ] ``` Runs on the listener (repl), defines a quotation (anonymous function) that takes a string and outputs { 0 | 1/2 | 1 }. Defining it as a word it's 97 chars: ``` USE: regexp : v ( s -- n ) R/ [_a-zA-Z]\w*/ R/ _.*/ [ matches? 1 0 ? ] bi-curry@ bi 0 = 1 2 ? / ; ``` ### How does it work: `R/ [_a-zA-Z]\w*/ R/ _.*/` defines two regular expressions. `bi-curry@` partially applies the quotation `[ matches? 1 0 ? ]` to each regex, leaving two curried quotations on the stack. `bi` applies each quotation to the argument string. Each of those (curried quotations) leave either a 1 or a 0, depending if they matched. The first matches on the well formed names, the second on names starting with underscore. `0 = 1 2 ? /` The last value is replaced with a 1 if it was 0, or with a 2 if it was 1. Then the first (1 or 0, valid or not) is divided by the second (2 or 1, starts with underscore or not). This is loooong! Any pointers to shrinking a bit more appreciated... And I hate regexps! ### PS. ``` { 0 } [ "" v ] unit-test { 0 } [ "" v ] unit-test { 0 } [ "1" v ] unit-test { 0 } [ "1var" v ] unit-test { 0 } [ "var$" v ] unit-test { 0 } [ "foo var" v ] unit-test { 1 } [ "v" v ] unit-test { 1 } [ "var" v ] unit-test { 1 } [ "var_i_able" v ] unit-test { 1 } [ "v4r14bl3" v ] unit-test { 1/2 } [ "_" v ] unit-test { 1/2 } [ "_v" v ] unit-test { 1/2 } [ "_var" v ] unit-test { 1/2 } [ "_var_i_able" v ] unit-test { 1/2 } [ "_v4r14bl3" v ] unit-test ``` all test pass ;) [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 19 bytes - 10% = 17.1 ``` {(0≤⎕NC⍵)÷1+'_'=⊃⍵} ``` `{`…`⍵`…`}` anonymous function where the right argument is represented by `⍵` `⊃⍵` first character (gives space if empty) `'_'=` 1 if equal to 'underbar, 0 otherwise `1+` evaluates to 2 if initial underbar, 1 otherwise `⎕NC⍵` [name class](http://help.dyalog.com/14.1/Content/Language/System%20Functions/nc.htm); -1 if invalid name, 0 if undefined (but valid name), 2-9 if defined (and thus valid) [Answer] # Mathematica, 93 bytes ``` If[#~StringMatchQ~RegularExpression@"[A-Za-z_][0-9A-Za-z_]*",If[#~StringTake~1=="_",.5,1],0]& ``` I'm honestly not sure if this *can* be golfed further. [Answer] # Perl, 34 + 1 = 35 bytes ``` $_=/^([^\W\d])\w*$//(($1 eq"_")+1) ``` Uses the `-p` flag. ## Explanation ``` $_=/^([^\W\d])\w*$//(($1 eq"_")+1) /^([^\W\d])\w*$/ matches any string that starts with an underscore or a letter of the alphabet followed by 0 or more alphanumeric + underscore characters. The first character is stored in a capture group / divide result by (($1 eq"_")+1) (capture == "_") + 1. This is 1 if the first character was not an underscore and 2 if it was. $_= assign to $_ and implicitly print ``` [Answer] # Python, 84 -10% = 76 bytes ``` lambda x:[0,[[.5,1][x[0]>'z'],0][x[0]<'A']][x.replace('_','a').isalnum()]if x else 0 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 22 bytes ``` hkdc¬:[kr\_+?F¬?h\_=ß½ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=hkdc%C2%AC%3A%5Bkr%5C_%2B%3FF%C2%AC%3Fh%5C_%3D%C3%9F%C2%BD&inputs=_test_&header=&footer=) A mess. [Answer] # [Japt](https://github.com/ETHproductions/japt), 23 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Guess which genius once upon a time suggested removing `_` from Japt's `\w` character class thereby costing himself 3 bytes here! ETH *was* going to add a new class with `_` included but then he disappeared. ``` ¥f"[%l_][%w_]+")/ÒUè"^_ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=pWYiWyVsX11bJXdfXSsiKS/SVegiXl8&input=ImFiY2RlZmdoaWprbG1ub3Ai) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=pWYiWyVsX11bJXdfXSsiKS/SVegiXl8&input=WwoiYWJjZGVmZ2hpamtsbW5vcCIKIl90ZXN0XyIKIjEyM2FiYyIKIkFfYjFDXzIzIgoiXyEiCiJtYWdpY2FsIHBvbnkxIgpdLW1S) [Answer] # JavaScript ES7, 37 bytes ``` x=>!x.match(/\W|^\d/)/2**/^_/.test(x) ``` [Try it online](http://vihan.org/p/esfiddle/?code=f%3Dx%3D%3E!x.match(%2F%5CW%7C%5E%5Cd%2F)%2F2**%2F%5E_%2F.test(x)%3B%0A%5B%0A%20%20%20%20%5B%22abcdefghijklmnop%22%2C%201%5D%2C%0A%20%20%20%20%5B%22_test_%22%2C%20.5%5D%2C%0A%20%20%20%20%5B%22123abc%22%2C%200%5D%2C%0A%20%20%20%20%5B%22A_b1C_23%22%2C%201%5D%2C%0A%20%20%20%20%5B%22_!%22%2C%200%5D%2C%0A%20%20%20%20%5B%22magical%20pony1%22%2C%200%5D%0A%5D.map(x%3D%3E%60%27%24%7Bx%5B0%5D%7D%27%20%3D%20%24%7Bf(x%5B0%5D)%7D%2C%20expected%20%24%7Bx%5B1%5D%7D%60).join(%60%0A%60)) How it works: ``` x=> // Fat arrow function !x.match(/\W|^\d/) // Gives false if contains non word or starting // with a digit. Booleans in numeric context will // be 0 or 1 2** // 2 to the power of... /^_/.test(x) // gives true if starting with '_'. // true -> 1 -> 2**1 -> 2 // false -> 0 -> 2**0 -> 1 / // Devide the lValue boolean with the numeric rValue: // lValue = 0 or 1 // rValue = 2 or 1 ``` Port of @Dennis's Perl answer [Answer] # Ruby, 44 bytes ``` ->(s){s=~/^(_|\d)?\w*$/?$1?$1==?_?0.5:0:1:0} ``` [Answer] # Ruby, 57 - 10% = 51.3 bytes ``` ->(s){case s when'',/^\d/,/\W/ 0 when/^_/ 0.5 else 1 end} ``` A pretty naïve approach [Answer] # Lua, 82 - 10% = 73.8 ``` v=function(s)return(s:match("^[_%a]+[_%w]*$")and 1or 0)*(s:match("_")and.5or 1)end ``` Test Cases: ``` print(v("a") == 1) -- true print(v("1") == 0) -- true print(v("_") == 0.5) -- true print(v("") == 0) -- true print(v("1a") == 0) -- true print(v("a1") == 1) -- true print(v("_1") == 0.5) -- true print(v("_a") == 0.5) -- true print(v("1_") == 0) -- true print(v("a_") == 0.5) -- true ``` [Answer] # Lua, 68 \* .9 = 61.2 bytes ``` s=arg[1]print(s:find("^[%a_][%w_]*$")and(s:find("^_")and.5or 1)or 0) ``` Takes arguments on the command line [Answer] # [Julia 1.3](http://julialang.org/), ~~46~~ 44 -10% = ~~41.4~~ 39.6 bytes ``` !s=[1 .5]count.(r"^[a-z]\w*$"i=>r"^_\w*$",s) ``` [Try it online!](https://tio.run/##RY6/TsMwEMZ3P4WbMiSoTUgrlqBUFMSCEAMdGEqJzo7ruDhOFF/6h4k35JGCE7VisP2777v7fLtWK4iP3ZhCnoucKkOfe4nG4ZyMaYFY2ySKpMKiZSGvymiwX8DIaNdTxHTFor1rD2@i16f3VVjmYyMOU61YA81pum0NR1UZSx7AChfRGvRrQBSNSZI3IcVxQi02ysgkWTJHwHE11He02otGQ51uQVsRpFoYiYXPK60FR18AL0pAXlzyLkH/g@c3CIJuZNN1TMPbzbBC6Dfe5xqm35uPw/WVp9KFq7OBJzboUFi0NKVr4nnEA8ZzsZWF2n3p0lS1k7K@I3MQz@bOdrDMWPyYzea9OXJXCVJx0LSuzCnuRXd@fzyyIeQ@pLXbE7Xxzx8t6GigoPsD "Julia 1.0 – Try It Online") ### explanation * `r"^[a-z]\w*$"i` is the regex for a variable not starting with a `_` (the `i` means case-insensitive) * `r"^_\w*$"` for a variable starting with a `_` * `count.()` counts the number of time each regex appears in s, result is in a vector (similar to a 2×1 matrix) * `[1 .5]` is a 1×2 matrix, when multiplied by the previous result, gives the expected result (0.5 when starting with `_`, 1 otherwise) ]
[Question] [ You are given the RGB values of a color. Your task is simple: to calculate the hue, in the simplest definition. Say the channels with highest, middle and lowest value are X, Y, Z (which are either red, green or blue) and their values are x, y, z. The hue of this color is (h(X)-h(Y))\*(1 + (x-y)/(x-z))/2 + h(Y), where: ``` h(red) = 0 (or 360 if one of X or Y is blue) h(green) = 120 h(blue) = 240 ``` The input consists of 3 integers from 0 to 255 which are not all equal, in any consistent order. The output can be floats, or integers rounded either up or down, which doesn't have to be consistent. If the integer part of the output is 0 or 360, you can print either of them. You cannot call builtins for color space conversions, including implicit conversions such as while manipulating an image. This is code-golf. Shortest code wins. ## Examples ``` Input: 0 182 255 Output: 197 (or 198) Input: 127 247 103 Output: 110 Input: 0 0 1 Output: 240 Input: 255 165 245 Output: 307 (or 306) ``` ## Edit You don't have to follow the exact formula, but only have to give the same result as the above formula. I'd like to also see some answers golfing the formula itself. [Answer] # C#, ~~188~~ ~~210~~ ~~206~~ ~~197~~ 191 bytes ``` int H(int r,int g,int b){int[]a={r,g,b};System.Array.Sort(a);int x=a[2],y=a[1],c=x==g?1:(x==b?2:(y==b?3:0)),d=y==g?1:(y==b?2:(x==b?3:0));return(int)((c-d)*120*(1+(x-y)*1D/(x-a[0]))/2+d*120);} ``` Thanks to Sok for saving 4 bytes and to SLuck49 for saving 15! [Answer] ## Pyth, ~~41~~ ~~55~~ ~~53~~ 51 bytes ``` A.)JohN,VQ*L120?qeQhSQ3j312T+/*-HKeeJhc-GheJ-GhhJ2K ``` Input is expected in the form `r,g,b`. Here's an explanation: ``` Implicit: Q=eval(input()), evaluates to (r,g,b) ?qeQhSQ Is b the smallest? 3j312T Choose [0,1,2] or [3,1,2] based on above *L120 Convert to [0,120,240] or [360,120,240] ,VQ Pair -> [[r,0/360],[g,120],[b,240]] JohN Order by 1st element in each pair, store in J A.)J Pop biggest from J, set G = x, H = h(X) Output calculation: -GheJ x - y -GhhJ x - z hc Divide and increment KeeJ Set K = h(Y) *-HK Multiply by (h(X) - h(Y)) / 2 Integer division by 2 + K Add h(Y) ``` *Saved 4 bytes, thanks to @Jakube and @isaacg* [Answer] # Javascript (ES6), ~~145~~ ~~115~~ ~~108~~ ~~100~~ ~~97~~ 90 bytes Returns floats. Assign to a function to use. ``` (r,g,b)=>([x,y,z]=[r,g,b].sort((a,b)=>b-a),m=x-z,(x-r?x-g?r-g+4*m:b-r+2*m:g-b+6*m)/m%6*60) ``` Saved 30 bytes by inlining everything into a single ternary operator sequence and waiting until the end to normalize to 0-360. Thanks to edc65, Vasu Adari, and ETHproductions for saving even more bytes. [JSFiddle](http://jsfiddle.net/ndbkx9jk/) with tests. Try in Firefox. If removing the function declaration `h=` is not legal, add 2 bytes. [Answer] # Pyth, 27 bytes ``` *60%+c-Ft.<QJxQKeSQ-KhSQyJ6 ``` [Demonstration.](https://pyth.herokuapp.com/?code=*60%25%2Bc-Ft.%3CQJxQKeSQ-KhSQyJ6&input=255%2C+165%2C+245&test_suite_input=0%2C+182%2C+255%0A127%2C+247%2C+103%0A0%2C+0%2C+1%0A255%2C+165%2C+245%0A1%2C+0%2C+0%0A0%2C+1%2C+0&debug=0) [Test harness.](https://pyth.herokuapp.com/?code=*60%25%2Bc-Ft.%3CQJxQKeSQ-KhSQyJ6&input=255%2C+165%2C+245&test_suite=1&test_suite_input=0%2C+182%2C+255%0A127%2C+247%2C+103%0A0%2C+0%2C+1%0A255%2C+165%2C+245%0A1%2C+0%2C+0%0A0%2C+1%2C+0&debug=0) Fomula taken from [Wikipedia](https://en.wikipedia.org/wiki/HSL_and_HSV#Hue_and_chroma). Essentially, the steps are: 1. `.<QJxQKeSQ`: Roate the largest value to the front of the list. 2. `-Ft`: Take the difference of the other two values. 3. `-KhSQ`: Subtract the minimum value from the maximum value. 4. `c`: Divide 2 by 3. 5. `+ ... yJ` Add twice the index of the maximum value in the list (0 if R, 2 if G, 4 if B). 6. `% ... 6`: Mod 6, to fix issues with negatives. 7. `*60`: Multiply by 60 to convert to degrees, and print. [Answer] # Octave, ~~65~~ ~~60~~ 50 bytes ### Edit: Saved 10 bytes thanks to pawel.boczarski ### An approximate solution... ``` @(c)mod(atan2d(.866*c*[0;1;-1],c*[2;-1;-1]/2),360) ``` ### Test run ``` @(c)mod(atan2d(.866*c*[0;1;-1],c*[2;-1;-1]/2),360) ans([0 182 255]) ans = 196.14 @(c)mod(atan2d(.866*c*[0;1;-1],c*[2;-1;-1]/2),360) ans([127 247 103]) ans = 111.05 @(c)mod(atan2d(.866*c*[0;1;-1],c*[2;-1;-1]/2),360) ans([0 0 1]) ans = 240.00 @(c)mod(atan2d(.866*c*[0;1;-1],c*[2;-1;-1]/2),360) ans([255 165 245]) ans = 305.82 ``` --- # Octave, 107 bytes ### My original (exact-ish) solution... ### Code: ``` function H=r(c) [b,i]=sort(c);h=60*[6*(i(1)~=3),2,4](i);H=(h(3)-h(2))*(1+(b(3)-b(2))/(b(3)-b(1)))/2+h(2); ``` ### Explained: ``` function H=r(c) [b,i]=sort(c); h=60*[6*(i(1)~=3),2,4](i); H=(h(3)-h(2))*(1+(b(3)-b(2))/(b(3)-b(1)))/2+h(2); ``` This function takes a vector containing the R,G,B values as input `c` and sorts the input in ascending order * `b` contains the sorted values [z, y, x] * `i` contains the RGB plane associated with each value in b The vector `h` is populated with the values * `60*[6, 2, 4]` = `[360, 120, 240]` (but 3 bytes shorter) * unless the lowest value is in Blue (`i(1) == 3`), in which case the first hue value becomes zero * then use `(i)` to rearrange `h` into `[h(Z), h(Y), h(X)]` order From there it's just a straight transcription of the formula. You can try it [here](http://ideone.com/vkJLYJ). [Answer] # Pyth, 55 I know @Sok's answer beats mine, but since I finished mine just after he/she posted, I thought I would still post. This was my first time using Pyth so I'm sure I made some obvious mistakes. ``` DlZK*120ZRKJSQFNJ=Y+YxQN)=kl@Y1+k/*-leYk+1c-eJ@J1-eJhJ2 ``` Input is expected to be `r, g, b`. You can try it [here](https://pyth.herokuapp.com/?code=DlZK*120ZRKJSQFNJ%3DY%2BYxQN)%3Dkl%40Y1%2Bk%2F*-leYk%2B1c-eJ%40J1-eJhJ2&debug=0). [Answer] ## PowerShell, ~~232~~ ~~226~~ ~~222~~ 161 Bytes See revision history for previous versions ``` $z,$y,$x=($r,$g,$b=$args)|sort $c=((2,(0,3)[$y-eq$b])[$x-ne$b],1)[$x-eq$g] $d=((2,(0,3)[$x-eq$b])[$y-ne$b],1)[$y-eq$g] (($c-$d)*120*(1+($x-$y)/($x-$z))/2+$d*120) ``` Hoo boy, let's see if I can walk through this. Since `\n` counts the same as `;` I left the line breaks in for clarity. The first line takes input as three `$args` and stores them into `$r, $g, $b`. We're really only going to be using `$b` later, but we need all three so the `|sort` works appropriately. This makes `$z, $y, $x` the smallest-to-largest of the input arguments. The next two lines setup `$c` and `$d` by using multiple index-into-an-array calls to set the numbers appropriately. Working from outside in, if `$x` is `-eq`ual to `$g` (i.e., green was the largest), we set `$c=1` ... else, if `$x` is `-n`ot`e`qual to `$b` (i.e., blue wasn't the largest) `$c` is either `0` or `3` depending if blue was the second largest ... else, `$c=2`. Similar logic sets `$d`. We then calculate and print the output with the following, which is just the algorithm from the challenge golfed a little bit. ``` (($c-$d)*120*(1+($x-$y)/($x-$z))/2+$d*120) ``` [Answer] # Ruby, ~~117~~ ~~96~~ 94 bytes **Code:** ``` h=->r,g,b{z,y,x=[r,g,b].sort;v=x-z.to_f;({r=>(g-b)/v,g=>2+(b-r)/v,b=>4+(r-g)/v}[x]%6*60).to_i} ``` * Saved 21 bytes by removing `()` and using r,g,b variables. * Taking modulus of 6 to convert negative value and multiplying it by 60 to convert to degrees that saved 2 bytes. **Examples:** ``` irb(main):274:0> h.call 0,182,255 => 197 irb(main):275:0> h.call 127,247,103 => 110 irb(main):276:0> h.call 0,0,1 => 240 irb(main):277:0> h.call 255,165,245 => 306 ``` [Answer] # SWI-Prolog, 133 bytes ``` a(L,H):-L=[R,G,B],max_list(L,X),min_list(L,Y),member(X:I:J:U,[R:G:B:0,G:B:R:2,B:R:G:4]),Z is 60*(U+(I-J)/(X-Y)),(Z<0,H is Z+360;H=Z). ``` Example: `a([255,165,245],Hue).` outputs `Hue = 306.666666666666 .` This uses the following formula: * `Max = max(R,G,B)`, `Min = min(R,G,B)`. * If `Max = R`, `U = 0`. Else if `Max = G`, `U = 2`. Else `U = 4`. * If `Max = R`, `I = G` and `J = B`. Else if `Max = G`, `I = B` and `J = R`. Else `I = R` and `J = G`. * `Z = U + (I - J)/(Max - Min)` * `Hue` is either `Z` or `Z + 360` if `Z < 0`. [Answer] # Perl 5, 138 132 119 bytes ### Code: ``` ($m,$c,$M)=sort@A=($R,$G,$B)=@ARGV;print 60*(6+$M>$m?($G>$c?$B-$R:$B>$c?$R-$G:$G-$B)/($M-$m)+($G>$c?2:$B>$c?4:0):0)%360 ``` ### Remarks: Surely Perl can't win such challenge with all the Pyth'oresque golfing. But I wondered if this was possible to do with only 1 calculation step. Thanks to the modulus that worked out nicely. :) ### Test: ``` $ perl hue.pl 0 182 255 197 $ perl hue.pl 127 247 103 110 $ perl hue.pl 0 0 1 240 $ perl hue.pl 255 165 245 307 ``` [Answer] # R, 125 bytes Very similar to beaker's Octave solution. Floating point output. ## Code: ``` h=function(x){ o=seq(3)[order(-x)]; y=c(60*c(6*(o[3]!=3),2,4)[o],x[o]); return((y[1]-y[2])*(1+(y[4]-y[5])/(y[4]-y[6]))/2+y[2]); } ``` ## Examples: ``` > h(c(0,182,255)) [1] 197.1765 > h(c(127,247,103)) [1] 110 > h(c(0,0,1)) [1] 240 > h(c(255,165,245)) [1] 306.6667 ``` [Answer] # Python, 154 bytes ``` def h(c):r=c[:];c.sort();c=c[::-1];x,y,z=c;i,j=[120if n==r[1]else 240if n==r[2]else 0if z==r[2]else 360for n in[x,y]];print ((i-j)*(1+(x-y+0.)/(x-z))/2)+j ``` Accepts a list of values. Not sure if this can be broken down further. Here it is ungolfed: ``` def hue(color): rgb=color[:] # copy list color.sort() # sort list color=color[::-1] # reverse sort x,y,z=color # pull out x,y,z # The line # i,j=[120if n==r[1]else 240if n==r[2]else 0if z==r[2]else 360for n in[x,y]] # is basically the following, twice, once for x/hx and the second time for y/hy if x==rgb[1]: # if x is green hx = 120 else: if x==rgb[2]: # if x is blue hx = 240 else: if z==rgb[2]: # if z is blue and x is red hx = 0 else: # if x is red and y is blue hx = 1 print ((hx-hy)*(1+(x-y+0.)/(x-z))/2)+hy # calculate, print ``` [Answer] # JavaScript 108 Alternate method. ``` function H(r,g,b){a=[r,g,b].sort(),M=a[2],c=M-a[0],h=M==r?(g-b)/c%6:M==g?(b-r)/c+2:(r-g)/c+4 return h*60|0;} ``` **JavaScript 194** Using the example method. ``` Array.prototype.i=[].indexOf function H(r,g,b,a){a=[r,g,b].sort(),i=[a.i(r),a.i(g),a.i(b)],x=[i[2]?360:0,120,240],hx=x[i.i(2)]|0,hy=x[i.i(1)]|0 return (hx-hy)*(1+(a[2]-a[1])/(a[2]-a[0]))/2+hy|0} var input = document.getElementById("input").innerHTML; var output = document.getElementById("output"); var html = ""; input.replace(/(\d+)\,(\d+)\,(\d+)/g, function(m, r, g, b) { html += H(r, g, b) + "\n"; }); output.innerHTML = html; ``` ``` <pre id="input"> 0,182,255 127,247,103 0,0,1 255,165,245 </pre> <pre id="output"> </pre> ``` ]
[Question] [ This is supposed to be a code golf challenge on the simpler end of the spectrum. But I figured it could be nice to bring out some micro-optimisation here. There are [three basic types of DVI connectors](http://en.wikipedia.org/wiki/Digital_Visual_Interface): DVI-A (analog), DVI-D (digital) and DVI-I (integrated). Furthermore, there are single-link and dual-link versions of the DVI-D and DVI-I connectors. Each of those five different connectors uses a different set of pins. Given one of `A`, `D1`, `D2`, `I1`, `I2` as an identifier for the type of connector, print the corresponding ASCII representation of the connector's pins: ``` A: # # # # # # # ===== # # # # # # # # # D1: # # # # # # ===== # # # # # # # # # # # # D2: # # # # # # # # ===== # # # # # # # # # # # # # # # # I1: # # # # # # # # ===== # # # # # # # # # # # # # # I2: # # # # # # # # # # ===== # # # # # # # # # # # # # # # # # # ``` (The `X:` lines are not part of the output, you should only print 3 lines.) You may write a program or function, taking input via STDIN, ARGV or function argument. The output must be printed to STDOUT, with an optional trailing line feed. You may or may not include trailing spaces in the second line of the `A` connector. You must not use additional leading *or* trailing spaces anywhere else. This is code golf, so the shortest answer (in bytes) wins. [Answer] # Perl - ~~100~~ 91 (including 1 flag) Uses nutki's ideas of using `-p` and reducing double-spaces. Also simplified elimination of trailing spaces. ``` #!perl -p $x=$_|" qb";$_="dbd xxxqqqax# =====bxxxqqqaaa!dbd xxaqqqax#";s/[$x]/ /g;s/\w/# /g;s/ !/ / ``` Input comes from stdin and must contain only the connector type with no trailing newline. --- Previous: ``` $x=shift|" q";$_="d d xxxqqqaxx ===== xxxqqqaaa d d xxaqqqaxx";s/[$x]/ /g;s/\w/# /g;s/ $//mg;say ``` Takes a command-line argument. Ungolfed: ``` # Read argument, transform A->aq, I1->iq, I2->is, D1->dq, D2->ds $x=shift|" q"; # String compacted $_ = "d d xxxqqqaxx ===== xxxqqqaaa d d xxaqqqaxx"; # Clear any pins with matching char in input s/[$x]/ /g; # Convert rest to '#' s/\w/# /g; # Eliminate trailing spaces s/ $//mg; say ``` [Answer] # Python, 168 characters ``` t=raw_input()*2 Q="G G # # # 2 2 H # #\n===== # # # 2 2 H H H\nG G # # H 2 2 H # #" for A,B,N in('G0A','H0D','212'):Q=Q.replace(A,' #'[t[int(B)]in'I'+N]) print Q ``` Appears to be a new approach. I have the string: ``` G G # # # 2 2 H # # ===== # # # 2 2 H H H G G # # H 2 2 H # # ``` I replace the `G`, `H`, and `2` based on the input. [Answer] ## J, ~~153 121~~ 119 chars **Minified** ``` ('='(;/1,.i.5)}"_1' #'{~5 3 22$#:128#.32x-~3 u:'dt*`J%Q5"xjuH%Jv2uJ!H5 t*`J%@5Jp*uH%Jv2p*!H dp"')echo@{~I1`I2`D1`D2 i.< ``` A third approach: pack all 's and `#`'s into a huge integer as bits. Add the `=`'s afterwards. Still doesn't make use of the symmetry of many of the connector variants, though. **Unminified** ``` n =. 128 #. 32x -~ 3 u: 'dt*`J%Q5"xjuH%Jv2uJ!H5 t*`J%@5Jp*uH%Jv2p*!H dp"' f =. ('=' (;/1,.i.5)}"_1 ' #' {~ 5 3 22 $ #: n) echo@{~ I1`I2`D1`D2 i. < ``` --- **Minified** (153) ``` [:echo@>({&(' #=',LF)&.:>;._2#;._1#:96#.32x-~3 u:' (0%dziqrDwbh5Ds6[gEl)_xkBS6?61m$1ne/v(]!&yW?_{K.S^X#Yn_d%O71KqXEw=I;meH>@eG2|2/gcR0'){~D1`D2`I1`I2 i.< ``` Also as a function. This one uses a variable-length binary coding, by tallying ones in binary and separating by zeroes. 0 ones in a row means , 1 one means `#`, 2 ones means `=`, 3 ones means newline and 4 ones separate the five strings from each other. **Ungolfed** ``` s =. ' (0%dziqrDwbh5Ds6[gEl)_xkBS6?61m$1ne/v(]!&yW?_{K.S^X#Yn_d%O71KqXEw=I;meH>@eG2|2/gcR0' f =. [: echo@> ({&(' #=',LF)&.:>;._2 #;._1 #: 96 #. 32x -~ 3 u:s) {~ D1`D2`I1`I2 i. < ``` [Answer] # Marbelous, 281 bytes/characters ### Minified: ``` 00 ]] GG]] IIJJJJ :G }0 ++ >> >X{0 /\{<{> :H }0 -Z >E-2 -C// {0 :I 23232003002023}023 LLMMMMNNRROOMMRRLL 0003 0300 NNNN :J }0}1 HH-2 KKKK :K }1}0 }1}0}0 PPPPQQ :L }020 }0202020 :M 20}020}020}0 :N }0 }020 +W20 :O 3D3D3D3D3D}0 :P }023}1230A LLMMNNMM :Q 2023}0230A OOMMNNMM :R }0 \/0A ``` This takes `D1`, `D2`, `I1`, `I2` or `A` from STDIN. Trailing newlines in input is optional. Output is to STDOUT. This program calls subboards which print parts of connectors, either filling in `#`s or leaving spaces depending on inputs. [Try this answer here](https://codegolf.stackexchange.com/a/40808/29611); cylindrical boards are needed. ### with Comments: ``` 00 .. .. ]] .. .. # get A/D/I Gt ]] .. # pass into Gt; call PA if A or PrDI if D/I PA Pr DI # If 'A' is passed, a marble is emitted down # Otherwise, marbles are sent left/right # The value of the marble outputted is (I+1)/2, which creates a difference of 3 # between D and I, the difference between a space and a # :Gt }0 .. .. ++ .. .. >> .. .. >X {0 .. /\ {< {> # Returns 0 if '1' is passed, and 3 if '2' is passed :Ff }0 .. -Z .. >E -2 -C // {0 .. # Prints connector A # Calls made: P1(23) P2(23) P2(20) P3(03) LF(00) P4(20) P2(23) LF(}0) P1(23) # P3(03) P3(00) P3(00) P3(03) :PA 23 23 20 03 00 20 23 }0 23 P1 P2 P2 P3 LF P4 P2 LF P1 00 03 .. .. .. .. .. .. .. 03 00 .. .. .. .. .. .. .. P3 P3 .. .. .. .. .. .. .. # Prints connectors D0/D1/I0/I1 # }0 is either '1' or '2' # }1 is either 32 or 35 (for D or I) :PrDI }0 }1 Ff -2 Li DI # Helper for PrDI # Calls made: L1(}1, }0) L2(}0) L1(}1, }0) :LiDI }1 }0 .. }1 }0 }0 L1 L1 L2 # Prints '# # ' (}0 = 0x23) or ' ' (}0 = 0x20) :P1 }0 20 .. .. }0 20 20 20 # Prints ' # # #' (}0 = 0x23) or ' ' (}0 = 0x20) :P2 20 }0 20 }0 20 }0 # Prints ' # #' (}0 = 0x03) or ' ' (}0 = 0x00) :P3 }0 .. }0 20 +W 20 # Prints '===== ', }0 must be 0x20 :P4 3D 3D 3D 3D 3D }0 # Prints the top/bottom line of D/I connectors + newline # Calls made: P1(}0) P2(23) P3(}1) P2(23) :L1 }0 23 }1 23 0A P1 P2 P3 P2 .. # Prints the middle line of D/I connectors + newline # Calls made: P4(20) P2(23) P3(}0) P2(23) :L2 20 23 }0 23 0A P4 P2 P3 P2 .. # Emits a newline (0x0A) regardless of input :LF }0 .. \/ 0A ``` [Answer] # Perl 5: 105 (including 1 flag) Yet another Perl solution. Uses stdin for the parameter. ``` #!perl -p @x=map$_?'#':$",!/D/,-/2/,!/A/,1,0;$_='040 33311233 =====433311222 040 33211233';s/\d/$x[$&] /g;s/ $//mg ``` [Answer] # GNU sed, 116 bytes ``` s/.*/&:# # 33322433\n===== 33322444\n# # 33422433/ /A/s/[42]/ /g /1/s/2/ /g /D/s/#/ /g s/[2-4]/ #/g s/.*:// ``` ### Output: ``` $ echo "A D1 D2 I1 I2"|sed -f dvi.sed # # # # # # # ===== # # # # # # # # # # # # # # # ===== # # # # # # # # # # # # # # # # # # # # ===== # # # # # # # # # # # # # # # # # # # # # # # # ===== # # # # # # # # # # # # # # # # # # # # # # # # ===== # # # # # # # # # # # # # # # # # # $ ``` [Answer] # CJam, ~~79~~ 70 bytes Inspired from [nutki's answer](https://codegolf.stackexchange.com/a/41588/31414). This also makes sure that there are no trailing white spaces (except for second line) ``` "VF­wGC}*D"176b6b" DG1A="f=r'1+2<" "aer{_s" ="&\"# "?}%s23/Wf<N* ``` Use [this link](https://mothereff.in/byte-counter#%22VF%C2%8B%C2%ADwG%C2%95%C2%85C%7D%C2%8F*D%C2%96%22176b6b%22%20DG1A%3D%22f%3Dr%271%2B2%3C%22%20%20%22aer%7B_s%22%20%3D%22%26%5C%22%23%20%22%3F%7D%25s23%2FWf%3CN*) to copy the code as SE strips non-printable characters. There are 5 characters in non-printable ASCII range but well within a byte (ASCII code 255) **How it works**: ``` "VF­wGC}*D"176b6b" DG1A="f= "This effectively results into this string:" "D D GGG11AGG===== GGG11AAAD D GGA11AGG"; r'1+2< "Read the input, convert A to A1"; " "er "Replace the occurrences of above two characters" "with double space ' '"; {_s" ="&\"# "?}%s "Convert every non = and space character to '# '"; 23/ "Divide the string into parts of 23 characters"; Wf< "String last character from above parts"; N* "Join with new line"; ``` [Try it online here](http://cjam.aditsu.net/) [Answer] ## J, ~~198 194~~ 157 chars **Minified** ``` 3 22 echo@$'x x # # # x x x # #===== # # # x x x x xx x # # x x x x # #'('x'I.@:=])}~(5 16$(#' #'$~#)"."0'4123212128262126290901824'){~D1`D2`I1`I2 i.< ``` Implemented as a function. Note that the function is a train, meaning one would have to surround it by parentheses or assign it to a name in order to use it (maybe I should count the parens as part of the function, even though technically they aren't). **Ungolfed** ``` S1 =. (#' #'$~#)"."0'4123212128262126290901824' S2 =. 'x x # # # x x x # #===== # # # x x x x xx x # # x x x x # #' f =. 3 22 echo@$ S2 ('x'I.@:=])}~ (5 16$S1) {~ D1`D2`I1`I2 i. < ``` The idea is to store the common part of the string separately from the characters that differ between the connector types. `S1` stores the unique characters, and `S2` acts as a pattern with `x`'s acting as placeholders to fill in. [Answer] # Python - ~~167 166 164 161~~ 159 ``` C=raw_input() a=["# # "," "*6]["D"in C] r=" #" b="A"in C i=3-b d=(r*[i,5][C[1:]>"1"]).rjust(10) t=r*3 print a+t+d+"\n===== "+t+d*~-len(C)+"\n"+a+r*i+" "*b+d ``` [Answer] # JavaScript (ES6) 178 ~~186~~ **Edit** Having 7 base blocks, use base 7 The straight way, using string building with replace and 7 building blocks. Output to stdout using alert as requested by OP. Now I'll try some micro-optimizations... ``` F=t=>alert( {A:21349062249,D1:538695058296,D2:534740169498,I1:151139015296,I2:147184126498}[t] .toString(7).replace(/./g,c=>'\n0# # 0===== 0 # # #0 # #0 0 '.split(0)[c]) ) ``` **Test** In FireFox/FireBug console - removing 'alert' to simplify test ``` ;['A','D1','D2','I1','I2'].forEach(i=>console.log(F(i))) ``` *Output* ``` # # # # # # # ===== # # # # # # # # # # # # # # # ===== # # # # # # # # # # # # # # # # # # # # ===== # # # # # # # # # # # # # # # # # # # # # # # # ===== # # # # # # # # # # # # # # # # # # # # # # # # ===== # # # # # # # # # # # # # # # # # # ``` [Answer] ## APL (115) ``` V←3 22⍴''⋄V[2;⍳5]←'='⋄V[⍳3;(2=⍴I)/(6+2×⍳8)~14 16/⍨'1'∊I]←V[⍳2;12]←V[⍳3;8 10]←V[R/1 3;1 5 20 22/⍨R←∨/'AI'∊I←⍞]←'#'⋄V ``` Test: ``` V←3 22⍴''⋄V[2;⍳5]←'='⋄V[⍳3;(2=⍴I)/(6+2×⍳8)~14 16/⍨'1'∊I]←V[⍳2;12]←V[⍳3;8 10]←V[R/1 3;1 5 20 22/⍨R←∨/'AI'∊I←⍞]←'#'⋄V A # # # # # # # ===== # # # # # # # # # V←3 22⍴''⋄V[2;⍳5]←'='⋄V[⍳3;(2=⍴I)/(6+2×⍳8)~14 16/⍨'1'∊I]←V[⍳2;12]←V[⍳3;8 10]←V[R/1 3;1 5 20 22/⍨R←∨/'AI'∊I←⍞]←'#'⋄V D1 # # # # # # ===== # # # # # # # # # # # # V←3 22⍴''⋄V[2;⍳5]←'='⋄V[⍳3;(2=⍴I)/(6+2×⍳8)~14 16/⍨'1'∊I]←V[⍳2;12]←V[⍳3;8 10]←V[R/1 3;1 5 20 22/⍨R←∨/'AI'∊I←⍞]←'#'⋄V D2 # # # # # # # # ===== # # # # # # # # # # # # # # # # V←3 22⍴''⋄V[2;⍳5]←'='⋄V[⍳3;(2=⍴I)/(6+2×⍳8)~14 16/⍨'1'∊I]←V[⍳2;12]←V[⍳3;8 10]←V[R/1 3;1 5 20 22/⍨R←∨/'AI'∊I←⍞]←'#'⋄V I1 # # # # # # # # ===== # # # # # # # # # # # # # # V←3 22⍴''⋄V[2;⍳5]←'='⋄V[⍳3;(2=⍴I)/(6+2×⍳8)~14 16/⍨'1'∊I]←V[⍳2;12]←V[⍳3;8 10]←V[R/1 3;1 5 20 22/⍨R←∨/'AI'∊I←⍞]←'#'⋄V I2 # # # # # # # # # # ===== # # # # # # # # # # # # # # # # # # ``` [Answer] # JavScript ES6, 186 bytes ``` f=c=>(b=(c[0]=='D'?' ':'# # '))+(e=(g=r=>parseInt(r,36).toString(2).replace(/./g,n=>' '+[' ','#'][n]))((o=c[1])?(o-1?73:'6f'):'6b'))+'\n===== '+(o?e:' # # #')+'\n'+b+(o?e:g('5f')) ``` ``` f=c=>(b=(c[0]=='D'?' ':'# # '))+(e=(g=r=>parseInt(r,36).toString(2).replace(/./g,n=>' '+[' ','#'][n]))((o=c[1])?(o-1?73:'6f'):'6b'))+'\n===== '+(o?e:' # # #')+'\n'+b+(o?e:g('5f')) alert(f(prompt())) ``` The code is quick and dirty, but it gets the job done. Mostly, the `#`'s and spaces are put into binary and then base 36. I'm looking into a more elegant and hopefully shorter solution. [Answer] # Perl 5 - 150 (149 + 1 for `n`) ### Golfed: ``` @b=split//;$_='0 0 ###112## ===== ###11222 0 0 ##2112##'; @c=(@b[0]eq D,@b[1]ne 2,@b[0]eq A);@d=('#',$");s/([#12])/ \1/g;s/(\d)/$d[$c[$1]]/ge;say ``` Input from STDIN, output to STDOUT. Works by doing filling in certain characters with `#` or depending on the input. ### Ungolfed: ``` @b=split//; # char array from input $_='0 0 ###112## ===== ###11222 0 0 ##2112##'; @c=(@b[0] eq 'D',@b[1] ne '2',@b[0] eq 'A'); @d=('#',' '); s/([#12])/ \1/g; # add spaces s/(\d)/$d[$c[$1]]/ge; # replace numbers with appropriate character say $_; ``` ]
[Question] [ ><>, or Fish, is a two-dimensional esoteric programming language where the instruction pointer (IP) toroidally moves around the codebox, wrapping when it hits an edge. ><> has four basic movement instructions - `<`, `>`, `^`, and `v`, which respectively mean to change the IP's direction to left, right, up and down. It also has the termination instruction `;`, which halts the program. For any program, some characters may never have the IP move through them. For example, with the program ``` > v ; < ``` The program starts at the `>`, changes direction at the `v` and `<`, and halts at the `;`. The squares marked with `#` are never passed through: ``` > v ## ; < ``` So if we wanted to obfuscate this program and make it harder to read, we could replace these with any printable ASCII characters and the program would still do exactly the same thing! In this challenge, we will be working with a very limited set of <>< - Just the four movement instructions, spaces, the terminator (`;`) and newlines. Your challenge is to, when given a program in this subset of ><> as input, output the same program with all characters that will never be passed through replaced with random printable ASCII characters - 0x20 to 0x7e. For each position, each printable ASCII character should have an equal chance of being printed, including ><> instructions and spaces. Note that this means replacing *all* characters that are never passed through, not just spaces. You can assume that the ><> program will always halt, and will always be a rectangle. You may take input as a list of lines, a matrix of characters, ascii-art, etc. The program will only ever contain said instructions. The IP starts at 0,0, moving left to right. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! # Testcases In these testcases, `#` represent characters that should be replaced with random characters. ``` v; > v ^< => v;# > v #^< ; v v <<< => ;## ### ### > v ; ; < => > v ## ; < > v v > > ^ >; => > v v# > > ^# ##>; >v> ^ v<^v< > v>; => >v> ^ v<### > v#; ``` [Answer] # ><>, 555 bytes ``` ffv $@$f$+1~< $>i:1+?!v:a=?^}$:@@:@{@p$1+ @@:@(?$&$>~&l1=?v: ^}f-&0~~~~&< >&1+$ff0 v :@@=?v:@@=?^:@@=?v:@@=?v:@@=?vv>}$:@@:@{@g::0$-:@(?$~&">v<;^"& v/~~&</ 2~~~&/ 1~~&/ 0~&/>~" "&>}$:@@:@{@0&-@p:&1$3=?v&:&1=?v$@&:&0=?+&:&2=?-$ v>~~~3> > > !^ !0^! < >0$- >+ > :e=?v>:{:}=?v$> :e=?v>:{{:@}}=?v$&^ ^-1}:{~<^ f~< ^-1}}@:{{~<^ f~< >$:{{:@}}=?v>$:@@:@4[1+r]g:0(?!v0$-o ^!}:{:$f+1~<^$oa;?= >! ]! o!0! r v >l7=?v0 > ~l]0$>$~[r $>x0^>@:@0~(@:@)@@+?!^^ p >1^^@"~ "< }{2*+l1= >?^ ``` [Try it online!](https://tio.run/##XVJRasMwDP3XKZQgTLcQaneDgZsovseooB9zNyi0dGAGIb56J6db203gJyGk92TL8ePz/XyOMSEiBYrUuNwBEn941wxV8tt@kIl8CD6M4UiugRIuBjLE2exdPyQPMsXW2KxmOiVCNq6hGC1eLIH2l8KCchf/YOKrws57S@0skE3NqVtLbRAhLQv3cqZbFZ0luhnRKnKusTY3FmvacPTG0ZOyGw3UUdDA9kOjbtUPLUFiJXpivBrfIVaix0qlYYf/jHXG4hrQYv@m7OxHPxWVS/dvbvRhmtNGQFo3@TF3Ugpi7rAkpqBFP7lLGphufXy50fOra06bnbcLXYlqH0Aq5fIUy7qEDtv10Os8ZdhNhYfKVggnTMj7F2Wx@PeOeb@xxJRfT0D8ZYVVwuaF4kMIunUROCI7kVBnrDuYxtVjo6tGHuR85nmjgDqz/hTkTh8S9CHW8A0 "><> – Try It Online") Note that there is a trailing space on line 11 (after `o!0!`). ><> programs can only access a stack of stacks for data storage, which would be difficult to use as a 2d array. Thus, this modifies the program grid to use as a 2d array, storing the input & tracing the path through it. Additionally, the only source of randomness in ><> is the `x` instruction, which sends the IP in one of 4 random directions. Printable ASCII has 95 (19 \* 5) characters, which is not divisible by numbers less than 5. Thus, to generate the random characters, it generates 7 random bits, joins them into a number from 0 to 128, and then checks if the number is within printable ASCII. If not, it discards it, generates a new random number, and repeats until it is. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~90~~ 55 bytes ``` WS⊞υιP⪫Eυ⭆ι‽γ¶≔¹ηW¬⁼;ψ«≔§§υⅉⅈψ≔∨⊕⌕>^<vψηη✳⊗⊖ηψJ﹪ⅈLθ﹪ⅉLυ ``` [Try it online!](https://tio.run/##TY9BS8QwEIXPm18x9DSBePBcKSxUYReri3pwQRZqG5pAOum2SXURf3tNtnX1kmRm3nvfpFJlX9nSTNOH0kYCbqjz7tn1mhrkHHZ@UOgFaJ6ywhunuzBxuLWasCi7OJrFsdACnkqqbYsN51xA8kYJD8b1MOiG8FqACtUCerAOb4@@NAMmaSLgFCzwxVaLeO02VMvPyx1Ae4yhr@fzFIJ@pY992LrqZSvJyRrvNNWYZIebcU6N1Jm82p2Xz3UvK6ctYW79uwmWXP7ZFb/kb33bvVgsbO2NxQAWcC@pcQqPUbP09//6nsf/fk9TBjCyESBjGRyAhUfKpqvR/AA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated lines. Explanation: ``` WS⊞υι ``` Read the program. ``` P⪫Eυ⭆ι‽γ¶ ``` Output a rectangle of random printable ASCII. ``` ≔¹η ``` Start at the origin facing east. ``` W¬⁼;ψ« ``` Repeat until the end of the program is reached. ``` ≔§§υⅉⅈψ ``` Get the current character of the program. ``` ≔∨⊕⌕>^<vψηη ``` If the current character is a direction then update the direction variable. ``` ✳⊗⊖ηψ ``` Replace the random character with the current character and update the position. ``` J﹪ⅈLθ﹪ⅉLυ ``` Wrap around the sides of the rectangle as necessary. [Answer] # [J](http://jsoftware.com/), 120 bytes ``` (([:u:32+94?@$~#@[)`[`]})~($#:,@i.@$);/@-.[:{."2]($@[|"1{.@](+,:])(]0,~((,-)=i.2),~{:){~' v>^<'i.({~<@{.))^:a:0 0,:0 1"_ ``` [Try it online!](https://tio.run/##hY5BS8QwFITv@RVvu4XksemzrYvQl7QGBE@evJZ0d1lcrCCCaBCi@eu1da/CHmYOwzfDvEzNiit/s@JGSpGRPEHLIEFDCTyrILh7fLiflOr5k6/rTbO9dXlaux73/d7/YFL5mrUbyeVorlxBPUfKaq9y139nVSTn1UazR@VLnZTSBbYj1ahTZIxJQugGK0dSMVkXCXHgA5dQ6tmqbDeheD18vI9fLXlDu1o8HZ/f4ATncDlZimBAdBAEDFbgGZBFIf9DzYLNsvYi@rc4Lxu4jIYOBhHsEOxS68xcENMv "J – Try It Online") It's late, and this one kind of got away from me, but, what the hell, looks like it works. I have some ideas to improve it tomorrow. [Answer] # [Python 3](https://docs.python.org/3/), ~~253~~ 212 bytes Takes input as a character matrix. ``` from random import* def f(g): r=x=y=a=0;b=1;N=[[chr(randint(32,126))for _ in t]for t in g] while';'!=r:N[y][x]=r=g[y][x];a,b=[0,1,0,2,-1,a,-1,0,1,2,0,b][ord(r)%9%6::6];x=(x+b)%len(g[0]);y=(y+a)%len(g) return N ``` [Try it online!](https://tio.run/##NVBRjoMgEP3nFLMfjdCyjdqkyYp4hF7A2o2uaE0sGmCtnt4dbJeE4b03b2CGcXH3QZ/WtTHDA0ypazy6xzgYtye1aqChLUsIGDnLRZYyFJWMxEXm@c/dUO/vtKOnmEfxmbFmMPANnQZXeOg8bAsCz3vXq0AEH9Ikl3wp8rmQRrYvJEpeyTzkEQ95zD8jXvrgeYyxKvLB1NSw3dfunCTnQsySzoeK7XqlaZuHBROLpMuhfCsMm1Xu12i4rK9BwC6WEKessyA9OVqHbR@NKmvKjnbsO0eDq77qgBGyNY7ebQxfg9NDi4V531lH@04rBt7k0b/pdYlXLGU48GYww9Pn3z@IazT@s/aoc7BqlAG@96@ydRJAMpgI3FJChAe40xTJpmJWwEaQTQAZohugKRMoTkjIlN6m1Lsz8Qc "Python 3 – Try It Online") **Commented:** ``` from random import* def f(g): r=0 # last instruction x=y=0 # current position in the grid a=0 # y-direction b=1 # x-direction # grid of random characters of the same dimensions as g N=[[chr(randint(32,126))for _ in t]for t in g] # until the last instruction was a ; while';'!=r: # update instruction and random character N[y][x]=r=g[y][x] # update direction, ord(r)%9%6 maps # < -> 0, v -> 1, ^ -> 2, ^ -> 4, ' ' -> 5 a,b=[0,1,0,2,-1,a,-1,0,1,2,0,b][ord(r)%9%6::6] # update position, modulo takes care of the wrapping x=(x+b)%len(g[0]); y=(y+a)%len(g) # return random matrix where visited indices are replaced with the program return N ``` [Try it online!](https://tio.run/##ZVP/jqJADP6fp@jFGGB3NOremZyIj@ALsHoZYYTJwUA6I8rTe@0od3EPA22/fv0x7dgNrmrNx/1@xrYBlKYgoZuuRfcWFOoM56iMNwEApgugZwK1tA60sQ4vudOtId8tHdg7gfyCqIyDrrWafcQDVykoURfEk2OOYVZoVGP4KV0@4NsLPPFh0J7HtvJKosydQssg57WyUVDoRhlLMRakhZIi92mW5RVGHKeNiz5WYrlax/G5RfjlezqwyseA8hD4WhfjdO2Tfj0gXCmthIRo10rXKkzCbynyTHxcV0inXvhU9b@WPXufDYfsdkgxLR/aa46/hxfQYhFhPP05XUMjO/vkbWG2g4WAnuVSwJHl6im/CwjpR9oPT5filGYLsRQLsRKzpZD8YXtF39Mh@1dis1l/6WTcn4CmLS51C07@VhZyiWoc/RVl12lT@sBbGt3eT/G0ViYqs8UhTmBIo@FdPqHYjxiVu6AZR9NIh/pGI1WUtNdUUBU0xkLnVIkLoepqmRN41a7yNTtsS5QN38ZHqv39cVXBDjYInLLOQsrG3Dra/ByVLKJ4brtauyj8NJ8mjIPA7175JXtpeZclBWa1ti6qtVExMIm1kfRIwoiNYh4XE7C9sn/8jwB1yPftjXABVnVpGPLRH2h87xMIdtAHcNwGQcIKvdstGR4lbwLeIKsH2JF2BCLtEgJ7MoJ@e@y3zN4lfwA "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~70~~ 59 bytes ``` O%19ịı*Ɱ6ḊḊŻƲÆiḞݤ4Ṭs2¤‘œị¥@ȯƭƒ+ḷƭⱮ⁸%⁹,ZẈW¤ʋƬḢ€‘ŒṬ¬aØṖX¤€€o ``` [Try it online!](https://tio.run/##y0rNyan8/99f1dDy4e7uIxu1Hm1cZ/ZwRxcQHd19bNPhtsyHO@Yd3X1oicnDnWuKjQ4tedQw4@hkoNJDSx1OrD@29tgk7Yc7th9bC9T2qHGH6qPGnTpRD3d1hB9acqr72JqHOxY9aloD0jIJqP3QmsTDMx7unBYBNAUo2rQm/7/1o4Y5h7Yd2qZrByIfNcy1frh7y@H2yGNdXEBbdi5@1LgPJHG4Hag6C6ZWVxeq@P//MmsFLjuFMi6FOBsuLmsQA4htbIAcsChQ1loBzAHyyhQU7ICsOAWgIjtroGAZkMNVZhNXZgNSbWcNAA "Jelly – Try It Online") A link that is called as a monad with a list of Jelly strings and returns a list of Jelly strings. [Here’s a version that shows # in place of the random characters.](https://tio.run/##y0rNyan8/99f1dDy4e7uIxu1Hm1cZ/ZwRxcQHd19bNPhtsyHO@Yd3X1oicnDnWuKjQ4tedQw4@hkoNJDSx1OrD@29tgk7Yc7th9bC9T2qHGH6qPGnTpRD3d1hB9acqr72JqHOxY9aloD0jIJqP3QmsRHDXOVQSJNa/L/Wz9qmHNo26FtunYgEihj/XD3lsPtkce6uIA27Fz8qHEfSOJwO1B1Fkytri5U8f//ZdYKXHYKZVwKcTZcXNYgBhDb2AA5YFGgrLUCmAPklSko2AFZcQpARXbWQMEyIIerzCauzAak2s4aAA) ## Explanation (outdated) ### Helper link Takes `[[pos_x, pos_y], [dir_x, dir_y]]` as its left argument and a converted grid as its right (see below) and returns an updated list of position and direction ``` ¥1¦ | Do the following to the position component of the lost: ‘ | - Add 1 œị | - Multidimensional index into grid ȯ/ | Reduce using logical or ⁸ | Using the original left argument: +ṛƭ€ | - Add the new direction to the position, and append the new direction % | Mod with: ⁹ ¤ | - The grid ,Z | - Paired with its transpose Ẉ | - Lengths W | - Wrapped (which will mean only the position is affected) ``` ### Main link ``` “;>^<v”iⱮⱮ | Positions of each character in the grid in ";>^<v" ‘ | Increase by 1 ị ¤ | Index into: ı | - i *Ɱ4¤ | - ** each of 1..4 Ż | - Prepend zero Æi | - Convert from complex Ḟ | - Floor Ż | - Prepend zero ¤ | Starting with: 4 | - 4 Ṭ | - Untruthy ([0,0,0,1]) s2 | - Split into lists length 2 ([[0,0],[0,1]]) çƬ | Call the helper link with the grid as the right argument until no new value encountered Ḣ€ | Head of each (i.e. positions) ‘ | Add 1 ŒṬ | Multidimensional untruthy ¬ | Not aØṖX¤€€ | And with a list of lists of random printable characters for each original character in the grid o| Logical or with original grid ``` [Answer] # [R](https://www.r-project.org/), ~~217~~ ~~175~~ ~~178~~ ~~173~~ ~~155~~ 154 bytes ``` function(A,B=A,j=1:0,i=t(j+!j)){B[]=intToUtf8(runif(A,,95)+32,T);while(";"!=(B[i]=a=A[i]))i=(i-(j=switch(a,">"=1:0,"<"=1:2,v=0:1,"^"=2:1,j)))%%dim(A)+1;B} ``` [Try it online!](https://tio.run/##pY5Ba8JAEIXv@RWbAWGWbEFjC627E0h@gz2lCYTU4AaNEte1UPrb04la8CIeeni8w7z3zeuHhobm2NXO7jpMVUapamm2mCpLDtsobKX8zvKCbOeWu3fXvGJ/7GzDUfX2IqN5rJZSn9Z2s0LQEBJmuS2oopRNSkton7Clw8m6eo2VggTOdDCjx8rTdDFTUALF7PxMTiafdoupjGY6@xka3Faut19YI1cVeJZgaZAqVvxbBrcRfz5dIsnV/yoljF@lml9qgdvuabXBg@sP@411PF/4QLCMMRyFWzRnc1ZI8NFBcR@RjAgtAi3@gWCGFyIJElEKHpToB6jnuyjPiMCb0huG@Yeg66bhFw "R – Try It Online") Thanks to [@Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy) for very nice golfs resulting in -42 bytes (!) and clarifying some issues with the OP. -5 bytes inspired by [@Neil's Charcoal answer](https://codegolf.stackexchange.com/a/233243/55372), but as I understand this approach is also used in some other answers. Thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) for -17 bytes. [Answer] # Excel VBA, 400 bytes ``` Sub f() Set a=UsedRange m=a.Rows.Count n=a.Columns.Count r=1 c=1 Set u=[A1] While e=0 Set x=Cells(r,c) Set u=Union(u,x) Select Case x Case">":s=0:d=1 Case"<":s=0:d=-1 Case"v":s=1:d=0 Case"^":s=-1:d=0 Case";":e=1 End Select r=r+s c=c+d If r<1 Then r=m If r>m Then r=1 If c<1 Then c=n If c>n Then c=1 Wend For Each b In a.Cells If Intersect(b,u)Is Nothing Then b.Value=Chr(Int(113*Rnd+14)) Next End Sub ``` Formatted code with comments explaining function: ``` Sub f() Set a = UsedRange 'Save this here for shorter reference later m = a.Rows.Count 'Ditto n = a.Columns.Count 'Ditto r = 1 'Row c = 1 'Col Set u = [A1] 'Prime the collection with the first cell While e = 0 ' Pick the cell we're going to examine and add it to the collection Set x = Cells(r, c) Set u = Union(u, x) ' Change the row / column shift if we hit a control character Select Case x Case ">": s = 0: d = 1 Case "<": s = 0: d = -1 Case "v": s = 1: d = 0 Case "^": s = -1: d = 0 Case ";": e = 1 'Triggers the end of the While loop End Select ' Shift the row / cell and correct for edge (heh) cases r = r + s c = c + d If r < 1 Then r = m If r > m Then r = 1 If c < 1 Then c = n If c > n Then c = 1 Wend ' Loop through all the cells in the used range For Each b In a.Cells ' If that cell was not collected when moving through the program, fill it with a random character If Intersect(b, u) Is Nothing Then b.Value = Chr(Int(113 * Rnd + 14)) Next End Sub ``` Input is one character per cell: [![Input](https://i.stack.imgur.com/ovBn4.png)](https://i.stack.imgur.com/ovBn4.png) Output is editing in-place: [![Output](https://i.stack.imgur.com/1WeZr.png)](https://i.stack.imgur.com/1WeZr.png) [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~194~~ 188 bytes Expects and returns a matrix of characters. ``` m=>m.map((r,Y)=>r.map((C,X)=>(g=x=>(x%=W)-X|(y%=H)-Y?~(c="^<v> ".indexOf(m[y][x]))?g(x+(c<4?(v=--c%2,h=~-c%2):h)+W,y+=v+H):Buffer([Math.random()*95+32])+'':C)(W=m[0].length,y=H=m.length))) ``` [Try it online!](https://tio.run/##TZBPb5wwEMXv/hSjrVb2FHBWaXroglmpUau9VD3ksIlYqChr/kRgtsaxQG3y1TeGRmoP9rzfzBvJfo@5zYdCN2cTqP4kL1dXIFX@s5Vg6mYA00MlDdB3FKSVejJNJ4nzfMtNzXWuTn0HAn6AiGHDNzeElOLSibjjXX5mTPsPKGL9F279ewesEqO7x7U4YHD/h01rscfgYffCCrHKIhvDijfqJMfvJeuSKU3GFHFXsdFjRXSzY1YEQbG@9mvxMlfc1ugd/MkT1tvj9vNTWUrNkv@ex/D9p4/eh@sUPUq3t8gOoks2KW@lqkztT2IvujdAxIuWv54aLRktB4pcy/z0tWnl3aQKtkFu@jujG1Ux5MO5bQxbHdVRrZCXvf6SFzUb5iR@E4A5luGfyVnmEJZxwjkfUgydS0vXAffThYpeDX0redtXzE2WDT1vaP7YN4pRivimjooieLBU8owXGwKJwRLIIkLCWbgTRQ6WrpuGsIAjCxA7lYEzxaFrutAzYqPMRrM7Dl8B "JavaScript (Node.js) – Try It Online") ]
[Question] [ The [Cantor function](https://en.wikipedia.org/wiki/Cantor_function) is continuous everywhere and constant [almost everywhere](https://en.wikipedia.org/wiki/Almost_everywhere), but has an average slope of 1: [![fncantor](https://i.stack.imgur.com/cauCV.png)](https://i.stack.imgur.com/cauCV.png) The function can be found recursively: \$f\_0(x)=x\$ \$f\_{n+1}(x)=\left\{\begin{matrix}\frac{1}{2}f\_n(3x)&x\in[0,\frac{1}{3})\\ \frac{1}{2}&x\in[\frac{1}{3},\frac{2}{3})\\ \frac{1}{2}+\frac{1}{2}f\_n(3x-2)&x\in[\frac{2}{3},1] \end{matrix}\right.\$ The Cantor function is the limit of this process, \$\lim\limits\_{n\to\infty} f\_n(x)\$: [![iteration limit](https://i.stack.imgur.com/JpLpm.gif)](https://i.stack.imgur.com/JpLpm.gif) # The Challenge Given real x (which can assume the form of a float or rational number) of the interval \$[0,1]\$ and nonnegative integer n, return \$f\_n(x)\$. # Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins. * Assume only valid input will be given. * Error should be under one ten-thousandth (±0.0001) for the test cases. # Test Cases ``` In: 0.3 3 Out: 0.3875 In: 0.1 0 Out: 0.1 In: 0.29 4 Out: 0.375 In: 0.11 5 Out: 0.2415625 ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~25~~ 27 bytes ``` {⊥1⊥1⌊⊤1∘≠⍛×\0,3⊤⍵×3*⍺}÷2*⊣ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR11JDMO7petS1xPBRx4xHnQse9c4@PD3GQMcYKPSod@vh6cZaj3p31R7ebqT1qGvx/7RHbRMe9fY96mo@tN74UdvER31Tg4OcgWSIh2fwf2OFNAUDPWMuAzBtyGUCpo0suUwhAoZcEBXmRlApYyMuXV1dLg0jBaNHvVsMFAw1H3UuNFAwVQA6Rg@oQMGQi0vT382NyzPPCqRcwVhBwb@0BMy2MDeFChsCFcKEDaFiRpYKJnClCJWGQLOhokYmhqZmRqYA "APL (Dyalog Extended) – Try It Online") Inline tacit function, which can be used as `n f x`. Uses the method described in [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/207417/78410). I changed one part of the algorithm: * This one doesn't consider integer and fractional parts separately; rather, the fractional part is included in the last digit. (e.g. the base-3 representation of 8.1 is `[2, 2.1]`.) Later, at the step where 2s are changed into 1s, all digits `≥2` are reduced by 1 instead, and **(+2 bytes)** the fractional part of the last digit is removed if its integer part is 1. ``` {⊥1⊥1⌊⊤1∘≠⍛×\0,3⊤⍵×3*⍺}÷2*⊣ ⍝ Left: n, Right: x { ⍵×3*⍺} ⍝ 3^n*x 3⊤ ⍝ Convert to base 3; last digit may have fractional part 0, ⍝ Prepend 0 to avoid error on ⊤ over an empty array 1∘≠⍛×\ ⍝ Keep each digit unless at least one 1 appears somewhere on its left ⊤ ⍝ Convert each digit to binary 1⌊ ⍝ Clamp all digits >1 to 1 (effectively cuts the fractional part of ⍝ the last digit if its integer part is 1) 1⊥ ⍝ Treat the binary of each digit as base 1 and convert back to a number ⍝ Since all numbers are <3, effectively "decrement if ≥2" ⊥ ⍝ Treat as base 2 and convert to single number ÷2*⊣ ⍝ Divide by 2^n ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 33 bytes ``` 3y^i*1&\3_YAt1=f"O@QJh(wkw]XB+wW/ ``` Inputs are `n`, then `x`. [Try it online!](https://tio.run/##y00syfn/37gyLlPLUC3GOD7SscTQNk3J3yHQK0OjPLs8NsJJuzxcH6iEy0DPGAA) Or [verify all test cases](https://tio.run/##y00syfmf8N@4Mi5Ty1Atxjg@0rHE0DZNyd8h0CtDozy7PDbCSbs8XP@/S8h/Yy4DPSAGkoZcJkDSyJLLFMQxBAA). ## Approach The code uses a non-recursive approach, based on the procedure for computing the Cantor function \$f\_\infty(x)\$ that appears in [Wikipedia](https://en.wikipedia.org/wiki/Cantor_function#Definition), modified so that it computes \$f\_n(x)\$ instead: 1. Multiply \$x\$ by \$3^n\$. 2. Decompose the result into integer part \$M\$ and decimal part \$F\$. 3. Express \$M\$ in base \$3\$. Let \$B\$ be the resulting sequence of up to \$n\$ digits from the set \$\{0, 1, 2\}\$. 4. If \$B\$ contains a \$1\$, replace every digit after the first \$1\$ by \$0\$. 5. Replace any remaining \$2\$s with \$1\$s. 6. Interpret the result as a binary number. 7. If \$B\$ didn't contain \$1\$s, add \$F\$. 8. Divide by \$2^n\$. ## Some golfing tricks * Using a `for` loop instead of an `if` branch for step 4 saved quite a few bytes. The value for the branch condition (index of first \$1\$) needed to be used within the branch code (to replace subsequent digits by \$0\$). This is cumbersome in MATL, as the `if` branch consumes (pops) its condition. Instead, the loop solves this more elegantly: since the branch condition was either empty or a vector of indices of \$1\$s in \$B\$, it can be looped over: if it's empty the loop is simply not entered. And then the loop variable can be used within the loop code. The fact that the loop, unlike the conditional branch, may iterate *several* times (if there are more than one \$1\$ digit) is not harmful here, because the substitutions in step 4 are idempotent: they simply overwrite some of the previous \$0\$s with new \$0\$s. * Step 7 is partly handled within the `for` loop. Specifically, if the loop is entered, the decimal part \$F\$ should not be added later on. To implement this, the loop iteration replaces \$F\$ (previously stored in the stack) by \$0\$. This is done by a round-down operation (`k`), which is convenient because it uses only 1 byte and is, again, idempotent: the result remains equal to \$0\$ in all iterations after the first. * The MATL function that converts from binary to decimal (`XB`) treats any digit other than \$0\$ as if it were \$1\$, which is useful for steps 5 and 6. ## Commented code ``` 3 % Step 1. Push 3 y % Implicit input: n. Duplicate from below: pushes n below and % above the 3 ^ % Power: gives 3^n i* % Input: x. Multiply: gives x*3^n 1 % Step 2. Push 1 &\ % Two-output modulus: gives modulus (F) and quotient (M) 3_YA % Step 3. Convert to base 3, with digis 0, 1, 2 t1= % Step 4 and part of step 7. Duplicate. Compare each entry with 1 f % Vector (possibly empty) of indices of true values; that is, % positions of digit 1 " % For each index k O % Push 0 @Q % Push k+1 Jh( % Write 0 at positions k+1, k+2, ..., end wkw % Swap, round down, swap. This replaces F by 0 ] % End XB % Steps 5 and 6. Convert from binary to decimal, with digit 2 % interpreted as 1 + % Part of step 7. Add F, or 0 wW/ % Step 8. Swap (brings n to top), 2 raised to that, divide % Implicit display ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 38 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/) ``` {×⍺×1-⍵:2÷⍨(1∘≤+(1≠⌊)×(⍺-1)∇⊢-⌊)3×⍵⋄⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/rw9Ee9uw5PN9R91LvVyujw9ke9KzQMH3XMeNS5RBvI6FzwqKdL8/B0DaAqXUPNRx3tj7oW6YLEjEE6tz7qbgGStf/THrVNeNTb96ir@VHvmke9Ww6tN37UNvFR39TgIGcgGeLhGfzfB6xmlbGCgYKJgimQBGOuIIiwgR5QQs8QiI0sQQwgCwgNFQy5fHSCdDR8FNIOrQjSBAA "APL (Dyalog Unicode) – Try It Online") Combines the cases of the recurrence using $$ f\_{n+1}(x) = \frac{1}{2}\begin{cases} 0+1×f\_n(3x-0), x\in[0,1/3) \\ 1+0×f\_n(3x-1), x\in[1/3,2/3)\\ 1+1×f\_n(3x-2), x\in[2/3,1] \end{cases} $$ which can be condensed (note \$u=3x\$) to $$ f\_{n+1}\left(\frac{1}{3}u\right) = \frac{1}{2}\big( (u<1)+(\lfloor u\rfloor\neq 1)×f\_n(u-\lfloor u \rfloor)\big) $$ (since comparisons resolve to True=1 or False=0). This fails for `x=1` since then `⌊u` is 3 instead of 2. Using ceiling instead of floor would then fail for `x=0`, so it ends up shorter to check specifically for `x=1`. ``` { ... } ⍺=n; ⍵=x ×⍺×1-⍵: ⍝ If n>0 or x≠1: 3×⍵ ⍝ Let u=3x (⍺-1)∇⊢-⌊ ⍝ f(n-1, u-floor(u)) (`1∘|` ←→ `⊢-⌊`) (1≠⌊)× ⍝ Multiply by 1 unless floor(u)=1 1∘≤+ ⍝ Add 1 unless 1 > u 2÷⍨ ⍝ Half of this ⋄ ⍝ Else: ⍵ ⍝ x ``` [Answer] # [Python 3](https://docs.python.org/3/), 54 bytes ``` f=lambda n,x:n and(1<x*3<2or x//.5+f(n-1,3*x%1))/2or x ``` [Try it online!](https://tio.run/##LYxBCoNADADvfUUuhY1NXWP0UNHHrMiiYKOIh/T1q7a9DMMcZv3s46KSUuzm8O6HAErWKAQdHLeWSVsuG5j3ef2ITp9MktmdEf23p3iRQGFScEUuJEiXMBU/KV9U/RNTjc0NYN0m3d15I0NMBw "Python 3 – Try It Online") Python 3 is used just for the `/2` to do float division; Python 2 would be a byte longer with `/2.`. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 62 bytes ``` f=lambda n,x:n and[f(n-1,e:=3*x),1+e//2*f(n-1,e-2)][e>1]/2or x ``` [Try it online!](https://tio.run/##LYxBCsIwEADvvmKP2bo13URBA/UjpYdIEyzoNoQe4uujxV6GYQ6TPutzEXtNudbYv/z7MXkQKk7AyzREJS1TcL1tChIfg9am2WNrcBzCnUdtlgylxo0EArOA6k6WLNImTN1fzI3Oe2K6oDsApDzLqn5DKoj1Cw "Python 3.8 (pre-release) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` _2çH+. ñH¥.ç<2$?<1$? ×3çɗ⁸⁹?’} ``` A full program accepting \$x\$ and \$n\$ which prints a floating-point representation of \$f\_n(x)\$ **[Try it online!](https://tio.run/##AToAxf9qZWxsef//XzLDp0grLgrDsUjCpS7DpzwyJD88MSQ/CsOXM8OnyZfigbjigbk/4oCZff///y4yOf80 "Jelly – Try It Online")** [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 69 bytes of course mathematica has a built-in for this: `CantorStaircase[x]` but you cannot choose `n` ``` x_~f~0:=x x_~f~n_:=If[(y=3x)<1,f[y,n-1]/2,If[y<2,.5,.5+f[y-2,n-1]/2]] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/78ivi6tzsDKtoILzMqLt7L1TIvWqLQ1rtC0MdRJi67UydM1jNU30gEKV9oY6eiZApE2kK1rBJWJjf0fUJSZV6LgkBZtoGeso2Acy4UkYKijYIAiYGSpo2CCqgSoxjT2/38A "Wolfram Language (Mathematica) – Try It Online") *@JonathanAllan saved 2 bytes* Here is also another approach from @att which is great! # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 57 bytes ``` If[#2<1,#,If[1<3#<2,1,(s=Boole[2#>1])+#0[3#-2s,#2-1]]/2]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zMtWtnIxlBHWQfIMrQxVrYx0jHU0Si2dcrPz0mNNlK2M4zV1FY2iDZW1jUq1lE20jWMjdU3ilX7H1CUmVei4JAWbaBnrKNgHMuFJGCoo2CAImBkqaNggqoEqMY09v9/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # JavaScript (ES6), 45 bytes Expects `(n)(x)`. ``` n=>g=x=>n--?((x*=3)<1?g(x):x<2||1+g(x-2))/2:x ``` [Try it online!](https://tio.run/##fcw9DoJAEEDh3pPMaHbdHykkDHTeg8CywZAdI8RMwd1XsaOhe8WX92w/7dy9x9eiEvchD5QT1ZGE6qRUAyBn8ljZJoJgKZVbV3v5tXKIV1dK7jjNPAU9cYQBPILR3qBe@DFK6KFAPO2J2Yg9JLeNuPsRKf4XuyP5Cw "JavaScript (Node.js) – Try It Online") ### Commented ``` n => // outer function taking n g = x => // inner recursive function taking x n-- ? // decrement n; if it was not equal to 0: ( // compute f_n(x): (x *= 3) < 1 ? // multiply x by 3; if the result is less than 1: g(x) // use g(x) : // else: x < 2 || // use 1 if x is less than 2 1 + g(x - 2) // otherwise, use 1 + g(x - 2) ) / 2 // in all cases, divide the result by 2 : // else: x // stop recursion and return f_0(x) = x ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~73~~ \$\cdots\$ ~~71~~ 69 bytes Saved 4 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! ``` float f(n,x)float x;{x*=3;x=n--?(x<1?f(n,x):x<2?1:1+f(n,x-2))/2:x/3;} ``` [Try it online!](https://tio.run/##bZHtaoMwFIb/9yoOgpC0sTWxbmuj64@xq1jLEI2b0MWiMsKK1@7yYW33IRhO8j7nPSc5efCW58NQHuusgxJJorCLFT@reRpxlcog2CGV0J2TtyphO7qlC7sNGMYrtlWriPdDJTv4yCqJPuuqwLPzDPSXv2fNHJqXA6Rw9vbqme3V5kn/sUfgdh95PbcZroFOtN2rcmnhMiIQLqlZ2MaGdIRNTYtKhxqQwJpA/MNNqJNQnSgsZA0f7uPJM3IxW9P4jk2JdQPI2FeyEEqnhXwME2irL1GX6OKKV@OBxjGHxcJyGNwLXLswLuO9LHHgE2AKyYss/8guv9WAm8JvRWhluuP/yYU4dpnGWghA3BQuATkpgRCP1DyFgF6ZU6PbK5FnGvQLYu/hlxA8mtVv91KPUupjAi3Rox7t9IstwzCkh7HbftYP3w "C (gcc) – Try It Online") [Answer] # [Python 3.8](https://docs.python.org/3.8/), 70 ~~74~~ bytes *1 byte saved thanks to @FryAmTheEggman* ``` f=lambda n,x:n and((1<=(t:=x*3))+f(n-1,t-2*(t>=2))*(t>=2or 1>t))/2or x ``` [Try it online!](https://tio.run/##NYxBDoIwEEXXcIpZzuCgtNVEieUixkUNaSTBoSFd4OkrRd389/IWP7zjcxJzDnNK3o7u9egdCC@tgJMeUV0txtYulSHaeZRacax1hbGzmujLaQbVRaJDtiX5vAwCg8CtLLDZGwZDvKliaH6qLwzHf177afV7WxZhHiSicD7xG4nSBw "Python 3.8 (pre-release) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 78 bytes ``` sub f{my$b=pop;my$a=pop;$b--?($a<1/3?f(3*$a,$b):$a<2/3?1:1+f(3*$a-2,$b))/2:$a} ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhrTq3UiXJtiC/wBrISAQzVJJ0de01VBJtDPWN7dM0jLVUEnVUkjStgCJGQBFDK0NtiKiuEUhcU98IKFX7XyXeNs3B7b@BnrGCMZeBnqGCAZA0slQwAXEMFUz/5ReUZObnFf/XLUjMAQA "Perl 5 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~76~~ ... ~~60~~ 58 bytes *-6 bytes thanks to Robin Ryder, +1 byte to fix bug spotted by Neil, -2 bytes thanks to Giuseppe* ``` f=function(x,n,y=x*3)`if`(n,(min(f(y%%2,n-1),1)+!y<2)/2,x) ``` [Try it online!](https://tio.run/##VczbDoIwDIDhe55ihpBsWg7tmKfIu0BwUy4sCWACT49GDupd@@Vvm7EsuKubbHSZe3LZVTXLHhiGrN9qlVculwzyUbF0cggCAg5RAardZriQigl6Nb@QSaRBK@GL93A8GG9lhGRi/BqdIJ3bvxTBTEwpmj0ZzxcFX0V3t8JebzYsi9a25/UA6FMvO8Z6lsiIBekH13AS9MYX "R – Try It Online") Un-golfed: ``` cantor=f=function(x,n){ y=3*x # define y=3*x # to save characters later. if(n==0){ x } # if n==0 just return x else { # otherwise ( min( # whichever is smaller of: cantor(y%%2,n-1), # - call self using y mod 2 # (this works for the first & last thirds # but gives a result >1 for middle third) 1) # - 1 (to fix the middle third) +(y>=2) # for the top third we need to add 1 to # the result of the self call ) /2 # finally, we divide all above results by 2 } } ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes ``` Nθ≔↨×NX³θ³ηI∕↨²Eη∧¬№…ηκ¹§⟦ι¹⊖ι⟧ιX²θ ``` [Try it online!](https://tio.run/##TY4xD4IwEIV3f0XHu6QagTg5ISwMEgY341DhIo3QQltQf32tmBiHl9zL@@7l1a0wtRad94UaJldO/ZUMjLhfpdbKm4KDsAQn2ZOFfwI5q/QjHAlnIwaXBLXhrTJSOciEdZDLWTb0bYg5O4oBWs5S1UCpA6KnD/iqO8pavUT30BEFpa5QDT3hLIPnLKfaUE/KUQMSL5xJRPwNiJcBiHvvd2y7iSK/nrs3 "Charcoal – Try It Online") Link is to verbose version of code. Based on the Wikipedia entry, I convert the `3ⁿx` to base 3, then massage the digits so that the result can be interpreted as base 2 and divided by `2ⁿ`. Takes input in the order `n`, `x`. Explanation: ``` Nθ ``` Input `n`. ``` ≔↨×NX³θ³ηI∕ ``` Multiply `x` by `3ⁿ` and convert it to base 3. The last entry includes any remaining fractional part. ``` Eη∧¬№…ηκ¹§⟦ι¹⊖ι⟧ι ``` Map over the digits. If there was a previous `1` then set this digit to zero, otherwise map the digit to itself, `1`, or subtract `1`, depending on the floor of the digit. This ensures that the last digit (with the remaining fractional part) is converted correctly. ``` I∕↨²...X²θ ``` Convert from base 2, divide by `2ⁿ`, and output the final decimal as a string. Previous 34-byte solution did not work for `x=1`, as it only considered the decimal part of `x`: ``` Nθ≔×NX³θη≔⁻η⌊ηζFθ≔⊘§⟦ζ¹⊕ζ⟧∕ηX³ιζIζ ``` [Try it online!](https://tio.run/##TY6xDoIwEIZ3n6LjNalGYpyYiMbIgCHGzThUqPQSaKEtaHj5WoNGtrvvvy/3F5KbQvPa@1S1vTv1zV0Y6Gi8SKzFSsEFG2FhHlJGcv0Mw4aRjoZN/q8PtdYGZIBjgBlvJ37GSjrIUPU2JJPx0IaER@RrHnk9iBISl6pSvOAqGYkYSVVhRCOUC5Gktw9wexywFDDOaiClvyK5QeVgx60LAo2935L1Kor8cqjf "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order `n`, `x`. Explanation: ``` Nθ ``` Input `n`. ``` ≔×NX³θη ``` Multiply `x` by `3ⁿ`. ``` ≔⁻η⌊ηζ ``` Take the decimal part of that. ``` Fθ ``` Loop `n` times. ``` ≔⊘§⟦ζ¹⊕ζ⟧∕ηX³ιζ ``` Depending on the next base 3 digit of the above product, replace the decimal part with half of itself, half of 1, or half of the sum. ``` Iζ ``` Output the final decimal as a string. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 3Im*1‰`s3в¹£εTYèsi1V]2βY≠i+}¹o/ ``` Takes the loose inputs in the order \$n,x\$. Port of [*@LuisMendo*'s MATL answer](https://codegolf.stackexchange.com/a/207417/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##AToAxf9vc2FiaWX//zNJbSox4oCwYHMz0LLCucKjzrVUWcOoc2kxVl0yzrJZ4omgaSt9wrlvL///NAowLjI5) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6H/jiFwtw0cNGxKKjS9siji0@NzWkMjDK4ozDcNqa43ObYp81LkgU7s2Il//v45R2P/oaAM9Yx3jWB0gbahjAKaNLHVMIAKGOqaxsQA). **Explanation:** ``` 3Im # Push 3 to the power of the first input-integer * # Multiply it by the (implicit) input-decimal 1‰ # Get the divmod-1 to split the integer and decimal parts `s # Pop and push them separated to the stack in reversed order 3в # Convert the integer part to base-3 as list ¹£ # Only leave the first input-integer amount of base-3 digits ε # Map this list to: T # Push 10 Yè # Index `Y` into this # (`Y` is 2 by default, which wraps modulair indices into the 1) si # If the current digit we're mapping over is 1: 1V # Set `Y` to 1 ] # Close both the if-statement and map 2β # Convert the resulting list from base-2 to an integer Y≠i } # If `Y` is NOT 1: + # Add the decimal part that's still on the stack ¹o/ # And divide this by 2 to the power the first input-integer # (after which the result is output implicitly) ``` ]
[Question] [ ## Challenge Given an image of the sky, you must output the cloud cover in oktas. The image supplied will be an image file (the type is up to you) and the output should be to STDOUT. ## Oktas In meteorology, an okta is a unit of measurement used to describe the amount of cloud cover at any given location such as a weather station. Sky conditions are estimated in terms of how many eighths of the sky are covered in cloud, ranging from 0 oktas (completely clear sky) through to 8 oktas (completely overcast). The sky will always be a picture from around midday (so, blue sky, not red/night sky). The colour of a cloud will always be a colour which follows the following pattern: ``` #ABCDEF ``` Where `AB >= C0`, `CD >= C0` and `EF >= C0`. Or, in RGB: ``` (A, B, C) ``` Where `A >= 192`, `B >= 192` and `C >= 192`. Here are the percentage coverages related to the oktas: ``` 0% - 0 oktas 12.5% - 1 okta 25% - 2 oktas 37.5% - 3 oktas 50% - 4 oktas 62.5% - 5 oktas 75% - 6 oktas 87.5% - 7 oktas 100% - 8 oktas ``` The percentages are the percentage of the image which is cloud. If you the percentage cloud of your image is not a multiple of 12.5, you should round to the nearest. ## Output The output should just be the okta number (you don't have to say the unit). ## Examples ***1 okta*** (18.030743615677714% cloud) ![](https://upload.wikimedia.org/wikipedia/commons/1/16/Appearance_of_sky_for_weather_forecast,_Dhaka,_Bangladesh.JPG) ***0 oktas*** (0.0% cloud) ![](https://1.bp.blogspot.com/-lstV3uZJbPM/UHhLG5_vqAI/AAAAAAAAHGw/Hr9GN52jasM/s1600/spanish-sky.jpeg) ***3 oktas*** (42.66319444444445% cloud) [![](https://i.stack.imgur.com/qmRjN.jpg)](https://i.stack.imgur.com/qmRjN.jpg) (source: [hswstatic.com](https://s.hswstatic.com/gif/why-is-sky-blue-1.jpg)) ***1 okta*** (12.000401814778645% cloud) ![](https://i.stack.imgur.com/KTBF5.jpg) [**Python code used to calculate numbers**](https://gist.github.com/beta-decay/fbcdb6626c9ed50529596e78cd6dffc8) ## Winning Shortest code in bytes wins. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~18~~ 17 bytes ``` Yi191>3&A1eYm8*Yo ``` Example runs with the four provided images (sorry about preview quality; click for full resolution): [![enter image description here](https://i.stack.imgur.com/YXPQ5.png)](https://i.stack.imgur.com/YXPQ5.png) Or remove the last four characters to see the results without rounding: [![enter image description here](https://i.stack.imgur.com/gw2rg.png)](https://i.stack.imgur.com/gw2rg.png) ### Explanation ``` Yi % Implicitly input filename or URL. Read image. Gives an M×N×3 array 191> % Does each entry exceed 191? 3&A % True for 3rd-dim "lines" that only contain true. Gives an M×N matrix 1e % Linearize (flatten) into a 1×L row vector, with L = M*N Ym % Mean of vector 8* % Multiply by 8 Yo % Round. Implicitly display ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~114~~ ~~110~~ 98 bytes -4 bytes thanks to TheLethalCoder -12 bytes thanks to Ruud ``` import PIL.Image as P i=P.open(input()).getdata() print round(8.*sum(min(x)>191for x in i)/len(i)) ``` [Try it online!](https://tio.run/##FcsxCsMwDADAPa/QKHVwSaZ0aPdAB3/BECcV1JJwZEhf75Lbz37@UZl652JaHeLyDktJe4Z0QBz4GYNaFmSx5kgU9uxr8oQ0WGVxqNpkxTncjlawsOBJr/ExblrhBBZgun@vT9T7Hw "Python 2 – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 204 bytes ``` i->{int x=0,y=0,t=0,w=i.getWidth(),h=i.getHeight();for(;x<w;)for(y=0;y<h;){java.awt.Color c=new java.awt.Color(i.getRGB(x++,y++));if(c.getRed()>191&&c.getBlue()>191&&c.getGreen()>191)t++;}return 8*t/w/h;} ``` [Try it online!](https://tio.run/##VY/BasMwDIbvfQqfit2kyXrbcNNBB@t6GINtsMPYwYudWF1qF0duWkKePXPaMtaDkPT96ANtxF5M7U6ZjfzpYbuzDskmsMQjVEnhTY5gTTLho/@haDCBrSjVEIx2/ruCnOSVqGvyLMC0F1KjwND2FiTZBk7f0IEpP7@EK2vWPl7s86UvCuWUXA/KeG1QlcotgtB6CUYFa0Z6mC5aMEgO2U18DIWhmgySUuEHSNSUxfq8PikoNVLGC@soP8wbzoYpHPHjXHPW/v3wYCvrSJ4Z1ZBrSE@m19WSHqIoPkYRYxwKmp@okpQtZnez8fi0LyuvrsDKKWXOhGEU8c4p9M6Q2wmmTap51/M01bYhtba@kgRIZYUkqKEmYMj7@uV@1HX9Lw "Java (OpenJDK 8) – Try It Online") I always forget that TIO outputs STDERR to the debug tab.. Maybe it could like highlight red in case of an error? [Answer] # C#, ~~150~~ 146 bytes ``` b=>{int t=0,c=0,w=0,h;for(;w<b.Width;++w)for(h=0;h<b.Height;++t){var p=b.GetPixel(w,h++);if(p.R>191&p.G>191&p.B>191)c++;}return(int)(c/(t+0d)*8);} ``` *Saved 4 bytes thanks to @Ian H.* Full/Formatted version: ``` using System.Drawing; namespace System { class P { static void Main() { Func<Bitmap, int> f = b => { int t = 0, c = 0, w = 0, h; for (; w < b.Width; ++w) for (h = 0; h < b.Height; ++t) { var p = b.GetPixel(w, h++); if (p.R > 191 & p.G > 191 & p.B > 191) c++; } return (int)(c / (t + 0d) * 8); }; string[] testCases = { @"Appearance_of_sky_for_weather_forecast,_Dhaka,_Bangladesh.JPG", @"spanish-sky.jpeg", @"why-is-sky-blue-1.jpg", }; foreach (string testCase in testCases) { using (Bitmap bitmap = new Bitmap(testCase)) { Console.WriteLine(f(bitmap)); } } Console.ReadLine(); } } } ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 200 bytes ``` $a=New-Object System.Drawing.Bitmap $args[0] 0..($a.Height-1)|%{$h=$_;0..($a.Width-1)|%{$i+=(("$($a.GetPixel($_,$h)|select R,G,B)"|iex)['R','G','B']-ge192).count-eq3}} [int]($i/($a.Height*$a.Width)*8) ``` Gets input `$args[0]` as the full image file-path, constructs a `New` `Bitmap` object into `$a`. This is just the internal object name; it supports JPG, PNG, etc. We then double-loop through the `.height` and then the `.width` of the image, touching each `pixel`. We pull out the `R,G,B` values and then select those that are `-g`reaterthanor`e`qual to `192` and make sure that `count` is `3` (i.e., all of them are white-ish). That Boolean result is added into our accumulator `$i`. We then divide out to get the percentage, multiply it by `8` to get the number of oktas, and then `[int]` to get just an integer output. *(Note that this performs Banker's Rounding -- if that's not allowed it'll be several more bytes to change the rounding method.)* [Answer] # x86 Machine Code, 34 bytes ``` 51 31 D2 AD F7 D0 25 C0 C0 C0 00 75 01 42 E2 F3 C1 E2 03 DB 04 24 52 DB 04 24 DE F1 DB 1C 24 58 5A C3 ``` These bytes of code define a function that takes a bitmap input and returns an integer value indicating its oktas. [As in C](https://codegolf.meta.stackexchange.com/questions/13210/list-input-in-c-and-length-argument), arrays (like bitmaps) are represented as a pointer to the first element and a size/length. Thus, this function takes two parameters: the total number of pixels in the bitmap (rows × columns) and a pointer to the bitmap itself. This code uses a custom register-based calling convention, where the bitmap pointer is passed in the `ESI` register and the bitmap size is passed in the `ECX` register. The result (oktas) is, per usual, returned in `EAX`. As already stated above, the input is taken as a bitmap. Specifically, a 32-bpp format is used, in a little-endian format, but the alpha channel (highest-order byte) is ignored. This simplifies a lot of things, allowing us to simply iterate through each pixel and check its 32-bit RGB color value. A clever optimization is also used here. Instead of isolating each color component and checking whether it is >= 192, we just mask the entire 32-bit value by 0xC0C0C0 and test whether the result is >= 0xC0C0C0. This will evaluate to true for all "cloud" colors, and false for all "sky" (non-cloud) colors. Well, *I* thought it was clever! :-) It certainly saves a large number of bytes. Therefore, in order to test this code, you will need to convert the input images to 32-bpp bitmaps. You cannot use Windows Paint for this, because it supports maximum of 24 bits-per-pixel. However, there are a number of other software solutions that can do it, such as Adobe Photoshop. I used [this free tool](https://pngtobmp32.codeplex.com), which converts a PNG to a 32-bpp BMP on Windows, meaning that you need only convert from JPEG to PNG (which Paint can do). Other assumptions that I posit are eminently reasonable: * The bitmap is assumed to have a size greater than 0 (*i.e.*, it is assumed to contain at least one pixel). This is reasonable because, when they sky is null, we have bigger problems than meteorology. * The direction flag (`DF`) is assumed to be clear so that we will iterate correctly through the bitmap using the `LODSD` instruction. This is the same assumption made by most x86 calling conventions, so it seems fair. If you don't like it, add 1 byte to the count for a `CLD` instruction. * The rounding mode for the x87 FPU is assumed to be set to round-to-nearest-even. This ensures that we get the correct behavior when we convert the number of oktas from a floating-point temporary to the final integer result, as verified by test case #4. This assumption is reasonable because this is the default state for the FPU *and* it is required to be maintained even in C code (where truncation is the default rounding behavior, forcing compilers that wish to be standards-compliant to generate inefficient code that changes the rounding mode, does the conversion, and then changes the rounding mode back). **Ungolfed assembly mnemonics:** ``` ; int ComputeOktas(void* bmpBits /* ESI */, ; uint32_t bmpSize /* ECX */); push ecx ; save size on stack xor edx, edx ; EDX = 0 (cloudy pixel counter) CheckPixels: lodsd ; EAX = DS:[ESI]; ESI += 4 not eax and eax, 0x00C0C0C0 jnz NotCloudy inc edx NotCloudy: loop CheckPixels ; ECX -= 1; loop if ECX > 0 shl edx, 3 ; counter *= 8 fild DWORD PTR [esp] ; load original size from stack push edx fild DWORD PTR [esp] ; load counter from stack fdivrp st(1), st(0) ; ST(0) = counter*8 / size fistp DWORD PTR [esp] ; convert to integer, rounding to nearest even pop eax ; load result pop edx ret ``` Surely you haven't made it all this way down and are still wondering how the code works? :-) Well, it's pretty simple. We just iterate through the bitmap one 32-bit value at a time, checking to see if that pixel RGB value is "cloudy" or "not cloudy". If it's cloudy, we increment our pre-zeroed counter. At the end, we compute: cloudy pixels⁄total pixels × 8 (which is equivalent to: cloudy pixels⁄total pixels ÷ 0.125). I can't include a TIO link for this because of the need for input images. I can, however, provide you with the harness I used to test this on Windows: ``` #include <stdio.h> #include <assert.h> #include <Windows.h> int main() { // Load bitmap as a DIB section under Windows, ensuring device-neutrality // and providing us direct access to its bits. HBITMAP hBitmap = (HBITMAP)LoadImage(NULL, TEXT("C:\\...\\test1.bmp"), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION); assert(hBitmap != NULL); // Get the bitmap's bits and attributes. DIBSECTION dib; GetObject(hBitmap, sizeof(dib), &dib); assert(dib.dsBm.bmBitsPixel == 32); uint32_t cx = dib.dsBm.bmWidth; uint32_t cy = abs(dib.dsBm.bmHeight); uint32_t sz = cx * cy; assert(sz > 0); int oktas = ComputeOktas(sz, dib.dsBm.bmBits); printf("%d\n", oktas); return 0; } ``` Be careful with this, though! As defined above, `ComputeOktas` uses a custom calling convention, which a C compiler will not respect. You need to add code at the top of the assembly language procedure to load values from the stack into the expected registers, *e.g.*: ``` mov ecx, DWORD PTR [bmpSize] mov esi, DWORD PTR [bmpBits] ``` [Answer] # C#, 313 bytes ``` namespace System.Drawing.Imaging{b=>{unsafe{int t=0,c=0,y=0,x,w=b.Width,h=b.Height;var d=b.LockBits(new Rectangle(0,0,w,h),(ImageLockMode)1,(PixelFormat)137224);for(;y<h;++y){var r=(byte*)d.Scan0+y*d.Stride;for(x=0;x<w*3;++t)if(r[x++]>191&r[x++]>191&r[x++]>191)c++;}b.UnlockBits(d);return(int)(c/(t+0d)/0.125);}}} ``` Obviously longer than my other answer but this one uses `LockBits` and `unsafe` code to directly access the image in memory; as such it is incredibly quick. I could probably remove the call to `UnlockBits` but it's more correct with it there. Full/Formatted version: ``` namespace System.Drawing.Imaging { class P { static void Main() { Func<Bitmap, int> f = b => { unsafe { int t = 0, c = 0, y = 0, x, w = b.Width, h = b.Height; var d = b.LockBits(new Rectangle(0, 0, w, h), (ImageLockMode)1, (PixelFormat)137224); for (; y < h; ++y) { var r = (byte*)d.Scan0 + y * d.Stride; for (x = 0; x < w * 3; ++t) if (r[x++] > 191 & r[x++] > 191 & r[x++] > 191) c++; } b.UnlockBits(d); return (int)(c / (t + 0d) / 0.125); } }; string[] testCases = { @"Appearance_of_sky_for_weather_forecast,_Dhaka,_Bangladesh.JPG", @"spanish-sky.jpeg", @"why-is-sky-blue-1.jpg", }; foreach (string testCase in testCases) { using (Bitmap bitmap = new Bitmap(testCase)) { Console.WriteLine(f(bitmap)); } } Console.ReadLine(); } } } ``` [Answer] # JavaScript, ~~83~~ 77 bytes -6 bytes by *ETHproductions* ``` f=i=>(z=a=b=0,i.map(e=>{z=e<192||z;(++b%4)||((z||(a+=64))&&(z=0))}),a/b+1>>1) ``` ## Inputs [Picture #1](https://www.dropbox.com/s/8r7julq4drprz4d/1.jpg?dl=1) [Picture #2](https://www.dropbox.com/s/po6xsob6nvxu4fq/2.jpg?dl=1) [Picture #3](https://www.dropbox.com/s/4hvn9kix4v1bfad/3.jpg?dl=1) [Picture #4](https://www.dropbox.com/s/sjf6xr6tixgjoem/4.jpg?dl=1) ## Demo ``` f=i=>(z=a=b=0,i.map(e=>{z=e<192||z;(++b%4)||((z||(a+=64))&&(z=0))}),a/b+1>>1) window.onload = function(){ var input = document.getElementById('input'); input.addEventListener('change', handleFiles); } function handleFiles(e){ var canvas = document.getElementById('canvas') var ctx = canvas.getContext('2d'); var img = new Image; img.onload = function(){ canvas.height = img.height canvas.width = img.width ctx.drawImage(img, 0,0); data = ctx.getImageData(0,0,canvas.width,canvas.height).data; console.log(f(data))//invoke f, send imageData as input } img.src = URL.createObjectURL(e.target.files[0]); } ``` ``` <input type="file" id="input"/><br> <canvas id="canvas" style="max-width:400px"/> ``` [Answer] # C (POSIX), 103 bytes Assumes input as BMP file on stdin. ``` b,c,i,m=0xc0c0c0;main(){lseek(0,54,0);for(;read(0,&b,3);c+=(b&m)==m,i++);printf("%d",(i+16*c)/(2*i));} ``` [Answer] # dc, 74 bytes ``` ???*sa?[1+]ss[r1+r]st[?191<s]su0ddsd[0luxluxlux3=t1+dla>r]dsrxr8*la2/+la/p ``` Input is taken as a P3 ppm file, with all whitespace as newlines. Output is to STDOUT. [Try it online!](https://tio.run/##bYkxCoAwDEX3HqUdbCqCgporuJcMxYwdJKng7StVR3n/wYfHe62IaDVhBEeqUcAJaYkIE8xKenpm5ejzeb3rlwKOc1qFWOWS0eYUOpdTd9S69SY0hsH4h/b@/NoN) [Answer] # JavaScript (ES6), 218 bytes ``` (a,c=document.createElement`canvas`,w=c.width=a.width,h=c.height=a.height,x=c.getContext`2d`)=>x.drawImage(a,0,0)||x.getImageData(0,0,w,h).data.reduce((o,_,i,d)=>o+(i%4|d[i++]<192|d[i++]<192|d[i]<192?0:1),0)/w/h*8+.5|0 ``` Takes an `Image` object as input, which can be created from an `<image>` element. [Test it out here on CodePen!](https://codepen.io/justinm53/pen/MvaLdM) ## Alternative If input can be taken as flat array of RGBA values, with dimensions: **82 bytes** ``` (d,w,h)=>d.reduce((o,_,i)=>o+(i%4|d[i++]<192|d[i++]<192|d[i]<192?0:1),0)/w/h*8+.5|0 ``` This input format is very similar to what [this answer on meta](https://codegolf.meta.stackexchange.com/a/9099/69583) suggests. [Answer] # Mathematica 89 bytes The following binarizes the picture and determines the fraction of clouds, i.e. white pixels. Then it determines how many times .125 fits into the result. It returns the floor of that value. ``` o@i_:=⌊8Tr@Flatten[ImageData@MorphologicalBinarize[i,.932],1]/Times@@ImageDimensions@i⌋ ``` ]
[Question] [ The goal of this challenge is to take a positive integer `n` and output (in lexicographic order) all sequences \$S = [a\_1, a\_2, ..., a\_t]\$ of distinct positive integers such that \$\max(S) = n\$. For example, for an input `n = 3` your program should output the following eleven sequences in the following order: ``` [ [1, 2, 3], [1, 3], [1, 3, 2], [2, 1, 3], [2, 3], [2, 3, 1], [3], [3, 1], [3, 1, 2], [3, 2], [3, 2, 1], ] ``` (In general, for an input `n`, your program should output [\$A001339(n-1)\$](https://oeis.org/A001339) sequences.) --- This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code wins. [Answer] # [Python 2](https://docs.python.org/2/), 78 bytes ``` f=lambda n,l=[]:sum([f(n,l+[i+1])for i in range(n)if~-(i+1in l)],[l]*(n in l)) ``` [Try it online!](https://tio.run/##HcmxDkAwEIDhV7nxjhqwSTxJ06HCcUmdphgsXr0a4/f/8bm2Q7uceQx@n2YPasJo3XDeO1rGotpK3TriI4GAKCSv64JKwm@DZZUUyBkbXIUKvyjHJHoBY0/5Aw "Python 2 – Try It Online") Python 3 lets us save some bytes with set unpacking. **[Python 3](https://docs.python.org/3/), 74 bytes** ``` f=lambda n,l=[]:sum([f(n,l+[i])for i in{*range(1,n+1)}-{*l}],[l]*(n in l)) ``` [Try it online!](https://tio.run/##DclNCoAgEEDhq7gcf1qEu6CTiAujLGGcxGwR4tnN3ft46SvXTbp3v6KL2@4YKVyNXZ43gvEwJE2w3N@ZBRaoiuzoPGBWJGfepiqwWWXQCqCxGXLeUw5UwIMe/QM "Python 3 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` Of€¹umu´π ``` [Try it online!](https://tio.run/##yygtzv7/3z/tUdOaQztLc0sPbTnf8P//f2MA "Husk – Try It Online") ### Explanation ``` Of€¹umu´π ´π All length n combinations of 1..n mu Get the unique values of each list u Get the unique lists f€¹ Filter by those that contain n O And sort lexographically ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` {⟦₆⊇,?p}ᶠo ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/rR/GWPmtoedbXr2BfUPty2IP//f@P/UQA "Brachylog – Try It Online") * `{…}ᶠo`: order all results of: * `⟦₆`: from `[1,2,…,N-1]` * `⊇`: try a subset (e.g. `[1,2]` then `[2]` then `[1]` then `[]`) * `,?`: append the input `[1,2,3]` * `p`: permute the list [Answer] # [Haskell](https://www.haskell.org/), 60 bytes ``` n!b=[[]|all(<n)b]++[k:c|k<-b,c<-n!filter(/=k)b] f n=n![1..n] ``` [Try it online!](https://tio.run/##DcmxCoAgEADQva84ocEojWgL/RJxUFESryPK0X@33vpO95aI2Dsxr42xzSFyRZO382zKEVpRwi9BCWIpY40PX3X5d0hAmpjZpCTbL5cJNNxPpgojJNj7Bw "Haskell – Try It Online") Very much like xnor's Python approach, but my `b` is the complement of their `l`. ## Explanation Definition: an `n`-SDPI is a sequence of distinct positive integers `1 ≤ i ≤ n`, among which is `n`. We can think about "using up" numbers as we write such a sequence: if `n=5` and we start by writing down a `2`, only `[1,3,4,5]` are left at our disposal (we can't reuse 2). `n!b` computes all of the *continuations* of an `n`-SDPI where we have only the numbers in `b` left at our disposal. Let's call `b` our "bag" of numbers that could still go in the sequence. For example: `4![1,3]` returns all the ways we can continue if we've already written down a 2 and a 4 (in some order), and we have a `1` and a `3` left in our bag. Which continuations are there? Either we stop here (yielding `[]`), or we turn to our bag (yielding some non-empty continuations). 1. If `n` is no longer in our bag (`all(<n)b`), then we've made a valid n-SDPI, so we're happy ending the list here and yield `[]` as a possible continuation. 2. Furthermore, for every `k` in our bag, we can place `k`, followed by every continuation `c` from `n!filter(/=k)b` (removing `k` from the bag). Since `b` is always sorted, and we yield `[]` before non-empty lists, the result is also lexicographically sorted. Finally, `f` asks which `n`-SDPIs we can make with a full bag (`[1..n]`). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ ~~9~~ ~~8~~ 7 bytes ``` œ!RẎṢiƇ ``` [Try it online!](https://tio.run/##y0rNyan8///oZMWgh7v6Hu5clHms/f/hdvf//40B "Jelly – Try It Online") -1 byte [thanks to](https://codegolf.stackexchange.com/questions/213543/sequences-of-distinct-positive-integers/213546?noredirect=1#comment500174_213546) [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus) -1 more byte [thanks to](https://codegolf.stackexchange.com/questions/213543/sequences-of-distinct-positive-integers?answertab=votes#comment500194_213546) Sisyphus ## How it works ``` œ!RẎṢiƇ - Main link. Takes n on the left R - Yield [1, 2, ..., n] œ! - For each i = 1, 2, ..., n, yield all length-n permutations of [1, 2, ..., n] Ẏ - Join into a single list Ṣ - Sort Ƈ - Keep those where i - The 1-based index of n is non-zero (i.e n is in the list) ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 24 bytes ``` {t@<t:(x=|/)#??'1++!x#x} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqrrEwabESqPCtkZfU9neXt1QW1uxQrmi9n@agvF/AA "K (ngn/k) – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), ~~132~~ ~~124~~ 117 bytes ``` n=>1.to(n-1).toSet.subsets().flatMap(_.+(n).toSeq.permutations).toSeq.sorted(Ordering.Implicits.seqOrdering[Seq,Int]) ``` * Thanks to [user](https://codegolf.stackexchange.com/users/95792/user) for -7 characters! [Try it online!](https://scastie.scala-lang.org/O5hgqCR8R2iDufhaSD7oDA) [Answer] # JavaScript (ES6), ~~89~~ 82 bytes This started as a port of [@xnor's method](https://codegolf.stackexchange.com/a/213547/58563) and then was golfed the JS way from there. ``` f=(n,s=[],i)=>i>n?[]:[...!i^s.includes(i||n)?[]:i?f(n,[...s,i]):[s],...f(n,s,-~i)] ``` [Try it online!](https://tio.run/##VYxNDoIwEIX3nmJMXLSxNrpwA6IHITUYLDiGTJURN4BXxymuXL28v@9@eV@4bPHx2lC4@mmqMkWGs9wZ1NkRj3TKXZJba5d4ZotUNt3Vs8JhIB0rPFVyiAM26HSSszNiYshm80Htpiq0iiCDXQoEB9htRddrDf0CoPUsjax1Kq4MxKHxtgm1KuJl1dMIiYjsbOOpft1GYP/sPJVesS7mG8pfwPsf8h8T0fPoP56jcTFOXw "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input s = [], // s[] = current sequence i // i = counter, initially undefined ) => // i > n ? // if i is greater than n: [] // stop the recursion and return an empty array : // else: [ // build a new array: ... // append the following values: !i ^ // if i = 0 and s[] does not include n s.includes(i || n) ? // OR i > 0 and s[] includes i: [] // append nothing : // else: i ? // if i > 0: f(n, [...s, i]) // append all the values returned by a // recursive call with i appended to s[] : // else: [s], // append s[] ... // append all the values returned f(n, s, -~i) // by a recursive call with i + 1 ] // end of new array ``` [Answer] # [SageMath](https://www.sagemath.org/), 93 bytes ``` lambda n:sorted(sum([[*Permutations(l)]for l in Subsets(range(1,n+1))if n in l],[]),key=list) ``` [Try it online!](https://sagecell.sagemath.org/?z=eJw1i7EKwjAURfd-xaVQeE_j0MWhUL9BcKwdUpJIMH2VvHTQr9cWPNvl3BP6e5XsPDkL6XTJxTvSdaZhOFx9ntdiS1xEKfEYloyEKLitk_qilK08PLVGji1zDJBNptEMI5unf_cpauGq2rpd_f84c1fhh6JHIOF9vHKUQnXjcLqANH48Gsc1GpCY5IWU2UD5CyZUNSk=&lang=sage&interacts=eJyLjgUAARUAuQ==) Inputs \$n\$ and returns a list of all permutations of every \$s\$ in \$\{s\subseteq\{1,2,\dots,n\} \mid n\in s\}\$ sorted lexicographically. ### Explanation ``` lambda n: # function taking integer n # returning a list of [*Permutations(l)]for l in # all permutations Subsets(range(1,n+1)) # of all subsets of {1,2,...,n} if n in l # that have n as an element sum( . . . ,[]) # flattened sorted( . . . ,key=list) # and sorted lexicographically ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~55~~ 45 bytes ``` Do[i!=##2&&##~#0~i,{i,0!=##||Print@{##2};#}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yU/OlPRVlnZSE1NWblO2aAuU6c6U8cAJFRTE1CUmVfiUA2UrbVWro1V@5/m4Jqcke@grFYXnJyYVxeUmJee6mD6HwA "Wolfram Language (Mathematica) – Try It Online") Inspired by xnor's python solution, and borrows from my answers to some [prior](https://codegolf.stackexchange.com/a/185137/81203) [problems](https://codegolf.stackexchange.com/a/191556/81203). Prints the list of sequences. Recursively traverses through all permutations of subsequences of `1..n` in lexicographic order, printing those which contain `n`. ``` 0!=##|| (* If n is in the current sequence, *) Print@{##2}; (* output. *) {i, % ;#} (* for i=1..n: *) Do[i!=##2&& (* if i is not in the current sequence, *) ##~#0~i, % ]& (* append it and recurse. *) ``` [Answer] # Scala, 87 bytes ``` n=>1.to(n-1).toSet.subsets.toSeq.flatMap(_.toSeq:+n permutations)sortBy(_ mkString " ") ``` [Try it online!](https://scastie.scala-lang.org/ilXuJlPYQxyGExZuIgi8aQ) [Answer] # Scala 3, 130 bytes ``` | =>(for< <-1 to|;> <-1 to|combinations<if>toSet|;? <- >permutations yield?)sortBy(_.map("%10s"format _ replace(' ','0'))mkString) ``` [Try it online!](https://scastie.scala-lang.org/MgYAPttOQCCwgmqkLX04mg) Readable variable names are so overrated. Who needs `n` when you can have `|`? # Scala, ~~140~~ 137 bytes ``` | =>(for{< <-1 to| > <-1 to|combinations<if>toSet| ? <- >permutations}yield?)sortBy(_.map("%10s"format _ replace(' ','0')).mkString) ``` Wow, this got long. [Try it online](https://scastie.scala-lang.org/XTxVkIU6Q029PmWndFDUNw) Ungolfed, with comments and sensible variable names: ``` n => (for { i <- 1 to n //For every i in the range [1..n] c <- 1 to n combinations i //Every subset of [1..n] of size i if c contains n //Make sure the max is n first p <- c.permutations //For every permutation of that subset } yield p //Yield that permutation ) sortBy( //Sort it with this function _.map( //For every number in the sublist "%10s"format _ replace(' ','0') //Pad it on the right to a width of ten using 0 ).mkString //Smoosh it into one string ) ``` ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes ``` Nθ≔⟦υ⟧ηFθ«≔ηζ≔⟦υ⟧ηF⊕ιFζ⊞η⁺⟦κ⟧Eλ⁺쬋μκ»IΦ⊕η⁼θ⌈ι ``` [Try it online!](https://tio.run/##XU69CsIwEJ6bp8h4gTg5dhJRKGjpXhxijSY0Sdv8iFR89piUDuJNd9/vdYLZbmAqxsqMwddBX7mFiZRo55x8GGjDhWKR7vtgcSLwGxUrJSieE1H8K4tFWpnOcs2N5zeQhOAFnAlughPZ2qjgoO2T58xGUCugKa4HDyfulr0neUr0QY2VxsOeOQ9HqXx68rdAEIoPU2DKwZQDX1IHnWuzO8Zt3DzVFw "Charcoal – Try It Online") Link is to verbose version of code. Directly generates all sequences containing values up to `n` in lexicographical order and then prints those containing `n`. Outputs values on separate lines with sequences double-spaced. Explanation: ``` Nθ ``` Input `n`. ``` ≔⟦υ⟧η ``` Start off with a list containing an empty sequence. ``` Fθ« ``` Loop `n` times. ``` ≔ηζ ``` Save the previous list of sequences. ``` ≔⟦υ⟧η ``` Start a new list containing an empty sequence. ``` F⊕ι ``` Loop from `0` to `i` inclusive. ``` Fζ ``` Loop over the previous list of sequences. ``` ⊞η⁺⟦κ⟧Eλ⁺쬋μκ ``` Make a space in the sequence for the inner index and add that at the beginning of the sequence. For example, if current sequence was `1 0`, then an inner index of `0` would give `0 2 1`, an inner index of `1` would give `1 2 0` and an inner index of `2` would give `2 1 0`. This is required so that the sequences are generated in lexicographical order. (Charcoal doesn't have an easy way to sort.) ``` »IΦ⊕η⁼θ⌈ι ``` Increment the sequences and print those containing `n`. [Answer] # [Wolfram Language](https://www.wolfram.com/language/), 109 bytes ``` {a_,b___}~p~{c_,d___}:=If[a==c,{b}~p~{d},a~Order~c] Sort[Join@@Permutations/@Append@#/@Subsets@Range[#-1],p]& ``` [Try it online!](https://tio.run/##Hcy7CsMgFIDhva8R6GQJpVtBOB3bpSEZReR4ax2iomaS@Or2sv3wwb9ieZsVi1PYe0VBpBBib7FVJYj@9ZXeLUNKFanyD3on2J5Jm9QUP1i6hFTYIzgPMJm0buV7Cz6PcIvReA3DCMsmsykZZvQvw4bTmZPIj31Kzhdm4cL7Bw "Wolfram Language (Mathematica) – Try It Online") Thanks to [@att](https://codegolf.stackexchange.com/users/81203/att) for a suggestion that saves four bytes. The first line of this answer is actually a lexicographic ordering function since the default sorting is not lexicographic. It checks if the first two terms of two lists are equal: if so it recurses on the remainder of the lists, and if not it returns the ordering of the two first elements. I expected to need to provide special cases for when one arrives at empty lists, but it appears that in the case of not returning a proper value, `Sort` falls back to the default `Order` function, which works fine. The function itself generates all subsets of `{1,2,...,n-1}`, appends `n` to each, then generates the permutations of each. These are then sorted into lexicographic ordering using the function defined. **att's impressive 74-byte answer:** (it feels improper to take credit for it, but I think it deserves recognition) ``` SortBy[Join@@Permutations/@Append@#/@Subsets@Range[#-1],aa~PadRight~#]& ``` `` is [\[Function]](http://reference.wolfram.com/language/ref/character/Function.html). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Lœ€æ€`êʒIå ``` [Try it online.](https://tio.run/##yy9OTMpM/f/f5@jkR01rDi8DEgmHV52a5Hl46f//xgA) **Explanation:** ``` L # Push a list in the range [1,(implicit) input] œ # Get all permutations of this list € # Map each permutation to: æ # Get its powerset €` # Flatten it one level down ê # Sort and uniquify this list of lists ʒ # Filter it by: Iå # Check if the current list contains the input # (after which the result is output implicitly) ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 36 bytes ``` {∧∪{⍵/⍨w∊¨⍵}⊃,/⊃¨(⊢,,¨)/¨↓⌂pmat⊢w←⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pRx/JHHauqH/Vu1X/Uu6L8UUfXoRVATu2jrmYdfSBxaIXGo65FOjqHVmjqA2XaJj/qaSrITSwBCpY/apsAUvo/DczoA6p@1LvmUe@WQ@uNH7VNfNQ3NTjIGUiGeHgG/09TMAYA "APL (Dyalog Extended) – Try It Online") Uses [Bubbler's APL tip](https://codegolf.stackexchange.com/a/211449/80214) for generating subsequences of a vector. ## Explanation ``` {∧∪{⍵/⍨w∊¨⍵}⊃,/⊃¨(⊢,,¨)/¨↓⌂pmat⊢w←⍵} w←⍵ assign input to w for later ⌂pmat⊢ generate matrix of all permutations of 1..input (⌂ is an extended symbol) ↓ convert matrix to list of vectors (⊢,,¨)/¨ generate all subsequences of each, which include the last item ⊃,/⊃¨ remove nesting for each, and join into a list of vectors ⍵/⍨ filter the vectors by: w∊¨⍵ whether the input exists in them ∪ remove duplicates ∧ Sort lexicographically (Extended symbol) ``` [Answer] # [Perl 5](https://www.perl.org/), 52 bytes ``` $n=$_;map/(.).*\1|[^1-$n]/|!/$n/||say,sort 1..$n x$n ``` [Try it online!](https://tio.run/##K0gtyjH9/18lz1Yl3jo3sUBfQ09TTyvGsCY6zlBXJS9Wv0ZRXyVPv6amOLFSpzi/qETBUE9PJU@hQiXv/3@Tf/kFJZn5ecX/dX3LTPUMDf7r5uUAAA "Perl 5 – Try It Online") Can run like this for n=3: ``` echo 3 | perl -nlE'$n=$_;map/(.).*\1|[^1-$n]/|!/$n/||say,sort 1..$n x$n' ``` But doesn't work for n > 9. For n=7 it used twelve seconds on my humble laptop and then about ten minutes for n=8. [Answer] # [Gaia](https://github.com/splcurran/Gaia), 9 bytes ``` ┅zf¦e¦Ė⁇ȯ ``` [Try it online!](https://tio.run/##ARoA5f9nYWlh///ilIV6ZsKmZcKmxJbigYfIr///Mw "Gaia – Try It Online") Generate all permutations of subsets of `[1..n]`, filter out those not containing `n`, and sort. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), ~~12~~ 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` õ à cá ÍüøU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=9SDgIGPhIM38%2bFU&input=MwotUg) ``` õ à cá ÍüøU :Implicit input of integer U õ :Range [1,U] à :Combinations c :Flat map á : Permutations Í :Sort ü :Group and sort by øU : Contains U? ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=uniq -na`, 106 bytes It's twice as long as the other Perl 5 answer, but it works (slowly) for any `n`; ``` map/\b@F\b/&&!/\b(\d+),.*\b\1\b/&&say,uniq sort map{s/,+/,/g;s/^,+|,+$//gr}glob join',',("{",1..$_,"}")x$_ ``` [Try it online!](https://tio.run/##HYy9CsIwGABfpYbSH/M1n0G6VAQnJx3dgqVBKZGY1CaKUvvqxup2HMd1516XIVybDoXcbIXEJJlNmIkTzYHNhRT8L13zgrtRt8jZ3kdTPzgEioDtyuER6BtojNj2Y6utjC5WmRRSyMhAgDMW10BGkj/jOoTlx3ZeWeNCsd8p56vq4JVe/@aTeZSML0JhdPMF "Perl 5 – Try It Online") ]
[Question] [ Write a program or function that takes in the following input in a reasonable format of your choice: * Two positive integers W and H that define the width and height of the image you'll be generating. * Two RGB colors C1 and C2 that will be used to color the image. * A list of 3-tuples of the form `(r, x, y)` that define circles with radius `r` and center `x, y` in the plane of the image. `r` is a positive integer and `x` and `y` are any integers. The top left pixel of the image is `0, 0` and the x-axis increases to the right and the y-axis increases downward. Output an image with dimensions W by H that is colored with C1 and C2 **such that no two neighboring regions defined by all the overlapping circles are the same color.** > > **For example:** If the input is > > > > ``` > W = 300 > H = 200 > C1 = (255, 200, 0) > C2 = (128, 0, 255) > Circles = (25, 50, 80), (40, 80, 120), (300, -100, 6), (17, 253, 162) > > ``` > > then the circle boundaries look like this: > > > [![example 1 circle boundaries](https://i.stack.imgur.com/32ZWG.png)](https://i.stack.imgur.com/32ZWG.png) > > > There are six distinct, contiguous regions in the image created by the > circles. Each region must be colored with C1 (yellow) or C2 (purple) > such that no two neighboring regions are the same color. > > > There are two ways to do this, their only difference being that the > colors are swapped: > > > [![example 1 output 1](https://i.stack.imgur.com/B9i2M.png)](https://i.stack.imgur.com/B9i2M.png) [![example 1 output 2](https://i.stack.imgur.com/xYDKp.png)](https://i.stack.imgur.com/xYDKp.png) > > > Thus, either of these two images would be valid output for the example > input. > > > Something like [this](https://i.stack.imgur.com/cvBOo.png) would be invalid output since two yellow regions > neighbor each other. > > > Your output images should follow these guidelines: * Besides C1 and C2, a third, neutral color such as black or white may be used for circle boundaries as long as they are no more than 5 pixels thick. (Black, 1-pixel thick boundaries are present in the example above.) * Circles boundaries are not required, however. The regions may neighbor each other directly: [![example 1 output 3](https://i.stack.imgur.com/FxVwY.png)](https://i.stack.imgur.com/FxVwY.png) [![example 1 output 4](https://i.stack.imgur.com/22Ll0.png)](https://i.stack.imgur.com/22Ll0.png) Both of these is another valid output to the example above. * Circles should be as accurate as reasonably possible, using [circle drawing algorithms](https://en.wikipedia.org/wiki/Midpoint_circle_algorithm) or whatever your graphics library provides. * In general, pixel-perfection is not required, but if the input parameters are scaled equally larger and larger, the resulting image should become more and more accurate. * Anti-aliasing is allowed but not required. * Gridlines or axis labels etc. in the background are not allowed. **The shortest code in bytes wins.** # More Examples All using these inputs with different sets of circles: ``` W = 100 H = 60 C1 = (255, 0, 0) C2 = (0, 0, 255) ``` In any example the colors can be swapped and remain valid. ``` Circles = A. empty list B. (13, 16, 20) C. (30, 16, 20) D. (200, 16, 20) E. (42, 50, 20) F. (42, 50, 20), (17, 40, 30) G. (42, 50, 20), (17, 20, 30) H. (42, 50, 20), (17, 10, 30), (10, 50, 30) I. (42, 50, 20), (17, 10, 30), (35, 50, 20) J. (18, 36, 40), (18, 63, 40), (18, 50, 20) K. (100, -10, -20), (60, 50, -10) L. (18, 36, 40), (18, 63, 40), (18, 50, 20), (14, 50, 20), (5, 50, 18), (20, 0, 0), (70, 22, 0), (10000, -9970, 0), (135, 100, -80) ``` `A.` [![ex A](https://i.stack.imgur.com/lvbth.png)](https://i.stack.imgur.com/lvbth.png) `B.` [![ex B](https://i.stack.imgur.com/bVjqk.png)](https://i.stack.imgur.com/bVjqk.png) `C.` [![ex C](https://i.stack.imgur.com/8Ashr.png)](https://i.stack.imgur.com/8Ashr.png) `D.` [![ex D](https://i.stack.imgur.com/lvbth.png)](https://i.stack.imgur.com/lvbth.png) `E.` [![ex E](https://i.stack.imgur.com/2P9tT.png)](https://i.stack.imgur.com/2P9tT.png) `F.` [![ex F](https://i.stack.imgur.com/GygSx.png)](https://i.stack.imgur.com/GygSx.png) `G.` [![ex G](https://i.stack.imgur.com/aArsj.png)](https://i.stack.imgur.com/aArsj.png) `H.` [![ex H](https://i.stack.imgur.com/2TEYw.png)](https://i.stack.imgur.com/2TEYw.png) `I.` [![ex I](https://i.stack.imgur.com/Aig4n.png)](https://i.stack.imgur.com/Aig4n.png) `J.` [![ex J](https://i.stack.imgur.com/FkZLe.png)](https://i.stack.imgur.com/FkZLe.png) `K.` [![ex K](https://i.stack.imgur.com/AWrkW.png)](https://i.stack.imgur.com/AWrkW.png) `L.` [![ex L](https://i.stack.imgur.com/kXh8W.png)](https://i.stack.imgur.com/kXh8W.png) Make sure your output behaves similar to all these examples. [Answer] # Mathematica, 165 bytes ``` ContourPlot[Cos@Tr[Boole[Norm[{x,y}-#2]<#]Pi&@@@#4],{x,0,#},{y,0,#2},PlotPoints->5!,AspectRatio->Automatic,Frame->False,ContourShading->RGBColor@@@#3,Contours->{0}]& ``` Pure function taking four arguments: the width, the height (both integers), an ordered pair of triples of numbers between 0 and 1 (representing the two RGB colors), and a list of items of the form `{r, {x, y}}` to record the radii and centers of the circles. For example, the first example in the OP would be called with the arguments `[300, 200, {{1, 0.784, 0}, {0.5, 0, 1}}, {{25, {50, 80}}, {40, {80, 120}}, {300, {-100, 6}}, {17, {253, 162}}}]`. The positive y-axis points upwards in Mathematica. `Norm[{x,y}-#2]<#` detects whether a point is inside a given circle; `Boole[...]Pi` converts that `True` or `False` to `π` or `0`. After computing those πs/0s over all the input circles, `Tr` adds them up and `Cos` converts even multiples of π to 1, odd multiples of π to –1. `ContourPlot[...,Contours->{0}]` then colors the appropriate region of the plane in two colors depending on whether the value is greater or less than `0`. `AspectRatio->Automatic` makes circles look like circles; `PlotPoints->5!` gives a decent accuracy (boost it to `9!` if you really want an amazing picture, far in the future!); `Frame->False` gets rid of the axes; and `ContourShading->RGBColor@@@#3` uses the input colors for the contours. Sample output, with the first pair of colors (since they're nice) but the last set of circles: [![sample output](https://i.stack.imgur.com/6zcLD.png)](https://i.stack.imgur.com/6zcLD.png) [Answer] ## JavaScript/SVG/HTML5, 219 bytes ``` f=// for demo (w,h,b,f,a)=>`<svg width=${w} height=${h}><rect width=${w} height=${h} fill=rgb(${b}) /><path fill=rgb(${f}) fill-rule=evenodd d=${a.map(([r,x,y])=>[`M`+x,y-r+`a`+r,r,0,0,0,0,r+r+`a`+r,r,0,0,0,0,-r-r]).join``} /></svg>` ;//demo [[`A`, []], [`B`, [[13, 16, 20]]], [`C`, [[30, 16, 20]]], [`D`, [[200, 16, 20]]], [`E`, [[42, 50, 20]]], [`F`, [[42, 50, 20], [17, 40, 30]]], [`G`, [[42, 50, 20], [17, 20, 30]]], [`H`, [[42, 50, 20], [17, 10, 30], [10, 50, 30]]], [`I`, [[42, 50, 20], [17, 10, 30], [35, 50, 20]]], [`J`, [[18, 36, 40], [18, 63, 40], [18, 50, 20]]], [`K`, [[100, -10, -20], [60, 50, -10]]], [`L`, [[18, 36, 40], [18, 63, 40], [18, 50, 20], [14, 50, 20], [5, 50, 18], [20, 0, 0], [70, 22, 0], [10000, -9970, 0], [135, 100, -80]]] ].forEach(([c, a])=>document.write(`<nobr><tt>&nbsp;${c}.&nbsp;</tt>${f(100, 60, [255, 0, 0], [0, 0, 255], a)}</nobr><wbr>`)); ``` [Answer] # BBC Basic, ~~120~~ 117 bytes Download interpreter at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html> ``` I.w,h,R,G,B,r,g,b:V.22,4,19;16,r,g,b,275;16,R EORr,G EORg,B EORb,24,0;0;w;h;16 5I.r,x,y:V.25,4,x;h-y;25,154,r;0;:G.5 ``` BBC Basic has a range of colour modes allowing you to plot raster graphics according to basic logic operations: OR, AND, XOR etc. It also supports pallete reprogramming, meaning that for example here a 2 colour image can have its colours reprogrammed to any of 4096 colours. The implementation used here has some (undocumented) differences from the original BBC implementation, in which the EOR operators would not be necessary. **Ungolfed** ``` INPUTw,h,R,G,B,r,g,b: :REM Input size and colours VDU22,4 :REM Change to MODE 4 (2 colours) as the default mode gives odd behaviour VDU19,0,16,r,g,b,19,1,16,R EORr,G EORg,B EORb :REM Reprogram the colours to R,G,B and R^r,G^g,B^b VDU24,0;0;w;h;16 :REM Setup a graphics viewport of the right size, and "clear" it to change background colour 5 INPUTr,x,y :REM take input coordinates VDU25,4,x;h-y; :REM move to x,y (h-y required as BBC BASIC y axis increases upward, reverse of spec) VDU25,154,r;0; :REM draw circle in "logical inverse colour" of existing pixels (this implementation seems however to XOR with colour 1 instead) GOTO5 :REM repeat infinitely until user presses escape ``` **Typical output screen** Example image scaled up by a factor of 10 in units / factor of 5 in pixels (BBC basic uses 1 pixel = 2 units.) [![enter image description here](https://i.stack.imgur.com/tqLMN.png)](https://i.stack.imgur.com/tqLMN.png) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~30~~ ~~29~~ 25 bytes ``` 2ZG:i:!J*+2&!-|i<so2&!1YG ``` Input format: * Colormap as a matrix of values between 0 and 255, where each row defines a color * *W* * *H* * Column vector of 1-based center coordinates as complex values (*x* is the real part, *y* is the imaginary part) * Column vector of radii. Try at [MATL Online!](https://matl.io/?code=2ZG%3Ai%3A%21J%2a%2B2%26%21-%7Ci%3Cso2%26%211YG&inputs=%5B255+200+0%3B+128+0+255%5D%0A300%0A200%0A%5B51%2B81i%3B+81%2B121i%3B+-99%2B7i%3B+254%2B163i%5D%0A%5B25%3B+40%3B+300%3B+17%5D&version=19.8.0) Or [verify the last test case](https://matl.io/?code=2ZG%3Ai%3A%21J%2a%2B2%26%21-%7Ci%3Cso2%26%211YG&inputs=%5B255+0+0%3B+0+0+255%5D%0A100%0A60%0A%5B37%2B41i%3B+64%2B41i%3B+51%2B21i%3B+51%2B21i%3B+51%2B19i%3B+1%2B1i%3B+23%2B1i%3B+-9969%2B1i%3B+101-79i%5D%0A%5B18%3B+18%3B+18%3B+14%3B+5%3B+20%3B+70%3B+10000%3B+135%5D&version=19.8.0). (The interpreter is still experimental. You may need to refresh the page and try again if it doesn't work). ### Explanation The code uses complex numbers to define the grid of points and to compute distances, and makes heavy use of array operations with [broadcasting](https://www.gnu.org/software/octave/doc/interpreter/Broadcasting.html). ``` 2ZG % Implicitly input matrix of colors. Set as colormap : % Implicitly input W. Push [1 2 ... W] i: % Input H. Push [1 2 ... H] !J* % Transpose, multiply by 1i + % Add element-wise with broadcast. Gives H×W grid of points as % complex numbers, 1-based 2&! % Permute first dimension with the third. Gives a 1×W×H array -| % Implicitly input center coordinates. Subtract grid from them, % element-wise with broadcast. Gives a C×H×W array, where C is the % number of circles i % Input column vector of circle radii < % Less than, element-wise with broadcast so % Sum along first dimension, modulo 2. Gives a 1×W×H array 2&! % Permute first dimension with the third. Gives a a H×W array 1YG % Display as scaled image ``` [Answer] # Python using [pypng](https://github.com/drj11/pypng), ~~140~~ 138 bytes ``` import png f=lambda W,H,c,d,C:png.from_array([[[c,d][sum(abs(x-X+1j*(y-Y))<r for r,x,y in C)%2]for X in range(W)]for Y in range(H)],'RGB') ``` Example usage: ``` W = 100 H = 60 C1 = (255, 0, 0) C2 = (0, 0, 255) Circles = (18, 36, 40), (18, 63, 40), (18, 50, 20), (14, 50, 20), (5, 50, 18), (20, 0, 0), (70, 22, 0), (10000, -9970, 0), (135, 100, -80) f(W, H, C1, C2, Circles).save('test.png') ``` Thanks to xnor for saving 2 bytes. [Answer] # Math (non-competiting) [![](https://i.stack.imgur.com/IXSBG.png)](https://i.stack.imgur.com/IXSBG.png) (idk how to do LaTeX in PPCG, so I used a LaTeX to png tool) ## Explanation The product of multiple circle equations (`(x-a)^2+(y-b)^2-r^2`) >= 0 will make a graph which this question needs. In the equation, `n` is the size of the array, and `(x, y or r)_k` is the `k`th `(x, y, or r)` element. ## Example `(0,0,2),(2,2,2)` [![(Thank you WolframAlpha)](https://i.stack.imgur.com/Ev0ZK.gif)](https://i.stack.imgur.com/Ev0ZK.gif) (Inequality plot by WolframAlpha) # Get/Run equation for WolframAlpha > > Getting script : Complete > > > ``` <input id="in" placeholder="input, with () changed to []"> <br> <input type="color" id="c1" value="#ff0000"> <input type="color" id="c2" value="#00ff00"> <br> <input id="w" placeholder="width"> <input id="h" placeholder="height"> <br> <button onclick="change()"> Convert! </button> <br> <input id="res" placeholder="result"> <script> function change() { var a = document.getElementById("in").value; document.getElementById("res").value = ""; var arr = JSON.parse("[" + a + "]"); document.getElementById("res").value += "plot "; for (var i = 0; i < arr.length; i++) { document.getElementById("res").value += "((x-(" document.getElementById("res").value += arr[i][1]; document.getElementById("res").value += "))^2+(y-("; document.getElementById("res").value += arr[i][2]; document.getElementById("res").value += "))^2-("; document.getElementById("res").value += arr[i][0]; document.getElementById("res").value += ")^2)"; } document.getElementById("res").value += ">=0"; document.getElementById("res").value += " from x=0 to x="; document.getElementById("res").value += document.getElementById("w").value; document.getElementById("res").value += " and y=0 to y="; document.getElementById("res").value += document.getElementById("h").value/2; document.getElementById("res").value += "> color "; document.getElementById("res").value += document.getElementById("c1").value; document.getElementById("res").value += " background color "; document.getElementById("res").value += document.getElementById("c2").value; } </script> ``` > > Running script : Not done yet > > > Now make it work with Mathematica... [Answer] # Python 2.x, ~~166~~ 158 ``` import re;def f(W,H,c,d,C):print'P3',W,H,255,re.sub('[^0-9]',' ',repr([[d,c][sum([abs(x-X+1j*(y-Y))<r for r,x,y in C])%2]for Y in range(H)for X in range(W)])) ``` The function generates a PPM file on the standard output. # example: ``` W = 300 H = 200 C1 = (255, 200, 0) C2 = (128, 0, 255) Circles = [(25, 50, 80), (40, 80, 120), (300, -100, 6), (17, 253, 162)] f(W, H, C1, C2, Circles) ``` [![example](https://i.stack.imgur.com/ZbZd2.png)](https://i.stack.imgur.com/ZbZd2.png) [Answer] # Common Lisp + Quicklisp + ZPNG 260 + 20 = 280 chars This is some of the widest code I've ever written in CL, and if I weren't doing a code golf I would've restructured this to make it much easier to read... Prelude (20 chars) ``` (ql:quickload 'zpng) ``` Golfed (260 chars) ``` (lambda(w h g b c)(make-instance'zpng:png :image-data(coerce(loop :for j :below h :nconc(loop :for i :below w :append(if(evenp(count t(mapcar(lambda(c)(<(abs(complex(-(cadr c)i)(-(caddr c)j)))(car c)))c)))g b)))'(array(unsigned-byte 8)(*))):width w :height h)) ``` Ungolfed: (Uses defun to allow testing and longer variable names for readability) ``` (defun mk-png (width height color1 color2 circles) (make-instance 'zpng:png :image-data (coerce (loop :for j :below height :nconc (loop :for i :below width :append (if (evenp (count t (mapcar (lambda (circ) (< (abs (complex (- (cadr circ) i) (- (caddr circ) j))) (car circ))) circles))) color1 color2))) '(array (unsigned-byte 8) (*))) :width width :height height)) ``` Example Usage: ``` (let ((png (mk-png 300 200 '(255 200 0) '(128 0 255) '((25 50 80) (40 80 120) (300 -100 6) (17 253 162))))) (zpng:write-png png #p"path/to/file.png")) ``` ### Explaination ``` (lambda (circ) (< (abs (complex (- (cadr circ) i) (- (caddr circ) j))) (car circ))) ``` Returns true if the point (i, j) falls within the given circle circ. Euclidean distance is calculated by taking the absolute value of the complex number which represents the vector from (i, j) to the center of circ. ``` (evenp (count t (mapcar ___ circles))) ``` Map that function across the circles list and check if the given point (i, j) falls within an even number of circles. ``` (if ____ color1 color2) ``` Select color based on that test. ``` (loop :for j :below height :nconc (loop :for i :below width :append ____)) ``` Collect together a flat list of all the rgb bytes by looping over each (i, j) in the image and appending the resulting lists together. ``` (coerce ____ '(array (unsigned-byte 8) (*))) ``` Convert that list of bytes into a proper array of bytes, so zpng can ingest it properly. ``` (make-instance 'zpng:png :image-data ____ :width width :height height) ``` Create the png object. ``` (defun mk-png (width height color1 color2 circles) ___) ``` Create the function to take the width, height, two colors, and list of circles and return the created png object. [Answer] # JavaScript (ES6), 224 bytes I saw the JS + SVG solution, but I just had to create a canvas-based solution ;-) This is a function which returns a canvas element. If an existing canvas element can be provided, remove 40 bytes. Call like `f(width, height, [[r1, g1, b1], [r2, g2, b2]], [[r1, x1, y1], [r2, x2, y2], ...])` ``` let f = (w,h,a,c,O=document.createElement`canvas`)=>{O.width=w;O.height=h;C=O.getContext`2d`;for(y=0;y<h;y++)for(x=0;x<w;x++)C.fillStyle=`rgb(${a[c.filter(([R,X,Y])=>(X-x)**2+(Y-y)**2<R**2).length%2]})`,C.fillRect(x,y,1,1);return O} let tests = A.innerHTML.match(/.+/g); A.innerHTML = ""; for (let i of tests) { let p = document.createElement("span"); p.innerHTML = "<br>" + i.slice(0, 3); p.style["font-family"] = "monospace"; A.append(p); A.append(f(100, 60, [[255,0,0], [0,0,255]], eval(`[${ i.slice(3).replace(/\(/g, "[").replace(/\)/g, "]") }]`) )); } ``` ``` <div id=A> A. B. (13, 16, 20) C. (30, 16, 20) D. (200, 16, 20) E. (42, 50, 20) F. (42, 50, 20), (17, 40, 30) G. (42, 50, 20), (17, 20, 30) H. (42, 50, 20), (17, 10, 30), (10, 50, 30) I. (42, 50, 20), (17, 10, 30), (35, 50, 20) J. (18, 36, 40), (18, 63, 40), (18, 50, 20) K. (100, -10, -20), (60, 50, -10) L. (18, 36, 40), (18, 63, 40), (18, 50, 20), (14, 50, 20), (5, 50, 18), (20, 0, 0), (70, 22, 0), (10000, -9970, 0), (135, 100, -80) </div> ``` Example output: [![two-colored circles](https://i.stack.imgur.com/JG8ZW.png)](https://i.stack.imgur.com/JG8ZW.png) [Answer] # [Löve2D](https://love2d.org/), 353 Bytes. ``` o=love.graphics a=arg w,h,r,g,b,R,G,B=...c={}for i=9,#a,3 do c[#c+1]={a[i],a[i+1],a[i+2]}end C=o.newCanvas(w,h)o.setCanvas(C)o.clear(R,G,B)for k,v in pairs(c)do o.stencil(function()o.circle("fill",v[2],v[3],v[1],9^3)end,"invert",1,true)end o.setStencilTest("greater",0)o.setColor(r,g,b)o.rectangle("fill",0,0,w,h)local C:newImageData():encode("png","c") ``` ]
[Question] [ I'm tired, but I can't seem to fall asleep. Help me count sheep. Given an input N (positive integer), make N sheep jump over an ascii fence, like the sample below. Only one frame should be displayed at once: ``` o |-| ──|-|── 0 ``` --- ``` o|-| ──|-|── 0 ``` --- ``` o |-| ──|-|── 0 ``` --- ``` |-|o ──|-|── 0 ``` --- ``` |-| o ──|-|── 0 ``` --- ``` o |-| ──|-|── 1 ``` --- ``` o|-| ──|-|── 1 ``` --- ``` o |-| ──|-|── 1 ``` Count should be kept at the lower right side of the 'ground'. Trailing and leading whitespace and newlines are allowed. If your language of choice has difficulty clearing the screen for each frame you can add sufficient newlines to clear the screen - please state how many lines you add for this in your answer. The program should terminate when the N'th sheep is on the fifth floortile. I need to get up early tomorrow, so shortest code in bytes wins. Please submit a function or complete program. Standard loopholes apply. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~60~~ ~~56~~ 53 bytes ``` :"@qXJx[HKCbO]"7Z"' |-| 'v'o'@('--|-|-- ' JVhXxXD ``` The animation with the above code runs very fast. The following version includes a pause to make the animation slower and thus easier to see (not required by the challenge), at the cost of 4 more bytes: ``` :"@qXJx[HKCbO]"7Z"' |-| 'v'o'@('--|-|-- ' JVhXxXD.2Y. ``` Try it at [**MATL Online!**](https://matl.io/?code=%3A%22%40qXJx%5BHKCbO%5D%227Z%22%27++%7C-%7C++%27v%27o%27%40%28%27--%7C-%7C--++%27++JVhXxXD.2Y.&inputs=5&version=19.2.0) The interpreter is a beta; refresh the page if it doesn't work. Or see a recording from the offline compiler: [![enter image description here](https://i.stack.imgur.com/Yrm2G.gif)](https://i.stack.imgur.com/Yrm2G.gif) ### Explanation ``` :" % Input N implicitly. Repeat N times @q % Push iteration index minus 1, that is, from 0 to N-1. This % are the numbers of sheep XJx % Copy into clipboard J and delete [HKCbO] % Push array [2 4 7 -2 0] " % For each value in that array. This loops generates the 5 % frames for each number of sheep 7Z" % Push string of 7 spaces ' |-| ' % Push this string v % Concatenate vertically. This gives a 2x7 char array % with the upper part of the frame, except the 'o', % which will be now placed in a varying position 'o' % Push string 'o' @ % Push loop variable, that is, 2, 4, 7, -2 or 0 ( % Write 'o' into that position of the 2x7 char array. % The position is interpreated linearly, that is, a single % number is used as index into the 2D array in column-major % order (down, then across). So index 2 is lower-left corner, % index 4 is to the right of that etc. Indexing is % semi-modular (modular for non-positive values). So 0 is % the lower-right corner, and -2 is to the left of that '--|-|-- ' % Push this string JV % Push current number of sheep converted to string h % Concatenate horizontally Xx % Clear screen XD % Display all stack contents .2Y. % Pause for 0.2 seconds (optional) % End implicitly % End implicitly ``` [Answer] # JavaScript (ES6), ~~120~~ 124 bytes ``` f=(n,m=` 2 43|-|10 ──|-|── `,s=0)=>n?alert(m.replace(s%5,'o').replace(/\d/g,' ')+' '+(n-1),(++s%5?f(n,m,s):f(n-1,m,0))):'' ``` The last frame computed is showing first. Thanks to this the jump number is `n-1` In `alert`, charaters have different width so it looks like it's broken. ``` f=(n,m=` 2 43|-|10 ──|-|── `,s=0)=>n?alert(m.replace(s%5,'o').replace(/\d/g,' ')+' '+(n-1),(++s%5?f(n,m,s):f(n-1,m,0))):'' ; f(2);//You'll get 10 alert popup ``` --- Previous answer: 120 bytes, the jump number is wrong because it starts at 1 instead of 0 ``` f=(n,m=` 2 43|-|10 ──|-|── `,s=0)=>n?alert(m.replace(s%5,'o').replace(/\d/g,' ')+' '+n,(++s%5?f(n,m,s):f(n-1,m,0))):'' ``` [Answer] ## JavaScript (ES6), ~~144~~ 142 bytes Clears the output and waits 300ms between each frame: ``` n=>(F=j=>((c=console).clear(),c.log(` 2 01|-|34 ──|-|── `.replace(/\d/g,i=>(j-i)%5?' ':'o')+(j/5|0)),++j<n*5&&setTimeout(`F(${j})`,300)))(0) ``` You can **[test it here](https://jsfiddle.net/Arnauld/6sr7Lyzy/1/)** (make sure to open the console). [Answer] # Ruby, 83 bytes ``` ->n{(n*5).times{|i|$><<" c |-| ab|-|de #{i/5} ".tr('abcde',' '*(i%5)+'o ')}} ``` Prints to stdout. Output separated by newlines. Reducing screen height to 3 makes only one image visible at a time. [Answer] # C#, 234 Bytes ``` using C=System.Console;class P{static void Main(string[]a){for(int n=0;n-1+""!=a[0];++n){foreach(int p in new[]{5,6,3,10,11}){C.Clear();C.Write(" \n |-| \n──|-|── ".Remove(p,1).Insert(p,"o")+n);for(var w=3e7;w>0;--w);}}}} ``` [Answer] # PHP+JavaScript, 168 bytes ``` <?extract($_GET);$s=" ";$s[$f=++$f%5]=o;echo strtr("<pre> C AB|─|DE ──|─|── $c",EABCD,$s),($c+=!$f)<$n?"<script>location.href='s.php?n=$n&c=$c&f=$f'</script>":""; ``` Save to file `s.php`, call in browser with `s.php?n=<n>`. Calls itself with new parameters for every frame, no delay. --- I could save 5 more with `index.php`; but I don´t want to go that far. [Answer] # Tcl, 168 bytes Version using 10-row-high screen. (Replace the `7` below with your screen height in columns minus four.) ``` set s {0 1 2 3 4 } for {set n 0} {$n<$argv} {incr n} {foreach x $s { puts [string repe \n 6][string map [split $s {}] [string map "$x o" { 2 01|-|34 --|-|-- }]]$n}} ``` That runs really fast, so you can add a pause on line two: # Tcl, 177 bytes ``` set s {0 1 2 3 4 } for {set n 0} {$n<$argv} {incr n} {foreach x $s {after 250 puts [string repe \n 6][string map [split $s {}] [string map "$x o" { 2 01|-|34 --|-|-- }]]$n}} ``` It works by reusing the string at the top for two different things: * as a list for the inner loop (to display each version of the sheep+fence) * as a mapping of digit→space to remove digits from the sheep+fence image template The template itself is the string image to display. First we map (string replace) the sheep's current position digit (inner loop) to an 'o'. Then we map the remaining digits to spaces. Then we print the resulting string. (The string itself starts after the last { on the third line and ends with the leftmost } on the last line.) [Answer] ## QBasic, 110 bytes ``` INPUT n FOR i=0TO 5*n-1 CLS ? ?" |-|" ?"--|-|-- ";i\5 x=i MOD 5 LOCATE(x=2)+2,1+x-(x>1)+x\3 ?"o" SLEEP 1 NEXT ``` Loops over `5*n` ticks. At each tick, clears the screen, prints the stile and sheep count, and then uses `LOCATE` to print the `o` at the appropriate spot. With `x` being the position code between 0 and 4: * Row: `(x=2)+2` + If `x=2` is true, `-1+2` = `1` + If `x=2` is false, `0+2` = `2` * Column: `1+x-(x>1)+x\3` + If `x` is `0` or `1`, `x>1` is false and `x\3` is `0`: `1+x-0+0` = `1` or `2` + If `x` is `2`, `x>1` is true and `x\3` is `0`: `1+x-(-1)+0` = `4` + If `x` is `3` or `4`, `x>1` is true and `x\3` is `1`: `1+x-(-1)+1` = `6` or `7` Finally, `SLEEP` for 1 second and loop. If you don't mind hitting enter at every frame, I can shave two bytes by removing the argument to `SLEEP`. [Answer] # PHP, ~~132~~ 131 bytes Edits after comments (thanks!): ``` <?php for(;$i<$argv[1]*5;sleep(1),system(clear),$c=" |-| ──|-|── ".floor($i/5),$c[[5,6,3,10,11][$i++%5]]=o)echo$c; ``` Which is ungolfed: ``` <?php ini_set('error_reporting', '0'); # golfing precondition for(; $i<$argv[1]*5; # repeat N times sleep(1), # sleep after iteration system(clear), # clear screen (linux only) $c = " |-| ──|-|── " . floor($i / 5), # define template $c[[5, 6, 3, 10, 11][$i++ % 5]] = o) # replace with sheep (and finish "for" statement) echo $c; # output result ``` ### Original post ``` <?php $i=0;for(;;){system("clear");$c=" \n |-| \n──|-|── ";$c[[3,4,1,8,9][$i%5]]='o';echo" $c".floor($i++/5);sleep(1);} ``` Tested on ubuntu (don't know, if `system("clear")` works on windows) Ungolfed: ``` <?php $i = 0; for(;;) { system("clear"); $content = " \n |-| \n──|-|── "; $content[[3,4,1,8,9][$i%5]] = 'o'; echo " $content " . floor($i++/5); sleep(1); } ``` [Answer] # node.js + [sleep](https://www.npmjs.com/package/sleep), 169 bytes ``` c=' 2\n01|-|34\n──|-|── ' for(i=0;i<process.argv[2]*5;require('sleep').sleep(1))console.log('\033[2J'+c.replace(i%5,'o').replace(/\d/g,' ')+Math.floor(i++/5)) ``` ### Original solution # node.js, ~~146~~ ~~142~~ 185 bytes Tested with ubuntu terminal only (and now with n sheeps): ``` i=0 c=' 2\n01|-|34\n──|-|── ' setInterval(function(){console.log('\033[2J'+c.replace(i%5,'o').replace(/\d/g,' ')+Math.floor(i++/5)) if(process.argv[2]*5==i)process.exit()},9) ``` Well, that's a frame every 9 ms. A more sleep-soothing version (frame every 1s): ``` i=0;setInterval(function(){console.log('\033[2J'+' 2\n01|-|34\n──|-|── '.replace(i%5,'o').replace(/\d/g,' ')+Math.floor(i++/5))},1000) ``` And ungolfed: ``` var i = 0; setInterval(function(){ console.log('\033[2J' + ' 2\n01|-|34\n──|-|── '.replace(i%5, 'o').replace(/\d/g, ' ') + Math.floor(i++/5)); }, 1000) ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~66~~ ~~60~~ 59 bytes ``` FNU5Fð4×N<i¨'oJ},N<iðë'o}ðNÉis}"|-| "JN1›iR},…──|Â'-sððXJ, ``` Uses [CP-1252](http://www.cp1252.com/) encoding. ## Explanantion Iteration refers to the inner iteration (0 -> 4) of the sheeps journey. **Main loops** ``` F # For N in range [0 .. input) NU # Save N in variable X 5F # For N in range [0 .. 5) ``` **Generate top row** ``` ð4× # push 4 spaces N<i } # if we're on the 2nd iteration ¨'oJ # replace the last space with an "o" , # print row ``` **Generate middle row** ``` N<iðë'o} # push a space if we're on the 2nd iteration, else push "o" ð # push a space NÉis} # if we're on an odd numbered iteration, swap the stacks top 2 chars "|-| " # push this string J # join the stack to one string N1›iR} # if we're on the any of the last 3 iterations, reverse the string , # print row ``` **Generate bottom row** ``` …──| # push the string "──|"  # push a reversed copy '-s # push "-" between the 2 strings on the stack ðð # push 2 spaces X # push the N we saved in the main loop (current sheep number) J, # join and print row ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~55 54~~ 53 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ị30214D¤“o ”ṙ“ “ ““|-|““ __|-|__ ”ż ×5Ḷµ:5ż@Ç€Y ``` **[TryItOnline](http://jelly.tryitonline.net/#code=4buLMzAyMTREwqTigJxvICAgIOKAneG5meKAnCAgIOKAnArigJzigJx8LXzigJzigJwKX198LXxfXyAg4oCdxbwKw5c14bi2wrU6NcW8QMOH4oKsWQ&input=&args=MjA)** Prints frames separated by line feeds. How? ``` ị30214D¤“o ”ṙ“ “ ““|-|““ __|-|__ ”ż - Link 1, build a frame without counts: frameNumber ¤ - nilad and link(s) as a nilad: 30214 - literal 30214 (a nilad) D - to decimal: [3,0,2,1,4] ị - index into (1-based and modular, so frames go 4,3,0,2,1,4,...) “o ” - string "o " ṙ - rotated to the left by that number “ “ - the rest, except the last character, is: ““|-|““ - an array of strings [" ","\n","","|-|","","\n__|-|__ "] __|-|__ ” - i.e. split where a sheep might go ż - zip the sheep (the rotated "o ") into that ×5Ḷµ:5ż@Ç€Y - Main link: nSheep ×5 - multiply by 5 -> nFrames Ḷ - lowered range: [0,1,2,...nFrames-1] µ - monadic chain separation :5 - integer division by 5 (vectorises): [5 zeros, 5 ones, ..., 5 (nSheep-1)s] ż@ - zip with reversed arguments Ç€ - call last link (1) as a monad for each (zip sheep numbers with frames) Y - join with line feeds (TODO: replace with future animate frames atom :p) ``` [Answer] # Python 2, ~~171~~ ~~159~~ 144 bytes, ~~163~~ ~~151~~ 136 characters Solution using a recursive function. Call as f(int) **EDIT** -12 after rereading the comments and seeing that the count does not have to increment when the sheep reaches the end of the field -15 by iterating through the index list directly and losing a variable ``` def f(a,x=0): if a>0: for c in 5,6,3,10,11: b=list(' \n |-| \n──|-|── ');b[c]='o';print"\n"*50+"".join(b)+(`x`) f(a-1,x+1) ``` **Notes** Assumes UTF-8 encoding Using - instead of ─ (as in @Luis MATL answer) would bring the byte count down by 8 to match the character count and would lose the UTF-8 dependency 50 newlines added - output is at the bottom on the console (cheaper than importing and using os.system("clear") and works on Windows and Linux) Version with 1 second time delay between outputs (170 bytes, 162 characters) ``` import time def f(a,x=0): if a>0: for c in 5,6,3,10,11: b=list(' \n |-| \n──|-|── ');b[c]='o';print"\n"*50+"".join(b)+(`x`);time.sleep(1) f(a-1,x+1) ``` [Answer] # Bash + standard Linux utilities (339 bytes) ``` e(){ echo "$@";} n(){ e -n "$@";} r(){ [ $? -eq 0 ]&&s=o||s=" ";[ $1 ]&&n " $s "||n "$s";} f(){ k=$(($1%5));n " ";[ $k -eq 2 ];r .;e " ";for i in 0 1;do [ $k -eq $i ];r;done;n "|-|";for i in 3 4;do [ $k -eq $i ];r;done;e;n "──|-|──";} for l in `seq 1 $1`;do for z in `seq 0 4`;do clear;f $z;e " $((l-1))";sleep 1;done;done ``` ]
[Question] [ ### Introduction XOR is a digital logic gate that implements an exclusive or. Most of the times, this is shown as `^`. The four possible outcomes in binary: ``` 0 ^ 0 = 0 0 ^ 1 = 1 1 ^ 0 = 1 1 ^ 1 = 0 ``` This can also be seen as addition modulo 2 in binary. In decimal, we need to convert the decimal to binary, `35 = 100011` and `25 = 11001`.To compute the XOR value, we place them on top of each other: ``` 100011 11001 ^ -------- 111010 = 58 in decimal ``` **The task**: When given an integer value N greater than 1, output an XOR table with the size N + 1. For example, N = 5: ``` 0 1 2 3 4 5 1 0 3 2 5 4 2 3 0 1 6 7 3 2 1 0 7 6 4 5 6 7 0 1 5 4 7 6 1 0 ``` You can see that there is one space in front of each number, because the highest amount in the table has length 1. However, if we take N = 9, we get the following grid: ``` 0 1 2 3 4 5 6 7 8 9 1 0 3 2 5 4 7 6 9 8 2 3 0 1 6 7 4 5 10 11 3 2 1 0 7 6 5 4 11 10 4 5 6 7 0 1 2 3 12 13 5 4 7 6 1 0 3 2 13 12 6 7 4 5 2 3 0 1 14 15 7 6 5 4 3 2 1 0 15 14 8 9 10 11 12 13 14 15 0 1 9 8 11 10 13 12 15 14 1 0 ``` The highest value has length 2, so the value is right-aligned to length 3 (highest length + 1). **Rules:** * Leading whitespace is not mandatory, only if used (or not) consistently * You must output a table in the form shown above. * The padding between columns should be as small as possible * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! [Answer] # [MATL](https://esolangs.org/wiki/MATL), 10 bytes ``` 0i2$:tXgZ~ ``` The compiler (and in particular this program) now seems to work in Octave, although it still needs some refinement. You can provisionally use [this GitHub commit](https://github.com/lmendo/MATL/tree/77a5eba228ccedec8ac0d58d0f1842aba03858cc). *Edit (Mar 30 '16)*: [**Try it online!**](http://matl.tryitonline.net/#code=MGkyJDp0WGdafg&input=OQ) ### Example ``` >> matl 0i2$:tXgZ~ > 9 0 1 2 3 4 5 6 7 8 9 1 0 3 2 5 4 7 6 9 8 2 3 0 1 6 7 4 5 10 11 3 2 1 0 7 6 5 4 11 10 4 5 6 7 0 1 2 3 12 13 5 4 7 6 1 0 3 2 13 12 6 7 4 5 2 3 0 1 14 15 7 6 5 4 3 2 1 0 15 14 8 9 10 11 12 13 14 15 0 1 9 8 11 10 13 12 15 14 1 0 ``` ### Explanation ``` 0i2$: % vector 0, 1, 2, ... up to input number t % duplicate Xg % nd-grid Z~ % bitxor ``` [Answer] # Bash + BSD utils, 45 ``` eval echo \$[{0..$1}^{0..$1}]|rs -jg1 $[$1+1] ``` I've been waiting a long time to find a use for [`rs`](http://www.freebsd.org/cgi/man.cgi?query=rs&sektion=1&apropos=0&manpath=freebsd). This seems to be a good one. `rs` may need to be installed on Linux systems. But it runs right out of the box on OS X. * `$1` expands to N, and thus `echo \$[{0..$1}^{0..$1}]` expands to `echo $[{0..N}^{0..N}]` * This is then `eval`ed: * The brace expansion expands to `$[0^0] $[0^1] $[0^2] ... $[0^N] ... $[N^N]` * This is a series of xor arithmetic expansions which expand to one line of terms * `rs` (reshape) reshapes this line to N+1 rows. `-j` right justifies, and `-g1` gives a gutter-width of 1. This ensures the final output table has minimal width between columns. I've tested up to N=1000, which took 3.8 seconds. Large N is theoretically possible, though bash will run out of memory at some point with the (N+1)² memory usage of the brace expansion. [Answer] # C, 114 ~~128 152~~ **Edit** Simplified space counting, inspired by the work of Khaled A Khunaifer A C function that follows the specs. ``` T(n){int i=0,j,x=1,d=0;while(x<=n)x+=x,++d;for(;i<=n;i++)for(j=0;j<=n;j++)printf("%*d%c",d*3/10+1,i^j,j<n?32:10);} ``` [Try it](http://ideone.com/t658Bd) insert n as input, default 9 **Less golfed** ``` T(n) { int i=0, j, x=1,d=0; while(x<=n) x+=x,++d; // count the digits // each binary digit is approximately 0.3 decimal digit // this approximation is accurate enough for the task for(;i<=n;i++) for(j=0;j<=n;j++) printf("%*d%c",d*3/10+1, i^j, j < n ? 32:10); // space between columns, newline at end } ``` [Answer] # JavaScript (ES6) 120 ~~122~~ **Edit** 2 bytes saved thx ETHproductions An anonymous function. Note: the number in the table are limited to 7 digits, that is more than reasonable given the overall size of a table allowing for bigger numbers Now I should find a shorter way to get the max columns size, avoiding logarithms ``` n=>(a=Array(n+1).fill(-~Math.log10(2<<Math.log2(n)))).map((m,i)=>a.map((z,j)=>` ${i^j}`.slice(~m)).join``).join` ` ``` **Test** ``` f=n=>(a=Array(n+1).fill(-~Math.log10(2<<Math.log2(n)))).map((m,i)=>a.map((z,j)=>` ${i^j}`.slice(~m)).join``).join`\n` function update() { var v=+I.value O.textContent = f(v) } update() ``` ``` N: <input id=I type=number value=9 oninput='update()'> <pre id=O></pre> ``` [Answer] **MathCAD, 187 Bytes** [![enter image description here](https://i.stack.imgur.com/ExXn2.png)](https://i.stack.imgur.com/ExXn2.png) MathCAD handles built in tables easily - but has absolutely no bitwise Xor, nor decimal to binary or binary to decimal converters. The for functions iterate through the possible values. The i, a2, Xa and Xb place hold. The while loop actively converts to binary, and while converting to binary also performs the xor function (the little cross with the circle around it). It stores the binary number in a base-10 number consisting of 0's and 1's. This is then converted before being stored in the M matrix via the summation function. This can easily be golfed down (if only by swapping out the placeholders for shorter ones), but I figured I'd post it and see if anyone can golf down the binary to decimal converter more than anything else. [Answer] # C, 149 bytes ``` int i=0,j,n,k=2;char b[256];scanf("%d",&n);while((k*=2)<=n);k^=k-1;while(i++<=n&&putchar(10))for(j=0;j<=n;j++)printf(" %*d",sprintf(b,"%d",k),i-1^j); --------- ``` Detailed ``` #include <stdio.h> int main() { int i=0, j, n, k=2; char b[256] = { 0 }; scanf("%d", &n); // find max xor value in the table while((k*=2)<=n); k^=k-1; printf("> %d ~ %d", k, sprintf(b,"%d",k)); while(i++ <= n && putchar(10)) { for(j = 0; j <= n;j++) { printf(" %*d", sprintf(b,"%d",k), (i-1)^j); } } return 0; } ``` [Answer] # C, 103 bytes ``` Y(n){int i,j=n++;char*f="%2u";while(j/=8)++f[1];for(;j<n;++j,puts(""))for(i=0;i<n;++i)printf(f,i^j);} ``` [Answer] # Python 3, ~~133~~ 131 bytes ``` import math n=int(input()) r,p=range(n+1),print for y in r:[p(end='%%%dd '%len(str(2**int(math.log2(n)+1)-1))%(x^y))for x in r];p() ``` [Answer] ## R, 38 bytes Usually R requires a lot of bytes just to format the output. In this case it's quite the opposite. `outer` which is usually refers to the outer product of two arrays, can when supplied a function perform this across the margins of the vectors. In this case, we apply the bitwise XOR function `bitwXor`. ``` names(x)=x=1:scan();outer(x,x,bitwXor) ``` [Answer] # Jelly, 7 bytes ``` 0r©^'®G ``` [Try it online!](http://jelly.tryitonline.net/#code=MHLCqV4nwq5H&input=&args=OQ) ### How it works ``` 0r©^'®G Main link. Input: n (integer) 0r Range; yield [0, ..., n]. © Save the range in the register. ® Yield the range from the register. ^' XOR each integer in the left argument with each integer in the right one. G Grid; separate rows by newlines, columns by spaces, with a fixed width for all columns. Since the entries are numeric, align columns to the right. ``` [Answer] ## CJam, ~~29~~ 27 bytes ``` ri:X),_ff{^s2X2b,#s,)Se[}N* ``` [Test it here.](http://cjam.aditsu.net/#code=ri%3AX)%2C_ff%7B%5Es2X2b%2C%23s%2C)Se%5B%7DN*&input=9) ## Explanation ``` ri e# Read input and convert to integer. :X e# Store in X. ), e# Get range [0 1 ... X]. _ff{ e# Nested map over all repeated pairs from that range... ^ e# XOR. s e# Convert to string. 2 e# Push 2. X2b, e# Get the length of the base-2 representation of X. This is the same as getting e# getting the base-2 integer logarithm and incrementing it. # e# Raise 2 to that power. This rounds X up to the next power of 2. s, e# Convert to string and get length to determine column width. ) e# Increment for additional padding. Se[ e# Pad string of current cell from the left with spaces. } N* e# Join with linefeeds. ``` [Answer] ## k4, 50 bytes ``` {-1@" "/:'(-|//#:''x)$x:$2/:''~x=/:\:x:0b\:'!1+x;} ``` E.g.: ``` {-1@" "/:'(-|//#:''x)$x:$2/:''~x=/:\:x:0b\:'!1+x;}9 0 1 2 3 4 5 6 7 8 9 1 0 3 2 5 4 7 6 9 8 2 3 0 1 6 7 4 5 10 11 3 2 1 0 7 6 5 4 11 10 4 5 6 7 0 1 2 3 12 13 5 4 7 6 1 0 3 2 13 12 6 7 4 5 2 3 0 1 14 15 7 6 5 4 3 2 1 0 15 14 8 9 10 11 12 13 14 15 0 1 9 8 11 10 13 12 15 14 1 0 ``` [Answer] ## Mathematica, 108 bytes ``` StringRiffle[Thread[Map[ToString,a=Array[BitXor,{#,#}+1,0],{2}]~StringPadLeft~IntegerLength@Max@a]," "," "]& ``` Disregard the error, it's just `Thread` not knowing what it's doing. [Answer] # Emacs Lisp, 193 bytes ``` (defun x(n)(set'a 0)(set'n(1+ n))(while(< a n)(set'b 0)(while(< b n)(princ(format(format"%%%ss "(ceiling(log(expt 2(ceiling(log n 2)))10)))(logxor a b)))(set'b(1+ b)))(set'a(1+ a))(message""))) ``` Ungolfed: ``` (defun x(n) (set'a 0) (set'n(1+ n)) (while(< a n) (set'b 0) (while(< b n) (princ (format ;; some format string magic to get the length of the longest ;; possible string as a format string (format "%%%ss " (ceiling(log(expt 2(ceiling(log n 2)))10))) (logxor a b))) (set'b(1+ b))) (set'a(1+ a)) ;; new line (message""))) ``` The output is sent to the `*Message*` buffer, which would be `stdout` if `x` were to be used inside a script. ``` (x 9) 0 1 2 3 4 5 6 7 8 9 1 0 3 2 5 4 7 6 9 8 2 3 0 1 6 7 4 5 10 11 3 2 1 0 7 6 5 4 11 10 4 5 6 7 0 1 2 3 12 13 5 4 7 6 1 0 3 2 13 12 6 7 4 5 2 3 0 1 14 15 7 6 5 4 3 2 1 0 15 14 8 9 10 11 12 13 14 15 0 1 9 8 11 10 13 12 15 14 1 0 ``` [Answer] # Python 2, 114 bytes It took some looking to find a way to do variable-width padding in `.format()` (some, not a lot) and get it right-adjusted, but I think I've got it all to spec now. Could use more golfing in that width calculation though. ``` N=input()+1 for i in range(N):print''.join(' {n:>{w}}'.format(w=len(`2**(len(bin(N))-2)`),n=i^r)for r in range(N)) ``` [Answer] ## [**Caché ObjectScript**](http://docs.intersystems.com/cache20161/csp/docbook/DocBook.UI.Page.cls?KEY=GCOS), 127 bytes ``` x(n)s w=$L(2**$bitfind($factor(n),1,100,-1))+1 f i=0:1:n { w $j(i,w) } f i=1:1:n { w !,$j(i,w) f j=1:1:n { w $j($zb(i,j,6),w) } } ``` Detailed: ``` x(n) set w=$Length(2**$bitfind($factor(n),1,100,-1))+1 for i=0:1:n { write $justify(i,w) } for i=1:1:n { write !,$justify(i,w) for j=1:1:n { write $justify($zboolean(i,j,6),w) } } ``` [Answer] # [Go](https://golang.org/), 145 bytes A function literal which prints to `STDOUT`. Abuses `Sprintf` heavily. ``` import ."fmt" func(n int){s:=Sprintf n++ for i:=0;i<n*n;i++{Printf(s(" %%%dd",len(s("%d",1<<len(s("%b",n-1))-1))),i/n^i%n) if-^i%n<1{Println()}}} ``` ~~[Try it online!](https://tio.run/##zY5BCoMwFET3/xQhEEiMVrPVeIdC9wWrRj7Vr6hdSc6eqqWL3qCLgTcMDK8bQxoFHKZxXtmFu2Hl4F5US2JIq9qWvLxN844OSGtw48wwL7MCLUVUoNbb9VzlIjkTQjQNj/uWjip2NNZ@24PHlBiljqgYU7qjIAXokgOs@Rz1JJX3PkQpwFTVz6pr2VAhwa/i6XgOUrENXF7@gfRuJU2mwIc3 "Go – Try It Online")~~ - it appears the Go installation on TIO is older than on my machine, this code runs perfectly locally: ``` go run "xortable.go" (with n=10) 0 1 2 3 4 5 6 7 8 9 10 1 0 3 2 5 4 7 6 9 8 11 2 3 0 1 6 7 4 5 10 11 8 3 2 1 0 7 6 5 4 11 10 9 4 5 6 7 0 1 2 3 12 13 14 5 4 7 6 1 0 3 2 13 12 15 6 7 4 5 2 3 0 1 14 15 12 7 6 5 4 3 2 1 0 15 14 13 8 9 10 11 12 13 14 15 0 1 2 9 8 11 10 13 12 15 14 1 0 3 10 11 8 9 14 15 12 13 2 3 0 ``` ## Explanation First, we declare the function's arguments (a single integer `n`) and alias `Sprintf` to `s`, as we use it many times later. ``` func(n int){s:=Sprintf n++ ... } ``` Notice that we also increment `n`. Because the table goes up to `n` and includes, we actually want `n+1` rows. Incrementing `n` here saves bytes later. Next, we declare the loop; rather than using a two-dimensional loop, we can simply loop one variable `i` up to `n*n`, and use `i/n` and `i^n` to access the current coordinates. ``` for i:=0;i<n*n;i++{...} ``` Now comes the string padding. To work out the padding required, we need to find the largest entry in the table. This will be `n`, but with all its non-leading binary `0`s changed to `1`s. So, we format `n` into its binary representation, find its length, right-shift `1` by this amount, and decrement. ``` 1<<len(s("%b",n-1))-1 ``` We now format this into base 10 and find its length. ``` len(s("%d",...)) ``` This, plus `1` is the width that entries should be padded to. Using `%Kd` pads an integer with spaces to width `K`, so we create the padding string by using `Sprintf` once again (note that using a leading space here is a byte shorter than using a `+1` for the length): ``` s(" %%%dd",...) ``` Now, we print the entry in the XOR table (given by `i/n^i%n`) via this string format: ``` Printf(...,i/n^i%n) ``` Finally, if we have reached the end of a row, we output a newline. We check if `(i+1) % n == 0` in the golfiest way possible: ``` if-^i%n<1{Println()} ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` üvx`₧¥ⁿ∙√ ``` [Run and debug it](https://staxlang.xyz/#p=817678609e9dfcf9fb&i=9) [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `Rj`, 21 bytes ``` Ẋƛ÷꘍;:GSL£:L√ẇƛvS¥v↳Ṅ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=Rj&code=%E1%BA%8A%C6%9B%C3%B7%EA%98%8D%3B%3AGSL%C2%A3%3AL%E2%88%9A%E1%BA%87%C6%9BvS%C2%A5v%E2%86%B3%E1%B9%84&inputs=9&header=&footer=) ``` Ẋ # Cartesian product with self ƛ ; # Map to... ÷꘍ # xor :GSL£ # Store the largest's length in the register :L√ẇ # Squareify ƛ # Map to... vS # Stringified ¥v↳ # Padded Ṅ # Joined by spaces # (J flag) joined by newlines ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 58 bytes ``` <L&⟦gjẋ{ḃᵐ↔ᵐz₁-ᵐ↔cẹ~ḃṫ↔}ᵐP,Ṣzztg;Pz{z₁tᵐ↔c}ᵐġ↙L{~ṇṇ₂~ṇ₁ẉ}ᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/38ZH7dH8ZelZD3d1Vz/c0fxw64RHbVOAZNWjpkZdCC/54a6ddSC5nauBvFqgYIDOw52LqqpK0q0DqqpBKkugKkGSRxY@apvpU133cGc7ED1qaqoDU40Pd3WCpP//twQA "Brachylog – Try It Online") I don't *entirely* regret writing this... only took *one* hour... ``` {...}ᵐ XOR (and do a bit of other stuff to) each pair from ẋ the flat Cartesian product of ⟦gj [0 .. input] with itself. { } ḃᵐ Get the binary representation of each argument ↔ᵐ least significant bit first. z₁ Non-cycling zip. -ᵐ Subtract each pair/singleton. ↔ Reverse back. cẹ Concatenate then explode--remove signs and leading zeroes. ~ḃ Convert from binary. ṫ Convert to string. ↔ Reverse again. P Let the result of that mess be P. ,Ṣ Append " ", zz cycle each element to the length of the longest, t then get just the cycled space back. g;Pz Pair it with each element of P. { }ᵐ For each pair: z₁ non-cycling zip. tᵐ take the last element of each pair or singleton, ↔ reverse back, c and concatenate back to a string. ġ Split that result into slices of a length <L& ... ↙L equal to the least integer greater than the input. { }ᵐ For each slice: ~ṇ join it on newlines, ṇ₂ split it on newlines and spaces simultaneously, ~ṇ₁ join it on spaces, ẉ and print it with a trailing newline. (~ṇ₁ can't be used for lists with strings which already contain spaces, because they couldn't result from ṇ₁--that being split on spaces ``` [Answer] ## Pyke, 8 bytes ``` hD]UA.&P ``` Explanation: ``` - auto-add eval_or_not_input() to the stack h - increment the input D] - Create a list containing [inp+1, inp+1] U - Create a 2d range A.^ - Deeply apply the XOR function to the range P - print it out prettily ``` [Try it here](http://pyke.catbus.co.uk/?code=hD%5DUA.%5EP&input=10) [Answer] # Python 2, 77 bytes ``` n=input()+1 t=range(n) for i in t: print "%3d"*n % tuple([x^i for x in t]) ``` [Answer] # [J](http://jsoftware.com/), 10 bytes ``` XOR/~@,~i. ``` [Try it online!](https://tio.run/##y/r/P81WTyHCP0i/zkGnLlPvf2pyRr5CmoIpF5Rh@R8A "J – Try It Online") [Answer] # Excel VBA, 95 bytes Anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the console. ``` For y=0To[A1]:For x=0To[A1]:z=x Xor y:?Spc([Len(2^-Int(-Log(A1,2)))]-Len(z))Str(z);:Next:?:Next ``` [Answer] # [Small Basic](http://www.smallbasic.com "Microsoft Small Basic"), 499 bytes A script that takes input from the `TextWindow` object and outputs to the same ``` a=TextWindow.Read() For y=0To a For x=0To a n=x b() z1=z n=y b() l=Math.Max(Array.GetItemCount(z),Array.GetItemCount(z1)) o=0 For i=1To l If z1[i]<>z[i]And(z[i]=1Or z1[i]=1)Then z2=1 Else z2=0 EndIf o=o+z2*Math.Power(2,i-1) EndFor TextWindow.Write(Text.GetSubText(" ",1,Text.GetLength(Math.Power(2,Math.Ceiling(Math.Log(a)/Math.Log(2))))-Text.GetLength(o))+o+" ") EndFor TextWindow.WriteLine("") EndFor Sub b z=0 c=0 While n>0 c=c+1 z[c]=Math.Remainder(n,2) n=Math.Floor(n/2) EndWhile EndSub ``` [Try it at SmallBasic.com](http://smallbasic.com/program/?TNX767 "SmallBasic.com") *Uses Silverlight and thus must be run in IE or Edge* Select the black console, then type input integer and press `Enter`. [Answer] # APL(NARS), 57 chars, 114 bytes ``` {∘.{⍺=0:⍵⋄k←⌈/{⌊1+2⍟⍵}¨⍺⍵⋄(2⍴⍨≢m)⊥m←↑≠/{⍵⊤⍨k⍴2}¨⍺⍵}⍨0..⍵} ``` (NARS2000 0.5.13) test: ``` q←{∘.{⍺=0:⍵⋄k←⌈/{⌊1+2⍟⍵}¨⍺⍵⋄(2⍴⍨≢m)⊥m←↑≠/{⍵⊤⍨k⍴2}¨⍺⍵}⍨0..⍵} q 5 0 1 2 3 4 5 1 0 3 2 5 4 2 3 0 1 6 7 3 2 1 0 7 6 4 5 6 7 0 1 5 4 7 6 1 0 q 1 0 1 1 0 q 9 0 1 2 3 4 5 6 7 8 9 1 0 3 2 5 4 7 6 9 8 2 3 0 1 6 7 4 5 10 11 3 2 1 0 7 6 5 4 11 10 4 5 6 7 0 1 2 3 12 13 5 4 7 6 1 0 3 2 13 12 6 7 4 5 2 3 0 1 14 15 7 6 5 4 3 2 1 0 15 14 8 9 10 11 12 13 14 15 0 1 9 8 11 10 13 12 15 14 1 0 ``` [Answer] # [Perl 5](https://www.perl.org/) `-n`, 62 bytes ``` for$i(0..$_){printf+(" %".(0|log).d)x($_+1).$/,map$_^$i,0..$_} ``` [Try it online!](https://tio.run/##HctBCoAgEADAr4RsoJibHTz0iL6QBGUIpmIdgurrbdDcJy8lGCKXCniuEcGKKxcfDyc5q2qGXN8hrQJncXKwshMIbbNNGewIvvnHQ9S/KR8@xZ3UYFB3mlScPg "Perl 5 – Try It Online") [Answer] # APL, 20 bytes ``` {2⊥¨∘.≠⍨↓⍉2⊥⍣¯1⍳⍵+1} ``` Explanation: ``` ⍳⍵+1 ``` integers from 0 to n ``` 2⊥⍣¯1 ``` base 2 encoding ``` ↓⍉ ``` create nested of boolean vectors ``` ∘.≠⍨ ``` xor matrix ``` 2⊥¨ ``` base 2 to base 10 conversion [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Ż^þ`G ``` [Try it online!](https://tio.run/##y0rNyan8///o7rjD@xLc////bwkA "Jelly – Try It Online") ## How it works ``` Ż^þ`G - Main link. Takes N on the left Ż - Range from 0 to N ` - Using this range as both arguments: ^þ - Create an XOR table G - Format into a padded grid ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` ʀ:v꘍vvS:fÞGL↳⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLKgDp26piNdnZTOmbDnkdM4oaz4oGLIiwiIiwiOSJd) ]
[Question] [ *Your challenge*: The code must print "Hello, World!" and nothing else. *Your restrictions*: Your program must satisfy these requirements: 1. The program must be a pangram. * It must use every character in printable ASCII, or, if you chose a particularly strange language, characters which are stored as one byte. * You are allowed to use other characters. 2. The program may not have unnecessary characters. * No subset of individual characters may be removed from the program while the program still outputs "Hello, World!" * For example, if code `ABBC` outputs `Hello, World!` then neither codes `AC` nor `BC` may output "Hello, World!", although code `BA` may. * This also means you cannot have a statement to print "Hello, World!" *per se* anywhere in your program, as everything other than that statement could be deleted and the program would do the same thing. 3. The program must not take input. 4. Your program does not create any errors. 5. You must not use any "Hello, World!" builtins. *Your score*: Your score is calculated by [length of the program in characters] - [number of different characters]. Lowest score wins. (Tie-breakers are oldest post.) *Nota Bene*: the second requirement is almost impossible to verify, so an answer is valid only after a week has passed for anyone who wishes to do so to be able to disprove the validity of your answer. [Answer] # [Husk](https://github.com/barbuz/Husk), 256 bytes, 256 characters, score=0 ``` m←`C₁†ȯ→*2c¨abqnpsyhkzjwf ¢"H½↕↑↓↔∟¦¡¿‼…‰‡√≤≥±∂∫∞≈≠≡⌐¬÷×τ►#$%&'()+Φ-./013456789:;<=>?@ABDEFG¤IJKLMNOPQRSTUVṄXYZ[\]^_⁵ı§χituvxg¹{|}~·₀₂₃₄₅₆₇₈₉⌈⌉⌊⌋ΓΔΘΛΞΠΣ€ΨΩαβγδεζηθλμξπρςσ▲φƒψω⁰r²³⁴d⁶⁷⁸⁹£,¥o´ ▼!◄lȦḂĊḊĖḞĠḢİĿṀWȮṖṘṠṪẆẊẎŻȧḃċḋėḟġḣeȷŀṁṅṗṙṡṫẇẋẏżÄËÏÖÜŸØäëïöüÿø◊□¶«» ``` [Try it online!](https://tio.run/##DcTXchJRHAfge5/C3nvvvffejV2jscfYdXYPZLMLjIlJXLAMYQMhUTIGCIE9C8rMOYvD1dln@P9eBP0uvvauzo5W6yGMvmu7wHRoqeYEjP6FK2@Kses3nj560vm6vePN/Zd3ponhmfvFbxifYXyCMQBjEOaQyApH1KHVoGWh5aE5ML/CysAaEQWYDGYOZhKWCSsFy0GsT4zLiowHYdjerNlz5s6bv2CRyi5Zumz5ilWr16xdt37Dxk2bt2zdtn3Hzt179u4TmQMHDx0@cvTY8RMnT50@c5Z4@PyFi5cuX2m7Cn3KL4jRoOfe864Xr@4K/vbd@w@iAqaBMbAQWBisG8wA6wEzwSzETMT@H0EsqgbUoEqobyqpUioNNq7G1A9VUEU1qUpqSpVVRbmqqmrqT6AFesCCEOxiYPztD8zAgp5/JopiEnrpFvQy9Ap0FzoX6cVi5LEoTYddm4F4@EEzSy7zI@RGfJvcpJ8id9jP@3Xi2rnmL@I28QTxFPGf5BnkRcj72Kg2R8kN@VFyo36c3CHfITd9u1lpaMR14t3E48S/EHeI58jrIS9KXm@jJsMyKnulLb83XJmQGZmTE7Isa7IuXcQjsB1RFjlRbbX@AQ "Husk – Try It Online") I *think* this is irreducible. It certainly took a bit of effort to build, but striving for a score of zero is inviting pretty close scrutiny... [Husk](https://github.com/barbuz/Husk) has 256 characters on its [codepage](https://github.com/barbuz/Husk/wiki/Codepage), so this pangram needs to use all of them. Aiming for a zero score also means that (a) the 'program' code cannot easily include any of the letters of 'Hello, World!', and (b) we need to find a way to 'recycle' the letters 'l' and 'o', which each occur more-than-once in the output. Unfortunately, [Husk](https://github.com/barbuz/Husk) uses '!' as its indexing function, which rules-out the most straightforward approach to extracting elements from a long string, so we need to find a different way to do this. Here's my approach: **line 2: the encoding string (228 characters, + 2 characters `¢"`)** ``` ¢"H½↕↑↓↔∟¦¡¿ ... öüÿø◊□¶«» # A 228-character string, repeated forever. # Since one of the characters is a '\', though, # this is read by Husk as a 227-character array. # The characters of 'Hello, World!' are inserted # at specific positions in the infinite string, # (so they occur out-of-order in the single copy). ``` **line 1: the indexing program (26 characters)** ``` †ȯ c¨abqnpsyhkzjwf # For all the codepoints of the index string "abqnpsyhkzjwf": *2 # double them → # and add 1. `C₁ # Now divide the encoding string into substrings with these lengths m← # and get the first letter of each. ``` The indexing string `"abqnpsyhkzjwf"` is constructed to 'hit' the letters 'o' and 'l' 2 and 3 times, respectively, by 'wrapping around' in the infinite list, so that those letters only need to occur once in the encoding string. The largest index needs to be the same as the length of the encoding string, in order to 'hit' the same target ('l') twice in a row: this is achieved with 'q' (2x codepoint 113 + 1 = 227). [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~111~~ 109 bytes, score = 14 ``` main(){printf("H%cllo, Wo\x72ld!",39+sizeof"14568:<=>?@ABCDEFGIJKLMNOPQRSTUVXYZ[]`bghjkquvwy0|~#$&'*-./^_");} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oCgzryRNQ8lDNTknJ19HITw/psLcKCdFUUnH2FK7OLMqNT9NydDE1MzCysbWzt7B0cnZxdXN3dPL28fXzz8gMCg4JDQsIjIqOjYhKT0jK7uwtKy80qCmTllFTV1LV08/Ll5J07r2//9/yWk5ienF/3XLAQ "C (gcc) – Try It Online") Edit: bugfix thanks to Noodle9 Edit 2: changed order of numbers and operators in the string to fix a problem found by G B, replaced `"Hello, World!"` with `"Hello, Wo\x72ld!"` ## shorter solution based on Sheik Yerboutis Code (107 bytes, score = 12) ``` main(){printf("H%cllo, Wo\x72ld!","_:?=<#$&*-+^|./4138596@ABCDEFGIJKLMNOPQRSTUVXYZ`bghjkquvwysz0~e"['>']);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oCgzryRNQ8lDNTknJ19HITw/psLcKCdFUUlHKd7K3tZGWUVNS1c7rkZP38TQ2MLU0szB0cnZxdXN3dPL28fXzz8gMCg4JDQsIjIqISk9Iyu7sLSsvLK4yqAuVSla3U49VtO69v//f8lpOYnpxf91ywE "C (gcc) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~119~~ 112 bytes / score 17 ``` puts ["%x"%(("!\#&+,-01245:;<>?@ABDEFIJKLNOQRUVWXYZ`dflqnry{|}"=~/$/)^"s8j9bePwGp7SgMTCvznH".to_i(36))].pack'h*' ``` [Try it online!](https://tio.run/##KypNqvz/v6C0pFghWkm1QklVQ0NJMUZZTVtH18DQyMTUytrGzt7B0cnF1c3Ty9vHzz8wKDQsPCIyKiElLacwr6iyuqZWybZOX0VfM06p2CLLMik1oNy9wDw43TfEuawqz0NJryQ/PlPD2ExTM1avIDE5Wz1DS/3/fwA "Ruby – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 101 bytes, 101 - 95 = 6 ``` print('o#$%&*./0W368;<=>? @ABCDEFG,IJKLMNOPoQRSTUVXY\154Z^_`abcflghjkmqsuevwyz{|}~H'[::-9]+"\x72ld!") ``` [Try it online!](https://tio.run/##K6gsycjPM/5fUJSfXpSYq2CrUKSkpATkZuaVaKjnK6uoqmnp6RuEG5tZWNvY2tkrODg6Obu4urnreHp5@/j6@QfkBwYFh4SGRUTGGJqaRMXFJyQmJaflpGdkZecWFpemlpVXVlXX1NZ5qEdbWelaxmorxVSYG@WkKCpp/gfapFdcUpRZoKHJlVqRmqwBdYUmV1p@kUKyQmaeQlFiXnqqhkGFkYGOgkGFeZqmFZeCQmaaQnJGkUaypkJefglIFVQfSE5BAeJ2iALN/wA "Python 3 – Try It Online") [Answer] # [Backhand](https://github.com/GuyJoKing/Backhand), 100 - 95 = 5 ``` M#$%&"()*+H-./0e1234l5678l9:;<o=>?@,ABCD FGIJWKLNOoPQRSrTUVXlYZ[\c^_`b"dfgh]ikmn'pqst!uvwxryz{}a|~jE ``` [Try it online!](https://tio.run/##lVh7d9M2FP@7@RRqSrHdxE1c9sJrC4Xx6AaUDTa2hRAcR00Ejmxkp014ffXuSrIsWXHKWc9JY@v@7tXVfSvZqpil9NbVzjbqLXLWGxPay@Raq0XmWcoKlK9y9cgiOknnrVacRHmOXhRR/N71wtbWBJ@j0YhQUoxGbo6Tc764xR/2cw5CR2gwbElclmYawnCxYBRp5D4ne4icG2sIJzlGfcW/yGdCQBfRxTwXYgBerDLsigVEcpSQvOCErfOUcRgiVKBDc6soyzCdcCYPoHyTDeTca6kz3wPKDKwwOqUFZhnoj1mzCbooTidYG2IegQ5giNJqajktZpgZy2o9SwnfASh9tcTlwTv/UksfFmnB1x5GoL1anBDOFmgP4Azeb6l3vIxxnt@fRRz1LKWaD48XU1sYw1OwJa6w8qTposgWxRnF2pUpIErNM3E8cIofoEOUwqe/DII@/IU8mkCjCQjYv2SkwG48Y27qWR7AjKXMbb9kBE9QkaKMgTXAiRdRQiYI/i8wcncnHopyFMNJohhUfE3bu6lX0/AkSbSGlzOSYFQ5Q7q53FAfiGsiRRQEPCK5yT7sQqf4ufSKS4RV9wi3dVcaTG1cB1aB2kX4IgETvWQLIyiUlztHHAOr8QyLdOGwSmWxKMJZkZWLtlSiKEHHRyjB1K3iRWy1FlJ1CPKRWwP4FoAjDrQcGV@@ehYES2/wpa0ZBEGjLr75/r82gR3ApmF9G7@MQuDZq8J/U@kwgkHQZK5bZQqZRUpiRYRL3BQXPJV0lKlz6zSTnlPpoddbW9dkpEiGilEmDWzNcDRxA08RUjZxY1EuY1kl/UBX1Vir@GwxH2NDyWVZV2R8LdH2Ec9VqGuIp@PSQzTl6YacfnBw67vvf/jxp9uO0GYFjEv@sFTnUQYoUx7WuazKakIhCmBwjyuFe60N7Bu1adKEy6R7QR91LNHNstcNvZQKc8aVx7V2fCdEXKxPtRFpaUS2oNp8lTN5egzM@BsaESDqqdBVlC8jofSag5y9eiVw3jiexaOrlU0R3cMgEQpVTLlCd4iwLBWxOGbbCVFj9zArsE4KGWNCPHx20BOo2gw4WmWWx5Z7onEMBlN7CBHr1H1CJ3hZyi3FNOpW5rqGtJ12WGWOKNFe9Vrpu8E5nizucAjRbtE8oiRbJFFBUlrX42ulf9nNDNqN2tkGGtY1WIYWU7iJabh3YEFvOqFZ2qsOvC2Lg1lFVUGrQJ4m2p17yygqa4hNZ2VOaHdMhdYrgzD0g2GdMamdt@onRihbO7k1BiO6hVYW2FPgElKxNIGX5hm6qDZ26ZeuxqgguZ/SgqUJepikl3WRh0pk2aaCOvm4TraonxS1Pir4gaX3l2acDXvjVGMrDHqdte2e2vSDOv2iRvfX@F/ZdIv/TrOa8q4AiymJsTvwg24wtD3zztGpXB947Ul2q2GHjQ7PQaNv8uypHSzmu07Vu1RdFMFwDw4Uzwid1uGjTc5EegDiNxrRnW3XfbbCqHpu4DUmIUPCdi1reF/gnduwjLXjkzW8sc/hNYyPrmM8vobxwXWMR0c2p7D1CdwMZnMM1b3eZPZ6ux1fxkzUHdfKVrdewnS365XBIJq20@s54gXIESf36xeOk6LA86yQl44JuSBw4xqv0EfM0rbVZjDcQty8YO7Y68Qd/hCtnX2wXtOEgmupPtwA7ASVTU7P6ixknaWadyzpqdN4yzEQp43CyqnRFnfmNFzjuAE2B8Fr6oRybLEIj536fK2vbZ4YAFUKGiwzg@VbWhgy9EgnRgo51Um3yyvBHEbDaAo3Jh4upWSgl5JLKkybbbhnilMsScGLcStj6ZRFcwivdrt99XTnxu7NNtSXzmN/v9fHfPJJ@OiT3A5/PkyPju/c7Z7cu/8Levjo9NdXvz15dpY@//2PF@zln3/9nfzz7@B1/Gb0dtyenE9nQ/J@Tp3sQ15sLy4ul2z18dOX6PPXdw@uYKNBIJpui/DfHWg0x6ORGI9GI97CRiM@JRHQqfEXi1JlOAaw84pRLogLjEqG5@W54ohyyBgjnhsrfvgdUv1aIAc0ObqTfT4mgwVJOZld/Qc "Python 3 – Try It Online") Note that the version on TIO is missing a couple of instructions (notably `'`), so I've copied the interpreter here. This program works because Backhand executes every fifth instruction thanks to the first `M` (it's actually a little more complex than this), so the actual code is more like: ``` M " H e l l o , W o r l c " ] ' ! r a j ``` However, since you can't remove the spaces inbetween without breaking the flow of the program, you can replace them with whatever you want. The final check is that the `j` jumps to the 10th character (`H`) to halt and output,, which is less feasible if you modify the program. It's possible you might be able to form a valid program from this mishmash, but it is unlikely, and I'm sure that there's another permutation that fixes that. ### Explanation: ``` M Increase the step count from 3 to 5 "Hello, Worlc" Push the string to the stack ] Increment c to d '! Push ! r Reverse the stack aj Jump back to the 10th character H Halt and output the stack ``` [Answer] # JavaScript (ES6), score ~~30~~ 124 - 95 = 29 ``` alert(`Hell`+String.fromCharCode(057^"#$%&*-/1234689:;<=>?@ABDEFGIJKLMNOPQRTUVXYZ][_bcjkpqsuvwxyz{|}~\\".length)+', World!') ``` The `o`s of `fromCharCode` cannot be put inside quotes. Its char code is 111, which can't be uses directly as an argument to `String.fromCharCode`. You can't XOR to get it because you need 64, 86, 104 or 106, which are also impossible, I think. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 118 117 116 - 95 = 21 shoutout to [tsh](https://codegolf.stackexchange.com/users/44718/tsh) for spotting 2 issues ``` alert(`Hello, Wo${('\71'+";#%&*/8025:<=>[]?@ABCDEFGIJKLMNOPQRTUVXYZ|_bcfjkpmqsuvwxyz".length^-~94).toString(36)}d!`) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@Yk1pUYpucn1ecn5Oql5OfDhHRSPBIzcnJ11EIz1ep1lCPMTdU11ayVlZV09K3MDAytbKxtYuOtXdwdHJ2cXVz9/Ty9vH18w8IDAoJDYuIjKqJT0pOy8ouyC0sLi0rr6isUtLLSc1LL8mI062zNNHUK8kPLinKzEvXMDbTrE1RTND8/x8A "JavaScript (Node.js) – Try It Online") [Answer] # [BASIC](http://www.yabasic.de), 129 bytes ``` FOR i=8-2 TO 79 STEP 3+3:PRINT MID$("9*./!H065<>e?@ABClGJKLQlUVYZ[o\]^_`,abcf ghjksWmnpqxotuvwyrz4{|}l~#%&'d",MOD(i,73),1);:NEXT ``` [Try it online!](https://tio.run/##q0xMSizOTP7/380/SCHT1kLXSCHEX8HcUiE4xDVAwVjb2CogyNMvRMHX00VFQ8lSS09f0cPAzNTGLtXewdHJOcfdy9snMCc0LDIqOj8mNi4@QScxKTlNQSE9Iyu7ODw3r6CwIr@ktKy8sqjKpLqmNqdOWVVNPUVJx9ffRSNTx9xYU8dQ09rKzzUi5P9/AA "Yabasic – Try It Online") Updated to a valid version thanks to Dominic van Essen. [Answer] # [R](https://www.r-project.org/), ~~119~~ 117 bytes, score=~~24~~ 22 Thanks to Dominic van Essen for spotting a bug. ``` cat('Hello, Wo',intToUtf8(nchar("#$%&*-./012479:;<>?@ABDEFGIJKLMNOPQRSVXYZ[]^_`bgjkmquvwyz{|}~")+53),"\x6Cd!",sep="") ``` [Try it online!](https://tio.run/##K/r/PzmxREPdIzUnJ19HITxfXSczryQkP7QkzUIjLzkjsUhDSVlFVU1LV0/fwNDIxNzSytrGzt7B0cnF1c3d08vbx9fPPyAwKDgsIjIqOjYuPiEpPSs7t7C0rLyyqrqmtk5JU9vUWFNHKabCzDlFUUmnOLXAVklJ8/9/AA "R – Try It Online") Uses the [hex code trick](https://codegolf.stackexchange.com/a/191117/86301) to encode the last `l` as `\x6C`. This saves 2 bytes: 1 by avoiding the reuse of the `l` (none of the other characters are used anywhere else), and 1 by avoiding having to escape the `\` (as `\\`) in the string. The long string in the middle is 61 characters long. They are all necessary to get the character `r` (ASCII code 114), which is produced by the `intToUtf8(nchar("...")+53)` part. [Answer] # [C (gcc)](https://gcc.gnu.org/), score 114 - 95 = 19 Saved 2 bytes and removed 3 points thanks to [Sheik Yerbouti](https://codegolf.stackexchange.com/users/100356/sheik-yerbouti)!!! ``` j;main(){for(;j<74;j+=6)putchar("H#$%&'e*-./0l12358l9:>?@oABCDE,FGIJK LMNOPWQRSTUoVXYZ\\r^_`bglkqsvwdxyz|~!"[j]);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/LOjcxM09Dszotv0jDOsvG3MQ6S9vWTLOgtCQ5I7FIQ8lDWUVVTT1VS1dP3yDH0MjY1CLH0srO3iHf0cnZxVXHzd3Ty1vBx9fPPyA8MCg4JDQ/LCIyKiamKC4@ISk9J7uwuKw8paKyqqZOUSk6K1bTuvb//3/JaTmJ6cX/dcsB "C (gcc) – Try It Online") All characters outside of the double-quotes are needed in order for the program to compile and run properly. Taking any of the characters out from the double-quoted string will mess-up `Hello, World!` from being printed properly. That string is *exactly* `Hello, World!` with 5 characters in between each character. [Answer] # [Zsh](https://www.zsh.org/), score \$ 116 - 108 = 8 \$ ``` 1=`wc -m<<<'␀␁␂␃␄␅␆␇␈␎␏ABCDEFGIJKMNOPQRSTUVXYZabfghjkqsuvxyz234567890_+[];:~./>?\|"%^&*'` print He${(L#)@}lo, World! ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwbrk_JRUWxUNGxt1Vz8X9aWlJWm6FjdLDG0TypMVdHNtgOIMjEzMLKxs7Bx8_I5Ozi6ubu6eXt6-fv4BgUHBIaFhEZFRiUlp6RlZ2YXFpWUVlVVGxiamZuYWlgbx2tGx1lZ1evp29jE1SqpxalrqCVwFRZl5JZweqSrVGj7Kmg61Ofk6CuH5RTkpilC75wHdwaXJVVJZkFqcWqKgmxiqUJqXWViaygWhbDWAWouVlDRBLq_V5CpILE7OzLTVqFbU06sD8lOTM_IVcjOLizPz0q0UVKoh8lY1EN21EPni5PyiVKCsMsgQBV0gAyKtYKugEo0hGsuVWpaYo6ACEoa4csECCA0A) `␀␁␂␃␄␅␆␇␈␎␏` should be the unprintable characters `0x00` to `0x08` and `0x0E` to `0x0F`, but these don't render in SE markdown. ]
[Question] [ Given *N* decanters (0 < *N* < 10) with that can hold *C0* ... *CN-1* liters (0 < *C* < 50) and a goal *G* liters, please determine if it is possible to reach that goal using only the following actions: * Fill a decanter * Empty a decanter * Pour from one decanter to another until the one being poured to is full or the one being poured from is empty The goal amount *G* must be the amount of water in one of the containers at the end. You cannot have a 'output decanter'. ## Examples *N*: 2 *C0*: 5 *C1*: 12 *G*: 1 Result: Yes *N*: 3 *C0*: 6 *C1*: 9 *C2*: 21 *G*: 5 Result: No **Hint:** To calculate if it is possible, check to see if *G* is divisible by the GCD of the capacities. Also, make sure it will fit in a container. Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the lowest number of bytes wins. ## 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=94202,OVERRIDE_USER=12537;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] ## Haskell, 35 bytes ``` l%n=n`mod`foldr1 gcd l<1&&any(>=n)l ``` [This paper](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.96.6047&rep=rep1&type=pdf) proves a result that vastly simplifies the problem. Prop 1 says that > > You can achieve a goal exactly when it's both: > > > * A multiple of the greatest common divisor (gcd) of the capacities, > * At most the maximum capacity > > > It's clear why both of these are necessary: all amounts remain multiples of the gcd, and the goal must fit in a container. The key of the result is an algorithm to produce any goal amount that fits these conditions. Call the operator `%` like `[3,6,12]%9`. A 37-byte alternative: ``` l%n=elem n[0,foldr1 gcd l..maximum l] ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~9~~ ~~8~~ 9 bytes Uses the [CP-1252](http://www.cp1252.com/) encoding ``` ZU¿%²X>‹‹ ``` **Explanation** ``` # true if % # target size modulo ZU¿ # gcd of decanter sizes ‹ # is smaller than ²X>‹ # target size is less than or equal to max decanter size ``` [Try it online!](http://05ab1e.tryitonline.net/#code=WlXCvyXCslg-4oC54oC5&input=WzYsNiw2XQo2) Saved 1 byte utilizing the less than trick from [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/94217/47066) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9 8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to @Dennis (use integer division, `:`, rather than not less than, `<¬`) ``` Ṁ:a⁸g/ḍ ``` **[TryItOnline](http://jelly.tryitonline.net/#code=4bmAOmHigbhnL-G4jQ&input=&args=WzYsOSwyMV0+NQ)** How? ``` Ṁ:a⁸g/ḍ - Main link: capacities, goal Ṁ - maximum capacity : - integer division with goal (effectively not less than goal since non-0 is True) a - and ⁸ - left argument (capacities) g/ - gcd reduce over list (gcd of capacities) ḍ - divides ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 10 bytes ``` &Zd\&G<~a< ``` [Try it online!](http://matl.tryitonline.net/#code=JlpkXCZHPH5hPA&input=WzYgOSAyMV0KNQ) This uses [@xnor's approach](https://codegolf.stackexchange.com/a/94206/36398). ``` &Zd % Take array C as input. Compute the gcd of its elements \ % Take number G as input. Compute that number modulo the above. Call this A &G % Push the two inputs again: C, then G <~a % Gives 1 if some element of C is at least G; 0 otherwise. Call this B < % Gives true if A is 0 and B is 1; otherwise gives false ``` [Answer] # Excel: 43 bytes `=AND(MOD(A10,GCD(A1:A9))=0,A10<=MAX(A1:A9))` [Try it online](https://docs.google.com/spreadsheets/d/1YVzoKQjNg90RVLMN_0-VUlCkjrzpdJ2GlM7ItV1K0zI/edit?usp=sharing)! **How to use:** Put this formula anywhere Except A1-A10. Then input your Decant holding volumes in cells A1:A9 (because the number of decants is fixed) and the goal in A10. cells without decants should be left blank. Wherever you put the formula will contain the result. TRUE if you can achieve the goal, FALSE if you cannot. [Answer] ## JavaScript (ES6), 58 bytes ``` (n,a)=>a.some(e=>n<=e)&n%a.reduce(g=(d,e)=>d?g(e%d,d):e)<1 ``` Another port of @xnor's answer. Yes, I get to use `reduce` again! [Answer] ## [Retina](http://github.com/mbuettner/retina), 39 bytes ``` \d+ $* ^(?>(1+)(,?\1)*;)(\1+)$(?<=\3.+) ``` Input should be a comma-separated list of the decanters, followed by a semicolon, followed by the target volume. E.g.: ``` 6,9,21;5 ``` Output is `0` (falsy) or `1` (truthy). [Try it online!](http://retina.tryitonline.net/#code=JShHYApcZCsKJCoKXig_PigxKykoLD9cMSkqOykoXDErKSQoPzw9XDMuKyk&input=NSwxMjsxCjYsOSwyMTs1) (The first line enables a linefeed-separated test suite.) ### Explanation ``` \d+ $* ``` This just converts the input to unary. Afterwards we simply match valid inputs with a single regex: ``` ^(?>(1+)(,?\1)*;)(\1+)$(?<=\3.+) ``` The part inside `(?>...)` finds the GCD. We do this by finding the largest substring `1+` with which we can match all the decanters (allowing an optional `,` only after a full match of the GCD). The atomic group (the `(?>...)`) itself so that the regex engine doesn't backtrack to divisors of the GCD if the target volume can't be matched (otherwise group `1` will at some point be reduced to matching a single `1` and all inputs will be truthy). Once we've found the GCD, we try to match the target volume as a multiple of it with a simple `(\1+)$`. Finally, we check that the target volume not greater than the largest decanter's capacity, by ensuring that the volume can be matched inside any decanter with `(?<=\3.+)`. [Answer] # Ruby, 35 bytes ``` ->n,g{g<=n.max&&1>g%n.reduce(:gcd)} ``` [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr/), 31 bytes Pretty much straightforward. Checking the max (`vecmax`) is very costly, I wonder if it can be done better. ``` f(c,g)=g%gcd(c)<1&&vecmax(c)>=g ``` [Answer] # Perl, 47 bytes Includes +2 for `-ap` Run with the jar sizes on the first line of STDIN and the target jar on the second line: ``` decanter.pl; echo 2 5 12 1 ^D ``` `decanter.pl`: ``` #!/usr/bin/perl -p $_=($_<@G)>$_%$=;$=--while@G[@F]=grep$_%$=,@F ``` This solution is unusual in that it processes the input line by line and outputs something for each of them. The output for the first line was carefully designed to be empty while the second line prints the solution. Two bytes are lost on `()` because `<` and `>` are designed to be non-associative in perl. The regex solution is also nice but 49 bytes: ``` #!/usr/bin/perl -p s/\d+/1x$&/eg;$_=/^(?>(1+)( |\1)*:)(\1+)$/&/$3./ ``` (some parts stolen from the Retina solution) For this one give input on STDIN as jars separated by spaces and target after a `:`: ``` decanter.pl <<< "2 5 12:1" ``` Hard to beat languages with a builtin `gcd` (21 bytes) and `max` (7 bytes) for this one... [Answer] # Scala, ~~90~~ 53 bytes ``` def h(g:Int,a:BigInt*)=a.max>g&&a.reduce(_ gcd _)%g<1 ``` Works basically the same as the other answers, ~~but scala doesn't have a built-in gcd function.~~ Scala has a built.in gcd function, but only for BigInt. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 7 years ago. [Improve this question](/posts/17285/edit) # Rules: * **Any language** you choose (Standard Libraries). * Output displayed in **Terminal** or **Windows Command Processor** or ***any other way*** you prefer. (width buffer = 80) * **ASCII** Characters are enough. (may add Unicode) * Shouldn't fill up the entire screen at start-up (Should look like a rain, duh!). * **Colors** gets bonus points (+5). * **Effects** : Random characters, different fall sizes, regenerates periodically. # Points: *(update)* * **+32** points to start with. * **-1** point for every byte *(not chars)* in the code after the \*\*1024\*\*\*th\* byte. * Points could reach zero and negative. * **Note:** Languages using *multibyte characters* should count bytes not characters. * **+5** for every new effect. (not posted by others) * **+15** for any of these effects: 1. Wind(blows characters to the side) 2. Number Matching(user input, eg:90210): Number is randomly located within the matrix ![enter image description here](https://i.stack.imgur.com/qCev9.jpg) 3. Sound 4. Encrypted msg(user input): Characters represent a secret encrypted message 5. Galaga mode: Fires ^ to destroy characters ![enter image description here](https://i.stack.imgur.com/GRBRv.jpg) # Scoreboard: ``` ┌-----┬------------┬------------┬-------------┬---------------┬--------------┐ | pos | name | type | bytes | effects | points ^ | |-----|------------|------------|-------------|---------------|--------------| |1 |nitro2k01 |QBasic |913 |Colours |+57 | | | | | |Colour Fade | | | | | | |Sound (+15) | | |-----|------------|------------|-------------|---------------|--------------| |2 |squeamish |HTML, Java- |1024 |Colours |+47 | | |ossifrage |Script, CSS | |Transition | | | | | | |Size Variation | | |-----|------------|------------|-------------|---------------|--------------| |3 |manatwork |Ruby |374 |Colours |+47 | | | | | |Actual Words | | | | | | |Character - | | | | | | | Disperse | | |-----|------------|------------|-------------|---------------|--------------| |4 |plg |Bash |1024 |Colours |+42 | | | | | |Random Pause | | |-----|------------|------------|-------------|---------------|--------------| |5 |Timtech |TI-84 calc |120 |Umbrella |+42 | | | | | |Run Inside | | |-----|------------|------------|-------------|---------------|--------------| |6 |Samuel Cook |JavaScript |830 |Colours |+42 | | | | | |Transition | | └-----┴------------┴------------┴-------------┴---------------┴--------------┘ ``` **Note :** *Scoreboard will/could be updated by anyone after posting a valid answer. Do not exceed top ten positions. Add more effects to your code and beat your own score! Clearing initial screen, cleanup, bugs, third party libraries etc. would not count towards the points Remember to include details about no. of bytes used and the name of language or program.* > > Neo: What are you trying to tell me? That I can dodge bullets? > > > Morpheus: No, Neo. I'm trying to tell you that when you're ready, you > won't have to. > > > [Answer] # HTML, Javascript and CSS: 1024 bytes, 47 points ![Matrix rain demo](https://i.stack.imgur.com/Ns53Z.png) **Features:** * Uses Unicode characters (don't think this scores any points though) * Trails fade from bright to dark green while they are being drawn (\*) * Trails also fade from dark green to black after the drawing has finished (\*) * Random text size in each trail (\*) * Trails are randomly repositioned and resized each time they are drawn (\*) I'll claim +5 points for each of these, but let me know if you disagree :-) **Demo:** <http://ruletheweb.co.uk/matrix.html> **Source code:** Exactly 1024 bytes. It's a bit ugly, I'm afraid. ``` <head><style>*{margin:0;padding:0;line-height:1;overflow:hidden;}div{width:1em;position:absolute;}</style><script> w=window;n=w.innerWidth;m=w.innerHeight;d=document;q="px";function z(a,b){return Math.floor(Math.random()*(b-a)+a)}f=" 0123456789";for(i=0;i<45;i++)f+=String.fromCharCode(i+65393);function g(){for(i=0;i<90;i++){r=d.createElement("div");for(j=z(20,50);j;j--){x=d.createElement("pre");y=d.createTextNode(f[z(0,56)]);x.appendChild(y);x.style.opacity=0;r.appendChild(x)}r.id="r"+i;r.t=z(-99,0);with(r.style){left=z(0,n)+q;top=z(-m,0)+q;fontSize=z(10,25)+q}d.body.appendChild(r);setInterval("u("+i+")",z(60,120))}}function u(j){e=d.getElementById("r"+j);c=e.childNodes;t=e.t+1;if((v=t-c.length-50)>0){if((e.style.opacity=1-v/32)==0){for(f in c)if(c[f].style)c[f].style.opacity=0;with(e.style){left=z(0,n)+q;top=z(-m/2,m/2)+q;opacity=1}t=-50}}e.t=t;if(t<0||t>c.length+12)return;for(f=t;f&&f>t-12;f--){s=1-(t-f)/16;if(f<c.length&&c[f].style){c[f].style.opacity=s;}}} </script><body text=#0f0 bgcolor=#000 onload=g()> ``` [Answer] **Bash** 1024 bytes (including comments) ``` COL=80 ROW=$(tput lines) cleanup() { wait # wait for background jobs (the drops) # clear; move cursor to (1,1); show cursor # reset color printf '\033[2J\033[1;1H\033[?25h\033[0;0m' } drop() { # $1=column ; $2=row to end on ; $3 = drop size (ranges from 5 to 15) for ((r=1; r<$2+$3+1; r++)); do # if before drop's end point : print lowest char in white [ $r -lt $2 ] && printf "\033[$r;$1H\033[0;0m\u$[RANDOM % 59 + 21]" # if before or on drop's end point : replace older white char with a green one [ $r -le $2 ] && printf "\033[$[r-1];$1H\033[0;32m\u$[RANDOM % 59 + 21]" # if drop's longer than it's size : erase last char [ $r -gt $3 ] && printf "\033[$[r-$3];$1H " # wait before moving drop down sleep .1 done } # cleanup on exit trap cleanup EXIT # clear screen; hide cursor printf '\033[2J\033[?25l' # loop with delay while sleep .1; do # start a drop in background : column; ending row; size drop $[RANDOM % COL] $[RANDOM % ROW + ROW/3] $[RANDOM % 10 + 5] & done ``` New effects: * everything (first entry) ;) * drops will stop randomly on the screen * cool color effects: the last char is white while the others are green * random chars and escape sequences stay on the console... Ok, that's a bug but it's because the term can't keep up with the cursor movement **Golfed @ 188 186 176** : ``` d(){ for((r=1;r<$2+41;r++));do $4"$3$r;$1H\u$[RANDOM%59+21]";(($r>$2))&&$4"$3$[r-$2];$1H ";$s;done;} s=sleep\ .1;while $s;do d $[RANDOM%80] $[RANDOM%10+5] '\033[' printf\ &done ``` This works in a 80x40 grid. You can change that in `RANDOM%80` on the last line, and `r<$2+41` on the 2nd one. I don't clear the drops after they get out of the grid so either resize your term to 80x40 or change 41 to `$LINES+1`. There are a couple things it doesn't have compared to the full version : * term preparation or cleanup * fancy coloring (takes 52 bytes, so not worth it) * stopping randomly (here drops always go down to the bottom) * I could bring it down to 174 by not specifying a minimum length for "drops" : `$[RANDOM%10+5]` would become `$[RANDOM%15]` Even with those limitations I think it's pretty cool! Edit: I tried using unicode chars like squeamish ossifrage, but because they're double width chars they fill the grid pretty rapidly and it ends up looking strange. I also reduced the golfed version by using unicode code points instead of ASCII, so I don't have to go octal before getting a character, saving a step. I did the same thing in the main version, but added comments to keep it at 1024 bytes. And then changed int comparison from `[ $r -gt $2 ]` to `(($r>$2))`, that white space was killing me but I couldn't find another method that compared ints and not strings. This got the golfed version down to 176 btyes! [Answer] ## JavaScript, 830 bytes It has all of the classic features like: 1. black background 2. green text 3. white text when falling 4. random characters 5. empty holes 6. infinite looping ``` window.onload=function(){ var tbl=document.createElement('table'), body=document.body; body.style.backgroundColor='#000'; body.style.color='#060'; body.style.fontFamily='Lucida Console'; for(var i = 0; i <= 30; i++){ var tr = tbl.insertRow(); for(var j = 0; j <= 50; j++){ var td = tr.insertCell(); td.style.width="2%"; } } body.appendChild(tbl); setInterval(function(){ rain(Math.floor((Math.random()*50)),0) },20); } function rain(n,i) { setTimeout(function (){ var e=document.getElementsByTagName('tr')[i].childNodes[n]; e.style.color='#fff'; e.innerHTML = '&#'+Math.floor((Math.random()*127)+1)+';'; setTimeout(function(){e.style.color=''},200) if (i++ < 30) rain(n,i); },20); }; ``` I like it because it is incredibly light weight, fluid in motion, and simple. enjoy! [Answer] ## QBasic 1, 587 bytes, 32+5=37 points ``` DECLARE SUB d (p!, s!, x!, y!) DIM t(80) FOR i = 1 TO 80 t(i) = INT(-50 * RND) NEXT s = TIMER CLS WHILE 1 FOR i = 1 TO 80 IF t(i) > 28 THEN t(i) = 0 t(i) = t(i) + 1 y = t(i) d 0, 0, i, y - 6 d 2, 0, i, y - 5 d 2, 0, i, y - 4 d 10, 0, i, y - 3 d 10, 0, i, y - 2 d 11, 0, i, y - 1 d 0, 2, i, y NEXT l = TIMER WHILE l = TIMER WEND WEND SUB d (p, s, x, y) COLOR p, s IF y > 0 AND y < 24 THEN LOCATE y, x: PRINT CHR$(33 + (x * y) MOD 200); END SUB ``` Sample screenshot: ![QBasic matrix 1](https://i.stack.imgur.com/GOrSs.png) 32 base points + 5 points for color. But since I'm floating happily well below 1024 byte even without whitespace trimming or optimization, let's add a few more things to steal some points: ## QBasic 2, 913 bytes, 32+5+15+5=57 points ``` DECLARE SUB d (p!, s!, x!, y!) DIM t(80) FOR i = 1 TO 80 t(i) = INT(-50 * RND) NEXT s = TIMER f = 0 w$ = "bullet" o = 1 CLS WHILE 1 FOR i = 1 TO 80 IF t(i) > 28 THEN t(i) = 0: IF f THEN SOUND 100 * i, 1 t(i) = t(i) + 1 y = t(i) d 0, 0, i, y - 6 d 2 + x, 0, i, y - 5 d 2 + x, 0, i, y - 4 d 10 + x, 0, i, y - 3 d 10 + x, 0, i, y - 2 d 11 + x, 0, i, y - 1 d 0, 2 + x, i, y NEXT k$ = INKEY$ IF k$ <> "" THEN IF MID$(w$, o, 1) = k$ THEN o = o + 1 IF o = LEN(w$) + 1 THEN z = 1: f = 100 ELSE o = 1 END IF END IF x = x + z l = TIMER WHILE l = TIMER WEND WEND SUB d (p, s, x, y) COLOR p MOD 16, s MOD 16 IF y > 0 AND y < 24 THEN LOCATE y, x: PRINT CHR$(33 + (x * y) MOD 200); END SUB ``` Sample screenshot (color effect activated): ![Qbasic matrix 2](https://i.stack.imgur.com/FB1gQ.png) Same features as the first one. Additionally it has: * Color (+5) * A password to activate extra features. (I'm claiming +5 for this as a new feature.) * The password activates a palette fade and sound effects. (+15 for sound.) Video showing it in action, including the color effect and sound effect activated by the password: <http://www.youtube.com/watch?v=MQc-FDl_AZ8> [Answer] ## [GTB](http://timtechsoftware.com/?page_id=1309), 42 points Executed from a TI-84 calculator, about 100 bytes: ``` " O O O O O"→Str1:"O O O O O O "→Str2:0→X[@getkey=25$~""~""~""~""~""~""~""p;&@round(r;$~""#@round(r;$~Str1#~Str2&:&] ``` **Effects** Since the calculator is black + white to begin with, can't do much there... * **Umbrella** - Pressing the up key clears off the rain and keeps you dry until you press `Enter` * **Run Inside** - Pressing `ON` breaks the program and gives you a nice roof to keep you dry (you can go back out into the rain by pressing `Enter` twice [Answer] # Ruby: 374 characters ``` $><<"^[[2J" w=->c,d,m{$><<"^[[0;3%d;%dm^[[%d;%dH%s"%[c,d[4],d[3]+d[1]-m,d[2],d[0][d[1]-m]]} t=%w{Stack Exchange Programming Puzzle Code Golf} r=[] loop{r.map{|o|w[2,o,1]if o[1]>0 w[7,o,0] o[1]+=1 o[0][0]==" "?r.delete(o):(o[0]=" "*o[1])*o[1]=0if o[1]>o[0].size} sleep 0.1 r<<[(k=rand(10)%2)==0 ?t.sample: [*?a..?z].sample(rand(10)+5)*"",0,rand(80),rand(20),k+1]while r.size<25} ``` (Note: `^[` are single characters.) Description: * 25 simultaneous runs (kept low so the predefined texts remain readable) * each run has 50% / 50% chance to be either + a predefined word – displayed in bright colors + a random string of 5..15 lowercase letters – displayed in dark colors * while displaying the run the bottom color is white, the others green * after the run is fully displayed, it is removed character by character Sample run: ![matrix rain](https://i.stack.imgur.com/Kg4r7.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/1/edit). Closed 7 years ago. [Improve this question](/posts/1/edit) Classic code golf challenge. Write the most obscure Perl program to print "Just another Perl hacker". Here's the [Wikipedia article on it.](http://en.wikipedia.org/wiki/Just_another_Perl_hacker) Bonus points if it fits in 3 lines / 70 characters each. [Answer] ``` eval eval '"'. ('['^"\+").( ('[')^ ')').('`'|')'). ('`'|'.'). ('['^'/').('{'^'[' ).'\\'.'"' .('`'^ '*').('['^'.').('['^ '(').('['^'/').('{'^ '[').('`'|'!').(('`')| '.').('`'|'/').("\["^ '/').('`'|'(').('`'|'%' ).('['^')').(('{')^ '[').('{'^'+').('`'|'%').( '['^')').('`'| ',').('{'^'[').('`'|'(').('`' |'!').('`'|'#' ).('`'|'+').('`'|'%').('['^')'). '\\'.'"'.("\!"^ '+').'"';$:='.'^'~';$~='@'|"\(";$^= ')'^'[';$/='`'| '.';$,='('^'}';$\='`'|'!';$:=')'^"\}"; $~='*'|"\`";$^= '+'^'_';$/='&'|'@';$,='['&'~';$\=','^'|' ;$:='.'^'~';$~ ='@'|'(';$^=')'^'[';$/='`'|'.';$,='('^'}' ;$\='`'|'!';$: =')'^'}';$~='*'|'`';$^='+'^'_';$/='&'|'@'; $,='['&'~';$\=','^'|';$:='.'^'~';$~='@'|'(';$^=')'^'[';$/= '`'|'.';$,='('^'}';$\='`'|'!';$:=')'^'}';$~='*'|'`';$^='+'^ '_';$/='&'|'@';$,='['&'~';$\=','^'|';$:='.'^'~';$~='@'|'(' ;$^=')'^'[';$/='`'|'.';$,='('^'}';$\='`'|'!';$:=')'^'}';$~= '*'|'`';$^='+'^'_';$/='&'|'@';$,='['&'~';$\=','^'|';$:='.'^ '~';$~='@'|'(';$^=')'^'[';$/='`'|'.';$,='('^'}';$\='`'|'!' ;$:=')'^'}';$~='*'|'`';$^='+'^'_';$/='&'|'@';$,="\["& '~' ;$\=','^'|';$:='.'^'~';$~='@'|'(';$^=')'^'[';$/='`' |(( '.'));$,='('^'}';$\='`'|'!';$:=')'^'}';$~ ='*'|'`' ;$^ ='+'^'_';$/='&'|'@';$,='['&'~';$\=','^ '|';$:= '.' ^'~'; $~='@'|'(';$^=')'^'[';$/="\`"| '.';$,= '(' ^'}';$\='`'|'!';$:=')'^'}';$~ =('*')| '`' ;$^='+'^ '_';$/='&' |"\@"; $,='[' &+ '~';$\= ','^'|'; $:='.' ^"\~"; $~ =('@')| "\(";$^= "\)"^ "\["; ( ($/))= '`'|'.'; ($,) ='(' ^"\}"; $\=('`')| '!'; ($:) =')'^ "\}";$~= '*'| '`'; ($^)= '+'^'_' ;$/= '&'| '@'; $,='[' &'~' ;$\= ','^ '|' ;$:= '.'^ '~'; $~= '@' |(( '(' )); $^= ')' ^(( '[' )); $/= '`' |(( '.' )) ;( ($,))= (( (( '(')) )) ^+ "\}";$\= (( '`' ))|+ "\!"; $: =(( ')'))^ '}'; $~= '*'| "\`";$^= '+' ^'_' ;($/)= ('&')| "\@";$,= '['&'~' ``` [Answer] ``` @H=@h=(176,138,140,17,87,54,126,182,217,223,136,130,136,117,73,52,154, 134,161,36,33,92,60,51);for(;$j<24;$j++){$x=0;for($k=0;$k<24;$k++){$x +=@h[$k]<<($j*$k%24);$x%=241;}@H[$j]=$x;}print pack('c*',@H) ``` I'm not sure whether a newline at the end is required: if so, the addition of `."\n"` still doesn't take me up to the limit of 3 lines \* 70 chars/line. If it weren't for encoding issues the initialisation could be much smaller and extracted with unpack, so I expect someone can improve on this. I'm thinking about making a more efficient version - this is O(n^2), and O(n lg n) decoding is possible. [Answer] ``` use Time'HiRes"usleep";$|=@q=(a..z,' ');@w=('just another perl hacker' =~/./g);while("@w"ne"@e"){$e[$_]eq$w[$_]or$e[$_]=$q[rand@q]for+0..$#w; print"\r@e";usleep+1e5} ``` animated version :) [Answer] ### Less than 70 character on 3 lines: ``` $_=unpack("H21","9Ø HvÂláµöÂ");s/(.)/" "x(hex$1<3).substr "AHPJocehtunarslk",hex$1,1/eg;say ``` Care: It's **ISO-8859-1** encoded. ``` perl -E '$_=unpack("H21","9Ø HvÂláµöÂ");s/(.)/" "x(hex$1<3).substr "AHPJocehtunarslk",hex$1,1/eg;say' Just Another Perl Hacker ``` More than 70 chars at all, but less than **100!** ``` wc -clL <<< '$_=unpack("H21","9Ø HvÂláµöÂ");s/(.)/" "x(hex$1<3).substr "AHPJocehtunarslk",hex$1,1/eg;say' 3 92 37 ``` And a little *obfuscated*! ### A little away?! There is a *<1'000* perl script with a full help and some features: (It's **ISO-8859-1** encoded too ;) ``` #!/usr/bin/perl -s $;=$/;$_=q=sub'O{un=."\144e".q[f}sub'l{$#_==-1?leng].q[th:leng].'t'.q[h&a}sub'u{($.= q;?02:;)=~y+0-@+a-q+;$. =~s/^/&a?"un].q[":""/mxe;$..=' "b';$..=do{$.].q[=~m+^u+?&a:1 }<<3;$..='","';$..=do{$.].q[=~m+^u+?"\44_":&a};eval $.."\42"}s].q[ub'a{pop}sub'b{$.= "Hauri Félix, ";$v?do{$_=$.;y+?-^+_-~+;].q[s/\s.*/.ch/mgx;$_=do{$0=~m-j\w+-?$&.q.@.: (q.w.x3).q,.,}.q qf-q].q[.$_;$..$_}:sub].q[str("lockpents ".$.,&a,1)}sub'p{pr]."in". q<t do{$#_+1?&a."\n":do{/\n/?$_:$_.".\n"}}};sub'x{e>.pack("v",27000).q<t}sub't{sel>. "ec".q<t O,&O,O,&a};$v&&{p $0." \251".(30*67)." ".b}&&x;$j&&do{$_="Îx¹\26§ÕIÕ\220º". "2Õ";$_=>.q<u 12,1;s/.{4}/b ord u O,"$&",O/meg;tr+@-[+`-{+;s/./($.=$&)=~y.^-{.?-\\>. q<\\.;$./xe;p;$c&&do{$c!=1&&do{$_=$c." ";p};fo>."reac".q<h$=(1..2*l){s/.//m;$_.=$&;p "\33[A\r".$_;t.1}};x};$/=O;o>.chr(0x38*2).q-en$_,$0;$_=<$_>;$k&&p&&x||$p&&do{p;op-.q len$p,$p;p<$p>;x};$h&&do{$_="Usal.q lge: ".$0." [ -v | -h | -j [-c[=string]] | -k |l .q+ -p=file.pl ]";p;x};1+;eval||die+No.$;; ``` There are some features: ``` ./japh.pl -h Usage: ./japh.pl [ -v | -h | -j [-c[=string]] | -k | -p=file.pl ]. ``` Where: * `-v` signature * `-h` help string * `-j` prompt *Just another perl hacker.* * `-c` animate the *japh* string or a submited string if any * `-k` dump the script himself * `-p` polute another script So: ``` ./japh.pl -j Just another perl hacker. ./japh.pl -k | wc -lcL 14 998 84 ./japh.pl -p=$(which perldoc) >japhedPerldoc chmod +x japhedPerldoc ./japhedPerldoc perl | head PERL(1) User Contributed Perl Documentation PERL(1) NAME perl - The Perl 5 language interpreter SYNOPSIS perl [ -sTtuUWX ] [ -hv ] [ -V[:configvar] ] [ -cw ] [ -d[t][:debugger] ] [ -D[number/list] ] ./japhedPerldoc -j -c Just another perl hacker. ``` (The last string is animated:) ### Trying to *de-obfucate* There is a nice [B::Deparse](http://search.cpan.org/search?query=B%3a%3aDeparse) module available on CPAN: ``` perl -MO=Deparse japh.pl $; = $/; $_ = qq[sub'O{undef}sub'l{\$#_==-1?length:length&a}sub'u{(\$.=\nq;?02:;)=~y+0-\@+a-q+;\$. =~s/^/&a?"un":""/mxe;\$..=' "b';\$..=do{\$.=~m+^u+?&a:1\n}<<3;\$..='","';\$..=do{\$.=~m+^u+?"\\44_":&a};eval\$.."\\42"}sub'a{pop}sub'b{\$.=\n"Hauri F\351lix, ";\$v?do{\$_=\$.;y+?-^+_-~+;s/\\s.*/.ch/mgx;\$_=do{\$0=~m-j\\w+-?\$&.q.\@.:\n(q.w.x3).q,.,}.q qf-q.\$_;\$..\$_}:substr("lockpents ".\$.,&a,1)}sub'p{print do{\$#_+1?&a."\\n":do{/\\n/?\$_:\$_.".\\n"}}};sub'x{e] . pack('v', 27000) . q[t}sub't{sel] . 'ec' . qq[t O,&O,O,&a};\$v&&{p \$0." \\251".(30*67)." ".b}&&x;\$j&&do{\$_="\316x\271\\26\247\325I\325\\220\272".\n"2\325";\$_=] . 'u 12,1;s/.{4}/b ord u O,"$&",O/meg;tr+@-[+`-{+;s/./($.=$&)=~y.^-{.?-\\' . '\\.;$./xe;p;$c&&do{$c!=1&&do{$_=$c." ";p};fo' . 'reac' . qq(h\$=(1..2*l){s/.//m;\$_.=\$&;p\n"\\33[A\\r".\$_;t.1}};x};\$/=O;o) . 'p' . 'en$_,$0;$_=<$_>;$k&&p&&x||$p&&do{p;op' . 'en$p,$p;p<$p>;x};$h&&do{$_="Usa' . 'ge: ".$0." [ -v | -h | -j [-c[=string]] | -k |' . ' -p=file.pl ]";p;x};1'; die 'No' . $; unless eval $_; japh.pl syntax OK ``` Well, this is *more* readable, but... Ok, there is a `pack('v', 27000)`, what it mean: ``` perl -E "say pack('v', 27000)"; xi ``` Hmm. so we could try to simplify deparser's work: ``` perl -MO=Deparse <(sed -e <japh.pl 's/pack("v",27000)/"xi"/') $; = $/; $_ = qq(sub'O{undef}sub'l{\$#_==-1?length:length&a}sub'u{(\$.=\nq;?02:;)=~y+0-\@+a-q+;\$. =~s/^/&a?"un":""/mxe;\$..=' "b';\$..=do{\$.=~m+^u+?&a:1\n}<<3;\$..='","';\$..=do{\$.=~m+^u+?"\\44_":&a};eval \$.."\\42"}sub'a{pop}sub'b{\$.=\n"Hauri F\351lix, ";\$v?do{\$_=\$.;y+?-^+_-~+;s/\\s.*/.ch/mgx;\$_=do{\$0=~m-j\\w+-?\$&.q.\@.:\n(q.w.x3).q,.,}.q qf-q.\$_;\$..\$_}:substr("lockpents ".\$.,&a,1)}sub'p{print do{\$#_+1?&a."\\n":do{/\\n/?\$_:\$_.".\\n"}}};sub'x{exit}sub't{select O,&O,O,&a};\$v&&{p \$0." \\251".(30*67)." ".b}&&x;\$j&&do{\$_="\316x\271\\26\247\325I\325\\220\272".\n"2\325";\$_=u 12,1;s/.{4}/b ord u O,"\$&",O/meg;tr+\@-[+`-{+;s/./(\$.=\$&)=~y.^-{.?-\\\\.;\$./xe;p;\$c&&do{\$c!=1&&do{\$_=\$c." ";p};foreach\$=(1..2*l){s/.//m;\$_.=\$&;p\n"\\33[A\\r".\$_;t.1}};x};\$/=O;open\$_,\$0;\$_=<\$_>;\$k&&p&&x||\$p&&do{p;open\$p,\$p;p<\$p>;x};\$h&&do{\$_="Usage: ".\$0." [ -v | -h | -j [-c[=string]] | -k | -p=file.pl ]";p;x};1); die 'No' . $; unless eval $_; /dev/fd/63 syntax OK ``` Well, now it is clear that whole script is contained in `qq(...)` on line 2 and have to be submited to `eval`. We could now: ``` perl -MO=Deparse <(sed -e <japh.pl 's/pack("v",27000)/"xi"/') | sed -ne 's/$_ = \(qq(.*)\);/print \1/p' | perl /dev/fd/63 syntax OK sub'O{undef}sub'l{$#_==-1?length:length&a}sub'u{($.= q;?02:;)=~y+0-@+a-q+;$. =~s/^/&a?"un":""/mxe;$..=' "b';$..=do{$.=~m+^u+?&a:1 }<<3;$..='","';$..=do{$.=~m+^u+?"\44_":&a};eval $.."\42"}sub'a{pop}sub'b{$.= "Hauri Félix, ";$v?do{$_=$.;y+?-^+_-~+;s/\s.*/.ch/mgx;$_=do{$0=~m-j\w+-?$&.q.@.: (q.w.x3).q,.,}.q qf-q.$_;$..$_}:substr("lockpents ".$.,&a,1)}sub'p{print do{$#_+1?&a."\n":do{/\n/?$_:$_.".\n"}}};sub'x{exit}sub't{select O,&O,O,&a};$v&&{p $0." \251".(30*67)." ".b}&&x;$j&&do{$_="Îx¹\26§ÕIÕ\220º". "2Õ";$_=u 12,1;s/.{4}/b ord u O,"$&",O/meg;tr+@-[+`-{+;s/./($.=$&)=~y.^-{.?-\\.;$./xe;p;$c&&do{$c!=1&&do{$_=$c." ";p};foreach$=(1..2*l){s/.//m;$_.=$&;p "\33[A\r".$_;t.1}};x};$/=O;open$_,$0;$_=<$_>;$k&&p&&x||$p&&do{p;open$p,$p;p<$p>;x};$h&&do{$_="Usage: ".$0." [ -v | -h | -j [-c[=string]] | -k | -p=file.pl ]";p;x};1 ``` In the hope *deparser* could better understand, now: ``` perl -MO=Deparse <(sed -e <japh.pl 's/pack("v",27000)/"xi"/') | sed -ne 's/$_ = \(qq(.*)\);/print \1/p' | perl | perl -MO=Deparse /dev/fd/63 syntax OK sub O { undef; } sub l { $#_ == -1 ? length $_ : length &a; } sub u { ($. = '?02:') =~ tr/0-@/a-q/; $. =~ s/^/&a ? 'un' : '';/emx; $. .= ' "b'; $. .= do { $. =~ /^u/ ? &a : 1 } << 3; $. .= '","'; $. .= do { $. =~ /^u/ ? '$_' : &a }; eval $. . '"'; } sub a { pop(); } sub b { $. = "Hauri F\351lix, "; $v ? do { $_ = $.; tr/?-^/_-~/; s/\s.*/.ch/gmx; $_ = do { $0 =~ /j\w+/ ? $& . '@' : 'w' x 3 . '.' } . 'f-' . $_; $. . $_ } : substr('lockpents ' . $., &a, 1); } sub p { print do { $#_ + 1 ? &a . "\n" : do { /\n/ ? $_ : $_ . ".\n" } }; } sub x { exit; } sub t { select O(), &O, O(), &a; } x if $v and {p($0 . " \251" . 2010 . ' ' . b())}; if ($j) { $_ = "\316x\271\cV\247\325I\325\220\2722\325"; $_ = u(12, 1); s/.{4}/b ord u(O(), "$&", O());/egm; tr/@-[/`-{/; s[.][($. = $&) =~ tr/^-{/?-\\/; $.;]ex; p ; if ($c) { if ($c != 1) { $_ = $c . ' '; p ; } foreach $= (1 .. 2 * l()) { s/.//m; $_ .= $&; p "\e[A\r" . $_; t 0.1; } } x ; } $/ = O(); open $_, $0; $_ = <$_>; $p and do { p ; open $p, $p; p <$p>; x } unless $k and p and x ; if ($h) { $_ = 'Usage: ' . $0 . ' [ -v | -h | -j [-c[=string]] | -k | -p=file.pl ]'; p ; x ; } '???'; - syntax OK ``` Well! We got something near readable, now. Do this alway give same result? ``` perl -MO=Deparse <(sed -e <japh.pl 's/pack("v",27000)/"xi"/') | sed -ne 's/$_ = \(qq(.*)\);/print \1/p' | perl | perl -MO=Deparse | perl -s /dev/stdin -j -c="That's all folks" /dev/fd/63 syntax OK - syntax OK Just another perl hacker. That's all folks . ``` (And the last line is animated:) [Answer] ``` use strict;*1=*CORE'die,*!=*=,@=='hacker',s??'&1(@!,$/)'?ee;s;;%ENV=~m ,..$,,$&+10;e,@!=(chr.'ust',~~reverse('rehtona'),'Perl',$@);&1("@{=}") ``` It works with strictures enabled. Although it does not work on all machines/perls, because of `CORE'die` and `~~%ENV`. ``` $ perl use strict;*1=*CORE'die,*!=*=,@=='hacker',s??'&1(@!,$/)'?ee;s;;%ENV=~m ,..$,,$&+10;e,@!=(chr.'ust',~~reverse('rehtona'),'Perl',$@);&1("@{=}") ^Z Just another Perl hacker ``` ]
[Question] [ [Related](https://codegolf.stackexchange.com/questions/19450/enlarge-ascii-art) Given a piece of ascii art and a factor to enlarge it by, which will always be an odd number >1, replace each character with the corresponding ascii-art, resized to fit on a grid the size of the input number: | Character | What to do | | --- | --- | | `\` | ``` \ \ \ ``` A line of `\` to the length of the enlarging factor, padded to form a line. | | `/` | ``` / / / ``` A line of `/` to the length of the enlarging factor, padded to form a line. | | `|` | ``` | | | ``` A line of `|` to the length of the enlarging factor, centred horizontally. | | `-` | ``` --- ``` A line of `-` to the length of the enlarging factor, centered vertically. | | `_` | ``` ___ ``` A line of `_` to the length of the enlarging factor, at the bottom of the square it's in. | And of course, a space should be resized to a n-by-n grid of spaces. The input will only contain these six characters, plus newlines. You may take input as a list of lines, a matrix of characters, whatever. This is a bit confusing, so here's an example: ``` -\ /, 3 => \ --- \ \ / / / ``` Because each character is enlarged to size 3. Any trailing whitespace is allowed. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! # Testcases ``` \, 3 => \ \ \ ---, 3 => --------- | | |, 3 => | | | | | | | | | |\_/| | | \_/ , 3 => | \ / | | \ / | | \___/ | | | | | | | \ / \ / \___/ _____ \ / / \ \___/, 3 => _______________ \ / \ / \ / / \ / \ / \ \ / \ / \_________/ /\ / \ /____\ || || _/__\_, 3 => /\ / \ / \ / \ / \ / \ / \ / \ / ____________ \ | | | | | | | | | | | | / \ / \ ___/ ______ \___ \/ \/, 5 => \ / \ / \ / \ / \/ \ / \ / \ / \ / \/ /-/ \-\, 7 => / / / / / / / ------- / / / / / / / \ \ \ \ \ \ \ ------- \ \ \ \ \ \ \ _ _ / \_/ \ | | | | |_| |_|, 11 => ___________ ___________ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \___________/ \ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ___________ | | ___________ | __ __ __ __ ___ /\ /\ | |\ | | / | | /\ | | / \/ \ | | \ | |-- | |--\ /__\ |-- | / \ | | \| |__ \__ | \ / \ | | , 5 => __________ __________ __________ __________ _______________ /\ /\ | | \ | | / | | /\ | | / \ / \ | | \ | | / | | / \ | | / \ / \ | | \ | | / | | / \ | | / \ / \ | | \ | | / | | / \ | | / \ / \ | | \ | | / | | / \ | | / \ / \ | | \ | | | | \ / \ | | / \ / \ | | \ | | | | \ / \ | | / \ / \ | | \ | | ---------- | | ---------- \ / \ | ---------- | / \ / \ | | \ | | | | \ / \ | | / \/ \ | | \ | | | | \ / __________ \ | | / \ | | \ | | \ | \ / \ | | / \ | | \ | | \ | \ / \ | | / \ | | \ | | \ | \ / \ | | / \ | | \ | | \ | \ / \ | | / \ | | \ | | __________ \__________ | \ / \ | | ``` [Reference implementation](https://lyxal.pythonanywhere.com?flags=&code=%E2%86%B5%C6%9B%60%5C%2F_-%7C%20%60%E2%9F%A8%E2%81%B0%CA%81%5C%5C%EA%98%8D%E2%81%B0%E2%86%B2%7C%E2%81%B0%CA%81%5C%2F%EA%98%8D%E2%81%B0%E2%86%B2v%E1%B9%98%7C%E2%81%B0%C3%B0*%E2%81%B0%E2%80%B9%3A%E2%80%9F*%E2%80%9E%2F%E2%81%B0%5C_*J%7C%E2%81%B0%C3%B0*%E2%81%B0%E2%80%B9%C2%BD%3A%E2%80%9F*%E2%80%9E%2F%C2%A4%E2%81%B0-J%C3%B8m%7C%E2%81%B0%E2%80%B9%C2%BD%5C%7C%EA%98%8D%C3%B8m%E2%81%B0*%7C%E2%81%B0%C2%B2%C3%B0*%E2%9F%A9v%E2%88%91%C4%BF%E2%81%B0%C2%B2%E1%BA%87v%C2%B2%C3%9ETv%E2%88%91%E2%81%8B%2C&inputs=%27%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20__%20%20%20%20__%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%5Cn%5C%20%20%20%20%20%20%20%20%2F%20%20%7C%20%20%7C%20%20%2F%7C%20%20%7C%20%20%20%20%20%2F%20%20%20%20%7C%20%20%20%2F%20%20%5C%20__%20%2F%20%20%7C%20%20%20%20%20%7C%20%5Cn%20%5C%20%20%2F%5C%20%20%2F%20%20%20%7C%20%20%7C%20%2F%20%7C%20%20%7C--%20%20%7C%20%20%20%20%20%7C--%2F%20%20%20%20%5C%20%20%2F%20%20%20%7C--%20%20%20%7C%20%5Cn%20%20%5C%2F%20%20%5C%2F%20%20%20%20%7C%20%20%7C%2F%20%20%7C%20%20%7C__%20%20%20%5C__%20%20%7C__%7C%20%20%20%20%20%5C%2F%20%20%20%20%7C__%20%20_%7C_%27%0A5&header=&footer=) [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), ~~118 114 90 88 83~~ 80 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {⊃,/⍪⌿⍵{' '⍺[⍵]}¨1+(⍺ ⍺∘⍴¨o(⌽o←∘.=⍨⍳⍺)i(⌽⍺/⍺↑1)(⍉⍺ ⍺⍴i←(⌈⍺÷2)=⍳⍺)0)['\/|_- '⍳⍵]} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37U1ayj/6h31aOe/Y96t1arK6g/6t0VDWTG1h5aYaitAeQpAPGjjhmPerccWpGv8ahnb/6jtglAAT3bR70rHvVuBkprZoLEgQx9kNq2iYaaQI2dML29WzKBOoAqOoC8w9uNNG2hugw0o9Vj9GvidUG2bgZbCgA&f=bVAxbsMwDNz9Cm6aCMJxYn@GALfmEWE6djPQd3ROljxHLyl5tF0EqAycdLojefJw7V/ft0atrz/tE4hzX18ffX3eh4muNNLY10fTtrEpGTMXn0p1951fwNXEnYic4kSlnUuzXBqaSIBqMCnDTHMaQoEcIslmRjOgxZVaGy5Ic0K2qF@CniqcsChH3nHE0AU9LcotemYcdcLnFmBevSLdNv3fZXZgHd8US8jUSB69ybU2WGS/LLZ7CvOdeOtmUWzMh4UZBVJ/DUpIss8/BmluCKeJXpr8eVDXfgE&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) A dfn submission which takes a char matrix on the right and a scale factor on the left. Indexes each character into its specific pattern, and then uses the original matrix to index back into it. More byte saves can be done by figuring out a formula for getting the boolean arrays. [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), 311 bytes ``` "aDj:%s:\([ \-_]\):=repeat("\\1",a) :g :%s:\\:\\=repeat(" ",a-1) :g :%s:/:=repeat(" ",a-1) /:g :%s:|:=repeat(" ",a/2) |=repeat(" ",a/2) :g {qqYp:s:\\ : \\:ge :s: /:/ :ge qdkG{Go ggqtjjkk@a@qdd@tq@tggqb@ajk:s:_:Y:ge j@bq@bi=a/2+1 D@"kkqc:s:-:X:ge @ak@cq@c:%s:[-_]: :g :%s:X:-:g :%s:Y:_:g gg:s:-: :g ``` [Try it online!](https://tio.run/##bZA9awMxDEB3jbdmEQeBHK0x126CgIZA/kKOuBjfB6b20Lg9suT@uysnoYUQY7Cs9ywJn3Ou3S7Q@ofM5ohG2Q/TULX9nk6Tmze1MW39WrkGyMNVMrL/MRao2j@s6QnTd7g8Qv3WwPIkJ/4lpe5EpR8SSlM/gdxQk8YSpzHuL/svWHmf5hBiZMdpHHlOPEuqZxei@Ja6YgfuE/ef1baUf2lhteM6xjSIoehQDHaRh8RDGfMof0B4n/kgxi3qpJoH76@PBOf8DojaIAJqRIOgrSwjyWUpydthtVLGZnX@BQ "V (vim) – Try It Online") Thanks to PyGamer for the idea of solving this in Vim. It's not extremely well golfed, can change some substitutions and bad hacks around the many macros that are in use. Outputs the required art with two trailing newlines. [Answer] # [C (clang)](http://clang.llvm.org/), ~~170 147 143~~ 137 bytes ``` a,j,i;f(*m,x,z){for(;*m;m+=x)for(j=z;j--;puts(""))for(i=-1;++i<x*z;putchar((a-92?a-47?a-45?a-95|j:j-~j-z:i%z-j:~j+z-i%z)?32:a))a=m[i/z];} ``` [Try it online!](https://tio.run/##TU5bCsIwEPzPKUJASNos4qOIXYMX8AYqEorVBFOlrVBS7dVroyLOxzAzOwObQXbRxanvtbTSYM4jJxvpRZtfS46RQxerRgRjlUcLgLd7XXHGxDs0CiYYx2bVRD5csrMuOdewnK41zBeBkoGWycOmFjoLPjUjDzbtbOxhkGI9m6ZaCK3c1oz9Hp@9KWpaH6t6u1eEbhgA7Hbsq8ZvcRjAkJDQdNoUlIuW0JyHlZzLhUBCP29Gf2Ah/pWSwT37Fw "C (clang) – Try It Online") * thanks to @ceilingcat suggestion ! * added for loop instead of recursion * thanks to @Johan du Toit for suggesting using int\*array as input! `f(*m,x,z){` function taking: * m : ~~char~~ int array without newlines * x : width * z : scale ~~`m+=x;*m&&f(m,x,z);`~~ => `for(;*m;m+=x)` for every row of input, loop actually better than recursion. `for(j=z;j--;puts(""))` we iterate z times every row of input and put \n each time. `for(i=-1;++i<x*z;putchar(..) )` we put x\*z characters. `a=m[i/z]` we use `a` to save on m[i/z] repetitions which is current input being enlarged. `putchar(( ... )?32:a` ... => many nested ternary operators to select proper character based on a and i / j relations which evaluates to 1 or 0 , we then puts a space or `a`. [Answer] # [J](http://jsoftware.com/), 89 bytes ``` [(a{~[:,/[:,./"3[*({0:0}(,:|.)@=@i.,/@,~(1,>.@-:)(,:~|:)@|."{1:0},~$0:))~(a=.' _|-\/')i.] ``` [Try it online!](https://tio.run/##VY4xawMxDIV3/QpxFGwVW3KaoeByxVDo1KnrKZgQEpouGZLtXP/1q44s7fD04L3vgb6Xgd0Jx4wOAybMpsj49vnxvkx@P/cpBzGxDNvp0c8ppx8fcmMqYzlzkBK634RXLjGTFb1lKo2HeWNg6A8pE3W/H9lhbVHF0Zl3C8HteL2NjM7h8fB1KdPd/Al3L1yfCGCLK7J@lEARUUDsKmitVYD@9dYaAmiEIogRVS1sbQ3vVi3VarvnPzuJAhoVaPkF "J – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~261~~ ~~184~~ ~~165~~ ~~163~~ 159 bytes ``` {k:y;v:" ";a:{[g]{(x#v),g,(k-x+1)#v}'!k};h:{[s]{k#s@x=_k%2}'!k};,/{,/'+{$[92=x;a x;47=x;|:'a x;45=x;h v,x;95=x;{k#" _"@x=k-1}'!k;v=x;(k;k)#v;+h v,x]}'x}'";"\x} ``` [Try it online!](https://tio.run/##JY5NCoMwEIX3niKNLYmYkGpbihkE76HBulFhFl0IISXm7Glqdx9v3s@gfGOMs/aoP2A1JRQm7fvFeO5yW4hFcJSurIrcBnbCAGu6bsZjvnWuHfFS/2WhvFCs9Oe@qVsHE3FwfybYNTv4kXglVjhofpjylIw0VaCsfg1gk8oRMA1BeThNYC4wCnRwIfrQva6azz1VQzYomY17evVmivgF "K (oK) – Try It Online") I lost my sanity several times while creating this. Thanks to ngn and Razetime for helping me with this. Thanks to Razetime for helping me to golf off a lot. The basic approach is to split by newlines, replace each character with a list of subrows, take the transpose of that, join each line, and flatten. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 51 bytes ``` {,/,'/'`c$32|x*(a@<a;+a;|=y;=y;a=:|a:y#'!y)8!19!-x} ``` [Try it online!](https://ngn.bitbucket.io/k#eJxLs6rW0ddR11dPSFYxNqqp0NJIdLBJtNZOtK6xrbQGokRbq5pEq0pldcVKTQtFQ0tF3YpaLq5iKw0lhZqYGH0layX9mJgaBSCtG6+rpMnFVV1rmGBgpaSkX12hoxSTp1SrnhZdbG0ci0PCNJYLACp9I3Q=) [Answer] # [Python 2](https://docs.python.org/2/), 135 bytes Takes input as a list of lines. ``` s,f=input() R=range(f) for r in s: for w in R:print''.join([i-w,i-~w-f,w-f/2,f+~w,i-f/2][ord(c)%23%5]and' 'or c for c in r for i in R) ``` [Try it online!](https://tio.run/##pY5BCsIwEEX3OcXfyLSYGqy4KXgJcdeWIjXRiKQlbamCePWaCd7AgYH3/8Bj@td461y@zDf70Dj5SRfQT92CiJZBmoN1/TQmqTge/NlddWJSYToPD@swFAIcZg7HovfWjUSbe2ddUtpsljb7zJmRYVUuzfrDTcC67PwladNVvlvt67O7ECho2ihrWeYj2uhNlygW/FFJgKoqgCQICgjMqJowVRVbvN@/OxNDo/jYUC234l/D7m/D/gs "Python 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 55 bytes ``` Nθ≔⊘⊕θη↑WS«J⁰⁺θⅉFι¿⁼κ_×θκ«M⊖η↗≡κ-P-η/P/η|P|η\P\ηPκM⊖η↘→ ``` [Try it online!](https://tio.run/##dZDLasMwEEXX9lcMXslgoW66SVeFFJpCSmjTRUEgXEeJheW3nCzqfLurR23j0BpLGuncO5pRksZNUsZyGDZF1anXLv/iDarDB/@xbcWpQM@xPPMD2hRJw3NeKB3XYRhBqiXb8szR6qPS4SUVkgOySd5VI4oTCkP49r2XLq/2JbqLYCe7FtURfGqiHd6xbACJEMQR0FPdxbJFWQQBC7RxpzMotBc5t5bMGrhsuUnp2XvXfK4o1QXpOt7EKVVG6bUXoZIUUGZr8JJYOwMcrGDbSSUqm32FXRcjJjeYLHF/g/slpvSG05Ef@DHW5wuaWXL9t5d1eSnmbtw7T/urfx2Gex/@/hibZhcuCGNMGwl1A6DXP3WL1ZDx0O1GjZ19Q6kZo4baBeNJg7F1EMYo/BJjJGMJ01XULLY@aubeMTJrnHHAZ/kD "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ≔⊘⊕θη ``` Input the scale factor `n` and calculate half, rounded up. ``` ↑WS«J⁰⁺θⅉ ``` Output each transformed row on its own set of `n` lines. ``` Fι ``` Loop through the characters on each line. ``` ¿⁼κ_×θκ« ``` If the next character is a `_` then print `n` of them, otherwise... ``` M⊖η↗ ``` Move to the centre of the square. ``` ≡κ-P-η/P/η|P|η\P\ηPκ ``` Print a line in the desired direction. (TIO's version of Charcoal doesn't support computed multidirectionals, so I'm not sure whether that would beat a switch statement.) ``` M⊖η↘→ ``` Move to the bottom left of the next square. [Answer] # JavaScript (ES2020), ~~157~~ ~~151~~ ~~148~~ 147 bytes Takes a 2D character array `A` and a size `n` as `f(A)(n)`. ``` A=>n=>A.flatMap(L=>(N=[...Array(n)]).map((_,y)=>L.flatMap(c=>N.map((_,x)=>[a=y-n+1,a+y,a+=x,a+x-y]['_-/|'.indexOf(c)]??x-y?' ':c)).join``)).join` ` ``` [Try it online!](https://tio.run/##bZHLaoQwFIb3PkV2SZhJQummFKK4d2YWXRqJwY6DgxNFZargu9tcGkuhIeeSfP8hh5y7eqqxGpp@Is@3reZbymPN45TWrZpOqkcZj9GZ55TSdBjUgjQuMH0YgORxwTzOdmXF43MgsyG54gvRh5ejOizG@GzcTJYih5KwFdJGf17nS40qXCSJAQkE8L3CmN67RpdlSKJyqzo9du2Vtt0N1ehjGhp9o4P6KsH/S8rd@/QPkVJGADDhDYDVbOGD07Bw6U9B43xkqbAWNMIFQnYNIa6CSSnAD7GFLLSwPyVscP0J61fP2K/GFZZ07NtmQlBo6D/eTMSOIyswRq8Yb98 "JavaScript (V8) – Try It Online") --- # JavaScript (ES2020), ~~157~~ ~~151~~ ~~148~~ 147 bytes ``` A=>n=>A.flatMap(L=>(N=[...Array(n)]).map((_,y)=>L.flatMap(c=>N.map((_,x)=>({_:a=y-n+1,'-':a+y,'/':a+=x,'|':a+x-y})[c]??x-y?' ':c)).join``)).join` ` ``` [Try it online!](https://tio.run/##bVHBboQgEL37FdyArECaXhoTMN7tXnpcDBJTN25cNGq2mtpvtwLFpkkJM@/BexMmzE0/9FgNTT@Rx8tW8y3jwnCR0brV06vuUc4FOvMLpTQbBr0ggwtM77uAVLxgLvLDWXFxDsq8K@hTJZovxJyeYkhgok9LDJlFPsdwtWQmyxe@VEWa7iyFACYVxvTWNaYsA4nKrerM2LXvtO2uqEZv09CYKx30Rwn@X0od2dM/ilIqAoBJHwCs@5YenIeFS38KHpcjq0obwSMdEHJ4CHEVTCkJfhRbyEILx1PSgutP2rx6jf16XGFJx75tJgSlgf7j94nYceQFxugZ4@0b "JavaScript (V8) – Try It Online") --- # JavaScript (ES2019), ~~161~~ ~~158~~ ~~152~~ ~~149~~ 148 bytes ``` A=>n=>A.flatMap(L=>(N=[...Array(n)]).map((_,y)=>L.flatMap(c=>N.map((_,x)=>[a=y-n+1,x-y,a+y,a+=x,a+x-y]['_\\-/|'.indexOf(c)]?' ':c)).join``)).join` ` ``` [Try it online!](https://tio.run/##bVFNa4QwEL37K3JLwpqE0kspJMW73R56NBKDXRcXG0Vlq@B/t/loLIWGzJuP94YMmZu@66ke22Em96e94XvGheEio02n51c9oJwLdOYFpTQbR70ig0tMPy2BVLpiLvJDWXNxjsximULzlZjTQ7qQNdUnZ3yxYNOygEpKwjZIW/NxWd4aVOPyBQL4XGNMb31rqioGSbXXvZn67kK7/ooa9D6PrbnSUX9V4P@j1IEh/MMopRIAmAwGwGavDM5rWCyGLGo8Jo6VzqJGekfIoSHEdzClJPhhXCOLIxxPSef8fNLhFjj2q/GNFZ2Grp0RlAaGn7crcfvIS4zRI8b7Nw "JavaScript (V8) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 97 bytes ``` n%a|z<-[1-n,3-n..n]=[do c<-r;x<-z;max" "[c|(l,0)<-zip"|_/\\-"[x,y-n+1,y+x,y-x,y],c==l]|r<-a,y<-z] ``` [Try it online!](https://tio.run/##FYrRCoJAEAB/ZVkSCnc1iZ68@4N66vHukMOCpHMTM1C5f7/sYWAY5uk/r0cIKUnm46rYVCx0YikKcdrc39AqHutZ8Vr3fkZA08Z9oONhK92AsSmtZTQzLSx5RUv@tw1HrdbBxVGxp2WbXep9J6Ch98MVhu90m8aLwA7OmUG2tkRCaCK69AM "Haskell – Try It Online") I/O: `size%listOfLines` is a new list of lines. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~162~~ ~~152~~ ~~149~~ ~~143~~ 138 bytes ``` param($k,$o)$o|%{$l=$_;1..$k|%{$y=$_ -join($l|% t*y|%{$c=$_;1..$k|%{" $c"[@{1=$y-$_+$k+1 8=$_+$y 7=2*$_ 6=2*$y 4=$y+1}[$c%13]-eq$k+1]}})}} ``` [Try it online!](https://tio.run/##pVVNj9owEL37V4zAlAQILt12t1KFRA@9VHvsbb1KUQjdlJBQklUbkfx2OmMnjkMWtVVNFOaNn@fTdg7pz/CYPYVxfOZbWMLpfFgf13uH72Y8dXlajk48XnL/w2I@5ztCBSLmfU@jxOFxOYJ8UpA6sEkD4MHgYXVaLHnhcX/Kd9MFe78kqWB3yzcTNHFLfwV7i5TponrgwWhx8@iFP4j7WFVuVZ0rxlYOYzNnNWaSjVczuJmBkgEfIJWrZ0vpM/CExYGSOCXUb5C@j5R6CJI8z9OCUhhTqLbMENSDWd7Uz/Z19bEjFLgKfaEe5YtQm8DUKqixgBqq6AUY2Iw/Qmgtq0ylJWujbYQ@DSbVPPmSrCGYYmhOO5gEe6Bd2YUWJiQMwq4IiyqZ6FiSf2HZRGHlgFPaMhqkKdomZalfPmpwm1h1b6xJZsoPjSzqKI3cIGGlYGeksOgm0cV1mnYBW3/UufL/5Wuh6v1jnFLvTNGkoIfq8k4fr37VTStFvafq7ST@jWxcCjyr0tNn@s5qhrjs@jXlCzqhzzSN3narSZeKSywvugU9xQsapWodS@ugdWhXlD0tFYm52NMRnBSFp8fo2wyv1DTcbqMgCpMcUfjrEAZ5uMFLm/st7z5Kwox0BMDLDnGUw@BrMtCUY5g9xznOv8Lr3rZorWY29csx2u/Dzcdk8xmvfOXOqafo2vfnRPiUbBy3ckF9Fnreeibwlm/jV8xhExgM4TkJUuRjSPlTlEGsEspT2ESYzLoAzcz0uvFwPLl9zarzbw "PowerShell – Try It Online") Less golfed: ``` param($k,$origLines) $origLines|%{ $line = $_ 1..$k|%{ $y = $_ -join($line|% toCharArray|%{ $char = $_ 1..$k|%{ $x = $_ $rasterFont = @{ 1 = $y-$x+$k+1 # \ 8 = $x+$y # / 7 = 2*$x # | 6 = 2*$y # - 4 = $y+1 # _ } " $char"[$rasterFont[$char%13]-eq$k+1] # space or $char } }) } } ``` ]
[Question] [ Let's define a sequence of positive integers. We will define the value of the sequence at every even index to be double the previous term. The odd indices of the sequence will be smallest positive integer not yet appearing in the sequence. Here are the first couple terms. ``` 1,2,3,6,4,8,5,10,7,14,9,18,11,22,12,24,13,26,15,30 ``` You can also think of this as the list of concatenated pairs **(n,2n)** where **n** is the least unused positive integer so far. ## Task Given a number **n** as input calculate the **n**th term in this sequence. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so you should aim to minimize the size of your source code as measured in bytes. [OEIS A036552](http://oeis.org/A036552) [Answer] ## Haskell, 40 bytes ``` l(a:r)=a:2*a:l[x|x<-r,x/=2*a] (l[1..]!!) ``` Zero-based. `l` incrementally builds the sequence from a lazy list of remaining integers. [Answer] ## JavaScript (ES6), ~~92~~ ~~82~~ ~~69~~ ~~67~~ 65 bytes ``` n=>(F=i=>i^n?F(a[b=i&1?2*b:(g=k=>a[k]?g(k+1):k)(1)]=-~i):b)(a={}) ``` ### How? We keep track of: * The last inserted value ***b***. * All previously encountered values in the lookup table ***a***. Internally, we're using a 0-based index ***i***. Odd and even behaviors are therefore inverted: * At odd positions, the next value is simply `2 * b`. * At even positions, we use the recursive function ***g()*** and the lookup table ***a*** to identify the smallest matching value: ``` (g = k => a[k] ? g(k + 1) : k)(1) ``` To save a few bytes, ***i*** is initialized to `{}` rather than `0`. This compels us to use: * `i^n` to compare ***i*** with ***n*** because `({}) ^ n === n` whereas `({}) - n` evaluates to `NaN`. * `-~i` to increment ***i***, because `({}) + 1` would generate a string. ### Demo ``` let f = n=>(F=i=>i^n?F(a[b=i&1?2*b:(g=k=>a[k]?g(k+1):k)(1)]=-~i):b)(a={}) for(n = 1; n <= 20; n++) { console.log('a[' + n + '] = ' + f(n)); } ``` [Answer] # [Python 3](https://docs.python.org/3/), 80 72 69 bytes -7 bytes thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)! ``` f=lambda n:n and[f(n-1)*2,min({*range(n+1)}-{*map(f,range(n))})][n%2] ``` [Try it online!](https://tio.run/##LcoxCoQwEEbhq6QRZmIsotgIexKxGNFowPwGN80inj0r6CsfX/yldUeTs/tsEsZJFDoowdQ7QmVZ1yZ40KkPwTITSstXdeogkZx5H/PFQ4@iHnI8PBJt/pvoIeox1ijb8l3@Aw "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` Jḟ⁸ḢðḤṭṭ 0Ç¡Ḋị@ ``` [Try it online!](https://tio.run/##AS0A0v9qZWxsef//SuG4n@KBuOG4osOw4bik4bmt4bmtCjDDh8Kh4biK4buLQP///zU "Jelly – Try It Online") [Answer] # [Mathics](http://mathics.github.io/), 56 53 bytes -3 bytes thanks [JungHwan Min](https://codegolf.stackexchange.com/users/60043/junghwan-min)! ``` (w={};Do[w~FreeQ~k&&(w=w~Join~{k,2k}),{k,#}];w[[#]])& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvtfo9y2utbaJT@6vM6tKDU1sC5bTQ0oVl7nlZ@ZV1edrWOUXaupA6SVa2Oty6OjlWNjNdX@BxRl5pVEpynoOygEJealp0Yb6igYmsXG/gcA "Mathics – Try It Online") Based on the Mathematica expression given in the OEIS link. [Answer] # [PHP](https://php.net/), 64 bytes ``` for(;$argn-$i++;)if($i&$$e=1)for(;${$e=++$n};);else$e*=2;echo$e; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkqWT9Py2/SMMazNdVydTWttbMTNNQyVRTUUm1NdSESFYD2draKnm11prWqTnFqSqpWrZG1qnJGfkqqdb//wMA "PHP – Try It Online") # [PHP](https://php.net/), 77 bytes ``` for(;$argn-$i++;$r[]=$e)if($i&1)for(;in_array($e=++$n,$r););else$e*=2;echo$e; ``` [Try it online!](https://tio.run/##HcpBCoMwEEbhvcfQn5KYdlF3MoYepBQJZTQDEoepm54@pS4f39OsdXpo1gbJ1hLbsaW67Obo7BskBII9XxHsZXGQy92fLmVOZunrwDEElCvMkyfePgzu40D8zjuYaqcm5ZjN/Yf6Aw "PHP – Try It Online") # [PHP](https://php.net/), 78 bytes ``` for(;$argn-$i++;)$e=$r[]=$i&1?end(array_diff(range($i,1),$r?:[])):2*$e;echo$e; ``` [Try it online!](https://tio.run/##HccxDsIwDADAnWcUC9m0DGWjJspDqqqKqNN4SS2LhdcHxHQ6K9ae0YqdIPleQ/fouOXDkf@/gfY9E0gAn5cAehmj1A2Te/qsm@aMnuouCDqMNIDHaV6IpvsVhOVVjh/tbK71vTqCE7cv "PHP – Try It Online") [Answer] # PHP, 56 bytes ``` while($$n=$i++<$argn)for($n*=2;$i&$$k&&$n=++$k;);echo$n; ``` # PHP, ~~75~~ 72 bytes ``` for($a=range(1,$argn);$i++<$argn;)$a[~-$n=$i&1?min($a):2*$n]=INF;echo$n; ``` [Try it online](http://sandbox.onlinephpfunctions.com/code/2b919bcdf58b06055846cc4c3ea4a5cf8d860522) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ ~~15~~ 14 bytes 1-indexed. Uses the fact that the binary representation of elements at odd indices in the sequence ends in an even number of zeroes: [A003159](http://oeis.org/A003159). ``` Lʒb1¡`gÈ}€x¹<è ``` [Try it online!](https://tio.run/##ASEA3v8wNWFiMWX//0zKkmIxwqFgZ8OIfeKCrHjCuTzDqP//MTY "05AB1E – Try It Online") **Explanation** ``` L # range [1 ... input] ʒ } # filter, keep only elements whose b # ... binary representation 1¡ # ... split at 1's `gÈ # ... ends in an even length run €x # push a doubled copy of each element in place ¹<è # get the element at index (input-1) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~59~~ ~~51~~ 49 bytes ``` f=lambda n,k=2:2/n%-3*(1-k)or f(n+~(k&-k)%-3,k+1) ``` [Try it online!](https://tio.run/##FcyxDoIwFEbhWZ/iXyr3Qhtp2UjwXWqkSKoX0sDAwqvXOp5vOOuxvRdxOYfh47/Pl4foOLje3UWZriZrIi8JgaQ5Kd5KFdaxsZxDccEsSF6mkayGbVvur5c1zbKhUm6HeUB1ewUFEv2/MOcf "Python 2 – Try It Online") ### Background Every positive **n** integer can be expressed uniquely as **n = 2o(n)c(n)**, where **c(n)** is odd. Let **⟨an⟩n>0** be the sequence from the challenge spec. We claim that, for all positive integers **n**, **o(a2n-1)** is even. Since **o(a2n) = o(2a2n-1) = o(a2n-1) + 1**, this is equivalent to claiming that **o(a2n)** is always odd. Assume the claim is false and let **2m-1** be the first odd index of the sequence such that **o(a2m-1)** is odd. Note that this makes **2m** be the first even index of the sequence such that **o(a2m-1)** is even. **o(a2m-1)** is odd and **0** is even, so **a2m-1** is divisible by **2**. By definition, **a2m-1** is the *smallest positive integer not yet appearing in the sequence*, meaning that **a2m-1/2** must have appeared before. Let **k** be the (first) index of **a2m-1/2** in **a**. Since **o(ak) = o(a2m-1/2) = o(a2m-1) - 1** is even, the minimality of **n** implies that **k** is odd. In turn, this means that **ak+1 = 2ak = a2m-1**, contradicting the definition of **a2m-1**. ### How it works *yet to come* [Answer] # [R](https://www.r-project.org/), ~~70~~ ~~69~~ 65 bytes ``` function(n){for(i in 2*1:n)F[i-1:0]=which(!1:n%in%F)[1]*1:2 F[n]} ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT7M6Lb9II1MhM0/BSMvQKk/TLTpT19DKINa2PCMzOUNDESimmpmn6qYZbRgLVGDE5RadF1v7vzixoCCnUgMoYKCTpsmVpmGo@R8A "R – Try It Online") An anonymous function that takes one argument. `F` defaults to `FALSE` or `0` so that the algorithm correctly assesses that no positive integers are in the sequence yet. The algorithm generates the pairs in a `for` loop in the following manner (where `i` goes from `2` to `2n` by `2`): ``` which(!1:n%in%l)[1] # the missing value *1:2 # keep one copy the same and double the next l[i-1:0]= # store into l at the indices i-1 and i ``` [Answer] # [Haskell](https://www.haskell.org/), 63 bytes ``` g x=[2*g(x-1),[a|a<-[1..],a`notElem`map g[1..x-1]]!!0]!!mod x 2 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P12hwjbaSCtdo0LXUFMnOrEm0UY32lBPL1YnMSEvv8Q1JzU3ITexQCEdJAhUExurqGgAxLn5KQoVCkb/cxMz82wLijLzSlRKErNTFYwMVODKY/8DAA "Haskell – Try It Online") This one abuses Haskell's lazy evaluation to the fullest extent. [Answer] # [Perl 6](http://perl6.org/), 50 bytes ``` {(1,{@_%2??2*@_[*-1]!!first *∉@_,1..*}...*)[$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WsNQp9ohXtXI3t5IyyE@WkvXMFZRMS2zqLhEQetRR6dDvI6hnp5WrR6Q0IxWiY@t/W@tUJxYqZCbWAA0QUchzsjA@j8A "Perl 6 – Try It Online") * `1, { ... } ... *` is a lazily-generated infinite sequence where each term after the first is provided by the brace-delimited code block. Since the block references the `@_` array, it receives the entire current sequence in that array. * If the current number of elements is odd (`@_ % 2`), we're generating an even-indexed element, so the next element is double the last element we have so far: `2 * @_[*-1]`. * Otherwise, we get the first positive integer that does not yet appear in the sequence: `first * ∉ @_, 1..*`. * `$_` is the argument to the outer function. It indexes into the infinite sequence, giving the function's return value. [Answer] # [k](https://en.wikipedia.org/wiki/K_(programming_language)), 27 bytes ``` *|{x,*(&^x?!y;|2*x)2!y}/!2+ ``` 1-indexed. [Try it online!](https://tio.run/##y9bNz/7/P81Kq6a6QkdLQy2uwl6x0rrGSKtC00ixslZf0Uj7vwZXmoOhAVeauqG2ohGYNjDQVgSKaP4HAA "K (oK) – Try It Online") Using `(!y)^x` instead of `&^x?!y` works too. [Answer] # Mathematica, 82 bytes ``` (s={};a=1;f=#;While[f>0,If[s~FreeQ~a,s~AppendTo~{a,2a}];a++;f--];Flatten[s][[#]])& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvtfo9i2utY60dbQOs1W2To8IzMnNTrNzkDHMy26uM6tKDU1sC5Rp7jOsaAgNS8lJL@uOlHHKLE21jpRW9s6TVc31totJ7GkJDUvujg2Olo5NlZT7X9AUWZeiYJDmoKDkcF/AA "Mathics – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 82 bytes ``` x=>{int y=1;for(var s="";x>2;x-=2)for(s+=2*y+":";s.Contains(++y+""););return x*y;} ``` [Try it online!](https://tio.run/##FYwxC4MwEEb3/orjpsSrRR17XpZCp@6dRRRuiZDEEin97WkcvuF78N4c2zlqee5@HtWna52DFaRkcd964JCe1y2YzxQgCiJnN3BuZbAnjSRDcxDekePtsfk0qY@GqCK0bDksaQ8ecnPwr/DlVM6o1qiO0ncdK5G9ALyDpuWlfjFKCOIAaTVqLZc/ "C# (Visual C# Interactive Compiler) – Try It Online") -6 bytes thanks to @ASCIIOnly! [Answer] # JavaScript, 51 bytes After golfing this down, it pretty much turned into edc65's solution. ``` n=>(g=x=>g[++x]?g(x):(g[y=x*2]=--n)?--n?g(x):y:x)`` ``` [Try it online!](https://tio.run/##JcixCoMwEADQX3HocNcQKYKL9vQjOoqQoCa0yJ3EIJHSb08LXd7wXvaw@xSeW9Qs85IdZaYOPCXq/KBUGnsPCRvww0npWo2kNWP/4/9nk9CY7CQA063le1W3OAnvsi7lKh7M5a0UfwoqTLnZ@RFtiFCjcsCI@Qs) [Answer] ## Clojure, 102 bytes ``` #(nth(loop[l[0 1 2 3]i %](if(= i 0)l(recur(conj l(*(last l)2)(nth(remove(set l)(range))0))(dec i))))%) ``` Iterates `n` times to build up the sequence and returns the `n`th item, 1-indexed. [Answer] # Ruby, 60 bytes ``` ->n,*a{eval"v+=1while a[v];a[v]=a[2*v]=v+v*n%=2;"*(n/2+v=1)} ``` 0-indexed. We loop `n/2+1` times, generating two values each time and storing them by populating an array at their indices. `v+v*n%2` gives the output, either `v` or `v*2` depending on the parity of `n`. [Answer] # [Ruby](https://www.ruby-lang.org/), 49 bytes ``` ->n{*s=t=0;s|[t+=1]==s||s<<t<<t*2until s[n];s[n]} ``` Start with [0], add pairs to the array until we have at least n+1 elements, then take the n+1th (1-based) [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWqvYtsTWwLq4JrpE29Yw1ta2uKam2MamBIi0jErzSjJzFIqj82KtQUTtf2MDvZLM3NTi6prMmoLSkmKFtOhMoDAA "Ruby – Try It Online") [Answer] # JavaScript (ES6), 60 ~~65~~ bytes An iterative solution. ``` n=>eval("for(s={},i=0;n;)s[++i]?0:(s[i+i]=--n)?--n?0:i+i:i") ``` *Less golfed* ``` n=>{ s = {}; //hashtable for used values for(i=0; n; ) { if ( ! s[++i] ) { s[i*2] = 1; // remember i*2 is already used if (--n) if (--n) 0; else result = i*2; else result = i; } } return result; } ``` **Test** ``` F= n=>eval("for(s={},i=0;n;)s[++i]?0:(s[i+i]=--n)?--n?0:i+i:i") for (a=1; a < 50; a++) console.log(a,F(a)) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ ~~12~~ 10 bytes ``` ḤRọ2ḂĠZFị@ ``` This uses the observation from [my Python answer](https://codegolf.stackexchange.com/a/132217/12012). [Try it online!](https://tio.run/##ASoA1f9qZWxsef//4bikUuG7jTLhuILEoFpG4buLQP8xMDBSwrXFvMOH4oKsR/8 "Jelly – Try It Online") ### How it works ``` ḤRọ2ḂĠZFị@ Main link. Argument: n Ḥ Unhalve; yield 2n. R Range; yield [1, ... , 2n]. ọ2 Compute the order of 2 in the factorization of each k in [1, ..., 2n]. Ḃ Bit; compute the parity of each order. G Group the indices [1, ..., 2n] by the corresponding values. Z Zip/transpose the resulting 2D array, interleaving the indices of 0 with the indices of 1, as a list of pairs. F Flatten. This yields a prefix of the sequence. ị@ Take the item at index n. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 18 bytes ``` !ṁSeDfȯ¬%2öL→x1ḋḣ¹ ``` [Try it online!](https://tio.run/##ASkA1v9odXNr//8h4bmBU2VEZsivwqwlMsO2TOKGkngx4biL4bijwrn///8yOA "Husk – Try It Online") Same method as the 05AB1E solution from Emigna. Both are 1-indexed. # [Husk](https://github.com/barbuz/Husk), 19 bytes ``` !!¡S+ȯSeD←S-ȯḣ→▲ḣ2¹ ``` [Try it online!](https://tio.run/##yygtzv7/X1Hx0MJg7RPrg1NdHrVNCNY9sf7hjsWP2iY9mrYJyDA6tPP///9GFgA "Husk – Try It Online") Uses infinite iteration to generate the sequence. ## Explanation ``` !!¡S+ȯSeD←S-ȯḣ→▲ḣ2¹ ḣ2 array [1,2] ¡ apply function repeatedly on array, yielding intermediate results S hook: S f g x = s f x (g x) + f → list addition ȯ g → compose 3: ȯ f g h x = f (g (h x)) S f → hook: S f g x = s f x (g x) e f → list of two elements D g → number doubled ← g → decrement S h → hook: S f g x = s f x (g x) - f → list subtraction ȯ g → compose 3: ȯ f g h x = f (g (h x)) ḣ f → range 1..n → g → increment ▲ h → maximum altogether, this appends the first element of 1..max+1 not in the array, and it's double. ! take the nth result ! take the nth value ``` ]